The Drift Log · Model independence and repeatable builds
Deterministic Ordering of JSON Keys for Stable Snapshots
21 November 2026 · 3 min read · 693 words · established

Flaky CI snapshot diffs caused by nondeterministic JSON key order can be eliminated with SHPBL’s certified, repeatable canonicalisation routine.
The failure mode: flaky snapshot diffs
Your CI job stores a JSON snapshot of a data structure. The same test run on two agents produces different byte streams. The diff shows a handful of lines that have moved, not a real behavioural change. The build fails. The root cause is that the serializer emitted object keys in an order that depends on the runtime environment – V8 version, Node flag, or even the hash seed of the process. Because the order is not fixed, the stored snapshot is not reproducible. The failure appears as a “snapshot mismatch” even though the logical content is identical.
Why JSON ordering varies
The ECMAScript specification leaves object key enumeration order to the engine, except for a few well‑defined cases (integer‑like keys first, then insertion order). In practice, engines differ in how they treat non‑integer keys that were added via Object.assign, spread syntax, or JSON.stringify. When a library builds an object from a map, the iteration order of that map may depend on insertion sequence, which can change when the code runs under a different Node version or when a parallel test worker reuses a pool. The result is a non‑deterministic byte representation.
Because JSON is a text format, any change in whitespace or key order changes the checksum. Snapshot testing tools compare the raw file, not a parsed structure, so they flag the change as a regression.
Enforcing a canonical order
The simplest way to guarantee repeatable snapshots is to sort keys before serialisation. The sort must be stable and based only on the key string. A small helper can be added to the test harness:
function stableStringify(value: unknown): string {
const seen = new WeakSet();
const replacer = (_key: string, v: unknown) => {
if (v && typeof v === 'object') {
if (seen.has(v as object)) return '[Circular]';
seen.add(v as object);
}
return v;
};
const ordered = (obj: any): any => {
if (Array.isArray(obj)) return obj.map(ordered);
if (obj && typeof obj === 'object') {
const out: any = {};
Object.keys(obj).sort().forEach(k => {
out[k] = ordered(obj[k]);
});
return out;
}
return obj;
};
return JSON.stringify(ordered(value), replacer, 2);
}
The function walks the structure, sorts each object's own keys, and then calls JSON.stringify. The output is byte‑identical across Node versions, platforms, and parallel workers, provided the input data is the same. The helper adds negligible overhead compared with the cost of a failing CI run.
When the test suite writes a snapshot, replace the default JSON.stringify call with stableStringify. Existing snapshot files can be regenerated once; after that the CI will only flag genuine changes.
Integrating deterministic JSON into your CI
Add the helper as a small module in your repository. Export it from a test utilities file and import it wherever snapshots are written. Ensure the module is part of the build artefact so that the same version runs in every environment.
Configure your test runner to treat the snapshot file as a generated artefact. In a typical Jest setup, you can override the snapshot serializer:
// jest.setup.js
const { stableStringify } = require('./stable-json');
expect.addSnapshotSerializer({
test: val => typeof val === 'object',
print: (val, _serializer) => stableStringify(val),
});
Now every toMatchSnapshot call uses the canonical ordering.
Run the suite locally, confirm that the snapshot files are unchanged after a clean checkout, then push the change. The next CI run will compare byte‑identical files, eliminating the flaky failures you observed.
If you already have a large corpus of snapshots, a one‑off regeneration step is required. Check out a clean branch, delete the old __snapshots__ directories, run the tests to recreate them, and commit the new files. The effort is a single CI pass, far cheaper than debugging intermittent failures week after week.
SHPBL’s solution
SHPBL provides a reusable library that includes a certified, repeatable JSON canonicalisation routine. The routine is part of the same artifact that powers the HTTP API, the TypeScript SDK, and the offline file‑based edition. Because the library is model‑independent, the ordering logic is computed, not generated, and its byte‑for‑byte output is sealed by published checksums in the root of trust. You can evaluate the library on a sample repository for free at /evaluation. The full set of capabilities is available through the Practitioner tier or the Complete Master Library. See the live harness execution at /harness to verify that the canonicalisation passes the CERTIFIED verdict.
What to do on Monday
- Add the
stableStringifyhelper to your repo (or import the SHPBL routine). - Wire it into your snapshot serializer.
- Regenerate existing snapshots in a clean checkout.
- Commit the new files and watch the next CI run pass without spurious diffs.
These three steps turn a nondeterministic test artefact into a repeatable component of your build pipeline.
This post supports the longer argument in Model Independence and Repeatable Software Builds.
Keep reading
Next in the log
- Model Independence and Repeatable Software Builds
Runtime model variance and non-reproducible builds compound to break production systems. Here is how to isolate probabilistic logic and pin artifacts.
- Capturing Build-Time Environment to Freeze Artifact Output
Scrub ambient host variables with an allowlist and record environment manifests to guarantee byte-for-byte repeatable build artifacts.
- Fixing Locale Drift in Build Scripts
Locale inheritance causes checksum drift in build scripts; pin LC_ALL=C to ensure byte-identical outputs across environments.
The Strategic Master Library · written and reviewed under the house's own epistemic rules: nothing claimed that we cannot show.