Repository navigation
feat(sparql): burn-down Wave 2 — GRAPH conformance (D-2), multi-op UPDATE (#1438), BASE resolution, Turtle-star ingest (−31+ registers) - #1454
Conversation
…::iri The Turtle parser owned the only spec-correct IRI reference resolver in the workspace (RFC 3986 §5: fragment rules, dot-segment removal, authority/path merging). SPARQL lowering needs the identical semantics for BASE-relative resolution, so the resolver moves to the dependency-free fluree-vocab crate as pub fns is_absolute_iri / resolve_iri, with unit tests covering the W3C-relevant shapes (sibling-document refs, fragment refs, <> against a fragmented base, dot segments, scheme-only absolutes like urn:/did:). The Turtle parser now delegates; its resolve_iri keeps only the Turtle-specific relative-without-base error. Behavior is unchanged — the existing @base integration tests in fluree-graph-turtle keep guarding the delegated implementation.
…ier pipeline
Lex/parse reified triples ('<< s p o ~ reifier >>') and annotation
blocks ('{| ... |}') in Turtle data and emit the SAME durable
f:reifies* flakes the JSON-LD @annotation lowering produces, via the
shared EdgeKey::to_reifies_facts_jsonld_compatible encoder (no
f:reifiesDatatype flake — cascade-retract symmetric). A FRESH
blank-node reifier is minted per anonymous occurrence, mirroring the
JSON-LD _:fluree_ann_N minting; reifiers are never deduplicated by
base-triple identity (W3C eval pattern-3-nomatch depends on this).
- fluree-graph-ir: GraphSink gains supports_reified_triples() +
emit_reified_triple() (default: unsupported), keeping the generic
crates encoding-agnostic — the f:reifies* schema lives only in core.
- fluree-graph-turtle lexer: '<<'/'<<(' recognized inside the existing
IRI-parse error fallback (zero extra work for valid IRIs); '{|'
costs one byte peek on the '{' branch; '>>'/'|}'/'~' reuse arms that
were hard lex errors before. A non-star corpus pin test asserts
star-free lexing is unchanged.
- fluree-graph-turtle parser: rtSubject/verb/rtObject grammar with
nesting through the reifier node; annotation tails ('~ r', blocks,
shared pending reifier); base triple asserted (documented divergence
from RDF 1.2's non-asserting '<< >>' — Fluree's edge-annotation
model reifies an asserted edge, per the burn-down roadmap).
- Deferred with specific errors: '<<( ... )>>' triple terms as values
(Option-1 epic), annotation-of-annotation (mirrors the JSON-LD v1
deferral), annotations on collections, star on sinks that don't
support reified triples, and TriG-star inside GRAPH blocks (kept
narrow so D-8 builder-path routing for plain TriG stays viable).
- fluree-db-transact: FlakeSink (transactional insert) and ImportSink
(bulk import, commit writer + spool) implement the event; the
AttachmentNovelty observer picks the bundles up unchanged.
- Turtle-star <-> JSON-LD flake-equivalence tests live next to the
edgekey_roundtrip_* gates, including the repeated-anonymous case.
The lowering context carried the prologue BASE but applied it with a naive
string concatenation gated on !contains("://") — fragment references
(<#x>) were skipped entirely, relative PREFIX namespaces (PREFIX : <>,
PREFIX : <#>) were never resolved, scheme-only absolutes (urn:, did:) were
mis-detected as relative, and IRI()/URI() ignored the base outright
(expression-semantics D8). Constant GRAPH names therefore missed the
graph registry, which stores absolute IRIs (the refuted "BUG-4" of the
named-graph audit: graph-exist fails on base resolution, not on a dropped
existence row).
Lowering now resolves every constant IRI position through the shared
fluree_vocab::iri resolver (RFC 3986 §5), entirely at prepare time:
- expand_iri resolves relative full-IRI references against BASE; every
constant position funnels through it (patterns, GRAPH/SERVICE names,
paths, CONSTRUCT/DESCRIBE templates, VALUES terms).
- Relative PREFIX namespaces resolve against BASE once, when the prologue
environment is built (SPARQL 1.1 §4.1.1).
- IRI()/URI() constant string arguments are base-resolved by a lowering-time
constant fold (SPARQL 1.1 §17.4.2.8); the eval path stays base-free, so
per-row cost is zero. Variable/computed arguments are not resolved, by
design.
- Without a BASE, relative IRIs keep the historical verbatim passthrough
(ledger-local names, e.g. relative @id values created via JSON-LD).
Also lands the dataset-clause resolution plumbing for the roadmap's PR-G2:
resolve_dataset_clause() returns FROM / FROM NAMED (and FROM..TO) IRIs
prefix-expanded and base-resolved. FROM execution on a single-ledger
GraphDb stays rejected — validate_sparql_for_view is untouched; only the
future dataset construction consumes this.
W3C: greens basic#base-prefix-2/5, graph#graph-exist, functions#iri01,
property-path#pp34, exists#exists03 (registers pruned in the harness
commit). basic#base-prefix-1 additionally needs the empty-IRIREF lexer fix
owned by roadmap PR-1; pp35 additionally needs the GraphOperator fixes
owned by PR-G1.
…r ingest
pattern-3 and pattern-3-nomatch go green (-2, exactly the wave-1
prediction) and are removed. Every remaining entry is re-pointed at
its OBSERVED post-ingest gap from a live suite run, replacing the
inferred-from-source classification: 15 wave-2 query-syntax (bare
'<< >>' patterns hit the legacy rdf_star lowering), 10 D-1
triple-terms-as-values data files, 5 result-mismatch (triple-term
serialization / rdf:reifies exposure), 5 TriG multi-graph data (D-8),
1 D-2 functions (isTriple), 1 D-4 CONSTRUCT projection, and 2 harness
expected-graph parses (construct-5, update-3 — whose '{| |}' INSERT
DATA already executes, per roadmap 1.1-11).
W3C engines resolve relative IRIs in a query against the query document's URL (RFC 3986 §5.1.3); the harness already did this for data files (@base prepended in prepare_for_insert) but executed query text with no base at all, so every document-relative constant IRI (GRAPH <data-g1.ttl>) missed the absolutely-keyed graph registry. The eval runner now prepends BASE <query-url> — an explicit BASE in the query text overrides it (last declaration wins), exactly like a document-supplied base. Register shrink (both directions verified by the suite's stale-entry policing; full run 36/36 green): - SPARQL10_QUERY_EVAL: basic#base-prefix-2, basic#base-prefix-5, graph#graph-exist removed. - SPARQL11_FUNCTIONS: iri01 removed. - SPARQL11_PROPERTY_PATH: pp34 removed (greened by base resolution alone, verified empirically); pp35 stays with a second-lander note (needs PR-G1's GraphOperator fixes on top). - SPARQL11_EXISTS: exists03 removed (greened by base resolution alone). - basic#base-prefix-1 stays registered with a note: its remaining failure is the empty-IRIREF (<>) lexer rejection owned by roadmap PR-1.
The W3C harness exercises harness-injected document bases; these integration tests pin the product-facing behavior for a user-authored BASE declaration: fragment references (<#x>, base-prefix-5 shape), relative PREFIX namespaces (PREFIX : <#>, base-prefix-2 shape), RFC-correct path merging (directory base vs sibling-document base, the graph-exist mechanism), constant GRAPH names resolving to the absolute registry key, IRI()/URI() constant folding (D8/iri01), and the no-BASE verbatim passthrough for relative IRIs created via JSON-LD raw @id.
…ault graph (#1442) BUG-1: GraphOperator materialized the graph variable as a plain xsd:string literal (graph.rs merge loop); SPARQL requires an IRI term. Bind Binding::iri(graph_iri) instead — the value string was already correct, only the term kind changes. BUG-2 (decision D-2, ADOPTED): unbound GRAPH ?g no longer enumerates the ledger alias (default graph). SPARQL 1.1 defines GRAPH ?g to range over named graphs only; the #1279 extension implicitly appended the default graph to the fan-out, which broke every W3C GRAPH-enumeration test. Explicit alias addressing (GRAPH <alias>, bound ?g = alias) is KEPT — no W3C test names a ledger alias, and it preserves the useful query-the-default-graph-by-name affordance. No opt-in toggle is shipped (docs/audit/burn-down/ROADMAP.md par.4 D-2; named-graph-dataset.md par.3). Updates the three tests that pinned the extension: - it_query_dataset.rs sparql_single_db_graph_variable_unbound: unbound GRAPH ?g over a ledger with no user graphs is now empty - it_query_dataset.rs sparql_single_db_graph_variable_discovers_user_graphs: discovers user graphs only, not the alias - it_upsert_duplicate_ids_repro.rs: the GRAPH probe now addresses the default graph explicitly (GRAPH <ledger-id>, the kept half) and pins that unbound GRAPH ?g stays empty on the file-backed/binary-index path Adds the FQL parity regression (same GraphOperator serves ["graph",...]): fql_single_db_graph_variable_excludes_default_binds_iri asserts the IRI term kind and the default-graph exclusion on the JSON-LD surface.
…#1442) BUG-3: the merge loop unconditionally stamped the graph name over whatever the inner subplan bound to the graph variable, so GRAPH ?g { ?g :p ?o } returned every subject with :p and GRAPH ?g { spo OPTIONAL { ?s ?p ?g } } kept incompatible optional rows. Per the SPARQL algebra the {?g -> graph} binding is JOINED with the inner solutions. Two-part, all plan/seed/merge-time (zero per-scan-row branching): - Seed-when-produced: when the inner body binds ?g in EVERY solution (required top-level triple / property path / slice-free sub-SELECT — the same self_produced_vars rule SubqueryOperator uses for hash-join keys, now pub(crate)), seed Binding::iri(graph) into the inner SeedOperator row. Join-equivalent by construction and strictly narrows the inner scan; it also correlates a sub-SELECT projecting ?g (residual-eval defect A4 → W3C subquery02). - Join-at-merge: otherwise the inner runs with ?g free (W3C graph-variable-scope: ?g is NOT in scope for a FILTER-only reference) and merge drops rows whose inner ?g is bound to a different term than the active graph's name (W3C graph-optional / graph-variable-join). Together with the D-2 enumeration fix this also greens subquery04 (residual-eval defect A3: default graph must not leak into a GRAPH-scoped subquery). FQL parity regression: fql_single_db_graph_variable_join_inner_use (["graph","?g",{"@id":"?g",...}] constrained to the graph's own name).
…ding (#1443) BUG-5: extract_graph_iri_from_binding handled Iri/IriMatch/Sid and the back-compat string literal, but not Binding::EncodedSid/EncodedLit — the form a binary-index scan binds by default. A ?g bound from a triple scan object and consumed by a correlated GRAPH (the EXISTS shape: ?s :p ?g . FILTER EXISTS { GRAPH ?g { ... } }) silently resolved no graph. Add the encoded arms: materialize against the active graph view, then extract from the decoded form. Runs per parent row of a correlated GRAPH, bound-var arm only — never on a scan hot path; subject/string dictionaries are store-global, so the outer view decode is sound. Companion plan-time fix: choose_exists_strategy now falls back to per-row ExistsOperator (new reason: GraphVarCorrelated) when the EXISTS body contains a GRAPH ?g whose graph variable is bound by the outer schema. The Semijoin strategy would evaluate the body standalone — enumerating every named graph and keying ?g as a raw Binding::Iri that can never hash-match the outer scan's Sid/EncodedSid representation of the same IRI — and is also strictly more work than resolving the one graph the row's ?g addresses. Greens W3C exists-graph-variable (FILTER EXISTS lowers to the same Pattern::Exists dispatch). FQL parity regression: fql_single_db_graph_variable_bound_from_scan_exists uses the EXISTS/late-materialized shape — a top-level scan-bound ?g was eagerly resolved and passed even before this fix, so it would pin nothing.
… (-14) Removed (now passing; the both-directions register check enforces this): - SPARQL10_QUERY_EVAL (11): dawg-graph-03/04/06/07/08/09/10b/11, graph-empty, graph-variable-join, graph-optional - SPARQL11_EXISTS (1): exists-graph-variable - SPARQL11_SUBQUERY (2): subquery02, subquery04 (register now empty) Kept, with corrected ownership comments: - graph-exist: relative-IRI/BASE resolution of the constant graph name — owner PR-BASE (distinct defect; NOT part of #1442) - exists03: second lander (PR-G1 landed / PR-BASE pending) - pp34/pp35: graph-cluster base-expansion misses, second lander (PR-G1 landed / PR-BASE pending) - eq-graph-1/2/4: remaining blocker is FILTER = value-equality (D5) — second lander (PR-G1 landed / PR-X2 pending) - bindings#graph: remaining blocker is empty-named-graph modeling (D-6) - agg-empty-group-count-graph: same empty-named-graph dependency (D-6) Verified empirically: full W3C run is 36/36 suites green with these exact removals (0 unexpected failures, 0 stale entries).
…' loop) QueryBody::Update now carries an UpdateRequest — the grammar's full Update ::= Prologue ( Update1 ( ';' Update )? )? sequence — instead of a single UpdateOperation. The parser loops over ';'-separated operations, accumulating PREFIX/BASE declarations across operations per spec, with each operation snapshotting the prologue in effect for it (a later redeclaration cannot retroactively rebind an earlier operation). One trailing ';' stays legal, and an empty or prologue-only request parses as a valid zero-operation no-op (W3C syntax-update-1 test_38/39/40). This replaces PR #1438's D-10a interim guard (the loud multi-op rejection at the trailing-token assertion) with real support; the trailing-token/EOF assertion itself remains for genuine garbage. Two validations land with the loop, both previously green only because the guard rejected every multi-op request: - cross-operation blank-node label reuse in template/data positions is a parse error (SPARQL 1.1 Update §19.6; W3C syntax-update-54); - an anonymous annotation (no explicit reifier) in DELETE DATA is a validation error — it would mint a fresh blank node that can never name the reifier to delete (W3C sparql12 syntax-update-anonreifier-02).
… one atomic commit Implements roadmap D-10(b): a ';'-separated SPARQL UPDATE request stages its operations sequentially — operation N+1's WHERE observes the graph-store state operation N produced (SPARQL 1.1 Update §3.1) — and the whole request lands as ONE atomic commit at t+1 (not N commits). Pieces: - lower_sparql_update_request lowers an UpdateRequest to Vec<Txn>, one per operation against its own accumulated prologue; lower_sparql_update_ast stays as the single-operation convenience and now fails loudly on zero/multi-op requests. - LedgerState::apply_staged_flakes_for_sequential_staging: a commit- record-less 'virtual commit' that overlays staged flakes as committed novelty (envelope deltas + dict/novelty apply) so the next operation stages against the evolving state. Transient staging use only. - Fluree::stage_transaction_from_txns: dispatches 1 txn to the existing single-op path (untouched fast path), 0 txns to a zero-flake staged view (empty/prologue-only request = valid no-op via the existing zero-staged-flakes success path), and N>=2 to the sequential loop. Each op runs the full per-op pipeline (policy, SHACL, uniqueness); flakes fold into one merged set re-stamped to the final commit t with last-wins per fact identity (g,s,p,o,dt,m), so INSERT x; DELETE x nets to the retract and DELETE x; INSERT x nets to the assert. The final StagedLedger layers the fold over the ORIGINAL base, so build_commit stamps t+1 and applies the union envelope deltas exactly as a single-op commit would. - Both SPARQL seams (commit fast path + stage preview) route through the new entry point. End-to-end tests cover the #1438 truncation scenario (op 2 sees op 1's insert), the W3C dawg-delete-insert-01c shape, insert-then-delete / delete-then-reinsert netting, the no-op empty request, and the cross-operation blank-node rejection at the seam. Benches (--quick, small): transact_commit fresh 88.2->86.7us, populated 314.3->304.7us; query_hot_bsbm q3 537->528us, q5 680->676us, q9 952->961us — all within noise.
Removed (now passing; CI's stale-entry policing enforced each): - syntax-update-1 test_38/test_39/test_40, both register copies (6) — empty / BASE-only / PREFIX-only requests are valid no-ops; - delete-insert dawg-delete-insert-01b and -01c (2) — multi-op requests execute sequentially (01b was re-registered by the D-10a guard; 01c is the classic op-2-sees-op-1 case); - sparql12 triple-terms-positive update-reifier-08 (1) — the multi-op reifier request parses. Re-pointed with corrected comments (still registered): basic-update insert-05a + insert-data-same-bnode + insert-where-same-bnode(2) — the multi-op prefix now stages, but each request ends in DROP GRAPH, a graph-management verb owned by PR-U3; they fail at parse until it lands. Net register delta: -9. syntax-update-54 (both copies) and triple-terms-negative syntax-update-anonreifier-02 stay green through the new real validations rather than the interim guard. Full suite: green, 0 unexpected passes, 0 stale entries.
# Conflicts: # fluree-db-sparql/src/validate/mod.rs # testsuite-sparql/tests/registers/mod.rs
# Conflicts: # testsuite-sparql/tests/registers/mod.rs
# Conflicts: # testsuite-sparql/tests/registers/mod.rs
# Conflicts: # testsuite-sparql/tests/registers/mod.rs
46 tests green only in integration (joint BASE+G1 entries like pp35 and exists03, G1-gated algebra/optional-complex tests, eq-graph second-lander interplay) — resolved by the both-way gate rather than hand set-math.
bplatz
left a comment
There was a problem hiding this comment.
A few issues from reviewing the wave-2 diff. Two don't land on changed lines, so noting them here:
fluree-db-transact/src/parse/trig_meta.rs:616(resolve_iri) still doesformat!("{base}{iri}")instead of the RFC-3986fluree_vocab::iri::resolve_irithis PR wired into the Turtle parser and SPARQL lowering. A document-IRI@baseplus a sibling relative ref (e.g.sibling.ttl) resolves wrong, and this is the production TriG import/upsert path.docs/query/sparql.md:549still documents unboundGRAPH ?gas enumerating the ledger alias / default graph — the exact behavior D-2 removes here. Docs weren't updated in this changeset.
Inline comments below.
bplatz
left a comment
There was a problem hiding this comment.
Some comments inline to investigate.
PR-1454 review (blocking): anonymous mints — bare '{| … |}'/'~' star
reifiers and '[]' nodes — used the generic 'b{N}' label scheme, whose
skolemized Sid is identical to a user-written '_:b{N}' in the same
transaction. '_:b1 ex:name "Bob" . ex:a ex:b ex:c {| ex:source "hr" |}'
silently attached the reifier bundle and annotation body to Bob's node
(and '_:b1 ex:p [ ex:q ex:r ]' merged the '[]' the same way — the
pre-existing case this closes for free).
Anonymous mints now use '-b{N}': a BLANK_NODE_LABEL must start with
PN_CHARS_U | [0-9], so no user label can ever lex into the '-'-prefixed
namespace, while '-' stays legal medially — the full skolemized
'fdb-{txn}--b{N}' label still serializes and re-imports as the same
stored node. Same hazard class main's PR-1453 remediation closed for
DELETE WHERE variable names with '_:[]{N}' (those never serialize;
these do, hence the lexable-when-prefixed choice).
The old unit test compared TermIds, which never collided — the
collision was at the Sid level; the new unit case pins Sid-level
disjointness, and the integration test pins both the reifier and '[]'
cases end-to-end.
PR-1454 review (blocking; found by bplatz, live-verified): the update
lowering's 'expand_iri' returned IriValue::Full verbatim and never read
'prologue.base', so 'BASE <http://x/> INSERT DATA { <s1> <p1> "v" }'
committed literal 's1'/'p1' while the query surface resolves the same
document's '<s1>' to '<http://x/s1>' — one document, two different sets
of IRIs, and pr-u2's per-op BASE accumulation threaded a base the
lowering then ignored.
Constant IRIs (subjects, predicates, objects, datatypes, and GRAPH
names — all 16 call sites funnel through the one leaf) now resolve with
the same 'fluree_vocab::iri' primitives as the query path's
'expand_iri_with': relative references resolve against BASE per
RFC 3986 §5, a relative PREFIX namespace itself resolves against BASE
per SPARQL 1.1 §4.1.1, and absolute references (any scheme, including
'urn:'/'did:') pass through verbatim. Without a BASE, relative
references stay as written (ledger-local names), unchanged.
The staged-WHERE half needs no change: deferred WHERE lowering already
runs through the query-side environment at staging time. Unit tests pin
the RFC 3986 cases; the seam-level pin lands with the atomicity tests.
PR-1454 review (blocking-decision; found by bplatz, live-verified): the
request-level §19.6 label-reuse walker fed DELETE WHERE patterns and
Modify DELETE templates into the check, so
'DELETE WHERE { _:b1 :flag "a" } ; DELETE WHERE { _:b1 :flag "b" }'
was rejected as a duplicate label — though Fluree's own operation mode
table treats DELETE WHERE blank nodes as locally-scoped existential
matching variables (documented extension), making the two operations
independent matches.
Decision, per both reviews: §19.6's cross-operation label ban protects
blank-node MINTING positions only. The walker now collects INSERT DATA
quad data and Modify INSERT templates, nothing else. DELETE-side blank
nodes either act as variables (DELETE WHERE, Fluree extension) or are
rejected outright downstream by the strict validator/lowering with the
real error ('blank nodes are not allowed in DELETE …') — which a
cross-operation-label complaint would only have masked. W3C
syntax-update-54 rejection (INSERT DATA / INSERT template reuse) is
unchanged and stays pinned; the W3C strict profile still rejects
DELETE-side bnodes at validate(), so no harness register moves.
Parse-level tests pin label reuse across DELETE WHERE, across DELETE
templates, and mint-then-match mixes; the seam-level execution pin
lands with the atomicity tests.
…op commit envelope
Investigating bplatz's PR-1454 graph_delta-ordering concern with a
discriminating reload test surfaced a harder bug in the sequential
multi-op staging loop: the between-ops virtual apply and the final
commit envelope both used LOWERING-time namespace deltas, but the
namespace of a 'GRAPH <iri>' name is allocated at STAGING time by each
operation's own registry. Three consequences, worst first:
1. A request whose op 1 writes to a new named graph failed to COMMIT
at all — the between-ops apply registered the graph IRI but not its
namespace, so 'build_reverse_graph' couldn't encode it and novelty
routing errored with 'flake references unknown graph Sid'
('INSERT DATA { GRAPH <urn:g:zzz> { … } } ; INSERT DATA { GRAPH
<urn:g:aaa> { … } }' reproduces).
2. Later ops' registries, built from a virtual snapshot missing those
staging allocations, could assign the same namespace code to a
DIFFERENT namespace — constructible cross-op Sid collisions.
3. The final envelope took its delta from the LAST op's registry, for
which earlier ops' allocations look pre-existing (they were baked
into the virtual snapshot) — so a cold reload from storage could
not decode earlier ops' flakes.
The loop now captures each op's POST-staging registry delta (lowering
allocations adopted + staging allocations) for the between-ops apply,
accumulates the union across operations, and re-adopts the union into
the final registry via 'adopt_delta_for_persistence' so 'take_delta'
at commit carries the whole request's allocations relative to the
original base. Code assignment stays globally consistent because each
op's registry now derives from a virtual snapshot that includes all
prior staging allocations.
On bplatz's original point: the persisted graph_delta KEYS are the
staging-order simulated ids while load-time registration re-derives
ids from sorted 'apply_delta' batches — but every consumer (live
routing, commit replay, index metadata) reads the VALUES and
re-derives ids through the registry, so instances are internally
consistent; the discriminating test pins exactly that property.
Tests: multi-op two-new-graphs request in anti-sorted arrival order,
asserted live AND after a cold reload from disk; plus the
dangling-retract ('INSERT x ; DELETE x') novelty→index merge with a
mid-request-only namespace surviving index build + cold reload.
Four additions, one per open review item: - Multi-op atomicity on mid-request failure (review blocking #4): op 1 INSERT DATA stages cleanly, op 2 fails at staging while evaluating over op 1's data (BIND(STRDT(?m, <bad:datatype>)) — proving op 2 ran against the sequential state); the request errors as a unit, 't' is unchanged, and op 1 leaves no trace. - UPDATE BASE resolution at the seam (review blocking #2): the same BASE-carrying document stores and finds identical absolute IRIs on the update and query surfaces, GRAPH names included. - DELETE WHERE label independence at the seam (review blocking #5): label reuse across DELETE WHERE ops executes, each op deleting its own matches. - Indexed EXISTS-with-GRAPH-?g (review blocking #3): the GraphVarCorrelated strategy driven end-to-end on a binary-indexed ledger — including the string-literal back-compat — which no memory-backed suite (W3C harness included) ever exercised. On the #1443 EncodedSid/EncodedLit extraction arms specifically, the audit went one step past the review's finding: no current plan shape delivers a still-encoded binding to either extraction site (probed: plain join, OPTIONAL, FILTER EXISTS, UNION, string variant — upstream operators materialize batches first). The arms stay as defense-in-depth with their comment rewritten to say exactly that (this also retires the stale 'never on a scan hot path' wording the review flagged).
…r test
PR-1454 review (blocking, bookkeeping): the wave-2 re-baseline left 10
entries duplicated inside SPARQL12_EVAL_TRIPLE_TERMS — construct-4/5,
expr-1, graphs-1/2, op-1/2, order-1/2, update-3 each attributed to two
ownership clusters at once (44 physical entries, 34 unique). The
set-based both-way gate can't see intra-register duplicates, but this
register is Wave 3's work inventory and double-counts every duplicated
test.
Attribution re-verified empirically: unregistered all 10 and read the
harness's actual failure reasons, then re-added each under the single
matching cluster —
- construct-4 → D-4 CONSTRUCT annotation projection (lowering error);
- construct-5, update-3 → harness EXPECTED-graph parsing (star
constructs in the expected .ttl/.trig; the queries themselves run);
- expr-1, graphs-1/2 → TriG GRAPH-block parsing, D-8 ('expected
subject, found KwGraph' on data-4.trig);
- op-1/2, order-1/2 → D-1 triple-terms-as-values ('<<( … )>>' deferred
ingest error).
Stale cluster counts corrected as they stood ((13)/(22)/(1) never
matched their contents). 36/36 suites stay green; both-way policing
still enforces the register exactly.
bplatz's PR-1454 review: docs/query/sparql.md still documented unbound 'GRAPH ?g' as discovering the ledger alias / default graph — the exact #1279 behavior D-2 (issue #1442) removes in this changeset. Per SPARQL 1.1, 'GRAPH ?g' ranges over named graphs only; the default graph stays explicitly addressable via 'GRAPH <ledger-alias>' when named directly or bound from another pattern.
bplatz's PR-1454 review: trig_meta's 'resolve_iri' still did
'!iri.contains(':')' + string concat — the exact heuristic this
changeset replaced for the Turtle parser and SPARQL prologues — on the
production TriG import/upsert path. A document-IRI @base plus a sibling
relative reference resolved to '…/doc.trigsibling.ttl' instead of
merging paths; '<//host/x>', '</rooted>', dot-segments, and
colon-in-path relatives ('<a/b:c>') mis-resolved the same way.
Delegates to the shared 'fluree_vocab::iri' resolver (is_absolute_iri +
resolve_iri), matching the Turtle parser and SPARQL lowering. Relative
@base directives now chain correctly for free (parse_iri resolves the
new base against the current one). Without a @base, relative references
keep passing through verbatim — this path's historical ledger-local
behavior, which also keeps the relative '<#txn-meta>' sentinel matching
TXN_META_GRAPH_IRI exactly.
…ons, and expression-embedded EXISTS
PR-1454 review (bplatz + local follow-on): 'has_outer_correlated_graph_var'
missed three pattern containers whose bodies 'produced_vars' walks
transparently — 'Pattern::Service', 'EdgeAnnotation'/'AnnotationTarget'
bodies, and pattern lists embedded in expressions
('FILTER(EXISTS { … } && …)', 'BIND(EXISTS { … } AS ?x)', pattern
comprehensions). An outer-bound '?g' whose 'GRAPH ?g { … }' sat inside
any of them still selected Semijoin, re-opening the #1443
'Binding::Iri' vs 'Sid'/'EncodedSid' hash mismatch (silently empty
EXISTS) that the GraphVarCorrelated fallback exists to close.
Adds 'Expression::for_each_embedded_patterns' (traversal mirror of
'contains_function') so planners can reach expression-embedded pattern
lists without duplicating the variant walk.
Decision-level tests pin the bare shape (previously integration-only),
all three container shapes, and a negative control proving the
Semijoin fast path survives for uncorrelated graph vars behind
SERVICE.
bplatz's PR-1454 review: 'FlakeSink::emit_reified_triple' and 'ImportSink::emit_reified_triple' duplicated the resolve → dt/lang → validate → 'EdgeKey' → 'to_reifies_facts_jsonld_compatible' sequence, leaving the bit-identical-bundles guarantee (Turtle-star ≡ JSON-LD '@annotation' at the flake level, transactional ≡ bulk-import) to parallel maintenance. The construction now lives in one place ('generate::flakes::reified_triple_bundle', next to the 'validate_value_dt_pair' guard both paths share); each sink keeps only its own error channel (invariant_error vs encode_error) and emission (Vec-extend vs commit-writer/spool) — mirroring the existing 'build_flake'/'push_triple' split.
…§5.2.4)
PR-1454 review: 'remove_dot_segments' dropped the trailing slash when
the resolved path ends in a '.'/'..' segment —
'resolve_iri("http://abc/def/ghi", ".")' returned 'http://abc/def'
where RFC 3986 (and the W3C IRI-resolution-08 fixtures) require
'http://abc/def/'. Pre-existing and carried over byte-identically, but
this changeset brands the module as the canonical RFC 3986 §5 resolver
and now routes three surfaces through it (Turtle @base, SPARQL BASE on
both query and update, TriG import), so fix-in-place beat
document-as-limitation.
A final '.'/'..' segment now re-emits the directory's trailing slash;
bare '.'/'..' with an empty output stay empty per rule 2D. Tests encode
the six IRI-resolution-08 dot-segment cases (s295–s300) plus the
empty-segment ('//de//') and colon-in-path ('d:f') groups (s301–s306).
PR-1454 review optionals, batched: - Per-operation validation semantics (policy/SHACL/uniqueness run against the sequential state; a transiently-invalid-but-finally-valid request aborts at the offending operation) documented in docs/query/sparql.md's new multi-operation section + the staging-loop doc, and pinned by a seam test: duplicate-then-free on an inline-unique property must abort with nothing landed. - graph.rs merge-join: comment the two deliberate edges — a row whose inner '?g' fails extraction drops (lossy-but-safe over erroring mid-merge), and the string-literal back-compat joins by value across term kinds where strict SPARQL term-equality would drop. - lower/mod.rs prologue environment: comment the last-wins BASE simplifications (relative PREFIX before BASE still resolves against it; relative BASEs don't chain; redeclared prefixes last-wins). - SPARQL results JSON: pin the '"type":"uri"' rendering for graph-variable bindings.
Includes the pre-existing testsuite-sparql drift the root-workspace 'cargo fmt' never covers (excluded workspace member).
|
Review response for both reviews (bplatz's inline pass + the local from-scratch pass) — 12 commits on top of the Blocking items from the request-changes review:
Beyond the reviews (found while writing the discriminating test bplatz suggested): a multi-op request writing to ≥2 new named graphs failed to commit outright, and a new-namespace-in-an-early-op request persisted a commit envelope that couldn't decode after reload — root cause and fix in a9106bb (staging-time namespace allocations now reach the virtual state, later ops' registries, and the commit envelope). Optional items landed: trig_meta RFC 3986 resolution on the production TriG import path (cd8e8d8), where_plan recursion gaps incl. expression-embedded EXISTS (3f0e2ae), shared reified-triple bundle builder (6418e99), the RFC 3986 trailing-slash resolver bug fixed with the six W3C IRI-resolution-08 fixture cases (dd2636e), unbound Deferred with issues: #1479 (O(n²) cumulative ns-delta re-adoption), #1480 (parser recursion depth ceiling), #1481 (lexer pin corpus + intra-prologue redeclared-prefix divergence between surfaces). Verification at HEAD (2e8bba8): full nextest across all six touched crates |
Reviewer quick reference
End-user API/contract changes: (a)
GRAPH ?gsemantics change (D-2) —?gbinds as an IRI term (was: a string literal), and unboundGRAPH ?gno longer enumerates the ledger-alias default graph; explicitGRAPH <alias>addressing still works. Queries relying on the old implicit enumeration must name the alias. Three pinning tests updated; 2-reviewer sign-off requested on this component. (b) Multi-operation UPDATE requests now execute fully and atomically (previously: silent first-op-only, then Wave 1's loud error) — a new capability, closing #1438. (c)BASE-relative constant IRIs now resolve per RFC 3986 at query preparation (spec behavior; previously unresolved text). (d) Turtle-star asserting forms are newly accepted input; documented divergence: Fluree's edge-annotation model asserts the base triple of a reified statement (RDF 1.2's non-asserting reading belongs to the triple-terms epic).Performance verdict: all changes are plan/lower/materialization-time or update-staging; the single-operation UPDATE path delegates byte-identically. BSBM at noise level on every component (numbers per component below);
transact_commitmeasured marginally faster; import benches for the Turtle-star lexer within budget on a 6-round interleave.Production bugs found & fixed along the way:
GRAPH ?gbinding graph names asxsd:stringliterals and leaking the default graph (#1442); boundGRAPH ?gsilently matching nothing for late-materialized encoded bindings in EXISTS/correlated shapes (#1443); multi-op UPDATE silent data loss (#1438, fully); GRAPH-variable joins overwriting inner solutions instead of joining; a base-IRI resolution hole that five seemingly-unrelated test failures were hiding in.Decisions actioned in this PR
D-2 (
GRAPH ?ggoes W3C-by-default) — actioned by pr-g1.GRAPH <iri> { ... }returns no results unless preceded byFROM NAMED <iri>— every named graph must be explicitly enumerated in the dataset clause #1279 extension as-is — rejected: it makesGRAPH ?gresults wrong per SPARQL (the default graph must not appear) and blocked ~14 W3C tests.GRAPH <iri> { ... }returns no results unless preceded byFROM NAMED <iri>— every named graph must be explicitly enumerated in the dataset clause #1279 history and the deviation from the audit's original seeding design (which regressedgraph-variable-scopewhen implemented as written) are documented in the component section.D-10b (multi-op UPDATE staging model) — actioned by pr-u2.
Vec<Txn>with sequential staging against an evolving novelty overlay, folded into ONE atomic commit — chosen; (2) a newUpdateRequestIR wrapper — rejected: ripples through every Txn consumer (JSON-LD lowering,pre_built_txn, Cypher) for no semantic gain; (3) N separate commits, one per operation — rejected: a mid-request failure would leave a partially-applied request durably committed, violating the atomicity a client sending one request expects.D-8 (TriG parser strategy) — partially constrained by pr-w15: TriG-star inputs get clean, construct-specific deferred errors that do not foreclose the adopted try-the-existing-
parse_trig_phase1-route-first plan for the harness's TriG needs.Wave 2 of the W3C SPARQL burn-down (4 components, ≈−31 direct + joint entries)
Stacks on the Wave-1 PR. This wave carries the two approved behavior-change decisions (D-2 GRAPH semantics, D-10 multi-op UPDATE) plus base-IRI resolution and Turtle-star ingest. Two components deliberately modify pinned engine semantics — flagged for 2-reviewer sign-off in their sections.
Components
1. Base-relative IRI resolution (
pr-base, −6 + joints). Extracts the Turtle parser's RFC 3986 resolver into dependency-freefluree_vocab::iri(behavior-identical delegation) and threads the queryBASEthrough lowering: constant IRIs in patterns/GRAPH/paths/templates/VALUES, relative PREFIX namespaces, and anIRI()/URI()constant fold — all at prepare time, eval path stays base-free (variable-argumentIRI()deliberately not resolved; documented). Shipsresolve_dataset_clause()for the future within-ledger FROM work without lifting the guard. The harness now supplies the query-document base, mirroring its data-side@base. This PR exists because the audit's "BUG-4" was refuted —graph-existactually failed on base resolution, exposing an ownership vacuum five tests were hiding in.2. GRAPH operator W3C conformance (
pr-g1, −14 + joints) — DELIBERATE SEMANTICS CHANGE (D-2), 2-reviewer sign-off requested.?gnow binds as an IRI term (was: string literal); unboundGRAPH ?gno longer enumerates the ledger-alias default graph (the intentional #1279 extension — removed; explicitGRAPH <alias>addressing kept; no toggle). Three pinning tests updated. Join semantics: seed-when-produced + join-at-merge (the audit's unconditional-seeding design was refuted by W3Cgraph-variable-scoperegressing — deviation documented);EncodedSid/EncodedLitextraction arms plus aGraphVarCorrelatedEXISTS fallback (#1443 — Semijoin hash keys can never match across encodings; the regression test uses the EXISTS/late-materialized shape that actually pins it). Adopts the residual-audit defects A3/A4 (subquery02/04). Does NOT close #1317 (distinct defect; see its issue comment). Changelog: queries relying on implicit default-graph enumeration underGRAPH ?gmust address the alias explicitly. FQL parity: three regression tests (sameGraphOperator).3. Multi-operation UPDATE requests (
pr-u2, −9) — closes #1438 (D-10). Request-level;loop with accumulating prologue (one trailing;legal; empty/prologue-only request = valid no-op); cross-op blank-node label reuse is a parse error; sequential staging within ONE atomic commit: each op's WHERE sees the previous ops' effects via a virtual-commit overlay, folded last-wins over the original base — the single-op path delegates unchanged. Replaces Wave-1's loud-reject interim guard with real support. Decision transparency (D-10b):Vec<Txn>sequential staging was chosen over a new UpdateRequest IR and over N separate commits (atomicity per the SPARQL update-request semantics); options and rationale in the description body and ROADMAP §4.insert-05a+ the same-bnode trio remain registered — their requests end inDROP GRAPH(Wave-3 PR-U3 territory). Benches: parse entry + commit path within noise (transact_commitmarginally faster).4. Turtle-star ingest, asserting forms (
pr-w15, −2 + re-baseline). Reified triples (<< s p o ~ r >>) and annotation blocks ({| |}) in Turtle data now lex/parse and emit byte-identical flakes to the JSON-LD@annotationpath via the sharedEdgeKey::to_reifies_facts_jsonld_compatibleencoder (the full-variant alternative would have emitted orphan flakes under cascade retracts — adversarial-verification catch). Fresh reifier per anonymous occurrence, never deduplicated by EdgeKey (pattern-3-nomatchis green precisely because two anonymous occurrences don't join); equivalence tests sit next toedgekey_roundtrip_*.<<( )>>triple terms and TriG-star get clean, specific deferred errors (D-8-compatible). Documented divergence: Fluree's edge-annotation model asserts the base triple of a reified statement; RDF 1.2's non-asserting semantics belong to the Option-1 epic. The 39 remaining eval-triple-terms entries were re-baselined against their REAL post-ingest errors (15 wave-2 syntax / 10 D-1 data / 5 serialization / 5 TriG / 2 harness / 2 misc). Import benches: 6-round interleave, all within budget (a 3-round phantom +11.5% dissolved at 6 rounds).Integration notes
The wave-2 fixpoint commit prunes 46 tests that green only in integration — the BASE+G1 joint entries (
pp34/pp35,exists03), the G1-gated algebra/optional-complextests, and the eq-graph second-lander interplay — all resolved by the both-way gate.pr-u2's cross-op walker was migrated to theAnnotationUnitAST during integration.Verification
Full W3C suite 36/36, 0 failed, 0 stale; merged-crate tests green (
fluree-db-sparql1178 incl. integration-migrated tests, transact, turtle, query); JSON-LD groups green; fmt + clippy clean.Issues closed when merged: #1438 (fully), #1442, #1443.
Performance notes (per component)
Base-IRI resolution (pr-base): all resolution happens at lowering/preparation on constant IRIs — the evaluation path stays completely base-free, by design: variable-argument
IRI()is deliberately NOT resolved (documented partial-spec choice; no W3C test exercises it) precisely so no per-row resolution exists anywhere. The resolver extraction intofluree_vocab::iriis behavior-identical delegation for the Turtle parser (its tests pin this).GRAPH conformance (pr-g1): every fix is plan/seed/materialization-time —
?gterm-kind at binding materialization, enumeration-set construction at plan time, seed-when-produced decided from the subplan's produced-variable set, and theGraphVarCorrelatedEXISTS fallback selected at strategy-choice time (its per-row evaluation applies only to a shape that previously returned silently-wrong empty results). BSBM: q3 −1.4%, q5 −1.0%, q9 +1.2%, bi/f2 −0.7% — noise-level, as predicted (BSBM never instantiates GRAPH; run for the shared context helpers).Multi-op UPDATE (pr-u2): the single-operation path delegates to the existing code byte-identically — multi-op machinery engages only when a second operation exists. Touches the shared parse entry and the commit path, so both were measured:
query_hot_bsbmq3 537→528 / q5 680→676 / q9 952→961 µs (noise);transact_commitpopulated 314.3→304.7 µs (marginally faster).Turtle-star ingest (pr-w15) — import-hot lexer: star detection costs at most one extra peek on
</{/~; a byte-identical assertion over a star-free corpus pins that non-star lexing is unchanged. Interleaved A/B, 6 rounds: turtle 10txn_10nodes +0.84% (a 3-round phantom reading of +11.5% dissolved at 6 rounds — worth remembering when reviewing bench claims on this box), turtle 100nodes +2.87%, jsonld −0.5/−1.0%, import_bulk −7.5/−22% (noise-wide) — all within the 5% budgets. Flake emission reuses the existingEdgeKey::to_reifies_facts_jsonld_compatibleencoder — no new storage shapes, no index changes.Issues closed on merge
Closes #1438
Closes #1442
Closes #1443
Mechanics note: these keywords fire when this PR merges into the default branch — in the stacked flow, after #1437 and the prior waves merge and GitHub auto-retargets this PR to
main. #1317 is deliberately NOT closed by this PR (distinct defect class — see the cross-reference comment on that issue).