Skip to content

fix(engine) #5627: report a procedure's wrong argument count the way a function's is - #5698

Merged
robfrank merged 5 commits into
mainfrom
fix/5627-procedure-validateargs-arity
Aug 1, 2026
Merged

robfrank merged 5 commits into
mainfrom
fix/5627-procedure-validateargs-arity

Conversation

@robfrank

@robfrank robfrank commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

Closes #5627

Follow-up from #5602 (PR #5612), which unified the function side and deliberately left the procedure side alone. Procedure declared a validateArgs() of its own that hand-wrote the count check and raised IllegalArgumentException with older wording, so CallStep.executeProcedure wrapped it in a CommandExecutionException - a 500 for what is entirely the caller's mistake, while the identical mistake against a function had returned 400 with Function 'x' expects N arguments but got M since #5602. Procedure now has a checkArity() reading its declared getMinArgs()/getMaxArgs() and phrased through the shared FunctionArity, so a wrong argument count reads with the same sentence and carries the same status whichever kind the name resolved to: Procedure 'algo.dijkstra' expects 4-5 arguments but got 2. The move also picks up the two guards the hand-written check lacked - FunctionArity.effectiveMax(), so a procedure spelling "unbounded" the registry's way (-1) is not read as "at most -1 arguments", and a null argument array counted as zero arguments instead of dereferenced.

The word stays Procedure rather than Function: reusing FunctionArity.message verbatim would tell a caller that algo.dijkstra is a function, which it is not. The sentence shape, the accepted-count phrasing and the exception type are what the issue asks to unify, and all three now match.

The ~80 hand-written validateArgs(args) calls at the top of each execute() are kept, and the issue's question about dropping them is answered in the tracking doc: unlike the function-side duplication Function.checkArity replaced, these are not a second hand-written count check that can drift - they call the same default method reading the same declared bounds - and Procedure.execute() is public, so dropping the guard would leave a direct caller with an ArrayIndexOutOfBoundsException instead of the client error.

Note on existing tests. ProcedureInterfaceTest's five arity cases asserted IllegalArgumentException and the literal strings "exactly 2" / "2 to 4" - which are the behaviour this issue asks to replace. They were testing the correct thing (the guard fires, with the right numbers) against the wording of the day, so the assertions are retargeted at the new contract rather than deleted or loosened to accept both. This is a deliberate exception to the "never modify existing tests" rule, flagged here for review.

Test plan

  • mvn -pl engine test -Dtest=ProcedureArityIssue5627Test - 8 cases, all new. 7 of them fail on main (the eighth asserts a correct call still runs). Covers: the CALL path raising CommandSemanticException rather than a wrapped CommandExecutionException; exact-count and range phrasings; too many as well as too few; OPTIONAL CALL no longer swallowing it; a null argument array; a sweep over every registered procedure asserting the canonical sentence, so a procedure added later cannot reintroduce a wording of its own.
  • mvn -pl engine test -Dtest=ProcedureInterfaceTest - 10 cases, including the new unbounded-maximum (-1 and Integer.MAX_VALUE) and null-array coverage.
  • mvn -pl engine test -Dtest='com.arcadedb.query.opencypher.**,com.arcadedb.function.**' - 8918 tests, 0 failures, 98 skipped.
  • mvn -DskipTests compile - full reactor.
  • Repo-wide scan for the old wording (Error executing procedure, requires exactly N argument(s), requires N to M arguments, got) finds no other dependant.

🤖 Generated with Claude Code

…a function's is

Procedure declared a validateArgs() of its own that hand-wrote the count check
and raised IllegalArgumentException, which CallStep.executeProcedure wrapped as
a CommandExecutionException - a 500 for what is entirely the caller's mistake,
while the same mistake on a function had given 400 since #5602.

Procedure now has checkArity(), phrased through the shared FunctionArity, so the
sentence and the exception type match the function side. It also picks up the
two guards the hand-written check lacked: effectiveMax(), so a procedure
spelling unbounded as -1 is not read as "at most -1 arguments", and a null
argument array counted as no arguments rather than dereferenced.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@codacy-production

codacy-production Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 6 complexity

Metric Results
Complexity 6

View in Codacy

🟢 Coverage 100.00% diff coverage · -7.49% coverage variation

Metric Results
Coverage variation ✅ -7.49% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (83448ea) 150078 114508 76.30%
Head commit (1ffdcff) 182250 (+32172) 125404 (+10896) 68.81% (-7.49%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#5698) 11 11 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@mergify

mergify Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: #5627 procedure arity unification

Reviewed the diff against CallStep, FunctionArity, Function, the exception hierarchy, and the procedure registry. This is a clean, well-scoped fix and the reasoning in the PR body/tracking doc holds up under checking.

What's correct and verified

  • The core mechanism works as claimed. CommandSemanticException extends CommandParsingException (confirmed in engine/src/main/java/com/arcadedb/exception/), so CallStep.executeProcedure's catch (CommandParsingException clientError) rethrows the arity error untouched instead of falling into the catch (Exception) that wraps it in CommandExecutionException. The 500->400 change and "OPTIONAL CALL no longer swallows it" both follow directly from that, and both are covered by tests.
  • The two extra guards are genuine improvements, not just message polish: effectiveMax(getMaxArgs()) (so a -1 "unbounded" isn't read as "at most -1"), and the args == null ? 0 guard (the old args.length would NPE and get wrapped as a 500). Both mirror Function.checkArity exactly.
  • FunctionArity overloads are unambiguous - the 3-arg message/mismatch keep the "Function" shorthand and delegate to the new 4-arg kind-aware forms; no existing caller changes.
  • The registry sweep test (everyRegisteredProcedureReportsTheCanonicalSentence) is a good regression guard - it asserts the registry is non-empty first, so it can't silently pass on an empty sweep. Confirmed no procedure overrides validateArgs/checkArity (the ~80 validateArgs(args) hits are all call sites), so the default path it exercises is the real one.
  • Modifying ProcedureInterfaceTest is the right call and is explicitly flagged/justified per the CLAUDE.md "don't modify existing tests" rule - the old assertions encoded the exact wording the issue asks to replace.
  • Committing docs/5627-*.md matches the established issue-numbered convention in docs/ (73 such files already).

Observations (non-blocking)

  1. The unification is partial, worth a one-line scoping note in the doc. This PR unifies wrong-argument-count reporting. But procedure argument-value validation - e.g. MergeRelationship/AbstractPathProcedure throwing IllegalArgumentException for a null required argument (MergeRelationship.java:190+) - still propagates through CallStep's catch (Exception) and surfaces as a 500. So CALL merge.relationship(null, ...) stays a 500 while a wrong count is now a 400. Legitimately outside [Cypher] Procedure.validateArgs() still reports a wrong argument count differently from functions #5627's scope (count only), but since the doc frames it as "the same mistake reads the same way whichever kind," scoping the claim to count would avoid the remaining divergence being mistaken for fixed.

  2. checkArity + validateArgs are now two default methods where validateArgs only delegates. Mirrors Function for symmetry, which is a fair justification, but since nothing overrides checkArity independently on the procedure side it's essentially a rename alias. Fine to keep for parity; just noting it's slightly more surface than strictly needed.

  3. User-visible message change. Wording goes from x() requires exactly N argument(s), got M to Procedure 'x' expects N arguments but got M. Anyone parsing the old string breaks; the PR's repo-wide scan for the old phrasings is the right diligence. Flagging only because it's an external-contract change for API clients.

Not verified

Could not run mvn in this environment (blocked), so I relied on static analysis of the exception flow, message construction, and registry rather than executing the suite. The logic all checks out; the PR reports 8918 tests green.

Nice work - the change is minimal, the guards are correct, and the test coverage (CALL path, range vs exact, too-many, OPTIONAL, null array, full-registry sweep) is thorough.

…he message contract change

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: procedure arity unification (#5627)

I traced the full path (CallStep.executeProcedure -> Procedure.validateArgs -> checkArity -> FunctionArity) and the exception hierarchy. The change is well-scoped, correct, and unusually well-documented. Approving with only minor, optional notes.

What's right

  • Root fix is sound. CommandSemanticException extends CommandParsingException, and CallStep.executeProcedure (CallStep.java:337) rethrows CommandParsingException untouched while wrapping everything else in CommandExecutionException. So switching the arity guard from IllegalArgumentException to FunctionArity.mismatch(...) genuinely turns the 500 into a 400 and stops OPTIONAL CALL from swallowing it. The behavioural claim holds.
  • Two latent bugs fixed for free, both mirroring the function side: a null argument array now counts as 0 args instead of NPE, and a -1 unbounded max is resolved through effectiveMax() instead of rejecting every call.
  • Backward compatible. The 3-arg message/mismatch overloads delegate to the new 4-arg ones with "Function", producing byte-identical output; all existing callers (Function, TrimFunction, FunctionValidator) still bind to the 3-arg forms since their last arg is int. No ambiguity.
  • Test coverage is strong. The registry sweep in ProcedureArityIssue5627Test (asserting every registered procedure yields the canonical sentence) is a nice guard against a future procedure reintroducing its own wording. Null-array, exact/range/too-many, and function-vs-procedure parity are all covered.
  • The modified existing tests are handled correctly - retargeted at the new contract rather than loosened to accept both, and explicitly flagged per the CLAUDE.md "don't modify tests" rule. Good call surfacing it.
  • Verified no other production caller depends on the old wording or catches IllegalArgumentException around procedure execution (CallStep is the only external caller; the ~76 in-execute() calls just propagate). The coll.sort() requires exactly 1 argument matches are an unrelated SQL function, not this path.

Minor / optional

  1. Small duplication. Procedure.checkArity and Function.checkArity are now byte-identical except for the noun passed to mismatch. This could collapse into a single FunctionArity.check(kind, name, min, max, args) helper. That said, the PR deliberately keeps the two guards separate and documents why, so this is a judgment call, not a defect - fine to leave as is.
  2. New test author tag. ProcedureArityIssue5627Test carries @author Luca Garulli while the PR is from a different author; consistent with repo convention but worth a glance.
  3. Docs file. docs/5627-procedure-arity-unification.md is a thorough design record; just confirm the team wants per-issue tracking docs living under docs/ long-term vs. the PR description.

Nothing blocking. Nice, careful change.

…Arity.check

Function.checkArity and Procedure.checkArity were byte-identical but for the
noun - the same shape the two messages had before this issue, and how they came
to disagree. Both are now one line over a shared FunctionArity.check, so the
effectiveMax() and null-array rules exist once.

Also drops an @author tag attributing the new test to someone who did not write
it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: unify procedure wrong-argument-count reporting (#5627)

Reviewed against CLAUDE.md. Overall this is a clean, well-scoped fix that does exactly what the issue asks and nothing more. I traced the key claims and they hold up.

What I verified

  • Status code fix is real. CommandSemanticException extends CommandParsingException, and CallStep.executeProcedure/executeFunction both catch (CommandParsingException clientError) and rethrow untouched before the catch (Exception) that wraps into CommandExecutionException. So switching the procedure guard from IllegalArgumentException to CommandSemanticException genuinely moves it from 500 -> 400, and also fixes OPTIONAL CALL no longer swallowing it. Well covered by optionalCallDoesNotSwallowAWrongArgumentCount.
  • Shared body, no drift. Collapsing both Function.checkArity and Procedure.checkArity onto FunctionArity.check(kind, ...) is the right call - the two were byte-identical but for the noun, which is exactly how the two messages drifted apart originally. The kind-aware message/mismatch overloads keep "Procedure" in the sentence, which is correct (it isn't a function).
  • effectiveMax() and null-array guards are genuine latent-bug fixes folded into the shared path, both directly tested (anUnboundedMaximumIsNotReadAsAnUpperLimit, aNullArgumentArrayCountsAsNoArguments).
  • No orphaned code. The 3-arg FunctionArity.mismatch/message overloads are still used by TrimFunction and FunctionValidator, so keeping them is correct. No procedure overrides validateArgs/checkArity with the old behaviour.
  • Test edits are justified. The ProcedureInterfaceTest changes retarget assertions at the new contract rather than loosening them, and the PR explicitly flags this as a deliberate exception to the "don't modify tests" rule. The registry-sweep test (everyRegisteredProcedureReportsTheCanonicalSentence) is a nice guard against a future procedure reintroducing its own wording, and its getMinArgs()>0 / getMaxArgs() < MAX_VALUE bounds correctly skip the unbounded/zero edges.
  • Doc file docs/5627-...md follows the established docs/<issue>-<slug>.md convention (73 such files already).

Observations (non-blocking)

  1. Out-of-scope follow-up: several Function implementations still hand-write their own count checks and throw CommandExecutionException (500) with the old "requires exactly N" wording - CollMin, CollMax, CollSort, CollDistinct, CollInsert, CollIndexOf, and SQLFunctionCypherRID. Same inconsistency class this effort unifies, just on the function side, surfacing a 500 for a caller mistake. Not this PR's job, but worth a tracking note so the unification is eventually complete.

  2. Three-hop indirection (validateArgs -> checkArity -> FunctionArity.check) now exists symmetrically on both interfaces. Justified by keeping validateArgs as the stable name the ~80 execute() call sites and CallStep use, so I'd keep it - just flagging that validateArgs is now a pure passthrough on both sides.

  3. aCorrectArgumentCountIsStillAccepted executes algo.degree() against an empty DB and relies on it not throwing for unrelated reasons; fine as a smoke check, just slightly coupled to that procedure tolerating an empty graph.

Couldn't verify locally

Maven compile/test is blocked in this sandbox (no network), so I relied on the PR's documented compile + test runs. All symbols the new test references (CypherProcedureRegistry.get, getAllProcedures) exist, so it should compile.

Nice work - the reasoning in the commit messages and tracking doc made this easy to follow, and the "keep the noun, share everything after it" decision is the right one.

…cks as a follow-up

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review: #5627 procedure arity unification

Reviewed the full diff and traced the call path (CallStep.executeProcedure → Procedure.validateArgs → checkArity → FunctionArity.check), the exception hierarchy, and every registered procedure implementation. This is a clean, well-scoped fix. My take: approve with a few minor observations, none blocking.

What's good

  • Correct root cause and fix. CommandSemanticException extends CommandParsingException, and CallStep.executeProcedure rethrows CommandParsingException untouched (line 337) before the catch (Exception) wrap into CommandExecutionException. So routing the arity error through FunctionArity.check (which throws CommandSemanticException) genuinely turns the former wrapped-500 into a 400, and makes OPTIONAL CALL stop swallowing it. The behavior claims in the PR body check out against the code.
  • Real de-duplication. Extracting the shared body into FunctionArity.check(kind, name, min, max, args) and reducing both Function.checkArity and Procedure.checkArity to one-line delegations removes the byte-identical-but-for-the-noun duplication rather than adding a third copy. The two picked-up guards (effectiveMax(-1) and the null-array count) now live in exactly one place.
  • No behavioral regression on the function side. The old Function.checkArity built its message via mismatch(getName(), describe(...), actualArgs) → message(\"Function\", ...); the new path reaches the same 4-arg message(\"Function\", ...). Output string is identical.
  • Verified no other dependents. No procedure overrides validateArgs/checkArity (all ~80 implementations call the default), and a repo scan finds no remaining test or caller asserting the old IllegalArgumentException / "requires exactly" / "Error executing procedure" wording outside the retargeted comments.
  • Strong test coverage. The new ProcedureArityIssue5627Test covers the CALL path exception type, exact vs range phrasing, too-few/too-many, OPTIONAL CALL, the null array, and a registry-wide sweep that pins the canonical sentence so a future procedure can't reintroduce its own wording. ProcedureInterfaceTest adds the unbounded-max (-1 and MAX_VALUE) and null-array cases. The assertion style and @Test conventions match the repo.
  • The modified-tests exception is handled correctly: the five retargeted assertions in ProcedureInterfaceTest were testing the pre-issue wording, and they're retargeted at the new contract (not loosened to accept both), with the deviation flagged in the PR body. That's the right call.

Minor observations (non-blocking)

  1. Two-level indirection. validateArgs → checkArity → FunctionArity.check is one hop more than strictly needed, but it deliberately mirrors the Function side and preserves validateArgs as the public name both CallStep and the implementations call. Keeping the symmetry is worth the extra hop; fine as-is.
  2. Sweep test on misconfigured bounds. everyRegisteredProcedureReportsTheCanonicalSentence guards maxArgs + 1 behind maxArgs < Integer.MAX_VALUE (no overflow) and skips unbounded (-1) via getMaxArgs() >= 0. Solid. It does assume every procedure's validateArgs is arity-only (true today, since none override it); if a future procedure overrode validateArgs to add type checks, a bare new Object[argCount] of nulls could trip a different error first. Not a concern now, just noting the assumption.
  3. Docs file docs/5627-procedure-arity-unification.md is a helpful tracking record; no product impact.

Note

I could not execute mvn in this review sandbox, so I did not independently run the suite. The reasoning above is from static tracing; the PR's stated test results are consistent with the diff.

Nice, surgical change with the messaging and status now genuinely unified across the two callable kinds.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 1, 2026

Copy link
Copy Markdown

Review - PR #5698: unify procedure wrong-argument-count reporting

Reviewed the diff, the surrounding CallStep.executeProcedure path, and the exception hierarchy. Well-scoped, well-motivated fix with an excellent write-up. Summary: looks good to merge, with a few minor notes.

What's right

  • Correct root-cause fix. CommandSemanticException extends CommandParsingException (verified), so catch (CommandParsingException clientError) { throw clientError; } in executeProcedure now rethrows the arity error untouched instead of falling into the CommandExecutionException wrapper. Lands the same 400 the function side has given since [Misc] OpenCypher follow-ups from #5484: arity-guard blind spot, locale-dependent name folding, unimplemented registered functions #5602, and stops OPTIONAL CALL swallowing a malformed call - both covered by tests.
  • Good reuse. Routing procedures through shared FunctionArity.check(...) keeps the check and message in one place, and the two folded-in guards (effectiveMax() for the -1 unbounded spelling, and null-array-as-zero) are real improvements, not just cosmetics. Keeping the noun as Procedure via the kind param is the right call.
  • Backward compat preserved. The pre-existing 3-arg mismatch/message overloads stay and are still used by TrimFunction and FunctionValidator.
  • Strong tests. The registry sweep in everyRegisteredProcedureReportsTheCanonicalSentence prevents a future procedure reintroducing bespoke wording; the -1/Integer.MAX_VALUE and null-array cases hit exactly the guards that were missing.
  • Modifying ProcedureInterfaceTest is justified and correctly flagged. Those assertions pinned the old wording the issue asks to replace; retargeting (rather than loosening to accept both) is the right move.

Minor notes (non-blocking)

  1. Sweep allocation. assertRejects(procedure, getMaxArgs() + 1) does new Object[argCount]. Guarded by getMaxArgs() < Integer.MAX_VALUE and real maxima are tiny, so safe - just be aware a procedure with a huge finite max would allocate that array.
  2. Sweep coverage gap. A procedure with minArgs == 0 and an unbounded max is skipped by both branches, contributing nothing. Fine (nothing to reject), just noting it.
  3. Tracking doc in docs/. docs/5627-procedure-arity-unification.md (191 lines) is useful rationale but reads as a PR/issue artifact; consider whether it belongs permanently under docs/.
  4. Commit trailers. Commits carry Co-Authored-By: Claude ...; CLAUDE.md asks not to add Claude as author of source code - worth a check against project commit conventions (does not affect the code).

Verification

Could not run mvn in this environment (sandbox approvals), so relying on the PR's documented test runs. Logic and exception wiring check out on inspection; if CI is green on ProcedureArityIssue5627Test and ProcedureInterfaceTest, this is good to go.

Nice, surgical change.

Automated review by Claude.

@codecov

codecov Bot commented Aug 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 66.83%. Comparing base (83448ea) to head (1ffdcff).
⚠️ Report is 7 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #5698      +/-   ##
============================================
- Coverage     67.49%   66.83%   -0.66%     
- Complexity        0     1112    +1112     
============================================
  Files          1770     1771       +1     
  Lines        150078   150258     +180     
  Branches      31809    31867      +58     
============================================
- Hits         101290   100421     -869     
- Misses        35607    36788    +1181     
+ Partials      13181    13049     -132     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@robfrank
robfrank merged commit 82f4852 into main Aug 1, 2026
28 of 31 checks passed
@robfrank
robfrank deleted the fix/5627-procedure-validateargs-arity branch August 1, 2026 16:22
robfrank added a commit that referenced this pull request Aug 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Cypher] Procedure.validateArgs() still reports a wrong argument count differently from functions

1 participant