Repository navigation
feat(rdf): RDF Dataset Canonicalization (RDFC-1.0) - #2285
Conversation
Two writings of one dataset differ in their blank node labels and statement order, so their text cannot be compared, hashed or signed. RDFC-1.0 labels blank nodes from the statements alone and fixes the order: equal datasets give equal canonical N-Quads. - fluree_graph_format::canon::canonicalize implements RDFC-1.0: first-degree hashes, Hash N-Degree Quads over the paths between blank nodes that share one, SHA-256 or SHA-384, canonical N-Quads escaping, and the issued identifiers map. A triple term is written <<( s p o )>> and its blank nodes are labeled with the quad's. - A poison dataset is refused rather than worked on without end: calls to Hash N-Degree Quads are limited, by default to 16 per blank node and at least 1,024. The W3C suite's poison graphs that must canonicalize take under 512; its 10-node clique is refused. - rdf::canonicalize and fluree.canonicalize(quads, hash=...) expose it. It runs only when called: nothing in reading, writing or transacting canonicalizes. Checked against the W3C RDFC-1.0 test suite (w3c/rdf-canon): all 65 tests pass, the SHA-384, identifier-map and negative poison tests included.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is really nice, and at a design level I have no pushback: it's a faithful transcription of the Recommendation (Claude walked §4.4-4.8 step by step against it), and Claude's run of the current W3C manifest passes all 86 tests, not just 65. The one element I don't think should merge as-is is the poison-graph guard. It counts Hash N-Degree Quads calls, but a group of identical related blank nodes (one node shared across m named graphs) walks m! permutations without making a single call. So a 25-quad dataset runs past two minutes no matter what the limit is, while rdf-canonize does it in a millisecond with the same output. Generating only distinct permutations fixes it, and the 86 tests still pass with that change. Since the consumer this is for (VC checking) takes untrusted input, I'd also love to see the suite wired into CI next to a regression test for that shape. Details below:
Full review below:
Approving so as not to block you
This is a careful piece of work, @bplatz. The algorithm follows the Recommendation closely (Claude checked the early-exit checks, the canonical-before-temporary precedence and the code-point ordering against the text), all 86 tests in the current W3C rdf-canon manifest pass at this head, and keeping it a standalone utility with nothing in read/write/transact calling it is the right altitude. The one thing that needs to change before merge is the poison guard at canon.rs:388: duplicate entries in a related-hash group are permuted m! times without a counted call, so the documented limit can be bypassed by a tiny dataset. The fix is a 7-line change to Permutations that Claude verified against the full suite. The rest are small fold-ins: the U+FFFE/U+FFFF escape (reuse syntax::push_string), literals="lexical" in the README example, the suite in CI, and a Python knob for the limit.
Adherence to repo commitments:
- Patterns/abstractions:
⚠️ The right home and inputs (fluree-graph-format, IRDataset, re-exported throughfluree_db_api::rdf), but the string escaper re-implementssyntax::push_stringand diverges from it on U+FFFE/U+FFFF. - Performance (speed first, memory second): ✔ No hot path is touched: nothing in query, transact, index or read calls it. Within the function, the costs are proportional apart from the B1 factorial loop, which is a DoS on new callers, not a regression.
- Deployment targets: ✔ n/a for existing paths: builds for wasm32 (pure-Rust
sha2;wasm32andwasm-smokegreen) and runs only when an embedder calls it. B1 is the one host-shaped risk: an embedder canonicalizing untrusted input would pin a request until its execution ceiling. - Testing:
⚠️ The unit tests andtest_canonicalize.pyrun in CI on this head (testand the threepythonjobs), but the W3C suite ran only locally, and nothing covers the duplicate-permutation shape. - Conventions: ✔ Self-describing subject, thorough body, fmt and clippy green, docs page and README updated. The body's "65 of 65" should read 86.
Verified at branch HEAD (d31bb3134, by Claude, on an EC2 box with rustc 1.97.0): canon unit tests 5/5; W3C rdf-canon (15619df) 86/86; the B1 reproduction (m=11 takes 31.456 s, m=12 still running at 120 s, max_deep_calls: Some(4) doesn't stop it); the candidate fix gives 86/86 and m=20 in under 1 ms; rdf-canonize 5.0.0 cross-check with identical m=8 output; CI on this head green.
Just be sure to get the permutation fix in before this merges, ideally with the suite and that 25-quad case in CI so it stays fixed.
| data.push_str(&related_hash); | ||
| let mut chosen_path = String::new(); | ||
| let mut chosen_issuer = None; | ||
| for permutation in permutations(&blank_nodes) { |
There was a problem hiding this comment.
Blocking: the poison-graph limit can be bypassed, and a 25-quad dataset runs for minutes whatever max_deep_calls is set to.
The limit counts calls to Hash N-Degree Quads (:359-362), but the expensive loop here doesn't always make one. A related blank node that shares the reference node's quads once per named graph lands in one related-hash group m times (the spec keeps duplicates, and so does :376-379). When that node already has a canonical or temporary id, every one of the m! index orderings permutations yields (:451-484) builds the identical path. It never recurses, so deep_calls never moves, and it never prunes, because an equal path isn't "beaten" (:414-416). RDFC-1.0 §7.1 asks for the limit to cover "recursive steps and permutations of long lists", and the second half is the one missing.
Claude reproduced it at d31bb3134 with _:y <name> "Y" plus _:x <p> _:y <g_i> and _:x2 <p> _:y <g_i> for i < m: m=10 (21 quads) takes 2.539 s, m=11 takes 31.456 s, and m=12 and m=13 were still running at 120 s. With max_deep_calls: Some(4), m=10 still finishes, Ok, in 2.725 s, so the limit never sees the work. It's a legitimate dataset, not a poison one: rdf-canonize 5.0.0 does m=20 in under a millisecond, and at m=8 its output is byte-identical to this PR's. The planned consumer (VC checking) takes untrusted input, so this is exactly the input the guard is there for.
Fix: generate only distinct permutations. Do lexicographic next-permutation over the labels, not the indices, starting from sorted order:
fn permutations<'i, 'a>(items: &'i [&'a str]) -> Permutations<'i, 'a> {
let mut order: Vec<usize> = (0..items.len()).collect();
order.sort_by_key(|&i| items[i]);
Permutations { items, order, started: false }
}
// in next():
let items = self.items;
let pivot = (1..order.len()).rev().find(|&i| items[order[i - 1]] < items[order[i]])?;
let swap = (pivot..order.len()).rev().find(|&j| items[order[j]] > items[order[pivot - 1]])?;Claude ran that on a scratch copy: all 86 W3C rdf-canon tests still pass (the 21 issued-map tests included), and m=20 finishes in under a millisecond. With duplicates collapsed, every permutation of a group with more than one distinct label recurses at least once, so the call budget becomes a real bound on the work. Charging each permutation against the budget as well would be cheap belt-and-braces. Either way, a regression test with this input belongs next to too_complex_a_dataset_is_refused.
There was a problem hiding this comment.
Addressed in 10b1fe7. I left the budget counting calls only: a group with two or more distinct labels forms only from nodes with no id yet, so each of its orderings recurses and is counted.
|
|
||
| /// Canonical N-Quads string escaping: `\b \t \n \f \r \" \\`, `\uXXXX` | ||
| /// (uppercase) for the other control characters, and nothing else. | ||
| fn push_escaped(out: &mut String, text: &str) { |
There was a problem hiding this comment.
Optional: U+FFFE / U+FFFF are written raw, and syntax::push_string already does this escape the way the Recommendation says.
This is more of a question than a suggestion. RDFC-1.0's Appendix A says characters "not matching the Char production from XML 1.1 MUST be represented by UCHAR", which takes in U+FFFE and U+FFFF. push_escaped writes them natively (Claude's probe: "a\u{ffff}b\u{fffe}c"). fluree_graph_ir::syntax::push_string (syntax.rs:20-60), the escaper the N-Triples/N-Quads C14N suites already gate, writes �/�. With push_escaped replaced by push_string, all 86 W3C tests still pass. To be fair, rdf-canonize 5.0.0 writes them raw too, and the suite has no test for it, so if you matched rdf-canonize on purpose, that's a reasonable call. Otherwise I'd lean toward the spec text and one escaper instead of two. Language-tag case is the one place rdf_text's writer shouldn't be reused, since it lowercases and RDFC-1.0 leaves that alone. It's minor, but if you agree it's right, I'd rather see it folded in now than lost in the backlog.
| statements give the same text, whatever their blank node labels and order: | ||
|
|
||
| ```python | ||
| same = fluree.canonicalize(fluree.parse(a, "trig")) == fluree.canonicalize(fluree.parse(b, "trig")) |
There was a problem hiding this comment.
Optional: the example canonicalizes away lexical forms, so two different datasets can come out equal.
fluree.parse(a, "trig") defaults to literals="value". Per docs/reference/rdf-documents.md:39-42, that reads "01"^^xsd:long as the int 1, which canonicalize then writes as "1"^^xsd:integer. So "01"^^xsd:long and "1"^^xsd:integer canonicalize alike, and "same text, same statements" is exactly what someone hashing or signing this text relies on. Claude didn't run this from Python; it follows from the documented parse behaviour and Nodes::object → ir_term. We may want literals="lexical" in the example and a sentence in _canon.py's docstring. Minor, but cheap to fold in now.
| - **When it runs:** only when called. Reading, writing and transactions never | ||
| canonicalize. | ||
|
|
||
| The implementation passes the W3C RDFC-1.0 test suite, its SHA-384, |
There was a problem hiding this comment.
Optional: let's get the W3C suite into CI, and the count is higher than the body says.
The current w3c/rdf-canon manifest (15619df) has 86 approved tests (64 eval, 21 issued-map, 1 negative), not 65. Claude ran all 86 against d31bb3134 with a manifest-driven harness, and all pass in about 0.05 s. The harness is about 50 lines (it reads manifest.jsonld, then runs eval/map/negative with the SHA-384 option), so vendoring the rdfc10/ fixtures or adding the submodule next to rdf-tests, as the body suggests, is a small step that keeps this page's claim true. I recognize this is non-blocking, but if you agree it's right I'd rather see it in this PR than lost in the backlog. Happy to share the harness Claude wrote.
There was a problem hiding this comment.
Addressed in 10b1fe7. The manifest and fixtures are vendored under fluree-graph-format/tests/rdf-canon (592 KB), so all 86 run in the test job with no workflow change.
| graph.as_ref(), | ||
| ); | ||
| } | ||
| let options = rdf::CanonicalizeOptions { |
There was a problem hiding this comment.
Optional: Python can't set the limit.
§7.1 asks for a "configurable limit", and Rust callers have CanonicalizeOptions::max_deep_calls. fluree.canonicalize always uses the default. A max_deep_calls= keyword on canonicalize / canonicalize_rdf is a few lines, and it lets a caller verifying untrusted input tighten it. Not a big deal, but worth folding in while this is open.
….0 suite A blank node is in a neighbour group once per quad it shares with the node being hashed. Every ordering of those copies was tried, though they all give one path, and none of them is a counted call: one node shared across m named graphs cost m! orderings that the limit never saw, so a 25-quad dataset ran for minutes. Only distinct orderings are made now. The W3C rdf-canon suite is vendored under fluree-graph-format/tests and all 86 of its tests run with the crate's tests. String literals are escaped by the shared N-Triples escaper, which writes U+FFFE and U+FFFF as escapes as the Recommendation asks. Python's `canonicalize` takes `max_deep_calls`, and its docs say to parse with `literals="lexical"` before hashing or signing.
Adds RDF Dataset Canonicalization (RDFC-1.0, a W3C Recommendation, formerly URDNA2015). It is a standalone utility: nothing in parsing, serializing or transacting calls it.
Two writings of the same dataset differ in their blank-node labels and statement order, so their text can't be compared, hashed or signed. RDFC-1.0 labels blank nodes
_:c14n0,_:c14n1, … from the statements alone and fixes the order, so equal datasets give equal canonical N-Quads.What's here
fluree_graph_format::canon::canonicalizeimplements the algorithm:\b \t \n \f \r \" \\, and uppercase\uXXXXfor other control characters.CanonicalizeOptions::max_deep_callssets the limit, and so doesmax_deep_calls=in Python.<<( s p o )>>, and its blank nodes are hashed as components of the quad that holds it, in the object position.rdf::canonicalize(dataset, &options), and in Pythonfluree.canonicalize(quads, hash="sha256"), which returns the canonical N-Quads text.sha2(already a workspace dependency) is added tofluree-graph-format. That adds one line each to the lockfiles of the separatetestsuite-sparql,testsuite-shaclandwasm-probeworkspaces.Fluree also needs this for Verifiable Credential checking, which is stubbed in
fluree-db-credentialwaiting on URDNA2015, and it is the planned fix for blank-node churn on graph sync. Neither is wired up here.Conformance
The W3C RDFC-1.0 test suite (
w3c/rdf-canonat15619df) passes in full, 86 of 86: 64 evaluation tests, 21 issued-identifier-map tests and the negative poison-graph test, the SHA-384 ones included. The suite's manifest and fixtures are vendored underfluree-graph-format/tests/rdf-canon(592 KB, unmodified), andtests/rdf_canon_w3c.rsruns every manifest entry with the crate's tests, so it runs in CI. The runner fails if the manifest holds a different number of tests than it expects.Tests
canonunit tests:rdf_canon_w3c.rs): all 86 manifest entries.test_canonicalize.py):hash="sha384"works, and an unknown hash is refused.max_deep_calls=lowers the limit.literals="lexical"keep a literal's spelling and datatype.