A saved calculation can survive a schema migration and still return a different answer after a refresh. The JSON parser accepts it, every field has the expected type, and the migration succeeds. What changed was the meaning of the calculation: a rounding rule, a coefficient table, or another dependency that the saved record did not identify.
For applications that promise to reconstruct an earlier result, restoration needs three separate contracts: the shape of the record, the algorithm that interprets it, and the data that algorithm consumes. This article builds a small JavaScript example that makes those contracts observable. It concerns deterministic recalculation, not preserving arbitrary UI state.
Define what “restore” promises
Consider a calibration tool that accepts integer samples and computes:
floor((gain * sample + offset) / divisor)
With coefficients [3, 1, 2], samples [0, 1, 2] produce [0, 2, 3]. Replacing floor with nearest rounding produces [1, 2, 4]. Keeping floor but changing the offset to 2 produces that same changed answer.
Neither change requires changing the JSON structure. A schema number alone cannot distinguish them.
Our contract is deliberately narrow: restore the accepted samples under their original computational context, or reject the restore. Preserve sample order and duplicates. Ignore cached answers. A failure must leave the previously published state untouched. Draft text and presentation state are outside this contract.
Recalculating old inputs with today's rules is also a reasonable feature. It needs a different name and an explicit user decision because it makes a different promise.
Give each compatibility question its own identity
| Identity | Question it answers | Example |
|---|---|---|
| Storage schema | Can this reader interpret the record's fields? | schema: 2 |
| Algorithm | Which computation gives those fields meaning? | algorithm: "floor-v1" |
| Computation data | Which coefficients does that computation use? | dataHash: "0497…3349" |
The schema transition in this example renames inputs to samples. It does not change the algorithm label or data hash. Migration translates a representation; it does not grant permission to reinterpret the calculation.
A single release identifier could bind all three. That is simpler when code, data, and storage always ship together. Separate identities become useful when data updates independently, or when several storage formats represent the same calculation. The cost is a larger compatibility contract to maintain and test.
The development project behind Chainle supplied the source material for this analysis; this is a project-associated implementation discussion. Its inspected local implementation binds saved inputs to versioned context and recomputes derived results, while a separate asset loader checks data bytes. The numerical example below is independently constructed and does not establish what the live deployment runs.
Pin the data before crossing an asynchronous boundary
The example permits only finite safe integers bounded by one million, at most 1,000 samples, and a positive divisor. Negative zero is rejected as an input. These restrictions give the encoding a small, explicit domain and keep the integer multiplication and addition within JavaScript's safe integer range. They do not make floating-point division suitable for every financial or scientific calculation.
The context builder copies and freezes the coefficient tuple before calling the asynchronous digest operation:
export async function context(algorithm, coefficients) {
if (algorithm !== 'floor-v1' && algorithm !== 'nearest-v2') throw Error('UNKNOWN_ALGORITHM');
const tuple = samples(coefficients);
if (tuple.length !== 3 || tuple[2] <= 0) throw Error('INVALID_COEFFICIENTS');
// Defined encoding: UTF-8 JSON array, positional integers, domain prefix.
// Copy before await: hashing and evaluation must see the same values.
Object.freeze(tuple);
const bytes = new TextEncoder().encode(JSON.stringify(['calibration-v1', ...tuple]));
const digest = await crypto.subtle.digest('SHA-256', bytes);
const dataHash = Array.from(new Uint8Array(digest), n => n.toString(16).padStart(2, '0')).join('');
return Object.freeze({algorithm, dataHash, coefficients: tuple});
}
This is an excerpt from the complete module below. If a caller mutates its original coefficient array while the digest is pending, evaluation must still use the values that were hashed. Hashing one array and later reading a mutable alias would break the binding without changing either identifier.
The encoding is UTF-8 JSON for a positional integer tuple with a domain prefix. It is not a general canonical-JSON algorithm: arbitrary objects, Unicode normalization, floating-point encodings, and unordered collections would need additional rules. Different tuples that happen to describe equivalent functions also receive different hashes. That conservative rejection is acceptable here.
The implementation uses the global Web Crypto API available in the tested Node.js 22.22.0 runtime. No runtime package is required.
The algorithm label is a release-maintenance contract, not a digest of executable code. Changing floor-v1 without changing its label defeats this protection. Tests can detect selected behavioral changes; the label itself cannot enforce disciplined releases.
Validate, bind, compute, then publish
Restoration follows one direction:
bounded text → validated record → shape migration
→ context comparison → recomputation → candidate state
The complete decoder rejects unknown schemas and algorithms, malformed hashes, excessive record sizes, and invalid samples. Schema 1 uses inputs; schema 2 uses samples. Both emerge from decoding with schema 2 and their original computational identities.
export function restore(raw, expected) {
const saved = decode(raw);
if (saved.algorithm !== expected.algorithm) throw Error('ALGORITHM_MISMATCH');
if (saved.dataHash !== expected.dataHash) throw Error('DATA_MISMATCH');
// Return a whole candidate; no storage writes or mutation of live state.
return {snapshot: saved, values: evaluate(saved.samples, expected)};
}
This excerpt is the entire restoration function. Its expected context comes from trusted application configuration through context(). Constructing it from the saved record would turn the comparisons into self-confirmation. Likewise, a context carrying a hash copied from a manifest without checking the actual bytes would not establish which data evaluation used. This example computes the hash directly from the frozen coefficients.
The function returns a complete candidate. A synchronous integration can assign live = restore(text, expected) only after the right-hand side succeeds. A malformed later sample cannot leave half the results installed. If loading the context is asynchronous, the caller additionally needs cancellation or a generation check to prevent an older request from replacing newer state; this synchronous core does not solve that race.
Unknown cached fields are ignored deliberately. The decoder does not copy an imported values array into the candidate. Validation still applies to every accepted input: Array.from materializes sparse slots before checking them, avoiding the holes that Array.every alone skips.
Keep storage failure separate from computation failure
The browser demonstration accepts and computes samples before attempting to persist them. If storage fails, the current values remain visible with an unsaved status. It does not claim the next reload can recover them.
The storage accessor is a callback so that both obtaining localStorage and calling setItem occur inside the error boundary. The Web Storage specification describes access restrictions and quota errors, and warns authors not to assume a locking mechanism across agent clusters.
The example makes one write to one key. This is not a transaction spanning application state, browser storage, and other tabs. There is no claim about physical disk durability or concurrent writers. A successful restore also does not automatically overwrite the saved record: reading an old format and upgrading persisted bytes are separate decisions.
Test a readable record under incompatible contexts
The fixed schema-1 fixture is a synthetic old-format record written for this experiment. It is not a recovered production artifact. Tests read its literal bytes rather than regenerate an “old” snapshot with the current writer. That makes the decoder test independent of changes to today's serializer, although it cannot prove compatibility with real historical data that was never supplied.
These are the outputs of node demo.mjs. Each row uses the same saved record; “unchecked” means evaluating its inputs under the row's context without validating the binding.
| Context | Unchecked result | Restore outcome |
|---|---|---|
| Original context | [0,2,3] |
accepted [0,2,3] |
| Changed algorithm | [1,2,4] |
ALGORITHM_MISMATCH |
| Changed coefficients | [1,2,4] |
DATA_MISMATCH |
The last two unchecked outputs coincide, but their causes differ. Separate checks identify which contract failed. Replacing both saved identifiers with the current ones would make validation pass while discarding the promise to reproduce the earlier calculation.
On Windows with Node.js 22.22.0, the independent suite passed 17 tests, with 0 failures. These cover migration, context mismatches, ordered duplicates, malformed inputs, mutation during hashing, storage exceptions, and unchanged live state after rejection. A separate copy of the example installed its own pinned compiler and passed strict checking. The copy remained inside the permitted workspace, but used its own dependency directory and no project imports.
A browser run on Chrome 157.0.8103.79 passed 5 checks: real save/reload, excluding an unaccepted draft, rejection without changing visible or stored state, old-format import, and an injected quota failure. The last check deliberately throws an exception; it does not measure actual disk exhaustion. These are controlled example results, not evidence of production incidents or all-browser compatibility.
One negative test is particularly important: changing the fixture's samples to [4], while keeping a compatible context, is accepted and yields [6]. The data digest is a compatibility check, not authentication. It does not protect user inputs against editing, establish who wrote a record, or replace server-side validation where authority matters.
Reproduce the experiment without an application repository
Create a directory named snapshot-contract. Expand the file blocks below and save each under its indicated relative filename, including the fixtures subdirectory. All implementation, tests, browser files, and the fixed fixture are included here; no private repository or project website is needed.
Use Node.js 22.22.0, the tested runtime. The built-in test runner and runtime example need no dependency installation:
cd snapshot-contract
node --test restore.test.mjs
node demo.mjs
node serve.mjs
Open http://127.0.0.1:4179 for the browser demonstration. Accept the initial values, reload, and then try importing invalid samples. The Restore button changes in-memory state; Accept and save persists it. Stop the server with Ctrl+C.
For the optional strict JavaScript type check, also save the supplied package manifest, lockfile, and TypeScript configuration, then run:
npm ci --ignore-scripts --no-audit --no-fund
npm run typecheck
TypeScript 5.9.3 checks restore.mjs through JSDoc and checkJs. This check does not cover the test files or inline browser integration. The clean-install check used npm 10.9.4; runtime tests do not resolve any project modules.
restore.mjs — complete file
// @ts-check
/** @typedef {'floor-v1'|'nearest-v2'} Algorithm */
/** @typedef {Readonly<{algorithm: Algorithm, dataHash: string,
* coefficients: readonly number[]}>} Context */
/** @typedef {{schema: 2, algorithm: Algorithm, dataHash: string,
* samples: number[]}} Snapshot */
/** @param {unknown} value @returns {value is Record<string, unknown>} */
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
/** @param {unknown} value @returns {value is number} */
const integer = value => typeof value === 'number' && Number.isSafeInteger(value)
&& Math.abs(value) <= 1_000_000 && !Object.is(value, -0);
/** @param {unknown} value @returns {number[]} */
function samples(value) {
if (!Array.isArray(value) || value.length > 1000) throw Error('INVALID_SAMPLES');
// Array.from visits holes too; Array.every alone skips sparse slots.
const copy = Array.from(value);
if (!copy.every(integer)) throw Error('INVALID_SAMPLES');
return copy;
}
/** @param {unknown} algorithm @param {unknown} coefficients @returns {Promise<Context>} */
export async function context(algorithm, coefficients) {
if (algorithm !== 'floor-v1' && algorithm !== 'nearest-v2') throw Error('UNKNOWN_ALGORITHM');
const tuple = samples(coefficients);
if (tuple.length !== 3 || tuple[2] <= 0) throw Error('INVALID_COEFFICIENTS');
// Defined encoding: UTF-8 JSON array, positional integers, domain prefix.
// Copy before await: hashing and evaluation must see the same values.
Object.freeze(tuple);
const bytes = new TextEncoder().encode(JSON.stringify(['calibration-v1', ...tuple]));
const digest = await crypto.subtle.digest('SHA-256', bytes);
const dataHash = Array.from(new Uint8Array(digest), n => n.toString(16).padStart(2, '0')).join('');
return Object.freeze({algorithm, dataHash, coefficients: tuple});
}
/** @param {readonly number[]} input @param {Context} ctx */
export function evaluate(input, ctx) {
const [gain, offset, divisor] = ctx.coefficients;
return samples(input).map(x => {
const value = (gain * x + offset) / divisor;
const rounded = ctx.algorithm === 'floor-v1' ? Math.floor(value) : Math.round(value);
return Object.is(rounded, -0) ? 0 : rounded;
});
}
/** @param {readonly number[]} input @param {Context} ctx @returns {Snapshot} */
export function snapshot(input, ctx) {
return {schema: 2, algorithm: ctx.algorithm, dataHash: ctx.dataHash, samples: samples(input)};
}
/** @param {unknown} raw @returns {Snapshot} */
export function decode(raw) {
if (typeof raw !== 'string' || raw.length > 16_000) throw Error('INVALID_TEXT');
/** @type {unknown} */
const value = JSON.parse(raw);
if (!record(value)) throw Error('INVALID_RECORD');
if (value.schema !== 1 && value.schema !== 2) throw Error('UNKNOWN_SCHEMA');
if (value.algorithm !== 'floor-v1' && value.algorithm !== 'nearest-v2') throw Error('UNKNOWN_ALGORITHM');
if (typeof value.dataHash !== 'string' || !/^[a-f0-9]{64}$/.test(value.dataHash)) throw Error('INVALID_HASH');
// Schema 1 used inputs. Migration changes structure, never the binding.
return {schema: 2, algorithm: value.algorithm, dataHash: value.dataHash,
samples: samples(value.schema === 1 ? value.inputs : value.samples)};
}
/** @param {unknown} raw @param {Context} expected */
export function restore(raw, expected) {
const saved = decode(raw);
if (saved.algorithm !== expected.algorithm) throw Error('ALGORITHM_MISMATCH');
if (saved.dataHash !== expected.dataHash) throw Error('DATA_MISMATCH');
// Return a whole candidate; no storage writes or mutation of live state.
return {snapshot: saved, values: evaluate(saved.samples, expected)};
}
/** @param {() => Pick<Storage, 'setItem'>} openStorage
* @param {readonly number[]} input @param {Context} ctx */
export function save(openStorage, input, ctx) {
// Validate and copy inputs; the caller owns acceptance and presentation.
const text = JSON.stringify(snapshot(input, ctx));
try {
openStorage().setItem('calibration-snapshot', text);
return {saved: true, error: null};
} catch (error) {
return {saved: false, error: error instanceof Error ? error.name : 'StorageError'};
}
}
restore.test.mjs — complete file
import test from 'node:test';
import assert from 'node:assert/strict';
import {readFile} from 'node:fs/promises';
import {context, decode, evaluate, snapshot, restore, save} from './restore.mjs';
const old = await context('floor-v1', [3, 1, 2]);
// Frozen, handwritten old-format sample. Never regenerated by this test.
const fixture = await readFile(new URL('./fixtures/schema-1.json', import.meta.url), 'utf8');
const saved = () => JSON.parse(fixture);
test('fixed schema-1 record migrates while preserving meaning', () => {
const result = restore(fixture, old);
assert.deepEqual(result.values, [0, 2, 3]);
assert.equal(result.snapshot.schema, 2);
assert.equal(result.snapshot.algorithm, 'floor-v1');
assert.equal(result.snapshot.dataHash, saved().dataHash);
});
test('current format roundtrip preserves order and duplicate inputs', () => {
const input = [2, 0, 2];
const text = JSON.stringify(snapshot(input, old));
assert.deepEqual(restore(text, old).values, [3, 0, 3]);
});
test('algorithm change is rejected even when JSON shape is supported', async () => {
const next = await context('nearest-v2', [3, 1, 2]);
assert.deepEqual(evaluate([0, 1, 2], next), [1, 2, 4]);
assert.throws(() => restore(fixture, next), /ALGORITHM_MISMATCH/);
});
test('data change is rejected even with the same algorithm label', async () => {
const changed = await context('floor-v1', [3, 2, 2]);
assert.deepEqual(evaluate([0, 1, 2], changed), [1, 2, 4]);
assert.throws(() => restore(fixture, changed), /DATA_MISMATCH/);
});
test('extra cached values never control the restored answer', () => {
assert.deepEqual(restore(JSON.stringify({...saved(), values: [999]}), old).values, [0, 2, 3]);
});
test('unknown schema and unknown algorithm remain unsupported', () => {
assert.throws(() => restore(JSON.stringify({...saved(), schema: 9}), old), /UNKNOWN_SCHEMA/);
assert.throws(() => restore(JSON.stringify({...saved(), algorithm: 'future'}), old), /UNKNOWN_ALGORITHM/);
});
test('malformed JSON and malformed records are rejected', () => {
for (const raw of ['{', 'null', '[]', '{}', '42', JSON.stringify({...saved(), dataHash: 'oops'})]) {
assert.throws(() => restore(raw, old));
}
});
test('input bounds, null, strings, fractions, and sparse arrays are rejected', () => {
for (const inputs of [[null], ['2'], [1.5], [1_000_001], [NaN], [Infinity], [-0], Array(1)]) {
assert.throws(() => snapshot(inputs, old), /INVALID_SAMPLES/);
}
assert.throws(() => decode(JSON.stringify({...saved(), inputs: [0, null]})), /INVALID_SAMPLES/);
});
test('record and collection limits are enforced', () => {
assert.throws(() => decode(' '.repeat(16001)), /INVALID_TEXT/);
assert.throws(() => snapshot(Array(1001).fill(0), old), /INVALID_SAMPLES/);
});
test('invalid coefficients cannot create a context', async () => {
for (const tuple of [[1, 0, 0], [1, 0, -1], [1, 0], [1, 0, 0.5]]) {
await assert.rejects(context('floor-v1', tuple));
}
});
test('caller mutations during hashing cannot change the pinned coefficients', async () => {
const tuple = [3, 1, 2];
const pending = context('floor-v1', tuple);
tuple[1] = 2;
const pinned = await pending;
assert.equal(pinned.dataHash, old.dataHash);
assert.deepEqual(evaluate([0, 1, 2], pinned), [0, 2, 3]);
assert.throws(() => { pinned.coefficients[1] = 2; }, TypeError);
});
test('snapshot copies accepted inputs', () => {
const input = [0, 1, 2];
const document = snapshot(input, old);
input[0] = 100;
assert.deepEqual(document.samples, [0, 1, 2]);
});
test('failed restore leaves the previously published object untouched', () => {
let live = restore(fixture, old);
const before = live;
assert.throws(() => { live = restore(JSON.stringify({...saved(), inputs: [0, 1, null]}), old); });
assert.equal(live, before);
assert.deepEqual(live.values, [0, 2, 3]);
});
test('storage getter and write failures are reported without changing accepted inputs', () => {
const input = [0, 1, 2];
assert.deepEqual(save(() => { throw new DOMException('blocked', 'SecurityError'); }, input, old),
{saved: false, error: 'SecurityError'});
assert.deepEqual(save(() => ({setItem() { throw new DOMException('full', 'QuotaExceededError'); }}), input, old),
{saved: false, error: 'QuotaExceededError'});
assert.deepEqual(input, [0, 1, 2]);
});
test('one successful storage write contains inputs and binding only', () => {
const writes = [];
assert.equal(save(() => ({setItem(key, value) { writes.push([key, value]); }}), [0, 1, 2], old).saved, true);
assert.equal(writes.length, 1);
assert.deepEqual(Object.keys(JSON.parse(writes[0][1])).sort(), ['algorithm', 'dataHash', 'samples', 'schema']);
});
test('empty input and bounded negative input are deterministic', () => {
assert.deepEqual(restore(JSON.stringify(snapshot([], old)), old).values, []);
assert.deepEqual(evaluate([-1, -2, -1_000_000, 1_000_000], old), [-1, -3, -1500000, 1500000]);
});
test('editing a valid input is accepted: the digest is not authentication', () => {
assert.deepEqual(restore(JSON.stringify({...saved(), inputs: [4]}), old).values, [6]);
});
demo.mjs — complete file
import {readFile} from 'node:fs/promises';
import {context, evaluate, restore} from './restore.mjs';
const fixture = await readFile(new URL('./fixtures/schema-1.json', import.meta.url), 'utf8');
const rows = [];
for (const [name, algorithm, coefficients] of [
['Original context', 'floor-v1', [3, 1, 2]],
['Changed algorithm', 'nearest-v2', [3, 1, 2]],
['Changed coefficients', 'floor-v1', [3, 2, 2]],
]) {
const ctx = await context(algorithm, coefficients);
let outcome;
try { outcome = 'accepted ' + JSON.stringify(restore(fixture, ctx).values); }
catch (error) { outcome = error.message; }
rows.push({scenario: name, unchecked: evaluate([0, 1, 2], ctx), restore: outcome});
}
console.log(JSON.stringify(rows, null, 2));
fixtures/schema-1.json — complete file
{
"schema": 1,
"algorithm": "floor-v1",
"dataHash": "0497b4a4a649ce508c8c6c8cb1597dff98fc907bc365b031c2f9b1eb59c93349",
"inputs": [0, 1, 2]
}
index.html — complete file
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Snapshot contract experiment</title>
<style>body{max-width:720px;margin:40px auto;padding:0 20px;font:18px/1.6 system-ui}input,button,textarea{font:inherit;padding:8px;max-width:100%;box-sizing:border-box}textarea{width:100%;height:180px}pre{overflow:auto;background:#eee;padding:15px}button{margin:8px 0}</style></head><body>
<h1>Snapshot contract experiment</h1>
<p>Calibration: floor((3 × input + 1) / 2). Draft edits become accepted inputs only when Save is selected.</p>
<label>Samples (JSON array) <input id="samples" value="[0,1,2]"></label>
<button id="save" disabled>Accept and save</button>
<p>Accepted values</p><pre id="values">[]</pre><p id="status" role="status">Loading</p>
<label>Snapshot to restore<textarea id="import"></textarea></label>
<button id="restore" disabled>Restore snapshot</button>
<script type="module">
import {context, evaluate, restore, save} from './restore.mjs';
const ctx = await context('floor-v1', [3,1,2]);
const input = document.querySelector('#samples'), values = document.querySelector('#values');
const status = document.querySelector('#status'), raw = document.querySelector('#import');
let accepted = [];
function publish(candidate) {
accepted = candidate.snapshot.samples;
input.value = JSON.stringify(accepted);
values.textContent = JSON.stringify(candidate.values);
}
try {
const text = localStorage.getItem('calibration-snapshot');
if (text) { publish(restore(text, ctx)); raw.value = text; }
status.textContent = text ? 'Restored' : 'Ready';
} catch (error) { status.textContent = 'Restore failed: ' + error.message; }
document.querySelector('#save').onclick = () => {
try {
const next = JSON.parse(input.value);
const result = evaluate(next, ctx);
accepted = [...next];
values.textContent = JSON.stringify(result);
const outcome = save(() => localStorage, accepted, ctx);
status.textContent = outcome.saved ? 'Saved' : 'Unsaved: ' + outcome.error;
if (outcome.saved) raw.value = localStorage.getItem('calibration-snapshot');
} catch (error) { status.textContent = 'Input failed: ' + error.message; }
};
document.querySelector('#restore').onclick = () => {
try { const candidate = restore(raw.value, ctx); publish(candidate); status.textContent = 'Restored in memory'; }
catch (error) { status.textContent = 'Restore failed: ' + error.message; }
};
document.querySelectorAll('button').forEach(button => button.disabled = false);
</script></body></html>
serve.mjs — complete file
import {createServer} from 'node:http';
import {readFile} from 'node:fs/promises';
const files = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
['/restore.mjs', ['restore.mjs', 'text/javascript; charset=utf-8']],
['/fixtures/schema-1.json', ['fixtures/schema-1.json', 'application/json']],
]);
const port = Number(process.argv[2] || 4179);
createServer(async (req, res) => {
const entry = files.get(new URL(req.url, 'http://localhost').pathname);
if (!entry) { res.writeHead(404).end(); return; }
try {
res.writeHead(200, {'Content-Type': entry[1], 'Cache-Control': 'no-store'});
res.end(await readFile(new URL(entry[0], import.meta.url)));
} catch { res.writeHead(500).end(); }
}).listen(port, '127.0.0.1', () => console.log('http://127.0.0.1:' + port));
package.json — complete file
{
"name": "snapshot-contract-example",
"version": "1.0.0",
"private": true,
"type": "module",
"engines": { "node": ">=22.22.0" },
"scripts": {
"test": "node --test restore.test.mjs",
"typecheck": "tsc -p tsconfig.json",
"demo": "node demo.mjs",
"serve": "node serve.mjs"
},
"devDependencies": { "typescript": "5.9.3" }
}
package-lock.json — complete file
{
"name": "snapshot-contract-example",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "snapshot-contract-example",
"version": "1.0.0",
"devDependencies": {
"typescript": "5.9.3"
},
"engines": {
"node": ">=22.22.0"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
}
}
}
tsconfig.json — complete file
{
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"noEmit": true,
"strict": true,
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM"],
"types": []
},
"include": ["restore.mjs"]
}
Decide what must remain available
Rejecting incompatible state prevents silent reinterpretation, but rejection is not historical replay. Reproducing older results requires retaining the old algorithm and its data, plus a resolver that selects them by the recorded identities. Changing a migration to point at current coefficients cannot substitute for that retention policy.
This approach fits small deterministic computations whose authoritative inputs can be saved and whose dependencies can be pinned. If the calculation depends on time, randomness, remote responses, locale-sensitive behavior, or an external numerical engine, those conditions must be recorded or constrained too. A hash of only the coefficient table would then describe too little.
Saving final outputs can be preferable when historical dependencies cannot be retained, or when recomputation is too expensive. That alternative changes the trust and validation problem: the application must decide how stored outputs become authoritative and whether their provenance is sufficient. No performance comparison was performed here.
Before defining a snapshot format, write the promise made by restoration. Then make each dependency needed to keep that promise explicit. A successful parse proves that a reader understands a record's syntax. Rebuilding the same result requires a contract for its meaning.