Skip to content

fix: end-to-end named-graph support — TriG/SPARQL ingest and GRAPH queries - #1292

Merged
bplatz merged 7 commits into
mainfrom
fix/trig
Jun 9, 2026
Merged

bplatz merged 7 commits into
mainfrom
fix/trig

Conversation

@bplatz

@bplatz bplatz commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Completes named-graph support across the write and read paths.

Write / ingest

Read / query

In single-db mode every graph of a ledger shares one snapshot/overlay partitioned by g_id, so resolution reads the snapshot's graph registry directly — no dataset is constructed, and queries that contain no GRAPH block are unaffected. The ledger alias keeps precedence for the default graph (so a registered graph whose IRI equals the ledger id can't shadow it), and reserved system graphs (txn-meta, config) stay private. Bound GRAPH ?g now also accepts IRI-typed terms, so VALUES ?g { <iri> } resolves named graphs.

This covers the ledger-scoped query endpoint, MCP sparql_query, and the library query() path. Connection-scoped FROM <ledger> GRAPH resolution is a planned follow-up.

bplatz added 4 commits June 4, 2026 17:30
The TriG parser shared by the `/v1/fluree/upsert` endpoint and the bulk
`import_trig_commit` path (both via `parse_trig_phase1`) only recognized the
SPARQL-style keyword form `GRAPH <iri> { ... }`. The W3C-compliant compact form
`<iri> { ... }` — what rdflib, Apache Jena, and RDF4J emit by default — was
rejected: the graph-block detection gate keyed off the literal "GRAPH" substring,
and `parse_statement` routed a bare IRI/prefixed-name to a default triple, so the
block leaked into the reconstructed Turtle and surfaced as a misleading
"expected predicate, found LBrace" error downstream.

Fix:
- `might_contain_graph_block` now also triggers on a `{` (every graph block has
  one; a `{` in plain Turtle can only be inside a string literal, which
  round-trips unchanged through the parser).
- `parse_statement` routes a leading IRI/IriEscaped/PrefixedName/PrefixedNameNs
  followed by `{` to the graph-block parser (the `GRAPH` keyword is optional per
  the TriG grammar; the keyword arm now consumes the keyword itself).
- The two remaining unhandled brace forms — anonymous `{ ... }` and blank-node
  labels `_:b { ... }` — now return a clear, actionable error instead of
  silently mis-parsing.

Closes #1278.
Per SPARQL 1.1 Update §3.1.1, `QuadData` admits `QuadsNotTriples`
(`GRAPH VarOrIri '{' TriplesTemplate? '}'`), but the update parser only handled
the plain `TriplesTemplate` form and returned 400 ("expected subject in quad
data") on a GRAPH block. This blocked any RDF4J client writing to a named graph,
since `SPARQLConnection.add(stmts, context)` emits
`INSERT DATA { GRAPH <ctx> { ... } }`.

The named-graph machinery already existed for DELETE/INSERT ... WHERE (Modify):
`QuadPatternElement::Graph`, `TemplateGraphIds`, and `graph_delta`-driven
staging. INSERT/DELETE DATA simply bypassed it. This wires it in:

- QuadData now carries `Vec<QuadPatternElement>` (was triples-only), so it can
  represent GRAPH blocks alongside default-graph triples.
- parse_quad_data dispatches on the GRAPH keyword to the shared graph-block
  parser, mirroring parse_quad_pattern.
- The validator walks graph blocks, keeps the ground-only constraint, and
  rejects a variable graph name (DATA must be ground).
- lower_insert_data / lower_delete_data route through
  lower_quad_pattern_to_templates with a TemplateGraphIds, producing
  graph-tagged templates and a graph_delta that registers the named graph.
  The now-redundant lower_triples_to_templates is removed.

Covered by parser, validator, and lowering unit tests plus end-to-end
named-graph INSERT DATA / DELETE DATA integration tests.

Closes #1288.
…ulator

`Flake`'s `Eq`/`Hash` intentionally ignore the graph component `g`, and the
`FlakeAccumulator` keyed its dedup directly on `Flake`. So within a single
transaction the same `(s,p,o,dt,m)` written to two different graphs collapsed
into one bucket:

- INSERT of the same triple into the default graph and a named graph kept only
  one flake (the other graph's copy was silently dropped).
- DELETE of the same triple from two graphs retracted only one.
- An assertion in one graph and a retraction of the same fact in another graph
  cross-cancelled (1:1) and both vanished.

Nest the accumulator maps by `Option<Sid>` (the graph; `None` = default graph),
so dedup and 1:1 cancellation are scoped to a single graph. Single-graph
transactions are unchanged (one outer entry, identical clone profile — only a
cheap `Sid` clone per push to key the outer map).

Surfaced while verifying #1288 (SPARQL INSERT/DELETE DATA named graphs).
Cross-transaction novelty was already graph-partitioned, so this only affected
multi-graph writes within one transaction.

Tests: accumulator unit tests for per-graph dedup, non-cancellation across
graphs, and cancellation within a graph; end-to-end named-graph tests for
same-triple-in-two-graphs INSERT and DELETE in one transaction.
On the ledger-scoped query endpoint, GRAPH <iri> / GRAPH ?g returned empty
unless the caller also listed each graph in FROM NAMED. In single-db mode the
GraphOperator only matched the ledger alias and ignored the user named graphs
already registered in the snapshot.

Resolve user named graphs (g_id >= FIRST_USER_GRAPH_ID) directly from the
active snapshot's graph registry. All graphs of a ledger share one
snapshot/overlay partitioned by binary_g_id, so no DataSet is built and
non-GRAPH queries are unaffected. The ledger alias keeps precedence for the
default graph, and reserved system graphs (txn-meta, config) stay private.
Also accept IRI-typed ?g bindings (Sid/Iri/IriMatch) so VALUES ?g { <iri> }
resolves named graphs.

Covers the ledger-scoped endpoint, MCP sparql_query, and the lib query() path.
Connection-scoped FROM <ledger> is deferred.
@bplatz
bplatz requested review from aaj3f and zonotope June 5, 2026 01:53
… dirs

derive_session_dir keys import scratch space on {alias, session_id} only,
and session_id() was effectively just a nanosecond timestamp (the
seed ^ (seed >> 64) xor-fold is a no-op for sub-2^64 nanos). Two concurrent
imports of the same ledger alias that landed in the same nanosecond bucket
shared one run_dir/remap_dir. Their parallel subject/string vocab merges then
File::create(truncate)'d the same mmap'd .rmp files the other was mapping,
yielding a length-0 mmap with len > 0 and panicking in vocab_merge.rs
("range end index 8 out of range for slice of length 0").

Combine nanos, process id, and a per-process atomic counter so no two live
imports can collide, across processes (nextest workers) or within one.
Base automatically changed from fix/langstring-novelty-dedup-1273 to main June 5, 2026 18:03

@zonotope zonotope 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.

🧔🏾

/// reserved for the default graph and never resolves here, even if a
/// registered graph shares the ledger's IRI.
pub fn single_db_user_graph_id(&self, iri: &str) -> Option<GraphId> {
if self.dataset.is_some() || iri == self.active_snapshot.ledger_id.as_str() {

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.

probably not for this pr, but explicit checks for dataset mode (or any other "queryable" type) suggests that we could benefit from a trait here.

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.

Created issue #1304 to track it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants