Zero-dependency JSON Schema validation, streaming profile diffs, and 4.6x cached ELF closures
Shipping fast, zero-dependency CLI tools runs into the same tension across unrelated domains: naive implementations either allocate per-record heap objects that blow up peak resident memory, or cache full parsed graphs in RAM until batch jobs stall on allocator overhead. The fix in each case is splitting what must live in memory from what can stream or drop immediately, then proving both output equivalence and memory bounds mechanically.
Across three safe-Rust (#![forbid(unsafe_code)]) repositories, that pattern guided three distinct pieces of work: pure-Rust Draft 2020-12 JSON Schema validation and --group-by aggregations in convto v0.8.0, a streaming oa profile-diff rewrite in oa v0.15.0 that cut peak live heap by 93.4%, and a canonical-path TreeParseCache plus zero-clone ClosureWalker in bincompat that sped up multi-root ELF closure walks across 833 /usr/bin binaries by 4.66x while lowering Peak RSS.
convto v0.8.0, borrowed offset-slice streaming in oa v0.15.0, and lightweight dependency caching with owned analysis moves in bincompat.
1. Draft 2020-12 JSON Schema validation and the format_mask round-trip bug
In convto v0.8.0 (~1.3 MB stripped binary, zero external crates, 196 tests), adding convto validate --schema <FILE> (convto#33) paired schema inference (convto schema) with full pure-Rust Draft 2020-12 validation across all nine structured formats (JSON, JSONL, YAML, TOML, INI, ENV, XML, CSV, TSV) plus stdin (-). Schema documents themselves can be JSON, YAML, or TOML and run through upfront structural pre-validation (returning exit code 2 on malformed schemas) with a 128-level nesting guard (MAX_SCHEMA_DEPTH = 128).
The validator enforces type (distinguishing integer and number), required, properties, additionalProperties (boolean or subschema), items, enum, const (with numeric 1 == 1.0 and order-independent object equality), numeric bounds (minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf), Unicode-scalar minLength/maxLength, string format hints (date-time, date, uuid, uri, email, ipv4), array and object cardinality rules, and boolean combinators (allOf, anyOf, oneOf, not), reporting canonical violation paths such as $.users[2].email and $["weird.key"] in text or structured --json output.
Wiring convto schema --strict directly into convto validate --schema as a round-trip test caught a real inference defect immediately. Inside src/schema.rs, SchemaNode::observe_string() originally skipped format classification whenever a string was empty (""). If a dataset contained valid email addresses on rows 1 through 99 and an empty string on row 100, the inferred schema still emitted "format": "email" and then rejected row 100 during strict validation. Clearing self.format_mask = 0 on empty strings fixed the invariant permanently:
fn observe_string(&mut self, s: &str) {
self.saw_str = true;
if s.is_empty() {
self.format_mask = 0;
} else {
self.non_empty_str_count += 1;
if self.format_mask != 0 {
self.format_mask = classify_string_formats(s, self.format_mask);
}
}
}
In the same release (convto#34), convto query --group-by <FIELD> added deterministic first-seen row grouping across JSON, JSONL, YAML, CSV, TSV, and stdin with optional --sum, --avg, --min, and --max reductions plus --format csv|tsv output. Integer columns accumulate with checked i64 arithmetic so whole-number sums never lose precision, while floating-point and mixed sums use Neumaier/Kahan compensated summation before downstream --sort-by, --desc, --offset, and --limit stages run.
2. Self-dogfooding streaming oa profile-diff to -93.4% peak live heap
In oa v0.15.0 (oa#39), I pointed oa compare --heap-track at oa profile-diff using a synthetic pair of 60,000-line, 360,000-frame folded-stack files (two 8.9 MB profiles). The original implementation read every line into an owned String, split stacks into Vec<String>, and built a fresh HashSet<String> on every line just to deduplicate recursive frames so inclusive percentages could never exceed 100%. That single call path churned 87.0 MiB of temporary heap allocations and held 9.6 MiB live to diff 17.8 MB of text.
Rewriting src/profile_diff.rs replaced those per-line allocations with four zero-unsafe changes:
- Streamed folded-stack input in 64 KiB chunks, parsing sample counts directly from ASCII bytes and storing frame boundaries as
(usize, usize)byte offsets inside one reusableself.framesbuffer. - Added an inline zero-allocation deduplication scan for stacks up to 24 frames (falling back to a cleared reusable hash set only for deeper stacks), eliminating 60,000 per-line hash-set allocations on typical call stacks.
- Switched internal aggregation tables to a zero-unsafe
FxHashermap with borrowed&strlookups so existing symbols never allocate a keyStringon cache hits. - Diffed folded profiles directly without materializing intermediate JSON reports, merged sorted symbol maps in two-pointer linear order, and used
select_nth_unstable_byforO(N + K log K)top-K selection.
if frame_count <= 24 {
let mut leaf_seen = false;
for (i, &(s, e)) in self.frames[..frame_count - 1].iter().enumerate() {
let frame_len = e - s;
let frame = &stack_part[s..e];
let duplicate = self.frames[..i]
.iter()
.any(|&(ps, pe)| pe - ps == frame_len && &stack_part[ps..pe] == frame);
if !duplicate {
// Update self and inclusive counts via borrowed &str FxHashMap lookup
}
}
}
Verified with oa compare --pairs 9 --warmup 2 --check-output (100% SHA-256 identical across HTML, JSON, and text), wall time dropped from 90.02 ms to 21.95 ms (4.16x, 95% CI [4.08x, 4.20x], p = 0.0004), Peak RSS fell 13.3%, peak live heap dropped -93.4% (9,593.2 KiB to 634.4 KiB), and total heap churn fell -98.7% (87,039.2 KiB to 1,139.3 KiB).
3. Canonical-path TreeParseCache and zero-clone ClosureWalker
Evaluating transitive dependency closures across an entire directory tree (bincompat matrix --tree /usr/bin or bincompat check --tree /usr/bin) exposes massive overlap: 833 executables in /usr/bin repeatedly depend on the same core shared libraries (libc.so.6, libm.so.6, libgcc_s.so.1, libstdc++.so.6). Walking each executable independently re-ran fs::canonicalize(), directory probes, ELF architecture header checks, and full symbol-table parses on the same DSOs hundreds of times.
The obvious cache design (retaining every parsed Arc<BinaryAnalysis> for the whole run) speeds up CPU time while duplicating symbol metadata in resident memory. Instead, bincompat/src/tree.rs separates lightweight graph state inside TreeParseCache from full ELF analysis inside ClosureWalker:
pub struct TreeParseCache {
analyses: HashMap<(PathBuf, bool, bool), Arc<BinaryAnalysis>>,
deps_only: HashMap<PathBuf, Arc<CachedDeps>>,
arch_probes: HashMap<PathBuf, Option<Elf64Arch>>,
canonical_paths: HashMap<PathBuf, PathBuf>,
dir_exists_cache: HashMap<PathBuf, bool>,
hits: usize,
misses: usize,
}
During multi-root closure walks (check_dependency_trees_with_cache and collect_dependency_tree_analyses_with_cache), ClosureWalker tracks an emitted_keys: BTreeSet<PathBuf> across roots, caches only tiny CachedDeps edge lists (DT_NEEDED, DT_RPATH, DT_RUNPATH) plus canonical path and architecture probes, and parses each unique shared library once via owned BinaryAnalysis moves with zero clones. In bincompat matrix, analyzed inputs are dropped right after evaluate_matrix() finishes and before report rendering begins, keeping Peak RSS below the uncached baseline.
Tool & workload (--pairs 9 --check-output) |
Before -> After | Speedup (p) |
Memory delta |
|---|---|---|---|
oa profile-diff (60k folded lines, 2 x 8.9 MB) |
90.02 -> 21.95 ms | 4.16x (0.0004) |
-13.3% Peak RSS |
oa profile-diff --heap-track (live heap / churn) |
9,593 -> 634 KiB live | 87,039 -> 1,139 KiB churn | -93.4% live / -98.7% churn |
bincompat matrix --tree --format csv (833 /usr/bin ELFs) |
464.43 -> 101.73 ms | 4.66x (0.0004) |
-2.4% Peak RSS |
bincompat check --tree --format json (833 /usr/bin ELFs) |
454.38 -> 100.17 ms | 4.51x (0.0004) |
-7.6% Peak RSS |
Every run produced identical stdout SHA-256 hashes between baseline and candidate binaries. To harden the cache and matrix renderers against hostile inputs, tests/fuzz_verdef_and_matrix.rs exercises 2,000 deterministic adversarial cases: 1,200 malformed .gnu.version_d, LLD/mold shared-Verdaux, and section-stripped PT_DYNAMIC binary mutations plus 800 hostile filename, SONAME, and symbol matrix renders checked for strict RFC 4180 CSV round-trip fidelity, RFC 8259 JSON validity, HTML XSS escaping, and exact cache vs uncached parity.
4. Reproduce locally
# Infer a strict Draft 2020-12 schema and validate any of 9 formats (or stdin)
convto schema ./events.jsonl --strict -o events.schema.json
convto validate ./events.jsonl --schema events.schema.json --json
# Group and aggregate rows with Neumaier/Kahan compensation
convto query ./benchmarks.jsonl --group-by tool --avg speedup --max speedup --sort-by avg --desc
# Stream-diff two folded CPU profiles into an offline HTML report
oa profile-diff base.folded cand.folded --format html -o diff.html
# Evaluate transitive /usr/bin ELF closures across all 15 Linux targets in one pass
bincompat matrix /usr/bin --tree --format csv -o distro-matrix.csv
Limitations
convto validate --schemaimplements core Draft 2020-12 structural, numeric, string-format, and combinator keywords without pulling in a regex engine or HTTP client; external$refURI resolution and arbitrary ECMA-262patternregexes are intentionally out of scope.oa profile-diffinline deduplication handles stacks up to 24 frames with zero heap allocation; deeply recursive call stacks (>24 frames) fall back cleanly to a reusable hash set rather than truncating frame attribution.bincompat'sTreeParseCacheis scoped to a single CLI invocation and caches static ELF64 loader metadata only; dynamically openeddlopen()plugins still require runtime tracing.