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 / src / runtime / rx_semantic.c

964 lines · 36105 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_semantic.c -- Omega semantic variables and incremental recomputation.
19 * See rx_semantic.h for the model. Simple reference: one mutex, fixed tables.
20 */
21#include "rx_semantic.h"
22
23#include "omega_native.h"
24#include "sha256.h"
25
26#include <stdlib.h>
27#include <string.h>
28#include <time.h>
29
30#define NONE UINT32_MAX
31
32/* ---- hashing --------------------------------------------------------------- */
33
34static void h_u32(sha256_ctx *c, uint32_t v) {
35 uint8_t b[4];
36 for (int i = 0; i < 4; i++) b[i] = (uint8_t)(v >> (8 * i));
37 sha256_update(c, b, 4);
38}
39
40static void h_u64(sha256_ctx *c, uint64_t v) {
41 uint8_t b[8];
42 for (int i = 0; i < 8; i++) b[i] = (uint8_t)(v >> (8 * i));
43 sha256_update(c, b, 8);
44}
45
46static void h_dig(sha256_ctx *c, const RxSemDigest *d) { sha256_update(c, d->b, 32); }
47
48static void h_tag(sha256_ctx *c, const char *tag) {
49 sha256_update(c, (const uint8_t *)tag, strlen(tag) + 1);
50}
51
52bool rx_sem_digest_eq(const RxSemDigest *a, const RxSemDigest *b) {
53 uint64_t eq = 0;
54 (void)omega2_rx_sem_digest_eq_om2(&eq, a->b, 32, b->b, 32);
55 return eq != 0;
56}
57
58void rx_sem_digest_value(uint32_t type, const uint64_t *words, uint32_t n, RxSemDigest *out) {
59 sha256_ctx c;
60 sha256_init(&c);
61 h_tag(&c, "omega.sem.value.v1");
62 h_u32(&c, type);
63 h_u32(&c, n);
64 for (uint32_t i = 0; i < n; i++) h_u64(&c, words[i]);
65 sha256_final(&c, out->b);
66}
67
68void rx_sem_digest_impl(const char *text, RxSemDigest *out) {
69 sha256_hash((const uint8_t *)text, strlen(text), out->b);
70}
71
72static uint64_t now_ns(void) {
73 struct timespec ts;
74 clock_gettime(CLOCK_MONOTONIC, &ts);
75 return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
76}
77
78/* ---- lookup ---------------------------------------------------------------- */
79
80static uint32_t source_index(const RxSemEngine *e, uint64_t sid) {
81 for (uint32_t i = 0; i < e->n_sources; i++)
82 if (e->sources[i].used && e->sources[i].semantic_id == sid) return i;
83 return NONE;
84}
85
86static uint32_t node_index(const RxSemEngine *e, uint64_t sid) {
87 for (uint32_t i = 0; i < e->n_nodes; i++)
88 if (e->nodes[i].used && e->nodes[i].semantic_id == sid) return i;
89 return NONE;
90}
91
92static RxSemBranch *branch_of(RxSemEngine *e, uint32_t b) {
93 if (b >= RX_SEM_MAX_BRANCHES || !e->branches[b].live) return NULL;
94 return &e->branches[b];
95}
96
97/* ---- lifecycle ------------------------------------------------------------- */
98
99int rx_sem_init(RxSemEngine *e, uint64_t event_cap) {
100 if (!e || event_cap == 0) return RX_SEM_ERR_ARG;
101 memset(e, 0, sizeof *e);
102 if (pthread_mutex_init(&e->mu, NULL) != 0) return RX_SEM_ERR_ARG;
103 e->branches = calloc(RX_SEM_MAX_BRANCHES, sizeof *e->branches);
104 e->cache = calloc(RX_SEM_CACHE_SLOTS, sizeof *e->cache);
105 e->events = calloc(event_cap, sizeof *e->events);
106 if (!e->branches || !e->cache || !e->events) {
107 rx_sem_destroy(e);
108 return RX_SEM_ERR_FULL;
109 }
110 e->event_cap = event_cap;
111 e->grain = RX_SEM_GRAIN_FIELD;
112 e->cache_enabled = true;
113 return RX_SEM_OK;
114}
115
116void rx_sem_destroy(RxSemEngine *e) {
117 if (!e) return;
118 free(e->branches);
119 free(e->cache);
120 free(e->events);
121 e->branches = NULL;
122 e->cache = NULL;
123 e->events = NULL;
124 pthread_mutex_destroy(&e->mu);
125}
126
127void rx_sem_set_mode(RxSemEngine *e, uint32_t grain, bool cache_enabled, bool audit) {
128 pthread_mutex_lock(&e->mu);
129 e->grain = grain;
130 e->cache_enabled = cache_enabled;
131 e->audit = audit;
132 pthread_mutex_unlock(&e->mu);
133}
134
135/* ---- declarations ---------------------------------------------------------- */
136
137int rx_sem_add_fn(RxSemEngine *e, const RxSemFnDesc *d, uint32_t *out_fn) {
138 if (!e || !d || !d->fn || !d->name) return RX_SEM_ERR_ARG;
139 pthread_mutex_lock(&e->mu);
140 if (e->n_fns >= RX_SEM_MAX_FNS) {
141 pthread_mutex_unlock(&e->mu);
142 return RX_SEM_ERR_FULL;
143 }
144 uint32_t id = e->n_fns++;
145 e->fns[id] = *d;
146 sha256_ctx c;
147 sha256_init(&c);
148 h_tag(&c, "omega.sem.derivation.v1");
149 h_tag(&c, d->name);
150 h_u32(&c, d->out_type);
151 h_u32(&c, d->generation);
152 h_dig(&c, &d->impl_digest);
153 sha256_final(&c, e->fn_derivation[id].b);
154 if (out_fn) *out_fn = id;
155 pthread_mutex_unlock(&e->mu);
156 return RX_SEM_OK;
157}
158
159int rx_sem_add_source(RxSemEngine *e, RxObjRef obj, uint32_t field, uint32_t type,
160 bool world_bound, uint64_t *out_sid) {
161 if (!e || field >= RX_MAX_FIELDS || obj.id >= RX_MAX_OBJECTS) return RX_SEM_ERR_ARG;
162 uint64_t sid = RX_SEM_SOURCE_ID(obj.id, field);
163 pthread_mutex_lock(&e->mu);
164 int rc = RX_SEM_OK;
165 if (source_index(e, sid) != NONE) rc = RX_SEM_ERR_EXISTS;
166 else if (e->n_sources >= RX_SEM_MAX_SOURCES) rc = RX_SEM_ERR_FULL;
167 else {
168 RxSemSource *s = &e->sources[e->n_sources++];
169 memset(s, 0, sizeof *s);
170 s->used = true;
171 s->semantic_id = sid;
172 s->type = type;
173 s->world_bound = world_bound;
174 s->obj = obj;
175 s->field = field;
176 if (out_sid) *out_sid = sid;
177 }
178 pthread_mutex_unlock(&e->mu);
179 return rc;
180}
181
182static uint64_t node_id(const RxSemDigest *deriv, const uint64_t *inputs, uint32_t n) {
183 sha256_ctx c;
184 uint8_t d[32];
185 sha256_init(&c);
186 h_tag(&c, "omega.sem.node.v1");
187 h_dig(&c, deriv);
188 h_u32(&c, n);
189 for (uint32_t i = 0; i < n; i++) h_u64(&c, inputs[i]);
190 sha256_final(&c, d);
191 uint64_t id = 0;
192 (void)omega2_rx_sem_node_id_from_hash(&id, d, 32, (uint64_t)RX_SEM_KIND_DERIVED);
193 return id;
194}
195
196int rx_sem_add_node(RxSemEngine *e, uint32_t fn, const uint64_t *inputs, uint32_t n,
197 uint64_t *out_sid) {
198 if (!e || !inputs || n == 0 || n > RX_SEM_MAX_INPUTS) return RX_SEM_ERR_ARG;
199 pthread_mutex_lock(&e->mu);
200 int rc = RX_SEM_OK;
201 if (fn >= e->n_fns) { rc = RX_SEM_ERR_ARG; goto out; }
202 /* Inputs must already exist; that makes the graph acyclic by construction. */
203 for (uint32_t i = 0; i < n; i++) {
204 uint32_t k = RX_SEM_KIND(inputs[i]);
205 if ((k == RX_SEM_KIND_SOURCE && source_index(e, inputs[i]) == NONE) ||
206 (k == RX_SEM_KIND_DERIVED && node_index(e, inputs[i]) == NONE) ||
207 (k != RX_SEM_KIND_SOURCE && k != RX_SEM_KIND_DERIVED)) {
208 rc = RX_SEM_ERR_NOT_FOUND;
209 goto out;
210 }
211 }
212 uint64_t sid = node_id(&e->fn_derivation[fn], inputs, n);
213 uint32_t have = node_index(e, sid);
214 if (have != NONE) {
215 RxSemNode *h = &e->nodes[have];
216 bool same = h->function_id == fn && h->n_inputs == n &&
217 memcmp(h->inputs, inputs, n * sizeof *inputs) == 0;
218 if (!same) rc = RX_SEM_ERR_EXISTS; /* 56-bit id collision: refuse */
219 else if (out_sid) *out_sid = sid; /* same question: same node */
220 goto out;
221 }
222 if (e->n_nodes >= RX_SEM_MAX_NODES) { rc = RX_SEM_ERR_FULL; goto out; }
223 /* An input listed twice is refused: checked in pure OM-2. */
224 uint64_t uniq = 0;
225 (void)omega2_rx_sem_inputs_unique(&uniq, inputs, n, (uint64_t)n);
226 if (!uniq) { rc = RX_SEM_ERR_ARG; goto out; }
227 uint32_t idx = e->n_nodes++;
228 RxSemNode *nd = &e->nodes[idx];
229 memset(nd, 0, sizeof *nd);
230 nd->used = true;
231 nd->semantic_id = sid;
232 nd->function_id = fn;
233 nd->n_inputs = n;
234 memcpy(nd->inputs, inputs, n * sizeof *inputs);
235 for (uint32_t i = 0; i < n; i++) {
236 if (RX_SEM_KIND(inputs[i]) == RX_SEM_KIND_SOURCE) {
237 RxSemSource *s = &e->sources[source_index(e, inputs[i])];
238 s->readers[s->n_readers++] = idx;
239 } else {
240 RxSemNode *p = &e->nodes[node_index(e, inputs[i])];
241 p->readers[p->n_readers++] = idx;
242 }
243 }
244 if (out_sid) *out_sid = sid;
245out:
246 pthread_mutex_unlock(&e->mu);
247 return rc;
248}
249
250/* ---- branches -------------------------------------------------------------- */
251
252static int branch_alloc(RxSemEngine *e, uint32_t *out) {
253 for (uint32_t i = 0; i < RX_SEM_MAX_BRANCHES; i++) {
254 if (!e->branches[i].live) {
255 *out = i;
256 return RX_SEM_OK;
257 }
258 }
259 return RX_SEM_ERR_FULL;
260}
261
262int rx_sem_branch_root(RxSemEngine *e, uint32_t agent, uint64_t task, uint32_t *out) {
263 if (!e || !out) return RX_SEM_ERR_ARG;
264 pthread_mutex_lock(&e->mu);
265 uint32_t id;
266 int rc = branch_alloc(e, &id);
267 if (rc == RX_SEM_OK) {
268 RxSemBranch *b = &e->branches[id];
269 memset(b, 0, sizeof *b);
270 b->live = true;
271 b->id = id;
272 b->parent = NONE;
273 b->agent = agent;
274 b->task = task;
275 for (uint32_t i = 0; i < RX_SEM_MAX_NODES; i++) b->memo_entry[i] = NONE;
276 *out = id;
277 }
278 pthread_mutex_unlock(&e->mu);
279 return rc;
280}
281
282int rx_sem_branch_fork(RxSemEngine *e, uint32_t parent, uint32_t agent, uint64_t task,
283 uint64_t candidate, uint32_t *out) {
284 if (!e || !out) return RX_SEM_ERR_ARG;
285 pthread_mutex_lock(&e->mu);
286 RxSemBranch *p = branch_of(e, parent);
287 uint32_t id;
288 int rc = p ? branch_alloc(e, &id) : RX_SEM_ERR_NOT_FOUND;
289 if (rc == RX_SEM_OK) {
290 RxSemBranch *b = &e->branches[id];
291 memcpy(b, p, sizeof *b);
292 b->id = id;
293 b->parent = parent;
294 b->agent = agent;
295 b->task = task;
296 b->candidate = candidate;
297 b->invalidations = 0;
298 *out = id;
299 }
300 pthread_mutex_unlock(&e->mu);
301 return rc;
302}
303
304int rx_sem_branch_drop(RxSemEngine *e, uint32_t branch) {
305 pthread_mutex_lock(&e->mu);
306 RxSemBranch *b = branch_of(e, branch);
307 if (b) b->live = false;
308 pthread_mutex_unlock(&e->mu);
309 return b ? RX_SEM_OK : RX_SEM_ERR_NOT_FOUND;
310}
311
312int rx_sem_branch_context(RxSemEngine *e, uint32_t branch, uint32_t agent, uint64_t task,
313 uint64_t candidate) {
314 pthread_mutex_lock(&e->mu);
315 RxSemBranch *b = branch_of(e, branch);
316 if (b) {
317 b->agent = agent;
318 b->task = task;
319 b->candidate = candidate;
320 }
321 pthread_mutex_unlock(&e->mu);
322 return b ? RX_SEM_OK : RX_SEM_ERR_NOT_FOUND;
323}
324
325/* ---- invalidation ---------------------------------------------------------- */
326
327/* Mark node `idx` and everything that reads it DIRTY in branch b. */
328static void dirty_from(RxSemEngine *e, RxSemBranch *b, uint32_t idx, uint8_t *seen) {
329 if (seen[idx]) return;
330 seen[idx] = 1;
331 if (b->state[idx] == RX_SEM_CLEAN) {
332 b->state[idx] = RX_SEM_DIRTY;
333 b->invalidations++;
334 e->stats.invalidations++;
335 }
336 const RxSemNode *n = &e->nodes[idx];
337 for (uint32_t i = 0; i < n->n_readers; i++) dirty_from(e, b, n->readers[i], seen);
338}
339
340static void dirty_source(RxSemEngine *e, RxSemBranch *b, uint32_t si) {
341 uint8_t seen[RX_SEM_MAX_NODES];
342 memset(seen, 0, sizeof seen);
343 if (e->grain == RX_SEM_GRAIN_OBJECT) {
344 /* Baseline: any field of the object dirties readers of every field. */
345 uint32_t obj = e->sources[si].obj.id;
346 for (uint32_t j = 0; j < e->n_sources; j++) {
347 if (!e->sources[j].used || e->sources[j].obj.id != obj) continue;
348 for (uint32_t r = 0; r < e->sources[j].n_readers; r++)
349 dirty_from(e, b, e->sources[j].readers[r], seen);
350 }
351 return;
352 }
353 const RxSemSource *s = &e->sources[si];
354 for (uint32_t r = 0; r < s->n_readers; r++) dirty_from(e, b, s->readers[r], seen);
355}
356
357static int set_source_locked(RxSemEngine *e, RxSemBranch *b, uint32_t si, uint32_t generation,
358 const uint64_t *words, uint32_t n, uint32_t confidence,
359 const RxSemDigest *evidence) {
360 const RxSemSource *s = &e->sources[si];
361 RxSemValue v;
362 memset(&v, 0, sizeof v);
363 v.semantic_id = s->semantic_id;
364 v.type = s->type;
365 v.generation = generation;
366 v.confidence = confidence;
367 v.n_words = n;
368 memcpy(v.value, words, n * sizeof *words);
369 rx_sem_digest_value(v.type, v.value, n, &v.value_digest);
370 if (evidence) {
371 v.n_evidence = 1;
372 v.evidence_refs[0] = *evidence;
373 }
374 e->stats.source_writes++;
375 RxSemValue *cur = &b->source[si];
376 bool had = b->have_source[si];
377 bool was_stale = b->source_stale[si];
378 b->source_stale[si] = false;
379 if (had && !was_stale && cur->generation == generation &&
380 rx_sem_digest_eq(&cur->value_digest, &v.value_digest) && cur->confidence == confidence) {
381 /* Same meaning. Keep the newest evidence; wake nobody. */
382 if (evidence) {
383 cur->n_evidence = 1;
384 cur->evidence_refs[0] = *evidence;
385 }
386 e->stats.source_writes_unchanged++;
387 return 0;
388 }
389 v.value_version = ++b->version_clock;
390 *cur = v;
391 b->have_source[si] = true;
392 dirty_source(e, b, si);
393 return 1;
394}
395
396int rx_sem_set_source(RxSemEngine *e, uint32_t branch, uint64_t sid, uint32_t generation,
397 const uint64_t *words, uint32_t n, uint32_t confidence,
398 const RxSemDigest *evidence) {
399 if (!e || !words || n > RX_SEM_VALUE_WORDS) return RX_SEM_ERR_ARG;
400 pthread_mutex_lock(&e->mu);
401 RxSemBranch *b = branch_of(e, branch);
402 uint32_t si = source_index(e, sid);
403 int rc = !b ? RX_SEM_ERR_NOT_FOUND : si == NONE ? RX_SEM_ERR_NOT_FOUND
404 : set_source_locked(e, b, si, generation, words, n, confidence, evidence);
405 pthread_mutex_unlock(&e->mu);
406 return rc < 0 ? rc : RX_SEM_OK;
407}
408
409int rx_sem_sync_world(RxSemEngine *e, uint32_t branch, RxWorld *w) {
410 if (!e || !w) return RX_SEM_ERR_ARG;
411 pthread_mutex_lock(&e->mu);
412 RxSemBranch *b = branch_of(e, branch);
413 if (!b) {
414 pthread_mutex_unlock(&e->mu);
415 return RX_SEM_ERR_NOT_FOUND;
416 }
417 int changed = 0;
418 for (uint32_t si = 0; si < e->n_sources; si++) {
419 RxSemSource *s = &e->sources[si];
420 if (!s->used || !s->world_bound) continue;
421 RxObject o;
422 if (rx_world_read(w, s->obj, &o) != RX_OK) {
423 /* Retired: nothing derived from the old object may be served. */
424 if (!b->source_stale[si]) {
425 b->source_stale[si] = true;
426 dirty_source(e, b, si);
427 changed++;
428 }
429 continue;
430 }
431 RxSemValue *cur = &b->source[si];
432 if (b->have_source[si] && !b->source_stale[si] && cur->generation == o.generation &&
433 b->world_version[si] == o.field_version[s->field])
434 continue; /* world version unchanged: not even read further */
435 b->world_version[si] = o.field_version[s->field];
436 /* Evidence: the causal crumb that last wrote this field. */
437 RxSemDigest ev;
438 memset(&ev, 0, sizeof ev);
439 const RxCrumb *cr = rx_world_crumb(w, o.field_writer[s->field]);
440 if (cr) memcpy(ev.b, cr->digest, 32);
441 uint64_t word = o.field[s->field];
442 int r = set_source_locked(e, b, si, o.generation, &word, 1, RX_SEM_CONFIDENCE_ONE, &ev);
443 if (r > 0) changed++;
444 }
445 pthread_mutex_unlock(&e->mu);
446 return changed;
447}
448
449int rx_sem_rebind(RxSemEngine *e, uint64_t sid, RxObjRef obj) {
450 pthread_mutex_lock(&e->mu);
451 uint32_t si = source_index(e, sid);
452 if (si != NONE) e->sources[si].obj = obj;
453 pthread_mutex_unlock(&e->mu);
454 return si == NONE ? RX_SEM_ERR_NOT_FOUND : RX_SEM_OK;
455}
456
457/* ---- cache ----------------------------------------------------------------- */
458
459static void compute_key(const RxSemDigest *deriv, const RxSemInputVersion *in, uint32_t n,
460 RxSemDigest *out) {
461 sha256_ctx c;
462 sha256_init(&c);
463 h_tag(&c, "omega.sem.key.v1");
464 h_dig(&c, deriv);
465 h_u32(&c, n);
466 for (uint32_t i = 0; i < n; i++) {
467 h_u64(&c, in[i].semantic_id);
468 h_u32(&c, in[i].generation);
469 h_dig(&c, &in[i].value_digest);
470 }
471 sha256_final(&c, out->b);
472}
473
474static void digest_result(sha256_ctx *c, const RxSemValue *v) {
475 h_u64(c, v->semantic_id);
476 h_u32(c, v->type);
477 h_u32(c, v->generation);
478 h_dig(c, &v->derivation_id);
479 h_u32(c, v->confidence);
480 h_u32(c, v->n_deps);
481 for (uint32_t i = 0; i < v->n_deps; i++) h_u64(c, v->dependencies[i]);
482 h_u32(c, v->n_words);
483 for (uint32_t i = 0; i < v->n_words; i++) h_u64(c, v->value[i]);
484 h_dig(c, &v->value_digest);
485}
486
487static void entry_digest(const RxSemDerived *d, RxSemDigest *out) {
488 sha256_ctx c;
489 sha256_init(&c);
490 h_tag(&c, "omega.sem.entry.v1");
491 h_u32(&c, d->function_id);
492 h_dig(&c, &d->derivation_id);
493 h_dig(&c, &d->key);
494 h_u32(&c, d->n_inputs);
495 for (uint32_t i = 0; i < d->n_inputs; i++) {
496 h_u64(&c, d->input_versions[i].semantic_id);
497 h_u32(&c, d->input_versions[i].generation);
498 h_dig(&c, &d->input_versions[i].value_digest);
499 h_u64(&c, d->input_versions[i].value_version);
500 h_dig(&c, &d->input_versions[i].evidence);
501 }
502 digest_result(&c, &d->result);
503 h_u32(&c, d->producer_branch);
504 h_u32(&c, d->producer_agent);
505 h_u64(&c, d->producer_task);
506 h_u64(&c, d->producer_candidate);
507 h_u64(&c, d->compute_ns);
508 h_u64(&c, d->seq);
509 sha256_final(&c, out->b);
510}
511
512static bool same_inputs(const RxSemDerived *d, const RxSemDigest *deriv,
513 const RxSemInputVersion *in, uint32_t n) {
514 if (!rx_sem_digest_eq(&d->derivation_id, deriv) || d->n_inputs != n) return false;
515 for (uint32_t i = 0; i < n; i++) {
516 if (d->input_versions[i].semantic_id != in[i].semantic_id ||
517 d->input_versions[i].generation != in[i].generation ||
518 !rx_sem_digest_eq(&d->input_versions[i].value_digest, &in[i].value_digest))
519 return false;
520 }
521 return true;
522}
523
524static uint32_t slot_of(const RxSemDigest *key) {
525 uint32_t h = (uint32_t)key->b[0] | (uint32_t)key->b[1] << 8 | (uint32_t)key->b[2] << 16 |
526 (uint32_t)key->b[3] << 24;
527 return h & (RX_SEM_CACHE_SLOTS - 1u);
528}
529
530/* Returns the slot holding `key`, or NONE; *free_slot gets the first empty. */
531static uint32_t cache_find(const RxSemEngine *e, const RxSemDigest *key, const RxSemDigest *deriv,
532 const RxSemInputVersion *in, uint32_t n, uint32_t *free_slot) {
533 uint32_t s = slot_of(key);
534 *free_slot = NONE;
535 for (uint32_t probe = 0; probe < RX_SEM_CACHE_SLOTS; probe++) {
536 const RxSemDerived *d = &e->cache[(s + probe) & (RX_SEM_CACHE_SLOTS - 1u)];
537 if (!d->used) {
538 *free_slot = (s + probe) & (RX_SEM_CACHE_SLOTS - 1u);
539 return NONE;
540 }
541 /* The key is a digest; the full input record is compared as well. */
542 if (rx_sem_digest_eq(&d->key, key) && same_inputs(d, deriv, in, n))
543 return (s + probe) & (RX_SEM_CACHE_SLOTS - 1u);
544 }
545 return NONE;
546}
547
548static void event_append(RxSemEngine *e, uint32_t kind, uint32_t slot, const RxSemBranch *b,
549 const RxSemDigest *inputs_evidence) {
550 if (e->n_events >= e->event_cap) {
551 e->event_overflow++;
552 return;
553 }
554 RxSemEvent *ev = &e->events[e->n_events];
555 memset(ev, 0, sizeof *ev);
556 ev->id = e->n_events + 1;
557 ev->kind = kind;
558 ev->entry = slot;
559 ev->entry_digest = e->cache[slot].entry_digest;
560 ev->branch = b->id;
561 ev->agent = b->agent;
562 ev->task = b->task;
563 ev->candidate = b->candidate;
564 ev->inputs_evidence = *inputs_evidence;
565 if (e->n_events > 0) ev->prev = e->events[e->n_events - 1].digest;
566 sha256_ctx c;
567 sha256_init(&c);
568 h_tag(&c, "omega.sem.event.v1");
569 h_dig(&c, &ev->prev);
570 h_u64(&c, ev->id);
571 h_u32(&c, ev->kind);
572 h_u32(&c, ev->entry);
573 h_dig(&c, &ev->entry_digest);
574 h_u32(&c, ev->branch);
575 h_u32(&c, ev->agent);
576 h_u64(&c, ev->task);
577 h_u64(&c, ev->candidate);
578 h_dig(&c, &ev->inputs_evidence);
579 sha256_final(&c, ev->digest.b);
580 e->n_events++;
581}
582
583static bool event_ok(const RxSemEvent *ev, const RxSemDigest *prev) {
584 if (!rx_sem_digest_eq(&ev->prev, prev)) return false;
585 RxSemDigest d;
586 sha256_ctx c;
587 sha256_init(&c);
588 h_tag(&c, "omega.sem.event.v1");
589 h_dig(&c, &ev->prev);
590 h_u64(&c, ev->id);
591 h_u32(&c, ev->kind);
592 h_u32(&c, ev->entry);
593 h_dig(&c, &ev->entry_digest);
594 h_u32(&c, ev->branch);
595 h_u32(&c, ev->agent);
596 h_u64(&c, ev->task);
597 h_u64(&c, ev->candidate);
598 h_dig(&c, &ev->inputs_evidence);
599 sha256_final(&c, d.b);
600 return rx_sem_digest_eq(&d, &ev->digest);
601}
602
603/* ---- evaluation ------------------------------------------------------------ */
604
605static int run_fn(RxSemEngine *e, const RxSemNode *nd, const RxSemValue *const *in,
606 RxSemValue *out, uint64_t *ns) {
607 const RxSemFnDesc *f = &e->fns[nd->function_id];
608 memset(out, 0, sizeof *out);
609 uint32_t conf = RX_SEM_CONFIDENCE_ONE;
610 for (uint32_t i = 0; i < nd->n_inputs; i++)
611 if (in[i]->confidence < conf) conf = in[i]->confidence;
612 out->confidence = conf;
613 uint64_t t0 = now_ns();
614 int rc = f->fn(in, nd->n_inputs, out, f->user);
615 uint64_t t1 = now_ns();
616 if (ns) *ns = t1 - t0;
617 if (rc != 0 || out->n_words > RX_SEM_VALUE_WORDS) return RX_SEM_ERR_FN;
618 if (out->confidence > RX_SEM_CONFIDENCE_ONE) out->confidence = RX_SEM_CONFIDENCE_ONE;
619 out->semantic_id = nd->semantic_id;
620 out->type = f->out_type;
621 out->generation = f->generation;
622 out->derivation_id = e->fn_derivation[nd->function_id];
623 out->n_deps = nd->n_inputs;
624 memcpy(out->dependencies, nd->inputs, nd->n_inputs * sizeof nd->inputs[0]);
625 out->n_evidence = 0;
626 out->value_version = 0;
627 rx_sem_digest_value(out->type, out->value, out->n_words, &out->value_digest);
628 return RX_SEM_OK;
629}
630
631static bool same_content(const RxSemValue *a, const RxSemValue *b) {
632 return a->type == b->type && a->n_words == b->n_words && a->confidence == b->confidence &&
633 memcmp(a->value, b->value, a->n_words * sizeof a->value[0]) == 0;
634}
635
636static int get_locked(RxSemEngine *e, RxSemBranch *b, uint32_t idx, RxSemServed *served);
637
638/* Collect the current inputs of node idx in branch b (bringing nodes up to date). */
639static int gather(RxSemEngine *e, RxSemBranch *b, const RxSemNode *nd,
640 const RxSemValue **in, RxSemInputVersion *iv, RxSemDigest *inputs_evidence) {
641 sha256_ctx c;
642 sha256_init(&c);
643 h_tag(&c, "omega.sem.inputs-evidence.v1");
644 for (uint32_t i = 0; i < nd->n_inputs; i++) {
645 uint64_t sid = nd->inputs[i];
646 const RxSemValue *v;
647 if (RX_SEM_KIND(sid) == RX_SEM_KIND_SOURCE) {
648 uint32_t si = source_index(e, sid);
649 if (!b->have_source[si]) return RX_SEM_ERR_NOT_FOUND;
650 if (b->source_stale[si]) return RX_SEM_ERR_STALE;
651 v = &b->source[si];
652 iv[i].evidence = v->n_evidence ? v->evidence_refs[0] : (RxSemDigest){ { 0 } };
653 } else {
654 uint32_t ci = node_index(e, sid);
655 int rc = get_locked(e, b, ci, NULL);
656 if (rc != RX_SEM_OK) return rc;
657 v = &b->memo[ci];
658 iv[i].evidence = b->memo_entry[ci] != NONE ? e->cache[b->memo_entry[ci]].entry_digest
659 : (RxSemDigest){ { 0 } };
660 }
661 in[i] = v;
662 iv[i].semantic_id = sid;
663 iv[i].generation = v->generation;
664 iv[i].value_digest = v->value_digest;
665 iv[i].value_version = v->value_version;
666 h_dig(&c, &iv[i].evidence);
667 }
668 sha256_final(&c, inputs_evidence->b);
669 return RX_SEM_OK;
670}
671
672static void install_memo(RxSemBranch *b, uint32_t idx, const RxSemValue *v, const RxSemDigest *key,
673 uint32_t slot, const RxSemDigest *entry_dig,
674 const RxSemDigest *inputs_evidence) {
675 bool changed = b->state[idx] == RX_SEM_ABSENT ||
676 !rx_sem_digest_eq(&b->memo[idx].value_digest, &v->value_digest);
677 uint64_t ver = changed ? ++b->version_clock : b->memo[idx].value_version;
678 b->memo[idx] = *v;
679 b->memo[idx].value_version = ver;
680 b->memo[idx].n_evidence = 0;
681 if (entry_dig) b->memo[idx].evidence_refs[b->memo[idx].n_evidence++] = *entry_dig;
682 b->memo[idx].evidence_refs[b->memo[idx].n_evidence++] = *inputs_evidence;
683 b->memo_key[idx] = *key;
684 b->memo_entry[idx] = slot;
685 b->state[idx] = RX_SEM_CLEAN;
686}
687
688/* In audit mode, recompute a served value and compare. */
689static void audit_hit(RxSemEngine *e, const RxSemNode *nd, const RxSemValue *const *in,
690 const RxSemValue *served) {
691 if (!e->audit) return;
692 RxSemValue fresh;
693 e->stats.audits++;
694 if (run_fn(e, nd, in, &fresh, NULL) != RX_SEM_OK || !same_content(&fresh, served))
695 e->stats.false_hits++;
696}
697
698static int get_locked(RxSemEngine *e, RxSemBranch *b, uint32_t idx, RxSemServed *served) {
699 const RxSemNode *nd = &e->nodes[idx];
700 e->stats.gets++;
701 const RxSemValue *in[RX_SEM_MAX_INPUTS];
702 RxSemInputVersion iv[RX_SEM_MAX_INPUTS];
703 RxSemDigest ievid;
704
705 if (b->state[idx] == RX_SEM_CLEAN) {
706 e->stats.memo_hits++;
707 if (b->memo_entry[idx] != NONE) e->stats.saved_ns += e->cache[b->memo_entry[idx]].compute_ns;
708 if (served) *served = RX_SEM_SERVED_MEMO;
709 if (e->audit) {
710 /* Clean inputs are already current: gathering does no work. The
711 * audit's own reads are not counted as service. */
712 RxSemStats keep = e->stats;
713 int grc = gather(e, b, nd, in, iv, &ievid);
714 uint64_t audits = e->stats.audits, false_hits = e->stats.false_hits;
715 e->stats = keep;
716 e->stats.audits = audits;
717 e->stats.false_hits = false_hits;
718 if (grc == RX_SEM_OK) audit_hit(e, nd, in, &b->memo[idx]);
719 else e->stats.false_hits++;
720 }
721 return RX_SEM_OK;
722 }
723
724 int rc = gather(e, b, nd, in, iv, &ievid);
725 if (rc != RX_SEM_OK) return rc;
726 const RxSemDigest *deriv = &e->fn_derivation[nd->function_id];
727 RxSemDigest key;
728 compute_key(deriv, iv, nd->n_inputs, &key);
729
730 if (b->state[idx] == RX_SEM_DIRTY && rx_sem_digest_eq(&b->memo_key[idx], &key)) {
731 /* Marked, but every input came back with the same content. */
732 b->state[idx] = RX_SEM_CLEAN;
733 e->stats.cutoffs++;
734 if (b->memo_entry[idx] != NONE) e->stats.saved_ns += e->cache[b->memo_entry[idx]].compute_ns;
735 if (served) *served = RX_SEM_SERVED_CUTOFF;
736 audit_hit(e, nd, in, &b->memo[idx]);
737 return RX_SEM_OK;
738 }
739
740 uint32_t free_slot = NONE;
741 uint32_t slot = cache_find(e, &key, deriv, iv, nd->n_inputs, &free_slot);
742 if (slot != NONE && e->cache_enabled) {
743 RxSemDerived *d = &e->cache[slot];
744 d->reuses++;
745 e->stats.cache_hits++;
746 e->stats.saved_ns += d->compute_ns;
747 if (d->producer_branch != b->id) e->stats.cache_hits_cross_branch++;
748 if (d->producer_agent != b->agent) e->stats.cache_hits_cross_agent++;
749 if (d->producer_task != b->task) e->stats.cache_hits_cross_task++;
750 if (d->producer_candidate != b->candidate) e->stats.cache_hits_cross_candidate++;
751 install_memo(b, idx, &d->result, &key, slot, &d->entry_digest, &ievid);
752 event_append(e, RX_SEM_EVENT_REUSE, slot, b, &ievid);
753 if (served) *served = RX_SEM_SERVED_CACHE;
754 audit_hit(e, nd, in, &d->result);
755 return RX_SEM_OK;
756 }
757
758 RxSemValue out;
759 uint64_t ns = 0;
760 rc = run_fn(e, nd, in, &out, &ns);
761 if (rc != RX_SEM_OK) return rc;
762 e->stats.computes++;
763 e->stats.compute_ns += ns;
764 if (served) *served = RX_SEM_SERVED_COMPUTED;
765
766 if (slot == NONE && free_slot != NONE &&
767 e->cache_used < RX_SEM_CACHE_SLOTS - RX_SEM_CACHE_SLOTS / 8u) {
768 RxSemDerived *d = &e->cache[free_slot];
769 memset(d, 0, sizeof *d);
770 d->used = true;
771 d->function_id = nd->function_id;
772 d->derivation_id = *deriv;
773 d->key = key;
774 d->n_inputs = nd->n_inputs;
775 memcpy(d->input_versions, iv, nd->n_inputs * sizeof iv[0]);
776 d->result = out;
777 d->producer_branch = b->id;
778 d->producer_agent = b->agent;
779 d->producer_task = b->task;
780 d->producer_candidate = b->candidate;
781 d->compute_ns = ns;
782 d->seq = ++e->cache_seq;
783 entry_digest(d, &d->entry_digest);
784 e->cache_used++;
785 install_memo(b, idx, &out, &key, free_slot, &d->entry_digest, &ievid);
786 event_append(e, RX_SEM_EVENT_PRODUCE, free_slot, b, &ievid);
787 } else if (slot != NONE) {
788 /* Cache lookups are off (baseline) and this key is already filed. */
789 install_memo(b, idx, &out, &key, slot, &e->cache[slot].entry_digest, &ievid);
790 } else {
791 e->stats.cache_full++;
792 install_memo(b, idx, &out, &key, NONE, NULL, &ievid);
793 }
794 return RX_SEM_OK;
795}
796
797int rx_sem_get(RxSemEngine *e, uint32_t branch, uint64_t sid, RxSemValue *out,
798 RxSemServed *served) {
799 if (!e) return RX_SEM_ERR_ARG;
800 pthread_mutex_lock(&e->mu);
801 RxSemBranch *b = branch_of(e, branch);
802 int rc = RX_SEM_ERR_NOT_FOUND;
803 if (b) {
804 uint32_t idx = node_index(e, sid);
805 if (idx != NONE) {
806 rc = get_locked(e, b, idx, served);
807 if (rc == RX_SEM_OK && out) *out = b->memo[idx];
808 } else {
809 uint32_t si = source_index(e, sid);
810 if (si != NONE && b->have_source[si] && !b->source_stale[si]) {
811 rc = RX_SEM_OK;
812 if (out) *out = b->source[si];
813 } else if (si != NONE && b->source_stale[si]) rc = RX_SEM_ERR_STALE;
814 }
815 }
816 pthread_mutex_unlock(&e->mu);
817 return rc;
818}
819
820int rx_sem_read_source(RxSemEngine *e, uint32_t branch, uint64_t sid, RxSemValue *out) {
821 if (RX_SEM_KIND(sid) != RX_SEM_KIND_SOURCE) return RX_SEM_ERR_ARG;
822 return rx_sem_get(e, branch, sid, out, NULL);
823}
824
825int rx_sem_state(RxSemEngine *e, uint32_t branch, uint64_t sid) {
826 pthread_mutex_lock(&e->mu);
827 RxSemBranch *b = branch_of(e, branch);
828 uint32_t idx = node_index(e, sid);
829 int st = (!b || idx == NONE) ? RX_SEM_ERR_NOT_FOUND : b->state[idx];
830 pthread_mutex_unlock(&e->mu);
831 return st;
832}
833
834int rx_sem_explain(RxSemEngine *e, uint32_t branch, uint64_t sid, RxSemDerived *out) {
835 pthread_mutex_lock(&e->mu);
836 RxSemBranch *b = branch_of(e, branch);
837 uint32_t idx = node_index(e, sid);
838 int rc = RX_SEM_ERR_NOT_FOUND;
839 if (b && idx != NONE && b->state[idx] == RX_SEM_CLEAN && b->memo_entry[idx] != NONE) {
840 *out = e->cache[b->memo_entry[idx]];
841 rc = RX_SEM_OK;
842 }
843 pthread_mutex_unlock(&e->mu);
844 return rc;
845}
846
847/* ---- verification ---------------------------------------------------------- */
848
849int rx_sem_verify(RxSemEngine *e, uint64_t *entries_checked, uint64_t *events_checked,
850 uint64_t *memos_checked) {
851 pthread_mutex_lock(&e->mu);
852 int rc = RX_SEM_OK;
853 uint64_t ne = 0, nv = 0, nm = 0;
854 for (uint32_t s = 0; s < RX_SEM_CACHE_SLOTS; s++) {
855 const RxSemDerived *d = &e->cache[s];
856 if (!d->used) continue;
857 ne++;
858 RxSemDigest k, dd, vd;
859 compute_key(&d->derivation_id, d->input_versions, d->n_inputs, &k);
860 entry_digest(d, &dd);
861 rx_sem_digest_value(d->result.type, d->result.value, d->result.n_words, &vd);
862 if (!rx_sem_digest_eq(&k, &d->key) || !rx_sem_digest_eq(&dd, &d->entry_digest) ||
863 !rx_sem_digest_eq(&vd, &d->result.value_digest) ||
864 d->function_id >= e->n_fns ||
865 !rx_sem_digest_eq(&d->derivation_id, &e->fn_derivation[d->function_id]))
866 rc = RX_SEM_ERR_VERIFY;
867 }
868 RxSemDigest prev;
869 memset(&prev, 0, sizeof prev);
870 for (uint64_t i = 0; i < e->n_events; i++) {
871 const RxSemEvent *ev = &e->events[i];
872 nv++;
873 if (ev->id != i + 1 || !event_ok(ev, &prev) || ev->entry >= RX_SEM_CACHE_SLOTS ||
874 !e->cache[ev->entry].used ||
875 !rx_sem_digest_eq(&ev->entry_digest, &e->cache[ev->entry].entry_digest))
876 rc = RX_SEM_ERR_VERIFY;
877 prev = ev->digest;
878 }
879 /* Every clean memo is exactly its entry's result, and that entry was
880 * derived from what the branch holds now. */
881 for (uint32_t bi = 0; bi < RX_SEM_MAX_BRANCHES; bi++) {
882 const RxSemBranch *b = &e->branches[bi];
883 if (!b->live) continue;
884 for (uint32_t n = 0; n < e->n_nodes; n++) {
885 if (b->state[n] != RX_SEM_CLEAN) continue;
886 nm++;
887 const RxSemNode *nd = &e->nodes[n];
888 if (b->memo_entry[n] == NONE) continue;
889 const RxSemDerived *d = &e->cache[b->memo_entry[n]];
890 if (!same_content(&d->result, &b->memo[n]) || d->n_inputs != nd->n_inputs) {
891 rc = RX_SEM_ERR_VERIFY;
892 continue;
893 }
894 for (uint32_t i = 0; i < nd->n_inputs; i++) {
895 uint64_t sid = nd->inputs[i];
896 const RxSemValue *v;
897 if (RX_SEM_KIND(sid) == RX_SEM_KIND_SOURCE) {
898 uint32_t si = source_index(e, sid);
899 if (b->source_stale[si] || !b->have_source[si]) { rc = RX_SEM_ERR_VERIFY; break; }
900 v = &b->source[si];
901 } else {
902 uint32_t ci = node_index(e, sid);
903 if (b->state[ci] != RX_SEM_CLEAN) { rc = RX_SEM_ERR_VERIFY; break; }
904 v = &b->memo[ci];
905 }
906 if (d->input_versions[i].semantic_id != sid ||
907 d->input_versions[i].generation != v->generation ||
908 !rx_sem_digest_eq(&d->input_versions[i].value_digest, &v->value_digest)) {
909 rc = RX_SEM_ERR_VERIFY;
910 break;
911 }
912 }
913 }
914 }
915 if (entries_checked) *entries_checked = ne;
916 if (events_checked) *events_checked = nv;
917 if (memos_checked) *memos_checked = nm;
918 pthread_mutex_unlock(&e->mu);
919 return rc;
920}
921
922/* ---- structure ------------------------------------------------------------- */
923
924int rx_sem_node_inputs(RxSemEngine *e, uint64_t sid, uint64_t *inputs, uint32_t *n) {
925 pthread_mutex_lock(&e->mu);
926 uint32_t idx = node_index(e, sid);
927 if (idx != NONE) {
928 *n = e->nodes[idx].n_inputs;
929 memcpy(inputs, e->nodes[idx].inputs, *n * sizeof *inputs);
930 }
931 pthread_mutex_unlock(&e->mu);
932 return idx == NONE ? RX_SEM_ERR_NOT_FOUND : RX_SEM_OK;
933}
934
935static void collect(const RxSemEngine *e, uint32_t idx, uint8_t *seen) {
936 if (seen[idx]) return;
937 seen[idx] = 1;
938 for (uint32_t i = 0; i < e->nodes[idx].n_readers; i++) collect(e, e->nodes[idx].readers[i], seen);
939}
940
941int rx_sem_downstream(RxSemEngine *e, uint64_t sid, uint64_t *out, uint32_t cap, uint32_t *n) {
942 pthread_mutex_lock(&e->mu);
943 uint8_t seen[RX_SEM_MAX_NODES];
944 memset(seen, 0, sizeof seen);
945 int rc = RX_SEM_OK;
946 uint32_t si = source_index(e, sid);
947 uint32_t ni = node_index(e, sid);
948 if (si != NONE) {
949 for (uint32_t r = 0; r < e->sources[si].n_readers; r++)
950 collect(e, e->sources[si].readers[r], seen);
951 } else if (ni != NONE) {
952 for (uint32_t r = 0; r < e->nodes[ni].n_readers; r++)
953 collect(e, e->nodes[ni].readers[r], seen);
954 } else rc = RX_SEM_ERR_NOT_FOUND;
955 uint32_t k = 0;
956 for (uint32_t i = 0; i < e->n_nodes && rc == RX_SEM_OK; i++) {
957 if (!seen[i]) continue;
958 if (k >= cap) { rc = RX_SEM_ERR_FULL; break; }
959 out[k++] = e->nodes[i].semantic_id;
960 }
961 *n = k;
962 pthread_mutex_unlock(&e->mu);
963 return rc;
964}