Skip to content

feat(curl): losslessly minify JSON response bodies - #94

Merged
thehoff merged 4 commits into
developfrom
feat/curl-json-minify
May 20, 2026
Merged

thehoff merged 4 commits into
developfrom
feat/curl-json-minify

Conversation

@thehoff

@thehoff thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner

Summary

curl_cmd previously passed JSON bodies through whole. Its only filter is truncation, and truncating JSON mid-stream produces invalid JSON (rtk-ai#1536) — so JSON was deliberately left untouched. Result: pretty-printed API responses reach the agent at full size. A live landscape-dashboard endpoint measured 265 KB at 0% filtered, ~159 K tokens across 4 calls.

Change — Tier 1, lossless only

Parse the JSON body and re-serialise it without whitespace:

  • Minified JSON is still valid JSON (serde_json preserve_order keeps key ordering stable), so curl ... | jq keeps working — the exact thing mid-stream truncation broke.
  • Applies on both the TTY and pipe paths, because it's lossless.
  • Falls back to untouched Cow::Borrowed passthrough when the body isn't strictly-valid JSON, or is already compact (no needless allocation/clone of a multi-MB body).

Measured result

Live endpoint, real data: 265 KB → 207 KB (22%). Output verified to round-trip through a JSON parser.

22% is the honest ceiling for lossless on this data — the dashboard JSON is mostly content, not whitespace.

Explicitly out of scope — Tier 2

Lossy value-level compaction (truncating long string values, keys-only summaries) could reach 60%+, but it would corrupt a downstream curl ... | jq, and a captured-by-hook invocation is indistinguishable from a piped one at the curl process. Doing it safely needs pipe detection at the hook/rewrite layer, which sees the full pipeline. Deferred to a separate PR.

Test plan

  • cargo test --workspace — 2242 pass (5 new curl tests)
  • New tests: pretty-JSON minified, minified-on-pipe, already-minified passthrough, malformed-JSON passthrough, key-order preservation
  • All pre-existing curl tests still pass (their fixtures are already-minified, so they hit the unchanged passthrough path)
  • cargo build --release clean
  • Live run against a real API endpoint — 22% reduction, output round-trips as valid JSON

🤖 Generated with Claude Code

thehoff added 2 commits May 20, 2026 13:55
curl_cmd previously passed JSON through whole — its only filter was
truncation, and truncating JSON mid-stream produces invalid JSON (rtk-ai#1536).
So a pretty-printed API response reached the agent at full size: a live
landscape-dashboard endpoint measured 265KB at 0% filtered.

Tier 1 (lossless only): parse the body and re-serialise without
whitespace. Minified JSON is still valid JSON — `preserve_order` keeps
key ordering stable — so a downstream `curl ... | jq` keeps working.
Applies on both TTY and pipe paths because it's lossless. Falls back to
untouched passthrough when the body isn't strictly-valid JSON or is
already compact (no allocation, Cow::Borrowed).

Measured on the real endpoint: 265KB -> 207KB (22%), output verified
to round-trip as valid JSON.

Lossy value-level compaction (Tier 2) is intentionally deferred — it
would break `| jq` and needs hook-layer pipe detection to gate safely.
Verification with jq caught it: the parse/re-serialise approach was NOT
lossless. A JS millisecond timestamp with a fractional part —
`1779167626250.6921` — exceeds f64 precision, so serde re-emitted it as
`1779167626250.692`, silently corrupting the value.

Replace the round-trip with a textual whitespace stripper: validate the
body with serde (a yes/no `IgnoredAny` parse), then strip insignificant
whitespace directly. Numbers, key order and string contents stay
byte-identical; only whitespace outside string literals is removed.

Verified against a frozen 265KB API capture: jq -S canonical form is
hash-identical raw vs filtered, the fractional timestamp survives, and
the output round-trips through jq, node JSON.parse and python json.loads.

New regression tests: float precision, whitespace inside strings,
escaped quotes.
@thehoff

thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Verification update — round-trip bug found and fixed

JSON-validation testing (jq + frozen-capture equivalence) caught a real defect in the first commit: the serde parse/re-serialise approach was not lossless. A JS millisecond timestamp with a fractional part — 1779167626250.6921 — exceeds f64 precision, so serde re-emitted it as 1779167626250.692. Every fractional number in an API response would have been silently corrupted.

Fix (6e93b3b): minify textually instead. Validate the body with serde (IgnoredAny yes/no parse), then strip insignificant whitespace directly — numbers, key order and string contents stay byte-identical; only whitespace outside string literals is removed.

Verification evidence (frozen 265 KB API capture, no live drift)

Check Result
jq -S canonical form, raw vs filtered hash-identical
Fractional timestamp 1779167626250.6921 survives byte-for-byte
jq query on filtered output ✓
node JSON.parse ✓
python3 json.loads ✓
Reduction 265 KB → 207 KB (22%)

New regression tests: float precision, whitespace-inside-strings, escaped-quote handling. Workspace suite 2245 pass.

JSON (curl_cmd): 9 new tests for the textual minifier — braces/whitespace
inside string values, unicode, number forms (negative/exponent/zero/
high-precision), deep nesting, escaped backslash-before-quote, literal
\n\t escape sequences, empty {}/[], CRLF stripping, and a
parse-to-same-Value semantic round-trip.

Tracking harness (#69 — the env race): tests mutating the process-global
RTK_DB_PATH each declared their *own* local `static ENV_LOCK`, so they
serialised nothing — a write-then-read test could have the DB path
swapped underneath it by a parallel env-mutating test. This was the
intermittent `test_timed_execution_passthrough` failure.

- One shared module-level ENV_LOCK; all env-touching tests hold it.
  Poison-tolerant (into_inner) so one panic doesn't cascade.
- New PinnedDb RAII guard: TimedExecution tests pin RTK_DB_PATH to a
  private tempfile so write + read hit one DB, restored on drop.
- test_tracker_record_and_recent / test_track_passthrough_no_dilution
  converted to Tracker::new_in_memory() — fully isolated, unraceable.

Verified: 3 consecutive `cargo test --workspace` runs, 2254 pass, 0 fail.

Closes #69.
@thehoff

thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Added: JSON edge-case tests + flaky-harness fix (#69)

JSON coverage (curl_cmd) — 9 new tests

Braces/whitespace inside string values, unicode, number forms (negative / exponent / zero / high-precision fraction), deep nesting, escaped backslash-before-quote, literal \n/\t escape sequences, empty {}/[], CRLF stripping, and a parse-to-same-Value semantic round-trip.

Flaky tracking harness — fixes #69

While verifying this PR, test_timed_execution_passthrough flaked. Root cause is the known env race (#69): tests mutating the process-global RTK_DB_PATH each declared their own local static ENV_LOCK, so they serialised nothing — a write-then-read test could have the DB path swapped underneath it by a parallel env-mutating test.

  • One shared module-level ENV_LOCK, poison-tolerant, held by every env-touching test.
  • New PinnedDb RAII guard — TimedExecution tests pin RTK_DB_PATH to a private tempfile (write + read hit one DB), restored on drop.
  • test_tracker_record_and_recent / test_track_passthrough_no_dilution → Tracker::new_in_memory(), fully isolated.

Verified: 3 consecutive cargo test --workspace runs — 2254 pass, 0 fail.

This PR now also Closes #69.

Codex flagged test_parse_failure_roundtrip and
test_parse_failure_recovery_rate as latent races — they used
Tracker::new() against the process-shared test DB without ENV_LOCK.
No in-tree writer makes them flaky today, but a future test would.

Convert both to Tracker::new_in_memory(). Isolation also makes the
assertions exact: total == 1 (was >= 1), recovery_rate == 2/3 (was
just a 0..100 range check the test admitted it couldn't tighten).
@thehoff

thehoff commented May 20, 2026

Copy link
Copy Markdown
Owner Author

Codex review — clean, no blockers

Adversarial review of the full branch (JSON minifier state machine, validity gate, harness fix). No CRITICAL or IMPORTANT findings. Verified:

  • Escape state machine — even/odd backslash runs tracked correctly; dangling backslash is rejected by the serde gate before the stripper runs.
  • Whitespace losslessness — RFC 8259 has no position outside string literals where space/tab/LF/CR is significant.
  • Validity gate — from_str::<IgnoredAny> calls end(), so trailing garbage ({}xyz, {} {}) is rejected before the stripper touches it.
  • UTF-8 safety, PinnedDb drop order (env restored before mutex releases), new_in_memory() isolation — all sound.

One NICE-TO-HAVE actioned in 1d0fb60: test_parse_failure_roundtrip / test_parse_failure_recovery_rate used Tracker::new() without ENV_LOCK (latent race). Converted both to new_in_memory() — isolation also tightened the assertions to exact values (total == 1, recovery_rate == 2/3) instead of loose ranges.

Branch is review-clean and ready.

@thehoff
thehoff merged commit 0bf6608 into develop May 20, 2026
4 checks passed
@thehoff
thehoff deleted the feat/curl-json-minify branch May 20, 2026 04:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant