Skip to content

engine#315: investigation record only (split from #414) - #425

Merged
bong-water-water-bong merged 1 commit into
mainfrom
1bit/315-record
Oct 16, 2026
Merged

bong-water-water-bong merged 1 commit into
mainfrom
1bit/315-record

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Part 1 of the #414 split. Refs #315 (stays open).

Carries only the record: docs/315-*, docs/315-campaign/**, KNOWN-ISSUES.md, taken unchanged from #414's head, plus the tools/copyright.py exemption for the record's .patch / .csv / .cfg evidence files (and *.hip in the // list) so the copyright check passes.

Not included:

tools/copyright.py --check passes locally.

🤖 Generated with Claude Code

The record only: docs/315-*, docs/315-campaign/**, KNOWN-ISSUES.md, plus the
tools/copyright.py exemption for the record's .patch/.csv/.cfg evidence files
(and *.hip in the C-style list) so the copyright check passes.

No third_party/llama.cpp gitlink move, no registry change, no agent scaffolding.
Refs #315.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

🎫 Ticket compliance analysis 🔶

315 - Partially compliant

Compliant requirements:

  • Carry investigation record for intermittent HRX GLM-4.7-Flash faults
  • Record the evidence of the campaign including pre-registered experiments, results, falsifications, and tooling
  • Ensure the change is a forward-only move, not a revert

Non-compliant requirements:

  • Move llama.cpp submodule pin forward from e44c9d01a to 47a8fe929
  • Update registry/architectures.json to agree with the gitlink

Requires further human verification:

  • Verification that the pin move is correctly implemented and tested
  • Confirmation that the registry/architectures.json update is accurate
⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 No relevant tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Memory Fault Risk

The debug harness glm-mla-race.cpp performs repeated computations on HRX0 and reports differences. If not properly managed, this could lead to memory faults or inconsistencies in the HRX0 backend, especially under varied-length requests.

// Debug harness: repeat one MLA-shaped FLASH_ATTN_EXT (+ the v_mla de-absorption matmul) on HRX0 and report
// Copyright 2026 bong-water-water-bong
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// where runs differ. Adapted from the earlier investigation's fa-race.cpp, which used a Qwen-shaped graph
// (Hq=16/Hkv=8, head 128) - GLM-4.7-Flash is MLA (deepseek2): 20 query heads over a single latent KV head, a
// 576-wide key (512 kv_lora_rank + 64 rope) and a 512-wide value, with the de-absorption done afterwards by
// `ggml_mul_mat(v_mla, reshape_4d(cur, 512, 1, 20, T))` (llama-graph.cpp:2442-2454).
//
// Usage: glm-mla-race <T> <cells> <visible> <reps> [seed] [device]
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "ggml.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <map>
#include <random>
#include <tuple>
#include <vector>

int main(int argc, char ** argv) {
    const int64_t kVK     = 576;   // latent key: kv_lora_rank 512 + rope 64
    const int64_t kVL     = 512;   // latent value = kv_lora_rank
    const int64_t kVHead  = 256;   // per-head value width after de-absorption
    const int64_t Hq      = 20;    // query heads
    const int64_t T       = argc > 1 ? atoll(argv[1]) : 190;
    const int64_t cells   = argc > 2 ? atoll(argv[2]) : 2048;
    const int64_t visible = argc > 3 ? atoll(argv[3]) : 810;
    const int     reps    = argc > 4 ? atoi(argv[4]) : 250;
    const int     seed    = argc > 5 ? atoi(argv[5]) : 1;

    std::mt19937                    rng(seed);
    std::normal_distribution<float> nd(0.0f, 1.0f);

    std::vector<ggml_fp16_t> mask(cells * T);
    for (int64_t r = 0; r < T; ++r) {
        const int64_t qp = visible - T + r;
        for (int64_t c = 0; c < cells; ++c) mask[r * cells + c] = ggml_fp32_to_fp16(c <= qp ? 0.0f : -INFINITY);
    }
    std::vector<float> q(kVK * Hq * T);
    for (float & x : q) x = 2.0f * nd(rng);
    std::vector<ggml_fp16_t> k(kVK * cells), v(kVL * cells);
    for (int64_t c = 0; c < cells; ++c) {
        for (int64_t i = 0; i < kVK; ++i) k[c * kVK + i] = ggml_fp32_to_fp16(c < visible ? nd(rng) : 0.0f);
        for (int64_t i = 0; i < kVL; ++i) v[c * kVL + i] = ggml_fp32_to_fp16(c < visible ? nd(rng) : 0.0f);
    }
    std::vector<float> vmla(kVL * kVHead);
    for (float & x : vmla) x = nd(rng);

    ggml_backend_load_all();
    ggml_backend_t be = ggml_backend_init_by_name(argc > 6 ? argv[6] : "HRX0", nullptr);
    if (!be) { fprintf(stderr, "no backend\n"); return 1; }

    ggml_init_params ip = { 64 * ggml_tensor_overhead() + ggml_graph_overhead(), nullptr, true };
    ggml_context * ctx = ggml_init(ip);

    ggml_tensor * tq   = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, kVK, Hq, T);
    ggml_tensor * tk   = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, kVK, 1, cells);
    ggml_tensor * tv   = ggml_new_tensor_3d(ctx, GGML_TYPE_F16, kVL, 1, cells);
    ggml_tensor * tm   = ggml_new_tensor_2d(ctx, GGML_TYPE_F16, cells, T);
    ggml_tensor * wv   = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, kVL, kVHead);

    ggml_tensor * kv = ggml_view_3d(ctx, tk, kVK, cells, 1, tk->nb[2], tk->nb[1], 0);
    ggml_tensor * vv = ggml_view_3d(ctx, tv, kVL, cells, 1, tv->nb[2], tv->nb[1], 0);
    ggml_tensor * fa = ggml_flash_attn_ext(ctx, ggml_permute(ctx, tq, 0, 2, 1, 3), kv, vv, tm,
                                          1.0f / std::sqrt((float) kVK), 0.0f, 0.0f);
    ggml_flash_attn_ext_set_prec(fa, GGML_PREC_F32);
    // MLA de-absorption, exactly as llama-graph.cpp does it for deepseek2/GLM
    ggml_tensor * cur = ggml_reshape_4d(ctx, fa, kVL, 1, Hq, T);
    ggml_tensor * abs = ggml_mul_mat(ctx, wv, cur);
    ggml_tensor * out = ggml_reshape_2d(ctx, abs, kVHead * Hq, T);

    ggml_cgraph * gf = ggml_new_graph(ctx);
    ggml_build_forward_expand(gf, out);
    ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors(ctx, be);
    if (buf == nullptr) { fprintf(stderr, "alloc failed\n"); return 1; }

    ggml_backend_tensor_set(tq, q.data(), 0, ggml_nbytes(tq));
    ggml_backend_tensor_set(tk, k.data(), 0, ggml_nbytes(tk));
    ggml_backend_tensor_set(tv, v.data(), 0, ggml_nbytes(tv));
    ggml_backend_tensor_set(tm, mask.data(), 0, ggml_nbytes(tm));
    ggml_backend_tensor_set(wv, vmla.data(), 0, ggml_nbytes(wv));

    std::vector<float> ref, o(ggml_nelements(out));
    int                bad_runs = 0;
    for (int r = 0; r < reps; ++r) {
        if (ggml_backend_graph_compute(be, gf) != GGML_STATUS_SUCCESS) { fprintf(stderr, "compute failed\n"); return 1; }
        ggml_backend_tensor_get(out, o.data(), 0, o.size() * sizeof(float));
        if (r == 0) {
            ref = o;
            double cs = 0;
            for (float x : o) cs += x;
            printf("checksum %.6f\n", cs);
            continue;
        }
        std::map<std::tuple<int64_t, int64_t, int64_t>, int> groups;
        int n = 0, nn = 0;
        for (size_t i = 0; i < o.size(); ++i) {
            if (memcmp(&o[i], &ref[i], sizeof(float)) == 0) continue;
            ++n;
            if (!std::isfinite(o[i])) ++nn;
            const int64_t tok = i / (kVHead * Hq);
            const int64_t ch  = i % kVHead;
            const int64_t hd  = (i / kVHead) % Hq;
            ++groups[{tok, hd, ch / 16}];
        }
        if (n != 0) {
            ++bad_runs;
            printf("run %d: %d differ (%d nonfinite):", r, n, nn);
            int shown = 0;
            for (const auto & g : groups) {
                if (shown++ == 3) break;
                printf(" [tok %lld head %lld ch %lld..%lld: %d]", (long long) std::get<0>(g.first),
                       (long long) std::get<1>(g.first), (long long) std::get<2>(g.first) * 16,
                       (long long) std::get<2>(g.first) * 16 + 15, g.second);
            }
            printf("\n");
        }
    }
    printf("T=%lld cells=%lld visible=%lld reps=%d bad_runs=%d\n", (long long) T, (long long) cells,
           (long long) visible, reps, bad_runs);
    ggml_backend_buffer_free(buf);
    ggml_free(ctx);
    return bad_runs != 0 ? 2 : 0;
}
Eviction Counting Logic

The tool 315-evict-per-arm.py counts evictions per arm window. If the logic for determining the window boundaries or the fault time is flawed, it could lead to incorrect conclusions about the eviction patterns and their correlation with faults.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""engine#315: per-arm eviction counts, faulting vs clean - the H2 discriminating test.

WHY THIS TOOL EXISTS. The mechanism candidate (H2) is that a wave preempted mid-execution has
its buffers evicted underneath it. Its discriminating prediction is: **faulting arms show more
evictions in their own arm window than clean arms at the same GTT**.

That test was attempted on run 7's existing data and found INVALID (see
evidence/315-pid-capture.md): an arm server keeps being evicted after its arm ends, so its total
is a function of post-arm survival, and the long-lived neighbours cannot be told apart from arm
servers after the fact. It therefore REQUIRES the per-arm PID captured at arm start, which the
driver now writes to $O/server.pid.

HOW THE WINDOW IS BOUNDED. For each arm:
  start = that PID's PROC_START boot_ns in the KFD SMI stream
  end   = that PID's PROC_END, or the next arm's PROC_START, whichever comes first
Only Q_EVICT rows for THAT pid inside THAT window are counted. This is what makes the count
attributable to the arm rather than to the process's whole life.

THE CONFOUND, AND WHY THERE IS ALSO A PRE-FAULT COUNT. A whole-window total cannot tell
"more evictions caused the fault" from "the fault caused more evictions": a faulting arm's server
crashes, may be retried, and lives on after the failure, so its window can simply be longer. The
fix is to count evictions in the window only up to the moment the fault actually happened, which
the fault cannot have caused. server.log timestamps the fault line, e.g.

    0.07.279.709 E common_sampler_sample: HRX returned NaN logits: ...

in minutes.seconds.milliseconds.microseconds, i.e. 7.28 s into the arm (the `pre-fault` column).
Both counts are printed: `pre-fault` is the causal test, `window` is kept for continuity with the
earlier analysis and because a large gap between them is itself informative.

    ./315-evict-per-arm.py <outdir> <console.log> --smi <smi.tsv> [--tag TAG] [--gate 95]

<outdir> is the driver's arm root (e.g. ~/wt/rt-det), and each arm directory must contain
server.pid (written by 315-paired-pidcap.sh) and detector.json.
"""
import argparse
import glob
import json
import os
import re
import sys

# `0.07.279.709 E common_sampler_sample: HRX returned NaN logits` -> the fault time.
# Fields are minutes.seconds.milliseconds.microseconds (verified against arm req counts and
# against the listening-on-http line landing ~5.6 s in).
TS = re.compile(r"^(\d+)\.(\d+)\.(\d+)\.(\d+)\s")
# BOTH faces must be matched, or a Face-B arm looks like it has no recoverable fault time.
# Face A: the HRX NaN logits line.  Face B: the chat-parse failure that surfaces as HTTP 500
# ("unparsed Content-only output"). Whichever comes first in the log wins, which is the first
# fault the arm actually suffered.
FAULT = re.compile(r"HRX returned NaN logits|NaN logits|unparsed Content-only|"
                   r"does not match the expected")


def fault_time_s(dirpath):
    """Seconds from arm start to the first recorded fault, or None if none is timestamped.

    Returns (seconds, raw) so the caller can show what it matched rather than trusting a number.
    """
    path = os.path.join(dirpath, "server.log")
    if not os.path.exists(path):
        return None, None
    with open(path, errors="replace") as fh:
        for line in fh:
            if not FAULT.search(line):
                continue
            m = TS.match(line)
            if not m:
                return None, line.strip()[:120]
            mi, s, ms, us = (int(g) for g in m.groups())
            return mi * 60 + s + ms / 1e3 + us / 1e6, line.strip()[:120]
    return None, None


def load_smi(path):
    """Return {pid: (start_ns, end_ns)} for llama-server, and a list of Q_EVICT rows."""
    procs, evicts = {}, []
    with open(path, errors="replace") as fh:
        for line in fh:
            if line.startswith("#"):
                continue
            p = line.rstrip("\n").split("\t")
            if len(p) < 5:
                continue
            try:
                ns, pid = int(p[0]), int(p[4])
            except ValueError:
                continue
            ev = p[2]
            if ev == "PROC_START":
                procs[pid] = [ns, None]
            elif ev == "PROC_END" and pid in procs:
                procs[pid][1] = ns
            elif ev == "Q_EVICT":
                evicts.append((ns, pid))
    return procs, evicts


def verdicts(console, gate):
    """{pair,cell -> (verdict, gtt)} from the console's per-arm lines."""
    out = {}
    pat = re.compile(r"pair\s+(\d+)\s+arm\s+([cl]):\s+(OK|FAULT|OOR|INVALID).*?gtt_start=(\d+)G")
    for line in open(console, errors="replace"):
        m = pat.search(line)
        if m:
            out[(int(m.group(1)), m.group(2))] = (m.group(3), int(m.group(4)))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("outdir")
    ap.add_argument("console")
    ap.add_argument("--smi", required=True)
    ap.add_argument("--gate", type=int, default=95)
    ap.add_argument("--tag", default="",
                    help="restrict to arm dirs for one campaign tag (strongly recommended: "
                         "the arm root holds every past run, and mixing tags mixes recipes)")
    a = ap.parse_args()

    pat = f"{a.tag}-p[0-9]*[cl]-*" if a.tag else "*-p[0-9]*[cl]-*"
    dirs = sorted(glob.glob(os.path.join(a.outdir, pat)))
    if not dirs:
        print(f"no arm directories under {a.outdir}", file=sys.stderr)
        return 1

    procs, evicts = load_smi(a.smi)
    verd = verdicts(a.console, a.gate)

    # Order arms by their PID's PROC_START so the window can be bounded by the next arm.
    arms = []
    for d in dirs:
        pidf = os.path.join(d, "server.pid")
        if not os.path.exists(pidf):
            arms.append((d, None, None))
            continue
        try:
            pid = int(open(pidf).read().split()[0])
        except (ValueError, IndexError):
            arms.append((d, None, None))
            continue
        st, en = procs.get(pid, (None, None))
        arms.append((d, pid, st))
    arms.sort(key=lambda t: (t[2] is None, t[2] or 0))

    rows = []
    for i, (d, pid, st) in enumerate(arms):
        base = os.path.basename(d)
        m = re.search(r"-p(\d+)([cl])-", base)
        key = (int(m.group(1)), m.group(2)) if m else None
        v, gtt = verd.get(key, ("?", 0))
        if pid is None or st is None:
            rows.append(dict(arm=base, pid=pid, n=None, verdict=v, gtt=gtt, note="no PID captured"))
            continue
        # window end: this pid's PROC_END, else the next arm's start
        en = procs[pid][1]
        if en is None:
            nxt = next((s for (_, p2, s) in arms[i + 1:] if s and s > st), None)
            en = nxt if nxt else (max((ns for ns, _ in evicts), default=st) + 1)
        n = sum(1 for ns, ep in evicts if ep == pid and st <= ns < en)
        # pre-fault count: the causal test. A fault cannot cause evictions that precede it.
        fsec, raw = fault_time_s(d)
        pre = None
        if fsec is not None:
            dur = (en - st) / 1e9
            if fsec > dur + 1.0:
                note = f"fault time {fsec:.1f}s exceeds window {dur:.1f}s - NOT used"
                pre, fsec = None, None
            else:
                pre = sum(1 for ns, ep in evicts if ep == pid and st <= ns < st + int(fsec * 1e9))
                note = f"fault at {fsec:.1f}s"
        else:
            note = ""
        rows.append(dict(arm=base, pid=pid, n=n, pre=pre, fault_s=fsec, verdict=v, gtt=gtt,
                         note=note))

    print(f"{'arm':46} {'pid':>8} {'gtt':>4} {'verdict':>8} {'pre-fault':>9} {'window':>7}")
    for r in rows:
        n = "n/a" if r["n"] is None else str(r["n"])
        pre = "" if r.get("pre") is None else str(r["pre"])
        print(f"{r['arm'][:46]:46} {str(r['pid'] or '-'):>8} {r['gtt']:>3}G {r['verdict']:>8} "
              f"{pre:>9} {n:>7}" + (f"   {r['note']}" if r["note"] else ""))

    inreg = [r for r in rows if r["n"] is not None and r["gtt"] >= a.gate]
    fault = [r for r in inreg if r["verdict"] == "FAULT"]
    clean = [r for r in inreg if r["verdict"] == "OK"]
    print()
    if not inreg:
        print("no in-regime arms with a captured PID - the comparison cannot be made.")
        print("(apply the PID capture BEFORE the run: see evidence/315-pid-capture.md)")
        return 1
    for label, sel in (("FAULT", fault), ("clean", clean)):
        if sel:
            vals = sorted(r["n"] for r in sel)
            mean = sum(vals) / len(vals)
            print(f"  {label:5} n={len(sel):2}  evictions/arm: min={vals[0]} median={vals[len(vals)//2]} "
                  f"max={vals[-1]} mean={mean:.1f}")
    if fault and clean:
        fm = sum(r['n'] for r in fault) / len(fault)
        cm = sum(r['n'] for r in clean) / len(clean)
        print(f"\n  H2 prediction: faulting arms are evicted MORE than clean arms.")
        print(f"  window total, mean: faulting {fm:.1f} vs clean {cm:.1f}  ->  "
              f"{'CONSISTENT with H2' if fm > cm * 1.5 else 'NOT supportive (faulting <= 1.5x clean)'}")
        pf = [r for r in fault if r.get("pre") is not None]
        if pf:
            pfm = sum(r['pre'] for r in pf) / len(pf)
            pc = [r['pre'] for r in clean if r.get("pre") is None]
            print(f"  pre-fault, mean:    faulting {pfm:.1f} ({len(pf)} of {len(fault)} fault arms had a "
                  f"recoverable fault time)")
            print(f"  >>> the pre-fault figure is the causal test: a fault cannot cause evictions")
            print(f"      that precede it. Compare it against the clean arms' FULL windows")
            print(f"      (mean {cm:.1f}), since a clean arm has no fault to truncate at - it is a")
            print(f"      conservative comparison that favours NOT finding an effect.")
        else:
            print(f"  pre-fault: no fault arm had a recoverable fault time; only the confounded")
            print(f"  window total is available. Do not draw a causal conclusion from it.")
    else:
        print("\n  both a faulting and a clean in-regime arm are needed for the comparison.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
Fault Rate Calculation

The tool 315-rate.py computes the campaign rate and confidence intervals. If the reconciliation logic between console and detector data is not robust, it could lead to incorrect fault rate calculations and misinterpretation of the campaign results.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""engine#315: compute the campaign rate, exact CI and the power statement from a console.

Criterion 3 requires ">=60 arms, every arm inside the declared regime gate, zero faults across
both faces, reported with CI and an explicit power statement (60 clean arms => ~95% confidence
the true rate is <5%)". This produces exactly that, from the driver's own per-arm lines, so the
numbers cannot be transcribed by hand.

    ./315-rate.py <console.log> [--gate 95]

Reads lines of the form the arm driver writes:
  pair <N> arm <c|l>: <OK|FAULT|OOR|INVALID> nan=<n> req=<n> ret3=<n> parse=<n> gtt_start=<G>G ...

Counting rules, taken from the frozen pre-registration:
  * only arms with gtt_start >= <gate> count (out-of-regime arms are reported, never counted)
  * BOTH faces count as faults: Face A = nan>0, Face B = parse>0 or utf8>0
  * an arm that faults on either face is a fault; an arm with neither and verdict OK is clean
  * OOR and INVALID are neither clean nor faulted and are excluded from the rate

The console line is NOT sufficient on its own to certify zero faults: it carries nan=, req=,
parse= and utf8= but NOT the detector's http_failures or transport_failures. A Face-B fault that
surfaces as HTTP 500 therefore leaves no trace in the console and a console-only count would report
a FALSE clean arm on the very criterion it must certify. So when --det points at the arm root, every
arm's detector.json is read and the detector is treated as authoritative for faults: any arm the
console calls clean but the detector calls failed is counted as a fault and named "MISSED". An arm
with no detector.json is reported as unverifiable rather than assumed clean.
"""
import argparse
import json
import os
import re
import sys
from math import comb

LINE = re.compile(
    r"(?:pair\s+(\d+)\s+)?arm\s+([cl]):\s+(OK|FAULT|OOR|INVALID)\s+nan=(\d+)\s+req=(\d+)\s+"
    r"ret3=\d+\s+parse=(\d+)\s+gtt_start=(\d+)G(?:\s+utf8=(\d+))?"
)

ARM = re.compile(r"-p(\d+)([cl])-")

# detector fields that mean a failure; http_failures/transport_failures are the ones the
# console cannot see at all.
DET_FIELDS = (("parse_failures", "parse"), ("utf8_failures", "utf8"),
              ("http_failures", "http"), ("transport_failures", "transport"))


def detector_verdicts(arm_root, tag):
    """{(pair, cell): {parse,utf8,http,transport,failed,error}} for every arm dir present.

    Enumerates the whole arm root rather than sampling: a missed arm here is a missed fault.
    """
    out = {}
    if not arm_root or not os.path.isdir(arm_root):
        return out
    for name in sorted(os.listdir(arm_root)):
        if tag and not name.startswith(tag):
            continue
        m = ARM.search(name)
        if not m:
            continue
        key = (int(m.group(1)), m.group(2))
        path = os.path.join(arm_root, name, "detector.json")
        if not os.path.exists(path):
            out[key] = dict(error="no detector.json", failed=None)
            continue
        try:
            d = json.load(open(path))
        except Exception as e:
            out[key] = dict(error=f"unreadable: {e}", failed=None)
            continue
        rec = {short: int(d.get(field) or 0) for field, short in DET_FIELDS}
        rec["failed"] = any(rec[s] > 0 for _, s in DET_FIELDS) or d.get("first_failure") is not None
        rec["error"] = None
        out[key] = rec
    return out


def parse(path, gate):
    rows = []
    for line in open(path, errors="replace"):
        m = LINE.search(line)
        if not m:
            continue
        pair, cell, verdict, nan, req, parse, gtt, utf8 = m.groups()
        rows.append(dict(pair=int(pair) if pair else None, cell=cell, verdict=verdict,
                         nan=int(nan), req=int(req), parse=int(parse), gtt=int(gtt),
                         utf8=int(utf8 or 0)))
    in_reg = [r for r in rows if r["gtt"] >= gate]
    oor = [r for r in rows if r["gtt"] < gate]
    def is_fault(r):
        return r["nan"] > 0 or r["parse"] > 0 or r["utf8"] > 0
    clean = [r for r in in_reg if r["verdict"] == "OK" and not is_fault(r)]
    fault = [r for r in in_reg if is_fault(r) or r["verdict"] == "FAULT"]
    invalid = [r for r in in_reg if r["verdict"] == "INVALID" and not is_fault(r)]
    return rows, in_reg, oor, clean, fault, invalid


def reconcile(clean, fault, dets, tag):
    """Move arms the detector failed but the console passed from clean to fault.

    Returns (clean, fault, missed, unverified). The detector is authoritative: its http and
    transport failure counters exist only in detector.json, so the console is blind to them.
    """
    if not dets:
        return clean, fault, [], []
    missed, unverified, keep = [], [], []
    by_key = {(r["pair"], r["cell"]): r for r in clean}
    for key, r in by_key.items():
        d = dets.get(key)
        if d is None:
            unverified.append(r)
        elif d.get("failed") is True:
            missed.append((r, d))
        elif d.get("failed") is None:
            unverified.append(r)
        else:
            keep.append(r)
    keep = [r for r in clean if (r["pair"], r["cell"]) not in by_key or dets.get((r["pair"], r["cell"]), {}).get("failed") is False]
    return keep, fault + [r for r, _ in missed], missed, unverified


def cp_upper(k, n, alpha=0.05):
    """Exact Clopper-Pearson one-sided upper bound, by bisection (no scipy)."""
    if n == 0:
        return float("nan")
    if k == 0:
        return 1.0 - alpha ** (1.0 / n)
    lo, hi = 0.0, 1.0
    for _ in range(200):
        mid = (lo + hi) / 2
        tail = sum(comb(n, i) * mid ** i * (1 - mid) ** (n - i) for i in range(k + 1))
        if tail > alpha:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("console")
    ap.add_argument("--gate", type=int, default=95)
    ap.add_argument("--det", default=os.path.expanduser("~/wt/rt-det"),
                    help="arm root; each arm's detector.json is read and the detector is "
                         "treated as authoritative for faults. Pass '' to disable.")
    ap.add_argument("--tag", default="",
                    help="only reconcile arms whose directory name starts with this")
    a = ap.parse_args()
    rows, in_reg, oor, clean, fault, invalid = parse(a.console, a.gate)

    dets = detector_verdicts(a.det, a.tag) if a.det else {}
    clean, fault, missed, unverified = reconcile(clean, fault, dets, a.tag)

    print(f"console : {a.console}")
    print(f"gate    : gtt_start >= {a.gate} GiB   (the frozen pre-registration's gate)")
    print()
    print(f"  arms parsed          {len(rows)}")
    print(f"  in-regime            {len(in_reg)}")
    print(f"  out-of-regime (OOR)  {len(oor)}   reported, NOT counted")
    print(f"  clean                {len(clean)}")
    print(f"  FAULT                {len(fault)}")
    print(f"  INVALID              {len(invalid)}")
    if dets:
        print(f"  detector.json read   {len(dets)} arm(s) under {a.det}"
              f"{f' (tag {a.tag})' if a.tag else ''}")
        if missed:
            print(f"  !! MISSED BY CONSOLE  {len(missed)} arm(s) the console passed but the")
            print(f"     detector failed -- these are counted as faults (http/transport are not in the")
            print(f"     console line at all):")
            for r, d in missed[:10]:
                print(f"       pair {r['pair']} cell {r['cell']} "
                      f"http={d.get('http', 0)} transport={d.get('transport', 0)} "
                      f"parse={d.get('parse', 0)} utf8={d.get('utf8', 0)}")
        if unverified:
            print(f"  UNVERIFIED           {len(unverified)} clean arm(s) with no usable")
            print(f"     detector.json -- reported as clean from the console alone; NOT certified")
    else:
        print("  WARNING: no detector.json read (--det disabled or root absent); a Face-B fault")
        print("  surfacing as HTTP 500 is invisible to the console and would be counted CLEAN.")
    print()

    n, k = len(clean) + len(fault), len(fault)
    if n == 0:
        print("rate: undefined (no in-regime scored arms)")
        return 1

    faces_a = [r for r in fault if r["nan"] > 0]
    faces_b = [r for r in fault if r["parse"] > 0 or r["utf8"] > 0]
    unattr = [r for r in fault if not (r["nan"] > 0 or r["parse"] > 0 or r["utf8"] > 0)]

    print(f"  rate                 {k}/{n} = {100.0*k/n:.2f}%")
    if k == 0:
        ub = cp_upper(0, n)
        print(f"  exact 95% upper CI   {100*ub:.2f}%   (Clopper-Pearson, one-sided)")
        print(f"  rule of three (3/n)  {100*3.0/n:.2f}%   (approximation; the exact value is above)")
        print(f"  P(0 faults | 5%)     {(0.95)**n:.4f}")
        print()
        if n >= 60:
            print(f"  POWER STATEMENT: {n} clean in-regime arms with zero faults on either face gives")
            print(f"  ~95% confidence the true fault rate is below {100*3.0/n:.1f}% (rule of three).")
            print(f"  Criterion 3's bar (>=60 arms) is {'MET' if n >= 60 else 'NOT met'}.")
        else:
            print(f"  POWER STATEMENT: {n} clean arms is BELOW the pre-registered 60-arm bar.")
            print(f"  The upper bound does not yet reach the ~5% target (it is {100*ub:.1f}%).")
    else:
        print(f"  exact 95% CI         [{100*cp_upper(k, n, 0.975)!r}, ...]  k>0: acceptance has FAILED")
        print(f"  ACCEPTANCE FAILS: {k} in-regime arm(s) faulted; the criterion is zero on BOTH faces.")
    print()
    print(f"  face tally           FaceA(nan)={len(faces_a)}  FaceB(parse/utf8)={len(faces_b)}"
          f"  unattributed={len(unattr)}")
    for r in fault[:10]:
        f = []
        if r["nan"] > 0:
            f.append(f"FaceA nan={r['nan']}")
        if r["parse"] > 0 or r["utf8"] > 0:
            f.append(f"FaceB parse={r['parse']} utf8={r['utf8']}")
        print(f"    fault: cell {r['cell']} gtt_start={r['gtt']}G req={r['req']} {' '.join(f) or 'see server log'}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
Classification Rule Consistency

The tool 315-analyse.py applies the pre-registered classification rules. If the classification logic is inconsistent with the pre-registered rules, it could lead to incorrect categorization of arms and affect the validity of the campaign's acceptance criteria.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""engine#315 pre-registered analyser.

Reads the campaign console produced by `315-paired.sh` and applies the classification fixed in
`docs/315-preregistration.md` — which differs from `issue-315-analysis.py` in one decisive way:

    Face B (invalid UTF-8 / JSON parse failure) is a FAULT face, not "harness-side truncation".
    The issue's own record characterises invalid-UTF-8 output as the second real defect, and
    "zero NaN" alone was explicitly ruled out as an acceptance result.

Console line grammar (produced by 315-paired.sh; the existing script's regex also matches it):

    pair <N> arm <c|l>: <verdict> nan=<n> req=<n> ret3=<n> parse=<n> gtt_start=<G>G utf8=<n> alloc=<n>

Classification:
    invalid        alloc>0, verdict INVALID, or the request phase produced nothing (req==0)
    out-of-regime  gtt_start < 95 GiB (gate) or > 110 GiB (invalid-upper bound)
    fault          nan>0 or hsa>0 or parse>0 or utf8>0 or idn>1 or verdict in {FAULT,TRUNCATED} or req<66
    clean          otherwise

Usage: 315-analyse.py <console> [<console>...] [--baseline-a 2/37] [--baseline-b 1/25]
Exit status 0 only if the acceptance criterion is met: >=60 in-regime clean arms in every
non-control cell AND zero faults among the in-regime arms.
"""
from __future__ import annotations

import math
import random
import re
import sys
from math import comb

ARM = re.compile(
    r"^\s*pair\s+(\d+)\s+arm\s+([cl]):\s+(\S+)\s+nan=(\d+)\s+req=(\d+)\s+ret3=(\d+)\s+parse=(\d+)"
    r"\s+gtt_start=(\d+)G(?:\s+utf8=(\d+))?(?:\s+alloc=(\d+))?(?:\s+idn=(\d+))?")
GATE = 95          # GiB, pre-registered
UPPER = 110        # GiB, above this the detector fails to allocate (invalid, not faulted)
CELL_NAME = {"c": "control", "l": "fix"}
SEED = 20261007


def parse(path):
    arms = []
    with open(path, errors="replace") as fh:
        for line in fh:
            m = ARM.match(line)
            if not m:
                continue
            pair, cell, verdict, nan, req, ret3, parse_, gtt, utf8, alloc, idn = m.groups()
            arms.append(dict(pair=int(pair), cell=cell, verdict=verdict, nan=int(nan), req=int(req),
                             parse=int(parse_), gtt=int(gtt), utf8=int(utf8 or 0),
                             alloc=int(alloc or 0),
                             # no idn= field (a console written before the 2026-10-10 freeze note) reads as
                             # 1, i.e. no signal, so historical consoles keep their classification
                             idn=int(idn if idn is not None else 1)))
    return arms


def classify(a):
    """Pre-registered classification. Order matters: invalid, then regime, then fault, then clean."""
    if a["alloc"] > 0 or a["verdict"] == "INVALID" or a["req"] == 0:
        return "invalid"
    if a["gtt"] < GATE or a["gtt"] > UPPER:
        return "oor"
    if (a["nan"] > 0 or a["verdict"] in ("FAULT", "TRUNCATED")
            or a["parse"] > 0 or a["utf8"] > 0 or a["idn"] > 1 or a["req"] < 66):
        return "fault"
    return "clean"


def classify_old_rule(a):
    """The recorded study's rule, for comparability: Face B counted as harness-side, not faulted."""
    if a["nan"] > 0:
        return "fault"
    if a["verdict"] == "TRUNCATED" or a["req"] < 66 or a["parse"] > 0 or a["utf8"] > 0:
        return "trunc"
    return "clean"


def wilson(k, n, z=1.96):
    if n == 0:
        return (0.0, 0.0)
    p = k / n
    d = 1 + z * z / n
    c = (p + z * z / (2 * n)) / d
    h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
    return (max(0.0, c - h), min(1.0, c + h))


def rule_of_three(n):
    """95% upper bound on the rate when 0 events are observed in n trials (capped at certainty)."""
    return min(1.0, 3.0 / n) if n else 1.0


def fisher_two_sided(a, nA, b, nB):
    N, K = nA + nB, a + b
    if K == 0 or K == N:
        return 1.0

    def prob(x):
        if x < 0 or K - x < 0 or x > nA or K - x > nB:
            return 0.0
        return comb(nA, x) * comb(nB, K - x) / comb(N, K)

    p0, tot = prob(a), 0.0
    for x in range(max(0, K - nB), min(nA, K) + 1):
        p = prob(x)
        if p <= p0 + 1e-12:
            tot += p
    return min(1.0, tot)


def p_rate_a_below_b(a, nA, b, nB, draws=200000):
    random.seed(SEED)
    hit = 0
    for _ in range(draws):
        if random.betavariate(1 + a, 1 + nA - a) < random.betavariate(1 + b, 1 + nB - b):
            hit += 1
    return hit / draws


def main(argv):
    paths = [a for a in argv if not a.startswith("--")]
    base_a, base_b = (2, 37), (1, 25)
    for arg in argv:
        if arg.startswith("--baseline-a"):
            base_a = tuple(int(x) for x in arg.split("=")[1].split("/"))
        if arg.startswith("--baseline-b"):
            base_b = tuple(int(x) for x in arg.split("=")[1].split("/"))

    arms = [a for p in paths for a in parse(p)]
    if not arms:
        print("no arms parsed — check the console path and the line grammar")
        return 2

    print(f"arms parsed: {len(arms)} from {len(paths)} console(s)\n")
    cells = {}
    for cell in sorted({a["cell"] for a in arms}):
        mine = [a for a in arms if a["cell"] == cell]
        counts = {"invalid": 0, "oor": 0, "fault": 0, "clean": 0}
        old = {"fault": 0, "trunc": 0, "clean": 0}
        for a in mine:
            counts[classify(a)] += 1
            old[classify_old_rule(a)] += 1
        inreg = counts["clean"] + counts["fault"]
        lo, hi = wilson(counts["fault"], inreg) if inreg else (0.0, 1.0)
        cells[cell] = dict(total=len(mine), inreg=inreg, **counts)
        print(f"cell {CELL_NAME.get(cell, cell)} ({cell}): scheduled={len(mine)} "
              f"in-regime={inreg} clean={counts['clean']} fault={counts['fault']} "
              f"invalid={counts['invalid']} out-of-regime={counts['oor']}")
        if inreg:
            rate = 100.0 * counts["fault"] / inreg
            print(f"    fault rate {counts['fault']}/{inreg} = {rate:.1f}%  95% CI {100*lo:.1f}-{100*hi:.1f}%")
        if counts["clean"]:
            ub = 100.0 * rule_of_three(counts["clean"])
            print(f"    if clean count stands: 95% upper bound on the true rate = {ub:.1f}% "
                  f"(rule of three over {counts['clean']} clean arms)")
        print(f"    under the recorded study's rule (Face B = harness-side): "
              f"clean={old['clean']} fault={old['fault']} trunc={old['trunc']}")

    if "c" in cells and "l" in cells:
        c, l = cells["c"], cells["l"]
        p = fisher_two_sided(c["fault"], c["inreg"] or 1, l["fault"], l["inreg"] or 1)
        pb = p_rate_a_below_b(c["fault"], c["inreg"] or 1, l["fault"], l["inreg"] or 1)
        print(f"\ncontrol vs fix: Fisher exact two-sided p = {p:.3f}; "
              f"P(rate_control < rate_fix) = {pb:.3f}")
        print(f"recorded baseline for reference: A {base_a[0]}/{base_a[1]} "
              f"({100*base_a[0]/base_a[1]:.1f}%), B {base_b[0]}/{base_b[1]} "
              f"({100*base_b[0]/base_b[1]:.1f}%)")

    fix = cells.get("l") or cells.get("c")
    ok = fix["clean"] >= 60 and fix["fault"] == 0
    print("\nacceptance (fix cell): >=60 in-regime clean arms AND zero faults on both faces")
    print(f"  clean={fix['clean']} (need 60)   faults={fix['fault']} (need 0)   -> "
          f"{'PASS' if ok else 'NOT MET'}")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
Device Probe Patching

The patch script patch-device-producer-probe.py modifies graph-executor.cpp to add device mode support for the producer probe. If the patching logic is not idempotent or if anchors are not correctly matched, it could lead to compilation errors or incorrect behavior in the instrumented code.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Add the DEVICE-buffer producer probe to graph-executor.cpp, per
docs/315-campaign/evidence/315-device-buffer-probe-proposal.md.

Run on the box, inside the instrumented llama tree (the default is ~/wt/llama-315probe). Every anchor is
asserted to occur exactly once, so a silent no-op is impossible — the same discipline as tools/patch-*.py.

WHY A PATCH SCRIPT AND NOT JUST THE CODE: the change cannot be compile-tested here. This script verifies the
anchors and the idempotency marker, which are the parts that CAN be verified offline; that a build then
compiles is explicitly NOT established by running it. Do not report the instrument as working until a build
has succeeded and an arm has produced an `armed`/`anomaly` line.

WHAT IT CHANGES (3 functions, ~40 lines) and why each is needed:

  producer_probe_target   accept non-host tensors when GGML_HRX_PRODUCER_DEVICE is set, selected by an exact
                          row-multiple (bytes % 8192 == 0) so the residual family is chosen without needing T.
  producer_probe_fill     for a device target, upload a finite pattern from a host staging buffer with
                          ggml_backend_tensor_set. The existing raw node->data write is a HOST pointer; on a
                          device tensor it would write through a device address from the CPU. Also ARMS AT MOST
                          ONE TENSOR PER GRAPH, because that selector matches essentially every 2048-wide
                          activation and arming all of them would perturb far beyond the declared confound.
  producer_probe_scan     for a device target, download with ggml_backend_tensor_get after the drained
                          stream and classify the staging buffer. Same reason, on the read side.

The payload in device mode is FINITE (0xDEADBEEF), not the NaN sentinel: this probe fills a live layer input,
so a NaN fill would propagate and manufacture the very symptom under study.
"""
from __future__ import annotations

import pathlib
import sys

REL = "ggml/src/ggml-hrx/runtime/graph-executor.cpp"

MARKER = "GGML_HRX_PRODUCER_DEVICE"

A_TARGET_OLD = """bool producer_probe_target(const ggml_tensor * t) {
    if (t == nullptr || t->data == nullptr) return false;
    if (t->buffer == nullptr || !ggml_backend_buffer_is_host(t->buffer)) return false;
"""

A_TARGET_NEW = """// engine#315: device mode. The host-only probe cannot reach a layer residual (hrx-producer prints host=0
// for every layer node), so this admits device tensors too. The payload is FINITE here, not the NaN
// sentinel: this fills a tensor that is also an op's input, so a NaN fill would propagate and manufacture
// the symptom under study.
bool producer_probe_device_enabled() {
    const char * v = std::getenv("GGML_HRX_PRODUCER_DEVICE");
    return v != nullptr && *v != '\\0' && *v != '0';
}

bool producer_probe_target(const ggml_tensor * t) {
    if (t == nullptr || t->data == nullptr) return false;
    if (producer_probe_device_enabled()) {
        // Exact row-multiple: an integer number of n_embd(2048)-wide rows, so the residual family is
        // selected without needing to know T. Verified against the graph: the layer residuals are the
        // device tensors whose byte size is an exact multiple of 8192.
        const size_t dbytes = ggml_nbytes(t);
        return dbytes >= 8192u && dbytes % 8192u == 0u;
    }
    if (t->buffer == nullptr || !ggml_backend_buffer_is_host(t->buffer)) return false;
"""

A_FILL_OLD = """        uint32_t * words = static_cast<uint32_t *>(node->data);
        const size_t n = ggml_nbytes(node) / sizeof(uint32_t);
        for (size_t w = 0; w < n; ++w) words[w] = kProbeSentinel;
"""

A_FILL_NEW = """        const size_t n = ggml_nbytes(node) / sizeof(uint32_t);
        if (producer_probe_device_enabled()) {
            // Device target: node->data is not CPU-addressable, so upload from a host staging buffer.
            static std::vector<uint32_t> staging;
            staging.assign(n, kProbeFinite);
            ggml_backend_tensor_set(const_cast<ggml_tensor *>(node), staging.data(), 0, ggml_nbytes(node));
            // ENGINE#315: ARM AT MOST ONE TENSOR PER GRAPH, and log it HERE rather than falling through to
            // the shared logging block below -- breaking before that block would suppress the `armed` line,
            // which the pre-registration's INVALID clause depends on. The device selector is "an exact number
            // of n_embd(2048)-wide rows", i.e. bytes % 8192 == 0, and since bytes = 8192 * T for every
            // 2048-wide activation it matches essentially ALL of them - several per 9-node chunk, every graph,
            // thousands of graphs per arm. Filling and re-downloading all of them each time is a far larger
            // cost and perturbation than the pre-registration declared, and it would make the run characterise
            // the probe rather than the fault. One tensor per graph keeps it bounded and deterministic
            // (the first match in node order), which is all the sentinel question needs.
            if (!armed_logged) {
                GGML_LOG_WARN("[hrx-producer] armed(device) op=%s name=%s bytes=%zu words=%zu\\n",
                              ggml_op_name(node->op), node->name, ggml_nbytes(node), n);
                armed_logged = true;
            }
            ++armed;
            break;
        }
        {
            uint32_t * words = static_cast<uint32_t *>(node->data);
            for (size_t w = 0; w < n; ++w) words[w] = kProbeSentinel;
        }
        // the host path falls through to the shared `armed` logging block below, unchanged
"""

A_SCAN_OLD = """        const float *  fp = static_cast<const float *>(node->data);
"""

A_SCAN_NEW = """        // Device target: download through the backend instead of dereferencing node->data, which is a
        // device address. The stream is already drained above, so this reads completed writes. NOTE: `n`
        // is declared AFTER this point in the original, so it must not be referenced here.
        static std::vector<float> down;
        const float *            fp = nullptr;
        if (producer_probe_device_enabled()) {
            const size_t dfloats = ggml_nbytes(node) / sizeof(float);
            down.assign(dfloats, 0.0f);
            ggml_backend_tensor_get(const_cast<ggml_tensor *>(node), down.data(), 0, ggml_nbytes(node));
            fp = down.data();
        } else {
            fp = static_cast<const float *>(node->data);
        }
"""

# The finite payload constant goes next to the existing NaN sentinel so the two are read together. The anchor
# includes the sentinel's TRAILING COMMENT deliberately: matching only the declaration prefix left that
# comment stranded on the end of the new line, which compiles but reads as a mangled double comment.
A_SENT_OLD = "constexpr uint32_t kProbeSentinel = 0x7FC0DEADu;  // payload NaN, distinguishable from a plain 0x7FC00000"
A_SENT_NEW = ("constexpr uint32_t kProbeSentinel = 0x7FC0DEADu;  // payload NaN, distinguishable from a plain 0x7FC00000\n"
              "constexpr uint32_t kProbeFinite   = 0xDEADBEEFu;  // engine#315 device mode: FINITE, never a NaN")


def apply(text: str, old: str, new: str, label: str) -> str:
    n = text.count(old)
    if n != 1:
        print(f"FAIL: anchor {label} found {n} times, expected 1")
        sys.exit(1)
    return text.replace(old, new)


def main() -> int:
    path = pathlib.Path(REL)
    if not path.exists():
        print(f"FAIL: {REL} not found; run from the instrumented tree root")
        return 1
    text = path.read_text()
    if MARKER in text:
        print("already patched")
        return 0
    # A pre-check on every anchor before any replacement, so a partial patch cannot be written.
    for old, label in ((A_SENT_OLD, "sentinel-const"), (A_TARGET_OLD, "target"),
                       (A_FILL_OLD, "fill"), (A_SCAN_OLD, "scan")):
        if text.count(old) != 1:
            print(f"FAIL: anchor {label} found {text.count(old)} times, expected 1 — nothing written")
            return 1
    text = apply(text, A_SENT_OLD, A_SENT_NEW, "sentinel-const")
    text = apply(text, A_TARGET_OLD, A_TARGET_NEW, "target")
    text = apply(text, A_FILL_OLD, A_FILL_NEW, "fill")
    text = apply(text, A_SCAN_OLD, A_SCAN_NEW, "scan")
    # Balance check: a cheap structural guard against a truncated or mis-spliced replacement. Also require
    # <vector> to be reachable, since the staging buffers use std::vector.
    if text.count("{") != text.count("}"):
        print(f"FAIL: brace imbalance after patch ({text.count('{')} vs {text.count('}')}) — nothing written")
        return 1
    if "#include <vector>" not in text and "<vector>" not in text.split("namespace")[0]:
        print("WARN: <vector> not found before the namespace; the patch needs it for the staging buffers.")
        print("      Add the include before building.")
    path.write_text(text)
    print(f"patched {path}")
    print(f"  device-enable branch: {text.count(MARKER)} occurrence(s)")
    print("  NOTE: this only proves the anchors applied and braces balance. It does NOT prove it compiles —")
    print("        build it before claiming the instrument works.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
Synchronization Instrument Patching

The patch script patch-id-instrument-sync.py modifies ggml-hrx.cpp to add synchronization support for the ID instrument. If the patching logic is not idempotent or if anchors are not correctly matched, it could lead to compilation errors or incorrect behavior in the instrumented code.

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# engine#315: the id probe reads an i32 tensor that, by construction, must hold ranks in [0, ne0) - and it
# returns float-shaped values instead (evidence: 315-idprobe-result.md). ggml_argsort allocates a FRESH i32
# tensor (ggml.c:5347) and ggml_argsort_top_k views it, so after the graph executes that buffer must hold
# ranks. It does not, in faulting or clean arms. Two candidate explanations, and they are separable:
#
#   (a) the read path returns memory that is not the tensor's contents. buffer_get does a plain memcpy and
#       RETURNS when the buffer is host-visible (context->base != GGML_HRX_FAKE_PTR_BASE); it never reaches
#       hrx_synchronous_d2h. If that mapping is non-coherent, the memcpy can return a stale or reused
#       occupant - which is exactly what "float probabilities in an i32 rank tensor" looks like.
#   (b) the argsort op did not write that buffer at all.
#
# This patch separates them by reading the SAME tensor twice, in the same line of output: once the way the
# probe has been reading it (plain memcpy) and once through hrx_synchronous_d2h, which is the synchronising
# path buffer_get skips for host-visible buffers. Both reads are printed, tagged `hrx-ids-fp` (unchanged, so
# prior logs stay comparable) and `hrx-ids-sync` (new).
#
# Readout, fixed here before the run:
#   - memcpy floats and sync ranks in [0, ne0)  -> (a) confirmed: the read path was the defect, the tensor is
#                                                  fine, and the id family becomes testable.
#   - both float-shaped                         -> (b): the argsort output genuinely is not in that buffer.
#   - both ranks                                -> the earlier float reading did not reproduce; the probe is
#                                                  then re-read against this run only.
#
# Diagnostic only: no criterion changes, no arm from it is eligible.
#
# Idempotent: refuses to apply twice.
import pathlib
import sys

SRC = pathlib.Path.home() / "wt/llama-315copy/ggml/src/ggml-hrx/ggml-hrx.cpp"

REPORT_HELPER = r'''
// engine#315: print the shape of an i32 index list - min/max, how many entries fall outside [0, ne0), and how
// many repeat within a row. Shared by the plain-memcpy and the synchronising read so the two lines are
// computed identically and can be compared directly.
static void hrx_ids_report(const char * tag, int call, const char * name, size_t ibytes, int64_t ine0,
                           const int32_t * ids) {
    const size_t icount = ibytes / sizeof(int32_t);
    const size_t irows  = ine0 > 0 ? icount / static_cast<size_t>(ine0) : 0;
    size_t       oor = 0, dup = 0;
    int32_t      imin = 0, imax = 0;
    for (size_t j = 0; j < icount; ++j) {
        const int32_t v = ids[j];
        if (j == 0 || v < imin) { imin = v; }
        if (j == 0 || v > imax) { imax = v; }
        if (v < 0 || v >= static_cast<int32_t>(ine0)) { ++oor; }
    }
    for (size_t r = 0; r < irows; ++r) {
        for (size_t a = 0; a < static_cast<size_t>(ine0); ++a) {
            for (size_t b = a + 1; b < static_cast<size_t>(ine0); ++b) {
                if (ids[r * static_cast<size_t>(ine0) + a] == ids[r * static_cast<size_t>(ine0) + b]) { ++dup; }
            }
        }
    }
    std::fprintf(stderr,
                 "[%s] call=%d name=%s bytes=%zu count=%zu ne0=%lld rows=%zu "
                 "min=%d max=%d oor=%zu dup_pairs=%zu first8=[",
                 tag, call, name, ibytes, icount, (long long) ine0, irows, imin, imax, oor, dup);
    for (size_t j = 0; j < icount && j < 8; ++j) {
        std::fprintf(stderr, "%s%d", j == 0 ? "" : " ", (int) ids[j]);
    }
    std::fprintf(stderr, "]\n");
    std::fflush(stderr);
}
'''

HERO_ANCHOR = "static bool hrx_fp_name_listed("

OLD_BLOCK = '''                        const size_t         ibytes = ggml_nbytes(node);
                        std::vector<uint8_t> ihost(ibytes);
                        ggml_backend_tensor_get(node, ihost.data(), 0, ibytes);
                        const int32_t * ids = reinterpret_cast<const int32_t *>(ihost.data());
                        const size_t    icount = ibytes / sizeof(int32_t);
                        const int64_t   ine0   = node->ne[0] > 0 ? node->ne[0] : 1;
                        const size_t    irows  = ine0 > 0 ? icount / static_cast<size_t>(ine0) : 0;
                        size_t          oor = 0, dup = 0;
                        int32_t         imin = 0, imax = 0;
                        for (size_t j = 0; j < icount; ++j) {
                            const int32_t v = ids[j];
                            if (j == 0 || v < imin) { imin = v; }
                            if (j == 0 || v > imax) { imax = v; }
                            if (v < 0 || v >= static_cast<int32_t>(ine0)) { ++oor; }
                        }
                        for (size_t r = 0; r < irows; ++r) {
                            for (size_t a = 0; a < static_cast<size_t>(ine0); ++a) {
                                for (size_t b = a + 1; b < static_cast<size_t>(ine0); ++b) {
                                    if (ids[r * static_cast<size_t>(ine0) + a] == ids[r * static_cast<size_t>(ine0) + b]) { ++dup; }
                                }
                            }
                        }
                        std::fprintf(stderr,
                                     "[hrx-ids-fp] call=%d name=%s bytes=%zu count=%zu ne0=%lld rows=%zu "
                                     "min=%d max=%d oor=%zu dup_pairs=%zu first8=[",
                                     fp_calls, node->name, ibytes, icount, (long long) ine0, irows, imin, imax, oor, dup);
                        for (size_t j = 0; j < icount && j < 8; ++j) {
                            std::fprintf(stderr, "%s%d", j == 0 ? "" : " ", (int) ids[j]);
                        }
                        std::fprintf(stderr, "]\\n");
                        std::fflush(stderr);
                        continue;'''

NEW_BLOCK = '''                        const size_t ibytes = ggml_nbytes(node);
                        const int64_t ine0  = node->ne[0] > 0 ? node->ne[0] : 1;

                        // (1) the read the probe has always done: plain memcpy for a host-visible buffer.
                        std::vector<uint8_t> ihost(ibytes);
                        ggml_backend_tensor_get(node, ihost.data(), 0, ibytes);
                        hrx_ids_report("hrx-ids-fp", fp_calls, node->name, ibytes, ine0,
                                       reinterpret_cast<const int32_t *>(ihost.data()));

                        // (2) the same tensor through the synchronising path that buffer_get skips for a
                        // host-visible buffer. If (1) and (2) disagree, the read path is what (1) reported.
                        ggml_backend_buffer_t node_buffer =
                            node->view_src != nullptr ? node->view_src->buffer : node->buffer;
                        if (node_buffer != nullptr) {
                            auto *       nctx = buffer_context(node_buffer);
                            const size_t noff = tensor_offset(nctx, node);
                            std::vector<uint8_t> isync(ibytes);
                            if (HRX_CHECK(hrx_synchronous_d2h(nctx->device->device, nctx->buffer, noff,
                                                              isync.data(), ibytes))) {
                                hrx_ids_report("hrx-ids-sync", fp_calls, node->name, ibytes, ine0,
                                               reinterpret_cast<const int32_t *>(isync.data()));
                            }
                        }
                        continue;'''


def main() -> int:
    if not SRC.exists():
        print(f"missing {SRC}", file=sys.stderr)
        return 2
    text = SRC.read_text()
    if "hrx-ids-sync" in text:
        print("already applied (hrx-ids-sync present)")
        return 0
    if OLD_BLOCK not in text:
        print("anchor block not found - the id instrument is not in the expected state", file=sys.stderr)
        return 3
    if HERO_ANCHOR not in text:
        print("helper anchor not found", file=sys.stderr)
        return 4
    text = text.replace(HERO_ANCHOR, REPORT_HELPER + "\n" + HERO_ANCHOR, 1)
    text = text.replace(OLD_BLOCK, NEW_BLOCK, 1)
    SRC.write_text(text)
    print(f"patched {SRC}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

⚠️ Review coverage: The following files were not included in this review because of the token budget:

  • docs/315-campaign/tools/test-analyse.py
  • docs/315-campaign/315-detector.py
  • docs/315-campaign/tools/patch-f32-read-twice-control.py
  • docs/315-campaign/315-wbfp-read.py
  • docs/315-campaign/tools/315-lever-check.py
  • docs/315-campaign/tools/patch-sync-between-reads.py
  • docs/315-campaign/tools/row-readout.py
  • docs/315-campaign/tools/patch-writeback-read-probe.py
  • docs/315-campaign/tools/patch-fp-wavemask.py
  • docs/315-campaign/tools/audit-binding-access.py
  • docs/315-campaign/tools/patch-staging-coherence-ab.py
  • docs/315-campaign/tools/row-position-census-by-family.py
  • docs/315-campaign/tools/fa-variant-profile.py
  • docs/315-campaign/tools/scan-global-handoffs.py
  • docs/315-campaign/tools/arm-pid.py
  • docs/315-campaign/tools/gen-nan-dump.py
  • docs/315-campaign/tools/patch-sync-dose.py
  • docs/315-campaign/tools/row-position-census.py
  • docs/315-campaign/tools/gord-analysis.py
  • docs/315-campaign/315-classify.py
  • docs/315-campaign/tools/patch-fp-sync.py
  • docs/315-campaign/tools/lever-census.py
  • tools/copyright.py
  • docs/315-campaign/315-paired.sh
  • docs/315-campaign/315-evict-trace.sh
  • docs/315-campaign/315-campaign.sh
  • docs/315-campaign/315-regression.sh
  • docs/315-campaign/315-instr-capture.sh
  • docs/315-campaign/315-fp2.sh
  • docs/315-campaign/315-idprobe.sh
  • docs/315-campaign/315-forcebarrier.sh
  • docs/315-campaign/315-dose.sh
  • docs/315-campaign/315-regime.sh
  • docs/315-campaign/tools/verify-evidence.sh
  • docs/315-campaign/315-differential.sh
  • docs/315-campaign/315-mode.sh
  • docs/315-campaign/315-cwsr-control.sh
  • docs/315-campaign/315-trace-premise.sh
  • docs/315-campaign/315-rowprobe.sh
  • docs/315-campaign/315-cheap-probe.sh
  • docs/315-campaign/315-instr-build.sh
  • docs/315-campaign/315-graphsync.sh
  • docs/315-campaign/315-faceb.sh
  • docs/315-campaign/315-chain2.sh
  • docs/315-campaign/315-fix-build.sh
  • docs/315-campaign/315-attrib.sh
  • docs/315-campaign/315-cell-build.sh
  • docs/315-campaign/315-fp-hunt.sh
  • docs/315-campaign/315-when-free.sh
  • docs/315-campaign/tools/fa-sweep.sh
    ... and 194 more

@bong-water-water-bong
bong-water-water-bong merged commit 99f0322 into main Oct 16, 2026
7 checks passed
@bong-water-water-bong
bong-water-water-bong deleted the 1bit/315-record branch October 16, 2026 09:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant