11 · Question a recording
Build an index, a saved lookup table, that explains values in a recording, a saved execution with game requests and server results, without running it again.
A tick counts finished instructions, numbered machine operations. At tick 89,345, instruction 89,345 changes the shell position bytes, stored numbers from 0 to 255, during game_tick, the function advancing one game frame. You might expect one earlier change. The real sources(89345) lookup lists 16 earlier stores, instructions that write bytes, plus results from cos, a math function, and server_wind, the server function supplying wind.
Start
First prove that the machine, recorder and reverse debugger still work:
node lab.mjs check project 08
node lab.mjs check project 09
node lab.mjs check project 10If a prerequisite fails, create a supplied project and record a run:
node examples/start-chapter.mjs project11 supplied
node examples/start-recorder.mjs project11 supplied
node examples/start-debugger.mjs project11 supplied
node lab.mjs record project11 --world 42 --out project11/run42.jsonUse project11 below if you took that route.
Choose how to create project/query.mjs:
| Route | Command | What you receive |
|---|---|---|
| Type in | node examples/start-query.mjs project write | Ten unfinished regions with support code |
| Inspect working code | node examples/start-query.mjs project supplied | The working checkpoint to test and break |
| Build from the contract | No setup command | The stub from lab.mjs start; use API.md |
The setup command refuses to replace an edited file. Both setup routes create unfinished project/value-sources.mjs. The ten regions are keep-writes, by-byte, last-writer, leaves, producers, frames, follow, memory, replay and sources.
Run the first check with the description matching where you started:
# Type-in route (write), including AI users before requesting changes:
node lab.mjs check project 11 --help-used "chapter write starter; ten regions unfinished"
# Supplied route:
node lab.mjs check project 11 --help-used "supplied query checkpoint; initial baseline"The route command records write or supplied in PROJECT.json, and every check receipt keeps it as unit11_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 every unit 11 check with not written yet, and the supplied route passes them all. 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 line there that throws "not written yet". The listings omit the marker lines. To recover later without losing edits, run the supplied setup commands above from the course folder with project-recovery in place of project11, then run node examples/start-query.mjs project-recovery supplied and compare its query.mjs with yours. Don't copy the checkpoint over your attempt.
The index reads two machine fields that API.md does not name:
| Field | Meaning | Regions that read it |
|---|---|---|
state.stack | Values waiting for instructions | follow, memory |
state.result | Value returned by a finished call | replay |
Lesson 08's machine uses those names. If yours differs, change those reads.
Last writers, indexed
Build the index during one replay:
| Kept data | Use |
|---|---|
| Each byte's write ticks, in order | Binary search for the last tick below beforeTick |
Function and instruction number at | Report the writing instruction |
| Write start and size | Report the whole write |
A 4-byte store adds four byte entries. Lesson 09's recording makes 65,859 entries. Growing typed arrays hold them in a few megabytes. A byte written 1,000 times needs about ten comparisons.
Tour the supplied List near the top of your query.mjs now. It is that growing typed array: push doubles the array when it is full, and done() returns a copy of exactly what was pushed. Then tour the supplied lines at the start of buildIndex. They make one machine whose imports answer from the recording, as lesson 09's replay did, and prepared, which gives every instruction of every function a kind from the table KIND ('load', 'binary', 'call' and so on), so the replay looks up how an instruction moves values without reading its name again. An instruction outside the table stops the index before it runs anything.
Keep every write
In project/query.mjs, replace the keep-writes region:
Replace the keep-writes region.
// Every write, one entry in each list, in tick order.
const wTick = new List(Int32Array);
const wFunc = new List(Int32Array);
const wAt = new List(Int32Array);
const wAddress = new List(Int32Array);
const wSize = new List(Int32Array);
// Per byte: the tick of the store that last wrote it so far, 0 if none.
const writer = new Int32Array(memorySize);
const keepWrites = (event, t) => {
for (const w of event.writes) {
wTick.push(t);
wFunc.push(event.func);
wAt.push(event.at);
wAddress.push(w.address);
wSize.push(w.size);
writer.fill(t, w.address, w.address + w.size);
}
};The replay calls keepWrites after every instruction with the instruction's event and tick. Each write goes into five lists at the same position, so write number w is wTick[w], wFunc[w], wAt[w], wAddress[w] and wSize[w]. The replay runs in tick order, so the lists are in tick order without any sorting. writer is different: it holds, for every byte, only the latest store that wrote it. lastWriter doesn't use it. The chains later in this lesson do, because a load needs to know which store wrote each byte it reads at the moment it reads it.
Group the writes by byte
After the replay, makeIndex turns the writes into one list per byte. Replace the by-byte region:
Replace the by-byte region.
// Per byte, the writes that touched it in tick order:
// byteWrites[byteStart[a]] up to byteWrites[byteStart[a + 1]].
const byteStart = new Int32Array(memorySize + 1);
for (let w = 0; w < writes.tick.length; w++)
for (let i = 0; i < writes.size[w]; i++)
byteStart[writes.address[w] + i + 1]++;
for (let a = 0; a < memorySize; a++) byteStart[a + 1] += byteStart[a];
const byteWrites = new Int32Array(byteStart[memorySize]);
const next = byteStart.slice(0, memorySize);
for (let w = 0; w < writes.tick.length; w++)
for (let i = 0; i < writes.size[w]; i++)
byteWrites[next[writes.address[w] + i]++] = w;All the per-byte lists live in one Int32Array, byteWrites, one after another, and byteStart[a] is where byte a's list begins. The first loop counts how many writes cover each byte, the second turns the counts into starting places, and the third puts each write's number at the next free place of every byte it covers. Writes are placed in tick order, so each byte's list is in tick order too, which is what the binary search needs.
Binary search one byte's list
Replace the last-writer region:
Replace the last-writer region.
const lastWriter = (address, beforeTick) => {
if (!Number.isInteger(address) || address < 0 || address >= memorySize)
throw Error(
`lastWriter: ${address} is not an address in memory (0 to ${memorySize - 1})`,
);
if (typeof beforeTick !== 'number' || Number.isNaN(beforeTick))
throw Error(`lastWriter: beforeTick must be a number, got ${beforeTick}`);
// Binary search for the first write at or after beforeTick.
let lo = byteStart[address];
let hi = byteStart[address + 1];
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (writes.tick[byteWrites[mid]] < beforeTick) lo = mid + 1;
else hi = mid;
}
if (lo === byteStart[address]) return null;
const w = byteWrites[lo - 1];
return {
tick: writes.tick[w],
func: writes.func[w],
at: writes.at[w],
address: writes.address[w],
size: writes.size[w],
};
};The loop narrows lo and hi to the first write at or after beforeTick, so the write just before it, at lo - 1, is the answer. If there is none, nothing wrote the byte before that tick. The answer is the whole write, its start and size, even when the byte is inside a wider store. The debugger's lastWrite at position p is lastWriter(address, p + 1), because the instruction at tick p has already run at position p.
Question 11a: in Lob, seed 3, mode 0 (no defences), how many times is the byte at the address g + 72 written during game_init and the first 10 game frames, where g is the 4 bytes at 78,112? g + 72 is the lowest byte of the game-frame counter. Commit:
node lab.mjs predict project 11a YOUR_ANSWERCheck 11.last-writer asks generated questions about recordings you haven't seen and compares with a scan of every write. It and the other checks this lesson names make up unit 11's checks, which one command runs:
node lab.mjs check project 11 --help-used "describe what helped"On the type-in route they still fail with "not written yet" at this point, because buildIndex runs the regions that follow values before it returns. Run the command again once the sources region is filled.
Where a value came from
A store copies a value off the stack, and that value was computed by an earlier instruction from its operands. Those came from loads, constants, locals or calls, and each load read bytes that an earlier store wrote or that still held their initial value. Following those links backward from a store gives the chain of the stored value.
A box is a store, named by the field of g it wrote, with its tick and call. An oval is an outside answer, named by its recording index. An arrow points to an input value.
sources(tick) takes a store tick and returns four sorted lists:
| List | Contents |
|---|---|
stores | Earlier stores on the chain, by tick |
answers | Outside answers, by recording.answers index |
args | Game-call arguments as [call, index] |
initial | Bytes loaded before any store wrote them |
The chain follows values, not addresses. A load depends on bytes read, while a store passes on its value. Otherwise every chain would include the pointer g.
| Producer | Inputs followed |
|---|---|
Arithmetic or select | Every value operand |
| Load or store | Data bytes or stored value, never the address |
| Local, global or defined call | The value passed through |
| Outside function | Its recorded answer |
| Constant | None |
API.md settles the cases that could go either way: select depends on its condition as well as both values, a one-byte store on the whole value it was given, and a load of bytes written by several stores on all of them.
Question 11f: a store at g + 8 writes the i32.add of two operands: a load of the 4 bytes at g + 4, which the store at tick 5,000 last wrote, and i32.const 3. The address g came from a load at 78,112, which the store at tick 1,000 wrote. Which of these stores are on the stored value's chain: (a) tick 5,000 only, (b) tick 1,000 only, or (c) both? Answer a, b or c, and commit:
node lab.mjs predict project 11f YOUR_ANSWERHow to follow a value
Replay once and give every value a producer, the tick of the instruction that made it. Keep a producer beside stack values, locals, globals and memory bytes.
| Instruction | Producer movement |
|---|---|
| Arithmetic | Pop operand producers; push this tick |
| Constant | Push a value with no inputs |
| Local or global | Move the producer with the value |
| Load | Record each read byte's producer; push this tick |
| Store | Record the value producer; mark written bytes with this tick |
| Outside call | Push the recorded answer's producer |
| Defined call | Move argument producers into parameters; return the result producer |
| Game-call argument | Create a producer reported as [call, index] |
Branches cut the stack back, so cut the producers back with it, keeping a block's result.
Record, for each tick, the producers it took as inputs. sources(tick) then walks backward from the store's input. Visit a tick, add its inputs to the walk, note each store, answer and argument met, and never visit a tick twice. The walk only touches the chain, so most questions finish in a few thousand steps whatever the recording's length.
The seven listings below build that procedure. Three of their choices save memory without changing any answer: a constant gets the producer "nothing" instead of its own tick, since nothing can be on its chain; a value computed from a single producer takes that producer instead of a tick of its own, since its chain is the same; and an import call's value takes its answer's producer directly.
Number the leaves
A producer has to fit in one slot of an Int32Array. A chain ends at leaves: an answer, a call argument or an initial byte. Ticks are positive, so leaves get negative numbers. Replace the leaves region:
Replace the leaves region.
// A producer is one whole number: 0 is nothing (a constant), t > 0 is the
// instruction at tick t, and the leaves are negative: the answers first, then
// every argument of every call, then the initial bytes by address.
const nAnswers = recording.answers.length;
const argBase = [];
let nArgs = 0;
for (const c of calls) {
argBase.push(nArgs);
nArgs += c.args.length;
}
const argCall = new Int32Array(nArgs);
const argPos = new Int32Array(nArgs);
calls.forEach((c, k) =>
c.args.forEach((_, i) => {
argCall[argBase[k] + i] = k;
argPos[argBase[k] + i] = i;
}),
);
const answerId = (a) => -1 - a;
const argId = (k, i) => -1 - nAnswers - argBase[k] - i;
const initialId = (address) => -1 - nAnswers - nArgs - address;The leaves are the producers a chain ends at: an answer, an argument of a call into the game, or an initial byte. Ticks are positive, so the leaves take the negative numbers, one range after another: answer a is -1 - a, then every argument of every call, in call order, then every byte of memory by address. argBase[k] is where call k's arguments start in that range, and argCall and argPos turn an argument's number back into [call, index] when sources reports it. The number 0 is left for nothing.
Producers beside the machine's values
Replace the producers region:
Replace the producers region.
// Per tick: where its inputs start in deps, and whether it was a store.
const depStart = new List(Int32Array);
const deps = new List(Int32Array);
const isStore = new List(Uint8Array);
depStart.push(0); // tick 0 is no instruction
isStore.push(0);
// The producers of what the machine holds right now: one per stack value,
// one per global, and the frames with one per local.
let P = new Int32Array(1024);
let sp = 0;
const G = new Int32Array(program.globals.length);
const frames = []; // { func, locals, base, labels: [{ height, arity, loop }] }
const push = (id) => {
if (sp === P.length) {
const bigger = new Int32Array(P.length * 2);
bigger.set(P);
P = bigger;
}
P[sp++] = id;
};
// A computed value. With no operand producer it is nothing; with one, it
// carries that operand's chain, so it takes its producer; with more, it is
// tick t, whose inputs are the operands' producers.
const scratch = new Int32Array(8);
let nScratch = 0;
const add = (id) => {
if (id === 0) return;
for (let i = 0; i < nScratch; i++) if (scratch[i] === id) return;
scratch[nScratch++] = id;
};
const made = (t) => {
if (nScratch === 0) return 0;
if (nScratch === 1) return scratch[0];
for (let i = 0; i < nScratch; i++) deps.push(scratch[i]);
return t;
};depStart, deps and isStore are what the index keeps for the questions. Tick t's inputs run from deps[depStart[t]] up to, but not including, deps[depStart[t + 1]], so every tick costs one number in depStart and one byte in isStore, however many inputs it has. P and sp mirror the machine's value stack, one producer per value, G mirrors the globals, and each frame will hold one producer per local. These last only as long as the replay.
add and made make a computed value's producer. add collects the operands' producers, skipping 0, which means no producer, and any producer already collected. made(t) returns 0 if none was collected, the one producer if only one was, and otherwise records them all as tick t's inputs and returns t. An i32.add of a loaded value and a constant therefore passes on the load's producer, and its chain is the load's chain, as the rules ask.
Branches, returns and calls
Replace the frames region:
Replace the frames region.
// A branch keeps its target's results and cuts the producers back with the
// stack; a loop's label stays, because the loop can be branched to again.
const branch = (frame, depth) => {
const label = frame.labels[frame.labels.length - 1 - depth];
for (let i = 0; i < label.arity; i++)
P[label.height + i] = P[sp - label.arity + i];
sp = label.height + label.arity;
frame.labels.length -= label.loop ? depth : depth + 1;
};
// A return hands the results' producers back to the caller; the outermost
// call's result leaves the machine.
const leave = () => {
const frame = frames.pop();
const n = prepared.get(frame.func).results;
for (let i = 0; i < n; i++) P[frame.base + i] = P[sp - n + i];
sp = frame.base + (frames.length ? n : 0);
};
// A call's arguments become the new frame's first locals; the other locals
// start as nothing.
const enter = (func, args) => {
const locals = new Int32Array(args.length + prepared.get(func).locals);
locals.set(args);
frames.push({ func, locals, base: sp, labels: [] });
};branch, leave and enter follow lesson 08's branch, return and call. A label remembers the stack's height when its block began and how many results the block leaves. branch copies those results' producers down to that height and cuts sp there, so the values a branch drops take their producers with them. A branch to a loop keeps the loop's label, because the loop can be branched to again. leave does the same for a function's results, and enter starts a frame whose first locals are the producers of the call's arguments and whose other locals are nothing.
Move the producers instruction by instruction
Replace the follow region:
Replace the follow region.
// Move the producers as the instruction at tick t is about to move values.
// stack is the machine's value stack before the instruction runs.
const follow = (kind, ins, frame, t, stack) => {
switch (kind) {
case 'block':
frame.labels.push({ height: sp, arity: ins[1] ? 1 : 0, loop: false });
break;
case 'loop':
frame.labels.push({ height: sp, arity: 0, loop: true });
break;
case 'br':
branch(frame, ins[1]);
break;
case 'br_if':
sp--; // the condition is a decision: on no chain
if (stack[stack.length - 1] !== 0) branch(frame, ins[1]);
break;
case 'end':
if (frame.labels.length) frame.labels.pop();
else leave();
break;
case 'return':
leave();
break;
case 'call': {
const n = program.typeOf(ins[1]).params.length;
if (ins[1] < nImports) {
sp -= n; // an import's arguments are not followed
if (program.typeOf(ins[1]).results.length)
push(answerId(answered.position()));
} else {
const args = P.slice(sp - n, sp);
sp -= n;
enter(ins[1], args);
}
break;
}
case 'local.get':
push(frame.locals[ins[1]]);
break;
case 'local.set':
frame.locals[ins[1]] = P[--sp];
break;
case 'local.tee':
frame.locals[ins[1]] = P[sp - 1];
break;
case 'global.get':
push(G[ins[1]]);
break;
case 'global.set':
G[ins[1]] = P[--sp];
break;
case 'const':
push(0);
break;
case 'unary':
break; // the same operand, so the same chain
case 'binary':
nScratch = 0;
add(P[sp - 2]);
add(P[sp - 1]);
sp -= 1;
P[sp - 1] = made(t);
break;
case 'select':
nScratch = 0;
add(P[sp - 3]);
add(P[sp - 2]);
add(P[sp - 1]);
sp -= 2;
P[sp - 1] = made(t);
break;
case 'load':
load(ins, t, stack);
break;
case 'store':
store();
break;
}
};follow runs just before the machine runs the instruction, while the operands are still on the machine's stack, and does to P what the instruction is about to do to the stack. br_if drops its condition's producer without recording it anywhere, because a branch's condition is on no chain ("Decisions are not followed" below says why); it reads the condition's value from the machine's stack only to know whether the branch will be taken. An import call drops its arguments' producers and pushes the leaf of the answer the machine is about to use. A call to a defined function moves its arguments' producers into the new frame. Loads and stores go to the next region.
Loads and stores: bytes, not addresses
Replace the memory region:
Replace the memory region.
// A load depends on the bytes it read, each on the store that last wrote
// it, or on the byte itself if no store has. Its address is not followed.
const load = (ins, t, stack) => {
const address = (stack[stack.length - 1] >>> 0) + ins[2];
nScratch = 0;
for (let i = 0; i < LOAD_SIZE[ins[0]]; i++) {
if (address + i >= memorySize) break;
const w = writer[address + i];
add(w !== 0 ? w : initialId(address + i));
}
P[sp - 1] = made(t);
};
// A store's only input is its value's producer; its address is not
// followed. keepWrites then makes this tick the writer of every byte.
const store = () => {
const value = P[--sp];
sp--;
if (value !== 0) deps.push(value);
};A load reads its address from the machine's stack and looks up, in writer, the store that last wrote each byte it is about to read. A byte no store has written gives its initial leaf. The load's result replaces the address's producer on top of P, so the address is never an input. A store pops its value's producer and records it as its only input, then drops the address's producer. After the machine runs it, keepWrites makes this tick the writer of every byte it wrote, so the next load of those bytes depends on this store.
Replay once
Replace the replay region:
Replace the replay region.
for (let k = 0; k < calls.length; k++) {
m.begin(calls[k].name, calls[k].args);
enter(
program.exportIndex(calls[k].name),
calls[k].args.map((_, i) => argId(k, i)),
);
while (m.running) {
const top = s.frames[s.frames.length - 1];
const frame = frames[frames.length - 1];
const fn = prepared.get(top.func);
const ins = fn.code[top.at];
const kind = fn.kinds[top.at];
const t = s.tick + 1;
depStart.push(deps.n);
isStore.push(kind === 'store' ? 1 : 0);
follow(kind, ins, frame, t, s.stack);
const asked = answered.position();
const event = m.step();
keepWrites(event, t);
// The producers must still match the machine: its stack, its frames and
// the answers it has used.
const used = kind === 'call' && ins[1] < nImports ? 1 : 0;
if (
frame.func !== top.func ||
sp !== s.stack.length ||
frames.length !== s.frames.length ||
answered.position() !== asked + used ||
(event.writes.length !== 0) !== (kind === 'store')
)
throw Error(
`buildIndex: lost track of the machine at tick ${t} (${ins[0]} at (${event.func}, ${event.at}))`,
);
}
const result = s.result === undefined ? null : s.result;
if (!Object.is(result, recording.results[k]))
throw Error(
`buildIndex: call ${k} returned ${result}, the recording says ${recording.results[k]}`,
);
}
depStart.push(deps.n);Each call begins with a frame whose locals are the call's argument leaves. Then, for every instruction, the loop records where its inputs start, moves the producers with follow, lets your machine run it and keeps its writes. After each instruction it compares the producers with the machine: the same stack height, the same number of frames, one answer used by an import call and none otherwise, and writes exactly when the instruction was a store. A mistake in follow then stops the replay at the first tick where one of these disagrees, instead of giving wrong chains later. After each call, the result must be the recorded one, as in lesson 09.
Walk back from a store
Replace the sources region:
Replace the sources region.
// seenTick[t] === epoch: tick t was visited during the current question.
const { nAnswers, nArgs, argCall, argPos } = leaves;
const seenTick = new Int32Array(end + 1);
const seenLeaf = new Int32Array(nAnswers + nArgs + memorySize);
let epoch = 0;
const sources = (tick) => {
if (!Number.isInteger(tick) || tick < 1 || tick > end || !isStore[tick])
throw Error(
`sources: tick ${tick} is not the tick of a store instruction`,
);
epoch++;
const stores = [];
const answers = [];
const args = [];
const initial = [];
const todo = [];
for (let i = depStart[tick]; i < depStart[tick + 1]; i++)
todo.push(deps[i]);
while (todo.length) {
const id = todo.pop();
if (id > 0) {
if (seenTick[id] === epoch) continue;
seenTick[id] = epoch;
if (isStore[id]) stores.push(id);
for (let i = depStart[id]; i < depStart[id + 1]; i++)
todo.push(deps[i]);
continue;
}
const leaf = -1 - id;
if (seenLeaf[leaf] === epoch) continue;
seenLeaf[leaf] = epoch;
if (leaf < nAnswers) answers.push(leaf);
else if (leaf < nAnswers + nArgs) args.push(leaf - nAnswers);
else initial.push(leaf - nAnswers - nArgs);
}
const up = (a, b) => a - b;
return {
stores: stores.sort(up),
answers: answers.sort(up),
args: args.sort(up).map((x) => [argCall[x], argPos[x]]),
initial: initial.sort(up),
};
};The walk starts from the store's value producer. It visits each tick once, adds that tick's inputs, and sorts each leaf into its output list. seenTick and seenLeaf hold an epoch number that changes for every question, so the arrays need no clearing. The requested store stays out of its own chain.
For sources(89345), the first flight gives this state trace:
| Value | Earlier source |
|---|---|
| New shell position | Prior position, horizontal speed, answer 3 (server_wind) |
| Horizontal speed | Power, a constant, answer 1 (cos) |
| Power | 11 key-press stores, then game_init |
| First position | Cannon position at g + 20 |
| Stored power key | game_init store at g + 92 |
The result holds 16 stores and 2 answers. game_init wrote the starting angle and power together in one 8-byte store. Mode 4 is off, so the XOR key at g + 92 is 0.
By rule, the angle isn't on the chain, because it reached the outside world only as the argument of cos, and an import's arguments aren't followed. Nor is the pointer g, because it was only ever an address.
Question 11b: in lesson 09's recording, made with the server defences on, the shell's position is stored at g + 40 on every game frame of a flight. How many server_wind answers are on the chain of the position stored on the tenth game frame of the first flight? Commit:
node lab.mjs predict project 11b YOUR_ANSWERChecks 11.sources-lob and 11.sources-lob2 ask generated questions about Lob and Lob II recordings, and 11.sources-rules asks about a small program built to use the rules Lob never needs: a global that carries a value, a function that takes arguments and returns a result, a block that leaves a value, a branch that drops values. Every address that small program loads from or stores to is a constant, or computed only from constants, such as a loop counter that starts at a constant. Each check compares your four lists one by one. The lists it expects were worked out by a brute force that carries every value's full set of sources forward through the whole recording, a different method from the walk above, so the same mistake is unlikely in both.
All ten regions are filled. Run the unit's checks, describing what you did:
# After filling the type-in route's starter from the listings:
node lab.mjs check project 11 --help-used "filled ten regions from chapter listings"
# After following the supplied route:
node lab.mjs check project 11 --help-used "supplied query checkpoint; followed the explanations and tours"Every unit 11 check should pass. If one fails, its first mismatch names the section to reread. Keep the failing attempt and your explanation before you edit.
Cost
buildIndex may replay the recording once or twice, and after that no question may replay it. Check 11.no-replay counts the instructions your machine runs while hundreds of questions are answered, and expects none.
See what your index kept for lesson 09's recording, and what asking it costs:
node examples/show-index.mjs project project/run42.jsonproject/run42.json: 652927 instructions in 759 calls
building the index ran 652927 instructions on your machine
per-byte lists: 65859 entries, for 12301 bytes written at least once
the most written byte is 65508, written 2944 times; a binary search in its list takes at most 12 comparisons
sources asked about all 36810 stores: the longest chain holds 739 stores
instructions run while answering those questions: 0Building the index ran exactly one replay of the run. The per-byte lists hold the 65,859 entries counted earlier, for 12,301 bytes. The most written byte lies in the C stack just below 65,536, and a binary search finds any write in its list in at most 12 comparisons. The script then asked sources about every store of the run, and your machine ran no instruction while it did: everything a question needs was kept during the replay.
node debug.mjs project project/run42.jsonAs in lesson 10, you can also put the commands in a file, one per line, and pass it as the last argument, for a session with no keyboard.
In debug.mjs, who ADDR asks your index for the last writer, and sources asks for the chain of the store at the current tick. Stand right after a store with who or last-write, then ask sources. It prints how many stores the chain holds and the newest 8 of them, newest first, each with its tick, its function and instruction, and the address it wrote. sources N shows the newest N, and sources all shows every one. Then come the chain's answers, call arguments and initial bytes.
examples/query-session.txt asks for the worked chain of tick 89,345 twice:
node debug.mjs project project/run42.json examples/query-session.txtproject/run42.json: 759 calls, 652927 instructions. Type help for commands.
> seek 89345
tick 89345, call 20 (game_tick), next: function 8, instruction 539: local.get 1
> sources
stores: 16 on the chain; the newest 8, newest first (sources N shows N, sources all every one):
tick 88553: function 7, instruction 181: f32.store 2 48 wrote 4 bytes at 65952
tick 88529: function 7, instruction 157: f32.store 2 40 wrote 4 bytes at 65944
tick 83439: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
tick 82713: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
tick 81987: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
tick 81261: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
tick 80535: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
tick 79809: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
answers: 1 (cos) 3 (server_wind)
call arguments: none
initial bytes: none
> cost
1306199 instructions run by your machine so far, 652927 of them while your Debugger opened the recording
> sources 3
stores: 16 on the chain; the newest 3, newest first (sources N shows N, sources all every one):
tick 88553: function 7, instruction 181: f32.store 2 48 wrote 4 bytes at 65952
tick 88529: function 7, instruction 157: f32.store 2 40 wrote 4 bytes at 65944
tick 83439: function 7, instruction 91: i32.store 2 4 wrote 4 bytes at 65908
answers: 1 (cos) 3 (server_wind)
call arguments: none
initial bytes: none
> cost
1306199 instructions run by your machine so far, 652927 of them while your Debugger opened the recordingThe listed stores are the ones the worked chain named: the speed and the position stored by firing, then the presses of up storing the power at g + 4. The first cost counts the replay your Debugger made when it opened the recording, the short replay seek made from the snapshot at 89,000, and one more replay of the whole run, for the index, which debug.mjs builds the first time you ask who or sources. The second cost is the same number: the second question ran no instruction.
Question 11c: in project/run42.json the second shot is fired by call 396, and as it fires the game adds 1 to its shot counter and stores it. How many stores are on the chain of the value that store writes? Lesson 08's loop that clears memory is part of the answer. Commit before you check with who and sources:
node lab.mjs predict project 11c YOUR_ANSWERNow follow a chain from the status line. The getter r_line_ptr returns its address, and read ADDR text shows the bytes as text. Character i lives at the returned address plus i.
| Character | What its chain reaches |
|---|---|
| Fixed letter | A constant |
| Angle, power or score digit | Earlier stores, back to game_init |
Wind arrow > or < | An outside answer in project/run42.json |
Use who on one wind-arrow byte, then ask sources. In project/report.md, record each store's tick, function and address. Name the final answer and its outside function. Explain why a character chosen from constants still has a chain. listing FUNC:AT 30 shows the choosing instructions around the store.
Decisions are not followed
A br_if pops a condition and branches, and the branch decides which instructions run, but no value flows from the condition into what those instructions compute.
Question 11d: in project/run42.json the first shell lands in call 148, and the game stores 0 in its flying flag at g + 36 (tick 192,256). The store runs only because a br_if found the shell below the ground. How many entries does sources(192256) list, in all four lists together? Commit:
node lab.mjs predict project 11d YOUR_ANSWERA store of a constant has an empty chain even when it ran only because of a long computation before it. When a store's chain is empty or doesn't explain a wrong value, the cause may be a decision, so look at the branch that led to the store, with back and listing (listing FUNC:AT N prints the instructions from N before AT to N after it).
Follow an address, then repair it
In your project only, make a load depend on its address as well. In the load function of the memory region, add this line right after nScratch = 0;, so that the address's producer, the top of P, is collected with the bytes':
add(P[sp - 1]);Question 11e: with this change, how many of unit 11's five checks fail? Before you run anything, write in project/report.md which ones you expect to fail and why, and what you expect sources at tick 89,345 to show, then commit the number. Then run the check with --help-used describing this prescribed change, and open debug.mjs and ask sources all at tick 89,345 (seek 89345, then sources all; as in lesson 10, those two commands can also go in a file passed as the last argument):
node lab.mjs predict project 11e YOUR_ANSWER
node lab.mjs check project 11 --help-used "prescribed change: a load also follows its address"
node debug.mjs project project/run42.jsonCompare the checks that failed, and the chain at tick 89,345, with what the lab said after your prediction. Explain in project/report.md which entries the change added to that chain, and why one rule can add the same entries to many chains. Remove the line and rerun the check, keeping both attempts:
node lab.mjs check project 11 --help-used "prescribed change removed"This guided change alters an existing rule. The next application combines the index's rules in a new way.
Use it on a new case: where a value in memory came from
sources starts from a store tick. Memory inspection starts from bytes at a position. Write valueSources(index, { address, size, position }) in project/value-sources.mjs. The setup routes created it. Otherwise, copy starter/value-sources.mjs there first.
| Contract part | Requirement |
|---|---|
| Result | { stores, answers, args, initial } for the bytes after position instructions |
| Written byte | Include its last store and that store's chain |
| Unwritten byte | Include its address in initial |
| Ordering | Increasing, without repeats; args by call then index |
| Invalid input | Refuse non-whole values, bad sizes, positions or memory ranges |
| Memory bound | Addresses 0 through 131,071; two 64 KiB WebAssembly pages |
| Budget | Run no machine instruction |
| Allowed index data | end, lastWriter and sources only |
Before you write code, answer two questions in project/report.md. Which beforeTick do you pass to lastWriter for a value at position p, and what goes wrong with the other choice? Two bytes of a 4-byte value were written by one store: how many times does that store appear in your answer, and why? Keep that first reasoning. Then run the checker on the unfinished file, implement, and run it again, describing assistance honestly each time:
node examples/check-value-sources.mjs project --help-used "initial attempt; nothing written"
node examples/check-value-sources.mjs project --help-used "describe what helped your implementation"Every question, including a refused one, must run zero machine instructions. The checker counts step calls around each valueSources call. Building its indexes is outside that count, and the whole check has 120 seconds.
| Evidence saved | Cases asked |
|---|---|
Source, PROJECT.json, report and vsources-receipt.json in a new attempt folder | Invalid inputs and g after game_init |
| Earlier attempts stay intact | Four one-byte stores and unwritten bytes |
| Expected lists kept as length plus salted hash | A store's own tick, the tick before, and a Lob II value |
Your query.mjs must pass unit 11 first because every expected answer uses its index.
As a stretch, add a value ADDR SIZE command to your own copy of debug.mjs that asks valueSources about the bytes at the current position.
Keep the working tool
project/query.mjs now builds an index of a recording in one replay and answers, without replaying, who last wrote any byte before any tick and which stores, answers, arguments and initial bytes a stored value was computed from. debug.mjs uses it for who and sources. Its end-of-unit checkpoint is examples/query-checkpoint.mjs; recover from it with a new project, as in "Start", never by copying it over your file. Lesson 12 gives the debugger function names, the call stack and line numbers, and lesson 13's investigations use who and sources to find planted bugs.
Earlier ideas, new cases
Question 08b3: a loop starts with local 1 at 150, subtracts 5 from it each time round, and ends with br_if 0, which branches back while local 1 isn't zero. How many times does br_if 0 branch back?
node lab.mjs predict project 08b3 YOUR_ANSWERQuestion 09a3: record lesson 09's game (Lob, seed 5) in mode 0, with no server defences, and with three shots instead of two. How many answers does the recording hold?
node lab.mjs predict project 09a3 YOUR_ANSWERQuestion 10b3: snapshots are every 2,000 instructions, at ticks 0, 2,000, 4,000 and so on. You stand at position 96,568 and call stepBack(600). How many instructions does the debugger replay?
node lab.mjs predict project 10b3 YOUR_ANSWER