fix(replay): share one seeded generator and present builtins with real identity (#539)

This commit is contained in:
morluto
2026-10-05 16:47:20 +08:00
committed by GitHub
parent 333d118c0f
commit 5b51fa01e2
5 changed files with 176 additions and 19 deletions
+7 -7
View File
@@ -2,6 +2,10 @@ import canonicalize from "canonicalize";
import { createHash } from "node:crypto";
import type { JsonValue } from "../domain/jsonValue.js";
import {
createSeededRandomUint,
NON_DEGENERATE_XORSHIFT32_SEED,
} from "../replay/seededRandom.js";
import type {
ControlledReplayInput,
ReplayExecutionResult,
@@ -252,13 +256,9 @@ const replayCases = (
arguments: item.arguments,
}));
if (input.generator === undefined) return uniqueCases(explicit);
let state = input.generator.seed || 0x9e37_79b9;
const next = (): number => {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return state >>> 0;
};
const next = createSeededRandomUint(
input.generator.seed || NON_DEGENERATE_XORSHIFT32_SEED,
);
const corpus = boundaryCorpus(input.generator.preset);
const generated: {
readonly case_id: string;
+19 -12
View File
@@ -13,6 +13,7 @@ import type {
WorkerRequest,
WorkerSide,
} from "./JavaScriptReplayWorkerTypes.js";
import { createSeededRandom } from "./seededRandom.js";
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === "object" && value !== null && !Array.isArray(value);
@@ -272,13 +273,7 @@ const loadEntry = async (
};
const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
let state = (request.determinism.randomSeed + caseIndex) >>> 0;
const random = (): number => {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return (state >>> 0) / 0x1_0000_0000;
};
const random = createSeededRandom(request.determinism.randomSeed + caseIndex);
const epoch = Date.parse(request.determinism.clockIso);
class ReplayDate extends Date {
constructor(...arguments_: unknown[]) {
@@ -293,13 +288,25 @@ const deterministicContext = (request: WorkerRequest, caseIndex: number) => {
return epoch;
}
}
const replayMath: Math = Object.create(Math);
Object.defineProperty(replayMath, "random", { value: random });
// Observable identity must match the real builtin, or a bundle that feature-
// detects (`Date.name`, `Date.length`, `Object.getPrototypeOf(Math)`) takes a
// different branch in replay than in production.
Object.defineProperties(ReplayDate, {
name: { value: "Date", configurable: true },
length: { value: Date.length, configurable: true },
});
const replayDate = new Proxy(ReplayDate, {
apply: () => new ReplayDate().toString(),
});
// Intercept only `random`; everything else, including the prototype chain and
// property descriptors, is forwarded to the real Math.
const replayMath = new Proxy(Math, {
get: (target, property, receiver) =>
property === "random" ? random : Reflect.get(target, property, receiver),
});
return createContext(
{
Date: new Proxy(ReplayDate, {
apply: () => new ReplayDate().toString(),
}),
Date: replayDate,
Math: replayMath,
},
{
+43
View File
@@ -0,0 +1,43 @@
import { describe, expect, it } from "vitest";
import {
createSeededRandom,
createSeededRandomUint,
normalizeXorshift32Seed,
NON_DEGENERATE_XORSHIFT32_SEED,
} from "./seededRandom.js";
describe("seeded replay randomness", () => {
it("does not collapse to a constant when seeded with zero", () => {
const random = createSeededRandom(0);
const values = [random(), random(), random()];
expect(new Set(values).size).toBe(3);
expect(values.every((value) => value === 0)).toBe(false);
expect(values.every((value) => value >= 0 && value < 1)).toBe(true);
});
it("substitutes a fixed non-zero state for a zero seed", () => {
expect(normalizeXorshift32Seed(0)).toBe(NON_DEGENERATE_XORSHIFT32_SEED);
expect(normalizeXorshift32Seed(7)).toBe(7);
// Deterministic: the same seed must always give the same stream.
expect(Array.from({ length: 3 }, createSeededRandom(0))).toEqual(
Array.from({ length: 3 }, createSeededRandom(0)),
);
});
it("produces the same stream regardless of which generator is used", () => {
const floats = createSeededRandom(11);
const uints = createSeededRandomUint(11);
expect([floats(), floats(), floats()]).toEqual([
uints() / 0x1_0000_0000,
uints() / 0x1_0000_0000,
uints() / 0x1_0000_0000,
]);
});
it("keeps distinct seeds on distinct streams", () => {
const first = Array.from({ length: 4 }, createSeededRandom(1));
const second = Array.from({ length: 4 }, createSeededRandom(2));
expect(first).not.toEqual(second);
});
});
+53
View File
@@ -0,0 +1,53 @@
/**
* Deterministic pseudo-random generation for controlled replay.
*
* The generator lives here so the replay worker and the case planner cannot
* drift: they previously each inlined the same xorshift32 loop, and a fix to
* one (such as the zero-seed collapse below) would silently not apply to the
* other.
*/
/** One xorshift32 step. Returns the next unsigned 32-bit state. */
export const nextXorshift32 = (state: number): number => {
let next = state >>> 0;
next ^= next << 13;
next ^= next >>> 17;
next ^= next << 5;
return next >>> 0;
};
/**
* xorshift32 has a fixed point at zero: seeding it with 0 yields 0 forever, so
* every "random" value collapses to the same constant and two runs look
* identical for the wrong reason. Substitute a fixed non-zero state instead.
*/
export const NON_DEGENERATE_XORSHIFT32_SEED = 0x9e37_79b9;
export const normalizeXorshift32Seed = (seed: number): number => {
const state = seed >>> 0;
return state === 0 ? NON_DEGENERATE_XORSHIFT32_SEED : state;
};
/** A seeded generator returning floats in [0, 1). */
export type SeededRandom = () => number;
/** A seeded generator returning unsigned 32-bit integers. */
export type SeededRandomUint = () => number;
/** Build a float generator in [0, 1) whose values depend only on `seed`. */
export const createSeededRandom = (seed: number): SeededRandom => {
let state = normalizeXorshift32Seed(seed);
return () => {
state = nextXorshift32(state);
return state / 0x1_0000_0000;
};
};
/** Build an unsigned 32-bit generator whose values depend only on `seed`. */
export const createSeededRandomUint = (seed: number): SeededRandomUint => {
let state = normalizeXorshift32Seed(seed);
return () => {
state = nextXorshift32(state);
return state;
};
};