Skip to content

rdf:JSON Canonicalization - #1854

Merged
zonotope merged 13 commits into
mainfrom
fix/rdf-json-canonicalization
Sep 17, 2026
Merged

zonotope merged 13 commits into
mainfrom
fix/rdf-json-canonicalization

Conversation

@zonotope

@zonotope zonotope commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1781

Problem

rdf:JSON literals were stored as whatever text the writer serialized. A literal's identity is its text, so {"a":1,"b":2} and {"b":2,"a":1} were two terms. Retraction matching, upsert replace, and merge conflict detection all worked on the wrong unit. The reported case: a branch replaced an @json value while main rewrote the same value with different key order, and the merge left both on a sh:maxCount 1 property.

Fix

Canonicalize per RFC 8785 at every ingest point: the JSON-LD @json path, both lexical converters in fluree-db-transact, the native literal converter, and both coercion entry points in fluree-db-core.

The implementation lives in fluree-graph-ir, which already owned the "must be canonical" contract on LiteralValue::json_canonical. fluree-graph-json-ld::normalize had a second, hand-rolled implementation; it now delegates, which removes ~170 lines and puts its existing RFC 8785 vectors behind the shared code. fluree-db-core gains a dependency on fluree-graph-ir (acyclic; that crate depends only on fluree-vocab and serde).

Numbers follow ECMAScript's Number::toString, including the even-tie rule: when two shortest decimal strings both round-trip, the spec takes the even one and Rust's Display does not. Roughly 1 in 4000 doubles. Without it, another conformant implementation canonicalizing the same document produces a different lexical, and therefore a second fact.

One deviation from the RFC. It renders every number as a double, which rounds integers past 2^53. An integer that fits i64 or u64 is kept exact. Deterministic either way; declining to silently rewrite a value a writer sent.

Behavior changes

  • A value reads back canonicalized: members in key order, 1.0 as 1.
  • An rdf:JSON lexical that is not valid JSON is stored as written, on every path. parse_xsd_lexical briefly rejected these, which failed whole cross-ledger shape bundles.
  • Existing ledgers keep their non-canonical text. Reindexing does not change it: the rebuild re-derives the index from commit flakes, which hold the original text. No data rewrite, no index format change.
  • Two consequences for those ledgers. A literal named in a where, delete, or FILTER is canonicalized before comparison, so it misses a value stored under another spelling; bind it with a variable instead. And an upsert whose delete names the old text will miss, leaving both spellings on the subject.
  • Repair is a where-bound replace per affected property: bind ?old, delete it, insert the value. That collapses any duplicates the bug already created, since the binding matches every spelling. History is untouched.

@zonotope
zonotope requested review from aaj3f and bplatz September 16, 2026 02:45
@zonotope zonotope added bug Something isn't working as expected breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section area:transact Staging, commit, import/bulk-import, novelty, retraction semantics labels Sep 16, 2026

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

@zonotope this is great, particularly because this issue was causing me grief (obviously, I guess, as I was the one who opened it). I think my only human-note is that I do quite agree with the decision behind this line in your PR description:

One deviation from the RFC. It renders every number as a double, which rounds integers past 2^53. An integer that fits i64 or u64 is kept exact. Deterministic either way; declining to silently rewrite a value a writer sent.

After the Claude-assisted review (below), I do think possibly that that deviation is one of the reasons for an issue observed in the PR's code for even_tie / ECMAScript stringification, but I'll leave the details of that as-is in the full review (approving so as not to block you, though the even_tie item should, I think, land before merge):


The bug is real and important, the placement is right (folding normalize.rs's second implementation into fluree-graph-ir, which already owned the canonical-form contract, is consolidation rather than addition), and the migration documentation in datatypes.md is the best part of the change — the where-bound repair recipe with the note about why it also collapses existing duplicates is exactly what someone will need and it's already written. The integer-exactness deviation is the call I'd have made too.

The blocker is even_tie at json_canonical.rs:136: it swaps in the neighbouring even digit string whenever that string round-trips, but ECMAScript only wants the even one when the two candidates are equidistant — and round-tripping is a much weaker condition, so it fires on ordinary values. Claude ran 40,004 finite doubles through it against Node's JSON.stringify: as shipped, 9,816 (24.5%) differ from ECMAScript; with even_tie bypassed, 106 (0.26%) — and all 106 of those residuals have an even last digit on Node's side and an odd one on ours, so they're genuine ties and the rule is definitely worth keeping. As it stands it fixes 106 doubles and breaks 9,710. Concretely, the double at bits 4801034663128815763 is exactly 9181757771948.287109375, and we write …288 where everyone else writes …287; the minimum subnormal comes out as 4e-324 rather than 5e-324. That matters more here than it normally would, because the body's own argument for the rule is that a conformant implementation would otherwise produce a second fact for the same value — which is what this does, for a quarter of all doubles, on a breaking-change PR about one byte string per value. The second half of the fix is the test: every_double_round_trips_through_its_canonical_form sweeps 20,000 doubles but asserts only that the output re-parses, which is even_tie's own selection criterion — so no amount of sweeping can fail on this. Asserting the canonical string on a handful of non-tie values closes it.

Adherence to repo commitments:

  • Patterns/abstractions: ✔ Consolidates two canonicalizers into the crate that already owned the contract; fluree-db-core's new dep on fluree-graph-ir is acyclic and light (verified: fluree-vocab + serde + thiserror only).
  • Performance (speed first, memory second): ⚠️ Acceptable, not neutral. Canonicalization is new work on the transaction ingest path — parse plus re-serialize per rdf:JSON literal — confined to that datatype, idempotent, and unavoidable given the bug. No bench covers it; worth a sentence in the body.
  • Testing: ✖ The suites run (grp_ledger 5 passed; fluree-graph-ir --lib all green) and the integration tests cover the #1781 shape well — but the number tests are structurally blind to the defect above, which is why it shipped. That's the part I'd most like fixed alongside the code.
  • Conventions: ✔ Well-factored commits with real messages, thiserror-free pure module, no unwrap on a fallible path, docs updated in both datatypes.md and compatibility.md, breaking-change label applied honestly.

Verified locally at branch HEAD 25a2f39c5: 40,004-double differential against Node 22 (9,816 mismatches as shipped vs 106 with even_tie bypassed; all 106 genuine ties); confirmed the ties_pick_the_even_digit_string exemplar is a true .2500 tie so the rule is needed; cargo test -p fluree-graph-ir --lib green including all four number tests; cargo test -p fluree-db-api --test grp_ledger -- json_canonical → 5 passed; dependency graph checked; all six canonicalization call sites enumerated and their strict-vs-lenient split traced. Mutation reverse-sed'd back to byte-identical and the temporary test removed — worktree is clean.

Requesting changes only on the even_tie predicate and the string-level assertion that would have caught it — everything else here I'd merge as-is, and if you'd rather land the gating fix as a follow-up commit on this branch than rework the approach, that's completely fine by me.

Comment thread fluree-graph-ir/src/json_canonical.rs Outdated
/// Break a tie the way ECMAScript does.
///
/// Two digit strings of the same length can both round trip to `abs`. Rust
/// returns whichever its algorithm reaches; ECMAScript requires the even one.

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.

🔴 Blocking — the even-tie rule fires on "the even neighbour round-trips" instead of on an actual tie, so ~24.5% of doubles canonicalize to a farther digit string than ECMAScript produces. The rule itself is right and necessary — only its trigger is wrong.

Mechanism. even_tie takes the shortest digit string from Rust's {:e}, and if it ends in an odd digit tries value - 1 then value + 1, returning the first candidate that round-trips to the same double. ECMAScript's rule (and therefore RFC 8785's) is: among the minimal-length digit strings pick the one closest to x, and only if two are exactly equally close pick the even one. Round-tripping is far weaker than equidistance — a double's rounding interval routinely contains two adjacent shortest decimals — so the predicate fires on ordinary values and swaps the closest string for a farther even one.

Measured. Claude dumped canonicalize_json_value for 40,004 finite doubles (a deterministic xorshift sweep over the bit space plus edges) and diffed against Node 22's JSON.stringify, which is Number::toString:

differs from ECMAScript
as shipped 9,816 / 40,004 (24.5%)
with even_tie bypassed 106 / 40,004 (0.26%)

So it fixes 106 and breaks 9,710. And in all 106 residuals Node's last digit is even, Rust's is odd, and they differ by exactly one — every residual is a genuine tie. That's the cleanest possible evidence that the rule belongs here and only its trigger needs changing.

Concrete case. The double at bits 4801034663128815763 is exactly 9181757771948.287109375. ECMAScript and any JCS implementation write 9181757771948.287 (distance 0.000109375); this writes 9181757771948.288 (distance 0.000890625, about 8x farther) purely because ...288 is even and round-trips. And the simplest one: the minimum subnormal canonicalizes to 4e-324 where everyone else writes 5e-324.

Why it's blocking rather than a nit. This is the #1781 bug class for a different input class. The body's own justification for the rule is that "another conformant implementation canonicalizing the same document produces a different lexical, and therefore a second fact" — which is exactly what happens here for a quarter of all doubles, and on a breaking-change PR whose premise is one byte string per value. A JCS-conformant peer, a JSON-LD processor, or a client that pre-canonicalizes will disagree with us and we'll store the second fact.

Fix direction. Gate the swap on equidistance rather than on round-tripping — the candidate should only win when it is exactly as far from abs as digits is (equivalently: abs's k+1-digit expansion ends in a 5 with nothing after it). Rust's {:e} already gives the closest shortest string, so the untouched path is correct; the rule only needs to intervene on the true .5 tie. I'd rather not hand you a specific implementation since the precision handling is the hard part and it's your area — but the sweep above is a cheap way to confirm whichever predicate you pick.

Comment thread fluree-graph-ir/src/json_canonical.rs Outdated

#[test]
fn every_double_round_trips_through_its_canonical_form() {
// A deterministic sweep: whatever spelling is chosen, it must parse

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.

🔴 Blocking, and it's the reason the above shipped: every_double_round_trips_through_its_canonical_form asserts the one property even_tie cannot violate.

The sweep covers 20,000 doubles, which is more than enough coverage — but it asserts only that ecmascript_number(f).parse::<f64>() == f. Round-tripping is even_tie's own selection criterion, so a candidate it returns always round-trips by construction. The test is structurally incapable of failing on this bug, however many doubles you throw at it.

Its two siblings don't close the gap either: doubles_follow_ecmascript (:251) is ten hand-picked values that happen not to trip the predicate, and ties_pick_the_even_digit_string (:269) proves the rule fires when it should — I checked its exemplar and it's a real tie, exactly 810553441865041.2500, so ECMAScript's .2 is correct and the rule really is needed — which is a different claim from proving it doesn't fire when it shouldn't.

What would have caught it is asserting the string. Concretely: pin a handful of the non-tie values from the sweep (5e-324, 9181757771948.287, -0.20221894534048165) as literal expected strings, and — if you want the strong version — check in a small table of (bits, expected) pairs generated from a reference implementation so the sweep compares canonical forms rather than re-parsed values.

}
// Canonicalizing gives one term per value (#1781). It validates the
// string on the way.
(FlakeValue::String(s), dt) if dt == rdf::JSON => fluree_graph_ir::canonicalize_json(s)

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 pre-existing — your change didn't introduce this. The real location is fluree-db-api/src/tx.rs:2352, which isn't in this diff; commenting here because this is the coerce entry point the claim is about.

The body says an rdf:JSON lexical that isn't valid JSON "is stored as written, on every path." At tx.rs:2352 the coerce_string_value result is .unwrap_or_else(|_| FlakeValue::String(value.clone())), so the text survives but the flake is a FlakeValue::String rather than a FlakeValue::Json — which is the mislabeling the comment three lines above it explicitly warns about ("storing the raw String here would persist a string flake mislabeled with the datatype, diverging from the bulk-import path"). Every other ingest point stores FlakeValue::Json.

That asymmetry predates this PR and I'm not asking you to fix it here. I'd just narrow the sentence in the body to "the text is preserved rather than rejected" — someone will lean on "every path" later, and the variant difference is the sort of thing that surfaces as a baffling query miss.

rdf::JSON => FlakeValue::Json(value.to_string()),
// Canonicalizing gives one term per value (#1781). This converter is
// the lenient one, so a lexical that is not valid JSON is kept as
// written rather than failing the write.

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. This is more of a question than a suggestion: canonicalization is now real work on the transaction ingest path — a parse plus a re-serialize per rdf:JSON literal, proportional to document size — where previously the lexical was stored verbatim at zero cost.

I don't think there's an alternative worth having (the alternative is wrong data), the cost is confined to rdf:JSON literals rather than all flakes, and canonicalizing_twice_changes_nothing means a value crossing two ingest points is merely canonicalized twice rather than corrupted. So I'm not asking for a change. But there's no bench covering it, and on a breaking-change transact-path PR I'd like the body to say the cost was weighed — even one sentence — so the next person profiling a @json-heavy import doesn't have to rediscover where the time went.

result
// Every ingest path shares one implementation of the scheme. Two that
// disagreed anywhere would split one value into two terms.
fluree_graph_ir::canonicalize_json_value(data)

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. Deleting the second hand-rolled implementation and delegating to fluree-graph-ir — which already owned the "must be canonical" contract on LiteralValue::json_canonical — is the right structural call, and it puts this module's existing RFC 8785 vectors behind the shared code instead of beside it. That's -162 lines that were a latent divergence.

I checked the dependency claim too: fluree-graph-ir depends only on fluree-vocab, serde, serde_json and thiserror, so fluree-db-core taking it on really is acyclic and light.

- **A value reads back canonicalized, not as written.** Members come back in key order. A number written as `1.0` reads back as `1`. The JSON is the same. Only its spelling changes.
- **Integers keep their exact value.** RFC 8785 treats every number as a double, which rounds integers past 2^53. Fluree keeps them exact instead.

`@value` may be a JSON document or a string holding one. Either is canonicalized. A string that is not valid JSON is stored as written.

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, and I mean this. The two consequences for existing ledgers are stated plainly, and the repair recipe is a working transaction with the reason it works ("the where clause binds every spelling on that property, so this collapses duplicates as well"). That's the paragraph someone will need at an awkward moment and it's already written, including the fluree validate pointer for finding the affected properties. Please keep it exactly as is.

}
Value::Object(members) => {
// Keys sort by UTF-16 code unit, not by code point. A non-BMP
// character encodes to a surrogate pair at 0xD800. It therefore

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. "Keys sort by UTF-16 code unit, not by code point. A non-BMP character encodes to a surrogate pair at 0xD800. It therefore sorts before any BMP character above 0xD7FF" — that's the one subtlety in JCS key ordering that implementations get wrong, explained in three lines, with keys_sort_by_code_unit_not_by_length pinning it.

@zonotope
zonotope merged commit a5fdba9 into main Sep 17, 2026
16 checks passed
@zonotope
zonotope deleted the fix/rdf-json-canonicalization branch September 17, 2026 03:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:transact Staging, commit, import/bulk-import, novelty, retraction semantics breaking-change Backwards-incompatible change; drives the Breaking Changes release-notes section bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rdf:JSON literals skip JCS canonicalization, so equal JSON is distinct facts — branch merge then duplicates a "replaced" @json value

2 participants