Skip to content

Commit ff287a3

Browse files
committed
fix(stack-encrypt): open JSON index floats to the exact value sealed
The JSON index stores a number leaf as its shortest round-trip text (serde_json::Number::to_string in encode_node) and parses it back when the entry opens (decode_node) or the sealed root opens (PlainJson::parse). serde_json without float_roundtrip parses floats with a fast path that is not guaranteed to return the nearest f64, so a value with a full-precision expansion could open one unit in the last place off: -926809.5051008083 opened as -926809.5051008085, through JsonDocument, JsonNode and JsonSubtree alike. Enable float_roundtrip on stack-encrypt's serde_json dependency. Cargo unifies features, so it reaches every build graph that compiles this crate (the EQL workspace through eql-bindings' stack-encrypt feature, and the Go guests) without a change to their manifests or lockfiles. The read side derives no term from the parsed value: value selectors and ordering terms are computed on the write side only, from the caller's value. A regression test reads the issue's value back four ways, and a property test does the same for arbitrary finite f64 under the generated-documents suite's seed and case count. Both fail without the feature; the shrunk seed is kept in the regressions file. Closes #1364 Claude-Session: https://claude.ai/code/session_01N7bCqa3ZVJMcEE99RzVqEu
1 parent e4dd59a commit ff287a3

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
@@ -1775,7 +1775,7 @@ mod given_generated_documents {
17751775
/// proptest's defaults, which read `PROPTEST_CASES` and
17761776
/// `PROPTEST_RNG_SEED`, with this suite's own default for each one left
17771777
/// unset.
1778-
fn config() -> Config {
1778+
pub(super) fn config() -> Config {
17791779
let mut config = Config::default();
17801780
if std::env::var_os("PROPTEST_CASES").is_none() {
17811781
config.cases = DEFAULT_CASES;
@@ -2179,6 +2179,127 @@ mod given_generated_documents {
21792179
}
21802180
}
21812181

2182+
mod given_a_float_at_full_precision {
2183+
//! A number leaf is stored as its shortest round-trip text and parsed
2184+
//! back when it opens: from the sealed root's document text, or from
2185+
//! the node's own entry. Only serde_json's `float_roundtrip` parser
2186+
//! promises the nearest `f64` to that text; without it a value can come
2187+
//! back one unit in the last place off (#1364). Each case seals a
2188+
//! document holding the number and reads it back every way the column
2189+
//! hands it out, comparing bit patterns.
2190+
2191+
use proptest::prelude::*;
2192+
use proptest::test_runner::TestRunner;
2193+
2194+
use super::*;
2195+
2196+
/// The value a property test found coming back as
2197+
/// `-926809.5051008085` (#1364).
2198+
const FOUND: f64 = -926_809.505_100_808_3;
2199+
2200+
/// The document a case seals: the number as an array element under a
2201+
/// key, so a walk under `$.list` and the extracted element both reach
2202+
/// it. Its entries, by ordinal: `$`, `$.list`, `$.list[0]`.
2203+
fn document(f: f64) -> Value {
2204+
json!({"list": [f]})
2205+
}
2206+
2207+
/// The number back out of each way of reading it, named.
2208+
async fn read_back(cipher: &Cipher, f: f64) -> Vec<(&'static str, Value)> {
2209+
let value = document(f);
2210+
let sealed = seal(cipher, &value).await;
2211+
let entries = seal_with(cipher, &value, &open_root()).await;
2212+
let key = subtree_key(cipher, "$.list", JsonOptions::default())
2213+
.await
2214+
.unwrap();
2215+
let rows = subtree_nodes(&sealed, key.token_bytes());
2216+
let element = sealed.node(2).unwrap();
2217+
vec![
2218+
(
2219+
"the document, from the sealed root",
2220+
open(cipher, sealed).await.unwrap()["list"][0].take(),
2221+
),
2222+
(
2223+
"the document, from its entries",
2224+
open(cipher, entries).await.unwrap()["list"][0].take(),
2225+
),
2226+
(
2227+
"the extracted element, as `->` returns it",
2228+
cipher
2229+
.decrypt_as::<Value, JsonNode>(element, aead())
2230+
.await
2231+
.unwrap(),
2232+
),
2233+
(
2234+
"the walk under $.list",
2235+
cipher
2236+
.decrypt_as::<Value, JsonSubtree>(key.open(rows), aead())
2237+
.await
2238+
.unwrap()[0]
2239+
.take(),
2240+
),
2241+
]
2242+
}
2243+
2244+
/// The bit pattern of `value` as an `f64`, or `None` for a value that
2245+
/// is not a number.
2246+
fn bits(value: &Value) -> Option<u64> {
2247+
value.as_f64().map(f64::to_bits)
2248+
}
2249+
2250+
#[tokio::test]
2251+
async fn reads_back_the_value_that_came_back_one_ulp_off() {
2252+
let Scenario { cipher, .. } = scenario().await;
2253+
let wrong: Vec<String> = read_back(&cipher, FOUND)
2254+
.await
2255+
.into_iter()
2256+
.filter(|(_, back)| bits(back) != Some(FOUND.to_bits()))
2257+
.map(|(how, back)| format!("{how} read back {back}"))
2258+
.collect();
2259+
assert!(
2260+
wrong.is_empty(),
2261+
"every read should give back {FOUND:?}: {wrong:#?}"
2262+
);
2263+
}
2264+
2265+
/// Any finite `f64` reads back bit for bit, every way. The cases run
2266+
/// under the generated-documents suite's configuration: its fixed seed
2267+
/// and case count, each overridden by `PROPTEST_RNG_SEED` and
2268+
/// `PROPTEST_CASES`, and its regressions file.
2269+
#[test]
2270+
fn reads_back_any_finite_f64_bit_for_bit() {
2271+
let config = given_generated_documents::config();
2272+
let replay = format!(
2273+
"seed {seed}, {cases} cases; replay with PROPTEST_RNG_SEED={seed} PROPTEST_CASES={cases}",
2274+
seed = config.rng_seed,
2275+
cases = config.cases
2276+
);
2277+
let runtime = tokio::runtime::Builder::new_current_thread()
2278+
.enable_all()
2279+
.build()
2280+
.unwrap();
2281+
let Scenario { cipher, .. } = runtime.block_on(scenario());
2282+
let finite = proptest::num::f64::ANY.prop_filter("a finite f64", |f| f.is_finite());
2283+
let mut runner = TestRunner::new(config);
2284+
let outcome = runner.run(&finite, |f| {
2285+
for (how, back) in runtime.block_on(read_back(&cipher, f)) {
2286+
prop_assert_eq!(
2287+
bits(&back),
2288+
Some(f.to_bits()),
2289+
"{} should read back {:?}, read back {}",
2290+
how,
2291+
f,
2292+
back
2293+
);
2294+
}
2295+
Ok(())
2296+
});
2297+
if let Err(error) = outcome {
2298+
panic!("json_index full-precision floats: {replay}\n{error}");
2299+
}
2300+
}
2301+
}
2302+
21822303
// =============================================================================
21832304
// Queries
21842305
// =============================================================================

0 commit comments

Comments
 (0)