Repository navigation
feat: edge annotations and GRAPH blocks in CONSTRUCT templates - #1948
Conversation
3f6eb5f to
a2a416e
Compare
aaj3f
left a comment
There was a problem hiding this comment.
@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 (
Refreused for both new fields,GraphNamereused in the AST,DatasetcomposingGraph), and three helpers were shared rather than copied.⚠️ the three parallelpubcollections onConstructTemplatekeep 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 StoreGETpath 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.jsonis 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 whenconstruct_graphis 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::removeexplanation ina2a416e39is exactly the right level of detail), nine docs pages updated alongside. CI green ona2a416e39(the cancelled duplicate run is a superseded earlier trigger; thetestjob that succeeded started later, at 11:26 vs 11:25).⚠️ docs/contributing/benches.md:223not updated, andir/adapters.rs/ir/path.rsare 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.rsandir/path.rsare 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 isfix/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)isdiverged ahead=2 behind=1andcompare(1944head...1948head)isdiverged 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 tomain— the license to do that is that there is zero code-file overlap with either PR (git merge-baseputs all three atffeeec554). 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.mdis edited by all three PRs anddocs/api/headers.mdby #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, andfluree-graph-turtle's parser has noGRAPHsupport 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 aGRAPH-template result, mirroringannotated_graphs_round_trip, would close both.
| accept: Option<&str>, | ||
| allowed: &[GraphFormat], | ||
| ) -> Option<GraphFormat> { | ||
| let Some(accept) = accept.filter(|a| !a.trim().is_empty()) else { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| let mut node = Map::new(); | ||
| node.insert( | ||
| "@id".to_string(), | ||
| JsonValue::String(term_to_subject_key(name, config, &mut bnode_renamer)), |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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 arepubwithpush_patternas 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 adebug_assert!(self.graphs.is_empty() || self.graphs.len() == self.patterns.len())— would make the invariant structural.
There was a problem hiding this comment.
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.
a2a416e to
cfea0de
Compare
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.
cfea0de to
edfcb86
Compare
- 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.
|
Thanks for the review. Everything below is in d3e8033 unless noted; the three inline threads have their own replies. RDF/XML Graph Store
RDF/XML attribute names: RDF 1.2 XML Syntax §2.20, "Annotating Triples: Docs:
Perf residual: took the per-graph Round trip for datasets: not added here. One correction on the gap: TriG does have a parser that understands
Base pointer and docs ordering: resolved. #1944 and #1945 have merged, this branch was rebased onto |
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.
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
GRAPHblocks returns a dataset in TriG, N-Quads or JSON-LD.This also lifts the known limitation in #1934: Graph Store
GETnow returns edge annotations, so aGETfollowed by aPUTof the result keeps them.Template forms
Edge annotations. Two SPARQL forms, both allowed inside
GRAPHblocks:?s ?p ?o ~ ?rand an optional{| ... |}body.?r rdf:reifies <<( ?s ?p ?o )>>.JSON-LD puts
@annotationon the object, the same way a transaction writes an annotation.[ ]:~,{| |},~ _:r.CONSTRUCT WHEREshorthand keeps the edge annotations in its WHERE clause.Named graphs.
GRAPH <iri> { ... }orGRAPH ?g { ... }in the template. In JSON-LD it's["graph", name, node-map, ...], the form awhereclause already uses. Apache Jena ARQ supports the same extension.A row that leaves the graph variable unbound writes nothing.
Output
o ~ ro ~ rGRAPH <g> { ... }r rdf:reifies <<( s p o )>> .r rdf:reifies <<( s p o )>> <g> .@annotation{"@id": g, "@graph": [...]}nodesrdf:annotation/rdf:annotationNodeIDattributes (RDF 1.2)r rdf:reifies <<( s p o )>>. Turtle, TriG, N-Triples and N-Quads all use this form, asfluree exportdoes. RDF/XML has no way to write it and returns an error.GRAPHblocks negotiates only TriG, N-Quads and JSON-LD.Acceptheader that admits only Turtle, N-Triples or RDF/XML gets a406.Graph Store
GETGETuses{ ?s ?p ?o } UNION { ?r rdf:reifies <<( ?s ?p ?o )>> }so that reifier links come back.GETruns anASKthrough 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 perGET; 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_formatsscenarios:Round-to-round spread was about 1–2%.
The first version measured +14% on Turtle and RDF/XML.
HashMap::removehashes the whole triple even on an empty map. The second commit skips that lookup when there are no annotations, and gives templates without annotations orGRAPHblocks a direct path into the default graph.Implementation
fluree-db-query:ConstructTemplategainsgraphs(parallel topatterns, empty when no pattern names a graph) andreifications: Vec<TemplateReification>.patterns,graphsandreificationsare private and change only throughpush_patternandpush_reification, so they can't fall out of step. Readers usepatterns(),reifications()andgraph(i).@annotationand["graph", ...].fluree-db-sparql: the AST template carriesgraphs; the parser acceptsGRAPHblocks and rejects nested ones; lowering handles annotation tails and the reifies form.fluree-graph-ir: newDataset(default graph plus named graphs), andGraph::reifiers_by_triple.fluree-graph-format: writers for TriG and N-Quads, reifiers in Turtle and N-Triples, andformat_jsonld_dataset. API change:format_jsonldandformat_jsonld_datasetreturnResult<_, LiteralAsNode>; a literal subject, graph name or reifier is an error instead of a panic.fluree-db-api:instantiate_construct_graphreturns aDataset.OutputFormat::TriGandOutputFormat::NQuads.rdf:annotation/rdf:annotationNodeID, RDF 1.2 XML Syntax §2.20), with blank-node labels encoded as forrdf:nodeID.Fluree::has_annotations.fluree-db-server:GraphFormatgainsTriGandNQuads, andnegotiate_graph_formattakes the set of formats allowed.AcceptJSON-LD default respects the allowed formats.docs/contributing/benches.mdlists the new bench scenarios. These pages are updated:Not supported
GRAPHblocks can't nest, and theCONSTRUCT WHEREshorthand has noGRAPHform (per SPARQL 1.1).rdf:reifies. Nested triple terms and property paths inside an annotation block are rejected.?r rdf:reifies <<( s p o )>>in a template also writess p o, as every Fluree write form does: Fluree reifies asserted edges only.Testing
it_query_construct.rs, moduleannotations_and_graphs, 10 tests):GRAPHblocks produce a dataset, and a graph variable copies named graphs;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.it_datalog_rules_sparql.rs): a rule head that annotates an edge or names a graph is rejected.rdf:reifieslines;@annotation;GRAPHblocks (including a template that starts with one) and of annotations;graph_store_http::annotated_graphs_round_trip: default and named graphs;GETreturns the annotations, and aPUTof 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 anonymousGETof the default or a named graph gets a 401 and leaves the ledger unloaded.construct_graphis forced to the plain template.push_patternbug that dropped the graph when the first pattern had one.GRAPHblocks.Acceptdefault test each fail with their fix reverted.query_hot_construct_formatsadds Graph Store scenarios (plain vs UNION, default and named graph, with and without annotations).