Skip to content

feat(server): accept Turtle, N-Triples and TriG on /sync - #1932

Merged
bplatz merged 3 commits into
mainfrom
feat/sync-rdf-formats
Sep 26, 2026
Merged

bplatz merged 3 commits into
mainfrom
feat/sync-rdf-formats

Conversation

@bplatz

@bplatz bplatz commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

POST /sync now accepts the graph's desired contents as Turtle (text/turtle), N-Triples (application/n-triples) or TriG (application/trig), as well as JSON-LD. It commits only the difference, as it already did for JSON-LD, so one request replaces a named graph and an unchanged body commits nothing.

This is the first step toward a Graph Store Protocol PUT. It lets an RDF client replace a graph in one request and one commit, instead of CLEAR followed by a full reload, which costs two commits and leaves retraction history for every unchanged triple.

Behaviour

  • Turtle / N-Triples: the document's triples are the graph's contents.
  • TriG: still one graph per request.
    • Every GRAPH block (keyword or compact form) must name the graph parameter's IRI. A block for another graph is a 400.
    • Several blocks for the target are merged, and a blank-node label shared between them is one node.
    • Default-graph triples beside a block are a 400. In TriG they belong to the default graph, which sync doesn't write.
    • A GRAPH <#txn-meta> block annotates the commit, as on /upsert.
  • Empty bodies: an RDF body with no triples needs allowEmpty=true, the same guard as "@graph": [].
  • Policy: for RDF bodies it comes from headers only, as on the other Turtle routes. dryRun works for every format.
  • Parse path: every format stages through the JSON-LD sync path, so blank-node identity (graph-scoped skolem IDs) and the diff are shared. A graph written in one format and re-synced in another commits nothing.

Implementation

  • fluree-db-transact: new unwrap_trig_graph_blocks. It blanks a TriG body's block delimiters in place with same-length edits, so the full Turtle parser reads block contents (including [ … ] and ( … ), which the /upsert block parser rejects; see Bulk import's TriG reader rejects [ … ], ( … ) and bare { … } blocks that insert accepts #1930), and parse errors keep their original line and column.
  • fluree-db-api: new SyncPayload { JsonLd, Rdf { text, allow_empty } } threaded through stage_sync_transaction_tracked and the builder (sync_graph_payload), plus sync_named_graph_rdf_with. The RDF checks (other graph, mixed body, empty body) run at staging, so every entry point enforces them.
  • fluree-db-consensus: new TransactionBody::RdfGraphSync and BodyKind::RdfGraphSync, appended at ordinal 13 (pinned by body_kind_ordinals_are_append_only). Both the local committer and the Raft commit worker handle it. The queued request keeps the original text; the Raft entry refers to it by CID.
  • Raft refusals: the commit worker now poisons a 400 or 413 from build_commit immediately, as BodyMalformed, instead of treating it as transient. Before, it re-staged three times with backoff and a ledger refresh, then poisoned as StagingFailed, so a TriG body naming another graph burned the retry budget before it was refused. Other statuses keep the retry: a conflict heals after a refresh, and policy or SHACL can depend on state the node hasn't caught up with. The client still gets the 422 that every poisoned submission returns.
  • fluree-db-server: /sync branches on content type, the dry run is shared (dry_run_sync), and the Turtle executor gains a Sync op. Peer forwarding is unchanged.
  • CLI: fluree sync still converts Turtle to JSON-LD client-side, so it keeps working against older servers.
  • Docs: transactions/sync.md gains a "Payload formats" section. TriG/sync statements are corrected across the API, Turtle, concepts, cookbook and compatibility pages, and Bulk import's TriG reader rejects [ … ], ( … ) and bare { … } blocks that insert accepts #1930 is documented as a known limitation of /upsert.

Testing

  • it_sync_graph_rdf.rs (8 tests):

    • Turtle delta and no-op;
    • N-Triples and JSON-LD parity;
    • TriG block vs Turtle parity across literal types and labeled and anonymous blank nodes;
    • multi-block bodies with a shared label and txn-meta;
    • TriG-star annotations and collections inside a block;
    • refusals (other graph, mixed body);
    • the empty-body guard;
    • dry run.
  • trig_meta unit tests: same-length unwrap, dot insertion, a } inside a string literal, txn-meta removal, passthrough.

  • Consensus: RdfGraphSync codec round trip, and body_hash covers the graph and allow_empty.

  • HTTP: sync_route_accepts_rdf_bodies covers all three content types, dry run, the refusals and allowEmpty. sync_route_contract no longer expects a Turtle body to be a 400.

  • Raft: rdf_graph_sync_commits_through_the_raft_queue sends TriG through a follower and checks the resync is a no-op and a smaller payload retracts. It also sends a wrong-graph body and asserts the immediate BodyMalformed refusal, which fails with the old mapping (StagingFailed { .., attempts: 3 }), and that the next sync still commits. A unit test pins which statuses poison and which retry.

  • Non-vacuity: each check was broken on purpose and a test failed each time. Covered: the mixed-body refusal, the other-graph refusal, dot insertion, txn-meta removal, the empty-body guard, and the Raft worker arm staged as an upsert.

  • Local runs:

    • transact unit tests;
    • API unit tests, grp_ledger, grp_transact, grp_misc, grp_import, it_sync_graph_scan_backstop;
    • consensus unit tests with raft;
    • server unit tests, grp_http, grp_raft.

    liveness_monitor_demotes_killed_follower failed once in grp_raft and passed on 3 reruns and a full group rerun; it's a known flaky test.

  • Clippy on the touched crates, with and without raft, and fmt.

  • Not run locally: the full workspace suite (CI), testsuite-sparql (not touched), and fluree-db-docs, which passes 21 of 22 here; the one failure comes from gitignored design pages on this machine.

Follow-up: #1931. The Raft test varies whitespace between identical resyncs, because byte-identical keyless submissions share a queue envelope that the first one's apply releases.
Related: #1930.

@bplatz bplatz added enhancement New feature or request area:transact Staging, commit, import/bulk-import, novelty, retraction semantics area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph labels Sep 25, 2026
@bplatz
bplatz requested review from aaj3f and zonotope September 25, 2026 10:37
@bplatz
bplatz added this pull request to stack #1922 September 25, 2026 10:37
@bplatz
bplatz removed this pull request from stack #1922 September 25, 2026 18:27
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch from 2aaa794 to 1469c0a Compare September 25, 2026 19:15
@bplatz
bplatz added this pull request to stack #1947 September 25, 2026 19:15

@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 nice and I think designed well. I was curious how we'd handle "skolemized" (I love using this word now that I've learned it) blank node identifiers, and I think the PR does a good job of thinking about this (explicitly or implicitly) as it considers the "format --> path" handling, for example. I think the only things Claude's review helped me note were maybe some RAFT- / cluster-related test patterns we may want in before merge, but I'll include full review below


The TriG handling here is fantastic. The obvious move was to teach TrigMetaParser's block parser about [ … ] and ( … ), and that's the trap, because it means maintaining a second Turtle grammar forever. Using the block parser only to locate blocks, blanking their delimiters with same-length edits, and letting the real Turtle parser read the whole document is the maintainable fork — and keeping the edits same-length so a parse error's line and column still point into the document the user actually sent is the kind of detail that only shows up as an absence of support tickets. Routing every format through the JSON-LD sync path rather than the direct Turtle→flake route is the other decision I'd flag as load-bearing: it's what makes blank-node identity (and therefore the delta) stable across formats, and the three-directional parity tests pin exactly that.

I went at it along the axes an untrusted-RDF-on-a-write-endpoint change earns — a stray } in a literal or comment, {| / |} inside a block, unbalanced braces, content-type disagreeing with the payload, @base-relative and prefixed graph labels, blank-node scoping across requests, whether the new formats route around SHACL or policy or auth, and whether a mid-document parse failure can half-commit — and it held on all of them. Auth is the same bind_authorization + enforce_write_access pair the JSON-LD branch uses; the RDF dry run and the committed run derive governance from identical inputs (bound_governance(headers.identity, …) both sides), so a dry run can't report a delta the real run wouldn't produce; block labels are resolved before the confinement comparison, so GRAPH ex:g, <http://example.org/g> and a @base-relative label all normalise; and a parse failure happens before staging, so there's nothing partial to commit. I mutation-checked two of the six non-vacuity claims in your body and both came back exactly as advertised.

The one thing I'd like you to look at is the inline note on transact.rs:1328, and it's a question rather than a finding. Your JSON-LD branch gates its empty payload at the route on purpose — the comment says "because the consensus submission below calls the builder directly" — while the RDF branch leaves all four of its refusals to staging. Locally that's a clean 400 and your test proves it. On the Raft path the same build_commit failure goes through stage_failure → WorkerError::Transient, which the worker's retry loop treats as a retryable backend hiccup: backoff, ledger refresh, re-stage, up to MAX_STAGE_ATTEMPTS, then poison the entry. If I've traced that right, a TriG body naming the wrong graph burns the whole retry budget on a client typo. That funnel is pre-existing and catches every staging-time refusal today, so this isn't a regression you introduced — but these are the first refusals that are pure request syntax, and the Raft test only covers the happy path, so nothing currently says what a refusal does there. I'd love a sanity check from you on it, and one refusal case added to rdf_graph_sync_commits_through_the_raft_queue either way.

On #1930, since anyone reading this diff will wonder: this PR neither fixes nor causes it — it builds the mechanism the issue proposes and applies it to /sync only, which you've documented rather than papered over. The consequence worth saying out loud is that after this lands, the same TriG document is accepted on /sync and rejected on /upsert, which is a confusing thing to hit. Generalising unwrap_trig_graph_blocks to multi-graph /upsert and import is genuinely a big piece of work (each block's triples homed on its own graph, blank-node labels staying document-scoped across blocks), so I think it's right that it's separable and that #1930 carries it — just naming it as a real rough edge that exists between now and then.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Extends rather than parallels — every format converges on the existing JSON-LD sync path, SyncPayload threads through the existing builder, the consensus body is an appended variant on the existing enum, and the dry run is now shared between formats (dry_run_sync) instead of duplicated. The one new construct, unwrap_trig_graph_blocks, is new because the alternative was a second Turtle grammar.
  • Performance (speed first, memory second): ✔ No hot-path or query-engine change, and a real win on the side: OpPlan::Sync borrowing instead of owning removes a deep clone of the whole sync payload per builder sync. The new RDF path pays one extra full-body tokenize and one body copy for requests that previously 400'd — the same double-lex /upsert's TriG path already pays, so parity rather than a new tax. No regression risk.
  • Testing: ✔ 8 new integration tests wired into grp_ledger (verified, not assumed), 3 trig_meta unit tests, a consensus codec + body_hash test, sync_route_accepts_rdf_bodies in grp_http, and a Raft test in grp_raft. All the ones I ran pass by name, and the two I mutation-checked go red. The ⚠️ I'd otherwise raise — no coverage of a refusal under Raft — is folded into the note above rather than counted twice.
  • Conventions: ✔ Self-describing subjects and real multi-line bodies, including a second commit that exists purely to explain a wasm32 build fix. The docs work is genuinely above the bar: transactions/sync.md gains a "Payload formats" section, and the TriG/sync claims are corrected across api/, concepts/, cookbook/ and compatibility.md rather than only where the feature landed. #1930 is documented as a known limitation instead of being quietly left for a user to find. W3C registers untouched.

Verified locally at 2aaa794fd: cargo nextest run -p fluree-db-transact -E 'test(unwrap_)' (3/3), -p fluree-db-api --features shacl --test grp_ledger -E 'test(it_sync_graph_rdf::)' (8/8), -p fluree-db-server --test grp_http -E 'test(sync_route)' (2/2, including sync_route_accepts_rdf_bodies); two mutation checks, each producing exactly the expected single failure. Not run: the Raft test (3-node cluster) and --all-features, which won't build on my machine for an unrelated reason (usearch → cxx can't find <algorithm>) — CI's --all-features run covers both and is green at this head (run 36140510545, event=pull_request).

Approving so you can merge when ready — but I'd really like your read on the Raft refusal path first, even if the answer is "that's fine and it's #1931-adjacent."

));
};

if credential.is_turtle_or_trig() {

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.

Optional, and more of a question than a suggestion — the RDF refusals are all pure syntactic properties of the request, but they're only checked at staging, and I'm not sure that lands where you want it on a Raft cluster.

Right below this, the JSON-LD branch gates its empty payload at the route (transact.rs:1389-1397) with a comment saying exactly why — "Enforced here (not only in sync_named_graph) because the consensus submission below calls the builder directly." The RDF branch takes the other choice, so parse_rdf_sync_transaction's three refusals (block names another graph, default triples beside a block, empty body without allowEmpty) plus any Turtle parse error all surface from inside build_commit().

On the local committer that's fine and the test proves it: execution_failure (fluree-db-consensus/src/local.rs:399-420) preserves ApiError::status_code(), so ApiError::Http { status: 400 } comes back as a 400 and sync_route_accepts_rdf_bodies asserts it. The Raft worker takes a different route with the same failure — fluree-db-consensus/src/raft/commit_worker.rs:697 wraps it as stage_failure(&format!("build_commit failed: {e}")) → WorkerError::Transient, and the retry loop at commit_worker.rs:238-268 treats that as a "retryable backend hiccup": sleep with exponential backoff, fluree.refresh(...) the ledger, re-stage, up to MAX_STAGE_ATTEMPTS, then poison the entry. So as far as I can trace it, curl -H 'content-type: application/trig' --data-binary @wrong-graph.trig against a clustered deployment spends the whole retry budget on a deterministic client typo and then poisons a per-ledger queue entry, rather than 400-ing.

Two honest caveats. This shape is pre-existing and not yours — every staging-time refusal on the Raft path goes through the same build_commit → stage_failure funnel today, including SHACL violations and policy denials. And I traced it rather than observing it; I didn't stand up the 3-node cluster, so I'd want you to confirm before acting on it. What's new here is that this PR adds the first refusals that are pure request syntax — the kind the JSON-LD sibling deliberately catches at the edge — and rdf_graph_sync_commits_through_the_raft_queue covers only the happy path, the no-op and the shrink, so nothing in the suite says what a refusal does under Raft.

So mostly I'd like to know which of these you intended:

  • it's fine as-is, because a client sending a malformed TriG body deserves what it gets;
  • the route should run unwrap_trig_graph_blocks once before submitting and do the confinement / mixed-body checks there (paying a second parse to keep the JSON-LD branch's "refuse before consensus" property);
  • or the real answer is that build_commit failures carrying a 4xx shouldn't be Transient on the Raft path at all — in which case it's a separate PR and this one just made it more visible.

Either way, adding one refusal case to the Raft test would be cheap and would document whatever today's answer actually is.

The Raft half of this lives in fluree-db-consensus/src/raft/commit_worker.rs:697 and :238-268, which aren't in this diff — commenting here because this is the branch that creates the refusals.

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.

Your trace was right. I confirmed it on a 3-node cluster: a wrong-graph TriG body through a follower came back 422 with StagingFailed { error: "build_commit failed: sync replaces one graph, …", attempts: 3 }.

I went with a narrow version of your third option, in 4f6617e. The worker now poisons a 400 or 413 from build_commit immediately, as BodyMalformed, since those statuses describe the request itself. Everything else keeps the transient retry: a 409 conflict is what the refresh-and-retry loop exists to heal, and a 403 or 422 from policy or SHACL can depend on state the node hasn't caught up with. It uses an existing PoisonReason, so nothing new goes into the Raft log. The status stays at 422, since poisoned_maps_to_422_with_reason_in_message pins that for every poison.

I skipped the route-level check: for RDF it would mean a second lex of every sync body, and the worker fix covers every request error on every Raft write route, not only this one.

rdf_graph_sync_commits_through_the_raft_queue now sends the wrong-graph body and asserts the BodyMalformed refusal plus a following sync that still commits. It fails with the old mapping, and all 19 grp_raft tests pass.

/// Skip a labeled block's contents (positioned just past its `{`),
/// recording its delimiters. The contents are left for the Turtle parser,
/// which also reports their errors.
fn skip_graph_block(&mut self, iri: String, start_pos: usize) -> Result<()> {

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.

Praise — skip_graph_block is the right call, and I want to say why, because "scan forward to the next }" is the kind of thing that looks fragile and usually is.

It isn't here: it scans the token stream, and {| / |} lex as distinct AnnotationOpen / AnnotationClose kinds (fluree-graph-turtle/src/lex/token.rs:193-195), a } inside a string literal is a String token, and a } in a comment never reaches the stream.

Leaving the block parser to locate blocks and handing their contents to the real Turtle parser — instead of teaching a second grammar about [ … ] — is the maintainable half of that fork, and the same-length in-place editing so a parse error's line and column still point into the user's own document is the detail most implementations skip and then regret.

for block in &parser.unwrapped {
blank(&mut turtle[block.header.0..block.header.1]);
// A block's last triple may omit its `.`; Turtle's may not.
turtle[block.close] = if block.needs_dot { b'.' } else { b' ' };

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.

Praise, verified — this line is doing a lot of work, and it's pinned.

turtle[block.close] = if block.needs_dot { b'.' } else { b' ' } is the whole "a block's last triple may omit its ., Turtle's may not" rule. Breaking it to always write a space turns both unwrap_keeps_block_triples_in_place and it_sync_graph_rdf::trig_blocks_read_as_one_turtle_document red.

Same for the graph-confinement refusal at fluree-db-api/src/tx.rs:2263 — neutering it to .find(|_iri| false) turns trig_body_is_confined_to_the_target_graph red and nothing else. Two of the six checks in your "Non-vacuity" list independently confirmed.

// Every staging path dispatches sync first; parsing it as a plain
// insert would write the payload without the retraction wave.
TransactOperation::SyncGraph { .. } => Err(ApiError::internal(
"graph sync must be staged through stage_sync_transaction_tracked",

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.

Praise — turning the SyncGraph arm from a fall-through into a hard error is a genuine hardening, not just tidiness.

The old behaviour would have staged a sync payload as a plain insert, i.e. written the new contents with no retraction wave, leaving every triple the payload dropped still in the graph. Silently.

I traced all five call sites (tx_builder.rs:932, 1074, 1382, 1672, graph_transact_builder.rs:277) — the first four dispatch sync first and the fifth has no sync_graph setter at all, so the arm is unreachable today and now stays that way loudly.

@@ -1318,8 +1363,8 @@ enum OpPlan<'a> {
},
/// Graph sync (see [`fluree_db_transact::Txn::sync_graph`]).
Sync {

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.

Praise, performance — OpPlan::Sync going from owned { String, JsonValue } to borrowed { &'a str, SyncPayload<'a> } deletes a deep clone of the entire sync payload on every builder-driven sync.

A sync payload is a whole graph's contents, so that clone scaled with the largest thing the caller has. Easy to miss in a feature PR; nice that it came along.

///
/// Appended last, for the same postcard-ordinal reason as
/// `JsonLdGraphSync`.
RdfGraphSync {

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.

Praise — appended variant, ordinal 13 pinned by body_kind_ordinals_are_append_only, and body_hash covering graph_iri and allow_empty as well as the text.

The unit test asserting that flipping either non-text field changes the hash is the right paranoia. Given the hash is the content-addressed queue key, treating allow_empty as part of request identity rather than as metadata is the right instinct: "clear this graph" and "don't clear this graph" must never share an envelope.

@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch 2 times, most recently from cadab4a to b58d54c Compare September 25, 2026 21:07
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch 2 times, most recently from bd1d6f4 to f1638d2 Compare September 25, 2026 21:31
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch 3 times, most recently from 5f7acc3 to ee3b602 Compare September 25, 2026 23:13
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch from ee3b602 to b220f1f Compare September 25, 2026 23:31
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch from b220f1f to 386777b Compare September 25, 2026 23:37
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch 2 times, most recently from 1e065c6 to c197641 Compare September 26, 2026 00:45
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch from c197641 to 8fd3eb1 Compare September 26, 2026 01:02
Base automatically changed from refactor/staging-helper-dedup to main September 26, 2026 01:06
POST /sync now takes the graph's desired contents as text/turtle,
application/n-triples or application/trig as well as JSON-LD, and commits
only the delta, as it does for JSON-LD.

A TriG body is still one graph's contents: its GRAPH blocks must name the
`graph` parameter's IRI, and default-graph triples beside a block are
refused, since in TriG they belong to the default graph. Blocks are unwrapped
in place (unwrap_trig_graph_blocks) and the whole body is read by the Turtle
parser, so block contents get the full Turtle grammar and every format stages
through the JSON-LD sync path.

RDF bodies travel through consensus as a new RdfGraphSync body (appended,
BodyKind ordinal 13), carrying allow_empty because an RDF body's emptiness is
only known once parsed.
`admin` is compiled out on wasm32, but the transaction builder takes a
`SyncPayload` on every target, so the wasm32 build failed to resolve it.
The type now lives in `tx_builder` and is re-exported unconditionally;
the empty-JSON-LD check that only `admin` uses stays native-only.
@bplatz
bplatz force-pushed the feat/sync-rdf-formats branch from 8fd3eb1 to 20e2947 Compare September 26, 2026 01:06
The Raft commit worker treated every build_commit failure as transient:
it re-staged up to three times with backoff and a ledger refresh, then
poisoned the entry as StagingFailed. A request error fails identically
every time. A TriG sync body naming another graph, for example, burned the
whole retry budget before it was refused.

A 400 or 413 from build_commit now poisons immediately as BodyMalformed.
Other statuses keep the retry. Conflicts heal after a refresh, and policy
or SHACL checks can depend on state this node has not caught up with.

The Raft RDF sync test now sends a wrong-graph TriG body through a follower
and asserts the immediate BodyMalformed refusal. With the old mapping it
fails with `StagingFailed { .., attempts: 3 }`. A valid sync after it still
commits.
@bplatz

bplatz commented Sep 26, 2026

Copy link
Copy Markdown
Contributor Author

@aaj3f thanks. My read on the Raft path is on the thread: your trace reproduced on a 3-node cluster, and 4f6617e poisons request errors (400 and 413) from build_commit immediately instead of retrying. The Raft test now covers the refusal. I agree with your note on #1930: the /sync vs /upsert difference is a real rough edge until it lands.

@bplatz
bplatz merged commit 1c26b6c into main Sep 26, 2026
16 checks passed
@bplatz
bplatz deleted the feat/sync-rdf-formats branch September 26, 2026 01:51
@aaj3f aaj3f mentioned this pull request Sep 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:server HTTP surface, routes, error mapping, swagger, timeouts/admission, config graph area:transact Staging, commit, import/bulk-import, novelty, retraction semantics enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants