Skip to content

feat: edge annotations and GRAPH blocks in CONSTRUCT templates - #1948

Merged
bplatz merged 4 commits into
mainfrom
feat/construct-annotations-graph
Sep 29, 2026
Merged

bplatz merged 4 commits into
mainfrom
feat/construct-annotations-graph

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

CONSTRUCT templates can now write RDF 1.2 edge annotations and write into named graphs, in both SPARQL and JSON-LD queries. Every output format writes the annotations. A template with GRAPH blocks returns a dataset in TriG, N-Quads or JSON-LD.

This also lifts the known limitation in #1934: Graph Store GET now returns edge annotations, so a GET followed by a PUT of the result keeps them.

Template forms

Edge annotations. Two SPARQL forms, both allowed inside GRAPH blocks:

  • An annotation tail: ?s ?p ?o ~ ?r and an optional {| ... |} body.
  • The reifies form: ?r rdf:reifies <<( ?s ?p ?o )>>.

JSON-LD puts @annotation on the object, the same way a transaction writes an annotation.

# Carry each edge's stored reifiers into the result
CONSTRUCT { ?s ex:worksFor ?o ~ ?r }
WHERE { ?s ex:worksFor ?o  OPTIONAL { ?r rdf:reifies <<( ?s ex:worksFor ?o )>> } }

# Describe each edge with a new reifier for each row
CONSTRUCT { ?s ex:worksFor ?o {| ex:source ex:hrExport |} }
WHERE { ?s ex:worksFor ?o }
  • A reifier variable that a row leaves unbound attaches nothing, and the triple is still written.
  • These three mint a fresh blank node for each row, like [ ]:
    • a bare ~,
    • an anonymous {| |},
    • ~ _:r.
  • The CONSTRUCT WHERE shorthand keeps the edge annotations in its WHERE clause.

Named graphs. GRAPH <iri> { ... } or GRAPH ?g { ... } in the template. In JSON-LD it's ["graph", name, node-map, ...], the form a where clause already uses. Apache Jena ARQ supports the same extension.

CONSTRUCT { GRAPH ?g { ?s ?p ?o } } WHERE { GRAPH ?g { ?s ?p ?o } }

A row that leaves the graph variable unbound writes nothing.

Output

Format Annotations Named graphs
Turtle o ~ r error
TriG (new) o ~ r GRAPH <g> { ... }
N-Triples r rdf:reifies <<( s p o )>> . error
N-Quads (new) r rdf:reifies <<( s p o )>> <g> . fourth term
JSON-LD @annotation {"@id": g, "@graph": [...]} nodes
RDF/XML rdf:annotation / rdf:annotationNodeID attributes (RDF 1.2) error
  • A reifier whose triple isn't in the result is written as r rdf:reifies <<( s p o )>>. Turtle, TriG, N-Triples and N-Quads all use this form, as fluree export does. RDF/XML has no way to write it and returns an error.
  • Server negotiation:
    • A query whose template has GRAPH blocks negotiates only TriG, N-Quads and JSON-LD.
    • An Accept header that admits only Turtle, N-Triples or RDF/XML gets a 406.
    • Everything else still gets all six formats.
    • The API returns an error that names the formats to use if a triples-only format is requested for a dataset.

Graph Store GET

  • When the ledger has ever stored an annotation, GET uses { ?s ?p ?o } UNION { ?r rdf:reifies <<( ?s ?p ?o )>> } so that reifier links come back.
    • The ledger flag it checks is monotonic.
    • It's checked again after the query, so an annotation committed while the query runs isn't missed.
  • Ledgers without annotations keep the plain query. The UNION costs about 25% on the default graph even when nothing matches.
  • UNION rather than OPTIONAL: on a named graph, OPTIONAL measured 225 ms against 40 ms for UNION.
  • Every GET runs an ASK through the query route first (named graphs already did), so authentication and read policy answer before the annotation check loads the ledger. For the default graph that's one extra query per GET; the bench scenarios time the CONSTRUCT queries directly, so they don't include it.

Performance of queries that don't use this

  • SELECT and other non-CONSTRUCT queries: unaffected. The engine and SELECT output are unchanged.

  • Plain CONSTRUCT: measured on the second commit, before the review fixes; not re-measured since. Allocations matched the base except one string per graph in the Turtle writer, which the review fixes removed. Timings, median of 6 rotated rounds on the 48k-row query_hot_construct_formats scenarios:

    Turtle RDF/XML N-Triples JSON-LD
    vs base +2.0% +3.5% +3.0% +1.0%

    Round-to-round spread was about 1–2%.

  • The first version measured +14% on Turtle and RDF/XML. HashMap::remove hashes the whole triple even on an empty map. The second commit skips that lookup when there are no annotations, and gives templates without annotations or GRAPH blocks a direct path into the default graph.

Implementation

  • fluree-db-query:
    • ConstructTemplate gains graphs (parallel to patterns, empty when no pattern names a graph) and reifications: Vec<TemplateReification>.
    • patterns, graphs and reifications are private and change only through push_pattern and push_reification, so they can't fall out of step. Readers use patterns(), reifications() and graph(i).
    • The JSON-LD parser and lowering handle @annotation and ["graph", ...].
    • Datalog rule heads reject templates that name a graph or annotate an edge.
  • fluree-db-sparql: the AST template carries graphs; the parser accepts GRAPH blocks and rejects nested ones; lowering handles annotation tails and the reifies form.
  • fluree-graph-ir: new Dataset (default graph plus named graphs), and Graph::reifiers_by_triple.
  • fluree-graph-format: writers for TriG and N-Quads, reifiers in Turtle and N-Triples, and format_jsonld_dataset. API change: format_jsonld and format_jsonld_dataset return Result<_, LiteralAsNode>; a literal subject, graph name or reifier is an error instead of a panic.
  • fluree-db-api:
    • instantiate_construct_graph returns a Dataset.
    • New OutputFormat::TriG and OutputFormat::NQuads.
    • RDF/XML writes annotation attributes (rdf:annotation / rdf:annotationNodeID, RDF 1.2 XML Syntax §2.20), with blank-node labels encoded as for rdf:nodeID.
    • New Fluree::has_annotations.
  • fluree-db-server:
    • GraphFormat gains TriG and NQuads, and negotiate_graph_format takes the set of formats allowed.
    • The Graph Store read builds the annotated query.
    • The no-Accept JSON-LD default respects the allowed formats.
  • Docs: the CONSTRUCT page gets new sections on named graphs and annotations in the template. docs/contributing/benches.md lists the new bench scenarios. These pages are updated:
    • output formats,
    • Graph Store,
    • endpoints,
    • headers,
    • edge annotations,
    • SPARQL,
    • Turtle,
    • compatibility,
    • multi-query.

Not supported

  • GRAPH blocks can't nest, and the CONSTRUCT WHERE shorthand has no GRAPH form (per SPARQL 1.1).
  • A triple term in a template is accepted only as the object of rdf:reifies. Nested triple terms and property paths inside an annotation block are rejected.
  • ?r rdf:reifies <<( s p o )>> in a template also writes s p o, as every Fluree write form does: Fluree reifies asserted edges only.

Testing

  • API integration (it_query_construct.rs, module annotations_and_graphs, 10 tests):
    • annotations reach every output format;
    • annotation blocks write their bodies;
    • the reifies form and the annotation tail produce the same output;
    • GRAPH blocks produce a dataset, and a graph variable copies named graphs;
    • SPARQL/JSON-LD twin tests for annotations, anonymous annotation blocks, and graph templates;
    • trig_dataset_round_trips_through_upsert: a default graph and two named graphs, with annotations and annotation bodies, go through CONSTRUCT → TriG → upsert into a fresh ledger and come back unchanged.
  • Datalog rules (it_datalog_rules_sparql.rs): a rule head that annotates an edge or names a graph is rejected.
  • Unit tests:
    • Turtle reifier placement, with a round trip through the Turtle parser;
    • N-Triples rdf:reifies lines;
    • TriG and N-Quads datasets;
    • JSON-LD @annotation;
    • blank-node labels shared across named graphs;
    • RDF/XML annotation attributes, including reifier labels that aren't XML names;
    • JSON-LD refuses a literal subject, graph name or reifier;
    • SPARQL lowering of GRAPH blocks (including a template that starts with one) and of annotations;
    • server format negotiation.
  • HTTP:
    • graph_store_http::annotated_graphs_round_trip: default and named graphs; GET returns the annotations, and a PUT of the result makes no commit.
    • construct_graph_template_negotiates_dataset_formats.
    • graph_store_http::an_unauthenticated_read_does_not_load_the_ledger: with auth required, an anonymous GET of the default or a named graph gets a 401 and leaves the ledger unloaded.
  • Non-vacuous checks:
    • The round-trip test fails when construct_graph is forced to the plain template.
    • The integration tests caught a push_pattern bug that dropped the graph when the first pattern had one.
    • The TriG round trip fails when the TriG writer drops annotations inside GRAPH blocks.
    • The RDF/XML label test, the unauthenticated-read test and the Accept default test each fail with their fix reverted.
  • Bench: query_hot_construct_formats adds Graph Store scenarios (plain vs UNION, default and named graph, with and without annotations).

@bplatz bplatz added enhancement New feature or request area:sparql SPARQL/Turtle/TriG/JSON-LD parsing, lowering, UPDATE semantics, W3C conformance area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph area:query Query execution, planning, fast paths, overlay, result formatting labels Sep 25, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 25, 2026 20:16
@bplatz
bplatz added this pull request to stack #1947 September 25, 2026 20:16
@bplatz
bplatz force-pushed the feat/construct-annotations-graph branch from 3f6eb5f to a2a416e Compare September 26, 2026 11:24

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

@bplatz this is good and a nice stacked follow-up to the rest of the stack. Claude helped me find some items below you'll likely want to consider carefully and in advance of merge, but the one item I wanted to surface headline was that--given some of our conversations around "making invariant conditions compile-time/structural guarantees rather than convention guarantees"--it seems that for the 3 collections on ConstructTemplate (patterns, graphs, reifications), it's only push_pattern that guarantees invariant preservation. Desync failure could fail either silently or with a panic. The PR even mentions such an exact such bug was fixed mid-development during the work on this effort. Worth probably making it structurally impossible to violate this (now rather than later if later code re-enables that possibility). Full review below:


I want to lead with how much of this stood up, because I went at it hard and most of it didn't move. The parity story is clean: every non-exempt form has both front ends and a twin test, and the call to leave ?r rdf:reifies <<( … )>> SPARQL-only is right — it's a triple term, which the parity guideline exempts as RDF-star, while ~ / {| |} / @annotation are the edge-annotation surface that has always had a JSON-LD twin. The abstraction work is the repo's instinct applied properly: graphs and TemplateReification reuse Ref, Dataset composes Graph rather than duplicating it, and three helpers got extracted and shared — parse_graph_block_start now serves WHERE, CONSTRUCT and UPDATE and deletes the copy that was living in update.rs. And the perf commit's diagnosis is exactly right; I reproduced it with a counting BuildHasher on the pinned toolchain — over 1000 calls on an empty map, get builds 0 hashers and remove builds 1000. That's a genuinely non-obvious find.

I also specifically chased the language-tag class from #1940 through every new writer path, since a PR adding six serialization paths is where that would recur. It's closed — every new path routes through push_iri_ref/escape_iri, PrefixMap::push_iri, push_blank or push_quoted, and check_lang_tags now chains graph.reifications(). A graph name of http://example.org/g}\n<urn:x> <urn:y> <urn:z> .\nGRAPH <urn:evil> { came out fully escaped in both TriG and N-Quads, and neutering the lang-tag chain turned invalid_language_tag_is_refused_not_written red with the real injection payload. Nice.

Two things I'd like fixed before this lands.

fluree-db-api/src/format/rdf_xml.rs:174 and :184 — the rdf:annotationNodeID arms call escape_attr_into where every other blank-node attribute in the file calls push_node_id. No breakout (the escaper does handle "), but no XML-Name normalization either, so the same blank node is written under two labels. A reifier bound to a stored label like old/ledger:1 emits rdf:nodeID="x6f6c…" on the subject and rdf:annotationNodeID="old/ledger:1" on the annotation — the first is hex-encoded, the second isn't an XML Name at all, and the document is rejected. With café it's worse in a quieter way: it parses, and the annotation now points at a blank node nothing else describes. Your own doc comment on push_node_id names both trigger classes ("ids minted by old imports contain / and :, and a Turtle label may start with a digit"). Turtle and N-Triples get this right via push_blank; it's RDF/XML only. Swapping the helper in both arms is the fix, plus a legacy-shaped label in rdfxml_reifiers_use_annotation_attributes.

fluree-db-server/src/routes/graph_store.rs:295 — has_annotations() touches the ledger before the caller is authenticated. Scope first, because it changes the urgency: this only affects servers running DataAuthMode::Required, and the default is None (config.rs:53-56). So it's "fix before someone turns auth on", not a live incident. On such a server, though: for a plain GET of the default graph the :260 guard is skipped, so this is the first thing to hit the ledger, and it resolves through ledger_cached → LedgerManager::get_or_load — a real storage load and cache fill, then a snapshot() whose compact_if_needed can escalate to the state write lock. An anonymous GET /v1/fluree/data/<any-ledger>?default does all that before the 401. Nothing leaks and there's no existence oracle (the unwrap_or(false) sees to that), so this isn't an auth bypass — but it's unauthenticated work on a named resource, it's amplifiable, and it sits against your own module docstring at :9 ("so auth and read policy apply") and against ~20 sibling handlers that all carry the DataAuthMode::Required && bearer.is_none() early-out. Your comment does flag the ordering, but reasons only about the failure path; it's the successful probe's side effects that are the gap. Running the existing ASK probe for the default graph too, and moving has_annotations below it, would fix it and delete the :260 special case at the same time.

Then a handful I'd like considered but wouldn't hold the PR for: the second probe at :298 uses ? where the first uses unwrap_or(false), so a transient error there discards a good 200 you're already holding; the rdf:reifies template form also asserts its base triple (lower/construct.rs:125), which may well be deliberate but isn't in Current Limitations — and it's why the writers' unasserted-reifier paths are unreachable from any query; and docs/api/graph-store.md:74 describes the annotation cost as "a lookup per annotation", where your own number is ~25% of the whole read with zero matches, on a ledger-wide bit that never clears. I verified the monotonicity claim end to end, including the full-rebuild path at root_assembly.rs:302 that derives it from the predicate dictionary — it holds, which is what makes the "forever" worth writing down.

On performance: I'd stop short of calling the +2–3.5% on Turtle/N-Triples/RDF-XML noise. There are three identifiable sources left — the Chain in check_lang_tags, the per-graph format! at rdf_text.rs:154 (which also means allocations aren't quite byte-identical to base — the base pushed a &'static str there), and the end_line closure's per-triple branch. All cheap to reclaim if you want the number back to flat.

Two last things, neither a criticism of the testing, which is otherwise thorough.

The structural reason CRITICAL-1 got through: nothing in-repo parses this writer's output back. Turtle has two round-trip tests; RDF/XML has no reader at all, and TriG/N-Quads have no GRAPH-aware parser to round-trip against. Standing gap worth knowing for anything touching those writers. Relatedly, and cheap for you to answer in one line — I couldn't confirm rdf:annotation / rdf:annotationNodeID are the correct RDF 1.2 RDF/XML attribute names. docs/concepts/edge-annotations.md:30 spells out the accepted annotation form for Turtle, N-Triples, TriG and N-Quads and names no RDF/XML form at all, so it's the one serialization with no provenance in the corpus. A spec section or another implementation that emits them settles it, and is worth adding to that table either way.

And a process note. This PR's base is fix/branch-from-empty-ledger, so merging today lands it on #1945's branch rather than main. The declared stack isn't real in either direction: compare(1945head...1948head) is diverged ahead=2 behind=1 and compare(1944head...1948head) is diverged ahead=2 behind=4 — this tree contains neither #1945's fix nor #1944's commits, while the body says "Stacked on #1945". A reviewer who takes that at face value will assume the 400-not-500 work is present in what they're reading. Since git merge-base puts all three at ffeeec554 and there's zero code-file overlap between them, re-targeting to main and dropping the line costs nothing. The genuine ordering constraint is docs: docs/api/endpoints.md is edited by all three and docs/api/headers.md by #1944 and this one, so second and third to land will need those resolved by hand — that's the whole of it, and it replaces the dependency story rather than adding to it.

Adherence to repo commitments

  • Patterns / abstractions — ✔ extends the shared IR rather than paralleling it (Ref reused for both new fields, GraphName reused in the AST, Dataset composing Graph), and three helpers were shared rather than copied. ⚠️ the three parallel pub collections on ConstructTemplate keep an invariant by convention that a desync bug has already tested once.
  • Performance (speed first, memory second) — ⚠️ no regression on SELECT, on any non-CONSTRUCT query, or on plain CONSTRUCT → JSON-LD, all confirmed by reading the per-row work. A real but small residual remains on the text formats with three named mechanical sources. The Graph Store GET path takes a deliberate ~25% on annotated ledgers, permanently and ledger-wide, which is a sound design given a monotone bit but is under-described in the docs. regression-budget.json is consistent — the PR adds scenarios to an existing target, not a new [[bench]].
  • Testing — ✔ broad and mostly non-vacuous: all four touched test files confirmed wired into their grp_* targets, nine new API integration tests plus unit and HTTP coverage, and the round-trip test verified to fail when construct_graph is forced to the plain template. ✖ the gap is output parsing — no reader exists for RDF/XML, TriG or N-Quads, which is what let CRITICAL-1 through.
  • Conventions — ✔ self-describing subjects, unusually good commit bodies (the HashMap::remove explanation in a2a416e39 is exactly the right level of detail), nine docs pages updated alongside. CI green on a2a416e39 (the cancelled duplicate run is a superseded earlier trigger; the test job that succeeded started later, at 11:26 vs 11:25). ⚠️ docs/contributing/benches.md:223 not updated, and ir/adapters.rs / ir/path.rs are unrelated refactors riding along.

Requesting changes on the two above — both are small, and everything else here is genuinely strong work. Happy to talk through any of it, especially the rdf:reifies assertion question, where I may well be reading the intent wrong.

Not anchorable inline (no line of this diff to attach them to):

docs/contributing/benches.md:223 — the hand-maintained row for query_hot_construct_formats.rs still says "JSON-LD, RDF/XML, Turtle and N-Triples" with no mention of the new Graph Store scenarios or TriG/N-Quads. The file itself warns "nothing enforces this table, so it is the one that rots."

  • Scope creep — fluree-db-query/src/ir/adapters.rs and ir/path.rs are struct-literal dedup refactors unrelated to CONSTRUCT. They're semantics-preserving as far as I can tell; they just make a 2350-line diff harder to read.
  • The base pointer means "merge" doesn't put this on main. #1948's base is fix/branch-from-empty-ledger (#1945's branch), so merging today lands these two commits there. And the declared stack isn't real in either direction: compare(1945head...1948head) is diverged ahead=2 behind=1 and compare(1944head...1948head) is diverged ahead=2 behind=4, so this tree contains neither #1945's fix nor #1944's four commits, while the body says "Stacked on #1945". A reviewer who believes that line will assume the 400-not-500 work is present in what they're reading; it isn't. Worth dropping or rewording the line and re-targeting to main — the license to do that is that there is zero code-file overlap with either PR (git merge-base puts all three at ffeeec554). The real ordering constraint is the next bullet, and it replaces the dependency story rather than adding to it.
  • The actual merge-order constraint is docs, not code. docs/api/endpoints.md is edited by all three PRs and docs/api/headers.md by #1944 and this one, so whichever lands second and third will need those resolved by hand. Nothing else in the cluster collides.
  • No test parses the new dataset output back. datasets_as_trig_and_nquads (rdf_text.rs:588-622) asserts exact strings only. Turtle has two real round-trip tests; TriG and N-Quads have none, and fluree-graph-turtle's parser has no GRAPH support to round-trip against. That absence is precisely why CRITICAL-1 survived — there's no RDF/XML reader in-repo either. A GET→PUT test for a GRAPH-template result, mirroring annotated_graphs_round_trip, would close both.

accept: Option<&str>,
allowed: &[GraphFormat],
) -> Option<GraphFormat> {
let Some(accept) = accept.filter(|a| !a.trim().is_empty()) else {

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.

fluree-db-server/src/extract/headers.rs:166 — an absent or blank Accept short-circuits to GraphFormat::JsonLd before the allowed.contains(f) filter at :180. Harmless today since JSON-LD is in all three lists, but a future allowed without it would silently return a disallowed format.

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.

Fixed in d3e8033. The no-Accept default now goes through the same allowed filter, so it returns None when JSON-LD isn't allowed. graph_format_negotiation_follows_q covers it and fails without the change.

Comment thread fluree-graph-format/src/jsonld.rs Outdated
let mut node = Map::new();
node.insert(
"@id".to_string(),
JsonValue::String(term_to_subject_key(name, config, &mut bnode_renamer)),

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.

Commenting at this new call site; the function itself is jsonld.rs:518, which is not in the diff. term_to_subject_key term_to_subject_key panics on a literal, and is newly reached from :278 (named-graph @id) and :350 (reifier). Not reachable from CONSTRUCT (both positions map Binding::Lit → None and skip the row at construct.rs:349-352), but these are pub fns taking any Term. RDF/XML returns a FormatError for the same case at rdf_xml.rs:188-192; matching that would be more consistent than a panic in a formatter.

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.

Fixed in d3e8033. term_to_subject_key returns an error instead of panicking, so format_jsonld and format_jsonld_dataset now return Result<_, LiteralAsNode>. That also removes the older panic on a literal subject. The API callers map it to FormatError::InvalidBinding, as RDF/XML does. New test: a_literal_node_is_refused (subject, reifier and graph name).

}
for r in &template.reifications {
let reifier = slot_of(&mut terms, &r.reifier, Position::Subject)?;
patterns[r.triple].2.push(reifier);

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.

fluree-db-api/src/format/construct.rs:120 — patterns[r.triple] panics on an out-of-range reification index rather than erroring. patterns.get_mut(r.triple) with a FormatError is a one-line hardening in a path where a panic is a server-side abort on a query.

  • fluree-db-query/src/ir/query.rs:34,47,51 — the three parallel collections are pub with push_pattern as the only invariant-preserving mutator. Given the body records that a desync bug was already found once here, private fields with accessors — or at minimum a debug_assert!(self.graphs.is_empty() || self.graphs.len() == self.patterns.len()) — would make the invariant structural.

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.

Took the structural option (d3e8033). patterns, graphs and reifications are private now and change only through push_pattern and a new push_reification, which asserts the index names an existing pattern. Readers use patterns(), reifications() and graph(i).

So patterns[r.triple] here can't be out of range, and I left it as an index rather than adding an error path that can't fire.

@bplatz
bplatz force-pushed the feat/construct-annotations-graph branch from a2a416e to cfea0de Compare September 28, 2026 23:57
Base automatically changed from fix/branch-from-empty-ledger to main September 29, 2026 00:30
CONSTRUCT templates can now carry RDF 1.2 annotations and write into named
graphs, on both query surfaces:

- SPARQL: an annotation tail on a template triple (`?s ?p ?o ~ ?r`, with
  an optional `{| ... |}` body; a bare block or blank reifier mints a
  fresh blank node per row), `?r rdf:reifies <<( s p o )>>`, and
  `GRAPH <iri>` / `GRAPH ?g` blocks (an extension, as in Jena ARQ). The
  CONSTRUCT WHERE shorthand keeps its WHERE clause's annotations.
- JSON-LD `construct`: `@annotation` on an object (without an `@id` it
  mints a fresh reifier per row) and `["graph", <iri or ?var>, ...]`
  blocks, which a template used to drop silently.

The template IR records each pattern's graph and its reifier
attachments; instantiation builds a `Dataset` (default graph plus named
graphs, each with its attachments). Every writer carries annotations:
`o ~ r` in Turtle, `r rdf:reifies <<( s p o )>>` in N-Triples, the RDF
1.2 `rdf:annotation` attribute in RDF/XML, `@annotation` in JSON-LD.
New TriG and N-Quads writers carry named graphs, as does JSON-LD
(`{"@id": g, "@graph": [...]}`). Over HTTP, `application/trig` and
`application/n-quads` join the Accept negotiation, and a template with
GRAPH blocks negotiates only among TriG, N-Quads and JSON-LD (406
otherwise). A SPARQL datalog rule whose head annotates or names a graph
is rejected.

The Graph Store GET now returns a graph's annotations, so an annotated
graph read and PUT back commits nothing. The lookup runs only on a
ledger that has held annotations, as a UNION branch rooted at
rdf:reifies (an OPTIONAL probing every triple was 5.5x slower inside a
named graph); the annotation flag is re-checked after the query, since
a refresh or commit can bring a ledger's first annotations into the
snapshot the query read.

Also: `ConstructTemplate::push_pattern` keeps pattern graphs aligned;
shared helpers for reifier lookup, fresh blank-node variables, graph
name parsing and property-path construction; the CONSTRUCT bench gains
Graph Store scenarios.
Turtle and RDF/XML hashed every triple into an empty reifier map
(HashMap::remove hashes before checking emptiness), and instantiation
routed every triple through the graph/reifier path. Templates without
annotations or GRAPH blocks now take a direct path.
@bplatz
bplatz force-pushed the feat/construct-annotations-graph branch from cfea0de to edfcb86 Compare September 29, 2026 00:30
- RDF/XML writes `rdf:annotationNodeID` through `push_node_id`, as it
  writes `rdf:nodeID`, so a blank-node reifier whose label is not an XML
  name names the node its description does.
- A Graph Store `GET` of the default graph runs the ASK probe too, so
  authentication answers before `has_annotations` loads the ledger. A
  failed second `has_annotations` check no longer discards the response.
- `ConstructTemplate`'s patterns, graphs and reifications are private and
  change only through `push_pattern` and `push_reification`, so they cannot
  fall out of step.
- JSON-LD formatting returns `LiteralAsNode` for a literal subject, graph
  name or reifier instead of panicking.
- The no-`Accept` JSON-LD default respects the allowed formats.
- The Turtle writer no longer allocates a continuation string per graph.
- Docs: the `rdf:reifies` template form asserts its triple; the Graph
  Store annotation cost; the RDF/XML attributes' spec section; the
  CONSTRUCT bench row.
@bplatz

bplatz commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Everything below is in d3e8033 unless noted; the three inline threads have their own replies.

RDF/XML rdf:annotationNodeID: both arms now use push_node_id. rdfxml_reifiers_use_annotation_attributes adds a reifier labelled old/ledger:1, which is also described as a subject, and one labelled 1. It asserts the annotation and the description carry the same encoded label. It fails with the old helper.

Graph Store has_annotations before auth: done as you suggested. The ASK probe now runs for the default graph too, and has_annotations comes after it, so the :260 special case is gone. The second check uses unwrap_or(false), so an error there no longer throws away a good response. New test an_unauthenticated_read_does_not_load_the_ledger runs with auth required. It disconnects the ledger, sends anonymous GETs of the default and a named graph, and asserts the 401 comes back with the ledger still unloaded. It fails with the old ordering.

rdf:reifies asserting its triple: deliberate. Fluree only reifies asserted edges, and every write form treats rdf:reifies <<( s p o )>> as asserting (edge-annotations.md). It's now listed under Current Limitations on the CONSTRUCT page.

RDF/XML attribute names: RDF 1.2 XML Syntax §2.20, "Annotating Triples: rdf:annotation or rdf:annotationNodeID" (Working Draft, 24 Sep 2026). rdf:annotationNodeID takes the same identifier as rdf:nodeID, which is why the helper mattered. The CONSTRUCT page cites it. I left it out of the edge-annotations.md table, since that table lists write surfaces and RDF/XML is output-only here.

Docs:

  • graph-store.md now gives the real annotation cost: about a quarter of the read, paid on every read once the ledger has held an annotation.
  • The benches.md row lists the Graph Store scenarios. The bench doesn't run TriG or N-Quads, so they aren't listed.

Perf residual: took the per-graph format! in rdf_text.rs, since it was the allocation the base didn't have. I left the Chain and the end_line branch alone and haven't re-measured.

Round trip for datasets: not added here. One correction on the gap: TriG does have a parser that understands GRAPH blocks in-repo (trig_meta.rs, used by upsert), so CONSTRUCT → TriG → upsert → compare is possible. RDF/XML still has no reader.

ir/adapters.rs / ir/path.rs: fair; they're unrelated cleanups that rode along, and I've left them in.

Base pointer and docs ordering: resolved. #1944 and #1945 have merged, this branch was rebased onto main, and the base is main.

Copies a default graph and two named graphs, each with an annotated edge,
through CONSTRUCT, writes the result as TriG, upserts it into a fresh
ledger and compares the N-Quads of both. It also checks the annotation
lines are present, so a writer that dropped them from both sides cannot
pass.
@bplatz
bplatz merged commit 0d3c857 into main Sep 29, 2026
16 checks passed
@bplatz
bplatz deleted the feat/construct-annotations-graph branch September 29, 2026 01:23
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 area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph area:sparql SPARQL/Turtle/TriG/JSON-LD parsing, lowering, UPDATE semantics, W3C conformance enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants