Skip to content

fix(query): the ?var = <const> memo is keyed by the constant, not its address - #2419

Merged
aaj3f merged 2 commits into
mainfrom
fix/filter-const-sid-key-alias
Nov 19, 2026
Merged

aaj3f merged 2 commits into
mainfrom
fix/filter-const-sid-key-alias

Conversation

@aaj3f

@aaj3f aaj3f commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2385.

On an indexed ledger, a FILTER(?x = <iri>) in a later UNION branch could compare against an earlier branch's IRI, so the branch dropped the rows it should keep and kept the ones it should drop, with no error. The cause is the one the issue proposes: the ?var = <const> fast path in eval/compare.rs memoized the constant operand's subject id under ConstSidKey::ExprPtr, the operand's address, for the whole query. That's only safe while the expression outlives the memo, and a correlated UNION (UnionOperator::next_batch, via build_where_operators_seeded) builds each branch's operator tree per input row and drops it before building the next, with each FILTER owning its own expr.clone(). A later branch's copy that lands at an earlier one's address reads back that branch's s_id. MINUS does the same per row (the issue's "wrong the other way" variant), and so does the FilterOperator for a compound FILTER with an EXISTS in it (resolve_exists_for_row rebuilds the expression per row). Novelty-only bindings never take this fast path (it needs a Binding::EncodedSid), which is why only indexed ledgers saw it.

What changes

The memo is keyed by the constant itself, never by where its expression lives (fluree-db-query/src/eval/compare.rs, fluree-db-query/src/context.rs):

  • const_operand_key reads the key straight off the operand, without evaluating it: IRI("…"), which is how both SPARQL and JSON-LD lower an IRI constant, by its string, and a SID constant (Const(Ref(sid)), which is what Cypher lowers to) by its SID. On a miss it evaluates and resolves exactly as before and stores the result under that key. So the per-row eval_to_comparable and IRI re-encode (canonical_split / namespace lookup) that ec52f38 hoisted out still don't run per row. I think this is also a bit better than the address key for the per-row subplans above, since every rebuilt tree's copy of the operand now hits the memo, where a fresh address always missed it.
  • Any other operand (say IRI(CONCAT(…))) is evaluated per row and takes the value-keyed memo a few lines further down, the same one that already handled what the address key didn't. That's the one place this costs something over main: those operands lose the hoist of their evaluation, though not the memoized dictionary lookup. I don't think they're common in an =/!= against an indexed subject, but worth knowing.
  • ConstSidKey is now a borrowed key into a small ConstSidMemo struct (what ConstSidCache wraps), so a lookup allocates nothing. That also drops the per-row Box<str> the value-keyed path used to build just to look up its key. IRI("…") strings are kept apart from evaluated IRIs, since an IRI("…") operand resolves to whatever it evaluates to (a SID when the snapshot knows the namespace), not always a lookup by full IRI.

The memo's scoping doesn't change: still one per ExecutionContext store, fresh across with_graph_ref, with the constant alone as its key.

I didn't go with a per-expression id assigned at plan time, or with a memo owned by the FILTER operator. The id would need a field on Expression that survives the per-row clones (including resolve_exists_for_row's rebuilds). An operator-owned memo dies with its operator, so nothing would have to reset it, but it would miss on every rebuilt subplan, which is exactly where this bug lived, and the IN and compound-filter paths have no prepared struct to hold one. Keying by value keeps the fix inside the memo, and it can't alias by construction.

Tests

  • it_issue_2385_filter_const_per_branch (in grp_query_sparql): the issue's query, its "middle branch that matches nothing" variant and its MINUS variant, over a novelty-only ledger and over a published index, five runs each. On main (beb851f30) on a Mac, all 15 indexed runs answer wrong, exactly as in the issue's table (3 ex:Widget for both UNIONs, 3 ex:box1 for the MINUS). On Linux, CI's platform, with the fix reverted the two UNION cases fail on 10 of the 15 indexed runs, in debug and release, while the MINUS case rarely reproduces there; it goes through the same memo key, so the UNION cases guard it too, and I've kept it as the witness for the platform where it does reproduce. With this PR all 30 runs are right on both.
  • const_operand_key_is_the_constant_not_its_address: an operand overwritten in place, so at the same address by construction, gets the new constant's key. To be clear about what this one proves: const_operand_key reads the expression's contents, and ConstSidKey has no identity variant left, so the type already guarantees it and the test only documents it. The integration test above is what goes red if the bug comes back.
  • const_operand_key_reads_iri_strings_and_sids_only and const_sid_memo_keeps_each_constant_apart.

Verification

On a Mac at a214369d2, only for the touched crates (CI runs the full gate):

  • cargo fmt -p fluree-db-query -p fluree-db-api -- --check and cargo clippy -p fluree-db-query -p fluree-db-api --all-targets -- -D warnings: clean.
  • cargo test -p fluree-db-query --lib: 1,806 passed (1 ignored).
  • cargo test -p fluree-db-api for grp_query_sparql (569 passed, 3 ignored), it_query_sparql_indexed (90), grp_query (566, 1 ignored) and it_query_cypher (252).

On a clean Linux box, with compare.rs and context.rs put back to beb851f30 and the new test kept, the test fails on 10 of 15 indexed runs (the two UNION shapes), in debug and release, under nextest and cargo test. At the PR head it passes.

On cost: a memo hit now hashes the IRI string with Fx and compares it, instead of hashing a usize. Measured in isolation (the same rustc-hash map behind a Mutex, release, on an M-series Mac), that's +2.3 ns per hit for a 23-byte IRI and +4.7 ns for an 84-byte one. Against that, the value-keyed lookup path no longer allocates a Box<str> per row. No benchmark in the repo covers this path (none has a ?var = <iri> filter).

🤖 Generated with Claude Code

… address

On an indexed ledger, a FILTER(?x = <iri>) in a later UNION branch could
compare against an earlier branch's IRI. The query-wide memo for the
constant operand's subject id was keyed by the operand expression's
address (ConstSidKey::ExprPtr), on the premise that the expression lives
as long as the query. A correlated UNION (and MINUS) builds each branch's
operator tree per input row and drops it before the next, each with its
own copy of the FILTER expression, so a later branch's copy could land
at an earlier one's address and read back its subject id. Novelty
bindings never take that fast path, so only indexed ledgers saw it.

The memo is now keyed by the constant itself, read straight off the
expression: an IRI("...") operand, which is how SPARQL and JSON-LD lower
an IRI constant, by its string, and a SID constant by its SID. That
still skips the per-row eval_to_comparable and IRI re-encode the
address key was there to save, and it now also hits across the rebuilt
trees, which an address never could. Any other operand is evaluated and
takes the value-keyed memo, as before. The memo is a small struct with
borrowed keys, so a lookup allocates nothing, which also takes a
per-row Box<str> off that value-keyed path.

The regression test runs the issue's UNION shapes (an empty middle
branch, a middle branch that matches nothing) and the MINUS variant over
novelty and over an index, five times each; on main every indexed run
answered wrong. Unit tests pin that the key follows the constant when an
operand is overwritten at the same address, and that each kind of
constant keeps its own entries.

Fixes #2385

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

@bplatz bplatz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approving. Please review the inline comments before merging.

Comment thread fluree-db-query/src/eval/compare.rs Outdated
@@ -263,19 +286,15 @@ fn fast_eq_iri_binding_directional<R: RowAccess>(
// dictionary reverse-lookup (`find_subject_id_by_parts`)
// per row — the dominant cost of this filter at scale.
let key = match &r {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: this lock → get → resolve → insert sequence is now written twice in this function (also at line 229), each with its own ComparableValue → Ref → subject_ref_to_s_id mapping. A helper on ConstSidMemo that takes the key and a resolver closure would keep the two in step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is fair, and I think the two copies had already started to drift a little: the value-keyed one cloned the Sid/IRI into a Ref on every row just to borrow a key out of it, before it even checked the memo.

In 0abe0eb the memo half is now ConstSidMemo::get_or_resolve(cache, key, resolve). It's an associated fn on the memo that takes the Mutex (the lock lives outside the memo itself), releases the lock while the resolver runs since one of the two resolvers evaluates an expression, and doesn't memoize an error. The ComparableValue → Ref → subject_ref_to_s_id mapping is one comparable_subject_s_id, and comparable_subject_key gives the value-keyed site its key straight from the evaluated value, so a hit no longer clones anything. Both sites are a few lines now and resolve through the same code.

Added const_sid_memo_get_or_resolve_resolves_each_key_once for the contract (one resolve per key, a cached None included; a hit never calls the resolver; an error leaves nothing memoized). The #2385 regression test and the rest of eval::compare still pass, and clippy is clean.

@bplatz bplatz added bug Something isn't working as expected area:query Query execution, planning, fast paths, overlay, result formatting labels Nov 19, 2026
Both ?var = <const> memo sites in fast_eq_iri_binding_directional wrote
out lock, get, resolve, insert, each with its own ComparableValue to Ref
to subject_ref_to_s_id mapping. ConstSidMemo::get_or_resolve now does
the memo half (lock released while resolving, errors not memoized), and
comparable_subject_key / comparable_subject_s_id do the mapping, so the
two sites can't drift apart.

The value-keyed site also borrowed its key from a freshly cloned Ref on
every row; it now borrows from the evaluated value and clones only on a
miss.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aaj3f
aaj3f merged commit d132cb3 into main Nov 19, 2026
21 checks passed
@aaj3f
aaj3f deleted the fix/filter-const-sid-key-alias branch November 19, 2026 17:26
bplatz added a commit that referenced this pull request Nov 19, 2026
Brings #2418, #2419 and #2447, each of which applies to next.

- #2418 (frame lengths checked): every frame encoder returns PackResult
  and writes nothing on FrameTooLarge, next's own included. The erasure
  and authorization frames go through the checked JSON encoder with the
  manifest, the erasure artifact frame checks its length, and the
  erasure transfer's frames, its archive manifest and the retention
  journal manifest propagate the error. The stream's error path and
  next's retention-section error path share main's fallback, an Error
  frame with a short message, in encode_error_frame_or_short. The CLI's
  remote splice keeps next's erased-history manifest. main's archive
  test creates its ledger, as a commit needs on next.
- #2419 (the ?var = <const> memo keyed by the constant): applies as is.
  Its test seeds through next's async genesis_ledger.
- #2447 (the parity gate reads "1"^^xsd:boolean as true): applies as is.
@aaj3f aaj3f mentioned this pull request Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:query Query execution, planning, fast paths, overlay, result formatting bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Indexed ledgers: a FILTER(?x = <iri>) in a later UNION branch can match an earlier branch's IRI (wrong rows)

2 participants