Reduce replay copying and keep live controls limited to choice edits

This commit is contained in:
coyotte508 2026-11-10 21:37:11 +00:00
commit 8bc8910c24
9 changed files with 161 additions and 5 deletions

View file

@ -1611,7 +1611,11 @@ function applyMove(state, m, p, historical = false) {
(currentPlayers(state).includes(p) || canMoveOutOfTurn(state, m, p)),
"It is not your turn",
);
const s = clone(state),
// Historical transitions only receive private states constructed by replay
// (or this logSlice call). Entries are append-only and each incoming move is
// cloned below. Copy the array, not its entire growing prefix: no public
// input history is shared, and predecessor/checkpoint arrays remain stable.
const s = historical ? cloneReplayPosition(state) : clone(state),
t = playerTask(s, p),
a = s.players[p],
extra = { phase: t.kind, beforeCoins: s.players[p].coins };
@ -2260,6 +2264,10 @@ function stripSecretForLog(state, p, previous, checkpoint) {
export function logLength(s) {
return s.history.length + 1;
}
function cloneReplayPosition(state) {
const { history, ...position } = state;
return { ...clone(position), history: history.slice() };
}
export function replay(s, options = {}) {
const to =
typeof options === "number" ? options : (options.to ?? logLength(s));
@ -2302,8 +2310,17 @@ export function logSlice(
frames.push(stripSecret(s, player));
return { frames };
}
let position = replay(s, Math.max(1, start + 1));
let previous;
// Reconstruct the predecessor as part of the same prefix pass. Otherwise
// the first frame's canUndo check replays that entire prefix a second time.
let previous = start > 0 ? replay(s, start) : undefined;
let position = previous
? applyMove(
previous,
s.history[start - 1].move,
s.history[start - 1].p,
true,
)
: replay(s, 1);
let checkpoint;
for (let i = Math.max(0, start); i <= Math.min(end, logLength(s) - 1); i++) {
// Keep just the start of this role to accelerate production-edit checks.

View file

@ -1,6 +1,6 @@
{
"name": "@boardgamers/puerto-rico",
"version": "0.3.16",
"version": "0.3.17",
"private": true,
"type": "module",
"description": "Puerto Rico 1897 Special Edition for Boardgamers Space",

View file

@ -0,0 +1,39 @@
// Deterministic, non-ending fixture; no server/sandbox queue time is included.
import { performance } from "node:perf_hooks";
import * as E from "../engine/index.js";
let s = E.init(3, [], {}, "bounded-journal");
for (let i = 0; i < 450; i++) {
const moves = E.legal(s);
const m =
moves.find((m) => m.type === "pass") ??
moves.find(
(m) =>
m.type === "role" &&
["settler", "craftsman", "trader", "builder"].includes(m.id),
) ??
moves[0];
s = E.move(s, m, E.currentPlayer(s));
}
const player = s.history[448].p;
console.log(
`Node ${process.version}; ${s.history.length} moves / ${E.logLength(s)} frames; seat ${player}`,
);
const cases = {
replay: () => E.replay(s),
lateTwoFrames: () => E.logSlice(s, { player, start: 449, end: 450 }),
latestFrame: () => E.logSlice(s, { player, start: 450 }),
setPlayerMetaData: () =>
E.setPlayerMetaData(s, player, { name: "Benchmark" }),
};
for (const [name, run] of Object.entries(cases)) {
run();
const samples = Array.from({ length: 5 }, () => {
const start = performance.now();
run();
return performance.now() - start;
}).sort((a, b) => a - b);
console.log(
`${name}: median ${samples[2].toFixed(2)} ms (range ${samples[0].toFixed(2)}–${samples[4].toFixed(2)})`,
);
}

View file

@ -1603,6 +1603,23 @@ try {
type: "poachAll",
placements: [],
});
// Legacy engine undo remains compatible, but live hosted games expose
// only choice editing, even where a role selection could be undone.
const chosenRole = E.move(
E.init(3, [], {}, "browser-no-live-undo"),
{ type: "role", id: "builder" },
0,
);
assert.equal(E.canUndo(chosenRole, 0), true);
await page.evaluate(
(s) => {
host.emit("player", { index: 0 });
host.emit("state", s);
},
E.stripSecret(chosenRole, 0),
);
assert.equal(await page.locator(".dock-undo").count(), 0);
assert.equal(await page.locator('[data-local="undo"]').count(), 0);
let undoPlacement = E.init(3, [], {}, "browser-placement-undo");
undoPlacement = E.move(undoPlacement, { type: "role", id: "recruiter" }, 0);
undoPlacement = E.move(undoPlacement, { type: "recruitBonus" }, 0);

View file

@ -36,6 +36,16 @@ test("early production can be edited without retracting another producer's choic
assert.deepEqual(edited.players[1], start.players[1]);
assert.equal(edited.history.length, s.history.length - 1);
assert.deepEqual(E.replay(edited), edited);
const original = structuredClone(s);
for (let i = 0; i < 20; i++) {
const reopened = E.move(s, { type: "editProduction" }, 1);
assert.equal(reopened.history.length, original.history.length - 1);
assert.deepEqual(reopened.players[0], original.players[0]);
s = produce(reopened, 1);
assert.equal(s.history.length, original.history.length);
assert.deepEqual(s.players, original.players);
assert.deepEqual(E.replay(s), s);
}
});
test("early Craftsman bonus is editable and re-confirmation adds no time", () => {
let s = produce(fixture(), 2);

View file

@ -40,7 +40,10 @@ test("Smuggler selection can be undone before handing control away, without grow
assert.equal(E.canUndo(s, 0), true);
assert.equal(E.canUndo(s, 1), false);
for (let i = 0; i < 10; i++) {
const active = E.currentPlayers(s);
s = E.move(s, { type: "undo" }, 0);
assert.deepEqual(E.currentPlayers(s), active);
assert.equal(s.history.length, 0);
assert.deepEqual(s, start);
s = E.move(s, { type: "role", id: "smuggler" }, 0);
assert.equal(s.history.length, 1);

View file

@ -141,6 +141,19 @@ test("long pass sequences keep the journal bounded without losing deterministic
frames[450],
]);
assert.deepEqual(E.logSlice(s, { start: 450 }).frames, [E.stripSecret(s)]);
// A late slice must include an exact first frame (including undo), not just
// exact later frames. Seat 2 exercises the first-frame predecessor path.
for (const player of [undefined, 0, 1, 2]) {
for (const start of [448, 449]) {
const late = E.logSlice(s, { player, start, end: 450 }).frames;
assert.deepEqual(
late,
Array.from({ length: 451 - start }, (_, offset) =>
E.stripSecret(E.replay(s, { to: start + offset + 1 }), player),
),
);
}
}
assert.deepEqual(s, before);
});

View file

@ -0,0 +1,55 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as E from "../engine/index.js";
function freeze(value) {
if (value && typeof value === "object" && !Object.isFrozen(value)) {
Object.values(value).forEach(freeze);
Object.freeze(value);
}
return value;
}
test("replay and log frames own their data and preserve live metadata at every boundary", () => {
let s = E.init(3, [], {}, "replay-ownership");
for (let i = 0; i < 40; i++) s = E.moveAI(s);
s = E.setPlayerMetaData(s, 0, { name: "Renamed" });
s = E.dropPlayer(s, 1);
s = E.setPlayerSettings(s, 2, { autoForcedActions: true, autoStore: true });
const before = structuredClone(s);
freeze(s);
const n = E.logLength(s);
const replayed = E.replay(s);
assert.deepEqual(replayed, s);
const frames = E.logSlice(s, { player: 0, start: n - 3, end: n + 5 }).frames;
for (let i = 0; i < 3; i++) {
assert.deepEqual(frames[i], E.stripSecret(E.replay(s, n - 2 + i), 0));
assert.equal(frames[i].players[0].name, "Renamed");
assert.equal(frames[i].players[1].bot, true);
assert.deepEqual(frames[i].players[2].settings, s.players[2].settings);
for (const key of ["history", "config", "random", "bag", "discard"])
assert.equal(frames[i][key], undefined);
}
const untouchedFrame = structuredClone(frames[1]);
frames[0].players[0].name = "Mutated view";
frames[0].players[2].settings.autoStore = false;
frames[0].events.splice(0);
assert.deepEqual(frames[1], untouchedFrame);
replayed.history[0].move.type = "mutated";
replayed.history.push({ p: 0, move: { type: "bad" } });
replayed.players[2].settings.autoStore = false;
replayed.config.options.mutated = true;
assert.deepEqual(s, before);
assert.deepEqual(E.replay(s), before);
// Ordinary public moves must not reuse the private replay optimization.
const initial = freeze(E.init(3, [], {}, "public-move-ownership"));
const chosen = freeze(E.move(initial, { type: "role", id: "builder" }, 0));
const after = E.move(chosen, { type: "pass" }, 0);
after.history[0].move.id = "mutated";
assert.equal(chosen.history[0].move.id, "builder");
const undone = E.move(chosen, { type: "undo" }, 0);
assert.deepEqual(E.currentPlayers(undone), E.currentPlayers(chosen));
undone.players[0].name = "Independent undo";
assert.notEqual(initial.players[0].name, undone.players[0].name);
});

View file

@ -988,8 +988,10 @@ export function mountGame(
"quiet dock-order",
)
: "";
// Live hosted games only reopen eligible independent choices. Keep the
// legacy undo affordance for local play and analysis, not live role rewind.
const undo =
state.canUndo && enabled
(localControls || preferences.analysis) && state.canUndo && enabled
? moveButton({ type: "undo" }, t("undo"), "undo", "quiet dock-undo")
: "";
const edit =