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_sem_incremental.c

1530 lines · 70270 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 * rx_sem_incremental.c -- qualification of Omega semantic variables and
19 * incremental recomputation (gate OMEGA_INCREMENTAL_SEMANTICS_PASS).
20 *
21 * PROVE, against the resident world (rx_world) as the source of truth:
22 * dependency_tracking declared inputs, reverse index, transitive downstream
23 * correct_invalidation temperature dirties thermal placement (and what reads
24 * it) only; repository analysis, memory retrieval and
25 * capability resolution stay clean; unrelated world
26 * objects dirty nothing
27 * no_stale_reuse randomized differential run against a from-scratch
28 * evaluator, every hit re-computed (audit); 0 mismatches
29 * generation_isolation object retired and re-created with the same bytes, and
30 * a promoted function generation, are never served old results
31 * branch_isolation J-Space candidate writes never reach the parent, a
32 * sibling, or the world
33 * cross_branch_reuse same inputs across branch, agent, task and candidate
34 * reuse one result
35 * causal_provenance every entry and reuse event re-verified; a reused
36 * value explains back to its producer and to the world
37 * crumbs of its inputs; tampering is detected
38 *
39 * MEASURE, one deterministic workload replayed four ways:
40 * FULL recompute every derived value on every query (no incremental state)
41 * OBJECT memo + early cutoff, object-granular invalidation
42 * FIELD memo + early cutoff, field-granular invalidation
43 * ENGINE FIELD + the shared content-addressed cache
44 * recomputation avoided, compute saved, latency saved, energy saved (package
45 * energy counter, when the machine exposes one), cache-hit rate, false-hit
46 * rate, unnecessary invalidation rate.
47 *
48 * The derivations are stand-ins with real CPU cost (SHA-256 chains, vector
49 * scoring, table walks). They are not the AIEN model; the claim is when
50 * derived work runs, not what the cognition is.
51 */
52#include "runtime/rx_semantic.h"
53#include "runtime/rx_world.h"
54#include "runtime/rx_caproot.h"
55#include "omega_evidence.h"
56#include "sha256.h"
57
58#include <dirent.h>
59#include <inttypes.h>
60#include <stdio.h>
61#include <stdlib.h>
62#include <string.h>
63#include <sys/utsname.h>
64#include <time.h>
65#include <unistd.h>
66
67#define U(x) ((unsigned long long)(x))
68
69/* ---- harness --------------------------------------------------------------- */
70
71typedef struct {
72 const char *name;
73 int checks;
74 int failures;
75} Test;
76
77static Test g_tests[32];
78static int g_ntests;
79static Test *g_cur;
80
81#define CHECK(cond, ...) \
82 do { \
83 g_cur->checks++; \
84 if (!(cond)) { \
85 g_cur->failures++; \
86 fprintf(stderr, " FAIL %s:%d [%s] ", __FILE__, __LINE__, g_cur->name); \
87 fprintf(stderr, __VA_ARGS__); \
88 fputc('\n', stderr); \
89 } \
90 } while (0)
91
92static void begin(const char *name) {
93 g_cur = &g_tests[g_ntests++];
94 g_cur->name = name;
95 printf("[*] %s\n", name);
96}
97
98static bool test_ok(const char *name) {
99 for (int i = 0; i < g_ntests; i++)
100 if (strcmp(g_tests[i].name, name) == 0) return g_tests[i].failures == 0 && g_tests[i].checks > 0;
101 return false;
102}
103
104static uint64_t now_ns(void) {
105 struct timespec ts;
106 clock_gettime(CLOCK_MONOTONIC, &ts);
107 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
108}
109
110static void hex(const uint8_t *b, size_t n, char *out) {
111 static const char *d = "0123456789abcdef";
112 for (size_t i = 0; i < n; i++) {
113 out[2 * i] = d[b[i] >> 4];
114 out[2 * i + 1] = d[b[i] & 15];
115 }
116 out[2 * n] = 0;
117}
118
119static uint64_t splitmix(uint64_t *s) {
120 uint64_t z = (*s += 0x9e3779b97f4a7c15ull);
121 z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull;
122 z = (z ^ (z >> 27)) * 0x94d049bb133111ebull;
123 return z ^ (z >> 31);
124}
125
126/* ---- the derivations ------------------------------------------------------- */
127
128/* Work sizes. The qualification checks use small ones so the differential
129 * evaluator can run many operations; the measurement uses realistic ones. */
130typedef struct {
131 uint32_t thermal; /* mixing rounds */
132 uint32_t repo; /* SHA-256 chain length */
133 uint32_t memory; /* candidate vectors scored (32 dims each) */
134 uint32_t caps; /* table entries walked */
135 uint32_t plan; /* mixing rounds */
136} Work;
137
138static Work g_work;
139
140enum { T_TEMP = 0x100, T_POWER, T_FAN, T_REPO, T_MEM, T_CAPS, T_KNOB,
141 T_PLACEMENT = 0x200, T_FAN_HEALTH, T_REPO_SEM, T_RECALL, T_CAPRES, T_PLAN };
142
143static uint64_t mix_rounds(uint64_t seed, uint32_t rounds) {
144 uint64_t s = seed;
145 uint64_t acc = 0;
146 for (uint32_t i = 0; i < rounds; i++) acc ^= splitmix(&s) + i;
147 return acc;
148}
149
150/* Thermal placement over (temperature mC, power mW, knob). The decision
151 * depends on 5 C buckets, so a small drift recomputes it and returns the same. */
152static int fn_thermal(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
153 (void)user;
154 if (n != 3) return -1;
155 uint64_t bucket = in[0]->value[0] / 5000u;
156 uint64_t pw = in[1]->value[0] / 1000u;
157 uint64_t knob = in[2]->value[0];
158 uint64_t acc = mix_rounds(bucket * 1000003u + pw * 7919u + knob, g_work.thermal);
159 uint64_t core = (bucket >= 16 ? 1u : 0u) ^ (knob & 1u); /* 1 = efficiency cluster */
160 out->n_words = 4;
161 out->value[0] = core;
162 out->value[1] = bucket;
163 out->value[2] = knob;
164 out->value[3] = acc & 0xffu;
165 if (bucket >= 18) out->confidence = out->confidence * 9u / 10u;
166 return 0;
167}
168
169static int fn_fan(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
170 (void)user;
171 if (n != 1) return -1;
172 out->n_words = 1;
173 out->value[0] = in[0]->value[0] > 8000u ? 1u : 0u;
174 return 0;
175}
176
177static int fn_repo(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
178 (void)user;
179 if (n != 3) return -1;
180 uint8_t d[32];
181 uint64_t seed[3] = { in[0]->value[0], in[1]->value[0], in[2]->value[0] };
182 sha256_hash((const uint8_t *)seed, sizeof seed, d);
183 for (uint32_t i = 0; i < g_work.repo; i++) sha256_hash(d, 32, d);
184 out->n_words = 4;
185 for (int w = 0; w < 4; w++) {
186 uint64_t v = 0;
187 for (int k = 0; k < 8; k++) v |= (uint64_t)d[8 * w + k] << (8 * k);
188 out->value[w] = v;
189 }
190 return 0;
191}
192
193static int fn_recall(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
194 (void)user;
195 if (n != 2) return -1;
196 uint64_t qs = in[1]->value[0] * 0x9e37u + 1u;
197 int32_t q[32];
198 for (int i = 0; i < 32; i++) q[i] = (int32_t)(splitmix(&qs) & 0xff) - 128;
199 uint64_t ms = in[0]->value[0] * 0x51edu + 7u;
200 int64_t best = INT64_MIN;
201 uint64_t best_id = 0;
202 for (uint32_t k = 0; k < g_work.memory; k++) {
203 int64_t dot = 0;
204 for (int i = 0; i < 32; i += 8) {
205 uint64_t r = splitmix(&ms);
206 for (int j = 0; j < 8; j++) dot += (int64_t)q[i + j] * ((int64_t)((r >> (8 * j)) & 0xff) - 128);
207 }
208 if (dot > best) {
209 best = dot;
210 best_id = k;
211 }
212 }
213 out->n_words = 2;
214 out->value[0] = best_id;
215 out->value[1] = (uint64_t)best;
216 return 0;
217}
218
219static int fn_capres(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
220 (void)user;
221 if (n != 2) return -1;
222 uint64_t s = in[0]->value[0] * 31u + 3u;
223 uint64_t want = in[1]->value[0];
224 uint64_t granted = 0, rights = 0;
225 for (uint32_t i = 0; i < g_work.caps; i++) {
226 uint64_t row = splitmix(&s);
227 if ((row & 0xf) == (want & 0xf)) {
228 granted++;
229 rights |= (row >> 8) & 0xff;
230 }
231 }
232 out->n_words = 2;
233 out->value[0] = granted;
234 out->value[1] = rights;
235 return 0;
236}
237
238static int fn_plan(const RxSemValue *const *in, uint32_t n, RxSemValue *out, void *user) {
239 (void)user;
240 if (n != 4) return -1;
241 uint64_t seed = 0;
242 for (uint32_t i = 0; i < n; i++)
243 for (uint32_t w = 0; w < in[i]->n_words; w++) seed = seed * 0x100000001b3ull ^ in[i]->value[w];
244 out->n_words = 3;
245 out->value[0] = in[0]->value[0]; /* core class chosen */
246 out->value[1] = in[2]->value[0]; /* memory recalled */
247 out->value[2] = mix_rounds(seed, g_work.plan);
248 return 0;
249}
250
251/* ---- world + engine fixture ------------------------------------------------- */
252
253enum { SUBJ_EXTERNAL = 100, ISSUER = 3, RES_WORLD = 0x10 };
254enum { F_TEMP = 0, F_FAN = 1, F_POWER = 2 };
255#define N_NOISE 8
256
257typedef struct {
258 RxCapRoot root;
259 RxCapAdmin admin;
260 RxWorld w;
261 RxCapRef ext;
262 RxObjRef machine, repo, mem, caps, knob;
263 RxObjRef noise[N_NOISE];
264
265 RxSemEngine e;
266 uint32_t f_thermal, f_fan, f_repo, f_recall, f_capres, f_plan;
267 uint64_t s_temp, s_fan, s_power, s_repo0, s_repo1, s_repo2, s_mem0, s_mem1, s_caps0,
268 s_caps1, s_knob;
269 uint64_t n_placement, n_fan, n_repo, n_recall, n_capres, n_plan;
270 uint32_t root_branch;
271} Fx;
272
273static RxCapRef mint(Fx *x, uint64_t resource, uint32_t rights) {
274 RxCapMint m;
275 memset(&m, 0, sizeof m);
276 m.issuer = ISSUER;
277 m.subject = SUBJ_EXTERNAL;
278 m.resource = resource;
279 m.rights = rights;
280 m.parent = (RxCapRef){ UINT32_MAX, 0 };
281 m.authority = rx_capadmin_office(&x->admin);
282 RxCapRef r = { UINT32_MAX, 0 };
283 if (rx_capadmin_mint(&x->admin, &m, &r) != RX_CAP_OK) fprintf(stderr, "mint failed\n");
284 return r;
285}
286
287static RxObjRef mkobj(Fx *x, uint32_t type, const uint64_t *init) {
288 RxObjRef r = { UINT32_MAX, 0 };
289 rx_world_create(&x->w, type, RX_PERSIST_RESIDENT, RES_WORLD, init, &r);
290 return r;
291}
292
293static int64_t put(Fx *x, RxObjRef o, uint32_t f, uint64_t v) {
294 RxMutation m = { o, f, v };
295 return rx_world_publish_external(&x->w, x->ext, &m, 1);
296}
297
298static RxSemDigest impl(const char *s) {
299 RxSemDigest d;
300 rx_sem_digest_impl(s, &d);
301 return d;
302}
303
304static uint32_t add_fn(Fx *x, const char *name, uint32_t type, uint32_t gen, RxSemFn fn) {
305 RxSemFnDesc d = { name, type, gen, impl(name), fn, NULL };
306 uint32_t id = UINT32_MAX;
307 rx_sem_add_fn(&x->e, &d, &id);
308 return id;
309}
310
311static uint64_t src(Fx *x, RxObjRef o, uint32_t f, uint32_t t) {
312 uint64_t sid = 0;
313 rx_sem_add_source(&x->e, o, f, t, true, &sid);
314 return sid;
315}
316
317static uint64_t node(Fx *x, uint32_t fn, const uint64_t *in, uint32_t n) {
318 uint64_t sid = 0;
319 rx_sem_add_node(&x->e, fn, in, n, &sid);
320 return sid;
321}
322
323static int fx_start(Fx *x) {
324 memset(x, 0, sizeof *x);
325 if (rx_caproot_start(&x->root, &x->admin) != RX_CAP_OK) return -1;
326 if (rx_world_init(&x->w, &x->root, 1, 1u << 20) != RX_OK) return -1;
327 x->w.external_subject = SUBJ_EXTERNAL;
328 x->ext = mint(x, RES_WORLD, RX_RIGHT_WRITE | RX_RIGHT_READ);
329 uint64_t m0[RX_MAX_FIELDS] = { 60000, 3000, 45000 };
330 uint64_t r0[RX_MAX_FIELDS] = { 0xabc, 0xdef, 120 };
331 uint64_t me0[RX_MAX_FIELDS] = { 1, 7 };
332 uint64_t c0[RX_MAX_FIELDS] = { 1, 3 };
333 uint64_t k0[RX_MAX_FIELDS] = { 0 };
334 x->machine = mkobj(x, 1, m0);
335 x->repo = mkobj(x, 2, r0);
336 x->mem = mkobj(x, 3, me0);
337 x->caps = mkobj(x, 4, c0);
338 x->knob = mkobj(x, 5, k0);
339 for (int i = 0; i < N_NOISE; i++) {
340 uint64_t z[RX_MAX_FIELDS] = { (uint64_t)i };
341 x->noise[i] = mkobj(x, 9, z);
342 }
343 if (rx_sem_init(&x->e, 1u << 20) != RX_SEM_OK) return -1;
344 x->f_thermal = add_fn(x, "omega.thermal_placement", T_PLACEMENT, 1, fn_thermal);
345 x->f_fan = add_fn(x, "omega.fan_health", T_FAN_HEALTH, 1, fn_fan);
346 x->f_repo = add_fn(x, "aien.repository_semantics", T_REPO_SEM, 1, fn_repo);
347 x->f_recall = add_fn(x, "aien.memory_retrieval", T_RECALL, 1, fn_recall);
348 x->f_capres = add_fn(x, "aegis.capability_resolution", T_CAPRES, 1, fn_capres);
349 x->f_plan = add_fn(x, "aien.plan", T_PLAN, 1, fn_plan);
350 x->s_temp = src(x, x->machine, F_TEMP, T_TEMP);
351 x->s_fan = src(x, x->machine, F_FAN, T_FAN);
352 x->s_power = src(x, x->machine, F_POWER, T_POWER);
353 x->s_repo0 = src(x, x->repo, 0, T_REPO);
354 x->s_repo1 = src(x, x->repo, 1, T_REPO);
355 x->s_repo2 = src(x, x->repo, 2, T_REPO);
356 x->s_mem0 = src(x, x->mem, 0, T_MEM);
357 x->s_mem1 = src(x, x->mem, 1, T_MEM);
358 x->s_caps0 = src(x, x->caps, 0, T_CAPS);
359 x->s_caps1 = src(x, x->caps, 1, T_CAPS);
360 x->s_knob = src(x, x->knob, 0, T_KNOB);
361 uint64_t in_p[3] = { x->s_temp, x->s_power, x->s_knob };
362 uint64_t in_f[1] = { x->s_fan };
363 uint64_t in_r[3] = { x->s_repo0, x->s_repo1, x->s_repo2 };
364 uint64_t in_m[2] = { x->s_mem0, x->s_mem1 };
365 uint64_t in_c[2] = { x->s_caps0, x->s_caps1 };
366 x->n_placement = node(x, x->f_thermal, in_p, 3);
367 x->n_fan = node(x, x->f_fan, in_f, 1);
368 x->n_repo = node(x, x->f_repo, in_r, 3);
369 x->n_recall = node(x, x->f_recall, in_m, 2);
370 x->n_capres = node(x, x->f_capres, in_c, 2);
371 uint64_t in_plan[4] = { x->n_placement, x->n_repo, x->n_recall, x->n_capres };
372 x->n_plan = node(x, x->f_plan, in_plan, 4);
373 if (rx_sem_branch_root(&x->e, 1, 1, &x->root_branch) != RX_SEM_OK) return -1;
374 return rx_sem_sync_world(&x->e, x->root_branch, &x->w) >= 0 ? 0 : -1;
375}
376
377static void fx_stop(Fx *x) {
378 rx_sem_destroy(&x->e);
379 rx_world_destroy(&x->w);
380 rx_caproot_stop(&x->root, &x->admin);
381}
382
383static int st(Fx *x, uint32_t b, uint64_t sid) { return rx_sem_state(&x->e, b, sid); }
384
385static RxSemServed served_of(Fx *x, uint32_t b, uint64_t sid, RxSemValue *v) {
386 RxSemServed s = 0;
387 RxSemValue tmp;
388 if (rx_sem_get(&x->e, b, sid, v ? v : &tmp, &s) != RX_SEM_OK) return 0;
389 return s;
390}
391
392static Work small_work(void) { return (Work){ 8, 4, 16, 16, 8 }; }
393
394/* ---- a from-scratch evaluator (no engine state) ----------------------------- */
395
396typedef struct {
397 RxSemFn fn;
398 uint32_t out_type;
399 uint32_t n;
400 int in[4]; /* >= 0: source slot; < 0: -(node+1) */
401} ONode;
402
403enum { OS_TEMP, OS_POWER, OS_KNOB, OS_FAN, OS_R0, OS_R1, OS_R2, OS_M0, OS_M1, OS_C0, OS_C1, OS_N };
404enum { ON_PLACE, ON_FAN, ON_REPO, ON_RECALL, ON_CAPRES, ON_PLAN, ON_N };
405
406static const ONode g_on[ON_N] = {
407 { fn_thermal, T_PLACEMENT, 3, { OS_TEMP, OS_POWER, OS_KNOB } },
408 { fn_fan, T_FAN_HEALTH, 1, { OS_FAN } },
409 { fn_repo, T_REPO_SEM, 3, { OS_R0, OS_R1, OS_R2 } },
410 { fn_recall, T_RECALL, 2, { OS_M0, OS_M1 } },
411 { fn_capres, T_CAPRES, 2, { OS_C0, OS_C1 } },
412 { fn_plan, T_PLAN, 4, { -(ON_PLACE + 1), -(ON_REPO + 1), -(ON_RECALL + 1), -(ON_CAPRES + 1) } },
413};
414
415static void oracle_eval(int node_ix, const uint64_t *srcv, RxSemValue *out) {
416 const ONode *o = &g_on[node_ix];
417 RxSemValue vals[4];
418 const RxSemValue *in[4];
419 for (uint32_t i = 0; i < o->n; i++) {
420 memset(&vals[i], 0, sizeof vals[i]);
421 if (o->in[i] >= 0) {
422 vals[i].n_words = 1;
423 vals[i].value[0] = srcv[o->in[i]];
424 vals[i].confidence = RX_SEM_CONFIDENCE_ONE;
425 } else oracle_eval(-o->in[i] - 1, srcv, &vals[i]);
426 in[i] = &vals[i];
427 }
428 memset(out, 0, sizeof *out);
429 uint32_t conf = RX_SEM_CONFIDENCE_ONE;
430 for (uint32_t i = 0; i < o->n; i++) if (in[i]->confidence < conf) conf = in[i]->confidence;
431 out->confidence = conf;
432 o->fn(in, o->n, out, NULL);
433 out->type = o->out_type;
434}
435
436static uint64_t fx_sid_of_slot(Fx *x, int s) {
437 const uint64_t m[OS_N] = { x->s_temp, x->s_power, x->s_knob, x->s_fan, x->s_repo0, x->s_repo1,
438 x->s_repo2, x->s_mem0, x->s_mem1, x->s_caps0, x->s_caps1 };
439 return m[s];
440}
441
442static uint64_t fx_node_of(Fx *x, int n) {
443 const uint64_t m[ON_N] = { x->n_placement, x->n_fan, x->n_repo, x->n_recall, x->n_capres, x->n_plan };
444 return m[n];
445}
446
447static bool same_value(const RxSemValue *a, const RxSemValue *b) {
448 return a->n_words == b->n_words && a->confidence == b->confidence && a->type == b->type &&
449 memcmp(a->value, b->value, a->n_words * sizeof a->value[0]) == 0;
450}
451
452/* ---- PROVE ------------------------------------------------------------------ */
453
454static struct {
455 uint64_t diff_ops, diff_gets, diff_mismatch, diff_hits, diff_audits, diff_false_hits;
456 uint64_t diff_forks, diff_writes, diff_cross_branch_hits;
457 uint64_t inv_temp_dirty, inv_temp_clean_kept, inv_noise_invalidations, inv_noise_computes;
458 uint64_t prov_entries, prov_events, prov_memos, prov_world_crumbs;
459 bool tamper_entry_detected, tamper_event_detected;
460 uint64_t jspace_candidates, jspace_computes, jspace_cache_hits;
461 uint64_t gen_obj_recomputed, gen_fn_recomputed;
462} g_p;
463
464static void t_dependency(void) {
465 begin("dependency_tracking");
466 Fx x;
467 g_work = small_work();
468 CHECK(fx_start(&x) == 0, "fixture");
469 uint64_t in[8];
470 uint32_t n = 0;
471 CHECK(rx_sem_node_inputs(&x.e, x.n_placement, in, &n) == RX_SEM_OK && n == 3 &&
472 in[0] == x.s_temp && in[1] == x.s_power && in[2] == x.s_knob, "placement inputs");
473 CHECK(rx_sem_node_inputs(&x.e, x.n_plan, in, &n) == RX_SEM_OK && n == 4 &&
474 in[0] == x.n_placement && in[1] == x.n_repo, "plan inputs");
475 uint64_t ds[16];
476 CHECK(rx_sem_downstream(&x.e, x.s_temp, ds, 16, &n) == RX_SEM_OK && n == 2, "temp downstream %u", n);
477 bool has_p = false, has_plan = false;
478 for (uint32_t i = 0; i < n; i++) {
479 has_p |= ds[i] == x.n_placement;
480 has_plan |= ds[i] == x.n_plan;
481 }
482 CHECK(has_p && has_plan, "temp reaches placement and plan only");
483 CHECK(rx_sem_downstream(&x.e, x.s_fan, ds, 16, &n) == RX_SEM_OK && n == 1 && ds[0] == x.n_fan,
484 "fan reaches fan health only");
485 CHECK(rx_sem_downstream(&x.e, x.s_repo1, ds, 16, &n) == RX_SEM_OK && n == 2, "repo downstream");
486 CHECK(rx_sem_downstream(&x.e, x.n_plan, ds, 16, &n) == RX_SEM_OK && n == 0, "plan is a sink");
487 /* Same question, same node; a different question with a colliding id is refused. */
488 uint64_t again = 0, in_p[3] = { x.s_temp, x.s_power, x.s_knob };
489 CHECK(rx_sem_add_node(&x.e, x.f_thermal, in_p, 3, &again) == RX_SEM_OK && again == x.n_placement,
490 "idempotent node id");
491 uint64_t swapped[3] = { x.s_power, x.s_temp, x.s_knob };
492 uint64_t other = 0;
493 CHECK(rx_sem_add_node(&x.e, x.f_thermal, swapped, 3, &other) == RX_SEM_OK && other != x.n_placement,
494 "input order is part of the question");
495 uint64_t bogus[1] = { ((uint64_t)RX_SEM_KIND_DERIVED << 56) | 12345u };
496 CHECK(rx_sem_add_node(&x.e, x.f_fan, bogus, 1, &other) == RX_SEM_ERR_NOT_FOUND,
497 "inputs must exist first (acyclic by construction)");
498 uint64_t twice[2] = { x.s_temp, x.s_temp };
499 CHECK(rx_sem_add_node(&x.e, x.f_fan, twice, 2, &other) == RX_SEM_ERR_ARG,
500 "an input listed twice is refused");
501 /* The value carries its dependencies and derivation. */
502 RxSemValue v;
503 CHECK(rx_sem_get(&x.e, x.root_branch, x.n_plan, &v, NULL) == RX_SEM_OK, "get plan");
504 CHECK(v.n_deps == 4 && v.dependencies[0] == x.n_placement && v.dependencies[3] == x.n_capres,
505 "dependencies on value");
506 CHECK(v.generation == 1 && v.semantic_id == x.n_plan && v.type == T_PLAN, "identity on value");
507 CHECK(v.n_evidence == 2, "evidence refs: producing entry and input evidence");
508 RxSemValue t;
509 CHECK(rx_sem_read_source(&x.e, x.root_branch, x.s_temp, &t) == RX_SEM_OK && t.value[0] == 60000 &&
510 t.generation == x.machine.generation && t.n_evidence == 1, "source value from world");
511 fx_stop(&x);
512}
513
514static void t_invalidation(void) {
515 begin("correct_invalidation");
516 Fx x;
517 g_work = small_work();
518 CHECK(fx_start(&x) == 0, "fixture");
519 uint32_t b = x.root_branch;
520 RxSemValue plan0;
521 CHECK(served_of(&x, b, x.n_plan, &plan0) == RX_SEM_SERVED_COMPUTED, "first plan computed");
522 CHECK(served_of(&x, b, x.n_fan, NULL) == RX_SEM_SERVED_COMPUTED, "fan health computed");
523 uint64_t c0 = x.e.stats.computes;
524 CHECK(c0 == 6, "six derivations ran once each (%llu)", U(c0));
525
526 /* Unrelated world objects: nothing is invalidated, nothing runs. */
527 uint64_t inv0 = x.e.stats.invalidations;
528 for (int r = 0; r < 50; r++)
529 for (int i = 0; i < N_NOISE; i++) put(&x, x.noise[i], (uint32_t)(r % 4), (uint64_t)(r * 31 + i));
530 CHECK(rx_sem_sync_world(&x.e, b, &x.w) == 0, "noise changes no bound source");
531 RxSemValue p;
532 CHECK(served_of(&x, b, x.n_plan, &p) == RX_SEM_SERVED_MEMO && same_value(&p, &plan0),
533 "plan served from memo after 400 unrelated writes");
534 g_p.inv_noise_invalidations = x.e.stats.invalidations - inv0;
535 g_p.inv_noise_computes = x.e.stats.computes - c0;
536 CHECK(g_p.inv_noise_invalidations == 0 && g_p.inv_noise_computes == 0, "no work for noise");
537
538 /* Temperature: placement (and plan, which reads it) only. */
539 put(&x, x.machine, F_TEMP, 82000);
540 CHECK(rx_sem_sync_world(&x.e, b, &x.w) == 1, "one source changed");
541 CHECK(st(&x, b, x.n_placement) == RX_SEM_DIRTY, "placement dirty");
542 CHECK(st(&x, b, x.n_plan) == RX_SEM_DIRTY, "plan dirty (reads placement)");
543 int clean = (st(&x, b, x.n_repo) == RX_SEM_CLEAN) + (st(&x, b, x.n_recall) == RX_SEM_CLEAN) +
544 (st(&x, b, x.n_capres) == RX_SEM_CLEAN) + (st(&x, b, x.n_fan) == RX_SEM_CLEAN);
545 CHECK(clean == 4, "repository, memory, capability, fan health stay clean (%d/4)", clean);
546 g_p.inv_temp_dirty = (st(&x, b, x.n_placement) == RX_SEM_DIRTY) + (st(&x, b, x.n_plan) == RX_SEM_DIRTY);
547 g_p.inv_temp_clean_kept = (uint64_t)clean;
548 uint64_t c1 = x.e.stats.computes;
549 RxSemValue pl;
550 CHECK(served_of(&x, b, x.n_plan, &p) == RX_SEM_SERVED_COMPUTED, "plan recomputed");
551 CHECK(x.e.stats.computes - c1 == 2, "exactly placement and plan ran (%llu)", U(x.e.stats.computes - c1));
552 rx_sem_get(&x.e, b, x.n_placement, &pl, NULL);
553 CHECK(pl.value[1] == 82000 / 5000, "placement sees the new temperature");
554 CHECK(served_of(&x, b, x.n_repo, NULL) == RX_SEM_SERVED_MEMO, "repository analysis untouched");
555
556 /* Another field of the same object (fan): fan health only. */
557 put(&x, x.machine, F_FAN, 9500);
558 rx_sem_sync_world(&x.e, b, &x.w);
559 CHECK(st(&x, b, x.n_fan) == RX_SEM_DIRTY && st(&x, b, x.n_placement) == RX_SEM_CLEAN &&
560 st(&x, b, x.n_plan) == RX_SEM_CLEAN, "fan field dirties fan health, not placement");
561
562 /* World rewrites the same value: version moves, meaning does not. */
563 uint64_t inv1 = x.e.stats.invalidations;
564 put(&x, x.machine, F_TEMP, 82000);
565 rx_sem_sync_world(&x.e, b, &x.w);
566 CHECK(x.e.stats.invalidations == inv1 && st(&x, b, x.n_placement) == RX_SEM_CLEAN,
567 "same-value write invalidates nothing");
568
569 /* Early cutoff: drift inside the bucket reruns placement, not plan. */
570 put(&x, x.machine, F_TEMP, 83500);
571 rx_sem_sync_world(&x.e, b, &x.w);
572 uint64_t c2 = x.e.stats.computes;
573 RxSemServed ps = served_of(&x, b, x.n_plan, NULL);
574 CHECK(ps == RX_SEM_SERVED_CUTOFF, "plan cut off (placement unchanged) served=%d", ps);
575 CHECK(x.e.stats.computes - c2 == 1, "only placement ran (%llu)", U(x.e.stats.computes - c2));
576
577 /* The object-granular baseline would have thrown away the plan for the fan. */
578 rx_sem_set_mode(&x.e, RX_SEM_GRAIN_OBJECT, true, false);
579 put(&x, x.machine, F_FAN, 3000);
580 rx_sem_sync_world(&x.e, b, &x.w);
581 CHECK(st(&x, b, x.n_placement) == RX_SEM_DIRTY && st(&x, b, x.n_plan) == RX_SEM_DIRTY,
582 "object grain: fan dirties placement and plan (the baseline's waste)");
583 rx_sem_set_mode(&x.e, RX_SEM_GRAIN_FIELD, true, false);
584 fx_stop(&x);
585}
586
587/* Randomized differential run: every get compared with a from-scratch
588 * evaluation; every hit re-computed in audit mode. */
589static void t_no_stale(void) {
590 begin("no_stale_reuse");
591 Fx x;
592 g_work = small_work();
593 CHECK(fx_start(&x) == 0, "fixture");
594 rx_sem_set_mode(&x.e, RX_SEM_GRAIN_FIELD, true, true);
595 enum { NB = 12 };
596 uint32_t bid[NB];
597 bool live[NB] = { false };
598 uint64_t shadow[NB][OS_N];
599 uint32_t gen[NB][OS_N];
600 bid[0] = x.root_branch;
601 live[0] = true;
602 for (int s = 0; s < OS_N; s++) {
603 RxSemValue v;
604 rx_sem_read_source(&x.e, bid[0], fx_sid_of_slot(&x, s), &v);
605 shadow[0][s] = v.value[0];
606 gen[0][s] = v.generation;
607 }
608 uint64_t rng = 0x5eed0001;
609 const uint64_t ops = 200000;
610 for (uint64_t op = 0; op < ops; op++) {
611 uint64_t r = splitmix(&rng);
612 int bi = (int)(r % NB);
613 if (!live[bi]) bi = 0;
614 uint32_t kind = (uint32_t)((r >> 8) % 100);
615 if (kind < 40) {
616 /* Write a small-domain value so the same content recurs (ABA). */
617 int s = (int)((r >> 16) % OS_N);
618 uint64_t v = (r >> 24) % 4;
619 if (s == OS_TEMP) v = 50000 + v * 4000; /* crosses 5 C buckets and stays inside them */
620 rx_sem_set_source(&x.e, bid[bi], fx_sid_of_slot(&x, s), gen[bi][s], &v, 1,
621 RX_SEM_CONFIDENCE_ONE, NULL);
622 shadow[bi][s] = v;
623 g_p.diff_writes++;
624 } else if (kind < 45) {
625 int slot = -1;
626 for (int k = 1; k < NB; k++) if (!live[k]) { slot = k; break; }
627 if (slot > 0) {
628 uint32_t nb;
629 if (rx_sem_branch_fork(&x.e, bid[bi], (uint32_t)(r >> 40) % 5, r >> 48, op + 1, &nb) ==
630 RX_SEM_OK) {
631 bid[slot] = nb;
632 live[slot] = true;
633 memcpy(shadow[slot], shadow[bi], sizeof shadow[slot]);
634 memcpy(gen[slot], gen[bi], sizeof gen[slot]);
635 g_p.diff_forks++;
636 }
637 }
638 } else if (kind < 47) {
639 if (bi != 0) {
640 rx_sem_branch_drop(&x.e, bid[bi]);
641 live[bi] = false;
642 }
643 } else {
644 int n = (int)((r >> 16) % ON_N);
645 RxSemValue got, want;
646 RxSemServed sv = 0;
647 int rc = rx_sem_get(&x.e, bid[bi], fx_node_of(&x, n), &got, &sv);
648 oracle_eval(n, shadow[bi], &want);
649 g_p.diff_gets++;
650 if (sv != RX_SEM_SERVED_COMPUTED) g_p.diff_hits++;
651 if (rc != RX_SEM_OK || !same_value(&got, &want)) {
652 g_p.diff_mismatch++;
653 if (g_p.diff_mismatch < 5)
654 fprintf(stderr, " mismatch op %llu node %d served %d\n", U(op), n, sv);
655 }
656 }
657 g_p.diff_ops++;
658 }
659 g_p.diff_audits = x.e.stats.audits;
660 g_p.diff_false_hits = x.e.stats.false_hits;
661 g_p.diff_cross_branch_hits = x.e.stats.cache_hits_cross_branch;
662 CHECK(g_p.diff_mismatch == 0, "differential mismatches %llu of %llu gets", U(g_p.diff_mismatch),
663 U(g_p.diff_gets));
664 CHECK(g_p.diff_false_hits == 0, "audit false hits %llu of %llu", U(g_p.diff_false_hits),
665 U(g_p.diff_audits));
666 CHECK(g_p.diff_hits > g_p.diff_gets / 2, "reuse exercised (%llu hits)", U(g_p.diff_hits));
667 CHECK(x.e.stats.cutoffs > 0 && x.e.stats.cache_hits > 0 && x.e.stats.memo_hits > 0,
668 "every reuse path exercised (memo %llu cutoff %llu cache %llu)", U(x.e.stats.memo_hits),
669 U(x.e.stats.cutoffs), U(x.e.stats.cache_hits));
670 CHECK(g_p.diff_cross_branch_hits > 0, "cross-branch reuse inside the differential run");
671 uint64_t ne, nv, nm;
672 CHECK(rx_sem_verify(&x.e, &ne, &nv, &nm) == RX_SEM_OK, "verify after differential run");
673
674 /* Directed stale case: the old entry exists but its key no longer matches. */
675 uint32_t b = x.root_branch;
676 uint64_t t1 = 50000, t2 = 90000;
677 rx_sem_set_source(&x.e, b, x.s_temp, gen[0][OS_TEMP], &t1, 1, RX_SEM_CONFIDENCE_ONE, NULL);
678 RxSemValue a1, a2, a3;
679 rx_sem_get(&x.e, b, x.n_placement, &a1, NULL);
680 rx_sem_set_source(&x.e, b, x.s_temp, gen[0][OS_TEMP], &t2, 1, RX_SEM_CONFIDENCE_ONE, NULL);
681 rx_sem_get(&x.e, b, x.n_placement, &a2, NULL);
682 CHECK(a2.value[1] == 90000 / 5000 && a1.value[1] == 50000 / 5000, "new temperature, new answer");
683 rx_sem_set_source(&x.e, b, x.s_temp, gen[0][OS_TEMP], &t1, 1, RX_SEM_CONFIDENCE_ONE, NULL);
684 RxSemServed sv;
685 rx_sem_get(&x.e, b, x.n_placement, &a3, &sv);
686 CHECK(same_value(&a3, &a1) && sv == RX_SEM_SERVED_CACHE, "A-B-A: the A result is valid reuse");
687 fx_stop(&x);
688}
689
690static void t_generation(void) {
691 begin("generation_isolation");
692 Fx x;
693 g_work = small_work();
694 CHECK(fx_start(&x) == 0, "fixture");
695 uint32_t b = x.root_branch;
696 RxSemValue before;
697 CHECK(served_of(&x, b, x.n_plan, &before) == RX_SEM_SERVED_COMPUTED, "plan");
698
699 /* (a) Retire the repository object and create another in its slot with
700 * the same bytes. Same id, same content, new generation. */
701 RxObjRef old = x.repo;
702 CHECK(rx_world_retire(&x.w, old) == RX_OK, "retire");
703 rx_sem_sync_world(&x.e, b, &x.w);
704 CHECK(st(&x, b, x.n_repo) == RX_SEM_DIRTY && st(&x, b, x.n_plan) == RX_SEM_DIRTY,
705 "retirement dirties what read the old object");
706 RxSemValue v;
707 CHECK(rx_sem_get(&x.e, b, x.n_plan, &v, NULL) == RX_SEM_ERR_STALE,
708 "nothing derived from a retired object is served");
709 uint64_t r0[RX_MAX_FIELDS] = { 0xabc, 0xdef, 120 };
710 x.repo = mkobj(&x, 2, r0);
711 CHECK(x.repo.id == old.id && x.repo.generation != old.generation, "same slot, new generation");
712 rx_sem_rebind(&x.e, x.s_repo0, x.repo);
713 rx_sem_rebind(&x.e, x.s_repo1, x.repo);
714 rx_sem_rebind(&x.e, x.s_repo2, x.repo);
715 CHECK(rx_sem_sync_world(&x.e, b, &x.w) == 3, "three sources re-read");
716 uint64_t hits0 = x.e.stats.cache_hits;
717 RxSemServed sr = served_of(&x, b, x.n_repo, &v);
718 CHECK(sr == RX_SEM_SERVED_COMPUTED, "same bytes, new generation: recomputed (served %d)", sr);
719 CHECK(x.e.stats.cache_hits == hits0, "old-generation entry not served");
720 RxSemDerived ex;
721 CHECK(rx_sem_explain(&x.e, b, x.n_repo, &ex) == RX_SEM_OK &&
722 ex.input_versions[0].generation == x.repo.generation, "entry records the new generation");
723 g_p.gen_obj_recomputed = sr == RX_SEM_SERVED_COMPUTED;
724
725 /* (b) A promoted implementation generation of the same function. */
726 RxSemFnDesc d2 = { "aien.repository_semantics", T_REPO_SEM, 2, impl("aien.repository_semantics"),
727 fn_repo, NULL };
728 uint32_t f2;
729 CHECK(rx_sem_add_fn(&x.e, &d2, &f2) == RX_SEM_OK, "register generation 2");
730 uint64_t in_r[3] = { x.s_repo0, x.s_repo1, x.s_repo2 };
731 uint64_t n2 = node(&x, f2, in_r, 3);
732 CHECK(n2 != x.n_repo, "a new generation is a new derivation");
733 uint64_t h1 = x.e.stats.cache_hits;
734 RxSemValue v2;
735 sr = served_of(&x, b, n2, &v2);
736 CHECK(sr == RX_SEM_SERVED_COMPUTED && x.e.stats.cache_hits == h1,
737 "generation 1 results are not served for generation 2");
738 CHECK(v2.generation == 2 && !rx_sem_digest_eq(&v2.derivation_id, &v.derivation_id),
739 "value names its generation and derivation");
740 g_p.gen_fn_recomputed = sr == RX_SEM_SERVED_COMPUTED;
741 /* A second branch on generation 2 reuses generation 2, not 1. */
742 uint32_t b2;
743 rx_sem_branch_root(&x.e, 2, 2, &b2);
744 rx_sem_sync_world(&x.e, b2, &x.w);
745 RxSemValue v3;
746 CHECK(served_of(&x, b2, n2, &v3) == RX_SEM_SERVED_CACHE, "generation 2 reuses generation 2");
747 CHECK(rx_sem_explain(&x.e, b2, n2, &ex) == RX_SEM_OK && ex.result.generation == 2,
748 "served entry is generation 2");
749 uint64_t ne, nv, nm;
750 CHECK(rx_sem_verify(&x.e, &ne, &nv, &nm) == RX_SEM_OK, "verify");
751 fx_stop(&x);
752}
753
754static void t_branch_isolation(void) {
755 begin("branch_isolation");
756 Fx x;
757 g_work = small_work();
758 CHECK(fx_start(&x) == 0, "fixture");
759 uint32_t R = x.root_branch, A, B;
760 RxSemValue planR, planA, planB, v;
761 served_of(&x, R, x.n_plan, &planR);
762 served_of(&x, R, x.n_fan, NULL);
763 uint8_t wd0[32], wd1[32];
764 rx_world_digest(&x.w, wd0);
765 CHECK(rx_sem_branch_fork(&x.e, R, 10, 100, 1001, &A) == RX_SEM_OK, "fork candidate A");
766 CHECK(rx_sem_branch_fork(&x.e, R, 11, 100, 1002, &B) == RX_SEM_OK, "fork candidate B");
767 RxSemValue knob;
768 rx_sem_read_source(&x.e, R, x.s_knob, &knob);
769 uint64_t ka = 1, kb = 2, temp_b = 95000;
770 rx_sem_set_source(&x.e, A, x.s_knob, knob.generation, &ka, 1, RX_SEM_CONFIDENCE_ONE, NULL);
771 rx_sem_set_source(&x.e, B, x.s_knob, knob.generation, &kb, 1, RX_SEM_CONFIDENCE_ONE, NULL);
772 RxSemValue tmp;
773 rx_sem_read_source(&x.e, R, x.s_temp, &tmp);
774 rx_sem_set_source(&x.e, B, x.s_temp, tmp.generation, &temp_b, 1, RX_SEM_CONFIDENCE_ONE, NULL);
775 served_of(&x, A, x.n_plan, &planA);
776 served_of(&x, B, x.n_plan, &planB);
777 CHECK(planA.value[2] != planR.value[2] && planB.value[2] != planA.value[2], "candidates differ");
778 int cleanR = 0;
779 for (int n = 0; n < ON_N; n++) cleanR += st(&x, R, fx_node_of(&x, n)) == RX_SEM_CLEAN;
780 CHECK(cleanR == ON_N, "parent memo untouched by candidate writes (%d/%d clean)", cleanR, ON_N);
781 CHECK(served_of(&x, R, x.n_plan, &v) == RX_SEM_SERVED_MEMO && same_value(&v, &planR),
782 "parent plan unchanged");
783 rx_sem_read_source(&x.e, R, x.s_knob, &v);
784 CHECK(v.value[0] == 0, "parent knob unchanged");
785 rx_sem_read_source(&x.e, A, x.s_temp, &v);
786 CHECK(v.value[0] == tmp.value[0], "sibling A does not see B's temperature");
787 rx_world_digest(&x.w, wd1);
788 CHECK(memcmp(wd0, wd1, 32) == 0, "branch work never reaches the world");
789 /* After the fork, a world change in the parent does not reach candidates. */
790 put(&x, x.machine, F_TEMP, 99000);
791 rx_sem_sync_world(&x.e, R, &x.w);
792 rx_sem_read_source(&x.e, A, x.s_temp, &v);
793 CHECK(v.value[0] == tmp.value[0] && st(&x, A, x.n_placement) == RX_SEM_CLEAN,
794 "candidate keeps its forked view");
795 CHECK(st(&x, R, x.n_placement) == RX_SEM_DIRTY, "parent sees the world change");
796 CHECK(rx_sem_branch_drop(&x.e, A) == RX_SEM_OK, "drop A");
797 CHECK(served_of(&x, B, x.n_plan, &v) == RX_SEM_SERVED_MEMO && same_value(&v, &planB),
798 "dropping A leaves B intact");
799 CHECK(rx_sem_get(&x.e, A, x.n_plan, &v, NULL) == RX_SEM_ERR_NOT_FOUND, "dropped branch is gone");
800 uint64_t ne, nv, nm;
801 CHECK(rx_sem_verify(&x.e, &ne, &nv, &nm) == RX_SEM_OK, "verify");
802 fx_stop(&x);
803}
804
805static void t_cross_reuse(void) {
806 begin("cross_branch_valid_reuse");
807 Fx x;
808 g_work = small_work();
809 CHECK(fx_start(&x) == 0, "fixture");
810 uint32_t R = x.root_branch;
811 served_of(&x, R, x.n_plan, NULL);
812 uint64_t c0 = x.e.stats.computes;
813
814 /* Another agent on another task, its own branch synced from the world. */
815 uint32_t other;
816 rx_sem_branch_root(&x.e, 7, 77, &other);
817 rx_sem_sync_world(&x.e, other, &x.w);
818 CHECK(served_of(&x, other, x.n_plan, NULL) == RX_SEM_SERVED_CACHE, "other agent: plan from cache");
819 CHECK(x.e.stats.computes == c0, "no derivation ran for the second agent");
820 CHECK(x.e.stats.cache_hits_cross_agent >= 1 && x.e.stats.cache_hits_cross_task >= 1 &&
821 x.e.stats.cache_hits_cross_branch >= 1, "counted as cross agent, task and branch");
822
823 /* J-Space: 16 candidates propose 4 distinct knob settings. */
824 RxSemValue knob;
825 rx_sem_read_source(&x.e, R, x.s_knob, &knob);
826 uint64_t c1 = x.e.stats.computes, h1 = x.e.stats.cache_hits;
827 uint64_t hc = x.e.stats.cache_hits_cross_candidate;
828 RxSemValue plan_of[4];
829 bool seen[4] = { false };
830 int consistent = 1;
831 for (int c = 0; c < 16; c++) {
832 uint32_t cb;
833 rx_sem_branch_fork(&x.e, R, 20u + (uint32_t)c, 500, 9000u + (uint64_t)c, &cb);
834 uint64_t k = (uint64_t)(c % 4) + 1;
835 rx_sem_set_source(&x.e, cb, x.s_knob, knob.generation, &k, 1, RX_SEM_CONFIDENCE_ONE, NULL);
836 RxSemValue p;
837 served_of(&x, cb, x.n_plan, &p);
838 if (seen[c % 4]) consistent &= same_value(&p, &plan_of[c % 4]);
839 else {
840 plan_of[c % 4] = p;
841 seen[c % 4] = true;
842 }
843 rx_sem_branch_drop(&x.e, cb);
844 }
845 g_p.jspace_candidates = 16;
846 g_p.jspace_computes = x.e.stats.computes - c1;
847 g_p.jspace_cache_hits = x.e.stats.cache_hits - h1;
848 CHECK(g_p.jspace_computes == 8, "4 distinct proposals x (placement, plan) = 8 runs (%llu)",
849 U(g_p.jspace_computes));
850 CHECK(g_p.jspace_cache_hits == 24, "12 duplicate candidates x 2 served from cache (%llu)",
851 U(g_p.jspace_cache_hits));
852 CHECK(x.e.stats.cache_hits_cross_candidate - hc == 24, "counted as cross-candidate");
853 CHECK(consistent, "duplicate candidates got identical answers");
854 /* Repository analysis, memory and capability were never recomputed for any candidate. */
855 RxSemDerived ex;
856 CHECK(rx_sem_explain(&x.e, R, x.n_repo, &ex) == RX_SEM_OK && ex.reuses >= 1, "shared repo entry reused");
857 uint64_t ne, nv, nm;
858 CHECK(rx_sem_verify(&x.e, &ne, &nv, &nm) == RX_SEM_OK, "verify");
859 fx_stop(&x);
860}
861
862static void t_provenance(void) {
863 begin("causal_provenance");
864 Fx x;
865 g_work = small_work();
866 CHECK(fx_start(&x) == 0, "fixture");
867 uint32_t R = x.root_branch;
868 put(&x, x.machine, F_TEMP, 71000);
869 int64_t repo_crumb = put(&x, x.repo, 0, 0x1234);
870 CHECK(repo_crumb > 0, "world write");
871 rx_sem_sync_world(&x.e, R, &x.w);
872 served_of(&x, R, x.n_plan, NULL);
873 uint32_t cand;
874 rx_sem_branch_fork(&x.e, R, 42, 4242, 777, &cand);
875 uint32_t other;
876 rx_sem_branch_root(&x.e, 43, 4343, &other);
877 rx_sem_sync_world(&x.e, other, &x.w);
878 CHECK(served_of(&x, other, x.n_repo, NULL) == RX_SEM_SERVED_CACHE, "reused by another agent");
879
880 /* The reused value explains back to its producer ... */
881 RxSemDerived ex;
882 CHECK(rx_sem_explain(&x.e, other, x.n_repo, &ex) == RX_SEM_OK, "explain");
883 CHECK(ex.producer_branch == R && ex.producer_agent == 1 && ex.producer_task == 1,
884 "producer is the root branch's agent and task");
885 /* ... and to the world crumbs that wrote its inputs. */
886 uint64_t writer = rx_world_explain(&x.w, x.repo, 0);
887 const RxCrumb *cr = rx_world_crumb(&x.w, writer);
888 CHECK(writer == (uint64_t)repo_crumb && cr && memcmp(cr->digest, ex.input_versions[0].evidence.b, 32) == 0,
889 "input evidence is the world crumb that wrote repo field 0");
890 uint64_t checked = 0;
891 CHECK(rx_world_verify_crumbs(&x.w, &checked) == 0, "world crumbs verify");
892 g_p.prov_world_crumbs = checked;
893 /* The consumer's REUSE event names the consumer and the entry. */
894 bool found = false;
895 for (uint64_t i = 0; i < x.e.n_events; i++) {
896 const RxSemEvent *ev = &x.e.events[i];
897 if (ev->kind == RX_SEM_EVENT_REUSE && ev->branch == other && ev->agent == 43 &&
898 rx_sem_digest_eq(&ev->entry_digest, &ex.entry_digest))
899 found = true;
900 }
901 CHECK(found, "REUSE event for the consumer");
902 RxSemValue v;
903 rx_sem_get(&x.e, other, x.n_repo, &v, NULL);
904 CHECK(v.n_evidence == 2 && rx_sem_digest_eq(&v.evidence_refs[0], &ex.entry_digest),
905 "served value points at its producing entry");
906 uint64_t ne, nv, nm;
907 CHECK(rx_sem_verify(&x.e, &ne, &nv, &nm) == RX_SEM_OK, "verify");
908 g_p.prov_entries = ne;
909 g_p.prov_events = nv;
910 g_p.prov_memos = nm;
911 CHECK(ne > 0 && nv >= ne && nm > 0, "entries %llu events %llu memos %llu", U(ne), U(nv), U(nm));
912
913 /* Tampering is detected. */
914 uint32_t slot = UINT32_MAX;
915 for (uint32_t s = 0; s < RX_SEM_CACHE_SLOTS; s++)
916 if (x.e.cache[s].used && rx_sem_digest_eq(&x.e.cache[s].entry_digest, &ex.entry_digest)) slot = s;
917 CHECK(slot != UINT32_MAX, "entry slot");
918 if (slot != UINT32_MAX) {
919 x.e.cache[slot].result.value[0] ^= 1;
920 g_p.tamper_entry_detected = rx_sem_verify(&x.e, NULL, NULL, NULL) == RX_SEM_ERR_VERIFY;
921 x.e.cache[slot].result.value[0] ^= 1;
922 x.e.cache[slot].producer_agent ^= 1;
923 g_p.tamper_entry_detected &= rx_sem_verify(&x.e, NULL, NULL, NULL) == RX_SEM_ERR_VERIFY;
924 x.e.cache[slot].producer_agent ^= 1;
925 }
926 x.e.events[0].agent ^= 1;
927 g_p.tamper_event_detected = rx_sem_verify(&x.e, NULL, NULL, NULL) == RX_SEM_ERR_VERIFY;
928 x.e.events[0].agent ^= 1;
929 CHECK(g_p.tamper_entry_detected && g_p.tamper_event_detected, "tamper detected");
930 CHECK(rx_sem_verify(&x.e, NULL, NULL, NULL) == RX_SEM_OK, "restored");
931 fx_stop(&x);
932}
933
934/* ---- MEASURE ---------------------------------------------------------------- */
935
936enum { MODE_FULL = 0, MODE_OBJECT, MODE_FIELD, MODE_ENGINE, MODE_N };
937static const char *g_mode_name[MODE_N] = { "FULL", "OBJECT", "FIELD", "ENGINE" };
938
939typedef struct {
940 uint64_t queries;
941 uint64_t wall_ns; /* whole replay */
942 uint64_t query_ns; /* time inside queries */
943 uint64_t computes;
944 uint64_t compute_ns;
945 uint64_t memo_hits, cutoffs, cache_hits, gets;
946 uint64_t invalidations;
947 uint64_t false_hits, audits;
948 uint64_t saved_ns;
949 uint64_t p50_ns, p99_ns;
950 uint64_t mismatches; /* engine answer != FULL answer */
951 uint64_t answer_digest_lo;
952} RunStats;
953
954#define TRACE_TICKS 600
955#define JSPACE_EVERY 20
956#define JSPACE_WIDTH 6
957#define MAX_Q (TRACE_TICKS * (1 + JSPACE_WIDTH) + 16)
958
959static uint64_t g_lat[MAX_Q];
960
961static int cmp_u64(const void *a, const void *b) {
962 uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;
963 return x < y ? -1 : x > y;
964}
965
966static void full_query(Fx *x, const uint64_t *srcv, RxSemValue *out) {
967 (void)x;
968 oracle_eval(ON_PLAN, srcv, out);
969}
970
971static void world_srcv(Fx *x, uint64_t *s) {
972 RxObject m, r, me, c, k;
973 rx_world_read(&x->w, x->machine, &m);
974 rx_world_read(&x->w, x->repo, &r);
975 rx_world_read(&x->w, x->mem, &me);
976 rx_world_read(&x->w, x->caps, &c);
977 rx_world_read(&x->w, x->knob, &k);
978 s[OS_TEMP] = m.field[F_TEMP];
979 s[OS_POWER] = m.field[F_POWER];
980 s[OS_FAN] = m.field[F_FAN];
981 s[OS_KNOB] = k.field[0];
982 s[OS_R0] = r.field[0];
983 s[OS_R1] = r.field[1];
984 s[OS_R2] = r.field[2];
985 s[OS_M0] = me.field[0];
986 s[OS_M1] = me.field[1];
987 s[OS_C0] = c.field[0];
988 s[OS_C1] = c.field[1];
989}
990
991/* One deterministic organism trace: sensors tick constantly, temperature
992 * moves every few ticks (usually inside its 5 C bucket), the repository,
993 * memory query and capability table change rarely, the agent asks for a
994 * plan every tick, and every JSPACE_EVERY ticks J-Space evaluates
995 * JSPACE_WIDTH candidate knob settings (drawn from 3) in forked branches. */
996static int replay(int mode, bool audit, bool check, RunStats *rs) {
997 Fx x;
998 if (fx_start(&x) != 0) return -1;
999 memset(rs, 0, sizeof *rs);
1000 if (mode == MODE_OBJECT) rx_sem_set_mode(&x.e, RX_SEM_GRAIN_OBJECT, false, audit);
1001 else if (mode == MODE_FIELD) rx_sem_set_mode(&x.e, RX_SEM_GRAIN_FIELD, false, audit);
1002 else rx_sem_set_mode(&x.e, RX_SEM_GRAIN_FIELD, true, audit);
1003 uint64_t rng = 0x7ace0001;
1004 uint64_t temp = 60000;
1005 uint64_t nq = 0;
1006 uint64_t dig = 0xcbf29ce484222325ull;
1007 uint64_t t0 = now_ns();
1008 for (int tick = 0; tick < TRACE_TICKS; tick++) {
1009 for (int i = 0; i < N_NOISE; i++) put(&x, x.noise[i], (uint32_t)(tick % 4), splitmix(&rng));
1010 put(&x, x.machine, F_FAN, 2000 + splitmix(&rng) % 8000); /* fan jitters every tick */
1011 if (tick % 3 == 0) {
1012 uint64_t r = splitmix(&rng) % 100;
1013 temp = r < 80 ? (temp / 5000) * 5000 + splitmix(&rng) % 5000 /* drift inside bucket */
1014 : 55000 + (splitmix(&rng) % 6) * 5000; /* a real move */
1015 put(&x, x.machine, F_TEMP, temp);
1016 }
1017 if (tick % 50 == 49) put(&x, x.repo, 0, splitmix(&rng));
1018 if (tick % 25 == 24) put(&x, x.mem, 1, splitmix(&rng) % 6); /* topics recur */
1019 if (tick % 100 == 99) put(&x, x.caps, 0, splitmix(&rng) % 3);
1020 uint64_t srcv[OS_N];
1021 RxSemValue plan;
1022 uint64_t q0 = now_ns();
1023 if (mode == MODE_FULL) {
1024 world_srcv(&x, srcv);
1025 full_query(&x, srcv, &plan);
1026 } else {
1027 rx_sem_sync_world(&x.e, x.root_branch, &x.w);
1028 rx_sem_get(&x.e, x.root_branch, x.n_plan, &plan, NULL);
1029 }
1030 uint64_t q1 = now_ns();
1031 g_lat[nq++] = q1 - q0;
1032 rs->query_ns += q1 - q0;
1033 for (uint32_t w = 0; w < plan.n_words; w++) dig = (dig ^ plan.value[w]) * 0x100000001b3ull;
1034 if (mode != MODE_FULL && check) {
1035 /* Cross-check every engine answer against a from-scratch one (not timed;
1036 * off in the energy windows, where it would be most of the work). */
1037 RxSemValue want;
1038 world_srcv(&x, srcv);
1039 full_query(&x, srcv, &want);
1040 if (!same_value(&want, &plan)) rs->mismatches++;
1041 }
1042 if (tick % JSPACE_EVERY == JSPACE_EVERY - 1) {
1043 for (int c = 0; c < JSPACE_WIDTH; c++) {
1044 uint64_t k = splitmix(&rng) % 3 + 1;
1045 uint64_t cq0 = now_ns();
1046 RxSemValue p;
1047 if (mode == MODE_FULL) {
1048 world_srcv(&x, srcv);
1049 srcv[OS_KNOB] = k;
1050 full_query(&x, srcv, &p);
1051 } else {
1052 uint32_t cb;
1053 rx_sem_branch_fork(&x.e, x.root_branch, 100u + (uint32_t)c, (uint64_t)tick,
1054 (uint64_t)tick * 16u + (uint64_t)c + 1u, &cb);
1055 RxSemValue kv;
1056 rx_sem_read_source(&x.e, cb, x.s_knob, &kv);
1057 rx_sem_set_source(&x.e, cb, x.s_knob, kv.generation, &k, 1, RX_SEM_CONFIDENCE_ONE, NULL);
1058 rx_sem_get(&x.e, cb, x.n_plan, &p, NULL);
1059 rx_sem_branch_drop(&x.e, cb);
1060 }
1061 uint64_t cq1 = now_ns();
1062 g_lat[nq++] = cq1 - cq0;
1063 rs->query_ns += cq1 - cq0;
1064 for (uint32_t w = 0; w < p.n_words; w++) dig = (dig ^ p.value[w]) * 0x100000001b3ull;
1065 if (mode != MODE_FULL && check) {
1066 RxSemValue want;
1067 world_srcv(&x, srcv);
1068 srcv[OS_KNOB] = k;
1069 full_query(&x, srcv, &want);
1070 if (!same_value(&want, &p)) rs->mismatches++;
1071 }
1072 }
1073 }
1074 }
1075 rs->wall_ns = now_ns() - t0;
1076 rs->queries = nq;
1077 rs->answer_digest_lo = dig;
1078 qsort(g_lat, nq, sizeof g_lat[0], cmp_u64);
1079 rs->p50_ns = g_lat[nq / 2];
1080 rs->p99_ns = g_lat[(nq * 99) / 100];
1081 if (mode == MODE_FULL) {
1082 /* FULL runs every derivation of the plan on every query. */
1083 rs->computes = nq * 5u;
1084 rs->gets = nq * 5u;
1085 } else {
1086 rs->computes = x.e.stats.computes;
1087 rs->compute_ns = x.e.stats.compute_ns;
1088 rs->memo_hits = x.e.stats.memo_hits;
1089 rs->cutoffs = x.e.stats.cutoffs;
1090 rs->cache_hits = x.e.stats.cache_hits;
1091 rs->gets = x.e.stats.gets;
1092 rs->invalidations = x.e.stats.invalidations;
1093 rs->false_hits = x.e.stats.false_hits;
1094 rs->audits = x.e.stats.audits;
1095 rs->saved_ns = x.e.stats.saved_ns;
1096 /* Verification is a check, not service: kept out of the energy windows. */
1097 if (check && rx_sem_verify(&x.e, NULL, NULL, NULL) != RX_SEM_OK) rs->mismatches++;
1098 }
1099 fx_stop(&x);
1100 return 0;
1101}
1102
1103/* Package energy counter (hwmon "aien_spbm", energy1 = pkg, microjoules).
1104 * A window is valid only if both overflow indicators read zero and the
1105 * counter did not go backwards. */
1106typedef struct {
1107 bool present;
1108 char dir[300];
1109} Meter;
1110
1111static Meter g_meter;
1112
1113static bool read_u64_file(const char *path, uint64_t *out) {
1114 FILE *f = fopen(path, "r");
1115 if (!f) return false;
1116 unsigned long long v = 0;
1117 int ok = fscanf(f, "%llu", &v) == 1;
1118 fclose(f);
1119 *out = v;
1120 return ok;
1121}
1122
1123static void meter_find(void) {
1124 DIR *d = opendir("/sys/class/hwmon");
1125 if (!d) return;
1126 struct dirent *de;
1127 while ((de = readdir(d))) {
1128 if (de->d_name[0] == '.') continue;
1129 char p[600], name[64] = { 0 };
1130 snprintf(p, sizeof p, "/sys/class/hwmon/%s/name", de->d_name);
1131 FILE *f = fopen(p, "r");
1132 if (!f) continue;
1133 if (fgets(name, sizeof name, f) && strncmp(name, "aien_spbm", 9) == 0) {
1134 snprintf(g_meter.dir, sizeof g_meter.dir, "/sys/class/hwmon/%s", de->d_name);
1135 uint64_t v;
1136 char e[400];
1137 snprintf(e, sizeof e, "%s/energy1_input", g_meter.dir);
1138 g_meter.present = read_u64_file(e, &v);
1139 }
1140 fclose(f);
1141 }
1142 closedir(d);
1143}
1144/* Channels: 1 package, 2 CPU efficiency cores, 3 CPU performance cores. */
1145#define E_CH 3
1146static const char *g_ch_name[E_CH] = { "package", "cpu_e", "cpu_p" };
1147
1148static bool meter_read(uint64_t uj[E_CH]) {
1149 for (int c = 0; c < E_CH; c++) {
1150 char e[400], o[400];
1151 uint64_t ov0 = 1, ov1 = 1;
1152 snprintf(e, sizeof e, "%s/energy%d_input", g_meter.dir, c + 1);
1153 snprintf(o, sizeof o, "%s/energy%d_overflow_raw", g_meter.dir, c + 1);
1154 if (!read_u64_file(o, &ov0) || !read_u64_file(e, &uj[c]) || !read_u64_file(o, &ov1)) return false;
1155 if (ov0 != 0 || ov1 != 0) return false;
1156 }
1157 return true;
1158}
1159
1160typedef struct {
1161 bool valid;
1162 uint64_t uj[E_CH];
1163 uint64_t ns; /* window length */
1164 uint64_t busy_ns; /* time the replay itself took */
1165} EWin;
1166
1167static void sleep_ns(uint64_t ns) {
1168 struct timespec ts = { (time_t)(ns / 1000000000ull), (long)(ns % 1000000000ull) };
1169 while (nanosleep(&ts, &ts) != 0) {}
1170}
1171
1172/* Run one replay inside a window of at least `window_ns`; the remainder is
1173 * idle. Two windows of equal length differ only by the work done in them
1174 * (plus whatever else the machine did), so their difference is the marginal
1175 * energy of that work. */
1176/* Replays per window. One replay saves a few joules of CPU work, which is
1177 * inside the window-to-window noise of a shared machine; several replays
1178 * per window raise the signal without changing what is compared. */
1179#define E_REPLAYS_PER_WINDOW 8
1180
1181static EWin window_run(int mode, uint64_t window_ns) {
1182 EWin w;
1183 memset(&w, 0, sizeof w);
1184 uint64_t a[E_CH], b[E_CH];
1185 RunStats tmp;
1186 bool ok = g_meter.present && meter_read(a);
1187 uint64_t t0 = now_ns();
1188 for (int k = 0; k < E_REPLAYS_PER_WINDOW; k++) replay(mode, false, false, &tmp);
1189 w.busy_ns = now_ns() - t0;
1190 if (window_ns > w.busy_ns) sleep_ns(window_ns - w.busy_ns);
1191 w.ns = now_ns() - t0;
1192 ok = ok && meter_read(b);
1193 for (int c = 0; c < E_CH && ok; c++) {
1194 ok = b[c] >= a[c];
1195 w.uj[c] = ok ? b[c] - a[c] : 0;
1196 }
1197 w.valid = ok;
1198 return w;
1199}
1200
1201#define E_REPS 5
1202
1203static struct {
1204 RunStats run[MODE_N];
1205 RunStats audit_engine;
1206 bool answers_agree;
1207 EWin full[E_REPS], engine[E_REPS];
1208 bool energy_valid;
1209 double saved_j[E_CH][E_REPS]; /* FULL window minus ENGINE window, same length */
1210 double saved_med[E_CH], saved_min[E_CH], saved_max[E_CH];
1211 double cpu_saved[E_REPS], cpu_saved_med; /* cpu_e + cpu_p, per pair */
1212 int cpu_positive;
1213 double full_med[E_CH], engine_med[E_CH];
1214 double loadavg1;
1215} g_m;
1216
1217static double median_n(const double *v, int n) {
1218 double s[E_REPS];
1219 memcpy(s, v, (size_t)n * sizeof *v);
1220 for (int i = 1; i < n; i++)
1221 for (int j = i; j > 0 && s[j - 1] > s[j]; j--) {
1222 double t = s[j];
1223 s[j] = s[j - 1];
1224 s[j - 1] = t;
1225 }
1226 return s[n / 2];
1227}
1228
1229static void t_measure(void) {
1230 begin("measure");
1231 g_work = (Work){ 3000, 6000, 12000, 20000, 3000 };
1232 for (int m = 0; m < MODE_N; m++) {
1233 CHECK(replay(m, false, true, &g_m.run[m]) == 0, "replay %s", g_mode_name[m]);
1234 printf(" %-6s query %8.1f ms runs %6llu p50 %8.1f us p99 %8.1f us\n",
1235 g_mode_name[m], g_m.run[m].query_ns / 1e6, U(g_m.run[m].computes),
1236 g_m.run[m].p50_ns / 1e3, g_m.run[m].p99_ns / 1e3);
1237 }
1238 g_m.answers_agree = true;
1239 for (int m = 1; m < MODE_N; m++) {
1240 g_m.answers_agree &= g_m.run[m].answer_digest_lo == g_m.run[MODE_FULL].answer_digest_lo;
1241 CHECK(g_m.run[m].mismatches == 0, "%s answers equal FULL per query", g_mode_name[m]);
1242 }
1243 CHECK(g_m.answers_agree, "every mode produced the same answer stream");
1244 /* The same ENGINE replay with every hit re-computed and compared. */
1245 CHECK(replay(MODE_ENGINE, true, true, &g_m.audit_engine) == 0, "audited replay");
1246 CHECK(g_m.audit_engine.false_hits == 0 && g_m.audit_engine.audits > 0,
1247 "false hits %llu of %llu audited", U(g_m.audit_engine.false_hits), U(g_m.audit_engine.audits));
1248 const RunStats *E = &g_m.run[MODE_ENGINE], *F = &g_m.run[MODE_FULL];
1249 CHECK(E->computes < F->computes, "recomputation avoided");
1250 CHECK(E->query_ns < F->query_ns, "latency saved");
1251 CHECK(E->computes <= g_m.run[MODE_FIELD].computes && g_m.run[MODE_FIELD].computes <=
1252 g_m.run[MODE_OBJECT].computes, "each layer does no more work than the one below it");
1253 CHECK(g_m.run[MODE_FIELD].invalidations < g_m.run[MODE_OBJECT].invalidations,
1254 "field grain invalidates less than object grain");
1255
1256 meter_find();
1257 FILE *la = fopen("/proc/loadavg", "r");
1258 if (la) {
1259 if (fscanf(la, "%lf", &g_m.loadavg1) != 1) g_m.loadavg1 = -1;
1260 fclose(la);
1261 }
1262 if (!g_meter.present) {
1263 printf(" energy: no package energy counter on this machine; not measured\n");
1264 return;
1265 }
1266 bool ok = true;
1267 uint64_t last_full = 0;
1268 for (int r = 0; r < E_REPS; r++) {
1269 /* Alternate the order so drift in background load does not favour one side. */
1270 if (r % 2 == 0 || last_full == 0) {
1271 g_m.full[r] = window_run(MODE_FULL, 0);
1272 g_m.engine[r] = window_run(MODE_ENGINE, g_m.full[r].ns);
1273 } else {
1274 g_m.engine[r] = window_run(MODE_ENGINE, last_full);
1275 g_m.full[r] = window_run(MODE_FULL, 0);
1276 }
1277 last_full = g_m.full[r].ns;
1278 ok &= g_m.full[r].valid && g_m.engine[r].valid;
1279 double scale = g_m.engine[r].ns ? (double)g_m.full[r].ns / (double)g_m.engine[r].ns : 1.0;
1280 for (int c = 0; c < E_CH; c++)
1281 g_m.saved_j[c][r] = (g_m.full[r].uj[c] - g_m.engine[r].uj[c] * scale) / 1e6;
1282 }
1283 g_m.energy_valid = ok;
1284 for (int c = 0; c < E_CH; c++) {
1285 double fv[E_REPS], ev[E_REPS];
1286 g_m.saved_min[c] = g_m.saved_max[c] = g_m.saved_j[c][0];
1287 for (int r = 0; r < E_REPS; r++) {
1288 fv[r] = g_m.full[r].uj[c] / 1e6;
1289 ev[r] = g_m.engine[r].uj[c] / 1e6;
1290 if (g_m.saved_j[c][r] < g_m.saved_min[c]) g_m.saved_min[c] = g_m.saved_j[c][r];
1291 if (g_m.saved_j[c][r] > g_m.saved_max[c]) g_m.saved_max[c] = g_m.saved_j[c][r];
1292 }
1293 g_m.full_med[c] = median_n(fv, E_REPS);
1294 g_m.engine_med[c] = median_n(ev, E_REPS);
1295 g_m.saved_med[c] = median_n(g_m.saved_j[c], E_REPS);
1296 printf(" energy %-7s FULL window %7.3f J ENGINE window %7.3f J saved median %6.3f J "
1297 "(min %6.3f, max %6.3f)\n", g_ch_name[c], g_m.full_med[c], g_m.engine_med[c],
1298 g_m.saved_med[c], g_m.saved_min[c], g_m.saved_max[c]);
1299 }
1300 /* The saved work is one thread of CPU derivations. The CPU clusters are
1301 * where it runs; the package counter also carries memory, graphics and
1302 * every other process on the machine, whose window-to-window swing is
1303 * larger than this saving. The gate therefore judges the CPU clusters,
1304 * per pair, and requires the saving to be consistent (at least 4 of 5
1305 * pairs), not just a positive median. The package figure is reported. */
1306 for (int r = 0; r < E_REPS; r++) {
1307 g_m.cpu_saved[r] = g_m.saved_j[1][r] + g_m.saved_j[2][r];
1308 g_m.cpu_positive += g_m.cpu_saved[r] > 0;
1309 }
1310 g_m.cpu_saved_med = median_n(g_m.cpu_saved, E_REPS);
1311 printf(" energy CPU clusters saved per pair median %.3f J, %d of %d pairs positive\n",
1312 g_m.cpu_saved_med, g_m.cpu_positive, E_REPS);
1313 CHECK(ok, "energy windows valid (no overflow, monotonic)");
1314 CHECK(g_m.cpu_saved_med > 0 && g_m.cpu_positive >= E_REPS - 1,
1315 "CPU energy saved consistently (median %.3f J, %d/%d pairs positive)", g_m.cpu_saved_med,
1316 g_m.cpu_positive, E_REPS);
1317}
1318
1319/* ---- receipt ------------------------------------------------------------------ */
1320
1321static void binary_digest(char out[65]) {
1322 strcpy(out, "unavailable");
1323 FILE *f = fopen("/proc/self/exe", "rb");
1324 if (!f) return;
1325 sha256_ctx c;
1326 sha256_init(&c);
1327 uint8_t block[65536], digest[32];
1328 size_t n;
1329 while ((n = fread(block, 1, sizeof block, f)) > 0) sha256_update(&c, block, n);
1330 fclose(f);
1331 sha256_final(&c, digest);
1332 hex(digest, 32, out);
1333}
1334
1335static double ratio(uint64_t a, uint64_t b) { return b ? (double)a / (double)b : 0.0; }
1336
1337static void mode_json(FILE *f, const char *name, const RunStats *r, bool last) {
1338 uint64_t hits = r->memo_hits + r->cutoffs + r->cache_hits;
1339 fprintf(f,
1340 " \"%s\": {\"queries\": %llu, \"derivation_runs\": %llu, \"derivation_ns\": %llu, "
1341 "\"query_ns\": %llu, \"wall_ns\": %llu, \"p50_query_ns\": %llu, \"p99_query_ns\": %llu, "
1342 "\"resolutions\": %llu, \"memo_hits\": %llu, \"cutoffs\": %llu, \"cache_hits\": %llu, "
1343 "\"hit_rate\": %.4f, \"invalidations\": %llu, \"unnecessary_invalidations\": %llu, "
1344 "\"unnecessary_invalidation_rate\": %.4f, \"answers_differing_from_full\": %llu}%s\n",
1345 name, U(r->queries), U(r->computes), U(r->compute_ns), U(r->query_ns), U(r->wall_ns),
1346 U(r->p50_ns), U(r->p99_ns), U(r->gets), U(r->memo_hits), U(r->cutoffs), U(r->cache_hits),
1347 ratio(hits, r->gets), U(r->invalidations), U(r->cutoffs), ratio(r->cutoffs, r->invalidations),
1348 U(r->mismatches), last ? "" : ",");
1349}
1350
1351static const char *g_gate = "FAIL";
1352
1353static int receipt(int prove_ok, int measure_ok) {
1354 char path[512], commit[41] = { 0 }, binary[65];
1355 if (omega_evidence_path("SEM/omega_incremental_semantics_receipt.json", path, sizeof path) != 0) return 0;
1356 if (!omega_evidence_run_commit(commit)) strcpy(commit, "unknown");
1357 binary_digest(binary);
1358 const char *candidate = getenv("OMEGA_CANDIDATE_COMMIT");
1359 int dirty = omega_evidence_tree_dirty();
1360 int bound = candidate && candidate[0] && strcmp(candidate, commit) == 0 && !dirty;
1361 int all = prove_ok && measure_ok;
1362 int energy = g_meter.present && g_m.energy_valid;
1363 g_gate = !all ? "FAIL" : !energy ? "HOST_PASS_ENERGY_UNMEASURED" : !bound ? "PASS_UNBOUND" : "PASS";
1364 struct utsname host;
1365 memset(&host, 0, sizeof host);
1366 uname(&host);
1367 FILE *f = fopen(path, "w");
1368 if (!f) return 0;
1369 const RunStats *F = &g_m.run[MODE_FULL], *O = &g_m.run[MODE_OBJECT], *D = &g_m.run[MODE_FIELD],
1370 *E = &g_m.run[MODE_ENGINE];
1371 uint64_t e_hits = E->memo_hits + E->cutoffs + E->cache_hits;
1372 fprintf(f,
1373 "{\n"
1374 " \"schema\": \"AIEN_OMEGA_INCREMENTAL_SEMANTICS_V1\",\n"
1375 " \"run_id\": \"%s\",\n"
1376 " \"candidate_commit\": \"%s\",\n"
1377 " \"run_commit\": \"%s\",\n"
1378 " \"candidate_bound\": %s,\n"
1379 " \"tree_dirty\": %s,\n"
1380 " \"test_binary_sha256\": \"%s\",\n"
1381 " \"machine_identity\": {\"node\": \"%s\", \"system\": \"%s\", \"release\": \"%s\", "
1382 "\"architecture\": \"%s\"},\n"
1383 " \"gate\": {\"OMEGA_INCREMENTAL_SEMANTICS_PASS\": \"%s\"},\n",
1384 omega_evidence_run_id(), candidate ? candidate : "unknown", commit, bound ? "true" : "false",
1385 dirty ? "true" : "false", binary, host.nodename, host.sysname, host.release, host.machine, g_gate);
1386 fprintf(f, " \"prove\": {\n");
1387 const char *names[] = { "dependency_tracking", "correct_invalidation", "no_stale_reuse",
1388 "generation_isolation", "branch_isolation", "cross_branch_valid_reuse",
1389 "causal_provenance" };
1390 for (int i = 0; i < 7; i++) {
1391 int checks = 0;
1392 for (int t = 0; t < g_ntests; t++) if (strcmp(g_tests[t].name, names[i]) == 0) checks = g_tests[t].checks;
1393 fprintf(f, " \"%s\": {\"result\": \"%s\", \"checks\": %d},\n", names[i],
1394 test_ok(names[i]) ? "PASS" : "FAIL", checks);
1395 }
1396 fprintf(f,
1397 " \"details\": {\"temperature_change_dirtied\": %llu, \"unrelated_nodes_kept_clean\": %llu, "
1398 "\"unrelated_world_writes_invalidations\": %llu, \"unrelated_world_writes_runs\": %llu, "
1399 "\"differential_ops\": %llu, \"differential_gets\": %llu, \"differential_hits\": %llu, "
1400 "\"differential_mismatches\": %llu, \"differential_audits\": %llu, \"differential_false_hits\": %llu, "
1401 "\"differential_forks\": %llu, \"differential_cross_branch_hits\": %llu, "
1402 "\"retired_object_same_bytes_recomputed\": %s, \"promoted_fn_generation_recomputed\": %s, "
1403 "\"jspace_candidates\": %llu, \"jspace_derivation_runs\": %llu, \"jspace_cache_hits\": %llu, "
1404 "\"provenance_entries_verified\": %llu, \"provenance_events_verified\": %llu, "
1405 "\"provenance_memos_verified\": %llu, \"world_crumbs_verified\": %llu, "
1406 "\"tampered_entry_detected\": %s, \"tampered_event_detected\": %s}\n"
1407 " },\n",
1408 U(g_p.inv_temp_dirty), U(g_p.inv_temp_clean_kept), U(g_p.inv_noise_invalidations),
1409 U(g_p.inv_noise_computes), U(g_p.diff_ops), U(g_p.diff_gets), U(g_p.diff_hits),
1410 U(g_p.diff_mismatch), U(g_p.diff_audits), U(g_p.diff_false_hits), U(g_p.diff_forks),
1411 U(g_p.diff_cross_branch_hits), g_p.gen_obj_recomputed ? "true" : "false",
1412 g_p.gen_fn_recomputed ? "true" : "false", U(g_p.jspace_candidates), U(g_p.jspace_computes),
1413 U(g_p.jspace_cache_hits), U(g_p.prov_entries), U(g_p.prov_events), U(g_p.prov_memos),
1414 U(g_p.prov_world_crumbs), g_p.tamper_entry_detected ? "true" : "false",
1415 g_p.tamper_event_detected ? "true" : "false");
1416 fprintf(f,
1417 " \"workload\": {\"ticks\": %d, \"noise_objects\": %d, \"jspace_every\": %d, \"jspace_width\": %d, "
1418 "\"work\": {\"thermal_rounds\": %u, \"repo_sha256_chain\": %u, \"memory_vectors\": %u, "
1419 "\"caps_rows\": %u, \"plan_rounds\": %u}, "
1420 "\"note\": \"stand-in derivations with real CPU cost; not the AIEN model\"},\n",
1421 TRACE_TICKS, N_NOISE, JSPACE_EVERY, JSPACE_WIDTH, g_work.thermal, g_work.repo, g_work.memory,
1422 g_work.caps, g_work.plan);
1423 fprintf(f, " \"modes\": {\n");
1424 mode_json(f, "FULL", F, false);
1425 mode_json(f, "OBJECT", O, false);
1426 mode_json(f, "FIELD", D, false);
1427 mode_json(f, "ENGINE", E, true);
1428 fprintf(f, " },\n");
1429 fprintf(f,
1430 " \"measure\": {\"recomputation_avoided\": %llu, \"recomputation_avoided_fraction\": %.4f, "
1431 "\"compute_saved_ns\": %llu, \"compute_saved_ns_by_producer_timing\": %llu, "
1432 "\"latency_saved_ns\": %llu, \"latency_speedup\": %.2f, "
1433 "\"p50_latency_ns\": {\"FULL\": %llu, \"ENGINE\": %llu}, \"p99_latency_ns\": {\"FULL\": %llu, \"ENGINE\": %llu}, "
1434 "\"cache_hit_rate\": %.4f, \"cache_hits\": %llu, \"resolutions\": %llu, "
1435 "\"false_hits\": %llu, \"audited_hits\": %llu, \"false_hit_rate\": %.6f, "
1436 "\"unnecessary_invalidation_rate\": {\"OBJECT\": %.4f, \"FIELD\": %.4f, \"ENGINE\": %.4f}, "
1437 "\"invalidations\": {\"OBJECT\": %llu, \"FIELD\": %llu, \"ENGINE\": %llu}, "
1438 "\"answers_identical_across_modes\": %s,\n",
1439 U(F->computes - E->computes), 1.0 - ratio(E->computes, F->computes),
1440 U(F->query_ns > E->query_ns ? F->query_ns - E->query_ns : 0), U(E->saved_ns),
1441 U(F->query_ns > E->query_ns ? F->query_ns - E->query_ns : 0), ratio(F->query_ns, E->query_ns),
1442 U(F->p50_ns), U(E->p50_ns), U(F->p99_ns), U(E->p99_ns),
1443 ratio(e_hits, E->gets), U(e_hits), U(E->gets), U(g_m.audit_engine.false_hits),
1444 U(g_m.audit_engine.audits), ratio(g_m.audit_engine.false_hits, g_m.audit_engine.audits),
1445 ratio(O->cutoffs, O->invalidations), ratio(D->cutoffs, D->invalidations),
1446 ratio(E->cutoffs, E->invalidations), U(O->invalidations), U(D->invalidations),
1447 U(E->invalidations), g_m.answers_agree ? "true" : "false");
1448 if (g_meter.present) {
1449 fprintf(f,
1450 " \"energy\": {\"source\": \"hwmon aien_spbm energy1-3 (package, cpu_e, cpu_p), microjoules; "
1451 "overflow indicators checked before and after each read\", "
1452 "\"method\": \"paired equal-length windows: FULL replay, and ENGINE replay followed by idle "
1453 "to the same length; saved = FULL window - ENGINE window; order alternated\", "
1454 "\"replays_per_window\": %d, "
1455 "\"valid\": %s, \"repetitions\": %d, \"loadavg_1min_at_start\": %.2f, \"channels\": {",
1456 E_REPLAYS_PER_WINDOW, g_m.energy_valid ? "true" : "false", E_REPS, g_m.loadavg1);
1457 for (int c = 0; c < E_CH; c++) {
1458 fprintf(f, "%s\"%s\": {\"full_window_uj\": [", c ? ", " : "", g_ch_name[c]);
1459 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%llu", r ? ", " : "", U(g_m.full[r].uj[c]));
1460 fprintf(f, "], \"engine_window_uj\": [");
1461 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%llu", r ? ", " : "", U(g_m.engine[r].uj[c]));
1462 fprintf(f, "], \"saved_j\": [");
1463 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%.4f", r ? ", " : "", g_m.saved_j[c][r]);
1464 fprintf(f, "], \"saved_j_median\": %.4f, \"saved_j_min\": %.4f, \"saved_j_max\": %.4f}",
1465 g_m.saved_med[c], g_m.saved_min[c], g_m.saved_max[c]);
1466 }
1467 fprintf(f, "}, \"cpu_clusters_saved_j\": [");
1468 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%.4f", r ? ", " : "", g_m.cpu_saved[r]);
1469 fprintf(f, "], \"cpu_clusters_saved_j_median\": %.4f, \"cpu_clusters_pairs_positive\": %d, "
1470 "\"gated_on\": \"cpu_e + cpu_p per pair: median > 0 and at least %d of %d pairs positive; "
1471 "package is reported, not gated (its swing from other machine activity exceeds this saving)\"",
1472 g_m.cpu_saved_med, g_m.cpu_positive, E_REPS - 1, E_REPS);
1473 fprintf(f, ", \"window_ns\": [");
1474 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%llu", r ? ", " : "", U(g_m.full[r].ns));
1475 fprintf(f, "], \"engine_busy_ns\": [");
1476 for (int r = 0; r < E_REPS; r++) fprintf(f, "%s%llu", r ? ", " : "", U(g_m.engine[r].busy_ns));
1477 fprintf(f, "], \"limits\": \"on-device counters, not a wall-outlet meter; other machine activity "
1478 "falls in both windows; not an R15 quiet-machine qualification\"}\n");
1479 } else {
1480 fprintf(f, " \"energy\": {\"valid\": false, \"reason\": \"no package energy counter on this host\"}\n");
1481 }
1482 fprintf(f, " },\n");
1483 fprintf(f,
1484 " \"definitions\": {\n"
1485 " \"recomputation_avoided\": \"derivation runs FULL minus ENGINE on the same trace\",\n"
1486 " \"compute_saved_ns\": \"time inside queries, FULL minus ENGINE\",\n"
1487 " \"compute_saved_ns_by_producer_timing\": \"sum over every hit of the producing run's measured time\",\n"
1488 " \"cache_hit_rate\": \"(memo + cutoff + cache hits) / all node resolutions, nested ones included\",\n"
1489 " \"false_hit_rate\": \"hits whose audit recomputation differed / hits audited (every hit, audited replay)\",\n"
1490 " \"unnecessary_invalidation_rate\": \"invalidated memos whose inputs came back unchanged (cut off) / invalidations\"\n"
1491 " },\n"
1492 " \"limits\": [\n"
1493 " \"functions must be pure over declared inputs; the engine cannot see an undeclared read (the audit replay is how that would show)\",\n"
1494 " \"a fork copies the branch tables (simple reference, not copy-on-write)\",\n"
1495 " \"the cache is bounded and never evicts; when 7/8 full, new results are not filed (counted)\",\n"
1496 " \"single engine mutex; one process; the cache does not survive a restart\",\n"
1497 " \"cache reuse is not gated by capabilities: a reader must present the inputs to form a key, but a key's result is visible to any branch in the engine\"\n"
1498 " ],\n"
1499 " \"not_claimed\": [\"the AIEN model or neural cognition\", \"GPU realization\", \"R15 performance qualification\", "
1500 "\"durable or cross-process cache\", \"AIENOS kernel integration\"]\n"
1501 "}\n");
1502 fclose(f);
1503 printf("receipt: %s\n", path);
1504 return 1;
1505}
1506
1507int main(void) {
1508 t_dependency();
1509 t_invalidation();
1510 t_no_stale();
1511 t_generation();
1512 t_branch_isolation();
1513 t_cross_reuse();
1514 t_provenance();
1515 int prove_ok = 1;
1516 for (int i = 0; i < g_ntests; i++) prove_ok &= g_tests[i].failures == 0;
1517 t_measure();
1518 int measure_ok = g_tests[g_ntests - 1].failures == 0;
1519 int total_checks = 0, total_fail = 0;
1520 for (int i = 0; i < g_ntests; i++) {
1521 printf(" %-28s %s (%d checks)\n", g_tests[i].name, g_tests[i].failures ? "FAIL" : "PASS",
1522 g_tests[i].checks);
1523 total_checks += g_tests[i].checks;
1524 total_fail += g_tests[i].failures;
1525 }
1526 receipt(prove_ok, measure_ok);
1527 printf("TOTAL: %d tests, %d checks, %d failures\n", g_ntests, total_checks, total_fail);
1528 printf("OMEGA_INCREMENTAL_SEMANTICS_PASS: %s\n", g_gate);
1529 return total_fail == 0 ? 0 : 1;
1530}