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

1088 lines · 49646 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_cognitive_routing.c -- OMEGA_COGNITIVE_ROUTING qualification.
19 *
20 * 1. With no evidence the router runs each operation's reference realization.
21 * 2. Labelled trials and metered energy go into a ledger. The ledger becomes a
22 * candidate generation. The routing does not change until the candidate is
23 * promoted with the promotion right on the native Aienux authority; a
24 * promotion by the proposer, or without the right, is refused.
25 * 3. Gate: the same held-out workload runs routed and on the always-most-
26 * expensive realization. Both must meet the same quality requirement;
27 * routed must use less processor time and less metered energy.
28 * 4. Learning: the neural module is damaged. Routed quality drops under the
29 * active generation. A new ledger shows it; nothing changes until that
30 * candidate is promoted; after promotion quality is back.
31 * 5. Hard constraints, bounded escalation, torn and foreign models.
32 */
33#include "runtime/aienos_cap.h"
34#include "runtime/rx_cog_engines.h"
35#include "runtime/rx_route.h"
36
37#include "omega_evidence.h"
38#include "sha256.h"
39
40#include <dirent.h>
41#include <errno.h>
42#include <fcntl.h>
43#include <sched.h>
44#include <signal.h>
45#include <stdio.h>
46#include <stdlib.h>
47#include <string.h>
48#include <sys/stat.h>
49#include <sys/utsname.h>
50#include <time.h>
51#include <unistd.h>
52
53static int g_checks, g_fail;
54#define CHECK(c, ...) \
55 do { \
56 g_checks++; \
57 if (!(c)) { \
58 g_fail++; \
59 printf("FAIL %s:%d: ", __FILE__, __LINE__); \
60 printf(__VA_ARGS__); \
61 printf("\n"); \
62 } \
63 } while (0)
64
65#define SUBJ_PROPOSER 8u
66#define SUBJ_AUTHORITY 4u
67
68#define REC_CALIB RX_COG_MAX_SAMPLE
69#define PLAN_CALIB RX_COG_MAX_SAMPLE
70#define REC_EVAL 20000u
71#define PLAN_EVAL 2000u
72#define PASSES 9
73#define SEED_TRAIN 0x5eed0001ull
74
75/* ---- energy meter (aien_spbm hwmon, microjoules) ---- */
76
77static char g_meter[512];
78
79typedef struct {
80 uint64_t pkg, cpu_e, cpu_p;
81} Energy;
82
83static void meter_find(void) {
84 DIR *d = opendir("/sys/class/hwmon");
85 if (!d) return;
86 struct dirent *e;
87 while ((e = readdir(d))) {
88 if (e->d_name[0] == '.') continue;
89 char path[600], name[64] = {0};
90 snprintf(path, sizeof path, "/sys/class/hwmon/%s/name", e->d_name);
91 FILE *fp = fopen(path, "r");
92 if (!fp) continue;
93 if (fgets(name, sizeof name, fp) && strncmp(name, "aien_spbm", 9) == 0)
94 snprintf(g_meter, sizeof g_meter, "/sys/class/hwmon/%s", e->d_name);
95 fclose(fp);
96 }
97 closedir(d);
98}
99
100static uint64_t meter_channel(const char *label) {
101 for (int i = 1; i <= 8; i++) {
102 char path[640], lab[64] = {0};
103 snprintf(path, sizeof path, "%s/energy%d_label", g_meter, i);
104 FILE *fp = fopen(path, "r");
105 if (!fp) continue;
106 int ok = fgets(lab, sizeof lab, fp) != NULL;
107 fclose(fp);
108 lab[strcspn(lab, "\n")] = 0;
109 if (!ok || strcmp(lab, label) != 0) continue;
110 snprintf(path, sizeof path, "%s/energy%d_input", g_meter, i);
111 fp = fopen(path, "r");
112 if (!fp) return 0;
113 unsigned long long v = 0;
114 if (fscanf(fp, "%llu", &v) != 1) v = 0;
115 fclose(fp);
116 return v;
117 }
118 return 0;
119}
120
121static Energy meter_read(void) {
122 Energy e = {0, 0, 0};
123 if (!g_meter[0]) return e;
124 e.pkg = meter_channel("pkg");
125 e.cpu_e = meter_channel("cpu_e");
126 e.cpu_p = meter_channel("cpu_p");
127 return e;
128}
129
130static uint64_t cpu_uj(Energy a, Energy b) { return (b.cpu_p - a.cpu_p) + (b.cpu_e - a.cpu_e); }
131
132static uint64_t now_ns(clockid_t c) {
133 struct timespec ts;
134 clock_gettime(c, &ts);
135 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
136}
137
138/* ---- placement ---- */
139
140static char g_cpus[64] = "unpinned";
141
142static void place(void) {
143 long n = sysconf(_SC_NPROCESSORS_CONF);
144 for (long c = n - 1; c >= 0; c--) {
145 char path[128];
146 snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%ld/regs/identification/midr_el1", c);
147 FILE *fp = fopen(path, "r");
148 if (!fp) continue;
149 unsigned long long midr = 0;
150 int ok = fscanf(fp, "%llx", &midr) == 1;
151 fclose(fp);
152 if (ok && ((midr >> 4) & 0xfffu) == 0xd85u) {
153 cpu_set_t set;
154 CPU_ZERO(&set);
155 CPU_SET(c, &set);
156 if (sched_setaffinity(0, sizeof set, &set) == 0) {
157 snprintf(g_cpus, sizeof g_cpus, "cpu%ld (Cortex-X925)", c);
158 printf("[*] placed on %s\n", g_cpus);
159 }
160 return;
161 }
162 }
163}
164
165/* ---- authority ---- */
166
167typedef struct {
168 AienosCapAdmin *admin;
169 AienosCapView *view;
170} Auth;
171
172static int native_auth(void *ctx, uint32_t cap_id, uint64_t cap_generation, uint32_t subject,
173 uint64_t resource, uint32_t rights) {
174 Auth *a = ctx;
175 AienosCapRef ref = {cap_id, cap_generation};
176 AienosCapEntry entry;
177 return aienos_cap_validate(a->view, ref, subject, resource, rights, &entry);
178}
179
180static int mint(Auth *a, uint32_t subject, uint32_t rights, AienosCapRef *out) {
181 AienosCapMint m;
182 memset(&m, 0, sizeof m);
183 m.issuer = 3;
184 m.subject = subject;
185 m.resource = RX_GEN_RES_PROMOTION;
186 m.rights = rights;
187 m.parent.cap_id = UINT32_MAX;
188 if (aienos_cap_office(a->admin, &m.authority) != 0) return -1;
189 return aienos_cap_mint(a->admin, &m, out);
190}
191
192static int promote(RxGenStore *store, Auth *a, uint64_t cand, uint32_t subject, AienosCapRef cap) {
193 RxPromotionRequest q;
194 memset(&q, 0, sizeof q);
195 q.candidate_id = cand;
196 q.subject = subject;
197 q.cap_id = cap.cap_id;
198 q.cap_generation = cap.generation;
199 q.resource = RX_GEN_RES_PROMOTION;
200 q.rights = RX_GEN_RIGHT_PROMOTE;
201 return rx_gen_promote(store, &q, native_auth, a, NULL, NULL, NULL, NULL);
202}
203
204/* ---- workloads ---- */
205
206typedef struct {
207 RecInput *rec;
208 uint8_t *rec_truth;
209 uint32_t n_rec;
210 uint8_t *map;
211 PlanInput *plan;
212 int *plan_truth;
213 uint32_t n_plan;
214} Workload;
215
216static void workload_make(Workload *w, uint64_t seed, uint32_t n_rec, uint32_t n_plan) {
217 memset(w, 0, sizeof *w);
218 uint64_t rng = seed;
219 w->n_rec = n_rec;
220 w->rec = malloc(n_rec * sizeof(RecInput));
221 w->rec_truth = malloc(n_rec);
222 for (uint32_t i = 0; i < n_rec; i++) {
223 rec_sample(&rng, &w->rec[i]);
224 w->rec_truth[i] = (uint8_t)rec_truth(&w->rec[i]);
225 }
226 w->map = malloc(GRID_CELLS);
227 plan_map(seed ^ 0xabcdef, w->map);
228 w->n_plan = n_plan;
229 w->plan = malloc(n_plan * sizeof(PlanInput));
230 w->plan_truth = malloc(n_plan * sizeof(int));
231 for (uint32_t i = 0; i < n_plan; i++) {
232 plan_sample(&rng, w->map, &w->plan[i]);
233 w->plan_truth[i] = plan_truth(&w->plan[i]);
234 }
235}
236
237static void workload_free(Workload *w) {
238 free(w->rec);
239 free(w->rec_truth);
240 free(w->map);
241 free(w->plan);
242 free(w->plan_truth);
243}
244
245static RxCogRequirement req_rec(void) {
246 RxCogRequirement q;
247 memset(&q, 0, sizeof q);
248 q.operation_class = RX_COG_OP_RECOGNIZE;
249 q.minimum_quality_ppm = 950000;
250 q.uncertainty_budget_ppm = 20000;
251 q.memory_requirement = 64;
252 q.precision_requirement = RX_COG_PREC_APPROX;
253 q.latency_budget_ns = 200000;
254 q.hardware_constraints = RX_COG_HW_CPU_P | RX_COG_HW_CPU_E;
255 q.escalation_allowed = 3;
256 return q;
257}
258
259static RxCogRequirement req_plan(uint32_t depth) {
260 RxCogRequirement q;
261 memset(&q, 0, sizeof q);
262 q.operation_class = RX_COG_OP_PLAN;
263 q.minimum_quality_ppm = 998000;
264 q.uncertainty_budget_ppm = 1000;
265 q.memory_requirement = GRID_CELLS;
266 q.planning_depth = depth;
267 q.precision_requirement = RX_COG_PREC_EXACT;
268 q.latency_budget_ns = 2000000;
269 q.hardware_constraints = RX_COG_HW_CPU_P | RX_COG_HW_CPU_E;
270 q.escalation_allowed = 2;
271 return q;
272}
273
274/* All engines of an operation on the same labelled requests. */
275static const uint32_t REC_ENGINES[] = {ENG_POLICY, ENG_NEURAL, ENG_GENERAL, ENG_ENSEMBLE};
276static const uint32_t PLAN_ENGINES[] = {ENG_GREEDY, ENG_FOCUSED, ENG_JSPACE};
277
278static PlanOutput g_pout;
279
280static uint64_t thread_ns(void) { return now_ns(CLOCK_THREAD_CPUTIME_ID); }
281
282static void calibrate(RxCogLedger *l, const Workload *w) {
283 for (uint32_t i = 0; i < w->n_rec; i++) {
284 uint32_t conf[4];
285 uint8_t ok[4], failed[4];
286 uint64_t ns[4];
287 for (int k = 0; k < 4; k++) {
288 RecOutput out;
289 uint64_t t0 = thread_ns();
290 int rc = cog_engine_fn(REC_ENGINES[k])(NULL, RX_COG_OP_RECOGNIZE, &w->rec[i], &out, &conf[k]);
291 ns[k] = thread_ns() - t0;
292 failed[k] = rc != 0;
293 ok[k] = rc == 0 && out.label == w->rec_truth[i];
294 }
295 CHECK(rx_route_observe(l, RX_COG_OP_RECOGNIZE, 4, REC_ENGINES, conf, ok, ns, failed) == RX_COG_OK,
296 "observe recognition");
297 }
298 for (uint32_t i = 0; i < w->n_plan; i++) {
299 uint32_t conf[3];
300 uint8_t ok[3], failed[3];
301 uint64_t ns[3];
302 for (int k = 0; k < 3; k++) {
303 uint64_t t0 = thread_ns();
304 int rc = cog_engine_fn(PLAN_ENGINES[k])(NULL, RX_COG_OP_PLAN, &w->plan[i], &g_pout, &conf[k]);
305 ns[k] = thread_ns() - t0;
306 failed[k] = rc != 0;
307 ok[k] = rc == 0 && plan_correct(&w->plan[i], &g_pout, w->plan_truth[i]);
308 }
309 CHECK(rx_route_observe(l, RX_COG_OP_PLAN, 3, PLAN_ENGINES, conf, ok, ns, failed) == RX_COG_OK,
310 "observe planning");
311 }
312 /* Cost per call: each engine alone over its calibration set, repeated for
313 * at least 400 ms: processor time for the batch, and metered energy when
314 * there is a meter (the 1 mJ counter step is then < 0.1%). */
315 for (int op = 0; op < 2; op++) {
316 const uint32_t *ids = op == 0 ? REC_ENGINES : PLAN_ENGINES;
317 int n = op == 0 ? 4 : 3;
318 for (int k = 0; k < n; k++) {
319 RxCogEngineFn fn = cog_engine_fn(ids[k]);
320 uint64_t calls = 0, t0 = now_ns(CLOCK_MONOTONIC), c0 = thread_ns();
321 Energy e0 = meter_read();
322 do {
323 uint32_t conf;
324 if (op == 0) {
325 RecOutput out;
326 for (uint32_t i = 0; i < w->n_rec; i++) fn(NULL, 0, &w->rec[i], &out, &conf);
327 calls += w->n_rec;
328 } else {
329 for (uint32_t i = 0; i < w->n_plan; i++) fn(NULL, 1, &w->plan[i], &g_pout, &conf);
330 calls += w->n_plan;
331 }
332 } while (now_ns(CLOCK_MONOTONIC) - t0 < 400000000ull);
333 Energy e1 = meter_read();
334 uint64_t cpu = thread_ns() - c0;
335 CHECK(rx_route_observe_batch(l, ids[k], (uint32_t)op, calls, cpu, g_meter[0] != 0,
336 cpu_uj(e0, e1) * 1000ull) ==
337 RX_COG_OK, "observe batch cost");
338 }
339 }
340}
341
342typedef struct {
343 uint64_t cpu_ns, wall_ns, cpu_uj, pkg_uj;
344 uint32_t rec_correct, plan_correct;
345 uint32_t exhausted, refused, max_escalations, escalation_violations;
346 uint32_t final_count[32];
347 uint32_t escalated;
348} PassResult;
349
350/* One pass over the workload. routed = 1: through the router.
351 * routed = 0: the always-most-expensive realization for each operation. */
352static void run_pass(RxCogRouter *r, const Workload *w, int routed, PassResult *pr) {
353 memset(pr, 0, sizeof *pr);
354 RxCogRequirement qr = req_rec();
355 uint32_t top_rec = 0, top_plan = 0;
356 RxCogEngineFn frec = NULL, fplan = NULL;
357 if (!routed) {
358 rx_route_most_expensive(r, &qr, &top_rec);
359 RxCogRequirement qp = req_plan(0);
360 rx_route_most_expensive(r, &qp, &top_plan);
361 frec = cog_engine_fn(top_rec);
362 fplan = cog_engine_fn(top_plan);
363 }
364 Energy e0 = meter_read();
365 uint64_t c0 = thread_ns(), w0 = now_ns(CLOCK_MONOTONIC);
366 for (uint32_t i = 0; i < w->n_rec; i++) {
367 RecOutput out = {-1};
368 if (routed) {
369 RxCogTrace t;
370 int rc = rx_route_run(r, &qr, &w->rec[i], &out, sizeof out, &t);
371 if (rc == RX_COG_ERR_EXHAUSTED) pr->exhausted++;
372 else if (rc != RX_COG_OK) pr->refused++;
373 if (t.escalations > pr->max_escalations) pr->max_escalations = t.escalations;
374 if (t.escalations > qr.escalation_allowed) pr->escalation_violations++;
375 if (t.escalations) pr->escalated++;
376 pr->final_count[t.final_engine % 32]++;
377 } else {
378 uint32_t conf;
379 frec(NULL, RX_COG_OP_RECOGNIZE, &w->rec[i], &out, &conf);
380 pr->final_count[top_rec % 32]++;
381 }
382 pr->rec_correct += out.label == w->rec_truth[i];
383 }
384 for (uint32_t i = 0; i < w->n_plan; i++) {
385 RxCogRequirement qp = req_plan(w->plan[i].bound);
386 g_pout.status = -1;
387 g_pout.len = 0;
388 if (routed) {
389 RxCogTrace t;
390 int rc = rx_route_run(r, &qp, &w->plan[i], &g_pout, sizeof g_pout, &t);
391 if (rc == RX_COG_ERR_EXHAUSTED) pr->exhausted++;
392 else if (rc != RX_COG_OK) pr->refused++;
393 if (t.escalations > pr->max_escalations) pr->max_escalations = t.escalations;
394 if (t.escalations > qp.escalation_allowed) pr->escalation_violations++;
395 if (t.escalations) pr->escalated++;
396 pr->final_count[t.final_engine % 32]++;
397 } else {
398 uint32_t conf;
399 fplan(NULL, RX_COG_OP_PLAN, &w->plan[i], &g_pout, &conf);
400 pr->final_count[top_plan % 32]++;
401 }
402 pr->plan_correct += (uint32_t)plan_correct(&w->plan[i], &g_pout, w->plan_truth[i]);
403 }
404 pr->cpu_ns = thread_ns() - c0;
405 pr->wall_ns = now_ns(CLOCK_MONOTONIC) - w0;
406 Energy e1 = meter_read();
407 pr->cpu_uj = cpu_uj(e0, e1);
408 pr->pkg_uj = e1.pkg - e0.pkg;
409}
410
411static int cmp_u64(const void *a, const void *b) {
412 uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b;
413 return x < y ? -1 : x > y;
414}
415
416static uint64_t median(uint64_t *v, int n) {
417 qsort(v, (size_t)n, sizeof *v, cmp_u64);
418 return v[n / 2];
419}
420
421/* ---- results for the receipt ---- */
422
423static struct {
424 double train_s;
425 uint32_t gen0, gen1, gen2;
426 RxCogLadder ladder0_rec, ladder0_plan, ladder1_rec, ladder1_plan, ladder2_rec;
427 uint32_t top_rec, top_plan;
428 PassResult routed, base;
429 uint64_t r_cpu_ns, b_cpu_ns, r_cpu_uj, b_cpu_uj, r_pkg_uj, b_pkg_uj, r_wall, b_wall;
430 int energy_measured;
431 uint32_t bypass_attempts, bypass_refused;
432 uint32_t damaged_rec_correct, damaged_n, repaired_rec_correct, repaired_n;
433 uint64_t repaired_cpu_ns, repaired_cpu_uj, damaged_base_cpu_uj, damaged_base_cpu_ns;
434 uint32_t repaired_base_correct;
435 RxCogRealization prof[8];
436 uint32_t n_prof;
437 char model_digest[65];
438} R;
439
440static void hex(const uint8_t *d, char *out) {
441 for (int i = 0; i < 32; i++) sprintf(out + 2 * i, "%02x", d[i]);
442}
443
444static int ladder_eq(const RxCogLadder *a, const RxCogLadder *b) {
445 if (a->n != b->n) return 0;
446 for (uint32_t i = 0; i < a->n; i++)
447 if (a->engine[i] != b->engine[i] || a->accept_min_bin[i] != b->accept_min_bin[i]) return 0;
448 return 1;
449}
450
451static void print_ladder(const char *name, const RxCogLadder *l) {
452 printf(" %-22s", name);
453 for (uint32_t i = 0; i < l->n; i++) printf(" %u(bin>=%u)", l->engine[i], l->accept_min_bin[i]);
454 printf(" q=%.4f lower=%.4f ns=%llu nj=%llu why=%u\n", l->expected_quality_ppm / 1e6,
455 l->quality_lower_ppm / 1e6, (unsigned long long)l->expected_ns,
456 (unsigned long long)l->expected_nj, l->reason);
457}
458
459static void rm_rf(const char *dir) {
460 char cmd[1024];
461 snprintf(cmd, sizeof cmd, "rm -rf '%s'", dir);
462 if (system(cmd) != 0) printf("warning: could not clear %s\n", dir);
463}
464
465/* ---- scenarios ---- */
466
467static void t_constraints(RxCogRouter *r) {
468 RxCogLadder l;
469 RxCogRequirement q = req_rec();
470 q.precision_requirement = RX_COG_PREC_EXACT;
471 CHECK(rx_route_plan(r, &q, &l) == RX_COG_ERR_UNSATISFIABLE, "exact recognition has no realization");
472 q = req_rec();
473 q.temporal_requirement = 4;
474 CHECK(rx_route_plan(r, &q, &l) == RX_COG_ERR_UNSATISFIABLE, "no engine keeps 4 steps of history");
475 q = req_rec();
476 q.hardware_constraints = RX_COG_HW_CPU_E;
477 int rc = rx_route_plan(r, &q, &l);
478 int uses_p = 0;
479 for (uint32_t i = 0; rc == RX_COG_OK && i < l.n; i++)
480 uses_p |= l.engine[i] == ENG_GENERAL || l.engine[i] == ENG_ENSEMBLE;
481 CHECK(rc != RX_COG_OK || !uses_p, "efficiency-core-only request never reaches a P-core engine");
482 q = req_rec();
483 q.memory_requirement = 1u << 20;
484 CHECK(rx_route_plan(r, &q, &l) == RX_COG_ERR_UNSATISFIABLE, "no engine holds 1 MiB");
485 q = req_rec();
486 q.minimum_quality_ppm = 999900;
487 CHECK(rx_route_plan(r, &q, &l) == RX_COG_ERR_UNSATISFIABLE,
488 "a quality no ladder is shown to reach is refused, not approximated");
489 q = req_rec();
490 q.latency_budget_ns = 1;
491 CHECK(rx_route_plan(r, &q, &l) == RX_COG_ERR_UNSATISFIABLE, "latency budget is enforced");
492 q = req_rec();
493 q.escalation_allowed = 0;
494 rc = rx_route_plan(r, &q, &l);
495 CHECK(rc == RX_COG_OK && l.n == 1, "no escalation allowed: one rung (rc %d n %u)", rc, l.n);
496 print_ladder("recognize, no escal.", &l);
497 q = req_plan(2000);
498 rc = rx_route_plan(r, &q, &l);
499 CHECK(rc == RX_COG_OK && l.n == 1 && l.engine[0] == ENG_JSPACE,
500 "planning depth 2000 leaves only exhaustive exploration");
501 q = req_plan(100);
502 q.escalation_allowed = 9;
503 rc = rx_route_plan(r, &q, &l);
504 CHECK(rc == RX_COG_OK && l.n <= RX_COG_MAX_LADDER, "ladder length is capped");
505 if (R.energy_measured) {
506 q = req_rec();
507 RxCogLadder base;
508 rx_route_plan(r, &q, &base);
509 q.energy_budget_nj = base.expected_nj / 2 ? base.expected_nj / 2 : 1;
510 rc = rx_route_plan(r, &q, &l);
511 CHECK(rc == RX_COG_ERR_UNSATISFIABLE || l.expected_nj <= q.energy_budget_nj, "energy budget is enforced");
512 }
513}
514
515/* A model built against a different registry, and a model torn on disk,
516 * never replace the loaded profiles. */
517static void t_model_integrity(Auth *a, AienosCapRef cap, const Workload *calib) {
518 char dir[512];
519 if (omega_evidence_path("COGNITIVE_ROUTING/store-integrity/x", dir, sizeof dir) != 0) return;
520 dir[strlen(dir) - 2] = 0;
521 rm_rf(dir);
522 mkdir(dir, 0700);
523 RxGenStore *store = NULL;
524 CHECK(rx_gen_open(dir, &store) == RX_GEN_OK, "open integrity store");
525 if (!store) return;
526 RxCogRouter *r = NULL, *other = NULL;
527 rx_route_create(&r);
528 cog_register_all(r);
529 RxCogLedger *l = NULL;
530 rx_route_ledger_create(r, &l);
531 Workload small = *calib;
532 small.n_rec = 256;
533 small.n_plan = 64;
534 calibrate(l, &small);
535 uint64_t good = 0;
536 CHECK(rx_route_propose(l, store, SUBJ_PROPOSER, 1, 1, &good) == RX_COG_OK, "propose good");
537 CHECK(promote(store, a, good, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promote good");
538 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == good, "load good");
539 RxCogRealization before;
540 rx_route_realization(r, ENG_POLICY, &before);
541
542 /* foreign: a router whose policy engine declares another capacity */
543 rx_route_create(&other);
544 RxCogDeclaration d = {ENG_POLICY, RX_COG_CLASS_SMALL_POLICY, 1, 0, 9999, 0, 0, RX_COG_PREC_APPROX, 0};
545 rx_route_register(other, &d, cog_engine_fn(ENG_POLICY), NULL, 1);
546 RxCogLedger *lf = NULL;
547 rx_route_ledger_create(other, &lf);
548 uint64_t foreign = 0;
549 CHECK(rx_route_propose(lf, store, SUBJ_PROPOSER, 1, 1, &foreign) == RX_COG_OK, "propose foreign");
550 CHECK(promote(store, a, foreign, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promote foreign");
551 CHECK(rx_route_load(r, store) == RX_COG_ERR_MODEL, "foreign model refused");
552 CHECK(rx_route_generation(r) == good, "router kept the good generation after a foreign model");
553 RxCogRealization after;
554 rx_route_realization(r, ENG_POLICY, &after);
555 CHECK(memcmp(&before, &after, sizeof before) == 0, "profiles unchanged after foreign model");
556
557 /* torn: promote the good ledger again, then flip one byte of its model */
558 uint64_t again = 0;
559 CHECK(rx_route_propose(l, store, SUBJ_PROPOSER, 1, 1, &again) == RX_COG_OK, "propose again");
560 CHECK(promote(store, a, again, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promote again");
561 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == again, "load again");
562 char path[640];
563 snprintf(path, sizeof path, "%s/g/%llu/model", dir, (unsigned long long)again);
564 int fd = open(path, O_RDWR);
565 CHECK(fd >= 0, "open model file");
566 if (fd >= 0) {
567 uint8_t b;
568 if (pread(fd, &b, 1, 100) == 1) {
569 b ^= 1;
570 CHECK(pwrite(fd, &b, 1, 100) == 1, "flip");
571 }
572 close(fd);
573 }
574 RxCogRouter *fresh = NULL;
575 rx_route_create(&fresh);
576 cog_register_all(fresh);
577 CHECK(rx_route_load(fresh, store) == RX_COG_ERR_MODEL, "torn model refused by a fresh router");
578 CHECK(rx_route_load(r, store) == RX_COG_ERR_MODEL && rx_route_generation(r) == again,
579 "torn model refused; loaded generation kept");
580 rx_route_destroy(fresh);
581 rx_route_ledger_destroy(lf);
582 rx_route_destroy(other);
583 rx_route_ledger_destroy(l);
584 rx_route_destroy(r);
585 rx_gen_close(store);
586}
587
588/* Each pair is one routed and one most-expensive pass, back to back, order
589 * alternating. The meter covers whole CPU clusters, so other work on the
590 * machine lands in both; a pair is won only by the routed pass using less. */
591static uint64_t g_pair_cpu_uj[PASSES][2], g_pair_cpu_ns[PASSES][2];
592static uint32_t g_pair_compute_wins, g_pair_energy_wins;
593static double g_load_before, g_load_after;
594
595static double loadavg(void) {
596 double v = -1;
597 FILE *fp = fopen("/proc/loadavg", "r");
598 if (fp) {
599 if (fscanf(fp, "%lf", &v) != 1) v = -1;
600 fclose(fp);
601 }
602 return v;
603}
604
605/* An engine that fails outright on part of its input: the failures are in its
606 * profile, and a failed rung escalates like an unconfident one. */
607static int eng_flaky(void *ctx, uint32_t op, const void *input, void *output, uint32_t *conf) {
608 (void)ctx;
609 const RecInput *in = input;
610 if (op != RX_COG_OP_RECOGNIZE || in->x[0] > 0.3f) return -1;
611 ((RecOutput *)output)->label = rec_truth(in);
612 *conf = RX_COG_CONF_ONE;
613 return 0;
614}
615
616static void t_failure(Auth *a, AienosCapRef cap) {
617 char dir[512];
618 if (omega_evidence_path("COGNITIVE_ROUTING/store-failure/x", dir, sizeof dir) != 0) return;
619 dir[strlen(dir) - 2] = 0;
620 rm_rf(dir);
621 mkdir(dir, 0700);
622 RxGenStore *store = NULL;
623 CHECK(rx_gen_open(dir, &store) == RX_GEN_OK, "open failure store");
624 if (!store) return;
625 RxCogRouter *r = NULL;
626 rx_route_create(&r);
627 RxCogDeclaration flaky = {31, RX_COG_CLASS_SMALL_POLICY, 1, 0, 64, 0, 0, RX_COG_PREC_APPROX, 0};
628 RxCogDeclaration general = {ENG_GENERAL, RX_COG_CLASS_GENERAL, 1, 0, 1u << 16, 0, 0, RX_COG_PREC_APPROX, 0};
629 CHECK(rx_route_register(r, &flaky, eng_flaky, NULL, 0) == RX_COG_OK, "register flaky");
630 CHECK(rx_route_register(r, &general, cog_engine_fn(ENG_GENERAL), NULL, 1) == RX_COG_OK, "register general");
631 RxCogLedger *l = NULL;
632 rx_route_ledger_create(r, &l);
633 uint64_t rng = 0xf1a4e;
634 const uint32_t ids[2] = {31, ENG_GENERAL};
635 uint32_t failures = 0;
636 for (uint32_t i = 0; i < 1500; i++) {
637 RecInput in;
638 rec_sample(&rng, &in);
639 uint32_t conf[2];
640 uint8_t ok[2], failed[2];
641 uint64_t ns[2];
642 for (int k = 0; k < 2; k++) {
643 RecOutput out = {-1};
644 RxCogEngineFn fn = k ? cog_engine_fn(ENG_GENERAL) : eng_flaky;
645 uint64_t t0 = thread_ns();
646 int rc = fn(NULL, 0, &in, &out, &conf[k]);
647 ns[k] = thread_ns() - t0;
648 failed[k] = rc != 0;
649 ok[k] = rc == 0 && out.label == rec_truth(&in);
650 }
651 failures += failed[0];
652 rx_route_observe(l, 0, 2, ids, conf, ok, ns, failed);
653 }
654 uint64_t cand = 0;
655 CHECK(rx_route_propose(l, store, SUBJ_PROPOSER, 1, 1, &cand) == RX_COG_OK, "propose flaky evidence");
656 CHECK(promote(store, a, cand, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promote flaky evidence");
657 CHECK(rx_route_load(r, store) == RX_COG_OK, "load flaky evidence");
658 RxCogRealization x;
659 rx_route_realization(r, 31, &x);
660 CHECK(x.quality_profile[0].failures == failures && failures > 300,
661 "failures are in the profile (%u of %u)", x.quality_profile[0].failures, x.quality_profile[0].observations);
662 RxCogRequirement q = req_rec();
663 q.hardware_constraints = RX_COG_HW_CPU_P | RX_COG_HW_CPU_E;
664 RxCogLadder lad;
665 int rc = rx_route_plan(r, &q, &lad);
666 CHECK(rc == RX_COG_OK && lad.n == 2 && lad.engine[0] == 31 && lad.engine[1] == ENG_GENERAL,
667 "flaky but cheap and right when it answers: tried first");
668 uint32_t failed_runs = 0, escalated = 0, wrong_escalation = 0;
669 for (uint32_t i = 0; i < 2000; i++) {
670 RecInput in;
671 rec_sample(&rng, &in);
672 RecOutput out = {-1};
673 RxCogTrace t;
674 rx_route_run(r, &q, &in, &out, sizeof out, &t);
675 int flaky_failed = in.x[0] > 0.3f;
676 failed_runs += (uint32_t)flaky_failed;
677 escalated += t.escalations > 0;
678 wrong_escalation += (uint32_t)(flaky_failed != (t.escalations == 1));
679 }
680 CHECK(wrong_escalation == 0 && escalated == failed_runs,
681 "every failure escalated and nothing else did (%u failures, %u escalations)", failed_runs, escalated);
682 rx_route_ledger_destroy(l);
683 rx_route_destroy(r);
684 rx_gen_close(store);
685}
686
687static void measure(RxCogRouter *r, const Workload *w, PassResult *routed, PassResult *base,
688 uint64_t out[8]) {
689 uint64_t rc[PASSES], bc[PASSES], re[PASSES], be[PASSES], rp[PASSES], bp[PASSES], rw[PASSES], bw[PASSES];
690 PassResult tmp;
691 run_pass(r, w, 1, &tmp); /* warm caches for both */
692 run_pass(r, w, 0, &tmp);
693 for (int p = 0; p < PASSES; p++) {
694 PassResult a, b;
695 if (p % 2 == 0) {
696 run_pass(r, w, 1, &a);
697 run_pass(r, w, 0, &b);
698 } else {
699 run_pass(r, w, 0, &b);
700 run_pass(r, w, 1, &a);
701 }
702 if (p == 0) {
703 *routed = a;
704 *base = b;
705 }
706 CHECK(a.rec_correct == routed->rec_correct && a.plan_correct == routed->plan_correct &&
707 b.rec_correct == base->rec_correct && b.plan_correct == base->plan_correct,
708 "answers identical across passes");
709 rc[p] = a.cpu_ns, bc[p] = b.cpu_ns, re[p] = a.cpu_uj, be[p] = b.cpu_uj;
710 rp[p] = a.pkg_uj, bp[p] = b.pkg_uj, rw[p] = a.wall_ns, bw[p] = b.wall_ns;
711 g_pair_cpu_uj[p][0] = a.cpu_uj, g_pair_cpu_uj[p][1] = b.cpu_uj;
712 g_pair_cpu_ns[p][0] = a.cpu_ns, g_pair_cpu_ns[p][1] = b.cpu_ns;
713 g_pair_compute_wins += a.cpu_ns < b.cpu_ns;
714 g_pair_energy_wins += a.cpu_uj < b.cpu_uj;
715 }
716 out[0] = median(rc, PASSES), out[1] = median(bc, PASSES), out[2] = median(re, PASSES);
717 out[3] = median(be, PASSES), out[4] = median(rp, PASSES), out[5] = median(bp, PASSES);
718 out[6] = median(rw, PASSES), out[7] = median(bw, PASSES);
719}
720
721/* ---- receipt ---- */
722
723static void binary_digest(char out[65]) {
724 strcpy(out, "unavailable");
725 FILE *fp = fopen("/proc/self/exe", "rb");
726 if (!fp) return;
727 sha256_ctx c;
728 sha256_init(&c);
729 uint8_t buf[65536];
730 size_t n;
731 while ((n = fread(buf, 1, sizeof buf, fp)) > 0) sha256_update(&c, buf, n);
732 fclose(fp);
733 uint8_t d[32];
734 sha256_final(&c, d);
735 hex(d, out);
736}
737
738static void ladder_json(FILE *fp, const RxCogLadder *l) {
739 fprintf(fp, "{\"engines\": [");
740 for (uint32_t i = 0; i < l->n; i++) fprintf(fp, "%s%u", i ? ", " : "", l->engine[i]);
741 fprintf(fp, "], \"accept_from_bin\": [");
742 for (uint32_t i = 0; i < l->n; i++) fprintf(fp, "%s%u", i ? ", " : "", l->accept_min_bin[i]);
743 fprintf(fp, "], \"expected_quality\": %.4f, \"quality_lower_95\": %.4f, \"expected_ns\": %llu, "
744 "\"expected_nj\": %llu, \"reason\": \"%s\"}",
745 l->expected_quality_ppm / 1e6, l->quality_lower_ppm / 1e6, (unsigned long long)l->expected_ns,
746 (unsigned long long)l->expected_nj, l->reason == RX_COG_WHY_NO_EVIDENCE ? "no_evidence_reference" : "evidence");
747}
748
749static double ece(const RxCogCalibration *c) {
750 uint64_t n = 0;
751 double e = 0;
752 for (uint32_t b = 0; b < RX_COG_BINS; b++) n += c->n[b];
753 if (!n) return 0;
754 for (uint32_t b = 0; b < RX_COG_BINS; b++) {
755 if (!c->n[b]) continue;
756 double mid = (b + 0.5) / RX_COG_BINS, acc = (double)c->correct[b] / c->n[b];
757 e += (double)c->n[b] / (double)n * (acc > mid ? acc - mid : mid - acc);
758 }
759 return e;
760}
761
762static int gate_pass(void) {
763 double qmin_rec = req_rec().minimum_quality_ppm / 1e6, qmin_plan = req_plan(0).minimum_quality_ppm / 1e6;
764 int quality = (double)R.routed.rec_correct / REC_EVAL >= qmin_rec &&
765 (double)R.routed.plan_correct / PLAN_EVAL >= qmin_plan &&
766 (double)R.base.rec_correct / REC_EVAL >= qmin_rec &&
767 (double)R.base.plan_correct / PLAN_EVAL >= qmin_plan;
768 int compute = R.r_cpu_ns < R.b_cpu_ns && g_pair_compute_wins == PASSES;
769 int energy = !R.energy_measured || (R.r_cpu_uj < R.b_cpu_uj && g_pair_energy_wins == PASSES);
770 return g_fail == 0 && quality && compute && energy && R.bypass_refused == R.bypass_attempts &&
771 R.routed.escalation_violations == 0;
772}
773
774static void write_receipt(void) {
775 char path[512];
776 if (omega_evidence_path("COGNITIVE_ROUTING/rx_cognitive_routing_receipt.json", path, sizeof path) != 0) return;
777 FILE *fp = fopen(path, "w");
778 if (!fp) return;
779 char commit[41];
780 memset(commit, 0, sizeof commit);
781 if (!omega_evidence_run_commit(commit)) memcpy(commit, "unknown", 8);
782 const char *candidate = getenv("OMEGA_CANDIDATE_COMMIT");
783 int bound = candidate && candidate[0] && strcmp(candidate, commit) == 0 && !omega_evidence_tree_dirty();
784 const char *aienos = getenv("AIENOS_COMMIT");
785 char digest[65];
786 binary_digest(digest);
787 struct utsname u;
788 memset(&u, 0, sizeof u);
789 uname(&u);
790 int pass = gate_pass();
791 fprintf(fp, "{\n \"schema\": \"OMEGA_COGNITIVE_ROUTING_V1\",\n \"run_id\": \"%s\",\n",
792 omega_evidence_run_id());
793 fprintf(fp, " \"candidate_commit\": %s%s%s,\n \"candidate_bound\": %s,\n \"run_commit\": \"%s\",\n",
794 candidate ? "\"" : "", candidate ? candidate : "null", candidate ? "\"" : "",
795 bound ? "true" : "false", commit);
796 fprintf(fp, " \"tree_dirty\": %s,\n \"aienos_commit\": %s%s%s,\n \"checks\": %d,\n \"failures\": %d,\n",
797 omega_evidence_tree_dirty() ? "true" : "false", aienos ? "\"" : "", aienos ? aienos : "null",
798 aienos ? "\"" : "", g_checks, g_fail);
799 fprintf(fp, " \"test_binary_sha256\": \"%s\",\n", digest);
800 fprintf(fp, " \"host\": {\"sysname\": \"%s\", \"release\": \"%s\", \"machine\": \"%s\", \"cpus\": \"%s\"},\n",
801 u.sysname, u.release, u.machine, g_cpus);
802 fprintf(fp, " \"scope\": \"host processor; stand-in engines (not AIEN); native AIENOS authority library\",\n");
803 fprintf(fp, " \"energy_meter\": %s%s%s,\n", g_meter[0] ? "\"" : "", g_meter[0] ? "aien_spbm cpu_p+cpu_e, pkg" : "null",
804 g_meter[0] ? "\"" : "");
805 fprintf(fp, " \"engines_train_seconds\": %.2f,\n", R.train_s);
806 fprintf(fp, " \"generations\": {\"before_evidence\": %u, \"calibrated\": %u, \"after_damage\": %u, "
807 "\"model_sha256\": \"%s\"},\n", R.gen0, R.gen1, R.gen2, R.model_digest);
808 fprintf(fp, " \"realizations\": [\n");
809 for (uint32_t i = 0; i < R.n_prof; i++) {
810 const RxCogRealization *x = &R.prof[i];
811 uint32_t op = (x->decl.supported_operations & 1) ? 0 : 1;
812 const RxCogCost *c = &x->resource_cost_model[op];
813 const RxCogQuality *q = &x->quality_profile[op];
814 fprintf(fp, " {\"id\": %u, \"class\": %u, \"op\": %u, \"generation\": %llu, \"accuracy\": %.4f, "
815 "\"failures\": %u, \"calibration_error\": %.4f, \"mean_ns\": %llu, \"p99_ns\": %llu, "
816 "\"nj_per_call\": %llu, \"energy_measured\": %s}%s\n",
817 x->cognitive_engine_id, x->decl.realization_class, op, (unsigned long long)x->generation,
818 q->observations ? (double)q->correct / q->observations : 0.0, q->failures,
819 ece(&x->uncertainty_profile[op]), (unsigned long long)c->mean_ns,
820 (unsigned long long)c->p99_ns, (unsigned long long)c->nj_per_call,
821 c->energy_measured ? "true" : "false", i + 1 < R.n_prof ? "," : "");
822 }
823 fprintf(fp, " ],\n \"ladders\": {\n \"recognize_no_evidence\": ");
824 ladder_json(fp, &R.ladder0_rec);
825 fprintf(fp, ",\n \"plan_no_evidence\": ");
826 ladder_json(fp, &R.ladder0_plan);
827 fprintf(fp, ",\n \"recognize\": ");
828 ladder_json(fp, &R.ladder1_rec);
829 fprintf(fp, ",\n \"plan_bound_100\": ");
830 ladder_json(fp, &R.ladder1_plan);
831 fprintf(fp, ",\n \"recognize_after_damage\": ");
832 ladder_json(fp, &R.ladder2_rec);
833 fprintf(fp, "\n },\n");
834 fprintf(fp, " \"gate_workload\": {\"recognize\": %u, \"plan\": %u, \"passes\": %d, "
835 "\"most_expensive\": {\"recognize\": %u, \"plan\": %u},\n",
836 REC_EVAL, PLAN_EVAL, PASSES, R.top_rec, R.top_plan);
837 fprintf(fp, " \"requirement\": {\"recognize_min_quality\": %.4f, \"plan_min_quality\": %.4f},\n",
838 req_rec().minimum_quality_ppm / 1e6, req_plan(0).minimum_quality_ppm / 1e6);
839 fprintf(fp, " \"routed\": {\"recognize_quality\": %.4f, \"plan_quality\": %.4f, \"median_cpu_ns\": %llu, "
840 "\"median_wall_ns\": %llu, \"median_cpu_energy_uj\": %llu, \"median_pkg_energy_uj\": %llu, "
841 "\"escalated\": %u, \"exhausted\": %u, \"refused\": %u, \"max_escalations\": %u, "
842 "\"escalation_bound_violations\": %u},\n",
843 (double)R.routed.rec_correct / REC_EVAL, (double)R.routed.plan_correct / PLAN_EVAL,
844 (unsigned long long)R.r_cpu_ns, (unsigned long long)R.r_wall, (unsigned long long)R.r_cpu_uj,
845 (unsigned long long)R.r_pkg_uj, R.routed.escalated, R.routed.exhausted, R.routed.refused,
846 R.routed.max_escalations, R.routed.escalation_violations);
847 fprintf(fp, " \"most_expensive_always\": {\"recognize_quality\": %.4f, \"plan_quality\": %.4f, "
848 "\"median_cpu_ns\": %llu, \"median_wall_ns\": %llu, \"median_cpu_energy_uj\": %llu, "
849 "\"median_pkg_energy_uj\": %llu},\n",
850 (double)R.base.rec_correct / REC_EVAL, (double)R.base.plan_correct / PLAN_EVAL,
851 (unsigned long long)R.b_cpu_ns, (unsigned long long)R.b_wall, (unsigned long long)R.b_cpu_uj,
852 (unsigned long long)R.b_pkg_uj);
853 fprintf(fp, " \"compute_ratio\": %.4f, \"cpu_energy_ratio\": %s%.4f%s, \"pkg_energy_ratio\": %.4f\n },\n",
854 (double)R.r_cpu_ns / (double)(R.b_cpu_ns ? R.b_cpu_ns : 1), R.energy_measured ? "" : "\"n/a ",
855 R.energy_measured ? (double)R.r_cpu_uj / (double)(R.b_cpu_uj ? R.b_cpu_uj : 1) : 0.0,
856 R.energy_measured ? "" : "\"", R.energy_measured ? (double)R.r_pkg_uj / (double)(R.b_pkg_uj ? R.b_pkg_uj : 1) : 0.0);
857 fprintf(fp, " \"pairs\": {\"load_average_before\": %.2f, \"load_average_after\": %.2f, "
858 "\"compute_wins\": %u, \"energy_wins\": %u, \"of\": %d,\n \"cpu_ns\": [",
859 g_load_before, g_load_after, g_pair_compute_wins, g_pair_energy_wins, PASSES);
860 for (int p = 0; p < PASSES; p++)
861 fprintf(fp, "%s[%llu, %llu]", p ? ", " : "", (unsigned long long)g_pair_cpu_ns[p][0],
862 (unsigned long long)g_pair_cpu_ns[p][1]);
863 fprintf(fp, "],\n \"cpu_energy_uj\": [");
864 for (int p = 0; p < PASSES; p++)
865 fprintf(fp, "%s[%llu, %llu]", p ? ", " : "", (unsigned long long)g_pair_cpu_uj[p][0],
866 (unsigned long long)g_pair_cpu_uj[p][1]);
867 fprintf(fp, "]},\n");
868 fprintf(fp, " \"learning\": {\"damaged_engine\": %u, \"quality_under_old_generation\": %.4f, "
869 "\"quality_after_promotion\": %.4f, \"most_expensive_quality_same_inputs\": %.4f, "
870 "\"cpu_ns_after_promotion\": %llu, \"most_expensive_cpu_ns\": %llu, "
871 "\"cpu_energy_uj_after_promotion\": %llu, \"most_expensive_cpu_energy_uj\": %llu},\n",
872 ENG_NEURAL, R.damaged_n ? (double)R.damaged_rec_correct / R.damaged_n : 0.0,
873 R.repaired_n ? (double)R.repaired_rec_correct / R.repaired_n : 0.0,
874 R.repaired_n ? (double)R.repaired_base_correct / R.repaired_n : 0.0,
875 (unsigned long long)R.repaired_cpu_ns, (unsigned long long)R.damaged_base_cpu_ns,
876 (unsigned long long)R.repaired_cpu_uj, (unsigned long long)R.damaged_base_cpu_uj);
877 fprintf(fp, " \"promotion\": {\"bypass_attempts\": %u, \"bypass_refused\": %u, "
878 "\"router_links_promote\": false, \"router_links_authority_admin\": false},\n",
879 R.bypass_attempts, R.bypass_refused);
880 fprintf(fp, " \"gates\": {\n \"OMEGA_COGNITIVE_ROUTING_PASS\": \"%s\",\n", pass ? "PASS" : "FAIL");
881 fprintf(fp, " \"not_claimed\": [\"AIEN cognition (engines are stand-ins)\", \"graphics-processor realizations\", "
882 "\"energy below idle (the meter is whole-cluster and includes idle draw)\", "
883 "\"routing across concurrent requests\", \"online learning without labelled trials\"]\n }\n}\n");
884 fclose(fp);
885 printf("receipt: %s\n", path);
886}
887
888int main(void) {
889 signal(SIGPIPE, SIG_IGN);
890 place();
891 meter_find();
892 R.energy_measured = g_meter[0] != 0;
893 printf("[*] energy meter: %s\n", g_meter[0] ? g_meter : "none (compute only)");
894
895 uint64_t t0 = now_ns(CLOCK_MONOTONIC);
896 cog_engines_train(SEED_TRAIN, 20000, 8);
897 R.train_s = (double)(now_ns(CLOCK_MONOTONIC) - t0) / 1e9;
898 printf("[*] engines trained in %.1f s\n", R.train_s);
899
900 Auth a;
901 CHECK(aienos_cap_start(&a.admin, &a.view) == 0, "authority start");
902 AienosCapRef cap = {0, 0}, weak = {0, 0};
903 CHECK(mint(&a, SUBJ_AUTHORITY, RX_GEN_RIGHT_PROMOTE, &cap) == 0, "mint promotion right");
904 CHECK(mint(&a, SUBJ_AUTHORITY, 0x1u, &weak) == 0, "mint a right that is not promotion");
905
906 char dir[512];
907 CHECK(omega_evidence_path("COGNITIVE_ROUTING/store/x", dir, sizeof dir) == 0, "store path");
908 dir[strlen(dir) - 2] = 0;
909 rm_rf(dir);
910 mkdir(dir, 0700);
911 RxGenStore *store = NULL;
912 CHECK(rx_gen_open(dir, &store) == RX_GEN_OK, "open store");
913
914 RxCogRouter *r = NULL;
915 CHECK(rx_route_create(&r) == RX_COG_OK, "router");
916 CHECK(cog_register_all(r) == RX_COG_OK, "register engines");
917
918 /* 1. no evidence */
919 {
920 uint64_t genesis = 0, lineage = 0;
921 rx_gen_active(store, &genesis, &lineage);
922 R.gen0 = (uint32_t)genesis;
923 }
924 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == R.gen0, "load the genesis generation (no model)");
925 RxCogRequirement qr = req_rec(), qp = req_plan(100);
926 CHECK(rx_route_plan(r, &qr, &R.ladder0_rec) == RX_COG_OK && R.ladder0_rec.n == 1 &&
927 R.ladder0_rec.engine[0] == ENG_GENERAL && R.ladder0_rec.reason == RX_COG_WHY_NO_EVIDENCE,
928 "no evidence: recognition runs the reference (general) alone");
929 CHECK(rx_route_plan(r, &qp, &R.ladder0_plan) == RX_COG_OK && R.ladder0_plan.n == 1 &&
930 R.ladder0_plan.engine[0] == ENG_JSPACE, "no evidence: planning runs exhaustive exploration");
931 CHECK(rx_route_register(r, &(RxCogDeclaration){99, 1, 1, 0, 0, 0, 0, 1, 0}, cog_engine_fn(ENG_POLICY), NULL, 0) ==
932 RX_COG_ERR_ARG, "registry is sealed once routing starts");
933 print_ladder("recognize, gen 0", &R.ladder0_rec);
934 print_ladder("plan, gen 0", &R.ladder0_plan);
935
936 /* 2. evidence -> candidate -> promotion */
937 Workload calib;
938 workload_make(&calib, 0xca11b0001ull, REC_CALIB, PLAN_CALIB);
939 RxCogLedger *l1 = NULL;
940 CHECK(rx_route_ledger_create(r, &l1) == RX_COG_OK, "ledger");
941 calibrate(l1, &calib);
942 uint64_t cand = 0;
943 CHECK(rx_route_propose(l1, store, SUBJ_PROPOSER, 1, 1, &cand) == RX_COG_OK, "propose calibrated model");
944 {
945 uint8_t *m = NULL;
946 size_t mn = 0;
947 rx_route_ledger_model(l1, &m, &mn);
948 uint8_t d[32];
949 sha256_hash(m, mn, d);
950 hex(d, R.model_digest);
951 printf("[*] model %zu bytes\n", mn);
952 free(m);
953 }
954 RxCogLadder chk;
955 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == R.gen0, "a proposal changes nothing");
956 CHECK(rx_route_plan(r, &qr, &chk) == RX_COG_OK && ladder_eq(&chk, &R.ladder0_rec), "ladder unchanged by proposal");
957 R.bypass_attempts++;
958 R.bypass_refused += promote(store, &a, cand, SUBJ_PROPOSER, cap) != RX_GEN_OK;
959 R.bypass_attempts++;
960 R.bypass_refused += promote(store, &a, cand, SUBJ_AUTHORITY, weak) != RX_GEN_OK;
961 CHECK(R.bypass_refused == R.bypass_attempts, "promotion by the proposer or without the right is refused");
962 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == R.gen0, "refused promotion changes nothing");
963 CHECK(promote(store, &a, cand, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promotion with the right");
964 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == cand, "router follows the promotion");
965 R.gen1 = (uint32_t)cand;
966 CHECK(rx_route_plan(r, &qr, &R.ladder1_rec) == RX_COG_OK, "calibrated recognition ladder");
967 CHECK(rx_route_plan(r, &qp, &R.ladder1_plan) == RX_COG_OK, "calibrated planning ladder");
968 print_ladder("recognize, gen 1", &R.ladder1_rec);
969 print_ladder("plan<=100, gen 1", &R.ladder1_plan);
970 CHECK(R.ladder1_rec.quality_lower_ppm >= qr.minimum_quality_ppm, "chosen recognition ladder meets requirement on evidence");
971 static const uint32_t ALL[] = {ENG_POLICY, ENG_NEURAL, ENG_GENERAL, ENG_ENSEMBLE, ENG_GREEDY, ENG_FOCUSED, ENG_JSPACE};
972 for (uint32_t i = 0; i < 7; i++) {
973 rx_route_realization(r, ALL[i], &R.prof[i]);
974 uint32_t op = (R.prof[i].decl.supported_operations & 1) ? 0 : 1;
975 const RxCogQuality *q = &R.prof[i].quality_profile[op];
976 const RxCogCost *c = &R.prof[i].resource_cost_model[op];
977 printf(" engine %u class %u: accuracy %.4f ece %.4f mean %llu ns p99 %llu ns %llu nJ/call\n", ALL[i],
978 R.prof[i].decl.realization_class, (double)q->correct / (q->observations ? q->observations : 1),
979 ece(&R.prof[i].uncertainty_profile[op]), (unsigned long long)c->mean_ns,
980 (unsigned long long)c->p99_ns, (unsigned long long)c->nj_per_call);
981 CHECK(R.prof[i].generation == cand, "profile carries its generation");
982 }
983 R.n_prof = 7;
984
985 /* 5a. constraints */
986 t_constraints(r);
987
988 /* 3. gate */
989 Workload eval;
990 workload_make(&eval, 0xe7a10001ull, REC_EVAL, PLAN_EVAL);
991 rx_route_most_expensive(r, &qr, &R.top_rec);
992 rx_route_most_expensive(r, &qp, &R.top_plan);
993 printf("[*] most expensive: recognize %u, plan %u\n", R.top_rec, R.top_plan);
994 uint64_t m[8];
995 g_load_before = loadavg();
996 measure(r, &eval, &R.routed, &R.base, m);
997 g_load_after = loadavg();
998 CHECK(g_pair_compute_wins == PASSES, "routed used less processor time in every pair (%u of %d)", g_pair_compute_wins, PASSES);
999 if (R.energy_measured)
1000 CHECK(g_pair_energy_wins == PASSES, "routed used less metered energy in every pair (%u of %d)", g_pair_energy_wins, PASSES);
1001 R.r_cpu_ns = m[0], R.b_cpu_ns = m[1], R.r_cpu_uj = m[2], R.b_cpu_uj = m[3];
1002 R.r_pkg_uj = m[4], R.b_pkg_uj = m[5], R.r_wall = m[6], R.b_wall = m[7];
1003 printf("[*] routed: recognize %.4f plan %.4f cpu %.1f ms cpu energy %.1f mJ pkg %.1f mJ escalated %u\n",
1004 (double)R.routed.rec_correct / REC_EVAL, (double)R.routed.plan_correct / PLAN_EVAL, R.r_cpu_ns / 1e6,
1005 R.r_cpu_uj / 1e3, R.r_pkg_uj / 1e3, R.routed.escalated);
1006 printf("[*] baseline: recognize %.4f plan %.4f cpu %.1f ms cpu energy %.1f mJ pkg %.1f mJ\n",
1007 (double)R.base.rec_correct / REC_EVAL, (double)R.base.plan_correct / PLAN_EVAL, R.b_cpu_ns / 1e6,
1008 R.b_cpu_uj / 1e3, R.b_pkg_uj / 1e3);
1009 printf(" final engines (routed):");
1010 for (int i = 0; i < 32; i++)
1011 if (R.routed.final_count[i]) printf(" %d:%u", i, R.routed.final_count[i]);
1012 printf("\n");
1013 CHECK(R.routed.escalation_violations == 0, "escalation stayed within its bound");
1014 CHECK(R.routed.refused == 0, "no routed request refused");
1015 CHECK((double)R.routed.rec_correct / REC_EVAL >= qr.minimum_quality_ppm / 1e6, "routed recognition meets requirement");
1016 CHECK((double)R.routed.plan_correct / PLAN_EVAL >= qp.minimum_quality_ppm / 1e6, "routed planning meets requirement");
1017 CHECK((double)R.base.rec_correct / REC_EVAL >= qr.minimum_quality_ppm / 1e6, "baseline recognition meets requirement");
1018 CHECK((double)R.base.plan_correct / PLAN_EVAL >= qp.minimum_quality_ppm / 1e6, "baseline planning meets requirement");
1019 CHECK(R.r_cpu_ns < R.b_cpu_ns, "routed uses less processor time");
1020 if (R.energy_measured) CHECK(R.r_cpu_uj < R.b_cpu_uj, "routed uses less metered energy");
1021
1022 /* 4. learning under promotion */
1023 cog_damage_neural(0xdead, 0.6f);
1024 Workload audit;
1025 workload_make(&audit, 0xa0d17001ull, REC_EVAL, 0);
1026 PassResult dam;
1027 run_pass(r, &audit, 1, &dam);
1028 R.damaged_rec_correct = dam.rec_correct;
1029 R.damaged_n = REC_EVAL;
1030 printf("[*] neural module damaged: routed recognition %.4f under still-active generation %u\n",
1031 (double)dam.rec_correct / REC_EVAL, R.gen1);
1032 CHECK((double)dam.rec_correct / REC_EVAL < qr.minimum_quality_ppm / 1e6,
1033 "the damage is real: quality under the old generation falls below the requirement");
1034 Workload calib2;
1035 workload_make(&calib2, 0xca11b0002ull, REC_CALIB, PLAN_CALIB);
1036 RxCogLedger *l2 = NULL;
1037 rx_route_ledger_create(r, &l2);
1038 calibrate(l2, &calib2);
1039 uint64_t cand2 = 0;
1040 CHECK(rx_route_propose(l2, store, SUBJ_PROPOSER, 1, 1, &cand2) == RX_COG_OK, "propose after damage");
1041 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == cand, "new evidence alone changes nothing");
1042 CHECK(rx_route_plan(r, &qr, &chk) == RX_COG_OK && ladder_eq(&chk, &R.ladder1_rec), "ladder unchanged before promotion");
1043 R.bypass_attempts++;
1044 R.bypass_refused += promote(store, &a, cand2, SUBJ_AUTHORITY, weak) != RX_GEN_OK;
1045 CHECK(promote(store, &a, cand2, SUBJ_AUTHORITY, cap) == RX_GEN_OK, "promote the new evidence");
1046 CHECK(rx_route_load(r, store) == RX_COG_OK && rx_route_generation(r) == cand2, "router follows");
1047 R.gen2 = (uint32_t)cand2;
1048 CHECK(rx_route_plan(r, &qr, &R.ladder2_rec) == RX_COG_OK, "recognition ladder after damage");
1049 print_ladder("recognize, gen 2", &R.ladder2_rec);
1050 Workload after;
1051 workload_make(&after, 0xaf7e0001ull, REC_EVAL, 0);
1052 PassResult rep, rbase;
1053 uint64_t best_r = UINT64_MAX, best_b = UINT64_MAX, e_r = 0, e_b = 0;
1054 for (int p = 0; p < 3; p++) {
1055 run_pass(r, &after, 1, &rep);
1056 run_pass(r, &after, 0, &rbase);
1057 if (rep.cpu_ns < best_r) best_r = rep.cpu_ns, e_r = rep.cpu_uj;
1058 if (rbase.cpu_ns < best_b) best_b = rbase.cpu_ns, e_b = rbase.cpu_uj;
1059 }
1060 R.repaired_rec_correct = rep.rec_correct;
1061 R.repaired_base_correct = rbase.rec_correct;
1062 R.repaired_n = REC_EVAL;
1063 R.repaired_cpu_ns = best_r, R.damaged_base_cpu_ns = best_b, R.repaired_cpu_uj = e_r, R.damaged_base_cpu_uj = e_b;
1064 printf("[*] after promotion: routed recognition %.4f (most expensive %.4f), cpu %.1f vs %.1f ms\n",
1065 (double)rep.rec_correct / REC_EVAL, (double)rbase.rec_correct / REC_EVAL, best_r / 1e6, best_b / 1e6);
1066 CHECK((double)rep.rec_correct / REC_EVAL >= qr.minimum_quality_ppm / 1e6, "quality restored after promotion");
1067 CHECK(best_r < best_b, "still cheaper than the most expensive after learning");
1068 cog_restore_neural();
1069
1070 /* 5b. model integrity */
1071 t_model_integrity(&a, cap, &calib);
1072 t_failure(&a, cap);
1073
1074 rx_route_ledger_destroy(l1);
1075 rx_route_ledger_destroy(l2);
1076 workload_free(&calib);
1077 workload_free(&calib2);
1078 workload_free(&eval);
1079 workload_free(&audit);
1080 workload_free(&after);
1081 rx_route_destroy(r);
1082 rx_gen_close(store);
1083 aienos_cap_stop(a.admin, a.view);
1084 printf("checks %d failures %d\n", g_checks, g_fail);
1085 write_receipt();
1086 printf("OMEGA_COGNITIVE_ROUTING_PASS: %s\n", gate_pass() ? "PASS" : "FAIL");
1087 return gate_pass() ? 0 : 1;
1088}