Skip to content

fix(#5799): sum() and avg() reject non-numeric input instead of silently ignoring it - #5908

Merged
robfrank merged 1 commit into
mainfrom
fix/5799-cypher-sum-avg-silently-ignore-non-numeric
Aug 7, 2026
Merged

robfrank merged 1 commit into
mainfrom
fix/5799-cypher-sum-avg-silently-ignore-non-numeric

Conversation

@robfrank

@robfrank robfrank commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

sum() and avg() in Cypher now raise a client-facing type error (HTTP 400) instead of
silently ignoring non-numeric input.

  • SQLFunctionSum (shared by SQL's sum() and Cypher's sum(), reached via
    SQLFunctionBridge): a non-numeric, non-null value used to be silently skipped in the
    single-argument aggregate path, and blindly cast (throwing an undecorated
    ClassCastException) in the multi-argument per-row and list-element paths. All three now
    validate the value and throw IllegalArgumentException with a clear message, matching the
    existing SQL-function convention (e.g. SQLFunctionAbsoluteValue).
  • CypherAvgFunction (Cypher-only avg()): now uses
    CypherFunctionHelper.requireNumberArgument(), the same helper the numeric math family
    (abs(), sqrt(), ...) already uses since [OpenCypher] abs() returns HTTP 500 for invalid argument instead of client-facing error #5484 for this exact class of defect, throwing
    CommandSemanticException.

Null handling and empty-input identities are unchanged: sum() over nulls/empty still returns
0, avg() over nulls/empty still returns null.

Motivation

Silently ignoring out-of-domain values let sum()/avg() return a plausible but wrong result
with no error at all:

  • UNWIND ['1', '2'] AS x RETURN sum(x) returned 0, indistinguishable from summing
    [null, null].
  • UNWIND [true, 1] AS x RETURN sum(x) returned 1, hiding the invalid boolean.
  • UNWIND ['a', 'b'] AS x RETURN avg(x) returned null, indistinguishable from averaging
    [null, null].

Neo4j reports a type error for all of these. This is the same class of defect fixed for the
numeric math family (abs(), sqrt(), ...) in #5484.

Why two different exception types

SQLFunctionSum is genuinely shared with plain SQL (SELECT sum(...) FROM ...), so it follows
the existing SQL-function convention (IllegalArgumentException) rather than pulling in the
Cypher-only CommandSemanticException/CypherFunctionHelper. CypherAvgFunction has no SQL
counterpart reachable from Cypher, so it follows the Cypher convention directly. Both map to
HTTP 400 at AbstractServerHttpHandler, so the externally observable behavior is the same.

Why sum() didn't get its own Cypher-specific executor

A tempting alternative was giving Cypher its own CypherSumFunction (mirroring
CypherAvgFunction). This was rejected: CypherFunctionArityRegistryTest pins sum in
NARROWER_IN_CYPHER specifically because the shared SQLFunctionSum executor is variadic
(sum(a,b,c)) while the Cypher parser only allows the single-argument aggregation, and that
test asserts the pin still bites. A dedicated single-arg-only Cypher executor would make the
parser and executor arities match exactly, breaking that existing regression test for an
unrelated reason. Fixing SQLFunctionSum in place keeps its arity untouched.

Related issues

Closes #5799

Same class of defect as #5484.

Additional Notes

Verification performed (see the tracking doc at
docs/5799-cypher-sum-avg-silently-ignore-non-numeric.md for full detail):

  • Wrote the regression tests first and confirmed all 7 new Cypher-level tests failed against the
    unmodified code.
  • OpenCypherAggregatingFunctionsComprehensiveTest + SQLFunctionSumAverageMultiArgTest: pass.
  • CypherFunctionArityRegistryTest + CypherNumericFunctionArgumentIssue5484Test +
    CypherFunctionFactoryTest + CypherFunctionFactoryExtendedTest: pass (confirms the sum
    arity pin still holds and the [OpenCypher] abs() returns HTTP 500 for invalid argument instead of client-facing error #5484 numeric-family tests are unaffected).
  • Full com.arcadedb.query.opencypher.** + com.arcadedb.function.** packages: 4415 tests, 0
    failures, 0 errors.
  • Full com.arcadedb.query.sql.** package: 404 tests, 0 failures, 0 errors.
  • Searched the repo for other callers of the changed classes and for sum(/avg( usages with
    string literals across wire-protocol test modules (postgresw, mongodbw, graphql, bolt): none
    found outside engine/.

Test plan

  • UNWIND ['1', '2'] AS x RETURN sum(x) raises a client error instead of returning 0
  • UNWIND [true, 1] AS x RETURN sum(x) raises a client error instead of returning 1
  • UNWIND ['a', 'b'] AS x RETURN avg(x) raises a client error instead of returning null
  • UNWIND [1, null] AS x RETURN sum(x) still returns 1 (nulls still skipped)
  • UNWIND [] AS x RETURN sum(x) still returns 0 (empty-input identity unchanged)
  • UNWIND [] AS x RETURN avg(x) still returns null (empty-input identity unchanged)
  • mvn -pl engine -am test -Dtest=OpenCypherAggregatingFunctionsComprehensiveTest,SQLFunctionSumAverageMultiArgTest passes

Checklist

  • I have run the build using mvn clean package command
  • My unit tests cover both failure and success scenarios

…tly ignoring it

Cypher's sum() (shared with SQL's sum() via SQLFunctionSum) and avg()
(CypherAvgFunction) only advanced their accumulator when the aggregated
value was a Number, silently skipping anything else - a STRING, a
BOOLEAN, ... - the same way they skip null. That made an all-invalid
input indistinguishable from an all-null one (sum(['1','2']) == 0,
same as sum([null,null])) and let a mixed input report a plausible but
incomplete total (sum([true, 1]) == 1).

Both now throw a client-facing type error instead: SQLFunctionSum
throws IllegalArgumentException (matching the existing SQL-function
convention, e.g. SQLFunctionAbsoluteValue), and CypherAvgFunction uses
CypherFunctionHelper.requireNumberArgument(), the same helper the
numeric math family (abs(), sqrt(), ...) already uses since #5484 for
this exact class of defect. Both map to HTTP 400 at
AbstractServerHttpHandler. Null handling and empty-input identities
(sum() -> 0, avg() -> null) are unchanged.
@mergify

mergify Bot commented Aug 7, 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

@codacy-production

codacy-production Bot commented Aug 7, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

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

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

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (6bbb0e7) 152707 117904 77.21%
Head commit (4f182e6) 185054 (+32347) 130239 (+12335) 70.38% (-6.83%)

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 (#5908) 10 10 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.

@claude

claude Bot commented Aug 7, 2026

Copy link
Copy Markdown

Review

Reviewed the diff (CypherAvgFunction.java, SQLFunctionSum.java, plus tests) and traced the call paths (CypherFunctionFactory -> SQLFunctionBridge -> SQLFunctionSum; CypherFunctionFactory -> CypherAvgFunction) and the HTTP error mapping in AbstractServerHttpHandler (confirmed both IllegalArgumentException and CommandSemanticException/CommandParsingException map to 400). Overall this is a clean, well-scoped fix with good regression tests and a solid write-up of the reasoning, including why sum() wasn't given its own Cypher executor. A couple of things worth a look before merging.

1. SQLFunctionAverage (plain SQL avg()) has the exact same defect and is left unfixed

SQLFunctionSum is described as 'shared with plain SQL,' which is exactly why it was fixed in place rather than getting a Cypher-only executor. Its sibling, engine/src/main/java/com/arcadedb/function/sql/math/SQLFunctionAverage.java, has the identical bug pattern fixed here in SQLFunctionSum:

  • single-arg path: falls through both if/else-if branches silently for a non-numeric, non-null value
  • multi-value path: blind (Number) n cast, raw ClassCastException
  • multi-arg per-row path: blind (Number) params[i] cast, raw ClassCastException

Since sum() is now fixed to throw a clean IllegalArgumentException (-> 400) but SELECT avg(...) on the same kind of dirty/mixed-type data still either silently drops the bad value or blows up with an undecorated ClassCastException (likely a 500, not 400), this PR introduces a visible inconsistency between the two aggregate functions for plain SQL callers. Issue #5799 is scoped to Cypher so this may be intentionally out of scope, but it's the same class of bug in an untouched sibling class, worth a follow-up so sum() and avg() don't diverge in error behavior for the same bad input.

2. Behavior change scope for plain SQL sum()

Because SQLFunctionSum is shared, this also changes behavior for plain SELECT sum(field) FROM ... in ArcadeDB's schema-less document model, not just Cypher. Previously a heterogeneous bucket (e.g. some documents have price stored as a String) would silently skip non-numeric values when summing; now the whole query throws. That's arguably correct (matches the stated goal of not hiding bad data), but it is a behavior change for existing SQL users too, and the PR description frames the motivation entirely around Cypher/Neo4j parity. Worth confirming this SQL-side behavior change is intentional and acceptable, since it could break existing queries that ran (silently) against dirty data before.

Nits

  • requireNumericOrNull in SQLFunctionSum is a good, minimal helper; the comment explaining it's a no-op for null is helpful.
  • The new else branch in SQLFunctionSum.execute()'s single-arg path calls requireNumericOrNull(params[0]) even though at that point it's statically known to be neither null, a Number, nor multi-value, so it will always throw. That's intentional (reuses the shared message) rather than dead code, just flagging it for readers.
  • Preserving the null/empty-input identities (sum() -> 0, avg() -> null) with explicit tests is a nice touch.
  • Tests assert on exception type and message content rather than just 'throws', covering single-arg, list-literal, multi-arg, and mixed valid/invalid cases for both functions.

Test coverage

Good coverage for the Cypher-facing behavior described in the PR. There's no test exercising the plain-SQL sum() path via an actual SELECT sum(...) query (only direct SQLFunctionSum.execute(...) unit tests), which is a minor gap since the unit tests do exercise the same code path.

Nice work tracing this back to the shared SQLFunctionSum class and documenting the rejected alternative (a dedicated CypherSumFunction) instead of just bolting on a new class.

@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 68.01%. Comparing base (6bbb0e7) to head (4f182e6).
⚠️ Report is 5 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5908      +/-   ##
==========================================
- Coverage   68.39%   68.01%   -0.39%     
==========================================
  Files        1794     1794              
  Lines      152707   152711       +4     
  Branches    32366    32365       -1     
==========================================
- Hits       104450   103862     -588     
- Misses      34843    35469     +626     
+ Partials    13414    13380      -34     

☔ 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 5c31e94 into main Aug 7, 2026
27 of 31 checks passed
@robfrank
robfrank deleted the fix/5799-cypher-sum-avg-silently-ignore-non-numeric branch August 7, 2026 14:14
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Aug 11, 2026
Brings the fork up to 26.9.1-SNAPSHOT, which carries the August fixes we
filed: ArcadeData#5711 (HTTP row truncation), ArcadeData#5745/ArcadeData#5788 (GAV), ArcadeData#5746 (Cypher through
GAVFusedChain), ArcadeData#5747 (close-time HNSW rebuild, our PR ArcadeData#5787), ArcadeData#5796 (Redis
port), ArcadeData#5824 (@Rid IN replanned as FETCH FROM RIDs). All verified against
the shipped jars before this merge.

Conflicts resolved:
- 15 .github files kept deleted. Upstream CI the fork does not run; we carry
  only the five Python workflows.
- test-python-examples.yml took upstream's two dependabot SHA bumps
  (setup-java v5.6.0 -> v5.7.0, cache v4.3.0 -> v6.1.0), staying aligned
  with the SHA-pinning their review requires.
- test_server_wire_protocols.py kept ours. Upstream carries the version from
  PR ArcadeData#5807, which still has the redis xfail; ArcadeData#5796 is fixed and the marker
  was retired in a5d82c0.

Behaviour changes to watch, none of which renamed or removed a JPype-facing
API: ArcadeData#5969 now validates SQL function and method arity, ArcadeData#5908 makes sum/avg
reject non-numeric input, ArcadeData#5983 bounds regex backtracking, and ArcadeData#5786 caps
vector.neighbors groupBy output per index.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_0173qFfapQBiGxaV7apSZ4X8
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.

sum() and avg() silently ignore non-numeric inputs instead of reporting a type error

1 participant