Skip to content

Commit ebdb5de

Browse files
authored
Merge pull request #1366 from cipherstash/fix/json-float-roundtrip
2 parents bf42fc5 + ff287a3 commit ebdb5de

4 files changed

Lines changed: 146 additions & 2 deletions

File tree

‎packages/stack-encrypt/CHANGELOG.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## [Unreleased]
99

10+
### Fixed
11+
12+
- **A float in a JSON index document opens to the value that was sealed**
13+
(#1364). A number leaf is stored as its shortest round-trip text and
14+
parsed back when its entry or the sealed root opens, and serde_json's
15+
default float parser can land one unit in the last place off the `f64`
16+
that text names: `-926809.5051008083` opened as `-926809.5051008085`,
17+
through `JsonDocument`, `JsonNode` and `JsonSubtree` alike. The crate now
18+
builds serde_json with `float_roundtrip`, whose parser returns the
19+
nearest `f64`. The trade is slower float parsing and slightly more code.
20+
Cargo unifies features, so every serde_json parse in a program that links
21+
this crate (the caller's own included) uses that parser. Integers and
22+
short decimals were never affected, and the read side derives no term
23+
from the value it parses.
24+
1025
### Added
1126

1227
- **A JSON index, `target::Json`** (`docs/plans/2026-10-17-json-tree-index.md`,

‎packages/stack-encrypt/Cargo.toml‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,14 @@ ore-rs = { workspace = true }
7272
# can act) and gives its structured fields as a `serde_json` map through
7373
# `ErrorPayload`. Both are already in the graph through stack-kms.
7474
miette = { workspace = true }
75-
serde_json = { workspace = true }
75+
# `float_roundtrip`: the JSON index stores a number leaf as its shortest
76+
# round-trip text and parses it back when the entry or the sealed root
77+
# opens (`json::derive::decode_node`, `json::plain::PlainJson::parse`).
78+
# serde_json's default float parser is fast and can land one unit in the
79+
# last place off the `f64` that text names; this one returns the nearest
80+
# `f64`, so the value opens to the one sealed (#1364). It costs slower
81+
# float parsing and a little more code, and nothing new is compiled.
82+
serde_json = { workspace = true, features = ["float_roundtrip"] }
7683
thiserror = { workspace = true }
7784
uuid = { workspace = true }
7885
zeroize = { workspace = true }

‎packages/stack-encrypt/proptest-regressions/json_index.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@
44
#
55
# It is recommended to check this file in to source control so that
66
# everyone who runs the test benefits from these saved cases.
7+
cc 3a9d08b71f8b70cf7c0cebd989de39291421711362e5e5267242443d02e2c037 # shrinks to -5.7483763378806435e-244

‎packages/stack-encrypt/tests/json_index.rs‎

Lines changed: 122 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1720,7 +1720,7 @@ mod given_generated_documents {
17201720
/// proptest's defaults, which read `PROPTEST_CASES` and
17211721
/// `PROPTEST_RNG_SEED`, with this suite's own default for each one left
17221722
/// unset.
1723-
fn config() -> Config {
1723+
pub(super) fn config() -> Config {
17241724
let mut config = Config::default();
17251725
if std::env::var_os("PROPTEST_CASES").is_none() {
17261726
config.cases = DEFAULT_CASES;
@@ -2124,6 +2124,127 @@ mod given_generated_documents {
21242124
}
21252125
}
21262126

2127+
mod given_a_float_at_full_precision {
2128+
//! A number leaf is stored as its shortest round-trip text and parsed
2129+
//! back when it opens: from the sealed root's document text, or from
2130+
//! the node's own entry. Only serde_json's `float_roundtrip` parser
2131+
//! promises the nearest `f64` to that text; without it a value can come
2132+
//! back one unit in the last place off (#1364). Each case seals a
2133+
//! document holding the number and reads it back every way the column
2134+
//! hands it out, comparing bit patterns.
2135+
2136+
use proptest::prelude::*;
2137+
use proptest::test_runner::TestRunner;
2138+
2139+
use super::*;
2140+
2141+
/// The value a property test found coming back as
2142+
/// `-926809.5051008085` (#1364).
2143+
const FOUND: f64 = -926_809.505_100_808_3;
2144+
2145+
/// The document a case seals: the number as an array element under a
2146+
/// key, so a walk under `$.list` and the extracted element both reach
2147+
/// it. Its entries, by ordinal: `$`, `$.list`, `$.list[0]`.
2148+
fn document(f: f64) -> Value {
2149+
json!({"list": [f]})
2150+
}
2151+
2152+
/// The number back out of each way of reading it, named.
2153+
async fn read_back(cipher: &Cipher, f: f64) -> Vec<(&'static str, Value)> {
2154+
let value = document(f);
2155+
let sealed = seal(cipher, &value).await;
2156+
let entries = seal_with(cipher, &value, &open_root()).await;
2157+
let key = subtree_key(cipher, "$.list", JsonOptions::default())
2158+
.await
2159+
.unwrap();
2160+
let rows = subtree_nodes(&sealed, key.token_bytes());
2161+
let element = sealed.node(2).unwrap();
2162+
vec![
2163+
(
2164+
"the document, from the sealed root",
2165+
open(cipher, sealed).await.unwrap()["list"][0].take(),
2166+
),
2167+
(
2168+
"the document, from its entries",
2169+
open(cipher, entries).await.unwrap()["list"][0].take(),
2170+
),
2171+
(
2172+
"the extracted element, as `->` returns it",
2173+
cipher
2174+
.decrypt_as::<Value, JsonNode>(element, aead())
2175+
.await
2176+
.unwrap(),
2177+
),
2178+
(
2179+
"the walk under $.list",
2180+
cipher
2181+
.decrypt_as::<Value, JsonSubtree>(key.open(rows), aead())
2182+
.await
2183+
.unwrap()[0]
2184+
.take(),
2185+
),
2186+
]
2187+
}
2188+
2189+
/// The bit pattern of `value` as an `f64`, or `None` for a value that
2190+
/// is not a number.
2191+
fn bits(value: &Value) -> Option<u64> {
2192+
value.as_f64().map(f64::to_bits)
2193+
}
2194+
2195+
#[tokio::test]
2196+
async fn reads_back_the_value_that_came_back_one_ulp_off() {
2197+
let Scenario { cipher, .. } = scenario().await;
2198+
let wrong: Vec<String> = read_back(&cipher, FOUND)
2199+
.await
2200+
.into_iter()
2201+
.filter(|(_, back)| bits(back) != Some(FOUND.to_bits()))
2202+
.map(|(how, back)| format!("{how} read back {back}"))
2203+
.collect();
2204+
assert!(
2205+
wrong.is_empty(),
2206+
"every read should give back {FOUND:?}: {wrong:#?}"
2207+
);
2208+
}
2209+
2210+
/// Any finite `f64` reads back bit for bit, every way. The cases run
2211+
/// under the generated-documents suite's configuration: its fixed seed
2212+
/// and case count, each overridden by `PROPTEST_RNG_SEED` and
2213+
/// `PROPTEST_CASES`, and its regressions file.
2214+
#[test]
2215+
fn reads_back_any_finite_f64_bit_for_bit() {
2216+
let config = given_generated_documents::config();
2217+
let replay = format!(
2218+
"seed {seed}, {cases} cases; replay with PROPTEST_RNG_SEED={seed} PROPTEST_CASES={cases}",
2219+
seed = config.rng_seed,
2220+
cases = config.cases
2221+
);
2222+
let runtime = tokio::runtime::Builder::new_current_thread()
2223+
.enable_all()
2224+
.build()
2225+
.unwrap();
2226+
let Scenario { cipher, .. } = runtime.block_on(scenario());
2227+
let finite = proptest::num::f64::ANY.prop_filter("a finite f64", |f| f.is_finite());
2228+
let mut runner = TestRunner::new(config);
2229+
let outcome = runner.run(&finite, |f| {
2230+
for (how, back) in runtime.block_on(read_back(&cipher, f)) {
2231+
prop_assert_eq!(
2232+
bits(&back),
2233+
Some(f.to_bits()),
2234+
"{} should read back {:?}, read back {}",
2235+
how,
2236+
f,
2237+
back
2238+
);
2239+
}
2240+
Ok(())
2241+
});
2242+
if let Err(error) = outcome {
2243+
panic!("json_index full-precision floats: {replay}\n{error}");
2244+
}
2245+
}
2246+
}
2247+
21272248
// =============================================================================
21282249
// Queries
21292250
// =============================================================================

0 commit comments

Comments
 (0)