perf(strategy): fuse validated state copying and freezing (P08)

This commit is contained in:
Boki 2026-10-28 12:58:21 -04:00
parent dbb6f4f5d1
commit 70d173a908
6 changed files with 6016 additions and 9 deletions

View file

@ -26,7 +26,17 @@ export function freeze<T>(value: T): DeepReadonly<T> {
/** Check descriptors before reading values: JSON.stringify would silently lose
* symbols/custom array keys, invoke accessors, or rewrite non-JSON objects. */
export function stateCopy(input: unknown, ancestors = new Set<object>()): unknown {
export function stateCopy(input: unknown): unknown {
return copyJsonState(input, new Set(), false);
}
/** Validate and detach callback state, freezing each completed container once.
* Never freeze author-owned input or trust its current frozen status. */
export function frozenStateCopy(input: unknown): DeepReadonly<unknown> {
return copyJsonState(input, new Set(), true);
}
function copyJsonState(input: unknown, ancestors: Set<object>, frozen: boolean): unknown {
if (input === null || typeof input === 'string' || typeof input === 'boolean') {
return input;
}
@ -44,7 +54,6 @@ export function stateCopy(input: unknown, ancestors = new Set<object>()): unknow
if (Object.getPrototypeOf(input) !== (array ? Array.prototype : Object.prototype)) {
throw invalid();
}
const descriptors = Object.getOwnPropertyDescriptors(input);
const keys = Reflect.ownKeys(input);
if (keys.some(key => typeof key !== 'string')) {
throw invalid();
@ -52,20 +61,27 @@ export function stateCopy(input: unknown, ancestors = new Set<object>()): unknow
ancestors.add(input);
try {
const data = (key: string): unknown => {
const descriptor = descriptors[key];
const descriptor = Object.getOwnPropertyDescriptor(input, key);
if (!descriptor?.enumerable || !('value' in descriptor)) {
throw invalid();
}
return stateCopy(descriptor.value, ancestors);
return copyJsonState(descriptor.value, ancestors, frozen);
};
let output: unknown[] | Record<string, unknown>;
if (array) {
if (keys.length !== input.length + 1) {
throw invalid();
}
return Array.from({ length: input.length }, (_, index) => data(String(index)));
const values = new Array<unknown>(input.length);
for (let index = 0; index < input.length; index++) {
values[index] = data(String(index));
}
output = values;
} else {
// fromEntries preserves an own '__proto__' key without changing prototype.
output = Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
}
// fromEntries preserves an own '__proto__' key without changing prototype.
return Object.fromEntries((keys as string[]).sort().map(key => [key, data(key)]));
return frozen ? Object.freeze(output) : output;
} finally {
ancestors.delete(input);
}
@ -185,7 +201,7 @@ export function stageStrategyDecision(
if (!output || typeof output !== 'object' || 'then' in output) {
throw new Error('Strategy decide must synchronously return nextState and intent');
}
const state = freeze(stateCopy(output.nextState));
const state = frozenStateCopy(output.nextState);
const decision = parseFinancialStrategyDecision({
version: 1,
sessionId: sessionId,

File diff suppressed because it is too large Load diff

View file

@ -7,6 +7,7 @@
* bun run scripts/benchmark-research.ts --session --measure # 1k/10k bars, actual TS decisions
* bun run scripts/benchmark-research.ts --session --measure --profile=sparse --bars=10000
* bun run scripts/benchmark-research.ts --session --measure --profile=all --format=both --bars=10000
* bun run scripts/benchmark-research.ts --sma --measure # SMA vs exact recorded decisions
* Build workspace libraries/config and the local engine first. JSON stdout; diagnostics stderr.
*/
import { createHash } from 'node:crypto';
@ -254,7 +255,7 @@ function command(args: string[]): string {
return result.stdout.toString().trimEnd();
}
function identity() {
export function identity() {
const paths = command(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'])
.split('\0')
.filter(Boolean)
@ -342,6 +343,7 @@ export function verifyRepeats(
export function parseBenchmarkArguments(args: string[]) {
const options = {
session: false,
sma: false,
measured: false,
large: false,
selfTest: false,
@ -357,6 +359,9 @@ export function parseBenchmarkArguments(args: string[]) {
}
seen.add(flag);
switch (flag) {
case '--sma':
options.sma = true;
break;
case '--session':
options.session = true;
break;
@ -406,10 +411,19 @@ export function parseBenchmarkArguments(args: string[]) {
if (options.totalBars !== undefined && (!options.measured || options.large)) {
throw new Error('--bars requires --measure and cannot be combined with --large');
}
if (options.sma && (options.session || options.large || ['--profile', '--format', '--bars'].some(flag => seen.has(flag)))) {
throw new Error('--sma supports only --measure or --self-test');
}
return options;
}
async function main(args: string[]) {
if (args[0] === '--sma-child') {
const { smaChild } = await import('./benchmark-sma');
const { workload, mode } = JSON.parse(args[1] ?? '');
process.stdout.write(JSON.stringify(await smaChild(root, workload, mode)) + '\n');
return;
}
if (args[0] === '--session-child') {
const { sessionChild } = await import('./benchmark-replay');
process.stdout.write(JSON.stringify(await sessionChild(JSON.parse(args[1] ?? ''))) + '\n');
@ -422,6 +436,11 @@ async function main(args: string[]) {
const selection = parseBenchmarkArguments(args);
const metadata = identity(); // Excluded from workload timings.
const measured = selection.measured;
if (selection.sma) {
const { smaBenchmark } = await import('./benchmark-sma');
await smaBenchmark(root, fileURLToPath(import.meta.url), metadata, measured);
return;
}
if (selection.session) {
const { sessionBenchmark } = await import('./benchmark-replay');
await sessionBenchmark(

185
scripts/benchmark-sma.ts Normal file
View file

@ -0,0 +1,185 @@
/** P08 paired workload, invoked through benchmark-research.ts --sma. */
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { loadavg } from 'node:os';
import { join } from 'node:path';
import type { ReplayOutput, ReplayProjectionResult } from '../apps/stock/orchestrator/src/contracts/native-replay';
import type { FinancialStrategyDecision } from '@stock-bot/types';
type Mode = 'sma' | 'recorded';
export type SmaWorkload = { totalBars: number; assets: number; owners: number; fastPeriod: number; slowPeriod: number; untradedAssets: number };
const hash = (value: string | Uint8Array) => createHash('sha256').update(value).digest('hex');
export function validateSmaWorkload(workload: SmaWorkload, mode: Mode): void {
assert(mode === 'sma' || mode === 'recorded', 'Unknown SMA benchmark mode');
const { totalBars, assets, owners, fastPeriod, slowPeriod, untradedAssets } = workload;
assert([totalBars, assets, owners, fastPeriod, slowPeriod, untradedAssets].every(Number.isSafeInteger), 'Expected integer benchmark selections');
assert(totalBars > 0 && assets > 0 && owners > 0 && owners <= assets && totalBars % assets === 0, 'Invalid asset/owner topology');
assert(fastPeriod > 0 && slowPeriod > fastPeriod && totalBars / assets > slowPeriod + 1, 'Invalid SMA periods or insufficient bars');
assert(untradedAssets === assets - owners, 'Incorrect untraded asset count');
}
export async function smaChild(root: string, workload: SmaWorkload, mode: Mode) {
validateSmaWorkload(workload, mode);
const addon = join(root, 'apps/stock/engine/dist/engine.node');
const start = performance.now();
const nativeSha256 = hash(readFileSync(addon));
const importsStart = performance.now();
const { nativeReplayFixture } = await import('../test/fixtures/native-replay');
const { validateDatasetV2 } = await import('../apps/stock/orchestrator/src/data/historical-dataset-v2');
const { builtinStrategySelectionSchema } = await import('../apps/stock/orchestrator/src/contracts/builtin-strategy');
const { createBuiltinStrategy, validateBuiltinStrategyBindings } = await import('../apps/stock/orchestrator/src/strategies/canonical-builtins');
const { prepareReplayLoad, NativeReplaySession, runReplaySession } = await import('../apps/stock/orchestrator/src/backtest/native-replay');
const { runStrategyReplay } = await import('../apps/stock/orchestrator/src/backtest/strategy-runtime');
const importMs = performance.now() - importsStart;
const preparationStart = performance.now();
const owners = Array.from({ length: workload.owners }, (_, i) => `owner-${i}`);
const barsPerAsset = workload.totalBars / workload.assets;
assert(Number.isSafeInteger(barsPerAsset) && barsPerAsset > workload.slowPeriod + 1);
assert(workload.owners <= workload.assets && workload.untradedAssets === workload.assets - workload.owners);
const fixture = nativeReplayFixture(barsPerAsset, workload.assets, owners);
fixture.config.matching.risk.ledger.initialCapital = '1000000.00000000';
// One owner selects one series. Remaining assets still replay/mark but are untraded.
fixture.config.cadence = owners.map((owner_id, i) => ({ owner_id, series_ids: [`${fixture.instruments[i]}:1m`] }));
const dataset = validateDatasetV2(JSON.parse(JSON.stringify(fixture.dataset)));
const load = prepareReplayLoad(dataset, fixture.config);
const selections = owners.map((ownerId, i) => builtinStrategySelectionSchema.parse({
ownerId, strategyId: 'sma_crossover', strategyVersion: 'sma-crossover-long-only/v1', seed: i + 42,
instrumentId: fixture.instruments[i], seriesId: `${fixture.instruments[i]}:1m`, ownerBudget: '1000.00000000',
parameters: { fastPeriod: workload.fastPeriod, slowPeriod: workload.slowPeriod },
}));
validateBuiltinStrategyBindings(selections, load);
const programs = selections.map(createBuiltinStrategy);
const preparationMs = performance.now() - preparationStart;
const selectedByOwner = new Map(selections.map((selection) => [selection.ownerId, selection.instrumentId]));
function validateFinancial(result: ReplayOutput): asserts result is ReplayProjectionResult {
assert('format' in result && result.format === 'projection');
assert.equal(result.status, 'complete');
assert.equal(result.view.orders.length, 0, 'Termination must clear active orders');
assert.equal(result.view.reservations.length, 0, 'Termination must clear reservations');
assert.equal(result.view.portfolio.fees.length, workload.owners);
assert(result.projection.fills.length > 0, 'Fixture must exercise actual trading');
for (const position of result.view.portfolio.positions) {
assert.equal(position.instrumentId, selectedByOwner.get(position.ownerId), 'Strategy crossed instrument ownership');
assert(!position.quantity.startsWith('-'), 'Long-only quantity became negative');
}
for (const fill of result.projection.fills) assert.equal(fill.instrumentId, selectedByOwner.get(fill.ownerId));
}
// Untimed reference captures ACTUAL owner-stamped decisions, including all IDs.
// The comparison removes author/state overhead without normalizing economic output.
const referenceStart = performance.now();
const tape: { barrierId: string; decisions: FinancialStrategyDecision[] }[] = [];
const originalSubmit = NativeReplaySession.prototype.submit;
NativeReplaySession.prototype.submit = function (barrierId: string, decisions: FinancialStrategyDecision[]) {
tape.push({ barrierId, decisions: structuredClone(decisions) });
return originalSubmit.call(this, barrierId, decisions);
};
let referenceResultHash: string, referenceDiagnosticsHash: string;
let economic: { cash: string; equity: string; positions: ReplayProjectionResult['view']['portfolio']['positions']; fees: ReplayProjectionResult['view']['portfolio']['fees']; fills: number; decisions: number };
try {
const reference = runStrategyReplay(load, programs, { resultFormat: 'projection', eventBudget: 64 });
validateFinancial(reference.result);
referenceResultHash = hash(JSON.stringify(reference.result));
referenceDiagnosticsHash = hash(JSON.stringify(reference.diagnostics));
assert.equal(tape.length, barsPerAsset - 1);
assert.equal(tape.reduce((sum, row) => sum + row.decisions.length, 0), workload.owners * (barsPerAsset - 1));
for (const strategy of reference.diagnostics.strategies) {
assert.equal(strategy.nextDecisionSequence, barsPerAsset - 1);
assert.equal(strategy.rng.draws, 0, 'Canonical SMA must not consume randomness');
assert.equal(strategy.observationCount, workload.assets * (barsPerAsset - 1));
assert.equal((strategy.state as { closes: unknown[] }).closes.length, workload.slowPeriod + 1);
}
economic = { cash: reference.result.view.portfolio.cash, equity: reference.result.view.equity, positions: reference.result.view.portfolio.positions, fees: reference.result.view.portfolio.fees, fills: reference.result.projection.fills.length, decisions: tape.reduce((sum, row) => sum + row.decisions.length, 0) };
} finally {
NativeReplaySession.prototype.submit = originalSubmit;
}
const referenceCaptureAndVerificationMs = performance.now() - referenceStart;
const tapeHash = hash(JSON.stringify(tape));
const trials = [];
for (let repeat = 0; repeat < 2; repeat++) {
const executionStart = performance.now();
let cursor = 0;
const output = mode === 'sma'
? runStrategyReplay(load, repeat === 1 ? [...programs].reverse() : programs, { resultFormat: 'projection', eventBudget: 64 })
: runReplaySession(new NativeReplaySession(load), {
stage(context) {
const recorded = tape[cursor++];
assert(recorded, 'Unexpected replay barrier');
assert.equal(recorded.barrierId, context.barrier.barrier_id);
assert(recorded.decisions.every(decision => decision.revision === context.barrier.revision));
return recorded.decisions;
},
}, { resultFormat: 'projection', eventBudget: 64 });
const executionWallMs = performance.now() - executionStart;
const verificationStart = performance.now();
if (mode === 'recorded') assert.equal(cursor, tape.length, 'Unused recorded decisions');
validateFinancial(output.result);
const resultHash = hash(JSON.stringify(output.result));
assert.equal(resultHash, referenceResultHash, 'Complete financial output differs from exact recorded-decision replay');
const diagnosticsHash = 'diagnostics' in output ? hash(JSON.stringify(output.diagnostics)) : null;
if (mode === 'sma') assert.equal(diagnosticsHash, referenceDiagnosticsHash, 'Owner state/RNG/cursors changed on fresh replay/reordered owners');
trials.push({ repeat, reversePrograms: mode === 'sma' && repeat === 1, resultHash, diagnosticsHash, executionWallMs, metrics: output.metrics, verificationMs: performance.now() - verificationStart, rssBytes: process.memoryUsage().rss });
}
const peak = process.platform === 'linux' ? /^VmHWM:\s+(\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8')) : null;
return { workload, mode, nativeSha256, datasetHash: dataset.manifest.hash, configHash: hash(JSON.stringify(load.config)), programHash: hash(JSON.stringify(selections)), selections, referenceResultHash, referenceDiagnosticsHash, tapeHash, economic,
phasesMs: { importMs, preparationMs, referenceCaptureAndVerificationMs, childWallMs: performance.now() - start }, peakRssBytes: peak ? Number(peak[1]) * 1024 : null, trials };
}
function median(values: number[]) {
const sorted = [...values].sort((a, b) => a - b), middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
}
export async function smaBenchmark(root: string, entrypoint: string, identity: ReturnType<typeof import('./benchmark-research').identity>, measured: boolean) {
const smoke = !measured, measurements = [];
assert(smoke || identity.native.matchedBuildProfiles.includes('release'), 'Full measurements require the matching release addon');
const shapes = smoke ? [[1, 1, 300], [10, 2, 3000], [10, 10, 3000]] : [[1, 1, 10000], [10, 2, 10000], [10, 10, 10000]];
for (const [fastPeriod, slowPeriod] of [[5, 15], [15, 252]]) {
for (const [assets, owners, totalBars] of shapes) {
const workload: SmaWorkload = { totalBars: totalBars!, assets: assets!, owners: owners!, fastPeriod: fastPeriod!, slowPeriod: slowPeriod!, untradedAssets: assets! - owners! };
const samples: (Awaited<ReturnType<typeof smaChild>> & { processRepeat: number; processWallMs: number })[] = [];
for (let processRepeat = 0; processRepeat < 2; processRepeat++) {
const modes: Mode[] = processRepeat === 0 ? ['recorded', 'sma'] : ['sma', 'recorded'];
for (const mode of modes) {
const start = performance.now();
const worker = Bun.spawn([process.execPath, entrypoint, '--sma-child', JSON.stringify({ workload, mode })], { cwd: root, stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NODE_ENV: 'production' } });
const [stdout, stderr, exit] = await Promise.all([new Response(worker.stdout).text(), new Response(worker.stderr).text(), worker.exited]);
if (stderr) process.stderr.write(`[${fastPeriod}/${slowPeriod}/${assets}/${owners}/${mode}/${processRepeat}]\n${stderr}`);
assert.equal(exit, 0, `${stderr}\n${stdout}`);
const sample = JSON.parse(stdout) as Awaited<ReturnType<typeof smaChild>>;
assert.deepEqual(sample.workload, workload);
assert.equal(sample.mode, mode);
assert.equal(sample.nativeSha256, identity.native.sha256);
samples.push({ ...sample, processRepeat, processWallMs: performance.now() - start });
}
}
const reference = samples[0]!;
for (const sample of samples) for (const key of ['datasetHash', 'configHash', 'programHash', 'referenceResultHash', 'referenceDiagnosticsHash', 'tapeHash'] as const) assert.equal(sample[key], reference[key]);
const summaries = (['recorded', 'sma'] as Mode[]).map(mode => {
const trials = samples.filter(s => s.mode === mode).flatMap(s => s.trials);
assert.equal(trials.length, 4);
const medianExecutionWallMs = median(trials.map(t => t.executionWallMs));
return { mode, samples: 4, medianExecutionWallMs, medianBarsPerSecond: workload.totalBars / (medianExecutionWallMs / 1000), medianDecisionsPerSecond: reference.economic.decisions / (medianExecutionWallMs / 1000), medianVerificationMs: median(trials.map(t => t.verificationMs)), resultHash: reference.referenceResultHash,
medianMetrics: Object.fromEntries(Object.keys(trials[0]!.metrics).map(key => [key, median(trials.map(t => t.metrics[key as keyof typeof t.metrics]))])) };
});
measurements.push({ workload, verified: true, summaries, samples });
process.stderr.write(`Verified SMA ${fastPeriod}/${slowPeriod}, ${assets} assets, ${owners} owners (${workload.untradedAssets} untraded assets): exact recorded/SMA financial hashes, 4 timed samples per mode\n`);
}
}
process.stdout.write(JSON.stringify({ schemaVersion: 1, path: 'canonical-sma-versus-exact-recorded', mode: smoke ? 'smoke' : 'measurement', ...identity, hostLoadAtFinish: loadavg(),
limitations: [
'10,000 TOTAL bars in full workloads, not per asset. Synthetic sawtooth fixture unchanged; one owner per selected asset. Ten-assets/two-owners explicitly leaves eight assets untraded while all ten replay/mark.',
'No database, durable queue, public-result mapping, real native-worker IPC, or production wall-clock throughput measurement. Each child imports modules and directly executes the canonical runtime.',
'Each fresh child first runs an untimed SMA reference to capture exact submitted financial identities. Timed fresh sessions therefore run in warmed processes; imports, preparation, reference capture and process wall time are separate.',
'Actual versioned SMA code uses bounded slow+1 JSON history and reviewed trailing calculations. Both 5/15 and 15/252 are measured; large-period copying/scanning costs remain included.',
'Recorded control replays exact captured decisions through the same Rust/native pull loop. Complete financial projection hashes including all IDs must match; there is no TypeScript accounting oracle or financial normalization.',
'executionWallMs includes native-session construction, replay, state copying/strategy/staging/feedback where applicable, finalization and disposal. Benchmark verification/hashing is measured separately.',
'decisionMs includes host validation/state copying/strategy execution/admission feedback for SMA and tape lookup/checks for recorded control. Difference is not pure callback or NAPI crossing cost.',
'Both modes retain reference decision tapes; RSS includes reference activity and tape memory. No allocation attribution or resident-dataset caching claim.',
'Two separate processes per mode, two fresh timed sessions each, counterbalanced mode order. Second SMA session reverses owner callback order and must preserve financial and diagnostic hashes. This checks fresh whole-attempt recomputation, not native checkpoint resume.',
'Shared host, no timing assertion, confidence interval, cold-start SLA, or cross-artifact performance attribution. Root must freeze source and use the matching release addon before execution.',
], measurements }, null, 2) + '\n');
}

View file

@ -0,0 +1,45 @@
import { expect, test } from 'bun:test';
import { parseBenchmarkArguments } from '../benchmark-research';
import { validateSmaWorkload } from '../benchmark-sma';
const workload = { totalBars: 10000, assets: 10, owners: 2, fastPeriod: 15, slowPeriod: 252, untradedAssets: 8 };
test('sma_benchmark_modes rejects incompatible modes, periods and topology', () => {
expect(parseBenchmarkArguments(['--sma', '--measure'])).toMatchObject({ sma: true, measured: true });
for (const flags of [['--sma', '--session'], ['--sma', '--measure', '--large'], ['--sma', '--profile=all'], ['--sma', '--measure', '--bars=10000']]) {
expect(() => parseBenchmarkArguments(flags)).toThrow();
}
expect(() => validateSmaWorkload(workload, 'sma')).not.toThrow();
expect(() => validateSmaWorkload(workload, 'recorded')).not.toThrow();
for (const changes of [{ owners: 11 }, { untradedAssets: 0 }, { fastPeriod: 252 }, { totalBars: 10001 }, { slowPeriod: 1000 }, { fastPeriod: 0 }, { owners: NaN }]) {
expect(() => validateSmaWorkload({ ...workload, ...changes }, 'sma')).toThrow();
}
});
test('sma_recorded_decision_parity verifies six shapes and actual financial/diagnostic identities', async () => {
const process = Bun.spawn([Bun.which('bun')!, 'scripts/benchmark-research.ts', '--sma', '--self-test'], { stdout: 'pipe', stderr: 'pipe' });
const [stdout, stderr, exit] = await Promise.all([new Response(process.stdout).text(), new Response(process.stderr).text(), process.exited]);
expect(exit, stderr).toBe(0);
const report = JSON.parse(stdout);
expect(report.mode).toBe('smoke');
expect(report.measurements).toHaveLength(6);
for (const measurement of report.measurements) {
expect(measurement.verified).toBe(true);
expect(measurement.workload.untradedAssets).toBe(measurement.workload.assets - measurement.workload.owners);
expect(measurement.samples).toHaveLength(4);
const reference = measurement.samples[0];
for (const sample of measurement.samples) {
expect(sample.economic.fills).toBeGreaterThan(0);
expect(sample.economic.decisions).toBe(sample.workload.owners * (sample.workload.totalBars / sample.workload.assets - 1));
expect(sample.nativeSha256).toBe(report.native.sha256);
for (const key of ['datasetHash', 'configHash', 'programHash', 'referenceResultHash', 'referenceDiagnosticsHash', 'tapeHash']) {
expect(sample[key]).toBe(reference[key]);
}
for (const trial of sample.trials) {
expect(trial.resultHash).toBe(reference.referenceResultHash);
if (sample.mode === 'sma') expect(trial.diagnosticsHash).toBe(reference.referenceDiagnosticsHash);
expect(trial.metrics).toHaveProperty('decisionMs');
}
}
}
}, 60000);

View file

@ -0,0 +1,96 @@
import { expect, test } from 'bun:test';
import {
frozenStateCopy,
stateCopy,
} from '../../apps/stock/orchestrator/src/strategies/strategy-decision';
test('copying preserves canonical key order and detaches each alias while freezing only copies', () => {
const shared = { z: [2, 3], a: 1 };
const input = { z: shared, a: shared, ...JSON.parse('{"__proto__":{"x":1}}') };
const copy = frozenStateCopy(input) as typeof input;
expect(JSON.stringify(copy)).toBe(
'{"__proto__":{"x":1},"a":{"a":1,"z":[2,3]},"z":{"a":1,"z":[2,3]}}'
);
expect(Object.getPrototypeOf(copy)).toBe(Object.prototype);
expect(copy.a).not.toBe(copy.z);
expect(copy.a.z).not.toBe(shared.z);
expect(Object.isFrozen(copy)).toBe(true);
expect(Object.isFrozen(copy.a)).toBe(true);
expect(Object.isFrozen(copy.a.z)).toBe(true);
expect(Object.isFrozen(shared)).toBe(false);
shared.z.push(4);
expect(copy.a.z).toEqual([2, 3]);
const mutable = stateCopy(copy) as typeof input;
expect(Object.isFrozen(mutable.a.z)).toBe(false);
mutable.a.z.push(9);
expect(copy.a.z).toEqual([2, 3]);
});
test('both copying paths reject lossy state without reading getters, even when frozen', () => {
let reads = 0;
const accessor = Object.defineProperty({}, 'x', {
enumerable: true,
get() {
reads++;
return 1;
},
});
const arrayAccessor = Object.defineProperty([1], '0', {
enumerable: true,
get() {
reads++;
return 1;
},
});
const cyclic: { self?: unknown } = {};
cyclic.self = cyclic;
const extraArrayKey = Object.assign([1], { extra: 2 });
const hiddenIndex = Object.defineProperty([1], '0', { enumerable: false });
const invalid = [
undefined,
-0,
NaN,
Infinity,
-Infinity,
1n,
() => 0,
Symbol('x'),
new Date(),
Object.create(null),
Object.create({ x: 1 }),
[, 1],
[undefined],
extraArrayKey,
hiddenIndex,
{ [Symbol('x')]: 1 },
Object.defineProperty({}, 'hidden', { value: 1 }),
accessor,
arrayAccessor,
cyclic,
];
for (const copy of [stateCopy, frozenStateCopy]) {
for (const value of invalid) expect(() => copy(value)).toThrow();
for (const value of [accessor, arrayAccessor, cyclic])
expect(() => copy(Object.freeze(value))).toThrow();
}
expect(reads).toBe(0);
});
test('both copying paths agree on empty containers, primitive roots and nonwritable data', () => {
for (const value of [
null,
true,
false,
'',
'x',
0,
1.25,
[],
{},
Object.freeze([1, { a: 'x' }]),
Object.defineProperty({}, 'x', { value: 1, enumerable: true }),
]) {
expect(frozenStateCopy(value)).toEqual(stateCopy(value));
expect(JSON.stringify(frozenStateCopy(value))).toBe(JSON.stringify(stateCopy(value)));
}
});