interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / tests / runtime / rx_r14_recovery.c

2708 lines · 130805 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * R14: attack the R13 organism while it is alive, and watch the mechanisms it
19 * already has contain, recover and resume (ADR 0016 R14).
20 *
21 * Every scenario starts a fresh R13 body: the same objects, faculties,
22 * authority and R9 store as tests/runtime/rx_r13_living.c. The harness may
23 * inject a fault and may publish what an outside party would publish (a
24 * production request, a human goal, a lane request, the body starting). It
25 * never writes a faculty's object, selects a fallback, wakes a reaction, edits
26 * a generation file or repairs the authority table.
27 *
28 * A corrupt candidate R10 verifier refuses; the valid candidate promotes
29 * B forged authority R7/R8/R9 refuse; honest authority works after revocation
30 * C reaction cycle R6 quarantines the cycle inside its episode
31 * D GPU saturation R5 holds work back; nothing is dropped or doubled
32 * E seat killed mid-claim R12 seat loss; the dead seat's result never lands
33 * F crash in promotion R9 crash points in a child process; restart,
34 * recover, restore what was in force, resume
35 *
36 * R14_SILICON runs D and E on the resident GB10 seat. The host build uses the
37 * R12 processor stand-in and cannot claim the gate.
38 */
39#include "runtime/rx_living.h"
40#include "runtime/rx_resident_gpu.h"
41#include "omega_evidence.h"
42#include "sha256.h"
43
44#include <dirent.h>
45#include <errno.h>
46#include <sched.h>
47#include <stdarg.h>
48#include <signal.h>
49#include <stdatomic.h>
50#include <stdio.h>
51#include <stdlib.h>
52#include <string.h>
53#include <sys/mman.h>
54#include <sys/utsname.h>
55#include <sys/wait.h>
56#include <time.h>
57#include <unistd.h>
58
59enum { EXTERNAL = 100, ISSUER = 3, LANE_SUBJ = 65, ROGUE_SUBJ = 66, STUFFER_SUBJ = 67,
60 CYCLE_SUBJ = 68 };
61#define M 64u
62#define N 256u
63#define CLASS_A725 0xd87u
64#define CLASS_X925 0xd85u
65#define RES_INTENT 0x6130010ull
66#define RES_LANE_IN 0x6140001ull
67#define RES_LANE_OUT 0x6140002ull
68#define RES_LANE_CHK 0x6140003ull
69#define RES_LANE_INTENT 0x6140004ull
70#define RES_ROGUE 0x6140010ull
71#define RES_CYCLE 0x6140020ull
72#define LANES 16u
73/* What one lane claim holds while it is on the seat (its two windows). R5
74 * admits at most LANE_CAP of them at once; the rest wait. */
75#define LANE_BYTES (2u * RX_OBJECT_WINDOW)
76#define LANE_CAP 4u
77#define BUDGET 256u /* R6 activations per reaction per causal episode */
78#ifndef TARGET_PCT
79#define TARGET_PCT 55u
80#endif
81#define U(x) ((unsigned long long)(x))
82
83typedef struct {
84 int defect; /* RxOmegaDefect for scenario A */
85 uint32_t lanes; /* GPU work lanes (B, D, E) */
86 int oscillation; /* R6 oscillation limit in addition to the budget (C) */
87 int crash_step; /* R9 crash point (F, first process) */
88 int seat; /* start the resident GB10 seat (silicon build only) */
89 const char *gen_dir; /* reuse an R9 store (F restart); else a new one */
90 int goal_after_research; /* adapt(): the goal arrives only after the body's own
91 research of the new cores has selected (A semantic) */
92} Opts;
93
94typedef struct {
95 AienosCapAdmin *admin;
96 AienosCapView *view;
97 RxWorld w;
98 RxOmegaFaculty omega;
99 RxAienFaculty aien;
100 RxAegisFaculty aegis;
101 RxLiving living;
102 RxLivingPromoter promoter;
103 RxLivingKeyrings keys; /* R16 C6: runtime-issued caller credentials */
104 RxCallerKeyring fixtures; /* LANE, ROGUE and CYCLE: enrolled, not privileged */
105 RxGenStore *gen;
106 RxGpuSeat *seat;
107 Opts opt;
108 pthread_t acceptor;
109 atomic_int acceptor_stop, acceptor_pause, acceptor_error;
110 int acceptor_live;
111 atomic_ullong acc_ok, acc_stale, acc_torn, acc_auth, acc_other;
112 RxObjRef intent;
113 RxCapRef ext_request, ext_goal, ext_placement, ext_intent, ext_restore;
114 RxCapRef seat_input, seat_output;
115 uint32_t r_ask;
116 uint64_t request_seq, served, wrong, unpromoted_use;
117 pthread_t producer;
118 atomic_int producer_stop, producer_error;
119 int producer_live;
120 uint64_t minted;
121 char generation_dir[128];
122 int own_dir;
123 /* GPU lanes: in -> seat add -> out -> CPU check. Output WRITE is read from
124 * AEGIS client 1, slot 0. */
125 RxObjRef lin[LANES], lout[LANES], lchk[LANES], lane_intent;
126 uint32_t r_lane[LANES], r_check[LANES], r_lane_ask;
127 RxCapRef ext_lane, ext_lane_intent, lane_in_read;
128 uint64_t lane_sent[LANES];
129 uint64_t lane_intent_seq;
130 /* Everything the harness itself gave a hostile party, so the sweep can
131 * prove none of it is live at the end. */
132 RxCapRef hostile[32];
133 uint32_t n_hostile;
134} Rig;
135
136typedef struct { Rig *r; uint32_t k; } LaneCtx;
137static LaneCtx g_lane_ctx[LANES];
138
139static int g_stage;
140
141static uint64_t now_ns(void) {
142 struct timespec ts;
143 clock_gettime(CLOCK_MONOTONIC, &ts);
144 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
145}
146
147/* Busy wait without a system call: a 20 us sleep costs about 80 us on Linux. */
148static void spin_us(unsigned us) {
149 uint64_t until = now_ns() + (uint64_t)us * 1000u;
150 while (now_ns() < until) {
151#if defined(__aarch64__)
152 __asm__ volatile("yield");
153#endif
154 }
155}
156
157static void pause_us(int us) {
158 struct timespec ts = {us / 1000000, (long)(us % 1000000) * 1000L};
159 nanosleep(&ts, NULL);
160}
161
162static RxCapRef mint(Rig *r, uint32_t subject, uint64_t resource, uint32_t rights) {
163 AienosCapRef office, ref = {UINT32_MAX, 0};
164 aienos_cap_office(r->admin, &office);
165 AienosCapMint m = {ISSUER, subject, resource, rights, 0, {UINT32_MAX, 0}, office};
166 if (aienos_cap_mint(r->admin, &m, &ref) == 0) r->minted++;
167 return (RxCapRef){ref.cap_id, ref.generation};
168}
169
170static RxCapRef hostile(Rig *r, uint32_t subject, uint64_t resource, uint32_t rights) {
171 RxCapRef c = mint(r, subject, resource, rights);
172 if (r->n_hostile < 32) r->hostile[r->n_hostile++] = c;
173 return c;
174}
175
176static int cap_revoke(Rig *r, RxCapRef c) {
177 AienosCapRef office;
178 aienos_cap_office(r->admin, &office);
179 return aienos_cap_revoke(r->admin, office, (AienosCapRef){c.cap_id, c.generation});
180}
181
182static uint64_t field(Rig *r, RxObjRef ref, uint32_t i) {
183 RxObject o;
184 return rx_world_read(&r->w, ref, &o) == RX_OK ? o.field[i] : UINT64_MAX;
185}
186
187static const RxSnapshotDep *snapshot(RxCtx *c, RxObjRef ref) {
188 for (uint32_t i = 0; i < c->n_in; i++)
189 if (c->in[i].obj.id == ref.id) return &c->in[i];
190 return NULL;
191}
192
193static uint64_t acts(Rig *r, uint32_t id) { return r->w.reactions[id].activations; }
194
195/* Client intent becomes an R8 request through a reaction of that client.
196 * The rig's user pointer says which client. */
197typedef struct { Rig *r; RxObjRef intent, request; } Ask;
198static Ask g_ask[2];
199static int ask(RxCtx *c) {
200 Ask *a = c->user;
201 const RxSnapshotDep *in = snapshot(c, a->intent);
202 const RxSnapshotDep *out = snapshot(c, a->request);
203 if (!in || !out) return -1;
204 if (!in->field[0] || in->field[0] == out->field[0]) return 0;
205 for (uint32_t i = 0; i < 6; i++)
206 c->out[c->n_out++] = (RxMutation){a->request, i, in->field[i]};
207 return 0;
208}
209
210static int core_sets(cpu_set_t *a, cpu_set_t *x) {
211 CPU_ZERO(a); CPU_ZERO(x);
212 DIR *d = opendir("/sys/devices/system/cpu");
213 if (!d) return -1;
214 struct dirent *e;
215 int na = 0, nx = 0;
216 while ((e = readdir(d))) {
217 int cpu = -1;
218 if (sscanf(e->d_name, "cpu%d", &cpu) != 1 || cpu < 0 || cpu >= CPU_SETSIZE) continue;
219 char path[256];
220 snprintf(path, sizeof path,
221 "/sys/devices/system/cpu/cpu%d/regs/identification/midr_el1", cpu);
222 FILE *f = fopen(path, "r");
223 unsigned long long midr = 0;
224 if (!f) continue;
225 int ok = fscanf(f, "%llx", &midr);
226 fclose(f);
227 if (ok != 1) continue;
228 uint32_t part = (uint32_t)(midr >> 4) & 0xfffu;
229 if (part == CLASS_A725) { CPU_SET(cpu, a); na++; }
230 if (part == CLASS_X925) { CPU_SET(cpu, x); nx++; }
231 }
232 closedir(d);
233 return na && nx ? 0 : -1;
234}
235
236static int move_threads(const cpu_set_t *set) {
237 DIR *d = opendir("/proc/self/task");
238 if (!d) return -1;
239 struct dirent *e;
240 int moved = 0;
241 while ((e = readdir(d))) {
242 int tid = atoi(e->d_name);
243 if (tid > 0 && sched_setaffinity(tid, sizeof(*set), set) == 0) moved++;
244 }
245 closedir(d);
246 return moved;
247}
248
249static int new_object(Rig *r, uint32_t type, uint64_t resource, RxObjRef *out) {
250 uint64_t z[RX_MAX_FIELDS] = {0};
251 return rx_world_create(&r->w, type, RX_PERSIST_RESIDENT, resource, z, out);
252}
253
254/* ---- GPU lanes ------------------------------------------------------------
255 * Workload of the same kind as production, but on the seat: an outside lane
256 * request writes operands into lane.in[k]; lane.blackwell.k (R5 Blackwell
257 * need, LANE_BYTES held while claimed, output WRITE from an R8 slot) is
258 * executed by the resident seat; lane.check.k checks the sum on the CPU. */
259static int fn_lane_seat(RxCtx *c) { (void)c; return -1; }
260
261static int fn_lane_check(RxCtx *c) {
262 LaneCtx *lc = c->user;
263 Rig *r = lc->r;
264 uint32_t k = lc->k;
265 const RxSnapshotDep *in = snapshot(c, r->lin[k]);
266 const RxSnapshotDep *out = snapshot(c, r->lout[k]);
267 const RxSnapshotDep *chk = snapshot(c, r->lchk[k]);
268 if (!in || !out || !chk) return -1;
269 uint64_t expected = (uint32_t)((uint32_t)in->field[0] + (uint32_t)in->field[1]);
270 c->out[c->n_out++] = (RxMutation){r->lchk[k], 0, chk->field[0] + 1};
271 c->out[c->n_out++] = (RxMutation){r->lchk[k], 1, in->field[2]};
272 c->out[c->n_out++] = (RxMutation){r->lchk[k], 2, chk->field[2] + (out->field[0] != expected)};
273 c->out[c->n_out++] = (RxMutation){r->lchk[k], 3, out->field[0]};
274 return 0;
275}
276
277static int lanes_create(Rig *r) {
278 for (uint32_t k = 0; k < r->opt.lanes; k++) {
279 if (new_object(r, 0x6141, RES_LANE_IN, &r->lin[k]) != RX_OK ||
280 new_object(r, 0x6142, RES_LANE_OUT, &r->lout[k]) != RX_OK ||
281 new_object(r, 0x6143, RES_LANE_CHK, &r->lchk[k]) != RX_OK ||
282 rx_world_attach_physical(&r->w, r->lin[k]) != RX_OK ||
283 rx_world_attach_physical(&r->w, r->lout[k]) != RX_OK)
284 return -1;
285 }
286 return new_object(r, 0x6144, RES_LANE_INTENT, &r->lane_intent);
287}
288
289static int lanes_register(Rig *r) {
290 const uint32_t R = RX_RIGHT_READ, RW = RX_RIGHT_READ | RX_RIGHT_WRITE;
291 RxObjRef slot = r->aegis.o[1].slot[0];
292 r->lane_in_read = mint(r, LANE_SUBJ, RES_LANE_IN, R);
293 RxCapRef slot_read = mint(r, LANE_SUBJ, rx_aegis_res(1, RX_AEGIS_RES_SLOT0), R);
294 RxCapRef out_read = mint(r, LANE_SUBJ, RES_LANE_OUT, R);
295 RxCapRef chk_rw = mint(r, LANE_SUBJ, RES_LANE_CHK, RW);
296 for (uint32_t k = 0; k < r->opt.lanes; k++) {
297 g_lane_ctx[k] = (LaneCtx){r, k};
298 RxReactionDesc d;
299 memset(&d, 0, sizeof d);
300 d.name = "lane.blackwell";
301 d.faculty = RX_FACULTY_OMEGA;
302 d.subject = LANE_SUBJ;
303 d.priority = RX_PRIO_LEARNING;
304 d.fn = fn_lane_seat;
305 d.user = &g_lane_ctx[k];
306 d.need.accelerator_features = RX_ACCEL_BLACKWELL;
307 d.need.memory_bytes = LANE_BYTES;
308 d.n_triggers = 1;
309 d.triggers[0] = (RxDep){r->lin[k], RX_FIELD(0) | RX_FIELD(1)};
310 d.n_writes = 1;
311 d.writes[0] = (RxDep){r->lout[k], RX_FIELD(0)};
312 d.n_caps = 3;
313 d.caps[0] = (RxCapNeed){r->lane_in_read, RES_LANE_IN, R};
314 d.caps[1] = (RxCapNeed){{UINT32_MAX, 0}, RES_LANE_OUT, RX_RIGHT_WRITE};
315 d.caps[2] = (RxCapNeed){slot_read, rx_aegis_res(1, RX_AEGIS_RES_SLOT0), R};
316 rx_aegis_use_slot(&d, 1, slot);
317 if (rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, &r->r_lane[k]) != RX_OK) return -1;
318
319 memset(&d, 0, sizeof d);
320 d.name = "lane.check";
321 d.faculty = RX_FACULTY_OMEGA;
322 d.subject = LANE_SUBJ;
323 d.priority = RX_PRIO_LEARNING;
324 d.fn = fn_lane_check;
325 d.user = &g_lane_ctx[k];
326 d.n_triggers = 1;
327 d.triggers[0] = (RxDep){r->lout[k], RX_FIELD(0)};
328 d.n_reads = 2;
329 d.reads[0] = (RxDep){r->lin[k], RX_ALL_FIELDS};
330 d.reads[1] = (RxDep){r->lchk[k], RX_ALL_FIELDS};
331 d.n_writes = 1;
332 d.writes[0] = (RxDep){r->lchk[k], RX_ALL_FIELDS};
333 d.n_caps = 3;
334 d.caps[0] = (RxCapNeed){out_read, RES_LANE_OUT, R};
335 d.caps[1] = (RxCapNeed){r->lane_in_read, RES_LANE_IN, R};
336 d.caps[2] = (RxCapNeed){chk_rw, RES_LANE_CHK, RW};
337 if (rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, &r->r_check[k]) != RX_OK) return -1;
338 }
339 return 0;
340}
341
342/* The lane client asks AEGIS for its output grant, as the R13 seat does. */
343static int lane_acquire(Rig *r) {
344 RxMutation m[6] = {{r->lane_intent, 0, ++r->lane_intent_seq},
345 {r->lane_intent, 1, RES_LANE_OUT},
346 {r->lane_intent, 2, RX_RIGHT_READ | RX_RIGHT_WRITE},
347 {r->lane_intent, 3, 0}, {r->lane_intent, 4, 0},
348 {r->lane_intent, 5, RX_AEGIS_OP_ACQUIRE}};
349 return rx_world_publish_external(&r->w, r->ext_lane_intent, m, 6) > 0 ? 0 : -1;
350}
351
352/* One lane request: operands chosen so consecutive sums differ. */
353static int lane_submit(Rig *r, uint32_t k) {
354 uint64_t j = ++r->lane_sent[k];
355 RxMutation m[3] = {{r->lin[k], 0, 0xfffff000u + j * 7u + k},
356 {r->lin[k], 1, 0x1000u + k}, {r->lin[k], 2, j}};
357 if (rx_world_publish_external(&r->w, r->ext_lane, m, 3) <= 0) {
358 r->lane_sent[k]--;
359 return -1;
360 }
361 return 0;
362}
363
364static uint64_t lane_done(Rig *r, uint32_t k) { return field(r, r->lchk[k], 1); }
365
366/* The R13 body, as tests/runtime/rx_r13_living.c starts it, with R6 switched
367 * on (an activation budget per causal episode), the restart reaction, and
368 * optionally the GPU lanes on a second AEGIS client. */
369static int start(Rig *r, const Opts *opt) {
370 memset(r, 0, sizeof *r);
371 r->opt = *opt;
372 g_stage = 1;
373 if (aienos_cap_start(&r->admin, &r->view) != 0) return -1;
374 if (rx_world_init_native(&r->w, r->view, 4, RX_CRUMBS_LONG_EPISODE) != RX_OK) return -1;
375 r->w.external_subject = EXTERNAL;
376 /* R16 C6: every subject that registers gets a runtime-issued credential
377 * (the rogue too: it is an enrolled in-process party whose capabilities
378 * are forged), then the world refuses registrations without one. */
379 if (rx_living_enroll_callers(&r->w, &r->keys) != RX_OK) return -1;
380 {
381 const uint32_t extra[] = {LANE_SUBJ, ROGUE_SUBJ, CYCLE_SUBJ};
382 for (uint32_t i = 0; i < 3; i++) {
383 if (rx_world_enroll_caller(&r->w, extra[i], &r->fixtures.cred[i]) != RX_CALLER_OK)
384 return -1;
385 r->fixtures.subject[i] = extra[i];
386 }
387 r->fixtures.n = 3;
388 }
389 if (rx_world_bind_callers(&r->w) != RX_OK) return -1;
390 if (opt->gen_dir) {
391 snprintf(r->generation_dir, sizeof r->generation_dir, "%s", opt->gen_dir);
392 } else {
393 if (!mkdtemp(strcpy(r->generation_dir, "/tmp/r14-living-XXXXXX"))) return -1;
394 r->own_dir = 1;
395 }
396 if (rx_gen_open(r->generation_dir, &r->gen) != RX_GEN_OK) return -1;
397 if (opt->crash_step) rx_gen_set_crash(r->gen, opt->crash_step);
398 if (rx_gen_bind_authority(r->gen, rx_world_caller_check_fn, &r->w,
399 rx_living_native_authority, r->view) != RX_GEN_OK) return -1;
400 RxStabilityBudget sb;
401 memset(&sb, 0, sizeof sb);
402 sb.activation_budget = BUDGET;
403 sb.oscillation_limit = (uint32_t)opt->oscillation;
404 rx_world_set_stability(&r->w, &sb);
405 g_stage = 2;
406 const uint32_t R = RX_RIGHT_READ, RW = RX_RIGHT_READ | RX_RIGHT_WRITE;
407 RxOmegaConfig oc;
408 rx_omega_default_config(&oc);
409 oc.hot_calls = 64; oc.hot_ns = 200000; oc.margin_pct = 10;
410 oc.defect = (RxOmegaDefect)opt->defect;
411 if (rx_omega_create_objects(&r->omega, &r->w, &oc) != RX_OK) return -1;
412 r->omega.keys = &r->keys.omega;
413 RxAienConfig ac;
414 rx_aien_default_config(&ac);
415 RxAienInputs ai = {r->omega.o.demand, r->omega.o.selection};
416 if (rx_aien_create_objects(&r->aien, &r->w, &ac, &ai) != RX_OK) return -1;
417 r->aien.keys = &r->keys.aien;
418 if (rx_living_create(&r->living, &r->w, &r->aien, &r->omega, r->gen, r->view) != RX_OK)
419 return -1;
420 r->living.keys = &r->keys.living;
421 if (new_object(r, 0x6135, RES_INTENT, &r->intent) != RX_OK) return -1;
422 if (opt->lanes && lanes_create(r) != 0) return -1;
423
424 /* R8: client 0 is the R13 experiment seat, client 1 the GPU lanes. */
425 RxAegisPolicy pol;
426 memset(&pol, 0, sizeof pol);
427 pol.n_rules = 2;
428 pol.rules[0] = (RxAegisRule){1, RX_LIVING_SEAT_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT,
429 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, RW, 0, 0};
430 pol.rules[1] = (RxAegisRule){2, LANE_SUBJ, RES_LANE_OUT, RES_LANE_OUT, RW, 0, 0};
431 RxAegisClient cl[2] = {
432 {RX_LIVING_SEAT_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT,
433 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, RW},
434 {LANE_SUBJ, RES_LANE_OUT, RES_LANE_OUT, RW}};
435 uint32_t n_clients = opt->lanes ? 2u : 1u;
436 if (rx_aegis_create(&r->aegis, &r->w, r->admin, &pol, cl, n_clients) != RX_OK) return -1;
437 r->aegis.keys = &r->keys.aegis;
438 RxAegisCaps aeg[2];
439 memset(aeg, 0, sizeof aeg);
440 for (uint32_t k = 0; k < n_clients; k++) {
441 aeg[k].aegis_request = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(k, RX_AEGIS_RES_REQUEST), R);
442 aeg[k].aegis_approval = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(k, RX_AEGIS_RES_APPROVAL), R);
443 aeg[k].aegis_decision = mint(r, RX_AEGIS_SUBJ, rx_aegis_res(k, RX_AEGIS_RES_DECISION), RW);
444 aeg[k].root_request = mint(r, RX_AEGIS_ROOT_SUBJ, rx_aegis_res(k, RX_AEGIS_RES_REQUEST), R);
445 aeg[k].root_decision = mint(r, RX_AEGIS_ROOT_SUBJ, rx_aegis_res(k, RX_AEGIS_RES_DECISION), R);
446 for (uint32_t j = 0; j < RX_AEGIS_SLOTS; j++)
447 aeg[k].root_slot[j] = mint(r, RX_AEGIS_ROOT_SUBJ,
448 rx_aegis_res(k, RX_AEGIS_RES_SLOT0 + j), RW);
449 }
450 if (rx_aegis_register(&r->aegis, aeg) != RX_OK) return -1;
451 g_stage = 3;
452
453 RxOmegaCaps omega;
454 memset(&omega, 0xff, sizeof omega);
455 omega.serve[RX_OMEGA_RES_REQUEST] = mint(r, RX_OMEGA_SUBJ_SERVE,
456 RX_OMEGA_RES_BASE + RX_OMEGA_RES_REQUEST, R);
457 omega.serve[RX_OMEGA_RES_SELECTION] = mint(r, RX_OMEGA_SUBJ_SERVE,
458 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
459 omega.serve[RX_OMEGA_RES_DEMAND] = mint(r, RX_OMEGA_SUBJ_SERVE,
460 RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, RW);
461 omega.serve[RX_OMEGA_RES_RESULT] = mint(r, RX_OMEGA_SUBJ_SERVE,
462 RX_OMEGA_RES_BASE + RX_OMEGA_RES_RESULT, RW);
463 omega.omega[RX_OMEGA_RES_DEMAND] = mint(r, RX_OMEGA_SUBJ_OMEGA,
464 RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, R);
465 omega.omega[RX_OMEGA_RES_SEARCH] = mint(r, RX_OMEGA_SUBJ_OMEGA,
466 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, RW);
467 omega.omega[RX_OMEGA_RES_SELECTION] = mint(r, RX_OMEGA_SUBJ_OMEGA,
468 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, RW);
469 for (uint32_t k = 0; k < r->omega.cfg.n_slots; k++) {
470 uint32_t idx[3] = {RX_OMEGA_RES_CANDIDATE0 + k, RX_OMEGA_RES_VERDICT0 + k,
471 RX_OMEGA_RES_MEASURE0 + k};
472 for (uint32_t j = 0; j < 3; j++)
473 omega.omega[idx[j]] = mint(r, RX_OMEGA_SUBJ_OMEGA, RX_OMEGA_RES_BASE + idx[j], RW);
474 }
475 RxCapRef omega_belief = mint(r, RX_OMEGA_SUBJ_OMEGA,
476 RX_AIEN_RES_BASE + RX_AIEN_RES_EXPERIMENT_BELIEF, R);
477 if (rx_omega_require_evidence(&r->omega, r->aien.o.experiment_belief, omega_belief) != RX_OK)
478 return -1;
479 if (rx_omega_serve_from(&r->omega, r->living.o.inforce, mint(r, RX_OMEGA_SUBJ_SERVE,
480 RX_LIVING_RES_BASE + RX_LIVING_RES_INFORCE, R)) != RX_OK) return -1;
481 if (rx_omega_register(&r->omega, &omega) != RX_OK) return -1;
482 g_stage = 4;
483
484 RxAienCaps aien;
485 memset(&aien, 0xff, sizeof aien);
486 for (uint32_t i = 0; i < RX_AIEN_RES_COUNT; i++)
487 aien.own[i] = mint(r, RX_AIEN_SUBJ, RX_AIEN_RES_BASE + i,
488 i == RX_AIEN_RES_PLACEMENT || i == RX_AIEN_RES_GOAL ? R : RW);
489 aien.demand = mint(r, RX_AIEN_SUBJ, RX_OMEGA_RES_BASE + RX_OMEGA_RES_DEMAND, R);
490 aien.selection = mint(r, RX_AIEN_SUBJ, RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
491 if (rx_aien_register(&r->aien, &aien) != RX_OK) return -1;
492 if (rx_aien_register_experiment(&r->aien, r->living.o.evidence,
493 mint(r, RX_AIEN_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, R),
494 aien.own[RX_AIEN_RES_EXPERIMENT_BELIEF]) != RX_OK) return -1;
495 if (rx_omega_register_reconsider(&r->omega, r->aien.o.plan,
496 mint(r, RX_OMEGA_SUBJ_OMEGA, RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R),
497 omega.omega[RX_OMEGA_RES_SEARCH], omega.omega[RX_OMEGA_RES_SELECTION]) != RX_OK)
498 return -1;
499 g_stage = 5;
500
501 RxLivingCaps lc;
502 memset(&lc, 0, sizeof lc);
503 lc.plan_read = mint(r, RX_LIVING_SUBJ, RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R);
504 lc.search_read = mint(r, RX_LIVING_SUBJ, RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, R);
505 lc.input_write = mint(r, RX_LIVING_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_INPUT, RW);
506 lc.input_seat_read = mint(r, RX_LIVING_SEAT_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_INPUT, R);
507 lc.output_read = mint(r, RX_LIVING_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, R);
508 lc.evidence_write = mint(r, RX_LIVING_SUBJ, RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, RW);
509 lc.belief_read = mint(r, RX_LIVING_PREPARE_SUBJ,
510 RX_AIEN_RES_BASE + RX_AIEN_RES_EXPERIMENT_BELIEF, R);
511 lc.selection_read = mint(r, RX_LIVING_PREPARE_SUBJ,
512 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SELECTION, R);
513 lc.evidence_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
514 RX_LIVING_RES_BASE + RX_LIVING_RES_EVIDENCE, R);
515 lc.candidate_write = mint(r, RX_LIVING_PREPARE_SUBJ,
516 RX_LIVING_RES_BASE + RX_LIVING_RES_CANDIDATE, RW);
517 lc.goal_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ, RX_AIEN_RES_BASE + RX_AIEN_RES_GOAL, R);
518 lc.plan_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ, RX_AIEN_RES_BASE + RX_AIEN_RES_PLAN, R);
519 lc.search_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
520 RX_OMEGA_RES_BASE + RX_OMEGA_RES_SEARCH, R);
521 lc.output_prepare_read = mint(r, RX_LIVING_PREPARE_SUBJ,
522 RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT, R);
523 r->promoter.world = &r->w;
524 r->promoter.keys = &r->keys.promoter;
525 r->promoter.store = r->gen;
526 r->promoter.authority = r->view;
527 r->promoter.candidate = r->living.o.candidate;
528 r->promoter.promotion = r->living.o.promotion;
529 r->promoter.inforce = r->living.o.inforce;
530 r->promoter.candidate_read = mint(r, RX_LIVING_PROMOTE_SUBJ,
531 RX_LIVING_RES_BASE + RX_LIVING_RES_CANDIDATE, R);
532 r->promoter.promotion_write = mint(r, RX_LIVING_PROMOTE_SUBJ,
533 RX_LIVING_RES_BASE + RX_LIVING_RES_PROMOTION, RW);
534 r->promoter.inforce_write = mint(r, RX_LIVING_PROMOTE_SUBJ,
535 RX_LIVING_RES_BASE + RX_LIVING_RES_INFORCE, RW);
536 r->promoter.promotion_authority = mint(r, RX_LIVING_PROMOTE_SUBJ,
537 RX_GEN_RES_PROMOTION, RX_GEN_RIGHT_PROMOTE);
538 lc.output_slot = r->aegis.o[0].slot[0];
539 lc.output_slot_read = mint(r, RX_LIVING_SEAT_SUBJ, rx_aegis_res(0, RX_AEGIS_RES_SLOT0), R);
540
541 /* R8 acquisition before any episode: the seat's grant, and the lanes'. */
542 r->ext_intent = mint(r, EXTERNAL, RES_INTENT, RX_RIGHT_WRITE);
543 uint32_t n_ask = opt->lanes ? 2u : 1u;
544 for (uint32_t k = 0; k < n_ask; k++) {
545 uint32_t subj = k ? LANE_SUBJ : RX_LIVING_SEAT_SUBJ;
546 uint64_t res_in = k ? RES_LANE_INTENT : RES_INTENT;
547 g_ask[k] = (Ask){r, k ? r->lane_intent : r->intent, r->aegis.o[k].request};
548 RxReactionDesc d;
549 memset(&d, 0, sizeof d);
550 d.name = k ? "lane.ask" : "living.experiment.ask";
551 d.faculty = RX_FACULTY_OMEGA;
552 d.subject = subj;
553 d.priority = RX_PRIO_FOREGROUND;
554 d.fn = ask; d.user = &g_ask[k]; d.stamp_proposed = true;
555 d.n_triggers = 1;
556 d.triggers[0] = (RxDep){g_ask[k].intent, RX_ALL_FIELDS};
557 d.n_reads = 1;
558 d.reads[0] = (RxDep){g_ask[k].request, RX_ALL_FIELDS};
559 d.n_writes = 1;
560 d.writes[0] = (RxDep){g_ask[k].request, RX_ALL_FIELDS};
561 d.n_caps = 2;
562 d.caps[0] = (RxCapNeed){mint(r, subj, res_in, R), res_in, R};
563 d.caps[1] = (RxCapNeed){mint(r, subj, rx_aegis_res(k, RX_AEGIS_RES_REQUEST), RW),
564 rx_aegis_res(k, RX_AEGIS_RES_REQUEST), RW};
565 if (rx_world_add_reaction_keyed(&r->w, k ? &r->fixtures : &r->keys.living, &d,
566 k ? &r->r_lane_ask : &r->r_ask) != RX_OK) return -1;
567 }
568 RxMutation request[6] = {{r->intent, 0, 1},
569 {r->intent, 1, RX_LIVING_RES_BASE + RX_LIVING_RES_OUTPUT},
570 {r->intent, 2, RW}, {r->intent, 3, 0}, {r->intent, 4, 0},
571 {r->intent, 5, RX_AEGIS_OP_ACQUIRE}};
572 if (rx_world_publish_external(&r->w, r->ext_intent, request, 6) <= 0) return -1;
573 if (opt->lanes) {
574 r->ext_lane_intent = mint(r, EXTERNAL, RES_LANE_INTENT, RX_RIGHT_WRITE);
575 if (lane_acquire(r) != 0) return -1;
576 }
577 if (rx_world_wait_quiescent(&r->w, 10000) != RX_OK) return -1;
578 r->seat_output = (RxCapRef){field(r, lc.output_slot, 0), field(r, lc.output_slot, 1)};
579 r->seat_input = lc.input_seat_read;
580 if (field(r, lc.output_slot, 2) != RX_AEGIS_SLOT_LIVE) return -1;
581 if (opt->lanes && field(r, r->aegis.o[1].slot[0], 2) != RX_AEGIS_SLOT_LIVE) return -1;
582 g_stage = 6;
583 if (rx_world_bind_capability(&r->w, r->living.o.input, r->seat_input) != RX_OK ||
584 rx_world_bind_capability(&r->w, r->living.o.output, r->seat_output) != RX_OK)
585 return -1;
586 if (rx_world_enable_resident(&r->w) != RX_OK) return -1;
587 if (rx_living_register(&r->living, &lc, &r->promoter) != RX_OK) return -1;
588 if (rx_living_register_restore(&r->living, &r->promoter, mint(r, RX_LIVING_PROMOTE_SUBJ,
589 RX_LIVING_RES_BASE + RX_LIVING_RES_RESTORE, RW)) != RX_OK) return -1;
590 r->ext_restore = mint(r, EXTERNAL, RX_LIVING_RES_BASE + RX_LIVING_RES_RESTORE, RX_RIGHT_WRITE);
591 if (opt->lanes) {
592 if (lanes_register(r) != 0) return -1;
593 for (uint32_t k = 0; k < opt->lanes; k++)
594 if (rx_world_bind_capability(&r->w, r->lin[k], r->lane_in_read) != RX_OK) return -1;
595 r->ext_lane = mint(r, EXTERNAL, RES_LANE_IN, RX_RIGHT_WRITE);
596 }
597 RxResourceBudget budget;
598 memset(&budget, 0, sizeof budget);
599 budget.slots = 8;
600 budget.memory_bytes = opt->lanes ? (uint64_t)LANE_CAP * LANE_BYTES : UINT64_MAX;
601 budget.energy_budget = UINT64_MAX;
602 budget.offered_locality = UINT32_MAX;
603 budget.offered_accel = RX_ACCEL_BLACKWELL;
604 budget.compute_mask = UINT32_MAX;
605 rx_world_set_resources(&r->w, &budget);
606 r->ext_request = mint(r, EXTERNAL, RX_OMEGA_RES_BASE + RX_OMEGA_RES_REQUEST, RX_RIGHT_WRITE);
607 r->ext_goal = mint(r, EXTERNAL, RX_AIEN_RES_BASE + RX_AIEN_RES_GOAL, RX_RIGHT_WRITE);
608 r->ext_placement = mint(r, EXTERNAL, RX_AIEN_RES_BASE + RX_AIEN_RES_PLACEMENT, RX_RIGHT_WRITE);
609#ifdef R14_SILICON
610 if (opt->seat && (rx_gpu_seat_begin(&r->w, &r->seat) != 0 || !r->seat)) return -1;
611#endif
612 g_stage = 7;
613 return 0;
614}
615
616/* ---- production and transport -------------------------------------------- */
617
618static uint64_t expected_digest(uint64_t seed) {
619 uint64_t *A = malloc((size_t)M * N * sizeof(uint64_t));
620 uint64_t *x = malloc((size_t)N * sizeof(uint64_t));
621 uint64_t *y = malloc((size_t)M * sizeof(uint64_t));
622 if (!A || !x || !y) { free(A); free(x); free(y); return 0; }
623 rx_omega_fill(seed, A, x, M, N);
624 omega_matvec_reference(A, x, y, M, N);
625 uint64_t result = rx_omega_digest(y, M);
626 free(A); free(x); free(y);
627 return result;
628}
629
630/* One ordinary production request; the harness publishes it and reads the
631 * result, and never touches a faculty. */
632static int serve(Rig *r) {
633 uint64_t seq = ++r->request_seq;
634 uint64_t seed = seq * 0x2545F4914F6CDD1Dull;
635 RxMutation m[4] = {{r->omega.o.request, 0, seq}, {r->omega.o.request, 1, M},
636 {r->omega.o.request, 2, N}, {r->omega.o.request, 3, seed}};
637 if (rx_world_publish_external(&r->w, r->ext_request, m, 4) <= 0) return -1;
638 uint64_t t = now_ns();
639 while (field(r, r->omega.o.result, 0) != seq) {
640 if (now_ns() - t > 10000000000ull) return -1;
641 spin_us(5);
642 }
643 if (field(r, r->omega.o.result, 1) != expected_digest(seed)) r->wrong++;
644 uint64_t used = field(r, r->omega.o.result, 2);
645 if (used != 0 && (field(r, r->living.o.inforce, 0) == 0 ||
646 field(r, r->living.o.inforce, 1) != used))
647 r->unpromoted_use++;
648 __atomic_add_fetch(&r->served, 1, __ATOMIC_RELAXED);
649 return 0;
650}
651
652static uint64_t served(Rig *r) { return __atomic_load_n(&r->served, __ATOMIC_RELAXED); }
653
654static void *producer_main(void *arg) {
655 Rig *r = arg;
656 while (!atomic_load(&r->producer_stop))
657 if (serve(r) != 0) { atomic_store(&r->producer_error, 1); break; }
658 return NULL;
659}
660
661static int start_producer(Rig *r) {
662 if (r->producer_live) return 0;
663 atomic_store(&r->producer_stop, 0);
664 if (pthread_create(&r->producer, NULL, producer_main, r) != 0) return -1;
665 r->producer_live = 1;
666 return 0;
667}
668
669static void stop_producer(Rig *r) {
670 if (!r->producer_live) return;
671 atomic_store(&r->producer_stop, 1);
672 pthread_join(r->producer, NULL);
673 r->producer_live = 0;
674}
675
676/* Production continues for n more correct results. */
677static int produce(Rig *r, uint64_t n, uint64_t timeout_ms) {
678 uint64_t until = served(r) + n, t = now_ns();
679 while (served(r) < until) {
680 if (atomic_load(&r->producer_error)) return -1;
681 if (now_ns() - t > timeout_ms * 1000000ull) return -1;
682 pause_us(200);
683 }
684 return 0;
685}
686
687/* Ring transport only: accept the seat's completion notices into the world.
688 * It decides nothing. Every refusal is tallied by its reason. */
689static void tally(Rig *r, int rc) {
690 if (rc == RX_OK) atomic_fetch_add(&r->acc_ok, 1);
691 else if (rc == RX_ERR_STALE_GEN) atomic_fetch_add(&r->acc_stale, 1);
692 else if (rc == RX_ERR_TORN) atomic_fetch_add(&r->acc_torn, 1);
693 else if (rc == RX_ERR_AUTHORITY) atomic_fetch_add(&r->acc_auth, 1);
694 else if (rc != RX_ERR_NOT_FOUND) atomic_fetch_add(&r->acc_other, 1);
695}
696
697static void progress(Rig *r) {
698#ifdef R14_SILICON
699 for (int i = 0; i < 64; i++) {
700 int rc = rx_resident_accept(&r->w);
701 if (rc == RX_ERR_NOT_FOUND) break;
702 tally(r, rc);
703 }
704#else
705 for (int i = 0; i < 64; i++) {
706 int rc = rx_resident_seat_step(&r->w);
707 if (rc == 0) break;
708 if (rc == 1) tally(r, rx_resident_accept(&r->w));
709 else if (rc < 0) tally(r, rx_resident_accept(&r->w));
710 else break;
711 }
712#endif
713}
714
715static void *acceptor_main(void *arg) {
716 Rig *r = arg;
717 while (!atomic_load(&r->acceptor_stop)) {
718 if (!atomic_load(&r->acceptor_pause)) progress(r);
719 pause_us(200);
720 }
721 return NULL;
722}
723
724static int start_acceptor(Rig *r) {
725 if (r->acceptor_live) return 0;
726 atomic_store(&r->acceptor_stop, 0);
727 if (pthread_create(&r->acceptor, NULL, acceptor_main, r) != 0) return -1;
728 r->acceptor_live = 1;
729 return 0;
730}
731
732static void stop_acceptor(Rig *r) {
733 if (!r->acceptor_live) return;
734 atomic_store(&r->acceptor_stop, 1);
735 pthread_join(r->acceptor, NULL);
736 r->acceptor_live = 0;
737}
738
739static int publish_placement(Rig *r, uint64_t cls) {
740 RxMutation m[2] = {{r->aien.o.placement, 0, field(r, r->aien.o.placement, 0) + 1},
741 {r->aien.o.placement, 1, cls}};
742 return rx_world_publish_external(&r->w, r->ext_placement, m, 2) > 0 ? 0 : -1;
743}
744
745static int publish_goal(Rig *r, uint64_t target) {
746 RxMutation m[3] = {{r->aien.o.goal, 0, field(r, r->aien.o.goal, 0) + 1},
747 {r->aien.o.goal, 1, rx_omega_regime(M, N)}, {r->aien.o.goal, 2, target}};
748 return rx_world_publish_external(&r->w, r->ext_goal, m, 3) > 0 ? 0 : -1;
749}
750
751/* The body started: the one outside event generation.restore answers. */
752static int64_t publish_boot(Rig *r) {
753 RxMutation m = {r->living.o.restore, 0, field(r, r->living.o.restore, 0) + 1};
754 return rx_world_publish_external(&r->w, r->ext_restore, &m, 1);
755}
756
757static void stop(Rig *r) {
758 stop_producer(r);
759 stop_acceptor(r);
760#ifdef R14_SILICON
761 if (r->seat) {
762 (void)rx_resident_shutdown(&r->w);
763 (void)rx_gpu_seat_finish(r->seat);
764 r->seat = NULL;
765 }
766#endif
767 rx_world_destroy(&r->w);
768 rx_aegis_destroy(&r->aegis);
769 rx_omega_destroy(&r->omega);
770 rx_gen_close(r->gen);
771 aienos_cap_stop(r->admin, r->view);
772 if (r->own_dir) {
773 char cmd[200];
774 snprintf(cmd, sizeof cmd, "rm -rf '%s'", r->generation_dir);
775 if (system(cmd) != 0) fprintf(stderr, "could not remove %s\n", r->generation_dir);
776 }
777}
778
779/* ---- audits ---------------------------------------------------------------- */
780
781/* Every capability the authority holds. Only the promotion subject holds the
782 * promotion right; no faculty, lane, seat, experiment, hostile or outside
783 * subject holds a privileged right; nothing the harness gave a hostile party
784 * is still live. */
785static int authority_sweep(Rig *r, uint64_t *swept, uint64_t *holders, uint64_t *unexpected) {
786 const uint32_t unprivileged[] = {RX_AIEN_SUBJ, RX_OMEGA_SUBJ_SERVE, RX_OMEGA_SUBJ_OMEGA,
787 RX_LIVING_SUBJ, RX_LIVING_SEAT_SUBJ, RX_LIVING_PREPARE_SUBJ, RX_AEGIS_SUBJ, EXTERNAL,
788 LANE_SUBJ, ROGUE_SUBJ, STUFFER_SUBJ, CYCLE_SUBJ};
789 AienosCapRef office;
790 if (aienos_cap_office(r->admin, &office) != 0) return -4;
791 *swept = 0; *holders = 0; *unexpected = 0;
792 for (uint32_t id = 1; id < 2048; id++)
793 for (uint64_t gen = office.generation; gen < office.generation + 8; gen++) {
794 AienosCapEntry e;
795 if (aienos_cap_inspect(r->view, (AienosCapRef){id, gen}, &e) != 0) continue;
796 if (e.state != 1u) continue; /* AIENOS_CAP_STATE_LIVE */
797 (*swept)++;
798 if ((e.rights & RX_RIGHT_PROMOTE) || e.resource == RX_GEN_RES_PROMOTION) {
799 if (e.subject != RX_LIVING_PROMOTE_SUBJ || e.rights != RX_GEN_RIGHT_PROMOTE)
800 (*unexpected)++;
801 else (*holders)++;
802 }
803 for (uint32_t i = 0; i < sizeof unprivileged / sizeof unprivileged[0]; i++)
804 if (e.subject == unprivileged[i] && (e.rights & RX_RIGHT_PRIVILEGED))
805 (*unexpected)++;
806 if (e.subject == RX_LIVING_PROMOTE_SUBJ &&
807 (e.rights & RX_RIGHT_PRIVILEGED & ~RX_RIGHT_PROMOTE))
808 (*unexpected)++;
809 }
810 for (uint32_t i = 0; i < r->n_hostile; i++) {
811 AienosCapEntry e;
812 if (aienos_cap_inspect(r->view, (AienosCapRef){r->hostile[i].cap_id,
813 r->hostile[i].generation}, &e) == 0 && e.state == 1u)
814 (*unexpected)++;
815 }
816 return *unexpected == 0 && *holders == 1 ? 0 : -1;
817}
818
819/* No claim outstanding, no charge held, every claim ended exactly once. */
820typedef struct {
821 uint64_t claims, closed, failed_seat, committed_seat, inflight, used_slots, used_memory;
822 uint64_t holding, blocked_peak;
823 int ok;
824} Accounting;
825
826static void account(Rig *r, Accounting *a) {
827 memset(a, 0, sizeof *a);
828 pthread_mutex_lock(&r->w.mu);
829 a->claims = r->w.stats.resident_claims;
830 a->closed = r->w.stats.resident_closed;
831 a->used_slots = r->w.used_slots;
832 a->used_memory = r->w.used_memory;
833 a->blocked_peak = r->w.peak_blocked;
834 for (uint32_t i = 0; i < r->w.n_reactions; i++) {
835 const RxReaction *x = &r->w.reactions[i];
836 if (x->resident_seat) a->inflight++;
837 if (x->holding) a->holding++;
838 }
839 for (uint64_t id = 1; id <= r->w.n_crumbs; id++) {
840 const RxCrumb *k = &r->w.crumbs[id - 1];
841 if (k->worker != RX_SEAT_BLACKWELL) continue;
842 if (k->kind == RX_CRUMB_COMMIT) a->committed_seat++;
843 else a->failed_seat++;
844 }
845 pthread_mutex_unlock(&r->w.mu);
846 a->ok = a->claims == a->closed && a->claims == a->committed_seat + a->failed_seat &&
847 a->inflight == 0 && a->used_slots == 0 && a->used_memory == 0 && a->holding == 0;
848}
849
850/* Is `wanted` a causal ancestor of (or equal to) `node`? */
851static uint8_t *g_seen;
852static uint64_t *g_stack;
853#define CRUMBS (1u << 18)
854/* The visited set and stack grow with the causal log. */
855static uint64_t g_seen_cap;
856static int seen_fit(uint64_t n) {
857 if (n + 1 <= g_seen_cap) return 0;
858 uint64_t cap = g_seen_cap ? g_seen_cap : 1024;
859 while (cap < n + 1) cap *= 2;
860 uint8_t *s = realloc(g_seen, (size_t)cap);
861 if (!s) return -1;
862 g_seen = s;
863 uint64_t *k = realloc(g_stack, sizeof(uint64_t) * (size_t)cap);
864 if (!k) return -1;
865 g_stack = k;
866 g_seen_cap = cap;
867 return 0;
868}
869static int ancestor(RxWorld *w, uint64_t node, uint64_t wanted) {
870 if (!node || !wanted || wanted > node || node > w->n_crumbs) return 0;
871 if (node == wanted) return 1;
872 if (seen_fit(w->n_crumbs) != 0) return 0;
873 memset(g_seen, 0, (size_t)w->n_crumbs + 1);
874 uint64_t sp = 0;
875 g_stack[sp++] = node;
876 g_seen[node] = 1;
877 while (sp) {
878 const RxCrumb *c = rx_world_crumb(w, g_stack[--sp]);
879 if (!c) continue;
880 for (uint32_t i = 0; i < c->n_parents; i++) {
881 uint64_t p = c->parents[i];
882 if (p == wanted) return 1;
883 if (p < wanted || p > w->n_crumbs || g_seen[p]) continue;
884 g_seen[p] = 1;
885 g_stack[sp++] = p;
886 }
887 }
888 return 0;
889}
890
891static uint64_t crumbs_of(Rig *r, uint32_t reaction, RxCrumbKind kind, int reason,
892 uint64_t after, uint64_t *last) {
893 uint64_t n = 0;
894 for (uint64_t id = after + 1; id <= r->w.n_crumbs; id++) {
895 const RxCrumb *k = rx_world_crumb(&r->w, id);
896 if (k->reaction != reaction || k->kind != kind) continue;
897 if (reason && k->reason != reason) continue;
898 n++;
899 if (last) *last = id;
900 }
901 return n;
902}
903
904/* ---- the living body -------------------------------------------------------
905 * R13's episode: production confirms the incumbent on the A725 cores, the
906 * body moves to the X925 cores, a human goal arrives, and the organism adapts
907 * by itself (plan, search, GPU experiment, belief, selection, R9 promotion).
908 * Production runs on its own thread from the move on and keeps running. The
909 * body also researches the new core class on its own, with no goal yet
910 * (AIEN's core-class hypothesis): with goal_after_research the goal is
911 * published only after that research has selected, so a selection older
912 * than the goal must still be proposed and promoted. */
913typedef struct {
914 uint64_t goal_crumb, served_at_move, served_at_promotion, gen_before, gen_after;
915 uint64_t promotion_crumb;
916 int promoted;
917} Episode;
918
919static int adapt(Rig *r, Episode *ep) {
920 memset(ep, 0, sizeof *ep);
921 cpu_set_t a, x;
922 if (core_sets(&a, &x) != 0 || move_threads(&a) <= 0) return -1;
923 if (field(r, r->aien.o.placement, 1) != CLASS_A725 && publish_placement(r, CLASS_A725) != 0)
924 return -2;
925 if (start_acceptor(r) != 0) return -3;
926 uint64_t limit = now_ns() + 60000000000ull;
927 while ((field(r, r->omega.o.selection, 0) < 1 ||
928 field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED) && now_ns() < limit)
929 if (serve(r) != 0) return -4;
930 if (field(r, r->aien.o.prediction, 6) != RX_AIEN_PRED_CONFIRMED) return -5;
931 uint64_t target = field(r, r->aien.o.prediction, 5) * TARGET_PCT / 100u;
932 uint64_t lineage = 0;
933 rx_gen_active(r->gen, &ep->gen_before, &lineage);
934 if (start_producer(r) != 0) return -6;
935 uint64_t sel_before = field(r, r->omega.o.selection, 0);
936 uint64_t declined_before = __atomic_load_n(&r->living.refusals, __ATOMIC_ACQUIRE);
937 if (move_threads(&x) <= 0 || publish_placement(r, CLASS_X925) != 0) return -7;
938 /* Production is counted from the move on, as before the goal was made
939 * late: every refusal (the late-goal decline included) comes after it. */
940 ep->served_at_move = served(r);
941 if (r->opt.goal_after_research) {
942 /* The body researches the new core class by itself, selects, and
943 * generation.prepare declines that selection for want of a goal. The
944 * goal is published only after that decline has been recorded. */
945 limit = now_ns() + 60000000000ull;
946 while (now_ns() < limit &&
947 (field(r, r->omega.o.selection, 0) <= sel_before ||
948 __atomic_load_n(&r->living.refusals, __ATOMIC_ACQUIRE) <= declined_before)) {
949 if (atomic_load(&r->producer_error)) return -9;
950 pause_us(200);
951 }
952 if (field(r, r->omega.o.selection, 0) <= sel_before ||
953 __atomic_load_n(&r->living.refusals, __ATOMIC_ACQUIRE) <= declined_before)
954 return -12;
955 }
956 if (publish_goal(r, target) != 0) return -8;
957 ep->goal_crumb = rx_world_explain(&r->w, r->aien.o.goal, 0);
958 limit = now_ns() + 90000000000ull;
959 while (now_ns() < limit && field(r, r->living.o.promotion, 0) == 0) {
960 if (atomic_load(&r->producer_error)) return -9;
961 pause_us(200);
962 }
963 ep->served_at_promotion = served(r);
964 ep->promoted = field(r, r->living.o.promotion, 0) != 0 && r->promoter.result == RX_GEN_OK;
965 rx_gen_active(r->gen, &ep->gen_after, &lineage);
966 ep->promotion_crumb = rx_world_explain(&r->w, r->living.o.promotion, 0);
967 if (!ep->promoted) return -10;
968 uint64_t epoch = field(r, r->living.o.inforce, 0);
969 limit = now_ns() + 60000000000ull;
970 while (now_ns() < limit && !atomic_load(&r->producer_error) &&
971 !(field(r, r->aien.o.prediction, 1) == epoch &&
972 field(r, r->aien.o.prediction, 6) == RX_AIEN_PRED_CONFIRMED &&
973 field(r, r->aien.o.assessment, 4) == RX_AIEN_GOAL_MET))
974 pause_us(200);
975 return field(r, r->aien.o.assessment, 4) == RX_AIEN_GOAL_MET ? 0 : -11;
976}
977
978/* ---- lane driver: an outside party with lane requests ----------------------
979 * Closed loop per lane: the next request waits for the check of the last one,
980 * so every request is a distinct, countable piece of work. */
981typedef struct {
982 Rig *r;
983 pthread_t t;
984 atomic_int stop, pause;
985 uint64_t quota; /* per lane; 0 = unbounded */
986 unsigned gap_us;
987 int live;
988 atomic_int error;
989 atomic_uint idle; /* turns sat out because pause was set */
990} Driver;
991
992static void *driver_main(void *arg) {
993 Driver *d = arg;
994 Rig *r = d->r;
995 while (!atomic_load(&d->stop)) {
996 if (atomic_load(&d->pause)) {
997 atomic_fetch_add(&d->idle, 1);
998 } else {
999 for (uint32_t k = 0; k < r->opt.lanes; k++) {
1000 if (d->quota && r->lane_sent[k] >= d->quota) continue;
1001 if (lane_done(r, k) != r->lane_sent[k]) continue;
1002 if (lane_submit(r, k) != 0) atomic_store(&d->error, 1);
1003 }
1004 }
1005 pause_us((int)d->gap_us);
1006 }
1007 return NULL;
1008}
1009
1010static int driver_start(Driver *d, Rig *r, uint64_t quota, unsigned gap_us) {
1011 memset(d, 0, sizeof *d);
1012 d->r = r;
1013 d->quota = quota;
1014 d->gap_us = gap_us;
1015 if (pthread_create(&d->t, NULL, driver_main, d) != 0) return -1;
1016 d->live = 1;
1017 return 0;
1018}
1019
1020/* Park the driver: returns once it has seen the pause from the top of its
1021 * loop, so a turn that was already inside the submit loop when the pause was
1022 * set has finished. Only after that is lanes_sent a count the caller can
1023 * wait for; sampling it earlier lets late submits reach the seat unseen.
1024 * -1 if the driver never parked within ms. */
1025static int driver_pause(Driver *d, int ms) {
1026 atomic_store(&d->pause, 1);
1027 unsigned idle0 = atomic_load(&d->idle);
1028 uint64_t t = now_ns();
1029 while (atomic_load(&d->idle) == idle0) {
1030 if (now_ns() - t > (uint64_t)ms * 1000000ull) return -1;
1031 pause_us(200);
1032 }
1033 return 0;
1034}
1035
1036static void driver_stop(Driver *d) {
1037 if (!d->live) return;
1038 atomic_store(&d->stop, 1);
1039 pthread_join(d->t, NULL);
1040 d->live = 0;
1041}
1042
1043static uint64_t lanes_sent(Rig *r) {
1044 uint64_t n = 0;
1045 for (uint32_t k = 0; k < r->opt.lanes; k++) n += r->lane_sent[k];
1046 return n;
1047}
1048
1049static uint64_t lanes_done(Rig *r) {
1050 uint64_t n = 0;
1051 for (uint32_t k = 0; k < r->opt.lanes; k++) n += lane_done(r, k);
1052 return n;
1053}
1054
1055/* Every lane: each request published exactly once (a seat commit that changed
1056 * the output), checked once, no mismatch. Seat commits that re-published an
1057 * unchanged value (a slot wake with the same operands) are counted apart. */
1058typedef struct { uint64_t sent, published, rewakes, checked, mismatches, lost, duplicates; } LaneTotals;
1059static void lane_totals(Rig *r, LaneTotals *t) {
1060 memset(t, 0, sizeof *t);
1061 for (uint32_t k = 0; k < r->opt.lanes; k++) {
1062 uint64_t pub = 0, same = 0;
1063 for (uint64_t id = 1; id <= r->w.n_crumbs; id++) {
1064 const RxCrumb *c = rx_world_crumb(&r->w, id);
1065 if (c->reaction != r->r_lane[k] || c->kind != RX_CRUMB_COMMIT) continue;
1066 if (c->n_outputs) pub++; else same++;
1067 }
1068 t->sent += r->lane_sent[k];
1069 t->published += pub;
1070 t->rewakes += same;
1071 t->checked += field(r, r->lchk[k], 0);
1072 t->mismatches += field(r, r->lchk[k], 2);
1073 if (pub < r->lane_sent[k]) t->lost += r->lane_sent[k] - pub;
1074 if (pub > r->lane_sent[k]) t->duplicates += pub - r->lane_sent[k];
1075 if (lane_done(r, k) != r->lane_sent[k]) t->lost++;
1076 }
1077}
1078
1079/* ---- per-scenario result ---------------------------------------------------- */
1080typedef struct {
1081 int ran, pass;
1082 int fault_observed;
1083 char containment[200], recovery[200];
1084 uint64_t prod_before, prod_during, prod_after;
1085 uint64_t crumbs;
1086 int crumbs_ok;
1087 int sweep_ok;
1088 uint64_t swept, holders, unexpected;
1089 Accounting acc;
1090 uint64_t gen_before, gen_after;
1091 char extra[16384];
1092} Result;
1093
1094static Result g_res[6];
1095static const char *g_names[6] = {"A_corrupt_candidate", "B_forged_capability",
1096 "C_reaction_cycle", "D_gpu_saturation", "E_gpu_seat_kill", "F_checkpoint_crash"};
1097
1098static int g_fail;
1099#define CHECK(cond, ...) do { if (!(cond)) { g_fail++; \
1100 fprintf(stderr, " FAIL %s:%d ", __FILE__, __LINE__); \
1101 fprintf(stderr, __VA_ARGS__); fputc('\n', stderr); } } while (0)
1102
1103static void extra(Result *res, const char *fmt, ...) __attribute__((format(printf, 2, 3)));
1104static void extra(Result *res, const char *fmt, ...) {
1105 size_t n = strlen(res->extra);
1106 va_list ap;
1107 va_start(ap, fmt);
1108 vsnprintf(res->extra + n, sizeof res->extra - n, fmt, ap);
1109 va_end(ap);
1110}
1111
1112/* Production continues for `after` more results, then the body settles and
1113 * is audited: causal crumbs verify, every lifecycle transition was legal, no
1114 * production result was wrong or used a realization not in force, the
1115 * authority sweep is clean, every claim ended once and no charge is held. */
1116static int finish(Rig *r, Result *res, uint64_t after) {
1117 uint64_t base = served(r);
1118 int ok = start_producer(r) == 0 && produce(r, after, 60000) == 0;
1119 res->prod_after = served(r) - base;
1120 CHECK(ok, "production did not resume (%llu of %llu)", U(res->prod_after), U(after));
1121 stop_producer(r);
1122 CHECK(rx_world_wait_quiescent(&r->w, 20000) == RX_OK, "the body did not settle");
1123 res->crumbs_ok = rx_world_verify_crumbs(&r->w, &res->crumbs) == 0;
1124 CHECK(res->crumbs_ok, "crumbs do not verify");
1125 CHECK(r->w.stats.crumb_overflow == 0, "the crumb log overflowed");
1126 CHECK(r->w.stats.illegal_transitions == 0, "illegal lifecycle transition");
1127 CHECK(r->wrong == 0, "%llu wrong production results", U(r->wrong));
1128 CHECK(r->unpromoted_use == 0, "production used a realization not in force");
1129 CHECK(atomic_load(&r->acc_other) == 0, "the transport saw %llu unexplained refusals",
1130 U(atomic_load(&r->acc_other)));
1131 res->sweep_ok = authority_sweep(r, &res->swept, &res->holders, &res->unexpected) == 0;
1132 CHECK(res->sweep_ok, "authority sweep: %llu promotion holders, %llu unexpected",
1133 U(res->holders), U(res->unexpected));
1134 account(r, &res->acc);
1135 CHECK(res->acc.ok, "accounting: claims %llu closed %llu committed %llu failed %llu "
1136 "in flight %llu slots %llu memory %llu holding %llu", U(res->acc.claims),
1137 U(res->acc.closed), U(res->acc.committed_seat), U(res->acc.failed_seat),
1138 U(res->acc.inflight), U(res->acc.used_slots), U(res->acc.used_memory),
1139 U(res->acc.holding));
1140 uint64_t lineage = 0;
1141 rx_gen_active(r->gen, &res->gen_after, &lineage);
1142 return 0;
1143}
1144
1145static Opts opts(void) {
1146 Opts o;
1147 memset(&o, 0, sizeof o);
1148#ifdef R14_SILICON
1149 o.seat = 1;
1150#endif
1151 return o;
1152}
1153
1154static void hex(const uint8_t *b, size_t n, char *out) {
1155 for (size_t i = 0; i < n; i++) sprintf(out + i * 2, "%02x", b[i]);
1156}
1157
1158/* ---- A: corrupt candidate realization ---------------------------------------
1159 * Omega's own test defects (R10): slot 4 carries unroll4 bytes that were
1160 * changed after their identity was computed (TAMPER), that drop N mod 4
1161 * (semantically wrong), or that load from address zero (crash). The valid
1162 * quad4 candidate is synthesized beside it in the same epoch. */
1163static int scenario_a_case(int defect, uint32_t want, const char *label, Result *res, int first) {
1164 Rig *r = calloc(1, sizeof *r);
1165 if (!r) return -1;
1166 Opts o = opts();
1167 o.defect = defect;
1168 /* The semantic case lets the body research the new cores on its own and
1169 * publishes the goal after that selection; the others publish it at once. */
1170 o.goal_after_research = defect == RX_OMEGA_DEFECT_SKIP_REMAINDER;
1171 int rc = start(r, &o);
1172 CHECK(rc == 0, "A %s: setup failed at stage %d", label, g_stage);
1173 Episode ep;
1174 if (rc == 0) {
1175 rc = adapt(r, &ep);
1176 CHECK(rc == 0, "A %s: the organism did not adapt (%d, refusal %d, promotion %d)", label,
1177 rc, r->living.last_refusal, r->promoter.result);
1178 }
1179 if (rc != 0) { if (r->admin) stop(r); free(r); return -1; }
1180 uint32_t bad = RX_OMEGA_SLOTS - 1;
1181 uint64_t bad_id = field(r, r->omega.o.candidate[bad], 2);
1182 uint64_t verdict = field(r, r->omega.o.verdict[bad], 1);
1183 uint64_t why = field(r, r->omega.o.verdict[bad], 5);
1184 int observed = bad_id != 0 && verdict == RX_OMEGA_REFUSED && why == want;
1185 CHECK(observed, "A %s: verdict %llu reason %llu (want refused, %u)", label, U(verdict),
1186 U(why), want);
1187 RxOmegaRealization e;
1188 int have = rx_omega_store_find(&r->omega, bad_id, &e) == 0;
1189 CHECK(have && !e.verified && e.parent_runs == 0,
1190 "A %s: the refused bytes are verified or ran in the parent", label);
1191 CHECK(field(r, r->omega.o.selection, 1) != bad_id && field(r, r->living.o.candidate, 2) != bad_id &&
1192 field(r, r->living.o.inforce, 1) != bad_id,
1193 "A %s: the refused realization was selected, proposed or put in force", label);
1194 /* The active R9 generation holds the valid realization, bytes and identity. */
1195 uint8_t code[AARCH64_MAX_CODE_BYTES];
1196 size_t n = 0;
1197 SemanticId id;
1198 RxOmegaRealization good;
1199 int durable = rx_gen_read_blob(r->gen, ep.gen_after, "realization", code, sizeof code, &n) ==
1200 RX_GEN_OK &&
1201 rx_omega_identity_of(&r->omega, code, n, &id) == 0 &&
1202 rx_omega_store_find(&r->omega, field(r, r->living.o.inforce, 1), &good) == 0 &&
1203 memcmp(id.bytes, good.id.bytes, 32) == 0 && good.verified &&
1204 good.kind == OMEGA_MATVEC_KIND_QUAD4;
1205 uint64_t durable_w0 = 0;
1206 for (uint32_t j = 0; j < 8; j++) durable_w0 |= (uint64_t)id.bytes[j] << (8 * j);
1207 CHECK(durable && durable_w0 != bad_id, "A %s: the active generation is not the verified quad4",
1208 label);
1209 /* The refusal is attributable: the verdict was written by verify.4, and its
1210 * ancestry reaches the synthesis that produced the bytes. */
1211 uint64_t kv = rx_world_explain(&r->w, r->omega.o.verdict[bad], 1);
1212 uint64_t ks = rx_world_explain(&r->w, r->omega.o.candidate[bad], 2);
1213 const RxCrumb *cv = rx_world_crumb(&r->w, kv), *cs = rx_world_crumb(&r->w, ks);
1214 int attributed = cv && cs && cv->reaction == r->omega.r_verify[bad] &&
1215 cs->reaction == r->omega.r_synth[bad] && ancestor(&r->w, kv, ks);
1216 CHECK(attributed, "A %s: the refusal is not attributable", label);
1217 /* The store's metadata still tells the truth: every verified entry's bytes
1218 * hash to its identity; the refused one is not verified. */
1219 uint32_t verified = 0, entries = 0, lies = 0;
1220 pthread_mutex_lock(&r->omega.mu);
1221 entries = r->omega.n_store;
1222 for (uint32_t i = 0; i < r->omega.n_store; i++) {
1223 if (!r->omega.store[i].verified) continue;
1224 verified++;
1225 SemanticId again;
1226 if (rx_omega_identity_of(&r->omega, r->omega.store[i].code, r->omega.store[i].code_len,
1227 &again) != 0 ||
1228 memcmp(again.bytes, r->omega.store[i].id.bytes, 32) != 0) lies++;
1229 }
1230 pthread_mutex_unlock(&r->omega.mu);
1231 CHECK(lies == 0, "A %s: %u verified store entries do not match their bytes", label, lies);
1232 uint64_t during = ep.served_at_promotion - ep.served_at_move;
1233 CHECK(during > 0, "A %s: production stopped while the candidate was refused", label);
1234 Result sub;
1235 memset(&sub, 0, sizeof sub);
1236 finish(r, &sub, 100);
1237 if (first) {
1238 *res = sub;
1239 res->prod_before = ep.served_at_move;
1240 res->prod_during = during;
1241 res->gen_before = ep.gen_before;
1242 res->fault_observed = 1;
1243 res->extra[0] = 0;
1244 } else {
1245 res->prod_after += sub.prod_after;
1246 res->crumbs += sub.crumbs;
1247 res->crumbs_ok &= sub.crumbs_ok;
1248 res->sweep_ok &= sub.sweep_ok;
1249 res->acc.ok &= sub.acc.ok;
1250 res->unexpected += sub.unexpected;
1251 }
1252 res->fault_observed &= observed;
1253 char idhex[65];
1254 hex(id.bytes, 32, idhex);
1255 extra(res, "%s{\"defect\": \"%s\", \"refusal_reason\": %llu, \"refused_id_word0\": \"0x%016llx\", "
1256 "\"refused_verified\": %s, \"refused_parent_runs\": %llu, "
1257 "\"store_entries\": %u, \"store_verified\": %u, \"store_mismatches\": %u, "
1258 "\"promoted_generation\": %llu, \"promoted_identity\": \"%s\", "
1259 "\"refusal_attributed\": %s, \"production_during\": %llu, \"production_after\": %llu}",
1260 first ? "" : ", ", label, U(why), U(bad_id), have && e.verified ? "true" : "false",
1261 U(have ? e.parent_runs : 0), entries, verified, lies, U(ep.gen_after), idhex,
1262 attributed ? "true" : "false", U(during), U(sub.prod_after));
1263 printf("R14 A %s: verdict REFUSED reason %llu; generation %llu -> %llu holds verified quad4; "
1264 "%llu served during, %llu after\n", label, U(why), U(ep.gen_before), U(ep.gen_after),
1265 U(during), U(sub.prod_after));
1266 stop(r);
1267 free(r);
1268 return observed && durable && attributed && lies == 0 ? 0 : -1;
1269}
1270
1271static void scenario_a(void) {
1272 Result *res = &g_res[0];
1273 int fails = g_fail;
1274 int rc = 0;
1275 rc |= scenario_a_case(RX_OMEGA_DEFECT_TAMPER, RX_OMEGA_WHY_IDENTITY, "tamper", res, 1);
1276 rc |= scenario_a_case(RX_OMEGA_DEFECT_SKIP_REMAINDER, RX_OMEGA_WHY_DIFFERENTIAL,
1277 "semantic", res, 0);
1278 rc |= scenario_a_case(RX_OMEGA_DEFECT_CRASH, RX_OMEGA_WHY_CRASHED, "crash", res, 0);
1279 char cases[sizeof res->extra];
1280 memcpy(cases, res->extra, sizeof cases);
1281 cases[sizeof cases - 16] = 0;
1282 res->extra[0] = 0;
1283 extra(res, "\"cases\": [%s]", cases);
1284 snprintf(res->containment, sizeof res->containment,
1285 "R10 verifier refused each corrupt realization (identity, differential, crash)");
1286 snprintf(res->recovery, sizeof res->recovery,
1287 "none needed: the valid quad4 candidate was verified, selected and promoted by R9");
1288 res->ran = 1;
1289 res->pass = rc == 0 && g_fail == fails;
1290}
1291
1292/* ---- B: forged authority while the organism serves ---------------------- */
1293typedef struct { RxObjRef target; uint32_t field; uint64_t value; } Poke;
1294static int fn_poke(RxCtx *c) {
1295 Poke *p = c->user;
1296 c->out[c->n_out++] = (RxMutation){p->target, p->field, p->value};
1297 return 0;
1298}
1299
1300/* rogue.decide: a reaction wrongly holding WRITE on the lane client's decision
1301 * overwrites it with a GRANT echoing the request (R8's jam). */
1302typedef struct { RxObjRef decision, request; } Forge;
1303static int fn_forge(RxCtx *c) {
1304 Forge *f = c->user;
1305 const RxSnapshotDep *rq = snapshot(c, f->request);
1306 if (!rq || rq->field[0] == 0) return 0;
1307 uint64_t v[8] = {rq->field[0], RX_AEGIS_GRANT, rq->field[1], rq->field[2], 0, rq->field[4],
1308 1, rq->field[5]};
1309 for (uint32_t i = 0; i < 8; i++) c->out[c->n_out++] = (RxMutation){f->decision, i, v[i]};
1310 return 0;
1311}
1312
1313static int rogue_add(Rig *r, const char *name, RxObjRef trig, RxObjRef write, uint32_t wfield,
1314 RxCapRef read_cap, uint64_t read_res, RxCapRef write_cap, uint64_t write_res,
1315 Poke *p, uint32_t *id) {
1316 RxReactionDesc d;
1317 memset(&d, 0, sizeof d);
1318 d.name = name;
1319 d.faculty = RX_FACULTY_EXTERNAL;
1320 d.subject = ROGUE_SUBJ;
1321 d.priority = RX_PRIO_FOREGROUND;
1322 d.fn = fn_poke;
1323 d.user = p;
1324 *p = (Poke){write, wfield, 0xBADBADull};
1325 d.n_triggers = 1;
1326 d.triggers[0] = (RxDep){trig, RX_FIELD(0)};
1327 d.n_writes = 1;
1328 d.writes[0] = (RxDep){write, RX_FIELD(wfield)};
1329 d.n_caps = 2;
1330 d.caps[0] = (RxCapNeed){read_cap, read_res, RX_RIGHT_READ};
1331 d.caps[1] = (RxCapNeed){write_cap, write_res, RX_RIGHT_READ | RX_RIGHT_WRITE};
1332 return rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, id);
1333}
1334
1335/* Wait until reaction `id` has run at least `n` times and is not in flight. */
1336static int ran(Rig *r, uint32_t id, uint64_t n, int ms) {
1337 uint64_t t = now_ns();
1338 while (now_ns() - t < (uint64_t)ms * 1000000ull) {
1339 pthread_mutex_lock(&r->w.mu);
1340 RxState s = r->w.reactions[id].state;
1341 uint64_t a = r->w.reactions[id].activations;
1342 pthread_mutex_unlock(&r->w.mu);
1343 if (a >= n && s == RX_DORMANT) return 0;
1344 pause_us(500);
1345 }
1346 return -1;
1347}
1348
1349static int wait_lanes(Rig *r, uint64_t done, int ms) {
1350 uint64_t t = now_ns();
1351 while (lanes_done(r) < done)
1352 if (now_ns() - t > (uint64_t)ms * 1000000ull) return -1;
1353 else pause_us(500);
1354 return 0;
1355}
1356
1357static int crumb_has_cap(const RxCrumb *k, RxCapRef c) {
1358 for (uint32_t i = 0; i < k->n_caps; i++)
1359 if (k->caps[i].cap_id == c.cap_id && k->caps[i].generation == c.generation) return 1;
1360 return 0;
1361}
1362
1363static int b_native_promotion(void *ctx, uint32_t cap_id, uint64_t generation, uint32_t subject,
1364 uint64_t resource, uint32_t rights) {
1365 AienosCapEntry entry;
1366 return aienos_cap_validate(ctx, (AienosCapRef){cap_id, generation}, subject, resource, rights,
1367 &entry);
1368}
1369
1370static void scenario_b(void) {
1371 Result *res = &g_res[1];
1372 int fails = g_fail;
1373 Rig *r = calloc(1, sizeof *r);
1374 if (!r) return;
1375 Opts o = opts();
1376 o.lanes = LANES;
1377 int rc = start(r, &o);
1378 CHECK(rc == 0, "B: setup failed at stage %d", g_stage);
1379 Episode ep;
1380 if (rc == 0) {
1381 rc = adapt(r, &ep);
1382 CHECK(rc == 0, "B: the organism did not adapt (%d)", rc);
1383 }
1384 if (rc != 0) { if (r->admin) stop(r); free(r); return; }
1385 Driver dv;
1386 CHECK(driver_start(&dv, r, 0, 300) == 0, "B: lane driver");
1387 CHECK(wait_lanes(r, 3 * LANES, 30000) == 0, "B: lanes never produced");
1388 res->prod_before = served(r);
1389 uint64_t lanes_before = lanes_done(r);
1390 uint64_t mints0 = r->aegis.mints, gen0 = 0, lin0 = 0;
1391 rx_gen_active(r->gen, &gen0, &lin0);
1392 res->gen_before = gen0;
1393 uint64_t mark = r->w.n_crumbs;
1394 uint64_t inforce_before[RX_MAX_FIELDS];
1395 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++) inforce_before[i] = field(r, r->living.o.inforce, i);
1396
1397 /* The outside party that pokes the rogue, and what the rogue holds. */
1398 RxObjRef trig, scratch, rin;
1399 CHECK(new_object(r, 0x6150, RES_ROGUE, &trig) == RX_OK &&
1400 new_object(r, 0x6151, RES_ROGUE + 2, &scratch) == RX_OK &&
1401 new_object(r, 0x6152, RES_ROGUE + 1, &rin) == RX_OK &&
1402 rx_world_attach_physical(&r->w, rin) == RX_OK, "B: rogue objects");
1403 RxCapRef ext_trig = mint(r, EXTERNAL, RES_ROGUE, RX_RIGHT_WRITE);
1404 RxCapRef ext_rin = mint(r, EXTERNAL, RES_ROGUE + 1, RX_RIGHT_WRITE);
1405 RxCapRef rogue_read = hostile(r, ROGUE_SUBJ, RES_ROGUE, RX_RIGHT_READ);
1406 RxCapRef rin_read = hostile(r, ROGUE_SUBJ, RES_ROGUE + 1, RX_RIGHT_READ);
1407 RxCapRef scratch_rw = hostile(r, ROGUE_SUBJ, RES_ROGUE + 2, RX_RIGHT_READ | RX_RIGHT_WRITE);
1408 const RxCapRef forged = {777, 3}, forged_gpu = {778, 1}, forged_promote = {779, 1};
1409 const RxCapRef stale = {scratch_rw.cap_id, scratch_rw.generation + 1};
1410 uint64_t inforce_res = RX_LIVING_RES_BASE + RX_LIVING_RES_INFORCE;
1411 static Poke p_forged, p_borrowed, p_revoked, p_stale, p_gpu;
1412 uint32_t r_forged, r_borrowed, r_revoked, r_stale, r_gpu;
1413 CHECK(rogue_add(r, "rogue.forged", trig, r->living.o.inforce, 1, rogue_read, RES_ROGUE,
1414 forged, inforce_res, &p_forged, &r_forged) == RX_OK &&
1415 rogue_add(r, "rogue.borrowed", trig, r->living.o.inforce, 1, rogue_read, RES_ROGUE,
1416 r->promoter.inforce_write, inforce_res, &p_borrowed, &r_borrowed) == RX_OK &&
1417 rogue_add(r, "rogue.revoked", trig, scratch, 0, rogue_read, RES_ROGUE, scratch_rw,
1418 RES_ROGUE + 2, &p_revoked, &r_revoked) == RX_OK &&
1419 rogue_add(r, "rogue.stale", trig, scratch, 1, rogue_read, RES_ROGUE, stale,
1420 RES_ROGUE + 2, &p_stale, &r_stale) == RX_OK, "B: rogue reactions");
1421 /* A rogue seat reaction: a GPU claim on lane 0's output with a forged grant. */
1422 CHECK(rx_world_bind_capability(&r->w, rin, rin_read) == RX_OK, "B: rogue input bind");
1423 RxReactionDesc d;
1424 memset(&d, 0, sizeof d);
1425 d.name = "rogue.blackwell";
1426 d.faculty = RX_FACULTY_EXTERNAL;
1427 d.subject = ROGUE_SUBJ;
1428 d.priority = RX_PRIO_FOREGROUND;
1429 d.fn = fn_lane_seat;
1430 d.user = &p_gpu;
1431 d.need.accelerator_features = RX_ACCEL_BLACKWELL;
1432 d.need.memory_bytes = LANE_BYTES;
1433 d.n_triggers = 1;
1434 d.triggers[0] = (RxDep){rin, RX_FIELD(0) | RX_FIELD(1)};
1435 d.n_writes = 1;
1436 d.writes[0] = (RxDep){r->lout[0], RX_FIELD(0)};
1437 d.n_caps = 2;
1438 d.caps[0] = (RxCapNeed){rin_read, RES_ROGUE + 1, RX_RIGHT_READ};
1439 d.caps[1] = (RxCapNeed){forged_gpu, RES_LANE_OUT, RX_RIGHT_WRITE};
1440 CHECK(rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, &r_gpu) == RX_OK, "B: rogue seat");
1441
1442 uint64_t t0 = served(r);
1443 /* B1-B3 fire together; rogue.revoked is still legitimate the first time. */
1444 RxMutation poke = {trig, 0, 1};
1445 CHECK(rx_world_publish_external(&r->w, ext_trig, &poke, 1) > 0, "B: poke");
1446 RxMutation gpu_poke[2] = {{rin, 0, 5}, {rin, 1, 6}};
1447 CHECK(rx_world_publish_external(&r->w, ext_rin, gpu_poke, 2) > 0, "B: gpu poke");
1448 CHECK(ran(r, r_forged, 1, 5000) == 0 && ran(r, r_borrowed, 1, 5000) == 0 &&
1449 ran(r, r_revoked, 1, 5000) == 0 && ran(r, r_stale, 1, 5000) == 0 &&
1450 ran(r, r_gpu, 1, 5000) == 0, "B: rogues did not run");
1451 CHECK(field(r, scratch, 0) == 0xBADBADull, "B: the legitimately held grant did not work");
1452 CHECK(cap_revoke(r, scratch_rw) == 0, "B: revoke");
1453 poke.value = 2;
1454 CHECK(rx_world_publish_external(&r->w, ext_trig, &poke, 1) > 0, "B: poke 2");
1455 CHECK(ran(r, r_revoked, 2, 5000) == 0, "B: revoked rogue did not run again");
1456 uint64_t blocked[5] = {0}, commits[5] = {0};
1457 uint32_t rogues[5] = {r_forged, r_borrowed, r_revoked, r_stale, r_gpu};
1458 uint64_t kblock = 0;
1459 for (int i = 0; i < 5; i++) {
1460 blocked[i] = crumbs_of(r, rogues[i], RX_CRUMB_BLOCKED_AUTHORITY, 0, mark, &kblock);
1461 commits[i] = r->w.reactions[rogues[i]].commits;
1462 }
1463 const RxCrumb *kf = NULL;
1464 for (uint64_t id = mark + 1; id <= r->w.n_crumbs && !kf; id++) {
1465 const RxCrumb *k = rx_world_crumb(&r->w, id);
1466 if (k->reaction == r_forged && k->kind == RX_CRUMB_BLOCKED_AUTHORITY) kf = k;
1467 }
1468 uint64_t rogue_claims = 0;
1469 for (uint64_t id = mark + 1; id <= r->w.n_crumbs; id++) {
1470 const RxCrumb *k = rx_world_crumb(&r->w, id);
1471 if (k->reaction == r_gpu && k->worker == RX_SEAT_BLACKWELL) rogue_claims++;
1472 }
1473 int b13 = blocked[0] && blocked[1] && blocked[2] && blocked[3] && blocked[4] &&
1474 !commits[0] && !commits[1] && commits[2] == 1 && !commits[3] && !commits[4] &&
1475 rogue_claims == 0 && kf && crumb_has_cap(kf, forged);
1476 for (uint32_t i = 0; i < RX_MAX_FIELDS; i++)
1477 if (field(r, r->living.o.inforce, i) != inforce_before[i]) b13 = 0;
1478 CHECK(b13, "B1-3: blocked %llu/%llu/%llu/%llu/%llu commits %llu/%llu/%llu/%llu/%llu claims %llu",
1479 U(blocked[0]), U(blocked[1]), U(blocked[2]), U(blocked[3]), U(blocked[4]),
1480 U(commits[0]), U(commits[1]), U(commits[2]), U(commits[3]), U(commits[4]),
1481 U(rogue_claims));
1482
1483 /* B4: an outside writer wrongly holding WRITE on the lanes' slot stuffs it
1484 * with another subject's valid grant. */
1485 RxObjRef lslot = r->aegis.o[1].slot[0];
1486 RxCapRef slot0 = {(uint32_t)field(r, lslot, 0), field(r, lslot, 1)};
1487 RxCapRef stuffer = hostile(r, EXTERNAL, rx_aegis_res(1, RX_AEGIS_RES_SLOT0), RX_RIGHT_WRITE);
1488 RxCapRef other = hostile(r, ROGUE_SUBJ, RES_LANE_OUT, RX_RIGHT_READ | RX_RIGHT_WRITE);
1489 uint64_t mark4 = r->w.n_crumbs, claims4 = r->w.stats.resident_claims;
1490 RxMutation st[3] = {{lslot, 0, other.cap_id}, {lslot, 1, other.generation},
1491 {lslot, 2, RX_AEGIS_SLOT_LIVE}};
1492 CHECK(rx_world_publish_external(&r->w, stuffer, st, 3) > 0, "B4: stuffed");
1493 pause_us(50000);
1494 uint64_t lanes_at_stuff = lanes_done(r), served_at_stuff = served(r);
1495 uint64_t claims_at_stuff = r->w.stats.resident_claims;
1496 pause_us(300000);
1497 uint64_t lane_blocked = 0, stuffed_claims = 0, inflight_refused = 0;
1498 for (uint64_t id = mark4 + 1; id <= r->w.n_crumbs; id++) {
1499 const RxCrumb *k = rx_world_crumb(&r->w, id);
1500 for (uint32_t j = 0; j < r->opt.lanes; j++)
1501 if (k->reaction == r->r_lane[j] && k->kind == RX_CRUMB_BLOCKED_AUTHORITY) lane_blocked++;
1502 if (k->worker == RX_SEAT_BLACKWELL && crumb_has_cap(k, other)) {
1503 if (k->kind == RX_CRUMB_COMMIT) stuffed_claims++;
1504 else if (k->kind == RX_CRUMB_REJECTED && k->reason == RX_ERR_AUTHORITY) inflight_refused++;
1505 }
1506 }
1507 int b4 = lane_blocked > 0 && stuffed_claims == 0 && lanes_done(r) == lanes_at_stuff &&
1508 r->w.stats.resident_claims == claims_at_stuff && served(r) > served_at_stuff;
1509 CHECK(b4, "B4: lane refusals %llu, publications under the stuffed grant %llu, lanes %llu -> %llu, "
1510 "claims %llu -> %llu, production %llu -> %llu", U(lane_blocked), U(stuffed_claims),
1511 U(lanes_at_stuff), U(lanes_done(r)), U(claims_at_stuff), U(r->w.stats.resident_claims),
1512 U(served_at_stuff), U(served(r)));
1513 (void)claims4;
1514
1515 /* B5: forged AEGIS decisions. A reaction wrongly holding WRITE on the lane
1516 * client's decision rewrites every decision as a GRANT; an outside writer
1517 * publishes one. The lane client (honestly) asks for the promotion right. */
1518 static Forge fg;
1519 fg = (Forge){r->aegis.o[1].decision, r->aegis.o[1].request};
1520 RxCapRef dec_w = hostile(r, ROGUE_SUBJ, rx_aegis_res(1, RX_AEGIS_RES_DECISION),
1521 RX_RIGHT_READ | RX_RIGHT_WRITE);
1522 RxCapRef req_r = hostile(r, ROGUE_SUBJ, rx_aegis_res(1, RX_AEGIS_RES_REQUEST), RX_RIGHT_READ);
1523 memset(&d, 0, sizeof d);
1524 d.name = "rogue.decide";
1525 d.faculty = RX_FACULTY_EXTERNAL;
1526 d.subject = ROGUE_SUBJ;
1527 d.priority = RX_PRIO_FOREGROUND;
1528 d.fn = fn_forge;
1529 d.user = &fg;
1530 d.n_triggers = 1;
1531 d.triggers[0] = (RxDep){fg.request, RX_ALL_FIELDS};
1532 d.n_writes = 1;
1533 d.writes[0] = (RxDep){fg.decision, RX_ALL_FIELDS};
1534 d.n_caps = 2;
1535 d.caps[0] = (RxCapNeed){req_r, rx_aegis_res(1, RX_AEGIS_RES_REQUEST), RX_RIGHT_READ};
1536 d.caps[1] = (RxCapNeed){dec_w, rx_aegis_res(1, RX_AEGIS_RES_DECISION),
1537 RX_RIGHT_READ | RX_RIGHT_WRITE};
1538 uint32_t r_decide;
1539 CHECK(rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, &r_decide) == RX_OK, "B5: rogue.decide");
1540 uint64_t mark5 = r->w.n_crumbs;
1541 RxMutation ask_promote[6] = {{r->lane_intent, 0, ++r->lane_intent_seq},
1542 {r->lane_intent, 1, RX_GEN_RES_PROMOTION},
1543 {r->lane_intent, 2, RX_GEN_RIGHT_PROMOTE},
1544 {r->lane_intent, 3, 0}, {r->lane_intent, 4, 1},
1545 {r->lane_intent, 5, RX_AEGIS_OP_ACQUIRE}};
1546 CHECK(rx_world_publish_external(&r->w, r->ext_lane_intent, ask_promote, 6) > 0, "B5: ask");
1547 CHECK(ran(r, r_decide, 1, 5000) == 0 && ran(r, r->aegis.r_install[1], 1, 5000) == 0,
1548 "B5: decision path did not run");
1549 pause_us(50000);
1550 RxCapRef ext_dec = hostile(r, EXTERNAL, rx_aegis_res(1, RX_AEGIS_RES_DECISION), RX_RIGHT_WRITE);
1551 uint64_t rs = field(r, r->aegis.o[1].request, 0);
1552 RxMutation fd[8] = {{fg.decision, 0, rs}, {fg.decision, 1, RX_AEGIS_GRANT},
1553 {fg.decision, 2, RX_GEN_RES_PROMOTION}, {fg.decision, 3, RX_GEN_RIGHT_PROMOTE},
1554 {fg.decision, 4, 0}, {fg.decision, 5, 2}, {fg.decision, 6, 1},
1555 {fg.decision, 7, RX_AEGIS_OP_ACQUIRE}};
1556 CHECK(rx_world_publish_external(&r->w, ext_dec, fd, 8) > 0, "B5: outside decision");
1557 pause_us(100000);
1558 uint64_t root_refusals = 0;
1559 for (uint64_t id = mark5 + 1; id <= r->w.n_crumbs; id++) {
1560 const RxCrumb *k = rx_world_crumb(&r->w, id);
1561 if (k->reaction == r->aegis.r_install[1] && k->kind == RX_CRUMB_COMMIT) root_refusals++;
1562 }
1563 int b5 = r->aegis.mints == mints0 && field(r, r->aegis.o[1].slot[1], 2) != RX_AEGIS_SLOT_LIVE &&
1564 field(r, r->aegis.o[1].slot[2], 2) != RX_AEGIS_SLOT_LIVE &&
1565 r->w.reactions[r_decide].commits > 0;
1566 CHECK(b5, "B5: mints %llu -> %llu, slot1 %llu slot2 %llu, rogue decisions %llu",
1567 U(mints0), U(r->aegis.mints), U(field(r, r->aegis.o[1].slot[1], 2)),
1568 U(field(r, r->aegis.o[1].slot[2], 2)), U(r->w.reactions[r_decide].commits));
1569
1570 /* B6: promotion forgery straight at R9, against a draft the rogue proposed. */
1571 uint64_t rogue_draft = 0;
1572 RxGenDraft gd;
1573 memset(&gd, 0, sizeof gd);
1574 static const uint8_t junk[] = "rogue";
1575 gd.proofs_ok = 1;
1576 gd.evidence = junk; gd.evidence_len = sizeof junk - 1;
1577 gd.realization = junk; gd.realization_len = sizeof junk - 1;
1578 /* R16 C6: the rogue is enrolled, so it proposes under its own credential;
1579 * it can present only that credential when it asks to promote. */
1580 const RxCallerCred *rogue_cred = rx_caller_find(&r->fixtures, ROGUE_SUBJ);
1581 CHECK(rx_gen_propose_as(r->gen, ROGUE_SUBJ, rogue_cred, &gd, &rogue_draft) == RX_GEN_OK,
1582 "B6: rogue draft");
1583 typedef struct { uint32_t subject; RxCapRef cap; } Try;
1584 Try tries[3] = {{RX_LIVING_PROMOTE_SUBJ, forged_promote},
1585 {ROGUE_SUBJ, r->promoter.promotion_authority},
1586 {ROGUE_SUBJ, forged_promote}};
1587 int b6 = 1;
1588 for (int i = 0; i < 3; i++) {
1589 RxPromotionRequest req = {rogue_draft, tries[i].subject, tries[i].cap.cap_id,
1590 tries[i].cap.generation, RX_GEN_RES_PROMOTION,
1591 RX_GEN_RIGHT_PROMOTE, *rogue_cred};
1592 int prc = rx_gen_promote(r->gen, &req, b_native_promotion, (void *)r->view,
1593 NULL, NULL, NULL, NULL);
1594 /* Try 0 claims the promoter subject with the rogue credential: the
1595 * store refuses the identity. Tries 1-2 are the rogue as itself: the
1596 * native authority refuses the capability. */
1597 int want = i == 0 ? RX_GEN_ERR_IDENTITY : RX_GEN_ERR_AUTHORITY;
1598 if (prc != want) b6 = 0;
1599 CHECK(prc == want, "B6: try %d returned %d, expected %d", i, prc, want);
1600 }
1601 uint64_t gen6 = 0, lin6 = 0;
1602 rx_gen_active(r->gen, &gen6, &lin6);
1603 RxRecoveryRecord rec;
1604 b6 = b6 && gen6 == gen0 && lin6 == lin0 && rx_gen_recover(r->generation_dir, &rec) == RX_GEN_OK &&
1605 rec.active_id == gen0;
1606 CHECK(b6, "B6: generation %llu -> %llu", U(gen0), U(gen6));
1607
1608 /* Containment: revoke what the compromised writers held. Then the lane
1609 * client asks again, honestly; AEGIS grants, the root renews the slot, and
1610 * the lanes resume under the renewed grant. */
1611 uint64_t mints_attack = r->aegis.mints - mints0;
1612 res->prod_during = served(r) - t0;
1613 for (uint32_t i = 0; i < r->n_hostile; i++) (void)cap_revoke(r, r->hostile[i]);
1614 uint64_t lanes_blocked_at = lanes_done(r);
1615 CHECK(lane_acquire(r) == 0, "B: honest re-acquire");
1616 uint64_t t = now_ns();
1617 while (now_ns() - t < 10000000000ull &&
1618 !(field(r, lslot, 2) == RX_AEGIS_SLOT_LIVE && field(r, lslot, 0) != other.cap_id &&
1619 field(r, lslot, 5) == field(r, r->aegis.o[1].request, 0)))
1620 pause_us(500);
1621 RxCapRef slot1 = {(uint32_t)field(r, lslot, 0), field(r, lslot, 1)};
1622 int renewed = field(r, lslot, 2) == RX_AEGIS_SLOT_LIVE &&
1623 (slot1.cap_id != slot0.cap_id || slot1.generation != slot0.generation) &&
1624 r->aegis.mints == mints0 + 1 &&
1625 rx_world_validate_cap(&r->w, slot1, LANE_SUBJ, RES_LANE_OUT, RX_RIGHT_WRITE,
1626 NULL) == RX_CAP_OK &&
1627 rx_world_validate_cap(&r->w, slot0, LANE_SUBJ, RES_LANE_OUT, RX_RIGHT_WRITE,
1628 NULL) != RX_CAP_OK;
1629 CHECK(renewed, "B: the honest grant was not renewed (state %llu, mints %llu)",
1630 U(field(r, lslot, 2)), U(r->aegis.mints));
1631 int resumed = wait_lanes(r, lanes_blocked_at + 2 * LANES, 30000) == 0;
1632 CHECK(resumed, "B: lanes did not resume (%llu -> %llu)", U(lanes_blocked_at), U(lanes_done(r)));
1633 driver_stop(&dv);
1634 CHECK(wait_lanes(r, lanes_sent(r), 30000) == 0, "B: lanes did not drain");
1635 int promote_ok = rx_world_validate_cap(&r->w, r->promoter.promotion_authority,
1636 RX_LIVING_PROMOTE_SUBJ, RX_GEN_RES_PROMOTION, RX_GEN_RIGHT_PROMOTE, NULL) == RX_CAP_OK;
1637 CHECK(promote_ok, "B: the legitimate promotion right no longer validates");
1638 res->fault_observed = b13 && b4 && b5 && b6;
1639 finish(r, res, 100);
1640 LaneTotals lt;
1641 lane_totals(r, &lt);
1642 CHECK(lt.lost == 0 && lt.duplicates == 0 && lt.mismatches == 0,
1643 "B: lanes lost %llu duplicated %llu mismatched %llu", U(lt.lost), U(lt.duplicates),
1644 U(lt.mismatches));
1645 snprintf(res->containment, sizeof res->containment,
1646 "R7 refused forged, borrowed, revoked and stale references and the rogue GPU claim; "
1647 "R8 root refused stuffed and forged authority; R9 refused promotion forgery");
1648 snprintf(res->recovery, sizeof res->recovery,
1649 "compromised writers revoked; the lane client re-acquired through AEGIS; the root "
1650 "renewed the slot; lanes resumed under the renewed grant");
1651 extra(res, "\"attacks\": {\"forged_reference\": \"%s\", \"wrong_subject_valid_reference\": \"%s\", "
1652 "\"revoked_reference\": \"%s\", \"stale_generation\": \"%s\", \"forged_gpu_claim\": \"%s\", "
1653 "\"slot_stuffing\": \"%s\", \"forged_aegis_decision\": \"%s\", \"promote_forgery\": \"%s\"}, "
1654 "\"rogue_blocked_crumbs\": [%llu, %llu, %llu, %llu, %llu], "
1655 "\"rogue_gpu_claims\": %llu, \"lane_refusals_while_stuffed\": %llu, "
1656 "\"publications_under_stuffed_grant\": %llu, \"inflight_claims_refused_at_publication\": %llu, \"root_install_runs_during_forgery\": %llu, "
1657 "\"mints_during_attacks\": %llu, \"renewal_mints\": %llu, "
1658 "\"rogue_draft_id_left_unpromoted\": %llu, \"lanes_before\": %llu, \"lanes_sent\": %llu, "
1659 "\"lanes_published\": %llu, \"lanes_lost\": %llu, \"lanes_duplicated\": %llu, "
1660 "\"legitimate_promotion_right_valid\": %s",
1661 b13 ? "BLOCKED" : "FAIL", b13 ? "BLOCKED" : "FAIL", b13 ? "BLOCKED" : "FAIL",
1662 b13 ? "BLOCKED" : "FAIL", b13 ? "BLOCKED" : "FAIL", b4 ? "CONTAINED" : "FAIL",
1663 b5 ? "NO_MINT" : "FAIL", b6 ? "REFUSED" : "FAIL",
1664 U(blocked[0]), U(blocked[1]), U(blocked[2]), U(blocked[3]), U(blocked[4]),
1665 U(rogue_claims), U(lane_blocked), U(stuffed_claims), U(inflight_refused), U(root_refusals), U(mints_attack),
1666 U(r->aegis.mints - mints0), U(rogue_draft), U(lanes_before), U(lt.sent),
1667 U(lt.published), U(lt.lost), U(lt.duplicates), promote_ok ? "true" : "false");
1668 printf("R14 B: forged/borrowed/revoked/stale/GPU refused, slot stuffing contained, forged "
1669 "decisions minted nothing, promotion forgery refused; renewed grant, lanes %llu "
1670 "published, production %llu during, %llu after\n", U(lt.published),
1671 U(res->prod_during), U(res->prod_after));
1672 stop(r);
1673 free(r);
1674 res->ran = 1;
1675 res->pass = g_fail == fails;
1676}
1677
1678/* ---- C: pathological reaction cycles in the same world ---------------------- */
1679typedef struct { RxObjRef from, to; int mode; int left; } Hop;
1680enum { HOP_BUMP, HOP_FLIP, HOP_DOWN, HOP_FLIP_N };
1681static int fn_hop(RxCtx *c) {
1682 Hop *h = c->user;
1683 uint64_t v = snapshot(c, h->from)->field[0];
1684 uint64_t out = h->mode == HOP_BUMP ? v + 1 : h->mode == HOP_DOWN ? (v ? v - 1 : 0) : v ^ 1u;
1685 if (h->mode == HOP_FLIP_N) {
1686 if (h->left <= 0) return 0;
1687 h->left--;
1688 }
1689 c->out[c->n_out++] = (RxMutation){h->to, 0, out};
1690 return 0;
1691}
1692
1693static int hop_add(Rig *r, const char *name, Hop *h, RxCapRef rw, uint32_t loop_kind,
1694 uint32_t *id) {
1695 RxReactionDesc d;
1696 memset(&d, 0, sizeof d);
1697 d.name = name;
1698 d.faculty = RX_FACULTY_AIEN;
1699 d.subject = CYCLE_SUBJ;
1700 d.priority = RX_PRIO_FOREGROUND;
1701 d.fn = fn_hop;
1702 d.user = h;
1703 d.loop_kind = loop_kind;
1704 d.n_triggers = 1;
1705 d.triggers[0] = (RxDep){h->from, RX_FIELD(0)};
1706 d.n_writes = 1;
1707 d.writes[0] = (RxDep){h->to, RX_FIELD(0)};
1708 d.n_caps = 1;
1709 d.caps[0] = (RxCapNeed){rw, RES_CYCLE, RX_RIGHT_READ | RX_RIGHT_WRITE};
1710 return rx_world_add_reaction_keyed(&r->w, &r->fixtures, &d, id);
1711}
1712
1713static void scenario_c(void) {
1714 Result *res = &g_res[2];
1715 int fails = g_fail;
1716 Rig *r = calloc(1, sizeof *r);
1717 if (!r) return;
1718 Opts o = opts();
1719 o.oscillation = 8;
1720 int rc = start(r, &o);
1721 CHECK(rc == 0, "C: setup failed at stage %d", g_stage);
1722 Episode ep;
1723 if (rc == 0) {
1724 rc = adapt(r, &ep);
1725 CHECK(rc == 0, "C: the organism did not adapt with R6 on (%d)", rc);
1726 }
1727 if (rc != 0) { if (r->admin) stop(r); free(r); return; }
1728 res->gen_before = ep.gen_after;
1729 CHECK(produce(r, 100, 30000) == 0, "C: production before the storm");
1730 res->prod_before = served(r);
1731 uint32_t organism = r->w.n_reactions; /* every reaction registered so far */
1732 uint64_t quarantines0 = r->w.stats.quarantines;
1733
1734 RxObjRef a, b, x, y, z, f, cv, pd;
1735 RxObjRef *objs[8] = {&a, &b, &x, &y, &z, &f, &cv, &pd};
1736 for (int i = 0; i < 8; i++) CHECK(new_object(r, 0x6160 + (uint32_t)i, RES_CYCLE, objs[i]) == RX_OK,
1737 "C: object");
1738 RxCapRef rw = mint(r, CYCLE_SUBJ, RES_CYCLE, RX_RIGHT_READ | RX_RIGHT_WRITE);
1739 RxCapRef ext = mint(r, EXTERNAL, RES_CYCLE, RX_RIGHT_WRITE);
1740 static Hop h[8];
1741 h[0] = (Hop){a, b, HOP_BUMP, 0}; h[1] = (Hop){b, a, HOP_BUMP, 0}; /* A <-> B, diverges */
1742 h[2] = (Hop){x, y, HOP_BUMP, 0}; h[3] = (Hop){y, z, HOP_BUMP, 0};
1743 h[4] = (Hop){z, x, HOP_BUMP, 0}; /* X -> Y -> Z -> X */
1744 h[5] = (Hop){f, f, HOP_FLIP, 0}; /* A-B-A flip */
1745 h[6] = (Hop){cv, cv, HOP_DOWN, 0}; /* converges to 0 */
1746 h[7] = (Hop){pd, pd, HOP_FLIP_N, 40}; /* declared periodic */
1747 const char *names[8] = {"cycle.ab.a", "cycle.ab.b", "cycle.xyz.x", "cycle.xyz.y",
1748 "cycle.xyz.z", "cycle.flip", "control.converge", "control.periodic"};
1749 uint32_t id[8];
1750 for (int i = 0; i < 8; i++)
1751 CHECK(hop_add(r, names[i], &h[i], rw, i == 7 ? RX_LOOP_PERIODIC : RX_LOOP_ORDINARY,
1752 &id[i]) == RX_OK, "C: %s", names[i]);
1753 uint64_t aien0 = acts(r, r->aien.r_observe), omega0 = acts(r, r->omega.r_watch);
1754 uint64_t crumbs0 = r->w.n_crumbs, served0 = served(r);
1755 uint64_t t0 = now_ns();
1756 RxObjRef starts[5] = {a, x, f, cv, pd};
1757 uint64_t start_v[5] = {1, 1, 1, 40, 1};
1758 int64_t root[5];
1759 for (int i = 0; i < 5; i++) {
1760 RxMutation m = {starts[i], 0, start_v[i]};
1761 root[i] = rx_world_publish_external(&r->w, ext, &m, 1);
1762 CHECK(root[i] > 0, "C: stimulus %d", i);
1763 }
1764 /* Containment: each pathological cycle stops inside its own episode. */
1765 uint64_t t = now_ns();
1766 int contained = 0;
1767 while (now_ns() - t < 20000000000ull && !contained) {
1768 pthread_mutex_lock(&r->w.mu);
1769 contained = (r->w.reactions[id[0]].quarantined || r->w.reactions[id[1]].quarantined) &&
1770 (r->w.reactions[id[2]].quarantined || r->w.reactions[id[3]].quarantined ||
1771 r->w.reactions[id[4]].quarantined) &&
1772 r->w.reactions[id[5]].quarantined && r->w.objects[cv.id].field[0] == 0 &&
1773 r->w.reactions[id[6]].state == RX_DORMANT &&
1774 r->w.reactions[id[7]].activations >= 40;
1775 pthread_mutex_unlock(&r->w.mu);
1776 pause_us(1000);
1777 }
1778 uint64_t contain_ms = (now_ns() - t0) / 1000000u;
1779 CHECK(contained, "C: the cycles were not contained");
1780 pause_us(200000);
1781 uint64_t cycle_crumbs_a = 0;
1782 for (uint64_t k = crumbs0 + 1; k <= r->w.n_crumbs; k++) {
1783 const RxCrumb *c = rx_world_crumb(&r->w, k);
1784 for (int i = 0; i < 6; i++) if (c->reaction == id[i]) cycle_crumbs_a++;
1785 }
1786 pause_us(500000); /* after containment the cycles stay stopped */
1787 uint64_t cycle_crumbs_b = 0;
1788 for (uint64_t k = crumbs0 + 1; k <= r->w.n_crumbs; k++) {
1789 const RxCrumb *c = rx_world_crumb(&r->w, k);
1790 for (int i = 0; i < 6; i++) if (c->reaction == id[i]) cycle_crumbs_b++;
1791 }
1792 uint64_t storm_served = served(r) - served0;
1793 uint64_t aien1 = acts(r, r->aien.r_observe), omega1 = acts(r, r->omega.r_watch);
1794 /* Evidence: each containment crumb names a cycle reaction, the limit, and
1795 * the outside publication that started that cycle's episode. */
1796 uint64_t named = 0, wrong_episode = 0, organism_contained = 0;
1797 int by_cycle[3] = {0, 0, 0};
1798 for (uint64_t k = crumbs0 + 1; k <= r->w.n_crumbs; k++) {
1799 const RxCrumb *c = rx_world_crumb(&r->w, k);
1800 if (c->kind != RX_CRUMB_QUARANTINE) continue;
1801 int which = -1;
1802 for (int i = 0; i < 8; i++) if (c->reaction == id[i]) which = i;
1803 if (which < 0) { organism_contained++; continue; }
1804 named++;
1805 int cyc = which <= 1 ? 0 : which <= 4 ? 1 : which == 5 ? 2 : -1;
1806 if (cyc < 0) { wrong_episode++; continue; }
1807 uint64_t want_root = (uint64_t)root[cyc];
1808 int want_reason = cyc == 2 ? RX_CONTAIN_OSCILLATION : RX_CONTAIN_BUDGET;
1809 if (c->episode != want_root || c->reason != want_reason) wrong_episode++;
1810 else by_cycle[cyc] = 1;
1811 }
1812 uint64_t max_acts = 0;
1813 for (int i = 0; i < 6; i++)
1814 if (r->w.reactions[id[i]].activations > max_acts) max_acts = r->w.reactions[id[i]].activations;
1815 int organism_quarantined = 0;
1816 for (uint32_t i = 0; i < organism; i++)
1817 if (r->w.reactions[i].quarantined) organism_quarantined++;
1818 CHECK(by_cycle[0] && by_cycle[1] && by_cycle[2] && wrong_episode == 0,
1819 "C: containment evidence %d/%d/%d, %llu wrong", by_cycle[0], by_cycle[1], by_cycle[2],
1820 U(wrong_episode));
1821 CHECK(organism_contained == 0 && organism_quarantined == 0,
1822 "C: %llu organism containments, %d organism reactions quarantined",
1823 U(organism_contained), organism_quarantined);
1824 CHECK(max_acts <= BUDGET + 2, "C: a cycle ran %llu times in one episode", U(max_acts));
1825 CHECK(cycle_crumbs_b == cycle_crumbs_a, "C: the cycles kept writing crumbs (%llu -> %llu)",
1826 U(cycle_crumbs_a), U(cycle_crumbs_b));
1827 CHECK(!r->w.reactions[id[6]].quarantined && field(r, cv, 0) == 0,
1828 "C: the convergent control was stopped");
1829 CHECK(!r->w.reactions[id[7]].quarantined && r->w.reactions[id[7]].activations >= 40,
1830 "C: the periodic control was stopped");
1831 CHECK(storm_served >= 100 && aien1 > aien0 && omega1 > omega0,
1832 "C: production %llu, aien.observe %llu -> %llu, omega.watch %llu -> %llu",
1833 U(storm_served), U(aien0), U(aien1), U(omega0), U(omega1));
1834 uint64_t deferred_peak = r->w.stats.deferred_peak;
1835 CHECK(deferred_peak < RX_MAX_REACTIONS, "C: deferred queue peaked at %llu", U(deferred_peak));
1836 /* A new outside stimulus is a new episode: it gets a fresh, still bounded budget. */
1837 uint64_t before_again = r->w.reactions[id[0]].activations;
1838 RxMutation again = {a, 0, field(r, a, 0) + 1000};
1839 int64_t root2 = rx_world_publish_external(&r->w, ext, &again, 1);
1840 t = now_ns();
1841 while (now_ns() - t < 10000000000ull && r->w.reactions[id[0]].activations == before_again)
1842 pause_us(1000);
1843 pause_us(300000);
1844 uint64_t second = 0;
1845 for (uint64_t k = (uint64_t)root2 + 1; k <= r->w.n_crumbs; k++) {
1846 const RxCrumb *c = rx_world_crumb(&r->w, k);
1847 if (c->kind == RX_CRUMB_QUARANTINE && c->episode == (uint64_t)root2 &&
1848 (c->reaction == id[0] || c->reaction == id[1])) second++;
1849 }
1850 uint64_t again_acts = r->w.reactions[id[0]].activations - before_again;
1851 CHECK(root2 > 0 && again_acts > 0 && again_acts <= BUDGET + 2 && second >= 1,
1852 "C: second episode ran %llu, containment crumbs %llu", U(again_acts), U(second));
1853 res->prod_during = storm_served;
1854 res->fault_observed = contained;
1855 finish(r, res, 100);
1856 snprintf(res->containment, sizeof res->containment,
1857 "R6: A<->B and X->Y->Z->X quarantined by the per-episode activation budget, "
1858 "the flip by the oscillation limit; each with a QUARANTINE crumb naming its episode");
1859 snprintf(res->recovery, sizeof res->recovery,
1860 "none needed: production, AIEN and Omega never stopped; the controls finished");
1861 extra(res, "\"activation_budget_per_episode\": %u, \"oscillation_limit\": %d, "
1862 "\"cycles\": [\"A<->B (+1 each way)\", \"X->Y->Z->X (+1)\", \"self flip A-B-A\"], "
1863 "\"controls\": [\"countdown converges to 0\", \"declared periodic flip x40\"], "
1864 "\"containment_crumbs_named\": %llu, \"containment_wrong\": %llu, "
1865 "\"organism_reactions_quarantined\": %d, \"max_cycle_activations\": %llu, "
1866 "\"cycle_crumbs_at_containment\": %llu, \"cycle_crumbs_500ms_later\": %llu, "
1867 "\"deferred_queue_peak\": %llu, \"containment_ms\": %llu, "
1868 "\"production_during_storm\": %llu, \"aien_observe_activations_during\": %llu, "
1869 "\"omega_watch_activations_during\": %llu, \"second_episode_activations\": %llu, "
1870 "\"quarantines\": %llu", BUDGET, o.oscillation, U(named), U(wrong_episode),
1871 organism_quarantined, U(max_acts), U(cycle_crumbs_a), U(cycle_crumbs_b),
1872 U(deferred_peak), U(contain_ms), U(storm_served), U(aien1 - aien0), U(omega1 - omega0),
1873 U(again_acts), U(r->w.stats.quarantines - quarantines0));
1874 printf("R14 C: cycles contained in %llu ms (max %llu activations), %llu containment crumbs, "
1875 "organism untouched; production %llu during, %llu after\n", U(contain_ms),
1876 U(max_acts), U(named), U(storm_served), U(res->prod_after));
1877 stop(r);
1878 free(r);
1879 res->ran = 1;
1880 res->pass = g_fail == fails;
1881}
1882
1883/* ---- D: saturate the GPU ------------------------------------------------------ */
1884typedef struct {
1885 uint64_t max_inflight, max_blocked, max_ring, max_ring_claims, max_memory, samples;
1886} Pressure;
1887
1888static void sample(Rig *r, Pressure *p) {
1889 pthread_mutex_lock(&r->w.mu);
1890 uint64_t inflight = 0, blocked = 0;
1891 for (uint32_t k = 0; k < r->opt.lanes; k++) {
1892 const RxReaction *x = &r->w.reactions[r->r_lane[k]];
1893 if (x->resident_seat) inflight++;
1894 if (x->state == RX_BLOCKED_RESOURCE) blocked++;
1895 }
1896 const OmegaSharedWorldRing *ring =
1897 (const OmegaSharedWorldRing *)(r->w.coherent + rx_world_off_c2g());
1898 uint64_t head = __atomic_load_n(&ring->head, __ATOMIC_ACQUIRE);
1899 uint64_t tail = __atomic_load_n(&ring->tail, __ATOMIC_ACQUIRE);
1900 uint64_t occ = tail - head, claims = 0;
1901 /* The ring carries claims and publication notices; count the claims. */
1902 for (uint64_t q = head; q < tail; q++)
1903 if (ring->slots[q & ring->mask].msg_type == RX_RING_CLAIM) claims++;
1904 uint64_t mem = r->w.used_memory;
1905 pthread_mutex_unlock(&r->w.mu);
1906 if (inflight > p->max_inflight) p->max_inflight = inflight;
1907 if (blocked > p->max_blocked) p->max_blocked = blocked;
1908 if (occ > p->max_ring) p->max_ring = occ;
1909 if (claims > p->max_ring_claims) p->max_ring_claims = claims;
1910 if (mem > p->max_memory) p->max_memory = mem;
1911 p->samples++;
1912}
1913
1914static void scenario_d(void) {
1915 Result *res = &g_res[3];
1916 int fails = g_fail;
1917 Rig *r = calloc(1, sizeof *r);
1918 if (!r) return;
1919 Opts o = opts();
1920 o.lanes = LANES;
1921 int rc = start(r, &o);
1922 CHECK(rc == 0, "D: setup failed at stage %d", g_stage);
1923 Episode ep;
1924 if (rc == 0) {
1925 rc = adapt(r, &ep);
1926 CHECK(rc == 0, "D: the organism did not adapt (%d)", rc);
1927 }
1928 if (rc != 0) { if (r->admin) stop(r); free(r); return; }
1929 res->gen_before = ep.gen_after;
1930 res->prod_before = served(r);
1931 const uint64_t quota = 200;
1932 uint64_t claims0 = r->w.stats.resident_claims, mark = r->w.n_crumbs;
1933 uint64_t rejected0 = r->w.stats.desc_rejected;
1934 uint64_t served0 = served(r), aien0 = acts(r, r->aien.r_observe);
1935 Pressure p;
1936 memset(&p, 0, sizeof p);
1937 Driver dv;
1938 uint64_t t0 = now_ns();
1939 CHECK(driver_start(&dv, r, quota, 20) == 0, "D: driver");
1940 uint64_t total = quota * LANES, t_last_submit = 0;
1941 while (now_ns() - t0 < 120000000000ull) {
1942 sample(r, &p);
1943 if (!t_last_submit && lanes_sent(r) == total) t_last_submit = now_ns();
1944 if (t_last_submit && lanes_done(r) == total) break;
1945 pause_us(100);
1946 }
1947 uint64_t t_drained = now_ns();
1948 driver_stop(&dv);
1949 uint64_t during = served(r) - served0;
1950 uint64_t aien1 = acts(r, r->aien.r_observe);
1951 LaneTotals lt;
1952 lane_totals(r, &lt);
1953 uint64_t retried = 0, failed = 0;
1954 for (uint64_t id = mark + 1; id <= r->w.n_crumbs; id++) {
1955 const RxCrumb *k = rx_world_crumb(&r->w, id);
1956 for (uint32_t j = 0; j < LANES; j++)
1957 if (k->reaction == r->r_lane[j] && k->worker == RX_SEAT_BLACKWELL &&
1958 k->kind != RX_CRUMB_COMMIT) failed++;
1959 }
1960 int reached = p.max_inflight == LANE_CAP && p.max_blocked >= 1 &&
1961 p.max_memory <= (uint64_t)LANE_CAP * LANE_BYTES;
1962 CHECK(reached, "D: the limit was not reached: %llu concurrent claims (cap %u), %llu waiting, "
1963 "%llu bytes held", U(p.max_inflight), LANE_CAP, U(p.max_blocked), U(p.max_memory));
1964 CHECK(lt.sent == total && lt.published == total && lt.checked == total && lt.lost == 0 &&
1965 lt.duplicates == 0 && lt.mismatches == 0,
1966 "D: sent %llu published %llu checked %llu lost %llu duplicated %llu mismatched %llu",
1967 U(lt.sent), U(lt.published), U(lt.checked), U(lt.lost), U(lt.duplicates),
1968 U(lt.mismatches));
1969 CHECK(atomic_load(&r->acc_torn) == 0 && atomic_load(&r->acc_stale) == 0 &&
1970 atomic_load(&r->acc_auth) == 0 && failed == 0,
1971 "D: torn %llu stale %llu refused %llu failed %llu", U(atomic_load(&r->acc_torn)),
1972 U(atomic_load(&r->acc_stale)), U(atomic_load(&r->acc_auth)), U(failed));
1973 uint64_t dropped = r->w.stats.desc_rejected - rejected0;
1974 CHECK(p.max_ring_claims <= LANE_CAP && p.max_ring < OMEGA_SW_RING_CAPACITY && dropped == 0,
1975 "D: ring held %llu claims, %llu notices in all, %llu dropped or refused",
1976 U(p.max_ring_claims), U(p.max_ring), U(dropped));
1977 CHECK(during >= 100 && aien1 > aien0, "D: CPU work during saturation: production %llu, "
1978 "aien.observe %llu", U(during), U(aien1 - aien0));
1979 res->prod_during = during;
1980 res->fault_observed = reached;
1981 finish(r, res, 100);
1982 uint64_t claims = r->w.stats.resident_claims - claims0;
1983 snprintf(res->containment, sizeof res->containment,
1984 "R5 admitted at most %u lane claims (their windows held against the memory "
1985 "budget); the rest waited BLOCKED_RESOURCE", LANE_CAP);
1986 snprintf(res->recovery, sizeof res->recovery,
1987 "backlog drained after submission stopped; every request published and checked once");
1988 extra(res, "\"lanes\": %u, \"requests_per_lane\": %llu, \"claim_capacity\": %u, "
1989 "\"max_concurrent_claims\": %llu, \"max_backlog_waiting\": %llu, "
1990 "\"max_ring_occupancy\": %llu, \"max_ring_claims\": %llu, \"ring_notices_dropped\": %llu, \"max_bytes_held\": %llu, \"total_submitted\": %llu, "
1991 "\"total_completed\": %llu, \"total_checked\": %llu, \"total_retried\": %llu, "
1992 "\"total_failed\": %llu, \"duplicates\": %llu, \"lost\": %llu, \"mismatches\": %llu, "
1993 "\"claims\": %llu, \"slot_rewakes_same_value\": %llu, \"drain_ms\": %llu, "
1994 "\"saturation_ms\": %llu, \"production_during\": %llu, \"torn_refused\": %llu, "
1995 "\"pressure_samples\": %llu",
1996 LANES, U(quota), LANE_CAP, U(p.max_inflight), U(p.max_blocked), U(p.max_ring), U(p.max_ring_claims),
1997 U(dropped), U(p.max_memory), U(lt.sent), U(lt.published), U(lt.checked), U(retried), U(failed),
1998 U(lt.duplicates), U(lt.lost), U(lt.mismatches), U(claims), U(lt.rewakes),
1999 U(t_last_submit ? (t_drained - t_last_submit) / 1000000u : 0),
2000 U((t_drained - t0) / 1000000u), U(during), U(atomic_load(&r->acc_torn)), U(p.samples));
2001 printf("R14 D: %llu lane requests, at most %llu claims at once (cap %u), up to %llu waiting; "
2002 "%llu published once, 0 lost, 0 duplicated; production %llu during, %llu after\n",
2003 U(lt.sent), U(p.max_inflight), LANE_CAP, U(p.max_blocked), U(lt.published), U(during),
2004 U(res->prod_after));
2005 stop(r);
2006 free(r);
2007 res->ran = 1;
2008 res->pass = g_fail == fails;
2009}
2010
2011/* ---- E: kill the resident seat while it holds real lane work ------------------ */
2012#ifdef R14_SILICON
2013static volatile uint32_t *hb_word(Rig *r, uint32_t off) {
2014 return (volatile uint32_t *)(r->w.coherent + rx_world_off_heartbeat() + off);
2015}
2016
2017static void barrier(void) {
2018#if defined(__aarch64__)
2019 __asm__ volatile("dsb sy" ::: "memory");
2020#else
2021 __sync_synchronize();
2022#endif
2023}
2024#endif
2025
2026static void scenario_e(void) {
2027 Result *res = &g_res[4];
2028 int fails = g_fail;
2029 Rig *r = calloc(1, sizeof *r);
2030 if (!r) return;
2031 Opts o = opts();
2032 o.lanes = LANES;
2033 int rc = start(r, &o);
2034 CHECK(rc == 0, "E: setup failed at stage %d", g_stage);
2035 Episode ep;
2036 if (rc == 0) {
2037 rc = adapt(r, &ep);
2038 CHECK(rc == 0, "E: the organism did not adapt (%d)", rc);
2039 }
2040 if (rc != 0) { if (r->admin) stop(r); free(r); return; }
2041 res->gen_before = ep.gen_after;
2042 Driver dv;
2043 CHECK(driver_start(&dv, r, 0, 300) == 0, "E: driver");
2044 CHECK(wait_lanes(r, 3 * LANES, 30000) == 0, "E: lanes never produced");
2045 CHECK(driver_pause(&dv, 30000) == 0, "E: the driver did not park");
2046 CHECK(wait_lanes(r, lanes_sent(r), 30000) == 0, "E: lanes did not go idle");
2047 res->prod_before = served(r);
2048 uint32_t seat_gen0 = r->w.seat_generation;
2049 uint32_t gens[RX_MAX_OBJECTS];
2050 for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) gens[i] = r->w.objects[i].generation;
2051 uint64_t mints0 = r->aegis.mints;
2052 RxObjRef lslot = r->aegis.o[1].slot[0];
2053 uint64_t slot_id0 = field(r, lslot, 0), slot_gen0 = field(r, lslot, 1);
2054 uint64_t pub0 = r->w.reactions[r->r_lane[0]].commits;
2055
2056 /* Hold: the chip keeps the next claim it takes (the R12 hold word). The
2057 * stand-in simply is not stepped. */
2058#ifdef R14_SILICON
2059 *hb_word(r, RX_SEAT_HB_HOLD) = 1;
2060 barrier();
2061#else
2062 atomic_store(&r->acceptor_pause, 1);
2063 pause_us(2000);
2064#endif
2065 uint64_t served_hold = served(r), mark = r->w.n_crumbs;
2066 CHECK(lane_submit(r, 0) == 0, "E: lane request");
2067 uint64_t stimulus = rx_world_explain(&r->w, r->lin[0], 2); /* the lane request */
2068 uint64_t t = now_ns();
2069 while (!(r->w.reactions[r->r_lane[0]].resident_seat &&
2070 r->w.reactions[r->r_lane[0]].state == RX_RUNNING) &&
2071 now_ns() - t < 5000000000ull)
2072 pause_us(200);
2073 uint64_t seq = r->w.reactions[r->r_lane[0]].resident_seq;
2074 int claimed = r->w.reactions[r->r_lane[0]].resident_seat;
2075 int held = claimed;
2076#ifdef R14_SILICON
2077 held = 0;
2078 t = now_ns();
2079 while (claimed && !held && now_ns() - t < 5000000000ull) {
2080 barrier();
2081 if (*hb_word(r, RX_SEAT_HB_HELD) == (uint32_t)(seq + 1)) held = 1;
2082 else pause_us(500);
2083 }
2084#endif
2085 CHECK(claimed && held, "E: the seat did not hold the lane claim (claimed %d held %d, lanes in flight %llu)",
2086 claimed, held, U(lanes_sent(r) - lanes_done(r)));
2087 uint64_t mem_held = r->w.used_memory;
2088 OmegaSharedWorldRing *c2g = (OmegaSharedWorldRing *)(r->w.coherent + rx_world_off_c2g());
2089 OmegaSharedWorldDesc old = c2g->slots[seq & c2g->mask];
2090 uint64_t fails0 = r->w.stats.transitions[RX_RUNNING][RX_FAILED];
2091 uint64_t t_kill = now_ns();
2092 int killed = 1;
2093#ifdef R14_SILICON
2094 killed = rx_gpu_seat_kill(r->seat) == 0;
2095#endif
2096 CHECK(killed, "E: the seat channel was not destroyed");
2097 int lost = rx_resident_seat_lost(&r->w, 1);
2098 uint64_t kill_ms = (now_ns() - t_kill) / 1000000u;
2099 uint64_t fail_id = 0;
2100 uint64_t n_fail = crumbs_of(r, r->r_lane[0], RX_CRUMB_FAILED, RX_ERR_SEAT_LOST, mark, &fail_id);
2101 const RxCrumb *kfail = rx_world_crumb(&r->w, fail_id);
2102 uint64_t mem_after = r->w.used_memory;
2103 int classified = lost == 1 && r->w.seat_generation == seat_gen0 + 1 &&
2104 r->w.stats.transitions[RX_RUNNING][RX_FAILED] == fails0 + 1 && n_fail == 1 &&
2105 kfail && kfail->worker == RX_SEAT_BLACKWELL && kfail->wake_cause == stimulus &&
2106 mem_after <= LANE_BYTES;
2107 CHECK(classified, "E: lost %d, seat generation %u -> %u, failures +%llu, loss crumbs %llu, "
2108 "memory %llu -> %llu, cause %llu want %llu", lost, seat_gen0, r->w.seat_generation,
2109 U(r->w.stats.transitions[RX_RUNNING][RX_FAILED] - fails0), U(n_fail), U(mem_held),
2110 U(mem_after), U(kfail ? kfail->wake_cause : 0), U(stimulus));
2111 /* The old seat's window is not the object: the canonical value came back. */
2112 CHECK(field(r, r->lout[0], 0) != UINT64_MAX, "E: output");
2113 /* A new seat on the same image; the retry was already posted under the
2114 * new seat generation by the loss itself. */
2115 int relaunched = 1;
2116#ifdef R14_SILICON
2117 relaunched = rx_gpu_seat_relaunch(r->seat) == 0;
2118#else
2119 atomic_store(&r->acceptor_pause, 0);
2120#endif
2121 CHECK(relaunched, "E: the seat did not come back");
2122 t = now_ns();
2123 while (lane_done(r, 0) != r->lane_sent[0] && now_ns() - t < 10000000000ull) pause_us(500);
2124 uint64_t recover_ms = (now_ns() - t_kill) / 1000000u;
2125 uint64_t pub_id = 0;
2126 uint64_t retried_pub = crumbs_of(r, r->r_lane[0], RX_CRUMB_COMMIT, 0, mark, &pub_id);
2127 const RxCrumb *kpub = rx_world_crumb(&r->w, pub_id);
2128 int retried = lane_done(r, 0) == r->lane_sent[0] && retried_pub == 1 && kpub &&
2129 kpub->wake_cause == fail_id && kpub->worker == RX_SEAT_BLACKWELL &&
2130 r->w.reactions[r->r_lane[0]].commits == pub0 + 1 && field(r, r->lchk[0], 2) == 0;
2131 CHECK(retried, "E: retry published %llu times, lane %llu of %llu", U(retried_pub),
2132 U(lane_done(r, 0)), U(r->lane_sent[0]));
2133 /* The dead seat's claim, posted again: the new seat refuses it and nothing lands. */
2134 uint64_t stale0 = atomic_load(&r->acc_stale);
2135 uint64_t out_before = field(r, r->lout[0], 0);
2136 CHECK(rx_world_inject_descriptor(&r->w, &old) == RX_OK, "E: old claim");
2137 t = now_ns();
2138 while (atomic_load(&r->acc_stale) == stale0 && now_ns() - t < 5000000000ull) pause_us(500);
2139 int stale_refused = atomic_load(&r->acc_stale) > stale0 &&
2140 r->w.reactions[r->r_lane[0]].commits == pub0 + 1 &&
2141 field(r, r->lout[0], 0) == out_before;
2142 CHECK(stale_refused, "E: the dead seat's claim was not refused");
2143 uint32_t moved = 0;
2144 for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++)
2145 if (r->w.objects[i].live && r->w.objects[i].generation != gens[i]) moved++;
2146 int no_remint = r->aegis.mints == mints0 && field(r, lslot, 0) == slot_id0 &&
2147 field(r, lslot, 1) == slot_gen0;
2148 CHECK(moved == 0 && no_remint, "E: %u object generations moved, mints %llu -> %llu", moved,
2149 U(mints0), U(r->aegis.mints));
2150 uint64_t during = served(r) - served_hold;
2151 /* Resume: the lanes and production keep going on the new seat. */
2152 uint64_t lanes_at = lanes_done(r);
2153 atomic_store(&dv.pause, 0);
2154 CHECK(wait_lanes(r, lanes_at + 3 * LANES, 30000) == 0, "E: lanes did not resume");
2155 driver_stop(&dv);
2156 CHECK(wait_lanes(r, lanes_sent(r), 30000) == 0, "E: lanes did not drain");
2157 res->prod_during = during;
2158 res->fault_observed = claimed && held && killed;
2159 finish(r, res, 100);
2160 LaneTotals lt;
2161 lane_totals(r, &lt);
2162 CHECK(lt.lost == 0 && lt.duplicates == 0 && lt.mismatches == 0,
2163 "E: lanes lost %llu duplicated %llu mismatched %llu", U(lt.lost), U(lt.duplicates),
2164 U(lt.mismatches));
2165 snprintf(res->containment, sizeof res->containment,
2166 "R12 seat loss: the held claim ended FAILED (RX_ERR_SEAT_LOST) once, its charge "
2167 "released, the seat generation moved");
2168 snprintf(res->recovery, sizeof res->recovery,
2169 "the seat was relaunched on the same image; the retry, caused by the loss crumb, "
2170 "published once; the dead seat's claim was refused");
2171 extra(res, "\"kill_method\": \"%s\", \"claim_held_at_kill\": %s, \"claims_lost\": %d, "
2172 "\"seat_generation_before\": %u, \"seat_generation_after\": %u, "
2173 "\"loss_crumbs\": %llu, \"loss_names_stimulus\": %s, \"bytes_held_before\": %llu, "
2174 "\"bytes_held_after_loss\": %llu, \"retry_publications\": %llu, "
2175 "\"retry_caused_by_loss\": %s, \"stale_result_refused\": %s, "
2176 "\"object_generations_moved\": %u, \"authority_reminted\": %s, "
2177 "\"kill_ms\": %llu, \"recovery_ms\": %llu, \"claims\": %llu, \"completions\": %llu, "
2178 "\"failures\": %llu, \"retries\": 1, \"duplicates\": %llu, \"lost\": %llu",
2179#ifdef R14_SILICON
2180 "host destroys the running GB10 channel group (rx_gpu_seat_kill); not a chip-raised fault",
2181#else
2182 "processor stand-in not stepped, then declared lost",
2183#endif
2184 held ? "true" : "false", lost, seat_gen0, r->w.seat_generation, U(n_fail),
2185 kfail && kfail->wake_cause == stimulus ? "true" : "false", U(mem_held), U(mem_after),
2186 U(retried_pub), kpub && kpub->wake_cause == fail_id ? "true" : "false",
2187 stale_refused ? "true" : "false", moved, no_remint ? "false" : "true", U(kill_ms),
2188 U(recover_ms), U(res->acc.claims), U(res->acc.committed_seat), U(res->acc.failed_seat),
2189 U(lt.duplicates), U(lt.lost));
2190 printf("R14 E: seat killed holding lane claim %llu; lost once, seat generation %u -> %u, "
2191 "retry published once, stale claim refused; production %llu during, %llu after\n",
2192 U(seq), seat_gen0, r->w.seat_generation, U(during), U(res->prod_after));
2193 stop(r);
2194 free(r);
2195 res->ran = 1;
2196 res->pass = g_fail == fails;
2197}
2198
2199/* ---- F: crash inside the R9 promotion the organism itself makes -------------
2200 * First process: the R13 body adapts; R9 is set to stop the process (_exit)
2201 * at one crash point inside rx_gen_promote, on the promotion authority's own
2202 * activation. Second process: the canonical recovery entry (rx_gen_recover),
2203 * then a new body on the same R9 directory; the body starting is published,
2204 * generation.restore rebuilds what was in force; production resumes. With the
2205 * old generation, the body adapts again and promotes a new one. */
2206typedef struct {
2207 /* first process */
2208 uint64_t served, gen_before, hook_ran, hook_links, hook_links_ok, hook_crumbs, hook_crumbs_ok;
2209 uint8_t hook_prov_sha[32];
2210 /* second process */
2211 int rec_rc, coherent, receipt_before, receipt_after, event_present, torn;
2212 uint64_t rec_active, rec_lineage;
2213 uint64_t restore_outcome, restore_why, restore_active, restore_id0, inforce_gen;
2214 int restore_by_boot, prov_ok, prov_same;
2215 uint64_t prov_links, served2, wrong2, realized2;
2216 int readapt_ok;
2217 uint64_t readapt_gen, readapt_lineage, readapt_served;
2218 int crumbs_ok;
2219 uint64_t crumbs;
2220 int sweep_ok, acc_ok;
2221 uint64_t holders, unexpected;
2222 char err[160];
2223} FShared;
2224
2225static FShared *g_fs;
2226static Rig *g_frig;
2227
2228/* R9 disk hook: after the candidate is on disk and before the root flip.
2229 * The dying process checks the durable provenance against its live crumbs. */
2230static void f_hook(const char *generation_dir, void *ctx) {
2231 Rig *r = ctx;
2232 char path[512];
2233 snprintf(path, sizeof path, "%s/provenance", generation_dir);
2234 RxLivingProvenance pv;
2235 FILE *f = fopen(path, "rb");
2236 size_t got = f ? fread(&pv, 1, sizeof pv, f) : 0;
2237 if (f) fclose(f);
2238 g_fs->hook_ran = 1;
2239 if (got != sizeof pv || memcmp(pv.magic, "R13PROV1", 8) != 0) return;
2240 sha256_hash((const uint8_t *)&pv, sizeof pv, g_fs->hook_prov_sha);
2241 uint64_t ok = 0;
2242 for (uint32_t i = 0; i < RX_LINK_COUNT; i++) {
2243 const RxCrumb *k = rx_world_crumb(&r->w, pv.link[i].crumb);
2244 if (k && memcmp(k->digest, pv.link[i].digest, 32) == 0 &&
2245 k->reaction == pv.link[i].reaction) ok++;
2246 }
2247 g_fs->hook_links = RX_LINK_COUNT;
2248 g_fs->hook_links_ok = ok;
2249 g_fs->hook_crumbs_ok = rx_world_verify_crumbs(&r->w, &g_fs->hook_crumbs) == 0;
2250}
2251
2252static void *f_reporter(void *arg) {
2253 Rig *r = arg;
2254 for (;;) {
2255 g_fs->served = served(r);
2256 pause_us(1000);
2257 }
2258 return NULL;
2259}
2260
2261static int f_first(const char *dir, int step) {
2262 Rig *r = calloc(1, sizeof *r);
2263 Opts o = opts();
2264 o.gen_dir = dir;
2265 o.crash_step = step;
2266 if (!r || start(r, &o) != 0) return 2;
2267 g_frig = r;
2268 uint64_t lineage = 0;
2269 rx_gen_active(r->gen, &g_fs->gen_before, &lineage);
2270 rx_gen_set_disk_hook(r->gen, f_hook, r);
2271 pthread_t rep;
2272 pthread_create(&rep, NULL, f_reporter, r);
2273 Episode ep;
2274 int rc = adapt(r, &ep);
2275 snprintf(g_fs->err, sizeof g_fs->err, "the first process was not stopped (adapt %d)", rc);
2276 return 3; /* the crash point never fired */
2277}
2278
2279static int receipt_of(const char *dir, uint64_t id) {
2280 char path[512];
2281 snprintf(path, sizeof path, "%s/g/%llu/receipt", dir, U(id));
2282 return access(path, R_OK) == 0;
2283}
2284
2285static int f_second(const char *dir, uint64_t want_active) {
2286 FShared *s = g_fs;
2287 s->receipt_before = receipt_of(dir, 2);
2288 RxRecoveryRecord rec;
2289 s->rec_rc = rx_gen_recover(dir, &rec);
2290 s->torn = s->rec_rc == RX_GEN_ERR_TORN;
2291 if (s->rec_rc != RX_GEN_OK) return 4;
2292 s->coherent = rec.coherent;
2293 s->rec_active = rec.active_id;
2294 s->rec_lineage = rec.lineage;
2295 s->event_present = rec.event_present;
2296 s->receipt_after = receipt_of(dir, 2);
2297 Rig *r = calloc(1, sizeof *r);
2298 Opts o = opts();
2299 o.gen_dir = dir;
2300 if (!r || start(r, &o) != 0) return 5;
2301 if (start_acceptor(r) != 0) return 6;
2302 /* The body starts where R13 starts it: on the A725 cores, and says so. */
2303 cpu_set_t ca, cx;
2304 if (core_sets(&ca, &cx) != 0 || move_threads(&ca) <= 0 || publish_placement(r, CLASS_A725) != 0)
2305 return 9;
2306 int64_t boot = publish_boot(r);
2307 uint64_t t = now_ns();
2308 while (field(r, r->living.o.restore, 1) != (uint64_t)field(r, r->living.o.restore, 0) &&
2309 now_ns() - t < 30000000000ull)
2310 pause_us(500);
2311 s->restore_outcome = field(r, r->living.o.restore, 2);
2312 s->restore_why = field(r, r->living.o.restore, 5);
2313 s->restore_active = field(r, r->living.o.restore, 3);
2314 s->restore_id0 = field(r, r->living.o.restore, 4);
2315 s->inforce_gen = field(r, r->living.o.inforce, 7);
2316 uint64_t kr = rx_world_explain(&r->w, r->living.o.restore, 2);
2317 const RxCrumb *k = rx_world_crumb(&r->w, kr);
2318 s->restore_by_boot = boot > 0 && k && k->reaction == r->living.r_restore &&
2319 k->wake_cause == (uint64_t)boot && k->episode == (uint64_t)boot;
2320 /* The durable provenance of the recovered generation, read through R9. */
2321 if (rec.active_id != 1) {
2322 RxLivingProvenance pv;
2323 size_t n = 0;
2324 if (rx_gen_read_blob(r->gen, rec.active_id, "provenance", (uint8_t *)&pv, sizeof pv, &n) ==
2325 RX_GEN_OK && n == sizeof pv && memcmp(pv.magic, "R13PROV1", 8) == 0) {
2326 uint8_t sha[32];
2327 sha256_hash((const uint8_t *)&pv, sizeof pv, sha);
2328 s->prov_same = memcmp(sha, s->hook_prov_sha, 32) == 0;
2329 uint64_t links = 0;
2330 for (uint32_t i = 0; i < RX_LINK_COUNT; i++) {
2331 int nonzero = 0;
2332 for (uint32_t j = 0; j < 32; j++) nonzero |= pv.link[i].digest[j];
2333 if (pv.link[i].crumb && nonzero) links++;
2334 }
2335 const uint32_t order[] = {RX_LINK_GOAL, RX_LINK_PLAN, RX_LINK_SEARCH,
2336 RX_LINK_GPU_INPUT, RX_LINK_GPU_OUTPUT, RX_LINK_EVIDENCE, RX_LINK_BELIEF,
2337 RX_LINK_SELECTION};
2338 int ordered = 1;
2339 for (uint32_t i = 1; i < sizeof order / sizeof order[0]; i++)
2340 if (pv.link[order[i]].crumb <= pv.link[order[i - 1]].crumb) ordered = 0;
2341 s->prov_links = links;
2342 s->prov_ok = links == RX_LINK_COUNT && ordered && pv.epoch >= 2;
2343 }
2344 }
2345 /* Production restarts on whatever is in force now. */
2346 if (start_producer(r) != 0 || produce(r, 200, 60000) != 0) return 7;
2347 s->served2 = served(r);
2348 s->wrong2 = r->wrong;
2349 s->realized2 = r->omega.served_realized;
2350 if (want_active == 1) {
2351 /* The old generation came back: the organism adapts again by itself. */
2352 stop_producer(r);
2353 Episode ep;
2354 int arc = adapt(r, &ep);
2355 s->readapt_ok = arc == 0 && ep.promoted;
2356 if (!s->readapt_ok)
2357 snprintf(s->err, sizeof s->err, "adapt %d plan %llu search %llu selection %llu "
2358 "evidence %llu candidate %llu promotion %llu refusal %d result %d crumbs %llu",
2359 arc, U(field(r, r->aien.o.plan, 0)), U(field(r, r->omega.o.search, 0)),
2360 U(field(r, r->omega.o.selection, 0)), U(field(r, r->living.o.evidence, 0)),
2361 U(field(r, r->living.o.candidate, 0)), U(field(r, r->living.o.promotion, 0)),
2362 r->living.last_refusal, r->promoter.result, U(r->w.n_crumbs));
2363 uint64_t lin = 0;
2364 rx_gen_active(r->gen, &s->readapt_gen, &lin);
2365 s->readapt_lineage = lin;
2366 s->readapt_served = served(r);
2367 }
2368 Result res;
2369 memset(&res, 0, sizeof res);
2370 finish(r, &res, 100);
2371 s->crumbs_ok = res.crumbs_ok;
2372 s->crumbs = res.crumbs;
2373 s->sweep_ok = res.sweep_ok;
2374 s->acc_ok = res.acc.ok;
2375 s->holders = res.holders;
2376 s->unexpected = res.unexpected;
2377 s->wrong2 = r->wrong;
2378 stop(r);
2379 free(r);
2380 return g_fail ? 8 : 0;
2381}
2382
2383static int run_child(int (*fn)(const char *, int), const char *dir, int arg, int timeout_s,
2384 int *status) {
2385 pid_t pid = fork();
2386 if (pid < 0) return -1;
2387 if (pid == 0) {
2388 g_fail = 0;
2389 _exit(fn(dir, arg));
2390 }
2391 uint64_t t = now_ns();
2392 for (;;) {
2393 pid_t w = waitpid(pid, status, WNOHANG);
2394 if (w == pid) return 0;
2395 if (w < 0 && errno != EINTR) return -1;
2396 if (now_ns() - t > (uint64_t)timeout_s * 1000000000ull) {
2397 kill(pid, SIGKILL);
2398 waitpid(pid, status, 0);
2399 return -2;
2400 }
2401 pause_us(10000);
2402 }
2403}
2404
2405static int f_second_int(const char *dir, int want) { return f_second(dir, (uint64_t)want); }
2406
2407typedef struct {
2408 int step, exit_first, exit_second;
2409 uint64_t want, recovered;
2410 FShared s;
2411} FRow;
2412static FRow g_rows[8];
2413
2414static void scenario_f(void) {
2415 Result *res = &g_res[5];
2416 int fails = g_fail;
2417 g_fs = mmap(NULL, sizeof *g_fs, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
2418 if (g_fs == MAP_FAILED) { CHECK(0, "F: shared memory"); return; }
2419 const int steps[8] = {RX_CRASH_BEFORE_CANDIDATE_WRITE, RX_CRASH_DURING_CANDIDATE_WRITE,
2420 RX_CRASH_AFTER_CANDIDATE_WRITE, RX_CRASH_BEFORE_ROOT_FLIP, RX_CRASH_DURING_ROOT_FLIP,
2421 RX_CRASH_AFTER_ROOT_FLIP, RX_CRASH_BEFORE_RECEIPT, RX_CRASH_AFTER_RECEIPT};
2422 /* The root flip is the commit: before it the old generation, after it the new. */
2423 const uint64_t want[8] = {1, 1, 1, 1, 1, 2, 2, 2};
2424 static const char *names[8] = {"BEFORE_CANDIDATE_WRITE", "DURING_CANDIDATE_WRITE",
2425 "AFTER_CANDIDATE_WRITE", "BEFORE_ROOT_FLIP", "DURING_ROOT_FLIP", "AFTER_ROOT_FLIP",
2426 "BEFORE_RECEIPT", "AFTER_RECEIPT"};
2427 int all_crashed = 1;
2428 uint64_t prod_before = 0, prod_after = 0, crumbs = 0;
2429 int crumbs_ok = 1, sweep_ok = 1, acc_ok = 1;
2430 extra(res, "\"crash_matrix\": [");
2431 for (int i = 0; i < 8; i++) {
2432 FRow *row = &g_rows[i];
2433 memset(g_fs, 0, sizeof *g_fs);
2434 char dir[64];
2435 if (!mkdtemp(strcpy(dir, "/tmp/r14-crash-XXXXXX"))) { CHECK(0, "F: dir"); continue; }
2436 int st = 0;
2437 int w = run_child(f_first, dir, steps[i], 240, &st);
2438 row->step = steps[i];
2439 row->want = want[i];
2440 row->exit_first = w == 0 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
2441 CHECK(row->exit_first == 86, "F %s: the first process ended with %d (%s)", names[i],
2442 row->exit_first, g_fs->err);
2443 if (row->exit_first != 86) all_crashed = 0;
2444 w = run_child(f_second_int, dir, (int)want[i], 400, &st);
2445 row->exit_second = w == 0 && WIFEXITED(st) ? WEXITSTATUS(st) : -1;
2446 row->s = *g_fs;
2447 FShared *s = &row->s;
2448 row->recovered = s->rec_active;
2449 CHECK(row->exit_second == 0, "F %s: the restarted process ended with %d", names[i],
2450 row->exit_second);
2451 CHECK(s->rec_rc == RX_GEN_OK && s->coherent && !s->torn && s->rec_active == want[i] &&
2452 s->rec_lineage == want[i],
2453 "F %s: recovered %llu (lineage %llu, rc %d), want %llu", names[i], U(s->rec_active),
2454 U(s->rec_lineage), s->rec_rc, U(want[i]));
2455 /* A receipt exists only for a generation that was committed; recovery may
2456 * complete a committed flip's receipt, never invent one. */
2457 CHECK(want[i] == 2 ? s->receipt_after : (!s->receipt_before && !s->receipt_after),
2458 "F %s: receipt before %d after %d", names[i], s->receipt_before, s->receipt_after);
2459 CHECK(s->event_present, "F %s: the recovered generation has no event", names[i]);
2460 uint64_t want_outcome = want[i] == 2 ? RX_LIVING_RESTORE_RESTORED
2461 : RX_LIVING_RESTORE_REFERENCE;
2462 CHECK(s->restore_outcome == want_outcome && s->restore_active == want[i] &&
2463 s->restore_by_boot,
2464 "F %s: restore outcome %llu (why %llu) for generation %llu, caused by boot %d",
2465 names[i], U(s->restore_outcome), U(s->restore_why), U(s->restore_active),
2466 s->restore_by_boot);
2467 if (want[i] == 2) {
2468 CHECK(s->inforce_gen == 2 && s->realized2 > 0 && s->prov_ok && s->prov_same &&
2469 s->hook_links_ok == RX_LINK_COUNT && s->hook_crumbs_ok,
2470 "F %s: in force %llu, realized %llu, provenance %d same %d, links %llu/%llu",
2471 names[i], U(s->inforce_gen), U(s->realized2), s->prov_ok, s->prov_same,
2472 U(s->hook_links_ok), U(s->hook_links));
2473 } else {
2474 CHECK(s->inforce_gen == 0 && s->realized2 == 0 && s->readapt_ok &&
2475 s->readapt_lineage == 2 && s->readapt_gen >= 3,
2476 "F %s: in force %llu, realized %llu, adapted again %d to %llu (lineage %llu): %s",
2477 names[i], U(s->inforce_gen), U(s->realized2), s->readapt_ok,
2478 U(s->readapt_gen), U(s->readapt_lineage), s->err);
2479 }
2480 CHECK(s->wrong2 == 0 && s->served2 >= 200, "F %s: production after restart %llu, wrong %llu",
2481 names[i], U(s->served2), U(s->wrong2));
2482 CHECK(s->crumbs_ok && s->sweep_ok && s->acc_ok, "F %s: audits crumbs %d sweep %d "
2483 "accounting %d", names[i], s->crumbs_ok, s->sweep_ok, s->acc_ok);
2484 prod_before += s->served;
2485 prod_after += s->served2;
2486 crumbs += s->crumbs;
2487 crumbs_ok &= s->crumbs_ok;
2488 sweep_ok &= s->sweep_ok;
2489 acc_ok &= s->acc_ok;
2490 extra(res, "%s{\"crash_point\": \"%s\", \"first_process_exit\": %d, "
2491 "\"recovered_old_or_new\": \"%s\", \"recovered_generation\": %llu, "
2492 "\"recovered_lineage\": %llu, \"torn_generation_detected\": %s, "
2493 "\"receipt_before_recovery\": %s, \"receipt_after_recovery\": %s, "
2494 "\"restore\": \"%s\", \"restore_caused_by_boot\": %s, \"in_force_generation\": %llu, "
2495 "\"production_before_crash\": %llu, \"production_after_restart\": %llu, "
2496 "\"production_used_restored_realization\": %llu, "
2497 "\"durable_provenance_links\": %llu, \"provenance_links_checked_before_crash\": %llu, "
2498 "\"provenance_bytes_same_after_restart\": %s, \"adapted_again_to_generation\": %llu}",
2499 i ? ", " : "", names[i], row->exit_first, s->rec_active == 1 ? "OLD" : "NEW",
2500 U(s->rec_active), U(s->rec_lineage), s->torn ? "true" : "false",
2501 s->receipt_before ? "true" : "false", s->receipt_after ? "true" : "false",
2502 s->restore_outcome == RX_LIVING_RESTORE_RESTORED ? "RESTORED"
2503 : s->restore_outcome == RX_LIVING_RESTORE_REFERENCE ? "REFERENCE" : "REFUSED",
2504 s->restore_by_boot ? "true" : "false", U(s->inforce_gen), U(s->served),
2505 U(s->served2), U(s->realized2), U(s->prov_links), U(s->hook_links_ok),
2506 s->prov_same ? "true" : "false", U(s->readapt_gen));
2507 printf("R14 F %s: first process exit %d; recovered %s generation %llu; restore %s; "
2508 "%llu served after restart%s\n", names[i], row->exit_first,
2509 s->rec_active == 1 ? "OLD" : "NEW", U(s->rec_active),
2510 s->restore_outcome == RX_LIVING_RESTORE_RESTORED ? "RESTORED" : "REFERENCE",
2511 U(s->served2), want[i] == 1 ? (s->readapt_ok ? ", adapted again" : ", NOT adapted")
2512 : "");
2513 char cmd[128];
2514 snprintf(cmd, sizeof cmd, "rm -rf '%s'", dir);
2515 if (system(cmd) != 0) fprintf(stderr, "could not remove %s\n", dir);
2516 }
2517 extra(res, "]");
2518 res->fault_observed = all_crashed;
2519 res->prod_before = prod_before;
2520 res->prod_during = 0; /* the process was dead */
2521 res->prod_after = prod_after;
2522 res->crumbs = crumbs;
2523 res->crumbs_ok = crumbs_ok;
2524 res->sweep_ok = sweep_ok;
2525 res->acc.ok = acc_ok;
2526 res->holders = 1;
2527 res->gen_before = 1;
2528 res->gen_after = 0;
2529 for (int i = 0; i < 8; i++)
2530 if (g_rows[i].recovered > res->gen_after) res->gen_after = g_rows[i].recovered;
2531 snprintf(res->containment, sizeof res->containment,
2532 "the process stopped inside rx_gen_promote at each R9 crash point");
2533 snprintf(res->recovery, sizeof res->recovery,
2534 "rx_gen_recover in a new process; generation.restore re-verified and put the "
2535 "recovered generation in force (or the reference for genesis); production resumed");
2536 munmap(g_fs, sizeof *g_fs);
2537 g_fs = NULL;
2538 res->ran = 1;
2539 res->pass = g_fail == fails;
2540}
2541
2542/* ---- receipt ------------------------------------------------------------------ */
2543static void binary_digest(char out[65]) {
2544 strcpy(out, "unavailable");
2545 FILE *f = fopen("/proc/self/exe", "rb");
2546 if (!f) return;
2547 sha256_ctx c;
2548 sha256_init(&c);
2549 uint8_t block[65536], digest[32];
2550 size_t n;
2551 while ((n = fread(block, 1, sizeof block, f)) > 0) sha256_update(&c, block, n);
2552 fclose(f);
2553 sha256_final(&c, digest);
2554 hex(digest, 32, out);
2555}
2556
2557static int receipt(int tests_ok) {
2558 char path[512], commit[41] = {0}, binary[65], physics[80] = {0};
2559 if (omega_evidence_path("R14/rx_recovery_receipt.json", path, sizeof path) != 0) return 0;
2560 if (!omega_evidence_run_commit(commit)) strcpy(commit, "unknown");
2561 if (!omega_evidence_physics_commit(physics, sizeof physics)) strcpy(physics, "unknown");
2562 binary_digest(binary);
2563 const char *candidate = getenv("OMEGA_CANDIDATE_COMMIT");
2564 const char *aienos = getenv("AIENOS_COMMIT");
2565 int dirty = omega_evidence_tree_dirty();
2566 int bound = candidate && candidate[0] && strcmp(candidate, commit) == 0 && !dirty;
2567 int silicon = 0;
2568#ifdef R14_SILICON
2569 silicon = 1;
2570#endif
2571 int all = tests_ok;
2572 for (int i = 0; i < 6; i++) all &= g_res[i].ran && g_res[i].pass;
2573 int pass = all && bound && silicon;
2574 const char *gate = pass ? "PASS" : !all ? "FAIL" : !silicon ? "HOST_PASS_NON_SILICON"
2575 : "SILICON_PASS_UNBOUND";
2576 struct utsname host;
2577 memset(&host, 0, sizeof host);
2578 uname(&host);
2579 FILE *f = omega_evidence_create(path);
2580 if (!f) return 0;
2581 uint64_t crumbs = 0, holders_max = 0, unexpected = 0;
2582 uint64_t final_gen = 0;
2583 for (int i = 0; i < 5; i++) if (g_res[i].gen_after > final_gen) final_gen = g_res[i].gen_after;
2584 int causal = 1;
2585 for (int i = 0; i < 6; i++) {
2586 crumbs += g_res[i].crumbs;
2587 causal &= g_res[i].crumbs_ok;
2588 unexpected += g_res[i].unexpected;
2589 if (g_res[i].holders > holders_max) holders_max = g_res[i].holders;
2590 }
2591 fprintf(f,
2592 "{\n"
2593 " \"schema\": \"AIEN_RX_R14_LIVING_RECOVERY_V1\",\n"
2594 " \"run_id\": \"%s\",\n"
2595 " \"candidate_commit\": \"%s\",\n"
2596 " \"run_commit\": \"%s\",\n"
2597 " \"candidate_bound\": %s,\n"
2598 " \"tree_dirty\": %s,\n"
2599 " \"aienos_commit\": \"%s\",\n"
2600 " \"physics_forge_commit\": \"%s\",\n"
2601 " \"test_binary_sha256\": \"%s\",\n"
2602 " \"machine_identity\": {\"node\": \"%s\", \"system\": \"%s\", \"release\": \"%s\", "
2603 "\"architecture\": \"%s\"},\n"
2604 " \"silicon_observed\": %s,\n"
2605 " \"gate\": {\"R14_LIVING_RECOVERY\": \"%s\"},\n"
2606 " \"r13_baseline_generation\": 1,\n"
2607 " \"final_generation\": %llu,\n"
2608 " \"recovered_generations\": [%llu, %llu, %llu, %llu, %llu, %llu, %llu, %llu],\n"
2609 " \"body\": \"R13 organism (rx_living) with R6 on: activation budget %u per causal "
2610 "episode\",\n"
2611 " \"scenarios\": {\n",
2612 omega_evidence_run_id(), candidate ? candidate : "unknown", commit,
2613 bound ? "true" : "false", dirty ? "true" : "false", aienos ? aienos : "unknown", physics,
2614 binary, host.nodename, host.sysname, host.release, host.machine,
2615 silicon ? "true" : "false", gate, U(final_gen), U(g_rows[0].recovered),
2616 U(g_rows[1].recovered), U(g_rows[2].recovered), U(g_rows[3].recovered),
2617 U(g_rows[4].recovered), U(g_rows[5].recovered), U(g_rows[6].recovered),
2618 U(g_rows[7].recovered), BUDGET);
2619 for (int i = 0; i < 6; i++) {
2620 const Result *s = &g_res[i];
2621 fprintf(f,
2622 " \"%s\": {\"result\": \"%s\", \"fault_observed\": %s, "
2623 "\"containment_result\": \"%s\", \"recovery_result\": \"%s\", "
2624 "\"production_before\": %llu, \"production_during_fault_window\": %llu, "
2625 "\"production_after\": %llu, \"crumbs_verified\": %llu, "
2626 "\"crumbs_evidence_verified\": %s, \"authority_sweep\": \"%s\", "
2627 "\"promotion_right_holders\": %llu, \"unexpected_privileged_holders\": %llu, "
2628 "\"resource_claim_accounting\": \"%s\", \"claims\": %llu, \"claims_closed\": %llu, "
2629 "\"inflight_final\": %llu, \"held_resource_charges\": %llu, "
2630 "\"active_generation_before\": %llu, \"active_generation_after\": %llu, %s}%s\n",
2631 g_names[i], s->ran ? (s->pass ? "PASS" : "FAIL") : "NOT_RUN",
2632 s->fault_observed ? "true" : "false", s->containment, s->recovery,
2633 U(s->prod_before), U(s->prod_during), U(s->prod_after), U(s->crumbs),
2634 s->crumbs_ok ? "true" : "false", s->sweep_ok ? "PASS" : "FAIL", U(s->holders),
2635 U(s->unexpected), s->acc.ok ? "PASS" : "FAIL", U(s->acc.claims), U(s->acc.closed),
2636 U(s->acc.inflight), U(s->acc.used_slots + s->acc.holding), U(s->gen_before),
2637 U(s->gen_after), s->extra[0] ? s->extra : "\"-\": null", i < 5 ? "," : "");
2638 }
2639 fprintf(f,
2640 " },\n"
2641 " \"authority\": {\"promotion_right_holders\": %llu, \"promotion_subject\": %u, "
2642 "\"unexpected_privileged_holders\": %llu},\n"
2643 " \"causal\": {\"crumb_count\": %llu, \"causal_verification_result\": \"%s\", "
2644 "\"durable_evidence_links_verified\": %s},\n"
2645 " \"earlier_gate_defects_fixed\": [\n"
2646 " \"R6: the activation budget reset only on a direct outside wake, so reactions one "
2647 "step down a chain (omega.watch, aien.observe) were quarantined after 256 "
2648 "activations over the body's life; now counted per causal episode (regression: "
2649 "episode_activation_budget in test-r3)\",\n"
2650 " \"R6: containment left no causal record; now a QUARANTINE crumb names the reaction, "
2651 "the limit and the episode\",\n"
2652 " \"R8/R12: after an R8 renewal the seat claim presented the revoked reference bound "
2653 "at start, so honest GPU work was refused forever; the claim now presents what the "
2654 "slot holds (regression: slot renewal in test-r12)\",\n"
2655 " \"R12: the GB10 seat refused every claim on an object id of 64 or more (it used the frozen "
2656 "ABI's 64-entry table size; the world projects RX_MAX_OBJECTS = 256 and the host "
2657 "stand-in accepted them), so GPU work on later objects failed on silicon only; found by "
2658 "scenario D (regression: objects past id 64 in test-r12-silicon)\",\n"
2659" \"R9: draft slots were never freed, so a body could promote at most four times per "
2660 "process; a promoted or stale draft now frees its slot (regression in test-r9)\"\n"
2661 " ],\n"
2662 " \"limits\": [\n"
2663 " \"R8: a principal wrongly given WRITE on a decision object can jam decisions until "
2664 "it is revoked; it cannot cause a mint\",\n"
2665 " \"R9: rx_gen_propose checks the proposer credential (R16 C6) but no capability; an "
2666 "enrolled in-process proposer can hold up to four unpromotable drafts until the "
2667 "generation moves\",\n"
2668 " \"R10: Omega's store keeps the first bytes filed under an identity; bytes that "
2669 "falsely claim an identity block the honest bytes for that identity in that "
2670 "process (found by reading, not exercised)\",\n"
2671 " \"the authority table is the host-library C port; it does not survive a process "
2672 "restart, and the restarted body mints its grants again\",\n"
2673 " \"the seat is killed by destroying its channel from the host; a chip-raised fault "
2674 "(MMU fault, Xid) is not exercised\"\n"
2675 " ],\n"
2676 " \"not_claimed\": [\"R15\", \"R16\", \"neural/general cognition beyond R11\", "
2677 "\"open-ended invention beyond R10\", "
2678 "\"AIENOS kernel isolation (authority is the host-library C port)\", "
2679 "\"immunity to every hardware fault\", \"recovery from machine destruction\", "
2680 "\"Byzantine hardware\", \"kernel/root compromise\", \"performance\"]\n"
2681 "}\n",
2682 U(holders_max), (unsigned)RX_LIVING_PROMOTE_SUBJ, U(unexpected), U(crumbs),
2683 causal ? "PASS" : "FAIL", g_res[5].pass ? "true" : "false");
2684 fclose(f);
2685 printf("R14 gate: R14_LIVING_RECOVERY=%s\nR14 receipt: %s\n", gate, path);
2686 return pass;
2687}
2688
2689int main(int argc, char **argv) {
2690 signal(SIGPIPE, SIG_IGN);
2691 setvbuf(stdout, NULL, _IONBF, 0);
2692 if (seen_fit(CRUMBS) != 0) return 1;
2693 const char *only = argc > 1 ? argv[1] : NULL;
2694 /* F first: its processes are forked before this one ever opens the GPU. */
2695 if (!only || strchr(only, 'F')) scenario_f();
2696 if (!only || strchr(only, 'A')) scenario_a();
2697 if (!only || strchr(only, 'B')) scenario_b();
2698 if (!only || strchr(only, 'C')) scenario_c();
2699 if (!only || strchr(only, 'D')) scenario_d();
2700 if (!only || strchr(only, 'E')) scenario_e();
2701 for (int i = 0; i < 6; i++)
2702 printf("R14 %-22s %s\n", g_names[i],
2703 g_res[i].ran ? (g_res[i].pass ? "PASS" : "FAIL") : "NOT RUN");
2704 receipt(g_fail == 0);
2705 free(g_seen);
2706 free(g_stack);
2707 return g_fail ? 1 : 0;
2708}