Repository navigation
feat(json-ld)!: type a number by its value, and RDF library fixes - #2364
Conversation
serde_json's default float parser reads about one in ten full-precision doubles as the neighbouring double (0.9452706955539223 as ...224), in a transaction and in rdf::parse alike. float_roundtrip parses them exactly.
…t to RDF A JSON-LD number with no @type is an xsd:double when it has a fractional part or is 10^21 or more, and an xsd:integer otherwise (JSON-LD 1.1 API 8.2.2; W3C toRdf rt01). So 1.0 and 1e3 are the integers 1 and 1000, in a transaction, a bulk import, a query's values and rdf::parse alike; they were xsd:double. A document that wants the double 1.0 gives the value its @type. An integer too large for 64 bits is kept exact as xsd:integer. The rdf library also: - writes N-Quads and N-Triples a line per statement, in order (rdf::serialize_document, Document::add_quad; fluree.serialize), where it gathered the lines by graph; - labels a parse's anonymous blank nodes with a prefix the caller gives (ParseOptions::blank_prefix; fluree.parse(blank_prefix=)), so two parses can be put together; - writes a JSON-LD number or boolean bare only where JSON-LD reads the same literal back, so a whole double and a number under another datatype keep their @type.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz this is a nice one, and at a design level no pushback from me: one JsonNumber reading that every reader goes through is the right altitude, and the claims hold up (Claude switched the by-value rule off and it_jsonld_number_by_value goes red; with both fixes reverted, 4 of the 7 toRdf cases fail, as you say). A few headline notes:
(1) On the release line, I said on #2283 that next was overkill for those fixes, but I think it's right for this one: it changes what every client that keeps the .0 stores on its most ordinary writes, and it can turn a working write into a SHACL rejection. The float_roundtrip commit (32ce2d4f5) is the opposite case, though. Main stores the wrong double for some full-precision floats today, which is the same "silently wrong today, so don't hold it for 5.0" reasoning as @index/@json on #2283. It cherry-picks cleanly onto main, and I'd like it there too.
(2) exact_native_values is exactly #2294's fix, but only rdf::serialize opts in. With the reader now spec-correct, CONSTRUCT's Fluree-to-Fluree round trip loses a whole double too (Claude reproduced it), so I think flipping the default here (or opting CONSTRUCT in) is worth doing in this PR, on 5.0 where that output change belongs.
(3) This is the eighth JSON-LD conversion deviation we've found by hand (the seven I listed on #2283, plus this one; #2294 is the same thing on the writer side). The five toRdf cases you ported into to_rdf_numbers.rs are the W3C suite in miniature. Not for this PR, but it's more evidence for running the suite with a skip register that can only shrink.
The two musts below are small: the red test job (it_query_negation still expects 3.0) and the upgrade note, which needs the consequences a 4.x user will actually hit plus the repair update.
Full review below:
Approving to unblock but take a look at some of these please
This is carefully built, @bplatz: the by-value rule lives in one place every JSON-LD reader shares, the W3C cases are pinned by number, and the RDF library pieces (line-order N-Quads, blank_prefix, typed numbers on write) are each small and well-tested. The two things holding it are small. The test job is red on this head because it_query_negation still expects 3.0. And the upgrade note needs the consequences a 4.x user writing doubles will actually hit (a second value on re-insert, SHACL rejections) plus the repair update, which is the floor we set on #2283. The optional notes are fold-it-in-now items: opting CONSTRUCT into exact_native_values (#2294), the two readers still outside JsonNumber, a bound on the "kept exact" sentence, and the i64::MIN boundary.
On cost, Claude measured float_roundtrip on a clean box, and the body's 9% understates the float-only case. Parsing a 34.7 MB array of shortest-spelling doubles went from 87.3–87.4 to 105.1–105.3 ms (best of 21, three rounds; about +20%), and 18-digit doubles about +46%. A 21.5 MB transaction-shaped insert didn't move (186.8–187.4 vs 185.4–188.4 ms, within noise). It's the price of reading the number that was sent, so no objection from me; maybe just update the body's Cost section.
Adherence to repo commitments:
- Patterns/abstractions: ✔ One
JsonNumberchokepoint in graph-ir that every swapped reader calls, over an existing dependency;exact_native_valuesextendsJsonLdFormatConfigrather than adding a writer.⚠️ Two readers still outside it (SPARQL parameters, the typed integer branch) and two writers that don't opt in (CONSTRUCT, ontology). - Performance (speed first, memory second): ✔ No query-engine or index path changes; the by-value check is a
fract()and a compare per untyped float on the parse path.float_roundtripcosts about +20% on float-only JSON and nothing measurable on transaction-shaped JSON (clean-box A/B). No performance-degradation risk. - Deployment targets: ✔ Pure parse and format code with no background work, caches or I/O, so host-neutral across the embedded library,
fluree-db-serverand wasm32 (wasm32andwasm-smokegreen).float_roundtripreaches an embedder's whole binary through Cargo feature unification, so everyserde_jsonparse there gets the same correctness and cost; maybe worth a line in the notes. - Testing: ✖
testis red on this head (one stale expectation). Otherwise good: the new tests run in CI by name, and Claude's mutation checks confirm they bite. - Conventions: ✔ Multi-line commits with full bodies; docs updated in
compatibility.md,rdf-documents.mdand the Python README.⚠️ The Behavior-changes entry is missing the consequences and repair above.
Verified at branch HEAD (14695d293) on an EC2 box: the PR's integration and toRdf tests pass, the negation test fails as CI shows, the mutation checks bite (by-value off: it_jsonld_number_by_value red; both fixes off: 4 of 7 toRdf red), probes for re-insert, upsert, SHACL sh:datatype/sh:maxCount, the CONSTRUCT round trip, big integers and the repair update, and a serde_json A/B with and without float_roundtrip.
Just be sure to get the test fix and the fuller note in before this merges; the rest I'd love to see here too, but they're yours to weigh.
| JsonNumber::Double(f) | ||
| } else if f.abs() < 9_223_372_036_854_775_808.0 { | ||
| // Exact: an integral double below 2^63. `-0.0` is `0`. | ||
| JsonNumber::Integer(f as i64) |
There was a problem hiding this comment.
Blocking (CI). The test job is red on this head (run 43270493838, 1 failure of 16,412), and it's this change: inner_filter_not_exists_vs_minus_behavior (it_query_negation.rs:781 and :801) inserts "ex:p": 3.0 and still expects 3.0 back.
With the by-value rule that value is now the integer 3, so both assertions compare Number(3) against Number(3.0). Claude reproduced the failure at 14695d293 and confirmed the cause: with this line switched back to a double, the test passes.
The value is incidental to what the test checks (NOT EXISTS vs MINUS scoping), so 3 in both expectations is the fix:
assert_eq!(r1, json!([["ex:b", 3]]));
// …
normalize_rows(&json!([["ex:a", 1], ["ex:b", 3]]))Commenting here because fluree-db-api/tests/it_query_negation.rs is not in this diff.
|
|
||
| A JSON-LD number with no `@type` now takes the datatype JSON-LD 1.1 gives it, which goes by the number's value: `xsd:double` with a fractional part (or from 10^21), `xsd:integer` otherwise. Earlier releases went by its spelling, so `1.0` and `1e3` were stored as `xsd:double`; they are now the integers `1` and `1000`, in a transaction, a bulk import and a query's `values` alike. The same document then stores the same data whichever client sends it: a JavaScript client never could send `1.0`, since its JSON writer drops the `.0`. An integer too large for 64 bits is kept exact as an `xsd:integer` rather than rounded into a double. | ||
|
|
||
| **Check clients whose JSON writer keeps the `.0`** (Python, Java, Rust). A property they wrote as doubles now takes an integer for each whole value unless the value is typed: `{"@value": 1.0, "@type": "xsd:double"}`, or a context term with `"@type": "xsd:double"`. Data already written stays as it is, so a delete that names a stored double as a bare `1.0` no longer removes it; name it with its type, or bind it in `where`. A query result writes a stored `xsd:double` as a bare number, so a whole one sent back untyped is an integer. Comparisons, a bare number in a query pattern and aggregates go by value, and are unchanged. A number in a filter expression is read as before. |
There was a problem hiding this comment.
Blocking (upgrade note). This is the floor we set on #2283 (the Behavior-changes entry plus a repair update), and the entry is most of the way there. What it doesn't name is what a 4.x user writing doubles from Python, Java or Rust will actually run into on a ledger that already holds 10.0^^xsd:double. Claude reproduced each of these at this head:
- Re-inserting the same document now adds a second value,
10^^xsd:integerbeside the stored double.COUNT(DISTINCT ?v)is 2,GROUP BY ?vgives two groups, and a JSON-LDwherewith10.0returns the subject twice. - With SHACL on, a
sh:datatype xsd:doubleshape rejects a bare10.0("Expected datatype double but found integer") while9.5passes, so whether a write succeeds depends on the value. Ash:maxCount 1shape rejects the re-insert above, which used to be a no-op. - An upsert rewrites the value once (the double retracted, the integer asserted) and is a no-op after that.
And the repair, which I think belongs as a bullet in "Data written by an earlier release that reads differently" (line 489). Claude ran this one on the mixed ledger: whole doubles become integers (10.0 merges into the existing 10, 7.0 becomes 7) and 2.5 stays a double:
DELETE { ?s ex:price ?old } INSERT { ?s ex:price ?new }
WHERE { ?s ex:price ?old FILTER(DATATYPE(?old) = xsd:double && ?old = FLOOR(?old) && ABS(?old) < 1e21) BIND(xsd:integer(?old) AS ?new) }The other direction you already give (type the term xsd:double), and Claude confirmed that writes no second value against the stored double.
| /// written `{"@value": 1.0, "@type": "xsd:double"}`, and a number or | ||
| /// boolean under another datatype keeps that datatype. When false | ||
| /// (default), each is the bare value. | ||
| pub exact_native_values: bool, |
There was a problem hiding this comment.
Optional (design). This is the one design note I'd most like to see land here. exact_native_values is exactly the fix #2294 asks for, but only rdf::serialize opts in (fluree-db-api/src/rdf.rs:722). CONSTRUCT (fluree-db-api/src/format/construct.rs:58, via construct_parity) and the ontology writer (fluree-db-ontology/src/write.rs:389) keep the bare default.
Before this PR, Fluree's own reader read a bare 10.0 back as a double, which is why #2294's integral-double row survived a Fluree-to-Fluree round trip. After it, that round trip loses it too: Claude ran a CONSTRUCT over a stored 10.0^^xsd:double, got "ex:price": [10.0], inserted that into a fresh ledger and got 10^^xsd:integer.
Only CONSTRUCT, the service description, rdf.rs and the ontology writer build a JsonLdFormatConfig (SELECT rows and graph crawl have their own formatter), so maybe the cleanest fix is flipping this default to true. That leaves SELECT output as it is and closes #2294 for CONSTRUCT on 5.0, which is where that output change belongs anyway. Opting construct_parity in is the narrower version. A few CONSTRUCT expectations will likely move. It's arguably past the title, but it's a one-line change that the reader change makes visible, so if you agree it's right, I'd rather see it in this PR than lost in the backlog.
There was a problem hiding this comment.
Addressed in a47cede — the setting is removed rather than defaulted on, so every JSON-LD writer keeps the datatype.
| //! value, not its spelling: one with a fractional part, or of 10^21 and | ||
| //! more, is an `xsd:double`, and any other an `xsd:integer`. So `1.0`, `1e3` | ||
| //! and `-0e0` are the integers `1`, `1000` and `0`. Every reader of JSON-LD | ||
| //! data (the RDF reader, a transaction, a bulk import, a query's constants) |
There was a problem hiding this comment.
Optional. "Every reader of JSON-LD data … goes through here" holds for every site this PR swaps, and Claude grepped for the rest. Two readers of JSON-LD-form numbers still read their own way:
fluree-db-sparql/src/params.rs:168-172: SPARQL parameters are documented as "the JSON-LD forms" (params.rs:19) but read1.0as anxsd:double, soINSERT { ex:s ex:p $x }withx = 1.0stores a double where a JSON-LD insert of1.0stores an integer.fluree-db-core/src/coerce.rs:623-647: the typed integer-family branch is i64-only.{"@value": 18446744073709551615, "@type": "xsd:integer"}in a transaction is refused ("Number 18446744073709552000 is out of range", Claude ran it) while the untyped form is now stored exact, and bulk import keeps the typed form exact (fluree-graph-json-ld/src/adapter.rs:859). So the sentence this PR deletes fromcompatibility.md:83still describes a real difference, now for the typed form only.
Both are a few lines: JsonNumber::read in Value::parse, and for unbounded xsd:integer a fallback through JsonNumber::read to a BigInt (with validate_bigint_range for the bounded subtypes). Minor and non-blocking, but since this PR owns the chokepoint, I'd rather see them folded in now than lost in the backlog.
There was a problem hiding this comment.
Addressed in a768a36 — also the removal selector that came in with the next merge (retention/removal.rs), which rounded an integer past i64 to a double and so matched nothing.
|
|
||
| #### A JSON-LD number is typed by its value (breaking) | ||
|
|
||
| A JSON-LD number with no `@type` now takes the datatype JSON-LD 1.1 gives it, which goes by the number's value: `xsd:double` with a fractional part (or from 10^21), `xsd:integer` otherwise. Earlier releases went by its spelling, so `1.0` and `1e3` were stored as `xsd:double`; they are now the integers `1` and `1000`, in a transaction, a bulk import and a query's `values` alike. The same document then stores the same data whichever client sends it: a JavaScript client never could send `1.0`, since its JSON writer drops the `.0`. An integer too large for 64 bits is kept exact as an `xsd:integer` rather than rounded into a double. |
There was a problem hiding this comment.
Optional (docs). Not a big deal, but "An integer too large for 64 bits is kept exact" holds up to u64::MAX only. Past that serde_json has already rounded the number to a double, and what's stored is that double's digits: Claude inserted 123456789012345678901 and got "123456789012345683968"^^xsd:integer (your to_rdf_numbers.rs:156 pins the same thing for 999999999999999900000). It's what jsonld.js does too, so the behavior is right; maybe just bound the sentence, e.g. "An integer up to 18446744073709551615 is kept exact; a larger one has already been read as a double, and is stored as that double's integer value." The PR body has the same sentence.
| let f = n.as_f64()?; | ||
| Some(if f.fract() != 0.0 || f.abs() >= 1e21 { | ||
| JsonNumber::Double(f) | ||
| } else if f.abs() < 9_223_372_036_854_775_808.0 { |
There was a problem hiding this comment.
Nit. So minor, but f.abs() < 2^63 sends exactly -9223372036854775808.0 (i64::MIN, which fits) to BigInteger. Claude ran it: the float spelling is stored as a BigInt and comes back as the string "-9223372036854775808", where the integer spelling comes back as a number. parse_string_to_integer (coerce.rs:775) keeps Long-whenever-it-fits, and the half-open range keeps that convention:
| } else if f.abs() < 9_223_372_036_854_775_808.0 { | |
| } else if (-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&f) { |
The value is incidental to what the test checks (NOT EXISTS against MINUS scoping); under the by-value rule the inserted 3.0 is the integer 3.
The integral-double range check was |f| < 2^63, which sent i64::MIN to BigInteger, so the float spelling came back as a string where the integer spelling comes back as a number. The half-open range keeps a value as an i64 whenever it fits, as parse_string_to_integer does.
… read a number by its value
Three readers of JSON-LD-form numbers still read their own way:
- A SPARQL parameter read 1.0 as an xsd:double, so INSERT { ?s ex:p $x }
with x = 1.0 stored a double where a JSON-LD insert stores an integer.
- A typed integer-family value was i64-only: {"@value":
18446744073709551615, "@type": "xsd:integer"} was refused while the
untyped form is stored exact, and 2^63 written as a float saturated to
i64::MAX. It now reads through JsonNumber to a BigInt, range-checked for
the bounded subtypes.
- A removal selector rounded a bare integer past i64 to a double, which
equals no stored integer (a double and a big integer compare exactly),
so selecting 18446744073709551615 removed nothing.
The JSON-LD writer wrote every integer and finite double bare unless the caller opted into exact_native_values, which only rdf::serialize did. With the reader now typing a bare 10.0 as an integer, a CONSTRUCT round trip of a stored whole xsd:double came back as xsd:integer, and xsd:int, xsd:long and xsd:float values lost their datatype as before. Every JSON-LD writer (CONSTRUCT, rdf::serialize, the ontology writer, the service description) now writes a number or boolean bare only where a JSON-LD reader gets the same literal back, and the setting is gone. SELECT rows have their own formatter and are unchanged. Addresses #2294.
…epair The by-value entry now names what a client that keeps the .0 runs into on a ledger that already holds 10.0^^xsd:double: a second value on re-insert, an upsert that swaps the double once, a bare-10.0 delete that misses, and SHACL datatype and maxCount rejections. It bounds the kept-exact sentence at u64::MAX, records the CONSTRUCT output change, and adds a one-update repair under the earlier-data section.
|
The |
Brings #2389 and #2391. - #2389 (JSON numbers read as the nearest double) is the float_roundtrip change next already took in #2364; it adds main's Cargo.toml comment, the coerce test, and the compatibility entries. Next's own paragraph under "A JSON-LD number is typed by its value" now points to the fuller entry instead of repeating it with the older "16 or 17 digits". - #2391 (raft compact_log, and the propose relay's log id) merges as is: next's only raft-core change since the last merge, a loaded snapshot applying its membership, does not touch compaction or the relay, and nothing outside raft-core implements its storage traits or calls propose_via_leader.
What this changes
A JSON-LD number is typed by its value (breaking). A number with no
@typeis anxsd:doublewhen it has a fractional part or is 10^21 or more, and anxsd:integerotherwise, as JSON-LD 1.1 API § 8.2.2 converts it to RDF. So1.0and1e3are now the integers1and1000; they were stored asxsd:double. The W3C testtoRdf/rt01requires this (-0e0is"0"^^xsd:integer), and it failed before.One reading is shared by a transaction, a bulk import, transaction metadata, a query's
valuescells and patterns, a SPARQL parameter, a removal selector, andrdf::parse(fluree_graph_ir::JsonNumber). A document that wants the double1.0gives the value its type:{"@value": 1.0, "@type": "xsd:double"}, or a context term typedxsd:double. An integer up to 18446744073709551615, typedxsd:integeror untyped, is kept exact rather than rounded into a double; a larger one has already been read as a double by the JSON parser, and is stored as that double's integer value.A number of 16 or 17 significant digits reads as the nearest double.
serde_json's default float parser read about one in ten of them as the neighbouring double (0.9452706955539223as…224; 210,588 of 2,000,000 random doubles). The workspace now builds it withfloat_roundtrip, which covers every JSON parse, transactions included. Through Cargo feature unification an embedder's whole binary gets the same parser.JSON-LD output keeps a number's datatype. CONSTRUCT,
rdf::serialize, the ontology writer and the service description write a number or boolean bare only where JSON-LD reads the same literal back: a wholexsd:doubleis written{"@value": 10.0, "@type": "…#double"}, and a number or boolean under another datatype (xsd:int,xsd:long,xsd:float, a datatype of your own) keeps its@type. With the reader now typing10.0as an integer, a CONSTRUCT round trip would otherwise turn a stored whole double into an integer. This is the one way the writer works; the opt-inexact_native_valuessetting is gone.The RDF library (
fluree_db_api::rdf, Pythonfluree.parse/fluree.serialize):rdf::serialize_document,Document::add_quad). They were gathered by graph, and a Python test asserted that; it now asserts the order given.ParseOptions::blank_prefix(Pythonblank_prefix=) labels a parse's anonymous blank nodes{prefix}Nin place ofbN, so the quads of two parses can be put together. Labels a document writes are kept.Fixes #2294
What users will notice
.0(Python, Java, Rust) now stores an integer for each whole value unless the value is typed. A JavaScript client already did, since its writer drops the.0.10.0^^xsd:double, re-inserting the same document adds10^^xsd:integerbeside it, an upsert swaps the double for the integer once, and a delete that names the double as a bare10.0no longer removes it. Under SHACL, ash:datatype xsd:doubleshape rejects a bare whole number, and ash:maxCount 1shape rejects that re-insert.docs/reference/compatibility.mdrecords the change under "A JSON-LD number is typed by its value (breaking)", and gives a one-update repair (whole doubles to integers) under "Data written by an earlier release that reads differently".@typeon whole doubles and on numbers and booleans under other datatypes, where it wrote bare numbers.Left as it was
xsd:doubleas a bare number, so a whole one sent back untyped is an integer.@containervalues@id,@typeand@graph, and remote contexts, are still refused.Cost
float_roundtripis the only cost. On a quiet box (best of 21, three rounds): a 34.7 MB array of shortest-spelling doubles parses in 105.1–105.3 ms against 87.3–87.4 ms (about +20%), and 18-digit doubles take about 46% longer. A 21.5 MB transaction-shaped insert does not move (186.8–187.4 ms against 185.4–188.4 ms). The by-value rule is afract()and a compare per untyped float on the parse path.Testing
fluree-db-api/tests/it_jsonld_number_by_value.rs: an insert, avaluesmatch and a delete with1.0; a typedxsd:integerandxsd:unsignedLongpast i64 stored exact, andxsd:longrefused; a removal selector naming18446744073709551615removing that stored integer (it read as the double 2^64 and matched nothing). The first fails with the by-value rule switched off.fluree-graph-json-ld/tests/to_rdf_numbers.rs: W3CtoRdfcases0022,0023,0035,e061andrt01, and the last-digit case. Four of these fail with the two fixes reverted.JsonNumberat the i64 bounds, the typed integer coercion past i64, SPARQL parameters by value, the writer's datatype rule, the N-Quads order and the blank prefix; Python tests for each library change.