diff --git a/mk/replay.mk b/mk/replay.mk new file mode 100644 index 000000000..6cfcac82d --- /dev/null +++ b/mk/replay.mk @@ -0,0 +1,80 @@ +# Lane LD (hardening): independent transcript verifier + World replayer. +# New files only: tools/replay/, tests/replay/, this file. Host only, CPU, +# no GPU. Picked up by the shared Makefile's `-include mk/*.mk`; also runs +# alone with `make -f mk/replay.mk test-replay`. +# +# test-replay build, then tests/replay/run_replay_suite.sh: record a +# World run, replay it from its log (1 and 4 workers), +# negative controls, the mutation suites (World crumb log +# and M22 dispatch.log), the causal-order 4-worker gate and +# its mutants (tools/replay/CAUSAL_ORDER.md; strict 4-worker +# sequence checks reported as non-gating KNOWN_FAIL, runtime +# finding I11), host-labelled receipt +# replay-asan the same suite with ASan/UBSan builds +# replay-purity the verifier links nothing from src/runtime or src/train +# +# The verifier (rx_replay) is built from tools/replay/rx_replay.c, +# tools/replay/rxlog.c and src/sha256.c only. +ifndef REPLAY_MK +REPLAY_MK := 1 +CC ?= gcc +OUT_DIR ?= build +PHYSICS_DIR ?= ../physics +# nvrm.h (via omega_evidence.h) lives in the physics repo; empty = world replay NOT_RUN +REPLAY_NVRM_H := $(wildcard $(PHYSICS_DIR)/nvrm/nvrm.h) +REPLAY_NVRM_INC = -I$(PHYSICS_DIR)/nvrm +.PHONY: replay-run test-replay replay-asan replay-purity replay-tools +REPLAY_DIR = $(OUT_DIR)/replay +# TRN1 shared corpus (aien-protocols specs/execution-transcript/vectors); empty = NOT_RUN +TRN1_VECTORS ?= +REPLAY_CFLAGS = -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -O2 -Isrc -Itools +REPLAY_SAN = -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all +REPLAY_VERIFIER_SRCS = tools/replay/rx_replay.c tools/replay/rxlog.c tools/replay/trn1.c src/sha256.c +REPLAY_MUTATE_SRCS = tools/replay/rxlog_mutate.c tools/replay/rxlog.c src/sha256.c +REPLAY_WORLD_SRCS = tests/replay/rx_world_replay.c tools/replay/rx_crumb_export.c tools/replay/rxlog.c \ + src/runtime/rx_caproot.c src/runtime/rx_world.c src/runtime/rx_coherent.c src/sha256.c src/omega_evidence.c +REPLAY_M22_SRCS = tests/replay/m22_dispatch_run.c src/train/tg_store.c src/train/tg_sgd.c src/sha256.c +REPLAY_HDRS = tools/replay/rxlog.h tools/replay/trn1.h tools/replay/rx_crumb_export.h src/runtime/rx_world.h \ + src/runtime/rx_caproot.h src/train/tg_store.h src/train/tg_sgd.h src/sha256.h + +# $(1) = output suffix, $(2) = extra flags +define REPLAY_BUILD +$(REPLAY_DIR)/rx_replay$(1): $(REPLAY_VERIFIER_SRCS) $(REPLAY_HDRS) + @mkdir -p $(REPLAY_DIR) + $(CC) $(REPLAY_CFLAGS) $(2) -o $$@ $(REPLAY_VERIFIER_SRCS) +$(REPLAY_DIR)/rxlog_mutate$(1): $(REPLAY_MUTATE_SRCS) $(REPLAY_HDRS) + @mkdir -p $(REPLAY_DIR) + $(CC) $(REPLAY_CFLAGS) $(2) -o $$@ $(REPLAY_MUTATE_SRCS) +$(REPLAY_DIR)/rx_world_replay$(1): $(REPLAY_WORLD_SRCS) $(REPLAY_HDRS) + @mkdir -p $(REPLAY_DIR) + $(CC) $(REPLAY_CFLAGS) $(2) -pthread $(REPLAY_NVRM_INC) -o $$@ $(REPLAY_WORLD_SRCS) +$(REPLAY_DIR)/m22_dispatch_run$(1): $(REPLAY_M22_SRCS) $(REPLAY_HDRS) + @mkdir -p $(REPLAY_DIR) + $(CC) $(REPLAY_CFLAGS) -ffp-contract=off $(2) -o $$@ $(REPLAY_M22_SRCS) -lm +endef +$(eval $(call REPLAY_BUILD,,)) +$(eval $(call REPLAY_BUILD,_asan,$(REPLAY_SAN))) + +REPLAY_BINS = $(REPLAY_DIR)/rx_replay $(REPLAY_DIR)/rxlog_mutate $(REPLAY_DIR)/rx_world_replay \ + $(REPLAY_DIR)/m22_dispatch_run +replay-tools: $(REPLAY_BINS) + +replay-purity: + @bad=$$(grep -hE '^[[:space:]]*#[[:space:]]*include' tools/replay/rx_replay.c tools/replay/rxlog.c tools/replay/rxlog.h tools/replay/trn1.c tools/replay/trn1.h | \ + grep -vE '#[[:space:]]*include[[:space:]]+(<[a-z/]+\.h>|"sha256\.h"|"replay/(rxlog|trn1)\.h")' || true); \ + if [ -n "$$bad" ]; then echo "replay-purity: FAIL, verifier includes:"; echo "$$bad"; exit 1; fi; \ + echo "replay-purity: verifier depends only on libc, sha256, rxlog and trn1" + +test-replay: replay-purity +ifeq ($(REPLAY_NVRM_H),) + @echo "test-replay: NOT_RUN (nvrm.h not found under PHYSICS_DIR=$(PHYSICS_DIR); set PHYSICS_DIR to a physics checkout)" +else + $(MAKE) -f mk/replay.mk PHYSICS_DIR=$(PHYSICS_DIR) OUT_DIR=$(OUT_DIR) replay-run +endif + +replay-run: $(REPLAY_BINS) + REPLAY_BIN=$(REPLAY_DIR) REPLAY_SUFFIX= TRN1_VECTORS=$(TRN1_VECTORS) sh tests/replay/run_replay_suite.sh $(REPLAY_DIR)/run + +replay-asan: replay-purity $(REPLAY_BINS:%=%_asan) + REPLAY_BIN=$(REPLAY_DIR) REPLAY_SUFFIX=_asan TRN1_VECTORS=$(TRN1_VECTORS) sh tests/replay/run_replay_suite.sh $(REPLAY_DIR)/run-asan +endif diff --git a/tests/replay/m22_dispatch_run.c b/tests/replay/m22_dispatch_run.c new file mode 100644 index 000000000..d7ce32424 --- /dev/null +++ b/tests/replay/m22_dispatch_run.c @@ -0,0 +1,59 @@ +/* m22_dispatch_run.c -- make an M22 store with a real dispatch.log through + * the public tg_store/tg_sgd API (host only), so tools/replay/rx_replay can + * verify it and compare two runs. + * + * m22_dispatch_run DIR [steps] [seed] [perturb] + * + * Deterministic: quadratic loss, seeded parameters, momentum SGD, every + * third step applies two dispatches in one generation. perturb "lr" uses a + * different learning rate from step 4 on (the negative control for + * compare-dispatch). DIR must not exist or be empty. */ +#include "train/tg_sgd.h" +#include "train/tg_store.h" + +#include +#include +#include +#include + +#define N 64 + +static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s; } +static float urand(uint32_t *s) { return (float)(lcg(s) >> 8) / 16777216.0f - 0.5f; } +static int accept(const tg_shadow *sh, const tg_snapshot *c, void *ctx) { (void)sh; (void)c; (void)ctx; return 0; } + +int main(int argc, char **argv) { + if (argc < 2) { fprintf(stderr, "usage: m22_dispatch_run DIR [steps] [seed] [lr]\n"); return 2; } + const char *dir = argv[1]; + int steps = argc > 2 ? atoi(argv[2]) : 12; + uint32_t seed = argc > 3 ? (uint32_t)strtoul(argv[3], NULL, 0) : 12345u; + int perturb = argc > 4 && !strcmp(argv[4], "lr"); + mkdir(dir, 0755); + float p[N], v[N], t[N], g[N]; + for (int i = 0; i < N; i++) { p[i] = 4.0f * urand(&seed); v[i] = 0; t[i] = urand(&seed); } + int r = tg_create(dir, p, sizeof p, v, sizeof v); + if (r) { fprintf(stderr, "tg_create: %s\n", tg_err_name(r)); return 2; } + tg_store *st; + if ((r = tg_open(dir, &st, NULL))) { fprintf(stderr, "tg_open: %s\n", tg_err_name(r)); return 2; } + for (int s = 0; s < steps; s++) { + tg_shadow sh; + if ((r = tg_shadow_begin(st, &sh))) break; + int reps = s % 3 == 2 ? 2 : 1; + for (int k = 0; k < reps && !r; k++) { + const float *cur = (const float *)(const void *)sh.params; + for (int i = 0; i < N; i++) g[i] = cur[i] - t[i]; + float lr = perturb && s >= 4 ? 0.06f : 0.05f; + r = tg_sgd_step(st, &sh, g, N, lr, 0.9f, (uint64_t)(s * 4 + k)); + } + if (r) { tg_shadow_discard(&sh); break; } + if ((r = tg_commit(st, &sh, accept, NULL))) break; + } + if (r) { fprintf(stderr, "step failed: %s\n", tg_err_name(r)); tg_close(st); return 2; } + const tg_snapshot *c = tg_committed(st); + char hx[2 * TG_DIGEST + 1]; + tg_hex(c->dispatch_head, hx); + printf("m22 store %s: gen %llu, %llu dispatch records, head %s\n", dir, (unsigned long long)c->gen, + (unsigned long long)(c->dispatch_len / 192u), hx); + tg_close(st); + return 0; +} diff --git a/tests/replay/run_replay_suite.sh b/tests/replay/run_replay_suite.sh new file mode 100755 index 000000000..7fece7a57 --- /dev/null +++ b/tests/replay/run_replay_suite.sh @@ -0,0 +1,320 @@ +#!/bin/sh +# run_replay_suite.sh OUTDIR -- lane LD replay suite (host only). +# Needs REPLAY_BIN (dir with the four tools) and REPLAY_SUFFIX ("" or _asan). +# Every expectation is checked from tool output; the verdict is computed, +# never written in. Exit 0 only if every gating expectation held. Strict +# 4-worker sequence checks are non-gating KNOWN_FAIL lines under runtime +# finding I11 (see known_check); the 4-worker gate is the causal-order +# compare (tools/replay/CAUSAL_ORDER.md), gated by its own mutants. +set -u +out=${1:?usage: run_replay_suite.sh OUTDIR} +bin=${REPLAY_BIN:?} +sfx=${REPLAY_SUFFIX:-} +V="$bin/rx_replay$sfx" +M="$bin/rxlog_mutate$sfx" +W="$bin/rx_world_replay$sfx" +T="$bin/m22_dispatch_run$sfx" +rm -rf "$out" +mkdir -p "$out/world" "$out/m22" +rec="$out/results.txt" +: > "$rec" +fails=0 +checks=0 + +# expect NAME WANT(MATCH|DIVERGENCE) [SUBSYSTEM-PREFIX] -- cmd... +expect() { + name=$1; want=$2; sub=$3; shift 4 + checks=$((checks + 1)) + "$@" > "$out/last.txt" 2>&1 + rc=$? + line=$(grep -E '^(MATCH|DIVERGENCE|REFUSED|refuse|ok |TRN1_)' "$out/last.txt" | head -n 1) + got=${line%% *} + ok=1 + if [ "$want" = MATCH ]; then + [ "$got" = MATCH ] && [ $rc -eq 0 ] || ok=0 + elif [ "$want" = OK ]; then + [ $rc -eq 0 ] || ok=0 + elif [ "$want" = DETECT ]; then + { [ "$got" = DIVERGENCE ] || [ "$got" = refuse ]; } && [ $rc -eq 1 ] || ok=0 + else + [ "$got" = DIVERGENCE ] && [ $rc -eq 1 ] || ok=0 + if [ $ok -eq 1 ] && [ -n "$sub" ]; then + case "$line" in *"subsystem=$sub"*) ;; *) ok=0 ;; esac + fi + fi + if [ $ok -eq 1 ]; then st=ok; else st=FAIL; fails=$((fails + 1)); fi + printf '%-4s %-34s want=%-10s %s\n' "$st" "$name" "$want" "${line:-}" >> "$rec" + [ $ok -eq 1 ] || { echo "FAIL $name: wanted $want ${sub:+($sub)}"; cat "$out/last.txt"; } +} + +run() { "$@" > "$out/last.txt" 2>&1 || { echo "FAIL setup: $*"; cat "$out/last.txt"; fails=$((fails + 1)); }; } + +# Known runtime findings. A strict check the engine is known to fail stays in +# the suite and is reported every run, both ways: "ok" when it passes, +# "KNOWN_FAIL" (non-gating, finding named) when it reports DIVERGENCE. It is +# never reported as ok when it fails, and a run that gives no DIVERGENCE +# verdict (tool error, refusal) is a normal FAIL. When the engine is fixed the +# line turns into "ok" by itself; nothing here has to change. +I11="runtime finding I11: concurrent commits are logged in schedule order (deterministic commit order requested)" +known=0 +known_names="" +# known_check NAME -- cmd...: one strict compare under finding I11. +known_check() { + name=$1; shift 2 + checks=$((checks + 1)) + "$@" > "$out/last.txt" 2>&1 + rc=$? + line=$(grep -E '^(MATCH|DIVERGENCE|REFUSED|refuse|ok |TRN1_)' "$out/last.txt" | head -n 1) + got=${line%% *} + if [ "$got" = MATCH ] && [ $rc -eq 0 ]; then st=ok + elif [ "$got" = DIVERGENCE ] && [ $rc -eq 1 ]; then + st=KNOWN_FAIL; known=$((known + 1)); known_names="$known_names $name" + else st=FAIL; fails=$((fails + 1)); fi + printf '%-4s %-34s want=%-10s %s%s\n' "$st" "$name" "MATCH" "${line:-}" \ + "$([ $st = KNOWN_FAIL ] && echo " [non-gating; $I11]")" >> "$rec" + [ $st = FAIL ] && { echo "FAIL $name: no verdict"; cat "$out/last.txt"; } + [ $st = KNOWN_FAIL ] && { echo "KNOWN_FAIL $name (non-gating, I11)"; head -n 4 "$out/last.txt"; } + return 0 +} + +echo "== World: record, verify, replay from the log ==" +ref="$out/world/ref.rxlog" +run "$W" record "$ref" 1 24 +expect world-verify-recorded MATCH "" -- "$V" verify "$ref" +run "$W" record "$out/world/ref2.rxlog" 1 24 +expect world-record-twice MATCH "" -- "$V" compare "$ref" "$out/world/ref2.rxlog" +run "$W" replay "$ref" "$out/world/replay1.rxlog" 1 +expect world-replay-1-worker MATCH "" -- "$V" compare "$ref" "$out/world/replay1.rxlog" +if cmp -s "$ref" "$out/world/replay1.rxlog"; then raw=identical; else raw=different; fi +echo "raw-bytes ref vs replay: $raw (clocks differ; the compared digest must not)" >> "$rec" + +echo "== World: 4 workers, 5 replays: strict sequence (non-gating, I11) and causal order (gating) ==" +# Strict sequence: every 4-worker replay crumb-identical to the 1-worker +# recording. The engine logs unrelated concurrent commits in schedule order, +# so this is KNOWN_FAIL until runtime finding I11 is fixed (see known_check). +sched_match=0 +sched_bad=0 +causal_match=0 +for i in 1 2 3 4 5; do + run "$W" replay "$ref" "$out/world/replay4-$i.rxlog" 4 + "$V" compare "$ref" "$out/world/replay4-$i.rxlog" > "$out/world/replay4-$i.txt" 2>&1 + rc=$? + v=$(head -n 1 "$out/world/replay4-$i.txt" | cut -d' ' -f1) + if [ "$v" = MATCH ] && [ $rc -eq 0 ]; then sched_match=$((sched_match + 1)) + elif [ "$v" != DIVERGENCE ] || [ $rc -ne 1 ]; then sched_bad=$((sched_bad + 1)); fi + # Causal order: the property concurrent commits must keep + # (rx_replay.c compare-causal, tools/replay/CAUSAL_ORDER.md). + "$V" compare-causal "$ref" "$out/world/replay4-$i.rxlog" > "$out/world/replay4-$i.causal.txt" 2>&1 + rc=$? + cl=$(head -n 1 "$out/world/replay4-$i.causal.txt") + [ "${cl%% *}" = MATCH ] && [ $rc -eq 0 ] && causal_match=$((causal_match + 1)) + echo " replay4-$i strict: $(head -n 1 "$out/world/replay4-$i.txt")" >> "$rec" + echo " replay4-$i causal: ${cl:-}" >> "$rec" +done +echo "schedule: 4-worker replays matching the 1-worker recording: strict $sched_match/5, causal order $causal_match/5" >> "$rec" +checks=$((checks + 1)) +if [ $sched_match -eq 5 ]; then + echo "ok world-replay-4-workers 5/5 MATCH" >> "$rec" +elif [ $sched_bad -eq 0 ]; then + known=$((known + 1)); known_names="$known_names world-replay-4-workers" + echo "KNOWN_FAIL world-replay-4-workers $sched_match/5 MATCH [non-gating; $I11]" >> "$rec" + echo "KNOWN_FAIL world-replay-4-workers (non-gating, I11)" + head -n 4 "$out"/world/replay4-*.txt +else + fails=$((fails + 1)) + echo "FAIL world-replay-4-workers $sched_bad/5 compares gave no verdict" >> "$rec" + cat "$out"/world/replay4-*.txt +fi +# Gating: committed history equal as a causal partial order on every replay. +checks=$((checks + 1)) +if [ $causal_match -eq 5 ]; then + echo "ok trn1-replay-4-workers-causal 5/5 MATCH (causal order; merged-wake counts excluded)" >> "$rec" +else + fails=$((fails + 1)) + echo "FAIL trn1-replay-4-workers-causal $causal_match/5 MATCH (causal order)" >> "$rec" + echo "FAIL trn1-replay-4-workers-causal: $causal_match/5" + for i in 1 2 3 4 5; do echo "-- replay4-$i"; head -n 4 "$out/world/replay4-$i.causal.txt"; done +fi +expect world-replay-1-worker-causal MATCH "" -- "$V" compare-causal "$ref" "$out/world/replay1.rxlog" + +echo "== World: negative controls (replay that really differs) ==" +run "$W" replay "$ref" "$out/world/neg-value.rxlog" 1 value +expect control-value-only DIVERGENCE world.state -- "$V" compare "$ref" "$out/world/neg-value.rxlog" +run "$W" replay "$ref" "$out/world/neg-structure.rxlog" 1 structure +expect control-structure DIVERGENCE world.crumb -- "$V" compare "$ref" "$out/world/neg-structure.rxlog" +run "$W" replay "$ref" "$out/world/neg-input.rxlog" 1 input +expect control-input DIVERGENCE world.input -- "$V" compare "$ref" "$out/world/neg-input.rxlog" +# The causal-order compare must see the same three real differences. +expect causal-control-value-only DIVERGENCE world.state -- "$V" compare-causal "$ref" "$out/world/neg-value.rxlog" +expect causal-control-structure DIVERGENCE "" -- "$V" compare-causal "$ref" "$out/world/neg-structure.rxlog" +expect causal-control-input DIVERGENCE world.input -- "$V" compare-causal "$ref" "$out/world/neg-input.rxlog" + +echo "== World: mutation suite ==" +wk=0; ws=0; wx=0 +for m in $("$M" list-world); do + f="$out/world/mut-$m.rxlog" + run "$M" world "$ref" "$f" "$m" + "$V" verify "$f" > "$out/world/mut-$m.verify.txt" 2>&1 + sv=$(head -n 1 "$out/world/mut-$m.verify.txt" | cut -d' ' -f1) + case $m in + excluded-*) + wx=$((wx + 1)) + expect "mutant:$m (verify=$sv)" MATCH "" -- "$V" compare "$ref" "$f" ;; + *) + before=$fails + expect "mutant:$m (verify=$sv)" DIVERGENCE "" -- "$V" compare "$ref" "$f" + if [ $fails -eq $before ]; then wk=$((wk + 1)); else ws=$((ws + 1)); fi ;; + esac +done +echo "world mutants: killed=$wk survived=$ws excluded-field controls=$wx" >> "$rec" + +echo "== Causal order: mutants (must FAIL the causal gate) and controls (must not) ==" +# causal-* forge one real difference into a self-consistent log; causal-control-* +# make only the changes concurrent commits legitimately make (unrelated +# commits swapped, a flagged superseded run with its rerun, the merged-wake +# count): the sequence compare must still catch those, the causal compare not. +ck=0; cs=0; cc=0 +for m in $("$M" list-causal); do + f="$out/world/causal-$m.rxlog" + run "$M" causal "$ref" "$f" "$m" + "$V" verify "$f" > "$out/world/causal-$m.verify.txt" 2>&1 + sv=$(head -n 1 "$out/world/causal-$m.verify.txt" | cut -d' ' -f1) + # every forged log verifies by itself: only a comparison can catch it + expect "cmutant-self-verify:$m" MATCH "" -- "$V" verify "$f" + case $m in + causal-control-*) + cc=$((cc + 1)) + expect "ccontrol:$m (strict)" DIVERGENCE "" -- "$V" compare "$ref" "$f" + expect "ccontrol:$m (causal)" MATCH "" -- "$V" compare-causal "$ref" "$f" ;; + *) + before=$fails + expect "cmutant:$m (verify=$sv)" DIVERGENCE "" -- "$V" compare-causal "$ref" "$f" + if [ $fails -eq $before ]; then ck=$((ck + 1)); else cs=$((cs + 1)); fi ;; + esac +done +# Every sequence-compare world mutant must also fail the causal compare, +# except the excluded-field controls (worker, clocks). +for m in $("$M" list-world); do + f="$out/world/mut-$m.rxlog" + case $m in + excluded-*) expect "causal-wmutant:$m" MATCH "" -- "$V" compare-causal "$ref" "$f" ;; + *) + before=$fails + expect "causal-wmutant:$m" DETECT "" -- "$V" compare-causal "$ref" "$f" + if [ $fails -eq $before ]; then ck=$((ck + 1)); else cs=$((cs + 1)); fi ;; + esac +done +echo "causal mutants: killed=$ck survived=$cs controls=$cc" >> "$rec" + +echo "== M22 dispatch.log ==" +run "$T" "$out/m22/a" 12 +run "$T" "$out/m22/b" 12 +run "$T" "$out/m22/lr" 12 12345 lr +expect m22-verify MATCH "" -- "$V" verify-dispatch "$out/m22/a" +expect m22-replay-run MATCH "" -- "$V" compare-dispatch "$out/m22/a" "$out/m22/b" +expect control-m22-lr DIVERGENCE m22.dispatch -- "$V" compare-dispatch "$out/m22/a" "$out/m22/lr" +dk=0; ds=0 +for m in $("$M" list-dispatch); do + d="$out/m22/mut-$m" + rm -rf "$d"; cp -r "$out/m22/a" "$d" + run "$M" dispatch "$d" "$m" + "$V" verify-dispatch "$d" > "$d.verify.txt" 2>&1 + sv=$(head -n 1 "$d.verify.txt" | cut -d' ' -f1) + before=$fails + expect "dmutant:$m (verify=$sv)" DIVERGENCE "" -- "$V" compare-dispatch "$out/m22/a" "$d" + if [ $fails -eq $before ]; then dk=$((dk + 1)); else ds=$((ds + 1)); fi +done +echo "dispatch mutants: killed=$dk survived=$ds" >> "$rec" + +echo "== TRN1: export, verify, compare, bit flips, shared corpus ==" +mkdir -p "$out/trn1" +tk=0; ts=0 +for f in ref replay1 replay4-1 neg-value neg-structure neg-input; do + run "$V" export-trn1 "$out/world/$f.rxlog" "$out/trn1/$f.trn" +done +expect trn1-verify-recorded OK "" -- "$V" verify-trn1 "$out/trn1/ref.trn" +expect trn1-replay-1-worker MATCH "" -- "$V" compare-trn1 "$out/trn1/ref.trn" "$out/trn1/replay1.trn" +known_check trn1-replay-4-workers -- "$V" compare-trn1 "$out/trn1/ref.trn" "$out/trn1/replay4-1.trn" +expect trn1-control-value DIVERGENCE omega-world -- "$V" compare-trn1 "$out/trn1/ref.trn" "$out/trn1/neg-value.trn" +expect trn1-control-structure DIVERGENCE omega-world -- "$V" compare-trn1 "$out/trn1/ref.trn" "$out/trn1/neg-structure.trn" +expect trn1-control-input DIVERGENCE external -- "$V" compare-trn1 "$out/trn1/ref.trn" "$out/trn1/neg-input.trn" +expect trn1-every-bit-flip-refused OK "" -- "$V" trn1-flipall "$out/trn1/ref.trn" +for m in $("$M" list-world); do + t="$out/trn1/mut-$m.trn" + run "$V" export-trn1 "$out/world/mut-$m.rxlog" "$t" + # Not TRN1 identity by spec 5.3 (episode is annotation) or RXCLOG container + # fields with no TRN1 counterpart (TRN1 has its own chain and END). + case $m in + excluded-*|flip-episode|flip-end-head|flip-end-count) expect "trn1-mutant:$m" MATCH "" -- "$V" compare-trn1 "$out/trn1/ref.trn" "$t" ;; + *) + before=$fails + expect "trn1-mutant:$m" DETECT "" -- "$V" compare-trn1 "$out/trn1/ref.trn" "$t" + if [ $fails -eq $before ]; then tk=$((tk + 1)); else ts=$((ts + 1)); fi ;; + esac +done +echo "trn1 world mutants: killed=$tk survived=$ts" >> "$rec" +vec=${TRN1_VECTORS:-} +if [ -n "$vec" ] && [ -f "$vec/expected.txt" ]; then + expect trn1-shared-corpus OK "" -- "$V" trn1-corpus "$vec" + corpus=$(grep '^TRN1_CONFORMANCE' "$out/last.txt") + corpus_src="$vec" +else + corpus="NOT_RUN (no TRN1_VECTORS directory)" + corpus_src=none + echo "NOT_RUN trn1-shared-corpus (set TRN1_VECTORS)" >> "$rec" +fi + +echo "== Path and line limits: refuse, never truncate ==" +# expect_refusal NAME RC TEXT -- cmd...: exit code RC and TEXT in the output. +# A truncated path or split corpus line must be refused loudly; before the +# fix these inputs were read as a different (shorter) path or two lines. +expect_refusal() { + name=$1; want_rc=$2; text=$3; shift 4 + checks=$((checks + 1)) + "$@" > "$out/last.txt" 2>&1 + rc=$? + if [ $rc -eq "$want_rc" ] && grep -qF "$text" "$out/last.txt"; then st=ok; else st=FAIL; fails=$((fails + 1)); fi + printf '%-4s %-34s want=rc%s+"%s" got rc=%s\n' "$st" "$name" "$want_rc" "$text" "$rc" >> "$rec" + [ $st = ok ] || { echo "FAIL $name: wanted rc=$want_rc and \"$text\""; head -c 2000 "$out/last.txt"; echo; } +} +# Same directory, spelled with 2100 "/." segments: over 4096 bytes. +lp_trn="$out/trn1"; lp_m22="$out/m22/a"; i=0 +while [ $i -lt 2100 ]; do lp_trn="$lp_trn/."; lp_m22="$lp_m22/."; i=$((i + 1)); done +expect_refusal limit-corpus-path-too-long 2 "path too long" -- "$V" trn1-corpus "$lp_trn" +expect_refusal limit-dispatch-path-too-long 1 "store path too long" -- "$V" verify-dispatch "$lp_m22" +expect_refusal limit-mutate-path-too-long 2 "path too long" -- "$M" dispatch "$lp_m22" flip-op +mkdir -p "$out/trn1/longline" +{ i=0; while [ $i -lt 1500 ]; do printf x; i=$((i + 1)); done; echo " OK"; } > "$out/trn1/longline/expected.txt" +: > "$out/trn1/longline/compare.txt" +expect_refusal limit-corpus-line-too-long 1 "line longer than" -- "$V" trn1-corpus "$out/trn1/longline" + +commit=$(git rev-parse HEAD 2>/dev/null || echo unknown) +if [ -n "$(git status --porcelain 2>/dev/null)" ]; then dirty=true; else dirty=false; fi +# Non-gating known failures are named in the verdict itself, never folded into PASS silently. +notes="" +[ "$corpus_src" = none ] && notes="trn1_corpus NOT_RUN" +if [ $known -ne 0 ]; then + kn="KNOWN FAIL (non-gating, runtime finding I11):$known_names" + notes="${notes:+$notes; }$kn" +fi +if [ $fails -ne 0 ]; then verdict=FAIL; else verdict="PASS${notes:+ ($notes)}"; fi +{ + echo "lane: LD replay suite${sfx:+ ($sfx build)}" + echo "evidence: host (CPU only; no GPU, no QEMU, no hardware chip run)" + echo "host: $(uname -srm)" + echo "commit: $commit" + echo "tree_dirty: $dirty" + echo "checks: $checks failed: $fails known_fail_non_gating: $known" + echo "world_mutants_killed: $wk world_mutants_survived: $ws excluded_field_controls: $wx" + echo "dispatch_mutants_killed: $dk dispatch_mutants_survived: $ds" + echo "trn1_world_mutants_killed: $tk trn1_world_mutants_survived: $ts" + echo "causal_mutants_killed: $ck causal_mutants_survived: $cs causal_controls: $cc" + echo "strict_4_worker_sequence: $([ $known -eq 0 ] && echo PASS || echo "KNOWN FAIL ($I11)")" + echo "causal_4_worker_gate: $causal_match/5 (merged-wake counts excluded from the comparison, kept in the log)" + echo "trn1_corpus: $corpus (vectors: $corpus_src)" + echo "verdict: $verdict" + echo "--- results" + cat "$rec" +} > "$out/receipt.txt" +sed -n '1,14p' "$out/receipt.txt" +[ $fails -eq 0 ] diff --git a/tests/replay/rx_world_replay.c b/tests/replay/rx_world_replay.c new file mode 100644 index 000000000..5a7e97668 --- /dev/null +++ b/tests/replay/rx_world_replay.c @@ -0,0 +1,325 @@ +/* rx_world_replay.c -- record a World run to an RXCLOG01 log, and replay a + * recorded run from its log alone (host only, CPU, no GPU). + * + * rx_world_replay record OUT [workers] [stimuli] [seed] + * rx_world_replay replay IN OUT [workers] [perturb] + * + * The World is the R3 heartbeat organism (tests/runtime/rx_heartbeat_test.c): + * sensor -> aien.hypothesis -> belief -> omega.realize -> plan, and + * omega.risk fed by sensor humidity and belief. Recording publishes seeded + * outside stimuli; each goes into the log as an INPUT record (with values), + * then the crumbs it caused, then a CHECKPOINT holding a hash of every + * object's fields, versions and writers. + * + * Replay rebuilds the same World and re-publishes exactly the INPUT records + * read from the log (nothing else comes from the recording), waiting for + * quiescence after each, and writes a new log. tools/replay/rx_replay + * compare then names the first divergent event. + * + * perturb (negative controls, so a passing compare means something): + * value omega.realize adds 1001 instead of 1000 (same crumbs, other values) + * structure omega.risk is not registered (different crumbs) + * input the third INPUT is replayed with value + 8 (recorded values are + * 0..7, so the write is never a no-op and never the recorded one) + * + * Every recorded stimulus value differs from the field's current value: the + * runtime leaves an unchanged field out of the EXTERNAL crumb's outputs, and + * the verifier requires every INPUT mutation to appear there. + * + * Capability generations are boot-time seeded by the capability root, so the + * log carries them relative to the run's office generation (rx_crumb_export.h); + * INPUT records store the external capability's generation the same way. */ +#include "replay/rx_crumb_export.h" +#include "runtime/rx_caproot.h" +#include "runtime/rx_world.h" +#include "sha256.h" + +#include +#include +#include + +enum { SUBJ_AIEN = 1, SUBJ_OMEGA = 2, SUBJ_EXTERNAL = 100, ISSUER_AEGIS_POLICY = 3 }; +enum { RES_SENSOR = 0x10, RES_BELIEF = 0x20, RES_PLAN = 0x30, RES_RISK = 0x40 }; +enum { F_TEMP = 0, F_HUMIDITY = 1 }; +enum { P_NONE = 0, P_VALUE, P_STRUCTURE, P_INPUT }; + +typedef struct { RxObjRef sensor, belief, plan, risk; int perturb; } HB; + +typedef struct { + RxCapRoot root; + RxCapAdmin admin; + RxWorld w; + HB h; + RxCapRef c_ext; +} Env; + +static const RxSnapshotDep *in_of(const RxCtx *c, RxObjRef o) { + for (uint32_t i = 0; i < c->n_in; i++) + if (c->in[i].obj.id == o.id) return &c->in[i]; + return NULL; +} + +static int fn_hypothesis(RxCtx *c) { + HB *h = c->user; + const RxSnapshotDep *s = in_of(c, h->sensor); + if (!s) return -1; + c->out[c->n_out++] = (RxMutation){ h->belief, 0, s->field[F_TEMP] * 2 + 1 }; + return 0; +} + +static int fn_realize(RxCtx *c) { + HB *h = c->user; + const RxSnapshotDep *b = in_of(c, h->belief); + if (!b) return -1; + c->out[c->n_out++] = (RxMutation){ h->plan, 0, b->field[0] + (h->perturb == P_VALUE ? 1001 : 1000) }; + return 0; +} + +static int fn_risk(RxCtx *c) { + HB *h = c->user; + const RxSnapshotDep *s = in_of(c, h->sensor); + const RxSnapshotDep *b = in_of(c, h->belief); + if (!s || !b) return -1; + c->out[c->n_out++] = (RxMutation){ h->risk, 0, s->field[F_HUMIDITY] * 100000 + b->field[0] }; + return 0; +} + +static RxCapRef mint(Env *e, uint32_t subject, uint64_t resource, uint32_t rights) { + RxCapMint m; + memset(&m, 0, sizeof m); + m.issuer = ISSUER_AEGIS_POLICY; + m.subject = subject; + m.resource = resource; + m.rights = rights; + m.parent = (RxCapRef){ UINT32_MAX, 0 }; + m.authority = rx_capadmin_office(&e->admin); + RxCapRef r = { UINT32_MAX, 0 }; + if (rx_capadmin_mint(&e->admin, &m, &r) != RX_CAP_OK) fprintf(stderr, "mint failed\n"); + return r; +} + +static RxObjRef mkobj(Env *e, uint64_t resource) { + uint64_t init[RX_MAX_FIELDS] = { 0 }; + RxObjRef r = { UINT32_MAX, 0 }; + rx_world_create(&e->w, 1, RX_PERSIST_RESIDENT, resource, init, &r); + return r; +} + +static void desc(RxReactionDesc *d, const char *name, uint32_t fac, uint32_t subj, RxFn fn, void *u) { + memset(d, 0, sizeof *d); + d->name = name; + d->faculty = fac; + d->subject = subj; + d->priority = RX_PRIO_FOREGROUND; + d->fn = fn; + d->user = u; +} +static void trig(RxReactionDesc *d, RxObjRef o, uint64_t m) { d->triggers[d->n_triggers++] = (RxDep){ o, m }; } +static void wr(RxReactionDesc *d, RxObjRef o, uint64_t m) { d->writes[d->n_writes++] = (RxDep){ o, m }; } +static void cap(RxReactionDesc *d, RxCapRef c, uint64_t res, uint32_t rights) { + d->caps[d->n_caps++] = (RxCapNeed){ c, res, rights }; +} + +static int setup(Env *e, uint32_t workers, int perturb) { + memset(e, 0, sizeof *e); + if (rx_caproot_start(&e->root, &e->admin) != RX_CAP_OK) return -1; + if (rx_world_init(&e->w, &e->root, workers, 1u << 16) != RX_OK) return -1; + e->w.external_subject = SUBJ_EXTERNAL; + e->h.perturb = perturb; + e->h.sensor = mkobj(e, RES_SENSOR); + e->h.belief = mkobj(e, RES_BELIEF); + e->h.plan = mkobj(e, RES_PLAN); + e->h.risk = mkobj(e, RES_RISK); + e->c_ext = mint(e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxCapRef a_rs = mint(e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ); + RxCapRef a_wb = mint(e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + RxCapRef o_rb = mint(e, SUBJ_OMEGA, RES_BELIEF, RX_RIGHT_READ); + RxCapRef o_wp = mint(e, SUBJ_OMEGA, RES_PLAN, RX_RIGHT_WRITE); + RxCapRef o_rs = mint(e, SUBJ_OMEGA, RES_SENSOR, RX_RIGHT_READ); + RxCapRef o_wr = mint(e, SUBJ_OMEGA, RES_RISK, RX_RIGHT_WRITE); + RxReactionDesc d; + uint32_t id; + desc(&d, "aien.hypothesis", RX_FACULTY_AIEN, SUBJ_AIEN, fn_hypothesis, &e->h); + trig(&d, e->h.sensor, RX_FIELD(F_TEMP)); + wr(&d, e->h.belief, RX_FIELD(0)); + cap(&d, a_rs, RES_SENSOR, RX_RIGHT_READ); + cap(&d, a_wb, RES_BELIEF, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &id) != RX_OK) return -1; + desc(&d, "omega.realize", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_realize, &e->h); + trig(&d, e->h.belief, RX_FIELD(0)); + wr(&d, e->h.plan, RX_FIELD(0)); + cap(&d, o_rb, RES_BELIEF, RX_RIGHT_READ); + cap(&d, o_wp, RES_PLAN, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &id) != RX_OK) return -1; + if (perturb != P_STRUCTURE) { + desc(&d, "omega.risk", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_risk, &e->h); + trig(&d, e->h.sensor, RX_FIELD(F_HUMIDITY)); + trig(&d, e->h.belief, RX_FIELD(0)); + wr(&d, e->h.risk, RX_FIELD(0)); + cap(&d, o_rs, RES_SENSOR, RX_RIGHT_READ); + cap(&d, o_rb, RES_BELIEF, RX_RIGHT_READ); + cap(&d, o_wr, RES_RISK, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &id) != RX_OK) return -1; + } + return 0; +} + +static void teardown(Env *e) { + rx_world_destroy(&e->w); + rx_caproot_stop(&e->root, &e->admin); +} + +static void put32(sha256_ctx *c, uint32_t v) { + uint8_t b[4] = { (uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24) }; + sha256_update(c, b, 4); +} +static void put64(sha256_ctx *c, uint64_t v) { put32(c, (uint32_t)v); put32(c, (uint32_t)(v >> 32)); } + +_Static_assert(RX_MAX_FIELDS == RXL_MAX_FIELDS, "RXCLOG01 state table field count must match RX_MAX_FIELDS"); + +/* State checkpoint: every object's identity, version, values, field + * versions and field writers (values are what crumbs do not carry). The + * hash is computed here from the runtime objects; the same fields go into + * the state table, from which the verifier recomputes the hash + * (rxl_state_hash) and the causal-order compare matches writers by causal + * identity instead of crumb id. */ +static int checkpoint(Env *e, rxl_log *log) { + const RxObjRef objs[4] = { e->h.sensor, e->h.belief, e->h.plan, e->h.risk }; + rxl_rec r; + memset(&r, 0, sizeof r); + r.type = RXL_CHECKPOINT; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"RXCLOG01-STATE", 14); + for (int i = 0; i < 4; i++) { + RxObject o; + if (rx_world_read(&e->w, objs[i], &o) != RX_OK) return -1; + put32(&c, o.id); put32(&c, o.generation); put32(&c, o.type); put64(&c, o.version); + rxl_obj *t = &r.u.ck.obj[r.u.ck.n_obj++]; + t->id = o.id; t->gen = o.generation; t->type = o.type; t->version = o.version; + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { + put64(&c, o.field[f]); put64(&c, o.field_version[f]); put64(&c, o.field_writer[f]); + t->value[f] = o.field[f]; t->fversion[f] = o.field_version[f]; t->writer[f] = o.field_writer[f]; + } + } + r.u.ck.through_crumb = e->w.n_crumbs; + r.u.ck.subsystem = 1; + sha256_final(&c, r.u.ck.hash); + return rxl_push(log, &r); +} + +/* Publish one INPUT record, log it and everything it caused. */ +static int drive(Env *e, rxl_log *log, rxx_ctx *x, const rxl_input *in) { + rxl_rec r; + memset(&r, 0, sizeof r); + r.type = RXL_INPUT; + r.u.in = *in; + r.u.in.after_crumb = e->w.n_crumbs; + if (rxl_push(log, &r)) return -1; + RxMutation m[RXL_MAX_MUTS]; + for (uint32_t i = 0; i < in->n; i++) + m[i] = (RxMutation){ { in->m[i].id, in->m[i].gen }, in->m[i].field, in->m[i].value }; + if (in->cap_gen > UINT64_MAX - x->cap_base) { fprintf(stderr, "input capability generation out of range\n"); return -1; } + int64_t rc = rx_world_publish_external(&e->w, (RxCapRef){ in->cap_id, x->cap_base + in->cap_gen }, m, in->n); + if (rc <= 0) { fprintf(stderr, "publish refused: %lld\n", (long long)rc); return -1; } + if (rx_world_wait_quiescent(&e->w, 10000) != RX_OK) { fprintf(stderr, "no quiescence\n"); return -1; } + if (rxx_append_crumbs(log, &e->w, x)) return -1; + return checkpoint(e, log); +} + +static uint32_t lcg(uint32_t *s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; } + +static int record(const char *out, uint32_t workers, uint32_t stimuli, uint32_t seed) { + Env e; + if (setup(&e, workers, P_NONE)) { fprintf(stderr, "setup failed\n"); return 2; } + rxl_log log; + rxl_init(&log, RXL_FLAG_INPUTS); + rxx_ctx x; + rxx_init(&x, rx_capadmin_office(&e.admin).generation); + int bad = e.c_ext.generation < x.cap_base || rxx_append_crumbs(&log, &e.w, &x) || checkpoint(&e, &log); + for (uint32_t k = 0; k < stimuli && !bad; k++) { + rxl_input in; + memset(&in, 0, sizeof in); + in.cap_id = e.c_ext.cap_id; + in.cap_gen = e.c_ext.generation - x.cap_base; + RxObject s; + if (rx_world_read(&e.w, e.h.sensor, &s) != RX_OK) { fprintf(stderr, "sensor read failed\n"); bad = 1; break; } + /* current + 1..7, mod 8: never the value the field already holds */ + uint32_t pick = lcg(&seed) % 3; /* temp, humidity, or both */ + if (pick != 1) in.m[in.n++] = (rxl_mut){ e.h.sensor.id, e.h.sensor.generation, F_TEMP, + (s.field[F_TEMP] + 1 + lcg(&seed) % 7) % 8 }; + if (pick != 0) in.m[in.n++] = (rxl_mut){ e.h.sensor.id, e.h.sensor.generation, F_HUMIDITY, + (s.field[F_HUMIDITY] + 1 + lcg(&seed) % 7) % 8 }; + bad = drive(&e, &log, &x, &in); + } + teardown(&e); + rxx_free(&x); + if (bad || rxl_finish(&log) || rxl_write(out, &log)) { fprintf(stderr, "record failed\n"); rxl_free(&log); return 2; } + printf("recorded %zu events (%llu crumbs, %u stimuli, %u workers) to %s\n", log.n - 1, + (unsigned long long)(x.next - 1), stimuli, workers, out); + rxl_free(&log); + return 0; +} + +static int replay(const char *in_path, const char *out, uint32_t workers, int perturb) { + rxl_log in; + char err[160]; + if (rxl_read(in_path, &in, err, sizeof err)) { fprintf(stderr, "replay: %s\n", err); return 2; } + Env e; + if (setup(&e, workers, perturb)) { fprintf(stderr, "setup failed\n"); rxl_free(&in); return 2; } + rxl_log log; + rxl_init(&log, RXL_FLAG_INPUTS); + rxx_ctx xc; + rxx_init(&xc, rx_capadmin_office(&e.admin).generation); + int bad = e.c_ext.generation < xc.cap_base || rxx_append_crumbs(&log, &e.w, &xc) || checkpoint(&e, &log); + uint32_t n_in = 0; + for (size_t i = 0; i < in.n && !bad; i++) { + if (in.recs[i].type != RXL_INPUT) continue; + rxl_input x = in.recs[i].u.in; + if (x.cap_id != e.c_ext.cap_id || x.cap_gen != e.c_ext.generation - xc.cap_base) { + fprintf(stderr, "replay: recorded capability %u/%llu is not the rebuilt one\n", x.cap_id, + (unsigned long long)x.cap_gen); + bad = 1; + break; + } + if (perturb == P_INPUT && n_in == 2) { + /* never the recorded value, never the value the field holds */ + RxObject s; + if (rx_world_read(&e.w, (RxObjRef){ x.m[0].id, x.m[0].gen }, &s) != RX_OK || x.m[0].field >= RX_MAX_FIELDS) { + fprintf(stderr, "replay: perturbed field unreadable\n"); + bad = 1; + break; + } + x.m[0].value += 8; + if (x.m[0].value == s.field[x.m[0].field]) x.m[0].value += 8; + } + n_in++; + bad = drive(&e, &log, &xc, &x); + } + teardown(&e); + rxx_free(&xc); + rxl_free(&in); + if (bad || rxl_finish(&log) || rxl_write(out, &log)) { fprintf(stderr, "replay failed\n"); rxl_free(&log); return 2; } + printf("replayed %u inputs into %zu events (%u workers) to %s\n", n_in, log.n - 1, workers, out); + rxl_free(&log); + return 0; +} + +int main(int argc, char **argv) { + if (argc >= 3 && !strcmp(argv[1], "record")) + return record(argv[2], argc > 3 ? (uint32_t)atoi(argv[3]) : 1, argc > 4 ? (uint32_t)atoi(argv[4]) : 24, + argc > 5 ? (uint32_t)strtoul(argv[5], NULL, 0) : 0xA11CEu); + if (argc >= 4 && !strcmp(argv[1], "replay")) { + int p = P_NONE; + if (argc > 5) { + if (!strcmp(argv[5], "value")) p = P_VALUE; + else if (!strcmp(argv[5], "structure")) p = P_STRUCTURE; + else if (!strcmp(argv[5], "input")) p = P_INPUT; + else { fprintf(stderr, "unknown perturbation %s\n", argv[5]); return 2; } + } + return replay(argv[2], argv[3], argc > 4 ? (uint32_t)atoi(argv[4]) : 1, p); + } + fprintf(stderr, "usage: rx_world_replay record OUT [workers] [stimuli] [seed]\n" + " rx_world_replay replay IN OUT [workers] [value|structure|input]\n"); + return 2; +} diff --git a/tools/replay/CAUSAL_ORDER.md b/tools/replay/CAUSAL_ORDER.md new file mode 100644 index 000000000..2fbeebc00 --- /dev/null +++ b/tools/replay/CAUSAL_ORDER.md @@ -0,0 +1,145 @@ +# Replay with concurrent commits: causal-order equivalence + +Lane LD replay suite (`mk/replay.mk test-replay`). This note covers the +4-worker replay checks: what the engine does today, what the suite compares, +and what it leaves out. + +## Known engine property (runtime finding I11) + +With one worker, a World replay is crumb-identical to its recording (the +strict sequence checks `world-replay-1-worker` and `trn1-replay-1-worker` +are gates and pass). With four workers the engine logs committed history +in schedule order. Decoded from the five 4-worker replays of forge run +LD-174654 (`build/replay/run/world`, decoded by shell/awk, nothing rerun): + +- Causally unrelated reactions (`omega.realize`, `omega.risk`) commit in + either order. All five replays first differ from the recording there. +- `omega.risk`'s merged-wake count (`coalesced_wakes`) is 1 with one worker + and 0 with four, for the same stimulus. +- A run that read a stale belief is superseded (an INVALIDATED crumb, + reason STALE_GEN, then a rerun) in only some replays (2 of 5). +- Every crumb id after the first difference shifts, so the CHECKPOINT field + writers for `plan` and `risk` differ by crumb id. + +Runtime finding I11 asks the engine for a deterministic commit order. Until +then the strict 4-worker sequence checks fail. That is an engine property, +not a replay harness bug, and the suite does not hide it (below). + +## What the suite gates on + +`rx_replay compare-causal EXPECTED ACTUAL` compares committed history as a +causal partial order. The rules are in the comment above `compare_causal` +in `rx_replay.c`. In short: + +- **Identity.** An entry's causal identity is a digest of its content (kind, + reaction, faculty, inputs and outputs with versions and masks, caps, + reason) plus the identities of its wake cause and of every parent. + Crumb ids are not part of it. Cause links are, compared by identity all + the way back to the first crumb. +- **Per stimulus.** The log is cut at INPUT records (the replayer waits for + quiescence after each). INPUT contents must be equal and in order. + Within each stimulus, the multiset of entry identities must be equal. +- **Superseded entries** (INVALIDATED) are left out of that multiset. Each + must be flagged (kind INVALIDATED, nonzero reason, no outputs) and paired + with its rerun: a later entry of the same reaction, in the same episode + and stimulus, that is not itself INVALIDATED. A run logged as committed + that the same reaction then repeats in the stimulus is reported as an + "unflagged superseded entry" and fails. +- **Snapshot writers** are matched by identity, not crumb id. To make this + possible, CHECKPOINT records now carry the state table they hash (object + id, generation, type, version; per field value, field version, writer). + `rx_replay verify` recomputes the state hash from the table, so the table + cannot disagree with what the recorder hashed. Values and versions must be + equal exactly. +- **Excluded:** the merged-wake count (`coalesced_wakes`). It stays in the log, + in the crumb digest and in the strict sequence compare. Only the causal + compare leaves it out, because how many wakes the scheduler folds into one + run is a scheduling fact. Worker and clocks are excluded, as in every + compare. Positions (crumb ids, INPUT `after_crumb`, CHECKPOINT + `through_crumb`) are excluded too, but each log must still pass its own + `verify` rules, which check them. + +The gating check is `trn1-replay-4-workers-causal`: all five 4-worker +replays must MATCH the 1-worker recording under compare-causal. It compares +the RXCLOG01 logs that the TRN1 transcripts are exported from, because a TRN1 +CHECKPOINT carries only the state hash, which does not let writer identity +be recovered. `world-replay-1-worker-causal` checks the 1-worker replay the +same way. + +## Mutants and controls (the gate is only as good as these) + +`rxlog_mutate causal IN OUT NAME` forges each change into the recording, +renumbers every id that refers to a crumb, and reseals the log so it passes +`verify` by itself (the suite checks that). Only the comparison can catch it. + +Each of these must make the causal gate FAIL: + +| mutant | change | +|---|---| +| `causal-cause-link` | an entry wakes on a different earlier crumb | +| `causal-parent-link` | an entry loses a parent | +| `causal-writer-swap` | two snapshot writers swapped (state hash recomputed) | +| `causal-unflagged-superseded` | a stale run of a reaction logged as committed before its real run | +| `causal-entry-changed` | a committed entry's output version changed | +| `causal-superseded-no-rerun` | a flagged superseded entry with no rerun after it | + +Every existing sequence-compare world mutant must also fail compare-causal +(except the `excluded-*` worker and clock controls). The three replay +negative controls (value, structure, input) must fail it as well. + +Each of these must MATCH under compare-causal and still fail the strict +sequence compare. They show that the tolerance is exactly the stated one: + +| control | change | +|---|---| +| `causal-control-swap-independent` | two causally unrelated commits swapped and renumbered | +| `causal-control-flagged-superseded` | a flagged superseded run inserted before its rerun | +| `causal-control-coalesced` | the merged-wake count changed | + +## How the strict 4-worker checks are reported + +`world-replay-4-workers` (5 replays, RXCLOG01) and `trn1-replay-4-workers` +(TRN1) stay in the suite. They are not gates. Each run reports one of: + +- `ok`, if the strict compare matches; +- `KNOWN_FAIL ... [non-gating; runtime finding I11 ...]`, if it reports + DIVERGENCE; +- `FAIL`, if it gives no verdict at all (tool error or refusal). That fails + the suite. + +A KNOWN_FAIL never counts as a pass. The receipt lists it on +`strict_4_worker_sequence:` and in the verdict itself, for example +`verdict: PASS (KNOWN FAIL (non-gating, runtime finding I11): world-replay-4-workers trn1-replay-4-workers)`. +Once the engine commits in a deterministic order, these lines turn into `ok` +with no change to the suite. + +## Second engine property, seen while building this (gate expected to FAIL) + +The five 4-worker replays of the next run (2026-10-01 13:07, the old queued +job on a dirty tree, so reported only as decoded evidence) show something +the causal compare does not tolerate, by design. In 4 of 5 replays, +`omega.risk` commits twice for one stimulus. It first runs on the humidity +wake alone, reads the belief before `aien.hypothesis` commits (a consistent +but older snapshot), and commits. Then it runs again on the belief wake and +commits again. With one worker the two wakes are merged and `risk` commits +once. Each unmerged wake adds exactly one committed `risk` run: + +| replay | crumbs | `risk` commits | merged wakes | +|---|---|---|---| +| recording (1 worker) | 88 | 24 | 9 | +| replay4-1 | 88 | 24 | 9 | +| replay4-2 | 93 | 29 | 4 | +| replay4-3 | 90 | 26 | 7 | +| replay4-4 | 89 | 25 | 8 | +| replay4-5 | 90 | 26 | 7 | + +The extra run is not INVALIDATED. It is a real commit, its value is +overwritten in the same stimulus, and the `risk` object's version stays +ahead from then on. So leaving the merged-wake count out of the comparison +does not make these histories equal. The extra entry and the version offset +are real differences in committed history and state. The causal gate +reports them (as an unflagged superseded entry) and fails, as its +`causal-unflagged-superseded` mutant requires. Accepting these runs would +mean ignoring object versions, and that is out of scope for the verifier. +This belongs with runtime finding I11: a deterministic commit order needs +deterministic wake merging too. diff --git a/tools/replay/rx_crumb_export.c b/tools/replay/rx_crumb_export.c new file mode 100644 index 000000000..1f8492143 --- /dev/null +++ b/tools/replay/rx_crumb_export.c @@ -0,0 +1,100 @@ +/* rx_crumb_export.c -- RxCrumb -> RXCLOG01 record. */ +#include "replay/rx_crumb_export.h" + +#include +#include +#include + +_Static_assert((int)RXL_MAX_DEPS == (int)RX_MAX_DEPS, "rxlog input limit drifted from rx_world.h"); +_Static_assert((int)RXL_MAX_WRITES == (int)RX_MAX_WRITES, "rxlog output limit drifted from rx_world.h"); +_Static_assert((int)RXL_MAX_CAPS == (int)RX_MAX_CAPS, "rxlog cap limit drifted from rx_world.h"); +_Static_assert((int)RXL_MAX_PARENTS == (int)RX_MAX_PARENTS, "rxlog parent limit drifted from rx_world.h"); +_Static_assert((int)RXL_MAX_MUTS == (int)RX_MAX_MUTATIONS, "rxlog mutation limit drifted from rx_world.h"); +_Static_assert((int)RXL_K_EXTERNAL == (int)RX_CRUMB_EXTERNAL && (int)RXL_K_CREATE == (int)RX_CRUMB_CREATE && + (int)RXL_K_MAX == (int)RX_CRUMB_QUARANTINE, "rxlog crumb kinds drifted from rx_world.h"); + +void rxx_crumb(const RxCrumb *k, rxl_crumb *o) { + memset(o, 0, sizeof *o); + o->id = k->id; + o->kind = (uint32_t)k->kind; + o->reaction = k->reaction; + o->faculty = k->faculty; + o->worker = k->worker; + o->wake_cause = k->wake_cause; + o->coalesced = k->coalesced_wakes; + o->n_inputs = k->n_inputs; + for (uint32_t i = 0; i < k->n_inputs && i < RX_MAX_DEPS; i++) + o->inputs[i] = (rxl_io){ k->inputs[i].obj.id, k->inputs[i].obj.generation, + k->inputs[i].version, k->inputs[i].mask }; + o->n_caps = k->n_caps; + for (uint32_t i = 0; i < k->n_caps && i < RX_MAX_CAPS; i++) + o->caps[i] = (rxl_cap){ k->caps[i].cap_id, k->caps[i].generation, k->cap_issuer[i] }; + o->n_outputs = k->n_outputs; + for (uint32_t i = 0; i < k->n_outputs && i < RX_MAX_WRITES; i++) + o->outputs[i] = (rxl_io){ k->outputs[i].obj.id, k->outputs[i].obj.generation, + k->outputs[i].version, k->outputs[i].mask }; + o->reason = k->reason; + o->n_parents = k->n_parents; + for (uint32_t i = 0; i < k->n_parents && i < RX_MAX_PARENTS; i++) o->parents[i] = k->parents[i]; + o->t_start = k->t_start_ns; + o->t_end = k->t_end_ns; + o->episode = k->episode; + memcpy(o->digest, k->digest, 32); +} + +void rxx_init(rxx_ctx *x, uint64_t cap_base) { + memset(x, 0, sizeof *x); + x->cap_base = cap_base; + x->next = 1; +} + +void rxx_free(rxx_ctx *x) { + free(x->raw); + free(x->rel); + memset(x, 0, sizeof *x); +} + +static int grow(rxx_ctx *x) { + if (x->n < x->cap) return 0; + size_t nc = x->cap ? x->cap * 2 : 256; + uint8_t (*r)[32] = realloc(x->raw, nc * sizeof *r); + if (!r) return -1; + x->raw = r; + uint8_t (*l)[32] = realloc(x->rel, nc * sizeof *l); + if (!l) return -1; + x->rel = l; + x->cap = nc; + return 0; +} + +int rxx_append_crumbs(rxl_log *log, RxWorld *w, rxx_ctx *x) { + for (;; x->next++) { + const RxCrumb *k = rx_world_crumb(w, x->next); + if (!k) return x->next > w->n_crumbs ? 0 : -1; + if (x->n != x->next - 1 || grow(x)) return -1; + rxl_rec r; + memset(&r, 0, sizeof r); + r.type = RXL_CRUMB; + rxx_crumb(k, &r.u.c); + uint8_t d[32]; + rxl_crumb_digest(&r.u.c, (const uint8_t (*)[32])x->raw, x->n, d); + if (memcmp(d, k->digest, 32)) { + fprintf(stderr, "export: crumb %llu: runtime digest is not reproduced from its fields\n", + (unsigned long long)k->id); + return -1; + } + memcpy(x->raw[x->n], k->digest, 32); + for (uint32_t i = 0; i < r.u.c.n_caps && i < RXL_MAX_CAPS; i++) { + if (r.u.c.caps[i].gen < x->cap_base) { + fprintf(stderr, "export: crumb %llu: capability generation below the run's root\n", + (unsigned long long)k->id); + return -1; + } + r.u.c.caps[i].gen -= x->cap_base; + } + rxl_crumb_digest(&r.u.c, (const uint8_t (*)[32])x->rel, x->n, r.u.c.digest); + memcpy(x->rel[x->n], r.u.c.digest, 32); + x->n++; + if (rxl_push(log, &r)) return -1; + } +} diff --git a/tools/replay/rx_crumb_export.h b/tools/replay/rx_crumb_export.h new file mode 100644 index 000000000..ed9dd7fc8 --- /dev/null +++ b/tools/replay/rx_crumb_export.h @@ -0,0 +1,40 @@ +/* rx_crumb_export.h -- copy World crumbs into an RXCLOG01 log (rxlog.h). + * The only replay file that includes rx_world.h; it reads crumbs through + * the public rx_world_crumb() and never changes the World. */ +#ifndef OMEGA_RX_CRUMB_EXPORT_H +#define OMEGA_RX_CRUMB_EXPORT_H + +#include "replay/rxlog.h" +#include "runtime/rx_world.h" + +#include + +/* Convert one runtime crumb, field for field (digest and episode copied as + * recorded, capability generations raw). */ +void rxx_crumb(const RxCrumb *k, rxl_crumb *out); + +/* Export state for one run. Capability generations are boot-time seeded by + * the capability root (rx_caproot.c take_boot_gen), so two runs of the same + * history never share them. The log stores every capability generation + * relative to cap_base, the run's capability office generation, and the + * crumb digests over that relative form (rxlog.h). Before rewriting a crumb + * the exporter recomputes the runtime digest over the raw fields with the + * independent rxl_crumb_digest and refuses the crumb if it differs, so the + * verifier stays checked against the runtime's own crumb hash. */ +typedef struct { + uint64_t cap_base; + uint64_t next; /* next crumb id to export, from 1 */ + uint8_t (*raw)[32]; /* runtime digest of crumb id, at [id - 1] */ + uint8_t (*rel)[32]; /* log digest of crumb id, at [id - 1] */ + size_t n, cap; +} rxx_ctx; + +void rxx_init(rxx_ctx *x, uint64_t cap_base); +void rxx_free(rxx_ctx *x); +/* Append crumbs [x->next, w->n_crumbs] to the log and advance x->next. Call + * only while the World is quiescent. Returns 0, or -1 on a missing crumb, a + * runtime digest the independent recomputation does not reproduce, a + * capability generation below cap_base, or out of memory. */ +int rxx_append_crumbs(rxl_log *log, RxWorld *w, rxx_ctx *x); + +#endif diff --git a/tools/replay/rx_replay.c b/tools/replay/rx_replay.c new file mode 100644 index 000000000..255f722af --- /dev/null +++ b/tools/replay/rx_replay.c @@ -0,0 +1,1161 @@ +/* rx_replay.c -- independent verifier and replay comparator for World crumb + * logs (RXCLOG01, tools/replay/rxlog.h) and M22 dispatch logs + * (src/train/tg_store.h dispatch.log). Links libc + src/sha256.c only. + * + * rx_replay verify LOG one log against its own rules + * rx_replay compare EXPECTED ACTUAL recorded run vs replayed run + * rx_replay compare-causal EXP ACT the same, committed history as a causal + * partial order (concurrent commits; see + * the section below and CAUSAL_ORDER.md) + * rx_replay verify-dispatch DIR dispatch.log chain + committed head + * rx_replay compare-dispatch A B two dispatch logs, record by record + * + * Output is exactly one verdict line: + * MATCH through event N + * DIVERGENCE event=N expected= actual= subsystem= + * optionally followed by one "detail:" line and, for a world compare, the two + * first differing records decoded ("expected-record:", "actual-record:"; + * diagnostic only, never parsed). Events are numbered from 1 in + * log order (crumbs, inputs and checkpoints alike; dispatch: record seq + 1). + * Exit 0 = MATCH, 1 = DIVERGENCE, 2 = cannot run (usage, or the reference + * log of a compare does not verify by itself). + * + * World rules (rx_world_verify_crumbs, plus stricter ones marked *): + * ids dense from 1; parents in [1, id); digest recomputes; episode follows + * wake_cause; * kind known; * parents strictly ascending (the runtime sorts + * and de-duplicates them); * wake_cause < id; * with RXL_FLAG_INPUTS every + * EXTERNAL crumb is directly preceded by an INPUT record that names it and + * whose objects and fields it writes; * checkpoints name the crumb count; + * * the END record counts every record and matches the head chain. */ +#include "replay/rxlog.h" +#include "replay/trn1.h" +#include "sha256.h" + +#include +#include +#include +#include +#include + +typedef struct { + int diverged; + uint64_t event; + char expected[80], actual[80], subsystem[32], detail[200]; + char rec_exp[640], rec_act[640]; /* first differing records, decoded (diagnostic only) */ +} verdict; + +static void hexs(char *out, const uint8_t d[32]) { rxl_hex(d, 32, out); } + +static int diverge(verdict *v, uint64_t ev, const char *sub, const char *exp, const char *act, + const char *fmt, ...) __attribute__((format(printf, 6, 7))); +static int diverge(verdict *v, uint64_t ev, const char *sub, const char *exp, const char *act, + const char *fmt, ...) { + v->diverged = 1; + v->event = ev; + snprintf(v->subsystem, sizeof v->subsystem, "%s", sub); + snprintf(v->expected, sizeof v->expected, "%s", exp); + snprintf(v->actual, sizeof v->actual, "%s", act); + va_list ap; + va_start(ap, fmt); + vsnprintf(v->detail, sizeof v->detail, fmt, ap); + va_end(ap); + return 1; +} + +static int report(const verdict *v) { + if (!v->diverged) { + printf("MATCH through event %llu\n", (unsigned long long)v->event); + return 0; + } + printf("DIVERGENCE event=%llu expected=%s actual=%s subsystem=%s\n", + (unsigned long long)v->event, v->expected, v->actual, v->subsystem); + if (v->detail[0]) printf("detail: %s\n", v->detail); + if (v->rec_exp[0]) printf("expected-record: %s\n", v->rec_exp); + if (v->rec_act[0]) printf("actual-record: %s\n", v->rec_act); + return 1; +} + +/* ---- World crumb logs --------------------------------------------------- */ + +static int verify_log(const rxl_log *l, verdict *v) { + memset(v, 0, sizeof *v); + uint8_t (*dig)[32] = calloc(l->n + 1, 32); + uint64_t *ep = calloc(l->n + 1, sizeof *ep); + if (!dig || !ep) { + free(dig); free(ep); + return diverge(v, 0, "verifier", "memory", "none", "out of memory"); + } + uint64_t nk = 0, events = 0; + uint8_t head[32] = { 0 }; + char a[80], b[80]; + int done = 0, pending_input = 0; + const rxl_input *last_in = NULL; + for (size_t i = 0; i < l->n && !done; i++) { + const rxl_rec *r = &l->recs[i]; + uint64_t ev = i + 1; + if (r->type == RXL_END) { + if (i != l->n - 1) { done = diverge(v, ev, "world.log", "end-last", "end-early", "END record is not the last record"); break; } + if (pending_input) { done = diverge(v, ev, "world.input", "external", "end", "INPUT record not followed by its EXTERNAL crumb"); break; } + if (r->u.end.n_records != events) { + snprintf(a, sizeof a, "records:%llu", (unsigned long long)events); + snprintf(b, sizeof b, "records:%llu", (unsigned long long)r->u.end.n_records); + done = diverge(v, ev, "world.log", a, b, "END record count does not match the log"); + break; + } + if (memcmp(head, r->u.end.head, 32)) { + hexs(a, head); hexs(b, r->u.end.head); + done = diverge(v, ev, "world.log", a, b, "END head does not chain the records before it"); + break; + } + done = 2; + break; + } + if (r->type == RXL_CRUMB) { + const rxl_crumb *k = &r->u.c; + uint64_t want = nk + 1; + if (k->id != want) { + snprintf(a, sizeof a, "id:%llu", (unsigned long long)want); + snprintf(b, sizeof b, "id:%llu", (unsigned long long)k->id); + done = diverge(v, ev, "world.order", a, b, "crumb ids must be dense and in order (omitted or reordered crumb)"); + break; + } + if (k->kind < 1 || k->kind > RXL_K_MAX) { + snprintf(b, sizeof b, "kind:%u", k->kind); + done = diverge(v, ev, "world.crumb", "kind:1..10", b, "unknown crumb kind (crumb %llu)", (unsigned long long)k->id); + break; + } + for (uint32_t p = 0; p < k->n_parents && !done; p++) { + if (k->parents[p] == 0 || k->parents[p] >= k->id || + (p && k->parents[p] <= k->parents[p - 1])) { + snprintf(a, sizeof a, "parent<%llu,ascending", (unsigned long long)k->id); + snprintf(b, sizeof b, "parent[%u]:%llu", p, (unsigned long long)k->parents[p]); + done = diverge(v, ev, "world.parents", a, b, "parent link out of range or out of canonical order (crumb %llu)", (unsigned long long)k->id); + } + } + if (done) break; + if (k->wake_cause >= k->id) { + snprintf(a, sizeof a, "cause<%llu", (unsigned long long)k->id); + snprintf(b, sizeof b, "cause:%llu", (unsigned long long)k->wake_cause); + done = diverge(v, ev, "world.parents", a, b, "wake cause is not an earlier crumb (crumb %llu)", (unsigned long long)k->id); + break; + } + uint8_t d[32]; + rxl_crumb_digest(k, (const uint8_t (*)[32])dig, nk, d); + if (memcmp(d, k->digest, 32)) { + hexs(a, d); hexs(b, k->digest); + done = diverge(v, ev, "world.crumb", a, b, "crumb %llu: recorded digest does not match its fields", (unsigned long long)k->id); + break; + } + uint64_t e = k->kind == RXL_K_EXTERNAL ? k->id + : k->wake_cause >= 1 ? ep[k->wake_cause - 1] : 0; + if (k->episode != e) { + snprintf(a, sizeof a, "episode:%llu", (unsigned long long)e); + snprintf(b, sizeof b, "episode:%llu", (unsigned long long)k->episode); + done = diverge(v, ev, "world.episode", a, b, "crumb %llu: episode does not follow its wake cause", (unsigned long long)k->id); + break; + } + if (l->flags & RXL_FLAG_INPUTS) { + if (k->kind == RXL_K_EXTERNAL) { + int ok = pending_input && last_in->after_crumb + 1 == k->id && k->n_outputs >= 1; + for (uint32_t m = 0; ok && m < last_in->n; m++) { + int hit = 0; + for (uint32_t o = 0; o < k->n_outputs; o++) + if (k->outputs[o].id == last_in->m[m].id && k->outputs[o].gen == last_in->m[m].gen && + last_in->m[m].field < 64 && ((k->outputs[o].mask >> last_in->m[m].field) & 1)) hit = 1; + ok = hit; + } + if (!ok) { + done = diverge(v, ev, "world.input", "input-record", pending_input ? "mismatched-input" : "none", + "EXTERNAL crumb %llu is not bound to the INPUT record before it", (unsigned long long)k->id); + break; + } + pending_input = 0; + } else if (pending_input) { + done = diverge(v, ev, "world.input", "external", "other-crumb", "INPUT record not followed by its EXTERNAL crumb"); + break; + } + } + memcpy(dig[nk], k->digest, 32); + ep[nk] = k->episode; + nk++; + } else if (r->type == RXL_INPUT) { + if (pending_input || r->u.in.after_crumb != nk || r->u.in.n == 0) { + snprintf(a, sizeof a, "after:%llu", (unsigned long long)nk); + snprintf(b, sizeof b, "after:%llu", (unsigned long long)r->u.in.after_crumb); + done = diverge(v, ev, "world.input", a, b, "INPUT record out of place"); + break; + } + pending_input = (l->flags & RXL_FLAG_INPUTS) != 0; + last_in = &r->u.in; + } else if (r->type == RXL_CHECKPOINT) { + if (r->u.ck.through_crumb != nk || pending_input) { + snprintf(a, sizeof a, "through:%llu", (unsigned long long)nk); + snprintf(b, sizeof b, "through:%llu", (unsigned long long)r->u.ck.through_crumb); + done = diverge(v, ev, "world.state", a, b, "CHECKPOINT does not name the crumbs before it"); + break; + } + if (r->u.ck.n_obj) { + uint8_t sh[32]; + rxl_state_hash(&r->u.ck, sh); + if (memcmp(sh, r->u.ck.hash, 32)) { + hexs(a, sh); hexs(b, r->u.ck.hash); + done = diverge(v, ev, "world.state", a, b, "CHECKPOINT state table does not hash to its state hash"); + break; + } + for (uint32_t o = 0; o < r->u.ck.n_obj && !done; o++) + for (uint32_t f = 0; f < RXL_MAX_FIELDS && !done; f++) + if (r->u.ck.obj[o].writer[f] > nk) { + snprintf(a, sizeof a, "writer<=%llu", (unsigned long long)nk); + snprintf(b, sizeof b, "writer:%llu", (unsigned long long)r->u.ck.obj[o].writer[f]); + done = diverge(v, ev, "world.state", a, b, "CHECKPOINT names a field writer that is not an earlier crumb"); + } + if (done) break; + } + } + rxl_head_step(head, r); + events++; + } + free(dig); free(ep); + if (done == 1) return 1; + if (l->malformed) + return diverge(v, l->n + 1, "world.log", "record", "malformed", "%s", l->why); + if (done != 2) + return diverge(v, events + 1, "world.log", "end", "none", "log ends without its END record (truncated)"); + v->event = events; + return 0; +} + +static const char *rec_sub(uint32_t t) { + return t == RXL_CRUMB ? "world.crumb" : t == RXL_INPUT ? "world.input" + : t == RXL_CHECKPOINT ? "world.state" : "world.log"; +} + +/* First field that differs between two crumbs, for the detail line. */ +static const char *crumb_field_diff(const rxl_crumb *x, const rxl_crumb *y) { + if (x->id != y->id) return "id"; + if (x->kind != y->kind) return "kind"; + if (x->reaction != y->reaction) return "reaction"; + if (x->faculty != y->faculty) return "faculty"; + if (x->wake_cause != y->wake_cause) return "wake_cause"; + if (x->coalesced != y->coalesced) return "coalesced_wakes"; + if (x->n_inputs != y->n_inputs) return "inputs"; + for (uint32_t i = 0; i < x->n_inputs; i++) + if (x->inputs[i].id != y->inputs[i].id || x->inputs[i].gen != y->inputs[i].gen || + x->inputs[i].version != y->inputs[i].version || x->inputs[i].mask != y->inputs[i].mask) return "inputs"; + if (x->n_caps != y->n_caps) return "caps"; + for (uint32_t i = 0; i < x->n_caps; i++) + if (x->caps[i].cap_id != y->caps[i].cap_id || x->caps[i].gen != y->caps[i].gen || + x->caps[i].issuer != y->caps[i].issuer) return "caps"; + if (x->n_outputs != y->n_outputs) return "outputs"; + for (uint32_t i = 0; i < x->n_outputs; i++) + if (x->outputs[i].id != y->outputs[i].id || x->outputs[i].gen != y->outputs[i].gen || + x->outputs[i].version != y->outputs[i].version || x->outputs[i].mask != y->outputs[i].mask) return "outputs"; + if (x->reason != y->reason) return "reason"; + if (x->n_parents != y->n_parents) return "parents"; + for (uint32_t i = 0; i < x->n_parents; i++) + if (x->parents[i] != y->parents[i]) return "parents"; + return "parent digests"; +} + +/* Diagnostic: one record decoded on one line, so a failing compare shows + * both sides of the first difference (worker and times included, though + * they are not compared). Appends stop at the buffer end. */ +static void cat_f(char *o, size_t n, size_t *at, const char *fmt, ...) __attribute__((format(printf, 4, 5))); +static void cat_f(char *o, size_t n, size_t *at, const char *fmt, ...) { + if (*at >= n) return; + va_list ap; + va_start(ap, fmt); + int k = vsnprintf(o + *at, n - *at, fmt, ap); + va_end(ap); + *at = k < 0 ? n : *at + (size_t)k; +} + +static void rec_line(const rxl_rec *r, char *o, size_t n) { + size_t at = 0; + o[0] = 0; + if (r->type == RXL_CRUMB) { + const rxl_crumb *k = &r->u.c; + cat_f(o, n, &at, "crumb id=%llu kind=%u reaction=%u faculty=%u worker=%u wake_cause=%llu coalesced=%llu reason=%d in=", + (unsigned long long)k->id, k->kind, k->reaction, k->faculty, k->worker, + (unsigned long long)k->wake_cause, (unsigned long long)k->coalesced, (int)k->reason); + for (uint32_t i = 0; i < k->n_inputs && i < RXL_MAX_DEPS; i++) + cat_f(o, n, &at, "%s%u/%u@v%llu:m%llx", i ? "," : "", k->inputs[i].id, k->inputs[i].gen, + (unsigned long long)k->inputs[i].version, (unsigned long long)k->inputs[i].mask); + cat_f(o, n, &at, " out="); + for (uint32_t i = 0; i < k->n_outputs && i < RXL_MAX_WRITES; i++) + cat_f(o, n, &at, "%s%u/%u@v%llu:m%llx", i ? "," : "", k->outputs[i].id, k->outputs[i].gen, + (unsigned long long)k->outputs[i].version, (unsigned long long)k->outputs[i].mask); + cat_f(o, n, &at, " parents="); + for (uint32_t i = 0; i < k->n_parents && i < RXL_MAX_PARENTS; i++) + cat_f(o, n, &at, "%s%llu", i ? "," : "", (unsigned long long)k->parents[i]); + } else if (r->type == RXL_INPUT) { + const rxl_input *in = &r->u.in; + cat_f(o, n, &at, "input after_crumb=%llu muts=", (unsigned long long)in->after_crumb); + for (uint32_t i = 0; i < in->n && i < RXL_MAX_MUTS; i++) + cat_f(o, n, &at, "%s%u.f%u=%llu", i ? "," : "", in->m[i].id, in->m[i].field, + (unsigned long long)in->m[i].value); + } else if (r->type == RXL_CHECKPOINT) { + cat_f(o, n, &at, "checkpoint through_crumb=%llu", (unsigned long long)r->u.ck.through_crumb); + } else { + cat_f(o, n, &at, "record type=%u", r->type); + } +} + +static int compare_logs(const char *pa, const char *pb) { + rxl_log A, B; + char err[160]; + verdict v; + if (rxl_read(pa, &A, err, sizeof err)) { fprintf(stderr, "rx_replay: expected log: %s\n", err); return 2; } + if (verify_log(&A, &v)) { + printf("REFUSED expected log does not verify: event=%llu subsystem=%s (%s)\n", + (unsigned long long)v.event, v.subsystem, v.detail); + rxl_free(&A); + return 2; + } + if (rxl_read(pb, &B, err, sizeof err)) { + printf("DIVERGENCE event=1 expected=RXCLOG01 actual=unreadable subsystem=world.log\ndetail: %s\n", err); + rxl_free(&A); + return 1; + } + /* Content first, in log order, so the first differing event is named + * even when the replayed log is also internally broken there. */ + size_t na = A.n - 1; /* reference verified: its last record is END */ + size_t nb = B.n && B.recs[B.n - 1].type == RXL_END ? B.n - 1 : B.n; + memset(&v, 0, sizeof v); + char a[80], b[80]; + for (size_t i = 0; i < na || i < nb; i++) { + uint64_t ev = i + 1; + uint8_t dx[32], dy[32]; + if (i >= nb) { + rxl_event_digest(&A.recs[i], dx); hexs(a, dx); + diverge(&v, ev, rec_sub(A.recs[i].type), a, "none", "replayed log stops early (missing event)"); + break; + } + if (i >= na) { + rxl_event_digest(&B.recs[i], dy); hexs(b, dy); + diverge(&v, ev, rec_sub(B.recs[i].type), "none", b, "replayed log has an extra event"); + break; + } + const rxl_rec *x = &A.recs[i], *y = &B.recs[i]; + rxl_event_digest(x, dx); rxl_event_digest(y, dy); + if (x->type != y->type || memcmp(dx, dy, 32)) { + hexs(a, dx); hexs(b, dy); + if (x->type == RXL_CRUMB && y->type == RXL_CRUMB) + diverge(&v, ev, "world.crumb", a, b, "crumb %llu differs first in: %s", + (unsigned long long)x->u.c.id, crumb_field_diff(&x->u.c, &y->u.c)); + else + diverge(&v, ev, rec_sub(x->type), a, b, "record type %u vs %u", x->type, y->type); + rec_line(x, v.rec_exp, sizeof v.rec_exp); + rec_line(y, v.rec_act, sizeof v.rec_act); + break; + } + } + if (!v.diverged) { + /* Same compared content: the replayed log must also hold its own + * rules (stored digests that were copied, not recomputed, and a + * missing END are caught here). */ + verdict w; + if (verify_log(&B, &w)) v = w; + else v.event = na; + } + rxl_free(&A); rxl_free(&B); + return report(&v); +} + +/* ---- Causal-order compare (concurrent commits) ------------------------- + * + * rx_replay compare-causal EXPECTED ACTUAL + * + * Committed history as a causal partial order, not a sequence. With more + * than one worker the World commits causally unrelated reactions in either + * order and may supersede a run that read a stale belief (INVALIDATED crumb, + * then a rerun); crumb ids, and every id that refers to them, then depend on + * the schedule (runtime finding I11; tools/replay/CAUSAL_ORDER.md). This + * compare is the property that holds anyway, and is stricter than a + * sequence compare in no place and looser only where stated here: + * + * identity an entry's causal identity is a digest of its content (kind, + * reaction, faculty, inputs with versions and masks, caps, + * outputs with versions and masks, reason) and of the causal + * identities of its wake cause and of every parent (as a sorted + * set). Crumb ids are not part of it; cause links are, by + * identity, recursively back to the first crumb. + * excluded coalesced_wakes (merged-wake count: how many wakes the + * scheduler folded into one run is a schedule fact, 1 with one + * worker and 0 with four in the decoded runs); it stays in the + * log and in the sequence compare. worker and clocks, as in the + * sequence compare. Crumb ids and the INPUT after_crumb / + * CHECKPOINT through_crumb counts (positions; each log must still + * verify by its own rules, which check them). + * segments the log is cut at INPUT records (the replayer waits for + * quiescence after each), so entries are matched only within + * the same stimulus. INPUT contents (capability, mutations, + * values) must be equal, in order. + * entries within a segment, the multiset of causal identities of all + * crumbs except superseded ones must be equal. + * superseded an INVALIDATED crumb (in either log) must be flagged as such: + * kind INVALIDATED, a nonzero reason, no outputs. It must be + * paired with its rerun: a later crumb of the same reaction in the + * same episode and segment that is not itself INVALIDATED. A run + * that was superseded but is logged as committed is not + * superseded: it is an extra entry and fails (named "unflagged + * superseded entry" when the same reaction has another entry in + * the same episode). + * state every CHECKPOINT state table (required in both logs) must + * match object for object: values, versions and field versions + * exactly, field writers by causal identity, not crumb id. + * + * Output and exit codes as compare. MATCH lines also report how many + * superseded entries each log had. */ + +typedef struct { + uint8_t (*cid)[32]; /* causal identity of crumb id, at [id - 1] */ + uint8_t (*content)[32]; /* content digest (no links), at [id - 1] */ + int *seg; /* segment of crumb id */ + size_t *rec; /* record index of crumb id */ + uint64_t n; /* crumbs */ + int n_seg; /* segments (INPUT records + 1) */ + uint64_t superseded; +} causal_ix; + +static void causal_free(causal_ix *x) { + free(x->cid); free(x->content); free(x->seg); free(x->rec); + memset(x, 0, sizeof *x); +} + +static void ch32(sha256_ctx *c, uint32_t v) { + uint8_t b[4] = { (uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24) }; + sha256_update(c, b, 4); +} +static void ch64(sha256_ctx *c, uint64_t v) { ch32(c, (uint32_t)v); ch32(c, (uint32_t)(v >> 32)); } + +static int cmp32(const void *a, const void *b) { return memcmp(a, b, 32); } + +/* Index a log that verify_log accepted (ids dense, links point back). */ +static int causal_index(const rxl_log *l, causal_ix *x) { + memset(x, 0, sizeof *x); + size_t cap = l->n + 1; + x->cid = calloc(cap, 32); x->content = calloc(cap, 32); + x->seg = calloc(cap, sizeof *x->seg); x->rec = calloc(cap, sizeof *x->rec); + uint8_t (*ps)[32] = calloc(RXL_MAX_PARENTS, 32); + if (!x->cid || !x->content || !x->seg || !x->rec || !ps) { free(ps); causal_free(x); return -1; } + int seg = 0; + for (size_t i = 0; i < l->n; i++) { + const rxl_rec *r = &l->recs[i]; + if (r->type == RXL_INPUT) { seg++; continue; } + if (r->type != RXL_CRUMB) continue; + const rxl_crumb *k = &r->u.c; + uint64_t j = x->n++; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"RXCLOG01-CAUSAL-CONTENT", 23); + ch32(&c, k->kind); ch32(&c, k->reaction); ch32(&c, k->faculty); + ch32(&c, k->n_inputs); + for (uint32_t q = 0; q < k->n_inputs; q++) { + ch32(&c, k->inputs[q].id); ch32(&c, k->inputs[q].gen); + ch64(&c, k->inputs[q].version); ch64(&c, k->inputs[q].mask); + } + ch32(&c, k->n_caps); + for (uint32_t q = 0; q < k->n_caps; q++) { + ch32(&c, k->caps[q].cap_id); ch64(&c, k->caps[q].gen); ch32(&c, k->caps[q].issuer); + } + ch32(&c, k->n_outputs); + for (uint32_t q = 0; q < k->n_outputs; q++) { + ch32(&c, k->outputs[q].id); ch32(&c, k->outputs[q].gen); + ch64(&c, k->outputs[q].version); ch64(&c, k->outputs[q].mask); + } + ch32(&c, (uint32_t)k->reason); + sha256_final(&c, x->content[j]); + /* links by identity: wake cause, then the sorted set of parents */ + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"RXCLOG01-CAUSAL-ID", 18); + sha256_update(&c, x->content[j], 32); + uint8_t z[32] = { 0 }; + ch32(&c, k->wake_cause ? 1u : 0u); + sha256_update(&c, k->wake_cause ? x->cid[k->wake_cause - 1] : z, 32); + for (uint32_t q = 0; q < k->n_parents; q++) memcpy(ps[q], x->cid[k->parents[q] - 1], 32); + qsort(ps, k->n_parents, 32, cmp32); + ch32(&c, k->n_parents); + for (uint32_t q = 0; q < k->n_parents; q++) sha256_update(&c, ps[q], 32); + sha256_final(&c, x->cid[j]); + x->seg[j] = seg; + x->rec[j] = i; + if (k->kind == RXL_K_INVALIDATED) x->superseded++; + } + x->n_seg = seg + 1; + free(ps); + return 0; +} + +/* Every superseded entry flagged and paired with its rerun. */ +static int causal_superseded(const rxl_log *l, const causal_ix *x, const char *side, verdict *v) { + char a[80], b[80]; + for (uint64_t j = 0; j < x->n; j++) { + const rxl_crumb *k = &l->recs[x->rec[j]].u.c; + if (k->kind != RXL_K_INVALIDATED) continue; + if (k->reason == 0 || k->n_outputs) { + snprintf(a, sizeof a, "flagged:reason!=0,outputs=0"); + snprintf(b, sizeof b, "reason:%d,outputs:%u", (int)k->reason, k->n_outputs); + return diverge(v, x->rec[j] + 1, "world.superseded", a, b, + "%s crumb %llu: superseded entry is not flagged as superseded", side, (unsigned long long)k->id); + } + int paired = 0; + for (uint64_t q = j + 1; q < x->n && !paired; q++) { + const rxl_crumb *y = &l->recs[x->rec[q]].u.c; + if (x->seg[q] == x->seg[j] && y->reaction == k->reaction && y->episode == k->episode && + y->kind != RXL_K_INVALIDATED) paired = 1; + } + if (!paired) { + snprintf(b, sizeof b, "crumb:%llu", (unsigned long long)k->id); + return diverge(v, x->rec[j] + 1, "world.superseded", "rerun", b, + "%s crumb %llu: superseded entry has no rerun of reaction %u in episode %llu", + side, (unsigned long long)k->id, k->reaction, (unsigned long long)k->episode); + } + } + return 0; +} + +static int same_input(const rxl_input *p, const rxl_input *q) { + if (p->cap_id != q->cap_id || p->cap_gen != q->cap_gen || p->n != q->n) return 0; + for (uint32_t i = 0; i < p->n; i++) + if (p->m[i].id != q->m[i].id || p->m[i].gen != q->m[i].gen || p->m[i].field != q->m[i].field || + p->m[i].value != q->m[i].value) return 0; + return 1; +} + +/* Records of one segment: [*lo, *hi). */ +static void seg_bounds(const rxl_log *l, int seg, size_t *lo, size_t *hi) { + int s = 0; + size_t i = 0; + while (i < l->n && s < seg) { if (l->recs[i].type == RXL_INPUT) s++; i++; } + *lo = i; + while (i < l->n && l->recs[i].type != RXL_INPUT && l->recs[i].type != RXL_END) i++; + *hi = i; +} + +static int causal_state(const rxl_checkpoint *p, const causal_ix *xa, const rxl_checkpoint *q, + const causal_ix *xb, uint64_t ev, verdict *v) { + char a[80], b[80]; + if (p->n_obj != q->n_obj) { + snprintf(a, sizeof a, "objects:%u", p->n_obj); + snprintf(b, sizeof b, "objects:%u", q->n_obj); + return diverge(v, ev, "world.state", a, b, "state tables have different object counts"); + } + for (uint32_t o = 0; o < p->n_obj; o++) { + const rxl_obj *s = &p->obj[o], *t = &q->obj[o]; + if (s->id != t->id || s->gen != t->gen || s->type != t->type || s->version != t->version) { + snprintf(a, sizeof a, "obj:%u/%u:t%u@v%llu", s->id, s->gen, s->type, (unsigned long long)s->version); + snprintf(b, sizeof b, "obj:%u/%u:t%u@v%llu", t->id, t->gen, t->type, (unsigned long long)t->version); + return diverge(v, ev, "world.state", a, b, "object %u identity or version differs", o); + } + for (uint32_t f = 0; f < RXL_MAX_FIELDS; f++) { + if (s->value[f] != t->value[f] || s->fversion[f] != t->fversion[f]) { + snprintf(a, sizeof a, "value:%llu@v%llu", (unsigned long long)s->value[f], (unsigned long long)s->fversion[f]); + snprintf(b, sizeof b, "value:%llu@v%llu", (unsigned long long)t->value[f], (unsigned long long)t->fversion[f]); + return diverge(v, ev, "world.state", a, b, "object %u field %u value or field version differs", s->id, f); + } + uint64_t wa = s->writer[f], wb = t->writer[f]; + int same = (!wa && !wb) || + (wa && wb && wa <= xa->n && wb <= xb->n && !memcmp(xa->cid[wa - 1], xb->cid[wb - 1], 32)); + if (!same) { + snprintf(a, sizeof a, "writer:crumb%llu", (unsigned long long)wa); + snprintf(b, sizeof b, "writer:crumb%llu", (unsigned long long)wb); + return diverge(v, ev, "world.state", a, b, + "object %u field %u: snapshot writer differs by causal identity", s->id, f); + } + } + } + return 0; +} + +static int causal_segment(const rxl_log *A, const causal_ix *xa, const rxl_log *B, const causal_ix *xb, + int seg, verdict *v) { + char a[80], b[80]; + size_t la, ha, lb, hb; + seg_bounds(A, seg, &la, &ha); + seg_bounds(B, seg, &lb, &hb); + if (seg > 0 && !same_input(&A->recs[la - 1].u.in, &B->recs[lb - 1].u.in)) { + uint8_t dx[32], dy[32]; + rxl_event_digest(&A->recs[la - 1], dx); rxl_event_digest(&B->recs[lb - 1], dy); + hexs(a, dx); hexs(b, dy); + diverge(v, la, "world.input", a, b, "INPUT %d differs (capability, mutations or values)", seg); + rec_line(&A->recs[la - 1], v->rec_exp, sizeof v->rec_exp); + rec_line(&B->recs[lb - 1], v->rec_act, sizeof v->rec_act); + return 1; + } + /* entries of this segment, superseded ones left out */ + uint64_t *ea = calloc(xa->n + 1, sizeof *ea), *eb = calloc(xb->n + 1, sizeof *eb); + char *used = calloc(xb->n + 1, 1); + if (!ea || !eb || !used) { free(ea); free(eb); free(used); return diverge(v, 0, "verifier", "memory", "none", "out of memory"); } + size_t na = 0, nb = 0; + for (uint64_t j = 0; j < xa->n; j++) + if (xa->seg[j] == seg && A->recs[xa->rec[j]].u.c.kind != RXL_K_INVALIDATED) ea[na++] = j; + for (uint64_t j = 0; j < xb->n; j++) + if (xb->seg[j] == seg && B->recs[xb->rec[j]].u.c.kind != RXL_K_INVALIDATED) eb[nb++] = j; + int bad = 0; + /* A reaction with more entries in the replayed stimulus than in the + * expected one ran again after a run that was logged as committed: a + * superseded run without its flag. Named before the entry match so the + * report says what happened, not only which entry differs. */ + for (size_t q = 0; q < nb && !bad; q++) { + const rxl_crumb *y = &B->recs[xb->rec[eb[q]]].u.c; + if (y->kind == RXL_K_EXTERNAL || y->kind == RXL_K_CREATE) continue; + size_t ca = 0, cb = 0; + for (size_t p = 0; p < nb; p++) { + const rxl_crumb *z = &B->recs[xb->rec[eb[p]]].u.c; + if (z->reaction == y->reaction && z->kind != RXL_K_EXTERNAL && z->kind != RXL_K_CREATE) cb++; + } + for (size_t p = 0; p < na; p++) { + const rxl_crumb *z = &A->recs[xa->rec[ea[p]]].u.c; + if (z->reaction == y->reaction && z->kind != RXL_K_EXTERNAL && z->kind != RXL_K_CREATE) ca++; + } + if (cb > ca) { + snprintf(a, sizeof a, "reaction%u:entries=%zu", y->reaction, ca); + snprintf(b, sizeof b, "reaction%u:entries=%zu", y->reaction, cb); + diverge(v, xb->rec[eb[q]] + 1, "world.superseded", a, b, + "stimulus %d: unflagged superseded entry (reaction %u logged as committed %zu times, expected %zu; first at replay crumb %llu)", + seg, y->reaction, cb, ca, (unsigned long long)y->id); + rec_line(&B->recs[xb->rec[eb[q]]], v->rec_act, sizeof v->rec_act); + bad = 1; + } + } + for (size_t i = 0; i < na && !bad; i++) { + uint64_t ja = ea[i]; + size_t hit = nb; + for (size_t q = 0; q < nb && hit == nb; q++) + if (!used[q] && !memcmp(xa->cid[ja], xb->cid[eb[q]], 32)) hit = q; + if (hit < nb) { used[hit] = 1; continue; } + const rxl_rec *ra = &A->recs[xa->rec[ja]]; + const rxl_crumb *k = &ra->u.c; + hexs(a, xa->cid[ja]); + size_t near = nb; + for (size_t q = 0; q < nb && near == nb; q++) + if (!used[q] && !memcmp(xa->content[ja], xb->content[eb[q]], 32)) near = q; + if (near < nb) { + hexs(b, xb->cid[eb[near]]); + diverge(v, xa->rec[ja] + 1, "world.cause", a, b, + "crumb %llu: same entry, different cause links (wake cause or parents, by identity; replay crumb %llu)", + (unsigned long long)k->id, (unsigned long long)eb[near] + 1); + } else { + for (size_t q = 0; q < nb && near == nb; q++) { + const rxl_crumb *y = &B->recs[xb->rec[eb[q]]].u.c; + if (!used[q] && y->kind == k->kind && y->reaction == k->reaction) near = q; + } + if (near < nb) { + hexs(b, xb->cid[eb[near]]); + diverge(v, xa->rec[ja] + 1, "world.causal", a, b, + "crumb %llu: committed entry differs (replay crumb %llu)", (unsigned long long)k->id, + (unsigned long long)eb[near] + 1); + } else { + diverge(v, xa->rec[ja] + 1, "world.causal", a, "none", + "crumb %llu: entry missing from the replayed run", (unsigned long long)k->id); + } + } + rec_line(ra, v->rec_exp, sizeof v->rec_exp); + if (near < nb) rec_line(&B->recs[xb->rec[eb[near]]], v->rec_act, sizeof v->rec_act); + bad = 1; + } + for (size_t q = 0; q < nb && !bad; q++) { + if (used[q]) continue; + const rxl_rec *rb = &B->recs[xb->rec[eb[q]]]; + const rxl_crumb *y = &rb->u.c; + int twice = 0; + for (size_t p = 0; p < nb && !twice; p++) { + const rxl_crumb *z = &B->recs[xb->rec[eb[p]]].u.c; + if (p != q && z->reaction == y->reaction && z->episode == y->episode && y->kind != RXL_K_EXTERNAL) twice = 1; + } + hexs(b, xb->cid[eb[q]]); + if (twice) + diverge(v, xb->rec[eb[q]] + 1, "world.superseded", "none", b, + "replay crumb %llu: unflagged superseded entry (reaction %u has another entry in episode %llu)", + (unsigned long long)y->id, y->reaction, (unsigned long long)y->episode); + else + diverge(v, xb->rec[eb[q]] + 1, "world.causal", "none", b, "replay crumb %llu: extra entry", + (unsigned long long)y->id); + rec_line(rb, v->rec_act, sizeof v->rec_act); + bad = 1; + } + free(ea); free(eb); free(used); + if (bad) return 1; + /* checkpoints of this segment, pairwise in order */ + size_t ia = la, ib = lb; + for (;;) { + while (ia < ha && A->recs[ia].type != RXL_CHECKPOINT) ia++; + while (ib < hb && B->recs[ib].type != RXL_CHECKPOINT) ib++; + if (ia >= ha && ib >= hb) break; + if (ia >= ha || ib >= hb) { + snprintf(a, sizeof a, "%s", ia < ha ? "checkpoint" : "none"); + snprintf(b, sizeof b, "%s", ib < hb ? "checkpoint" : "none"); + return diverge(v, ia < ha ? ia + 1 : ha, "world.state", a, b, "segment %d: checkpoint counts differ", seg); + } + const rxl_checkpoint *p = &A->recs[ia].u.ck, *q = &B->recs[ib].u.ck; + if (!q->n_obj) + return diverge(v, ia + 1, "world.state", "state-table", "hash-only", + "replayed CHECKPOINT has no state table: writers cannot be matched by identity"); + if (p->subsystem != q->subsystem || causal_state(p, xa, q, xb, ia + 1, v)) { + if (!v->diverged) { + snprintf(a, sizeof a, "subsystem:%u", p->subsystem); + snprintf(b, sizeof b, "subsystem:%u", q->subsystem); + diverge(v, ia + 1, "world.state", a, b, "checkpoint subsystems differ"); + } + return 1; + } + ia++; ib++; + } + return 0; +} + +static int compare_causal(const char *pa, const char *pb) { + rxl_log A, B; + char err[160]; + verdict v; + if (rxl_read(pa, &A, err, sizeof err)) { fprintf(stderr, "rx_replay: expected log: %s\n", err); return 2; } + if (verify_log(&A, &v)) { + printf("REFUSED expected log does not verify: event=%llu subsystem=%s (%s)\n", + (unsigned long long)v.event, v.subsystem, v.detail); + rxl_free(&A); + return 2; + } + for (size_t i = 0; i < A.n; i++) + if (A.recs[i].type == RXL_CHECKPOINT && !A.recs[i].u.ck.n_obj) { + printf("REFUSED expected log has a CHECKPOINT without a state table (event %zu)\n", i + 1); + rxl_free(&A); + return 2; + } + if (rxl_read(pb, &B, err, sizeof err)) { + printf("DIVERGENCE event=1 expected=RXCLOG01 actual=unreadable subsystem=world.log\ndetail: %s\n", err); + rxl_free(&A); + return 1; + } + /* The replayed log must hold its own rules first: dense ids, links that + * point back, recomputed digests, END chain, state tables that hash. */ + if (verify_log(&B, &v)) { rxl_free(&A); rxl_free(&B); return report(&v); } + causal_ix xa, xb; + if (causal_index(&A, &xa) || causal_index(&B, &xb)) { + causal_free(&xa); rxl_free(&A); rxl_free(&B); + fprintf(stderr, "rx_replay: out of memory\n"); + return 2; + } + memset(&v, 0, sizeof v); + char a[80], b[80]; + if (xa.n_seg != xb.n_seg) { + snprintf(a, sizeof a, "inputs:%d", xa.n_seg - 1); + snprintf(b, sizeof b, "inputs:%d", xb.n_seg - 1); + diverge(&v, 1, "world.input", a, b, "different number of INPUT records"); + } + if (!v.diverged) causal_superseded(&A, &xa, "expected", &v); + if (!v.diverged) causal_superseded(&B, &xb, "replayed", &v); + for (int s = 0; s < xa.n_seg && !v.diverged; s++) causal_segment(&A, &xa, &B, &xb, s, &v); + int rc; + if (v.diverged) rc = report(&v); + else { + printf("MATCH through event %llu (causal order: %d segments, %llu crumbs expected, %llu replayed; " + "superseded expected=%llu replayed=%llu; merged-wake counts excluded)\n", + (unsigned long long)(A.n - 1), xa.n_seg, (unsigned long long)xa.n, (unsigned long long)xb.n, + (unsigned long long)xa.superseded, (unsigned long long)xb.superseded); + rc = 0; + } + causal_free(&xa); causal_free(&xb); + rxl_free(&A); rxl_free(&B); + return rc; +} + +/* ---- M22 dispatch.log --------------------------------------------------- */ + +#define D_SIZE 192u +#define D_HASHED 160u +#define D_MAGIC 0x31444754u +#define G_HDR 152u + +static uint32_t g32(const uint8_t *p) { + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} +static uint64_t g64(const uint8_t *p) { return (uint64_t)g32(p) | (uint64_t)g32(p + 4) << 32; } + +static uint8_t *slurp(const char *path, size_t *len) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + size_t cap = 4096, n = 0; + uint8_t *b = malloc(cap); + if (!b) { fclose(f); return NULL; } + for (;;) { + if (n == cap) { + uint8_t *nb = realloc(b, cap *= 2); + if (!nb) { free(b); fclose(f); return NULL; } + b = nb; + } + size_t g = fread(b + n, 1, cap - n, f); + if (!g) break; + n += g; + } + fclose(f); + *len = n; + return b; +} + +/* Every file path the verifier builds fits in RX_PATH_CAP bytes or is + * refused. A silently truncated path can name a different file (or the + * store directory itself), so truncation is a hard error, never a guess. */ +#define RX_PATH_CAP 4096 + +/* Build DIR/NAME into out[cap]. 0 = built; -1 = would not fit (out is + * emptied and the reason goes to stderr). */ +static int join_path(char *out, size_t cap, const char *dir, const char *name) { + int w = snprintf(out, cap, "%s/%s", dir, name); + if (w < 0 || (size_t)w >= cap) { + fprintf(stderr, "rx_replay: path too long (%d bytes, limit %zu): %s/%s\n", w, cap - 1, dir, name); + if (cap) out[0] = 0; + return -1; + } + return 0; +} + +static void chain_step(const uint8_t prev[32], const uint8_t *rec, uint8_t out[32]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, prev, 32); + sha256_update(&c, rec, D_HASHED); + sha256_final(&c, out); +} + +/* Structure of one record beyond the chain: magic, seq, ref count, and the + * bytes the writer leaves zero (tg_dispatch memsets the record). */ +static const char *dispatch_shape(const uint8_t *r, uint64_t seq) { + if (g32(r) != D_MAGIC) return "magic"; + if (g64(r + 8) != seq) return "seq"; + uint32_t nr = g32(r + 48); + if (nr > 3) return "n_refs"; + for (int i = 52; i < 56; i++) if (r[i]) return "padding"; + for (uint32_t i = 0; i < 3; i++) { + const uint8_t *q = r + 56 + 24 * i; + if (i < nr) { for (int j = 4; j < 8; j++) if (q[j]) return "padding"; } + else { for (int j = 0; j < 24; j++) if (q[j]) return "unused ref"; } + } + return NULL; +} + +static const char *dispatch_field_diff(const uint8_t *x, const uint8_t *y) { + static const struct { int off, len; const char *name; } f[] = { + { 0, 4, "magic" }, { 4, 4, "op_id" }, { 8, 8, "seq" }, { 16, 8, "step" }, { 24, 8, "base_gen" }, + { 32, 8, "arg0" }, { 40, 8, "arg1" }, { 48, 8, "n_refs" }, { 56, 72, "refs" }, + { 128, 32, "base_digest" }, { 160, 32, "chain" } }; + for (size_t i = 0; i < sizeof f / sizeof f[0]; i++) + if (memcmp(x + f[i].off, y + f[i].off, (size_t)f[i].len)) return f[i].name; + return "none"; +} + +/* Read CURRENT and the generation it names: committed dispatch length and + * head. 0 = read, 1 = store has no CURRENT, -1 = malformed. */ +static int committed_head(const char *dir, uint64_t *len, uint8_t head[32], char *why, size_t wn) { + char p[RX_PATH_CAP]; + if (join_path(p, sizeof p, dir, "CURRENT")) { + snprintf(why, wn, "store path too long"); + return -1; + } + size_t n; + errno = 0; + uint8_t *cur = slurp(p, &n); + if (!cur) { + if (errno == ENOENT) return 1; + snprintf(why, wn, "CURRENT unreadable"); + return -1; + } + if (n != 95 || memcmp(cur, "OMTRCUR1 ", 9) || cur[29] != ' ' || cur[94] != '\n') { + free(cur); + snprintf(why, wn, "CURRENT malformed"); + return -1; + } + char gen[21], hexd[65]; + memcpy(gen, cur + 9, 20); gen[20] = 0; + memcpy(hexd, cur + 30, 64); hexd[64] = 0; + free(cur); + char gname[32]; /* "gen-" + 20 + ".bin" + NUL = 29 */ + snprintf(gname, sizeof gname, "gen-%s.bin", gen); + if (join_path(p, sizeof p, dir, gname)) { + snprintf(why, wn, "store path too long"); + return -1; + } + uint8_t *g = slurp(p, &n); + if (!g || n < G_HDR) { + free(g); + snprintf(why, wn, "generation file gen-%s.bin missing or short", gen); + return -1; + } + /* The generation digest covers header bytes [0,120) + parameters + optimizer. */ + uint8_t d[32]; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, g, 120); + sha256_update(&c, g + G_HDR, n - G_HDR); + sha256_final(&c, d); + char dh[65]; + rxl_hex(d, 32, dh); + if (memcmp(d, g + 120, 32) || strcmp(dh, hexd)) { + free(g); + snprintf(why, wn, "generation gen-%s.bin does not verify against CURRENT", gen); + return -1; + } + *len = g64(g + 48); + memcpy(head, g + 56, 32); + free(g); + return 0; +} + +static int verify_dispatch(const char *dir, verdict *v, uint8_t **out_log, size_t *out_n) { + memset(v, 0, sizeof *v); + char p[RX_PATH_CAP], a[80], b[80], why[160]; + if (join_path(p, sizeof p, dir, "dispatch.log")) + return diverge(v, 1, "m22.commit", "store-path", "too-long", "store path too long"); + size_t n = 0; + uint8_t *log = slurp(p, &n); + if (!log) { log = calloc(1, 1); n = 0; } + uint64_t clen = 0; + uint8_t chead[32]; + int ch = committed_head(dir, &clen, chead, why, sizeof why); + if (ch < 0) { free(log); return diverge(v, 1, "m22.commit", "committed-store", "malformed", "%s", why); } + if (ch == 0 && n < clen) { + snprintf(a, sizeof a, "bytes:%llu", (unsigned long long)clen); + snprintf(b, sizeof b, "bytes:%llu", (unsigned long long)n); + free(log); + return diverge(v, n / D_SIZE + 1, "m22.dispatch", a, b, "dispatch.log shorter than the committed length (records omitted)"); + } + uint64_t upto = ch == 0 ? clen : n - n % D_SIZE; + if (upto % D_SIZE) { + free(log); + return diverge(v, upto / D_SIZE + 1, "m22.commit", "whole-records", "partial", "committed length is not whole records"); + } + uint8_t head[32] = { 0 }; + for (uint64_t i = 0; i < upto / D_SIZE; i++) { + const uint8_t *r = log + i * D_SIZE; + const char *bad = dispatch_shape(r, i); + if (bad) { + snprintf(a, sizeof a, "seq:%llu", (unsigned long long)i); + if (!strcmp(bad, "seq")) snprintf(b, sizeof b, "seq:%llu", (unsigned long long)g64(r + 8)); + else snprintf(b, sizeof b, "bad-%s", bad); + free(log); + return diverge(v, i + 1, "m22.dispatch", a, b, "record %llu malformed: %s", (unsigned long long)i, bad); + } + uint8_t nh[32]; + chain_step(head, r, nh); + if (memcmp(nh, r + D_HASHED, 32)) { + hexs(a, nh); hexs(b, r + D_HASHED); + free(log); + return diverge(v, i + 1, "m22.dispatch", a, b, "record %llu: chain does not recompute", (unsigned long long)i); + } + memcpy(head, nh, 32); + } + if (ch == 0 && memcmp(head, chead, 32)) { + hexs(a, chead); hexs(b, head); + free(log); + return diverge(v, upto / D_SIZE, "m22.commit", a, b, "chain head does not match the committed generation"); + } + if (ch == 1 && n % D_SIZE) { + free(log); + return diverge(v, n / D_SIZE + 1, "m22.dispatch", "record", "truncated", "dispatch.log ends inside a record"); + } + if (n > upto) + snprintf(v->detail, sizeof v->detail, "%llu uncommitted bytes after the committed head (recovery drops them)", + (unsigned long long)(n - upto)); + v->event = upto / D_SIZE; + if (out_log) { *out_log = log; *out_n = upto; } else free(log); + return 0; +} + +static int compare_dispatch(const char *da, const char *db) { + verdict v; + uint8_t *A, *B; + size_t na, nb; + if (verify_dispatch(da, &v, &A, &na)) { + printf("REFUSED expected store does not verify: event=%llu subsystem=%s (%s)\n", + (unsigned long long)v.event, v.subsystem, v.detail); + return 2; + } + if (verify_dispatch(db, &v, &B, &nb)) { free(A); return report(&v); } + memset(&v, 0, sizeof v); + char a[80], b[80]; + for (size_t i = 0; i * D_SIZE < na || i * D_SIZE < nb; i++) { + if (i * D_SIZE >= nb) { + hexs(a, A + i * D_SIZE + D_HASHED); + diverge(&v, i + 1, "m22.dispatch", a, "none", "replayed log stops early"); + break; + } + if (i * D_SIZE >= na) { + hexs(b, B + i * D_SIZE + D_HASHED); + diverge(&v, i + 1, "m22.dispatch", "none", b, "replayed log has an extra record"); + break; + } + const uint8_t *x = A + i * D_SIZE, *y = B + i * D_SIZE; + if (memcmp(x + D_HASHED, y + D_HASHED, 32)) { + hexs(a, x + D_HASHED); hexs(b, y + D_HASHED); + diverge(&v, i + 1, "m22.dispatch", a, b, "record %zu differs first in: %s", i, dispatch_field_diff(x, y)); + break; + } + } + if (!v.diverged) v.event = na / D_SIZE; + free(A); free(B); + return report(&v); +} + +/* ---- TRN1 ---------------------------------------------------------------- */ + +static int trn1_verify_cmd(const char *path) { + size_t n = 0; + uint8_t *b = slurp(path, &n); + if (!b) { fprintf(stderr, "rx_replay: cannot read %s\n", path); return 2; } + trn1_result r; + trn1_verify(b, n, &r); + char line[256]; + trn1_verify_line(&r, line, sizeof line); + trn1_result_free(&r); + free(b); + puts(line); + return r.code ? 1 : 0; +} + +static int trn1_compare_cmd(const char *pa, const char *pb) { + size_t na = 0, nb = 0; + uint8_t *a = slurp(pa, &na), *b = slurp(pb, &nb); + if (!a || !b) { free(a); free(b); fprintf(stderr, "rx_replay: cannot read input\n"); return 2; } + char line[256]; + trn1_compare_line(a, na, b, nb, line, sizeof line); + free(a); free(b); + puts(line); + return !strncmp(line, "MATCH", 5) ? 0 : !strncmp(line, "refuse expected", 15) ? 2 : 1; +} + +/* Run a TRN1 corpus: every expected.txt and compare.txt line must be + * reproduced exactly. Prints each mismatch and the conformance line. */ +static int trn1_corpus(const char *dir) { + char p[RX_PATH_CAP], l[1024], line[256]; + int pass = 0, fail = 0; + for (int which = 0; which < 2; which++) { + if (join_path(p, sizeof p, dir, which ? "compare.txt" : "expected.txt")) return 2; + FILE *f = fopen(p, "r"); + if (!f) { fprintf(stderr, "rx_replay: cannot open %s\n", p); return 2; } + while (fgets(l, sizeof l, f)) { + size_t ll = strlen(l); + if (ll && l[ll - 1] != '\n' && !feof(f)) { + /* fgets split the line: refuse it instead of reading two halves. */ + printf("MISMATCH %s: line longer than %zu bytes\n", p, sizeof l - 2); + fail++; + int c; + while ((c = fgetc(f)) != EOF && c != '\n') {} + continue; + } + l[strcspn(l, "\r\n")] = 0; + if (!l[0] || l[0] == '#') continue; + char a[RX_PATH_CAP], b[RX_PATH_CAP]; + const char *want; + char *s1 = strchr(l, ' '); + if (!s1) { fail++; continue; } + *s1 = 0; + if (join_path(a, sizeof a, dir, l)) { printf("MISMATCH %s: path too long\n", l); fail++; continue; } + size_t na = 0, nb = 0; + uint8_t *A = slurp(a, &na), *B = NULL; + if (!A) { A = calloc(1, 1); na = 0; } + if (which) { + char *s2 = strchr(s1 + 1, ' '); + if (!s2) { free(A); fail++; continue; } + *s2 = 0; + if (join_path(b, sizeof b, dir, s1 + 1)) { + printf("MISMATCH %s: path too long\n", s1 + 1); + free(A); fail++; continue; + } + B = slurp(b, &nb); + if (!B) { B = calloc(1, 1); nb = 0; } + want = s2 + 1; + trn1_compare_line(A, na, B, nb, line, sizeof line); + } else { + want = s1 + 1; + trn1_result r; + trn1_verify(A, na, &r); + trn1_verify_line(&r, line, sizeof line); + trn1_result_free(&r); + } + if (!strcmp(line, want)) pass++; + else { fail++; printf("MISMATCH %s%s%s\n want %s\n got %s\n", l, which ? " " : "", which ? s1 + 1 : "", want, line); } + free(A); free(B); + } + fclose(f); + } + printf("TRN1_CONFORMANCE impl=omega-c pass=%d fail=%d\n", pass, fail); + return fail ? 1 : 0; +} + +static int trn1_export(const char *in, const char *out) { + rxl_log l; + char err[160]; + if (rxl_read(in, &l, err, sizeof err)) { fprintf(stderr, "rx_replay: %s\n", err); return 2; } + if (l.malformed) { fprintf(stderr, "rx_replay: %s: %s\n", in, l.why); rxl_free(&l); return 2; } + uint8_t *b; + size_t n; + int rc = trn1_from_rxlog(&l, &b, &n); + rxl_free(&l); + if (rc) { fprintf(stderr, "rx_replay: export failed\n"); return 2; } + FILE *f = fopen(out, "wb"); + rc = !f || fwrite(b, 1, n, f) != n; + if (f && fclose(f)) rc = 1; + free(b); + return rc ? 2 : 0; +} + +/* Flip every bit of a valid transcript, one at a time: each must be refused. + * Prints the number of accepted flips (survivors), which must be 0. */ +static int trn1_flipall(const char *path) { + size_t n = 0; + uint8_t *b = slurp(path, &n); + if (!b) return 2; + trn1_result r; + if (trn1_verify(b, n, &r)) { trn1_result_free(&r); free(b); printf("REFUSED input does not verify\n"); return 2; } + trn1_result_free(&r); + uint64_t tried = 0, survived = 0; + for (size_t i = 0; i < n; i++) + for (int bit = 0; bit < 8; bit++) { + b[i] ^= (uint8_t)(1u << bit); + if (trn1_verify(b, n, &r) == TRN1_OK) { + if (survived < 5) printf("survivor: byte %zu bit %d\n", i, bit); + survived++; + } + trn1_result_free(&r); + b[i] ^= (uint8_t)(1u << bit); + tried++; + } + free(b); + printf("TRN1_BITFLIP tried=%llu survived=%llu\n", (unsigned long long)tried, (unsigned long long)survived); + return survived ? 1 : 0; +} + +int main(int argc, char **argv) { + if (argc == 3 && !strcmp(argv[1], "verify-trn1")) return trn1_verify_cmd(argv[2]); + if (argc == 4 && !strcmp(argv[1], "compare-trn1")) return trn1_compare_cmd(argv[2], argv[3]); + if (argc == 3 && !strcmp(argv[1], "trn1-corpus")) return trn1_corpus(argv[2]); + if (argc == 4 && !strcmp(argv[1], "export-trn1")) return trn1_export(argv[2], argv[3]); + if (argc == 3 && !strcmp(argv[1], "trn1-flipall")) return trn1_flipall(argv[2]); + if (argc == 3 && !strcmp(argv[1], "verify")) { + rxl_log l; + char err[160]; + verdict v; + if (rxl_read(argv[2], &l, err, sizeof err)) { + printf("DIVERGENCE event=1 expected=RXCLOG01 actual=unreadable subsystem=world.log\ndetail: %s\n", err); + return 1; + } + verify_log(&l, &v); + rxl_free(&l); + return report(&v); + } + if (argc == 4 && !strcmp(argv[1], "compare")) return compare_logs(argv[2], argv[3]); + if (argc == 4 && !strcmp(argv[1], "compare-causal")) return compare_causal(argv[2], argv[3]); + if (argc == 3 && !strcmp(argv[1], "verify-dispatch")) { + verdict v; + verify_dispatch(argv[2], &v, NULL, NULL); + int rc = report(&v); + if (!rc && v.detail[0]) printf("detail: %s\n", v.detail); + return rc; + } + if (argc == 4 && !strcmp(argv[1], "compare-dispatch")) return compare_dispatch(argv[2], argv[3]); + fprintf(stderr, "usage: rx_replay verify LOG | compare EXPECTED ACTUAL | compare-causal EXPECTED ACTUAL |\n" + " verify-dispatch DIR | compare-dispatch DIR_A DIR_B |\n" + " export-trn1 RXLOG OUT.trn | verify-trn1 FILE | compare-trn1 EXPECTED ACTUAL |\n" + " trn1-corpus VECTORS_DIR | trn1-flipall FILE\n"); + return 2; +} diff --git a/tools/replay/rxlog.c b/tools/replay/rxlog.c new file mode 100644 index 000000000..ddf3260d2 --- /dev/null +++ b/tools/replay/rxlog.c @@ -0,0 +1,347 @@ +/* rxlog.c -- RXCLOG01 reader/writer and the independent crumb digest. */ +#include "replay/rxlog.h" +#include "sha256.h" + +#include +#include +#include + +static void w32(uint8_t **p, uint32_t v) { for (int i = 0; i < 4; i++) *(*p)++ = (uint8_t)(v >> (8 * i)); } +static void w64(uint8_t **p, uint64_t v) { for (int i = 0; i < 8; i++) *(*p)++ = (uint8_t)(v >> (8 * i)); } + +typedef struct { const uint8_t *p; size_t left; int bad; } rd; +static uint32_t r32(rd *r) { + if (r->left < 4) { r->bad = 1; return 0; } + uint32_t v = 0; + for (int i = 3; i >= 0; i--) v = (v << 8) | r->p[i]; + r->p += 4; r->left -= 4; + return v; +} +static uint64_t r64(rd *r) { + uint64_t lo = r32(r), hi = r32(r); + return lo | (hi << 32); +} +static void rbytes(rd *r, uint8_t *out, size_t n) { + if (r->left < n) { r->bad = 1; memset(out, 0, n); return; } + memcpy(out, r->p, n); r->p += n; r->left -= n; +} + +void rxl_init(rxl_log *l, uint32_t flags) { + memset(l, 0, sizeof *l); + l->version = RXL_VERSION; + l->flags = flags; +} + +void rxl_free(rxl_log *l) { free(l->recs); memset(l, 0, sizeof *l); } + +int rxl_push(rxl_log *l, const rxl_rec *r) { + if (l->n == l->cap) { + size_t nc = l->cap ? l->cap * 2 : 64; + rxl_rec *n = realloc(l->recs, nc * sizeof *n); + if (!n) return -1; + l->recs = n; l->cap = nc; + } + l->recs[l->n++] = *r; + return 0; +} + +static void enc_io(uint8_t **p, const rxl_io *io) { w32(p, io->id); w32(p, io->gen); w64(p, io->version); w64(p, io->mask); } + +size_t rxl_encode(const rxl_rec *r, uint8_t *buf) { + uint8_t *p = buf; + switch (r->type) { + case RXL_CRUMB: { + const rxl_crumb *k = &r->u.c; + w64(&p, k->id); w32(&p, k->kind); w32(&p, k->reaction); w32(&p, k->faculty); w32(&p, k->worker); + w64(&p, k->wake_cause); w64(&p, k->coalesced); + w32(&p, k->n_inputs); + for (uint32_t i = 0; i < k->n_inputs && i < RXL_MAX_DEPS; i++) enc_io(&p, &k->inputs[i]); + w32(&p, k->n_caps); + for (uint32_t i = 0; i < k->n_caps && i < RXL_MAX_CAPS; i++) { + w32(&p, k->caps[i].cap_id); w64(&p, k->caps[i].gen); w32(&p, k->caps[i].issuer); + } + w32(&p, k->n_outputs); + for (uint32_t i = 0; i < k->n_outputs && i < RXL_MAX_WRITES; i++) enc_io(&p, &k->outputs[i]); + w32(&p, (uint32_t)k->reason); + w32(&p, k->n_parents); + for (uint32_t i = 0; i < k->n_parents && i < RXL_MAX_PARENTS; i++) w64(&p, k->parents[i]); + w64(&p, k->t_start); w64(&p, k->t_end); w64(&p, k->episode); + memcpy(p, k->digest, 32); p += 32; + break; + } + case RXL_INPUT: { + const rxl_input *in = &r->u.in; + w64(&p, in->after_crumb); w32(&p, in->cap_id); w64(&p, in->cap_gen); w32(&p, in->n); + for (uint32_t i = 0; i < in->n && i < RXL_MAX_MUTS; i++) { + w32(&p, in->m[i].id); w32(&p, in->m[i].gen); w32(&p, in->m[i].field); w64(&p, in->m[i].value); + } + break; + } + case RXL_CHECKPOINT: { + const rxl_checkpoint *ck = &r->u.ck; + w64(&p, ck->through_crumb); w32(&p, ck->subsystem); + memcpy(p, ck->hash, 32); p += 32; + w32(&p, ck->n_obj); + for (uint32_t i = 0; i < ck->n_obj && i < RXL_MAX_OBJS; i++) { + const rxl_obj *o = &ck->obj[i]; + w32(&p, o->id); w32(&p, o->gen); w32(&p, o->type); w64(&p, o->version); + for (uint32_t f = 0; f < RXL_MAX_FIELDS; f++) { + w64(&p, o->value[f]); w64(&p, o->fversion[f]); w64(&p, o->writer[f]); + } + } + break; + } + case RXL_END: + w64(&p, r->u.end.n_records); + memcpy(p, r->u.end.head, 32); p += 32; + break; + default: + return 0; + } + return (size_t)(p - buf); +} + +static void dec_io(rd *d, rxl_io *io) { io->id = r32(d); io->gen = r32(d); io->version = r64(d); io->mask = r64(d); } + +/* Decode one payload; 0 on success, else a reason string in why. */ +static int decode(uint32_t type, const uint8_t *buf, size_t len, rxl_rec *r, char *why, size_t wn) { + rd d = { buf, len, 0 }; + memset(r, 0, sizeof *r); + r->type = type; + switch (type) { + case RXL_CRUMB: { + rxl_crumb *k = &r->u.c; + k->id = r64(&d); k->kind = r32(&d); k->reaction = r32(&d); k->faculty = r32(&d); k->worker = r32(&d); + k->wake_cause = r64(&d); k->coalesced = r64(&d); + k->n_inputs = r32(&d); + if (k->n_inputs > RXL_MAX_DEPS) { snprintf(why, wn, "n_inputs %u over limit", k->n_inputs); return -1; } + for (uint32_t i = 0; i < k->n_inputs; i++) dec_io(&d, &k->inputs[i]); + k->n_caps = r32(&d); + if (k->n_caps > RXL_MAX_CAPS) { snprintf(why, wn, "n_caps %u over limit", k->n_caps); return -1; } + for (uint32_t i = 0; i < k->n_caps; i++) { + k->caps[i].cap_id = r32(&d); k->caps[i].gen = r64(&d); k->caps[i].issuer = r32(&d); + } + k->n_outputs = r32(&d); + if (k->n_outputs > RXL_MAX_WRITES) { snprintf(why, wn, "n_outputs %u over limit", k->n_outputs); return -1; } + for (uint32_t i = 0; i < k->n_outputs; i++) dec_io(&d, &k->outputs[i]); + k->reason = (int32_t)r32(&d); + k->n_parents = r32(&d); + if (k->n_parents > RXL_MAX_PARENTS) { snprintf(why, wn, "n_parents %u over limit", k->n_parents); return -1; } + for (uint32_t i = 0; i < k->n_parents; i++) k->parents[i] = r64(&d); + k->t_start = r64(&d); k->t_end = r64(&d); k->episode = r64(&d); + rbytes(&d, k->digest, 32); + break; + } + case RXL_INPUT: { + rxl_input *in = &r->u.in; + in->after_crumb = r64(&d); in->cap_id = r32(&d); in->cap_gen = r64(&d); in->n = r32(&d); + if (in->n > RXL_MAX_MUTS) { snprintf(why, wn, "input count %u over limit", in->n); return -1; } + for (uint32_t i = 0; i < in->n; i++) { + in->m[i].id = r32(&d); in->m[i].gen = r32(&d); in->m[i].field = r32(&d); in->m[i].value = r64(&d); + } + break; + } + case RXL_CHECKPOINT: { + rxl_checkpoint *ck = &r->u.ck; + ck->through_crumb = r64(&d); ck->subsystem = r32(&d); + rbytes(&d, ck->hash, 32); + ck->n_obj = r32(&d); + if (ck->n_obj > RXL_MAX_OBJS) { snprintf(why, wn, "state table %u objects over limit", ck->n_obj); return -1; } + for (uint32_t i = 0; i < ck->n_obj; i++) { + rxl_obj *o = &ck->obj[i]; + o->id = r32(&d); o->gen = r32(&d); o->type = r32(&d); o->version = r64(&d); + for (uint32_t f = 0; f < RXL_MAX_FIELDS; f++) { + o->value[f] = r64(&d); o->fversion[f] = r64(&d); o->writer[f] = r64(&d); + } + } + break; + } + case RXL_END: + r->u.end.n_records = r64(&d); + rbytes(&d, r->u.end.head, 32); + break; + default: + snprintf(why, wn, "unknown record type %u", type); + return -1; + } + if (d.bad) { snprintf(why, wn, "payload shorter than its counts imply"); return -1; } + if (d.left) { snprintf(why, wn, "%zu extra payload bytes", d.left); return -1; } + return 0; +} + +int rxl_read(const char *path, rxl_log *l, char *err, size_t errlen) { + memset(l, 0, sizeof *l); + FILE *f = fopen(path, "rb"); + if (!f) { snprintf(err, errlen, "cannot open %s", path); return -1; } + uint8_t hdr[16]; + if (fread(hdr, 1, 16, f) != 16 || memcmp(hdr, RXL_MAGIC, 8)) { + fclose(f); snprintf(err, errlen, "not an RXCLOG01 file"); return -1; + } + rd h = { hdr + 8, 8, 0 }; + l->version = r32(&h); + l->flags = r32(&h); + if (l->version != RXL_VERSION) { + fclose(f); snprintf(err, errlen, "unknown version %u", l->version); return -1; + } + uint8_t buf[RXL_MAX_PAYLOAD]; + for (;;) { + uint8_t th[8]; + size_t got = fread(th, 1, 8, f); + if (got == 0) break; + if (got != 8) { l->malformed = 1; snprintf(l->why, sizeof l->why, "truncated record header"); break; } + rd t = { th, 8, 0 }; + uint32_t type = r32(&t), len = r32(&t); + if (len > RXL_MAX_PAYLOAD) { l->malformed = 1; snprintf(l->why, sizeof l->why, "payload length %u too large", len); break; } + if (fread(buf, 1, len, f) != len) { l->malformed = 1; snprintf(l->why, sizeof l->why, "truncated payload"); break; } + rxl_rec r; + if (decode(type, buf, len, &r, l->why, sizeof l->why)) { l->malformed = 1; break; } + if (rxl_push(l, &r)) { fclose(f); snprintf(err, errlen, "out of memory"); return -1; } + } + fclose(f); + return 0; +} + +int rxl_write(const char *path, const rxl_log *l) { + FILE *f = fopen(path, "wb"); + if (!f) return -1; + uint8_t hdr[16], *p = hdr + 8; + memcpy(hdr, RXL_MAGIC, 8); + w32(&p, l->version); w32(&p, l->flags); + int bad = fwrite(hdr, 1, 16, f) != 16; + uint8_t buf[RXL_MAX_PAYLOAD + 8]; + for (size_t i = 0; i < l->n && !bad; i++) { + size_t n = rxl_encode(&l->recs[i], buf + 8); + uint8_t *q = buf; + w32(&q, l->recs[i].type); w32(&q, (uint32_t)n); + bad = fwrite(buf, 1, n + 8, f) != n + 8; + } + if (fclose(f)) bad = 1; + return bad ? -1 : 0; +} + +/* The runtime's put32/put64: little-endian, 64-bit as low word then high. */ +static void h32(sha256_ctx *c, uint32_t v) { + uint8_t b[4] = { (uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24) }; + sha256_update(c, b, 4); +} +static void h64(sha256_ctx *c, uint64_t v) { h32(c, (uint32_t)v); h32(c, (uint32_t)(v >> 32)); } + +void rxl_crumb_digest(const rxl_crumb *k, const uint8_t (*digest_by_id)[32], uint64_t n_known, + uint8_t out[32]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_RX_CAUSAL_V1", 17); + h64(&c, k->id); + h32(&c, k->kind); + h32(&c, k->reaction); + h32(&c, k->faculty); + h64(&c, k->wake_cause); + h64(&c, k->coalesced); + h32(&c, k->n_inputs); + for (uint32_t i = 0; i < k->n_inputs; i++) { + h32(&c, k->inputs[i].id); h32(&c, k->inputs[i].gen); + h64(&c, k->inputs[i].version); h64(&c, k->inputs[i].mask); + } + h32(&c, k->n_caps); + for (uint32_t i = 0; i < k->n_caps; i++) { + h32(&c, k->caps[i].cap_id); h64(&c, k->caps[i].gen); h32(&c, k->caps[i].issuer); + } + h32(&c, k->n_outputs); + for (uint32_t i = 0; i < k->n_outputs; i++) { + h32(&c, k->outputs[i].id); h32(&c, k->outputs[i].gen); + h64(&c, k->outputs[i].version); h64(&c, k->outputs[i].mask); + } + h32(&c, (uint32_t)k->reason); + h32(&c, k->n_parents); + for (uint32_t i = 0; i < k->n_parents; i++) { + uint64_t p = k->parents[i]; + h64(&c, p); + if (p >= 1 && p <= n_known && p < k->id) sha256_update(&c, digest_by_id[p - 1], 32); + } + sha256_final(&c, out); +} + +void rxl_event_digest(const rxl_rec *r, uint8_t out[32]) { + if (r->type == RXL_CRUMB) { memcpy(out, r->u.c.digest, 32); return; } + uint8_t buf[RXL_MAX_PAYLOAD]; + size_t n = rxl_encode(r, buf); + sha256_ctx c; + sha256_init(&c); + h32(&c, r->type); + sha256_update(&c, buf, n); + sha256_final(&c, out); +} + +void rxl_head_step(uint8_t head[32], const rxl_rec *r) { + uint8_t ev[32]; + rxl_event_digest(r, ev); + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"RXCLOG01-HEAD", 13); + sha256_update(&c, head, 32); + h32(&c, r->type); + sha256_update(&c, ev, 32); + sha256_final(&c, head); +} + +int rxl_seal(rxl_log *l) { + if (l->n && l->recs[l->n - 1].type == RXL_END) l->n--; + uint8_t (*dig)[32] = calloc(l->n + 1, 32); + uint64_t *ep = calloc(l->n + 1, sizeof *ep); + if (!dig || !ep) { free(dig); free(ep); return -1; } + uint64_t nk = 0; + uint8_t head[32] = { 0 }; + for (size_t i = 0; i < l->n; i++) { + rxl_rec *r = &l->recs[i]; + if (r->type == RXL_CRUMB) { + rxl_crumb *k = &r->u.c; + rxl_crumb_digest(k, (const uint8_t (*)[32])dig, nk, k->digest); + k->episode = k->kind == RXL_K_EXTERNAL ? k->id + : k->wake_cause >= 1 && k->wake_cause < k->id && k->wake_cause <= nk + ? ep[k->wake_cause - 1] : 0; + memcpy(dig[nk], k->digest, 32); + ep[nk] = k->episode; + nk++; + } + rxl_head_step(head, r); + } + rxl_rec e; + memset(&e, 0, sizeof e); + e.type = RXL_END; + e.u.end.n_records = l->n; + memcpy(e.u.end.head, head, 32); + free(dig); free(ep); + return rxl_push(l, &e); +} + +void rxl_hex(const uint8_t *d, size_t n, char *out) { + static const char hx[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { out[2 * i] = hx[d[i] >> 4]; out[2 * i + 1] = hx[d[i] & 15]; } + out[2 * n] = 0; +} + +int rxl_finish(rxl_log *l) { + if (l->n && l->recs[l->n - 1].type == RXL_END) l->n--; + uint8_t head[32] = { 0 }; + for (size_t i = 0; i < l->n; i++) rxl_head_step(head, &l->recs[i]); + rxl_rec e; + memset(&e, 0, sizeof e); + e.type = RXL_END; + e.u.end.n_records = l->n; + memcpy(e.u.end.head, head, 32); + return rxl_push(l, &e); +} + +void rxl_state_hash(const rxl_checkpoint *ck, uint8_t out[32]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"RXCLOG01-STATE", 14); + for (uint32_t i = 0; i < ck->n_obj && i < RXL_MAX_OBJS; i++) { + const rxl_obj *o = &ck->obj[i]; + h32(&c, o->id); h32(&c, o->gen); h32(&c, o->type); h64(&c, o->version); + for (uint32_t f = 0; f < RXL_MAX_FIELDS; f++) { + h64(&c, o->value[f]); h64(&c, o->fversion[f]); h64(&c, o->writer[f]); + } + } + sha256_final(&c, out); +} diff --git a/tools/replay/rxlog.h b/tools/replay/rxlog.h new file mode 100644 index 000000000..9c893da10 --- /dev/null +++ b/tools/replay/rxlog.h @@ -0,0 +1,160 @@ +/* rxlog.h -- RXCLOG01: a portable file form of a World causal crumb log + * (src/runtime/rx_world.h RxCrumb), plus the outside inputs that drove the + * run and state checkpoints, so a run can be verified and replayed by a + * program that does not link the runtime. + * + * This header and rxlog.c depend on libc and src/sha256.h only. They never + * include rx_world.h: the verifier is an independent implementation of the + * crumb digest (rx_world.c crumb_hash, "AIEN_RX_CAUSAL_V1") and of the + * rx_world_verify_crumbs rules. The exporter (rx_crumb_export.c) is the only + * file that sees both layouts, and it static-asserts the limits match. + * + * File layout, all integers little-endian: + * header "RXCLOG01" | u32 version (1) | u32 flags + * record* u32 type | u32 payload_len | payload + * the last record is END (type 0xFF): u64 n_records | 32-byte head + * Payload encodings are fixed by rxl_encode(); counts bound every array and + * a payload must be exactly as long as its counts imply. + * + * Compared digest (what "the same run" means): + * CRUMB the crumb digest, recomputed from the fields the runtime + * hashes: id, kind, reaction, faculty, wake_cause, + * coalesced_wakes, inputs, caps (+issuer), outputs, reason, + * parents and the parents' digests. + * NOT compared: worker, t_start_ns, t_end_ns (where and when a + * reaction ran is placement and timing, not causal identity; + * the runtime itself leaves them out so the same history + * hashes the same on any schedule), and episode (derived from + * wake_cause, so it is checked by rule, not hashed). + * Capability generations (crumb caps and the INPUT capability) + * are stored relative to the run's capability office + * generation: the root seeds generations from boot time, so + * raw ones never repeat across runs. Stored crumb digests are + * over that relative form; the exporter first checks each + * runtime digest against rxl_crumb_digest over the raw fields + * (rx_crumb_export.h). + * INPUT SHA-256 of the encoded payload (capability + mutations with + * their values: the crumb log alone does not carry values). + * CHECKPOINT SHA-256 of the encoded payload: the state hash of every + * object and, since the causal-order compare, the state table + * it was hashed from (object id, generation, type, version and + * per field value, field version and writer crumb id). The + * verifier recomputes the state hash from the table, so the + * table cannot differ from what the recorder hashed. + * END.head chains the compared digests of every record before it, so a + * dropped tail or a forged middle is caught without trusting the file. */ +#ifndef OMEGA_RXLOG_H +#define OMEGA_RXLOG_H + +#include +#include + +#define RXL_MAGIC "RXCLOG01" +#define RXL_VERSION 1u +#define RXL_FLAG_INPUTS 0x1u /* every EXTERNAL crumb is preceded by its INPUT record */ + +#define RXL_MAX_DEPS 8u +#define RXL_MAX_WRITES 8u +#define RXL_MAX_CAPS 8u +#define RXL_MAX_PARENTS 65u /* RX_MAX_DEPS * RX_MAX_FIELDS + 1 */ +#define RXL_MAX_MUTS 16u +#define RXL_MAX_PAYLOAD 4096u +#define RXL_MAX_FIELDS 8u /* RX_MAX_FIELDS (static-asserted by the recorder) */ +#define RXL_MAX_OBJS 16u + +/* Crumb kinds, as numbered in rx_world.h RxCrumbKind. */ +enum { RXL_K_CREATE = 1, RXL_K_EXTERNAL = 2, RXL_K_COMMIT = 3, RXL_K_INVALIDATED = 4, RXL_K_MAX = 10 }; + +enum { RXL_CRUMB = 1, RXL_INPUT = 2, RXL_CHECKPOINT = 3, RXL_END = 0xFF }; + +typedef struct { uint32_t id, gen; uint64_t version, mask; } rxl_io; +typedef struct { uint32_t cap_id; uint64_t gen; uint32_t issuer; } rxl_cap; + +typedef struct { + uint64_t id; + uint32_t kind, reaction, faculty, worker; + uint64_t wake_cause, coalesced; + uint32_t n_inputs; + rxl_io inputs[RXL_MAX_DEPS]; + uint32_t n_caps; + rxl_cap caps[RXL_MAX_CAPS]; + uint32_t n_outputs; + rxl_io outputs[RXL_MAX_WRITES]; + int32_t reason; + uint32_t n_parents; + uint64_t parents[RXL_MAX_PARENTS]; + uint64_t t_start, t_end, episode; + uint8_t digest[32]; +} rxl_crumb; + +typedef struct { uint32_t id, gen, field; uint64_t value; } rxl_mut; +typedef struct { + uint64_t after_crumb; /* crumbs in the log when the input was published */ + uint32_t cap_id; + uint64_t cap_gen; + uint32_t n; + rxl_mut m[RXL_MAX_MUTS]; +} rxl_input; + +/* One object of a CHECKPOINT state table, in the order the state hash + * covers it. writer[f] is the crumb id of the field's last writer (0 = none). */ +typedef struct { + uint32_t id, gen, type; + uint64_t version; + uint64_t value[RXL_MAX_FIELDS], fversion[RXL_MAX_FIELDS], writer[RXL_MAX_FIELDS]; +} rxl_obj; + +typedef struct { + uint64_t through_crumb; + uint32_t subsystem; /* 1 = world object state */ + uint8_t hash[32]; + uint32_t n_obj; /* 0 = hash only (no state table) */ + rxl_obj obj[RXL_MAX_OBJS]; +} rxl_checkpoint; + +typedef struct { uint64_t n_records; uint8_t head[32]; } rxl_end; + +typedef struct { + uint32_t type; + union { rxl_crumb c; rxl_input in; rxl_checkpoint ck; rxl_end end; } u; +} rxl_rec; + +typedef struct { + uint32_t version, flags; + rxl_rec *recs; + size_t n, cap; + /* Set by rxl_read when the file stops being well formed: index of the + * record that could not be read (== n), and why. */ + int malformed; + char why[128]; +} rxl_log; + +void rxl_init(rxl_log *l, uint32_t flags); +void rxl_free(rxl_log *l); +int rxl_push(rxl_log *l, const rxl_rec *r); +/* Read a file. Returns 0 if the header is readable (records may still be + * malformed: see l->malformed), -1 if the file or header is unusable. */ +int rxl_read(const char *path, rxl_log *l, char *err, size_t errlen); +int rxl_write(const char *path, const rxl_log *l); +/* Encode one record payload; returns its length (0 for an unknown type). */ +size_t rxl_encode(const rxl_rec *r, uint8_t *buf); +/* Crumb digest exactly as rx_world.c crumb_hash. digest_by_id[i] is the + * digest of crumb id i+1, for the n_known crumbs before k. */ +void rxl_crumb_digest(const rxl_crumb *k, const uint8_t (*digest_by_id)[32], uint64_t n_known, + uint8_t out[32]); +/* Compared digest of a non-END record (crumb: its stored digest). */ +void rxl_event_digest(const rxl_rec *r, uint8_t out[32]); +/* One step of the END head chain. */ +void rxl_head_step(uint8_t head[32], const rxl_rec *r); +/* Append the END record over the records as they are (stored digests are + * used, not recomputed): what the exporter writes. */ +int rxl_finish(rxl_log *l); +/* Recompute every crumb digest, episode and the END record in place: the + * mutation tool uses it to build forged logs that are internally consistent. */ +int rxl_seal(rxl_log *l); +void rxl_hex(const uint8_t *d, size_t n, char *out); +/* State hash of a CHECKPOINT table, exactly as the recorder hashes the + * objects (tests/replay/rx_world_replay.c checkpoint()). */ +void rxl_state_hash(const rxl_checkpoint *ck, uint8_t out[32]); + +#endif diff --git a/tools/replay/rxlog_mutate.c b/tools/replay/rxlog_mutate.c new file mode 100644 index 000000000..a763355d5 --- /dev/null +++ b/tools/replay/rxlog_mutate.c @@ -0,0 +1,444 @@ +/* rxlog_mutate.c -- make one named, realistic fault in a recorded log, for + * the replay mutation suite (tests/replay/run_replay_suite.sh). + * + * rxlog_mutate world IN OUT NAME World RXCLOG01 log + * rxlog_mutate causal IN OUT NAME World log, causal-order mutant or control + * rxlog_mutate dispatch DIR NAME M22 store dir, edited in place + * rxlog_mutate list-world | list-causal | list-dispatch + * + * World names starting "forged-" are re-sealed afterwards: every crumb + * digest, episode and the END record are recomputed, so the log passes its + * own checks and only a comparison with the replayed run can catch it. + * Names starting "excluded-" touch fields that are deliberately outside the + * compared digest (worker, clocks); the suite expects MATCH for them. + * Dispatch "forged-" names recompute the chain; "forged-store-" also + * rewrites the committed generation header, its digest and CURRENT. */ +#include "replay/rxlog.h" +#include "sha256.h" + +#include +#include +#include + +static const char *WORLD[] = { + "omit-crumb", "omit-tail", "reorder-crumbs", "reorder-input", "omit-input", + "flip-kind", "flip-reaction", "flip-faculty", "flip-wake-cause", "flip-coalesced", + "flip-input-obj", "flip-input-version", "flip-input-mask", "flip-cap-id", "flip-cap-gen", + "flip-cap-issuer", "flip-output-obj", "flip-output-version", "flip-output-mask", "flip-reason", + "flip-parent", "reorder-parents", "drop-parent", "flip-digest", "flip-episode", + "flip-input-value", "flip-checkpoint", "flip-end-head", "flip-end-count", + "forged-output-version", "forged-input-value", "forged-omit-stimulus", "forged-reaction", + "forged-wake-cause", + "excluded-worker", "excluded-t-start", "excluded-t-end", NULL }; + +static const char *DISPATCH[] = { + "omit-record", "omit-last", "reorder-records", "flip-op", "flip-step", "flip-arg0", "flip-arg1", + "flip-ref-len", "flip-ref-buf", "flip-base-digest", "flip-chain", "flip-seq", "flip-padding", + "truncate-mid", "forged-arg0", "forged-store-arg0", NULL }; + +/* Index of the target crumb: the first COMMIT (kind 3) after the second + * INPUT with inputs, caps, outputs and at least two parents; else the first + * COMMIT with the most parents. */ +static long target_crumb(const rxl_log *l) { + int inputs = 0; + long best = -1; + uint32_t bestp = 0; + for (size_t i = 0; i < l->n; i++) { + const rxl_rec *r = &l->recs[i]; + if (r->type == RXL_INPUT) inputs++; + if (r->type != RXL_CRUMB || r->u.c.kind != 3) continue; + const rxl_crumb *k = &r->u.c; + if (inputs >= 2 && k->n_inputs && k->n_caps && k->n_outputs && k->n_parents >= 2) return (long)i; + if (k->n_parents > bestp) { bestp = k->n_parents; best = (long)i; } + } + return best; +} + +static long nth_type(const rxl_log *l, uint32_t type, int nth) { + for (size_t i = 0; i < l->n; i++) + if (l->recs[i].type == type && nth-- == 0) return (long)i; + return -1; +} + +static void remove_rec(rxl_log *l, size_t i) { + memmove(&l->recs[i], &l->recs[i + 1], (l->n - i - 1) * sizeof l->recs[0]); + l->n--; +} + +static void swap_rec(rxl_log *l, size_t i, size_t j) { + rxl_rec t = l->recs[i]; + l->recs[i] = l->recs[j]; + l->recs[j] = t; +} + +static int world(const char *in, const char *out, const char *name) { + rxl_log l; + char err[160]; + if (rxl_read(in, &l, err, sizeof err) || l.malformed) { fprintf(stderr, "mutate: %s\n", l.malformed ? l.why : err); return 2; } + long t = target_crumb(&l); + if (t < 0) { fprintf(stderr, "mutate: no target crumb\n"); return 2; } + rxl_crumb *k = &l.recs[t].u.c; + long in2 = nth_type(&l, RXL_INPUT, 2); + int forged = !strncmp(name, "forged-", 7); + int ok = 1; + if (!strcmp(name, "omit-crumb")) remove_rec(&l, (size_t)t); + else if (!strcmp(name, "omit-tail")) { l.n -= 2; } /* last record before END and END itself */ + else if (!strcmp(name, "reorder-crumbs")) swap_rec(&l, (size_t)t, (size_t)t + 1); + else if (!strcmp(name, "reorder-input")) swap_rec(&l, (size_t)in2, (size_t)in2 + 1); + else if (!strcmp(name, "omit-input")) remove_rec(&l, (size_t)in2); + else if (!strcmp(name, "flip-kind")) k->kind ^= 1; + else if (!strcmp(name, "flip-reaction")) k->reaction ^= 1; + else if (!strcmp(name, "flip-faculty")) k->faculty ^= 1; + else if (!strcmp(name, "flip-wake-cause")) k->wake_cause ^= 1; + else if (!strcmp(name, "flip-coalesced")) k->coalesced ^= 1; + else if (!strcmp(name, "flip-input-obj")) k->inputs[0].id ^= 1; + else if (!strcmp(name, "flip-input-version")) k->inputs[0].version ^= 1; + else if (!strcmp(name, "flip-input-mask")) k->inputs[0].mask ^= 2; + else if (!strcmp(name, "flip-cap-id")) k->caps[0].cap_id ^= 1; + else if (!strcmp(name, "flip-cap-gen")) k->caps[0].gen ^= 1ull << 40; /* high word of the 64-bit generation */ + else if (!strcmp(name, "flip-cap-issuer")) k->caps[0].issuer ^= 1; + else if (!strcmp(name, "flip-output-obj")) k->outputs[0].id ^= 1; + else if (!strcmp(name, "flip-output-version")) k->outputs[0].version ^= 1; + else if (!strcmp(name, "flip-output-mask")) k->outputs[0].mask ^= 2; + else if (!strcmp(name, "flip-reason")) k->reason ^= 1; + else if (!strcmp(name, "flip-parent")) k->parents[0] ^= 1; + else if (!strcmp(name, "reorder-parents")) { uint64_t x = k->parents[0]; k->parents[0] = k->parents[1]; k->parents[1] = x; } + else if (!strcmp(name, "drop-parent")) k->n_parents--; + else if (!strcmp(name, "flip-digest")) k->digest[7] ^= 0x10; + else if (!strcmp(name, "flip-episode")) k->episode ^= 1; + else if (!strcmp(name, "flip-input-value")) l.recs[in2].u.in.m[0].value ^= 1; + else if (!strcmp(name, "flip-checkpoint")) l.recs[nth_type(&l, RXL_CHECKPOINT, 3)].u.ck.hash[0] ^= 1; + else if (!strcmp(name, "flip-end-head")) l.recs[l.n - 1].u.end.head[31] ^= 1; + else if (!strcmp(name, "flip-end-count")) l.recs[l.n - 1].u.end.n_records -= 1; + else if (!strcmp(name, "forged-output-version")) k->outputs[0].version += 1; + else if (!strcmp(name, "forged-input-value")) l.recs[in2].u.in.m[0].value += 1; + else if (!strcmp(name, "forged-omit-stimulus")) { + /* Drop the last stimulus entirely (INPUT, its crumbs, CHECKPOINT): a + * shorter but self-consistent history. */ + long last = -1; + for (size_t i = 0; i < l.n; i++) if (l.recs[i].type == RXL_INPUT) last = (long)i; + l.n = (size_t)last; + } + else if (!strcmp(name, "forged-reaction")) k->reaction ^= 1; + else if (!strcmp(name, "forged-wake-cause")) + k->wake_cause = k->parents[0] != k->wake_cause ? k->parents[0] : k->parents[1]; + else if (!strcmp(name, "excluded-worker")) k->worker ^= 3; + else if (!strcmp(name, "excluded-t-start")) k->t_start += 12345; + else if (!strcmp(name, "excluded-t-end")) k->t_end += 999; + else ok = 0; + if (!ok) { fprintf(stderr, "mutate: unknown world mutant %s\n", name); rxl_free(&l); return 2; } + if (forged && rxl_seal(&l)) { rxl_free(&l); return 2; } + int rc = rxl_write(out, &l) ? 2 : 0; + rxl_free(&l); + return rc; +} + +/* ---- causal-order mutants and controls ------------------------------------ + * For rx_replay compare-causal (tests/replay/run_replay_suite.sh). Every one + * is re-sealed (digests, episodes, END) and its CHECKPOINT state hashes are + * recomputed from the tables, so each log verifies by itself; inserted or + * swapped crumbs renumber every id that refers to a crumb (ids, wake causes, + * parents, field writers, INPUT and CHECKPOINT counts). + * causal-* a real difference: compare-causal must report DIVERGENCE + * causal-control-* what concurrent commits legitimately change (order of + * unrelated commits, a flagged superseded run with its + * rerun, the merged-wake count): compare-causal must + * report MATCH and the sequence compare DIVERGENCE. */ +static const char *CAUSAL[] = { + "causal-cause-link", "causal-parent-link", "causal-writer-swap", "causal-unflagged-superseded", + "causal-entry-changed", "causal-superseded-no-rerun", + "causal-control-swap-independent", "causal-control-flagged-superseded", "causal-control-coalesced", NULL }; + +/* Last COMMIT with a wake cause, outputs and at least two parents. */ +static long causal_target(const rxl_log *l) { + long t = -1; + for (size_t i = 0; i < l->n; i++) { + const rxl_rec *r = &l->recs[i]; + if (r->type == RXL_CRUMB && r->u.c.kind == RXL_K_COMMIT && r->u.c.wake_cause && r->u.c.n_outputs && + r->u.c.n_parents >= 2) t = (long)i; + } + return t; +} + +static void sort_parents(rxl_crumb *k) { + for (uint32_t i = 1; i < k->n_parents; i++) + for (uint32_t j = i; j > 0 && k->parents[j - 1] > k->parents[j]; j--) { + uint64_t x = k->parents[j]; k->parents[j] = k->parents[j - 1]; k->parents[j - 1] = x; + } +} + +/* Apply map[old id] = new id to every crumb reference (map[0] = 0). */ +static void remap(rxl_log *l, const uint64_t *map, uint64_t n_ids) { + for (size_t i = 0; i < l->n; i++) { + rxl_rec *r = &l->recs[i]; + if (r->type == RXL_CRUMB) { + rxl_crumb *k = &r->u.c; + if (k->id <= n_ids) k->id = map[k->id]; + if (k->wake_cause <= n_ids) k->wake_cause = map[k->wake_cause]; + for (uint32_t p = 0; p < k->n_parents; p++) + if (k->parents[p] <= n_ids) k->parents[p] = map[k->parents[p]]; + sort_parents(k); + } else if (r->type == RXL_CHECKPOINT) { + for (uint32_t o = 0; o < r->u.ck.n_obj; o++) + for (uint32_t f = 0; f < RXL_MAX_FIELDS; f++) + if (r->u.ck.obj[o].writer[f] <= n_ids) r->u.ck.obj[o].writer[f] = map[r->u.ck.obj[o].writer[f]]; + } + } +} + +static uint64_t count_crumbs(const rxl_log *l, size_t upto) { + uint64_t n = 0; + for (size_t i = 0; i < upto && i < l->n; i++) n += l->recs[i].type == RXL_CRUMB; + return n; +} + +/* Insert crumb c as record idx: it takes id P = crumbs before idx + 1, and + * every later crumb shifts by one. c's own links must point below P. */ +static int insert_crumb(rxl_log *l, size_t idx, const rxl_crumb *c) { + uint64_t n_ids = count_crumbs(l, l->n), P = count_crumbs(l, idx) + 1; + uint64_t *map = calloc(n_ids + 2, sizeof *map); + if (!map) return -1; + for (uint64_t id = 0; id <= n_ids; id++) map[id] = id >= P ? id + 1 : id; + remap(l, map, n_ids); + free(map); + /* INPUT and CHECKPOINT records from idx on now have one more crumb before them */ + for (size_t i = idx; i < l->n; i++) { + rxl_rec *r = &l->recs[i]; + if (r->type == RXL_INPUT) r->u.in.after_crumb++; + if (r->type == RXL_CHECKPOINT) r->u.ck.through_crumb++; + } + rxl_rec nr; + memset(&nr, 0, sizeof nr); + nr.type = RXL_CRUMB; + nr.u.c = *c; + nr.u.c.id = P; + if (rxl_push(l, &nr)) return -1; /* grow; then move it into place */ + memmove(&l->recs[idx + 1], &l->recs[idx], (l->n - 1 - idx) * sizeof l->recs[0]); + l->recs[idx] = nr; + return 0; +} + +/* Swap the last adjacent pair of COMMITs where the second neither wakes on + * nor reads from the first (causally unrelated), renumbering both. */ +static int swap_independent(rxl_log *l) { + long at = -1; + for (size_t i = 0; i + 1 < l->n; i++) { + const rxl_rec *x = &l->recs[i], *y = &l->recs[i + 1]; + if (x->type != RXL_CRUMB || y->type != RXL_CRUMB) continue; + if (x->u.c.kind != RXL_K_COMMIT || y->u.c.kind != RXL_K_COMMIT) continue; + int dep = y->u.c.wake_cause == x->u.c.id; + for (uint32_t p = 0; p < y->u.c.n_parents; p++) if (y->u.c.parents[p] == x->u.c.id) dep = 1; + if (!dep) at = (long)i; + } + if (at < 0) return -1; + uint64_t n_ids = count_crumbs(l, l->n); + uint64_t *map = calloc(n_ids + 1, sizeof *map); + if (!map) return -1; + for (uint64_t id = 0; id <= n_ids; id++) map[id] = id; + uint64_t a = l->recs[at].u.c.id, b = l->recs[at + 1].u.c.id; + map[a] = b; map[b] = a; + swap_rec(l, (size_t)at, (size_t)at + 1); + remap(l, map, n_ids); + free(map); + return 0; +} + +static void rehash_states(rxl_log *l) { + for (size_t i = 0; i < l->n; i++) + if (l->recs[i].type == RXL_CHECKPOINT && l->recs[i].u.ck.n_obj) rxl_state_hash(&l->recs[i].u.ck, l->recs[i].u.ck.hash); +} + +/* A run of R that read a stale input: same wake and parents, the last input + * one version older. flagged: logged INVALIDATED (STALE_GEN, no outputs). */ +static rxl_crumb stale_copy(const rxl_crumb *R, int flagged) { + rxl_crumb c = *R; + c.coalesced = 0; + if (c.n_inputs && c.inputs[c.n_inputs - 1].version > 1) c.inputs[c.n_inputs - 1].version--; + if (flagged) { c.kind = RXL_K_INVALIDATED; c.reason = -3; c.n_outputs = 0; } + return c; +} + +static int causal(const char *in, const char *out, const char *name) { + rxl_log l; + char err[160]; + if (rxl_read(in, &l, err, sizeof err) || l.malformed) { fprintf(stderr, "mutate: %s\n", l.malformed ? l.why : err); return 2; } + if (l.n && l.recs[l.n - 1].type == RXL_END) l.n--; + long t = causal_target(&l); + if (t < 0) { fprintf(stderr, "mutate: no causal target crumb\n"); rxl_free(&l); return 2; } + rxl_crumb *k = &l.recs[t].u.c; + rxl_crumb R = *k; + int rc = 0; + if (!strcmp(name, "causal-cause-link")) { + /* wake on another earlier crumb of the same episode */ + uint64_t w = R.episode != R.wake_cause ? R.episode : R.parents[0] != R.wake_cause ? R.parents[0] : R.parents[1]; + if (w == R.wake_cause || !w) rc = -1; else k->wake_cause = w; + } else if (!strcmp(name, "causal-parent-link")) { + memmove(&k->parents[0], &k->parents[1], (k->n_parents - 1) * sizeof k->parents[0]); + k->n_parents--; + } else if (!strcmp(name, "causal-writer-swap")) { + long ck = -1; + for (size_t i = 0; i < l.n; i++) if (l.recs[i].type == RXL_CHECKPOINT && l.recs[i].u.ck.n_obj >= 2) ck = (long)i; + rc = -1; + if (ck >= 0) { + rxl_checkpoint *c = &l.recs[ck].u.ck; + /* field 0 of the last two objects whose writers differ */ + for (uint32_t o = c->n_obj - 1; o > 0 && rc; o--) + for (uint32_t p = o; p > 0 && rc; p--) { + rxl_obj *x = &c->obj[o], *y = &c->obj[p - 1]; + if (x->writer[0] && y->writer[0] && x->writer[0] != y->writer[0]) { + uint64_t s = x->writer[0]; x->writer[0] = y->writer[0]; y->writer[0] = s; + rc = 0; + } + } + } + } else if (!strcmp(name, "causal-unflagged-superseded")) { + rxl_crumb c = stale_copy(&R, 0); + rc = insert_crumb(&l, (size_t)t, &c); + } else if (!strcmp(name, "causal-entry-changed")) { + k->outputs[0].version += 1; + } else if (!strcmp(name, "causal-superseded-no-rerun")) { + rxl_crumb c = stale_copy(&R, 1); + rc = insert_crumb(&l, (size_t)t + 1, &c); /* after R: nothing reruns it */ + } else if (!strcmp(name, "causal-control-swap-independent")) { + rc = swap_independent(&l); + } else if (!strcmp(name, "causal-control-flagged-superseded")) { + rxl_crumb c = stale_copy(&R, 1); + rc = insert_crumb(&l, (size_t)t, &c); /* before R: R is its rerun */ + } else if (!strcmp(name, "causal-control-coalesced")) { + k->coalesced ^= 1; + } else { + fprintf(stderr, "mutate: unknown causal mutant %s\n", name); + rxl_free(&l); + return 2; + } + if (rc) { fprintf(stderr, "mutate: %s: cannot apply to this log\n", name); rxl_free(&l); return 2; } + rehash_states(&l); + if (rxl_seal(&l)) { rxl_free(&l); return 2; } + rc = rxl_write(out, &l) ? 2 : 0; + rxl_free(&l); + return rc; +} + +/* ---- dispatch ----------------------------------------------------------- */ + + +static uint8_t *slurp(const char *path, size_t *n) { + FILE *f = fopen(path, "rb"); + if (!f) return NULL; + fseek(f, 0, SEEK_END); + long len = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t *b = malloc((size_t)len + 1); + if (b && fread(b, 1, (size_t)len, f) != (size_t)len) { free(b); b = NULL; } + fclose(f); + *n = (size_t)len; + return b; +} +static int spit(const char *path, const uint8_t *b, size_t n) { + FILE *f = fopen(path, "wb"); + if (!f) return -1; + int bad = fwrite(b, 1, n, f) != n; + return fclose(f) || bad ? -1 : 0; +} + +static void rechain(uint8_t *log, size_t n, uint8_t head[32]) { + memset(head, 0, 32); + for (size_t i = 0; i + 192 <= n; i += 192) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, head, 32); + sha256_update(&c, log + i, 160); + sha256_final(&c, log + i + 160); + memcpy(head, log + i + 160, 32); + } +} + +/* Build DIR/NAME into out[cap]. 0 = built; -1 = would not fit (reason to + * stderr). A truncated path can name a different file, so it is refused. */ +static int join_path(char *out, size_t cap, const char *dir, const char *name) { + int w = snprintf(out, cap, "%s/%s", dir, name); + if (w < 0 || (size_t)w >= cap) { + fprintf(stderr, "mutate: path too long (%d bytes, limit %zu): %s/%s\n", w, cap - 1, dir, name); + if (cap) out[0] = 0; + return -1; + } + return 0; +} + +/* Rewrite the committed generation so it names `head`: header +56, digest + * at +120 over [0,120) + body, CURRENT's hex digest. */ +static int reforge_store(const char *dir, const uint8_t head[32]) { + char p[4096], gp[4096]; + size_t n; + if (join_path(p, sizeof p, dir, "CURRENT")) return -1; + uint8_t *cur = slurp(p, &n); + if (!cur || n != 95) { free(cur); return -1; } + char gen[21]; + memcpy(gen, cur + 9, 20); gen[20] = 0; + char gname[40]; + snprintf(gname, sizeof gname, "gen-%s.bin", gen); + if (join_path(gp, sizeof gp, dir, gname)) { free(cur); return -1; } + size_t gn; + uint8_t *g = slurp(gp, &gn); + if (!g || gn < 152) { free(cur); free(g); return -1; } + memcpy(g + 56, head, 32); + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, g, 120); + sha256_update(&c, g + 152, gn - 152); + sha256_final(&c, g + 120); + rxl_hex(g + 120, 32, (char *)cur + 30); + cur[94] = '\n'; + int rc = spit(gp, g, gn) || spit(p, cur, n) ? -1 : 0; + free(cur); free(g); + return rc; +} + +static int dispatch(const char *dir, const char *name) { + char p[4096]; + if (join_path(p, sizeof p, dir, "dispatch.log")) return 2; + size_t n; + uint8_t *b = slurp(p, &n); + if (!b || n < 192 * 4) { fprintf(stderr, "mutate: dispatch.log missing or under 4 records\n"); free(b); return 2; } + size_t nr = n / 192, t = nr / 2; /* target: a middle record */ + uint8_t *r = b + t * 192; + uint8_t head[32]; + int ok = 1; + if (!strcmp(name, "omit-record")) { memmove(r, r + 192, n - (t + 1) * 192); n -= 192; } + else if (!strcmp(name, "omit-last")) n -= 192; + else if (!strcmp(name, "reorder-records")) { uint8_t x[192]; memcpy(x, r, 192); memcpy(r, r + 192, 192); memcpy(r + 192, x, 192); } + else if (!strcmp(name, "flip-op")) r[4] ^= 1; + else if (!strcmp(name, "flip-step")) r[16] ^= 1; + else if (!strcmp(name, "flip-arg0")) r[32] ^= 1; + else if (!strcmp(name, "flip-arg1")) r[40] ^= 1; + else if (!strcmp(name, "flip-ref-len")) r[56 + 16] ^= 1; + else if (!strcmp(name, "flip-ref-buf")) r[56] ^= 1; + else if (!strcmp(name, "flip-base-digest")) r[128] ^= 1; + else if (!strcmp(name, "flip-chain")) r[160] ^= 1; + else if (!strcmp(name, "flip-seq")) r[8] ^= 1; + else if (!strcmp(name, "flip-padding")) r[52] ^= 1; + else if (!strcmp(name, "truncate-mid")) n -= 100; + else if (!strcmp(name, "forged-arg0")) { r[32] ^= 1; rechain(b, n, head); } + else if (!strcmp(name, "forged-store-arg0")) { + r[32] ^= 1; + rechain(b, n, head); + if (reforge_store(dir, head)) { fprintf(stderr, "mutate: cannot reforge store\n"); free(b); return 2; } + } + else ok = 0; + if (!ok) { fprintf(stderr, "mutate: unknown dispatch mutant %s\n", name); free(b); return 2; } + int rc = spit(p, b, n) ? 2 : 0; + free(b); + return rc; +} + +int main(int argc, char **argv) { + if (argc == 2 && !strcmp(argv[1], "list-world")) { for (int i = 0; WORLD[i]; i++) puts(WORLD[i]); return 0; } + if (argc == 2 && !strcmp(argv[1], "list-dispatch")) { for (int i = 0; DISPATCH[i]; i++) puts(DISPATCH[i]); return 0; } + if (argc == 2 && !strcmp(argv[1], "list-causal")) { for (int i = 0; CAUSAL[i]; i++) puts(CAUSAL[i]); return 0; } + if (argc == 5 && !strcmp(argv[1], "world")) return world(argv[2], argv[3], argv[4]); + if (argc == 4 && !strcmp(argv[1], "dispatch")) return dispatch(argv[2], argv[3]); + if (argc == 5 && !strcmp(argv[1], "causal")) return causal(argv[2], argv[3], argv[4]); + fprintf(stderr, "usage: rxlog_mutate world IN OUT NAME | causal IN OUT NAME | dispatch DIR NAME |\n" + " list-world | list-causal | list-dispatch\n"); + return 2; +} diff --git a/tools/replay/trn1.c b/tools/replay/trn1.c new file mode 100644 index 000000000..7212bb6f6 --- /dev/null +++ b/tools/replay/trn1.c @@ -0,0 +1,321 @@ +/* trn1.c -- TRN1 verifier, comparator and RXCLOG01 export (see trn1.h). + * Written from TRN1_TRANSCRIPT_SPEC.md sections 3-8; check order is the + * spec's section 7, which fixes the refusal code. */ +#include "replay/trn1.h" +#include "sha256.h" + +#include +#include +#include + +#define HDR 48u +#define RHDR 56u +#define MAXLEN 65536u +#define T_END 0xFFFFu +#define N_SUBSYS 11u + +static const char *SUBSYS[N_SUBSYS] = { + "transcript", "omega-world", "omega-cortex", "omega-jspace", "aienos-kernel", "aienos-argus", + "aienos-store", "sovcore-runtime", "sovcore-scheduler", "sovcore-kv", "external" }; + +const char *trn1_subsystem_name(uint16_t id) { return id < N_SUBSYS ? SUBSYS[id] : "?"; } + +static uint16_t l16(const uint8_t *p) { return (uint16_t)(p[0] | p[1] << 8); } +static uint32_t l32(const uint8_t *p) { return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; } +static uint64_t l64(const uint8_t *p) { return (uint64_t)l32(p) | (uint64_t)l32(p + 4) << 32; } +static int zero(const uint8_t *p, size_t n) { while (n--) if (*p++) return 0; return 1; } + +static int known_type(uint16_t t) { return (t >= 1 && t <= 16) || t == T_END; } + +/* Step 8 part 1: identity length rule. */ +static int ident_len_ok(uint16_t t, uint32_t n) { + static const uint32_t exact[17] = { 0, 32, 24, 24, 40, 24, 48, 32, 56, 56, 48, 0, 16, 48, 40, 0, 200 }; + if (t == T_END) return n == 16; + if (t == 11) return n >= 48 && n <= 48 + 4096; + if (t == 15) return n >= 32; + return n == exact[t]; +} + +/* RX_CRUMB canonical bytes must parse to exactly their length. */ +static int crumb_parse(const uint8_t *p, size_t n) { + size_t o = 0; +#define NEED(k) do { if (n - o < (size_t)(k)) return 0; } while (0) + NEED(8 + 4 + 4 + 4 + 8 + 8); + uint64_t id = l64(p); + o = 36; + NEED(4); + uint32_t c = l32(p + o); o += 4; + if (c > 8) return 0; + NEED(24ull * c); o += 24ull * c; + NEED(4); + c = l32(p + o); o += 4; + if (c > 8) return 0; + NEED(16ull * c); o += 16ull * c; + NEED(4); + c = l32(p + o); o += 4; + if (c > 8) return 0; + NEED(24ull * c); o += 24ull * c; + NEED(4 + 4); + o += 4; + c = l32(p + o); o += 4; + if (c > 65) return 0; + for (uint32_t i = 0; i < c; i++) { + NEED(8); + uint64_t par = l64(p + o); o += 8; + if (par >= 1 && par < id) { NEED(32); o += 32; } + } +#undef NEED + return o == n; +} + +/* Step 9: reserved fields inside the identity. */ +static int ident_reserved_zero(uint16_t t, const uint8_t *id) { + switch (t) { + case 3: return zero(id + 20, 4); + case 6: return zero(id + 4, 4); + case 7: return zero(id + 5, 3); + case 10: return zero(id + 12, 4); + case 11: return zero(id + 4, 4); + case 12: return zero(id + 4, 4); + case 14: return zero(id + 4, 4); + case 16: return zero(id + 129, 7); + case T_END: return zero(id + 8, 8); + default: return 1; + } +} + +static void cmp_digest(const uint8_t *rec, uint32_t ilen, uint8_t out[32]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_TRN1_CMP", 13); + sha256_update(&c, rec, 4); /* type, subsystem */ + sha256_update(&c, rec + 16, 8); /* seq */ + sha256_update(&c, rec + 4, 4); /* ident_len */ + sha256_update(&c, rec + RHDR, ilen); + sha256_final(&c, out); +} + +static int refuse(trn1_result *r, int code, uint64_t ev) { r->code = code; r->event = ev; return code; } + +int trn1_verify(const uint8_t *b, size_t len, trn1_result *r) { + memset(r, 0, sizeof *r); + if (len < 4) return refuse(r, TRN1_LENGTH, 0); + if (memcmp(b, "TRN1", 4)) return refuse(r, TRN1_MAGIC, 0); + if (len < 6) return refuse(r, TRN1_LENGTH, 0); + if (l16(b + 4) != 1) return refuse(r, TRN1_VERSION, 0); + if (len < HDR) return refuse(r, TRN1_LENGTH, 0); + if (l16(b + 6) != 0) return refuse(r, TRN1_NONCANONICAL, 0); + uint16_t prod = l16(b + 40); + if (prod == 0 || prod >= N_SUBSYS) return refuse(r, TRN1_UNKNOWN, 0); + if (!zero(b + 42, 6)) return refuse(r, TRN1_NONCANONICAL, 0); + memcpy(r->run_id, b + 8, 32); + uint8_t prev[32]; + sha256_hash(b, HDR, prev); + r->cmp = calloc(TRN1_MAX_RECORDS, 32); + r->subsys = calloc(TRN1_MAX_RECORDS, sizeof *r->subsys); + if (!r->cmp || !r->subsys) { trn1_result_free(r); return refuse(r, TRN1_LENGTH, 0); } + int have_argus = 0; + uint8_t argus_after[32]; + size_t pos = HDR; + for (uint64_t k = 1;; k++) { + if (pos == len) return refuse(r, TRN1_TRUNCATED, k); + if (len - pos < RHDR || k > TRN1_MAX_RECORDS) return refuse(r, TRN1_LENGTH, k); + const uint8_t *h = b + pos; + uint16_t type = l16(h), sub = l16(h + 2); + uint32_t ilen = l32(h + 4), alen = l32(h + 8); + if (!known_type(type) || sub >= N_SUBSYS) return refuse(r, TRN1_UNKNOWN, k); + if (!zero(h + 12, 4)) return refuse(r, TRN1_NONCANONICAL, k); + if (ilen > MAXLEN || alen > MAXLEN) return refuse(r, TRN1_LENGTH, k); + if (l64(h + 16) != k) return refuse(r, TRN1_GAP, k); + if (memcmp(h + 24, prev, 32)) return refuse(r, TRN1_CHAIN, k); + if ((uint64_t)len - pos - RHDR < (uint64_t)ilen + alen) return refuse(r, TRN1_LENGTH, k); + const uint8_t *id = h + RHDR; + int shape = ident_len_ok(type, ilen) && ((type == T_END) == (sub == 0)); + if (shape && type == 7) shape = id[4] >= 1 && id[4] <= 6; + if (shape && type == 13) shape = l64(id + 8) < k; + if (shape && type == 15) shape = crumb_parse(id + 32, ilen - 32); + if (shape && type == 16) shape = id[128] <= 1; + if (shape && type == T_END) shape = alen == 0; + if (!shape) return refuse(r, TRN1_SHAPE, k); + if (!ident_reserved_zero(type, id)) return refuse(r, TRN1_NONCANONICAL, k); + if (type == 15) { + uint8_t d[32]; + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_RX_CAUSAL_V1", 17); + sha256_update(&c, id + 32, ilen - 32); + sha256_final(&c, d); + if (memcmp(d, id, 32)) return refuse(r, TRN1_DIGEST, k); + } else if (type == 11 && ilen > 48) { + uint8_t d[32]; + sha256_hash(id + 48, ilen - 48, d); + if (memcmp(d, id + 16, 32)) return refuse(r, TRN1_DIGEST, k); + } else if (type == 16) { + if (have_argus && memcmp(id + 136, argus_after, 32)) return refuse(r, TRN1_DIGEST, k); + uint8_t d[32]; + if (id[128]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, id + 136, 32); + sha256_update(&c, id, 128); + sha256_final(&c, d); + } else memcpy(d, id + 136, 32); + if (memcmp(d, id + 168, 32)) return refuse(r, TRN1_DIGEST, k); + memcpy(argus_after, id + 168, 32); + have_argus = 1; + } + cmp_digest(h, ilen, r->cmp[k - 1]); + r->subsys[k - 1] = sub; + sha256_hash(h, RHDR + (size_t)ilen + alen, prev); + pos += RHDR + (size_t)ilen + alen; + if (type == T_END) { + if (l64(id) != k) return refuse(r, TRN1_GAP, k); + if (pos != len) return refuse(r, TRN1_LENGTH, k + 1); + r->records = k; + memcpy(r->final, prev, 32); + return TRN1_OK; + } + } +} + +void trn1_result_free(trn1_result *r) { + free(r->cmp); free(r->subsys); + r->cmp = NULL; r->subsys = NULL; +} + +void trn1_verify_line(const trn1_result *r, char *out, size_t n) { + if (r->code) { snprintf(out, n, "refuse %d event=%llu", r->code, (unsigned long long)r->event); return; } + char a[65], b[65]; + rxl_hex(r->run_id, 32, a); + rxl_hex(r->final, 32, b); + snprintf(out, n, "ok records=%llu run=%s final=%s", (unsigned long long)r->records, a, b); +} + +void trn1_compare_line(const uint8_t *a, size_t na, const uint8_t *b, size_t nb, char *out, size_t n) { + trn1_result x, y; + if (trn1_verify(a, na, &x)) { + snprintf(out, n, "refuse expected %d event=%llu", x.code, (unsigned long long)x.event); + trn1_result_free(&x); + return; + } + if (trn1_verify(b, nb, &y)) { + snprintf(out, n, "refuse actual %d event=%llu", y.code, (unsigned long long)y.event); + trn1_result_free(&x); trn1_result_free(&y); + return; + } + uint64_t m = x.records < y.records ? x.records : y.records; + snprintf(out, n, "MATCH through %llu", (unsigned long long)x.records); + for (uint64_t k = 0; k < m; k++) { + if (memcmp(x.cmp[k], y.cmp[k], 32)) { + char ha[65], hb[65]; + rxl_hex(x.cmp[k], 32, ha); + rxl_hex(y.cmp[k], 32, hb); + snprintf(out, n, "DIVERGENCE event=%llu expected=%s actual=%s subsystem=%s", (unsigned long long)k + 1, + ha, hb, trn1_subsystem_name(x.subsys[k])); + break; + } + } + trn1_result_free(&x); trn1_result_free(&y); +} + +/* ---- RXCLOG01 -> TRN1 ---------------------------------------------------- */ + +typedef struct { uint8_t *p; size_t n, cap; int bad; } buf; +static void put(buf *b, const void *d, size_t n) { + if (b->bad) return; + if (b->n + n > b->cap) { + size_t nc = b->cap ? b->cap : 4096; + while (nc < b->n + n) nc *= 2; + uint8_t *q = realloc(b->p, nc); + if (!q) { b->bad = 1; return; } + b->p = q; b->cap = nc; + } + memcpy(b->p + b->n, d, n); + b->n += n; +} +static void p16(buf *b, uint16_t v) { uint8_t x[2] = { (uint8_t)v, (uint8_t)(v >> 8) }; put(b, x, 2); } +static void p32(buf *b, uint32_t v) { uint8_t x[4]; for (int i = 0; i < 4; i++) x[i] = (uint8_t)(v >> (8 * i)); put(b, x, 4); } +static void p64(buf *b, uint64_t v) { p32(b, (uint32_t)v); p32(b, (uint32_t)(v >> 32)); } +static void pio(buf *b, const rxl_io *io) { p32(b, io->id); p32(b, io->gen); p64(b, io->version); p64(b, io->mask); } + +static int emit(buf *out, uint8_t prev[32], uint64_t seq, uint16_t type, uint16_t sub, + const buf *ident, const buf *annot) { + size_t start = out->n; + p16(out, type); p16(out, sub); + p32(out, (uint32_t)ident->n); p32(out, (uint32_t)annot->n); p32(out, 0); + p64(out, seq); + put(out, prev, 32); + put(out, ident->p, ident->n); + put(out, annot->p, annot->n); + if (out->bad) return -1; + sha256_hash(out->p + start, out->n - start, prev); + return 0; +} + +int trn1_from_rxlog(const rxl_log *l, uint8_t **out_p, size_t *out_len) { + buf o = { 0 }, id = { 0 }, an = { 0 }; + uint8_t (*dig)[32] = calloc(l->n + 1, 32); + if (!dig) return -1; + uint8_t run[32] = { 0 }; + if (l->n && l->recs[l->n - 1].type == RXL_END) memcpy(run, l->recs[l->n - 1].u.end.head, 32); + put(&o, "TRN1", 4); + p16(&o, 1); p16(&o, 0); + put(&o, run, 32); + p16(&o, 1); /* producer omega-world */ + uint8_t z[32] = { 0 }; + put(&o, z, 6); + uint8_t prev[32]; + if (o.bad) { free(dig); return -1; } + sha256_hash(o.p, 48, prev); + uint64_t seq = 0, nk = 0, nin = 0; + int rc = 0; + for (size_t i = 0; i < l->n && !rc; i++) { + const rxl_rec *r = &l->recs[i]; + if (r->type == RXL_END) break; + id.n = an.n = 0; + if (r->type == RXL_CRUMB) { + const rxl_crumb *k = &r->u.c; + put(&id, k->digest, 32); + p64(&id, k->id); p32(&id, k->kind); p32(&id, k->reaction); p32(&id, k->faculty); + p64(&id, k->wake_cause); p64(&id, k->coalesced); + p32(&id, k->n_inputs); + for (uint32_t j = 0; j < k->n_inputs; j++) pio(&id, &k->inputs[j]); + p32(&id, k->n_caps); + for (uint32_t j = 0; j < k->n_caps; j++) { p32(&id, k->caps[j].cap_id); p64(&id, k->caps[j].gen); p32(&id, k->caps[j].issuer); } + p32(&id, k->n_outputs); + for (uint32_t j = 0; j < k->n_outputs; j++) pio(&id, &k->outputs[j]); + p32(&id, (uint32_t)k->reason); + p32(&id, k->n_parents); + for (uint32_t j = 0; j < k->n_parents; j++) { + uint64_t p = k->parents[j]; + p64(&id, p); + if (p >= 1 && p < k->id) put(&id, p <= nk ? dig[p - 1] : z, 32); + } + p32(&an, k->worker); p64(&an, k->t_start); p64(&an, k->t_end); p64(&an, k->episode); + if (nk < l->n) memcpy(dig[nk++], k->digest, 32); + rc = emit(&o, prev, ++seq, 15, 1, &id, &an); + } else if (r->type == RXL_INPUT) { + uint8_t content[RXL_MAX_PAYLOAD], d[32]; + size_t cn = rxl_encode(r, content); + sha256_hash(content, cn, d); + p32(&id, 1); p32(&id, 0); p64(&id, ++nin); + put(&id, d, 32); + put(&id, content, cn); + rc = emit(&o, prev, ++seq, 11, 10, &id, &an); + } else if (r->type == RXL_CHECKPOINT) { + p32(&id, r->u.ck.subsystem); p32(&id, 0); + put(&id, r->u.ck.hash, 32); + rc = emit(&o, prev, ++seq, 14, 1, &id, &an); + } + } + if (!rc) { + id.n = an.n = 0; + p64(&id, seq + 1); p64(&id, 0); + rc = emit(&o, prev, seq + 1, (uint16_t)T_END, 0, &id, &an); + } + free(dig); free(id.p); free(an.p); + if (rc || o.bad) { free(o.p); return -1; } + *out_p = o.p; + *out_len = o.n; + return 0; +} diff --git a/tools/replay/trn1.h b/tools/replay/trn1.h new file mode 100644 index 000000000..a77228af2 --- /dev/null +++ b/tools/replay/trn1.h @@ -0,0 +1,41 @@ +/* trn1.h -- TRN1 execution transcript (aien-protocols + * specs/execution-transcript/TRN1_TRANSCRIPT_SPEC.md, contract 0.1.0, wire + * schema 1): an independent C verifier, comparator and corpus runner written + * from the spec text (no code imported), plus the RXCLOG01 -> TRN1 export. + * libc + src/sha256.h + rxlog.h only. */ +#ifndef OMEGA_TRN1_H +#define OMEGA_TRN1_H + +#include "replay/rxlog.h" + +#include +#include + +enum { + TRN1_OK = 0, TRN1_MAGIC = -1, TRN1_VERSION = -2, TRN1_LENGTH = -3, TRN1_NONCANONICAL = -4, + TRN1_UNKNOWN = -5, TRN1_SHAPE = -6, TRN1_GAP = -7, TRN1_CHAIN = -8, TRN1_DIGEST = -9, + TRN1_TRUNCATED = -10 +}; + +#define TRN1_MAX_RECORDS 4096u + +typedef struct { + int code; /* 0 accept, else a refusal code */ + uint64_t event; /* refusal position (0 = header) */ + uint64_t records; /* accepted: record count */ + uint8_t run_id[32], final[32]; + /* Accepted: per record (index k-1) compared digest and subsystem. */ + uint8_t (*cmp)[32]; + uint16_t *subsys; +} trn1_result; + +int trn1_verify(const uint8_t *buf, size_t len, trn1_result *r); +void trn1_result_free(trn1_result *r); +const char *trn1_subsystem_name(uint16_t id); +/* Spec section 8 lines, without newline. */ +void trn1_verify_line(const trn1_result *r, char *out, size_t n); +void trn1_compare_line(const uint8_t *a, size_t na, const uint8_t *b, size_t nb, char *out, size_t n); +/* Export an RXCLOG01 log (records up to END) as TRN1, producer omega-world. */ +int trn1_from_rxlog(const rxl_log *l, uint8_t **out, size_t *out_len); + +#endif