fix: bound recording timestamps before playback

Match upstream millisecond accumulation and bound native timer horizons.
Add deterministic rounding, overflow and non-progress regression casts,
with captured-player and WordPress playback/upload coverage.
This commit is contained in:
2026-10-15 11:30:31 +08:00
parent 487eedf0ba
commit e1cd87f87d
49 changed files with 1273 additions and 33 deletions
+76
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { loadRecording, DEFAULT_LIMITS, RecordingLoadError, validateInitialDimensions } from '../../src/recording-loader.js';
import { normalizePlayerOptions } from '../../src/options.js';
const encode = ( text ) => new TextEncoder().encode( text );
const h2 = { version: 2, width: 80, height: 24 };
@@ -127,6 +128,79 @@ test( 'non-finite timestamps and cumulative time overflow are rejected', async (
await rejectCode( JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ 1e305, 'x' ], [ 1e305, 'x' ] ] } ), 'time' );
} );
test( 'supported timeline boundary is inclusive across all formats and timing metadata', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
assert.equal( DEFAULT_LIMITS.timelineMs, 2147483647 );
for ( const version of [ 1, 2, 3 ] ) {
const header = version === 3 ? h3 : { ...h2, version };
const content = ( seconds, extra = {} ) => version === 1
? JSON.stringify( { ...header, ...extra, stdout: [ [ seconds, 'x' ] ] } )
: cast( { ...header, ...extra }, [ [ seconds, 'o', 'x' ] ] );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( maxSeconds ) ).fetchImpl } ) );
await rejectCode( content( maxSeconds + 0.001 ), 'time' );
await rejectCode( content( -0.001 ), 'time' );
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( 0, { [ key ]: maxSeconds } ) ).fetchImpl } ) );
for ( const value of [ maxSeconds + 0.001, -0.001, '1', null ] ) await rejectCode( content( 0, { [ key ]: value } ), 'time' );
}
}
} );
test( 'relative formats accumulate individually converted milliseconds in upstream order', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
const rounding = [ 307699.2378567164, 1839784.4091432837 ];
assert.equal( ( rounding[ 0 ] + rounding[ 1 ] ) * 1000, DEFAULT_LIMITS.timelineMs );
assert.ok( rounding[ 0 ] * 1000 + rounding[ 1 ] * 1000 > DEFAULT_LIMITS.timelineMs );
for ( const version of [ 1, 3 ] ) {
const content = ( intervals ) => version === 1
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: intervals.map( ( time ) => [ time, 'x' ] ) } )
: cast( h3, intervals.map( ( time ) => [ time, 'o', 'x' ] ) );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( [ 1, maxSeconds - 1 ] ) ).fetchImpl } ) );
for ( const intervals of [ [ 1, maxSeconds ], rounding, [ 2.996155224770526e303, 1.7677315826146105e305 ] ] ) {
await rejectCode( content( intervals ), 'time' );
}
}
await rejectCode( cast( h2, [ [ 1e20, 'o', 'x' ] ] ), 'time' );
} );
test( 'slow playback stays within native timer range without expanding the base horizon at higher speeds', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
for ( const version of [ 1, 2, 3 ] ) {
const content = ( seconds ) => version === 1
? JSON.stringify( { version: 1, width: 80, height: 24, stdout: [ [ seconds, 'x' ] ] } )
: cast( version === 3 ? h3 : h2, [ [ seconds, 'o', 'x' ] ] );
for ( const speed of [ 0.01, 0.5, 1, 100 ] ) {
const seconds = maxSeconds * Math.min( speed, 1 );
const options = { speed };
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( content( seconds ) ).fetchImpl, options } ) );
await rejectCode( content( seconds + 0.001 ), 'time', { options } );
}
}
// An idle limiter or late start does not waive validation of the raw horizon.
await rejectCode( cast( h2, [ [ maxSeconds, 'o', 'x' ] ] ), 'time', { options: { speed: 0.01, idleTimeLimit: 0.001, startAt: maxSeconds } } );
} );
test( 'normalized timing options are checked before any recording request', async () => {
const maxSeconds = DEFAULT_LIMITS.timelineMs / 1000;
for ( const options of [
...[ 0, -1, NaN, Infinity, 0.009, 101, '1' ].map( ( speed ) => ( { speed } ) ),
...[ 'startAt', 'idleTimeLimit' ].flatMap( ( key ) => [ maxSeconds + 0.001, -1, Infinity, NaN ].map( ( value ) => ( { [ key ]: value } ) ) ),
{ poster: 'npt:596:31:23.648' },
normalizePlayerOptions( { startAt: `${ '9'.repeat( 400 ) }:00:00` } ),
normalizePlayerOptions( { poster: `npt:${ '9'.repeat( 400 ) }:00:00` } ),
] ) {
const input = fixture( cast() );
await assert.rejects( loadRecording( '/cast', { fetchImpl: input.fetchImpl, options } ), { code: 'time' } );
assert.equal( input.calls.length, 0 );
}
for ( const options of [ { startAt: maxSeconds, idleTimeLimit: maxSeconds }, { poster: 'npt:596:31:23.647' }, { poster: 'data:text/plain,2147483648' } ] ) {
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast() ).fetchImpl, options } ) );
}
await assert.rejects( loadRecording( '/cast', { limits: { timelineMs: DEFAULT_LIMITS.timelineMs + 1 } } ), { code: 'policy' } );
assert.ok( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ] ] ) ).fetchImpl, limits: { timelineMs: 1000 } } ) );
await rejectCode( cast( h2, [ [ 1.001, 'o', 'x' ] ] ), 'time', { limits: { timelineMs: 1000 } } );
} );
test( 'invalid records do not report metadata', async () => {
for ( const content of [ '', '{}', cast( h2, [ [ 0, 'o', {} ] ] ), cast( h2, [ [ 0, '', 'x' ] ] ), `${ JSON.stringify( h2 ) }\n[invalid` ] ) {
let notified = false;
@@ -222,6 +296,8 @@ test( 'initial BOM is removed but later BOM-prefixed lines remain ignored', asyn
test( 'v2 absolute timestamps cannot move backward; equal timestamps remain valid', async () => {
await rejectCode( cast( h2, [ [ 2, 'o', 'x' ], [ 1, 'o', 'y' ] ] ), 'time' );
assert.equal( 10004.674 * 1000, 10004.673999999999 * 1000 );
await rejectCode( cast( h2, [ [ 10004.674, 'o', 'x' ], [ 10004.673999999999, 'o', 'y' ] ] ), 'time' );
assert.equal( ( await loadRecording( '/cast', { fetchImpl: fixture( cast( h2, [ [ 1, 'o', 'x' ], [ 1, 'o', 'y' ] ] ) ).fetchImpl } ) ).length, 3 );
} );
+53 -2
View File
@@ -31,7 +31,7 @@ function measure( entry, bytes ) {
const text = bytes.toString( 'utf8' );
let header;
let frames;
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0 };
const metrics = { bytes: bytes.length, v1Bytes: bytes.length, lineBytes: 0, events: 0, lines: 0, markers: 0, dimension: 0, cells: 0, depth: 0, tokens: 0, containers: 0, lineTokens: 0, timelineMs: 0 };
if ( entry.format === 1 ) {
header = JSON.parse( text );
assert.ok( Array.isArray( header.stdout ) );
@@ -71,6 +71,10 @@ function measure( entry, bytes ) {
}
size( ...dimensions );
let time = 0;
let milliseconds = 0;
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
if ( Object.hasOwn( header, key ) ) metrics.timelineMs = Math.max( metrics.timelineMs, header[ key ] * 1000 );
}
for ( const frame of frames ) {
assert.ok( Array.isArray( frame ) );
assert.equal( frame.length, 3 );
@@ -81,6 +85,8 @@ function measure( entry, bytes ) {
if ( entry.format === 2 ) assert.ok( frame[ 0 ] >= time );
time = entry.format === 2 ? frame[ 0 ] : time + frame[ 0 ];
assert.ok( Number.isFinite( time ) );
milliseconds = entry.format === 2 ? frame[ 0 ] * 1000 : milliseconds + frame[ 0 ] * 1000;
metrics.timelineMs = Math.max( metrics.timelineMs, milliseconds );
if ( frame[ 1 ] === 'm' ) metrics.markers++;
if ( frame[ 1 ] === 'r' ) {
assert.match( frame[ 2 ], /^[1-9][0-9]*x[1-9][0-9]*$/ );
@@ -107,7 +113,7 @@ test( 'golden recipes are deterministic, genuinely seeded, and bounded to known
test( 'every shared resource purpose retains its exact at/over pair', () => {
for ( const version of [ 1, 2, 3 ] ) {
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events' ] ) {
for ( const purpose of [ 'dimensions', 'cells', 'depth', 'events', 'timeline', 'duration', 'idle-limit' ] ) {
for ( const side of [ 'at', 'over' ] ) {
const entry = getSecurityCase( `${ purpose }-v${ version }-${ side }` );
assert.equal( entry.expected.accepted, side === 'at' );
@@ -126,6 +132,51 @@ test( 'every shared resource purpose retains its exact at/over pair', () => {
}
} );
test( 'timestamp regressions retain independently pinned witnesses and arithmetic', () => {
assert.equal( POLICY.timelineMs, 2147483647 );
assert.equal( securityManifest.policy.timelineMs, 2147483647 );
for ( const version of [ 1, 2, 3 ] ) {
for ( const purpose of [ 'timeline', 'duration', 'idle-limit' ] ) {
for ( const [ suffix, value ] of [ [ 'at', 2147483647 ], [ 'over', 2147483648 ] ] ) {
const entry = getSecurityCase( `${ purpose }-v${ version }-${ suffix }` );
assert.deepEqual( entry.boundary, { metric: 'timelineMs', limit: 2147483647, value } );
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
}
}
for ( const purpose of [ 'duration', 'idle-limit' ] ) assert.equal( getSecurityCase( `${ purpose }-v${ version }-zero` ).expected.accepted, true );
}
for ( const version of [ 1, 3 ] ) {
for ( const suffix of [ 'at', 'over' ] ) {
const entry = getSecurityCase( `interval-timeline-v${ version }-${ suffix }` );
assert.equal( entry.expected.jsError, suffix === 'over' ? 'time' : null );
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
assert.ok( frames.every( ( frame ) => frame[ 0 ] * 1000 < 2147483647 ), 'no individual interval may mask the cumulative boundary' );
}
for ( const [ id, a, b ] of [
[ 'ms-rounding-over', 307699.2378567164, 1839784.4091432837 ],
[ 'ms-sum-overflow', 2.996155224770526e303, 1.7677315826146105e305 ],
] ) {
const entry = getSecurityCase( `time-v${ version }-${ id }` );
assert.equal( entry.expected.jsError, 'time' );
assert.equal( entry.expected.accepted, false );
assert.ok( entry.bytes < 256, 'arithmetic witnesses must stay tiny' );
const text = securityFixtureBuffer( entry.id ).toString( 'utf8' );
const frames = version === 1 ? JSON.parse( text ).stdout : text.trimEnd().split( '\n' ).slice( 1 ).map( JSON.parse );
assert.deepEqual( frames.map( ( frame ) => frame[ 0 ] ), [ a, b ], 'the exact floating-point witness cannot silently change' );
assert.ok( Number.isFinite( a * 1000 ) && Number.isFinite( b * 1000 ) && Number.isFinite( ( a + b ) * 1000 ) );
assert.equal( ( a + b ) * 1000, id === 'ms-rounding-over' ? 2147483647 : 1.7976931348623155e308 );
assert.equal( a * 1000 + b * 1000, id === 'ms-rounding-over' ? 2147483647.0000002 : Infinity );
}
}
const stalled = getSecurityCase( 'time-v2-output-nonprogress' );
assert.equal( stalled.expected.jsError, 'time' );
assert.equal( stalled.expected.accepted, false );
assert.ok( stalled.bytes < 100 );
assert.deepEqual( JSON.parse( securityFixtureBuffer( stalled.id ).toString( 'utf8' ).split( '\n' )[ 1 ] ), [ 1e20, 'o', 'x' ] );
assert.equal( 1e20 * 1000 + 1000 / 60, 1e20 * 1000, 'the real 3.17 batch deadline cannot advance at this magnitude' );
} );
test( 'official native captures retain independently pinned provenance and identical output', () => {
const provenance = JSON.parse( readFileSync( new URL( 'provenance.json', root ), 'utf8' ) );
assert.deepEqual( provenance.artifacts.map( ( artifact ) => artifact.file ).sort(), [ 'official-v1.cast', 'official-v2.cast', 'official-v3.cast' ] );
+178 -2
View File
@@ -1,11 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { loadRecording, RecordingLoadError, DEFAULT_LIMITS } from '../../src/recording-loader.js';
import { securityManifest, securityCases, getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
test('shared security corpus pins the production policy and all six safe controls', () => {
assert.equal(DEFAULT_LIMITS.timelineMs, 2147483647, 'the test horizon is independently pinned');
assert.equal(securityManifest.schemaVersion, 1);
for (const [name, value] of Object.entries(securityManifest.policy)) {
assert.equal(DEFAULT_LIMITS[name], value, `the ${name} fixture boundary must match production`);
@@ -162,7 +164,11 @@ async function inspectPlayer(data) {
core.terminalReady();
await core.init();
const duration = core.getDuration();
assert.ok(Number.isFinite(duration));
assert.ok(Number.isFinite(core.getCurrentTime()));
await core.seek('100%');
assert.ok(Number.isFinite(core.getCurrentTime()), 'the actual seek destination remains finite');
assert.ok(Number.isFinite(core.getProgress()), 'the actual progress calculation remains finite');
const output = events.output.flat().join('');
await core.seek('0%');
assert.equal(core.getCurrentTime(), 0, 'the real driver can seek back to the start');
@@ -174,8 +180,9 @@ async function inspectPlayer(data) {
}
}
// Only known-small, accepted controls reach the real upstream parser/driver.
// Oversized/hostile corpus members are tested exclusively through our guard.
// Only known-small, accepted controls reach the real upstream parser/driver here.
// The tiny numeric witnesses below run separately with captured timers and a hard
// child-process deadline; no oversized payload reaches the real player.
const playableCases = securityCases.filter((entry) => entry.safePlayback === true);
for (const entry of playableCases) {
test(`pinned player 3.17 parses and seeks validated ${entry.id}`, async () => {
@@ -219,3 +226,172 @@ test('official outputs and seeded playback timelines are equivalent across all t
assert.deepEqual(controls.seeded[0].events.map((event) => event[0]), [0, 1, 8, 12]);
assert.ok(controls.seeded[0].output.includes(controls.official[0].output), 'seeded mutations retain the official captured output');
});
/**
* Actual upstream Core witness, isolated from the main runner. All timers are
* captured, never scheduled; at most three callbacks are invoked per witness.
* The parent also kills this child after 10 seconds if an upstream change causes
* an unexpected synchronous loop. No browser, terminal, real playback delay, or
* large payload is involved. The arithmetic checks above are not a Core double.
*/
async function timestampCoreRegression() {
const Core = await playerCore();
const realSetTimeout = globalThis.setTimeout;
const realClearTimeout = globalThis.clearTimeout;
const timers = new Map();
let timerId = 0;
globalThis.setTimeout = (callback, delay) => {
const id = ++timerId;
timers.set(id, { callback, delay });
return id;
};
globalThis.clearTimeout = (id) => { timers.delete(id); };
const parseFixture = (id) => {
const entry = getSecurityCase(id);
assert.ok(entry.bytes < 256, 'only pinned tiny witnesses may enter this child');
const text = securityFixtureBuffer(id).toString('utf8');
return entry.format === 1 ? JSON.parse(text) : text.trimEnd().split('\n').map(JSON.parse);
};
const createCore = (data) => {
const core = new Core({ data }, {
preload: true, speed: 1,
logger: { debug() {}, info() {}, warn() {}, error() {} },
});
const events = { output: [], error: [], ended: [] };
for (const [name, values] of Object.entries(events)) core.addEventListener(name, (value) => values.push(value));
core.terminalReady();
return { core, events };
};
const takeTimer = () => {
assert.equal(timers.size, 1, 'exactly one recording callback is pending');
const [id, timer] = timers.entries().next().value;
timers.delete(id);
return timer;
};
try {
// Deliberately bypass the guard ONLY for this fixed tiny upstream bug
// witness. A premature timer call safely exposes non-progress without
// waiting for 1e23 ms or advancing the clock into a synchronous loop.
const stalled = createCore(parseFixture('time-v2-output-nonprogress'));
try {
await stalled.core.init();
assert.ok(Number.isFinite(stalled.core.getDuration()));
assert.equal(timers.size, 0, 'initial loading timeout was cleared');
await stalled.core.play();
let previousCallback;
for (let n = 0; n < 3; n++) {
const timer = takeTimer();
assert.equal(timer.delay, 1e23, 'the unsafe upstream delay exceeds signed 32-bit timer range');
if (previousCallback) assert.equal(timer.callback, previousCallback, 'the same unconsumed event is rescheduled');
previousCallback = timer.callback;
timer.callback();
await Promise.resolve();
assert.deepEqual(stalled.events.output, Array.from({ length: n + 1 }, () => []), 'batching emits empty output without consuming x');
assert.deepEqual(stalled.events.ended, []);
}
assert.deepEqual(stalled.events.error, []);
process.stdout.write('v2 non-progress reproduced with three captured callbacks\n');
} finally {
await stalled.core.stop();
assert.equal(timers.size, 0, 'stopping removes the captured non-progress callback');
}
for (const version of [1, 3]) {
const overflow = createCore(parseFixture(`time-v${version}-ms-sum-overflow`));
try {
await overflow.core.init();
assert.equal(overflow.core.getDuration(), Infinity, 'real upstream interval arithmetic overflows although converted seconds sum is finite');
await overflow.core.seek('100%');
assert.equal(overflow.core.getCurrentTime(), Infinity);
assert.ok(Number.isNaN(overflow.core.getProgress()), 'real upstream progress is corrupted');
assert.deepEqual(overflow.events.error, []);
process.stdout.write(`v${version} infinite duration/seek reproduced\n`);
} finally {
await overflow.core.stop();
assert.equal(timers.size, 0);
}
}
// The production loader must reject all five pinned numerical attacks
// before their data can be handed to Core, including rounding-order bugs.
let coreHandoffs = 0;
for (const id of [
'time-v2-output-nonprogress',
'time-v1-ms-sum-overflow', 'time-v3-ms-sum-overflow',
'time-v1-ms-rounding-over', 'time-v3-ms-rounding-over',
]) {
assert.equal(getSecurityCase(id).expected.jsError, 'time');
const stream = streamedFixture(securityFixtureBuffer(id));
const handoff = async () => {
const data = await loadRecording('/security-fixture.cast', { fetchImpl: stream.fetchImpl });
coreHandoffs++;
return createCore(data);
};
await assert.rejects(handoff(), (error) => error instanceof RecordingLoadError && error.code === 'time');
assert.equal(coreHandoffs, 0, 'rejected data never reaches the actual Core constructor');
assert.equal(stream.state.cancels, 1);
assert.equal(stream.state.signal.aborted, true);
assert.equal(timers.size, 0, 'rejected loader leaves no captured timeouts');
process.stdout.write(`${id} rejected before Core handoff\n`);
}
// Accepted exact-boundary fixtures survive actual parser preparation,
// duration/progress arithmetic, end/start seeking and output batching.
for (const id of [
'timeline-v1-at', 'timeline-v2-at', 'timeline-v3-at',
'interval-timeline-v1-at', 'interval-timeline-v3-at',
]) {
const bytes = securityFixtureBuffer(id);
const data = await loadRecording('/security-fixture.cast', { fetchImpl: streamedFixture(bytes).fetchImpl });
assert.deepEqual(data, parseFixture(id), 'near-bound timestamps are preserved without clamping');
const expectedOutput = id.startsWith('interval-') ? 'xend' : 'x';
const inspected = await inspectPlayer(data);
assert.equal(inspected.duration, 2147483.647);
assert.equal(inspected.output, expectedOutput);
assert.equal(timers.size, 0);
const playback = createCore(data);
try {
await playback.core.init();
await playback.core.play();
for (let n = 0; n < (id.startsWith('interval-') ? 2 : 1); n++) {
const timer = takeTimer();
assert.ok(Number.isFinite(timer.delay) && timer.delay >= 0 && timer.delay <= 2147483647);
timer.callback();
await Promise.resolve();
}
assert.equal(playback.events.output.flat().join(''), expectedOutput, 'accepted boundary output always advances');
assert.equal(playback.events.ended.length, 1);
assert.ok(Number.isFinite(playback.core.getDuration()));
assert.ok(Number.isFinite(playback.core.getCurrentTime()));
assert.ok(Number.isFinite(playback.core.getProgress()));
assert.deepEqual(playback.events.error, []);
assert.equal(timers.size, 0, 'accepted output does not reschedule a consumed event');
process.stdout.write(`${id} actual Core init/seek/playback is finite and advances\n`);
} finally { await playback.core.stop(); }
}
} finally {
globalThis.setTimeout = realSetTimeout;
globalThis.clearTimeout = realClearTimeout;
}
}
test('actual 3.17 Core timestamp regressions are bounded and blocked before handoff', () => {
const script = `
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { loadRecording, RecordingLoadError } from ${JSON.stringify(new URL('../../src/recording-loader.js', import.meta.url).href)};
import { getSecurityCase, securityFixtureBuffer } from ${JSON.stringify(new URL('../fixtures/security/generate.mjs', import.meta.url).href)};
${playerCore.toString()}
${streamedFixture.toString()}
${inspectPlayer.toString()}
await (${timestampCoreRegression.toString()})();
process.stdout.write('bounded actual-Core timestamp witnesses passed\\n');
`;
const child = spawnSync(process.execPath, ['--input-type=module', '--eval', script], {
cwd: new URL('../../', import.meta.url), timeout: 10000, maxBuffer: 64 * 1024,
encoding: 'utf8', env: { ...process.env, NODE_OPTIONS: '' },
});
const diagnostics = `stdout:\n${child.stdout}\nstderr:\n${child.stderr}`;
assert.equal(child.error, undefined, `the bounded Core witness must finish: ${child.error?.message}\n${diagnostics}`);
assert.equal(child.signal, null, `the bounded Core witness was killed\n${diagnostics}`);
assert.equal(child.status, 0, diagnostics);
assert.match(child.stdout, /bounded actual-Core timestamp witnesses passed/);
});