Skip to content

fix(#9247,#9248,#9249): SQL plan cache parameter numbers, $N on records, $matched in subqueries - #9251

Merged
lvca merged 5 commits into
mainfrom
fix/9247-9248-9249-sql-params-match
Oct 5, 2026
Merged

lvca merged 5 commits into
mainfrom
fix/9247-9248-9249-sql-params-match

Conversation

@lvca

@lvca lvca commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Fixes #9247
Fixes #9248
Fixes #9249

Tests: Issue9247ScriptPositionalPlanCacheTest, Issue9248DollarParameterTest, Issue9249MatchedInSubqueryTest (fail before, pass after). Ran query.sql packages (3700 tests; only InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo fails, same on main) and postgresw (507).

Summary by CodeRabbit

  • Bug Fixes
    • Improved SQL parameter handling in queries and scripts, including cases where parameter positions differ between statements.
    • Fixed queries using PostgreSQL-style $N parameters in edge creation, filters, projections, and other expressions.
    • Corrected MATCH filters that reference matched values inside subqueries.
    • Improved IN subquery execution when it depends on the surrounding query context.

…read on records, $matched visible in nested statements

- #9247: the printed statement used as plan-cache key now carries the parameter numbers when they are not 0..n-1 (script statements, named parameters bound by position)
- #9248: BaseExpression.execute(Identifiable) resolves Postgres $N like the Result overload (CREATE EDGE SET, function arguments on records, MATCH filters after a hop)
- #9249: MATCH matchedDependencies walks nested statements; IN subquery runs with the enclosing context as parent
@lvca lvca added this to the 26.10.1 milestone Oct 4, 2026
@lvca lvca self-assigned this Oct 4, 2026
@mergify

mergify Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

codacy-production Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 14 complexity

Metric Results
Complexity 14

View in Codacy

🟢 Coverage 96.43% diff coverage · -5.77% coverage variation

Metric Results
Coverage variation ✅ -5.77% coverage variation
Diff coverage ✅ 96.43% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (9fbef12) 212641 180988 85.11%
Head commit (77d044c) 245272 (+32631) 194604 (+13616) 79.34% (-5.77%)

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 (#9251) 28 27 96.43%

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.

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 18 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9128d3f5-c955-4efc-bf8e-0574ba9d89c2
📥 Commits

Reviewing files that changed from the base of the PR and between 9fbef12 and 77d044c.

📒 Files selected for processing (9)
  • engine/src/main/java/com/arcadedb/query/sql/executor/MatchExecutionPlanner.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/SqlAstInspector.java
  • engine/src/main/java/com/arcadedb/query/sql/parser/BaseExpression.java
  • engine/src/main/java/com/arcadedb/query/sql/parser/InCondition.java
  • engine/src/main/java/com/arcadedb/query/sql/parser/Statement.java
  • engine/src/test/java/com/arcadedb/query/sql/executor/Issue9247ScriptPositionalPlanCacheTest.java
  • engine/src/test/java/com/arcadedb/query/sql/executor/Issue9248DollarParameterTest.java
  • engine/src/test/java/com/arcadedb/query/sql/executor/Issue9249MatchedInSubqueryTest.java
  • engine/src/test/java/com/arcadedb/query/sql/executor/SqlAstInspectorParameterNumbersTest.java
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9251 (fixes #9247, #9248, #9249)

Overall this is a well-scoped fix. Each issue has its own regression test, and the change reuses existing pieces (SqlAstInspector.allNodesMatch, collectMatchedAliases, postgresPositionalParameterKey). I read the diff and surrounding code only; I did not run the tests.

What looks good

Points to check

  1. Parse-time assignment of originalStatementAsString bypasses the suffix. SQLAntlrParser.parseScript (around line 185) sets stmt.originalStatementAsString = sqlScript for every statement. StatementCache.parse and SQLAntlrParser.parse also set it to the raw text. getOriginalStatement() only appends the suffix when that field is null. The tests suggest the script path goes through setOriginalStatement(...), which nulls the field, so this is probably fine. It is a fragile invariant, though: anything that reads the key while the field is still preset gets the old behaviour. A short comment in Statement.getOriginalStatement() stating that the suffix only applies to the lazily computed key would help. A direct unit test of the Statement key for a script statement would help too.

  2. Missing unit test for parameterNumbersSuffix. The behaviour is only covered end to end. A small direct test would pin down the contract:

    • sequential numbering returns ""
    • an offset or reordered numbering returns the suffix
    • mixed named and positional parameters
    • no parameters

    This matters because the key now depends on walk order. Same printed text means same tree shape, so same walk order, so the key is injective. That is correct, but it relies on AST_FIELDS ordering from getDeclaredFields(), which the JVM does not formally guarantee. It is stable in practice and only needs to be stable within one JVM run, so this is acceptable. The reasoning deserves a line in the Javadoc.

  3. Since #9218, an UPDATE or DELETE with positional parameters reuses the cached plan of an earlier statement with the same WHERE and reads the WHERE from the wrong parameter: the UPDATE changes another record, the DELETE deletes nothing #9245 DML source key. The PR description says this "also covers the DML source key for Since #9218, an UPDATE or DELETE with positional parameters reuses the cached plan of an earlier statement with the same WHERE and reads the WHERE from the wrong parameter: the UPDATE changes another record, the DELETE deletes nothing #9245", but no test exercises a DML statement (UPDATE ... WHERE x = ? or DELETE) inside a script with an offset parameter. Please add one, since DmlSourcePlanKey.resolve memoizes its key permanently.

  4. InCondition parent context. Passing the enclosing context as parent makes every enclosing variable visible to the subquery. For example $parent and $current now resolve differently, and a subquery's own variables could in principle be shadowed or confused. The $matched case is covered. There is no test that an uncorrelated IN (SELECT ...) in a plain SELECT, or one using $parent, still behaves the same. You mention InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo already fails on main. Since this change touches exactly the subquery-context area, please confirm it fails for the same reason and not a new one.

  5. Tests.

    • Issue9247...: inSubqueryNamedParameterBoundByPositionAlone and the sibling tests rely on the earlier statement populating the cache. Asserting on the cache size or key would make the intent explicit rather than relying on execution order.
    • The n property is set on H/I/J documents without being declared. That works (schemaless), but declaring it would match the other properties.
    • Issue9249: all counts are hard-coded (12, 2). A one-line comment explaining the arithmetic would help the next reader.

Minor / style

  • parameterNumbersSuffix uses an int[][] holder and an int[] size to mutate state from the lambda. It works but is awkward. A small private growable-int helper, or an existing primitive list in the code base, would read better. Primitives are the right choice for GC pressure per CLAUDE.md, so this is only about readability.
  • The Arrays import is used only for copyOf, which is fine.

No blocking issues found. I would address point 3 (a DML-in-script test) and point 4 (confirm the pre-existing failure) before merging.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9251

Well-scoped fix, and each of the three issues has a regression test. I read the diff and the surrounding code but did not run the tests. Findings below, none blocking.

What looks good

Points to consider

  1. matchedDependencies now also sees $matched in function arguments (MatchExecutionPlanner.java:754). collectMatchedAliases walks the whole tree, so it reports aliases that getMatchPatternInvolvedAliases() never did. That is more correct, but it can change node ordering or prefetch decisions for existing MATCH queries that pass $matched.x to a function. The new tests only cover IN and .size() subquery shapes. A test with a plain function argument, e.g. where: (coalesce($matched.a.g, 0) = g), would confirm the plan stays correct.

  2. InCondition now passes the enclosing context as the subquery's parent. This widens variable visibility ($matched, $parent, $current, user variables) for every IN subquery, not just inside MATCH. uncorrelatedAndParentInSubqueryUnchanged covers $parent.$current. Please also check that a subquery's own LET or $current cannot leak into or shadow the outer context. The PR notes InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo fails "same on main". Since this PR changes how the subquery is executed, please confirm the failure is identical before and after.

  3. parameterNumbersSuffix (SqlAstInspector.java)

    • It uses the reflection-based allNodesMatch. SelectStatement.executingPlanCanBeCached calls setOriginalStatement(this), which resets the cached string, so the walk runs on the first lookup of any statement not held in StatementCache. A fast path for statements without parameters would keep that cheap.
    • The int[][] holder plus int[] size pair is awkward. A small private holder class with int[] numbers and int size reads better and still avoids boxing.
    • The Javadocs on this method and on Statement.getOriginalStatement are long. CLAUDE.md asks for one short line max, so please trim them to the why.
  4. Reflection field order drives the walk. The Javadoc says the key is stable within a JVM run, which is enough for an in-memory cache, but the key must never be persisted or compared across nodes (for example in HA). A one-line note would prevent misuse.

  5. Tests

    • sameScriptRepeatedStaysRight checks correctness only. Asserting that an identical repeated script statement actually hits the plan cache would guard against the suffix making keys unstable and silently disabling caching.
    • The Issue9249 tests assert only counts (12 and 2). Asserting the returned rows for at least one case would catch a result that has the right size but the wrong content.
    • In Issue9248DollarParameterTest.createEdgeSet, the Object[] named from holds the parameters, so params would be a clearer name.

Security and performance

No security concerns. The extra walks happen at planning time on plan-cache misses, with no new per-row cost.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review

Overall this is a focused set of fixes and each bug has a regression test. I found no blocking issues, only some small points.

What looks good

Points to address

  1. Style, Statement.getOriginalStatement(): The if has a mis-indented standalone { and uses braces around a block, which doesn't match the surrounding code. It will probably trip formatters and reviewers. Something like this reads better:
    if (originalStatementAsString == null) {
      final String text = originalStatement.toString();
      originalStatementAsString = ...;
    }
  2. Failing test claimed as "same on main": InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo is about subqueries and memo leakage, which is exactly the code InCondition.executeQuery now touches (a new parent context). Please double-check that it fails on main for the same reason, and that passing the parent context does not extend the lifetime of anything memoized on the enclosing context. If it already fails on main, a link to the tracking issue would help.
  3. Variable visibility: With the enclosing context as parent, every variable of the outer context (LET variables, $current, etc.) is now visible to every IN subquery, not only $matched. That is probably desirable and consistent with other subquery paths. It is a behavior change, though, so a short test of a LET variable shadowing or being read inside an IN subquery would pin it down.
  4. Suffix for named parameters: Named parameters are bound by name, so a :x that is numbered 3 in a script and 0 alone now gets two cache entries for the same logical plan. This is harmless apart from some duplicate plans, and it is simpler than special-casing. The /*params:..*/ format also isn't tested against statements whose text contains ? or : inside string literals. Those only cost an unneeded tree walk, which is fine, but a test of the fast-path guard ('a:b' literal gives an empty suffix) would document it.
  5. Reflection walk cost: parameterNumbersSuffix goes through SqlAstInspector.allNodesMatch (reflection plus an IdentityHashMap). It runs once per statement object, so it's acceptable. That is only true while statements are cached or reused, though. If any hot path creates a fresh Statement per execution, with the preset-less text, this walk becomes a per-call cost. The StatementCache presetting originalStatementAsString suggests that path is covered, but it would be worth confirming for the non-cached command() path.
  6. matchedDependencies: The union of getMatchPatternInvolvedAliases() and the full-tree walk is correct. A bare $matched (no alias suffix) inside a nested statement is still invisible here, as it is in outerAliasesRead, which falls back to the whole tuple. Consider a one-line comment saying so, or a test for it, since the new Javadoc implies nested reads are now fully handled.
  7. Test nit: Issue9247...sameScriptRepeatedStaysRight asserts on the literal key text /*params:1*/. It is useful, but it couples the test to the exact format. The SqlAstInspectorParameterNumbersTest already pins the format, so this one could assert on cache size or presence instead.

Nothing else stood out for security or performance. Once the style nit and the item 2 clarification are addressed, this looks good to merge.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review

Overall this is a solid, well-targeted fix. I read the main-source diff in full and skimmed the tests. I did not build or run anything.

What looks good

Points to consider

  1. Parent context for IN subqueries (behavior change): The subquery now sees the outer context's variables ($parent, $matched, LET variables). The new tests cover the uncorrelated, $parent.$current and LET cases. One more test would help: a subquery that defines its own LET variable with the same name as an outer one. This confirms setParentWithoutOverridingChild really leaves the child's value in place. Also confirm that the subquery's plan is still cacheable and correct when run under different parent contexts.
  2. Walk-order stability of the key: parameterNumbersSuffix relies on allNodesMatch visiting nodes in an order that doesn't change. That order comes from reflection over fields (getDeclaredFields). The Javadoc notes it is only stable within a JVM, which is acceptable for an in-memory cache. If the order ever changed between two parses of the same text, you would get duplicate cache entries, not wrong results. So the failure mode is benign.
  3. Two key shapes for one statement: Statements whose text the parser presets (StatementCache.parse, SQLAntlrParser) keep the raw text with no suffix, and only computed texts get the suffix. That is correct today, because a statement parsed alone is always numbered from 0. It does make the invariant implicit, so it's worth a short test that pins it. For example, run the same text as a single query and as the first statement of a script, and assert they share one cache entry. sameScriptRepeatedStaysRight is a bit weak here (size() >= 2 plus one contains). Asserting the exact keys would catch regressions better.
  4. Test assertion style: assertThat(...).isEqualTo("S2:b2") on rendered strings works, but asserting on the returned records would be more explicit. This is minor.
  5. Comments: Several new comments reference the issue number and are written in ALL CAPS (// ... (ISSUE #9249)). The all-caps style matches nearby code, but CLAUDE.md asks for comments that explain the non-obvious WHY and not the task. Consider dropping the (ISSUE #...) suffixes, since git blame covers that.
  6. Unrelated failure: The PR notes that InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo also fails on main. It would help to link a tracking issue so it doesn't get lost.

Security and performance

  • I see no new security surface.
  • The cost of the key change is one extra AST walk per statement the first time its key is computed, and only for statements whose text contains ? or :. The result is memoized in originalStatementAsString, so it is not repeated per execution.

No blockers from my side. Items 1 and 3 are the ones I'd most like to see covered by a test before merge.

…che-key assertions, drop issue-number comments
@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of #9251

Solid, well-scoped fix for three related bugs. The regression tests cover the failing scenarios (the PR notes they fail before and pass after). I found no blocking problems; the notes below are small suggestions and questions.

What looks good

Points to consider

  1. Behavior change in InCondition.executeQuery: passing the enclosing context as parent makes every outer variable visible to the subquery ($parent, LET variables, $current...), not only $matched. Probably the desired semantics, but broader than the issue title suggests. Could you add a test that an uncorrelated IN (SELECT ...) behaves identically, and one where an outer LET variable or $parent is read inside the subquery, so the new visibility is pinned deliberately?
  2. matchedDependencies redundancy: getMatchPatternInvolvedAliases() is called and then collectMatchedAliases walks the whole tree, which should find everything the first call finds. If the full walk is a strict superset, the first call could be dropped, or a comment could say why both are needed. Planning-time only, so minor.
  3. Key stability: parameterNumbersSuffix depends on the reflective walk order of allNodesMatch. The Javadoc already says the key is JVM-local, and a different order could only cause a cache miss, never a collision, so this is safe.
  4. Style nit: final int[][] holder = { new int[4] }; final int[] size = { 0 }; is an awkward way to grow an array from inside a lambda. A tiny private accumulator or an existing int-list helper would read better.
  5. indexOf(':') heuristic: : in string or map literals only costs one extra AST walk per cached statement. It is a performance shortcut, not a correctness check, which is fine.

Tests

  • The four new test classes follow project conventions (assertThat(...), TestHelper, no System.out, no hardcoded ports).
  • InScalarPropertyNotConvertedTest.subqueryAndReexecutedStatementDoNotLeakTheMemo is reported failing on both this branch and main. Since this PR touches InCondition.executeQuery, please confirm the failure has the same cause as on main (or link an issue) before merging.

No security concerns: the suffix is built only from integer parameter numbers, never from user-supplied text.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Oct 4, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.85714% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.89%. Comparing base (9fbef12) to head (77d044c).

Files with missing lines Patch % Lines
...m/arcadedb/query/sql/executor/SqlAstInspector.java 91.30% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9251      +/-   ##
============================================
+ Coverage     76.88%   76.89%   +0.01%     
  Complexity     3914     3914              
============================================
  Files          2125     2125              
  Lines        212641   212668      +27     
  Branches      45156    45164       +8     
============================================
+ Hits         163479   163522      +43     
+ Misses        31690    31674      -16     
  Partials      17472    17472              

☔ 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.

@lvca
lvca merged commit 3543960 into main Oct 5, 2026
@lvca
lvca deleted the fix/9247-9248-9249-sql-params-match branch October 5, 2026 01:58
This was referenced Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment