Repository navigation
fix(query): answer an unknown predicate with no rows on three fast paths - #2449
Conversation
The string-prefix count, label-regex-type and star-const top-k fast paths returned an internal error when the query named a predicate the index has never seen. They run only when the index answers alone, so such a predicate has no rows: `ref_to_p_id` now reports the miss and each caller returns its empty result, as it already did for a missing object or class.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a clean fix, and the gate it leans on holds: Claude checked that all three lanes decline when the predicate exists only in novelty, so "no rows" can't hide a real answer, and that the new test goes red with the fix reverted or with the lanes declining.
One altitude note: a sweep of every fast lane over an unknown predicate found two more pre-existing spots that answer it differently from the generic pipeline. SUM(STRLEN(GROUP_CONCAT)) returns an unbound sum where SPARQL wants 0, and Cypher's type()/startNode() on a node hits an internal error once the ledger is indexed. The first is a silent wrong answer on the very input this PR fixes, so I'd want it in before merging (two lines); the Cypher one is a few lines too, and I'd rather see it folded in here than tracked separately.
Full review below:
✅ Approving to unblock: please get the SUM(STRLEN(GROUP_CONCAT)) empty answer in before merging. A tight, well-tested fix: the three lanes now give the generic pipeline's answer, and the test pins both the answer and the routing, so it can't pass by declining. The one must is a sibling lane that answers the same unknown-predicate input with a wrong value rather than an error, which is the worse failure, and it's two lines.
Before merging:
fluree-db-query/src/fast_sum_strlen_group_concat.rs:106-114: an unknown predicate (or no rows) returns an unbound sum instead of"0"^^xsd:integer;Some(0)at:108and:113, plus a case in the new test.
Notes:
- This is the second time we've had to decide what a predicate missing from the index dictionary means for a lane: 5281a06 moved the batched probes onto
p_id_or_none, and #2448 isref_to_p_id's lanes. Today the lanes answer it five ways: empty under the metadata gate, empty unless the overlay has rows (re-checked per lane), decline, refuse while merging, and wrong (the two spots inline). The class fix would be one resolver returningIndexed | Absent | Undecided, whereAbsentcan only be built from proof that the index answers alone (say, a tokenfast_path_storehands back instead of a bare store). Not this PR; the point fixes are right here.
Adherence: Patterns ✔ · Performance ✔ · Deployment targets ✔ · Testing ✔ · Conventions ✔ · verification
- Patterns/abstractions: ✔ Same shape as these lanes' existing missing-object/class handling and the other metadata lanes' missing-predicate handling; no new construct. One optional fail-closed guard inline.
- Performance (speed first, memory second): ✔ Resolution runs once per query per lane: an
Optionand alet … else, no per-row work. No performance-degradation risk. - Deployment targets: ✔ n/a: a host-neutral change in shared
fluree-db-query(no I/O, threads or clocks);wasm32andwasm-smokeare green on the head SHA. - Testing: ✔ Own
[[test]]binary (it flips the kill switch), imported ledger, aproceedstamp per lane, SPARQL and JSON-LD twins, known-predicate controls; it ran in CI on this head. - Conventions: ✔ One commit, self-describing subject, multi-line body; fmt and clippy green.
Verified at 24dbe7b20: CI run 44352515102 passed (it_fast_path_unknown_predicate PASS; 16446 tests run, 16446 passed). On a box, Claude ran the test at head (pass), with the four source files reverted to the merge base (18 failures: every unknown-predicate case, on value and on stamp), with each lane declining instead (9 failures, all on the proceed stamp), and restored (pass). A probe confirmed that all three lanes decline on a predicate that exists only in novelty (8/8 answers match the generic pipeline), that an unregistered-namespace predicate and REGEX(?o, "^…") are fixed too, and found the two sibling spots inline; with both fold-ins applied the probe passes. git merge-tree is clean against main and #2468.
Approving so you can merge once the SUM(STRLEN) sibling is in; the Cypher one and the fail-closed guard are worth folding in too.
| /// Uses `ExecutionContext` to decode `Sid` variants. Returns an error for `Ref::Var`. | ||
| pub fn ref_to_p_id(ctx: &ExecutionContext<'_>, store: &BinaryIndexStore, r: &Ref) -> Result<u32> { | ||
| /// `None` when the index has never seen the predicate: a fast path reading the | ||
| /// index at its own `t` with no novelty then has no rows for it. |
There was a problem hiding this comment.
Optional: we may want ref_to_p_id to fail closed where the index doesn't answer alone. This is more of a suggestion than a must. None here means "no rows" only because every caller already holds fast_path_store's gate (no novelty, to_t == max_t), and ref_to_p_id can't see that gate: the invariant lives in this doc comment.
A future caller on an overlay-aware gate (allow_cursor_fast_path tolerates novelty, for example) would turn a predicate that exists only in novelty into an empty answer, silently.
We settled the same question for the batched probes in 5281a06: p_id_or_none (fast_path_common.rs:3206) refuses a miss when the probe would merge novelty for that predicate, in release builds as well. Something like this on the miss arm would do it here, and it's unreachable for today's three callers:
match store.find_predicate_id(iri.as_ref()) {
Some(p_id) => Ok(Some(p_id)),
// "No rows" holds only where the index answers alone (`fast_path_store`).
None if overlay_has_novelty(ctx) || ctx.to_t != store.max_t() => Err(QueryError::Internal(
format!("{iri} is not in the index, and the index does not answer alone here"),
)),
None => Ok(None),
}It's minor and non-blocking, but if you agree it's right I'd rather see it folded in now than lost in the backlog.
| store.find_predicate_id(iri.as_ref()).ok_or_else(|| { | ||
| QueryError::execution(format!("predicate not found in binary index dict: {iri}")) | ||
| }) | ||
| Ok(store.find_predicate_id(iri.as_ref())) |
There was a problem hiding this comment.
Optional, pre-existing: the same miss still errors on the Cypher side. Claude swept for other places that turn an index-dictionary miss into an error and found one: fluree-db-query/src/eval/metadata.rs:312-321 (lookup_ref_objects, behind type(), startNode() and endNode()) answers a miss on f:reifiesPredicate / f:reifiesSubject with QueryError::execution("metadata lookup: unknown predicate …").
Scenario (box, at this head): on a ledger with no reified edges, MATCH (a:Person) RETURN type(a) and RETURN startNode(a) give null per row while the ledger is unindexed, and Internal error: metadata lookup: unknown predicate reifiesPredicate once it's indexed, still with novelty on top, and with the fast-path switch on or off. Whether type() of a node should be null or a clean type error is its own question; an internal error that depends on index state isn't either.
The function already has the right reader for a subject the index lacks, so a miss can fall through to it:
let Some(p_id) = store
.sid_to_p_id(predicate)
.or_else(|| store.find_predicate_id(&predicate.name))
else {
return lookup_ref_objects_via_range(ctx, subject, predicate);
};With that, Claude's probe gets null on indexed and index + novelty ledgers, and type(r) on a reifier that exists only in novelty still gives "RATED". Your code didn't introduce this, but it's #2448's bug on another surface and three lines, so I'd rather see it folded in here than tracked separately.
Commenting here because fluree-db-query/src/eval/metadata.rs is not in this diff.
|
|
||
| let p_id = ref_to_p_id(ctx, store.as_ref(), pred)?; | ||
| let Some(p_id) = ref_to_p_id(ctx, store.as_ref(), pred)? else { | ||
| return Ok(Some(0)); |
There was a problem hiding this comment.
Blocking, pre-existing: one lane answers an aggregate over an unknown predicate with an unbound value instead of 0. This line answers with 0, as the generic pipeline does. fluree-db-query/src/fast_sum_strlen_group_concat.rs:106-114 answers the same situation with an unbound sum: an absent predicate, or zero rows in the graph, returns Supported(None), which :74 renders as Binding::Unbound.
Scenario (box, at this head, imported ledger):
SELECT (SUM(STRLEN(?cat)) AS ?n) {
{ SELECT (GROUP_CONCAT(?o; SEPARATOR=" ") AS ?cat) WHERE { ?s ex:nope ?o } GROUP BY ?s }
}The SUM(STRLEN(GROUP_CONCAT)) lane proceeds and returns {"bindings":[{}]}; with fast paths off the answer is "0"^^xsd:integer. SPARQL 1.1 §18.5.1 gives "0"^^xsd:integer for SUM over the empty multiset, and fast_predicate_scalar_agg::empty_result already returns that for SUM and AVG, so the generic answer is the right one.
Fix: Supported(None) → Supported(Some(0)) at :108 and :113. The None arm at :74 then has no producer, so Supported can carry a plain i64. Claude checked that the change makes the lane agree with the generic pipeline on this query. Your code didn't introduce this (the unknown-predicate sweep walked into it), but it's the same input this PR fixes, answered with a silent wrong value instead of a 500, so I'd want it in before this merges, with a case in the new test.
Commenting here because fluree-db-query/src/fast_sum_strlen_group_concat.rs is not in this diff.
The fused SUM(STRLEN(GROUP_CONCAT)) lane answered a predicate the index does not hold, or one with no rows, with an unbound sum. The generic pipeline answers "0"^^xsd:integer, which is right: with no rows the inner GROUP BY yields no groups, and SUM over no values is 0. Both empty arms now return 0. With no producer left for an absent sum, Supported carries a plain i64 and the batch comes from build_i64_singleton_batch. The unknown-predicate regression test gains an unknown-predicate case and a known-predicate control for this lane, each stamped so it cannot pass by declining. There is no JSON-LD twin: a JSON-LD subquery's groupBy orders by its keys, and the lane declines an ordered subquery, so the JSON-LD form never reaches it.
lookup_ref_objects, behind Cypher's type(), startNode() and endNode(), resolves f:reifiesPredicate and f:reifiesSubject to index predicate ids before its batched read. On a ledger whose index holds no reified edge those predicates are absent, and the miss was an internal error: "metadata lookup: unknown predicate reifiesPredicate". The same query answered null while the ledger was unindexed, so the answer depended on index state. A miss now reads through lookup_ref_objects_via_range, where the function already goes when the batched read finds nothing. That path merges novelty, so a predicate that exists only there is still read. The new Cypher test runs type() and startNode() on a node over an index without reified edges, alone and with novelty on top; both cases fail with the internal error when the fix is reverted. A third case, an edge reified only in novelty, is a control that type(r) still resolves.
ref_to_p_id answers a predicate the index has never seen with None, which its callers read as no rows. That holds only where the index answers alone: no novelty, and the index at the query's t, as fast_path_store requires of every caller today. ref_to_p_id could not see that gate, so a future caller on a gate that tolerates novelty would answer a predicate whose rows are all in novelty with nothing. The miss arm now checks the same condition as index_is_current and returns an internal error when the index does not answer alone, in release builds as well, as p_id_or_none does for the batched probes. A hit pays nothing, and none of the current callers can reach the refusal.
Follow-up: #2479 |
Brings #2449, which applies to next. - The three ref_to_p_id lanes, the SUM(STRLEN(GROUP_CONCAT)) empty answer and the ref_to_p_id refusal apply as is: next's lanes, callers and gates are main's, plus next's pooled-graph decline in fast_path_store, which leaves a store-wide dictionary miss meaning the same thing. The fast-path test fails 19 cases against next's lanes without the fix. - The Cypher metadata hunk applies, with no reachable trigger on next: next reads type(), startNode() and endNode() from rdf:reifies links through the range path, so the error it fixes on main never arose here, and lookup_ref_objects serves only labels(), whose rdf:type lookup doesn't miss. The fall-through matches the function's existing empty-result route. The Cypher test pins the answers on next, seeds through next's async genesis_ledger, and its doc comment no longer names the f:reifies* predicates next doesn't read there.
Three fast paths returned an internal error (HTTP 500) when a query named a predicate the index has never seen. They now return no rows, as the generic pipeline does:
COUNT(*), orSUM(STRSTARTS(...)), with aSTRSTARTSfilter;rdf:type+regex;ORDER BY ?label LIMIT k.ref_to_p_idnow returnsNonefor a predicate missing from the index's predicate dictionary, and each caller returns its empty result. These lanes run only when the index answers alone (no novelty,to_t == max_t), so a predicate the index lacks has no rows. They already treated a missing object or class the same way. A miss where the index does not answer alone is refused, asp_id_or_nonedoes for the batched probes. No current caller can reach that.Two related places answered the same input wrongly, and are fixed here too:
SUM(STRLEN(GROUP_CONCAT))answered an unknown predicate, or one with no rows, with an unbound sum. It now answers"0"^^xsd:integer, as the generic pipeline does and SPARQL requires.type(),startNode()andendNode()hit an internal error once the ledger was indexed, if the index held no reified edge. They now read such a predicate through the range path, which also reads novelty.The new fast-path test imports its ledger, so every lane fires. For each shape it checks the answer from the fast lane and from the generic pipeline, and the lane's routing stamp. Shapes are in SPARQL and JSON-LD, except
SUM(STRLEN(GROUP_CONCAT)), which a JSON-LD subquery never reaches because itsgroupByadds an ordering the lane declines. A Cypher test covers the metadata functions over an index without reified edges, alone and with novelty on top.Fixes #2448
Follow-up: #2479