Repository navigation
fix(json): read a JSON number as the nearest double - #2389
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.
aaj3f
left a comment
There was a problem hiding this comment.
@bplatz thanks for carrying this over, and at a design level no pushback from me. It's the cherry-pick I asked for on #2364 (with a test standing in for to_rdf_numbers), and one feature switch is the right altitude: Cargo unifies it across the build, so it also fixes an embedder who parses their own JSON and hands us a Value, which no Fluree-only parser could reach.
Two headline notes.
(1) Per what we settled on #2283, a data-changing fix like this goes on main with a Behavior-changes entry and a repair recipe, and main has no entry yet (on next it's one paragraph inside #2364's typing entry). Claude ran a ledger written by main's build through this head, and the consequences are the ones a user will hit: a where or delete naming the number stops reaching the stored value, a re-insert adds a second value, and an xsd:decimal written as a JSON number keeps its changed digit. Since nothing tells a misread value apart, "upsert the source documents again" is the recipe; draft text is inline.
(2) On cost I'm on board. float_roundtrip isn't the fast correct algorithm (std's str::parse is correct and quicker than serde_json's wrong default), but nothing cheaper is reachable from serde_json, and end to end only embedding-heavy inserts move, about 6.6%. Good to merge once the entry is in.
Full review below:
✅ Approving to unblock: please get the Behavior-changes entry in before merging.
Thanks for bringing this over, @bplatz. It's the one-line fix that makes every JSON reader store the number that was sent, and it also closes a JSON-LD ↔ SPARQL gap on main: Claude found that main stores a JSON-LD write of 0.9452706955539223 where a SPARQL "0.9452706955539223"^^xsd:double can't find it, and a Turtle write of the same literal where a JSON-LD where can't. The one must is the entry and repair recipe for data written before the upgrade (inline on Cargo.toml:75), the floor we set on #2283. The other two inline notes are small fold-it-in-now items: the comment's scope wording and a decimal assertion in the test.
On cost, Claude measured main's merge base against this head on a clean c7i.4xlarge, best ms of each of three interleaved rounds:
| Workload | main | this PR |
|---|---|---|
| serde_json alone: 1.8M doubles, shortest spelling | 91.91–92.57 | 111.24–113.19 (+21%) |
| serde_json alone: 1.8M doubles, 17 / 18 digits | 93.47–94.25 / 96.04–96.95 | 134.07–136.49 / 137.51–138.88 (+43%) |
| serde_json alone: 1.8M f32 embeddings as f64 | 102.94–103.52 | 123.11–124.80 (+20%) |
| serde_json alone: 1.8M integers | 76.55–77.44 | 76.94–78.96 (noise) |
| serde_json alone: transaction-shaped, 21.5 MB | 194.92–199.14 | 192.68–195.35 (noise) |
| Fluree insert: 2k nodes × 768-dim vectors | 247.10–249.15 | 263.44–264.45 (+6.6%) |
| Fluree insert: 10k nodes × 10 doubles | 656.28–657.80 | 649.88–654.63 (noise) |
| Fluree insert: transaction-shaped, 20k nodes | 1343.79–1397.86 | 1338.50–1348.14 (noise) |
| Fluree insert: 10k nodes × 10 integers | 478.68–487.32 | 483.18–486.32 (noise) |
JSON-LD query with values of 20k doubles |
56.03–56.22 | 55.61–56.23 (noise) |
| Bulk import: 1M double flakes | 3070.7–3106.7 | 3043.2–3107.5 (noise) |
So the only workload that moves end to end is an embedding-heavy insert, where parsing is 26–30% of the time. float_roundtrip isn't the fast correct algorithm: per number, std's correctly rounded str::parse takes 15.7–17.7 ns on these doubles, quicker than serde_json's wrong default at 21.7–24.9 ns, while float_roundtrip takes 37.3–52.8 ns. But nothing cheaper is reachable from serde_json: arbitrary_precision reads correctly and is 2.6–2.9× slower than the default on the same documents, and it changes serde_json::Number for every embedder. So no objection from me; the remaining gap is serde_json's to close upstream.
Adherence to repo commitments:
- Patterns/abstractions: ✔ One workspace feature that every JSON reader inherits, no new parser. Claude found no text-to-double reader outside it: every other one already uses std's correctly rounded
str::parse(SPARQL, Turtle, Cypher, CSV import,xsd:doublelexical forms, filters, casts). - Performance (speed first, memory second): ✔ No engine or index change. Raw float parsing is 20–43% slower; end to end only embedding inserts move (+6.6%), and transactions, integers, queries and bulk import are within noise. No cheaper correct option is reachable from serde_json. No performance-degradation risk on the engine.
- Deployment targets: ✔ Pure parse code, host-neutral.
cargo treeshows the feature reaching the server, the no-default parse layer on wasm32,fluree-db-wasm,wasm-probeand the Python extension; at main's merge base no build Claude checked had it (the server, the API without default features, the whole workspace with all features). The wasm bundle grows 0.19% (26 KB raw). It also reaches an embedder's ownserde_jsonparsing, which the entry should say. - Testing: ✔ The new test runs in CI by name on this head, and Claude's mutation check confirms it bites (without the feature it reads
…3dinstead of…3c).⚠️ It pins the double only; the decimal assertion inline would pin the case where stored digits change. - Conventions: ✔ Self-describing title, multi-line body. ✖ No
compatibility.mdentry for a change to what gets stored (inline).
Verified at branch HEAD (7266ee07f): CI green on this SHA (the test job ran 16,026 tests, the new one included); on an EC2 box, the mutation check, the serde_json and end-to-end A/B above, correctness probes across JSON-LD, Turtle, SPARQL, xsd:decimal and @json, and a ledger written by main's build then read and modified by this one.
Approving so you can merge once the entry is in; the two small notes I'd love to see here too.
| serde_json = { version = "1.0", features = ["preserve_order"] } | ||
| # float_roundtrip: without it a number of 16-17 significant digits can read | ||
| # as the neighbouring double (0.9452706955539223 as ...224). | ||
| serde_json = { version = "1.0", features = ["preserve_order", "float_roundtrip"] } |
There was a problem hiding this comment.
Blocking (small): this needs its Behavior-changes entry and a repair recipe, as we settled for #2283.
On #2283 we agreed that data-changing fixes like this one ship on main (next was overkill) with an entry in docs/reference/compatibility.md that names the changed writes, what they mean for data already stored, and how to repair it. This PR changes the double stored for roughly one full-precision JSON number in ten, and main's compatibility.md doesn't mention it. On next it's one paragraph inside #2364's typing entry (compatibility.md:418 there), which main doesn't have, and that paragraph has no consequences or repair either.
Claude wrote a ledger with main's build (f1826fd05) and then read and modified it with this head, indexed and unindexed alike. For {"@id": "ex:a", "ex:p": 0.9452706955539223} written before the upgrade:
- the stored double stays
0.9452706955539224, and a stored{"@value": 0.9452706955539223, "@type": "xsd:decimal"}keeps the decimal0.9452706955539224; - a JSON-LD
wherenaming the number finds nothing (one row on main's build), and neither does the typed-decimalwhere; - a delete naming the number removes nothing;
- re-inserting the document adds a second value beside the stored one;
- an upsert of the document replaces it with the nearest double, after which the
wherematches again; FILTER(ABS(?v - 0.9452706955539223e0) < 1e-15)finds it on either build.
Nothing in the ledger tells a misread value from one that was sent as written (the neighbour is a valid double too), so I think the recipe is "upsert the source documents again", plus the tolerance filter for lookups that need to reach both. Something like this under Behavior changes, with a bullet pointing to it from "Data written by an earlier release that reads differently":
#### A JSON number reads as the nearest double
A JSON number is now read as the double nearest to it, as the SPARQL and Turtle readers already did. Roughly one in ten numbers written with 16 or more significant digits (one in six at exactly 17), and some with an exponent past ±22 (`1e-30`), used to read as a neighbouring double: `0.9452706955539223` was stored as `0.9452706955539224`. This applied to every JSON reader (a transaction, a bulk import, a JSON-LD query's `where` and `values`), including an `xsd:decimal` or `@json` value written as a JSON number, and a SPARQL literal did not match a value written through JSON-LD.
Data already written stays as it is. For a value an earlier release misread, a JSON-LD pattern or delete that names the number no longer reaches it, inserting the same document again adds a second value beside it, and an upsert replaces it. Fluree cannot tell such a value from one sent as written: upsert the source documents again to repair a property, or match within a tolerance, for example `FILTER(ABS(?v - 0.9452706955539223e0) < 1e-15)`.
An application that embeds `fluree-db-api` gets the same reading for its own `serde_json` parsing, because Cargo enables `float_roundtrip` for the whole build. Parsing JSON that is mostly floats takes about 20–43% longer; a transaction-shaped document parses as fast as before.When main is next merged into next, the paragraph at :418 there and this entry will both be present, so one of them should go then.
Commenting here because docs/reference/compatibility.md is not in this diff.
| async-trait = "0.1" | ||
| serde = { version = "1.0", features = ["derive"] } | ||
| serde_json = { version = "1.0", features = ["preserve_order"] } | ||
| # float_roundtrip: without it a number of 16-17 significant digits can read |
There was a problem hiding this comment.
Optional (wording): this is more of a nit than a suggestion, but "16-17 significant digits" undersells it a little. Claude measured the default reader on 1.8M numbers of each shape: 17.5% read wrong at 17 digits, 10.7% at 18, and 27.2% for doubles spread across 1e-300..1e300. Short numbers with a large exponent are hit too: on a real default build, 1e-30 reads as 9.999999999999999e-31 and 1.5e40 as 1.4999999999999999e40. serde_json's default f64_from_parts (1.0.149, de.rs:638-671) is one multiply or divide by a power of ten, so it's exact only when the significand fits in 53 bits and the exponent is within ±22. Maybe:
# float_roundtrip: without it a number of 16 or more significant digits, or
# with an exponent past ±22, can read as a neighbouring double
# (0.9452706955539223 as ...224, 1e-30 as 9.999999999999999e-31).Minor and non-blocking, but if you agree it's right I'd rather see it folded in now (the test's doc comment too) than lost in the backlog.
| let Ok(FlakeValue::Double(d)) = coerce_json_value(&json, xsd::DOUBLE) else { | ||
| panic!("expected a double"); | ||
| }; | ||
| assert_eq!(d.to_bits(), 0.945_270_695_553_922_3_f64.to_bits()); |
There was a problem hiding this comment.
Optional (test): not a big deal, but one more assertion here would pin the place where this shows up as changed digits rather than a one-ULP double. The decimal branch of coerce_json_value (coerce.rs:613-620) stores the number's shortest spelling and says that "recovers the written lexical", which only holds with this feature: on main's build Claude's probe stored {"@value": 0.9452706955539223, "@type": "xsd:decimal"} as the decimal 0.9452706955539224. Something like:
let Ok(FlakeValue::Decimal(dec)) = coerce_json_value(&json, xsd::DECIMAL) else {
panic!("expected a decimal");
};
assert_eq!(dec.to_string(), "0.9452706955539223");Minor and non-blocking, but if you agree it's right I'd rather see it in this PR than lost in the backlog.
Behavior-changes entry for float_roundtrip, and a bullet for values an earlier release read as a neighbouring double, with the repair. The Cargo.toml comment and the test now cover an exponent past ±22, and the test pins the xsd:decimal branch, which stores 0.9452706955539224 without float_roundtrip.
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.
Problem
serde_json's default float parser computes a number as its significand multiplied or divided by one power of ten. That is exact only when the significand fits in 53 bits and the exponent is within ±22; outside it, the result can be the neighbouring double.0.9452706955539223reads as0.9452706955539224(210,588 of 2,000,000 random doubles), and1e-30as9.999999999999999e-31.Every JSON parse goes through it, so a transaction, a bulk import, and a JSON-LD query's
whereandvaluesstore or match the wrong double with no error, as does anxsd:decimalor@jsonvalue written as a JSON number. A SPARQL or Turtle literal, read with std's correctly roundedstr::parse, does not match the same number written through JSON-LD.Fix
The workspace's
serde_jsondependency enablesfloat_roundtrip, which parses every number as the nearest double. Through Cargo feature unification, an embedder's whole binary gets the same parser, including its ownserde_jsonparsing.A value stored by an earlier release keeps the double it was given.
docs/reference/compatibility.mdgets a Behavior-changes entry, "A JSON number reads as the nearest double", and a bullet under "Data written by an earlier release that reads differently": a JSON-LD pattern or delete naming such a value no longer reaches it, a re-insert adds a second value, and an upsert replaces it. The repair is to upsert the source documents again, or to match within a tolerance.Cost
Only parsing documents that are mostly floats is slower. 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).
End to end (measured in review), an insert of 2k nodes with 768-dimension vectors takes about 6.6% longer; transactions, integer-heavy inserts,
valuesqueries and bulk import are within noise. Nothing cheaper is reachable fromserde_json:arbitrary_precisionis 2.6–2.9× slower and changesserde_json::Numberfor every embedder.Testing
coerce::tests::a_full_precision_number_reads_as_the_nearest_doublereads0.9452706955539223as anxsd:doubleand as anxsd:decimal. Each assertion fails withoutfloat_roundtrip: the double is one ULP up, and the decimal stores0.9452706955539224.This is the
float_roundtripcommit from #2364 (intonext), cherry-picked for main, since main stores these values wrong today. When main is next merged intonext, the one-line note innext'scompatibility.md(the paragraph ending the JSON-LD typing entry) should give way to this entry.