Free to Learn · Time-travel debuggerLesson 10 of 13

10 · Run backwards

Build debugger commands, which pause or rewind the game, that move to an earlier position, the state after a counted instruction, while copying only changed memory pages, fixed-size blocks of stored bytes.

In Lob, an artillery game, stand at position 96,569 and step back to 96,568. You might expect one instruction of work. The debugger restores the nearest snapshot, a saved state at 96,000, then replays, runs again, 568 instructions. This happens inside game_tick, the function that advances one displayed game update.

Start

Run the checks for the machine and recorder you built in lessons 08 and 09:

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

If either fails, make a supplied project and record the same run:

Terminal command
node examples/start-chapter.mjs project10 supplied
node examples/start-recorder.mjs project10 supplied
node lab.mjs record project10 --world 42 --out project10/run42.json
Select code to copy. Scroll horizontally if needed.

Use project10 below if you took that recovery route.

Choose how to create project/debugger.mjs:

RouteCommandWhat you receive
Type innode examples/start-debugger.mjs project writeEight unfinished regions with support code
Inspect working codenode examples/start-debugger.mjs project suppliedThe working checkpoint to test and break
Build from the contractNo setup commandThe stub from lab.mjs start; use API.md

The setup command refuses to replace an edited file. Both setup routes also create unfinished project/reverse-find.mjs. The eight regions are constructor, first-pass, capture, restore, move, stops, search-back and last-write.

Run the first check with the description matching where you started:

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

The route command records write or supplied in PROJECT.json, and every check receipt keeps it as unit10_start_route. That says where you began, not who wrote your current code; keep using --help-used to say what helped each attempt. The type-in route fails all nine checks with not written yet, and the supplied route passes them. Either result is a baseline, not evidence of understanding.

Keep the // region: NAME and // endregion: NAME markers. A listing replaces everything between its matching pair, including the unfinished methods there. The listings omit the marker lines. To recover later without losing edits, run the two supplied setup commands above from the course folder with project-recovery in place of project10, then run node examples/start-debugger.mjs project-recovery supplied and compare its debugger.mjs with yours. Don't copy the checkpoint over your attempt.

Positions

The debugger works on one recording. A position is a moment between instructions. Position t is the state after t instructions of the run, counted across all its calls, so position 0 is before game_init runs anything and position end is after the last call returns. Between two calls no function is running. The next instruction is the first one of the next call, and where() names it with that call's index.

The debugger answers each question at its current position:

MethodResult
seek(t)Move to position t
step(n) / stepBack(n)Move forward or backward by n instructions
continue(stops) / continueBack(stops)Find the nearest later or earlier stop
read(address, size)Return bytes from memory
state()Return a separate copy of the whole machine state

debug.mjs uses state() to call game getters. Check 10.state compares its memory and frames with a replay from tick 0.

Tour the supplied nextInstruction and where in your debugger.mjs now. During a call, the instruction that runs next is the innermost frame's at. Between calls the machine has no frames, so nextInstruction looks up the function the next call starts in, which the constructor keeps in this.callFunc, and answers its instruction 0. Breakpoints use the same method, which is how a breakpoint on a call's first instruction fires at the position between calls.

Every check this lesson names is one of unit 10's checks, and one command runs them all. Describe what helped each attempt, as in lessons 08 and 09:

Terminal command
node lab.mjs check project 10 --help-used "describe what helped"
Select code to copy. Scroll horizontally if needed.

Until you write your Debugger, its checks fail with "not written yet". Run the command again whenever you finish a region.

The obvious way, and its cost

The simplest debugger replays the recording from tick 0 every time it moves. seek(t) then costs t instructions, and so does every stepBack. On lesson 09's recording, 652,927 instructions long, stepping back once from near the end replays more than 650,000 instructions to move one.

Your Lesson 05 debugger replayed from the nearest checkpoint instead of from 0. Each checkpoint copied all 131,072 memory bytes.

Backward designWork to move one instruction near the end
Replay from tick 0More than 650,000 instructions
Restore a full checkpointShort replay, large saved state
Share unchanged pagesShort replay, small saved state

Snapshots that share pages

Cut memory into 4,096-byte pages. Lob's 131,072 bytes become 32 pages. These are debugger pages, not WebAssembly's 64 KiB pages. A snapshot keeps one page object for each part of memory.

State partSnapshot rule
Page written since the prior snapshotCopy its bytes
Page not writtenReuse the prior page object
Frames, stack, globals and countersCopy with structuredClone
Used-answer countSave it so imports resume at the right answer

Take a snapshot every K instructions. Each write event gives an address and size. Mark every page from Math.floor(address / 4096) through the page holding the last written byte.

One machine, answered from the recording

In project/debugger.mjs, replace the constructor region. It holds the constructor and the tick getter:

Open a recordingexamples/debugger-checkpoint.mjs · constructor

Replace the constructor region.

  constructor(
    program,
    recording,
    { every = 1000, pageSize = 4096, check = true } = {},
  ) {
    whole(every, 'every', 1);
    whole(pageSize, 'pageSize', 1);
    this.program = program;
    this.recording = recording;
    this.every = every;
    this.pageSize = pageSize;
    // The function each call starts in: what runs next between calls.
    this.callFunc = recording.calls.map(
      (call) =>
        program.exports.find((e) => e.kind === 'func' && e.name === call.name)
          .index,
    );
    // One machine for the whole session. Its imports ask this.answers, which
    // restore() replaces, so a replay answers from the right place.
    const imports = {};
    for (const { name } of program.imports)
      imports[name] = (...args) => this.answers.imports[name](...args);
    this.machine = new Machine(program, imports);
    this.answers = recordedImports(program, recording, () => this.machine);
    this.snapshots = [];
    this.end = this.firstPass(check);
    this.restore(this.snapshots[0]);
  }

  get tick() {
    return this.machine.state.tick;
  }
Select code to copy. Scroll horizontally if needed.

The Debugger keeps one machine for the whole session. Its imports don't answer from a fixed place in the recording: each one asks this.answers, which restore replaces whenever the machine jumps to a snapshot. That is lesson 09's recordedImports, started at the answer position the snapshot saved. The constructor replays the whole recording once, in firstPass, and then puts the machine back at the first snapshot, position 0. Opening a recording therefore costs one replay of the run, inside the checks' limit of about two.

this.callFunc turns each call's export name into its function index once, for nextInstruction. The options default to a snapshot every 1,000 instructions and pages of 4,096 bytes.

Mark written pages during the first pass

Replace the first-pass region:

Replay once, keeping a snapshot every `every` instructionsexamples/debugger-checkpoint.mjs · first-pass

Replace the first-pass region.

  firstPass(check) {
    const m = this.machine;
    const written = new Uint8Array(
      Math.ceil(m.state.memory.length / this.pageSize),
    );
    this.snapshots.push(this.capture());
    for (let k = 0; k < this.recording.calls.length; k++) {
      do {
        const event = this.forward();
        for (const w of event.writes) {
          const first = Math.floor(w.address / this.pageSize);
          const last = Math.floor((w.address + w.size - 1) / this.pageSize);
          for (let p = first; p <= last; p++) written[p] = 1;
        }
        if (m.state.tick % this.every === 0) {
          this.snapshots.push(this.capture(this.snapshots.at(-1), written));
          written.fill(0);
        }
      } while (m.running);
      if (check) this.checkCall(k);
    }
    return m.state.tick;
  }
Select code to copy. Scroll horizontally if needed.

written has one entry per page, set to 1 when any instruction writes that page and cleared after each snapshot. A write's first and last byte can sit on two pages, so the loop marks every page from the first to the last. A snapshot is taken whenever the tick reaches a multiple of every, which puts snapshot i at tick i * every; moveTo and the backward search rely on that. After each call, checkCall compares memory with the recording's hash, as replay did in lesson 09, so a debugger never answers questions about a run that isn't the recorded one.

Question 10a: in Lob, seed 3, mode 0 (no defences), the first game frame after game_init runs 827 instructions. How many of the 32 pages of 4,096 bytes does it write to? Commit before reading on:

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

Share what wasn't written

Replace the capture region:

Copy only the written pagesexamples/debugger-checkpoint.mjs · capture

Replace the capture region.

  capture(previous = null, written = null) {
    const { memory, ...rest } = this.machine.state;
    const pages = [];
    for (let p = 0; p * this.pageSize < memory.length; p++) {
      const start = p * this.pageSize;
      pages.push(
        previous && !written[p]
          ? previous.pages[p]
          : memory.slice(start, start + this.pageSize),
      );
    }
    return {
      tick: rest.tick,
      pages,
      state: globalThis.structuredClone(rest),
      answered: this.answers.position(),
    };
  }
Select code to copy. Scroll horizontally if needed.

Each page is either the previous snapshot's page object, when nothing wrote it, or a fresh slice, which copies those bytes. The rest of the state goes through structuredClone without its memory, and answered saves the position in the recording's answers. Called with no previous snapshot, capture copies every page; the first snapshot and lastWrite call it that way.

Restoring a snapshot means building a Uint8Array of 131,072 bytes from its pages, copying the small state back, and pointing the machine at both. Never let the machine write into a snapshot's pages. Copy them into a fresh memory first, or the next replay would write into the snapshot's pages, and a later restore of it would give different memory.

Restore without sharing

Replace the restore region:

Rebuild memory and answers from a snapshotexamples/debugger-checkpoint.mjs · restore

Replace the restore region.

  restore(snapshot) {
    const bytes = snapshot.pages.reduce((n, page) => n + page.length, 0);
    const memory = new Uint8Array(bytes);
    snapshot.pages.forEach((page, p) => memory.set(page, p * this.pageSize));
    this.machine.state = {
      ...globalThis.structuredClone(snapshot.state),
      memory,
    };
    this.answers = recordedImports(
      this.program,
      this.recording,
      () => this.machine,
      snapshot.answered,
    );
  }
Select code to copy. Scroll horizontally if needed.

memory.set copies pages, so replay cannot mutate the snapshot. structuredClone protects its smaller state. Restoring this.answers resumes at the saved answer.

Check 10.page-sharing takes your snapshots after a first pass and counts the bytes they hold, counting a page shared by several snapshots once. It also checks that each snapshot's pages, laid end to end, are exactly the memory at its tick.

Going back

continue(stops) and continueBack(stops) take stops = { breakpoints: [{ func, at }], watches: [{ address, size }] } and return { reason, tick }. A breakpoint { func, at } fires at a position whose next instruction is that one, so the debugger stops before it runs. A watch fires right after an instruction that changed one of its bytes, and the debugger stops after the write. Both continue and continueBack move at least one instruction, so from a position where a breakpoint fires, continue finds the next time it fires, not this one.

With snapshots, every backward move restores saved state and replays forward:

MoveRestore and replay rule
stepBack(n) from tRestore at or before t - n; replay to t - n
seek(t)Restore at or before t; replay to t
continueBack(stops)Replay earlier stretches, the instructions between snapshots; keep the latest stop in the first matching stretch
lastWrite(address)Search stretches for the latest instruction that wrote the byte, changed or not

Question 10b: your snapshots are every 1,000 instructions, at ticks 0, 1,000, 2,000 and so on. You stand at position 96,568 and call stepBack(1). How many instructions does the debugger replay? Commit:

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

Shared pages buy one more saving. If the page holding a watched byte is the very same object in two neighbouring snapshots, no instruction wrote that page between them, so the stretch between them can't hold a match and doesn't need to be replayed. For a byte on a page nothing has written for a long time, lastWrite then skips most of the run. How often that happens depends on the page size. A page is skipped only if none of its bytes was written, so smaller pages are skipped more often, and each snapshot then holds more page objects.

Check 10.lob2 asks the same kinds of question about a Lob II recording, so nothing may depend on Lob's own addresses.

Move by restoring and replaying

Replace the move region:

seek, step and stepBackexamples/debugger-checkpoint.mjs · move

Replace the move region.

  forward() {
    const m = this.machine;
    if (!m.running) {
      const call = this.recording.calls[m.state.calls];
      m.begin(call.name, call.args);
    }
    return m.step();
  }

  moveTo(t) {
    const snapshot = this.snapshots[Math.floor(t / this.every)];
    if (this.tick > t || this.tick < snapshot.tick) this.restore(snapshot);
    while (this.tick < t) this.forward();
  }

  seek(tick) {
    if (!Number.isInteger(tick) || tick < 0 || tick > this.end)
      throw RangeError(`seek: ${tick} is not a position from 0 to ${this.end}`);
    this.moveTo(tick);
    return this.tick;
  }

  step(n = 1) {
    this.moveTo(Math.min(this.end, this.tick + whole(n, 'step')));
    return this.tick;
  }

  stepBack(n = 1) {
    this.moveTo(Math.max(0, this.tick - whole(n, 'stepBack')));
    return this.tick;
  }
Select code to copy. Scroll horizontally if needed.

forward runs the run's next instruction. Between calls it first begins the next call, which is why a position between calls has no frames: the call starts only when its first instruction runs. moveTo picks the last snapshot at or before the target and restores it only when it has to: when the machine has passed the target, or hasn't reached that snapshot yet. Moving forward a little from where the machine stands replays only the distance. seek refuses a position outside 0 to end, step and stepBack clamp at end and 0, and all three go through moveTo.

With forward written, the constructor's first pass can run, so you can now look at the snapshots your debugger keeps for lesson 09's recording:

Observed output
node examples/show-snapshots.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.
What the snapshots holdexamples/snapshots-output.txt
project/run42.json: 652927 instructions, 653 snapshots
each snapshot: 32 pages of 4096 bytes, 131072 bytes in all
full copies would hold 85590016 bytes; these hold 7557120 (8.83%)
pages copied by a snapshot after the first: at most 3, on average 2.78
the last snapshot, page by page, holds the copy made by snapshot:
  pages 0-7: 0 0 0 0 0 0 0 0
  pages 8-15: 0 0 0 0 0 0 0 652
  pages 16-23: 652 652 68 70 0 0 0 0
  pages 24-31: 0 0 0 0 0 0 0 0
Select code to copy. Scroll horizontally if needed.
A grid of snapshots, one row per snapshot labelled by its tick, one column per page, 0 to 31. Snapshot 0 copies every page. Up to tick 70,000 the snapshots copy only pages among 16 to 19, which game_init's loop clears; from tick 75,000 every snapshot copies pages 15, 16 and 17 and shares the rest. The last snapshot, at 652,000, shares 27 pages with snapshot 0.

The rows are snapshot 0, each snapshot that copies a set of pages no earlier one copied, and the last. A filled page is a copy this snapshot made; a pale one is an earlier snapshot's object, shared. Pages 15 to 17, copied on every game frame, hold the C stack, the game's state and the status line from lesson 08's memory figure.

Stop before or after

Replace the stops region:

Test the position the machine has reachedexamples/debugger-checkpoint.mjs · stops

Replace the stops region.

  stopHere({ breakpoints = [], watches = [] }, event) {
    if (event && event.writes.some((w) => changesWatched(w, watches)))
      return 'watchpoint';
    const next = this.nextInstruction();
    if (
      next &&
      breakpoints.some((b) => b.func === next.func && b.at === next.at)
    )
      return 'breakpoint';
    return null;
  }

  continue(stops = {}) {
    while (this.tick < this.end) {
      const event = this.forward();
      const reason = this.stopHere(stops, event);
      if (reason) return { reason, tick: this.tick };
    }
    return { reason: 'end', tick: this.tick };
  }
Select code to copy. Scroll horizontally if needed.

stopHere looks at a position from two sides. A watch looks backward, at the event of the instruction that led here, because it fires after a write. A breakpoint looks forward, at the instruction that runs next. Tour the supplied changesWatched at the bottom of the file: a store that rewrites a byte with the value it already held doesn't fire a watch. continue steps first and tests after, so it never reports the position it started from. Lesson 12 adds function stops to stopHere.

Search backward one stretch at a time

Replace the search-back region:

continueBack, searchBack and the shared-page testexamples/debugger-checkpoint.mjs · search-back

Replace the search-back region.

  continueBack(stops = {}) {
    const here = this.tick;
    if (here === 0) return { reason: 'start', tick: 0 };
    const pages = (stops.watches ?? []).flatMap((w) =>
      pagesOf(w.address, w.size ?? 1, this.pageSize),
    );
    const watchesOnly = !stops.breakpoints?.length;
    const found = this.searchBack(
      here - 1,
      (event) => {
        const reason = this.stopHere(stops, event);
        return reason ? { reason, tick: this.tick } : null;
      },
      (i) => !watchesOnly || this.mayHaveWritten(i, pages),
    );
    if (found) {
      this.moveTo(found.tick);
      return found;
    }
    this.moveTo(0);
    return { reason: this.stopHere(stops, null) ?? 'start', tick: 0 };
  }

  searchBack(last, test, mayMatch = () => true) {
    for (let i = Math.ceil(last / this.every) - 1; i >= 0; i--) {
      if (!mayMatch(i)) continue;
      const snapshot = this.snapshots[i];
      const stop = Math.min(last, snapshot.tick + this.every);
      this.restore(snapshot);
      let found = null;
      while (this.tick < stop) {
        const finding = test(this.forward());
        if (finding) found = finding;
      }
      if (found) return found;
    }
    return null;
  }

  mayHaveWritten(i, pages) {
    const a = this.snapshots[i];
    const b = this.snapshots[i + 1];
    return !b || pages.some((p) => a.pages[p] !== b.pages[p]);
  }
Select code to copy. Scroll horizontally if needed.

searchBack(last, test, mayMatch) is the procedure the bullet list described, written once for both backward searches. Stretch i is the instructions after snapshot i, up to snapshot i + 1 or last. It restores the snapshot, replays the stretch once and keeps the latest finding, because the answer is the latest match, not the first. The first stretch, going back, that holds a finding has the answer, so the cost is about the distance to the match plus up to two stretches.

mayHaveWritten(i, pages) is the shared-page saving: it answers no when snapshot i + 1 holds the same page objects as snapshot i. continueBack uses it only when every stop is a watch, because a breakpoint can fire in a stretch that writes nothing. When nothing matches, continueBack goes to 0 and reports 'start', unless a breakpoint fires at position 0 itself.

Ask who last wrote a byte

Replace the last-write region:

lastWrite, and put the machine backexamples/debugger-checkpoint.mjs · last-write

Replace the last-write region.

  lastWrite(address) {
    const size = this.machine.state.memory.length;
    if (!Number.isInteger(address) || address < 0 || address >= size)
      throw RangeError(`lastWrite: ${address} is not an address inside memory`);
    const back = this.capture();
    const page = Math.floor(address / this.pageSize);
    const found = this.searchBack(
      back.tick,
      (event) => {
        const w = event.writes.findLast(
          (w) => address >= w.address && address < w.address + w.size,
        );
        if (!w) return null;
        const { tick, func, at } = event;
        return { tick, func, at, address: w.address, size: w.size };
      },
      (i) => this.mayHaveWritten(i, [page]),
    );
    this.restore(back);
    return found;
  }
Select code to copy. Scroll horizontally if needed.

lastWrite counts any write to the byte, changed or not, as the contract asks, and findLast picks the last write of an instruction that wrote the byte twice. It starts by capturing the current position, with every page copied, and restores it at the end: the method answers without moving the debugger. Only the page holding the byte matters, so every stretch in which that page stayed shared is skipped.

Try the moves on lesson 09's recording with examples/back-session.txt, a script of debug.mjs commands. In it, seek, back and rcontinue (continue backward) move your debugger, last-write goes to the last write of an address, break sets a breakpoint, where prints the position and cost the instructions your machine has run:

Observed output
node debug.mjs project project/run42.json examples/back-session.txt
Select code to copy. Scroll horizontally if needed.
Moving backward and what it costexamples/back-session-output.txt
project/run42.json: 759 calls, 652927 instructions. Type help for commands.
> seek 300000
tick 300000, call 295 (game_tick), next: function 6, instruction 768: i32.const 0
> where
tick 300000, call 295 (game_tick), next: function 6, instruction 768: i32.const 0
> cost
652927 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> back 1
tick 299999, call 295 (game_tick), next: function 6, instruction 767: i64.store 0 0
> cost
653926 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> break 8:0
stops: {"breakpoints":[{"func":8,"at":0}],"watches":[],"functions":[]}
> rcontinue
breakpoint at tick 299502, call 295 (game_tick), next: function 8, instruction 0: global.get 0
> cost
655426 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> last-write 78112
tick 69152: function 4, instruction 76: i32.store 2 78112 wrote 4 bytes at 78112
> cost
656578 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
Select code to copy. Scroll horizontally if needed.

cost counts every instruction since debug.mjs started, the opening replay included, so take differences. seek 300000 cost nothing, because position 300,000 is a snapshot. The next two moves each restore the snapshot before them and replay forward:

Two moves on the stretch between the snapshots at 299,000 and 300,000. back 1 from 300,000 restores the snapshot at 299,000 and replays 999 instructions to 299,999. rcontinue from 299,999 with breakpoint 8:0 restores the same snapshot, replays up to 299,998, 998 instructions, finds the breakpoint fires only at 299,502, then restores again and replays 502 to stand there: 1,500 in all.

The last write of g, the 4 bytes at 78,112, was made in game_init, more than 200,000 instructions before the position rcontinue reached, and finding it replayed about a thousand, because page 19 stayed shared for the rest of the run.

Budgets

The checks count every instruction your machine runs, by counting calls to its step. They ask questions near the end of a long recording and give each kind a budget, a few times what a snapshot every few thousand instructions needs, and far less than a replay from tick 0.

Question 10e: snapshots are every 1,000 instructions. The debugger stands at position 300,000 and calls seek(300400), then seek(300200). How many instructions does the second seek replay? Commit:

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

Each check makes its own debugger, moves it, and compares what it finds with a replay from tick 0 or with a scan of the recording:

CheckMoves, and the snapshots they restoreCompares
10.seekSeeks to positions spread over the run, the start and the end among them. The targets are far apart, so no two seeks restore the same snapshot.The position, where() and all of memory, after each seek, with a replay from tick 0
10.step-backSeeks, then steps back one instruction or a few hundred, or forward a few. A step back restores the snapshot at or before the new position, often the one the seek just restored.The same as 10.seek
10.continueSeeks and calls continue, which only runs forward, so nothing is restored after the seek.Each stop, with a scan of every instruction
10.continue-backSeeks and calls continueBack, which restores the snapshot of the stretch it stands in, often the one the seek just restored, then earlier ones.Each stop, with a scan of every instruction
10.last-writeSeeks and calls lastWrite, which searches back the same way and then puts the debugger back.The write found, with a scan of every write; and that the debugger did not move
10.stateSeeks inside a call and then to the next position between calls.state()'s memory and frames at each, with a replay from tick 0; then it changes the copy and checks that the debugger's memory did not change
10.page-sharingSeeks to the end, which restores the snapshot before the end, then counts the bytes the snapshots' pages hold.A sample of those bytes, with a replay; no position
10.budgetOpens a debugger, seeks near the end and asks backward questions in a row, which restore some snapshots more than once.The instructions each question replays: it fails a debugger that replays from the start for any of them. It compares no position, memory or answer with a replay
10.lob2On a Lob II recording, at a few positions: seeks, steps back one instruction, seeks there again, asks lastWrite and calls continueBack.Each result, with a replay or a scan

All eight 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 10 --help-used "filled eight regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 10 --help-used "supplied debugger checkpoint; followed the explanations and tours"
Select code to copy. Scroll horizontally if needed.

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

Try your debugger on lesson 09's recording by hand too:

Observed output
node debug.mjs project project/run42.json
Select code to copy. Scroll horizontally if needed.

With no keyboard, in a container or from another program, put the commands in a file, one per line, and pass that file as the last argument: node debug.mjs project project/run42.json project/session.txt. A script stops at its first error.

help lists the commands and their arguments. seek TICK, back N, break FUNC:AT, watch ADDR SIZE, continue, rcontinue (continue backward), call N (go to the start of call N) and last-write ADDR call your debugger, read ADDR SIZE TYPE reads memory as u8, i32, f32 or text, and cost shows how many instructions your machine has run since debug.mjs started, including any replay your Debugger made when it opened the recording. For example, break 8:0 and then continue stop where the next call to game_tick begins.

Break a snapshot, then repair it

In your project only, change the line in restore that copies the snapshot's small state, so that the machine gets the snapshot's own objects instead of a copy:

JavaScript
...snapshot.state,
Select code to copy. Scroll horizontally if needed.

Question 10d: with this change, how many of the nine 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:

Terminal command
node lab.mjs predict project 10d YOUR_ANSWER
node lab.mjs check project 10 --help-used "prescribed change: restore uses snapshot.state without a copy"
Select code to copy. Scroll horizontally if needed.

Compare the checks that failed with what the lab said after your prediction. Read the first failure's position and the one it expected. Explain what happened to the snapshot the first time a replay ran from it, and what a second restore of the same snapshot then gives. For each check that passed, say why this change doesn't reach it. Restore the copy and rerun the check, keeping both attempts:

Terminal command
node lab.mjs check project 10 --help-used "prescribed change removed"
Select code to copy. Scroll horizontally if needed.

This change is guided practice; the new application below asks for behavior none of these listings implements.

A question to ask backward

In project/run42.json, the first shot is fired by call 19. The getter r_px, a function that reads the shell's horizontal position, loads it from g + 40. The 4 bytes at address 78,112 hold g, the base address of the game's state.

Question 10c: use your debugger. Go to the start of call 301 (call 301 in debug.mjs), read g with read 78112 4 i32, and ask last-write for the address g + 40. In which call was that write made? Commit the call number your debugger reports:

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

Then work out what the backward search cost. Read cost just before last-write and again after it, and take the difference, because cost also counts any replay your Debugger made when it opened the recording, and the seeks call 301 made. Compare that with lesson 08's estimate for your Lesson 01–07 reverse search, and write both numbers in project/report.md.

Two last-write questions drawn as strips of the run from tick 0. For the pointer g, at 78,112 on page 19, asked at 299,502, only the stretch holding the write at tick 69,152 in call 0 is replayed and the other 230 are skipped: 1,000 instructions, then 152 to move there. For g + 40 at 65,944, on page 16, asked at the start of call 301, all 113 stretches back to the write at tick 191,487 in call 147 are replayed: 112,864, then 487 to move there, 113,351 in all.

What you should have seen: last-write costs 113,351 instructions here, far more than the earlier questions. g + 40 is on page 16, a page written so often that every snapshot copies it, so mayHaveWritten can't rule out any stretch and lastWrite replays every one between here and the write. g itself, on page 19, costs 1,152.

Use it on a new case: find a value backward

Lesson 08 timed reverseFind, a search for the latest earlier position where bytes held a chosen value. Rebuild it with snapshots in project/reverse-find.mjs. Both setup routes created that file. Otherwise, copy starter/reverse-find.mjs there first.

Contract partRequirement
InputreverseFind(debugger, { address, size, equals }); equals holds size bytes
MatchReturn the greatest earlier position, including 0, and stand there
No matchReturn null without moving
Invalid inputRefuse before moving; reject bad ranges, sizes and byte values
BudgetAt most 20,000 replayed instructions, or 80,000 for a missing value
Allowed dataPublic debugger methods plus each snapshot's tick and pages

Before you write code, answer two questions in project/report.md. A page holding your bytes is the same object in snapshots i and i + 1: what do you know about the value at every position between them, and how can you learn it without replaying? Inside a stretch you must replay, why is the first match you see not the answer? 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-reverse-find.mjs project --help-used "initial attempt; nothing written"
node examples/check-reverse-find.mjs project --help-used "describe what helped your implementation"
Select code to copy. Scroll horizontally if needed.

The budget covers the checker's chosen bytes, not every address. It asks near the end about a recent change and about pages untouched since game_init, including the page holding g at 78,112.

Checked caseReplay limit
Value present20,000 instructions
Value never present80,000 instructions
Busy pages 15 to 17Not asked; a missing value could require the whole run

The checker keeps each run inspectable:

ArtifactLocation
Source, project record and reportA new folder under project/attempts/
Resultrfind-receipt.json in that folder
CasesOne-pass histories from Lob and Lob II

As a stretch, make continueBack skip stretches for a breakpoint too: a breakpoint can fire only in a stretch that runs its instruction, and a first pass can note which functions each stretch ran.

Keep the working tool

project/debugger.mjs now moves to any position, steps back, continues back to a breakpoint or watch, and names the last write of a byte, each from a snapshot within its budget. Its end-of-unit checkpoint is examples/debugger-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file. Lesson 11 builds an index of the recording in one replay, so that a last write long ago on a busy page costs nothing to find, and lesson 12 adds the call stack and function stops to this file.

Earlier ideas, new cases

Questions from lessons 08 and 09, on cases you haven't seen. Commit each before checking.

Question 08a3: r_power, function 10, runs i32.const 0, i32.load offset 78112, local.tee 0, i32.load offset 92, local.get 0, i32.load offset 4, i32.xor, end. How many values are on the value stack after instruction 2, local.tee 0?

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

Question 08c3: an i32.store with offset 2 pops the value 287,454,020 (0x11223344) and then the address 5,000. What is the byte at address 5,004 afterwards, as a decimal number?

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

Question 09b3: a tampered recording first differs inside a call of 8,193 instructions. Bisecting inside it, at most how many tests until the two ends are one instruction apart?

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