Skip to content

fix: Cypher OR index seeks, index order for more ORDER BY shapes, parallel filtered scan (#8723 #8724 #8725) - #8771

Merged
lvca merged 9 commits into
mainfrom
fix/8723-8724-8725-cypher-or-desc-parallel
Sep 30, 2026
Merged

lvca merged 9 commits into
mainfrom
fix/8723-8724-8725-cypher-or-desc-parallel

Conversation

@lvca

@lvca lvca commented Sep 30, 2026 •

Copy link
Copy Markdown
Member

Fixes #8723, #8724, #8725.

Tests: Issue8723/8724/8725 tests added; Issue5362 test updated (OR is now a seek). Ran 6098 opencypher + parallel scan tests, green.

Summary by CodeRabbit

  • New Features

    • Cypher queries with indexed OR conditions can use index seeks, including conditions across multiple properties, while avoiding duplicate results.
    • Eligible filtered label scans can run in parallel.
    • Queries can use index-ordered scans for whole-label ORDER BY requests, including supported null-handling cases.
  • Bug Fixes

    • Corrected index-ordered results when null values are included or excluded.
    • Improved query-plan output for IN values and index-seek details.

Behavior note (#8724): for a property declared MANDATORY and NOTNULL, ORDER BY ... LIMIT over the whole label now trusts the constraint and reads the index without the null-key fallback scan, as SQL already does (#8701). ALTER PROPERTY does not validate vertices written before the constraint, so a type that gained it over existing data must be repaired first.

…r in more cases, parallel filtered label scan

- #8723: an OR of equalities/IN on indexed properties is an IN-list seek (one property) or a de-duplicated union of seeks (several); EXPLAIN prints IN values
- #8724: ORDER BY ... LIMIT reads the index in both directions for MANDATORY+NOTNULL, WHERE x IS NOT NULL, and NULL_STRATEGY INDEX
- #8725: NodeByLabelScan evaluates a parallel-safe filter in the workers of the shared parallel type scan
@lvca lvca added this to the 26.10.1 milestone Sep 30, 2026
@lvca lvca self-assigned this Sep 30, 2026
@mergify

mergify Bot commented Sep 30, 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.

@coderabbitai

coderabbitai Bot commented Sep 30, 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: fb7cd9cf-4bc9-4d21-a9f9-dda6535a0737

📥 Commits

Reviewing files that changed from the base of the PR and between cb43e1e and 517f6fe.

📒 Files selected for processing (18)
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/InListValues.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeByLabelDisjunctionIndexSeek.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeByLabelScan.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeIndexRangeScan.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/NodeIndexUnionSeek.java
  • engine/src/main/java/com/arcadedb/query/opencypher/executor/operators/ParallelSafeExpressions.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/AnchorSelector.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/CypherOptimizer.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/plan/AnchorSelection.java
  • engine/src/main/java/com/arcadedb/query/opencypher/optimizer/rules/IndexSelectionRule.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/MappedScanStep.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/ParallelRecordScan.java
  • engine/src/main/java/com/arcadedb/query/sql/executor/ParallelTypeScan.java
  • engine/src/test/java/com/arcadedb/query/opencypher/Issue5362DuplicatePredicateIndexSeekTest.java
  • engine/src/test/java/com/arcadedb/query/opencypher/Issue8723CypherOrIndexSeekTest.java
  • engine/src/test/java/com/arcadedb/query/opencypher/Issue8724CypherIndexOrderWholeLabelTest.java
  • engine/src/test/java/com/arcadedb/query/opencypher/Issue8725CypherParallelFilteredScanTest.java
  • engine/src/test/java/com/arcadedb/query/opencypher/ParallelSafeExpressionsStateTest.java
 ___________________________________________________________________
< Your PR title says 'refactor'. My diff viewer says 'crime scene'. >
 -------------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ
✨ 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

Autopilot is currently an internal CodeRabbit preview.


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.

@codacy-production

codacy-production Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 178 complexity

Metric Results
Complexity 178

View in Codacy

🟢 Coverage 91.89% diff coverage · -5.96% coverage variation

Metric Results
Coverage variation ✅ -5.96% coverage variation
Diff coverage ✅ 91.89% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (cb43e1e) 201419 169885 84.34%
Head commit (015fce6) 234324 (+32905) 183663 (+13778) 78.38% (-5.96%)

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 (#8771) 370 340 91.89%

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 Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, index order for more ORDER BY shapes, parallel filtered scan)

Overall this is a well-scoped change. The safety model is sound: seeks only need to return a superset because the WHERE is still evaluated above the anchor, the parallel predicate is whitelist-based and falls back on any unknown node, and the tests cross-check parallel against sequential runs. Nothing here blocks the merge, but the points below are worth addressing.

Potential bugs / correctness

  1. MappedScanStep can log the skipped-record warning repeatedly (fetchNextItem). ScanWithFilterStep guards this with a warnedAboutSkippedRecords flag (one-time warning). Here, every hasNext() call after the iterator is exhausted re-enters fetchNextItem(), falls through the while, and logs warnSkipped again. For a corrupted bucket this can spam the log. Add the same one-time flag.

  2. The filter AST is shared across workers, contrary to the ParallelTypeScan contract. stepFor documents "with its own copy of the filter, so no two workers share an AST", but MappedScanStep.copy() passes the same RowMapper (hence the same filter instance) to every worker. I checked the whitelisted nodes and they look safe: the only mutable state I found is ComparisonExpression.temporalCoercionMemo / zoneAdoptionMemo, which are volatile and hold immutable snapshot arrays. So this is not a bug today, but thread-safety of every whitelisted node becomes a silent invariant, and any future memo or cache added to one of those classes turns into a data race that only shows up under parallel scan. Please either (a) document this next to ParallelSafeExpressions, or (b) add a test that compares a temporal/parameter predicate (the memo path) in parallel vs sequential on a multi-bucket type. The RowMapper Javadoc says it "must not keep state", but does not cover the shared AST it closes over.

Design / performance

  1. Union seek has no cost check against the scan. tryUnionIndexSeek is used whenever every property has an index, with a fixed 0.1 selectivity for non-unique indexes. A union of non-selective seeks (low-cardinality property, large IN lists) does random record loads for a large fraction of the label and can be slower than the scan that openCypher: a filtered label scan runs on one thread while the same SQL scan runs in parallel since #8523 (298-347 ms against 38-44 ms on 12 cores at 1M vertices; within 1.25x on one core) #8725 now makes cheaper. The existing IN-list path has the same property, so this is not a regression, but since the two features interact it may be worth comparing totalCost with the scan cost before returning the union, or capping it when estimatedRows approaches typeCount.

  2. MappedScanStep duplicates much of ScanWithFilterStep (iterator setup, page range, WorkGuard, batch loop, skipped-record warning, copy). Consider extracting the shared part so the two cannot drift apart (point 1 is an example of drift).

Style / CLAUDE.md conformance

  • Issue8723CypherOrIndexSeekTest uses the fully qualified java.util.function.IntPredicate in expectedIds; please import it.
  • CypherOptimizer: IsNullExpression is imported before Expression, breaking the alphabetical order of the import block.
  • The new code carries long multi-line Javadoc/comment blocks (for example on NullKeys, servedInParallel, ParallelRecordScan). Much of it explains the why, which is useful, but some restates the code or references issue numbers; trimming would match the repo guidance of defaulting to no comments.

Tests

Coverage is good: OR on one property, parameters, two properties, both-disjunct dedup, IN plus AND disjunct, non-indexed disjunct keeping the scan, = null, OR on another variable, null placement in all NullKeys modes with SKIP windows, and parallel vs sequential equivalence with LIMIT/SKIP/aggregates/parameters/transactions. Suggestions:

  • Add x = 3 OR x = 3 (duplicate values on one property) to pin that the IN seek de-duplicates (I verified NodeIndexSeek does via seen, but no test covers it here).
  • Add a parallel scan test over a type with a subtype (polymorphic buckets).
  • Issue8725CypherParallelFilteredScanTest builds 2 x 20,000 vertices; probably fine, but tag it @Tag("slow") if it shows up as slow in CI.
  • Add a DESC test for the SKIPPED_IN_INDEX mode, since the IS NOT NULL path now drops the filter entirely in favour of the index.

Once points 1 and 2 are addressed I would be comfortable merging.

@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped change. Reusing NodeByLabelDisjunctionIndexSeek for the union, keeping the WHERE evaluated above the seek (so the seek only has to find a superset), and routing the Cypher parallel filter through the shared ParallelTypeScan (no new pool) all fit the existing design and the engine-concurrency rule. Points below are non-blocking.

Correctness / risk

  1. Stale Javadoc on CypherOptimizer.orderByIndex: it still describes the whole-label case as "no predicate at all ... ascending". It now also covers descending, IS NOT NULL, mandatory+notnull and NULL_STRATEGY INDEX. Please update it.
  2. Possible NPE in orderByIndex: type.getPolymorphicPropertyIfExists(property) is dereferenced (schemaProperty.isMandatory()) with no null check. Probably unreachable when an index exists on the property, but a guard is cheap.
  3. Value coercion in the OR seek: the union is only safe if each seek returns a superset of what its disjunct keeps; a seek that returns fewer rows than Cypher equality would drop rows the WHERE above cannot bring back (e.g. n.x = $p OR n.s = $q with $p = 1.0 against an INTEGER index, or a LONG param on an INTEGER index). Same exposure as the existing equality/IN anchors, so it may already be handled in NodeIndexSeek, but please add a numeric-type-mismatch parameter test to Issue8723CypherOrIndexSeekTest (only a null param is covered today).
  4. Dropped statement.getWhereClause() / matchClause.hasWhereClause() guards in orderByIndex: I traced LogicalPlan (~lines 323 and 332) and both end up in getWhereFilters(), so onlyExcludesNullKeys plus the whereFilter != null check cover them. It relies on that invariant, so a test with the WHERE on a second MATCH and one with OPTIONAL MATCH would pin it.
  5. Shared AST in workers: ParallelSafeExpressions is a good allow-list (default false). I checked StringMatchExpression, ComparisonExpression, ArithmeticExpression, PropertyAccessExpression and InExpression and found no mutable caches, so sharing one filter across workers looks safe. Since the allow-list is a blanket safety claim, a test running =~ / STARTS WITH / CONTAINS in parallel, and one where a worker throws (type error in a comparison; check propagation and worker shutdown) would guard against a cache being added later. Only the negative case (function call stays sequential) is tested now.
  6. MappedScanStep.fetchNextItem only warns about skipped records once the iterator is exhausted; fine if that mirrors ScanWithFilterStep.

Code quality / style

  • NodeIndexUnionSeek extending NodeByLabelDisjunctionIndexSeek to override a name and a label is reasonable reuse; the seekUnit() hook is slightly awkward but fine.
  • MappedScanStep overlaps heavily with ScanWithFilterStep; unifying later would reduce drift.
  • ParallelRecordScan.plan: please confirm ParallelTypeScan.plan handles an empty step list (all buckets filtered by bucketId > 0).
  • InListValues.toString() now calls getText() per element; fine for EXPLAIN, just make sure it is not on a hot path (logging, plan cache keys).
  • Import order in CypherOptimizer: IsNullExpression sits before Expression.
  • b -> b.getFileId() in ParallelRecordScan.plan could be a method reference.

Performance

  • Parallel filtering only kicks in when the filter is parallel-safe, the scan is not partition-pruned and ParallelTypeScan.plan accepts it, so small types and transactions keep the old path. Good.
  • Union seek de-dups with a per-execution RID set: memory proportional to result size, same as the label disjunction. Acceptable.
  • The non-unique union estimate uses a flat 0.1 selectivity per seek, which can overestimate and may steer the planner to a scan on some types. Not a correctness issue; worth a follow-up if regressions appear.

Tests

Good coverage of the main shapes (same property, two properties, dedup when both disjuncts match, AND inside OR, non-indexed disjunct, null param, other variable, EXPLAIN text, the NullKeys modes, transaction fallback). Suggested additions: items 3, 4 and 5 above, plus a descending NULL_STRATEGY INDEX test spanning more rows than one fetch batch to exercise the readNullKeyEntries resume path when the buffer fills. Also confirm the large-type parallel-scan tests are small enough for CI or tagged @Tag("slow").

No security concerns: no new dependencies and no new parameter handling beyond the existing IN-seek.

🤖 Generated with Claude Code

… tests (numeric param types, second MATCH, null-key batches, string predicates, worker failure)
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, ORDER BY index order, parallel filtered scan)

Overall this is a well-structured change. The WHERE is still evaluated above the new seeks, so the union is always a superset and correctness does not depend on the seek being exact. I found no blocking issues. Tests are thorough: each parallel answer is compared against the sequential run (rows and order), and the OR cases cover de-duplication, AND disjuncts, non-indexed disjuncts falling back to a scan, null disjuncts and other-variable ORs. I did not run the suite myself; this is from reading the diff.

Things worth a second look

  1. Ascending walk over leading null keys can be O(#nulls) before the first row (NodeIndexRangeScan.fetchMore, SKIPPED_IN_INDEX / PLACED_FROM_INDEX). With NULL_STRATEGY INDEX and a sparse property, WHERE n.p IS NOT NULL ... ORDER BY n.p LIMIT 10 reads and discards every null entry at the head of the index before returning anything, which defeats the point of LIMIT. If the index cursor can be positioned past the null key (a seek to the first non-null key), that would keep it O(limit). If not, it is worth a comment, and ideally a test with a mostly-null column documenting the cost.

  2. everyVertexHasAKey trusts MANDATORY + NOTNULL (CypherOptimizer.orderByIndex). ALTER PROPERTY ... MANDATORY true on a type that already holds vertices lacking the property does not (as far as I know) rewrite or validate them. Those vertices are not in the index, so with NullKeys.NONE they would be silently dropped from the ordered scan, whereas the old path never produced this shape. You reference Regression: the new NOTNULL fast path for an index-ordered ORDER BY drops every record that simply does not have the property, because NOTNULL does not make a property mandatory #8701 for the same concern, so I assume this was considered; a short note on why it is acceptable (or a check) would help.

  3. Removed guards in orderByIndex. The old code rejected statement.getWhereClause() != null and matchClause.hasWhereClause() explicitly; the new code relies on labelScan == rootOperator plus logicalPlan.getWhereFilters(). I believe that is sufficient (any other filter would sit above the scan, so the root would not be the label scan), and otherPredicatesKeepTheSort covers a basic case. Please add a case with the IS NOT NULL in a second MATCH's WHERE or after a WITH, to pin that excludesNulls cannot be computed from a WHERE that does not apply to the scan.

  4. Thread-safety of the shared predicate in ParallelSafeExpressions. Workers share one AST instance, unlike SQL which copies per worker. From a quick scan the only mutable state among the whitelisted nodes is ComparisonExpression's two volatile memos, which matches the Javadoc. That is an invariant that silently rots when someone adds a cache to InExpression, StringMatchExpression or ArithmeticExpression. A test that reflects over the whitelisted classes and fails on a non-final, non-volatile instance field would make the Javadoc warning enforceable.

  5. Union cost model. In tryUnionIndexSeek, values.size() is used for the cost of a branch, but a single IN $ids parameter counts as 1 while it may resolve to thousands of keys. The 0.1 selectivity for non-unique indexes is a heuristic. The totalCost >= scan cost guard limits the damage, but a huge parameter list can still be costed as a cheap seek. This is the same limitation the existing IN-list path has, so fine to leave, but worth noting.

Minor / style

  • ParallelRecordScan.plan: mapToInt(b -> b.getFileId()) can be Bucket::getFileId; bucketId > 0 silently drops bucket 0, so if that mirrors the SQL planner a one-line comment would explain it.
  • ParallelRecordScan.getWorkerCount() appears to be used only for tests; if so, consider keeping it package-private or confirming it is needed publicly.
  • AnchorSelection's Javadoc uses a fully qualified {@link com.arcadedb...InListValues}; an import would match the CLAUDE.md convention, though it is only Javadoc.
  • NodeByLabelScan: the ThreadLocal<Boolean> servedInParallel follows the existing servedByScan pattern, which is consistent. The comment is long for the repo's "one short line" guideline; consider trimming.
  • MappedScanStep duplicates much of ScanWithFilterStep (deadline guard, skipped-record warning). Acceptable given the different row shape, but a shared helper would reduce drift.

Performance / security

No security concerns: no new inputs are parsed, and the seek values are the same literal/parameter expressions the IN path already resolves. Performance looks positive overall (index seeks instead of scans, filter evaluated in workers, only survivors reach the consumer). The one regression risk is item 1.

Nice work, especially on keeping the WHERE above the anchor and on the sequential-equivalence tests.

…, state-safety test for parallel-safe expressions, more tests, cleanups
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, index order for more ORDER BY shapes, parallel filtered scan)

Overall this is a well-structured change. Reuse is good (NodeIndexUnionSeek extends the existing disjunction seek, ParallelRecordScan reuses ParallelTypeScan), the WHERE is still re-evaluated above the seek so a superset from the seek is safe, and the parallel-safety whitelist defaults to false for unknown nodes. The three test classes cover the main edge cases (dedupe by RID, null disjunct, numeric type mismatch, non-indexed disjunct falls back, worker failure, transaction stays sequential). Notes below, roughly by importance.

Potential issues

  1. 8724: everyVertexHasAKey trusts the schema constraint (CypherOptimizer.orderByIndex). MANDATORY+NOTNULL is enforced on write only. If the constraint is added after data already exists, vertices without the key can exist but are not in the index, and the new plan (NullKeys.NONE) silently drops them from ORDER BY ... LIMIT results where the old plan sorted the whole label and returned them. Please confirm ArcadeDB validates existing records when the constraint is created, or add a test for "constraint added after data". The Regression: the new NOTNULL fast path for an index-ordered ORDER BY drops every record that simply does not have the property, because NOTNULL does not make a property mandatory #8701 comment suggests this was considered; a regression test would pin it.

  2. 8724: skipping null keys is linear in the number of nulls (NodeIndexRangeScan.fetchMore). For SKIPPED_IN_INDEX and PLACED_FROM_INDEX ascending, leading null entries are read one by one with continue before the first real row. With a NULL_STRATEGY INDEX index where most rows are null, WHERE n.p IS NOT NULL RETURN n ORDER BY n.p LIMIT 10 reads every null entry first. No record is loaded for them so it is much cheaper than a label scan, but it is still O(nulls). A range seek past the null key, if the index supports one, would fix it; otherwise a javadoc note. In PLACED_FROM_INDEX ascending the null entries are also read twice in total (skipped first, then read again by readNullKeyEntries); correct, just noting it.

  3. 8724: isNullKey assumes a single-property index (keys[0] == null). getPolymorphicIndexByProperties(property) looks the index up by one property name; please verify it cannot return a composite index whose first key is property, or assert index.getPropertyNames().size() == 1 before taking this path. Otherwise a composite index with a null first key but non-null later keys would be mis-ordered.

  4. 8725: no deadline check on the consumer side of the parallel path. In NodeByLabelScan.fetchMore the parallel branch loops parallelRows.hasNext()/next() without guard.check(). The workers use WorkGuard.forCommandDeadline in MappedScanStep, so a timeout should still surface, but a test asserting the command timeout on a parallel filtered scan that rejects every row would be worthwhile, given arcadedb.command.timeout is described as the timeout for commands but is honoured by only two code paths #6266 is the motivation for the guard.

  5. 8725: shared predicate instance across workers. The design depends on every whitelisted AST node being free of unsynchronized mutable state (the class javadoc says so, good). I checked the whitelisted nodes: only ComparisonExpression has mutable fields (two volatile Object[] memos), which fits the stated rule. The risk is a future regression, for example someone adding a lazily compiled regex cache to StringMatchExpression. A small reflection test that fails when a whitelisted class gains a non-final, non-volatile instance field would protect this cheaply, since races are nondeterministic and stringAndRegexPredicatesRunInParallelAndAgree would not reliably catch them.

Minor / style

  • NodeByLabelScan.servedInParallel is a per-operator ThreadLocal that is never removed. It is documented and matches servedByScan in NodeIndexRangeScan, so fine; just be aware it accumulates on long-lived pool threads if plans churn.
  • AnchorSelector.tryUnionIndexSeek: the 0.1 selectivity for non-unique indexes is a magic number; reuse an existing cost-model constant if there is one.
  • collectSeekDisjuncts for an AND inside an OR takes the first seekable conjunct only. That is correct (superset), but if the left conjunct is unselective and the right one is unique, the seek uses the worse one. Acceptable now; maybe a follow-up.
  • If there are no remaining callers of setIndexOrder(boolean, boolean), remove it rather than keeping both overloads.
  • Tests: if Issue8725CypherParallelFilteredScanTest builds a dataset large enough to take noticeable time to cross the parallel threshold, add @Tag("slow") per CLAUDE.md. No test exercises the union seek on a polymorphic type (subtype vertices) or on a multi-label (n:A:B) composite type, both of which go through Labels.getCompositeTypeName in IndexSelectionRule.

Security / performance

No security concerns: no new external input handling, parameters are only used as seek keys. Performance looks positive overall: the OR seek replaces full scans, dedupe is a RID set bounded by the cost check against scan cost, and the parallel scan is gated by the same rules as the SQL one.

Nothing here is clearly blocking; items 1 and 3 are the ones I would like confirmed before merge.

…e deadline check, remove unused overload, subtype test, document constraint trust
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, ORDER BY index order, parallel filtered scan)

I read the diff and did not run the suite. Several earlier review comments exist on this PR, so I list only what is new.

The design is sound:

  • The WHERE stays above the anchor, so every seek only has to return a superset.
  • The IN-list seek already de-duplicates by RID (NodeIndexSeek seen set), so x = 1 OR x = 1 is safe.
  • NodeIndexUnionSeek reuses the existing disjunction seek.
  • ParallelSafeExpressions defaults to false for unknown nodes.
  • I checked StringMatchExpression and ParameterExpression: neither holds mutable state.

New observations

  1. NodeByLabelScan.close() followed by more reads restarts the scan. close() sets parallelRows = null, but iterator is still null and finished may be false. The init guard iterator == null && parallelRows == null is then true again, so a late hasNext() would re-plan a fresh parallel scan and emit duplicates. A closed flag avoids this. It is unlikely in practice but cheap to rule out.

  2. extractOrSeekBranches stops at the first OR conjunct. For WHERE (n.a = 1 OR n.u = 2) AND (n.x = 3 OR n.s = 1), where only the second OR is fully indexed, the first OR is returned. tryUnionIndexSeek then finds that u has no index and returns null, so the query scans even though a valid union exists. Collecting all qualifying OR conjuncts and picking the cheapest would fix it. This is a missed optimization, not a correctness bug.

  3. The single-property OR case bypasses the union path cost guard. With orBranches.size() == 1, the branch goes into inListPredicates and takes the existing IN-seek path, while tryUnionIndexSeek compares totalCost against estimateScanCost. x = 1 OR x = 2 OR ... OR x = 5000 becomes 5000 seeks plus a RID set. IN already behaves this way, so it is not new, but consider applying the same scan-cost comparison if the IN path has no cap.

  4. isNullKey assumes a single-key index. It checks keys[0] == null, and getPolymorphicIndexByProperties(property) looks up by one property name. A cheap guard is index.getPropertyNames().size() == 1 before choosing SKIPPED_IN_INDEX or PLACED_FROM_INDEX.

  5. iterator(true, new Object[] { null }, false) relies on the LSM cursor treating a null key element as the lowest exclusive bound. The continue on isNullKey makes it safe either way. A short comment saying the bound is an optimization, not the correctness mechanism, would help the next reader.

  6. Parallelism inside transactions. ParallelRecordScan.plan stays sequential in a transaction. CLAUDE.md notes that DatabaseAbstractHandler wraps HTTP commands in transactions, so openCypher: a filtered label scan runs on one thread while the same SQL scan runs in parallel since #8523 (298-347 ms against 38-44 ms on 12 cores at 1M vertices; within 1.25x on one core) #8725 may help embedded and non-transactional callers much more than HTTP ones. That matches SQL, but it is worth stating in the PR description.

Style (CLAUDE.md)

  • Several new comments are multi-line blocks (the servedInParallel Javadoc, the NullKeys enum). The repo guideline is one short line, only for a non-obvious WHY.
  • AnchorSelection has an awkward Javadoc line wrap around InListValues. Reflow it.
  • If the 8725 dataset is large enough to be slow, add @Tag("slow").

Test gaps

  • Close-then-read on the parallel NodeByLabelScan (item 1).
  • An OR-under-AND with two OR conjuncts where only the second is indexed (item 2).
  • A union seek on a polymorphic type or a multi-label (n:A:B) node.
  • A command timeout firing on a parallel filtered scan whose predicate rejects every row.

No security concerns. Performance is positive overall. Nothing here blocks the merge, and item 1 is the one I would fix before merging.

🤖 Generated with Claude Code

@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, index order for ORDER BY LIMIT, parallel filtered label scan)

I read the full diff and traced the riskier paths. I did not build the branch or run the tests. Overall this is solid work: the correctness strategy is sound (seeks only produce a superset and the WHERE is still evaluated above the anchor), the parallel whitelist is conservative (an unknown node keeps the scan sequential), and the tests cover the tricky edges. Nothing here looks like a blocker. Notes below, roughly by importance.

Correctness and risk

  1. orderByIndex dropped its explicit WHERE guards (CypherOptimizer.java, whole-label branch). The old code rejected the shortcut when statement.getWhereClause() != null or any matchClause.hasWhereClause(). The new code relies on logicalPlan.getWhereFilters() (via onlyExcludesNullKeys) plus NodeByLabelScan.getWhereFilter() == null. That is correct only if every WHERE source ends up either in getWhereFilters() or as an operator above the scan (so labelScan != rootOperator). anIsNotNullOnASecondMatchStillAnswersCorrectly covers one form. Please add regression cases for a WHERE in the other positions (e.g. OPTIONAL MATCH ... WHERE) so this invariant is pinned by a test and not just by reading the planner.
  2. Replacing the scan drops the IS NOT NULL filter in the excludesNulls case. That is right for a default-strategy index (no null key) and for SKIPPED_IN_INDEX, but it makes the index the only enforcer of the predicate. A short comment or test on properties that are missing versus explicitly null would help.
  3. everyVertexHasAKey trusts MANDATORY+NOTNULL. The comment already notes that ALTER PROPERTY does not validate pre-existing rows. The consequence is that a type that gained the constraint over old data silently loses rows from ORDER BY ... LIMIT (they are absent from the index), where the previous plan was correct. Consistent with the SQL side and acceptable, but worth calling out in the PR description as a behavior change.
  4. Exclusive null lower bound rangeIndex.iterator(true, new Object[] { null }, false) (NodeIndexRangeScan.openCursor) depends on how the LSM comparator orders a null key against real keys. The NULL_STRATEGY INDEX test exercises it for the shape it builds; a case with mixed values (nulls plus empty strings / zero) would make the dependency explicit.
  5. tryUnionIndexSeek cost model: the 0.1 non-unique selectivity is a magic number that duplicates the estimate used elsewhere in AnchorSelector. It only chooses between union and scan, so it is not critical, but a named constant or reuse of the existing estimator would avoid drift. The totalCost >= estimateScanCost guard is good.
  6. Union de-duplication memory: the RID de-dup set in NodeByLabelDisjunctionIndexSeek grows with the result, so a union returning a large share of the label holds all its RIDs. The cost guard mitigates this.

Parallel scan (#8725)

  • The shared-AST model is the delicate part: SQL gives each worker its own AST copy, while here all workers share one predicate instance. ParallelSafeExpressionsStateTest and the Javadoc warning are the right guards; please keep them in sync whenever a whitelisted node gains a cache or memo.
  • servedInParallel is a per-operator ThreadLocal that is never cleared. It mirrors the existing servedByScan pattern and the comment explains the lifetime, so I am fine with it (one Boolean per pool thread per cached plan until the plan is evicted).
  • MappedScanStep duplicates a fair amount of ScanWithFilterStep. Acceptable given the different row shape, but the two can drift (WorkGuard, skipped-record handling).
  • The transaction check in ParallelTypeScan.plan keeps a read after a write in the same tx sequential, which is the conservative choice, and inATransactionTheScanStaysOnTheCallingThread covers it.

Style and conventions (CLAUDE.md)

  • The code follows the project style well (final params, braceless single-statement ifs, imports rather than FQNs, no System.out, assertThat(...) syntax in tests).
  • Several comments are multi-line blocks (e.g. NodeByLabelScan.servedInParallel, the NullKeys enum constants, ParallelSafeExpressions). The project guidance is one short line. Much of it is WHY-level and worth keeping, but a few (the enum constants) restate what the names already say.
  • The new InListValues.toString() is a nice fix: EXPLAIN previously printed object identities.

Tests

Good breadth: dedupe when both disjuncts match, null disjunct, numeric type mismatch, OR on another variable, nullable descending fallback, null keys spanning several fetch batches, worker failure leaving the DB usable, function predicate staying sequential. Gaps I would add:

  • NULL_STRATEGY INDEX combined with IS NOT NULL in descending order (SKIPPED_IN_INDEX descending, which stops at the trailing null keys).
  • An OR mixing an IN $list disjunct (list-valued parameter) with a scalar-parameter equality, to exercise the InListValues flattening in the union path.
  • Please confirm the Issue8725 data sizes keep it fast; if not it needs @Tag("slow").

Nice work; the items above are mostly hardening and extra tests.

…, not the list; more tests (null keys vs zero/negative values, list+scalar parameters)
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of #8771 (Cypher OR index seeks, ORDER BY index order for whole-label scans, parallel filtered label scan)

I read the diff and the surrounding code and did not build or run the tests. Seven earlier review comments exist on this PR, so this one only covers what they did not, or where I can add information. I found no blocker. The core strategy holds: the WHERE stays above the anchor, so a seek only has to return a superset.

New findings

  1. Equality disjuncts are always seeked in IN-list form, which flattens collection parameters (AnchorSelector.tryUnionIndexSeek and the single-property inListPredicates.putIfAbsent path; NodeIndexSeek lines ~195-207). Under InListValues, NodeIndexSeek expands a Collection or array parameter into one key per element. For WHERE n.tags = $p OR n.s = "a" with $p = [1,2], Cypher equality compares the whole list, while the seek looks up keys 1 and 2. On an index whose key is the whole list value, the seek then returns fewer rows than the disjunct keeps, and the WHERE above cannot bring them back. That is a wrong-result risk, not a superset. The existing plain-equality anchor is not exposed because it adds a single key. It needs a list-typed indexed property, so it is narrow. A cheap fix is to skip the union (or the single-property merge) when an = disjunct uses a parameter, or to keep = separate from real IN disjuncts. A test with a list-valued parameter on an = disjunct would pin whichever behavior you choose.

  2. NodeByLabelScan can restart after close() (fetchMore). close() nulls parallelRows, but iterator is also null and finished may be false, so iterator == null && parallelRows == null holds again. A hasNext() or next() after close would re-plan the parallel scan and could re-emit rows. A closed flag, or keeping parallelRows non-null and only closing it, rules that out.

  3. Null-key skipping may already be bounded by the cursor, which would contradict the O(#nulls) concern raised earlier. openCursor now opens rangeIndex.iterator(true, new Object[]{null}, false) for SKIPPED_IN_INDEX and PLACED_FROM_INDEX. If the LSM comparator orders a null key lowest, that exclusive bound already starts past the nulls and the continue in fetchMore is only a safety net. If it does not behave that way, the continue silently becomes the linear walk. Either way, a test on a mostly-null column with LIMIT 10 that shows the null entries are not walked, plus a one-line comment saying which of the two is the correctness mechanism, would help.

  4. Union path coverage for composite, polymorphic and multi-label anchors. createAnchorOperator uses Labels.getCompositeTypeName(labels) for the union seeks, and findIndexForProperty returns an index whose first column is the property, so a union on a composite index seeks a key prefix (keyValues = List.of(value)). Please add one test with a composite index and one with a subtype vertex to pin that.

Minor

  • MappedScanStep duplicates logic from ScanWithFilterStep (skipped-record warning, WorkGuard, batch loop). Other reviews already noted the repeated skipped-record warning after exhaustion in MappedScanStep.fetchNextItem; worth fixing together with the duplication.
  • CLAUDE.md: the new Javadoc blocks (servedInParallel, NullKeys, ParallelSafeExpressions) are multi-line, while the guideline is one short line. CypherOptimizer imports IsNullExpression before Expression. Issue8723CypherOrIndexSeekTest uses a fully qualified IntPredicate.
  • everyVertexHasAKey trusts MANDATORY+NOTNULL on existing data, as its comment says. It changes results for a type that gained the constraint over old rows, so it deserves a line in the PR description.
  • Tag Issue8725CypherParallelFilteredScanTest with @Tag("slow") if the 2 x 20,000 vertex build shows up as slow in CI.

Verdict

Sound design and good coverage of the main shapes. I would address items 1 (possible wrong result) and 2 before merging; the rest is hardening.

🤖 Generated with Claude Code

… not split into keys; scan cannot restart after close; union tests for composite and sub types
@claude

claude Bot commented Sep 30, 2026

Copy link
Copy Markdown

Review of PR 8771 (Cypher OR index seeks, index order for more ORDER BY shapes, parallel filtered scan)

I read the main-source diff and the test names. I did not run the tests here. Overall this is a well-reasoned change. The safety argument (the seek yields a superset, the full WHERE is re-evaluated above the anchor) is sound, and the test coverage is broad. Nothing below blocks the merge. These are notes and questions.

What looks good

  • 8723: OR conjuncts nested under AND, disjuncts merged per property, x = $p versus x IN $p semantics handled (the identity scalar set), and an AND disjunct accepted on one seekable conjunct. The tests cover null disjuncts, a collection parameter under equality, numeric type coercion, sub-types with composite indexes, and OPTIONAL MATCH.
  • 8724: the NullKeys enum replaces a boolean and makes the four cases explicit. Reading the null-key entries in a separate pass, with buffer-resumable state, is handled carefully. There is a test for null keys spanning more than one fetch batch.
  • 8725: ParallelSafeExpressions is an allow-list that defaults to sequential for unknown nodes, which is the right default. I checked the listed AST nodes: their fields are final, apart from the volatile immutable memos in ComparisonExpression. Reusing ParallelTypeScan keeps the row order and the pool rules shared with SQL. close() stops the workers.

Points worth a look

  1. Silent wrong results when the constraint is stale (8724). everyVertexHasAKey = isMandatory() && isNotNull() makes the scan drop the label-scan fallback for null keys. The comment admits that ALTER PROPERTY does not validate existing vertices. A vertex written before the constraint and lacking the property would then silently vanish from ORDER BY ... LIMIT results, where it used to be returned. The comment says SQL makes the same assumption, so this is a defensible tradeoff. It may be worth a note in the docs or the PR description, since it is a behaviour change on existing data.
  2. Inconsistent cost gating (8723). tryUnionIndexSeek refuses the union when totalCost >= estimateScanCost, but trySingleOrSeek has no such guard. A single-property OR with many values on a non-unique index can therefore pick the seek even where a scan would be cheaper. This probably matches the existing IN-list path, but a one-line guard or a comment would make the intent clear.
  3. Identity-keyed scalar set (InListValues/SeekValues). This relies on the very Expression instances staying in InListValues.values. It works now because toInList() passes the same list and set. If a later change copies or rewrites expressions (parameter binding, plan cloning), isScalar silently returns false and a collection parameter under = would be split into keys again. The regression test aCollectionParameterOfAnEqualityIsComparedWholeNotSplitIntoKeys would catch that, so this is fine as long as that test stays.
  4. Duplication. MappedScanStep mirrors much of ScanWithFilterStep (page-range iteration, guard, skipped-record warning), and ParallelRecordScan.warnSkipped repeats the warning text. A shared helper would avoid drift, though keeping the SQL path untouched may be a deliberate choice.
  5. Union seek memory. NodeByLabelDisjunctionIndexSeek de-duplicates by RID with a set that grows with the result size. Acceptable for seeks, and the scan-cost cap bounds it somewhat. Just noting it, given the GC-lightness goal.
  6. Minor: extractOrSeekBranches runs for every anchor evaluation even when an AND-conjunct index seek is already chosen earlier in evaluateNode. It is plan-time only and cheap, but it could be computed lazily after the earlier returns.

Tests and conventions

  • The tests cover the new behaviour and the edge cases well. The worker-failure test and the in-transaction test are good.
  • Please confirm that Issue8725CypherParallelFilteredScanTest and the larger Issue8724 cases are either fast or tagged @Tag("slow"), and that none of them assert on raw wall-clock time (per CLAUDE.md).
  • Style follows the existing conventions (final, no braces on single statements, imports rather than fully qualified names). No new dependencies.

Nothing here looks like a correctness bug to me. Point 1 is the one I would want a conscious decision on before merge.

🤖 Generated with Claude Code

@lvca
lvca merged commit 8a3cec6 into main Sep 30, 2026
15 checks passed
@lvca
lvca deleted the fix/8723-8724-8725-cypher-or-desc-parallel branch September 30, 2026 20:03
tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Sep 30, 2026
…1; analytical reads outside a transaction (#32) (#33)

ArcadeData#8771 fixed ArcadeData#8723, ArcadeData#8724, and ArcadeData#8725. The ordered-reads
paragraph now says openCypher reads the index in order in both directions
for a MANDATORY + NOTNULL property, under IS NOT NULL, and for a
NULL_STRATEGY INDEX index (declare the constraints before loading); a
Disjunctions paragraph covers OR over indexed properties; and a paragraph
says filtered scans run in parallel only outside a transaction (43-57 ms
against 255-291 ms inside one, both languages, 1M records).


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

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@codecov

codecov Bot commented Sep 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.81081% with 71 lines in your changes missing coverage. Please review.
✅ Project coverage is 76.09%. Comparing base (15e23e0) to head (015fce6).
⚠️ Report is 45 commits behind head on main.

Files with missing lines Patch % Lines
...edb/query/opencypher/optimizer/AnchorSelector.java 79.33% 11 Missing and 14 partials ⚠️
...er/executor/operators/ParallelSafeExpressions.java 45.83% 7 Missing and 6 partials ⚠️
...db/query/opencypher/optimizer/CypherOptimizer.java 66.66% 2 Missing and 10 partials ⚠️
...om/arcadedb/query/sql/executor/MappedScanStep.java 79.54% 5 Missing and 4 partials ⚠️
...ncypher/executor/operators/NodeIndexRangeScan.java 90.56% 1 Missing and 4 partials ⚠️
...rcadedb/query/sql/executor/ParallelRecordScan.java 73.33% 3 Missing and 1 partial ⚠️
...ery/opencypher/optimizer/plan/AnchorSelection.java 86.66% 1 Missing and 1 partial ⚠️
.../arcadedb/query/sql/executor/ParallelTypeScan.java 75.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8771      +/-   ##
============================================
+ Coverage     76.06%   76.09%   +0.02%     
- Complexity     3701     3702       +1     
============================================
  Files          2075     2079       +4     
  Lines        201314   201747     +433     
  Branches      42410    42542     +132     
============================================
+ Hits         153131   153514     +383     
- Misses        31573    31589      +16     
- Partials      16610    16644      +34     

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

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