Free to Learn · Time-travel debuggerLesson 09 of 13

09 · Record and replay

Build a recorder that saves numbers a server returns to Lob, an artillery game, then reuses them to find the first changed instruction, one numbered machine operation.

game_init(5, 1) starts Lob with game seed 5 and mode 1, the defence switch that makes the game ask a server for wind. Run the same function calls, requests to run named functions, twice. You might expect identical memory, the game's stored bytes. Memory already differs after the first call: the server's own seed 42, a repeatable starting number, gives wind 1; seed 43 gives -2.

Start

lab.mjs is the course checker. Node runs it here to test lesson 08 code in your project folder:

Terminal command
node lab.mjs check project 08
Select code to copy. Scroll horizontally if needed.

If it fails, create a separate project with the supplied machine: node examples/start-chapter.mjs project9 supplied. Use project9 below.

Choose a recorder start. A route command refuses to replace edited code.

RouteCommandWhat you receive
Type in six marked regionsnode examples/start-recorder.mjs project writestarter/recorder-build.mjs plus supporting code
Inspect working regionsnode examples/start-recorder.mjs project suppliedexamples/recorder-checkpoint.mjs
Start from the APIKeep the stub from node lab.mjs startNo worked regions

Both route commands also create unfinished project/trim.mjs. If you use AI, share one marked region at a time, inspect the answer, and record the help used.

Run the matching recorder baseline:

Terminal command
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 09 --help-used "chapter write starter; six regions unfinished"
# Supplied route:
node lab.mjs check project 09 --help-used "supplied recorder checkpoint; initial baseline"
Select code to copy. Scroll horizontally if needed.

The type-in route fails with not written yet; the supplied route passes. Both establish a baseline. Check receipts record your starting route and --help-used note.

Keep each // region: NAME marker. Replace only the text inside its matching pair. For recovery, create a separate supplied project and compare files instead of overwriting your attempt.

What makes a run repeat

Make two recordings of the same calls with two worlds, the outside functions that answer the game. makeWorld(seed) creates those functions from a server seed.

Kept equalChangedFirst result
Game seed 5, mode 1, and all 759 callsWorld seed 42 versus 43Memory differs after game_init

game_init asks server_round(1) for wind. The worlds answer differently. A recording therefore keeps the calls and every imported answer, the value an outside function returned, in order.

Record

record(program, imports, calls) runs the calls on a new machine. Give the machine imports that call the real ones and push each answer onto a list as it passes: { name, args, result }. Keep each call's result, and after each call the memory hash, hashMemory(machine.state.memory) from public/hash.mjs. The whole recording is plain JSON, so it can be saved and read back.

Note every answer as it passes

In project/recorder.mjs, replace the record region:

Record calls, answers, results and hashesexamples/recorder-checkpoint.mjs · record

Replace the record region.

export function record(program, imports, calls) {
  const answers = [];
  const noting = {};
  for (const { name } of program.imports) {
    noting[name] = (...args) => {
      const result = imports[name](...args);
      answers.push({ name, args, result });
      return result;
    };
  }
  const machine = new Machine(program, noting);
  const results = [];
  const hashes = [];
  for (const call of calls) {
    const result = machine.invoke(call.name, call.args);
    results.push(result === undefined ? null : result);
    hashes.push(hashMemory(machine.state.memory));
  }
  return {
    format: 'ttd2-recording-1',
    program: program.name,
    sha256: program.sha256,
    calls: calls.map((call) => ({ name: call.name, args: [...call.args] })),
    results,
    answers,
    hashes,
  };
}
Emphasized lines: 4, 5, 6, 7, 8, 9. Select code to copy. Scroll horizontally if needed.

The machine never sees the real imports. It gets noting, one function per import the listing names, and each of those passes the question to the real import, notes the answer and hands it back unchanged. The world is asked exactly once per question, which check 09.record counts: asking it a second time to note the answer would move the server on and record an answer the game never got. args is the rest parameter, a fresh plain array, so the recording can keep it.

The machine is new, so the run starts from the listing's memory, as every replay will. invoke returns undefined for a function with no result, and JSON has no undefined, so the recording stores null. Each hash is taken after its call returns. The calls are copied, so a caller who later edits its own list doesn't change the recording.

Lob's two-shot recording above holds 759 calls and 277 answers. Question 09a: which of the four imports gave most of those 277 answers? Commit before you make the recording:

Observed output
node lab.mjs predict project 09a YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

The memory hash after every call isn't needed to replay. It costs 64 hex characters per call. In return, a replay can check at every call that its memory still matches the recording, and the last section of this lesson can find a divergence without replaying the original. rr offers a similar check as an option, comparing checksums of a program's memory as it replays.

Check 09.record compares your recording with an independent run that counts every answer, and 09.recording-json round-trips it through JSON.stringify.

Once record works, make the two recordings of the first section, then look inside them:

Observed output
node lab.mjs record project --world 42 --out project/run42.json
node lab.mjs record project --world 43 --out project/run43.json
node examples/show-recording.mjs project/run42.json project/run43.json
Select code to copy. Scroll horizontally if needed.

examples/show-recording.mjs prints the size of each recording, its first call and first answer, and the first call after which the two memory hashes differ:

Two worlds, the same callsexamples/recording-output.txt
project/run42.json: ttd2-recording-1, program lob
  759 calls, 277 answers, 759 hashes
  call 0: game_init(5, 1) returned null; memory hash after it 674f60c95fd31eab...
  answer 0: server_round(1) returned 1
project/run43.json: ttd2-recording-1, program lob
  759 calls, 277 answers, 759 hashes
  call 0: game_init(5, 1) returned null; memory hash after it 405cce2ea030c094...
  answer 0: server_round(1) returned -2
First call whose memory hashes differ: call 0, game_init(5, 1)
Select code to copy. Scroll horizontally if needed.

The calls are the same and the first answer is not, so the hashes part after call 0. That is the claim of the first section, read from your own recordings.

Replay

replay(program, recording) runs the recording's calls on a new machine whose imports answer from the recording, in order, without any world. Keep a position in the answers list. When the game calls an import, the next recorded answer must be for the same import with the same arguments. Return its result and move on.

If the next answer does not match, replay has left its recording. Throw an error with this divergence value:

FieldMeaning
tickInstructions finished before the import's call instruction
callIndex in recording.calls
reasonPlain account of the mismatch

The call instruction's event would report tick + 1. With check: true, a changed call result or ending memory hash is also a divergence.

Answer from the recording, or refuse

Replace the recorded-imports region. It builds the imports a replay gives its machine:

Imports that answer from a recordingexamples/recorder-checkpoint.mjs · recorded-imports

Replace the recorded-imports region.

export function recordedImports(program, recording, machineOf, start = 0) {
  let next = start;
  const imports = {};
  for (const { name } of program.imports) {
    imports[name] = (...args) => {
      const answer = recording.answers[next];
      const state = machineOf().state;
      const where = { tick: state.tick, call: state.calls - 1 };
      const asked = `${name}(${args.join(', ')})`;
      if (!answer)
        throw new ReplayDivergence({
          ...where,
          reason: `the program asked ${asked} after the recording's last answer`,
        });
      if (
        answer.name !== name ||
        answer.args.length !== args.length ||
        answer.args.some((value, i) => !Object.is(value, args[i]))
      )
        throw new ReplayDivergence({
          ...where,
          reason: `the program asked ${asked}, the recording holds ${answer.name}(${answer.args.join(', ')})`,
        });
      next++;
      return answer.result;
    };
  }
  return { imports, position: () => next };
}
Select code to copy. Scroll horizontally if needed.

next is the position in the answer list. It belongs to this replay, not the game, so restoring game state must not move it.

NameRole
nextIndex of the next recorded answer
position()Reports that index
startBegins answering partway through the recording

The imports have to exist before the machine does, because the Machine's constructor takes them. So they receive machineOf, a function that returns the machine once it has been made, and read the machine's state only when the game asks. An import runs in the middle of the call instruction's step. Lesson 08's Machine adds one to state.tick only after an instruction's work is done, so at that moment state.tick is the number of instructions finished before the call instruction, the tick the contract asks for. A machine that counts the tick before running the instruction makes every such tick one too high, and check 09.replay-questions says so. begin has already counted the call into the game, so its index is state.calls - 1.

Object.is compares each argument exactly, so a sin asked of an angle one part in 2^40 away from the recorded one is still a different question. Check 09.replay-questions makes that edit, among others.

Run the calls and compare

Replace the replay region:

Replay without a worldexamples/recorder-checkpoint.mjs · replay

Replace the replay region.

export function replay(program, recording, { check = true } = {}) {
  let machine;
  const answered = recordedImports(program, recording, () => machine);
  machine = new Machine(program, answered.imports);
  const results = [];
  const hashes = [];
  recording.calls.forEach((call, k) => {
    const value = machine.invoke(call.name, call.args);
    const result = value === undefined ? null : value;
    const hash = hashMemory(machine.state.memory);
    results.push(result);
    hashes.push(hash);
    const where = { tick: machine.state.tick, call: k };
    if (check && !Object.is(result, recording.results[k]))
      throw new ReplayDivergence({
        ...where,
        reason: `call ${k} returned ${result}, the recording says ${recording.results[k]}`,
      });
    if (check && hash !== recording.hashes[k])
      throw new ReplayDivergence({
        ...where,
        reason: `memory after call ${k} differs from the recording`,
      });
  });
  return { machine, results, hashes };
}
Select code to copy. Scroll horizontally if needed.

machine is declared before the imports and assigned after, so the closure given to recordedImports can return it.

DivergenceReported tick
No recorded answer matchesThe import's call instruction
Result or ending hash differsThe tick when the outer call returned

With { check: false }, replay still refuses an unanswerable question but continues past a wrong result or hash. It never changes recording, since lesson 10 reuses one recording many times.

Tour learnerRecorder in lab.mjs now. Before it imports your recorder.mjs, it wraps Machine.prototype.step from your machine.mjs with a counter, and the checks do the same. That counter is how every instruction count in this lesson is measured, so your recorder must make its machines from the Machine it imports from ./machine.mjs and run every instruction through step. invoke does, because it is a loop over step.

Try it on a recording with one answer's argument changed. Answers and calls are numbered from 0. In the recording above, the first cos answer is answer 1. Change its argument from 0.8028514385223389 to 0.8128514385223389 and replay the copy:

Observed output
node lab.mjs tamper project/run42.json --answer 1 --arg 0.01 --out project/edited.json
node lab.mjs replay project project/edited.json
Select code to copy. Scroll horizontally if needed.
A replay refuses a question it can't answerexamples/replay-output.txt
Answer 1 (cos) now says it was asked cos(0.8128514385223389), not cos(0.8028514385223389).
Wrote project/edited.json. Its hashes are still the original's.
The replay left its recording at tick 88494, call 19: the program asked cos(0.8028514385223389), the recording holds cos(0.8128514385223389)
Select code to copy. Scroll horizontally if needed.

The replay stops at call 19, the key press that fires the first shot, at tick 88,494. The game asks for the cosine of the barrel's angle, and the recording holds the cosine of another angle. node lab.mjs replay project project/run42.json replays the untouched recording to its end.

Tour tamperCmd in lab.mjs too. It changes one answer or one call in a copy and writes it out with the original's hashes untouched, which is why the replay above could compare every call with what the untampered run did.

Check 09.replay replays recordings of Lob and Lob II with no world at all. 09.replay-questions edits recordings and expects your error at the right tick and call, and 09.replay-check changes a recorded result or hash and expects a divergence only with check: true.

Finding where a tampered replay first differs

tampered is a copy of a recording with one answer changed, and its hashes are still the original's. After which tick does its replay first have different memory from the original's?

Observed output
node lab.mjs tamper project/run42.json --answer 12 --add 0.25 --out project/tampered.json
Select code to copy. Scroll horizontally if needed.

Answer 12 is the tenth server_wind answer, the wind during one game frame of the first shot's flight. Changing it changes that game frame's acceleration, and memory differs from the moment the shell's new position is stored.

The only test you have is whole-state equality, where two memories are the same if their hashes are the same. You can only compare hashes at moments you choose, not ask "which instruction made this hash different?" That is the setting for bisection. Keep two moments, one where the memories are known equal and one where they are known different, test the moment halfway between, and keep the half where they still change from equal to different.

Running both replays from tick 0 for every halfway test would cost two whole runs per test. Recorded hashes give the search a shorter route.

StageWorkEvidence kept
Find call kReplay the changed recording once and compare each ending hash with the originalA copied state from the start of the first changed call
Search call kStart two machines from that state, using each answer listThe first instruction whose memory differs

Inside call k, a bisection test runs each machine to a chosen halfway tick and compares hashes. Each result keeps the half that still crosses from equal to different. A side-by-side search instead steps both machines together and compares bytes after every write. It costs twice the changed instruction's offset, but still works if memory later becomes equal again.

Step 1 on the tampered recording: calls 0 to 28 end with the same memory hash as the original's, call 29 is the first that differs, and the scan stops there without replaying the rest of the 759 calls. Step 2 searches only call 29, 796 instructions from tick 96,469, where memory is still equal, to tick 97,265, where it differs.

For the tampered recording above, step 1 stops at call 29, a game frame of 796 instructions starting at tick 96,469, and keeps the state saved at that tick for step 2.

Inside one call, stepping side by side is the cheaper of the two, and either meets the checks. Bisection wins where only whole states can be compared at chosen moments. Step 1 compares whole states too, since one side exists only as recorded hashes, but every call's hash is already on hand, so it scans calls in order and stops at the first mismatch; so too is any test you can run only at chosen moments, such as comparing two debugging sessions that are too slow to step together. Bisection also assumes a difference, once made, lasts to the end of the call, and the checks' tampers do.

Question 09b: bisection over the 796 instructions of call 29 starts knowing memory is equal after 0 of them and different after all 796. Each test halves the interval. How many tests does it take, at most, until the two ends are one instruction apart? Commit:

Observed output
node lab.mjs predict project 09b YOUR_ANSWER
Select code to copy. Scroll horizontally if needed.

Find the call from the recorded hashes

Step 1 goes in the find-call region:

Replay once, saving each call's starting stateexamples/recorder-checkpoint.mjs · find-call

Replace the find-call region.

export function firstDivergence(program, original, tampered) {
  let machine;
  const answered = recordedImports(program, tampered, () => machine);
  machine = new Machine(program, answered.imports);
  for (let k = 0; k < tampered.calls.length; k++) {
    const start = globalThis.structuredClone(machine.state);
    const answerAt = answered.position();
    let left = false;
    try {
      machine.invoke(tampered.calls[k].name, tampered.calls[k].args);
    } catch (error) {
      if (!(error instanceof ReplayDivergence)) throw error;
      left = true;
    }
    const same =
      !left && hashMemory(machine.state.memory) === original.hashes[k];
    if (same) continue;
    return bisectCall(program, original, tampered, k, start, answerAt);
  }
  return null;
}
Emphasized lines: 6, 7. Select code to copy. Scroll horizontally if needed.

Only the tampered recording is replayed. The original takes part through its hashes alone, which is why this loop costs one replay up to the call where the two part, not two. Copying the state before every call costs memory and time, but it runs no instructions, so the counter doesn't see it. answerAt is the answer position at the start of the call: the search inside the call has to answer the same questions from the same place in both recordings.

A tampered replay can also ask a question its recording doesn't hold, a cos of an angle the tamper changed, for example. That counts as a call that ends different. A key the game ignores leaves the hash equal, so the loop goes on, and a tamper that never changes memory reaches the end and returns null.

Run one call from a saved state

Replace the run-from region:

Restore, begin and stop after a limitexamples/recorder-checkpoint.mjs · run-from

Replace the run-from region.

function runFrom(program, recording, k, start, answerAt, limit) {
  let machine;
  const answered = recordedImports(program, recording, () => machine, answerAt);
  machine = new Machine(program, answered.imports);
  machine.state = globalThis.structuredClone(start);
  machine.begin(recording.calls[k].name, recording.calls[k].args);
  let ran = 0;
  try {
    while (machine.running && ran < limit) {
      machine.step();
      ran++;
    }
  } catch (error) {
    if (!(error instanceof ReplayDivergence)) throw error;
    return { machine, ran, left: true };
  }
  return { machine, ran, left: false };
}
Emphasized lines: 5. Select code to copy. Scroll horizontally if needed.

Because the machine keeps everything in machine.state, as lesson 08 required, assigning a copy puts a new machine at the exact start of call k. The copy matters again here, because each test runs from the same saved state and must not change it for the next one. begin starts the call and step runs at most limit instructions of it. ran counts instructions that finished, so a question the recording can't answer stops the run with left set and ran short of the limit.

Bisect inside the call

Replace the bisect region:

Keep one end equal and the other differentexamples/recorder-checkpoint.mjs · bisect

Replace the bisect region.

function bisectCall(program, original, tampered, k, start, answerAt) {
  const run = (recording, limit) =>
    runFrom(program, recording, k, start, answerAt, limit);
  const a = run(original, Infinity);
  const b = run(tampered, Infinity);
  const differs = (t) => {
    const x = run(original, t);
    const y = run(tampered, t);
    if (y.left && y.ran < t) return true;
    return (
      hashMemory(x.machine.state.memory) !== hashMemory(y.machine.state.memory)
    );
  };
  let lo = 0; // memory is equal after lo instructions of call k
  let hi = Math.max(a.ran, b.left ? b.ran + 1 : b.ran); // and differs after hi
  while (hi - lo > 1) {
    const mid = (lo + hi) >> 1;
    if (differs(mid)) hi = mid;
    else lo = mid;
  }
  return start.tick + hi;
}
Emphasized lines: 14, 15, 16, 17, 18, 19. Select code to copy. Scroll horizontally if needed.

The two first runs measure each version of the call. Memory is equal after 0 instructions, because both start from the same state, and different once both versions have finished, because that is how step 1 chose this call. A tampered run that left its recording counts as different from the instruction that asked, which is why hi is then one more than the instructions it finished. differs(t) runs both versions t instructions from the saved state, and each loop keeps the half whose ends are still equal and different. When the ends are one apart, hi instructions into the call is the first moment memory differs, and the instruction that made it so has the tick start.tick + hi, the tick its own event reports.

Run the search on the tamper above:

Observed output
node lab.mjs diverge project project/run42.json project/tampered.json
Select code to copy. Scroll horizontally if needed.
The search and what it ranexamples/diverge-output.txt
Memory first differs after tick 96568.
Your firstDivergence ran 101431 instructions.
Select code to copy. Scroll horizontally if needed.
Bisection inside call 29, one row per test: t = 398, 199 and 99 differ, then t = 49, 74, 86, 92, 95, 97 and 98 are equal, so the interval in question halves each time until its ends are 98 and 99. Memory first differs 99 instructions into the call, at tick 96,469 + 99 = 96,568.

Each test halves the interval still in question. Your firstDivergence returns 96,568, or null when the two replays never differ, for example when an answer is "changed" to the value it already had.

The lab prints how many instructions your search ran. The worked solution finds the call from the hashes and then bisects inside it, and runs 101,431 for this case: 97,265 to replay the tampered recording up to the end of call 29, and the rest to run both versions of call 29 and bisect inside it. Stepping side by side inside the call runs fewer, because it costs only twice the distance to the divergence. Bisecting from tick 0 instead, replaying both recordings from the start for every test, takes about 20 tests over the run's 652,927 instructions, and each test replays both recordings up to the tick it tests.

The checks separate search from recording:

CheckEvidence
09.divergenceKnown first changed ticks match
09.divergence-noneChanges that leave memory equal return null
09.divergence-budgetLate changes match first, then stay inside the instruction limit
09.record, 09.recording-json, 09.replay, 09.replay-questions, 09.replay-checkRecord and replay behavior without calling firstDivergence

All six regions are filled. Run the unit's checks, describing what you did:

Terminal command
# After filling the type-in route's starter from the listings:
node lab.mjs check project 09 --help-used "filled six regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 09 --help-used "supplied recorder checkpoint; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

All 8 checks should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.

Break the saved state, then repair it

In your project only, change the first line inside the loop of find-call so that it keeps the machine's own state instead of a copy:

JavaScript
const start = machine.state;
Select code to copy. Scroll horizontally if needed.

Question 09d: with this change, how many of the eight checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, then commit the number. Then run the check with --help-used describing this prescribed change, and run the search again:

Terminal command
node lab.mjs predict project 09d YOUR_ANSWER
node lab.mjs check project 09 --help-used "prescribed change: find-call keeps machine.state without a copy"
node lab.mjs diverge project project/run42.json project/tampered.json
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed with what the lab said after your prediction. Compare the tick diverge prints with 96,568 and with the length of call 29. Explain the difference: what does start hold by the time bisectCall reads start.tick, and which state does runFrom restore? Which of the checks only record and replay, and what did they report? Restore the copy, rerun the check and keep both attempts. This change is guided practice; the new application below asks for behavior none of these listings implements.

A different tamper

Question 09c: in project/run42.json, call 12 is a key press, the last of eleven presses of up (key 3). Up and down (key 4) change the power, and N (key 6) starts a new round. API.md lists every key under "public/sessions.mjs". Change call 12 to down with node lab.mjs tamper project/run42.json --call 12 --key 4 --out project/key.json, then predict whether firstDivergence will find a tick inside call 12 or later. Answer inside or later, and commit before you run diverge:

Observed output
node lab.mjs predict project 09c YOUR_ANSWER
node lab.mjs diverge project project/run42.json project/key.json
Select code to copy. Scroll horizontally if needed.

Use it on a new case: trim a recording

A short recording that still shows a bug costs less to replay. Write trimRecording(program, recording, n) in project/trim.mjs. If needed, copy starter/trim.mjs there. No finished version is supplied.

Input or resultContract
nAccept an integer from 0 through the call count; reject anything else before stepping
Returned recordingKeep the first n calls, results and hashes, plus exactly their imported answers
WorkRun no more instructions than those calls take
OwnershipLeave the input unchanged and share no nested arrays or objects
ImportsUse only ./recorder.mjs and ./machine.mjs

The returned value must match a fresh record call on the same prefix. You may assume the input recording replays without a divergence.

Before you write code, answer two questions in project/report.md. Why can't the answers be cut by counting calls, or by looking at the recording alone? If call n - 1 is a game frame with a shell in the air, which side of the cut does its server_wind answer fall on, and how does your code know? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:

Terminal command
node examples/check-trim.mjs project --help-used "initial attempt; nothing written"
node examples/check-trim.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The checker preserves each attempt before running it.

Saved under project/attempts/Compared during the run
Machine, recorder, trim code, project data, report and trim-receipt.jsonYour trim against Node recordings of shorter Lob and Lob II call lists
Every earlier attempt, including failuresInstruction count and replay of the trimmed result

node lab.mjs status project lists these under "New-application attempts".

As a stretch, trim from the other end as well: a recording that starts at call m instead of call 0 needs the machine's state at the start of call m, not only the calls after it. Lesson 10 keeps those states.

Keep the working tool

project/recorder.mjs now records, replays and finds where two runs part, and the lab's record, replay and diverge commands run it. Its end-of-unit checkpoint is examples/recorder-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file.

Write the tick your search found and the instructions it ran in project/report.md, beside the numbers from lesson 08's wall. Lesson 10 keeps snapshots during a replay so that any moment, not only the start of a call, can be reached by replaying a few thousand instructions.