Repository navigation
fix(engine): native select must not cap the index candidate scan by the result limit - #6571
Conversation
…idate cap before evaluateWhere() and skip SelectExecutor.lookForIndexes() handed the query's RESULT limit straight to MultiIndexCursor as a CANDIDATE cap on the index scan. Downstream, evaluateWhere() and skip still reduce that candidate stream further, so the cap was spent before the filtering it was meant to survive. Two shapes lost rows silently: an indexed condition combined (via AND) with a non-indexable condition such as IS NOT NULL - only one AND child ever keeps its index cursor (filterWithIndexesFinalNode), so the other conjunct is re-checked later against a stream already capped too early - and ordinary skip+limit paging over an indexed equality, where reaching row skip+1 needs skip+limit candidates but the cap was just limit, going empty whenever skip >= limit. The candidate cap is now only applied when the index scan exactly reproduces the where-tree's result set (a bare indexed leaf, or an OR of such leaves - the union shape MultiIndexCursor already merges); otherwise the scan runs uncapped, matching what the SQL engine already does for the same query shapes. When it does apply, the cap is skip + limit rather than limit, and the nested per-value cursor built for an IN leaf now shares that same corrected cap instead of a raw select.limit that was missing skip. MultiIndexCursor.hasNext() also admitted one candidate more than asked for (browsed > limit instead of browsed >= limit); the two candidate-cap call sites were the only ones using a real limit, so tightening it does not affect the unbounded (-1) callers elsewhere. Fixes #6565
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 22 |
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.
Review of #6571This is a well-targeted fix with a clear write-up, and the Bug:
|
…ic run-wrapper Code review on #6571 found that isWhereExactlyIndexed() missed the tree shape Select.compile() actually produces for a where-clause with no and()/or(): its trailing setLogic(SelectOperator.run) wraps the lone condition in a synthetic node (Select.setLogic()'s "1ST TIME ONLY" branch) whose left is a SelectTreeNode and whose operator is run - a shape the exactness check didn't recognize as a leaf or as an or, so it fell through to false. That silently kept the restored skip+limit cap from ever engaging for the single most common query shape (a bare indexed equality, or a bare IN), leaving the fallback -1 (uncapped) in its place. Uncapped is always correct, so no query returned wrong results - but four of the seven regression tests only passed because that fallback is trivially correct too, not because they exercised the cap this PR restores. run is otherwise never used as a tree operator (grep-confirmed the only two call sites are compile()'s single finalizing call and the "1ST TIME ONLY" branch that consumes it, which always sets right to null), so it is now treated the same as or: a transparent pass-through to its children. Also widens lookForIndexes()/indexCandidateLimit from private to package-private so the new regression tests can assert on the computed cap directly - a row-count assertion can't tell a correctly applied cap apart from the uncapped fallback, since the lazy-pull consumers (SelectIterator, executeCount()) already stop at skip + limit on their own either way, which is exactly how the four tests above stayed green despite the bug.
|
Good catch, thanks - confirmed the tree shape via `Select.setLogic()`'s "1ST TIME ONLY" branch and `grep`-verified `SelectOperator.run` has no other call sites. Fixed in 8e6dd6e: `isWhereExactlyIndexed()` now treats `run` as a transparent pass-through, same as `or`. Since a row-count assertion can't distinguish "cap correctly computed" from "cap stayed at -1 but the lazy-pull consumers bounded it anyway" (as you pointed out for 4 of the 7 original tests), I widened `lookForIndexes()`/`indexCandidateLimit` to package-private and added two new tests (`singleBareEqualityCandidateCapCoversSkipPlusLimit`, `singleBareInCandidateCapCoversSkipPlusLimit`) that assert on the computed `indexCandidateLimit` directly. Both fail with `-1` instead of the expected `skip+limit` on the pre-fix code, confirmed by reverting the one-line fix locally and re-running. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages (222 classes / 1207 tests) still green. |
ReviewTraced the fix through Correctness
Minor observations (non-blocking)
Nothing here blocks merging - the core fix is sound, well-reasoned, and the regression test does a good job of exercising both the "shape disqualifies the cap" path and the "cap must be skip+limit" path independently. |
…candidate-cap fix Code review on #6571 flagged a gap: no test exercised a nested AND under an OR (e.g. (a=1 AND b=2) OR c=3, which precedence-driven Select.setLogic() builds as or(and(a,b), c)), or a bare NOT leaf, both of which must fall through isWhereExactlyIndexed()'s conservative false. Both are added, asserting on indexCandidateLimit directly for the same reason the two prior additions did: a row-count assertion can't tell "correctly stayed uncapped" apart from "should have been capped but wasn't". NOT has no fluent entry point on the Select builder today (SelectOperator.not exists but nothing in the fluent API reaches it), so that tree is built by hand with SelectTreeNode's public constructor.
|
Added the two suggested cases in 5c973a2, both asserting on `indexCandidateLimit` directly (`-1`), same rationale as before:
Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1209 tests). |
ReviewI traced the tree-construction logic in Correctness
Minor / non-blocking observations
Test coverageStrong. The regression suite covers both original bug shapes (AND + non-indexable conjunct, skip≥limit paging), the OR-of-ranges union shape, the IN nested-cursor path, and - added during the PR's own code review cycle - the AND-under-OR and bare-NOT tree shapes that must stay conservative. Asserting No security or performance concerns; this is a pure query-planner correctness fix with a well-justified, narrowly-scoped API widening ( |
…s second code-review round - The indexCandidateLimit computation must run before filterWithIndexes(): isWhereExactlyIndexed() unconditionally disqualifies 'and', so it doesn't currently observe the sibling node.index pruning filterWithIndexesFinalNode() does as a side effect of building an AND branch's cursor - but that ordering becomes load-bearing the moment 'and' disqualification is ever loosened. - computeExactCandidateLimit()'s overflow fallback deliberately returns -1 (the same "run uncapped" sentinel used everywhere else) rather than clamping to Integer.MAX_VALUE. - Sharing indexCandidateLimit with the nested per-value cursor built for an in_op leaf is a proven-safe over-approximation (the outer cursor never pulls more than skip + limit total across all children regardless), not just convenient reuse of the same number. Also opened #6575 to track a separate, currently-unreachable observation from the same review round: SelectOperator.not has no fluent entry point on Select today, so filterWithIndexesFinalNode()'s handling of an indexed leaf directly under a hypothetical NOT node is untested and would need attention if NOT ever becomes fluently reachable. No code changes needed here since it's unreachable and evaluateWhere() already guarantees correctness regardless.
|
Thanks for the thorough second pass. Addressed the three cheap documentation suggestions in e43242d:
For the out-of-scope `NOT` observation: agreed it's worth tracking, opened #6575. No code change here since it's unreachable via the fluent builder today and `evaluateWhere()` already guarantees correctness regardless (it would just be a latent efficiency issue if/when `NOT` becomes fluently reachable). All 11 regression tests + full `com.arcadedb.query.select`/`com.arcadedb.index` packages still green. |
ReviewNice, methodical fix - the root-cause analysis in the PR description matches the code ( Correctness: the cap is still unsafe for
|
…-memory sort Code review on #6571 found a third downstream consumer that reduces the index candidate stream further, the same bug class this PR is fixing for evaluateWhere()/skip: SelectIterator.fetchResultInCaseOfOrderBy() drains and sorts the *full* iterator whenever the requested order doesn't trivially match the where clause's forced ascending index scan (filterWithIndexesFinalNode() always scans ascending). When the candidate cap this PR restores capped that same iterator at skip + limit, the sort only ever saw the first few candidates in ascending scan order instead of every match - e.g. `WHERE n > -1 ORDER BY n DESC LIMIT 10` returned n=9..0 instead of the true n=999..990. Confirmed by reproducing exactly that query before this fix. This predates the PR (the old code capped unconditionally at select.limit, so the same query was already broken), and SelectOrderByTest.okOrderByNoIndexDescendingIndexServedProperty is a near-miss regression test for it - it exercises the same mismatched-direction shape but without a limit(), so select.limit < 0 already short-circuited the old cap to -1 and the test couldn't see the bug. Closing it here too since it's directly adjacent to the mechanism this PR changes. Fix: soleExactLeaf() finds the tree's one and only indexed leaf (null for anything but a bare leaf, since an OR always contributes 2+ usedIndexes entries and can never satisfy SelectIterator's own usedIndexes.size() == 1 trivial-match precondition either). isOrderBySafeForCap() then mirrors that same trivial-match check (single leaf, matching property, ascending direction) before letting the cap engage - preserving the optimization for the common case (ORDER BY the same ascending-indexed property) while falling back to -1 whenever the sort would need the full candidate set. Two new tests: one reproduces the bug exactly as described (fails pre-fix, passes post-fix), the other confirms the cap still engages when the order trivially matches, so the optimization isn't lost wholesale.
|
Good catch, and a real gap - confirmed by reproducing `WHERE n > -1 ORDER BY n DESC LIMIT 10` before fixing: got `n=9..0` instead of the correct `n=999..990`, exactly as predicted. Fixed in 9fbedca: `soleExactLeaf()` finds the tree's one and only indexed leaf (`null` for anything but a bare leaf, since an `or` always contributes 2+ `usedIndexes` entries and can never satisfy `SelectIterator`'s own `usedIndexes.size() == 1` trivial-match precondition either), and `isOrderBySafeForCap()` mirrors that same trivial-match check (single leaf, matching property, ascending direction) before letting the cap engage. So the optimization is preserved for the common case (`ORDER BY` the same ascending-indexed property) rather than disabling it wholesale for any `orderBy`. Two new tests: one reproduces the bug exactly as described (confirmed fails pre-fix), the other confirms the cap still engages when the order trivially matches, so the fix isn't overly conservative. Also tightened #6575's description per your correction - the `NOT` gap is a correctness bug (silently returns zero rows), not just an efficiency regression. No code change there since it's still unreachable via the fluent builder today. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1211 tests). |
ReviewTraced the fix end-to-end against Select.java's tree-building (setLogic/compile), SelectIterator.fetchResultInCaseOfOrderBy(), and every other new MultiIndexCursor(...) call site in the codebase. Solid piece of work - the commit history shows this already went through several self-review rounds (the synthetic run-node gap, the AND-under-OR shape, and the ORDER BY interaction were all caught and fixed before this review). A few notes below; nothing blocking. Correctness - verified
Minor / non-blocking observations
Test coverage One gap I don't see covered: a query that is exactly indexed and paginated (skip > 0) and has an IN leaf, combined with an OR - e.g. (g IN (...) OR n = 5) with skip/limit. The existing inOperatorWithSkipAndLimitPagesCorrectly and orOfTwoIndexedRangesWithSkipAndLimitPagesCorrectly tests cover each shape independently but not their combination (nested per-value cursor sharing indexCandidateLimit while also being one child of an outer OR-merged MultiIndexCursor). Given the "safe over-approximation" reasoning documented on the sharing, I'd expect this to already be correct, but a test would make that explicit rather than inferred. Note: I wasn't able to execute mvn test in this review environment (sandboxed, build commands require interactive approval), so I'm relying on the PR description's documented test run (222 classes / 1205 tests, 0 failures) rather than independently confirming it. |
…it for #6565 Code review on #6571's fourth round asked for this combination explicitly: the existing inOperatorWithSkipAndLimitPagesCorrectly and orOfTwoIndexedRangesWithSkipAndLimitPagesCorrectly tests each cover their own shape but not together, so the "safe over-approximation" reasoning documented at the IN leaf's nested cursor call site (sharing the whole tree's indexCandidateLimit is safe because no single child could ever need more than the outer cursor's total skip + limit demand) was inferred rather than tested directly. g IN (g0,g1,g2) OR n = 3 gives a union of 601 distinct matches out of 1000 rows (600 from the IN, plus exactly one row from n = 3 that falls outside the IN's residue classes) - skip(595).limit(10) exercises the nested per-value nested cursor as one child of an outer OR-merged MultiIndexCursor while paginating near the tail.
|
Thanks - "nothing blocking" on this round, and all the correctness claims check out against my own trace too. Added the suggested `(g IN (g0,g1,g2) OR n = 3)` + `skip`/`limit` test in c5316dd, making the "safe over-approximation" reasoning on sharing `indexCandidateLimit` with a nested `IN` cursor explicit rather than inferred: 601 distinct matches (600 from the IN, +1 from `n=3` falling outside the IN's residue classes), `skip(595).limit(10)` pages the tail correctly. On the two non-blocking observations (repeated tree walks, unifying the three helper methods into one pass): judged not worth it for this PR. Where-trees are small in practice (a handful of conditions, as you note), so 3-4 walks of a tiny tree is not a measurable cost, and folding `isWhereExactlyIndexed`/`soleExactLeaf`/`isOrderBySafeForCap` into one combined-return method would trade three individually-Javadoc'd, single-purpose predicates for one method returning a tuple-like result - more state to reason about for a perf win that doesn't exist at this data size. Leaving as-is; happy to revisit if a 4th consumer of "is this tree exactly indexed" ever shows up, as you suggested. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1212 tests). |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 20 |
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.
ReviewI traced the tree-construction logic ( Correctness
Test coverage is thorough: the 10 cases in Minor/non-blocking
No blocking issues found — this is a careful fix with good self-review already baked into the commit history. |
…p review-round references Code review on #6571's sixth round noted the inline comments had grown noticeably longer than the file's pre-existing style, and that a few referenced "code review round N" rather than stating the invariant directly - context that stops being discoverable once the PR scrolls off the recent-activity list. Tightened the longest blocks (lookForIndexes()'s three-invariant header, the IN-leaf nested cursor sharing note) and replaced "CODE REVIEW ON #6571" test comments with the invariant itself, following the existing Javadoc on computeExactCandidateLimit() as the model. No behavior change.
|
"No blocking issues found" on this round - thanks for the thorough field-for-field trace. Addressed the two style suggestions in 26fae67:
On the `Select.json()` deserialization path for `not`: good find, verified it independently - `parseJsonCondition()` does reach `setLogic(SelectOperator.not)` via `byName()`/`logicOperator`, and grepping `server/` plus every wire-protocol module confirms it's not wired into any handler today (only `SelectExecutionTest` calls it). Updated #6575 to note this second reachability path alongside the fluent one, since the fix is needed if either ever opens up. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1212 tests). |
ReviewSolid, well-documented fix for #6565, and the iterative self-review trail in the commit history (catching the Bug: the "OR of indexed leaves is exact" invariant doesn't hold when the branches can match the same record
So when OR branches overlap, each duplicate candidate burns one unit of the Concrete repro (single property, no cross-property setup needed): with database.select().fromType("T").where()
.property("n").gt().value(5)
.or().property("n").lt().value(500)
.limit(10).count();Every row with The new regression tests don't catch this because both OR-shaped tests deliberately use disjoint branches: Note this duplicate-candidate risk predates this PR (the old code capped every cursor-returning query at bare
Everything else looks correct
Minor / out of scope
Test coverage otherwise is thorough - the 7 (now more) cases in |
… for the candidate cap Code review on #6571's seventh round found that the "OR is exact" branch of isWhereExactlyIndexed() doesn't hold in general: MultiIndexCursor.next() is a plain k-way merge over its child cursors with no RID dedup. If the same record satisfies both OR branches - same-property ranges that overlap (e.g. `n > 5 OR n < 500`), or two different properties one record can satisfy together - it surfaces as two separate candidates, each burning one unit of the skip + limit cap before SelectIterator/executeCount()'s downstream filterOutRecords dedup ever runs. That can exhaust the cap on duplicates before enough distinct matches are found - the exact "cap spent before the filtering it needs to survive" defect this class exists to fix, reachable again through the very fast path this PR added to avoid it. Confirmed by reproducing `n > 5 OR n < 500 LIMIT 10` on every row (all 1000 satisfy the OR): got 8 instead of 10. Whether two OR branches can actually produce overlapping RID sets depends on the data, not just the where-tree's shape - unlike the AND-sibling-pruning case, there's no static structural test that proves disjointness in general (same-property range endpoints could be checked, but two different properties can never be ruled out without data statistics). So `or` now falls through to the same conservative `false` as `and`/`not`, rather than trying to special-case only the provably-safe shapes. An in_op leaf's own internal per-value cursor merge is unaffected: those values are distinct keys on the same single-valued property, so their RID sets are disjoint by construction, and that merge happens once inside filterWithIndexesFinalNode(), not through a top-level `or`. New test reproduces the duplicate-candidate bug exactly (confirmed count=8 instead of 10 before this fix), and a second test asserts indexCandidateLimit directly for a plain OR of two indexed leaves, locking in the new conservative classification the way the AND/NOT cases already do. The two existing OR-shaped tests (orOfTwoIndexedRangesWithSkipAndLimitPagesCorrectly, inLeafUnderOrWithSkipAndLimitPagesCorrectly) still pass - their comments are updated to reflect that they now exercise the uncapped fallback rather than a "correctly capped" fast path, since OR no longer gets one.
|
Excellent catch - a real, distinct bug from the one this PR started with, and one my own "OR is exact" reasoning genuinely got wrong. Confirmed by reproducing your exact repro (`n > 5 OR n < 500 LIMIT 10` over 1000 rows all satisfying the OR): got `8` instead of `10`. Fixed in 8b792ef: since disjointness of two OR branches can't be proven from the where-tree's shape alone (same-property overlap is checkable in principle, but two different properties never can be without data statistics), `or` now falls through to the same conservative `false` as `and`/`not` in `isWhereExactlyIndexed()`, rather than trying to special-case only the provably-safe shapes. The `in_op` leaf's own internal per-value merge is unaffected - those are distinct keys on the same single-valued property, so disjoint by construction, and that merge happens once inside `filterWithIndexesFinalNode()`, not through a top-level `or`. New test reproduces your exact scenario (confirmed count=8 before the fix), plus a low-level test asserting `indexCandidateLimit == -1` for a plain OR of two indexed leaves, locking in the new conservative classification. Updated the two existing OR-shaped tests' comments since they now exercise the uncapped fallback rather than a "correctly capped" fast path - OR no longer gets one. On the "minor/out of scope" `NEQ`/`LIKE`/`ILIKE`-under-OR observation: verified it independently with a scratch reproduction (`a != 'nonexistent' OR n = -1` over 1000 rows all satisfying the `!=`: returned `0` instead of `1000`) - it's real and dramatic, but confirmed pre-existing (reproduces identically on `main`) and genuinely orthogonal to the candidate-cap mechanism this PR changes (it's about which cursors get built, not how many candidates are consumed). Filed #6577 with the root cause and suggested fix rather than bundling it in here. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1214 tests). |
ReviewI traced through the where-tree construction ( Correctness
Minor, non-blocking observations
Test coverageThe 13 test cases in I wasn't able to run Nice work tracking down a genuinely subtle bug across all the shapes that could reintroduce it. |
|
Sharp catch - verified the equivalence by hand before touching anything, since this is exactly the "two predicates drift apart" failure mode this PR has already hit twice (the `run`-wrapper gap, the OR-duplicate-candidate gap). Confirmed: for a bare leaf both reduce to `node.index != null`; for a `run` node `isWhereExactlyIndexed`'s `&& isWhereExactlyIndexed(right)` is always `&& true` since `right` is always `null`, so it's the same as `soleExactLeaf`'s left-only recursion; everything else returns "not exact" either way. Folded in 378a584: dropped `isWhereExactlyIndexed()` entirely (~25 lines including Javadoc), call `soleExactLeaf()` directly at the one call site, merged the explanatory Javadoc onto the survivor. Also closed the one test gap (`computeExactCandidateLimit()`'s overflow branch, `skip + limit` overflowing `int`) - new test confirmed to fail with the wraparound value `-2147483634` when the guard is temporarily removed. One more thing worth flagging: a full-suite run after this change hit a single failure in `com.arcadedb.index.vector.Issue5558DeletedRegionSearchTest` (unrelated package, nothing there touches `MultiIndexCursor`/`SelectExecutor`) - confirmed it's a pre-existing flake by re-running it in isolation (11/11 clean) and re-running the full `select`+`index` packages again (222 classes / 1216 tests, 0 failures). PR link: #6571 |
ReviewI traced the fix end-to-end (
Minor observations (non-blocking)
Test coverage / process noteThe regression test class is thorough (14 cases covering both original shapes, the One thing worth double-checking before merge, since I can't run the suite in this environment: the PR description says the full Overall: solid, well-reasoned fix with good test coverage for a genuinely subtle bug class (candidate cap applied before downstream filtering). No blocking issues found. |
Code review on #6571's twelfth round noted the "sole exact leaf, skip+limit capped correctly" path was only tested for eq and in_op, not the range operators (gt/ge/lt/le/between) filterWithIndexesFinalNode()'s switch also turns into a cursor. soleExactLeaf() doesn't discriminate by operator, so the reasoning generalizes, but a test closes the gap explicitly rather than relying on the shared classification logic being correct by inspection. New test asserts both indexCandidateLimit (150 for skip=100/limit=50) and the actual paged count (50, out of 500 matches for n >= 500) for a bare ge leaf. Full com.arcadedb.query.select + com.arcadedb.index packages green (222 classes / 1217 tests) after this change, confirming the earlier Issue5558DeletedRegionSearchTest failure was indeed a one-off flake.
|
Thanks - "no blocking issues found" on this round. Addressed the test-coverage gap in 381144d: added `skipAndLimitOnPlainIndexedRangePagesCorrectly`, a bare `n >= 500` leaf with `skip`/`limit`, asserting both `indexCandidateLimit` (150) and the paged row count (50 out of 500 matches) - closes the gap for range operators as the sole exact leaf, alongside the existing `eq`/`in_op` coverage. Also re-ran the full `com.arcadedb.query.select` + `com.arcadedb.index` packages as you suggested given the `MultiIndexCursor` behavior change: 222 classes / 1217 tests, 0 failures - confirms the single `Issue5558DeletedRegionSearchTest` failure from a couple of rounds back really was a one-off flake, not a real regression. The two other points (pre-existing NOT gap already tracked under #6575, and the "three tree walks" redundancy note) - no action needed, as you yourself flagged them as already-covered/non-blocking. PR link: #6571 |
ReviewWent through
I did not find a remaining correctness gap in the shapes this PR now handles (bare leaf, Test coverage: strong. 19 tests (the PR description's "7 cases" reflects only the first commit; later rounds added AND-under-OR, NOT, overflow, order-by ×2, OR-duplicate, range-operator, and IN-under-OR-with-paging cases). Good mix of black-box ( Minor nits (non-blocking):
Performance note: this correctly trades away a previously-unsound optimization — No security concerns — this is pure query-planning logic over already-authenticated/authorized access, no new I/O, deserialization, or user-controlled paths. One process note: I wasn't able to execute |
…boring fields Code review on #6571's thirteenth round noted this field's declaration didn't follow the column alignment of evaluatedRecords/usedIndexes right above it. Cosmetic only.
|
Thanks for the thorough end-to-end pass - "did not find a remaining correctness gap" and "no security concerns." Fixed the trivial alignment nit in 2ad608e. The comment-length note is explicitly called out as a judgment call by you, and I've already trimmed once (round 6) and been asked to keep the remaining ones since they encode load-bearing invariants (rounds 6, 9, 11 all landed on "keep as-is") - leaving them. At this point every review round across 13 iterations has confirmed no blocking issues, and this round explicitly says it found no remaining correctness gap across all the shapes this PR now handles. I believe this PR is ready to merge. PR link: #6571 |
ReviewI traced the logic in The fix itself is sound. The core insight - a candidate cap is only safe when the index scan exactly reproduces the where-tree's result set, otherwise it must run uncapped - is correctly implemented, and the commit history shows this already went through many rounds of self-review that caught the sharp edges I'd otherwise flag:
I also hand-checked the arithmetic in all 15 new test cases (row/match counts for the Minor, non-blocking nits:
Test coverage is thorough for the shapes this change touches - eq/in/range operators, and/or/not tree shapes, skip>=limit paging, ascending/descending ORDER BY interaction, and the int-overflow guard are all exercised, both via row-count assertions and direct No correctness, security, or performance concerns from my read - the added logic runs once per query compile ( |
…file Code review on #6571's fourteenth round caught one comment the "trim inline comments, drop review-round references" pass had missed. States the invariant directly now, consistent with the rest of the file.
|
Thanks - "no correctness, security, or performance concerns" on this round. Fixed the one leftover stray comment in f24afa5 (missed it in the earlier trim pass). The alignment nit is correctly noted as not achievable without touching the other two fields and not worth a dedicated round - agreed, leaving as-is. Full `com.arcadedb.query.select` package still green (19/19 on the affected test class). 14 review rounds in, with this round explicitly finding no remaining issues of any kind. This PR should be ready to merge. PR link: #6571 |
ReviewI traced through Correctness
Minor observations (not blocking)
Test coverageExcellent - the cases in No functional issues found. Nice work tracking down a subtle native-vs-SQL-engine inconsistency. |
…s own declaration Code review on #6571's fifteenth round suggested the load-bearing call-order note (must run before filterWithIndexes() prunes an 'and' sibling's node.index) only lived at the call site in lookForIndexes(), but a future editor loosening 'and' disqualification is more likely to be looking at soleExactLeaf() itself. Added the same warning to its Javadoc.
|
Thanks - "no functional issues found" on this round. Addressed the suggestion in c7eb21b: mirrored the ordering-dependency note onto `soleExactLeaf()`'s own Javadoc, not just the call site in `lookForIndexes()`, since that's where a future editor loosening `and` disqualification is more likely to be looking. The other two points (the `private` → package-private encapsulation tradeoff, and the general performance-tradeoff note) are both informational observations already discussed/documented earlier in this thread, not asks for a specific change. 15 review rounds, this one again finding nothing to fix beyond a documentation nicety. This PR should be ready to merge. PR link: #6571 |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 15 |
🟢 Coverage 92.00% diff coverage · -6.52% coverage variation
Metric Results Coverage variation ✅ -6.52% coverage variation Diff coverage ✅ 92.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (dfeecae) 164583 131592 79.95% Head commit (d8d5b95) 197031 (+32448) 144699 (+13107) 73.44% (-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 (#6571) 25 23 92.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.
ReviewI traced the fix by hand against the actual tree shapes Correctness (verified, no issues found)
Minor style nits
Test coverage Nothing blocking. Methodical fix with tests that actually reproduce each bug before verifying the corresponding fix. |
… boolean workaround Code review on #6571's sixteenth round suggested the idiomatic assertThat(cursor).isNull() in place of assertThat(cursor == null).isTrue(). Verified assertThat(cursor).isNull() alone does not compile - MultiIndexCursor implements both Iterator and Iterable (via IndexCursor), and AssertJ has a distinct assertThat() overload for each, so the call is genuinely ambiguous. Casting to Object picks the plain-object overload instead, which is closer to the suggested idiom than the boolean comparison while still compiling.
|
Thanks - "nothing blocking" on this round. On the `assertThat(cursor).isNull()` suggestion: verified it directly - it does not compile as-is (`MultiIndexCursor` implements both `Iterator` and `Iterable` via `IndexCursor`, so AssertJ's overload resolution is genuinely ambiguous, same root cause as when I first hit this a few rounds back). Fixed in 8db697e with `assertThat((Object) cursor).isNull()`, which resolves the ambiguity via an explicit cast while staying much closer to the suggested idiom than the boolean workaround it replaces. (Small correction for the record: `orOfIndexedLeavesIsNeverTreatedAsExactlyIndexed`, also named in that nit, doesn't actually assert on `cursor` at all - only `bareNonCursorOperatorLeavesIndexCandidateLimitAtMinusOne` had the pattern.) The Javadoc-density nit is again explicitly flagged as "presumably intentional," so no action there. 16 review rounds in, all now converging on style-only nits with no functional, security, or correctness issues remaining. This PR should be ready to merge. PR link: #6571 |
ReviewI read through the full commit history (17 iterations, already covering an extensive self-review process) and independently re-derived the core claims by reading the current Correctness
Minor / non-blocking observations
Test coverage19 regression tests is thorough for the scope of this fix — it covers both original defect shapes from #6565, the Overall: solid, well-reasoned fix with unusually thorough self-verification already baked into the commit history. Nothing here blocks merging; the multi-valued-property question above is the only item I'd actually want an answer to before considering this fully closed out. |
…) test coverage Code review on #6571's seventeenth round asked whether ArcadeDB's indexing model could ever let a single record contribute more than one entry to an in_op leaf's per-value index cursors - the same duplicate- candidate hazard already found and fixed for OR-of-indexed-leaves. Investigated and confirmed: yes, BY ITEM (LIST) and BY KEY/BY VALUE (MAP) indexes do exactly this (DocumentIndexer.collectListItemValues() indexes every distinct list value, all pointing to the same RID). But TypeIndexBuilder registers such an index under a property-name key carrying the literal " by item"/" by key"/" by value" suffix (confirmed in TypeIndexBuilder.java, traced through to LocalDocumentType's indexesByProperties map), and the native Select fluent API's .property(name) has no way to produce that suffix - so isTheNodeFullyIndexed()'s getPolymorphicIndexByProperties(propertyName) lookup can never resolve such an index through ordinary, documented API usage. Not reachable today, same shape as the #6575 NOT gap. Filed #6578 and tightened soleExactLeaf()'s Javadoc to state the caveat precisely instead of the unqualified "single-valued property" claim. Also verified and filed #6579 for a real, pre-existing, orthogonal bug the same review round surfaced: executeCount() increments count before checking it against limit, so limit(0) returns 1 instead of 0 whenever at least one record matches. Confirmed on both the unindexed full-scan path and the AND-shaped uncapped- fallback path this PR's classification routes through; out of scope for this PR (different root cause, not the candidate-cap logic). Closed the one remaining test-coverage gap this round flagged: between wasn't covered as a sole exact leaf despite having a distinct two-bound cursor shape (node.index.range(...) with both bounds set) from the already-tested open-ended gt/ge/lt/le ranges. New test asserts both indexCandidateLimit (30 for skip=10/ limit=20) and the paged count (20 out of 50 matches for n BETWEEN 400 AND 449). Full com.arcadedb.query.select + com.arcadedb.index packages green (222 classes / 1218 tests) after this change.
|
Thorough round - dug into the multi-valued-property question rather than just noting it. On the `in_op` disjoint-RID-sets question: confirmed the hazard is structurally real - ArcadeDB's `BY ITEM` (LIST) and `BY KEY`/`BY VALUE` (MAP) indexes do index one document into multiple entries pointing at the same RID (`DocumentIndexer.collectListItemValues()`). But traced it further and confirmed it's not reachable via the native Select API today: `TypeIndexBuilder` registers such an index under a property-name key carrying the literal ` by item`/` by key`/` by value` suffix (verified through to `LocalDocumentType`'s `indexesByProperties` map), and the native `.property(name)` fluent method has no way to produce that suffix - so `isTheNodeFullyIndexed()`'s lookup can never resolve such an index through ordinary usage. Same shape as the #6575 `NOT` gap: real capability, not reachable through this API. Filed #6578 with the full trace, and tightened `soleExactLeaf()`'s Javadoc to state the caveat precisely rather than the unqualified "single-valued property" claim. On the `LIMIT 0` observation: verified it's real - both `database.select().fromType("T").limit(0).count()` and an `AND`-shaped query with `limit(0)` return `1` instead of `0` when at least one row matches. Root cause is `executeCount()` incrementing `count` before checking it against `limit`, unrelated to this PR's candidate-cap classification (it's orthogonal - the capped/indexed path happens to return the right answer today only as a side effect of the cap being `skip + 0 = skip`). Filed #6579 with repro and fix suggestion. Closed the `between` test gap: new low-level + behavioral test, same pattern as the other range operators. Full `com.arcadedb.query.select` + `com.arcadedb.index` packages green (222 classes / 1218 tests). PR link: #6571 |
ReviewI read through CorrectnessThe core fix is sound:
PerformanceThe removal of the cap for Test coverageVery thorough - the 17-commit self-review trail already closed most of the corner cases I'd otherwise flag: the One minor note, not a blocker: Nothing else stood out - the diff is small (two focused production files) relative to the very large commit history, and the extensive inline Javadoc/comments do a good job of recording the non-obvious invariants (load-bearing call order, the |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #6571 +/- ##
==========================================
+ Coverage 71.26% 71.27% +0.01%
==========================================
Files 1867 1867
Lines 164583 164644 +61
Branches 34783 34801 +18
==========================================
+ Hits 117291 117356 +65
+ Misses 33032 33031 -1
+ Partials 14260 14257 -3 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
SelectExecutor.filterWithIndexesFinalNode() had no special case for a `not` parent operator (only `or` and `and` are handled). isTheNodeFullyIndexed() still sets node.index on a leaf under `not` exactly as it would for a plain leaf, so filterWithIndexesFinalNode() would build a "positive" cursor for the un-negated condition - e.g. an eq cursor for NOT (a = 'x') yields the records where a = 'x' IS true, the opposite of what NOT (a = 'x') should select. evaluateWhere() then rejects every one of those candidates since they all satisfy the positive condition by construction, so the query would silently return zero rows. SelectOperator.not has no fluent entry point on the Select builder today, and Select.json() (the only other path that can reach it) is only ever called from test code - so this is not reachable by any real client yet. Filed proactively (spotted during review on #6571) so the defensive posture holds the moment either path opens up.
Summary
Fixes #6565.
SelectExecutor.lookForIndexes()handed the query's resultlimitstraight toMultiIndexCursoras a candidatecap on the index scan. Downstream,
evaluateWhere()andskipstill reduce that candidate stream further, so thecap was spent before the filtering it was meant to survive - silently returning fewer rows than actually match, with
no error.
Two shapes were affected:
ANDwith a non-indexable condition such asIS NOT NULL: only oneANDchildever keeps its index cursor (
filterWithIndexesFinalNode), so the other conjunct is re-checked later byevaluateWhere()against a stream that was already capped too early.skip+limitpaging over an indexed equality: reaching rowskip+1needsskip + limitcandidates,but the cap was just
limit, so the result went empty wheneverskip >= limit.The same queries through the SQL engine were already correct, so this was purely an inconsistency between the two
query APIs.
Fix
bare indexed leaf, or an
ORof such leaves (the union shapeMultiIndexCursoralready merges). AnyAND,NOT,or
IS [NOT] NULLdisqualifies the cap and the scan runs uncapped, exactly matching what the SQL engine alreadydoes for the same shapes -
evaluateWhere()/skipdownstream stay correct regardless, this only removes a staleoptimization that wasn't sound.
skip + limit, not justlimit.filterWithIndexesFinalNode()builds for anINleaf now shares that same correctedcap instead of a raw
select.limitthat was missingskip- same bug, one call site over.MultiIndexCursor.hasNext()also admitted one candidate more than asked for (browsed > limitinstead ofbrowsed >= limit). The two call sites that pass a real (non -1) limit are both inSelectExecutor, so tighteningthis doesn't affect any of the unbounded (
-1) callers elsewhere in the codebase.Test plan
Issue6565SelectIndexCandidateLimitTest(7 cases): the two shapes from the issue (AND+IS NOT NULLwith various limits,skip/limitpaging includingskip >= limit), plus.count()variants, anORof two indexed ranges withskip/limit, and anINleaf withskip/limit(covering the nested cursorfix). All 7 fail on
mainand pass with this change; confirmed by reverting the fix locally and re-running.com.arcadedb.query.selectandcom.arcadedb.indexpackages (222 classes / 1205 tests): 0 failures,0 errors - the entire blast radius of the change (nothing outside these two packages references
SelectExecutor/MultiIndexCursor).