Repository navigation
fix(#5855): re-enable plan cache for parameterized @rid filters - #6113
Conversation
PR #5854 (fixing #5824) rewrote WHERE @Rid = <RID> / WHERE @Rid IN [<RID list>] into a direct FetchFromRidsStep fetch, but that step resolves the bound RID(s) at plan-build time and bakes them in, and never overrode canBeCached()/copy() - so the whole plan defaulted to non-cacheable and a "get by id" query re-planned from scratch on every execution instead of hitting db.getExecutionPlanCache(). Mirror FetchFromTypeWithFilterStep's pattern: add a package-private BooleanExpression-based FetchFromRidsStep constructor that stores the original @Rid = ? / @Rid IN ? condition and re-resolves it lazily against the live CommandContext on the first pull of every execution, including a cache-hit re-execution with different bound parameters. That variant overrides canBeCached()=true and copy(); the legacy Iterable<RID> constructor (every other call site) is untouched and stays non-cacheable, matching the issue's own scoping note. SelectExecutionPlanner.handleTypeWithRidFilter now always chains the deferred-resolution step once the condition is resolvable in shape, instead of short-circuiting to EmptyStep when this particular build's resolved RID list happens to be empty - EmptyStep is explicitly non-cacheable for exactly this "bakes in a build-time fact" hazard, and baking "empty on this build" into a reused plan would be wrong for a later execution bound to a non-empty list. extractRidEqualityOrInList moved from private to package-private static so FetchFromRidsStep can call it during lazy resolution. Also fixes a millisecond-resolution test race exposed while running the new tests as part of the wider com.arcadedb.query.sql.** suite: RidInScanOptimizationTest.beginTest() creates types, which invalidates the plan cache (ExecutionPlanCache.lastInvalidation, stamped via System.currentTimeMillis()); on a hot/warmed-up JVM the type creation and the test's first query can land in the same millisecond tick, so SelectExecutionPlanner's cache-put guard (which requires planningStart to be strictly after lastInvalidation) skips caching a plan that was legitimately built after the invalidation. This only became reachable once these @Rid plans became cacheable. Not a bug in the fix itself; beginTest() now waits for the millisecond clock to tick forward before returning.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Coverage variation | ✅ -6.52% coverage variation |
| Diff coverage | ✅ 81.48% diff coverage |
Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (c66f0c8) 155549 121937 78.39% Head commit (845b9b8) 188489 (+32940) 135467 (+13530) 71.87% (-6.52%) 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 (#6113) 54 44 81.48% 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.
ReviewNice, well-documented fix for the core caching issue (#5855), and the PR description/commit message are unusually thorough. I dug into Correctness bug: mixed valid/invalid
|
…time shape check Review on PR #6113 found a real correctness regression: extractRidEqualityOrInList served two different callers with incompatible contracts. At build time (SelectExecutionPlanner.handleTypeWithRidFilter) it's a speculative "is this shape even a candidate" check where aborting the whole list to null on one unresolvable element is correct, because the caller falls back to a normal scan that evaluates the condition itself. But this PR also called the exact same method from FetchFromRidsStep.syncPull as the FINAL runtime answer on every cache-hit re-execution - with no scan fallback left. A list with one unresolvable element (e.g. "@Rid IN [validRid, notARid]") silently returned zero rows instead of matching the resolvable RID, a real behavioral divergence depending on whether the plan happened to be reused from the cache. Split into two methods: extractRidEqualityOrInList keeps its original abort-to-null behavior for the build-time shape check, and a new resolveRidEqualityOrInListAtRuntime resolves whatever it can and skips unresolvable elements, mirroring how a normal per-record IN scan treats a non-RID element. The runtime variant also no longer swallows an exception from evaluating the right-hand expression into "no rows" - that's a genuine execution-time error now, not "unknowable at plan time". Added ridInListWithOneUnresolvableElementStillMatchesTheResolvableOnesOnCacheReuse, reproducing the reviewer's exact repro: confirmed it fails against the pre-fix code (empty result instead of the one valid match) and passes after the fix. Re-ran com.arcadedb.query.sql.** (2486 tests) clean, 0 failures.
|
Addressed the correctness bug: split `extractRidEqualityOrInList` (build-time shape check, unchanged) from a new `resolveRidEqualityOrInListAtRuntime` (used by `FetchFromRidsStep.syncPull`), which resolves whatever it can and skips unresolvable list elements instead of aborting the whole result to empty, and no longer swallows a right-hand-expression exception into "0 rows" at runtime. Added `ridInListWithOneUnresolvableElementStillMatchesTheResolvableOnesOnCacheReuse`, reproducing your exact repro - confirmed it fails against the pre-fix code (empty result) and passes after the fix. Re-ran `com.arcadedb.query.sql.**` (2486 tests) clean. The two minor notes (exception-propagation semantics, and text-keyed-cache-decided-by-first-execution as a known limitation) are addressed by the same change / left as documented limitations respectively, per your own framing of them as non-blocking. |
ReviewWent through both commits (the caching fix plus the follow-up "split runtime resolution from build-time shape check"). Overall this is a well-reasoned fix with good test coverage, and the second commit shows the kind of self-review I'd want to see (catching the Design note: the cached plan's shape is still decided by the first execution's bound value
Before this PR that didn't matter, since nothing was cached - every execution re-ran the shape check against its own live value. Now that the resulting plan is cached under the raw statement text ( Minor: unused import
Minor: "exceptions propagate at runtime" isn't quite true for every path
Nit: duplicated "resolve the IN right-hand side" logic
Nit: FQN instead of import in the new test
What looks solid
|
…fix nits - Factor the shared "compute the IN right-hand raw value" logic out of extractRidEqualityOrInList and resolveRidEqualityOrInListAtRuntime into one resolveInRightHandRawValue helper, per review: the two methods having slightly different contracts is exactly what caused the bug fixed in the prior commit, so keep them from drifting apart silently again. The math-expression evaluation is left uncaught in the shared helper; each caller applies its own policy (catch-and-fallback at build time, propagate at runtime). - Removed FetchFromRidsStep.java's now-unused `import java.util.List`. - RidInScanOptimizationTest: import java.util.Arrays instead of the FQN. - Corrected resolveRidEqualityOrInListAtRuntime's Javadoc, which overstated the propagation guarantee: only the getRightMathExpression() path can throw and propagate; extractRidValue (equality operand, each IN-list literal item) still fails safe to "no match" on any exception in both methods, unchanged from before this split. - Documented the known tradeoff at the build-time call site: the cached plan's shape is decided by the first execution's bound value, so an atypical first bind (null, or one bad IN-list element) locks that statement text into the scan fallback until the next cache invalidation - not a correctness issue, just a missed optimization for that call pattern. Re-ran com.arcadedb.query.sql.** (2486 tests) clean, 0 failures.
ReviewSolid fix, and the PR description/commit history shows the author already caught and fixed a real correctness bug (the Correctness
Minor / non-blocking
Test coverageGood coverage of the actual regression: cacheability assertions ( No performance or security concerns — this only removes redundant re-planning work and doesn't change what records a query can return (confirmed the RID-existence check, type filter, and partition-pruning-bypass behavior in |
|
Review is clean, remaining notes are all explicitly non-blocking (double-evaluation on cache-miss builds is pre-existing shape, not a regression; the documented first-bind tradeoff is an accepted scope boundary). Leaving this for merge review. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #6113 +/- ##
==========================================
+ Coverage 69.62% 69.67% +0.05%
==========================================
Files 1818 1821 +3
Lines 155549 156146 +597
Branches 32848 32959 +111
==========================================
+ Hits 108299 108798 +499
- Misses 33651 33677 +26
- Partials 13599 13671 +72 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Closes #5855
Context
PR #5854 (fixing #5824) rewrites
WHERE @rid = <RID>/WHERE @rid IN [<RID list>]on a typetarget into a direct
FetchFromRidsStepfetch instead of a full type scan. That step resolves thebound RID(s) at plan-construction time and bakes them into the step.
FetchFromRidsStepdoesn'toverride
canBeCached()/copy(), so it defaults tocanBeCached() == false(
ExecutionStepInternal.java), making the whole plan non-cacheable. A "get by id" query executedrepeatedly with different bound RIDs re-plans from scratch every execution instead of hitting
db.getExecutionPlanCache().Before PR #5854 the same query fell through to
FetchFromTypeWithFilterStep, which is cacheable:it stores the
WhereClauseAST and re-evaluates it fresh against bound parameters on everyexecution.
Fix
Mirror
FetchFromTypeWithFilterStep's pattern: instead of baking resolvedRIDvalues intoFetchFromRidsStepat plan-build time, add a variant that stores the originalBooleanExpression(the
@rid = ?/@rid IN ?condition) and re-resolves it lazily against the liveCommandContexton the first pull of every execution, including a cache-hit re-execution withdifferent bound parameters. That step overrides
canBeCached()to returntrueandcopy()tocarry the (immutable) condition forward into the copy handed out by
ExecutionPlanCache.get()/put().The legacy
FetchFromRidsStep(Iterable<RID>, CommandContext)constructor (used by every othercall site:
FROM [#1:0, #1:1], a bind-parameter/variable RID target, a function-call target,FetchEdgesFromVertexStep's sibling paths, etc.) is untouched and stays non-cacheable, matchingthe issue's own scoping note that those call sites were already non-cacheable before PR #5854.
SelectExecutionPlanner.handleTypeWithRidFilternow always chains the deferred-resolution steponce the condition is confirmed resolvable in shape (
extractRidEqualityOrInList(...) != null)rather than short-circuiting to
EmptyStepwhen the value the condition resolves to at thisparticular build happens to be empty (e.g. an
IN-list bound tonullon the very firstexecution). Baking that build-time "this execution's RIDs happen to be empty" fact into a cached,
reused plan would be wrong for a later execution bound to a non-empty list -
EmptyStepitselfcarries the comment "DON'T TOUCH! ... this execution plan cannot be cached" for exactly this
reason. Resolving to an empty RID set inside
FetchFromRidsStep.syncPullproduces the samezero-row result without that hazard, on every execution.
extractRidEqualityOrInListmoved fromprivateto package-private static soFetchFromRidsStep(same package) can call it during lazy resolution.A test-only race found and fixed along the way
Running the new tests as part of the wider
com.arcadedb.query.sql.**suite (not the isolatedclass) surfaced one flaky failure in
ridInListBoundParameterPlanIsCacheableAndReresolvesOnReuse:assertThat(db.getExecutionPlanCache().contains(sql)).isTrue()occasionally failed.Root cause:
RidInScanOptimizationTest.beginTest()creates types, which callsExecutionPlanCache.invalidate()(stampslastInvalidationviaSystem.currentTimeMillis()).SelectExecutionPlanner.createExecutionPlan's cache-put guard requiresgetLastInvalidation() < planningStartbefore it will cache a freshly-built plan. On a hot/warmedJVM,
beginTest()'s schema setup and the test's first query can land in the same millisecond tick,so a plan legitimately built after the invalidation gets skipped by the guard anyway - a
pre-existing, unrelated millisecond-resolution artifact in
SelectExecutionPlanner/ExecutionPlanCache(predates this PR). It only became reachable here because this PR is whatmakes
@ridplans cacheable in the first place, so this is the first test to exercise the guardfor this step type.
Not fixing the production guard (shared, out of scope, and the actual functional correctness of
query results is unaffected either way - only the caching optimization is occasionally skipped).
Instead,
beginTest()now waits for the millisecond clock to tick forward before returning, so thesetup and the first query can never land in the same tick. Verified: re-ran the exact suite that
exposed the race (
mvn -pl engine test -Dtest='com.arcadedb.query.sql.**') after the fix - clean,2485/2485, 0 failures.
Test plan
planUsesFetchFromRidsStepForEquality/...ForBracketInList/ etc. (pre-existing SQL:WHERE @rid IN [list]is planned as a full type scan, so resolving k RIDs costs O(n) #5824 tests):keep passing unchanged - the rewrite's plan shape and results are untouched.
@rid = ?plan reportscanBeCached() == trueand is actually present indb.getExecutionPlanCache()after one execution.matching each execution's own bound value, not a stale RID baked in from the first (cached) plan
build - this is the actual regression the issue describes.
@rid IN ?bound to two different lists across two executions.IN ?bound to an empty list on the first execution, then to a non-empty list on thesecond (same cached plan reused), returns zero rows the first time and the matching rows the
second time - pins the
EmptyStep-caching hazard called out above.com.arcadedb.query.sql.**suite (2485 tests) run clean after the fix.