Skip to content

fix(#9021): an index on an integral key answers for the exact bound, not the truncated one - #9126

Merged
robfrank merged 3 commits into
mainfrom
fix/9021-index-fractional-bound-integer-key
Oct 4, 2026
Merged

robfrank merged 3 commits into
mainfrom
fix/9021-index-fractional-bound-integer-key

Conversation

@robfrank

@robfrank robfrank commented Oct 3, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #9021

An index whose key is BYTE, SHORT, INTEGER or LONG converted every bound to its key type with Type.convert, which truncates a fraction (12.5 -> 12) and clamps or wraps a value past the key range (1e19 -> Long.MAX_VALUE, 3e9 on an INTEGER wraps). So the index answered for a different bound than the scan: i = 12.5 returned the 12, i >= 12.5 returned 12, i < 12.5 lost it, l = 1e19 returned Long.MAX_VALUE. The new com.arcadedb.index.IntegralKeyBound maps a bound that no integral key equals onto the key that bounds the same set of keys, always inclusive: the smallest key above it for a lower bound, the largest key below it for an upper bound. An equality on such a bound matches nothing. A bound past the range clamps to MIN/MAX or matches nothing. NaN sorts as the greatest number, the same way the scan orders it. The mapping runs where each engine opens its index cursor, so literals and parameters go through the same code.

Coverage

Invariant: for a numeric bound on an integral index key, the index returns exactly the rows the scan returns.

Entry point Status Test
SQL FetchFromIndexStep AND-block seeks (=, <, <=, >, >=, two-sided range, composite prefix + range, IN, list parameter) fixed here sqlIndexAgreesWithTheScanForEveryOperatorAndInexactBound, sqlLiteralBoundsAgreeWithTheScan, sqlTwoSidedRangesBetweenAndInAgreeWithTheScan, sqlDescendingOrderOverAnInexactRange
SQL FetchFromIndexStep single-condition / BETWEEN / IN key paths (createCursor, processBetweenCondition) fixed here same tests (IN), sqlLinesOfTheIssue
SQL BETWEEN scan (BetweenCondition): cast the bound to the value's class, so 11 BETWEEN 11.5 AND 12.5 was true fixed here (otherwise the index and scan would disagree the other way) sqlLinesOfTheIssue
openCypher NodeIndexRangeScan (the < regression from 179cf8d) fixed here cypherLinesOfTheIssue, cypherIndexAgreesWithTheScanForEveryOperatorAndInexactBound
Fluent database.select() (SelectExecutor gt/ge/lt/le/between) fixed here (same defect: lt 12.5 lost 12) fluentSelectIndexAgreesWithTheScan
openCypher equality seeks / joins (NodeIndexSeek, IndexNestedLoopJoin, MatchEdgeByIndexStep), SQL subquery =/IN argued: probed empirically, already correct (downstream filter re-checks the candidates) Cypher = is in the operator matrix
DELETE FROM index:... WHERE key BETWEEN (DeleteFromIndexStep) filed as #9125 -

theIndexIsUsedForTheBoundsUnderTest asserts that the indexed type's plan really contains FETCH FROM INDEX, so the agreement checks never end up comparing a scan against a scan.

Known gaps: #9125 (direct index delete). #8970 (parameter bound past 2^53 on a DOUBLE key) is a separate issue and this PR does not touch it.

Test plan

  • Issue9021IntegralIndexInexactBoundTest (10 tests): before the fix 7 failed with the issue's exact outputs. With the fix, 10/10 pass. The fluent and BETWEEN-scan assertions also failed with only those two files reverted.
  • Issue8919FloatRangeBoundTest, Issue8333* (index range selectivity, SQL + Cypher): green
  • *Index*Test,*Between*Test,*Range*Test,Select*Test,Issue8*Test,Issue9*Test,*FetchFrom*Test in engine: 3052 tests. 3 failures, all of which also fail on main c611828 with this PR's sources reverted: Issue741InOperatorEdgeCompositeIndexTest.inValuesAreOrderedAsTheIndexStoresThemNotAsWritten, Issue8872DecimalLiteralDigitsTest.indexedAndUnindexedDoubleAgreeOnALongLiteral, Issue8872DecimalLiteralDigitsTest.updateDeleteAndInOnIndexedDecimalAndDouble
  • com/arcadedb/query/opencypher/**/*Test + com/arcadedb/query/sql/executor/**/*Test: 2007 tests, green
  • com/arcadedb/query/select/**, Cypher Where/Comparison tests, SQL parser and operator tests: 820, only the pre-existing Issue741 failure

Adversarial pass

There was no subagent (Task) tool in this run, so the Phase 1.5 independent pass did not run. Self-review in its place:

  • Inverted ranges after the mapping (i > 12.2 AND i < 12.7 maps to 13 <= i <= 12) are detected and answer empty, so the index is never asked to read a range backwards. Covered in SQL, Cypher and fluent.
  • A bound past the INTEGER range (i < 3e9) used to be dropped by valuesConvertToIndexKeyTypes before any mapping, which returned no rows. The mapping now runs first. Covered.
  • Seek de-duplication in sortSeeksInIndexOrder now also compares the inclusion flags, so two seeks with the same keys but different inclusion are not collapsed.

Residual risk

The direct index-delete statement (#9125). Non-numeric bounds (strings) on integral keys keep their existing #5900/#8888 behavior.

Summary by CodeRabbit

  • Bug Fixes
    • Corrected indexed range queries on byte, short, integer, and long values when bounds are fractional, outside the supported range, or non-finite.
    • Updated SQL, fluent-select, and Cypher queries to return results consistent with unindexed scans for equality, range, and BETWEEN conditions.
    • Improved handling of inclusive and exclusive range boundaries, including compound conditions and composite indexes.

…not the truncated one

A bound no BYTE/SHORT/INTEGER/LONG key equals (12.5, 1e19, 3e9 on an INTEGER) is mapped onto the
key that bounds the same set, inclusive, or matches nothing, in SQL (FetchFromIndexStep),
openCypher (NodeIndexRangeScan) and the fluent Select API. The SQL BETWEEN scan no longer
converts a numeric bound to an integer value's class.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

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

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ce850b87-1bba-47fe-8c2f-5187357174a4
📥 Commits

Reviewing files that changed from the base of the PR and between 50657bd and 2046858.

📒 Files selected for processing (6)
  • engine/src/main/java/com/arcadedb/index/IntegralKeyBound.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeIndexRangeScan.java
  • engine/src/main/java/com/arcadedb/query/select/SelectExecutor.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/FetchFromIndexStep.java
  • engine/src/main/java/com/arcadedb/query/sql/parser/BetweenCondition.java
  • engine/src/test/java/com/arcadedb/query/Issue9021IntegralIndexInexactBoundTest.java
 __________________________________________
< Given enough GPUs, all bugs are shallow. >
 ------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

❤️ Share

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

@mergify

mergify Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

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

@codacy-production

codacy-production Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 1 medium · 2 minor

Alerts:
⚠ 3 issues (≤ 0 issues of at least minor severity)

Results:
3 new issues

Category Results
BestPractice 1 minor
ErrorProne 1 medium
CodeStyle 1 minor

View in Codacy

🟢 Metrics 10 complexity

Metric Results
Complexity 10

View in Codacy

🟢 Coverage 63.16% diff coverage · -5.79% coverage variation

Metric Results
Coverage variation ✅ -5.79% coverage variation
Diff coverage ✅ 63.16% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (1b1ae3e) 211782 180120 85.05%
Head commit (9c3e515) 244390 (+32608) 193715 (+13595) 79.26% (-5.79%)

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 (#9126) 19 12 63.16%

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 Oct 3, 2026

Copy link
Copy Markdown

Review of #9126

The approach is sound. Mapping an inexact bound onto the nearest key that bounds the same set, always inclusive, is the right model, and it lives in one small class (IntegralKeyBound) that all three engines share. The I vs S agreement testing, plus theIndexIsUsedForTheBoundsUnderTest to make sure the indexed side really uses the index, is a strong way to pin the invariant. I read the diff only and did not run the tests, so the points below are from reading.

Issues worth addressing

  1. Misplaced field in SelectExecutor. NO_KEY (and its Javadoc) was inserted between the long all-caps comment block and the field it documents (CURSOR_BUILDABLE_OPERATORS). That block now reads as if it describes NO_KEY, and CURSOR_BUILDABLE_OPERATORS has lost its comment. Please move NO_KEY above the comment block or below the CURSOR_BUILDABLE_OPERATORS declaration.

  2. Inverted-range handling is inconsistent across the three engines. The SQL (mapInexactIntegralBounds, processBetweenCondition) and Cypher paths explicitly detect 13 <= i <= 12 and skip the index, with the rationale that the index must never be asked to read a range backwards. The fluent SelectExecutor between branch has no such guard and passes [13]..[12] straight to index.range. fluentSelectIndexAgreesWithTheScan covers between 12.2 AND 12.7 and passes, so it works today. It now depends on the LSM cursor tolerating from > to, though, which the other two paths avoid on purpose. Either add the same guard (cheap, and it makes the three consistent) or note in a comment why it is safe here.

  3. BetweenCondition is only covered for finite bounds. The new integralValue && bound instanceof Number branch hands Double.NaN and infinities to BinaryComparator.compareTo, but the tests only exercise NaN/infinity for =, <, <=, >, >= and never for BETWEEN (neither the scan nor the index). A one-line addition to sqlTwoSidedRangesBetweenAndInAgreeWithTheScan would close that, since the index side maps NaN to ceiling = null / floor = MAX.

Smaller points

  • Allocation on exact doubles. The isInexact Javadoc says it "allocates nothing for an integral bound in range", which is true for Byte/Short/Integer/Long but not for Double/Float. An exact 12.0d (common from JSON or parameters) goes through Type.floatingToBigDecimal, and ceiling/floor repeat it. This runs once per bound per query so it is not hot, but IN [..] lists with many doubles pay it per element. A primitive fast path for Double/Float (finite, d == Math.rint(d), and -2^63 <= d < 2^63 before comparing to min/max) would remove it, and would make the Javadoc true. Optional.
  • Redundant local. In createCursor, inclusive is just an alias for boundMapped. Using boundMapped directly would be clearer. Also, boundMapped is detected by reference inequality (key[last] != values[last]). That is correct today because the mapping always boxes a new Number, but it is subtle. A small comment, or having mapInexactIntegralBound return a tri-state, would protect against a future "return the same instance" optimization. The same applies to from != rightValue in SelectExecutor.
  • Duplicated mapping logic. mapInexactIntegralBound / mapInexactIntegralBounds in FetchFromIndexStep and the Cypher and SelectExecutor blocks all repeat "if inexact, then ceiling/floor, null means no match, else inclusive". A helper on IntegralKeyBound returning the mapped bound or a sentinel would shrink the three call sites and the chance that they drift (the SelectExecutor NO_KEY sentinel is already half of that).
  • Test coverage gaps.
    • Only NOTUNIQUE LSM indexes are exercised. A UNIQUE index (equality goes through a different lookup path) and a HASH index with i = 12.5 would be cheap additions.
    • The fluent test only covers the INTEGER column. LONG with 1e19, and SHORT/BYTE, are exercised in SQL and Cypher but not fluent.
    • Descending order (ORDER BY i DESC) is covered for single-sided ranges only, not for a mapped two-sided one where seek[2] inclusion flags are swapped with the bounds in index.range(false, convertedTo, toIncluded, convertedFrom, fromIncluded).
  • The test file has several very long lines (the wheres array, the bounds arrays). Not blocking, but the repo uses a 160-column width.

Security and performance

No security concerns: no new inputs are parsed, and bound mapping uses BigDecimal with bounded scale, so there is no overflow or wrap path. The fix removes wrap-around of out-of-range bounds, which is a correctness improvement. There is no per-row cost; everything runs once per cursor open.

Good call filing #9125 for DeleteFromIndexStep rather than widening this PR. Items 1 and 2 are the ones I would fix before merging.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Oct 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 47.36842% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.82%. Comparing base (1b1ae3e) to head (9c3e515).
⚠️ Report is 48 commits behind head on main.

Files with missing lines Patch % Lines
...rcadedb/query/sql/executor/FetchFromIndexStep.java 25.00% 7 Missing and 2 partials ⚠️
...java/com/arcadedb/query/select/SelectExecutor.java 66.66% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #9126      +/-   ##
============================================
+ Coverage     76.80%   76.82%   +0.02%     
- Complexity     3913     3914       +1     
============================================
  Files          2123     2123              
  Lines        211782   211786       +4     
  Branches      44906    44909       +3     
============================================
+ Hits         162665   162714      +49     
+ Misses        31699    31667      -32     
+ Partials      17418    17405      -13     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

robfrank and others added 2 commits October 4, 2026 16:01
Conflict in FetchFromIndexStep: keep both the #9032 null-IN skip (before the
mapping) and the #9021 inexact-bound mapping, and both helper sets.

Review (claude):
- SelectExecutor: NO_KEY moved below CURSOR_BUILDABLE_OPERATORS so the
  all-caps comment documents the field it belongs to again
- SelectExecutor between: a mapped range that inverts (12.2..12.7 -> [13, 12])
  answers empty instead of asking the index to read backwards, as SQL and
  Cypher already do
- FetchFromIndexStep: mapInexactIntegralBound returns NO_MATCH/BOUND_KEPT/
  BOUND_MAPPED instead of the caller detecting a mapping by reference; the
  redundant 'inclusive' alias is gone
- IntegralKeyBound.isInexact: primitive fast path for Double/Float below 2^53,
  no BigDecimal for an exact 12.0d
- tests: UNIQUE and UNIQUE_HASH indexes, fluent API on every integral key type
  plus mapped and inverted BETWEEN, SQL BETWEEN with NaN/infinite bounds,
  descending two-sided mapped ranges, fast-path bound cases, 160-column lines

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robfrank

robfrank commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

Review response (commits 2046858, 9c3e515):

Note: main already carries this PR's original #9021 commit (e54f8cb, brought in by #9160). After merging main, this PR's diff is only the review follow-ups below.

# Item Outcome
1 NO_KEY placed between the all-caps comment and CURSOR_BUILDABLE_OPERATORS Fixed: moved below the field, so the comment documents its own field again
2 Fluent between passed an inverted mapped range to the index Fixed: a mapped range that inverts (12.2..12.7 maps to [13, 12]) now answers empty, as SQL and Cypher do. Covered by {12.2, 12.7} and {1e19, -1e19} in the new fluent test
3 BETWEEN not tested with NaN or infinite bounds Added sqlBetweenWithNaNAndInfiniteBoundsAgreesWithTheScan: every pair of NaN, +Inf, -Inf and 12.5 on i/l/s/b/u, indexed vs. scan
- Exact doubles allocate a BigDecimal Fixed: isInexact has a primitive path for Double/Float below 2^53, where the binary value and the decimal reading the scan compares have the same integer part. At or above 2^53 it still uses the BigDecimal path, because the two readings can differ there (e.g. 2^63-1024). Boundary cases added to boundMapping
- inclusive alias, and the mapping detected by reference Fixed in FetchFromIndexStep: mapInexactIntegralBound returns NO_MATCH / BOUND_KEPT / BOUND_MAPPED. In SelectExecutor the reference check is safe by construction: a mapped key is an integral number in range, so it is never the same object as the inexact bound it replaces. A Javadoc now says so
- Duplicated "ceiling or floor" logic at the call sites Not done: each call site differs in what it does on "no key" (null cursor, NO_KEY, return false), so a shared helper would only fold one ternary per site. DeleteFromIndexStep (#9160) now uses the same primitives
- UNIQUE and HASH indexes, fluent API on LONG/SHORT/BYTE, descending two-sided range Added: UNIQUE u and UNIQUE_HASH h columns in the SQL agreement and EXPLAIN tests, a fluent test on every integral key type with all operators and mapped/inverted between, and descending two-sided mapped ranges, including on a composite prefix
- Long lines in the test Fixed: the test now fits 160 columns

Verification: Issue9021IntegralIndexInexactBoundTest 12/12. Related engine suites (query/sql/**, query/select/**, index/**, query/Issue*, Cypher index and range tests, delete tests; benchmark/slow/vector excluded): 4474 tests, 0 failures.

@claude

claude Bot commented Oct 4, 2026

Copy link
Copy Markdown

Review of the follow-up changes (IntegralKeyBound fast path, FetchFromIndexStep mapping status, SelectExecutor empty-range guard, extra tests)

I read the diff and the surrounding code. I did not run the tests in this environment (the sandbox blocked the Maven invocation), so everything below comes from reading.

Overall: the change looks correct and the invariant ("index returns exactly what the scan returns") is well covered. No blocking issues.

What looks good

  • IntegralKeyBound.isInexact fast path. For a finite Double/Float with |v| < 2^53, v != Math.rint(v) || v < min || v > max gives the same answer as the BigDecimal route. I checked where they could differ: binary and Double.toString readings share the integral part below 2^53 (the shortest representation never lands on a different double), an integral Float also prints as an integral decimal, and the long min/max promoted to double is harmless because the fast path never sees values near 2^63. It removes a BigDecimal allocation from the hot path for the common x < 12.5 case, in line with the performance guidance.
  • mapInexactIntegralBound now returns a tri-state (NO_MATCH / BOUND_KEPT / BOUND_MAPPED) instead of the caller inferring "mapped" with key[last] != values[last]. That removes a reference-identity trick and the redundant inclusive local in createCursor. The early return BOUND_MAPPED inside the loop is equivalent to the old fall-through, because the mapped element is always the last one.
  • SelectExecutor: moving NO_KEY below CURSOR_BUILDABLE_OPERATORS re-attaches the long warning comment to the field it describes. The inverted-range guard (12.2 BETWEEN 12.7 maps to [13, 12]) matches the SQL and Cypher behavior.
  • Tests: the added UNIQUE and UNIQUE_HASH indexes, all four integral key types in the fluent API, NaN/infinity BETWEEN combinations and the 2^53 boundary cases in boundMapping cover the paths most likely to diverge. theIndexIsUsedForTheBoundsUnderTest guards against comparing a scan with a scan, including for u and h.

Minor suggestions (non-blocking)

  1. SelectExecutor (the between branch): "was this bound mapped" is still detected by reference identity (from != range[0] || to != range[1]). The new Javadoc explains why it is safe today, but it is the same fragility just removed from FetchFromIndexStep. A mapped flag would keep both engines consistent.
  2. FetchFromIndexStep: private static final int NO_MATCH = -1, BOUND_KEPT = 0, BOUND_MAPPED = 1; sits mid-class between methods, as a multi-variable declaration. Moving the constants up with the other fields, one per line, would match the file layout.
  3. processBetweenCondition still applies the lower.longValue() > upper.longValue() check when neither bound was mapped (e.g. BETWEEN 13 AND 12). That is correct (empty range), just not limited to mapped bounds.
  4. In isInexact, the comment says the two readings are "the same number"; "same integral part and same fractional status" is the property the fast path actually relies on. A test with a Float such as 1.23456794E9f against INT would pin the Float branch, since current tests only use 12.0f and 12.5f.
  5. sqlIndexAgreesWithTheScanForEveryOperatorAndInexactBound now loops 6 fields x operators x 17 bounds with two queries each. Probably fast on a 3-row type, but if CI time grows consider @Tag("slow") per CLAUDE.md.

Residual

Nothing here blocks merging once CI is green.

@robfrank
robfrank merged commit 0ef1877 into main Oct 4, 2026
@robfrank
robfrank deleted the fix/9021-index-fractional-bound-integer-key branch October 4, 2026 14:09
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Oct 4, 2026
… entry says Fixed in 26.10.1 (PR ArcadeData#9126) (#166)

Upstream PR ArcadeData#9126 (merge 0ef1877) makes an index on an integral key
answer for the exact bound. The strict xfail for ArcadeData#9021 now asserts the
fixed rows (i = 12.5 matches nothing, i >= 12.5 returns 13, i < 12.5
returns 11 and 12) on the indexed and on the unindexed type, and checks
that the plan of the indexed query reads the index, so the test cannot
pass by comparing a scan with a scan.

Since #143 the ArcadeData#9021 entry in known-issues.md carried the Fixed paragraph
of ArcadeData#9014 and ArcadeData#9027 (PR ArcadeData#9121). That paragraph moves back to its own
entry, and ArcadeData#9021 gets a Fixed paragraph for PR ArcadeData#9126. The rounding
workaround is kept for engines before 26.10.1.

Checked with the 2026-10-03 wheel: on its engine (b22b5e9) the three
new cases fail with the answers the issue reports; with the wheel's
engine jars replaced by builds of upstream main 2e09816 and
422a5f6, all 11 tests in the file pass.


Claude-Session: https://claude.ai/code/session_01Ubz3m6QXHESerCkehC1qgi

Co-authored-by: Claude Opus 5.5 <[email protected]>
robfrank added a commit that referenced this pull request Oct 6, 2026
…not the truncated one (#9126)

(cherry picked from commit 0ef1877)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant