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
omega-mv / src / runtime / rx_route.c
| 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_route.c -- Omega cognitive compute routing. See rx_route.h and |
| 19 | * spec/cognitive-routing.md. |
| 20 | */ |
| 21 | #include "rx_route.h" |
| 22 | |
| 23 | #include "omega_native.h" |
| 24 | #include "sha256.h" |
| 25 | |
| 26 | #include <math.h> |
| 27 | #include <stdlib.h> |
| 28 | #include <string.h> |
| 29 | #include <time.h> |
| 30 | |
| 31 | #define MODEL_MAGIC 0x4d52434fu /* "OCRM" */ |
| 32 | #define MODEL_VERSION 1u |
| 33 | #define MODEL_MAX 65536u |
| 34 | #define PLAN_CACHE 512u |
| 35 | #define PLAN_PROBES 4u |
| 36 | #define NS_KEEP 4096u |
| 37 | |
| 38 | typedef struct { |
| 39 | RxCogDeclaration decl; |
| 40 | RxCogEngineFn fn; |
| 41 | void *ctx; |
| 42 | uint32_t reference_ops; |
| 43 | } Engine; |
| 44 | |
| 45 | /* Evidence sample for one operation: every record holds, for each engine in |
| 46 | * eng[], one byte: confidence bin (low 4 bits) and correct (bit 7). */ |
| 47 | typedef struct { |
| 48 | uint32_t n_records; |
| 49 | uint32_t n_eng; |
| 50 | uint32_t eng[RX_COG_MAX_ENGINES]; /* engine indices */ |
| 51 | uint8_t *rec; |
| 52 | } Sample; |
| 53 | |
| 54 | typedef struct { |
| 55 | int used; |
| 56 | uint64_t stamp; |
| 57 | uint64_t generation; |
| 58 | RxCogRequirement req; |
| 59 | int rc; |
| 60 | RxCogLadder ladder; |
| 61 | } PlanEntry; |
| 62 | |
| 63 | struct RxCogRouter { |
| 64 | Engine eng[RX_COG_MAX_ENGINES]; |
| 65 | uint32_t n; |
| 66 | int sealed; |
| 67 | uint64_t generation; |
| 68 | int have_profile; |
| 69 | RxCogRealization real[RX_COG_MAX_ENGINES]; |
| 70 | Sample sample[RX_COG_OP_COUNT]; |
| 71 | PlanEntry cache[PLAN_CACHE]; |
| 72 | uint32_t cache_next; |
| 73 | }; |
| 74 | |
| 75 | /* ---- small helpers ---- */ |
| 76 | |
| 77 | static uint32_t conf_bin(uint32_t conf) { |
| 78 | uint64_t res = 0; |
| 79 | (void)omega2_rx_rt_conf_bin(&res, (uint64_t)conf, (uint64_t)RX_COG_CONF_ONE, (uint64_t)RX_COG_BINS); |
| 80 | return (uint32_t)res; |
| 81 | } |
| 82 | |
| 83 | static uint64_t mono_ns(void) { |
| 84 | struct timespec ts; |
| 85 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 86 | return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; |
| 87 | } |
| 88 | |
| 89 | /* Wilson score interval at 95%, executed in pure OM-2 (om/runtime/rx_route_core.om). */ |
| 90 | static double wilson_lower(uint64_t k, uint64_t n) { |
| 91 | uint64_t dst[2] = { 0 }, res = 0; |
| 92 | double lo = 0.0; |
| 93 | (void)omega2_rx_rt_wilson(&res, k, n, dst, 2); |
| 94 | memcpy(&lo, &dst[0], sizeof(double)); |
| 95 | return lo; |
| 96 | } |
| 97 | |
| 98 | static double wilson_upper(uint64_t k, uint64_t n) { |
| 99 | uint64_t dst[2] = { 0 }, res = 0; |
| 100 | double hi = 1.0; |
| 101 | (void)omega2_rx_rt_wilson(&res, k, n, dst, 2); |
| 102 | memcpy(&hi, &dst[1], sizeof(double)); |
| 103 | return hi; |
| 104 | } |
| 105 | |
| 106 | static int index_of(const RxCogRouter *r, uint32_t id) { |
| 107 | for (uint32_t i = 0; i < r->n; i++) |
| 108 | if (r->eng[i].decl.cognitive_engine_id == id) return (int)i; |
| 109 | return -1; |
| 110 | } |
| 111 | |
| 112 | static void put32(uint8_t **p, uint32_t v) { |
| 113 | for (int i = 0; i < 4; i++) *(*p)++ = (uint8_t)(v >> (8 * i)); |
| 114 | } |
| 115 | static void put64(uint8_t **p, uint64_t v) { |
| 116 | for (int i = 0; i < 8; i++) *(*p)++ = (uint8_t)(v >> (8 * i)); |
| 117 | } |
| 118 | |
| 119 | typedef struct { |
| 120 | const uint8_t *p, *end; |
| 121 | int bad; |
| 122 | } Reader; |
| 123 | |
| 124 | static uint32_t get32(Reader *r) { |
| 125 | if (r->end - r->p < 4) { |
| 126 | r->bad = 1; |
| 127 | return 0; |
| 128 | } |
| 129 | uint32_t v = 0; |
| 130 | for (int i = 0; i < 4; i++) v |= (uint32_t)r->p[i] << (8 * i); |
| 131 | r->p += 4; |
| 132 | return v; |
| 133 | } |
| 134 | static uint64_t get64(Reader *r) { |
| 135 | uint64_t lo = get32(r), hi = get32(r); |
| 136 | return lo | hi << 32; |
| 137 | } |
| 138 | |
| 139 | static void decl_bytes(const RxCogDeclaration *d, uint8_t out[36]) { |
| 140 | uint8_t *p = out; |
| 141 | put32(&p, d->cognitive_engine_id); |
| 142 | put32(&p, d->realization_class); |
| 143 | put32(&p, d->supported_operations); |
| 144 | put32(&p, d->hardware_requirements); |
| 145 | put64(&p, d->memory_capacity); |
| 146 | put32(&p, d->temporal_horizon); |
| 147 | put32(&p, d->max_planning_depth); |
| 148 | put32(&p, d->precision | d->verifiable << 16); |
| 149 | } |
| 150 | |
| 151 | static void registry_digest(const Engine *eng, uint32_t n, uint8_t out[32]) { |
| 152 | sha256_ctx c; |
| 153 | sha256_init(&c); |
| 154 | uint8_t b[36]; |
| 155 | for (uint32_t i = 0; i < n; i++) { |
| 156 | decl_bytes(&eng[i].decl, b); |
| 157 | sha256_update(&c, b, sizeof b); |
| 158 | uint8_t ref[4] = {(uint8_t)eng[i].reference_ops, 0, 0, 0}; |
| 159 | sha256_update(&c, ref, 4); |
| 160 | } |
| 161 | sha256_final(&c, out); |
| 162 | } |
| 163 | |
| 164 | /* ---- router ---- */ |
| 165 | |
| 166 | int rx_route_create(RxCogRouter **out) { |
| 167 | if (!out) return RX_COG_ERR_ARG; |
| 168 | *out = calloc(1, sizeof(RxCogRouter)); |
| 169 | return *out ? RX_COG_OK : RX_COG_ERR_FULL; |
| 170 | } |
| 171 | |
| 172 | static void drop_profile(RxCogRouter *r) { |
| 173 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) { |
| 174 | free(r->sample[o].rec); |
| 175 | memset(&r->sample[o], 0, sizeof r->sample[o]); |
| 176 | } |
| 177 | for (uint32_t i = 0; i < r->n; i++) { |
| 178 | memset(&r->real[i], 0, sizeof r->real[i]); |
| 179 | r->real[i].cognitive_engine_id = r->eng[i].decl.cognitive_engine_id; |
| 180 | r->real[i].decl = r->eng[i].decl; |
| 181 | } |
| 182 | r->have_profile = 0; |
| 183 | } |
| 184 | |
| 185 | void rx_route_destroy(RxCogRouter *r) { |
| 186 | if (!r) return; |
| 187 | drop_profile(r); |
| 188 | free(r); |
| 189 | } |
| 190 | |
| 191 | int rx_route_register(RxCogRouter *r, const RxCogDeclaration *decl, RxCogEngineFn fn, void *ctx, |
| 192 | uint32_t reference_ops) { |
| 193 | if (!r || !decl || !fn || r->sealed) return RX_COG_ERR_ARG; |
| 194 | if (r->n >= RX_COG_MAX_ENGINES) return RX_COG_ERR_FULL; |
| 195 | if (index_of(r, decl->cognitive_engine_id) >= 0) return RX_COG_ERR_ARG; |
| 196 | uint32_t all_ops = (1u << RX_COG_OP_COUNT) - 1; |
| 197 | if (!decl->supported_operations || (decl->supported_operations & ~all_ops)) return RX_COG_ERR_ARG; |
| 198 | if ((reference_ops & ~decl->supported_operations) != 0) return RX_COG_ERR_ARG; |
| 199 | for (uint32_t i = 0; i < r->n; i++) |
| 200 | if (r->eng[i].reference_ops & reference_ops) return RX_COG_ERR_ARG; |
| 201 | Engine *e = &r->eng[r->n]; |
| 202 | e->decl = *decl; |
| 203 | e->fn = fn; |
| 204 | e->ctx = ctx; |
| 205 | e->reference_ops = reference_ops; |
| 206 | r->real[r->n].cognitive_engine_id = decl->cognitive_engine_id; |
| 207 | r->real[r->n].decl = *decl; |
| 208 | r->n++; |
| 209 | return RX_COG_OK; |
| 210 | } |
| 211 | |
| 212 | void rx_route_registry_digest(const RxCogRouter *r, uint8_t out[32]) { |
| 213 | registry_digest(r->eng, r->n, out); |
| 214 | } |
| 215 | |
| 216 | uint64_t rx_route_generation(const RxCogRouter *r) { return r ? r->generation : 0; } |
| 217 | |
| 218 | int rx_route_realization(const RxCogRouter *r, uint32_t engine_id, RxCogRealization *out) { |
| 219 | if (!r || !out) return RX_COG_ERR_ARG; |
| 220 | int i = index_of(r, engine_id); |
| 221 | if (i < 0) return RX_COG_ERR_ARG; |
| 222 | *out = r->real[i]; |
| 223 | return RX_COG_OK; |
| 224 | } |
| 225 | |
| 226 | /* Model layout (little endian): |
| 227 | * magic, version, registry digest[32], n engines |
| 228 | * per engine: id, then per op: quality (3 x u32), calibration (2 x 16 x u32), |
| 229 | * cost (calls, mean, p99, nj: u64; measured: u32) |
| 230 | * per op: n_records, n_eng, engine ids[n_eng], records[n_records * n_eng] |
| 231 | * An empty model means "no evidence". */ |
| 232 | static int parse_model(RxCogRouter *r, uint64_t gen, const uint8_t *buf, size_t len) { |
| 233 | RxCogRealization real[RX_COG_MAX_ENGINES]; |
| 234 | Sample sample[RX_COG_OP_COUNT]; |
| 235 | memset(real, 0, sizeof real); |
| 236 | memset(sample, 0, sizeof sample); |
| 237 | Reader rd = {buf, buf + len, 0}; |
| 238 | if (get32(&rd) != MODEL_MAGIC || get32(&rd) != MODEL_VERSION) return RX_COG_ERR_MODEL; |
| 239 | uint8_t want[32]; |
| 240 | registry_digest(r->eng, r->n, want); |
| 241 | if (rd.end - rd.p < 32 || memcmp(rd.p, want, 32) != 0) return RX_COG_ERR_MODEL; |
| 242 | rd.p += 32; |
| 243 | if (get32(&rd) != r->n) return RX_COG_ERR_MODEL; |
| 244 | for (uint32_t i = 0; i < r->n; i++) { |
| 245 | RxCogRealization *x = &real[i]; |
| 246 | x->cognitive_engine_id = get32(&rd); |
| 247 | if (x->cognitive_engine_id != r->eng[i].decl.cognitive_engine_id) return RX_COG_ERR_MODEL; |
| 248 | x->decl = r->eng[i].decl; |
| 249 | x->generation = gen; |
| 250 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) { |
| 251 | x->quality_profile[o].observations = get32(&rd); |
| 252 | x->quality_profile[o].correct = get32(&rd); |
| 253 | x->quality_profile[o].failures = get32(&rd); |
| 254 | for (uint32_t b = 0; b < RX_COG_BINS; b++) x->uncertainty_profile[o].n[b] = get32(&rd); |
| 255 | for (uint32_t b = 0; b < RX_COG_BINS; b++) x->uncertainty_profile[o].correct[b] = get32(&rd); |
| 256 | x->resource_cost_model[o].calls = get64(&rd); |
| 257 | x->resource_cost_model[o].mean_ns = get64(&rd); |
| 258 | x->resource_cost_model[o].p99_ns = get64(&rd); |
| 259 | x->resource_cost_model[o].nj_per_call = get64(&rd); |
| 260 | x->resource_cost_model[o].energy_measured = get32(&rd); |
| 261 | if (x->quality_profile[o].correct > x->quality_profile[o].observations) rd.bad = 1; |
| 262 | if (!(x->decl.supported_operations >> o & 1) && x->quality_profile[o].observations) rd.bad = 1; |
| 263 | } |
| 264 | } |
| 265 | const uint8_t *sample_start = rd.p; |
| 266 | int rc = RX_COG_ERR_MODEL; |
| 267 | for (uint32_t o = 0; o < RX_COG_OP_COUNT && !rd.bad; o++) { |
| 268 | Sample *s = &sample[o]; |
| 269 | s->n_records = get32(&rd); |
| 270 | s->n_eng = get32(&rd); |
| 271 | if (s->n_records > RX_COG_MAX_SAMPLE || s->n_eng > r->n) goto out; |
| 272 | for (uint32_t k = 0; k < s->n_eng; k++) { |
| 273 | int ix = index_of(r, get32(&rd)); |
| 274 | if (ix < 0 || !(r->eng[ix].decl.supported_operations >> o & 1)) goto out; |
| 275 | for (uint32_t j = 0; j < k; j++) |
| 276 | if (s->eng[j] == (uint32_t)ix) goto out; |
| 277 | s->eng[k] = (uint32_t)ix; |
| 278 | } |
| 279 | size_t bytes = (size_t)s->n_records * s->n_eng; |
| 280 | if (rd.bad || (size_t)(rd.end - rd.p) < bytes) goto out; |
| 281 | if (bytes) { |
| 282 | s->rec = malloc(bytes); |
| 283 | if (!s->rec) goto out; |
| 284 | memcpy(s->rec, rd.p, bytes); |
| 285 | for (size_t k = 0; k < bytes; k++) |
| 286 | if (s->rec[k] & 0x70) goto out; |
| 287 | } |
| 288 | rd.p += bytes; |
| 289 | } |
| 290 | if (rd.bad || rd.p != rd.end) goto out; |
| 291 | uint8_t ev[32]; |
| 292 | sha256_hash(sample_start, (size_t)(rd.end - sample_start), ev); |
| 293 | drop_profile(r); |
| 294 | for (uint32_t i = 0; i < r->n; i++) { |
| 295 | memcpy(real[i].evidence, ev, 32); |
| 296 | r->real[i] = real[i]; |
| 297 | } |
| 298 | memcpy(r->sample, sample, sizeof sample); |
| 299 | r->have_profile = 1; |
| 300 | return RX_COG_OK; |
| 301 | out: |
| 302 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) free(sample[o].rec); |
| 303 | return rc; |
| 304 | } |
| 305 | |
| 306 | int rx_route_load(RxCogRouter *r, const RxGenStore *store) { |
| 307 | if (!r || !store) return RX_COG_ERR_ARG; |
| 308 | r->sealed = 1; |
| 309 | uint64_t id = 0, lineage = 0; |
| 310 | if (rx_gen_active(store, &id, &lineage) != RX_GEN_OK) return RX_COG_ERR_MODEL; |
| 311 | if (id == 0) { |
| 312 | drop_profile(r); |
| 313 | r->generation = 0; |
| 314 | memset(r->cache, 0, sizeof r->cache); |
| 315 | return RX_COG_OK; |
| 316 | } |
| 317 | uint8_t *buf = malloc(MODEL_MAX); |
| 318 | if (!buf) return RX_COG_ERR_FULL; |
| 319 | size_t len = 0; |
| 320 | int grc = rx_gen_read_blob(store, id, "model", buf, MODEL_MAX, &len); |
| 321 | int rc; |
| 322 | if (grc != RX_GEN_OK) { |
| 323 | rc = RX_COG_ERR_MODEL; |
| 324 | } else if (len == 0) { |
| 325 | drop_profile(r); |
| 326 | rc = RX_COG_OK; |
| 327 | } else { |
| 328 | rc = parse_model(r, id, buf, len); |
| 329 | } |
| 330 | free(buf); |
| 331 | if (rc == RX_COG_OK) { |
| 332 | r->generation = id; |
| 333 | for (uint32_t i = 0; i < r->n; i++) r->real[i].generation = id; |
| 334 | memset(r->cache, 0, sizeof r->cache); |
| 335 | } |
| 336 | return rc; |
| 337 | } |
| 338 | |
| 339 | /* ---- choosing ---- */ |
| 340 | |
| 341 | static int eligible(const RxCogDeclaration *d, const RxCogRequirement *q) { |
| 342 | if (!(d->supported_operations >> q->operation_class & 1)) return 0; |
| 343 | if (d->hardware_requirements & ~q->hardware_constraints) return 0; |
| 344 | if (d->memory_capacity < q->memory_requirement) return 0; |
| 345 | if (d->temporal_horizon < q->temporal_requirement) return 0; |
| 346 | if (d->max_planning_depth < q->planning_depth) return 0; |
| 347 | if (q->precision_requirement == RX_COG_PREC_EXACT && d->precision != RX_COG_PREC_EXACT) return 0; |
| 348 | return 1; |
| 349 | } |
| 350 | |
| 351 | static int sample_slot(const Sample *s, uint32_t ix) { |
| 352 | for (uint32_t k = 0; k < s->n_eng; k++) |
| 353 | if (s->eng[k] == ix) return (int)k; |
| 354 | return -1; |
| 355 | } |
| 356 | |
| 357 | /* Smallest bin from which answers may be accepted: the pooled answers at |
| 358 | * and above it have a 95% upper error bound within the budget. RX_COG_BINS |
| 359 | * when no bin qualifies. |
| 360 | * |
| 361 | * A verifiable engine's checked answer (top bin) is accepted on the check, |
| 362 | * not on statistics: a sound check has no error to bound. The evidence can |
| 363 | * still refute the claim: one checked answer observed wrong, or none observed |
| 364 | * at all, and the engine's answers are never accepted early. */ |
| 365 | static uint32_t accept_bin(const RxCogDeclaration *d, const RxCogCalibration *c, uint32_t budget_ppm) { |
| 366 | if (d->verifiable) { |
| 367 | uint32_t top = RX_COG_BINS - 1; |
| 368 | return c->n[top] && c->correct[top] == c->n[top] ? top : RX_COG_BINS; |
| 369 | } |
| 370 | uint64_t n = 0, k = 0; |
| 371 | uint32_t best = RX_COG_BINS; |
| 372 | double budget = (double)budget_ppm / 1e6; |
| 373 | for (int b = (int)RX_COG_BINS - 1; b >= 0; b--) { |
| 374 | n += c->n[b]; |
| 375 | k += c->correct[b]; |
| 376 | if (n && wilson_upper(n - k, n) <= budget) best = (uint32_t)b; |
| 377 | } |
| 378 | return best; |
| 379 | } |
| 380 | |
| 381 | static int use_energy(const RxCogRouter *r, const uint32_t *ix, uint32_t n, uint32_t op) { |
| 382 | for (uint32_t i = 0; i < n; i++) |
| 383 | if (!r->real[ix[i]].resource_cost_model[op].energy_measured) return 0; |
| 384 | return 1; |
| 385 | } |
| 386 | |
| 387 | /* Ladder over engine indices ix[0..n) (cost order), evaluated on the evidence sample. */ |
| 388 | static void evaluate(const RxCogRouter *r, const RxCogRequirement *q, const uint32_t *ix, |
| 389 | uint32_t n, RxCogLadder *out) { |
| 390 | uint32_t op = q->operation_class; |
| 391 | const Sample *s = &r->sample[op]; |
| 392 | int slot[RX_COG_MAX_LADDER]; |
| 393 | memset(out, 0, sizeof *out); |
| 394 | out->n = n; |
| 395 | for (uint32_t i = 0; i < n; i++) { |
| 396 | out->engine[i] = r->eng[ix[i]].decl.cognitive_engine_id; |
| 397 | out->accept_min_bin[i] = accept_bin(&r->eng[ix[i]].decl, &r->real[ix[i]].uncertainty_profile[op], |
| 398 | q->uncertainty_budget_ppm); |
| 399 | slot[i] = sample_slot(s, ix[i]); |
| 400 | } |
| 401 | uint64_t correct = 0; |
| 402 | double ns = 0, nj = 0; |
| 403 | for (uint32_t k = 0; k < s->n_records; k++) { |
| 404 | const uint8_t *rec = s->rec + (size_t)k * s->n_eng; |
| 405 | for (uint32_t i = 0; i < n; i++) { |
| 406 | const RxCogCost *c = &r->real[ix[i]].resource_cost_model[op]; |
| 407 | ns += (double)c->mean_ns; |
| 408 | nj += (double)c->nj_per_call; |
| 409 | uint8_t v = rec[slot[i]]; |
| 410 | if (i + 1 == n || (uint32_t)(v & 0x0f) >= out->accept_min_bin[i]) { |
| 411 | correct += v >> 7; |
| 412 | break; |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | uint64_t m = s->n_records ? s->n_records : 1; |
| 417 | out->expected_ns = (uint64_t)(ns / (double)m); |
| 418 | out->expected_nj = use_energy(r, ix, n, op) ? (uint64_t)(nj / (double)m) : 0; |
| 419 | out->expected_quality_ppm = (uint32_t)(1e6 * (double)correct / (double)m); |
| 420 | out->quality_lower_ppm = (uint32_t)(1e6 * wilson_lower(correct, s->n_records)); |
| 421 | out->reason = RX_COG_WHY_EVIDENCE; |
| 422 | } |
| 423 | |
| 424 | static double ladder_cost(const RxCogLadder *l) { |
| 425 | return l->expected_nj ? (double)l->expected_nj : (double)l->expected_ns * 1e-3; |
| 426 | } |
| 427 | |
| 428 | static int engine_cost_less(const RxCogRouter *r, uint32_t op, uint32_t a, uint32_t b) { |
| 429 | const RxCogCost *x = &r->real[a].resource_cost_model[op], *y = &r->real[b].resource_cost_model[op]; |
| 430 | if (x->energy_measured && y->energy_measured && x->nj_per_call != y->nj_per_call) |
| 431 | return x->nj_per_call < y->nj_per_call; |
| 432 | return x->mean_ns < y->mean_ns; |
| 433 | } |
| 434 | |
| 435 | /* Eligible engines with enough evidence for the operation, cheapest first. */ |
| 436 | static uint32_t candidates(const RxCogRouter *r, const RxCogRequirement *q, uint32_t *ix) { |
| 437 | uint32_t n = 0, op = q->operation_class; |
| 438 | if (!r->have_profile) return 0; |
| 439 | for (uint32_t i = 0; i < r->n; i++) { |
| 440 | if (!eligible(&r->eng[i].decl, q)) continue; |
| 441 | if (r->real[i].quality_profile[op].observations < RX_COG_MIN_EVIDENCE) continue; |
| 442 | if (!r->real[i].resource_cost_model[op].calls) continue; |
| 443 | if (sample_slot(&r->sample[op], i) < 0) continue; |
| 444 | ix[n++] = i; |
| 445 | } |
| 446 | for (uint32_t a = 1; a < n; a++) |
| 447 | for (uint32_t b = a; b > 0 && engine_cost_less(r, op, ix[b], ix[b - 1]); b--) { |
| 448 | uint32_t t = ix[b]; |
| 449 | ix[b] = ix[b - 1]; |
| 450 | ix[b - 1] = t; |
| 451 | } |
| 452 | return n; |
| 453 | } |
| 454 | |
| 455 | static int reference_ladder(const RxCogRouter *r, const RxCogRequirement *q, RxCogLadder *out) { |
| 456 | for (uint32_t i = 0; i < r->n; i++) |
| 457 | if ((r->eng[i].reference_ops >> q->operation_class & 1) && eligible(&r->eng[i].decl, q)) { |
| 458 | memset(out, 0, sizeof *out); |
| 459 | out->n = 1; |
| 460 | out->engine[0] = r->eng[i].decl.cognitive_engine_id; |
| 461 | out->accept_min_bin[0] = 0; |
| 462 | out->reason = RX_COG_WHY_NO_EVIDENCE; |
| 463 | return RX_COG_OK; |
| 464 | } |
| 465 | return RX_COG_ERR_UNSATISFIABLE; |
| 466 | } |
| 467 | |
| 468 | static RxCogRequirement normalize(const RxCogRequirement *q) { |
| 469 | RxCogRequirement z; |
| 470 | memset(&z, 0, sizeof z); |
| 471 | z.operation_class = q->operation_class; |
| 472 | z.minimum_quality_ppm = q->minimum_quality_ppm; |
| 473 | z.uncertainty_budget_ppm = q->uncertainty_budget_ppm; |
| 474 | z.memory_requirement = q->memory_requirement; |
| 475 | z.temporal_requirement = q->temporal_requirement; |
| 476 | z.planning_depth = q->planning_depth; |
| 477 | z.precision_requirement = q->precision_requirement; |
| 478 | z.latency_budget_ns = q->latency_budget_ns; |
| 479 | z.energy_budget_nj = q->energy_budget_nj; |
| 480 | z.hardware_constraints = q->hardware_constraints; |
| 481 | z.escalation_allowed = q->escalation_allowed; |
| 482 | return z; |
| 483 | } |
| 484 | |
| 485 | static int choose(const RxCogRouter *r, const RxCogRequirement *q, RxCogLadder *out) { |
| 486 | uint32_t ix[RX_COG_MAX_ENGINES]; |
| 487 | uint32_t n = candidates(r, q, ix); |
| 488 | if (n == 0) { |
| 489 | /* Without evidence only the reference may run, and only when the |
| 490 | * operation has no evidence at all: evidence that disqualifies every |
| 491 | * engine is a refusal, not a bootstrap. */ |
| 492 | if (r->have_profile && r->sample[q->operation_class].n_records) return RX_COG_ERR_UNSATISFIABLE; |
| 493 | return reference_ladder(r, q, out); |
| 494 | } |
| 495 | uint32_t max_len = q->escalation_allowed + 1; |
| 496 | if (max_len > RX_COG_MAX_LADDER) max_len = RX_COG_MAX_LADDER; |
| 497 | int found = 0; |
| 498 | RxCogLadder best, cur; |
| 499 | memset(&best, 0, sizeof best); |
| 500 | for (uint32_t mask = 1; mask < (1u << n); mask++) { |
| 501 | uint32_t pick[RX_COG_MAX_LADDER], len = 0; |
| 502 | if ((uint32_t)__builtin_popcount(mask) > max_len) continue; |
| 503 | for (uint32_t i = 0; i < n; i++) |
| 504 | if (mask >> i & 1) pick[len++] = ix[i]; |
| 505 | evaluate(r, q, pick, len, &cur); |
| 506 | if (cur.quality_lower_ppm < q->minimum_quality_ppm) continue; |
| 507 | if (q->latency_budget_ns && cur.expected_ns > q->latency_budget_ns) continue; |
| 508 | if (q->energy_budget_nj && cur.expected_nj > q->energy_budget_nj) continue; |
| 509 | if (q->energy_budget_nj && !cur.expected_nj) continue; /* budget cannot be checked */ |
| 510 | if (!found || ladder_cost(&cur) < ladder_cost(&best) || |
| 511 | (ladder_cost(&cur) == ladder_cost(&best) && cur.n < best.n)) { |
| 512 | best = cur; |
| 513 | found = 1; |
| 514 | } |
| 515 | } |
| 516 | if (!found) return RX_COG_ERR_UNSATISFIABLE; |
| 517 | *out = best; |
| 518 | return RX_COG_OK; |
| 519 | } |
| 520 | |
| 521 | /* The ladder for a requirement is fixed for a generation, so it is cached: |
| 522 | * direct-mapped on a hash of the requirement with a few probes; the oldest |
| 523 | * probed entry is replaced. */ |
| 524 | static uint32_t req_hash(const RxCogRequirement *q) { |
| 525 | const uint8_t *p = (const uint8_t *)q; |
| 526 | uint32_t h = 2166136261u; |
| 527 | for (size_t i = 0; i < sizeof *q; i++) h = (h ^ p[i]) * 16777619u; |
| 528 | return h; |
| 529 | } |
| 530 | |
| 531 | int rx_route_plan(RxCogRouter *r, const RxCogRequirement *req, RxCogLadder *out) { |
| 532 | if (!r || !req || !out || req->operation_class >= RX_COG_OP_COUNT) return RX_COG_ERR_ARG; |
| 533 | r->sealed = 1; |
| 534 | RxCogRequirement q = normalize(req); |
| 535 | uint32_t h = req_hash(&q); |
| 536 | PlanEntry *victim = NULL; |
| 537 | for (uint32_t k = 0; k < PLAN_PROBES; k++) { |
| 538 | PlanEntry *e = &r->cache[(h + k) % PLAN_CACHE]; |
| 539 | int live = e->used && e->generation == r->generation; |
| 540 | if (live && memcmp(&e->req, &q, sizeof q) == 0) { |
| 541 | *out = e->ladder; |
| 542 | return e->rc; |
| 543 | } |
| 544 | int victim_live = victim && victim->used && victim->generation == r->generation; |
| 545 | if (!victim || (victim_live && (!live || e->stamp < victim->stamp))) victim = e; |
| 546 | } |
| 547 | RxCogLadder l; |
| 548 | memset(&l, 0, sizeof l); |
| 549 | int rc = choose(r, &q, &l); |
| 550 | victim->used = 1; |
| 551 | victim->stamp = ++r->cache_next; |
| 552 | victim->generation = r->generation; |
| 553 | victim->req = q; |
| 554 | victim->rc = rc; |
| 555 | victim->ladder = l; |
| 556 | *out = l; |
| 557 | return rc; |
| 558 | } |
| 559 | |
| 560 | int rx_route_most_expensive(RxCogRouter *r, const RxCogRequirement *req, uint32_t *engine_id) { |
| 561 | if (!r || !req || !engine_id || req->operation_class >= RX_COG_OP_COUNT) return RX_COG_ERR_ARG; |
| 562 | RxCogRequirement q = normalize(req); |
| 563 | uint32_t ix[RX_COG_MAX_ENGINES]; |
| 564 | uint32_t n = candidates(r, &q, ix); |
| 565 | if (n == 0) { |
| 566 | RxCogLadder l; |
| 567 | int rc = reference_ladder(r, &q, &l); |
| 568 | if (rc == RX_COG_OK) *engine_id = l.engine[0]; |
| 569 | return rc; |
| 570 | } |
| 571 | *engine_id = r->eng[ix[n - 1]].decl.cognitive_engine_id; |
| 572 | return RX_COG_OK; |
| 573 | } |
| 574 | |
| 575 | int rx_route_run(RxCogRouter *r, const RxCogRequirement *req, const void *input, void *output, |
| 576 | size_t output_size, RxCogTrace *trace) { |
| 577 | if (!r || !req || !output || !output_size || !trace) return RX_COG_ERR_ARG; |
| 578 | memset(trace, 0, sizeof *trace); |
| 579 | RxCogLadder l; |
| 580 | int rc = rx_route_plan(r, req, &l); |
| 581 | if (rc != RX_COG_OK) return rc; |
| 582 | uint32_t op = req->operation_class; |
| 583 | int last_ok = 0; |
| 584 | /* The ladder is bounded before it runs: at most escalation_allowed + 1 |
| 585 | * rungs (and RX_COG_MAX_LADDER), and admitted only if its expected cost |
| 586 | * fits the latency and energy budgets. Nothing measured while it runs |
| 587 | * changes which rungs run; only the answers do. The times in the trace |
| 588 | * are observations. */ |
| 589 | for (uint32_t i = 0; i < l.n; i++) { |
| 590 | int ix = index_of(r, l.engine[i]); |
| 591 | uint32_t conf = 0; |
| 592 | uint64_t t0 = mono_ns(); |
| 593 | int erc = r->eng[ix].fn(r->eng[ix].ctx, op, input, output, &conf); |
| 594 | uint64_t dt = mono_ns() - t0; |
| 595 | trace->engine[i] = l.engine[i]; |
| 596 | trace->confidence[i] = erc ? 0 : conf; |
| 597 | trace->ns[i] = dt; |
| 598 | trace->rungs_run = i + 1; |
| 599 | trace->escalations = i; |
| 600 | trace->final_engine = l.engine[i]; |
| 601 | last_ok = erc == 0; |
| 602 | if (erc == 0 && conf_bin(conf) >= l.accept_min_bin[i]) { |
| 603 | trace->accepted = 1; |
| 604 | return RX_COG_OK; |
| 605 | } |
| 606 | } |
| 607 | return last_ok ? RX_COG_ERR_EXHAUSTED : RX_COG_ERR_ENGINE; |
| 608 | } |
| 609 | |
| 610 | /* ---- learning ---- */ |
| 611 | |
| 612 | typedef struct { |
| 613 | RxCogQuality q; |
| 614 | RxCogCalibration c; |
| 615 | uint64_t calls, sum_ns; |
| 616 | uint64_t *ns; |
| 617 | uint32_t n_ns; |
| 618 | uint64_t e_calls, e_nj; |
| 619 | uint64_t b_calls, b_ns; /* batch timing: mean cost without per-call clock reads */ |
| 620 | } Acc; |
| 621 | |
| 622 | struct RxCogLedger { |
| 623 | uint32_t n; |
| 624 | Engine eng[RX_COG_MAX_ENGINES]; |
| 625 | Acc acc[RX_COG_MAX_ENGINES][RX_COG_OP_COUNT]; |
| 626 | Sample sample[RX_COG_OP_COUNT]; |
| 627 | }; |
| 628 | |
| 629 | int rx_route_ledger_create(const RxCogRouter *r, RxCogLedger **out) { |
| 630 | if (!r || !out) return RX_COG_ERR_ARG; |
| 631 | RxCogLedger *l = calloc(1, sizeof *l); |
| 632 | if (!l) return RX_COG_ERR_FULL; |
| 633 | l->n = r->n; |
| 634 | memcpy(l->eng, r->eng, sizeof l->eng); |
| 635 | *out = l; |
| 636 | return RX_COG_OK; |
| 637 | } |
| 638 | |
| 639 | void rx_route_ledger_destroy(RxCogLedger *l) { |
| 640 | if (!l) return; |
| 641 | for (uint32_t i = 0; i < RX_COG_MAX_ENGINES; i++) |
| 642 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) free(l->acc[i][o].ns); |
| 643 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) free(l->sample[o].rec); |
| 644 | free(l); |
| 645 | } |
| 646 | |
| 647 | static int ledger_index(const RxCogLedger *l, uint32_t id) { |
| 648 | for (uint32_t i = 0; i < l->n; i++) |
| 649 | if (l->eng[i].decl.cognitive_engine_id == id) return (int)i; |
| 650 | return -1; |
| 651 | } |
| 652 | |
| 653 | int rx_route_observe(RxCogLedger *l, uint32_t op, uint32_t n, const uint32_t *engines, |
| 654 | const uint32_t *conf, const uint8_t *correct, const uint64_t *ns, |
| 655 | const uint8_t *failed) { |
| 656 | if (!l || op >= RX_COG_OP_COUNT || !n || n > l->n || !engines || !conf || !correct || !ns || |
| 657 | !failed) |
| 658 | return RX_COG_ERR_ARG; |
| 659 | int ix[RX_COG_MAX_ENGINES]; |
| 660 | for (uint32_t k = 0; k < n; k++) { |
| 661 | ix[k] = ledger_index(l, engines[k]); |
| 662 | if (ix[k] < 0 || !(l->eng[ix[k]].decl.supported_operations >> op & 1)) return RX_COG_ERR_ARG; |
| 663 | for (uint32_t j = 0; j < k; j++) |
| 664 | if (ix[j] == ix[k]) return RX_COG_ERR_ARG; |
| 665 | } |
| 666 | Sample *s = &l->sample[op]; |
| 667 | if (s->n_eng == 0) { |
| 668 | s->n_eng = n; |
| 669 | for (uint32_t k = 0; k < n; k++) s->eng[k] = (uint32_t)ix[k]; |
| 670 | s->rec = malloc((size_t)RX_COG_MAX_SAMPLE * n); |
| 671 | if (!s->rec) { |
| 672 | s->n_eng = 0; |
| 673 | return RX_COG_ERR_FULL; |
| 674 | } |
| 675 | } else { |
| 676 | if (s->n_eng != n) return RX_COG_ERR_ARG; |
| 677 | for (uint32_t k = 0; k < n; k++) |
| 678 | if (s->eng[k] != (uint32_t)ix[k]) return RX_COG_ERR_ARG; |
| 679 | } |
| 680 | for (uint32_t k = 0; k < n; k++) { |
| 681 | Acc *a = &l->acc[ix[k]][op]; |
| 682 | uint32_t c = failed[k] ? 0 : conf[k]; |
| 683 | int ok = !failed[k] && correct[k]; |
| 684 | uint32_t b = conf_bin(c); |
| 685 | a->q.observations++; |
| 686 | a->q.correct += (uint32_t)ok; |
| 687 | a->q.failures += failed[k] ? 1u : 0u; |
| 688 | a->c.n[b]++; |
| 689 | a->c.correct[b] += (uint32_t)ok; |
| 690 | a->calls++; |
| 691 | a->sum_ns += ns[k]; |
| 692 | if (!a->ns) a->ns = malloc(NS_KEEP * sizeof(uint64_t)); |
| 693 | if (a->ns && a->n_ns < NS_KEEP) a->ns[a->n_ns++] = ns[k]; |
| 694 | } |
| 695 | if (s->n_records < RX_COG_MAX_SAMPLE) { |
| 696 | uint8_t *rec = s->rec + (size_t)s->n_records * n; |
| 697 | for (uint32_t k = 0; k < n; k++) { |
| 698 | int ok = !failed[k] && correct[k]; |
| 699 | rec[k] = (uint8_t)(conf_bin(failed[k] ? 0 : conf[k]) | (ok ? 0x80 : 0)); |
| 700 | } |
| 701 | s->n_records++; |
| 702 | } |
| 703 | return RX_COG_OK; |
| 704 | } |
| 705 | |
| 706 | int rx_route_observe_batch(RxCogLedger *l, uint32_t engine_id, uint32_t op, uint64_t calls, |
| 707 | uint64_t cpu_ns, int energy_measured, uint64_t nj) { |
| 708 | if (!l || op >= RX_COG_OP_COUNT || !calls) return RX_COG_ERR_ARG; |
| 709 | int i = ledger_index(l, engine_id); |
| 710 | if (i < 0 || !(l->eng[i].decl.supported_operations >> op & 1)) return RX_COG_ERR_ARG; |
| 711 | Acc *a = &l->acc[i][op]; |
| 712 | a->b_calls += calls; |
| 713 | a->b_ns += cpu_ns; |
| 714 | if (energy_measured) { |
| 715 | a->e_calls += calls; |
| 716 | a->e_nj += nj; |
| 717 | } |
| 718 | return RX_COG_OK; |
| 719 | } |
| 720 | |
| 721 | static int cmp_u64(const void *a, const void *b) { |
| 722 | uint64_t x = *(const uint64_t *)a, y = *(const uint64_t *)b; |
| 723 | return x < y ? -1 : x > y; |
| 724 | } |
| 725 | |
| 726 | int rx_route_ledger_model(const RxCogLedger *l, uint8_t **out, size_t *out_len) { |
| 727 | if (!l || !out || !out_len) return RX_COG_ERR_ARG; |
| 728 | size_t cap = 48 + (size_t)l->n * (4 + RX_COG_OP_COUNT * (12 + 128 + 36)); |
| 729 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) |
| 730 | cap += 8 + 4 * l->sample[o].n_eng + (size_t)l->sample[o].n_records * l->sample[o].n_eng; |
| 731 | if (cap > MODEL_MAX) return RX_COG_ERR_FULL; |
| 732 | uint8_t *buf = malloc(cap), *p = buf; |
| 733 | if (!buf) return RX_COG_ERR_FULL; |
| 734 | put32(&p, MODEL_MAGIC); |
| 735 | put32(&p, MODEL_VERSION); |
| 736 | registry_digest(l->eng, l->n, p); |
| 737 | p += 32; |
| 738 | put32(&p, l->n); |
| 739 | for (uint32_t i = 0; i < l->n; i++) { |
| 740 | put32(&p, l->eng[i].decl.cognitive_engine_id); |
| 741 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) { |
| 742 | const Acc *a = &l->acc[i][o]; |
| 743 | put32(&p, a->q.observations); |
| 744 | put32(&p, a->q.correct); |
| 745 | put32(&p, a->q.failures); |
| 746 | for (uint32_t b = 0; b < RX_COG_BINS; b++) put32(&p, a->c.n[b]); |
| 747 | for (uint32_t b = 0; b < RX_COG_BINS; b++) put32(&p, a->c.correct[b]); |
| 748 | uint64_t p99 = 0; |
| 749 | if (a->n_ns) { |
| 750 | uint64_t *tmp = malloc(a->n_ns * sizeof(uint64_t)); |
| 751 | if (!tmp) { |
| 752 | free(buf); |
| 753 | return RX_COG_ERR_FULL; |
| 754 | } |
| 755 | memcpy(tmp, a->ns, a->n_ns * sizeof(uint64_t)); |
| 756 | qsort(tmp, a->n_ns, sizeof(uint64_t), cmp_u64); |
| 757 | p99 = tmp[(a->n_ns * 99) / 100 < a->n_ns ? (a->n_ns * 99) / 100 : a->n_ns - 1]; |
| 758 | free(tmp); |
| 759 | } |
| 760 | put64(&p, a->calls); |
| 761 | put64(&p, a->b_calls ? a->b_ns / a->b_calls : a->calls ? a->sum_ns / a->calls : 0); |
| 762 | put64(&p, p99); |
| 763 | put64(&p, a->e_calls ? a->e_nj / a->e_calls : 0); |
| 764 | put32(&p, a->e_calls ? 1u : 0u); |
| 765 | } |
| 766 | } |
| 767 | for (uint32_t o = 0; o < RX_COG_OP_COUNT; o++) { |
| 768 | const Sample *s = &l->sample[o]; |
| 769 | put32(&p, s->n_records); |
| 770 | put32(&p, s->n_eng); |
| 771 | for (uint32_t k = 0; k < s->n_eng; k++) put32(&p, l->eng[s->eng[k]].decl.cognitive_engine_id); |
| 772 | size_t bytes = (size_t)s->n_records * s->n_eng; |
| 773 | if (bytes) memcpy(p, s->rec, bytes); |
| 774 | p += bytes; |
| 775 | } |
| 776 | *out = buf; |
| 777 | *out_len = (size_t)(p - buf); |
| 778 | return RX_COG_OK; |
| 779 | } |
| 780 | |
| 781 | int rx_route_propose(const RxCogLedger *l, RxGenStore *store, uint32_t proposer, |
| 782 | uint64_t authority_epoch, uint64_t authority_generation, uint64_t *candidate) { |
| 783 | if (!l || !store || !candidate) return RX_COG_ERR_ARG; |
| 784 | uint8_t *model = NULL; |
| 785 | size_t model_len = 0; |
| 786 | int rc = rx_route_ledger_model(l, &model, &model_len); |
| 787 | if (rc != RX_COG_OK) return rc; |
| 788 | uint8_t reg[32]; |
| 789 | registry_digest(l->eng, l->n, reg); |
| 790 | static const uint8_t config[] = "rx_route model v1"; |
| 791 | uint8_t evidence[32]; |
| 792 | sha256_hash(model, model_len, evidence); |
| 793 | RxGenDraft d; |
| 794 | memset(&d, 0, sizeof d); |
| 795 | d.authority_epoch = authority_epoch; |
| 796 | d.authority_generation = authority_generation; |
| 797 | d.proofs_ok = 1; |
| 798 | d.evidence = evidence; |
| 799 | d.evidence_len = sizeof evidence; |
| 800 | d.model = model; |
| 801 | d.model_len = model_len; |
| 802 | d.realization = reg; |
| 803 | d.realization_len = sizeof reg; |
| 804 | d.config = config; |
| 805 | d.config_len = sizeof config - 1; |
| 806 | int grc = rx_gen_propose(store, proposer, &d, candidate); |
| 807 | free(model); |
| 808 | return grc == RX_GEN_OK ? RX_COG_OK : RX_COG_ERR_MODEL; |
| 809 | } |