Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/patches/66b3bb04915e492f # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/omega-mv#174 (code only) closed derived `66b3bb04915e492f` #174 Imported from GitHub aien-dev/omega-mv#174 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `9ca297c6d377f41148bc366631b2b3891a445ceb` · Head `61c90e0eddfec7f332351b6bbe54d1e9c61560af` ### Apply it ``` git checkout -b patch-66b3bb04915e492f 9ca297c6d377f41148bc366631b2b3891a445ceb curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/66b3bb04915e492f.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/omega-mv 174 61c90e0eddfec7f332351b6bbe54d1e9c61560af ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":174,"url":"https://github.com/aien-dev/omega-mv/pull/174","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:38Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/mk/proof.mk b/mk/proof.mk new file mode 100644 index 000000000..58e908f9a --- /dev/null +++ b/mk/proof.mk @@ -0,0 +1,94 @@ +# Proof layer, hardening lane LG: World lifecycle model, differential harness +# against rx_world, and a ThreadSanitizer run of rx_world. Host only (no +# graphics chip, no physics headers). Owned files: tests/model/, this file. +# +# make test-model exhaustive model check + mutants +# make test-model-diff model vs real rx_world (+ concurrent stress) +# make test-model-tsan the same harness built with -fsanitize=thread +# (NOT_RUN when the toolchain has no tsan) +# make test-proof all three, then build/proof/LG-receipt.json +# +# Every target refuses to start while ~/workspace/.spark-quiet exists and +# says NOT_RUN instead. Knobs: PROOF_DEPTH (default 6), PROOF_TSAN_DEPTH (3). + +PROOF_OUT ?= $(OUT_DIR)/proof +PROOF_DEPTH ?= 6 +PROOF_TSAN_DEPTH ?= 3 +PROOF_QUIET ?= $(HOME)/workspace/.spark-quiet +PROOF_CFLAGS ?= -std=gnu11 -Wall -Wextra -Werror -D_GNU_SOURCE -Isrc -Itests/model -pthread +PROOF_MODEL_SRCS = tests/model/world_model.c tests/model/world_explore.c +PROOF_MODEL_HDRS = tests/model/world_model.h tests/model/world_explore.h +PROOF_RX_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c src/runtime/rx_coherent.c src/sha256.c +PROOF_RX_HDRS = src/runtime/rx_world.h src/runtime/rx_caproot.h src/runtime/rx_caller.h \ + src/runtime/omega_shared_world_abi.h + +PROOF_MODEL_BIN = $(PROOF_OUT)/model_check +PROOF_DIFF_BIN = $(PROOF_OUT)/world_diff +PROOF_TSAN_BIN = $(PROOF_OUT)/world_diff_tsan + +define proof_quiet_guard + @if [ -e "$(PROOF_QUIET)" ]; then echo "$(1): NOT_RUN (quiet flag $(PROOF_QUIET) is set)"; exit 1; fi +endef + +$(PROOF_OUT): + mkdir -p $@ + +$(PROOF_MODEL_BIN): tests/model/model_check.c $(PROOF_MODEL_SRCS) $(PROOF_MODEL_HDRS) | $(PROOF_OUT) + $(CC) $(PROOF_CFLAGS) -O2 -o $@ tests/model/model_check.c $(PROOF_MODEL_SRCS) + +$(PROOF_DIFF_BIN): tests/model/world_diff.c $(PROOF_MODEL_SRCS) $(PROOF_MODEL_HDRS) \ + $(PROOF_RX_SRCS) $(PROOF_RX_HDRS) | $(PROOF_OUT) + $(CC) $(PROOF_CFLAGS) -O2 -o $@ tests/model/world_diff.c $(PROOF_MODEL_SRCS) $(PROOF_RX_SRCS) + +$(PROOF_TSAN_BIN): tests/model/world_diff.c $(PROOF_MODEL_SRCS) $(PROOF_MODEL_HDRS) \ + $(PROOF_RX_SRCS) $(PROOF_RX_HDRS) | $(PROOF_OUT) + $(CC) $(PROOF_CFLAGS) -O1 -g -fsanitize=thread -o $@ tests/model/world_diff.c \ + $(PROOF_MODEL_SRCS) $(PROOF_RX_SRCS) + +.PHONY: test-model test-model-diff test-model-tsan test-proof + +test-model: + $(call proof_quiet_guard,test-model) + @$(MAKE) --no-print-directory $(PROOF_MODEL_BIN) + ./$(PROOF_MODEL_BIN) > $(PROOF_OUT)/model.log 2>&1; rc=$$?; cat $(PROOF_OUT)/model.log; exit $$rc + +test-model-diff: + $(call proof_quiet_guard,test-model-diff) + @$(MAKE) --no-print-directory $(PROOF_DIFF_BIN) + ./$(PROOF_DIFF_BIN) --depth $(PROOF_DEPTH) --stress > $(PROOF_OUT)/diff.log 2>&1; rc=$$?; \ + cat $(PROOF_OUT)/diff.log; exit $$rc + +# The tsan probe builds and runs a one-line program; a toolchain without +# libtsan (or a memory layout tsan rejects) is recorded as NOT_RUN. +test-model-tsan: + $(call proof_quiet_guard,test-model-tsan) + @mkdir -p $(PROOF_OUT) + @printf 'int main(void){return 0;}\n' > $(PROOF_OUT)/tsan_probe.c + @if ! $(CC) -fsanitize=thread -o $(PROOF_OUT)/tsan_probe $(PROOF_OUT)/tsan_probe.c 2>/dev/null || \ + ! $(PROOF_OUT)/tsan_probe >/dev/null 2>&1; then \ + echo "RESULT tsan=NOT_RUN (toolchain has no working -fsanitize=thread)" | tee $(PROOF_OUT)/tsan.log; \ + exit 0; \ + fi; \ + $(MAKE) --no-print-directory $(PROOF_TSAN_BIN) || exit 1; \ + TSAN_OPTIONS="halt_on_error=0 exitcode=66 second_deadlock_stack=1" \ + ./$(PROOF_TSAN_BIN) --depth $(PROOF_TSAN_DEPTH) --stress --stress-iters 400 \ + > $(PROOF_OUT)/tsan.log 2>&1; rc=$$?; \ + races=$$(grep -c 'WARNING: ThreadSanitizer' $(PROOF_OUT)/tsan.log); \ + echo "RESULT tsan.exit=$$rc" >> $(PROOF_OUT)/tsan.log; \ + echo "RESULT tsan.reports=$$races" >> $(PROOF_OUT)/tsan.log; \ + if [ "$$rc" = 0 ] && [ "$$races" = 0 ]; then v=PASS; else v=FAIL; fi; \ + echo "RESULT tsan=$$v" >> $(PROOF_OUT)/tsan.log; \ + grep '^RESULT tsan\|^WORLD DIFF' $(PROOF_OUT)/tsan.log; \ + grep -A12 'WARNING: ThreadSanitizer' $(PROOF_OUT)/tsan.log | head -60; \ + [ "$$v" = PASS ] + +test-proof: + @mkdir -p $(PROOF_OUT) + @rm -f $(PROOF_OUT)/model.log $(PROOF_OUT)/diff.log $(PROOF_OUT)/tsan.log + @if [ -e "$(PROOF_QUIET)" ]; then \ + echo "test-proof: NOT_RUN (quiet flag $(PROOF_QUIET) is set)"; \ + sh tests/model/receipt.sh $(PROOF_OUT) quiet; exit 1; fi + -@$(MAKE) --no-print-directory test-model + -@$(MAKE) --no-print-directory test-model-diff + -@$(MAKE) --no-print-directory test-model-tsan + sh tests/model/receipt.sh $(PROOF_OUT) diff --git a/tests/model/model_check.c b/tests/model/model_check.c new file mode 100644 index 000000000..2224f2e07 --- /dev/null +++ b/tests/model/model_check.c @@ -0,0 +1,75 @@ +/* + * model_check.c -- exhaustive check of the World lifecycle model (lane LG). + * + * For each profile, every reachable state is explored and every invariant is + * checked after every step: + * I1 no budget leak V_LEAK + * I2 cancel reaches children V_CANCEL_CHILD (and the target: V_CANCEL_SELF) + * I3 no double commit V_DOUBLE + * I4 deadline overrun surfaced V_DEADLINE + * + * Expectations (anything else is a FAIL of this checker): + * SPEC holds every invariant. + * AS_BUILT holds I1 and I3; fails I2 and I4 (KNOWN_FAIL: rx_world has no + * cancel entry point and counts a deadline only at admission). + * each mutant fails the invariant it targets (KILLED). + * Output: human lines plus "RESULT key=value" lines for the receipt. + */ +#include "world_explore.h" + +#include +#include + +static const char *bit_name[5] = { "I1_no_budget_leak", "I2_cancel_reaches_children", + "I3_no_double_commit", "I4_deadline_overrun_surfaced", + "I2b_cancel_reaches_target" }; + +static int bad; + +static void show(const char *tag, const WxResult *r, int b) { + printf(" %s %s counterexample (%d steps): ", tag, bit_name[b], r->trace_len[b]); + wx_print_trace(r->trace[b], r->trace_len[b]); + printf("\n"); +} + +static void run(const WmProfile *p, uint32_t must_hold, uint32_t must_fail, const char *role) { + WxResult r; + if (wx_explore(p, &r) != 0) { printf("RESULT model.%s=ERROR\n", p->name); bad++; return; } + printf("[*] %s (%s): %llu states, %llu transitions%s\n", p->name, role, + (unsigned long long)r.states, (unsigned long long)r.transitions, + r.truncated ? " TRUNCATED (not exhaustive)" : ""); + printf("RESULT model.%s.states=%llu\n", p->name, (unsigned long long)r.states); + printf("RESULT model.%s.transitions=%llu\n", p->name, (unsigned long long)r.transitions); + printf("RESULT model.%s.exhaustive=%s\n", p->name, r.truncated ? "NO" : "YES"); + if (r.truncated) bad++; + for (int b = 0; b < 5; b++) { + uint32_t bit = 1u << b; + int seen = (r.viol_seen & bit) != 0; + const char *verdict; + if (must_hold & bit) { + verdict = seen ? "FAIL" : "PASS"; + if (seen) { bad++; show("UNEXPECTED", &r, b); } + } else if (must_fail & bit) { + verdict = seen ? (strcmp(role, "mutant") == 0 ? "KILLED" : "KNOWN_FAIL") + : (strcmp(role, "mutant") == 0 ? "SURVIVED" : "UNEXPECTED_PASS"); + if (!seen) bad++; + else show(strcmp(role, "mutant") == 0 ? "killed by" : "FINDING", &r, b); + } else { + verdict = seen ? "violated" : "held"; + } + printf("RESULT model.%s.%s=%s\n", p->name, bit_name[b], verdict); + } +} + +int main(void) { + const uint32_t all = V_LEAK | V_CANCEL_CHILD | V_DOUBLE | V_DEADLINE | V_CANCEL_SELF; + run(&wm_spec, all, 0, "spec"); + run(&wm_as_built, V_LEAK | V_DOUBLE, V_CANCEL_CHILD | V_DEADLINE | V_CANCEL_SELF, "as-built"); + run(&wm_mut_leak, 0, V_LEAK, "mutant"); + run(&wm_mut_noprop, V_CANCEL_SELF, V_CANCEL_CHILD, "mutant"); + run(&wm_mut_double, 0, V_DOUBLE, "mutant"); + run(&wm_mut_deadline, 0, V_DEADLINE, "mutant"); + printf("RESULT model.verdict=%s\n", bad ? "FAIL" : "PASS"); + printf("MODEL CHECK: %s (%d unexpected)\n", bad ? "FAIL" : "PASS", bad); + return bad ? 1 : 0; +} diff --git a/tests/model/receipt.sh b/tests/model/receipt.sh new file mode 100755 index 000000000..1c99f3e56 --- /dev/null +++ b/tests/model/receipt.sh @@ -0,0 +1,131 @@ +#!/bin/sh +# receipt.sh OUT_DIR [quiet] -- build OUT_DIR/LG-receipt.json from the logs +# the proof targets wrote (model.log, diff.log, tsan.log). Every field is read +# from a log or from git; nothing is assumed. A missing log is NOT_RUN. +# Evidence class: host (CPU only; no QEMU, no hardware chip). +set -u +out=$1 +mode=${2:-run} +rcpt=$out/LG-receipt.json + +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 +cc_ver=$(${CC:-gcc} --version 2>/dev/null | head -n1) +host=$(uname -srm) +now=$(date -u +%Y-%m-%dT%H:%M:%SZ) + +# get KEY: value of the last "RESULT KEY=..." line in any log, else empty. +get() { + cat "$out/model.log" "$out/diff.log" "$out/tsan.log" 2>/dev/null | + sed -n "s/^RESULT $1=//p" | tail -n1 +} +# tsan values come only from tsan.log (the tsan build prints the same keys). +get_tsan() { sed -n "s/^RESULT $1=//p" "$out/tsan.log" 2>/dev/null | tail -n1; } +get_main() { + cat "$out/model.log" "$out/diff.log" 2>/dev/null | sed -n "s/^RESULT $1=//p" | tail -n1 +} +esc() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; } +or_nr() { if [ -z "$1" ]; then echo NOT_RUN; else echo "$1"; fi; } + +if [ "$mode" = quiet ]; then + cat > "$rcpt" < "$rcpt" +echo "receipt: $rcpt" +echo "LG proof: $overall (I1=$i1 I2=$i2 I3=$i3 I4=$i4 model=$model_v diff=$diff_v tsan=$tsan_v)" +case "$overall" in PASS|PASS_WITH_KNOWN_FAIL) exit 0 ;; *) exit 1 ;; esac diff --git a/tests/model/world_diff.c b/tests/model/world_diff.c new file mode 100644 index 000000000..cd8b3b36e --- /dev/null +++ b/tests/model/world_diff.c @@ -0,0 +1,746 @@ +/* + * world_diff.c -- differential harness: the lifecycle model against the real + * rx_world (hardening lane LG). Host only; no graphics chip. + * + * The real World is built with the model's tree (P -> C1, C2; C1 -> G), the + * model's budget (2 slots, 8 memory) and needs. Every reaction function is a + * gate: it parks inside the function until the harness says "finish" (commit + * a new, strictly increasing value) or "fail" (return an error). After every + * operation the harness waits until the World is settled (every admitted + * activation is parked inside its function, nothing pending) and compares + * what the World shows with what the AS_BUILT model predicts. + * + * Observed through rx_world.h only: rx_world_footprint, rx_world_crumb, + * rx_world_verify_crumbs, the RxStats block and each RxReaction's state, + * rearm, parked, yield_left and commits fields (declared in rx_world.h, read + * under the world lock). No src/runtime code is changed or shimmed. + * + * Parts: + * 1. Exhaustive differential: every operation sequence of the AS_BUILT model + * up to --depth (default 6), outside publications, finishes, failures + * and clock ticks, replayed on a fresh World. Expect 0 mismatches. + * 2. Harness mutants: the same comparison against the model with a leak and + * a double-commit fault switched on must find a mismatch (KILLED). + * 3. Real-side checks on every settled step and at the end of each run: + * budget held == budget of the activations in their functions, zero at + * quiescence; no two commits of one reaction answer the same wake; + * rx_world_verify_crumbs == 0. Each checker has a shim mutation that + * must trip it. + * 4. Directed replays of the model's counterexamples for the two known + * gaps (I2 cancel, I4 deadline) on the real World, reported as FINDINGS. + * --stress: concurrent publishers, clock ticks and observers against free + * running reactions (the ThreadSanitizer workload). + * Output: human lines plus "RESULT key=value" lines for the receipt. + */ +#include "runtime/rx_world.h" +#include "world_explore.h" +#include "world_model.h" + +#include +#include +#include +#include +#include +#include + +/* ---- gate ---------------------------------------------------------------- */ + +typedef struct { + pthread_mutex_t mu; + pthread_cond_t cv; + int in_fn[WM_N]; + int n_in_fn; + int cmd[WM_N]; /* 1 finish, 2 fail */ + int drain; /* functions return at once (commit) */ + int free_run; /* --stress: never park */ +} Gate; + +static Gate g = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, {0}, 0, {0}, 0, 0 }; +static uint64_t g_value; /* atomic; strictly increasing outputs */ +static RxObjRef g_out[WM_N]; +static uint32_t g_idx[WM_N] = { 0, 1, 2, 3 }; + +static int fn_gate(RxCtx *ctx) { + uint32_t i = *(const uint32_t *)ctx->user; + int c = 1; + pthread_mutex_lock(&g.mu); + if (g.free_run) { + uint64_t v = __atomic_add_fetch(&g_value, 1, __ATOMIC_SEQ_CST); + c = (v % 7u == 0) ? 2 : 1; + } else if (!g.drain) { + g.in_fn[i] = 1; + g.n_in_fn++; + while (!g.cmd[i] && !g.drain) pthread_cond_wait(&g.cv, &g.mu); + if (g.cmd[i]) c = g.cmd[i]; + g.cmd[i] = 0; + g.in_fn[i] = 0; + g.n_in_fn--; + } + pthread_mutex_unlock(&g.mu); + if (c == 2) return -1; + uint64_t v = __atomic_add_fetch(&g_value, 1, __ATOMIC_SEQ_CST); + ctx->n_out = 1; + ctx->out[0].obj = g_out[i]; + ctx->out[0].field = 0; + ctx->out[0].value = v; + return 0; +} + +/* ---- authority stand-in: every reference is valid ------------------------ */ + +static int auth_ok(const void *c, RxCapRef ref, uint32_t subject, uint64_t resource, + uint32_t rights, RxCapEntry *out) { + (void)c; (void)ref; (void)subject; (void)resource; (void)rights; + if (out) memset(out, 0, sizeof *out); + return RX_CAP_OK; +} +static int auth_inspect(const void *c, RxCapRef ref, RxCapEntry *out) { + (void)c; (void)ref; (void)out; + return RX_CAP_ERR_STATE; +} +static int g_auth_ctx; + +/* ---- real World ---------------------------------------------------------- */ + +typedef struct { + RxWorld *w; + RxObjRef e; + uint8_t tick; + uint32_t slots; + uint64_t mem; +} Real; + +static void set_budget(Real *R) { + RxResourceBudget b; + memset(&b, 0, sizeof b); + b.slots = R->slots; + b.memory_bytes = R->mem; + b.energy_budget = UINT64_MAX; + b.offered_locality = UINT32_MAX; + b.offered_accel = UINT32_MAX; + b.compute_mask = UINT32_MAX; + b.logical_tick = R->tick; + rx_world_set_resources(R->w, &b); +} + +static int real_start(Real *R, uint32_t workers, uint32_t slots, uint64_t mem) { + memset(R, 0, sizeof *R); + R->slots = slots; + R->mem = mem; + R->w = calloc(1, sizeof *R->w); + if (!R->w) return -1; + if (rx_world_init_with_auth(R->w, NULL, &g_auth_ctx, auth_ok, auth_inspect, workers, + 1u << 14) != RX_OK) { + free(R->w); + return -1; + } + R->w->external_subject = 100; + set_budget(R); + if (rx_world_create(R->w, 1, RX_PERSIST_RESIDENT, 1, NULL, &R->e) != RX_OK) return -1; + for (uint32_t i = 0; i < WM_N; i++) + if (rx_world_create(R->w, 1, RX_PERSIST_RESIDENT, 1, NULL, &g_out[i]) != RX_OK) return -1; + for (uint32_t i = 0; i < WM_N; i++) { + RxReactionDesc d; + memset(&d, 0, sizeof d); + d.name = wm_name[i]; + d.faculty = i + 1; + d.subject = 1; + d.priority = RX_PRIO_FOREGROUND; + d.need.memory_bytes = wm_mem[i]; + d.need.deadline = wm_deadline[i]; + d.n_triggers = 1; + d.triggers[0].obj = wm_parent[i] < 0 ? R->e : g_out[wm_parent[i]]; + d.triggers[0].mask = RX_FIELD(0); + d.n_writes = 1; + d.writes[0].obj = g_out[i]; + d.writes[0].mask = RX_FIELD(0); + d.n_caps = 1; + d.caps[0].ref = (RxCapRef){ 1, 1 }; + d.caps[0].resource = 1; + d.caps[0].rights = RX_RIGHT_READ | RX_RIGHT_WRITE; + d.fn = fn_gate; + d.user = &g_idx[i]; + uint32_t rid = UINT32_MAX; + if (rx_world_add_reaction(R->w, &d, &rid) != RX_OK || rid != i) return -1; + } + return 0; +} + +static uint64_t g_ext_value; + +static int real_ext(Real *R) { + RxMutation m = { R->e, 0, ++g_ext_value }; + return rx_world_publish_external(R->w, (RxCapRef){ 1, 1 }, &m, 1) > 0 ? 0 : -1; +} + +static int real_release(uint32_t r, int how) { + pthread_mutex_lock(&g.mu); + int ok = g.in_fn[r]; + if (ok) g.cmd[r] = how; + pthread_cond_broadcast(&g.cv); + pthread_mutex_unlock(&g.mu); + return ok ? 0 : -1; +} + +/* ---- observation ----------------------------------------------------------- */ + +enum { CL_IDLE = 0, CL_WAITING = 1, CL_RUN = 2, CL_PARKED = 3, CL_OTHER = 9 }; +typedef struct { + uint8_t cls[WM_N], rearm[WM_N], yield[WM_N]; + uint32_t commits[WM_N]; + uint32_t used_slots, in_flight; + uint64_t used_mem, overdue, invalidations, failed; + int in_fn[WM_N]; +} Obs; + +static const char *cls_name(int c) { + switch (c) { + case CL_IDLE: return "IDLE"; case CL_WAITING: return "WAITING"; + case CL_RUN: return "RUN"; case CL_PARKED: return "PARKED"; default: return "OTHER"; + } +} + +static void model_obs(const WmState *s, Obs *o) { + memset(o, 0, sizeof *o); + for (uint32_t r = 0; r < WM_N; r++) { + o->cls[r] = s->st[r] == WM_RUN ? CL_RUN : s->st[r] == WM_WAITING ? CL_WAITING + : s->st[r] == WM_IDLE ? (s->parked[r] ? CL_PARKED : CL_IDLE) : CL_OTHER; + o->rearm[r] = s->rearm[r]; + o->yield[r] = s->yield[r]; + o->commits[r] = s->commits[r]; + o->in_fn[r] = s->st[r] == WM_RUN; + } + o->used_slots = s->used_slots; + o->used_mem = s->used_mem; + o->in_flight = s->in_flight; + o->overdue = s->overdue; + o->invalidations = s->invalidations; + o->failed = s->failures; +} + +static int g_real_leak_shim; /* checker self-test: pretend one slot leaked */ + +/* Wait until settled, then capture. Lock order: world, then gate (the gate + * never takes the world lock), so the two counts are one consistent cut. */ +static int settle(Real *R, Obs *o) { + struct timespec t0, now; + clock_gettime(CLOCK_MONOTONIC, &t0); + for (;;) { + RxWorld *w = R->w; + pthread_mutex_lock(&w->mu); + pthread_mutex_lock(&g.mu); + int pending = 0; + for (uint32_t r = 0; r < WM_N; r++) pending |= g.cmd[r]; + int ok = !pending && w->in_flight == (uint32_t)g.n_in_fn && w->deferred_len == 0; + if (ok) { + memset(o, 0, sizeof *o); + for (uint32_t r = 0; r < WM_N; r++) { + const RxReaction *x = &w->reactions[r]; + o->cls[r] = x->state == RX_DORMANT ? (x->parked ? CL_PARKED : CL_IDLE) + : x->state == RX_BLOCKED_RESOURCE ? CL_WAITING + : x->state == RX_RUNNING ? CL_RUN : CL_OTHER; + o->rearm[r] = x->rearm; + o->yield[r] = (uint8_t)x->yield_left; + o->commits[r] = (uint32_t)x->commits; + o->in_fn[r] = g.in_fn[r]; + } + o->used_slots = w->used_slots + (g_real_leak_shim ? 1u : 0u); + o->used_mem = w->used_memory; + o->in_flight = w->in_flight; + o->overdue = w->stats.deadline_overdue; + o->invalidations = w->stats.invalidations; + o->failed = w->stats.failed; + } + pthread_mutex_unlock(&g.mu); + pthread_mutex_unlock(&w->mu); + if (ok) return 0; + clock_gettime(CLOCK_MONOTONIC, &now); + if ((now.tv_sec - t0.tv_sec) * 1000000000L + (now.tv_nsec - t0.tv_nsec) > 3000000000L) + return -1; + struct timespec ts = { 0, 20000 }; + nanosleep(&ts, NULL); + } +} + +/* Real-side I1 on one settled cut: held budget == the activations parked in + * their functions (each holds exactly its need). */ +static int real_leak_check(const Obs *o) { + uint32_t n = 0; + uint64_t mem = 0; + for (uint32_t r = 0; r < WM_N; r++) + if (o->in_fn[r]) { n++; mem += wm_mem[r]; } + return o->used_slots == n && o->used_mem == mem && o->in_flight == n ? 0 : -1; +} + +static int obs_diff(const Obs *m, const Obs *r, char *buf, size_t n) { + for (uint32_t i = 0; i < WM_N; i++) { + if (m->cls[i] != r->cls[i]) + return snprintf(buf, n, "%s state model=%s real=%s", wm_name[i], + cls_name(m->cls[i]), cls_name(r->cls[i])), 1; + if (m->rearm[i] != r->rearm[i]) + return snprintf(buf, n, "%s rearm model=%u real=%u", wm_name[i], m->rearm[i], r->rearm[i]), 1; + if (m->yield[i] != r->yield[i]) + return snprintf(buf, n, "%s yield model=%u real=%u", wm_name[i], m->yield[i], r->yield[i]), 1; + if (m->commits[i] != r->commits[i]) + return snprintf(buf, n, "%s commits model=%u real=%u", wm_name[i], m->commits[i], r->commits[i]), 1; + } +#define D(f) if (m->f != r->f) return snprintf(buf, n, #f " model=%llu real=%llu", \ + (unsigned long long)m->f, (unsigned long long)r->f), 1; + D(used_slots) D(used_mem) D(in_flight) D(overdue) D(invalidations) D(failed) +#undef D + return 0; +} + +/* Real-side I3 over the crumb log: no two COMMIT crumbs of one reaction share + * a wake cause. `dup_shim` appends a copy of the first commit (self-test). */ +static int commit_unique_check(RxWorld *w, int dup_shim, uint64_t *n_commits) { + uint64_t n = w->n_crumbs; + uint64_t cap = n + 1; + uint32_t *rx = malloc(sizeof(uint32_t) * cap); + uint64_t *cause = malloc(sizeof(uint64_t) * cap); + if (!rx || !cause) { free(rx); free(cause); return -1; } + uint64_t k = 0; + for (uint64_t id = 1; id <= n; id++) { + const RxCrumb *c = rx_world_crumb(w, id); + if (c && c->kind == RX_CRUMB_COMMIT) { rx[k] = c->reaction; cause[k] = c->wake_cause; k++; } + } + if (dup_shim && k) { rx[k] = rx[0]; cause[k] = cause[0]; k++; } + int bad = 0; + for (uint64_t i = 0; i < k && !bad; i++) + for (uint64_t j = i + 1; j < k; j++) + if (rx[i] == rx[j] && cause[i] == cause[j]) { bad = 1; break; } + if (n_commits) *n_commits = k; + free(rx); + free(cause); + return bad ? -1 : 0; +} + +static void gate_reset(void) { + pthread_mutex_lock(&g.mu); + memset(g.in_fn, 0, sizeof g.in_fn); + memset(g.cmd, 0, sizeof g.cmd); + g.n_in_fn = 0; + g.drain = 0; + pthread_mutex_unlock(&g.mu); +} + +/* Drain, wait quiescent, run end-of-run checks, destroy. */ +typedef struct { int quiesce_fail, leak_fail, dup_fail, verify_fail; } EndCheck; +static void real_finish(Real *R, EndCheck *ec) { + pthread_mutex_lock(&g.mu); + g.drain = 1; + pthread_cond_broadcast(&g.cv); + pthread_mutex_unlock(&g.mu); + if (rx_world_wait_quiescent(R->w, 5000) != RX_OK) ec->quiesce_fail++; + RxFootprint f; + rx_world_footprint(R->w, &f); + if (f.used_slots || f.used_memory || f.used_energy || f.in_flight) ec->leak_fail++; + if (commit_unique_check(R->w, 0, NULL) != 0) ec->dup_fail++; + uint64_t checked = 0; + if (rx_world_verify_crumbs(R->w, &checked) != 0) ec->verify_fail++; + rx_world_destroy(R->w); + free(R->w); + R->w = NULL; + gate_reset(); +} + +/* ---- one replay ------------------------------------------------------------ */ + +typedef struct { + uint64_t runs, steps, mismatches, real_leak, harness_err; + EndCheck end; + char first[512]; +} DiffStats; + +static void trace_str(const WmOp *t, int n, char *buf, size_t cap) { + size_t at = 0; + buf[0] = 0; + for (int i = 0; i < n && at + 24 < cap; i++) { + char b[32]; + wm_op_str(t[i], b, sizeof b); + at += (size_t)snprintf(buf + at, cap - at, "%s%s", i ? " -> " : "", b); + } +} + +/* Returns 1 on a model/real mismatch. */ +static int replay(const WmProfile *p, const WmOp *t, int n, DiffStats *ds) { + Real R; + gate_reset(); + if (real_start(&R, WM_N, WM_SLOTS, WM_MEM) != 0) { ds->harness_err++; return 0; } + WmState s; + wm_init(&s); + int mismatch = 0; + Obs mo, ro; + char why[200] = ""; + for (int i = 0; i < n && !mismatch; i++) { + wm_step(p, &s, t[i]); + int rc = 0; + switch (t[i].kind) { + case OP_EXT: rc = real_ext(&R); break; + case OP_TICK: R.tick++; set_budget(&R); break; + case OP_FIN: rc = real_release(t[i].r, 1); break; + case OP_FAIL: rc = real_release(t[i].r, 2); break; + default: break; + } + if (rc != 0 || settle(&R, &ro) != 0) { + mismatch = 1; + snprintf(why, sizeof why, "step %d: real World did not accept/settle (rc=%d)", i + 1, rc); + break; + } + ds->steps++; + if (real_leak_check(&ro) != 0) ds->real_leak++; + model_obs(&s, &mo); + if (obs_diff(&mo, &ro, why, sizeof why)) { + mismatch = 1; + char w2[200]; + snprintf(w2, sizeof w2, "after step %d: %s", i + 1, why); + memcpy(why, w2, sizeof why); + } + } + if (mismatch && !ds->first[0]) { + char tb[300]; + trace_str(t, n, tb, sizeof tb); + snprintf(ds->first, sizeof ds->first, "[%s] %s", tb, why); + } + if (mismatch) ds->mismatches++; + ds->runs++; + real_finish(&R, &ds->end); + return mismatch; +} + +/* Every sequence of the AS_BUILT model up to `depth` (no CANCEL: rx_world has + * no cancel entry point; see the directed replay). Replays leaves only; + * every prefix is compared along the way. */ +static int g_stop_on_first; +static void enumerate(const WmProfile *p, WmState *s, WmOp *t, int at, int depth, DiffStats *ds) { + if (g_stop_on_first && ds->mismatches) return; + WmOp ops[16]; + int nops = wm_all_ops(ops); + int any = 0; + if (at < depth) { + for (int o = 0; o < nops; o++) { + if (ops[o].kind == OP_CANCEL || !wm_enabled(p, s, ops[o])) continue; + any = 1; + WmState c = *s; + wm_step(p, &c, ops[o]); + t[at] = ops[o]; + enumerate(p, &c, t, at + 1, depth, ds); + } + } + if (!any && at > 0) replay(p, t, at, ds); +} + +/* ---- directed replays of the model's counterexamples ---------------------- */ + +static int directed_cancel(void) { + WxResult xr; + wx_explore(&wm_as_built, &xr); + int b = wx_bit_index(V_CANCEL_CHILD); + if (xr.trace_len[b] <= 0) { printf("RESULT real.I2.directed=NOT_RUN\n"); return -1; } + WmOp *t = xr.trace[b]; + int n = xr.trace_len[b]; + char tb[300]; + trace_str(t, n, tb, sizeof tb); + Real R; + gate_reset(); + if (real_start(&R, WM_N, WM_SLOTS, WM_MEM) != 0) return -1; + WmState spec; + wm_init(&spec); + Obs ro; + int remove_rc = 0, removed_busy = 0, still = 0; + uint32_t target = 0; + char who[64] = ""; + for (int i = 0; i < n; i++) { + wm_step(&wm_spec, &spec, t[i]); + switch (t[i].kind) { + case OP_EXT: real_ext(&R); break; + case OP_TICK: R.tick++; set_budget(&R); break; + case OP_FIN: real_release(t[i].r, 1); break; + case OP_FAIL: real_release(t[i].r, 2); break; + case OP_CANCEL: + /* No cancel entry point. The nearest public call, removal, is + * tried on every busy member of the subtree. */ + target = t[i].r; + settle(&R, &ro); + for (uint32_t x = 0; x < WM_N; x++) + if ((x == target || wm_is_descendant(x, target)) && ro.cls[x] != CL_IDLE) { + remove_rc = rx_world_remove_reaction(R.w, x); + if (remove_rc == RX_ERR_BUSY) removed_busy++; + } + break; + } + settle(&R, &ro); + } + uint32_t child = WM_N; + for (uint32_t x = 0; x < WM_N; x++) + if (wm_is_descendant(x, target) && ro.cls[x] != CL_IDLE) { + still++; + size_t l = strlen(who); + snprintf(who + l, sizeof who - l, "%s%s=%s", l ? "," : "", wm_name[x], cls_name(ro.cls[x])); + if (child == WM_N && ro.cls[x] == CL_RUN) child = x; + } + uint32_t commits_before = child < WM_N ? ro.commits[child] : 0, commits_after = 0; + if (child < WM_N) { + real_release(child, 1); + settle(&R, &ro); + commits_after = ro.commits[child]; + } + int spec_idle = 1; + for (uint32_t x = 0; x < WM_N; x++) + if ((x == target || wm_is_descendant(x, target)) && spec.st[x] != WM_IDLE) spec_idle = 0; + printf("FINDING I2 cancel does not reach children (KNOWN_FAIL)\n"); + printf(" trace: %s\n", tb); + printf(" SPEC model after cancel(%s): whole subtree idle=%s, budget slots held=%u\n", + wm_name[target], spec_idle ? "yes" : "no", spec.used_slots); + printf(" real rx_world: no cancel entry point (RX_CANCELLED is never entered);" + " rx_world_remove_reaction on busy members returned %d (%d x RX_ERR_BUSY)\n", + remove_rc, removed_busy); + printf(" real rx_world after the cancel: children still in flight: %s\n", who); + if (child < WM_N) + printf(" continuation FIN(%s): real commits %u -> %u (child published after its parent was cancelled)\n", + wm_name[child], commits_before, commits_after); + EndCheck ec = { 0, 0, 0, 0 }; + real_finish(&R, &ec); + int reproduced = still > 0 && spec_idle; + printf("RESULT real.I2.directed=%s\n", reproduced ? "KNOWN_FAIL" : "NOT_REPRODUCED"); + printf("RESULT real.I2.counterexample=%s\n", tb); + printf("RESULT real.I2.children_in_flight_after_cancel=%s\n", who[0] ? who : "none"); + printf("RESULT real.I2.child_commit_after_cancel=%s\n", + child < WM_N && commits_after > commits_before ? "YES" : "NO"); + return reproduced ? 0 : -1; +} + +static int directed_deadline(void) { + WxResult xr; + wx_explore(&wm_as_built, &xr); + int b = wx_bit_index(V_DEADLINE); + if (xr.trace_len[b] <= 0) { printf("RESULT real.I4.directed=NOT_RUN\n"); return -1; } + WmOp *t = xr.trace[b]; + int n = xr.trace_len[b]; + char tb[300]; + trace_str(t, n, tb, sizeof tb); + Real R; + gate_reset(); + if (real_start(&R, WM_N, WM_SLOTS, WM_MEM) != 0) return -1; + WmState spec; + wm_init(&spec); + Obs ro; + for (int i = 0; i < n; i++) { + wm_step(&wm_spec, &spec, t[i]); + switch (t[i].kind) { + case OP_EXT: real_ext(&R); break; + case OP_TICK: R.tick++; set_budget(&R); break; + case OP_FIN: real_release(t[i].r, 1); break; + case OP_FAIL: real_release(t[i].r, 2); break; + default: break; + } + settle(&R, &ro); + } + uint32_t late = WM_N; + for (uint32_t x = 0; x < WM_N; x++) + if (ro.cls[x] == CL_RUN && wm_deadline[x] && R.tick > wm_deadline[x]) { late = x; break; } + uint64_t real_overdue = ro.overdue; + uint32_t c0 = late < WM_N ? ro.commits[late] : 0, c1 = 0; + if (late < WM_N) { + real_release(late, 1); + settle(&R, &ro); + c1 = ro.commits[late]; + } + printf("FINDING I4 deadline overrun is not surfaced while running, and never enforced (KNOWN_FAIL)\n"); + printf(" trace: %s\n", tb); + if (late < WM_N) + printf(" %s (deadline %u) still running at tick %u: SPEC surfaced overruns=%u, real deadline_overdue=%llu\n", + wm_name[late], wm_deadline[late], R.tick, spec.overdue, (unsigned long long)real_overdue); + printf(" continuation FIN: real commits %u -> %u (late work still publishes)\n", c0, c1); + EndCheck ec = { 0, 0, 0, 0 }; + real_finish(&R, &ec); + int reproduced = late < WM_N && spec.overdue > real_overdue; + printf("RESULT real.I4.directed=%s\n", reproduced ? "KNOWN_FAIL" : "NOT_REPRODUCED"); + printf("RESULT real.I4.counterexample=%s\n", tb); + printf("RESULT real.I4.spec_overdue=%u\n", spec.overdue); + printf("RESULT real.I4.real_deadline_overdue=%llu\n", (unsigned long long)real_overdue); + printf("RESULT real.I4.late_commit_published=%s\n", c1 > c0 ? "YES" : "NO"); + return reproduced ? 0 : -1; +} + +/* ---- checker self-tests (shim mutations) ---------------------------------- */ + +static int self_tests(void) { + int bad = 0; + /* Leak checker: one settled run with the observation shim on must trip. */ + WmOp t[2] = { { OP_EXT, 0 }, { OP_FIN, WM_P } }; + DiffStats ds; + memset(&ds, 0, sizeof ds); + g_real_leak_shim = 1; + replay(&wm_as_built, t, 2, &ds); + g_real_leak_shim = 0; + int leak_killed = ds.real_leak > 0; + printf("RESULT shim.real_leak_check=%s\n", leak_killed ? "KILLED" : "SURVIVED"); + bad += !leak_killed; + /* Duplicate-commit checker: a copied COMMIT crumb must trip it. */ + Real R; + gate_reset(); + int dup_killed = 0, clean_ok = 0; + if (real_start(&R, WM_N, WM_SLOTS, WM_MEM) == 0) { + Obs ro; + real_ext(&R); + settle(&R, &ro); + real_release(WM_P, 1); + settle(&R, &ro); + uint64_t k = 0; + clean_ok = commit_unique_check(R.w, 0, &k) == 0 && k > 0; + dup_killed = commit_unique_check(R.w, 1, NULL) != 0; + EndCheck ec = { 0, 0, 0, 0 }; + real_finish(&R, &ec); + } + printf("RESULT shim.commit_unique_check=%s\n", dup_killed && clean_ok ? "KILLED" : "SURVIVED"); + bad += !(dup_killed && clean_ok); + return bad; +} + +/* ---- stress (ThreadSanitizer workload) ------------------------------------ */ + +typedef struct { Real *R; int iters; int stop; } StressCtx; + +static void *stress_pub(void *a) { + StressCtx *c = a; + for (int i = 0; i < c->iters; i++) { + RxMutation m = { c->R->e, 0, __atomic_add_fetch(&g_ext_value, 1, __ATOMIC_SEQ_CST) }; + rx_world_publish_external(c->R->w, (RxCapRef){ 1, 1 }, &m, 1); + } + return NULL; +} +static void *stress_tick(void *a) { + StressCtx *c = a; + for (int i = 0; i < 200; i++) { + RxResourceBudget b; + memset(&b, 0, sizeof b); + b.slots = 3; b.memory_bytes = 16; b.energy_budget = UINT64_MAX; + b.offered_locality = b.offered_accel = b.compute_mask = UINT32_MAX; + b.logical_tick = (uint64_t)i; + rx_world_set_resources(c->R->w, &b); + } + return NULL; +} +static void *stress_observe(void *a) { + StressCtx *c = a; + while (!__atomic_load_n(&c->stop, __ATOMIC_SEQ_CST)) { + RxFootprint f; + RxObject o; + uint8_t d[32]; + rx_world_footprint(c->R->w, &f); + rx_world_read(c->R->w, c->R->e, &o); + rx_world_digest(c->R->w, d); + } + return NULL; +} + +static int stress(int iters) { + Real R; + gate_reset(); + pthread_mutex_lock(&g.mu); + g.free_run = 1; + pthread_mutex_unlock(&g.mu); + if (real_start(&R, 8, 3, 16) != 0) { printf("RESULT stress=ERROR\n"); return 1; } + StressCtx c = { &R, iters, 0 }; + pthread_t pub[3], tick, obs; + for (int i = 0; i < 3; i++) pthread_create(&pub[i], NULL, stress_pub, &c); + pthread_create(&tick, NULL, stress_tick, &c); + pthread_create(&obs, NULL, stress_observe, &c); + for (int i = 0; i < 3; i++) pthread_join(pub[i], NULL); + pthread_join(tick, NULL); + int q = rx_world_wait_quiescent(R.w, 20000); + __atomic_store_n(&c.stop, 1, __ATOMIC_SEQ_CST); + pthread_join(obs, NULL); + RxFootprint f; + rx_world_footprint(R.w, &f); + uint64_t commits = 0, checked = 0; + int dup = commit_unique_check(R.w, 0, &commits); + int ver = rx_world_verify_crumbs(R.w, &checked); + pthread_mutex_lock(&R.w->mu); + RxStats st = R.w->stats; + pthread_mutex_unlock(&R.w->mu); + int ok = q == RX_OK && !f.used_slots && !f.used_memory && !f.in_flight && dup == 0 && ver == 0; + printf("[*] stress: %d x 3 publications, 200 clock ticks, observer thread: quiescent=%s " + "commits=%llu failed=%llu invalidations=%llu crumbs_verified=%llu held_at_rest=%u/%llu\n", + iters, q == RX_OK ? "yes" : "NO", (unsigned long long)commits, + (unsigned long long)st.failed, (unsigned long long)st.invalidations, + (unsigned long long)checked, f.used_slots, (unsigned long long)f.used_memory); + printf("RESULT stress.publications=%d\n", iters * 3); + printf("RESULT stress.commits=%llu\n", (unsigned long long)commits); + printf("RESULT stress.no_leak_at_rest=%s\n", !f.used_slots && !f.used_memory && !f.in_flight ? "PASS" : "FAIL"); + printf("RESULT stress.commit_unique=%s\n", dup == 0 ? "PASS" : "FAIL"); + printf("RESULT stress.crumbs_verify=%s\n", ver == 0 ? "PASS" : "FAIL"); + printf("RESULT stress=%s\n", ok ? "PASS" : "FAIL"); + EndCheck ec = { 0, 0, 0, 0 }; + real_finish(&R, &ec); + pthread_mutex_lock(&g.mu); + g.free_run = 0; + pthread_mutex_unlock(&g.mu); + return ok ? 0 : 1; +} + +/* ---- main ------------------------------------------------------------------ */ + +int main(int argc, char **argv) { + int depth = 6, do_stress = 0, stress_iters = 3000, only_stress = 0; + for (int i = 1; i < argc; i++) { + if (!strcmp(argv[i], "--depth") && i + 1 < argc) depth = atoi(argv[++i]); + else if (!strcmp(argv[i], "--stress")) do_stress = 1; + else if (!strcmp(argv[i], "--stress-only")) do_stress = only_stress = 1; + else if (!strcmp(argv[i], "--stress-iters") && i + 1 < argc) stress_iters = atoi(argv[++i]); + else { fprintf(stderr, "usage: %s [--depth N] [--stress|--stress-only] [--stress-iters N]\n", argv[0]); return 2; } + } + int bad = 0; + if (!only_stress) { + WmOp t[64]; + WmState s; + DiffStats ds; + memset(&ds, 0, sizeof ds); + wm_init(&s); + enumerate(&wm_as_built, &s, t, 0, depth, &ds); + printf("[*] differential AS_BUILT vs rx_world, depth %d: %llu runs, %llu settled steps, " + "%llu mismatches\n", depth, (unsigned long long)ds.runs, + (unsigned long long)ds.steps, (unsigned long long)ds.mismatches); + if (ds.first[0]) printf(" first mismatch: %s\n", ds.first); + printf("RESULT diff.depth=%d\n", depth); + printf("RESULT diff.runs=%llu\n", (unsigned long long)ds.runs); + printf("RESULT diff.steps=%llu\n", (unsigned long long)ds.steps); + printf("RESULT diff.mismatches=%llu\n", (unsigned long long)ds.mismatches); + printf("RESULT real.I1.settled_leak_violations=%llu\n", (unsigned long long)ds.real_leak); + printf("RESULT real.I1.quiescent_leak_violations=%d\n", ds.end.leak_fail); + printf("RESULT real.I3.duplicate_commit_runs=%d\n", ds.end.dup_fail); + printf("RESULT real.crumbs_verify_failures=%d\n", ds.end.verify_fail); + printf("RESULT real.quiesce_failures=%d\n", ds.end.quiesce_fail); + printf("RESULT diff.harness_errors=%llu\n", (unsigned long long)ds.harness_err); + int diff_ok = ds.runs > 0 && ds.mismatches == 0 && ds.real_leak == 0 && ds.end.leak_fail == 0 && + ds.end.dup_fail == 0 && ds.end.verify_fail == 0 && ds.end.quiesce_fail == 0 && + ds.harness_err == 0; + printf("RESULT diff.verdict=%s\n", diff_ok ? "PASS" : "FAIL"); + bad += !diff_ok; + + /* Harness mutants: AS_BUILT plus one fault; the comparison must notice. */ + const WmProfile mut_leak = { "DIFF_MUT_LEAK_ON_FAIL", CANCEL_NONE, 0, 1, 0 }; + const WmProfile mut_double = { "DIFF_MUT_COMMIT_KEEPS_ACTIVATION", CANCEL_NONE, 0, 0, 1 }; + const WmProfile *muts[2] = { &mut_leak, &mut_double }; + g_stop_on_first = 1; + for (int m = 0; m < 2; m++) { + DiffStats dm; + memset(&dm, 0, sizeof dm); + wm_init(&s); + enumerate(muts[m], &s, t, 0, depth < 4 ? depth : 4, &dm); + int killed = dm.mismatches > 0; + printf("RESULT diff.%s=%s\n", muts[m]->name, killed ? "KILLED" : "SURVIVED"); + if (killed) printf(" %s killed: %s\n", muts[m]->name, dm.first); + bad += !killed; + } + g_stop_on_first = 0; + bad += self_tests(); + if (directed_cancel() != 0) bad++; + if (directed_deadline() != 0) bad++; + } + if (do_stress) bad += stress(stress_iters); + printf("RESULT world_diff.verdict=%s\n", bad ? "FAIL" : "PASS"); + printf("WORLD DIFF: %s\n", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} diff --git a/tests/model/world_explore.c b/tests/model/world_explore.c new file mode 100644 index 000000000..7ff869822 --- /dev/null +++ b/tests/model/world_explore.c @@ -0,0 +1,112 @@ +/* + * world_explore.c -- breadth-first search over every reachable model state + * (bounded only by WM_EXT_MAX outside publications and WM_TICK_MAX clock + * steps). Breadth-first, so the first trace found for a violation is a + * shortest one. + */ +#include "world_explore.h" + +#include +#include +#include + +#define KEY_MAX 48 +#define TABLE_BITS 20u +#define TABLE_SIZE (1u << TABLE_BITS) + +typedef struct { + WmState s; + uint32_t parent; + WmOp op; + uint8_t key[KEY_MAX]; + uint8_t klen; +} Node; + +int wx_bit_index(uint32_t bit) { + for (int i = 0; i < 5; i++) if (bit == (1u << i)) return i; + return -1; +} + +static uint64_t fnv(const uint8_t *k, int n) { + uint64_t h = 1469598103934665603ull; + for (int i = 0; i < n; i++) { h ^= k[i]; h *= 1099511628211ull; } + return h; +} + +static int trace_of(const Node *nodes, uint32_t idx, WmOp *out) { + WmOp rev[WX_MAX_TRACE]; + int n = 0; + while (idx != 0 && n < WX_MAX_TRACE) { rev[n++] = nodes[idx].op; idx = nodes[idx].parent; } + for (int i = 0; i < n; i++) out[i] = rev[n - 1 - i]; + return n; +} + +int wx_explore(const WmProfile *p, WxResult *res) { + memset(res, 0, sizeof *res); + for (int i = 0; i < 5; i++) res->trace_len[i] = -1; + uint32_t cap = TABLE_SIZE / 2; + Node *nodes = calloc(cap, sizeof *nodes); + uint32_t *table = malloc(sizeof(uint32_t) * TABLE_SIZE); + if (!nodes || !table) { free(nodes); free(table); return -1; } + memset(table, 0xff, sizeof(uint32_t) * TABLE_SIZE); + uint32_t n = 0; + wm_init(&nodes[0].s); + nodes[0].klen = (uint8_t)wm_key(&nodes[0].s, nodes[0].key); + table[fnv(nodes[0].key, nodes[0].klen) & (TABLE_SIZE - 1)] = 0; + n = 1; + WmOp ops[16]; + int nops = wm_all_ops(ops); + for (uint32_t head = 0; head < n; head++) { + for (int o = 0; o < nops; o++) { + if (!wm_enabled(p, &nodes[head].s, ops[o])) continue; + WmState t = nodes[head].s; + uint32_t v = wm_step(p, &t, ops[o]); + res->transitions++; + uint8_t key[KEY_MAX]; + int kl = wm_key(&t, key); + uint64_t h = fnv(key, kl); + uint32_t slot = (uint32_t)(h & (TABLE_SIZE - 1)); + int found = 0; + while (table[slot] != UINT32_MAX) { + const Node *q = &nodes[table[slot]]; + if (q->klen == kl && memcmp(q->key, key, (size_t)kl) == 0) { found = 1; break; } + slot = (slot + 1) & (TABLE_SIZE - 1); + } + uint32_t at; + if (found) { + at = UINT32_MAX; + } else { + if (n >= cap) { res->truncated = 1; continue; } + at = n++; + nodes[at].s = t; + nodes[at].parent = head; + nodes[at].op = ops[o]; + memcpy(nodes[at].key, key, (size_t)kl); + nodes[at].klen = (uint8_t)kl; + table[slot] = at; + } + if (!v) continue; + res->viol_seen |= v; + for (int b = 0; b < 5; b++) { + if (!(v & (1u << b)) || res->trace_len[b] >= 0) continue; + /* Path to head, then this op. */ + int len = trace_of(nodes, head, res->trace[b]); + if (len < WX_MAX_TRACE) res->trace[b][len++] = ops[o]; + res->trace_len[b] = len; + } + (void)at; + } + } + res->states = n; + free(nodes); + free(table); + return 0; +} + +void wx_print_trace(const WmOp *t, int n) { + for (int i = 0; i < n; i++) { + char b[32]; + wm_op_str(t[i], b, sizeof b); + printf("%s%s", i ? " -> " : "", b); + } +} diff --git a/tests/model/world_explore.h b/tests/model/world_explore.h new file mode 100644 index 000000000..a0cc174a3 --- /dev/null +++ b/tests/model/world_explore.h @@ -0,0 +1,19 @@ +/* Exhaustive breadth-first exploration of the lifecycle model. */ +#ifndef WORLD_EXPLORE_H +#define WORLD_EXPLORE_H +#include "world_model.h" + +#define WX_MAX_TRACE 64 +typedef struct { + uint64_t states, transitions; + uint32_t viol_seen; /* OR of every violation bit */ + int trace_len[5]; /* shortest counterexample per bit */ + WmOp trace[5][WX_MAX_TRACE]; + int truncated; /* state table full: not exhaustive */ +} WxResult; + +/* Bit index 0..4 for V_* bits. */ +int wx_bit_index(uint32_t bit); +int wx_explore(const WmProfile *p, WxResult *res); +void wx_print_trace(const WmOp *t, int n); +#endif diff --git a/tests/model/world_model.c b/tests/model/world_model.c new file mode 100644 index 000000000..f2cc1df31 --- /dev/null +++ b/tests/model/world_model.c @@ -0,0 +1,290 @@ +/* + * world_model.c -- the lifecycle model (see world_model.h). + * + * Every AS_BUILT rule cites the rx_world.c function it mirrors, so a change + * there that the model does not follow shows up as a differential mismatch. + */ +#include "world_model.h" + +#include +#include + +const int wm_parent[WM_N] = { -1, WM_P, WM_P, WM_C1 }; +const uint32_t wm_mem[WM_N] = { 4, 4, 2, 2 }; +const uint32_t wm_deadline[WM_N] = { 1, 2, 0, 1 }; +const char *wm_name[WM_N] = { "P", "C1", "C2", "G" }; + +const WmProfile wm_spec = { "SPEC", CANCEL_TRANSITIVE, 1, 0, 0 }; +const WmProfile wm_as_built = { "AS_BUILT", CANCEL_NONE, 0, 0, 0 }; +const WmProfile wm_mut_leak = { "MUT_LEAK_ON_FAIL", CANCEL_TRANSITIVE, 1, 1, 0 }; +const WmProfile wm_mut_noprop = { "MUT_CANCEL_NO_PROPAGATE", CANCEL_TARGET_ONLY, 1, 0, 0 }; +const WmProfile wm_mut_double = { "MUT_COMMIT_KEEPS_ACTIVATION", CANCEL_TRANSITIVE, 1, 0, 1 }; +const WmProfile wm_mut_deadline = { "MUT_DEADLINE_ADMIT_ONLY", CANCEL_TRANSITIVE, 0, 0, 0 }; + +int wm_is_descendant(uint32_t d, uint32_t r) { + for (int a = wm_parent[d]; a >= 0; a = wm_parent[a]) + if ((uint32_t)a == r) return 1; + return 0; +} + +void wm_init(WmState *s) { memset(s, 0, sizeof *s); } + +/* res_fits */ +static int fits(const WmState *s, uint32_t r) { + if (s->used_slots >= WM_SLOTS) return 0; + if (s->used_mem > WM_MEM) return 0; + if (wm_mem[r] > WM_MEM - s->used_mem) return 0; + return 1; +} + +/* charge + enqueue; the harness waits until the worker is inside fn, so + * admitted == running here. */ +static void admit(WmState *s, uint32_t r) { + s->st[r] = WM_RUN; + s->used_slots++; + s->used_mem += wm_mem[r]; + s->in_flight++; + s->stale[r] = 0; + s->act_committed[r] = 0; + s->surfaced[r] = 0; + if (wm_deadline[r] && s->tick > wm_deadline[r]) { /* charge(): counted */ + s->overdue++; + s->surfaced[r] = 1; + } +} + +/* try_admit / pick_admit / best_waiting: one priority class, oldest + * fitting waiter first, until nothing fits. */ +static void try_admit(WmState *s) { + for (;;) { + int best = -1; + for (uint32_t r = 0; r < WM_N; r++) { + if (s->st[r] != WM_WAITING || !fits(s, r)) continue; + if (best < 0 || s->wait_seq[r] < s->wait_seq[best]) best = (int)r; + } + if (best < 0) return; + admit(s, (uint32_t)best); + } +} + +/* demand_inner (stability limits off, no fan-out limit). */ +static void demand(WmState *s, uint32_t r, int external) { + if (external) s->yield[r] = 0; + s->parked[r] = 0; + switch (s->st[r]) { + case WM_IDLE: + s->st[r] = WM_WAITING; + s->wait_seq[r] = ++s->seq; + try_admit(s); + break; + case WM_WAITING: + break; /* coalesced */ + default: + s->rearm[r] = 1; /* woken while running */ + break; + } +} + +/* others_busy */ +static int others_busy(const WmState *s, uint32_t self) { + for (uint32_t i = 0; i < WM_N; i++) + if (i != self && (s->st[i] == WM_WAITING || s->st[i] == WM_RUN)) return 1; + return 0; +} + +/* release_parked */ +static void release_parked(WmState *s) { + for (uint32_t i = 0; i < WM_N; i++) { + if (!s->parked[i]) continue; + if (s->yield[i] && others_busy(s, i)) continue; + s->parked[i] = 0; + s->yield[i] = 0; + demand(s, i, i == WM_P); + } +} + +/* arm_backoff */ +static uint8_t backoff(uint8_t y) { + uint32_t n = y ? y * 2u : 1u; + if (n > 8u) n = 8u; + return (uint8_t)n; +} + +static void uncharge(WmState *s, uint32_t r) { + if (s->used_slots) s->used_slots--; + s->used_mem = s->used_mem >= wm_mem[r] ? s->used_mem - wm_mem[r] : 0; +} + +/* end_activation_inner */ +static void end_activation(const WmProfile *p, WmState *s, uint32_t r, int failed) { + for (uint32_t i = 0; i < WM_N; i++) /* tick_parked */ + if (s->parked[i] && s->yield[i]) s->yield[i]--; + release_parked(s); + if (!(failed && p->mut_leak_on_fail)) uncharge(s, r); + s->st[r] = WM_IDLE; + if (s->in_flight) s->in_flight--; + if (s->rearm[r] && s->yield[r] && others_busy(s, r)) { + s->yield[r]--; + s->parked[r] = 1; + s->rearm[r] = 0; + try_admit(s); + } else if (s->rearm[r]) { + s->rearm[r] = 0; + demand(s, r, r == WM_P); + } else { + try_admit(s); + } + if (s->in_flight == 0) release_parked(s); +} + +/* A write to the object r's subscribers trigger on (finish_writes -> + * propagate): running subscribers now hold a stale snapshot. */ +static void write_and_wake(WmState *s, int writer) { + uint32_t kids[WM_N], nk = 0; + for (uint32_t c = 0; c < WM_N; c++) + if (wm_parent[c] == writer) kids[nk++] = c; + for (uint32_t i = 0; i < nk; i++) + if (s->st[kids[i]] == WM_RUN) s->stale[kids[i]] = 1; + for (uint32_t i = 0; i < nk; i++) demand(s, kids[i], writer < 0); +} + +static void cancel(const WmProfile *p, WmState *s, uint32_t r) { + if (p->cancel_mode == CANCEL_NONE) return; /* no entry point exists */ + for (uint32_t x = 0; x < WM_N; x++) { + if (x != r && !(p->cancel_mode == CANCEL_TRANSITIVE && wm_is_descendant(x, r))) + continue; + if (s->st[x] == WM_RUN) { + uncharge(s, x); + if (s->in_flight) s->in_flight--; + } + s->st[x] = WM_IDLE; + s->rearm[x] = s->parked[x] = s->yield[x] = s->stale[x] = 0; + s->cancels++; + } + try_admit(s); + if (s->in_flight == 0) release_parked(s); +} + +int wm_enabled(const WmProfile *p, const WmState *s, WmOp op) { + (void)p; + switch (op.kind) { + case OP_EXT: return s->ext < WM_EXT_MAX; + case OP_FIN: + case OP_FAIL: return op.r < WM_N && s->st[op.r] == WM_RUN; + case OP_TICK: return s->tick < WM_TICK_MAX; + case OP_CANCEL: return op.r == WM_P || op.r == WM_C1; + default: return 0; + } +} + +static uint32_t check(const WmState *s) { + uint32_t v = 0, n_run = 0, mem = 0; + for (uint32_t r = 0; r < WM_N; r++) + if (s->st[r] == WM_RUN) { n_run++; mem += wm_mem[r]; } + if (s->used_slots != n_run || s->used_mem != mem || + s->used_slots > WM_SLOTS || s->used_mem > WM_MEM) + v |= V_LEAK; + for (uint32_t r = 0; r < WM_N; r++) + if (s->st[r] == WM_RUN && wm_deadline[r] && s->tick > wm_deadline[r] && !s->surfaced[r]) + v |= V_DEADLINE; + return v; +} + +uint32_t wm_step(const WmProfile *p, WmState *s, WmOp op) { + s->viol = 0; + uint32_t r = op.r; + switch (op.kind) { + case OP_EXT: + s->ext++; + write_and_wake(s, -1); + break; + case OP_TICK: + s->tick++; + if (p->deadline_on_tick) + for (uint32_t i = 0; i < WM_N; i++) + if (s->st[i] == WM_RUN && wm_deadline[i] && s->tick > wm_deadline[i] && + !s->surfaced[i]) { + s->surfaced[i] = 1; + s->overdue++; + } + try_admit(s); /* rx_world_set_resources */ + break; + case OP_FAIL: /* fn < 0: FAILED, no back-off */ + s->failures++; + s->st[r] = WM_ENDING; + end_activation(p, s, r, 1); + break; + case OP_FIN: + if (s->stale[r]) { /* PUBLISHING -> INVALIDATED */ + s->invalidations++; + s->yield[r] = backoff(s->yield[r]); + s->rearm[r] = 1; + s->st[r] = WM_ENDING; + end_activation(p, s, r, 0); + break; + } + if (s->act_committed[r]) s->viol |= V_DOUBLE; + s->act_committed[r] = 1; + s->commits[r]++; + s->yield[r] = 0; /* note_value: progress, no flip */ + s->st[r] = WM_ENDING; + write_and_wake(s, (int)r); + if (p->mut_commit_keeps_act && !s->rearm[r]) { + s->st[r] = WM_RUN; /* activation never retired */ + break; + } + end_activation(p, s, r, 0); + break; + case OP_CANCEL: + cancel(p, s, r); + if (s->st[r] != WM_IDLE || s->rearm[r] || s->parked[r]) s->viol |= V_CANCEL_SELF; + for (uint32_t x = 0; x < WM_N; x++) + if (wm_is_descendant(x, r) && + (s->st[x] != WM_IDLE || s->rearm[x] || s->parked[x])) + s->viol |= V_CANCEL_CHILD; + break; + } + s->viol |= check(s); + return s->viol; +} + +int wm_key(const WmState *s, uint8_t *out) { + int n = 0; + for (uint32_t r = 0; r < WM_N; r++) { + uint32_t rank = 0; + if (s->st[r] == WM_WAITING) + for (uint32_t q = 0; q < WM_N; q++) + if (s->st[q] == WM_WAITING && s->wait_seq[q] <= s->wait_seq[r]) rank++; + out[n++] = s->st[r]; + out[n++] = s->rearm[r]; + out[n++] = s->stale[r]; + out[n++] = s->parked[r]; + out[n++] = s->yield[r]; + out[n++] = s->surfaced[r]; + out[n++] = s->act_committed[r]; + out[n++] = (uint8_t)rank; + } + out[n++] = s->ext; + out[n++] = s->tick; + out[n++] = s->used_slots; + out[n++] = (uint8_t)s->used_mem; + out[n++] = s->in_flight; + return n; +} + +void wm_op_str(WmOp op, char *buf, int n) { + static const char *k[] = { "EXT", "FIN", "FAIL", "TICK", "CANCEL" }; + if (op.kind == OP_EXT || op.kind == OP_TICK) snprintf(buf, (size_t)n, "%s", k[op.kind]); + else snprintf(buf, (size_t)n, "%s(%s)", k[op.kind], wm_name[op.r]); +} + +int wm_all_ops(WmOp *out) { + int n = 0; + out[n++] = (WmOp){ OP_EXT, 0 }; + out[n++] = (WmOp){ OP_TICK, 0 }; + for (uint8_t r = 0; r < WM_N; r++) out[n++] = (WmOp){ OP_FIN, r }; + for (uint8_t r = 0; r < WM_N; r++) out[n++] = (WmOp){ OP_FAIL, r }; + out[n++] = (WmOp){ OP_CANCEL, WM_P }; + out[n++] = (WmOp){ OP_CANCEL, WM_C1 }; + return n; +} diff --git a/tests/model/world_model.h b/tests/model/world_model.h new file mode 100644 index 000000000..a1d31c689 --- /dev/null +++ b/tests/model/world_model.h @@ -0,0 +1,96 @@ +/* + * world_model.h -- small explicit state machine of the rx_world activation + * lifecycle (hardening lane LG). + * + * wake -> admit (charge budget) -> run -> commit | invalidate | fail + * -> reclaim (uncharge) -> idle, plus cancel of a parent and its + * children. + * + * Four reactions in a fixed tree, written by the outside world into E: + * + * E --> P --> X --> C1 --> Y --> G + * \-> C2 --> Z + * + * The model has two roles: + * - SPEC: what the lifecycle should guarantee (cancel reaches every child, + * a deadline overrun is surfaced while the activation is still running). + * - AS_BUILT: what src/runtime/rx_world.c does today, step for step + * (admission order, re-arm, invalidation back-off, parking). This is the + * profile the differential harness compares against the real runtime. + * Mutants are SPEC with one realistic fault switched on; each must make the + * invariant it targets fail. + */ +#ifndef WORLD_MODEL_H +#define WORLD_MODEL_H + +#include + +#define WM_N 4u /* reactions: P, C1, C2, G */ +#define WM_P 0u +#define WM_C1 1u +#define WM_C2 2u +#define WM_G 3u +#define WM_SLOTS 2u /* admission slots in the budget */ +#define WM_MEM 8u /* memory budget */ +#define WM_EXT_MAX 3u /* outside publications per explored run */ +#define WM_TICK_MAX 3u /* logical clock bound */ + +/* Topology and needs (shared with the differential harness). */ +extern const int wm_parent[WM_N]; +extern const uint32_t wm_mem[WM_N]; +extern const uint32_t wm_deadline[WM_N]; /* 0 = none */ +extern const char *wm_name[WM_N]; + +enum { WM_IDLE = 0, WM_WAITING, WM_RUN, WM_ENDING }; + +enum { OP_EXT = 0, OP_FIN, OP_FAIL, OP_TICK, OP_CANCEL, OP_KINDS }; +typedef struct { uint8_t kind, r; } WmOp; + +/* Invariant violation bits. */ +#define V_LEAK 0x01u /* I1 budget held != budget of running work */ +#define V_CANCEL_CHILD 0x02u /* I2 cancel left a descendant in flight */ +#define V_DOUBLE 0x04u /* I3 one activation committed twice */ +#define V_DEADLINE 0x08u /* I4 running past its deadline, not surfaced */ +#define V_CANCEL_SELF 0x10u /* I2b cancel left the target itself in flight */ + +enum { CANCEL_NONE = 0, CANCEL_TRANSITIVE, CANCEL_TARGET_ONLY }; + +typedef struct { + const char *name; + int cancel_mode; + int deadline_on_tick; /* surface overrun when the clock passes it */ + int mut_leak_on_fail; /* failure path forgets to reclaim the budget */ + int mut_commit_keeps_act; /* commit path forgets to end the activation */ +} WmProfile; + +extern const WmProfile wm_spec, wm_as_built; +extern const WmProfile wm_mut_leak, wm_mut_noprop, wm_mut_double, wm_mut_deadline; + +/* Behaviour-relevant state (the dedup key is derived from it). */ +typedef struct { + uint8_t st[WM_N]; + uint8_t rearm[WM_N], stale[WM_N], parked[WM_N], yield[WM_N]; + uint8_t surfaced[WM_N], act_committed[WM_N]; + uint32_t wait_seq[WM_N]; + uint32_t seq; + uint8_t ext, tick; + uint8_t used_slots; + uint32_t used_mem; + uint8_t in_flight; + /* Observables, not part of the key. */ + uint32_t commits[WM_N], invalidations, failures, overdue, cancels; + uint32_t viol; /* violations raised by the last step */ +} WmState; + +void wm_init(WmState *s); +int wm_enabled(const WmProfile *p, const WmState *s, WmOp op); +/* Applies op, then checks every invariant; returns s->viol. */ +uint32_t wm_step(const WmProfile *p, WmState *s, WmOp op); +/* Canonical key bytes (wait order normalised); returns length. */ +int wm_key(const WmState *s, uint8_t *out); +int wm_is_descendant(uint32_t d, uint32_t r); +void wm_op_str(WmOp op, char *buf, int n); +/* All candidate ops in a fixed order; returns count. */ +int wm_all_ops(WmOp *out); + +#endif ```