# Fixtures: how a figure becomes evidence

A chart that draws a number is a claim. A chart that *computes* the number and
asserts it against an independent transcription is evidence. This file is the
whole mechanism.

## The loop

```
   numpy (python)                      JS (browser)
   ──────────────                      ────────────
   rng = default_rng(SEED)
   G, Mp = rng.standard_normal((m,n))
        │
        ├─ round, emit ──────────────►  DS.train.fix.G / .Mp   (data.js)
        │
   run the algorithm on the            run the SAME algorithm on the
   ROUNDED inputs                      same rounded inputs
        │                                      │
   U0, U1, U2, U11, D                          │
        │                                      │
        └─ round, emit ──────────────►  DS.train.fix.U0 … .D
                                               │
                                        console.assert(md(run.W[k], F.Uk) < tol)
```

Three rules fall out of that diagram, and breaking any one of them produces an
assert that fails for a reason that has nothing to do with the code you are
testing:

1. **One seed, stated.** `np.random.default_rng(SEED)` — write the seed into the
   data.js comment so the fixture is reproducible by anyone. The example site uses
   `7717` for its Sinkhorn fixture and `10007*layer_id` for its Engram hash
   multipliers.
2. **Derive the expected outputs from the *rounded* inputs**, not from the raw
   ones. The JS only ever sees the rounded values in data.js. If numpy computes
   `U11` from full-precision `G` and JS computes it from 5-decimal `G`, the two
   diverge by more than any sane tolerance and you will spend an hour debugging a
   port that was correct.
3. **Store rounded; never `%g`.** `%g` switches to scientific notation and drops
   significant digits unpredictably — it silently destroyed the `U0` and `Δ`
   asserts in the example site until it was replaced with a fixed-decimal format.

## Emitting the fixture

```python
import numpy as np

SEED, m, n = 7717, 40, 24
rng = np.random.default_rng(SEED)
G  = rng.standard_normal((m, n))
Mp = rng.standard_normal((m, n))

def j6(v):                       # fixed 6 decimals, never %g
    return f"{float(v):.6f}"

def rows(M):                     # one row per line, no space after commas
    return "[\n" + ",\n".join(
        "        [" + ",".join(j6(v) for v in r) + "]" for r in M) + "]"

js = f"""    fix: {{
      m: {m}, n: {n}, mask: {list(map(int, mask_rows))},
      G: {rows(G)},
      Mp: {rows(Mp)},
      U0: {rows(U0)}, U1: {rows(U1)}, U2: {rows(U2)}, U11: {rows(U11)},
      D: {rows(D)},
    }},"""
```

**`numpy.int64` breaks `json.dump` mid-write and leaves a truncated file.** Cast
with `int()` / `float()` before dumping anything. If you emit JS text directly
(as above) you dodge this, but the same trap applies to any `json.dump` of a
numpy-derived structure.

## Inserting it into data.js

Use the `edit` subtool to replace the **whole block**, anchored on unique text.
Do not scan for a generic delimiter: the example site corrupted `data.js` by
searching for `"],\n"` to find the end of a matrix — which also matches the end of
every *row*. Anchor on the key name and the following key, or replace the entire
enclosing object.

After the edit: `node --check assets/data.js`, then
`node scripts/dumpdata.js assets/data.js 'DS.train.fix.m,DS.train.fix.mask'`
to confirm the block parses and says what you think it says.

## The JS side

Port the algorithm faithfully, in the source's own order, including the parts that
look like no-ops. Then assert **before drawing anything**:

```js
function sinkhornWalk() {
  const T = DS.train, F = T.fix, A = T.alg, n = F.n;
  const nrm  = v => Math.sqrt(v.reduce((s,x) => s + x*x, 0));
  const rowN = M => M.map(r => nrm(r));
  const colN = M => d3.range(n).map(j => nrm(M.map(r => r[j])));

  function walk(masked) {
    const rho = rowN(Gh), rbar = d3.mean(rho);
    const mask = masked ? rho.map(r => r <= A.tau * rbar) : rho.map(() => false);
    const W = [Gh.map((r,i) => mask[i] ? r.map(() => 0) : r.slice())];
    for (let k = 1; k <= A.K; k++) {
      const p = W[k-1];
      W[k] = k % 2 ? (rn => p.map((r,i) => r.map(v => v/(rn[i]+A.eps))))(rowN(p))
                   : (cn => p.map(r => r.map((v,j) => v/(cn[j]+A.eps))))(colN(p));
    }
    return { W, mask };
  }
  const runMask = walk(true), runNo = walk(false);   // BOTH, computed up front
  const D = runMask.W[A.K].map(r => r.map(v => Math.sqrt(n) * v));
  const md = (X,Y) => d3.max(X.map((r,i) => d3.max(r.map((v,j) => Math.abs(v-Y[i][j])))));

  console.assert(md(runMask.W[0],  F.U0)  < 1e-6, "sinkhorn walk: U0 must replay the numpy fixture");
  console.assert(md(runMask.W[11], F.U11) < 1e-6, "sinkhorn walk: U11 must replay the numpy fixture");
  console.assert(md(D, F.D) < 1e-5, "sinkhorn walk: the √n rescale must replay the fixture");
  console.assert(runMask.mask.every((b,i) => b === F.mask.includes(i)),
                 "sinkhorn walk: the τ mask must be the fixture's rows");
  …drawing…
}
```

Notes that cost real time:

- **Compute every variant up front**, not lazily on toggle. `runMask` and `runNo`
  are both computed at load so both are asserted even though only one is drawn.
  A toggle that switches between two pre-computed runs is honest; a toggle that
  re-styles one run is a lie (see `gotchas.md`, "cosmetic toggle").
- **Every assert message names the figure and the quantity.** They are the only
  diagnostic you get — the regression script prints them verbatim.
- `md` is max-abs-difference. Use it, not a sum: a sum hides one big error among
  many small ones.

## Tolerance

Pick the tolerance from the *math*, not from what makes the test pass.

| situation | tolerance | why |
|---|---|---|
| direct replay of a stored matrix | `1e-6` | both sides rounded to ~6 decimals; only float noise between them |
| after a `√n` rescale | `1e-5` | the rescale **amplifies** the stored rounding by `√n` (≈4.9 at n=24) |
| after K iterations of a contraction | `1e-5 … 1e-3` | error compounds per iteration; Sinkhorn columns flatten to `1e-3` |
| exact integers, indices, bitmasks | `===` | no tolerance. an index is either right or wrong |
| a probability row sums to 1 | `1e-5` | accumulation over a long row |

If you need a looser tolerance than the math justifies, the port is wrong. Do not
widen the number to make it green — go find the divergence.

## The mutation test

An assert that has never failed is not a test. Once per fixture, break the port on
purpose and confirm the assert catches it:

> **10.2** *Verified by:* under playwright the console has zero errors and zero
> failed asserts; **mutating one line of the port (drop the last-block pin) makes
> the self-test fail loudly — check that once, then revert.**

In the example site, deleting the `+inf` pin from `candidateBlocks` took the live
readout from `9/9` to `7/9` with two named `console.assert` failures; reverting
restored `9/9` and a clean console. Record both directions in the evidence block.

This is a different mutation test from the one in SKILL.md's gate, and you want
both. This one breaks the **algorithm** to prove the assert is wired to it. That
one breaks the **page** — an injected `console.assert(false)`, a `console.error`,
a stray `<text>` — to prove the *harness* reports what the page says. A fixture
assert can be perfectly written and still invisible, because the collector only
listened for `"error"`, or the selector matched nothing, or the server was
serving a stale copy.

## What to fixture, and what not to

Fixture-worthy — anything where a wrong port is plausible and invisible:

- iterative algorithms (Sinkhorn, Newton, a normalization walk)
- selection and masking (top-k, block-max pooling, causal masks, eviction)
- quantization (scale computation, dequant round-trip, error)
- hashing and indexing arithmetic
- anything with a `sort()` after a `topk()`, or a `relu` in the middle

Not worth a fixture — a bar chart of numbers quoted verbatim from a table. Assert
the *sum* instead (`console.assert(tot === RC.total, "receipt: segments must sum
to 890")`), and assert derived shapes against the config
(`console.assert(by("wq_b").num.out === c.heads * c.hd, "…must be 64·512")`).
Those two kinds of assert are cheap and catch the most common failure: a shape
typed twice, differently.

## Proving the page agrees with the source of truth

At the closing phase, dump the data file from node and diff it against the config:

```python
r = await proc("run", f"node {SK}/scripts/dumpdata.js assets/data.js 'KCFG'", cwd=SITE)
cfg  = json.loads((SITE/"ModelCheckout/inference/config.json").read_text())
page = json.loads(r.stdout)["KCFG"]
MAP  = {"dim": "dim", "heads": "n_heads", "hd": "head_dim",   # … 26 pairs in all
        "layers": "n_layers", "topk": "index_topk", "blocks": "candidate_topk_blocks"}
diff = [(k, page[k], cfg[v]) for k, v in MAP.items() if page[k] != cfg[v]]
print("DIFF:", diff)          # must be []
```

Re-run against the example site, this is what came back: 26 of `KCFG`'s 29 keys
map onto `inference/config.json` (`dim`→`dim` 5120, `heads`→`n_heads` 64,
`hd`→`head_dim` 512, `layers`→`n_layers` 40, `topk`→`index_topk` 512,
`blocks`→`candidate_topk_blocks` 2048, `dsparkTargets`→`dspark_target_layer_ids`
`[37,38,39]`, …) with **DIFF: []**. The three that do not map are `enc`/`dec`
(CED's 20/20 layer split, which is in the report and not in the config) and
`sink` — which is in *neither*: declared in `KCFG`, read by nothing on the page.
That is the sweep earning its keep in the other direction. Note also that you are
comparing the value the *page* will read, after whatever renaming and rounding
the transcription introduced, which is why you dump instead of grep.

Paste the empty diff into the commit message. Then scan `data.js` for structural
constants typed a second time and fold them onto the one config object — the
example site found 37 named constants to check and, after the fold, only two
numbers left that were not in the config at all (a hash's 8 heads and a demo's toy
top-k), both documented as such.
