diff --git a/Makefile b/Makefile index 0e28b3f9a..639aa816f 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ LEARNER_OBJS = $(addprefix $(OUT_DIR)/,$(addsuffix .o,$(LEARNER_CORE))) \ $(patsubst src/crumbline/%.c,$(OUT_DIR)/crumbline/%.o,$(CL_SRCS)) $(OUT_DIR)/crumbline_learner.o LEARNER = $(OUT_DIR)/crumbline-learner -.PHONY: all clean check-physics-lock crumbline-learner test-crumbline test-m19 test test-m5 test-m6 test-m7 test-m8 test-m9 test-m10 test-m11 test-m12 test-m13 test-m14 test-m15 test-m17 +.PHONY: all clean check-physics-lock crumbline-learner test-crumbline test-m19 test test-m5 test-m6 test-m7 test-m8 test-m9 test-m10 test-m11 test-m12 test-m13 test-m14 test-m15 test-m17 test-r3 all: $(TARGET) @@ -152,3 +152,15 @@ clean: test-m19: $(TARGET) ./$(TARGET) --run-m19-gates + +# Resident reaction runtime heartbeat (ADR 0016, R3/R4 host reference). +# CPU only; links no PHYSICS/NVRM code (omega_evidence.c needs only the header). +RX_SRCS = src/runtime/rx_caproot.c src/runtime/rx_world.c src/sha256.c src/omega_evidence.c \ + tests/runtime/rx_heartbeat_test.c +RX_TEST = $(OUT_DIR)/rx_heartbeat_test + +$(RX_TEST): $(RX_SRCS) src/runtime/rx_caproot.h src/runtime/rx_world.h | $(OUT_DIR) + $(CC) $(CFLAGS) -pthread -o $@ $(RX_SRCS) + +test-r3: $(RX_TEST) + ./$(RX_TEST) diff --git a/evidence/R3/ef3e5565b9deda5226b58caf00c3e05f467cf03f6ae91984c10898d98e28c321.json b/evidence/R3/ef3e5565b9deda5226b58caf00c3e05f467cf03f6ae91984c10898d98e28c321.json new file mode 100644 index 000000000..a3fabc8b1 --- /dev/null +++ b/evidence/R3/ef3e5565b9deda5226b58caf00c3e05f467cf03f6ae91984c10898d98e28c321.json @@ -0,0 +1,52 @@ +{ + "schema": "AIEN_RX_HEARTBEAT_RECEIPT_V1", + "adr": "aien-architecture ADR 0016", + "run_id": "20260927T172541Z-9dd959455910", + "timestamp_utc": "2026-09-27T17:25:41Z", + "candidate_commit": "9dd959455910dbf5b86434a433461c091be39119", + "candidate_bound": true, + "run_commit": "9dd959455910dbf5b86434a433461c091be39119", + "tree_dirty": false, + "test_binary_sha256": "a8361352231f606f220d951c5e4053557cb286a5d477abaefb576f27b5e63f89", + "host": {"sysname": "Linux", "release": "7.0.0-1019-nvidia", "machine": "aarch64"}, + "hardware_scope": "host CPU only; no accelerator involved", + "gates": { + "R3_REACTION_CORE": "PASS (host reference)", + "R4_CAUSAL_TRACE": "PASS (host reference; every reaction crumb in every test audited)", + "not_claimed": ["R1 canonical shared pool (unify with OMEGA_SHARED_WORLD_V1)", "R2", "R5", "R6", "R7 native capability root", "R8", "R9", "R10-R16"] + }, + "tests": [ + {"name": "heartbeat_chain", "invariants": "I3,I4,I6,I7", "checks": 37, "failures": 0}, + {"name": "single_dependency_field_granularity", "invariants": "I7", "checks": 33, "failures": 0}, + {"name": "multiple_dependency_fan_in_two_triggers", "invariants": "I6,I7", "checks": 31, "failures": 0}, + {"name": "fan_out_64", "invariants": "I6,I7", "checks": 396, "failures": 0}, + {"name": "fan_in_8", "invariants": "I6,I7", "checks": 23, "failures": 0}, + {"name": "invalidation_stale_snapshot", "invariants": "I2,I6,I7", "checks": 26, "failures": 0}, + {"name": "concurrent_publication_no_torn_no_lost", "invariants": "I6,I7", "checks": 2685, "failures": 0}, + {"name": "stale_generation_rejected", "invariants": "I2,I7", "checks": 29, "failures": 0}, + {"name": "write_outside_declared_set_rejected", "invariants": "I6,I9", "checks": 27, "failures": 0}, + {"name": "duplicate_wake_coalesced", "invariants": "I7,I13", "checks": 29, "failures": 0}, + {"name": "capability_attacks_all_fail", "invariants": "I3,I4,I9", "checks": 143, "failures": 0}, + {"name": "revocation_during_run_rejected", "invariants": "I4,I7", "checks": 19, "failures": 0}, + {"name": "capability_table_unforgeable_by_runtime", "invariants": "I3", "checks": 8, "failures": 0}, + {"name": "causal_record_tamper_detected", "invariants": "I7,I15", "checks": 27, "failures": 0}, + {"name": "schedule_independent_result", "invariants": "I16", "checks": 5435, "failures": 0} + ], + "totals": {"tests": 15, "tests_passed": 15, "checks": 8948, "failures": 0}, + "causal": {"crumbs_digest_verified": 7016, "reaction_crumbs_audited": 1727}, + "lifecycle": {"illegal_transitions": 0, "observed": [ + {"from": "DORMANT", "to": "READY", "count": 1727}, + {"from": "READY", "to": "BLOCKED_AUTHORITY", "count": 28}, + {"from": "READY", "to": "RUNNING", "count": 1698}, + {"from": "READY", "to": "INVALIDATED", "count": 1}, + {"from": "BLOCKED_AUTHORITY", "to": "DORMANT", "count": 28}, + {"from": "RUNNING", "to": "PUBLISHING", "count": 1698}, + {"from": "PUBLISHING", "to": "COMMITTED", "count": 1361}, + {"from": "PUBLISHING", "to": "INVALIDATED", "count": 333}, + {"from": "PUBLISHING", "to": "REJECTED", "count": 4}, + {"from": "COMMITTED", "to": "DORMANT", "count": 1361}, + {"from": "INVALIDATED", "to": "DORMANT", "count": 334}, + {"from": "REJECTED", "to": "DORMANT", "count": 4} + ]}, + "heartbeat_trace": [{"crumb":5,"kind":"EXTERNAL","digest16":"db40ec1202f938c7"},{"crumb":6,"kind":"COMMIT","reaction":"aien.hypothesis","wake_cause":5,"digest16":"92d990c9f03e803d"},{"crumb":8,"kind":"COMMIT","reaction":"omega.realize","wake_cause":6,"digest16":"c59e4e82398a05f4"}] +} diff --git a/src/runtime/rx_caproot.c b/src/runtime/rx_caproot.c new file mode 100644 index 000000000..c93a2c4cd --- /dev/null +++ b/src/runtime/rx_caproot.c @@ -0,0 +1,378 @@ +/* + * rx_caproot.c -- host reference capability root. See rx_caproot.h. + */ +#include "rx_caproot.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef F_SEAL_FUTURE_WRITE +#define F_SEAL_FUTURE_WRITE 0x0010 +#endif + +enum { + RX_OP_MINT = 1, + RX_OP_REVOKE, + RX_OP_RECLAIM, + RX_OP_CLOCK, + RX_OP_EPOCH, + RX_OP_SHUTDOWN, +}; + +typedef struct { + uint32_t op; + uint32_t pad; + RxCapMint mint; + RxCapRef ref; + uint64_t arg; +} RxCapRequest; + +typedef struct { + int32_t status; + uint32_t pad; + RxCapRef ref; +} RxCapReply; + +/* ---- root process (the only writer) ------------------------------------ */ + +static void root_begin(RxCapTable *t) { + atomic_fetch_add_explicit(&t->seq, 1, memory_order_acq_rel); + atomic_thread_fence(memory_order_release); +} + +static void root_end(RxCapTable *t) { + atomic_thread_fence(memory_order_release); + atomic_fetch_add_explicit(&t->seq, 1, memory_order_acq_rel); +} + +/* Chain validation used by both sides; `t` must be a stable view. */ +static int chain_ok(const RxCapTable *t, const RxCapEntry *e) { + uint32_t depth = 0; + while (e->parent_id != UINT32_MAX) { + if (++depth > RX_CAP_MAX_DEPTH) return RX_CAP_ERR_CHAIN; + if (e->parent_id >= t->capacity) return RX_CAP_ERR_CHAIN; + const RxCapEntry *p = &t->entries[e->parent_id]; + if (p->generation != e->parent_generation) return RX_CAP_ERR_CHAIN; + if (p->state != RX_CAP_LIVE) return RX_CAP_ERR_CHAIN; + e = p; + } + return RX_CAP_OK; +} + +static int root_mint(RxCapTable *t, const RxCapMint *m, RxCapRef *out) { + uint64_t epoch = atomic_load_explicit(&t->epoch, memory_order_relaxed); + uint64_t clock = atomic_load_explicit(&t->clock, memory_order_relaxed); + if (m->rights == 0) return RX_CAP_ERR_RIGHTS; + if (m->parent.cap_id != UINT32_MAX) { + if (m->parent.cap_id >= t->capacity) return RX_CAP_ERR_BOUNDS; + const RxCapEntry *p = &t->entries[m->parent.cap_id]; + if (p->generation != m->parent.generation) return RX_CAP_ERR_STALE_GEN; + if (p->state != RX_CAP_LIVE) return RX_CAP_ERR_REVOKED; + if (p->epoch != epoch) return RX_CAP_ERR_EPOCH; + if (p->lease_expiry && clock >= p->lease_expiry) return RX_CAP_ERR_EXPIRED; + if (chain_ok(t, p) != RX_CAP_OK) return RX_CAP_ERR_CHAIN; + if (!(p->rights & RX_RIGHT_DELEGATE)) return RX_CAP_ERR_NOT_DELEGABLE; + if (p->resource != m->resource) return RX_CAP_ERR_RESOURCE; + if ((m->rights & ~p->rights) != 0) return RX_CAP_ERR_AMPLIFY; + if (p->lease_expiry && + (m->lease_ticks == 0 || clock + m->lease_ticks > p->lease_expiry)) + return RX_CAP_ERR_AMPLIFY; /* a child may not outlive its parent */ + } + for (uint32_t i = 0; i < t->capacity; i++) { + RxCapEntry *e = &t->entries[i]; + if (e->state != RX_CAP_FREE) continue; + root_begin(t); + e->state = RX_CAP_LIVE; + e->issuer = m->issuer; + e->subject = m->subject; + e->resource = m->resource; + e->rights = m->rights; + e->epoch = epoch; + e->lease_expiry = m->lease_ticks ? clock + m->lease_ticks : 0; + e->parent_id = m->parent.cap_id; + e->parent_generation = m->parent.cap_id == UINT32_MAX ? 0 : m->parent.generation; + root_end(t); + out->cap_id = e->cap_id; + out->generation = e->generation; + return RX_CAP_OK; + } + return RX_CAP_ERR_FULL; +} + +static int root_revoke(RxCapTable *t, RxCapRef r) { + if (r.cap_id >= t->capacity) return RX_CAP_ERR_BOUNDS; + RxCapEntry *e = &t->entries[r.cap_id]; + if (e->generation != r.generation) return RX_CAP_ERR_STALE_GEN; + if (e->state != RX_CAP_LIVE) return RX_CAP_ERR_STATE; + root_begin(t); + e->state = RX_CAP_REVOKED; + root_end(t); + return RX_CAP_OK; +} + +static int root_reclaim(RxCapTable *t, uint32_t id) { + if (id >= t->capacity) return RX_CAP_ERR_BOUNDS; + RxCapEntry *e = &t->entries[id]; + if (e->state != RX_CAP_REVOKED) return RX_CAP_ERR_STATE; + root_begin(t); + e->generation++; + e->state = RX_CAP_FREE; + root_end(t); + return RX_CAP_OK; +} + +static int read_full(int fd, void *buf, size_t n) { + uint8_t *p = buf; + while (n) { + ssize_t r = read(fd, p, n); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) return -1; + p += r; + n -= (size_t)r; + } + return 0; +} + +static int write_full(int fd, const void *buf, size_t n) { + const uint8_t *p = buf; + while (n) { + ssize_t r = write(fd, p, n); + if (r < 0 && errno == EINTR) continue; + if (r <= 0) return -1; + p += r; + n -= (size_t)r; + } + return 0; +} + +static void root_main(int memfd, int sock) { + /* Non-dumpable: the parent (same uid) may not ptrace this process or open + * its /proc fds, so the writable mapping stays private to the root. */ + prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); + prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); + RxCapTable *t = mmap(NULL, sizeof(RxCapTable), PROT_READ | PROT_WRITE, + MAP_SHARED, memfd, 0); + close(memfd); + if (t == MAP_FAILED) _exit(2); + memset(t, 0, sizeof(*t)); + t->magic = RX_CAP_TABLE_MAGIC; + t->capacity = RX_CAP_MAX; + atomic_store(&t->epoch, 1); + for (uint32_t i = 0; i < RX_CAP_MAX; i++) { + t->entries[i].cap_id = i; + t->entries[i].generation = 1; + t->entries[i].state = RX_CAP_FREE; + t->entries[i].parent_id = UINT32_MAX; + } + uint8_t ready = 1; + if (write_full(sock, &ready, 1) != 0) _exit(3); + + RxCapRequest q; + while (read_full(sock, &q, sizeof(q)) == 0) { + RxCapReply r; + memset(&r, 0, sizeof(r)); + switch (q.op) { + case RX_OP_MINT: r.status = root_mint(t, &q.mint, &r.ref); break; + case RX_OP_REVOKE: r.status = root_revoke(t, q.ref); break; + case RX_OP_RECLAIM: r.status = root_reclaim(t, q.ref.cap_id); break; + case RX_OP_CLOCK: + root_begin(t); + atomic_fetch_add(&t->clock, q.arg); + root_end(t); + break; + case RX_OP_EPOCH: + root_begin(t); + atomic_fetch_add(&t->epoch, 1); + root_end(t); + break; + case RX_OP_SHUTDOWN: + write_full(sock, &r, sizeof(r)); + _exit(0); + default: r.status = RX_CAP_ERR_STATE; break; + } + if (write_full(sock, &r, sizeof(r)) != 0) break; + } + _exit(0); +} + +/* ---- runtime side ------------------------------------------------------- */ + +int rx_caproot_start(RxCapRoot *root) { + memset(root, 0, sizeof(*root)); + root->ctl_fd = root->ro_fd = -1; + int memfd = memfd_create("aien-capability-root", MFD_ALLOW_SEALING | MFD_CLOEXEC); + if (memfd < 0) return RX_CAP_ERR_IO; + if (ftruncate(memfd, sizeof(RxCapTable)) != 0) { close(memfd); return RX_CAP_ERR_IO; } + int sv[2]; + if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) != 0) { + close(memfd); + return RX_CAP_ERR_IO; + } + pid_t pid = fork(); + if (pid < 0) { close(memfd); close(sv[0]); close(sv[1]); return RX_CAP_ERR_IO; } + if (pid == 0) { + close(sv[0]); + root_main(memfd, sv[1]); + } + close(sv[1]); + uint8_t ready = 0; + if (read_full(sv[0], &ready, 1) != 0 || ready != 1) goto fail; + /* The root holds the only writable mapping. Seal the inode so nothing else + * can ever obtain one, then map it read-only for this process. */ + if (fcntl(memfd, F_ADD_SEALS, + F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_FUTURE_WRITE | F_SEAL_SEAL) != 0) + goto fail; + const RxCapTable *t = mmap(NULL, sizeof(RxCapTable), PROT_READ, MAP_SHARED, memfd, 0); + if (t == MAP_FAILED) goto fail; + if (t->magic != RX_CAP_TABLE_MAGIC) { munmap((void *)t, sizeof(RxCapTable)); goto fail; } + root->table = t; + root->ctl_fd = sv[0]; + root->ro_fd = memfd; + root->root_pid = pid; + root->running = true; + return RX_CAP_OK; +fail: + kill(pid, SIGKILL); + waitpid(pid, NULL, 0); + close(memfd); + close(sv[0]); + return RX_CAP_ERR_IO; +} + +static int request(RxCapRoot *root, RxCapRequest *q, RxCapReply *r) { + if (!root->running) return RX_CAP_ERR_IO; + if (write_full(root->ctl_fd, q, sizeof(*q)) != 0) return RX_CAP_ERR_IO; + if (read_full(root->ctl_fd, r, sizeof(*r)) != 0) return RX_CAP_ERR_IO; + return r->status; +} + +void rx_caproot_stop(RxCapRoot *root) { + if (!root->running) return; + RxCapRequest q = { .op = RX_OP_SHUTDOWN }; + RxCapReply r; + request(root, &q, &r); + waitpid(root->root_pid, NULL, 0); + munmap((void *)root->table, sizeof(RxCapTable)); + close(root->ctl_fd); + close(root->ro_fd); + root->running = false; +} + +int rx_caproot_mint(RxCapRoot *root, const RxCapMint *req, RxCapRef *out) { + RxCapRequest q; + memset(&q, 0, sizeof(q)); + q.op = RX_OP_MINT; + q.mint = *req; + RxCapReply r; + int rc = request(root, &q, &r); + if (rc == RX_CAP_OK && out) *out = r.ref; + return rc; +} + +int rx_caproot_revoke(RxCapRoot *root, RxCapRef ref) { + RxCapRequest q; + memset(&q, 0, sizeof(q)); + q.op = RX_OP_REVOKE; + q.ref = ref; + RxCapReply r; + return request(root, &q, &r); +} + +int rx_caproot_reclaim(RxCapRoot *root, uint32_t cap_id) { + RxCapRequest q; + memset(&q, 0, sizeof(q)); + q.op = RX_OP_RECLAIM; + q.ref.cap_id = cap_id; + RxCapReply r; + return request(root, &q, &r); +} + +int rx_caproot_advance_clock(RxCapRoot *root, uint64_t ticks) { + RxCapRequest q; + memset(&q, 0, sizeof(q)); + q.op = RX_OP_CLOCK; + q.arg = ticks; + RxCapReply r; + return request(root, &q, &r); +} + +int rx_caproot_bump_epoch(RxCapRoot *root) { + RxCapRequest q; + memset(&q, 0, sizeof(q)); + q.op = RX_OP_EPOCH; + RxCapReply r; + return request(root, &q, &r); +} + +int rx_caproot_validate(const RxCapRoot *root, RxCapRef ref, + uint32_t subject, uint64_t resource, uint32_t rights, + RxCapEntry *out_entry) { + const RxCapTable *t = root->table; + if (!t || ref.cap_id >= RX_CAP_MAX) return RX_CAP_ERR_BOUNDS; + for (;;) { + uint64_t s0 = atomic_load_explicit(&t->seq, memory_order_acquire); + if (s0 & 1u) continue; + /* Copy the chain we need into a private view, then check the seqlock. */ + RxCapEntry chain[RX_CAP_MAX_DEPTH + 1]; + uint32_t n = 0; + uint32_t id = ref.cap_id; + int rc = RX_CAP_OK; + while (id != UINT32_MAX) { + if (n > RX_CAP_MAX_DEPTH || id >= RX_CAP_MAX) { rc = RX_CAP_ERR_CHAIN; break; } + memcpy(&chain[n], (const void *)&t->entries[id], sizeof(RxCapEntry)); + id = chain[n].parent_id; + n++; + } + uint64_t epoch = atomic_load_explicit(&t->epoch, memory_order_relaxed); + uint64_t clock = atomic_load_explicit(&t->clock, memory_order_relaxed); + atomic_thread_fence(memory_order_acquire); + if (atomic_load_explicit(&t->seq, memory_order_relaxed) != s0) continue; + if (rc != RX_CAP_OK) return rc; + + const RxCapEntry *e = &chain[0]; + if (e->generation != ref.generation) return RX_CAP_ERR_STALE_GEN; + if (e->state != RX_CAP_LIVE) return RX_CAP_ERR_REVOKED; + if (e->epoch != epoch) return RX_CAP_ERR_EPOCH; + if (e->lease_expiry && clock >= e->lease_expiry) return RX_CAP_ERR_EXPIRED; + for (uint32_t i = 1; i < n; i++) { + if (chain[i].generation != chain[i - 1].parent_generation) return RX_CAP_ERR_CHAIN; + if (chain[i].state != RX_CAP_LIVE) return RX_CAP_ERR_CHAIN; + if (chain[i].epoch != epoch) return RX_CAP_ERR_CHAIN; + if (chain[i].lease_expiry && clock >= chain[i].lease_expiry) return RX_CAP_ERR_CHAIN; + } + if (e->subject != subject) return RX_CAP_ERR_SUBJECT; + if (e->resource != resource) return RX_CAP_ERR_RESOURCE; + if ((e->rights & rights) != rights) return RX_CAP_ERR_RIGHTS; + if (out_entry) *out_entry = *e; + return RX_CAP_OK; + } +} + +const char *rx_cap_strerror(int code) { + switch (code) { + case RX_CAP_OK: return "ok"; + case RX_CAP_ERR_BOUNDS: return "bounds"; + case RX_CAP_ERR_STALE_GEN: return "stale-generation"; + case RX_CAP_ERR_REVOKED: return "revoked"; + case RX_CAP_ERR_EPOCH: return "epoch"; + case RX_CAP_ERR_SUBJECT: return "wrong-subject"; + case RX_CAP_ERR_RESOURCE: return "wrong-resource"; + case RX_CAP_ERR_RIGHTS: return "insufficient-rights"; + case RX_CAP_ERR_EXPIRED: return "lease-expired"; + case RX_CAP_ERR_CHAIN: return "delegation-chain-invalid"; + case RX_CAP_ERR_AMPLIFY: return "rights-amplification"; + case RX_CAP_ERR_NOT_DELEGABLE: return "not-delegable"; + case RX_CAP_ERR_FULL: return "table-full"; + case RX_CAP_ERR_IO: return "root-io"; + case RX_CAP_ERR_STATE: return "bad-state"; + default: return "unknown"; + } +} diff --git a/src/runtime/rx_caproot.h b/src/runtime/rx_caproot.h new file mode 100644 index 000000000..60e2bffa2 --- /dev/null +++ b/src/runtime/rx_caproot.h @@ -0,0 +1,138 @@ +/* + * rx_caproot.h -- host reference capability root for the resident reaction + * runtime (ADR 0016, Part II §3; gate R7 is NOT claimed by this file). + * + * The rule: the shared world may hold references to capabilities, it may + * never invent them. Here that rule is enforced by the operating system, not by + * convention: + * + * - The capability table lives in a sealed memfd. The only writable mapping + * belongs to a separate, non-dumpable root process (the mint). + * - The reaction runtime receives a read-only mapping. The memfd carries + * F_SEAL_FUTURE_WRITE | F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL, so no + * new writable mapping, write(2), or resize can be obtained from any fd. + * - Minting, delegation (attenuation only), revocation, slot reclaim, lease + * clock and epoch changes are requests over a socket; the root enforces + * every rule and the runtime only observes the result. + * + * A capability binds: id, slot generation, issuer, subject, resource, rights, + * epoch, lease expiry, parent (delegation), delegable flag, revocation state. + * A CapabilityRef in the world is only {cap_id, generation}; validation reads + * the root's table, so a forged, stale, revoked, expired, wrong-subject, + * wrong-resource or amplified reference fails. + * + * Scope: this is the Linux-hosted development root. On AIENOS the kernel + * capability authority is the root (ADR 0014); authenticating WHICH principal + * may ask for a fresh mint (AEGIS policy identity) is R7/R8 work. + */ +#ifndef RX_CAPROOT_H +#define RX_CAPROOT_H + +#include +#include +#include +#include + +#define RX_CAP_MAX 256u +#define RX_CAP_MAX_DEPTH 8u +#define RX_CAP_TABLE_MAGIC 0x50414358u /* 'XCAP' LE */ + +/* Rights */ +#define RX_RIGHT_READ 0x1u +#define RX_RIGHT_WRITE 0x2u +#define RX_RIGHT_EFFECT 0x4u +#define RX_RIGHT_DELEGATE 0x8u + +/* Slot state */ +#define RX_CAP_FREE 0u +#define RX_CAP_LIVE 1u +#define RX_CAP_REVOKED 2u + +/* Validation / request results */ +#define RX_CAP_OK 0 +#define RX_CAP_ERR_BOUNDS -1 +#define RX_CAP_ERR_STALE_GEN -2 +#define RX_CAP_ERR_REVOKED -3 +#define RX_CAP_ERR_EPOCH -4 +#define RX_CAP_ERR_SUBJECT -5 +#define RX_CAP_ERR_RESOURCE -6 +#define RX_CAP_ERR_RIGHTS -7 +#define RX_CAP_ERR_EXPIRED -8 +#define RX_CAP_ERR_CHAIN -9 +#define RX_CAP_ERR_AMPLIFY -10 +#define RX_CAP_ERR_NOT_DELEGABLE -11 +#define RX_CAP_ERR_FULL -12 +#define RX_CAP_ERR_IO -13 +#define RX_CAP_ERR_STATE -14 + +typedef struct { + uint32_t cap_id; + uint32_t generation; +} RxCapRef; + +typedef struct { + uint32_t cap_id; + uint32_t generation; + uint32_t state; + uint32_t issuer; + uint32_t subject; + uint32_t rights; + uint64_t resource; + uint64_t epoch; + uint64_t lease_expiry; /* logical clock tick; 0 = no lease */ + uint32_t parent_id; /* UINT32_MAX = root-issued */ + uint32_t parent_generation; +} RxCapEntry; + +/* Shared table. Written only by the root process under a seqlock. */ +typedef struct { + uint32_t magic; + uint32_t capacity; + _Atomic uint64_t seq; /* odd while the root is writing */ + _Atomic uint64_t epoch; + _Atomic uint64_t clock; + RxCapEntry entries[RX_CAP_MAX]; +} RxCapTable; + +/* Handle held by the runtime process. */ +typedef struct { + const RxCapTable *table; /* read-only mapping */ + int ctl_fd; /* request socket to the root */ + int ro_fd; /* sealed memfd, kept for attack tests */ + pid_t root_pid; + bool running; +} RxCapRoot; + +/* Mint request. parent.cap_id == UINT32_MAX means a root-issued capability + * (AEGIS policy decision); otherwise it is a delegation that may only + * attenuate rights and must keep the parent's resource. */ +typedef struct { + uint32_t issuer; + uint32_t subject; + uint64_t resource; + uint32_t rights; + uint64_t lease_ticks; /* 0 = no lease */ + RxCapRef parent; +} RxCapMint; + +int rx_caproot_start(RxCapRoot *root); +void rx_caproot_stop(RxCapRoot *root); + +int rx_caproot_mint(RxCapRoot *root, const RxCapMint *req, RxCapRef *out); +int rx_caproot_revoke(RxCapRoot *root, RxCapRef ref); +/* Return a revoked slot to the free pool; its generation advances, so every + * outstanding reference to the old occupant becomes stale. */ +int rx_caproot_reclaim(RxCapRoot *root, uint32_t cap_id); +int rx_caproot_advance_clock(RxCapRoot *root, uint64_t ticks); +int rx_caproot_bump_epoch(RxCapRoot *root); + +/* Validate a reference for (subject, resource, rights). Reads the root table + * with a seqlock and walks the delegation chain; any revoked ancestor fails. + * On success, *out_entry (optional) receives the entry snapshot. */ +int rx_caproot_validate(const RxCapRoot *root, RxCapRef ref, + uint32_t subject, uint64_t resource, uint32_t rights, + RxCapEntry *out_entry); + +const char *rx_cap_strerror(int code); + +#endif /* RX_CAPROOT_H */ diff --git a/src/runtime/rx_world.c b/src/runtime/rx_world.c new file mode 100644 index 000000000..9665d331e --- /dev/null +++ b/src/runtime/rx_world.c @@ -0,0 +1,783 @@ +/* + * rx_world.c -- resident reaction runtime, simple human reference. See rx_world.h. + */ +#include "rx_world.h" +#include "sha256.h" + +#include +#include +#include +#include + +/* ---- helpers ------------------------------------------------------------ */ + +static uint64_t now_ns(void) { + struct timespec ts; + clock_gettime(CLOCK_MONOTONIC, &ts); + return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; +} + +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 void object_digest(RxObject *o) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_RX_OBJECT_V1", 17); + put32(&c, o->type); + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) put64(&c, o->field[f]); + sha256_final(&c, o->digest); +} + +/* ---- lifecycle ---------------------------------------------------------- */ + +bool rx_state_transition_legal(RxState from, RxState to) { + switch (from) { + case RX_DORMANT: + return to == RX_READY; + case RX_READY: + return to == RX_RUNNING || to == RX_BLOCKED_AUTHORITY || + to == RX_BLOCKED_RESOURCE || to == RX_INVALIDATED; + case RX_RUNNING: + return to == RX_PUBLISHING || to == RX_FAILED || to == RX_CANCELLED || + to == RX_INVALIDATED; + case RX_PUBLISHING: + /* Stale input is detected while validating the publication, so the + * explicit exit is PUBLISHING -> INVALIDATED. */ + return to == RX_COMMITTED || to == RX_CONFLICT || to == RX_REJECTED || + to == RX_INVALIDATED; + case RX_COMMITTED: case RX_INVALIDATED: case RX_FAILED: case RX_CANCELLED: + case RX_CONFLICT: case RX_REJECTED: case RX_BLOCKED_AUTHORITY: case RX_BLOCKED_RESOURCE: + return to == RX_DORMANT; + default: + return false; + } +} + +const char *rx_state_name(RxState s) { + static const char *names[RX_STATE_COUNT] = { + "DORMANT", "READY", "BLOCKED_AUTHORITY", "BLOCKED_RESOURCE", "RUNNING", + "PUBLISHING", "COMMITTED", "INVALIDATED", "FAILED", "CANCELLED", "CONFLICT", + "REJECTED" + }; + return (unsigned)s < RX_STATE_COUNT ? names[s] : "?"; +} + +const char *rx_crumb_kind_name(RxCrumbKind k) { + switch (k) { + case RX_CRUMB_CREATE: return "CREATE"; + case RX_CRUMB_EXTERNAL: return "EXTERNAL"; + case RX_CRUMB_COMMIT: return "COMMIT"; + case RX_CRUMB_INVALIDATED: return "INVALIDATED"; + case RX_CRUMB_BLOCKED_AUTHORITY: return "BLOCKED_AUTHORITY"; + case RX_CRUMB_REJECTED: return "REJECTED"; + case RX_CRUMB_FAILED: return "FAILED"; + case RX_CRUMB_NOOP: return "NOOP"; + case RX_CRUMB_RETIRE: return "RETIRE"; + default: return "?"; + } +} + +static void set_state(RxWorld *w, RxReaction *r, RxState to) { + if (!rx_state_transition_legal(r->state, to)) w->stats.illegal_transitions++; + w->stats.transitions[r->state][to]++; + r->state = to; +} + +/* ---- causal crumbs ------------------------------------------------------ */ + +static void crumb_hash(const RxWorld *w, const RxCrumb *k, uint8_t out[32]) { + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_RX_CAUSAL_V1", 17); + put64(&c, k->id); + put32(&c, (uint32_t)k->kind); + put32(&c, k->reaction); + put32(&c, k->faculty); + put64(&c, k->wake_cause); + put64(&c, k->coalesced_wakes); + put32(&c, k->n_inputs); + for (uint32_t i = 0; i < k->n_inputs; i++) { + put32(&c, k->inputs[i].obj.id); + put32(&c, k->inputs[i].obj.generation); + put64(&c, k->inputs[i].version); + put64(&c, k->inputs[i].mask); + } + put32(&c, k->n_caps); + for (uint32_t i = 0; i < k->n_caps; i++) { + put32(&c, k->caps[i].cap_id); + put32(&c, k->caps[i].generation); + } + put32(&c, k->n_outputs); + for (uint32_t i = 0; i < k->n_outputs; i++) { + put32(&c, k->outputs[i].obj.id); + put32(&c, k->outputs[i].obj.generation); + put64(&c, k->outputs[i].version); + put64(&c, k->outputs[i].mask); + } + put32(&c, (uint32_t)k->reason); + put32(&c, k->n_parents); + for (uint32_t i = 0; i < k->n_parents; i++) { + uint64_t p = k->parents[i]; + put64(&c, p); + /* Parents always precede children, so their digests are final. */ + if (p >= 1 && p <= w->n_crumbs && p < k->id) + sha256_update(&c, w->crumbs[p - 1].digest, 32); + } + /* Timing and worker placement are recorded but are not identity: the + * same causal history must hash the same on any schedule. */ + sha256_final(&c, out); +} + +static void add_parent(RxCrumb *k, uint64_t p) { + if (p == 0) return; + for (uint32_t i = 0; i < k->n_parents; i++) + if (k->parents[i] == p) return; + if (k->n_parents < RX_MAX_PARENTS) k->parents[k->n_parents++] = p; +} + +/* Append a crumb; returns its id (0 if the log is full). Caller holds mu. */ +static uint64_t crumb_append(RxWorld *w, RxCrumb *k) { + if (w->n_crumbs >= w->crumb_cap) { + w->stats.crumb_overflow++; + return 0; + } + k->id = w->n_crumbs + 1; + /* Canonical parent order: ascending. */ + for (uint32_t i = 1; i < k->n_parents; i++) { + uint64_t v = k->parents[i]; + uint32_t j = i; + while (j > 0 && k->parents[j - 1] > v) { k->parents[j] = k->parents[j - 1]; j--; } + k->parents[j] = v; + } + crumb_hash(w, k, k->digest); + w->crumbs[w->n_crumbs++] = *k; + return k->id; +} + +const RxCrumb *rx_world_crumb(const RxWorld *w, uint64_t id) { + if (id == 0 || id > w->n_crumbs) return NULL; + return &w->crumbs[id - 1]; +} + +int rx_world_verify_crumbs(RxWorld *w, uint64_t *out_checked) { + pthread_mutex_lock(&w->mu); + int rc = 0; + uint64_t n = 0; + for (uint64_t i = 0; i < w->n_crumbs; i++) { + const RxCrumb *k = &w->crumbs[i]; + uint8_t d[32]; + if (k->id != i + 1) { rc = -1; break; } + for (uint32_t p = 0; p < k->n_parents; p++) + if (k->parents[p] == 0 || k->parents[p] >= k->id) { rc = -2; break; } + if (rc) break; + crumb_hash(w, k, d); + if (memcmp(d, k->digest, 32) != 0) { rc = -3; break; } + n++; + } + pthread_mutex_unlock(&w->mu); + if (out_checked) *out_checked = n; + return rc; +} + +/* ---- wakeups and admission ---------------------------------------------- */ + +static void enqueue(RxWorld *w, uint32_t rid) { + uint32_t p = w->reactions[rid].desc.priority; + uint32_t tail = (w->ready_head[p] + w->ready_len[p]) % RX_MAX_REACTIONS; + w->ready_q[p][tail] = rid; + w->ready_len[p]++; + w->in_flight++; + pthread_cond_signal(&w->work_cv); +} + +static void wake(RxWorld *w, uint32_t rid, uint64_t cause) { + RxReaction *r = &w->reactions[rid]; + w->stats.wakes++; + switch (r->state) { + case RX_DORMANT: + set_state(w, r, RX_READY); + r->wake_cause = cause; + r->coalesced = 0; + enqueue(w, rid); + break; + case RX_READY: + /* Already admitted-pending: fold this wake into the same activation. */ + r->wake_cause = cause; + r->coalesced++; + w->stats.coalesced_wakes++; + break; + default: + /* Running or publishing: its snapshot may be stale. Run again after. */ + r->wake_cause = cause; + r->rearm = true; + w->stats.coalesced_wakes++; + break; + } +} + +/* Only the subscribers of this object, filtered by field mask. */ +static void propagate(RxWorld *w, uint32_t obj, uint64_t changed, uint64_t cause) { + uint32_t gen = w->objects[obj].generation; + for (uint32_t i = 0; i < w->n_subs[obj]; i++) { + const RxSub *s = &w->subs[obj][i]; + w->stats.subscriptions_checked++; + if (s->generation != gen) continue; + if (s->mask & changed) wake(w, s->reaction, cause); + } +} + +static bool pop_ready(RxWorld *w, uint32_t *rid) { + for (uint32_t p = 0; p < RX_PRIORITY_CLASSES; p++) { + if (w->ready_len[p] == 0) continue; + *rid = w->ready_q[p][w->ready_head[p]]; + w->ready_head[p] = (w->ready_head[p] + 1) % RX_MAX_REACTIONS; + w->ready_len[p]--; + return true; + } + return false; +} + +/* ---- validation --------------------------------------------------------- */ + +static bool ref_live(const RxWorld *w, RxObjRef ref) { + return ref.id < RX_MAX_OBJECTS && w->objects[ref.id].live && + w->objects[ref.id].generation == ref.generation; +} + +static int validate_caps(const RxWorld *w, const RxReactionDesc *d, int *first_err) { + for (uint32_t i = 0; i < d->n_caps; i++) { + int rc = rx_caproot_validate(w->root, d->caps[i].ref, d->subject, + d->caps[i].resource, d->caps[i].rights, NULL); + if (rc != RX_CAP_OK) { + if (first_err) *first_err = rc; + return -1; + } + } + return 0; +} + +/* Static coverage: every object read needs a READ capability need on its + * resource and every object written a WRITE one. */ +static bool covered(const RxWorld *w, const RxReactionDesc *d, RxObjRef o, uint32_t right) { + uint64_t res = w->objects[o.id].resource; + for (uint32_t i = 0; i < d->n_caps; i++) + if (d->caps[i].resource == res && (d->caps[i].rights & right) == right) return true; + return false; +} + +/* Collect triggers + reads into one deduplicated dependency list. */ +static uint32_t gather_deps(const RxReactionDesc *d, RxDep out[RX_MAX_DEPS]) { + uint32_t n = 0; + for (uint32_t pass = 0; pass < 2; pass++) { + uint32_t cnt = pass ? d->n_reads : d->n_triggers; + const RxDep *src = pass ? d->reads : d->triggers; + for (uint32_t i = 0; i < cnt; i++) { + uint32_t j; + for (j = 0; j < n; j++) + if (out[j].obj.id == src[i].obj.id && out[j].obj.generation == src[i].obj.generation) { + out[j].mask |= src[i].mask; + break; + } + if (j == n && n < RX_MAX_DEPS) out[n++] = src[i]; + } + } + return n; +} + +/* ---- publication -------------------------------------------------------- */ + +typedef struct { + RxObjRef obj; + uint64_t changed; + uint64_t value[RX_MAX_FIELDS]; +} PendingWrite; + +/* Apply mutations atomically (caller holds mu). Returns the number of objects + * written into pw/n_pw, or a negative error with nothing applied. */ +static int stage_mutations(RxWorld *w, const RxMutation *m, uint32_t n, + const RxDep *write_set, uint32_t n_ws, + PendingWrite pw[RX_MAX_WRITES], uint32_t *n_pw) { + *n_pw = 0; + for (uint32_t i = 0; i < n; i++) { + if (m[i].field >= RX_MAX_FIELDS) return RX_ERR_WRITE_SET; + if (!ref_live(w, m[i].obj)) return RX_ERR_STALE_GEN; + if (write_set) { + bool ok = false; + for (uint32_t k = 0; k < n_ws; k++) + if (write_set[k].obj.id == m[i].obj.id && + write_set[k].obj.generation == m[i].obj.generation && + (write_set[k].mask & RX_FIELD(m[i].field))) ok = true; + if (!ok) return RX_ERR_WRITE_SET; + } + uint32_t j; + for (j = 0; j < *n_pw; j++) + if (pw[j].obj.id == m[i].obj.id) break; + if (j == *n_pw) { + if (*n_pw >= RX_MAX_WRITES) return RX_ERR_FULL; + pw[j].obj = m[i].obj; + pw[j].changed = 0; + memcpy(pw[j].value, w->objects[m[i].obj.id].field, sizeof(pw[j].value)); + (*n_pw)++; + } + pw[j].value[m[i].field] = m[i].value; + } + for (uint32_t j = 0; j < *n_pw; j++) { + const RxObject *o = &w->objects[pw[j].obj.id]; + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) + if (pw[j].value[f] != o->field[f]) pw[j].changed |= RX_FIELD(f); + } + return RX_OK; +} + +static void commit_writes(RxWorld *w, PendingWrite *pw, uint32_t n_pw, RxCrumb *k) { + k->n_outputs = 0; + for (uint32_t j = 0; j < n_pw; j++) { + if (!pw[j].changed) continue; + RxObject *o = &w->objects[pw[j].obj.id]; + o->version++; + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { + if (!(pw[j].changed & RX_FIELD(f))) continue; + o->field[f] = pw[j].value[f]; + o->field_version[f] = o->version; + } + object_digest(o); + k->outputs[k->n_outputs].obj = pw[j].obj; + k->outputs[k->n_outputs].version = o->version; + k->outputs[k->n_outputs].mask = pw[j].changed; + k->n_outputs++; + } +} + +/* After the crumb id is known: stamp writers, then wake subscribers. */ +static void finish_writes(RxWorld *w, PendingWrite *pw, uint32_t n_pw, uint64_t cid) { + for (uint32_t j = 0; j < n_pw; j++) { + if (!pw[j].changed) continue; + RxObject *o = &w->objects[pw[j].obj.id]; + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) + if (pw[j].changed & RX_FIELD(f)) o->field_writer[f] = cid; + } + for (uint32_t j = 0; j < n_pw; j++) + if (pw[j].changed) propagate(w, pw[j].obj.id, pw[j].changed, cid); +} + +/* ---- worker ------------------------------------------------------------- */ + +static void end_activation(RxWorld *w, uint32_t rid) { + RxReaction *r = &w->reactions[rid]; + set_state(w, r, RX_DORMANT); + w->in_flight--; + if (r->rearm) { + r->rearm = false; + set_state(w, r, RX_READY); + r->coalesced = 0; + enqueue(w, rid); + } + if (w->in_flight == 0) pthread_cond_broadcast(&w->idle_cv); +} + +static void fill_inputs(RxCrumb *k, const RxCtx *ctx, const RxDep *deps, uint32_t n) { + k->n_inputs = n; + for (uint32_t i = 0; i < n; i++) { + k->inputs[i].obj = deps[i].obj; + k->inputs[i].version = ctx ? ctx->in[i].version : 0; + k->inputs[i].mask = deps[i].mask; + } +} + +static void run_one(RxWorld *w, uint32_t rid, uint32_t worker) { + RxReaction *r = &w->reactions[rid]; + const RxReactionDesc *d = &r->desc; + RxCrumb k; + memset(&k, 0, sizeof(k)); + k.reaction = rid; + k.faculty = d->faculty; + k.worker = worker; + k.wake_cause = r->wake_cause; + k.coalesced_wakes = r->coalesced; + k.t_start_ns = now_ns(); + k.n_caps = d->n_caps; + for (uint32_t i = 0; i < d->n_caps; i++) k.caps[i] = d->caps[i].ref; + add_parent(&k, r->wake_cause); + r->activations++; + + RxDep deps[RX_MAX_DEPS]; + uint32_t n_deps = gather_deps(d, deps); + + /* Semantic readiness: required inputs exist. */ + for (uint32_t i = 0; i < n_deps; i++) { + if (!ref_live(w, deps[i].obj)) { + set_state(w, r, RX_INVALIDATED); + fill_inputs(&k, NULL, deps, n_deps); + k.kind = RX_CRUMB_INVALIDATED; + k.reason = RX_ERR_STALE_GEN; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.invalidations++; + end_activation(w, rid); + return; + } + } + /* Required authority exists. */ + int cap_err = 0; + if (validate_caps(w, d, &cap_err) != 0) { + set_state(w, r, RX_BLOCKED_AUTHORITY); + fill_inputs(&k, NULL, deps, n_deps); + k.kind = RX_CRUMB_BLOCKED_AUTHORITY; + k.reason = cap_err; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.blocked_authority++; + end_activation(w, rid); + return; + } + + set_state(w, r, RX_RUNNING); + RxCtx ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.user = d->user; + ctx.worker = worker; + ctx.n_in = n_deps; + for (uint32_t i = 0; i < n_deps; i++) { + const RxObject *o = &w->objects[deps[i].obj.id]; + ctx.in[i].obj = deps[i].obj; + ctx.in[i].mask = deps[i].mask; + ctx.in[i].version = o->version; + memcpy(ctx.in[i].field, o->field, sizeof(o->field)); + memcpy(ctx.in[i].field_version, o->field_version, sizeof(o->field_version)); + memcpy(ctx.in[i].field_writer, o->field_writer, sizeof(o->field_writer)); + } + + /* Compute against the snapshot, outside the world lock. */ + pthread_mutex_unlock(&w->mu); + int frc = d->fn(&ctx); + pthread_mutex_lock(&w->mu); + + fill_inputs(&k, &ctx, deps, n_deps); + /* Data ancestry: whoever last wrote each field this reaction read. */ + for (uint32_t i = 0; i < n_deps; i++) + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) + if (deps[i].mask & RX_FIELD(f)) add_parent(&k, ctx.in[i].field_writer[f]); + + if (frc < 0) { + set_state(w, r, RX_FAILED); + k.kind = RX_CRUMB_FAILED; + k.reason = frc; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.failed++; + end_activation(w, rid); + return; + } + + set_state(w, r, RX_PUBLISHING); + /* 1. Versioned reads still valid? */ + bool stale = false; + for (uint32_t i = 0; i < n_deps && !stale; i++) { + const RxObject *o = &w->objects[deps[i].obj.id]; + if (!ref_live(w, deps[i].obj)) { stale = true; break; } + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) + if ((deps[i].mask & RX_FIELD(f)) && o->field_version[f] != ctx.in[i].field_version[f]) { + stale = true; + break; + } + } + if (stale) { + set_state(w, r, RX_INVALIDATED); + k.kind = RX_CRUMB_INVALIDATED; + k.reason = RX_ERR_STALE_GEN; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.invalidations++; + /* The change that made this stale has already re-armed it. */ + end_activation(w, rid); + return; + } + /* 2. Authority still valid (revocation during the run must not execute). */ + if (validate_caps(w, d, &cap_err) != 0) { + set_state(w, r, RX_REJECTED); + k.kind = RX_CRUMB_REJECTED; + k.reason = cap_err; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.rejected++; + end_activation(w, rid); + return; + } + /* 3. Mutations inside the declared write set, targets not stale. */ + PendingWrite pw[RX_MAX_WRITES]; + uint32_t n_pw = 0; + int src = stage_mutations(w, ctx.out, ctx.n_out, d->writes, d->n_writes, pw, &n_pw); + if (src != RX_OK) { + set_state(w, r, RX_REJECTED); + k.kind = RX_CRUMB_REJECTED; + k.reason = src; + k.t_end_ns = now_ns(); + crumb_append(w, &k); + w->stats.rejected++; + end_activation(w, rid); + return; + } + /* 4. Atomic publish. */ + commit_writes(w, pw, n_pw, &k); + k.kind = k.n_outputs ? RX_CRUMB_COMMIT : RX_CRUMB_NOOP; + k.t_end_ns = now_ns(); + uint64_t cid = crumb_append(w, &k); + set_state(w, r, RX_COMMITTED); + if (k.n_outputs) { + w->stats.commits++; + r->commits++; + } else { + w->stats.noops++; + } + finish_writes(w, pw, n_pw, cid); + end_activation(w, rid); +} + +static void *worker_main(void *arg) { + RxWorld *w = arg; + pthread_mutex_lock(&w->mu); + uint32_t me = UINT32_MAX; + for (uint32_t i = 0; i < w->n_workers; i++) + if (pthread_equal(w->workers[i], pthread_self())) me = i; + for (;;) { + uint32_t rid; + while (!w->stopping && !pop_ready(w, &rid)) + pthread_cond_wait(&w->work_cv, &w->mu); + if (w->stopping) break; + run_one(w, rid, me); + } + pthread_mutex_unlock(&w->mu); + return NULL; +} + +/* ---- public API ---------------------------------------------------------- */ + +int rx_world_init(RxWorld *w, RxCapRoot *root, uint32_t n_workers, uint64_t crumb_cap) { + if (!w || !root || n_workers == 0 || n_workers > RX_MAX_WORKERS || crumb_cap == 0) + return RX_ERR_ARG; + memset(w, 0, sizeof(*w)); + w->root = root; + w->crumbs = calloc(crumb_cap, sizeof(RxCrumb)); + if (!w->crumbs) return RX_ERR_FULL; + w->crumb_cap = crumb_cap; + for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) { + w->objects[i].id = i; + w->objects[i].generation = 1; + } + pthread_mutex_init(&w->mu, NULL); + pthread_cond_init(&w->work_cv, NULL); + pthread_cond_init(&w->idle_cv, NULL); + pthread_mutex_lock(&w->mu); + w->n_workers = n_workers; + for (uint32_t i = 0; i < n_workers; i++) + pthread_create(&w->workers[i], NULL, worker_main, w); + pthread_mutex_unlock(&w->mu); + return RX_OK; +} + +void rx_world_destroy(RxWorld *w) { + pthread_mutex_lock(&w->mu); + w->stopping = true; + pthread_cond_broadcast(&w->work_cv); + pthread_mutex_unlock(&w->mu); + for (uint32_t i = 0; i < w->n_workers; i++) pthread_join(w->workers[i], NULL); + for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) free(w->subs[i]); + free(w->crumbs); + pthread_cond_destroy(&w->work_cv); + pthread_cond_destroy(&w->idle_cv); + pthread_mutex_destroy(&w->mu); +} + +int rx_world_create(RxWorld *w, uint32_t type, RxPersist persist, uint64_t resource, + const uint64_t init[RX_MAX_FIELDS], RxObjRef *out) { + pthread_mutex_lock(&w->mu); + for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) { + RxObject *o = &w->objects[i]; + if (o->live) continue; + o->live = true; + o->type = type; + o->persist = persist; + o->resource = resource; + o->version = 1; + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { + o->field[f] = init ? init[f] : 0; + o->field_version[f] = 1; + } + object_digest(o); + RxCrumb k; + memset(&k, 0, sizeof(k)); + k.kind = RX_CRUMB_CREATE; + k.reaction = UINT32_MAX; + k.faculty = RX_FACULTY_EXTERNAL; + k.n_outputs = 1; + k.outputs[0].obj = (RxObjRef){ i, o->generation }; + k.outputs[0].version = 1; + k.outputs[0].mask = RX_ALL_FIELDS; + k.t_start_ns = k.t_end_ns = now_ns(); + uint64_t cid = crumb_append(w, &k); + for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) o->field_writer[f] = cid; + out->id = i; + out->generation = o->generation; + pthread_mutex_unlock(&w->mu); + return RX_OK; + } + pthread_mutex_unlock(&w->mu); + return RX_ERR_FULL; +} + +int rx_world_retire(RxWorld *w, RxObjRef ref) { + pthread_mutex_lock(&w->mu); + if (!ref_live(w, ref)) { + pthread_mutex_unlock(&w->mu); + return RX_ERR_STALE_GEN; + } + RxObject *o = &w->objects[ref.id]; + o->live = false; + o->generation++; + RxCrumb k; + memset(&k, 0, sizeof(k)); + k.kind = RX_CRUMB_RETIRE; + k.reaction = UINT32_MAX; + k.n_inputs = 1; + k.inputs[0].obj = ref; + k.inputs[0].version = o->version; + k.inputs[0].mask = RX_ALL_FIELDS; + k.t_start_ns = k.t_end_ns = now_ns(); + crumb_append(w, &k); + pthread_mutex_unlock(&w->mu); + return RX_OK; +} + +int rx_world_add_reaction(RxWorld *w, const RxReactionDesc *d, uint32_t *out_id) { + if (!d || !d->fn || d->priority >= RX_PRIORITY_CLASSES || d->n_triggers == 0 || + d->n_triggers > RX_MAX_DEPS || d->n_reads > RX_MAX_DEPS || + d->n_writes > RX_MAX_WRITES || d->n_caps > RX_MAX_CAPS) + return RX_ERR_ARG; + pthread_mutex_lock(&w->mu); + int rc = RX_OK; + if (w->n_reactions >= RX_MAX_REACTIONS) { rc = RX_ERR_FULL; goto out; } + /* Declared dependencies must exist now, and every read and write must be + * covered by a declared capability need on that object's resource. The + * needs themselves are only validated against the root at run time. */ + for (uint32_t i = 0; i < d->n_triggers; i++) + if (!ref_live(w, d->triggers[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } + for (uint32_t i = 0; i < d->n_reads; i++) + if (!ref_live(w, d->reads[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } + for (uint32_t i = 0; i < d->n_writes; i++) + if (!ref_live(w, d->writes[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } + for (uint32_t i = 0; i < d->n_triggers; i++) + if (!covered(w, d, d->triggers[i].obj, RX_RIGHT_READ)) { rc = RX_ERR_AUTHORITY; goto out; } + for (uint32_t i = 0; i < d->n_reads; i++) + if (!covered(w, d, d->reads[i].obj, RX_RIGHT_READ)) { rc = RX_ERR_AUTHORITY; goto out; } + for (uint32_t i = 0; i < d->n_writes; i++) + if (!covered(w, d, d->writes[i].obj, RX_RIGHT_WRITE)) { rc = RX_ERR_AUTHORITY; goto out; } + /* Index triggers only: a read-only dependency is observed, not a wake. */ + for (uint32_t i = 0; i < d->n_triggers; i++) { + uint32_t o = d->triggers[i].obj.id; + if (!w->subs[o]) { + w->subs[o] = calloc(RX_MAX_SUBS, sizeof(RxSub)); + if (!w->subs[o]) { rc = RX_ERR_FULL; goto out; } + } + if (w->n_subs[o] >= RX_MAX_SUBS) { rc = RX_ERR_FULL; goto out; } + } + uint32_t rid = w->n_reactions++; + RxReaction *r = &w->reactions[rid]; + memset(r, 0, sizeof(*r)); + r->desc = *d; + r->state = RX_DORMANT; + for (uint32_t i = 0; i < d->n_triggers; i++) { + uint32_t o = d->triggers[i].obj.id; + w->subs[o][w->n_subs[o]++] = (RxSub){ rid, d->triggers[i].obj.generation, d->triggers[i].mask }; + } + if (out_id) *out_id = rid; +out: + pthread_mutex_unlock(&w->mu); + return rc; +} + +int64_t rx_world_publish_external(RxWorld *w, RxCapRef cap, const RxMutation *muts, uint32_t n) { + if (!muts || n == 0 || n > RX_MAX_MUTATIONS) return RX_ERR_ARG; + pthread_mutex_lock(&w->mu); + for (uint32_t i = 0; i < n; i++) { + if (!ref_live(w, muts[i].obj)) { pthread_mutex_unlock(&w->mu); return RX_ERR_STALE_GEN; } + int rc = rx_caproot_validate(w->root, cap, w->external_subject, + w->objects[muts[i].obj.id].resource, RX_RIGHT_WRITE, NULL); + if (rc != RX_CAP_OK) { pthread_mutex_unlock(&w->mu); return RX_ERR_AUTHORITY; } + } + PendingWrite pw[RX_MAX_WRITES]; + uint32_t n_pw = 0; + int rc = stage_mutations(w, muts, n, NULL, 0, pw, &n_pw); + if (rc != RX_OK) { pthread_mutex_unlock(&w->mu); return rc; } + RxCrumb k; + memset(&k, 0, sizeof(k)); + k.kind = RX_CRUMB_EXTERNAL; + k.reaction = UINT32_MAX; + k.faculty = RX_FACULTY_EXTERNAL; + k.n_caps = 1; + k.caps[0] = cap; + k.t_start_ns = now_ns(); + commit_writes(w, pw, n_pw, &k); + k.t_end_ns = now_ns(); + uint64_t cid = crumb_append(w, &k); + finish_writes(w, pw, n_pw, cid); + pthread_mutex_unlock(&w->mu); + return (int64_t)cid; +} + +int rx_world_wait_quiescent(RxWorld *w, int timeout_ms) { + struct timespec dl; + clock_gettime(CLOCK_REALTIME, &dl); + dl.tv_sec += timeout_ms / 1000; + dl.tv_nsec += (long)(timeout_ms % 1000) * 1000000L; + if (dl.tv_nsec >= 1000000000L) { dl.tv_sec++; dl.tv_nsec -= 1000000000L; } + pthread_mutex_lock(&w->mu); + int rc = RX_OK; + while (w->in_flight != 0) { + if (pthread_cond_timedwait(&w->idle_cv, &w->mu, &dl) == ETIMEDOUT) { + rc = RX_ERR_TIMEOUT; + break; + } + } + pthread_mutex_unlock(&w->mu); + return rc; +} + +int rx_world_read(RxWorld *w, RxObjRef ref, RxObject *out) { + pthread_mutex_lock(&w->mu); + int rc = ref_live(w, ref) ? RX_OK : RX_ERR_STALE_GEN; + if (rc == RX_OK) *out = w->objects[ref.id]; + pthread_mutex_unlock(&w->mu); + return rc; +} + +uint64_t rx_world_explain(RxWorld *w, RxObjRef ref, uint32_t field) { + pthread_mutex_lock(&w->mu); + uint64_t id = (ref_live(w, ref) && field < RX_MAX_FIELDS) + ? w->objects[ref.id].field_writer[field] : 0; + pthread_mutex_unlock(&w->mu); + return id; +} + +void rx_world_digest(RxWorld *w, uint8_t out[32]) { + pthread_mutex_lock(&w->mu); + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)"AIEN_RX_WORLD_V1", 16); + for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) { + const RxObject *o = &w->objects[i]; + if (!o->live) continue; + put32(&c, o->id); + put32(&c, o->generation); + sha256_update(&c, o->digest, 32); + } + sha256_final(&c, out); + pthread_mutex_unlock(&w->mu); +} diff --git a/src/runtime/rx_world.h b/src/runtime/rx_world.h new file mode 100644 index 000000000..d17a36771 --- /dev/null +++ b/src/runtime/rx_world.h @@ -0,0 +1,286 @@ +/* + * rx_world.h -- first heartbeat of the resident reaction runtime (ADR 0016). + * + * One shared object world. Reactions declare what wakes them, what they read, + * what they write and which capabilities they need. A dependency index maps a + * (object, field-mask) change to the interested reactions only; nothing scans + * the graph. Worker threads run whatever is READY, in admission order; they + * never decide the semantic sequence. A reaction computes against a versioned + * snapshot, then publishes atomically after re-validating its inputs and its + * capabilities. Every outcome leaves a content-addressed causal crumb. + * + * This is the simple human reference (ADR 0016 §56 step 2): one world mutex, + * bounded fixed-size tables. It is deliberately not optimized. + * + * Covered here: R1 subset (logical ids, generations, versions, persistence + * class, atomic publication, stale-reference rejection), R3 (reaction core), + * R4 subset (causal crumbs + ancestry). Not covered: R2 GPU ABI, R5 modulation + * beyond priority classes, R6 storm control beyond wake coalescing, R7 native + * root, R9 generation barrier. + */ +#ifndef RX_WORLD_H +#define RX_WORLD_H + +#include "rx_caproot.h" + +#include +#include +#include + +#define RX_MAX_OBJECTS 256u +#define RX_MAX_FIELDS 8u +#define RX_MAX_REACTIONS 256u +#define RX_MAX_DEPS 8u +#define RX_MAX_WRITES 8u +#define RX_MAX_CAPS 8u +#define RX_MAX_MUTATIONS 16u +#define RX_MAX_SUBS 512u /* subscriptions per object */ +#define RX_MAX_WORKERS 16u +#define RX_MAX_PARENTS (RX_MAX_DEPS * RX_MAX_FIELDS + 1u) +#define RX_PRIORITY_CLASSES 7u + +#define RX_ALL_FIELDS ((uint64_t)((1u << RX_MAX_FIELDS) - 1u)) +#define RX_FIELD(i) ((uint64_t)1u << (i)) + +/* Faculties (logical write domains, not memory owners). */ +enum { RX_FACULTY_EXTERNAL = 0, RX_FACULTY_AIEN, RX_FACULTY_OMEGA, RX_FACULTY_AEGIS }; + +/* Priority classes (ADR 0016 §9), highest first. */ +enum { + RX_PRIO_CRITICAL = 0, RX_PRIO_INTERACTIVE, RX_PRIO_FOREGROUND, RX_PRIO_LEARNING, + RX_PRIO_MAINTENANCE, RX_PRIO_SPECULATIVE, RX_PRIO_BACKGROUND +}; + +/* Persistence class (ADR 0016 §19; ADR 0015 §2 mapping in ADR 0016 Part I). */ +typedef enum { RX_PERSIST_EPHEMERAL = 0, RX_PERSIST_RESIDENT, RX_PERSIST_DURABLE } RxPersist; + +/* Reaction lifecycle (ADR 0016 §6). Every activation ends back in DORMANT. */ +typedef enum { + RX_DORMANT = 0, + RX_READY, + RX_BLOCKED_AUTHORITY, + RX_BLOCKED_RESOURCE, + RX_RUNNING, + RX_PUBLISHING, + RX_COMMITTED, + RX_INVALIDATED, + RX_FAILED, + RX_CANCELLED, + RX_CONFLICT, + RX_REJECTED, + RX_STATE_COUNT +} RxState; + +/* Causal crumb kinds. */ +typedef enum { + RX_CRUMB_CREATE = 1, + RX_CRUMB_EXTERNAL, + RX_CRUMB_COMMIT, + RX_CRUMB_INVALIDATED, + RX_CRUMB_BLOCKED_AUTHORITY, + RX_CRUMB_REJECTED, + RX_CRUMB_FAILED, + RX_CRUMB_NOOP, /* ran, proposed no change: fixed point */ + RX_CRUMB_RETIRE +} RxCrumbKind; + +/* Publication errors. */ +#define RX_OK 0 +#define RX_ERR_ARG -1 +#define RX_ERR_FULL -2 +#define RX_ERR_STALE_GEN -3 +#define RX_ERR_AUTHORITY -4 +#define RX_ERR_WRITE_SET -5 +#define RX_ERR_NOT_FOUND -6 +#define RX_ERR_TIMEOUT -7 + +typedef struct { uint32_t id; uint32_t generation; } RxObjRef; + +typedef struct { + RxObjRef obj; + uint64_t mask; /* fields of interest */ +} RxDep; + +typedef struct { + RxCapRef ref; + uint64_t resource; + uint32_t rights; +} RxCapNeed; + +typedef struct { + RxObjRef obj; + uint32_t field; + uint64_t value; +} RxMutation; + +/* Versioned snapshot of one read dependency. */ +typedef struct { + RxObjRef obj; + uint64_t mask; + uint64_t version; + uint64_t field[RX_MAX_FIELDS]; + uint64_t field_version[RX_MAX_FIELDS]; + uint64_t field_writer[RX_MAX_FIELDS]; /* causal id of the last writer */ +} RxSnapshotDep; + +typedef struct RxCtx { + uint32_t n_in; + RxSnapshotDep in[RX_MAX_DEPS]; + uint32_t n_out; + RxMutation out[RX_MAX_MUTATIONS]; + void *user; + uint32_t worker; +} RxCtx; + +/* Pure transformation: read ctx->in, append proposals to ctx->out. + * Return 0 to publish (possibly nothing), negative to fail. */ +typedef int (*RxFn)(RxCtx *ctx); + +typedef struct { + const char *name; + uint32_t faculty; + uint32_t subject; /* principal the capabilities must be bound to */ + uint32_t priority; + uint32_t n_triggers; + RxDep triggers[RX_MAX_DEPS]; + uint32_t n_reads; /* triggers are read implicitly */ + RxDep reads[RX_MAX_DEPS]; + uint32_t n_writes; + RxDep writes[RX_MAX_WRITES]; + uint32_t n_caps; + RxCapNeed caps[RX_MAX_CAPS]; + RxFn fn; + void *user; +} RxReactionDesc; + +typedef struct { + uint32_t id; + uint32_t generation; + uint32_t type; + bool live; + RxPersist persist; + uint64_t resource; /* capability resource that guards this object */ + uint64_t version; + uint64_t field[RX_MAX_FIELDS]; + uint64_t field_version[RX_MAX_FIELDS]; + uint64_t field_writer[RX_MAX_FIELDS]; + uint8_t digest[32]; /* content identity of (type, fields) */ +} RxObject; + +typedef struct { uint32_t reaction; uint32_t generation; uint64_t mask; } RxSub; + +typedef struct { + uint64_t id; /* 1-based, dense; 0 = none */ + RxCrumbKind kind; + uint32_t reaction; /* UINT32_MAX for external/create */ + uint32_t faculty; + uint32_t worker; + uint64_t wake_cause; /* crumb that last woke this activation */ + uint64_t coalesced_wakes; /* extra wakes folded into this activation */ + uint32_t n_inputs; + struct { RxObjRef obj; uint64_t version; uint64_t mask; } inputs[RX_MAX_DEPS]; + uint32_t n_caps; + RxCapRef caps[RX_MAX_CAPS]; + uint32_t n_outputs; + struct { RxObjRef obj; uint64_t version; uint64_t mask; } outputs[RX_MAX_WRITES]; + uint32_t n_parents; + uint64_t parents[RX_MAX_PARENTS]; + uint64_t t_start_ns; + uint64_t t_end_ns; + int32_t reason; + uint8_t digest[32]; /* SHA-256 over canonical crumb bytes + parent digests */ +} RxCrumb; + +typedef struct { + RxReactionDesc desc; + RxState state; + bool rearm; /* woken while running: go READY again after */ + uint64_t wake_cause; + uint64_t coalesced; + uint64_t activations; + uint64_t commits; +} RxReaction; + +typedef struct { + uint64_t transitions[RX_STATE_COUNT][RX_STATE_COUNT]; + uint64_t illegal_transitions; + uint64_t wakes; + uint64_t coalesced_wakes; + uint64_t subscriptions_checked; + uint64_t commits; + uint64_t invalidations; + uint64_t blocked_authority; + uint64_t rejected; + uint64_t failed; + uint64_t noops; + uint64_t crumb_overflow; +} RxStats; + +typedef struct RxWorld { + pthread_mutex_t mu; + pthread_cond_t work_cv; + pthread_cond_t idle_cv; + + RxCapRoot *root; + uint32_t external_subject; + + RxObject objects[RX_MAX_OBJECTS]; + RxSub *subs[RX_MAX_OBJECTS]; + uint32_t n_subs[RX_MAX_OBJECTS]; + + RxReaction reactions[RX_MAX_REACTIONS]; + uint32_t n_reactions; + + /* Physical admission: bounded per-priority FIFO rings. */ + uint32_t ready_q[RX_PRIORITY_CLASSES][RX_MAX_REACTIONS]; + uint32_t ready_head[RX_PRIORITY_CLASSES]; + uint32_t ready_len[RX_PRIORITY_CLASSES]; + uint32_t in_flight; /* READY + RUNNING + PUBLISHING */ + + RxCrumb *crumbs; + uint64_t n_crumbs; + uint64_t crumb_cap; + + pthread_t workers[RX_MAX_WORKERS]; + uint32_t n_workers; + bool stopping; + + RxStats stats; +} RxWorld; + +int rx_world_init(RxWorld *w, RxCapRoot *root, uint32_t n_workers, uint64_t crumb_cap); +void rx_world_destroy(RxWorld *w); + +/* Object lifecycle. Creation writes a CREATE crumb. Retiring bumps the slot + * generation, so every outstanding RxObjRef to it becomes stale. */ +int rx_world_create(RxWorld *w, uint32_t type, RxPersist persist, uint64_t resource, + const uint64_t init[RX_MAX_FIELDS], RxObjRef *out); +int rx_world_retire(RxWorld *w, RxObjRef ref); + +/* Register a reaction; subscriptions go into the dependency index. */ +int rx_world_add_reaction(RxWorld *w, const RxReactionDesc *d, uint32_t *out_id); + +/* A stimulus from outside the organism (sensor, human input). Requires a + * capability for (external_subject, object resource, WRITE). Returns the + * causal id of the EXTERNAL crumb, or a negative error. */ +int64_t rx_world_publish_external(RxWorld *w, RxCapRef cap, + const RxMutation *muts, uint32_t n); + +/* Wait until no reaction is READY/RUNNING/PUBLISHING. Observation only. */ +int rx_world_wait_quiescent(RxWorld *w, int timeout_ms); + +/* Read-only inspection (takes the world lock). */ +int rx_world_read(RxWorld *w, RxObjRef ref, RxObject *out); +const RxCrumb *rx_world_crumb(const RxWorld *w, uint64_t id); +/* Causal id of the publication that last wrote obj.field. */ +uint64_t rx_world_explain(RxWorld *w, RxObjRef ref, uint32_t field); +/* Recompute every crumb digest and check parent links; 0 on success. */ +int rx_world_verify_crumbs(RxWorld *w, uint64_t *out_checked); +/* SHA-256 over all live objects' (id, generation, type, fields). */ +void rx_world_digest(RxWorld *w, uint8_t out[32]); + +bool rx_state_transition_legal(RxState from, RxState to); +const char *rx_state_name(RxState s); +const char *rx_crumb_kind_name(RxCrumbKind k); + +#endif /* RX_WORLD_H */ diff --git a/tests/runtime/rx_heartbeat_test.c b/tests/runtime/rx_heartbeat_test.c new file mode 100644 index 000000000..0a62283c4 --- /dev/null +++ b/tests/runtime/rx_heartbeat_test.c @@ -0,0 +1,1078 @@ +/* + * rx_heartbeat_test.c -- qualification suite for the first heartbeat of the + * resident reaction runtime (ADR 0016; gates R3 and R4, host reference). + * + * The heartbeat this suite must show, with no central function sequencing it: + * + * shared object -> dependency change -> reaction becomes ready -> + * capability validates -> reaction executes -> atomic publication -> + * causal crumb + * + * The test code only (a) sets up objects and capabilities, (b) injects + * external stimuli, and (c) waits for quiescence and inspects. It never calls a + * reaction. Ordering comes from the dependency index. + * + * Receipt: build/qual-runs//R3/rx_heartbeat_receipt.json. A recorded + * receipt is committed separately as evidence/R3/.json in an + * evidence-only commit. Counts are observed, never literal. The candidate + * commit is an input (OMEGA_CANDIDATE_COMMIT), not HEAD. + */ +#include "runtime/rx_caproot.h" +#include "runtime/rx_world.h" +#include "omega_evidence.h" +#include "sha256.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ---- tiny check framework ----------------------------------------------- */ + +#define MAX_TESTS 32 +typedef struct { + const char *name; + const char *invariants; + int checks; + int failures; +} TestRec; + +static TestRec g_tests[MAX_TESTS]; +static int g_ntests; +static TestRec *g_cur; +static uint64_t g_crumbs_verified; +static uint64_t g_crumbs_audited; +static uint64_t g_illegal_transitions; +static uint64_t g_transitions[RX_STATE_COUNT][RX_STATE_COUNT]; + +#define CHECK(cond, ...) do { \ + g_cur->checks++; \ + if (!(cond)) { \ + g_cur->failures++; \ + fprintf(stderr, " FAIL %s:%d [%s] ", __FILE__, __LINE__, g_cur->name); \ + fprintf(stderr, __VA_ARGS__); \ + fputc('\n', stderr); \ + } \ + } while (0) + +static void begin(const char *name, const char *invariants) { + g_cur = &g_tests[g_ntests++]; + g_cur->name = name; + g_cur->invariants = invariants; + printf("[*] %s\n", name); +} + +static void sleep_ms(int ms) { + struct timespec ts = { ms / 1000, (long)(ms % 1000) * 1000000L }; + nanosleep(&ts, NULL); +} + +/* ---- principals and resources ------------------------------------------- */ + +enum { SUBJ_AIEN = 1, SUBJ_OMEGA = 2, SUBJ_AEGIS = 3, SUBJ_EXTERNAL = 100, SUBJ_OTHER = 7 }; +enum { ISSUER_AEGIS_POLICY = 3 }; +enum { + RES_SENSOR = 0x10, RES_BELIEF = 0x20, RES_PLAN = 0x30, RES_RISK = 0x40, + RES_FAN_SRC = 0x50, RES_FAN_OUT = 0x51, RES_PAIR = 0x60, RES_TICK = 0x61, + RES_CHECK = 0x62, RES_SCRATCH = 0x70 +}; +enum { F_TEMP = 0, F_HUMIDITY = 1 }; + +typedef struct { + RxCapRoot root; + RxWorld w; +} Env; + +static int env_start(Env *e, uint32_t workers) { + if (rx_caproot_start(&e->root) != RX_CAP_OK) return -1; + if (rx_world_init(&e->w, &e->root, workers, 1u << 18) != RX_OK) { + rx_caproot_stop(&e->root); + return -1; + } + e->w.external_subject = SUBJ_EXTERNAL; + return 0; +} + +static RxCapRef mint(Env *e, uint32_t subject, uint64_t resource, uint32_t rights) { + RxCapMint m = { ISSUER_AEGIS_POLICY, subject, resource, rights, 0, { UINT32_MAX, 0 } }; + RxCapRef r = { UINT32_MAX, 0 }; + int rc = rx_caproot_mint(&e->root, &m, &r); + if (rc != RX_CAP_OK) fprintf(stderr, "mint failed: %s\n", rx_cap_strerror(rc)); + return r; +} + +static RxObjRef mkobj(Env *e, uint64_t resource, uint64_t v0) { + uint64_t init[RX_MAX_FIELDS] = { v0 }; + RxObjRef r = { UINT32_MAX, 0 }; + rx_world_create(&e->w, 1, RX_PERSIST_RESIDENT, resource, init, &r); + return r; +} + +static uint64_t field(Env *e, RxObjRef r, uint32_t f) { + RxObject o; + if (rx_world_read(&e->w, r, &o) != RX_OK) return UINT64_MAX; + return o.field[f]; +} + +static int64_t stimulus(Env *e, RxCapRef cap, RxObjRef obj, uint32_t f, uint64_t v) { + RxMutation m = { obj, f, v }; + return rx_world_publish_external(&e->w, cap, &m, 1); +} + +static void desc_init(RxReactionDesc *d, const char *name, uint32_t faculty, uint32_t subject, + RxFn fn, void *user) { + memset(d, 0, sizeof(*d)); + d->name = name; + d->faculty = faculty; + d->subject = subject; + d->priority = RX_PRIO_FOREGROUND; + d->fn = fn; + d->user = user; +} + +static void add_trigger(RxReactionDesc *d, RxObjRef o, uint64_t mask) { + d->triggers[d->n_triggers++] = (RxDep){ o, mask }; +} +static void add_write(RxReactionDesc *d, RxObjRef o, uint64_t mask) { + d->writes[d->n_writes++] = (RxDep){ o, mask }; +} +static void add_cap(RxReactionDesc *d, RxCapRef c, uint64_t res, uint32_t rights) { + d->caps[d->n_caps++] = (RxCapNeed){ c, res, rights }; +} + +/* Find the snapshot entry for an object. */ +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; +} + +/* ---- causal audit: every reaction outcome must be explainable ------------ */ + +static bool reaches_root(const RxWorld *w, uint64_t id, int depth) { + const RxCrumb *k = rx_world_crumb(w, id); + if (!k || depth > 4096) return false; + if (k->kind == RX_CRUMB_EXTERNAL || k->kind == RX_CRUMB_CREATE) return true; + for (uint32_t i = 0; i < k->n_parents; i++) + if (reaches_root(w, k->parents[i], depth + 1)) return true; + return false; +} + +static void audit_and_close(Env *e) { + RxWorld *w = &e->w; + CHECK(rx_world_wait_quiescent(w, 10000) == RX_OK, "world did not quiesce"); + uint64_t checked = 0; + int vrc = rx_world_verify_crumbs(w, &checked); + CHECK(vrc == 0, "crumb digest chain verification failed (%d)", vrc); + CHECK(w->stats.crumb_overflow == 0, "crumb log overflowed"); + g_crumbs_verified += checked; + for (uint64_t id = 1; id <= w->n_crumbs; id++) { + const RxCrumb *k = rx_world_crumb(w, id); + if (k->reaction == UINT32_MAX) continue; + g_crumbs_audited++; + const RxReactionDesc *d = &w->reactions[k->reaction].desc; + /* trigger explainable: woken by an earlier crumb that wrote a trigger */ + const RxCrumb *cause = rx_world_crumb(w, k->wake_cause); + bool trig = false; + if (cause && cause->id < k->id) + for (uint32_t o = 0; o < cause->n_outputs; o++) + for (uint32_t t = 0; t < d->n_triggers; t++) + if (cause->outputs[o].obj.id == d->triggers[t].obj.id && + (cause->outputs[o].mask & d->triggers[t].mask)) trig = true; + CHECK(trig, "crumb %llu (%s): trigger not explainable", + (unsigned long long)id, d->name); + CHECK(k->n_inputs > 0, "crumb %llu: inputs not recorded", (unsigned long long)id); + CHECK(k->n_caps == d->n_caps, "crumb %llu: authority not recorded", (unsigned long long)id); + if (k->kind == RX_CRUMB_COMMIT) + CHECK(k->n_outputs > 0, "crumb %llu: commit without outputs", (unsigned long long)id); + CHECK(reaches_root(w, id, 0), "crumb %llu: ancestry does not reach a stimulus/creation", + (unsigned long long)id); + } + g_illegal_transitions += w->stats.illegal_transitions; + for (int a = 0; a < RX_STATE_COUNT; a++) + for (int b = 0; b < RX_STATE_COUNT; b++) { + g_transitions[a][b] += w->stats.transitions[a][b]; + if (w->stats.transitions[a][b]) + CHECK(rx_state_transition_legal((RxState)a, (RxState)b), + "illegal transition %s -> %s", rx_state_name((RxState)a), + rx_state_name((RxState)b)); + } + CHECK(w->stats.illegal_transitions == 0, "illegal lifecycle transitions observed"); + rx_world_destroy(w); + rx_caproot_stop(&e->root); +} + +/* ---- heartbeat reactions -------------------------------------------------- */ + +typedef struct { RxObjRef sensor, belief, plan, risk; } HB; + +static int fn_hypothesis(RxCtx *c) { /* AIEN: sensor -> belief */ + HB *h = c->user; + const RxSnapshotDep *s = in_of(c, h->sensor); + c->out[c->n_out++] = (RxMutation){ h->belief, 0, s->field[F_TEMP] * 2 + 1 }; + return 0; +} + +static int fn_realize(RxCtx *c) { /* OMEGA: belief -> plan */ + HB *h = c->user; + const RxSnapshotDep *b = in_of(c, h->belief); + c->out[c->n_out++] = (RxMutation){ h->plan, 0, b->field[0] + 1000 }; + return 0; +} + +static int fn_risk(RxCtx *c) { /* fan-in of two triggers */ + HB *h = c->user; + const RxSnapshotDep *s = in_of(c, h->sensor); + const RxSnapshotDep *b = in_of(c, h->belief); + c->out[c->n_out++] = (RxMutation){ h->risk, 0, s->field[F_HUMIDITY] * 100000 + b->field[0] }; + return 0; +} + +typedef struct { Env e; HB h; uint32_t ra, rb, rc; RxCapRef c_ext; } HBEnv; + +static int hb_setup(HBEnv *x, uint32_t workers) { + if (env_start(&x->e, workers) != 0) return -1; + Env *e = &x->e; + x->h.sensor = mkobj(e, RES_SENSOR, 0); + x->h.belief = mkobj(e, RES_BELIEF, 0); + x->h.plan = mkobj(e, RES_PLAN, 0); + x->h.risk = mkobj(e, RES_RISK, 0); + x->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; + desc_init(&d, "aien.hypothesis", RX_FACULTY_AIEN, SUBJ_AIEN, fn_hypothesis, &x->h); + add_trigger(&d, x->h.sensor, RX_FIELD(F_TEMP)); + add_write(&d, x->h.belief, RX_FIELD(0)); + add_cap(&d, a_rs, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, a_wb, RES_BELIEF, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &x->ra) != RX_OK) return -1; + + desc_init(&d, "omega.realize", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_realize, &x->h); + add_trigger(&d, x->h.belief, RX_FIELD(0)); + add_write(&d, x->h.plan, RX_FIELD(0)); + add_cap(&d, o_rb, RES_BELIEF, RX_RIGHT_READ); + add_cap(&d, o_wp, RES_PLAN, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &x->rb) != RX_OK) return -1; + + desc_init(&d, "omega.risk", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_risk, &x->h); + add_trigger(&d, x->h.sensor, RX_FIELD(F_HUMIDITY)); + add_trigger(&d, x->h.belief, RX_FIELD(0)); + add_write(&d, x->h.risk, RX_FIELD(0)); + add_cap(&d, o_rs, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, o_rb, RES_BELIEF, RX_RIGHT_READ); + add_cap(&d, o_wr, RES_RISK, RX_RIGHT_WRITE); + if (rx_world_add_reaction(&e->w, &d, &x->rc) != RX_OK) return -1; + return 0; +} + +/* ---- tests ---------------------------------------------------------------- */ + +static char g_heartbeat_trace[2048]; + +static void t_heartbeat(void) { + begin("heartbeat_chain", "I3,I4,I6,I7"); + HBEnv x; + CHECK(hb_setup(&x, 4) == 0, "setup"); + Env *e = &x.e; + int64_t ext = stimulus(e, x.c_ext, x.h.sensor, F_TEMP, 21); + CHECK(ext > 0, "external stimulus refused"); + CHECK(rx_world_wait_quiescent(&e->w, 5000) == RX_OK, "quiescence"); + CHECK(field(e, x.h.belief, 0) == 43, "belief = %llu", (unsigned long long)field(e, x.h.belief, 0)); + CHECK(field(e, x.h.plan, 0) == 1043, "plan = %llu", (unsigned long long)field(e, x.h.plan, 0)); + + /* Walk back from the result: plan <- omega.realize <- belief <- aien.hypothesis <- stimulus */ + uint64_t c_plan = rx_world_explain(&e->w, x.h.plan, 0); + const RxCrumb *kp = rx_world_crumb(&e->w, c_plan); + CHECK(kp && kp->kind == RX_CRUMB_COMMIT && kp->reaction == x.rb, "plan writer is omega.realize"); + uint64_t c_bel = rx_world_explain(&e->w, x.h.belief, 0); + const RxCrumb *kb = rx_world_crumb(&e->w, c_bel); + CHECK(kb && kb->kind == RX_CRUMB_COMMIT && kb->reaction == x.ra, "belief writer is aien.hypothesis"); + CHECK(kp && kp->wake_cause == c_bel, "omega.realize was woken by the belief commit"); + CHECK(kb && kb->wake_cause == (uint64_t)ext, "aien.hypothesis was woken by the stimulus"); + bool parent_ok = false; + for (uint32_t i = 0; kp && i < kp->n_parents; i++) if (kp->parents[i] == c_bel) parent_ok = true; + CHECK(parent_ok, "plan crumb lists the belief crumb as a causal parent"); + CHECK(kb && kb->n_caps == 2 && kp && kp->n_caps == 2, "authority used is recorded"); + CHECK(kb && kb->faculty == RX_FACULTY_AIEN && kp && kp->faculty == RX_FACULTY_OMEGA, + "faculty contributions recorded"); + CHECK(e->w.reactions[x.ra].activations == 1 && e->w.reactions[x.rb].activations == 1, + "each stage activated exactly once"); + if (kp && kb) { + const RxCrumb *ke = rx_world_crumb(&e->w, (uint64_t)ext); + char dg[3][17]; + const RxCrumb *ks[3] = { ke, kb, kp }; + for (int i = 0; i < 3; i++) + for (int j = 0; j < 8; j++) sprintf(&dg[i][j * 2], "%02x", ks[i]->digest[j]); + snprintf(g_heartbeat_trace, sizeof(g_heartbeat_trace), + "[{\"crumb\":%llu,\"kind\":\"EXTERNAL\",\"digest16\":\"%s\"}," + "{\"crumb\":%llu,\"kind\":\"COMMIT\",\"reaction\":\"aien.hypothesis\",\"wake_cause\":%llu,\"digest16\":\"%s\"}," + "{\"crumb\":%llu,\"kind\":\"COMMIT\",\"reaction\":\"omega.realize\",\"wake_cause\":%llu,\"digest16\":\"%s\"}]", + (unsigned long long)ke->id, dg[0], + (unsigned long long)kb->id, (unsigned long long)kb->wake_cause, dg[1], + (unsigned long long)kp->id, (unsigned long long)kp->wake_cause, dg[2]); + } + audit_and_close(e); +} + +static void t_single_dependency_narrow(void) { + begin("single_dependency_field_granularity", "I7"); + HBEnv x; + CHECK(hb_setup(&x, 2) == 0, "setup"); + Env *e = &x.e; + stimulus(e, x.c_ext, x.h.sensor, F_TEMP, 5); + rx_world_wait_quiescent(&e->w, 5000); + uint64_t a0 = e->w.reactions[x.ra].activations; + /* Humidity is not in aien.hypothesis's trigger mask: it must not wake. */ + stimulus(e, x.c_ext, x.h.sensor, F_HUMIDITY, 9); + rx_world_wait_quiescent(&e->w, 5000); + CHECK(e->w.reactions[x.ra].activations == a0, "temperature-only reaction woke on humidity"); + CHECK(e->w.reactions[x.rc].activations >= 1, "humidity subscriber did wake"); + /* Same value again: no change, no wake (fixed point). */ + uint64_t b0 = e->w.reactions[x.rb].activations; + stimulus(e, x.c_ext, x.h.sensor, F_TEMP, 5); + rx_world_wait_quiescent(&e->w, 5000); + CHECK(e->w.reactions[x.ra].activations == a0 && e->w.reactions[x.rb].activations == b0, + "unchanged value woke reactions"); + audit_and_close(e); +} + +static void t_multiple_dependency(void) { + begin("multiple_dependency_fan_in_two_triggers", "I6,I7"); + HBEnv x; + CHECK(hb_setup(&x, 4) == 0, "setup"); + Env *e = &x.e; + stimulus(e, x.c_ext, x.h.sensor, F_HUMIDITY, 3); + stimulus(e, x.c_ext, x.h.sensor, F_TEMP, 10); + rx_world_wait_quiescent(&e->w, 5000); + /* risk = humidity*100000 + belief, belief = 2*temp + 1 */ + CHECK(field(e, x.h.risk, 0) == 3 * 100000 + 21, "risk = %llu", + (unsigned long long)field(e, x.h.risk, 0)); + audit_and_close(e); +} + +typedef struct { RxObjRef src; RxObjRef out; uint64_t add; } FanArg; + +static int fn_fan(RxCtx *c) { + FanArg *a = c->user; + c->out[c->n_out++] = (RxMutation){ a->out, 0, in_of(c, a->src)->field[0] + a->add }; + return 0; +} + +static void t_fan_out(void) { + begin("fan_out_64", "I6,I7"); + Env e; + CHECK(env_start(&e, 8) == 0, "setup"); + RxObjRef src = mkobj(&e, RES_FAN_SRC, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_FAN_SRC, RX_RIGHT_WRITE); + RxCapRef r = mint(&e, SUBJ_OMEGA, RES_FAN_SRC, RX_RIGHT_READ); + RxCapRef wr = mint(&e, SUBJ_OMEGA, RES_FAN_OUT, RX_RIGHT_WRITE); + static FanArg args[64]; + uint32_t ids[64]; + for (int i = 0; i < 64; i++) { + args[i] = (FanArg){ src, mkobj(&e, RES_FAN_OUT, 0), (uint64_t)i }; + RxReactionDesc d; + desc_init(&d, "fan.out", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_fan, &args[i]); + add_trigger(&d, src, RX_FIELD(0)); + add_write(&d, args[i].out, RX_FIELD(0)); + add_cap(&d, r, RES_FAN_SRC, RX_RIGHT_READ); + add_cap(&d, wr, RES_FAN_OUT, RX_RIGHT_WRITE); + CHECK(rx_world_add_reaction(&e.w, &d, &ids[i]) == RX_OK, "add fan reaction %d", i); + } + stimulus(&e, ext, src, 0, 1000); + rx_world_wait_quiescent(&e.w, 5000); + int bad = 0, multi = 0; + for (int i = 0; i < 64; i++) { + if (field(&e, args[i].out, 0) != 1000u + (uint64_t)i) bad++; + if (e.w.reactions[ids[i]].activations != 1) multi++; + } + CHECK(bad == 0, "%d fan-out outputs wrong", bad); + CHECK(multi == 0, "%d fan-out reactions ran more or less than once", multi); + audit_and_close(&e); +} + +typedef struct { RxObjRef src[8]; RxObjRef agg; } FanInArg; + +static int fn_sum(RxCtx *c) { + FanInArg *a = c->user; + uint64_t s = 0; + for (int i = 0; i < 8; i++) s += in_of(c, a->src[i])->field[0]; + c->out[c->n_out++] = (RxMutation){ a->agg, 0, s }; + return 0; +} + +static void t_fan_in(void) { + begin("fan_in_8", "I6,I7"); + Env e; + CHECK(env_start(&e, 4) == 0, "setup"); + static FanInArg a; + for (int i = 0; i < 8; i++) a.src[i] = mkobj(&e, RES_FAN_SRC, 0); + a.agg = mkobj(&e, RES_FAN_OUT, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_FAN_SRC, RX_RIGHT_WRITE); + RxCapRef r = mint(&e, SUBJ_OMEGA, RES_FAN_SRC, RX_RIGHT_READ); + RxCapRef wr = mint(&e, SUBJ_OMEGA, RES_FAN_OUT, RX_RIGHT_WRITE); + RxReactionDesc d; + desc_init(&d, "fan.in", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_sum, &a); + for (int i = 0; i < 8; i++) add_trigger(&d, a.src[i], RX_FIELD(0)); + add_write(&d, a.agg, RX_FIELD(0)); + add_cap(&d, r, RES_FAN_SRC, RX_RIGHT_READ); + add_cap(&d, wr, RES_FAN_OUT, RX_RIGHT_WRITE); + uint32_t id; + CHECK(rx_world_add_reaction(&e.w, &d, &id) == RX_OK, "add"); + uint64_t want = 0; + for (int round = 0; round < 5; round++) + for (int i = 0; i < 8; i++) { + uint64_t v = (uint64_t)(round * 10 + i + 1); + stimulus(&e, ext, a.src[i], 0, v); + } + for (int i = 0; i < 8; i++) want += (uint64_t)(40 + i + 1); + rx_world_wait_quiescent(&e.w, 5000); + CHECK(field(&e, a.agg, 0) == want, "agg=%llu want %llu", + (unsigned long long)field(&e, a.agg, 0), (unsigned long long)want); + printf(" fan-in: 40 stimuli -> %llu activations (%llu wakes coalesced)\n", + (unsigned long long)e.w.reactions[id].activations, + (unsigned long long)e.w.stats.coalesced_wakes); + audit_and_close(&e); +} + +typedef struct { RxObjRef x, y; int delay_ms; } SlowArg; + +static int fn_slow(RxCtx *c) { + SlowArg *a = c->user; + uint64_t v = in_of(c, a->x)->field[0]; + sleep_ms(a->delay_ms); + c->out[c->n_out++] = (RxMutation){ a->y, 0, v * 10 }; + return 0; +} + +static void t_invalidation(void) { + begin("invalidation_stale_snapshot", "I2,I6,I7"); + Env e; + CHECK(env_start(&e, 2) == 0, "setup"); + static SlowArg a; + a.x = mkobj(&e, RES_SENSOR, 0); + a.y = mkobj(&e, RES_BELIEF, 0); + a.delay_ms = 80; + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxReactionDesc d; + desc_init(&d, "slow.derive", RX_FACULTY_AIEN, SUBJ_AIEN, fn_slow, &a); + add_trigger(&d, a.x, RX_FIELD(0)); + add_write(&d, a.y, RX_FIELD(0)); + add_cap(&d, mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ), RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE), RES_BELIEF, RX_RIGHT_WRITE); + uint32_t id; + CHECK(rx_world_add_reaction(&e.w, &d, &id) == RX_OK, "add"); + stimulus(&e, ext, a.x, 0, 1); + sleep_ms(20); /* first activation is computing on x=1 */ + stimulus(&e, ext, a.x, 0, 2); + rx_world_wait_quiescent(&e.w, 5000); + CHECK(field(&e, a.y, 0) == 20, "y=%llu (stale result committed?)", + (unsigned long long)field(&e, a.y, 0)); + CHECK(e.w.stats.invalidations >= 1, "no invalidation recorded"); + CHECK(e.w.reactions[id].commits == 1, "commits=%llu; the stale candidate must not commit", + (unsigned long long)e.w.reactions[id].commits); + bool saw = false; + for (uint64_t i = 1; i <= e.w.n_crumbs; i++) + if (rx_world_crumb(&e.w, i)->kind == RX_CRUMB_INVALIDATED) saw = true; + CHECK(saw, "INVALIDATED crumb missing"); + audit_and_close(&e); +} + +/* Concurrent publication: 8 incrementers on one PAIR object, driven by 4 + * publisher threads. a and b must always move together, and no increment may + * be lost: a == b == number of increment commits. */ +typedef struct { RxObjRef pair, tick; } IncArg; +typedef struct { RxObjRef pair, check; } ChkArg; + +static int fn_inc(RxCtx *c) { + IncArg *a = c->user; + const RxSnapshotDep *p = in_of(c, a->pair); + c->out[c->n_out++] = (RxMutation){ a->pair, 0, p->field[0] + 1 }; + c->out[c->n_out++] = (RxMutation){ a->pair, 1, p->field[1] + 1 }; + return 0; +} + +static int fn_chk(RxCtx *c) { + ChkArg *a = c->user; + const RxSnapshotDep *p = in_of(c, a->pair); + const RxSnapshotDep *k = in_of(c, a->check); + if (p->field[0] != p->field[1]) + c->out[c->n_out++] = (RxMutation){ a->check, 0, k->field[0] + 1 }; + return 0; +} + +typedef struct { Env *e; RxCapRef cap; RxObjRef ticks[8]; int base; } PubArg; + +static void *publisher(void *arg) { + PubArg *p = arg; + for (int n = 0; n < 250; n++) + for (int i = 0; i < 2; i++) + stimulus(p->e, p->cap, p->ticks[p->base + i], 0, (uint64_t)(n + 1)); + return NULL; +} + +static void t_concurrent_publication(void) { + begin("concurrent_publication_no_torn_no_lost", "I6,I7"); + Env e; + CHECK(env_start(&e, 8) == 0, "setup"); + RxObjRef pair = mkobj(&e, RES_PAIR, 0); + RxObjRef check = mkobj(&e, RES_CHECK, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_TICK, RX_RIGHT_WRITE); + RxCapRef rt = mint(&e, SUBJ_OMEGA, RES_TICK, RX_RIGHT_READ); + RxCapRef rwp = mint(&e, SUBJ_OMEGA, RES_PAIR, RX_RIGHT_READ | RX_RIGHT_WRITE); + RxCapRef rwc = mint(&e, SUBJ_AEGIS, RES_CHECK, RX_RIGHT_READ | RX_RIGHT_WRITE); + RxCapRef rp = mint(&e, SUBJ_AEGIS, RES_PAIR, RX_RIGHT_READ); + static IncArg inc[8]; + static ChkArg chk; + uint32_t ids[8], cid; + PubArg pa[4]; + RxObjRef ticks[8]; + for (int i = 0; i < 8; i++) { + ticks[i] = mkobj(&e, RES_TICK, 0); + inc[i] = (IncArg){ pair, ticks[i] }; + RxReactionDesc d; + desc_init(&d, "pair.increment", RX_FACULTY_OMEGA, SUBJ_OMEGA, fn_inc, &inc[i]); + add_trigger(&d, ticks[i], RX_FIELD(0)); + d.reads[d.n_reads++] = (RxDep){ pair, RX_FIELD(0) | RX_FIELD(1) }; + add_write(&d, pair, RX_FIELD(0) | RX_FIELD(1)); + add_cap(&d, rt, RES_TICK, RX_RIGHT_READ); + add_cap(&d, rwp, RES_PAIR, RX_RIGHT_READ | RX_RIGHT_WRITE); + CHECK(rx_world_add_reaction(&e.w, &d, &ids[i]) == RX_OK, "add inc"); + } + chk = (ChkArg){ pair, check }; + RxReactionDesc d; + desc_init(&d, "aegis.pair_invariant", RX_FACULTY_AEGIS, SUBJ_AEGIS, fn_chk, &chk); + add_trigger(&d, pair, RX_FIELD(0) | RX_FIELD(1)); + d.reads[d.n_reads++] = (RxDep){ check, RX_FIELD(0) }; + add_write(&d, check, RX_FIELD(0)); + add_cap(&d, rp, RES_PAIR, RX_RIGHT_READ); + add_cap(&d, rwc, RES_CHECK, RX_RIGHT_READ | RX_RIGHT_WRITE); + CHECK(rx_world_add_reaction(&e.w, &d, &cid) == RX_OK, "add checker"); + + pthread_t th[4]; + for (int i = 0; i < 4; i++) { + pa[i].e = &e; + pa[i].cap = ext; + memcpy(pa[i].ticks, ticks, sizeof(ticks)); + pa[i].base = i * 2; + pthread_create(&th[i], NULL, publisher, &pa[i]); + } + for (int i = 0; i < 4; i++) pthread_join(th[i], NULL); + rx_world_wait_quiescent(&e.w, 20000); + uint64_t commits = 0; + for (int i = 0; i < 8; i++) commits += e.w.reactions[ids[i]].commits; + uint64_t a = field(&e, pair, 0), b = field(&e, pair, 1); + CHECK(a == b, "torn pair a=%llu b=%llu", (unsigned long long)a, (unsigned long long)b); + CHECK(a == commits, "lost update: a=%llu commits=%llu", (unsigned long long)a, + (unsigned long long)commits); + CHECK(field(&e, check, 0) == 0, "invariant checker observed %llu torn states", + (unsigned long long)field(&e, check, 0)); + printf(" concurrent: 2000 ticks -> %llu increments committed, %llu invalidations, a=b=%llu\n", + (unsigned long long)commits, (unsigned long long)e.w.stats.invalidations, + (unsigned long long)a); + audit_and_close(&e); +} + +typedef struct { RxObjRef x, target; } StaleArg; + +static int fn_write_target(RxCtx *c) { + StaleArg *a = c->user; + c->out[c->n_out++] = (RxMutation){ a->target, 0, in_of(c, a->x)->field[0] }; + return 0; +} + +static int fn_read_target(RxCtx *c) { (void)c; return 0; } + +static void t_stale_input(void) { + begin("stale_generation_rejected", "I2,I7"); + Env e; + CHECK(env_start(&e, 2) == 0, "setup"); + static StaleArg a; + a.x = mkobj(&e, RES_SENSOR, 0); + a.target = mkobj(&e, RES_SCRATCH, 7); + RxObjRef reader_dep = a.target; + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxCapRef ext_s = mint(&e, SUBJ_EXTERNAL, RES_SCRATCH, RX_RIGHT_WRITE); + RxCapRef rs = mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ); + RxCapRef ws = mint(&e, SUBJ_AIEN, RES_SCRATCH, RX_RIGHT_READ | RX_RIGHT_WRITE); + RxReactionDesc d; + desc_init(&d, "stale.writer", RX_FACULTY_AIEN, SUBJ_AIEN, fn_write_target, &a); + add_trigger(&d, a.x, RX_FIELD(0)); + add_write(&d, a.target, RX_FIELD(0)); + add_cap(&d, rs, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, ws, RES_SCRATCH, RX_RIGHT_READ | RX_RIGHT_WRITE); + uint32_t wid, rid; + CHECK(rx_world_add_reaction(&e.w, &d, &wid) == RX_OK, "add writer"); + desc_init(&d, "stale.reader", RX_FACULTY_AIEN, SUBJ_AIEN, fn_read_target, NULL); + add_trigger(&d, a.x, RX_FIELD(0)); + d.reads[d.n_reads++] = (RxDep){ reader_dep, RX_FIELD(0) }; + add_cap(&d, rs, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, ws, RES_SCRATCH, RX_RIGHT_READ | RX_RIGHT_WRITE); + CHECK(rx_world_add_reaction(&e.w, &d, &rid) == RX_OK, "add reader"); + + /* Retire the target and reuse its slot: same id, next generation. */ + CHECK(rx_world_retire(&e.w, a.target) == RX_OK, "retire"); + RxObjRef reborn = mkobj(&e, RES_SCRATCH, 99); + CHECK(reborn.id == a.target.id && reborn.generation == a.target.generation + 1, + "slot reuse did not advance generation"); + CHECK(stimulus(&e, ext_s, a.target, 0, 5) == RX_ERR_STALE_GEN, + "external write through a stale reference was accepted"); + stimulus(&e, ext, a.x, 0, 1234); + rx_world_wait_quiescent(&e.w, 5000); + CHECK(field(&e, reborn, 0) == 99, "stale writer mutated the reborn object"); + CHECK(e.w.reactions[wid].commits == 0, "stale writer committed"); + CHECK(e.w.stats.rejected >= 1, "stale write not rejected"); + CHECK(e.w.stats.invalidations >= 1, "reader of retired object not invalidated"); + audit_and_close(&e); +} + +typedef struct { RxObjRef x, declared, undeclared; int mode; } WsArg; + +static int fn_outside(RxCtx *c) { + WsArg *a = c->user; + if (a->mode == 0) /* an object it holds WRITE authority for, but never declared */ + c->out[c->n_out++] = (RxMutation){ a->undeclared, 0, 555 }; + else /* the declared object, but a field outside its write mask */ + c->out[c->n_out++] = (RxMutation){ a->declared, 3, 555 }; + c->out[c->n_out++] = (RxMutation){ a->declared, 0, 1 }; + return 0; +} + +static void t_write_set_enforced(void) { + begin("write_outside_declared_set_rejected", "I6,I9"); + Env e; + CHECK(env_start(&e, 2) == 0, "setup"); + static WsArg a[2]; + RxObjRef x = mkobj(&e, RES_SENSOR, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxCapRef rs = mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ); + RxCapRef wb = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + uint32_t ids[2]; + for (int m = 0; m < 2; m++) { + a[m] = (WsArg){ x, mkobj(&e, RES_BELIEF, 0), mkobj(&e, RES_BELIEF, 0), m }; + RxReactionDesc d; + desc_init(&d, m ? "outside.field_mask" : "outside.object", RX_FACULTY_AIEN, SUBJ_AIEN, + fn_outside, &a[m]); + add_trigger(&d, x, RX_FIELD(0)); + add_write(&d, a[m].declared, RX_FIELD(0)); + add_cap(&d, rs, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, wb, RES_BELIEF, RX_RIGHT_WRITE); + CHECK(rx_world_add_reaction(&e.w, &d, &ids[m]) == RX_OK, "add"); + } + stimulus(&e, ext, x, 0, 1); + rx_world_wait_quiescent(&e.w, 5000); + for (int m = 0; m < 2; m++) { + RxObject o; + rx_world_read(&e.w, a[m].declared, &o); + CHECK(o.field[0] == 0 && o.field[3] == 0, "mode %d: partial publication leaked", m); + CHECK(field(&e, a[m].undeclared, 0) == 0, "mode %d: undeclared object written", m); + CHECK(e.w.reactions[ids[m]].commits == 0, "mode %d: committed", m); + } + CHECK(e.w.stats.rejected == 2, "rejected=%llu", (unsigned long long)e.w.stats.rejected); + audit_and_close(&e); +} + +typedef struct { RxObjRef d, out; } DupArg; + +static int fn_dup(RxCtx *c) { + DupArg *a = c->user; + uint64_t v = in_of(c, a->d)->field[0]; + sleep_ms(2); + c->out[c->n_out++] = (RxMutation){ a->out, 0, v }; + return 0; +} + +static void t_duplicate_wake(void) { + begin("duplicate_wake_coalesced", "I7,I13"); + Env e; + CHECK(env_start(&e, 4) == 0, "setup"); + static DupArg a; + a.d = mkobj(&e, RES_SENSOR, 0); + a.out = mkobj(&e, RES_BELIEF, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxReactionDesc d; + desc_init(&d, "dup.derive", RX_FACULTY_AIEN, SUBJ_AIEN, fn_dup, &a); + add_trigger(&d, a.d, RX_FIELD(0)); + add_write(&d, a.out, RX_FIELD(0)); + add_cap(&d, mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ), RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE), RES_BELIEF, RX_RIGHT_WRITE); + uint32_t id; + CHECK(rx_world_add_reaction(&e.w, &d, &id) == RX_OK, "add"); + for (uint64_t v = 1; v <= 1000; v++) stimulus(&e, ext, a.d, 0, v); + rx_world_wait_quiescent(&e.w, 10000); + uint64_t acts = e.w.reactions[id].activations; + CHECK(field(&e, a.out, 0) == 1000, "final output %llu != last input", + (unsigned long long)field(&e, a.out, 0)); + CHECK(acts < 1000, "no coalescing: %llu activations for 1000 wakes", (unsigned long long)acts); + CHECK(e.w.stats.coalesced_wakes > 0, "coalesced counter is zero"); + printf(" duplicate wake: 1000 wakes -> %llu activations, %llu commits\n", + (unsigned long long)acts, (unsigned long long)e.w.reactions[id].commits); + audit_and_close(&e); +} + +/* ---- authority ------------------------------------------------------------ */ + +static int fn_forbidden(RxCtx *c) { + HB *h = c->user; + c->out[c->n_out++] = (RxMutation){ h->belief, 0, 666 }; + return 0; +} + +static uint64_t blocked_with(Env *e, RxObjRef sensor, RxObjRef belief, RxCapRef ext, + uint32_t subject, RxCapRef rcap, RxCapRef wcap, uint64_t trigger_v, + int *out_reason) { + static HB h; + h.sensor = sensor; + h.belief = belief; + RxReactionDesc d; + desc_init(&d, "attack.writer", RX_FACULTY_AIEN, subject, fn_forbidden, &h); + add_trigger(&d, sensor, RX_FIELD(F_TEMP)); + add_write(&d, belief, RX_FIELD(0)); + add_cap(&d, rcap, RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, wcap, RES_BELIEF, RX_RIGHT_WRITE); + uint32_t id; + if (rx_world_add_reaction(&e->w, &d, &id) != RX_OK) return UINT64_MAX; + uint64_t first = e->w.n_crumbs + 1; + stimulus(e, ext, sensor, F_TEMP, trigger_v); + rx_world_wait_quiescent(&e->w, 5000); + *out_reason = 0; + uint64_t blocked = 0; + for (uint64_t i = first; i <= e->w.n_crumbs; i++) { + const RxCrumb *k = rx_world_crumb(&e->w, i); + if (k->reaction != id) continue; + if (k->kind == RX_CRUMB_BLOCKED_AUTHORITY) { *out_reason = k->reason; blocked++; } + else blocked += 1000; /* any other outcome is a failure */ + } + return blocked; +} + +static void t_capability_attacks(void) { + begin("capability_attacks_all_fail", "I3,I4,I9"); + Env e; + CHECK(env_start(&e, 2) == 0, "setup"); + RxObjRef sensor = mkobj(&e, RES_SENSOR, 0); + RxObjRef belief = mkobj(&e, RES_BELIEF, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxCapRef rs = mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ); + RxCapRef wb = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + int reason = 0; + uint64_t v = 1; + + struct { const char *name; RxCapRef w; uint32_t subject; int expect; } cases[8]; + int nc = 0; + cases[nc++] = (typeof(cases[0])){ "forged_reference", (RxCapRef){ 200, 7 }, SUBJ_AIEN, RX_CAP_ERR_STALE_GEN }; + cases[nc++] = (typeof(cases[0])){ "wrong_subject", wb, SUBJ_OTHER, RX_CAP_ERR_SUBJECT }; + cases[nc++] = (typeof(cases[0])){ "wrong_resource", mint(&e, SUBJ_AIEN, RES_PLAN, RX_RIGHT_WRITE), SUBJ_AIEN, RX_CAP_ERR_RESOURCE }; + cases[nc++] = (typeof(cases[0])){ "insufficient_rights", mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_READ), SUBJ_AIEN, RX_CAP_ERR_RIGHTS }; + RxCapRef rev = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + rx_caproot_revoke(&e.root, rev); + cases[nc++] = (typeof(cases[0])){ "revoked", rev, SUBJ_AIEN, RX_CAP_ERR_REVOKED }; + /* Generation replay: revoke, reclaim, the slot is re-minted to someone else. */ + RxCapRef old = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + rx_caproot_revoke(&e.root, old); + rx_caproot_reclaim(&e.root, old.cap_id); + RxCapRef reused = mint(&e, SUBJ_OTHER, RES_BELIEF, RX_RIGHT_WRITE); + CHECK(reused.cap_id == old.cap_id && reused.generation == old.generation + 1, + "reclaimed slot was not reused with a new generation"); + cases[nc++] = (typeof(cases[0])){ "generation_replay", old, SUBJ_AIEN, RX_CAP_ERR_STALE_GEN }; + RxCapMint lm = { ISSUER_AEGIS_POLICY, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE, 5, { UINT32_MAX, 0 } }; + RxCapRef leased; + rx_caproot_mint(&e.root, &lm, &leased); + rx_caproot_advance_clock(&e.root, 10); + cases[nc++] = (typeof(cases[0])){ "expired_lease", leased, SUBJ_AIEN, RX_CAP_ERR_EXPIRED }; + + for (int i = 0; i < nc; i++) { + uint64_t n = blocked_with(&e, sensor, belief, ext, cases[i].subject, + cases[i].subject == SUBJ_AIEN ? rs : mint(&e, cases[i].subject, RES_SENSOR, RX_RIGHT_READ), + cases[i].w, v++, &reason); + CHECK(n == 1 && reason == cases[i].expect, "%s: blocked=%llu reason=%s (want %s)", + cases[i].name, (unsigned long long)n, rx_cap_strerror(reason), + rx_cap_strerror(cases[i].expect)); + CHECK(field(&e, belief, 0) == 0, "%s: forbidden write reached the world", cases[i].name); + } + + /* Delegation may only attenuate. */ + RxCapRef parent = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_READ | RX_RIGHT_DELEGATE); + RxCapMint amp = { SUBJ_AIEN, SUBJ_OMEGA, RES_BELIEF, RX_RIGHT_READ | RX_RIGHT_WRITE, 0, parent }; + CHECK(rx_caproot_mint(&e.root, &, NULL) == RX_CAP_ERR_AMPLIFY, "rights amplification accepted"); + RxCapMint other = { SUBJ_AIEN, SUBJ_OMEGA, RES_PLAN, RX_RIGHT_READ, 0, parent }; + CHECK(rx_caproot_mint(&e.root, &other, NULL) == RX_CAP_ERR_RESOURCE, "resource widening accepted"); + RxCapMint nd = { SUBJ_AIEN, SUBJ_OMEGA, RES_SENSOR, RX_RIGHT_READ, 0, rs }; + CHECK(rx_caproot_mint(&e.root, &nd, NULL) == RX_CAP_ERR_NOT_DELEGABLE, "non-delegable parent delegated"); + RxCapMint ok = { SUBJ_AIEN, SUBJ_OMEGA, RES_BELIEF, RX_RIGHT_READ, 0, parent }; + RxCapRef child; + CHECK(rx_caproot_mint(&e.root, &ok, &child) == RX_CAP_OK, "valid attenuation refused"); + CHECK(rx_caproot_validate(&e.root, child, SUBJ_OMEGA, RES_BELIEF, RX_RIGHT_READ, NULL) == RX_CAP_OK, + "delegated child invalid"); + rx_caproot_revoke(&e.root, parent); + CHECK(rx_caproot_validate(&e.root, child, SUBJ_OMEGA, RES_BELIEF, RX_RIGHT_READ, NULL) == RX_CAP_ERR_CHAIN, + "child survived parent revocation"); + + /* External stimulus with a capability for the wrong subject. */ + CHECK(stimulus(&e, rs, sensor, F_TEMP, 77) == RX_ERR_AUTHORITY, "external write with wrong cap accepted"); + + /* Epoch change invalidates everything minted before it. */ + rx_caproot_bump_epoch(&e.root); + CHECK(rx_caproot_validate(&e.root, rs, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ, NULL) == RX_CAP_ERR_EPOCH, + "pre-epoch capability still valid"); + audit_and_close(&e); +} + +typedef struct { RxObjRef x, y; } RevArg; + +static int fn_rev(RxCtx *c) { + RevArg *a = c->user; + sleep_ms(80); + c->out[c->n_out++] = (RxMutation){ a->y, 0, in_of(c, a->x)->field[0] + 1 }; + return 0; +} + +static void t_revoke_during_run(void) { + begin("revocation_during_run_rejected", "I4,I7"); + Env e; + CHECK(env_start(&e, 2) == 0, "setup"); + static RevArg a; + a.x = mkobj(&e, RES_SENSOR, 0); + a.y = mkobj(&e, RES_BELIEF, 0); + RxCapRef ext = mint(&e, SUBJ_EXTERNAL, RES_SENSOR, RX_RIGHT_WRITE); + RxCapRef w = mint(&e, SUBJ_AIEN, RES_BELIEF, RX_RIGHT_WRITE); + RxReactionDesc d; + desc_init(&d, "revoked.midflight", RX_FACULTY_AIEN, SUBJ_AIEN, fn_rev, &a); + add_trigger(&d, a.x, RX_FIELD(0)); + add_write(&d, a.y, RX_FIELD(0)); + add_cap(&d, mint(&e, SUBJ_AIEN, RES_SENSOR, RX_RIGHT_READ), RES_SENSOR, RX_RIGHT_READ); + add_cap(&d, w, RES_BELIEF, RX_RIGHT_WRITE); + uint32_t id; + CHECK(rx_world_add_reaction(&e.w, &d, &id) == RX_OK, "add"); + stimulus(&e, ext, a.x, 0, 41); + sleep_ms(20); + CHECK(rx_caproot_revoke(&e.root, w) == RX_CAP_OK, "revoke"); + rx_world_wait_quiescent(&e.w, 5000); + CHECK(field(&e, a.y, 0) == 0, "revoked authority executed"); + CHECK(e.w.stats.rejected == 1, "publication not rejected"); + bool saw = false; + for (uint64_t i = 1; i <= e.w.n_crumbs; i++) { + const RxCrumb *k = rx_world_crumb(&e.w, i); + if (k->kind == RX_CRUMB_REJECTED && k->reason == RX_CAP_ERR_REVOKED) saw = true; + } + CHECK(saw, "REJECTED(revoked) crumb missing"); + audit_and_close(&e); +} + +static void t_root_table_unwritable(void) { + begin("capability_table_unforgeable_by_runtime", "I3"); + RxCapRoot root; + CHECK(rx_caproot_start(&root) == RX_CAP_OK, "root"); + void *page = (void *)root.table; + errno = 0; + CHECK(mprotect(page, sizeof(RxCapTable), PROT_READ | PROT_WRITE) != 0, + "runtime made the capability table writable"); + void *m = mmap(NULL, sizeof(RxCapTable), PROT_READ | PROT_WRITE, MAP_SHARED, root.ro_fd, 0); + CHECK(m == MAP_FAILED, "runtime obtained a writable mapping"); + if (m != MAP_FAILED) munmap(m, sizeof(RxCapTable)); + uint32_t junk = 0xffffffffu; + CHECK(pwrite(root.ro_fd, &junk, sizeof(junk), offsetof(RxCapTable, entries)) < 0, + "runtime wrote the capability table through its fd"); + CHECK(ftruncate(root.ro_fd, 0) != 0, "runtime resized the capability table"); + /* Reopen through /proc: the seal is on the inode, so every path is sealed. */ + char path[64]; + snprintf(path, sizeof(path), "/proc/self/fd/%d", root.ro_fd); + int fd2 = open(path, O_RDWR); + if (fd2 >= 0) { + CHECK(pwrite(fd2, &junk, sizeof(junk), offsetof(RxCapTable, entries)) < 0, + "reopened fd could write the table"); + close(fd2); + } + /* The root process is non-dumpable: its writable mapping is out of reach. */ + snprintf(path, sizeof(path), "/proc/%d/mem", (int)root.root_pid); + int memfd = open(path, O_RDWR); + CHECK(memfd < 0, "runtime opened the root's memory"); + if (memfd >= 0) close(memfd); + /* A direct store faults. Prove it in a throwaway child. */ + pid_t pid = fork(); + if (pid == 0) { + volatile uint32_t *rights = (volatile uint32_t *)&((RxCapTable *)page)->entries[0].rights; + *rights = 0xffffffffu; + _exit(0); + } + int st = 0; + waitpid(pid, &st, 0); + CHECK(WIFSIGNALED(st) && (WTERMSIG(st) == SIGSEGV || WTERMSIG(st) == SIGBUS), + "direct store into the capability table did not fault"); + rx_caproot_stop(&root); +} + +static void t_crumb_tamper_detected(void) { + begin("causal_record_tamper_detected", "I7,I15"); + HBEnv x; + CHECK(hb_setup(&x, 2) == 0, "setup"); + Env *e = &x.e; + stimulus(e, x.c_ext, x.h.sensor, F_TEMP, 3); + rx_world_wait_quiescent(&e->w, 5000); + uint64_t id = rx_world_explain(&e->w, x.h.belief, 0); + RxCrumb *k = &e->w.crumbs[id - 1]; + k->caps[0].cap_id ^= 1; /* rewrite "which authority allowed it" */ + CHECK(rx_world_verify_crumbs(&e->w, NULL) != 0, "rewritten authority went undetected"); + k->caps[0].cap_id ^= 1; + CHECK(rx_world_verify_crumbs(&e->w, NULL) == 0, "restored record fails verification"); + audit_and_close(e); +} + +/* No orchestrator, and the order does not matter: for a pure DAG the committed + * world is identical whatever the worker count or thread interleaving. */ +static void t_schedule_independence(void) { + begin("schedule_independent_result", "I16"); + uint8_t ref[32]; + int differ = 0, runs = 0; + for (uint32_t workers = 1; workers <= 8; workers++) + for (int rep = 0; rep < 6; rep++) { + HBEnv x; + if (hb_setup(&x, workers) != 0) { differ++; continue; } + Env *e = &x.e; + for (uint64_t v = 1; v <= 20; v++) { + stimulus(e, x.c_ext, x.h.sensor, F_TEMP, v * 3); + stimulus(e, x.c_ext, x.h.sensor, F_HUMIDITY, v); + } + rx_world_wait_quiescent(&e->w, 5000); + uint8_t dg[32]; + rx_world_digest(&e->w, dg); + if (runs == 0) memcpy(ref, dg, 32); + else if (memcmp(ref, dg, 32) != 0) differ++; + runs++; + audit_and_close(e); + } + CHECK(differ == 0, "%d of %d runs committed a different world", differ, runs); + printf(" %d runs across 1..8 workers, identical committed world\n", runs); +} + +/* ---- receipt -------------------------------------------------------------- */ + +static void write_receipt(int total_checks, int total_fail, const char *binary_digest) { + char path[512]; + if (omega_evidence_path("R3/rx_heartbeat_receipt.json", path, sizeof(path)) != 0) { + fprintf(stderr, "receipt: refused (path exists in record mode?)\n"); + return; + } + FILE *f = fopen(path, "w"); + if (!f) { perror("receipt"); return; } + char commit[41] = "unknown"; + omega_evidence_run_commit(commit); + const char *cand = getenv("OMEGA_CANDIDATE_COMMIT"); + struct utsname u; + uname(&u); + int tests_passed = 0; + for (int i = 0; i < g_ntests; i++) if (g_tests[i].failures == 0) tests_passed++; + bool all = total_fail == 0 && tests_passed == g_ntests; + time_t now = time(NULL); + char ts[32]; + strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", gmtime(&now)); + + fprintf(f, "{\n \"schema\": \"AIEN_RX_HEARTBEAT_RECEIPT_V1\",\n"); + fprintf(f, " \"adr\": \"aien-architecture ADR 0016\",\n"); + fprintf(f, " \"run_id\": \"%s\",\n \"timestamp_utc\": \"%s\",\n", omega_evidence_run_id(), ts); + fprintf(f, " \"candidate_commit\": %s%s%s,\n \"candidate_bound\": %s,\n", + cand ? "\"" : "", cand ? cand : "null", cand ? "\"" : "", cand ? "true" : "false"); + fprintf(f, " \"run_commit\": \"%s\",\n \"tree_dirty\": %s,\n", commit, + omega_evidence_tree_dirty() ? "true" : "false"); + fprintf(f, " \"test_binary_sha256\": \"%s\",\n", binary_digest); + fprintf(f, " \"host\": {\"sysname\": \"%s\", \"release\": \"%s\", \"machine\": \"%s\"},\n", + u.sysname, u.release, u.machine); + fprintf(f, " \"hardware_scope\": \"host CPU only; no accelerator involved\",\n"); + fprintf(f, " \"gates\": {\n"); + fprintf(f, " \"R3_REACTION_CORE\": \"%s\",\n", all ? "PASS (host reference)" : "FAIL"); + fprintf(f, " \"R4_CAUSAL_TRACE\": \"%s\",\n", all ? "PASS (host reference; every reaction crumb in every test audited)" : "FAIL"); + fprintf(f, " \"not_claimed\": [\"R1 canonical shared pool (unify with OMEGA_SHARED_WORLD_V1)\", \"R2\", \"R5\", \"R6\", \"R7 native capability root\", \"R8\", \"R9\", \"R10-R16\"]\n },\n"); + fprintf(f, " \"tests\": [\n"); + for (int i = 0; i < g_ntests; i++) + fprintf(f, " {\"name\": \"%s\", \"invariants\": \"%s\", \"checks\": %d, \"failures\": %d}%s\n", + g_tests[i].name, g_tests[i].invariants, g_tests[i].checks, g_tests[i].failures, + i + 1 < g_ntests ? "," : ""); + fprintf(f, " ],\n"); + fprintf(f, " \"totals\": {\"tests\": %d, \"tests_passed\": %d, \"checks\": %d, \"failures\": %d},\n", + g_ntests, tests_passed, total_checks, total_fail); + fprintf(f, " \"causal\": {\"crumbs_digest_verified\": %llu, \"reaction_crumbs_audited\": %llu},\n", + (unsigned long long)g_crumbs_verified, (unsigned long long)g_crumbs_audited); + fprintf(f, " \"lifecycle\": {\"illegal_transitions\": %llu, \"observed\": [", + (unsigned long long)g_illegal_transitions); + bool first = true; + for (int a = 0; a < RX_STATE_COUNT; a++) + for (int b = 0; b < RX_STATE_COUNT; b++) + if (g_transitions[a][b]) { + fprintf(f, "%s\n {\"from\": \"%s\", \"to\": \"%s\", \"count\": %llu}", first ? "" : ",", + rx_state_name((RxState)a), rx_state_name((RxState)b), + (unsigned long long)g_transitions[a][b]); + first = false; + } + fprintf(f, "\n ]},\n"); + fprintf(f, " \"heartbeat_trace\": %s\n}\n", g_heartbeat_trace[0] ? g_heartbeat_trace : "null"); + fclose(f); + printf("[*] receipt: %s\n", path); +} + +static void binary_digest(const char *argv0, char out[65]) { + strcpy(out, "unavailable"); + FILE *f = fopen("/proc/self/exe", "rb"); + if (!f) f = fopen(argv0, "rb"); + if (!f) return; + sha256_ctx c; + sha256_init(&c); + uint8_t buf[65536]; + size_t n; + while ((n = fread(buf, 1, sizeof(buf), f)) > 0) sha256_update(&c, buf, n); + fclose(f); + uint8_t d[32]; + sha256_final(&c, d); + for (int i = 0; i < 32; i++) sprintf(&out[i * 2], "%02x", d[i]); +} + +int main(int argc, char **argv) { + (void)argc; + signal(SIGPIPE, SIG_IGN); + printf("AIEN resident reaction runtime -- heartbeat qualification (ADR 0016, R3/R4 host)\n"); + t_heartbeat(); + t_single_dependency_narrow(); + t_multiple_dependency(); + t_fan_out(); + t_fan_in(); + t_invalidation(); + t_concurrent_publication(); + t_stale_input(); + t_write_set_enforced(); + t_duplicate_wake(); + t_capability_attacks(); + t_revoke_during_run(); + t_root_table_unwritable(); + t_crumb_tamper_detected(); + t_schedule_independence(); + + int checks = 0, fails = 0; + for (int i = 0; i < g_ntests; i++) { + checks += g_tests[i].checks; + fails += g_tests[i].failures; + printf(" %-45s %s (%d checks)\n", g_tests[i].name, + g_tests[i].failures ? "FAIL" : "PASS", g_tests[i].checks); + } + char dg[65]; + binary_digest(argv[0], dg); + printf("TOTAL: %d tests, %d checks, %d failures; %llu crumbs verified, %llu reaction crumbs audited, %llu illegal transitions\n", + g_ntests, checks, fails, (unsigned long long)g_crumbs_verified, + (unsigned long long)g_crumbs_audited, (unsigned long long)g_illegal_transitions); + write_receipt(checks, fails, dg); + printf("%s\n", fails == 0 ? "R3_REACTION_CORE: PASS (host) R4_CAUSAL_TRACE: PASS (host)" + : "R3/R4: FAIL"); + return fails == 0 ? 0 : 1; +}