From 6ffe6b9d3553ebbfe82b5b17939a7705e383c96d Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 19:43:50 -0600 Subject: [PATCH 1/4] fix(jq): handle serde_json arbitrary_precision numbers With serde_json/arbitrary_precision enabled via feature unification, non-integer numbers arrive as a single-entry map with the private key $serde_json::private::Number instead of visit_f64. JqSeed::visit_map now detects that shape and returns JqJson::Number with the exact text, so jq input, --argjson, and streams keep working in either build. Closes #2964 --- crates/bashkit/src/builtins/jq/convert.rs | 109 +++++++++++++++++++++- crates/bashkit/src/builtins/jq/tests.rs | 7 +- knowledge/foundations/jq.md | 16 ++++ 3 files changed, 130 insertions(+), 2 deletions(-) diff --git a/crates/bashkit/src/builtins/jq/convert.rs b/crates/bashkit/src/builtins/jq/convert.rs index 2a5bf221b..65419e922 100644 --- a/crates/bashkit/src/builtins/jq/convert.rs +++ b/crates/bashkit/src/builtins/jq/convert.rs @@ -17,6 +17,12 @@ use super::jaq_json::Val; /// like `[[[[...]]]]` or `{"a":{"a":{"a":...}}}`. pub(super) const MAX_JQ_JSON_DEPTH: usize = 100; +/// Private token serde_json uses when `arbitrary_precision` is on. +/// Non-integer numbers arrive as a single-entry map `{TOKEN: "1.5"}` +/// instead of `visit_f64`. Cargo feature unification can enable this even +/// when bashkit did not request it (see #2964), so `visit_map` handles it. +const ARBITRARY_PRECISION_NUMBER_TOKEN: &str = "$serde_json::private::Number"; + /// Tagged JSON value used internally by the jq builtin so we can preserve /// the original numeric representation through filter execution and /// output formatting. Real jq prints `1.0` as `1.0`; the stock @@ -129,7 +135,40 @@ impl<'de> serde::de::Visitor<'de> for JqSeed<'_> { } fn visit_map>(self, mut map: A) -> Result { - let mut out: Vec<(String, JqJson)> = Vec::new(); + let first_key: Option = map.next_key()?; + let Some(first_key) = first_key else { + return Ok(JqJson::Object(Vec::new())); + }; + let first_value = map.next_value_seed(self.child())?; + if first_key == ARBITRARY_PRECISION_NUMBER_TOKEN + && let JqJson::String(text) = &first_value + { + // `NumberDeserializer` yields exactly one entry, so no second key + // means this was a number. A real object that happens to start + // with the private token plus more keys falls through as an + // object below (serde_json's own Value treats the single-entry + // case as a number too). + let second_key: Option = map.next_key()?; + if second_key.is_none() { + return Ok(JqJson::Number(text.clone())); + } + let second_key = second_key.unwrap_or_default(); + let second_value = map.next_value_seed(self.child())?; + let mut out = Vec::with_capacity(2); + out.push((first_key, first_value)); + out.push((second_key, second_value)); + while let Some(key) = map.next_key::()? { + let value = map.next_value_seed(self.child())?; + // Duplicate keys: last value wins in its first position, as in jq. + if let Some(slot) = out.iter_mut().find(|(k, _)| *k == key) { + slot.1 = value; + } else { + out.push((key, value)); + } + } + return Ok(JqJson::Object(out)); + } + let mut out: Vec<(String, JqJson)> = vec![(first_key, first_value)]; while let Some(key) = map.next_key::()? { let value = map.next_value_seed(self.child())?; // Duplicate keys: last value wins in its first position, as in jq. @@ -430,4 +469,72 @@ mod tests { let result = parse_json_stream(&s); assert!(result.is_err()); } + + /// Regression for #2964: with `serde_json/arbitrary_precision` enabled + /// (via feature unification), non-integers arrive as a single-entry map + /// `{ "$serde_json::private::Number": "1.5" }` instead of `visit_f64`. + /// This simulates that shape without requiring the feature, so the test + /// fails before the `visit_map` fix and passes after, in any build. + #[test] + fn arbitrary_precision_number_shape_becomes_number() { + use serde::de::{MapAccess, Visitor}; + use std::cell::Cell; + + struct TokenMap { + done_key: bool, + done_value: bool, + } + impl<'de> MapAccess<'de> for TokenMap { + type Error = serde::de::value::Error; + fn next_key_seed>( + &mut self, + seed: K, + ) -> Result, Self::Error> { + if self.done_key { + return Ok(None); + } + self.done_key = true; + seed.deserialize(serde::de::value::BorrowedStrDeserializer::new( + "$serde_json::private::Number", + )) + .map(Some) + } + fn next_value_seed>( + &mut self, + seed: V, + ) -> Result { + self.done_value = true; + seed.deserialize(serde::de::value::BorrowedStrDeserializer::new("1.5")) + } + } + + struct TokenDeserializer; + impl<'de> serde::de::Deserializer<'de> for TokenDeserializer { + type Error = serde::de::value::Error; + fn deserialize_any>(self, visitor: V) -> Result { + visitor.visit_map(TokenMap { + done_key: false, + done_value: false, + }) + } + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str + string bytes byte_buf option unit unit_struct newtype_struct + seq tuple tuple_struct map struct enum identifier ignored_any + } + } + + let too_deep = Cell::new(None); + let seed = JqSeed { + depth: 0, + max: MAX_JQ_JSON_DEPTH, + too_deep: &too_deep, + }; + let value: JqJson = serde::de::DeserializeSeed::deserialize(seed, TokenDeserializer) + .expect("token map should deserialize"); + assert!( + matches!(value, JqJson::Number(ref s) if s == "1.5"), + "expected Number(1.5)" + ); + } } diff --git a/crates/bashkit/src/builtins/jq/tests.rs b/crates/bashkit/src/builtins/jq/tests.rs index b10b2bb41..2fee4a0d4 100644 --- a/crates/bashkit/src/builtins/jq/tests.rs +++ b/crates/bashkit/src/builtins/jq/tests.rs @@ -2098,7 +2098,12 @@ async fn computed_floats_print_like_jq() { #[tokio::test] async fn input_number_literals_keep_their_form_until_computed() { - let out = run_jq_with_args(&["-c", "[.[], (.[0] + 1)]"], "[1.0, 2.50]") + // NB: `2.50` is intentionally not used here. Without + // `serde_json/arbitrary_precision` it normalizes to `2.5` via `visit_f64`, + // while with it (#2964) the exact token `2.50` is preserved like real jq + // (`echo '[1.0, 2.50]' | jq -c '[.[], (.[0] + 1)]'` prints `[1.0,2.50,2]`). + // Using `2.5` keeps this test green in both builds. + let out = run_jq_with_args(&["-c", "[.[], (.[0] + 1)]"], "[1.0, 2.5]") .await .unwrap(); assert_eq!(out, "[1.0,2.5,2]\n"); diff --git a/knowledge/foundations/jq.md b/knowledge/foundations/jq.md index 1ed8662f7..251fa2e48 100644 --- a/knowledge/foundations/jq.md +++ b/knowledge/foundations/jq.md @@ -46,6 +46,19 @@ value, matching jq. This covers main input, `--slurpfile`, `--argjson`, The nesting cap (TM-DOS-027) is enforced while reading; a depth violation is reported verbatim, not as a generic parse error. +## Number precision + +We do not enable `serde_json/arbitrary_precision` because it changes `Number` +semantics crate-wide. Cargo feature unification can still turn it on when +another crate in the build enables it. With it on, non-integer numbers no +longer arrive via `visit_f64`; they arrive as a single-entry map with the +private key `$serde_json::private::Number` whose value is the number text. +`JqSeed::visit_map` detects that shape and returns `JqJson::Number` with the +exact text, so `jq` input, `--argjson`, `--jsonargs`, and streams keep working +in either build. With the feature on, the exact token is preserved (for +example `2.50` stays `2.50`, matching real jq); without it, floats normalize +through `f64` (for example `2.50` becomes `2.5`). + ## Resource accounting Normalization is a bounded single pass. It charges input length to the shared @@ -63,6 +76,9 @@ stdin/file/slurpfile paths, exact work/live-memory boundaries, debug-leak invariants, and differential filter/output semantics against real jq. `spec_cases/jq/jq.test.sh` `jq_object_key_order_*` cases pin key order for input, `del`, duplicate keys, `-S`, `--argjson` and `--slurpfile`. +`builtins::jq::convert::tests::arbitrary_precision_number_shape_becomes_number` +pins the `$serde_json::private::Number` map shape so the fix stays green with +or without `serde_json/arbitrary_precision` enabled. `builtins::json::tests::literal_control_in_string_remains_invalid_json` proves the exception does not cross into the strict `json` builtin. From 92a58169f0e8a531311fee49bcfc3ac143b80b02 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 20:19:22 -0600 Subject: [PATCH 2/4] fix(jq): collapse duplicate token key in fall-through object Address PR review: feed the second entry through the same last-wins dedupe as the normal path and pin the two-entry fall-through with a companion test. --- crates/bashkit/src/builtins/jq/convert.rs | 29 ++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/bashkit/src/builtins/jq/convert.rs b/crates/bashkit/src/builtins/jq/convert.rs index 65419e922..e2d8ae153 100644 --- a/crates/bashkit/src/builtins/jq/convert.rs +++ b/crates/bashkit/src/builtins/jq/convert.rs @@ -154,9 +154,14 @@ impl<'de> serde::de::Visitor<'de> for JqSeed<'_> { } let second_key = second_key.unwrap_or_default(); let second_value = map.next_value_seed(self.child())?; - let mut out = Vec::with_capacity(2); - out.push((first_key, first_value)); - out.push((second_key, second_value)); + let mut out = vec![(first_key, first_value)]; + // Same last-wins/first-position rule as the normal path, so a + // duplicate private token in second position collapses. + if let Some(slot) = out.iter_mut().find(|(k, _)| *k == second_key) { + slot.1 = second_value; + } else { + out.push((second_key, second_value)); + } while let Some(key) = map.next_key::()? { let value = map.next_value_seed(self.child())?; // Duplicate keys: last value wins in its first position, as in jq. @@ -537,4 +542,22 @@ mod tests { "expected Number(1.5)" ); } + + /// Companion for #2964: a real object that happens to start with the + /// private token plus another key must stay an `Object`, not become a + /// `Number`. Pins the two-entry fall-through (including duplicate-key + /// collapse) with or without `arbitrary_precision`. + #[test] + fn token_led_object_with_second_key_stays_object() { + let value = parse_json_value(r#"{"$serde_json::private::Number":"1.5","b":2}"#) + .expect("object should parse"); + match value { + JqJson::Object(entries) => { + assert_eq!(entries.len(), 2, "expected two entries"); + assert_eq!(entries[0].0, "$serde_json::private::Number"); + assert_eq!(entries[1].0, "b"); + } + _ => panic!("expected Object"), + } + } } From c823ac8e9f80acc3a2341f69c429aa25c5bd92f3 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 20:30:11 -0600 Subject: [PATCH 3/4] fix(jq): gate private-token handling on arbitrary_precision Only interpret single-entry $serde_json::private::Number map as Number when the build actually enabled arbitrary_precision (runtime OnceLock via 2.50 round-trip). Real objects with that key stay Objects without the feature; with it they match serde_json::Value parity. Add single_entry_token_object_matches_build_mode to pin both modes. --- crates/bashkit/src/builtins/jq/convert.rs | 52 ++++++++++++++++++++++- knowledge/foundations/jq.md | 17 +++++--- 2 files changed, 63 insertions(+), 6 deletions(-) diff --git a/crates/bashkit/src/builtins/jq/convert.rs b/crates/bashkit/src/builtins/jq/convert.rs index e2d8ae153..d440817cc 100644 --- a/crates/bashkit/src/builtins/jq/convert.rs +++ b/crates/bashkit/src/builtins/jq/convert.rs @@ -60,6 +60,25 @@ struct JqSeed<'a> { depth: usize, max: usize, too_deep: &'a std::cell::Cell>, + /// Whether to interpret the private-token single-entry map as a number. + /// True only when `serde_json` was built with `arbitrary_precision` (see + /// `serde_json_has_arbitrary_precision`); otherwise a real object with + /// that key must stay an object. + handle_token: bool, +} + +/// Whether the current build enabled `serde_json/arbitrary_precision` (often +/// via feature unification from another crate). Without it, floats arrive via +/// `visit_f64`; with it, non-integers arrive as a single-entry map. Detected +/// at runtime once: `"2.50"` normalizes to `"2.5"` via `f64` without the +/// feature but keeps `"2.50"` with it. +fn serde_json_has_arbitrary_precision() -> bool { + static CACHE: std::sync::OnceLock = std::sync::OnceLock::new(); + *CACHE.get_or_init(|| { + serde_json::from_str::("2.50") + .map(|n| n.to_string() == "2.50") + .unwrap_or(false) + }) } impl<'a> JqSeed<'a> { @@ -68,6 +87,7 @@ impl<'a> JqSeed<'a> { depth: self.depth + 1, max: self.max, too_deep: self.too_deep, + handle_token: self.handle_token, } } } @@ -140,7 +160,8 @@ impl<'de> serde::de::Visitor<'de> for JqSeed<'_> { return Ok(JqJson::Object(Vec::new())); }; let first_value = map.next_value_seed(self.child())?; - if first_key == ARBITRARY_PRECISION_NUMBER_TOKEN + if self.handle_token + && first_key == ARBITRARY_PRECISION_NUMBER_TOKEN && let JqJson::String(text) = &first_value { // `NumberDeserializer` yields exactly one entry, so no second key @@ -198,6 +219,7 @@ pub(super) fn parse_json_value(input: &str) -> std::result::Result (Vec, Option vals.push(v), @@ -534,6 +557,9 @@ mod tests { depth: 0, max: MAX_JQ_JSON_DEPTH, too_deep: &too_deep, + // Force handling on: this simulates the number shape regardless of + // how the current build enabled serde_json. + handle_token: true, }; let value: JqJson = serde::de::DeserializeSeed::deserialize(seed, TokenDeserializer) .expect("token map should deserialize"); @@ -560,4 +586,28 @@ mod tests { _ => panic!("expected Object"), } } + + /// Single-entry private-token object: without `arbitrary_precision` it + /// must stay an `Object` (real user data); with it, it is + /// indistinguishable from a number and becomes `Number`, matching + /// `serde_json::Value` parity. + #[test] + fn single_entry_token_object_matches_build_mode() { + let value = parse_json_value(r#"{"$serde_json::private::Number":"1.5"}"#) + .expect("object should parse"); + if serde_json_has_arbitrary_precision() { + assert!( + matches!(value, JqJson::Number(ref s) if s == "1.5"), + "expected Number(1.5)" + ); + } else { + match value { + JqJson::Object(entries) => { + assert_eq!(entries.len(), 1, "expected one entry"); + assert_eq!(entries[0].0, "$serde_json::private::Number"); + } + _ => panic!("expected Object"), + } + } + } } diff --git a/knowledge/foundations/jq.md b/knowledge/foundations/jq.md index 251fa2e48..3cb70acbc 100644 --- a/knowledge/foundations/jq.md +++ b/knowledge/foundations/jq.md @@ -53,9 +53,13 @@ semantics crate-wide. Cargo feature unification can still turn it on when another crate in the build enables it. With it on, non-integer numbers no longer arrive via `visit_f64`; they arrive as a single-entry map with the private key `$serde_json::private::Number` whose value is the number text. -`JqSeed::visit_map` detects that shape and returns `JqJson::Number` with the -exact text, so `jq` input, `--argjson`, `--jsonargs`, and streams keep working -in either build. With the feature on, the exact token is preserved (for +`JqSeed::visit_map` detects that shape only when the build actually enabled +the feature (detected once at runtime via `"2.50"` round-trip) and returns +`JqJson::Number` with the exact text, so `jq` input, `--argjson`, `--jsonargs`, +and streams keep working in either build. A real single-entry object with that +private key stays an `Object` when the feature is off; with it on, the two are +indistinguishable (same as `serde_json::Value`) and it becomes a `Number`. +With the feature on, the exact token is preserved (for example `2.50` stays `2.50`, matching real jq); without it, floats normalize through `f64` (for example `2.50` becomes `2.5`). @@ -77,8 +81,11 @@ invariants, and differential filter/output semantics against real jq. `spec_cases/jq/jq.test.sh` `jq_object_key_order_*` cases pin key order for input, `del`, duplicate keys, `-S`, `--argjson` and `--slurpfile`. `builtins::jq::convert::tests::arbitrary_precision_number_shape_becomes_number` -pins the `$serde_json::private::Number` map shape so the fix stays green with -or without `serde_json/arbitrary_precision` enabled. +pins the private-token map shape (forced on, so green in any build), +`token_led_object_with_second_key_stays_object` pins the two-entry fall-through, +and `single_entry_token_object_matches_build_mode` pins that a single-entry +private-token object stays an `Object` without the feature and becomes a +`Number` with it. `builtins::json::tests::literal_control_in_string_remains_invalid_json` proves the exception does not cross into the strict `json` builtin. From fac4a6049a224d9656ea19c141bcccaaf655485a Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Sat, 21 Nov 2026 21:00:16 -0600 Subject: [PATCH 4/4] fix(jq): gate token handling, add AP coverage and duplicate test Gate private-token number handling on runtime arbitrary_precision detection so real single-entry objects stay Objects without the feature. Extend fall-through test with duplicate-key collapse and add CI leg running jq tests with serde_json/arbitrary_precision unified on. --- .github/workflows/ci.yml | 6 ++++++ crates/bashkit/src/builtins/jq/convert.rs | 16 ++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 008962e11..8e7fb3b16 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -426,6 +426,12 @@ jobs: cargo test -p bashkit --features markkit --test integration -- markkit_builtin_tests cargo test -p bashkit --features markkit,fetchkit --doc -- markkit_fetchkit_guide + # jq must keep working when another crate unifies serde_json's + # arbitrary_precision on (issue #2964): non-integers then arrive via + # visit_map with the private token instead of visit_f64. + - name: Run jq tests with arbitrary_precision unified on + run: "cargo test -p bashkit --lib --features jq,serde_json/arbitrary_precision -- builtins::jq::" + - name: Run fail-point tests (single-threaded) run: cargo test --features failpoints --test security_failpoint_tests -- --test-threads=1 diff --git a/crates/bashkit/src/builtins/jq/convert.rs b/crates/bashkit/src/builtins/jq/convert.rs index d440817cc..260262e14 100644 --- a/crates/bashkit/src/builtins/jq/convert.rs +++ b/crates/bashkit/src/builtins/jq/convert.rs @@ -585,6 +585,22 @@ mod tests { } _ => panic!("expected Object"), } + // Duplicate private token collapses last-wins in first position. + let dup = parse_json_value( + r#"{"$serde_json::private::Number":"1","$serde_json::private::Number":"2"}"#, + ) + .expect("duplicate object should parse"); + match dup { + JqJson::Object(entries) => { + assert_eq!(entries.len(), 1, "expected collapsed entry"); + assert_eq!(entries[0].0, "$serde_json::private::Number"); + assert!( + matches!(entries[0].1, JqJson::String(ref s) if s == "2"), + "expected last value to win" + ); + } + _ => panic!("expected Object"), + } } /// Single-entry private-token object: without `arbitrary_precision` it