Skip to content

fix(engine): native select must not cap the index candidate scan by the result limit - #6571

Merged
lvca merged 18 commits into
mainfrom
fix/6565-native-select-limit-candidate-scan
Aug 22, 2026
Merged

lvca merged 18 commits into
mainfrom
fix/6565-native-select-limit-candidate-scan

Conversation

@lvca

@lvca lvca commented Aug 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes #6565.

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 - silently returning fewer rows than actually match, with
no error.

Two shapes were affected:

  • 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 by
    evaluateWhere() against a stream that was already capped too early.
  • Ordinary skip + limit paging over an indexed equality: reaching row skip+1 needs skip + limit candidates,
    but the cap was just limit, so the result went empty whenever skip >= limit.

The same queries through the SQL engine were already correct, so this was purely an inconsistency between the two
query APIs.

Fix

  • The candidate cap is now applied only 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). Any AND, NOT,
    or IS [NOT] NULL disqualifies the cap and the scan runs uncapped, exactly matching what the SQL engine already
    does for the same shapes - evaluateWhere()/skip downstream stay correct regardless, this only removes a stale
    optimization that wasn't sound.
  • When the cap does apply, it is now skip + limit, not just limit.
  • The nested per-value cursor filterWithIndexesFinalNode() builds for an IN leaf now shares that same corrected
    cap instead of a raw select.limit that was missing skip - same bug, one call site over.
  • MultiIndexCursor.hasNext() also admitted one candidate more than asked for (browsed > limit instead of
    browsed >= limit). The two call sites that pass a real (non -1) limit are both in SelectExecutor, so tightening
    this doesn't affect any of the unbounded (-1) callers elsewhere in the codebase.

Test plan

  • New regression test Issue6565SelectIndexCandidateLimitTest (7 cases): the two shapes from the issue (AND +
    IS NOT NULL with various limits, skip/limit paging including skip >= limit), plus .count() variants, an
    OR of two indexed ranges with skip/limit, and an IN leaf with skip/limit (covering the nested cursor
    fix). All 7 fail on main and pass with this change; confirmed by reverting the fix locally and re-running.
  • Ran the full com.arcadedb.query.select and com.arcadedb.index packages (222 classes / 1205 tests): 0 failures,
    0 errors - the entire blast radius of the change (nothing outside these two packages references
    SelectExecutor/MultiIndexCursor).

…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
@lvca lvca added this to the 26.9.1 milestone Aug 22, 2026
@lvca lvca self-assigned this Aug 22, 2026
@mergify

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

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 22 complexity

Metric Results
Complexity 22

View in Codacy

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 22, 2026

Copy link
Copy Markdown

Review of #6571

This is a well-targeted fix with a clear write-up, and the MultiIndexCursor.hasNext() off-by-one correction is solid. I traced the new eligibility logic against the actual tree shapes Select builds, and found one gap worth addressing before merge.

Bug: isWhereExactlyIndexed() misses the synthetic run root, so the cap never engages for a single bare condition

Select.compile() always fires one trailing setLogic(SelectOperator.run) when the query used .where() (Select.java:250-252). For a query with no .and()/.or(), rootTreeElement is still null at that point, so setLogic takes the "1ST TIME ONLY" branch (Select.java:304-308) and wraps the actual condition in a synthetic outer node whose operator is run:

root(operator=run) -> left = leaf(a = x), right = null

isWhereExactlyIndexed() (SelectExecutor.java:250-261) only special-cases or for non-leaf nodes:

if (!(node.left instanceof SelectTreeNode))
  return node.index != null;

if (node.operator == SelectOperator.or)
  return isWhereExactlyIndexed((SelectTreeNode) node.left) && isWhereExactlyIndexed((SelectTreeNode) node.right);

return false;

Since the root's left is itself a SelectTreeNode (the leaf-wrapper), the root is never treated as a leaf, and since its operator is run (not or), the function falls through to return false. So every single-condition query (.where().property(x).eq().value(y), or a lone .in()) is treated as "not exactly indexed," and indexCandidateLimit stays -1 (uncapped) - the exact opposite of what the PR intends for "a bare indexed leaf."

This doesn't cause wrong results (uncapped is always safe - that's the existing fallback), but it means:

  • The skip + limit cap this PR restores never actually fires for what's probably the most common query shape: a single indexed equality with skip/limit paging - i.e. "Shape B" from the PR description itself.
  • The nested per-value MultiIndexCursor built for a standalone IN leaf (SelectExecutor.java:310) also never gets a real cap for the same reason, so the "same bug, one call site over" fix is effectively dead code for a bare IN query.
  • Four of the seven new tests (skipAndLimitOnPlainIndexedEqualityPagesCorrectly, countHonoursSkipOnPlainIndexedEquality, secondPageIsNotEmptyWhenSkipEqualsOrExceedsLimit, inOperatorWithSkipAndLimitPagesCorrectly) still pass, but not because they exercise the new cap - they pass because the uncapped fallback is trivially correct too. Only orOfTwoIndexedRangesWithSkipAndLimitPagesCorrectly (root operator genuinely or) and the AND+isNotNull tests exercise the true/false branches this method is meant to distinguish at the top level.

Suggested fix: treat run as a transparent pass-through (its right is always null when it's a synthetic wrapper, so isWhereExactlyIndexed(null) trivially contributes true):

if (node.operator == SelectOperator.or || node.operator == SelectOperator.run)
  return isWhereExactlyIndexed((SelectTreeNode) node.left) && isWhereExactlyIndexed((SelectTreeNode) node.right);

I'd also suggest strengthening the regression test so it asserts the cap actually engages (e.g. assert on executor.metrics().get("evaluatedRecords") or an equivalent low-level counter) rather than only on final row counts, since row counts are correct either way and won't catch a regression back to "always uncapped."

Smaller notes

  • indexCandidateLimit is declared private, while the neighboring fields (evaluatedRecords, usedIndexes) are package-private with no modifier - purely cosmetic, not worth blocking on.
  • computeExactCandidateLimit()'s long overflow guard is good defensive coding for pathological skip/limit values.
  • Confirmed via grep that every other MultiIndexCursor constructor call site in the codebase passes limit = -1, so the browsed >= limit tightening in MultiIndexCursor.hasNext() is scoped exactly as claimed and can't affect unrelated unbounded scans.
  • Test style follows the repo conventions (assertThat, TestHelper, no unnecessary tags since nothing here is slow/benchmark).

Nice catch on the original bug, and the "exactly reproduces the where-tree" framing is the right mental model - it just needs to also see through the compiler's own run wrapper.

…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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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.

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

Traced the fix through SelectExecutor/MultiIndexCursor end-to-end against the tree-building logic in Select.setLogic(), and it holds up. Summary of what I verified:

Correctness

  • isWhereExactlyIndexed() is conservative in exactly the right places. For and, filterWithIndexesFinalNode()'s uniqueness-preference logic (lines ~342-357) means an AND never keeps both children's cursors, only one - so the discarded conjunct is always re-checked by evaluateWhere() regardless of shape. Unconditionally disqualifying and/not from the cap isn't just "conservative," it's precisely correct given that invariant.
  • The run-operator pass-through is a real edge case worth double-checking, and it checks out: walking Select.setLogic(), a run-operator node is only ever synthesized in the "1st time" branch (rootTreeElement == null), i.e. exactly the single-bare-condition where-clause. Once a .and()/.or() has run once, rootTreeElement is non-null and the final setLogic(run) call from compile() just does lastTreeElement.getParent().setRight(...) - it never creates a run node in a multi-condition tree. So treating run as left-only (right always null) in isWhereExactlyIndexed is safe, not just for the tested case but structurally.
  • MultiIndexCursor.hasNext()'s browsed > limit -> browsed >= limit is a genuine, separate off-by-one (previously admitted limit + 1 candidates). Confirmed the only two call sites that ever pass a real (non -1) limit are the two touched in SelectExecutor; TypeIndex's three call sites are all -1, so this tightening can't affect anything else.
  • Overflow (skip + limit as long, falling back to -1 if it exceeds Integer.MAX_VALUE) and negative-skip (Math.max(0, select.skip)) are both handled defensively.

Minor observations (non-blocking)

  • Now that and/not shapes always scan uncapped, a low-selectivity indexed leaf combined via AND with a cheap residual filter (e.g. indexedLowSelectivity = X AND cheapField IS NOT NULL LIMIT 10) will scan the entire matching index range instead of stopping early - this is the necessary trade-off for correctness and matches what the SQL engine already does for the same shape, but it's a real behavior change worth being aware of if anyone was (unknowingly) relying on the old capped-but-wrong fast path for such queries.
  • Test coverage is solid for the shapes the issue describes (AND+IS NOT NULL, skip/limit paging, OR of ranges, IN with skip/limit), plus two tests that assert on the computed indexCandidateLimit directly to catch a regression that a result-count-only assertion couldn't see (nice touch, since lazy-pull consumers already stop at skip+limit on their own). One gap: there's no test exercising a bare NOT leaf (e.g. NOT a = 'x' LIMIT n) or a nested AND under an OR (e.g. (a=1 AND b=2) OR c=3), both of which should fall through isWhereExactlyIndexed's conservative return false but aren't directly asserted. Given how easy this kind of tree-shape logic is to get subtly wrong, a couple more cases here would cheaply increase confidence.
  • lookForIndexes() and indexCandidateLimit were widened from private to package-private purely so the test can assert on the cap directly - reasonable given the stated rationale (a count-based assertion can't distinguish "correct cap" from "uncapped fallback"), just flagging it as an intentional visibility trade-off for reviewers who might otherwise flag it as scope creep.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

Added the two suggested cases in 5c973a2, both asserting on `indexCandidateLimit` directly (`-1`), same rationale as before:

  • `andUnderOrIsNeverTreatedAsExactlyIndexed`: `(a='x' AND b='set') OR n=5`. Traced `Select.setLogic()`'s precedence handling to confirm this fluent chain actually builds `or(and(a,b), n)` (and's precedence 2 > or's 0), so it's a real end-to-end test through the public builder, not synthetic.
  • `notLeafIsNeverTreatedAsExactlyIndexed`: `SelectOperator.not` has no fluent entry point on `Select` today, so this one builds the tree by hand with `SelectTreeNode`'s public constructor.

Full `com.arcadedb.query.select` + `com.arcadedb.index` packages still green (222 classes / 1209 tests).

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced the tree-construction logic in Select.setLogic()/compile() and the read paths in MultiIndexCursor to check the claims in the PR description, and I agree with the fix. Notes below.

Correctness

  • isWhereExactlyIndexed() tree-shape reasoning checks out. Walking Select.setLogic() confirms the "1ST TIME ONLY" branch only ever produces a run-operator node when the where-clause is a single bare condition with no and()/or() called at all (any compound tree gets its AND/OR root created directly in that same branch, never a trailing run wrapper). So treating run as a transparent pass-through with an always-null right is safe, and the added singleBareEqualityCandidateCapCoversSkipPlusLimit/singleBareInCandidateCapCoversSkipPlusLimit tests catching the original gap here (four of the seven tests only passing "by accident" via the uncapped fallback) show real rigor in the follow-up commits.
  • The shared indexCandidateLimit across nested cursors (the IN per-value cursor) is sound, not just "safe by uncapped fallback." When isWhereExactlyIndexed() returns true, the total number of candidates the outer MultiIndexCursor will ever pull is bounded by skip + limit regardless of how many children contribute; applying that same bound to each nested child individually can never starve the outer merge, since no single child could ever legitimately need to supply more than the outer's total demand anyway. Worth a one-line comment on computeExactCandidateLimit()'s call site at line 319 noting this isn't just reusing the same number for convenience but is a deliberate over-approximation-per-child that's provably still tight enough - future readers may wonder why a nested cursor gets the whole tree's cap rather than something scoped to its own subtree.
  • MultiIndexCursor.hasNext()'s browsed > limit → browsed >= limit matches next()'s ++browsed happening once per element actually handed to the caller - the old check let one extra candidate through. Confirmed via grep that the only two non--1 callers are the two in SelectExecutor touched by this PR, so the tightened check's blast radius is exactly as claimed.
  • isTheNodeFullyIndexed() vs. isWhereExactlyIndexed() gating stays consistent for the or case: the former's cursor-building gate (leftIsIndexed || rightIsIndexed at each level, re-checked in filterWithIndexesFinalNode) is strictly weaker than the latter's requirement (every leaf under a chain of or/run must itself have node.index != null), so whenever the cap applies, real index cursors are guaranteed to have been built for every contributing leaf.
  • and handling is safe despite filterWithIndexesFinalNode's side effect of nulling out a sibling's node.index (lines ~342-357, "prefer the unique index") - that mutation happens strictly after indexCandidateLimit is computed, and isWhereExactlyIndexed() already returns false unconditionally for any and node, so the ordering doesn't matter here, but it's a bit of a coincidence rather than an enforced invariant. If a future change makes isWhereExactlyIndexed() less conservative about and, this ordering dependency (computing the cap before the sibling-nulling side effect runs) would become load-bearing and worth flagging explicitly in a comment.

Minor / non-blocking observations

  • The dropped canUseIndexes local (previously computed but never read) was already dead before this PR - good incidental cleanup, not something this PR needs to call out.
  • computeExactCandidateLimit()'s overflow guard (sum > Integer.MAX_VALUE ? -1 : (int) sum) falls back to uncapped rather than clamping to Integer.MAX_VALUE; either is correct, but worth a one-line comment since it looks at first glance like it should clamp.
  • The not-leaf test builds the tree by hand since there's no fluent entry point for SelectOperator.not - that's fine for pinning isWhereExactlyIndexed()'s conservatism, but worth noting that filterWithIndexesFinalNode() looks like it would build a "positive" (non-negated) cursor for an indexed leaf directly under a not node if this operator ever became reachable through the builder, which would hand evaluateWhere() a candidate stream that can never satisfy the negation. Out of scope here since it's unreachable today, but worth a follow-up issue if not ever gets a fluent entry point.

Test coverage

Strong. 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 indexCandidateLimit directly (rather than only row counts) for the shapes where the lazy-pull consumers already mask the bug is exactly right, and the PR description states all 7 new tests were confirmed to fail on main and the full select/index package suite (1205 tests) passes - good verification discipline.

No security or performance concerns; this is a pure query-planner correctness fix with a well-justified, narrowly-scoped API widening (private → package-private) purely to support direct assertions in the regression test.

…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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

Thanks for the thorough second pass. Addressed the three cheap documentation suggestions in e43242d:

  • Added a comment on the `indexCandidateLimit` computation noting it must run before `filterWithIndexes()`, and why that ordering isn't currently load-bearing but would become so if `and` disqualification is ever loosened.
  • Added a comment on `computeExactCandidateLimit()`'s overflow guard explaining the deliberate `-1` fallback instead of clamping to `Integer.MAX_VALUE`.
  • Added a comment at the `IN`-leaf nested cursor call site explaining why sharing the whole tree's `indexCandidateLimit` is a proven-safe over-approximation, not just convenient reuse.

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.

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

Nice, methodical fix - the root-cause analysis in the PR description matches the code (SelectExecutor.lookForIndexes() was hard-coding select.limit as a candidate cap on MultiIndexCursor, when downstream evaluateWhere()/skip need more candidates than that to survive). The multi-round history (exactness check missing the run wrapper, then the AND-under-OR/NOT gaps) shows good self-review, and MultiIndexCursor.hasNext()'s browsed >= limit off-by-one fix is correct and its blast radius (only the two SelectExecutor call sites pass a non -1 limit) checks out via a grep.

Correctness: the cap is still unsafe for ORDER BY + LIMIT on a descending/mismatched index scan

isWhereExactlyIndexed()/computeExactCandidateLimit() only look at the WHERE tree - they don't consider select.orderBy at all. But SelectIterator.fetchResultInCaseOfOrderBy() (lines 215-228) only skips full materialization when there is exactly one used index and its property/direction matches the requested order:

if (orderBy.getFirst().equals(usedIndex.property) && orderBy.getSecond() == usedIndex.order)
    return; // resultset already ordered

filterWithIndexesFinalNode() always scans ascending (final boolean ascendingOrder = true;, line 315), so usedIndex.order is always true. That means any descending orderBy on the very same indexed property the WHERE clause uses falls through to full materialization: drain the iterator, sort in memory, then apply skip/limit.

The problem: draining "the iterator" means draining the same MultiIndexCursor that lookForIndexes() now caps at skip + limit whenever the WHERE tree is exactly indexed (a bare leaf like gt/ge/eq qualifies). So the sort only ever sees the first skip + limit candidates in ascending index order, not the full matching set - the exact same "cap spent before the filtering it was meant to survive" bug this PR fixes for AND/skip, just one consumer over (the in-memory sort instead of evaluateWhere()).

Concretely, with the fixture already in the repo (SelectOrderByTest, using Vertex.id 0..109, unique index on id):

database.select().fromType("Vertex").where().property("id").gt().value(-1)
    .orderBy("id", false).limit(10)

Expected: ids 109..100. Actual (by code reading - computeExactCandidateLimit() returns 0 + 10 = 10, so only ids 0..9 are ever pulled from the index before the sort): ids 9..0.

Notably, SelectOrderByTest.okOrderByNoIndexDescendingIndexServedProperty (lines 122-131) already exercises this exact shape - descending order on an ascending-scanned indexed property - but without a limit(), so select.limit < 0 short-circuits computeExactCandidateLimit() to -1 and the test can't see the bug. It's a near-miss regression test for exactly this gap.

This predates this PR (the old code capped unconditionally at select.limit, so the same query was already broken pre-PR), but since this PR is specifically about making the candidate cap sound with respect to downstream consumers that reduce the stream further, it'd be worth closing this gap here too rather than leaving a second occurrence of the same bug class. Suggest: in computeExactCandidateLimit()/isWhereExactlyIndexed(), also fall back to -1 whenever select.orderBy != null and isn't already satisfied by the (always-ascending) index scan - mirroring the check SelectIterator already does - and add a regression case for it alongside the new Issue6565SelectIndexCandidateLimitTest.

Minor: characterization of the NOT-leaf follow-up (#6575)

The last commit's message says the unreachable NOT-leaf gap is safe because "evaluateWhere() already guarantees correctness regardless." Tracing it through: filterWithIndexes() recurses through a not node into its child leaf unconditionally (it only special-cases and/or for pruning, not not), so if not ever gets a fluent entry point, filterWithIndexesFinalNode() would build a cursor for the positive condition (e.g. a = x) under a NOT. evaluateWhere() would then correctly evaluate NOT(a = x) against those candidates and reject all of them - so the failure mode isn't "wrong rows," it's "silently returns zero rows" for a query that should match everything else in the table. Worth tightening #6575's description now, so whoever wires up a fluent not() later doesn't read "evaluateWhere() guarantees correctness" and conclude no fix is needed.

Test coverage

The new Issue6565SelectIndexCandidateLimitTest is thorough for the shapes it targets (AND+IS_NOT_NULL, skip/limit paging including skip >= limit, OR of ranges, IN with skip/limit, AND-under-OR, NOT, the synthetic run wrapper) and the direct indexCandidateLimit assertions are a good call given a row-count assertion can't distinguish "correctly capped" from "uncapped fallback." The one gap is the ORDER BY interaction above.

Nit

The heavy inline uppercase commentary is consistent with this file's/module's existing style, so no change needed there.

Overall: solid, well-tested fix for the two shapes in #6565. The ORDER BY + LIMIT gap above is the one thing I'd want addressed (or explicitly deferred to a tracked follow-up, the way #6575 was) before merging, since it's directly adjacent to the mechanism this PR changes.

…-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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

Traced 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

  • isWhereExactlyIndexed()'s handling of the synthetic run wrapper checks out: Select.setLogic() only produces that wrapper via the "1ST TIME ONLY" branch, which fires exactly when the where-clause is a single bare condition (no prior and()/or()). Multi-condition trees never get a run node in the middle - traced through setLogic by hand for both the 2-condition and precedence-driven 3-condition (AND-under-OR) cases and both match what the new test asserts.
  • MultiIndexCursor.hasNext()'s browsed >= limit fix is safe: confirmed the only two call sites passing a non--1 limit are the two in SelectExecutor touched by this PR; TypeIndex's three call sites all pass -1.
  • isOrderBySafeForCap() correctly mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s own trivial-match precondition (single leaf, usedIndexes.size() == 1, matching property + ascending direction), including the OR-of-two-leaves case, which can never satisfy usedIndexes.size() == 1 since filterWithIndexesFinalNode() adds one IndexInfo per leaf.
  • Overflow handling in computeExactCandidateLimit() (long-sum, fallback to -1 rather than clamping) is correct and consistent with the "-1 means uncapped" convention used elsewhere in the class.

Minor / non-blocking observations

  1. Repeated tree walks: lookForIndexes() now walks select.rootTreeElement up to four times per execution - isTheNodeFullyIndexed(), isWhereExactlyIndexed(), soleExactLeaf() (only when whereExact is true, since && short-circuits), and filterWithIndexes(). Where-trees are small in practice (a handful of conditions), so this is very unlikely to matter, but if it's ever worth tightening, isWhereExactlyIndexed/soleExactLeaf could be folded into one pass that returns the sole leaf or a "not exact" sentinel.
  2. The three new private helpers (isWhereExactlyIndexed, soleExactLeaf, isOrderBySafeForCap) all recurse on the same shape (leaf / or / run pass-through) with slightly different bodies - readable as-is given the Javadoc, but a future 4th consumer of "is this tree exactly indexed" would be the point to unify them.
  3. SelectExecutor.filterWithIndexesFinalNode() would build a wrong cursor for a NOT-wrapped indexed leaf, if NOT ever gets a fluent entry point #6575 was opened to track the currently-unreachable NOT-directly-under-an-indexed-leaf gap - good call deferring that rather than adding speculative handling for a shape that has no fluent entry point today.

Test coverage
The 7-case regression test plus the 2 additional commits (AND-under-OR, bare NOT, and the two ORDER BY cases) cover the shapes I'd have asked about. Asserting on indexCandidateLimit directly (rather than only row counts) for the cases where the uncapped fallback would otherwise be indistinguishable from a correctly-applied cap is exactly right - a row-count-only test would have let the second and third review-round bugs ship silently, as the PR description itself notes.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@codacy-production

codacy-production Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 20 complexity

Metric Results
Complexity 20

View in Codacy

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 22, 2026

Copy link
Copy Markdown

Review

I traced the tree-construction logic (Select.setLogic) and the new isWhereExactlyIndexed/soleExactLeaf/isOrderBySafeForCap helpers by hand for the shapes involved (single leaf via the synthetic run wrapper, or-of-leaves, (a AND b) OR c, bare not), since the local checkout already has this PR's commits merged in. Findings below.

Correctness

  • isWhereExactlyIndexed correctly treats the synthetic run node as a pass-through. Confirmed via Select.setLogic: the "1ST TIME ONLY" branch only produces that wrapper when the where-clause has no .and()/.or() at all; any real and/or call folds the logic operator into the root itself instead, so run never shows up as an internal operator anywhere else in the tree.
  • Traced the precedence-driven build for (a AND b) OR c by hand through setLogic and it does produce a nested and node under the or root, exactly as the new andUnderOrIsNeverTreatedAsExactlyIndexed test assumes. isWhereExactlyIndexed's unconditional and disqualification correctly catches it regardless of the or wrapper.
  • MultiIndexCursor.hasNext(): browsed > limit → browsed >= limit is the right fix — browsed is incremented in next() after a value is handed out, so the old check let one extra candidate through the cap. Grepped the codebase and confirmed the PR's claim that the only two call sites passing a real (non -1) limit are both in SelectExecutor; the three TypeIndex call sites all pass -1, so tightening this is safe.
  • The ORDER BY fix (round 5 of the review history) is a legitimate, independent bug from the original Native select applies limit to the index candidate scan: skip/limit paging and IS NOT NULL silently lose rows #6565 report — capping the candidate stream ahead of SelectIterator.fetchResultInCaseOfOrderBy()'s full in-memory sort would silently truncate results whenever the requested order doesn't trivially match the forced-ascending index scan. isOrderBySafeForCap mirrors SelectIterator's own trivial-match check (single used index, matching property + ascending direction) field-for-field.
  • I double-checked the one thing that looked like it might undercut the "not is unreachable" reasoning behind the follow-up issue SelectExecutor.filterWithIndexesFinalNode() would build a wrong cursor for a NOT-wrapped indexed leaf, if NOT ever gets a fluent entry point #6575: SelectOperator.not is declared with logicOperator=true, so in principle Select.json()'s JSON-deserialization path could reach it via setLogic(). But Select.json() is only ever called from a test (SelectExecutionTest), not wired into any HTTP handler or wire-protocol module, so the "currently unreachable" claim holds today — just flagging it as the thing to re-check if that JSON path ever gets exposed to a client.

Test coverage is thorough: the 10 cases in Issue6565SelectIndexCandidateLimitTest cover both original bug shapes (AND + IS NOT NULL, skip>=limit paging), the nested AND-under-OR and hand-built bare-NOT tree shapes raised in review, the IN-leaf-under-OR combination, and — importantly — direct assertions on indexCandidateLimit for the cases where a row-count assertion can't tell "correctly capped" apart from "uncapped fallback that happens to be correct anyway." That distinction is easy to miss and the tests explicitly guard against it.

Minor/non-blocking

  • The new inline comments are dense, multi-sentence ALL-CAPS blocks — noticeably longer than the file's pre-existing ones (e.g. lookForIndexes()'s header comment runs ~10 lines). Style is consistent with what's already there, but a couple of the longest could be trimmed to just the load-bearing invariant.
  • A few comments/test names reference "CODE REVIEW ON fix(engine): native select must not cap the index candidate scan by the result limit #6571('s Nth round)" rather than stating the invariant directly. Fine for now, but that context won't be discoverable once the PR history scrolls away — the Javadoc on computeExactCandidateLimit() is a better model to follow throughout (states the why, not the review round it came from).
  • indexCandidateLimit/lookForIndexes() widened from private to package-private purely for test access, consistent with how usedIndexes is already exposed — no objection.
  • I couldn't run mvn in this review environment to execute the tests myself, so this is a static/manual review, not a verified test run. The PR description's account of running the full select/index packages (1205 tests, 0 failures) and reverting the fix to confirm the regression tests fail on main is exactly the verification I'd otherwise ask for.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

"No blocking issues found" on this round - thanks for the thorough field-for-field trace. Addressed the two style suggestions in 26fae67:

  • Trimmed the longest inline comment blocks (`lookForIndexes()`'s three-invariant header, the `IN`-leaf nested cursor note) to state the load-bearing invariant more directly.
  • Replaced "CODE REVIEW ON fix(engine): native select must not cap the index candidate scan by the result limit #6571(, round N)" test comments with the invariant itself, following `computeExactCandidateLimit()`'s Javadoc as the model - agreed that framing rots once the PR history isn't front-and-center.

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

Solid, well-documented fix for #6565, and the iterative self-review trail in the commit history (catching the run-wrapper gap, the missing ORDER BY interaction, the AND-under-OR/NOT test gaps) shows real rigor. One correctness gap survives, though, and it's directly relevant to the invariant this PR formalizes.

Bug: the "OR of indexed leaves is exact" invariant doesn't hold when the branches can match the same record

isWhereExactlyIndexed() (SelectExecutor.java:267-278) treats an or of two bare indexed leaves as exactly reproducing the where-tree's result set, on the reasoning that MultiIndexCursor "already merges" the union. That's true set-wise, but MultiIndexCursor.next() (MultiIndexCursor.java:133-188) is a plain k-way merge over its child cursors with no RID dedup - if the same record satisfies both OR branches, it is emitted twice (once per child cursor). Dedup only happens one layer up, in SelectIterator.fetchNext()/executeCount(), via filterOutRecords - after the candidate has already been counted against MultiIndexCursor's browsed cap.

So when OR branches overlap, each duplicate candidate burns one unit of the skip + limit budget without producing a unique result, and the cap can be exhausted before enough distinct matches are found - silently returning fewer than min(limit, true count) rows. This is the exact defect class #6565 is about, just reachable again through the new "OR is safe" fast path.

Concrete repro (single property, no cross-property setup needed): with n ranging densely over indexed integers,

database.select().fromType("T").where()
    .property("n").gt().value(5)
    .or().property("n").lt().value(500)
    .limit(10).count();

Every row with n in (5, 500) matches both branches. Tracing MultiIndexCursor's merge: the two range cursors interleave through the overlapping region, each duplicate (key, RID) pair is drained as two separate browsed increments, and the cap of 10 is reached after far fewer than 10 unique records have survived filterOutRecords. Expected count == 10; actual will be lower. (I wasn't able to compile/run this in the review sandbox - Write access to add a scratch test was denied - so please verify directly, but the trace through MultiIndexCursor.next()'s tie-handling and SelectIterator.fetchNext()'s dedup order is unambiguous.)

The new regression tests don't catch this because both OR-shaped tests deliberately use disjoint branches: n < 10 OR n >= 990 (structurally non-overlapping ranges) and g IN (g0,g1,g2) OR n = 3 (comment explicitly notes n = 3's row was chosen to fall outside the IN set to avoid overlap). That's a reasonable choice for isolating the fix being tested, but it means the "OR of leaves" branch of isWhereExactlyIndexed() is exercised only in the one case where it's actually safe.

Note this duplicate-candidate risk predates this PR (the old code capped every cursor-returning query at bare select.limit, OR-shaped or not), so it's not newly introduced - but this PR elevates "OR of leaves" to a documented, tested invariant, and that documentation overstates what's actually guaranteed. Worth fixing or at least explicitly scoping down before merge:

  • Simplest safe option: drop or from isWhereExactlyIndexed()'s allowed shapes (treat it like and/not, conservatively false) until overlap-safety can be established structurally (e.g., only when the two branches are provably on disjoint value domains, which is hard in general) or MultiIndexCursor/SelectIterator dedup before counting against the cap.
  • Alternative: keep the OR fast path but make the cap post-dedup - i.e., have SelectIterator/executeCount() stop the underlying cursor based on returned (post-filterOutRecords) rather than relying on MultiIndexCursor's pre-dedup browsed. That's a bigger structural change than this PR needs to make, though.

Everything else looks correct

  • computeExactCandidateLimit()'s overflow handling (fall back to -1 rather than clamping) is sound and consistent with the sentinel's meaning elsewhere in the class.
  • The run-node pass-through logic matches Select.setLogic()'s actual behavior - I traced through Select.java:298-335 and confirmed run only ever appears as the synthetic single-leaf wrapper with right == null, exactly as documented.
  • MultiIndexCursor.hasNext()'s browsed >= limit fix is correctly scoped - grepped for all new MultiIndexCursor(...) call sites with a real (non -1) limit and both are in SelectExecutor, as claimed.
  • The and-under-or and bare not test cases correctly assert on indexCandidateLimit directly rather than row counts, which is the right call given the lazy-pull consumers already mask the cap either way.
  • Widening lookForIndexes()/indexCandidateLimit to package-private for test access is a reasonable, minimal trade-off given the black-box-vs-white-box testing problem the comment explains.

Minor / out of scope

filterWithIndexesFinalNode()'s "under an OR, both sides must be indexed" check (SelectExecutor.java:329-338) uses isTheNodeFullyIndexed(), which considers neq/like/ilike "indexed" (since it only excludes is_null/is_not_null), but the cursor-building switch below only actually builds a cursor for eq/in_op/between/gt/ge/lt/le. For an OR branch using one of the unhandled operators (e.g. a LIKE 'x%' OR b = 2), that side is optimistically treated as "indexed" and the other side's cursor still gets built and returned alone, missing the LIKE branch's matches entirely - not a capping issue, a structurally incomplete union. This is pre-existing (untouched by this diff) and unrelated to the candidate-cap fix, so it shouldn't block this PR, but might be worth its own issue alongside #6575.

Test coverage otherwise is thorough - the 7 (now more) cases in Issue6565SelectIndexCandidateLimitTest map cleanly to the shapes described in the PR body, and asserting on the raw indexCandidateLimit where a row-count assertion can't distinguish "correctly capped" from "correctly uncapped" is a good instinct.

… 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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced through the where-tree construction (Select.setLogic), SelectExecutor.isWhereExactlyIndexed/soleExactLeaf/isOrderBySafeForCap, filterWithIndexesFinalNode, and MultiIndexCursor.hasNext() by hand against the new test cases. Overall this is a solid, well-reasoned fix; the commit history shows the PR already went through several rounds of self-review that caught the AND-under-OR shape, the NOT leaf shape, the ORDER BY full-drain-sort interaction, and the OR-duplicate-candidate issue, all of which check out correctly against the current code.

Correctness

  • MultiIndexCursor.hasNext(): browsed > limit to browsed >= limit is the right fix. Confirmed via grep that the only two non--1 callers are the two SelectExecutor sites this PR touches, so tightening it can't affect any unbounded caller elsewhere.
  • computeExactCandidateLimit(): skip/limit defaults (skip=0, limit=-1) and the overflow-to--1 fallback are handled correctly; the long sum avoids the int-overflow trap.
  • isWhereExactlyIndexed()'s run-wrapper handling matches Select.setLogic()'s actual behavior: run is only ever synthesized in the "1ST TIME ONLY" branch with right == null, and the trailing setLogic(run) call for a tree that already has and/or content takes the other branch (lastTreeElement.getParent().setRight(...)), which never introduces a run node. So treating run as a transparent pass-through is safe, and I couldn't find another code path that creates a run-operator node.
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s trivial-match check correctly (single usedIndexes entry, matching property, and ascendingOrder is hardcoded true in both places, so the direction comparison lines up).
  • Verified the ordering note ("isWhereExactlyIndexed must run before filterWithIndexes") is currently harmless: the only place that mutates node.index afterward is the AND-sibling uniqueness pruning in filterWithIndexesFinalNode, which only fires when the parent operator is and, and and is unconditionally excluded from the exactness check regardless of node.index. So the comment's caveat is accurate, this is a landmine for a future change, not a live bug.

Minor, non-blocking observations

  1. isWhereExactlyIndexed()'s leaf case is node.index != null, but node.index gets set by isTheNodeFullyIndexed() for any operator on an indexed property (including neq, like, ilike), not just the operators filterWithIndexesFinalNode() actually turns into a cursor (eq, in_op, between, gt, ge, lt, le). Today this is harmless: a bare LIKE/NEQ leaf never produces a cursor, so cursors stays empty and lookForIndexes() returns null before the (wrongly-computed) cap is ever consumed. But it's an implicit coupling: if a future change makes filterWithIndexesFinalNode() fall back to a partial cursor list instead of an all-or-nothing empty result, this would silently start applying a cap to a stream that isn't exact. Might be worth either a short comment noting the invariant it depends on, or tightening the check to the actual cursor-producing operator set.

  2. The Javadoc on isWhereExactlyIndexed() says "under an and only one child's cursor is kept". From reading filterWithIndexesFinalNode()'s uniqueness-preference block, that's only true when one side's index is unique; when neither side is unique, both children keep their cursors and get unioned by MultiIndexCursor (candidates only, evaluateWhere() still enforces the real AND). Doesn't affect correctness here since and is excluded unconditionally either way, but the comment overstates the "one child" claim.

  3. The new Javadoc blocks (computeExactCandidateLimit, isWhereExactlyIndexed, soleExactLeaf, isOrderBySafeForCap) are noticeably longer than this file's typical comment density. Given the PR history already shows one round of trimming, this looks like a deliberate choice to preserve non-obvious invariants (the run-wrapper quirk, the OR-dedup hazard) rather than fluff, so I'd call it acceptable, just flagging it since the project generally favors terser comments.

Test coverage

The 13 test cases in Issue6565SelectIndexCandidateLimitTest are thorough: both shapes from the issue, skip >= limit, OR of ranges (including the overlapping-duplicate case), IN under OR, AND under OR, a hand-built NOT leaf, and both ORDER BY directions. I hand-verified the expected counts for the trickier ones (the g IN (...) OR n = 3 601-match union, and the n > 5 OR n < 500 all-1000-rows overlap) and they match. Good use of assertThat(...) per project convention, and asserting indexCandidateLimit directly (rather than only row counts) is the right call, since a row-count assertion can't distinguish "correctly capped" from "uncapped fallback happened to be correct anyway," as the PR description itself notes.

I wasn't able to run mvn verify in this sandbox (the build invocation was blocked), so this review is based on static tracing of the tree-construction and cursor logic rather than executing the suite, but the reasoning above is consistent with the 0-failures run the PR description reports for the com.arcadedb.query.select and com.arcadedb.index packages.

Nice work tracking down a genuinely subtle bug across all the shapes that could reintroduce it.

@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced the fix end-to-end (SelectExecutor.lookForIndexes() / soleExactLeaf() / computeExactCandidateLimit() / isOrderBySafeForCap() / MultiIndexCursor.hasNext()) against evaluateWhere(), SelectIterator.fetchNext()/fetchResultInCaseOfOrderBy(), and executeCount()/executeExists(). The logic holds together:

  • soleExactLeaf() correctly restricts the cap to shapes where the index cursor is the result set: a bare leaf, or that leaf through the synthetic run wrapper Select.compile() adds. and/or/not all fall through to the conservative -1, and I confirmed the reasoning for excluding or (dedup-free k-way merge in MultiIndexCursor.next() can double-count an overlapping record against the cap) is real — filterWithIndexesFinalNode()/MultiIndexCursor indeed have no RID dedup at the cursor level; dedup only happens later via filterOutRecords in SelectIterator/executeCount().
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s trivial-match check correctly. Since filterWithIndexesFinalNode() hardcodes ascendingOrder = true for every index scan, usedIndex.order is always true, so orderBy.getSecond() && ...propertyName match is equivalent to what SelectIterator checks against usedIndexes. Good catch on this one — the full-drain sort truly would have seen a truncated candidate stream without it.
  • The indexCandidateLimit = -1 reset when cursors ends up empty is necessary and correct — without it a bare neq/like/ilike leaf (indexed per isTheNodeFullyIndexed()'s looser check per Native select: OR with a non-cursor-buildable operator (NEQ/LIKE/ILIKE) on one side silently drops the whole other branch #6577, but not turned into a cursor by filterWithIndexesFinalNode()'s switch) would leave a misleading finite value in a field the tests assert on directly.
  • MultiIndexCursor.hasNext()'s browsed >= limit fix is correct: browsed is incremented in next() right before the value is returned, so browsed == limit already means limit candidates were handed out. Confirmed the two call sites with a real (non -1) limit are both in SelectExecutor, so tightening this can't affect the unbounded (-1) callers elsewhere (TypeIndex).
  • The ordering requirement (soleExactLeaf()/cap computed before filterWithIndexes() mutates node.index via the AND-sibling pruning) is currently inert since and is unconditionally excluded from the cap, but the comment correctly flags it as load-bearing the moment that exclusion is ever loosened — worth keeping.
  • Confirmed evaluateWhere() is unconditionally re-run on every candidate in SelectIterator.fetchNext() regardless of whether it came from an index cursor, which is what makes an "exact" leaf's cap safe: for eq/range-leaf cursors it never discards, so the candidate count exactly matches the result count.

Minor observations (non-blocking)

  1. Pre-existing gap adjacent to this change, already tracked: filterWithIndexesFinalNode() has no NOT-negation handling at all — a leaf directly under a not node still gets a plain (non-negated) cursor built for it. It's unreachable today since SelectOperator.not has no fluent entry point, and this PR's own notLeafIsNeverTreatedAsExactlyIndexed test only exercises lookForIndexes()/indexCandidateLimit without executing the query, so it doesn't surface it — consistent with what's described as filed under SelectExecutor.filterWithIndexesFinalNode() would build a wrong cursor for a NOT-wrapped indexed leaf, if NOT ever gets a fluent entry point #6575. Just flagging that I independently hit the same edge while reviewing, no action needed here.
  2. Test coverage: the "sole exact leaf, skip+limit capped correctly" path is tested for eq and in, but not for gt/ge/lt/le/between as the sole leaf. The reasoning generalizes cleanly (any leaf whose node.index gets set and whose operator produces a cursor in the switch is equally exact), so I don't think there's a real bug, but a skipAndLimitOnPlainIndexedRangePagesCorrectly-style case would close the gap explicitly rather than relying on the shared classification logic being correct by inspection.
  3. Minor redundancy: lookForIndexes() now walks the where-tree three times (isTheNodeFullyIndexed(), soleExactLeaf(), filterWithIndexes()). Given where-trees are small (a handful of conditions per query), this is not a real performance concern, just noting it in case it's worth folding soleExactLeaf()'s check into the same traversal down the line.

Test coverage / process note

The regression test class is thorough (14 cases covering both original shapes, the run-wrapper gap, AND-under-OR, bare NOT, ORDER BY interaction, overflow, and the OR-duplicate-candidate case) and several assert on indexCandidateLimit directly where a row-count assertion couldn't distinguish "correctly capped" from "uncapped fallback" — that's the right call given how easy it'd be for a future edit to silently regress into the always-safe-but-unoptimized fallback.

One thing worth double-checking before merge, since I can't run the suite in this environment: the PR description says the full com.arcadedb.query.select + com.arcadedb.index run is green (222 classes/1205→1216 tests across the commits). Given MultiIndexCursor.hasNext()'s off-by-one fix is a behavior change usable by any caller passing a real limit, it'd be worth a final full run to be sure, though the grep-confirmed call-site audit makes me fairly confident nothing outside SelectExecutor is affected.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

Went through MultiIndexCursor.java, SelectExecutor.java, and the new Issue6565SelectIndexCandidateLimitTest.java line by line, plus the surrounding Select.java/SelectIterator.java/SelectOperator.java code that the new logic depends on (tree-building in setLogic, orderBy semantics, precedence values). Verified the invariants the new comments assert rather than taking them on faith:

  • run-wrapper claim holds. Traced Select.setLogic(): a run-operator node is created only in the "1ST TIME ONLY" branch when the whole where-clause is a single bare condition (no and()/or() ever called), and its right is unconditionally null. When and()/or() was already called, the trailing setLogic(run) from compile() takes the other branch and never allocates a run node at all — it just fills in right on the existing tree. So soleExactLeaf()'s pass-through for run is safe and exhaustive.
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s trivial-match check correctly — confirmed ascendingOrder is hardcoded true in filterWithIndexesFinalNode() (line 363), so comparing orderBy.getSecond() directly (rather than against usedIndex.order) is equivalent.
  • The unchecked cast (SelectPropertyValue) leaf.left is indeed guarded transitively: soleExactLeaf() only returns non-null when node.index != null, and isTheNodeFullyIndexed() only ever sets node.index after that exact same cast already succeeded on node.left.
  • MultiIndexCursor.hasNext()'s browsed >= limit fix is correct and I confirmed via grep that the only two call sites passing a real (non -1) limit are the two in SelectExecutor; every other caller (TypeIndex) passes -1, so tightening the comparison can't regress an unbounded consumer.
  • The OR-dedup fix is real and necessary, not defensive theater: SelectExecutor only allocates the filterOutRecords dedup set when getCursors() > 1, and MultiIndexCursor.next() is a plain k-way merge with no RID dedup of its own — so before this PR's 7th round, an overlapping OR really could exhaust the candidate cap on duplicates before the downstream dedup ever ran. Good catch, and the regression test (overlappingOrBranchesOnTheSamePropertyStillReturnLimitDistinctRows) reproduces it concretely rather than asserting on the shape alone.
  • computeExactCandidateLimit()'s overflow handling is correct (long-arithmetic sum, explicit -1 fallback rather than clamping), consistent with the -1 "uncapped" sentinel used everywhere else in the class.

I did not find a remaining correctness gap in the shapes this PR now handles (bare leaf, run-wrapped bare leaf, and, or, not, is_null/is_not_null, in_op nested cursor, ORDER BY interaction, overflow). The self-review history in the commit log is unusually thorough (12 rounds), and each round's fix checks out against the code as I read it.

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 (.count() on realistic data) and white-box (asserting indexCandidateLimit directly) tests — the latter matters because, as the test comments note, a pure row-count assertion can't distinguish "correctly capped" from "uncapped fallback that happens to be correct anyway."

Minor nits (non-blocking):

  • int indexCandidateLimit = -1; (SelectExecutor.java:48) doesn't follow the column alignment of the two adjacent field declarations (evaluatedRecords/usedIndexes) — cosmetic only.
  • Several of the new Javadoc/inline comments are quite long relative to the rest of the file's style (the class doc for soleExactLeaf() especially); the 6th commit already trimmed some of these, might be worth one more pass, but it's a judgment call given how much implicit tribal knowledge they're encoding.

Performance note: this correctly trades away a previously-unsound optimization — and/or/not/is_null shapes now run the index scan uncapped instead of capped-but-wrong. For a query combining one of those shapes with a small limit over a large index range, this can mean scanning more index entries than before. That's the right tradeoff (silently-wrong results are worse than a slower correct query), just worth knowing it's there if a follow-up perf report comes in for such a query shape.

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 mvn compile/mvn test in this review environment (sandboxed, no shell execution available), so this is a static/read-through review only — I'd lean on CI (and the PR description's own claim of a 1217-test green run across com.arcadedb.query.select + com.arcadedb.index) for the dynamic verification.

…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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced the logic in SelectExecutor.java/MultiIndexCursor.java against the new test suite by hand (this sandbox couldn't get approval to run mvn/mvnw, so this is a manual verification rather than a live test run - please make sure CI is green before merging).

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:

  • soleExactLeaf() correctly special-cases the synthetic run wrapper Select.compile() produces for a bare single-condition where-clause (I confirmed in Select.setLogic() that run is only ever a real tree-node operator in the "1ST TIME ONLY" branch, always with right == null - the multi-condition case reuses the last node's own operator instead, so the pass-through is safe).
  • Excluding or from the "exact" fast path is correct and necessary: MultiIndexCursor is a dedup-free k-way merge, so overlapping OR branches (same-property overlapping ranges, or two different properties one record can satisfy together) would double-count candidates against the cap. Good catch, and the regression test (overlappingOrBranchesOnTheSamePropertyStillReturnLimitDistinctRows) reproduces it convincingly.
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s own trivial-match condition (usedIndexes.size()==1, same property, ascending == true since the index is always scanned ascending) - I checked both sides and they agree.
  • MultiIndexCursor.hasNext()'s browsed >= limit (was >) is scoped correctly: grepped all constructor call sites, and the only two passing a real (non -1) limit are the two in SelectExecutor; every other caller (TypeIndex, tests) passes -1, so unbounded iteration is unaffected.
  • The indexCandidateLimit reset to -1 when cursors ends up empty (bare neq/like/ilike leaf, tracked separately as Native select: OR with a non-cursor-buildable operator (NEQ/LIKE/ILIKE) on one side silently drops the whole other branch #6577) closes a real gap - without it the test-visible field would report a cap that was never actually applied.

I also hand-checked the arithmetic in all 15 new test cases (row/match counts for the g/n/b distributions, skip/limit expectations, the IN-under-OR union size of 601, the overflow case) - they all check out.

Minor, non-blocking nits:

  1. One leftover comment in the test file still says // CODE REVIEW GAP: ... (Issue6565SelectIndexCandidateLimitTest.java around line 288), while the "trim inline comments, drop review-round references" commit cleaned up the others. Small inconsistency, worth a pass if there's a next revision.
  2. The final "align indexCandidateLimit's declaration with its neighboring fields" commit aligns the type column but not the = signs (the identifier itself is longer than evaluatedRecords/usedIndexes, so full alignment isn't achievable without touching the other two lines). Purely cosmetic, not worth another round by itself.

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 indexCandidateLimit assertions (correctly reasoned as necessary, since a result-count assertion alone can't distinguish "correctly capped" from "uncapped fallback that happens to be correct too").

No correctness, security, or performance concerns from my read - the added logic runs once per query compile (O(tree depth)), and the whole change is confined to com.arcadedb.query.select/com.arcadedb.index, matching the PR description's stated blast radius.

…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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced through lookForIndexes(), soleExactLeaf(), isOrderBySafeForCap(), filterWithIndexesFinalNode(), SelectIterator.fetchResultInCaseOfOrderBy(), and MultiIndexCursor to check the correctness argument end to end. Overall this is a solid, well-reasoned fix with unusually thorough test coverage for the shapes it changes. A few notes:

Correctness

  • The core diagnosis is right: MultiIndexCursor's limit needs to be a candidate cap that is guaranteed to leave evaluateWhere()/skip enough records to work with, not the result limit. Reusing select.limit for that (old code) is unsound whenever downstream filtering can shrink the stream, which is exactly the AND+non-indexable and skip>=limit cases the linked issue describes.
  • soleExactLeaf() walking through the synthetic run wrapper (Select.setLogic's "1ST TIME ONLY" branch) and disqualifying and/or/not/is_null/is_not_null matches how filterWithIndexesFinalNode() actually builds cursors - I confirmed and always prunes one side and or merges without RID dedup (MultiIndexCursor.next() is a plain k-way merge), so treating both conservatively is correct, not just cautious.
  • The or-dedup problem the comments raise (overlappingOrBranchesOnTheSamePropertyStillReturnLimitDistinctRows) is a real, separate landmine that would have resurfaced the exact bug this PR fixes if or had been optimistically included - good catch, and good that it's pinned by a test rather than just documented.
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s trivial-match check correctly, including the detail that filterWithIndexesFinalNode() always scans ascending (ascendingOrder = true) regardless of the requested order direction, so a descending ORDER BY must disable the cap. I checked this is exercised by orderByDescendingOnAscendingScannedIndexWithLimitReturnsTrueTail.
  • MultiIndexCursor.hasNext()'s browsed >= limit (was > limit) is a genuine off-by-one fix independent of the skip+limit change - the old code returned limit + 1 candidates instead of limit. I verified via grep that the only two non--1 callers of MultiIndexCursor are both in SelectExecutor, so this tightening can't affect any unbounded caller elsewhere, as the PR description claims.
  • computeExactCandidateLimit()'s overflow guard (falls back to -1 rather than clamping) is a reasonable choice given -1 already means "uncapped" elsewhere in this class - no new sentinel needed.
  • The #6577 fallback (bare neq/like/ilike leaf: node.index != null but filterWithIndexesFinalNode()'s switch never builds a cursor for it) is handled generically by resetting indexCandidateLimit = -1 whenever cursors ends up empty, not just for those specific operators - this also correctly covers a between leaf with a malformed range array, which hits the same early-return path.

Minor observations (not blocking)

  • indexCandidateLimit widening from private to package-private purely for test visibility is a reasonable tradeoff given the stated reason (a result-count assertion can't distinguish "cap correctly computed" from "uncapped fallback happened to still return enough rows"), but it's worth flagging since it's a slight crack in encapsulation for testability. If this pattern spreads, a package-private test-support seam might be preferable to widening fields one at a time.
  • The ordering dependency called out in the comment at SelectExecutor.lookForIndexes() ("harmless today only because and is already unconditionally disqualified") is a latent trap: if a future change ever made soleExactLeaf() less conservative for and, the current call order (soleExactLeaf() runs before filterWithIndexes() prunes a sibling's node.index) would silently read stale state. Not a bug now, but worth a short note at soleExactLeaf()'s own declaration too, not just at the call site, since that's where a future editor is more likely to be looking when they touch the and case.
  • Performance tradeoff: shapes that are now correctly uncapped (AND with a non-indexable conjunct, any OR, skip >= limit paging) will do a full index scan where before they did a (silently wrong) bounded one. The PR description notes this matches what the SQL engine already does for the same shapes, which is a fair bar, but it's worth calling out explicitly in case anyone was inadvertently relying on the old capped-but-wrong behavior for latency on a very large index with a highly selective indexed conjunct paired with a huge non-indexed table.

Test coverage

Excellent - the cases in Issue6565SelectIndexCandidateLimitTest cover both shapes from the issue plus the edge cases the fix's own reasoning surfaces (IN-leaf nested cursor, OR-overlap dedup exhaustion, ORDER BY ascending/descending trivial-match, int-overflow, AND-under-OR, bare not, bare neq). The direct assertions on executor.indexCandidateLimit (rather than only result counts) are the right call given the PR's own observation that lazy-pull consumers already clamp to skip+limit regardless of the internal cap, so a pure result-count test can't distinguish "capped correctly" from "fell back to uncapped."

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@codacy-production

codacy-production Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 15 complexity

Metric Results
Complexity 15

View in Codacy

🟢 Coverage 92.00% diff coverage · -6.52% coverage variation

Metric Results
Coverage variation ✅ -6.52% coverage variation
Diff coverage ✅ 92.00% diff coverage

View coverage diff in Codacy

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.

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I traced the fix by hand against the actual tree shapes Select.compile()/setLogic() produce (the run-wrapper, AND-under-OR precedence, etc.) and cross-checked the claims in the commit messages against the code rather than taking them at face value. Everything checked out - the logic is sound and the 16-commit self-review history already closed every gap I could find (OR duplicate-candidate merge, ORDER BY forcing a full sort, the neq/like/ilike "indexed but no cursor" case, overflow, NOT/AND-under-OR conservatism). A few notes below, all minor.

Correctness (verified, no issues found)

  • soleExactLeaf()'s handling of the synthetic run wrapper matches Select.setLogic()'s "1ST TIME ONLY" branch exactly - confirmed right is always null there, so the recursion is safe.
  • isOrderBySafeForCap() mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s own trivial-match condition (usedIndexes.size() == 1, same property, orderBy.getSecond() == usedIndex.order where order is always true/ascending) - the two independent checks agree.
  • MultiIndexCursor.hasNext()'s browsed >= limit (was >) is correct given browsed only increments in next(); the two other constructors/call sites all pass -1, so this can't affect any unbounded caller.
  • The IN-leaf nested cursor sharing the outer indexCandidateLimit is a safe over-approximation as documented - traced through filterWithIndexesFinalNode and confirmed the outer cursor can never legitimately need more than that shared cap.
  • Confirmed SelectOperator.not has no reachable fluent or JSON-parsing entry point today (Select.fromJSON/parseJsonCondition appear unused outside this package), so deferring that observation to SelectExecutor.filterWithIndexesFinalNode() would build a wrong cursor for a NOT-wrapped indexed leaf, if NOT ever gets a fluent entry point #6575 rather than fixing it here is reasonable.
  • No perf regression from disabling the cap on AND/OR/NOT/IS [NOT] NULL shapes: the outer consumers (executeCount(), SelectIterator) already stop pulling once skip + limit real matches are found, independent of the cursor's own internal cap - so removing the cap only removes an unsound optimization, it doesn't force a full scan.

Minor style nits

  • A couple of the new test assertions use assertThat(cursor == null).isTrue() (e.g. bareNonCursorOperatorLeavesIndexCandidateLimitAtMinusOne, orOfIndexedLeavesIsNeverTreatedAsExactlyIndexed) where AssertJ's assertThat(cursor).isNull() would be more idiomatic.
  • soleExactLeaf()'s Javadoc is quite dense; given the commit history already did a trim pass for verbosity elsewhere, that's presumably intentional since every paragraph documents a genuinely non-obvious invariant that was the subject of its own review round - just flagging in case another pass is wanted.

Test coverage
Very thorough - both result-count and direct indexCandidateLimit assertions, covering bare leaves for every cursor-producing operator (eq, in_op, ge), AND+non-indexable, AND-under-OR, a hand-built NOT leaf, OR overlap/duplicate-candidate reproduction, ORDER BY safe and unsafe directions, and the int overflow guard. I didn't find a gap.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I 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 SelectExecutor.java, MultiIndexCursor.java, SelectIterator.java, and Select.java (compile()/setLogic()) as merged. Summary: the fix and its safeguards check out.

Correctness

  • The core bug and fix are sound. lookForIndexes() now only caps the index candidate scan when soleExactLeaf() proves the scan reproduces the where-tree's result set exactly (a bare leaf, or the same leaf through the synthetic run wrapper), and the cap is skip + limit rather than limit. I traced Select.setLogic() myself: the run operator is indeed only ever used in the "1ST TIME ONLY" branch (single bare condition, no and()/or()), and its right is always null — confirms the javadoc's claim rather than just trusting it.
  • The OR-duplicate-candidate fix (round 7) is the most important corrective in the whole series. MultiIndexCursor does a plain k-way merge with no RID dedup, so an OR of overlapping ranges could exhaust the cap on duplicates before downstream filterOutRecords ever runs — the same defect class this PR exists to fix, reachable again through the very fast path meant to avoid it. Good catch, and disqualifying or unconditionally (rather than trying to special-case provably-disjoint shapes) is the right conservative call, since disjointness genuinely can't be proven from tree shape alone for cross-property ORs.
  • The ORDER BY interaction (round 5) is also a real, independent bug class (fetchResultInCaseOfOrderBy()'s full-drain sort would only see the first few ascending candidates under a mismatched sort direction) and I verified isOrderBySafeForCap() mirrors SelectIterator's own trivial-match precondition (usedIndexes.size() == 1, matching property, ascending) field-for-field.
  • The in_op nested-cursor safety argument holds for the ordinary case: values in the IN list are distinct keys on the same property, so their RID sets are disjoint by construction — given the property is single-valued. One thing I didn't see explicitly addressed: if the indexed property were ever a multi-valued/array type indexed with one index entry per element, the same document could match two different IN values and surface as two candidates through the nested merge, which is structurally the same hazard as the OR-overlap bug that was already found and fixed. Worth a quick sanity check (or a one-line comment) on whether ArcadeDB's indexing model rules this out for in_op's leaf property, since the "disjoint by construction" claim is the linchpin of that whole code path.

Minor / non-blocking observations

  • Unrelated to this diff, but noticed while tracing executeCount(): LIMIT 0 currently returns a count of 1, not 0 (the count >= select.limit check runs after count++). This PR's new cap (skip + limit = skip when limit == 0) incidentally makes the indexed, capped path return the correct 0, while the uncapped/non-indexed path still returns 1 — a pre-existing inconsistency this PR didn't create but now makes slightly more visible. Not something to fix here, just flagging in case it's useful for a follow-up issue.
  • Test coverage for "sole exact leaf, cap applied correctly" exercises eq, in_op, and ge; the other range operators (gt, lt, le, between) go through the same soleExactLeaf()/filterWithIndexesFinalNode() path without any operator-specific branching, so this is low-risk, but an explicit between case would close the loop given it's the one operator with a distinct two-bound cursor shape.
  • The javadoc on soleExactLeaf() is quite long (documents several rounds of accumulated invariants). Given the file already went through one "trim inline comments" pass, this is a judgment call rather than a real issue — the content is genuinely load-bearing (call-order dependency, the run-wrapper shape, the OR-exclusion reasoning), just dense for a single method's Javadoc. No action needed unless it grows further.
  • indexCandidateLimit's visibility was widened from private to package-private solely so the regression test can assert on the computed cap directly (a row-count assertion can't distinguish "correctly capped" from "uncapped fallback that happens to be correct anyway"). Reasonable trade-off for a field that exists purely as an internal optimization knob.

Test coverage

19 regression tests is thorough for the scope of this fix — it covers both original defect shapes from #6565, the run-wrapper gap, AND-under-OR, bare NOT, ORDER BY direction mismatch, OR-of-indexed-leaves duplication, IN-nested-under-OR, the int overflow guard, and the neq/like/ilike stray-cap reset. The commit messages note the full com.arcadedb.query.select + com.arcadedb.index suite (1217 tests) passed after the final round.

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.
@lvca

lvca commented Aug 22, 2026

Copy link
Copy Markdown
Member Author

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

@claude

claude Bot commented Aug 22, 2026

Copy link
Copy Markdown

Review

I read through SelectExecutor.java, MultiIndexCursor.java, SelectIterator.fetchResultInCaseOfOrderBy(), and Select.setLogic()/compile() to independently verify the reasoning in the PR description and commit trail, and traced the new test file against them.

Correctness

The core fix is sound:

  • soleExactLeaf() correctly identifies the only shape where an index cursor exactly reproduces the where-tree's result set (a bare leaf, or the synthetic run-wrapped leaf Select.compile() produces for a single bare condition). I confirmed by reading Select.setLogic() that run is only ever created in the "1ST TIME ONLY" branch with right == null, so treating it as a transparent pass-through is safe and exhaustive - run genuinely can't appear anywhere else in the tree.
  • Disqualifying and/not/or from the cap is correct given filterWithIndexesFinalNode()'s actual behavior (only one AND child's cursor survives when either side is unique; both survive as a union otherwise; MultiIndexCursor does a dedup-free k-way merge so overlapping OR branches would double-burn the cap). The n > 5 OR n < 500 LIMIT 10 repro described for the OR case is a real, non-obvious bug class, and disqualifying OR is the right conservative call since disjointness isn't provable from tree shape alone.
  • MultiIndexCursor.hasNext()'s browsed >= limit fix is correct (previously admitted one extra candidate), and I verified via grep that the only two call sites passing a real (non -1) limit are the two in SelectExecutor - the other three constructors elsewhere in the codebase all pass -1, so this can't regress any unbounded caller.
  • The isOrderBySafeForCap() guard correctly mirrors SelectIterator.fetchResultInCaseOfOrderBy()'s own trivial-match precondition (usedIndexes.size() == 1, matching property, ascending direction) - I checked filterWithIndexesFinalNode() always scans ascending (ascendingOrder = true is hardcoded), which is exactly what the check assumes.
  • The reset of indexCandidateLimit to -1 when cursors ends up empty (bare neq/like/ilike) is a good defensive touch for the field's new role as a test-visible signal - functionally inert but keeps the invariant "the field always reflects whether a cap was actually applied" from silently drifting.

Performance

The removal of the cap for AND/OR-shaped queries looks like a real correctness-over-performance tradeoff at first glance, but it isn't actually a regression: executeCount()/SelectIterator pull from the MultiIndexCursor lazily and stop as soon as count >= select.limit downstream, so an "uncapped" index scan for a disqualified shape is still bounded in practice by the same early-exit the consumer already does - the cap was only ever a (buggy) short-circuit, not the only bound. No new unbounded-scan risk here.

Test coverage

Very thorough - the 17-commit self-review trail already closed most of the corner cases I'd otherwise flag: the run-wrapper gap, AND-under-OR precedence shape, bare NOT, skip+limit overflow, ORDER BY direction mismatch, OR-overlap duplicate candidates, range/between operators as the sole leaf, and the neq non-cursor-building leaf. I don't have anything to add on top of what's already covered. The follow-up issues filed for out-of-scope findings (#6575, #6577, #6578, #6579) are legitimate and appropriately scoped out rather than bundled in.

One minor note, not a blocker: indexCandidateLimit and lookForIndexes() were widened from private to package-private purely for test visibility. That's a reasonable and honestly-documented tradeoff (a row-count assertion genuinely can't distinguish "correctly capped" from "uncapped fallback happens to be correct too"), but it's worth being aware this is now part of the class's test-observable surface if SelectExecutor is refactored later.

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 run-wrapper shape, the OR-duplicate-candidate hazard) for future readers.

@codecov

codecov Bot commented Aug 22, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 72.00000% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.27%. Comparing base (dfeecae) to head (d8d5b95).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
...java/com/arcadedb/query/select/SelectExecutor.java 75.00% 2 Missing and 4 partials ⚠️
...main/java/com/arcadedb/index/MultiIndexCursor.java 0.00% 0 Missing and 1 partial ⚠️
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.
📢 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 4051926 into main Aug 22, 2026
31 of 33 checks passed
@lvca
lvca deleted the fix/6565-native-select-limit-candidate-scan branch August 22, 2026 15:36
robfrank added a commit that referenced this pull request Aug 24, 2026
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.
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.

Native select applies limit to the index candidate scan: skip/limit paging and IS NOT NULL silently lose rows

1 participant