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_world.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_world.c -- resident reaction runtime, simple human reference. See rx_world.h. |
| 19 | */ |
| 20 | #include "rx_world.h" |
| 21 | #include "rx_argus.h" |
| 22 | #include "omega_native.h" |
| 23 | #include "sha256.h" |
| 24 | #include "rx_generation.h" /* RX_GEN_HALT_MARK */ |
| 25 | #include "omega_path_check.h" |
| 26 | |
| 27 | #include <errno.h> |
| 28 | #include <fcntl.h> |
| 29 | #include <stdio.h> |
| 30 | #include <stdlib.h> |
| 31 | #include <string.h> |
| 32 | #include <sys/mman.h> |
| 33 | #include <sys/random.h> |
| 34 | #include <sys/stat.h> |
| 35 | #include <time.h> |
| 36 | #include <unistd.h> |
| 37 | |
| 38 | /* ---- helpers ------------------------------------------------------------ */ |
| 39 | |
| 40 | /* The causal log is one address range reserved for crumb_cap records and |
| 41 | * backed only as records are written (MAP_NORESERVE; zero pages until |
| 42 | * touched). Records never move, so a crumb pointer stays valid for the life |
| 43 | * of the world, and a large capacity costs nothing until an episode uses it. |
| 44 | * The log is still bounded: a full log refuses the publication (no action |
| 45 | * without evidence) and counts crumb_overflow. */ |
| 46 | static RxCrumb *crumb_log_map(uint64_t cap) { |
| 47 | if (cap > UINT64_MAX / sizeof(RxCrumb)) return NULL; |
| 48 | void *p = mmap(NULL, (size_t)cap * sizeof(RxCrumb), PROT_READ | PROT_WRITE, |
| 49 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0); |
| 50 | return p == MAP_FAILED ? NULL : (RxCrumb *)p; |
| 51 | } |
| 52 | |
| 53 | static void crumb_log_unmap(RxCrumb *log, uint64_t cap) { |
| 54 | if (log) munmap(log, (size_t)cap * sizeof(RxCrumb)); |
| 55 | } |
| 56 | |
| 57 | static uint64_t now_ns(void) { |
| 58 | struct timespec ts; |
| 59 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 60 | return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; |
| 61 | } |
| 62 | |
| 63 | /* CPU time consumed by the calling thread (R15 scheduler CPU, spec ยง6.4). */ |
| 64 | static uint64_t thread_cpu_ns(void) { |
| 65 | struct timespec ts; |
| 66 | clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts); |
| 67 | return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; |
| 68 | } |
| 69 | |
| 70 | static void put32(sha256_ctx *c, uint32_t v) { |
| 71 | uint8_t b[4] = { (uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24) }; |
| 72 | sha256_update(c, b, 4); |
| 73 | } |
| 74 | |
| 75 | static void put64(sha256_ctx *c, uint64_t v) { |
| 76 | put32(c, (uint32_t)v); |
| 77 | put32(c, (uint32_t)(v >> 32)); |
| 78 | } |
| 79 | |
| 80 | static void object_digest(RxObject *o) { |
| 81 | sha256_ctx c; |
| 82 | sha256_init(&c); |
| 83 | sha256_update(&c, (const uint8_t *)"AIEN_RX_OBJECT_V1", 17); |
| 84 | put32(&c, o->type); |
| 85 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) put64(&c, o->field[f]); |
| 86 | sha256_final(&c, o->digest); |
| 87 | } |
| 88 | |
| 89 | /* ---- lifecycle ---------------------------------------------------------- */ |
| 90 | |
| 91 | bool rx_state_transition_legal(RxState from, RxState to) { |
| 92 | uint64_t res = 0; |
| 93 | if (omega2_rx_world_state_legal(&res, (uint64_t)from, (uint64_t)to) != OMEGA_OK) |
| 94 | return false; |
| 95 | return res != 0; |
| 96 | } |
| 97 | |
| 98 | const char *rx_state_name(RxState s) { |
| 99 | static const char *names[RX_STATE_COUNT] = { |
| 100 | "DORMANT", "READY", "BLOCKED_AUTHORITY", "BLOCKED_RESOURCE", "RUNNING", |
| 101 | "PUBLISHING", "COMMITTED", "INVALIDATED", "FAILED", "CANCELLED", "CONFLICT", |
| 102 | "REJECTED" |
| 103 | }; |
| 104 | return (unsigned)s < RX_STATE_COUNT ? names[s] : "?"; |
| 105 | } |
| 106 | |
| 107 | const char *rx_crumb_kind_name(RxCrumbKind k) { |
| 108 | switch (k) { |
| 109 | case RX_CRUMB_CREATE: return "CREATE"; |
| 110 | case RX_CRUMB_EXTERNAL: return "EXTERNAL"; |
| 111 | case RX_CRUMB_COMMIT: return "COMMIT"; |
| 112 | case RX_CRUMB_INVALIDATED: return "INVALIDATED"; |
| 113 | case RX_CRUMB_BLOCKED_AUTHORITY: return "BLOCKED_AUTHORITY"; |
| 114 | case RX_CRUMB_REJECTED: return "REJECTED"; |
| 115 | case RX_CRUMB_FAILED: return "FAILED"; |
| 116 | case RX_CRUMB_NOOP: return "NOOP"; |
| 117 | case RX_CRUMB_RETIRE: return "RETIRE"; |
| 118 | case RX_CRUMB_QUARANTINE: return "QUARANTINE"; |
| 119 | case RX_CRUMB_CANCELLED: return "CANCELLED"; |
| 120 | case RX_CRUMB_OPERATOR_STOP: return "OPERATOR_STOP"; |
| 121 | case RX_CRUMB_OPERATOR_RESUME: return "OPERATOR_RESUME"; |
| 122 | default: return "?"; |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | static void set_state(RxWorld *w, RxReaction *r, RxState to) { |
| 127 | if (!rx_state_transition_legal(r->state, to)) w->stats.illegal_transitions++; |
| 128 | w->stats.transitions[r->state][to]++; |
| 129 | r->state = to; |
| 130 | } |
| 131 | |
| 132 | /* ---- causal crumbs ------------------------------------------------------ */ |
| 133 | |
| 134 | static void crumb_hash(const RxWorld *w, const RxCrumb *k, uint8_t out[32]) { |
| 135 | sha256_ctx c; |
| 136 | sha256_init(&c); |
| 137 | sha256_update(&c, (const uint8_t *)"AIEN_RX_CAUSAL_V1", 17); |
| 138 | put64(&c, k->id); |
| 139 | put32(&c, (uint32_t)k->kind); |
| 140 | put32(&c, k->reaction); |
| 141 | put32(&c, k->faculty); |
| 142 | put64(&c, k->wake_cause); |
| 143 | put64(&c, k->coalesced_wakes); |
| 144 | put32(&c, k->n_inputs); |
| 145 | for (uint32_t i = 0; i < k->n_inputs; i++) { |
| 146 | put32(&c, k->inputs[i].obj.id); |
| 147 | put32(&c, k->inputs[i].obj.generation); |
| 148 | put64(&c, k->inputs[i].version); |
| 149 | put64(&c, k->inputs[i].mask); |
| 150 | } |
| 151 | put32(&c, k->n_caps); |
| 152 | for (uint32_t i = 0; i < k->n_caps; i++) { |
| 153 | put32(&c, k->caps[i].cap_id); |
| 154 | put64(&c, k->caps[i].generation); /* full 64-bit AIENOS generation */ |
| 155 | put32(&c, k->cap_issuer[i]); |
| 156 | } |
| 157 | put32(&c, k->n_outputs); |
| 158 | for (uint32_t i = 0; i < k->n_outputs; i++) { |
| 159 | put32(&c, k->outputs[i].obj.id); |
| 160 | put32(&c, k->outputs[i].obj.generation); |
| 161 | put64(&c, k->outputs[i].version); |
| 162 | put64(&c, k->outputs[i].mask); |
| 163 | } |
| 164 | put32(&c, (uint32_t)k->reason); |
| 165 | put32(&c, k->n_parents); |
| 166 | for (uint32_t i = 0; i < k->n_parents; i++) { |
| 167 | uint64_t p = k->parents[i]; |
| 168 | put64(&c, p); |
| 169 | /* Parents always precede children, so their digests are final. */ |
| 170 | if (p >= 1 && p <= w->n_crumbs && p < k->id) |
| 171 | sha256_update(&c, w->crumbs[p - 1].digest, 32); |
| 172 | } |
| 173 | /* Timing and worker placement are recorded but are not identity: the |
| 174 | * same causal history must hash the same on any schedule. */ |
| 175 | sha256_final(&c, out); |
| 176 | } |
| 177 | |
| 178 | static void add_parent(RxCrumb *k, uint64_t p) { |
| 179 | if (p == 0) return; |
| 180 | for (uint32_t i = 0; i < k->n_parents; i++) |
| 181 | if (k->parents[i] == p) return; |
| 182 | if (k->n_parents < RX_MAX_PARENTS) k->parents[k->n_parents++] = p; |
| 183 | } |
| 184 | |
| 185 | /* Append a crumb; returns its id (0 if the log is full). Caller holds mu. */ |
| 186 | static uint64_t crumb_append(RxWorld *w, RxCrumb *k) { |
| 187 | if (w->n_crumbs >= w->crumb_cap) { |
| 188 | w->stats.crumb_overflow++; |
| 189 | return 0; |
| 190 | } |
| 191 | k->id = w->n_crumbs + 1; |
| 192 | /* Canonical parent order: ascending. */ |
| 193 | for (uint32_t i = 1; i < k->n_parents; i++) { |
| 194 | uint64_t v = k->parents[i]; |
| 195 | uint32_t j = i; |
| 196 | while (j > 0 && k->parents[j - 1] > v) { k->parents[j] = k->parents[j - 1]; j--; } |
| 197 | k->parents[j] = v; |
| 198 | } |
| 199 | #ifndef RX_MEASURE_NO_CAUSAL_DIGEST |
| 200 | crumb_hash(w, k, k->digest); |
| 201 | #else |
| 202 | memset(k->digest, 0, sizeof(k->digest)); |
| 203 | #endif |
| 204 | w->stats.crumb_bytes += sizeof(*k); |
| 205 | if (k->kind == RX_CRUMB_EXTERNAL) k->episode = k->id; |
| 206 | else if (k->wake_cause >= 1 && k->wake_cause < k->id) |
| 207 | k->episode = w->crumbs[k->wake_cause - 1].episode; |
| 208 | else k->episode = 0; |
| 209 | w->crumbs[w->n_crumbs++] = *k; |
| 210 | if (k->reaction < w->n_reactions) w->reactions[k->reaction].last_crumb = k->id; |
| 211 | if (w->recorder) w->recorder(w->recorder_ctx, w, &w->crumbs[w->n_crumbs - 1]); |
| 212 | return k->id; |
| 213 | } |
| 214 | |
| 215 | /* R6 containment engaged. The crumb names the reaction, the limit and the |
| 216 | * crumb that caused it (so its episode). Wakes the quarantine suppresses |
| 217 | * later leave nothing, so the log stays bounded. Caller holds mu. */ |
| 218 | static void contain(RxWorld *w, uint32_t rid, uint32_t why, uint64_t cause) { |
| 219 | RxReaction *r = &w->reactions[rid]; |
| 220 | RxCrumb k; |
| 221 | memset(&k, 0, sizeof(k)); |
| 222 | k.kind = RX_CRUMB_QUARANTINE; |
| 223 | k.reaction = rid; |
| 224 | k.faculty = r->desc.faculty; |
| 225 | k.worker = UINT32_MAX; |
| 226 | k.wake_cause = cause; |
| 227 | add_parent(&k, cause); |
| 228 | k.reason = (int32_t)why; |
| 229 | k.t_start_ns = k.t_end_ns = now_ns(); |
| 230 | crumb_append(w, &k); |
| 231 | } |
| 232 | |
| 233 | #ifndef RX_MEASURE_NO_CAUSAL_DIGEST |
| 234 | const int rx_world_causal_digest_enabled = 1; |
| 235 | #else |
| 236 | const int rx_world_causal_digest_enabled = 0; |
| 237 | #endif |
| 238 | |
| 239 | const RxCrumb *rx_world_crumb(const RxWorld *w, uint64_t id) { |
| 240 | if (id == 0 || id > w->n_crumbs) return NULL; |
| 241 | return &w->crumbs[id - 1]; |
| 242 | } |
| 243 | |
| 244 | int rx_world_set_recorder(RxWorld *w, RxRecordFn fn, RxRecordReleaseFn release, void *ctx, |
| 245 | bool replay) { |
| 246 | if (!w || !fn) return RX_ERR_ARG; |
| 247 | pthread_mutex_lock(&w->mu); |
| 248 | if (w->recorder) { |
| 249 | pthread_mutex_unlock(&w->mu); |
| 250 | return RX_ERR_EXISTS; |
| 251 | } |
| 252 | if (replay) |
| 253 | for (uint64_t i = 0; i < w->n_crumbs; i++) fn(ctx, w, &w->crumbs[i]); |
| 254 | w->recorder = fn; |
| 255 | w->recorder_release = release; |
| 256 | w->recorder_ctx = ctx; |
| 257 | pthread_mutex_unlock(&w->mu); |
| 258 | return RX_OK; |
| 259 | } |
| 260 | |
| 261 | int rx_world_clear_recorder(RxWorld *w, void *ctx) { |
| 262 | if (!w) return RX_ERR_ARG; |
| 263 | pthread_mutex_lock(&w->mu); |
| 264 | int rc = RX_ERR_NOT_FOUND; |
| 265 | if (w->recorder && w->recorder_ctx == ctx) { |
| 266 | w->recorder = NULL; |
| 267 | w->recorder_release = NULL; |
| 268 | w->recorder_ctx = NULL; |
| 269 | rc = RX_OK; |
| 270 | } |
| 271 | pthread_mutex_unlock(&w->mu); |
| 272 | return rc; |
| 273 | } |
| 274 | |
| 275 | int rx_world_crumb_origin(RxWorld *w, uint64_t id, uint32_t *reaction, uint32_t *subject, |
| 276 | uint32_t *faculty) { |
| 277 | pthread_mutex_lock(&w->mu); |
| 278 | int rc = RX_ERR_NOT_FOUND; |
| 279 | if (id != 0 && id <= w->n_crumbs) { |
| 280 | const RxCrumb *c = &w->crumbs[id - 1]; |
| 281 | *reaction = c->reaction; |
| 282 | *faculty = c->faculty; |
| 283 | *subject = c->reaction < w->n_reactions ? w->reactions[c->reaction].desc.subject |
| 284 | : w->external_subject; |
| 285 | rc = c->kind == RX_CRUMB_COMMIT || c->kind == RX_CRUMB_EXTERNAL ? RX_OK |
| 286 | : c->kind == RX_CRUMB_CREATE ? 1 |
| 287 | : RX_ERR_ARG; |
| 288 | } |
| 289 | pthread_mutex_unlock(&w->mu); |
| 290 | return rc; |
| 291 | } |
| 292 | |
| 293 | void rx_world_crumb_digest(const RxWorld *w, const RxCrumb *k, uint8_t out[32]) { |
| 294 | crumb_hash(w, k, out); |
| 295 | } |
| 296 | |
| 297 | int rx_world_verify_crumbs(RxWorld *w, uint64_t *out_checked) { |
| 298 | pthread_mutex_lock(&w->mu); |
| 299 | int rc = 0; |
| 300 | uint64_t n = 0; |
| 301 | for (uint64_t i = 0; i < w->n_crumbs; i++) { |
| 302 | const RxCrumb *k = &w->crumbs[i]; |
| 303 | uint8_t d[32]; |
| 304 | if (k->id != i + 1) { rc = -1; break; } |
| 305 | for (uint32_t p = 0; p < k->n_parents; p++) |
| 306 | if (k->parents[p] == 0 || k->parents[p] >= k->id) { rc = -2; break; } |
| 307 | if (rc) break; |
| 308 | crumb_hash(w, k, d); |
| 309 | if (memcmp(d, k->digest, 32) != 0) { rc = -3; break; } |
| 310 | uint64_t ep = k->kind == RX_CRUMB_EXTERNAL ? k->id |
| 311 | : k->wake_cause >= 1 && k->wake_cause < k->id |
| 312 | ? w->crumbs[k->wake_cause - 1].episode : 0; |
| 313 | if (k->episode != ep) { rc = -4; break; } |
| 314 | n++; |
| 315 | } |
| 316 | pthread_mutex_unlock(&w->mu); |
| 317 | if (out_checked) *out_checked = n; |
| 318 | return rc; |
| 319 | } |
| 320 | |
| 321 | /* ---- wakeups and admission ---------------------------------------------- */ |
| 322 | |
| 323 | static bool cause_is_external(const RxWorld *w, uint64_t cause) { |
| 324 | if (cause == 0 || cause > w->n_crumbs) return false; |
| 325 | return w->crumbs[cause - 1].kind == RX_CRUMB_EXTERNAL; |
| 326 | } |
| 327 | |
| 328 | static bool res_fits(const RxWorld *w, const RxReaction *r) { |
| 329 | const RxResourceNeed *n = &r->desc.need; |
| 330 | uint64_t used[4] = { w->used_slots, w->used_memory, w->used_energy, 0 }; |
| 331 | uint64_t budget[6] = { |
| 332 | w->budget.slots, w->budget.memory_bytes, w->budget.energy_budget, |
| 333 | w->budget.offered_locality, w->budget.offered_accel, w->budget.compute_mask |
| 334 | }; |
| 335 | uint64_t need[5] = { |
| 336 | n->memory_bytes, n->energy_cost, n->locality, |
| 337 | n->accelerator_features, n->compute_class |
| 338 | }; |
| 339 | uint64_t res = 0; |
| 340 | if (omega2_rx_world_res_fits(&res, used, 4, budget, 6, need, 5) != OMEGA_OK) |
| 341 | return false; |
| 342 | return res != 0; |
| 343 | } |
| 344 | |
| 345 | static void enqueue(RxWorld *w, uint32_t rid) { |
| 346 | uint32_t p = w->reactions[rid].desc.priority; |
| 347 | if (p >= RX_PRIORITY_CLASSES) p = RX_PRIO_BACKGROUND; |
| 348 | if (w->ready_len[p] >= RX_MAX_REACTIONS) { |
| 349 | w->stats.suppressed_wakes++; |
| 350 | return; |
| 351 | } |
| 352 | uint32_t tail = (w->ready_head[p] + w->ready_len[p]) % RX_MAX_REACTIONS; |
| 353 | w->ready_q[p][tail] = rid; |
| 354 | w->ready_len[p]++; |
| 355 | w->stats.ready_inserts++; |
| 356 | if (w->timing) w->reactions[rid].t_ready = now_ns(); |
| 357 | w->in_flight++; |
| 358 | pthread_cond_signal(&w->work_cv); |
| 359 | } |
| 360 | |
| 361 | static void gauge_blocked(RxWorld *w) { |
| 362 | uint32_t n = 0; |
| 363 | for (uint32_t i = 0; i < w->n_reactions; i++) |
| 364 | if (w->reactions[i].state == RX_BLOCKED_RESOURCE) n++; |
| 365 | if (n > w->peak_blocked) w->peak_blocked = n; |
| 366 | } |
| 367 | |
| 368 | static int better_admit(const RxReaction *a, const RxReaction *b) { |
| 369 | uint64_t pa[3] = { a->desc.priority, a->wait_seq, a->service }; |
| 370 | uint64_t pb[3] = { b->desc.priority, b->wait_seq, b->service }; |
| 371 | uint64_t res = 0; |
| 372 | if (omega2_rx_world_better_admit(&res, pa, 3, pb, 3) != OMEGA_OK) return 0; |
| 373 | return res != 0; |
| 374 | } |
| 375 | |
| 376 | static void charge(RxWorld *w, RxReaction *r) { |
| 377 | r->holding = true; |
| 378 | r->memory_held = r->desc.need.memory_bytes; |
| 379 | r->energy_held = r->desc.need.energy_cost; |
| 380 | w->used_slots++; |
| 381 | w->used_memory += r->memory_held; |
| 382 | w->used_energy += r->energy_held; |
| 383 | r->service++; |
| 384 | if (w->used_slots > w->peak_slots) w->peak_slots = w->used_slots; |
| 385 | if (r->desc.need.deadline && w->budget.logical_tick > r->desc.need.deadline) |
| 386 | w->stats.deadline_overdue++; |
| 387 | } |
| 388 | |
| 389 | static void uncharge(RxWorld *w, RxReaction *r) { |
| 390 | if (!r->holding) return; |
| 391 | if (w->used_slots) w->used_slots--; |
| 392 | if (w->used_memory >= r->memory_held) w->used_memory -= r->memory_held; |
| 393 | else w->used_memory = 0; |
| 394 | if (w->used_energy >= r->energy_held) w->used_energy -= r->energy_held; |
| 395 | else w->used_energy = 0; |
| 396 | r->holding = false; |
| 397 | r->memory_held = 0; |
| 398 | r->energy_held = 0; |
| 399 | } |
| 400 | |
| 401 | static void admit_one(RxWorld *w, uint32_t rid) { |
| 402 | RxReaction *r = &w->reactions[rid]; |
| 403 | if (r->state != RX_BLOCKED_RESOURCE || !res_fits(w, r)) return; |
| 404 | set_state(w, r, RX_READY); |
| 405 | charge(w, r); |
| 406 | enqueue(w, rid); |
| 407 | } |
| 408 | |
| 409 | static bool waiting_fit(const RxReaction *r, const RxWorld *w) { |
| 410 | return r->state == RX_BLOCKED_RESOURCE && !r->quarantined && !r->parked && res_fits(w, r); |
| 411 | } |
| 412 | |
| 413 | static bool class_blocked(const RxWorld *w, uint32_t prio) { |
| 414 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 415 | const RxReaction *r = &w->reactions[i]; |
| 416 | if (r->desc.priority != prio || r->quarantined || r->parked) continue; |
| 417 | if (r->state == RX_BLOCKED_RESOURCE) return true; |
| 418 | } |
| 419 | return false; |
| 420 | } |
| 421 | |
| 422 | static int best_waiting(const RxWorld *w, int only_class) { |
| 423 | int best = -1; |
| 424 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 425 | const RxReaction *r = &w->reactions[i]; |
| 426 | if (only_class >= 0 && r->desc.priority != (uint32_t)only_class) continue; |
| 427 | if (!waiting_fit(r, w)) continue; |
| 428 | if (best < 0 || better_admit(r, &w->reactions[best])) best = (int)i; |
| 429 | } |
| 430 | return best; |
| 431 | } |
| 432 | |
| 433 | /* Higher class wins. After starvation_bound admissions of something more |
| 434 | * urgent, the highest class that has been waiting that long is served once. |
| 435 | * Every class is protected, not only the lowest one. Adapted from the AIENOS |
| 436 | * run queue's bounded background interval. */ |
| 437 | static int pick_admit(RxWorld *w) { |
| 438 | uint32_t bound = w->budget.starvation_bound; |
| 439 | int chosen = -1; |
| 440 | if (bound) { |
| 441 | for (uint32_t p = 0; p < RX_PRIORITY_CLASSES; p++) { |
| 442 | if (!class_blocked(w, p) || w->admit_debt[p] < bound) continue; |
| 443 | chosen = best_waiting(w, (int)p); |
| 444 | if (chosen >= 0) break; |
| 445 | } |
| 446 | } |
| 447 | if (chosen < 0) chosen = best_waiting(w, -1); |
| 448 | if (chosen < 0) return -1; |
| 449 | uint32_t served = w->reactions[chosen].desc.priority; |
| 450 | w->admit_debt[served] = 0; |
| 451 | if (bound) { |
| 452 | for (uint32_t p = served + 1; p < RX_PRIORITY_CLASSES; p++) { |
| 453 | if (!class_blocked(w, p)) w->admit_debt[p] = 0; |
| 454 | else if (w->admit_debt[p] < UINT32_MAX) w->admit_debt[p]++; |
| 455 | } |
| 456 | } |
| 457 | return chosen; |
| 458 | } |
| 459 | |
| 460 | static void try_admit(RxWorld *w) { |
| 461 | for (;;) { |
| 462 | int id = pick_admit(w); |
| 463 | if (id < 0) break; |
| 464 | admit_one(w, (uint32_t)id); |
| 465 | } |
| 466 | gauge_blocked(w); |
| 467 | } |
| 468 | |
| 469 | static void demand_inner(RxWorld *w, uint32_t rid, uint64_t cause); |
| 470 | |
| 471 | static void demand(RxWorld *w, uint32_t rid, uint64_t cause) { |
| 472 | if (!w->timing) { demand_inner(w, rid, cause); return; } |
| 473 | RxReaction *r = &w->reactions[rid]; |
| 474 | uint64_t c0 = thread_cpu_ns(); |
| 475 | uint64_t t0 = now_ns(); |
| 476 | RxState before = r->state; |
| 477 | bool outer = w->sched_nest++ == 0; |
| 478 | demand_inner(w, rid, cause); |
| 479 | w->sched_nest--; |
| 480 | uint64_t t1 = now_ns(); |
| 481 | uint64_t c1 = thread_cpu_ns(); |
| 482 | if (outer) { |
| 483 | w->stats.sched_wall_ns += t1 - t0; |
| 484 | w->stats.sched_cpu_ns += c1 - c0; |
| 485 | } |
| 486 | if (before == RX_DORMANT && r->state != RX_DORMANT) { |
| 487 | r->t_demand = t0; |
| 488 | r->sched_ns = t1 - t0; |
| 489 | r->sched_cpu_ns = c1 - c0; |
| 490 | } else { |
| 491 | r->sched_ns += t1 - t0; |
| 492 | r->sched_cpu_ns += c1 - c0; |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | static void demand_inner(RxWorld *w, uint32_t rid, uint64_t cause) { |
| 497 | RxReaction *r = &w->reactions[rid]; |
| 498 | if (r->removed) return; /* rx_world_remove_reaction: never woken again */ |
| 499 | w->stats.wakes++; |
| 500 | if (r->quarantined && !cause_is_external(w, cause)) { |
| 501 | r->suppressed++; |
| 502 | w->stats.suppressed_wakes++; |
| 503 | return; |
| 504 | } |
| 505 | if (cause_is_external(w, cause)) { |
| 506 | r->quarantined = false; |
| 507 | r->parked = false; |
| 508 | r->yield_left = 0; |
| 509 | r->osc_streak = 0; |
| 510 | r->noop_streak = 0; |
| 511 | r->conflict_streak = 0; |
| 512 | r->episode_activations = 0; |
| 513 | } |
| 514 | /* The budget is per causal episode: everything one outside publication |
| 515 | * set off, however far down the chain this reaction sits. */ |
| 516 | uint64_t ep = cause >= 1 && cause <= w->n_crumbs ? w->crumbs[cause - 1].episode : 0; |
| 517 | if (ep && ep != r->episode) { |
| 518 | r->episode = ep; |
| 519 | r->episode_activations = 0; |
| 520 | } |
| 521 | r->parked = false; |
| 522 | if (w->stability.activation_budget && |
| 523 | r->episode_activations >= w->stability.activation_budget) { |
| 524 | if (!r->quarantined) { |
| 525 | r->quarantined = true; |
| 526 | w->stats.quarantines++; |
| 527 | contain(w, rid, RX_CONTAIN_BUDGET, cause); |
| 528 | } |
| 529 | r->suppressed++; |
| 530 | w->stats.suppressed_wakes++; |
| 531 | return; |
| 532 | } |
| 533 | /* Sequential reference: the orchestrator decides what runs. A wake that |
| 534 | * reaches here (a re-arm after invalidation) is a debt it will see. */ |
| 535 | if (w->sequential) { |
| 536 | r->wake_cause = cause; |
| 537 | r->seq_pending = true; |
| 538 | return; |
| 539 | } |
| 540 | switch (r->state) { |
| 541 | case RX_DORMANT: |
| 542 | w->stats.wakes_accepted++; |
| 543 | set_state(w, r, RX_BLOCKED_RESOURCE); |
| 544 | r->wake_cause = cause; |
| 545 | r->coalesced = 0; |
| 546 | r->wait_seq = ++w->admit_seq; |
| 547 | w->stats.blocked_resource++; |
| 548 | try_admit(w); |
| 549 | break; |
| 550 | case RX_BLOCKED_RESOURCE: |
| 551 | r->wake_cause = cause; |
| 552 | r->coalesced++; |
| 553 | w->stats.coalesced_wakes++; |
| 554 | break; |
| 555 | case RX_READY: |
| 556 | r->wake_cause = cause; |
| 557 | r->coalesced++; |
| 558 | w->stats.coalesced_wakes++; |
| 559 | break; |
| 560 | default: |
| 561 | r->wake_cause = cause; |
| 562 | r->rearm = true; |
| 563 | w->stats.coalesced_wakes++; |
| 564 | break; |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | /* Fan-out limits bound one propagation wave, not semantic delivery. Excess |
| 569 | * dependents are queued and released in later waves. Allocation failure falls |
| 570 | * back to immediate demand so a valid dependency change is never dropped. */ |
| 571 | static int defer_wake(RxWorld *w, uint32_t rid, uint64_t cause) { |
| 572 | if (w->deferred_head + w->deferred_len >= w->deferred_cap) { |
| 573 | if (w->deferred_head && w->deferred_len) { |
| 574 | memmove(w->deferred, w->deferred + w->deferred_head, |
| 575 | w->deferred_len * sizeof(*w->deferred)); |
| 576 | w->deferred_head = 0; |
| 577 | } |
| 578 | if (w->deferred_len >= w->deferred_cap) { |
| 579 | uint32_t next = w->deferred_cap ? w->deferred_cap * 2u : RX_DEFERRED_INITIAL; |
| 580 | if (next < w->deferred_cap) return -1; |
| 581 | void *p = realloc(w->deferred, (size_t)next * sizeof(*w->deferred)); |
| 582 | if (!p) return -1; |
| 583 | w->deferred = p; |
| 584 | w->deferred_cap = next; |
| 585 | } |
| 586 | } |
| 587 | uint32_t at = w->deferred_head + w->deferred_len++; |
| 588 | w->deferred[at].reaction = rid; |
| 589 | w->deferred[at].cause = cause; |
| 590 | w->stats.deferred_wakes++; |
| 591 | if (w->deferred_len > w->stats.deferred_peak) |
| 592 | w->stats.deferred_peak = w->deferred_len; |
| 593 | return 0; |
| 594 | } |
| 595 | |
| 596 | static void drain_deferred(RxWorld *w, uint32_t quota) { |
| 597 | if (quota == 0) return; |
| 598 | for (;;) { |
| 599 | uint32_t left = quota; |
| 600 | while (left && w->deferred_len) { |
| 601 | uint32_t rid = w->deferred[w->deferred_head].reaction; |
| 602 | uint64_t cause = w->deferred[w->deferred_head].cause; |
| 603 | w->deferred_head++; |
| 604 | w->deferred_len--; |
| 605 | if (w->deferred_len == 0) w->deferred_head = 0; |
| 606 | demand(w, rid, cause); |
| 607 | left--; |
| 608 | } |
| 609 | /* If a wave produced runnable work, let that work make progress before |
| 610 | * releasing another wave. If every wake was suppressed or merely |
| 611 | * parked on an unavailable resource, nothing else can drain the queue, |
| 612 | * so continue here until the queue is empty. */ |
| 613 | if (w->in_flight != 0 || w->deferred_len == 0) break; |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | static int prio_less(const RxWorld *w, uint32_t a, uint32_t b) { |
| 618 | uint32_t pa = w->reactions[a].desc.priority; |
| 619 | uint32_t pb = w->reactions[b].desc.priority; |
| 620 | if (pa != pb) return pa < pb; |
| 621 | return a < b; |
| 622 | } |
| 623 | |
| 624 | /* Only the subscribers of this object, filtered by field mask and generation. |
| 625 | * Fanout above the configured limit is deferred, highest priority first. |
| 626 | * Limiting wake concurrency must never make a valid dependent miss a change. */ |
| 627 | static void propagate_inner(RxWorld *w, uint32_t obj, uint64_t changed, uint64_t cause); |
| 628 | |
| 629 | static void propagate(RxWorld *w, uint32_t obj, uint64_t changed, uint64_t cause) { |
| 630 | /* The sequential reference polls readiness instead of being told. */ |
| 631 | if (w->sequential) return; |
| 632 | if (!w->timing) { propagate_inner(w, obj, changed, cause); return; } |
| 633 | RxStats s0 = w->stats; |
| 634 | uint64_t c0 = thread_cpu_ns(); |
| 635 | uint64_t t0 = now_ns(); |
| 636 | propagate_inner(w, obj, changed, cause); |
| 637 | uint64_t t1 = now_ns(); |
| 638 | uint64_t c1 = thread_cpu_ns(); |
| 639 | const RxStats *s1 = &w->stats; |
| 640 | RxPropWave *p = &w->last_prop; |
| 641 | p->wall_ns = t1 - t0; |
| 642 | p->cpu_ns = c1 - c0; |
| 643 | p->inspected = s1->subscriptions_checked - s0.subscriptions_checked; |
| 644 | p->matched = s1->subscriptions_matched - s0.subscriptions_matched; |
| 645 | p->wake_attempts = s1->wakes - s0.wakes; |
| 646 | p->wakes_accepted = s1->wakes_accepted - s0.wakes_accepted; |
| 647 | p->ready_inserts = s1->ready_inserts - s0.ready_inserts; |
| 648 | p->coalesced = s1->coalesced_wakes - s0.coalesced_wakes; |
| 649 | p->deferred = s1->deferred_wakes - s0.deferred_wakes; |
| 650 | p->suppressed = s1->suppressed_wakes - s0.suppressed_wakes; |
| 651 | } |
| 652 | |
| 653 | static void propagate_inner(RxWorld *w, uint32_t obj, uint64_t changed, uint64_t cause) { |
| 654 | if (!w->objects[obj].live) return; |
| 655 | uint32_t gen = w->objects[obj].generation; |
| 656 | uint32_t hits[RX_MAX_REACTIONS]; |
| 657 | uint32_t nh = 0; |
| 658 | for (uint32_t i = 0; i < w->n_subs[obj]; i++) { |
| 659 | const RxSub *s = &w->subs[obj][i]; |
| 660 | w->stats.subscriptions_checked++; |
| 661 | if (s->generation != gen) continue; |
| 662 | if (!(s->mask & changed)) continue; |
| 663 | w->stats.subscriptions_matched++; |
| 664 | if (nh < RX_MAX_REACTIONS) hits[nh++] = s->reaction; |
| 665 | } |
| 666 | for (uint32_t i = 1; i < nh; i++) { |
| 667 | uint32_t v = hits[i]; |
| 668 | uint32_t j = i; |
| 669 | while (j > 0 && prio_less(w, v, hits[j - 1])) { |
| 670 | hits[j] = hits[j - 1]; |
| 671 | j--; |
| 672 | } |
| 673 | hits[j] = v; |
| 674 | } |
| 675 | uint32_t allow = nh; |
| 676 | if (w->stability.fanout_limit && allow > w->stability.fanout_limit) |
| 677 | allow = w->stability.fanout_limit; |
| 678 | for (uint32_t i = 0; i < allow; i++) demand(w, hits[i], cause); |
| 679 | for (uint32_t i = allow; i < nh; i++) { |
| 680 | if (defer_wake(w, hits[i], cause) != 0) |
| 681 | demand(w, hits[i], cause); |
| 682 | } |
| 683 | if (w->in_flight == 0 && w->deferred_len) { |
| 684 | uint32_t quota = w->stability.fanout_limit ? w->stability.fanout_limit : w->deferred_len; |
| 685 | drain_deferred(w, quota); |
| 686 | } |
| 687 | } |
| 688 | |
| 689 | static bool pop_ready(RxWorld *w, uint32_t *rid) { |
| 690 | int high = -1; |
| 691 | for (uint32_t p = 0; p < RX_PRIORITY_CLASSES; p++) { |
| 692 | if (w->ready_len[p] == 0) w->run_debt[p] = 0; |
| 693 | else if (high < 0) high = (int)p; |
| 694 | } |
| 695 | if (high < 0) return false; |
| 696 | uint32_t chosen = (uint32_t)high; |
| 697 | uint32_t bound = w->budget.starvation_bound; |
| 698 | if (bound) { |
| 699 | for (uint32_t p = chosen + 1; p < RX_PRIORITY_CLASSES; p++) { |
| 700 | if (w->ready_len[p] && w->run_debt[p] >= bound) { |
| 701 | chosen = p; |
| 702 | break; |
| 703 | } |
| 704 | } |
| 705 | } |
| 706 | *rid = w->ready_q[chosen][w->ready_head[chosen]]; |
| 707 | w->ready_head[chosen] = (w->ready_head[chosen] + 1) % RX_MAX_REACTIONS; |
| 708 | w->ready_len[chosen]--; |
| 709 | w->run_debt[chosen] = 0; |
| 710 | if (bound) { |
| 711 | for (uint32_t p = chosen + 1; p < RX_PRIORITY_CLASSES; p++) |
| 712 | if (w->ready_len[p] && w->run_debt[p] < UINT32_MAX) w->run_debt[p]++; |
| 713 | } |
| 714 | return true; |
| 715 | } |
| 716 | |
| 717 | /* ---- validation --------------------------------------------------------- */ |
| 718 | |
| 719 | static bool ref_live(const RxWorld *w, RxObjRef ref) { |
| 720 | return ref.id < RX_MAX_OBJECTS && w->objects[ref.id].live && |
| 721 | w->objects[ref.id].generation == ref.generation; |
| 722 | } |
| 723 | |
| 724 | int rx_world_validate_cap(const RxWorld *w, RxCapRef ref, uint32_t subject, |
| 725 | uint64_t resource, uint32_t rights, RxCapEntry *out) { |
| 726 | if (!w) return RX_CAP_ERR_STATE; |
| 727 | if (w->auth_validate) return w->auth_validate(w->auth_ctx, ref, subject, resource, rights, out); |
| 728 | if (!w->root) return RX_CAP_ERR_STATE; |
| 729 | return rx_caproot_validate(w->root, ref, subject, resource, rights, out); |
| 730 | } |
| 731 | |
| 732 | int rx_world_inspect_cap(const RxWorld *w, RxCapRef ref, RxCapEntry *out) { |
| 733 | if (!w) return RX_CAP_ERR_STATE; |
| 734 | if (w->auth_inspect) return w->auth_inspect(w->auth_ctx, ref, out); |
| 735 | if (!w->root) return RX_CAP_ERR_STATE; |
| 736 | return rx_caproot_inspect(w->root, ref, out); |
| 737 | } |
| 738 | |
| 739 | /* The reference a reaction presents for caps[i]. Caller holds the world lock. */ |
| 740 | static RxCapRef need_ref(const RxWorld *w, const RxReactionDesc *d, uint32_t i) { |
| 741 | if (!d->cap_slotted[i]) return d->caps[i].ref; |
| 742 | RxObjRef s = d->cap_slot[i]; |
| 743 | if (s.id >= RX_MAX_OBJECTS) return (RxCapRef){ UINT32_MAX, 0 }; |
| 744 | const RxObject *o = &w->objects[s.id]; |
| 745 | if (!o->live || o->generation != s.generation) return (RxCapRef){ UINT32_MAX, 0 }; |
| 746 | if (o->field[0] > UINT32_MAX) return (RxCapRef){ UINT32_MAX, 0 }; |
| 747 | return (RxCapRef){ (uint32_t)o->field[0], o->field[1] }; |
| 748 | } |
| 749 | |
| 750 | /* ---- R16 C5 caller credentials (rx_caller.h) ------------------------------ */ |
| 751 | |
| 752 | static void caller_digest(uint32_t subject, uint64_t generation, const uint8_t *secret, |
| 753 | uint8_t out[32]) { |
| 754 | sha256_ctx c; |
| 755 | sha256_init(&c); |
| 756 | sha256_update(&c, (const uint8_t *)"AIEN_RX_CALLER_V1", 17); |
| 757 | put32(&c, subject); |
| 758 | put64(&c, generation); |
| 759 | sha256_update(&c, secret, RX_CALLER_SECRET_LEN); |
| 760 | sha256_final(&c, out); |
| 761 | } |
| 762 | |
| 763 | /* Caller holds callers_mu. */ |
| 764 | static int caller_slot(const RxWorld *w, uint32_t subject) { |
| 765 | for (uint32_t i = 0; i < w->n_callers; i++) |
| 766 | if (w->callers[i].subject == subject) return (int)i; |
| 767 | return -1; |
| 768 | } |
| 769 | |
| 770 | /* Full check of a presented credential. Caller holds callers_mu. */ |
| 771 | static int caller_check_locked(const RxWorld *w, uint32_t subject, const RxCallerCred *cred) { |
| 772 | if (!cred || cred->generation == 0) return RX_CALLER_ERR_ABSENT; |
| 773 | int s = caller_slot(w, subject); |
| 774 | if (s < 0) return RX_CALLER_ERR_UNKNOWN; |
| 775 | if (!w->callers[s].live) return RX_CALLER_ERR_REVOKED; |
| 776 | if (cred->generation != w->callers[s].generation) return RX_CALLER_ERR_STALE; |
| 777 | uint8_t d[32]; |
| 778 | caller_digest(subject, cred->generation, cred->secret, d); |
| 779 | uint8_t diff = 0; |
| 780 | for (int i = 0; i < 32; i++) diff |= (uint8_t)(d[i] ^ w->callers[s].digest[i]); |
| 781 | return diff ? RX_CALLER_ERR_FORGED : RX_CALLER_OK; |
| 782 | } |
| 783 | |
| 784 | /* The enrollment a registered reaction was admitted under is still live at |
| 785 | * the same generation (its secret was checked at registration and is not |
| 786 | * kept). Caller holds mu. */ |
| 787 | static int caller_still_live(const RxWorld *w, uint32_t subject, uint64_t generation) { |
| 788 | RxWorld *mw = (RxWorld *)w; |
| 789 | pthread_mutex_lock(&mw->callers_mu); |
| 790 | int s = caller_slot(w, subject); |
| 791 | int rc = s < 0 ? RX_CALLER_ERR_UNKNOWN |
| 792 | : !w->callers[s].live ? RX_CALLER_ERR_REVOKED |
| 793 | : w->callers[s].generation != generation ? RX_CALLER_ERR_STALE : RX_CALLER_OK; |
| 794 | pthread_mutex_unlock(&mw->callers_mu); |
| 795 | return rc; |
| 796 | } |
| 797 | |
| 798 | int rx_world_enroll_caller(RxWorld *w, uint32_t subject, RxCallerCred *out) { |
| 799 | if (!w || !out) return RX_ERR_ARG; |
| 800 | memset(out, 0, sizeof *out); |
| 801 | pthread_mutex_lock(&w->callers_mu); |
| 802 | int rc = RX_CALLER_OK; |
| 803 | if (w->callers_bound) { rc = RX_CALLER_ERR_CLOSED; goto out; } |
| 804 | if (caller_slot(w, subject) >= 0) { rc = RX_CALLER_ERR_EXISTS; goto out; } |
| 805 | if (w->n_callers >= RX_CALLER_MAX) { rc = RX_CALLER_ERR_FULL; goto out; } |
| 806 | uint8_t secret[RX_CALLER_SECRET_LEN]; |
| 807 | size_t n = 0; |
| 808 | while (n < sizeof secret) { |
| 809 | ssize_t g = getrandom(secret + n, sizeof secret - n, 0); |
| 810 | if (g < 0) { |
| 811 | if (errno == EINTR) continue; |
| 812 | rc = RX_CALLER_ERR_ENTROPY; |
| 813 | goto out; |
| 814 | } |
| 815 | n += (size_t)g; |
| 816 | } |
| 817 | uint32_t s = w->n_callers++; |
| 818 | w->callers[s].subject = subject; |
| 819 | w->callers[s].live = true; |
| 820 | w->callers[s].generation = ++w->caller_generation; |
| 821 | caller_digest(subject, w->callers[s].generation, secret, w->callers[s].digest); |
| 822 | out->generation = w->callers[s].generation; |
| 823 | memcpy(out->secret, secret, sizeof secret); |
| 824 | for (size_t i = 0; i < sizeof secret; i++) ((volatile uint8_t *)secret)[i] = 0; |
| 825 | out: |
| 826 | pthread_mutex_unlock(&w->callers_mu); |
| 827 | return rc; |
| 828 | } |
| 829 | |
| 830 | int rx_world_bind_callers(RxWorld *w) { |
| 831 | if (!w) return RX_ERR_ARG; |
| 832 | pthread_mutex_lock(&w->mu); |
| 833 | int rc = RX_OK; |
| 834 | /* R16 C7: a reaction admitted without a credential while the world was |
| 835 | * unbound would run in the bound world under a subject nobody proved. |
| 836 | * Refuse, and leave the world unbound. */ |
| 837 | for (uint32_t i = 0; i < w->n_reactions; i++) |
| 838 | if (!w->reactions[i].removed && w->reactions[i].desc.caller.generation == 0) |
| 839 | rc = RX_ERR_IDENTITY; |
| 840 | if (rc == RX_OK) { |
| 841 | pthread_mutex_lock(&w->callers_mu); |
| 842 | w->callers_bound = true; |
| 843 | pthread_mutex_unlock(&w->callers_mu); |
| 844 | } |
| 845 | pthread_mutex_unlock(&w->mu); |
| 846 | return rc; |
| 847 | } |
| 848 | |
| 849 | int rx_world_revoke_caller(RxWorld *w, uint32_t subject, const RxCallerCred *cred) { |
| 850 | if (!w) return RX_ERR_ARG; |
| 851 | /* R16 C7: the world lock first (the order every path uses: mu, then |
| 852 | * callers_mu). A commit and a seat completion hold mu from their identity |
| 853 | * check to their publish, so a revocation precedes the check or follows |
| 854 | * the publish, never lands between them. Never call with mu held. */ |
| 855 | const int serialize = 1; |
| 856 | if (serialize) pthread_mutex_lock(&w->mu); |
| 857 | pthread_mutex_lock(&w->callers_mu); |
| 858 | int rc = caller_check_locked(w, subject, cred); |
| 859 | if (rc == RX_CALLER_OK) { |
| 860 | int s = caller_slot(w, subject); |
| 861 | w->callers[s].live = false; |
| 862 | memset(w->callers[s].digest, 0, sizeof w->callers[s].digest); |
| 863 | } |
| 864 | pthread_mutex_unlock(&w->callers_mu); |
| 865 | if (serialize) pthread_mutex_unlock(&w->mu); |
| 866 | return rc; |
| 867 | } |
| 868 | |
| 869 | int rx_world_check_caller(RxWorld *w, uint32_t subject, const RxCallerCred *cred) { |
| 870 | if (!w) return RX_ERR_ARG; |
| 871 | pthread_mutex_lock(&w->callers_mu); |
| 872 | int rc = caller_check_locked(w, subject, cred); |
| 873 | pthread_mutex_unlock(&w->callers_mu); |
| 874 | return rc; |
| 875 | } |
| 876 | |
| 877 | int rx_world_caller_check_fn(void *world, uint32_t subject, const RxCallerCred *cred, int op) { |
| 878 | RxWorld *w = world; |
| 879 | if (!w) return RX_ERR_ARG; |
| 880 | if (op == RX_CALLER_OP_RELEASE) { |
| 881 | pthread_mutex_unlock(&w->callers_mu); |
| 882 | return RX_CALLER_OK; |
| 883 | } |
| 884 | pthread_mutex_lock(&w->callers_mu); |
| 885 | /* R16 G6: under an operator stop a bound generation store neither |
| 886 | * proposes nor promotes. halted is written under callers_mu too. */ |
| 887 | if (w->halted) { |
| 888 | pthread_mutex_unlock(&w->callers_mu); |
| 889 | return RX_CALLER_ERR_HALTED; |
| 890 | } |
| 891 | int rc = caller_check_locked(w, subject, cred); |
| 892 | /* HOLD: a pass keeps the table locked until RELEASE (no revocation). */ |
| 893 | if (op != RX_CALLER_OP_HOLD || rc != RX_CALLER_OK) pthread_mutex_unlock(&w->callers_mu); |
| 894 | return rc; |
| 895 | } |
| 896 | |
| 897 | /* ---- R16 G6 operator emergency stop (spec/r16-operator-emergency-stop.md) ---- */ |
| 898 | |
| 899 | static void stamp_cap(RxWorld *w, RxCrumb *k, uint32_t i, RxCapRef ref); |
| 900 | |
| 901 | static uint64_t realtime_ns(void) { |
| 902 | struct timespec ts; |
| 903 | clock_gettime(CLOCK_REALTIME, &ts); |
| 904 | return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec; |
| 905 | } |
| 906 | |
| 907 | /* Caller holds mu and callers_mu. The credential, then the subject (no |
| 908 | * reaction ever added to this world runs under it), then the capability. */ |
| 909 | static int halt_authorize(RxWorld *w, uint32_t subject, const RxCallerCred *cred, RxCapRef cap) { |
| 910 | if (caller_check_locked(w, subject, cred) != RX_CALLER_OK) return RX_ERR_IDENTITY; |
| 911 | for (uint32_t i = 0; i < w->n_reactions; i++) |
| 912 | if (w->reactions[i].desc.subject == subject) return RX_ERR_AUTHORITY; |
| 913 | if (rx_world_validate_cap(w, cap, subject, RX_WORLD_RES_CONTROL, RX_WORLD_RIGHT_HALT, NULL) |
| 914 | != RX_CAP_OK) |
| 915 | return RX_ERR_AUTHORITY; |
| 916 | return RX_OK; |
| 917 | } |
| 918 | |
| 919 | /* The mark's text: fixed lines, then "sha256 <hex>" over every byte before it. */ |
| 920 | static int halt_record(const RxHaltStatus *h, char *buf, size_t cap) { |
| 921 | int n = snprintf(buf, cap, |
| 922 | "aien-operator-halt v1\nseq %llu\nsubject %u\ncap %u %llu\nreason %d\n" |
| 923 | "t_ns %llu\ncrumb %llu\n", |
| 924 | (unsigned long long)h->seq, h->subject, h->cap.cap_id, |
| 925 | (unsigned long long)h->cap.generation, |
| 926 | (int)h->reason, (unsigned long long)h->t_ns, (unsigned long long)h->crumb); |
| 927 | return n > 0 && (size_t)n < cap ? n : -1; |
| 928 | } |
| 929 | |
| 930 | static int seal_append(char *buf, size_t len, size_t cap) { |
| 931 | uint8_t d[32]; |
| 932 | sha256_ctx c; |
| 933 | sha256_init(&c); |
| 934 | sha256_update(&c, (const uint8_t *)buf, len); |
| 935 | sha256_final(&c, d); |
| 936 | if (len + 8 + 64 + 2 > cap) return -1; |
| 937 | memcpy(buf + len, "sha256 ", 7); |
| 938 | for (int i = 0; i < 32; i++) snprintf(buf + len + 7 + 2 * i, 3, "%02x", d[i]); |
| 939 | buf[len + 71] = '\n'; |
| 940 | buf[len + 72] = 0; |
| 941 | return (int)len + 72; |
| 942 | } |
| 943 | |
| 944 | static int fsync_dir(const char *dir) { |
| 945 | int fd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC); |
| 946 | if (fd < 0) return -errno; |
| 947 | int rc = fsync(fd) == 0 ? 0 : -errno; |
| 948 | close(fd); |
| 949 | return rc; |
| 950 | } |
| 951 | |
| 952 | /* Write `buf` to dir/name durably (temporary file, fsync, rename, fsync dir). |
| 953 | * With excl, an existing dir/name is never replaced (link, not rename). The |
| 954 | * name is one checked component (src/omega_path_check.h, no '/'); dir is |
| 955 | * w->halt_dir, checked when it was set. */ |
| 956 | static int durable_write(const char *dir, const char *name, const char *buf, size_t len, bool excl) { |
| 957 | char nm[160], tmp[512], dst[512]; |
| 958 | if (omega_path_copy(nm, sizeof nm, name) != 0 || strchr(nm, '/') || strcmp(nm, ".") == 0) |
| 959 | return -EINVAL; |
| 960 | if (snprintf(tmp, sizeof tmp, "%s/%s.partial", dir, nm) >= (int)sizeof tmp || |
| 961 | snprintf(dst, sizeof dst, "%s/%s", dir, nm) >= (int)sizeof dst) |
| 962 | return -ENAMETOOLONG; |
| 963 | int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); |
| 964 | if (fd < 0) return -errno; |
| 965 | size_t off = 0; |
| 966 | while (off < len) { |
| 967 | ssize_t n = write(fd, buf + off, len - off); |
| 968 | if (n < 0 && errno == EINTR) continue; |
| 969 | if (n <= 0) { int e = n < 0 ? errno : EIO; close(fd); unlink(tmp); return -e; } |
| 970 | off += (size_t)n; |
| 971 | } |
| 972 | if (fsync(fd) != 0) { int e = errno; close(fd); unlink(tmp); return -e; } |
| 973 | close(fd); |
| 974 | if (excl) { |
| 975 | if (link(tmp, dst) != 0) { int e = errno; unlink(tmp); return -e; } |
| 976 | unlink(tmp); |
| 977 | } else if (rename(tmp, dst) != 0) { |
| 978 | int e = errno; unlink(tmp); return -e; |
| 979 | } |
| 980 | return fsync_dir(dir); |
| 981 | } |
| 982 | |
| 983 | static int halt_mark_write(const RxWorld *w) { |
| 984 | if (!w->halt_dir[0]) return 0; |
| 985 | char buf[512]; |
| 986 | int n = halt_record(&w->halt, buf, sizeof buf); |
| 987 | if (n < 0 || (n = seal_append(buf, (size_t)n, sizeof buf)) < 0) return -EOVERFLOW; |
| 988 | int rc = durable_write(w->halt_dir, RX_GEN_HALT_MARK, buf, (size_t)n, false); |
| 989 | return rc == 0 ? 1 : rc; |
| 990 | } |
| 991 | |
| 992 | /* Read dir/OPERATOR_HALT. 0 absent, 1 read and its seal holds (h filled), |
| 993 | * RX_ERR_TORN present but unreadable as a sealed record, RX_ERR_IO cannot tell. */ |
| 994 | static int halt_mark_read(const char *dir, RxHaltStatus *h, char *raw, size_t cap, size_t *raw_len) { |
| 995 | char path[512]; |
| 996 | if (snprintf(path, sizeof path, "%s/%s", dir, RX_GEN_HALT_MARK) >= (int)sizeof path) |
| 997 | return RX_ERR_IO; |
| 998 | raw[0] = 0; |
| 999 | *raw_len = 0; |
| 1000 | /* Never follow a link or block on a FIFO under the world locks: a mark that |
| 1001 | * is not a regular file is damaged (TORN: the world stays stopped, and resume |
| 1002 | * keeps a record and removes it, so the store is never blocked for good). */ |
| 1003 | int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK); |
| 1004 | if (fd < 0) return errno == ENOENT ? 0 : errno == ELOOP ? RX_ERR_TORN : RX_ERR_IO; |
| 1005 | struct stat st; |
| 1006 | if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) { |
| 1007 | close(fd); |
| 1008 | return RX_ERR_TORN; |
| 1009 | } |
| 1010 | ssize_t n = read(fd, raw, cap - 1); |
| 1011 | close(fd); |
| 1012 | if (n < 0) return RX_ERR_IO; |
| 1013 | raw[n] = 0; |
| 1014 | *raw_len = (size_t)n; |
| 1015 | RxHaltStatus r; |
| 1016 | memset(&r, 0, sizeof r); |
| 1017 | unsigned long long seq, t, crumb, cgen; |
| 1018 | unsigned subject, cid; |
| 1019 | int reason, used = 0; |
| 1020 | if (sscanf(raw, "aien-operator-halt v1\nseq %llu\nsubject %u\ncap %u %llu\nreason %d\n" |
| 1021 | "t_ns %llu\ncrumb %llu\n%n", |
| 1022 | &seq, &subject, &cid, &cgen, &reason, &t, &crumb, &used) != 7 || used <= 0) |
| 1023 | return RX_ERR_TORN; |
| 1024 | char want[600]; |
| 1025 | memcpy(want, raw, (size_t)used); |
| 1026 | if (seal_append(want, (size_t)used, sizeof want) < 0 || strcmp(want, raw) != 0) |
| 1027 | return RX_ERR_TORN; |
| 1028 | r.seq = seq; r.subject = subject; r.cap.cap_id = cid; r.cap.generation = cgen; |
| 1029 | r.reason = reason; r.t_ns = t; r.crumb = crumb; |
| 1030 | *h = r; |
| 1031 | return 1; |
| 1032 | } |
| 1033 | |
| 1034 | static uint64_t halt_crumb(RxWorld *w, RxCrumbKind kind, RxCapRef cap, int32_t reason, |
| 1035 | uint64_t parent) { |
| 1036 | RxCrumb k; |
| 1037 | memset(&k, 0, sizeof k); |
| 1038 | k.kind = kind; |
| 1039 | k.reaction = UINT32_MAX; |
| 1040 | k.faculty = RX_FACULTY_EXTERNAL; |
| 1041 | k.worker = UINT32_MAX; |
| 1042 | k.n_caps = 1; |
| 1043 | stamp_cap(w, &k, 0, cap); |
| 1044 | add_parent(&k, parent); |
| 1045 | k.reason = reason; |
| 1046 | k.t_start_ns = now_ns(); |
| 1047 | k.t_end_ns = k.t_start_ns; |
| 1048 | return crumb_append(w, &k); |
| 1049 | } |
| 1050 | |
| 1051 | int rx_world_set_halt_dir(RxWorld *w, const char *dir) { |
| 1052 | /* Only the checked copy (src/omega_path_check.h) is kept and opened. */ |
| 1053 | char checked[sizeof w->halt_dir]; |
| 1054 | if (!w || omega_path_copy(checked, sizeof checked, dir) != 0) return RX_ERR_ARG; |
| 1055 | pthread_mutex_lock(&w->mu); |
| 1056 | pthread_mutex_lock(&w->callers_mu); |
| 1057 | memcpy(w->halt_dir, checked, strlen(checked) + 1); |
| 1058 | RxHaltStatus h; |
| 1059 | char raw[600]; |
| 1060 | size_t raw_len = 0; |
| 1061 | int rc = halt_mark_read(w->halt_dir, &h, raw, sizeof raw, &raw_len); |
| 1062 | if (rc == 0 && w->halted) { |
| 1063 | w->halt.durable = halt_mark_write(w); /* a stop taken before the directory was set */ |
| 1064 | } else if (rc != 0 && !w->halted) { |
| 1065 | /* A stop outlives the process: the world starts stopped. A mark that |
| 1066 | * cannot be read or verified still stops it (unknown is not "go"). */ |
| 1067 | if (rc != 1) { |
| 1068 | memset(&h, 0, sizeof h); |
| 1069 | h.reason = rc; |
| 1070 | } |
| 1071 | h.halted = true; |
| 1072 | h.restored = true; |
| 1073 | h.durable = 1; |
| 1074 | h.refused = w->halt.refused; |
| 1075 | h.cancelled = w->halt.cancelled; |
| 1076 | h.crumb = halt_crumb(w, RX_CRUMB_OPERATOR_STOP, h.cap, h.reason, 0); |
| 1077 | w->halt = h; |
| 1078 | w->halted = true; |
| 1079 | } |
| 1080 | pthread_mutex_unlock(&w->callers_mu); |
| 1081 | pthread_mutex_unlock(&w->mu); |
| 1082 | return rc; |
| 1083 | } |
| 1084 | |
| 1085 | int rx_world_emergency_stop(RxWorld *w, uint32_t subject, const RxCallerCred *cred, |
| 1086 | RxCapRef cap, int32_t reason, RxHaltStatus *out) { |
| 1087 | if (!w) return RX_ERR_ARG; |
| 1088 | /* mu then callers_mu (R16 C7 order): a commit or seat result holds mu from |
| 1089 | * its checks to its publish, and a promotion holds callers_mu (HOLD) across |
| 1090 | * its flip, so each finishes before the stop or sees it. */ |
| 1091 | pthread_mutex_lock(&w->mu); |
| 1092 | pthread_mutex_lock(&w->callers_mu); |
| 1093 | int rc = halt_authorize(w, subject, cred, cap); |
| 1094 | if (rc == RX_OK && w->halted) rc = RX_HALT_ALREADY; |
| 1095 | if (rc == RX_OK) { |
| 1096 | RxHaltStatus h; |
| 1097 | memset(&h, 0, sizeof h); |
| 1098 | h.halted = true; |
| 1099 | h.seq = w->halt.seq + 1; |
| 1100 | h.subject = subject; |
| 1101 | h.cap = cap; |
| 1102 | h.reason = reason; |
| 1103 | h.t_ns = realtime_ns(); |
| 1104 | h.refused = w->halt.refused; |
| 1105 | h.cancelled = w->halt.cancelled; |
| 1106 | h.crumb = halt_crumb(w, RX_CRUMB_OPERATOR_STOP, cap, reason, 0); |
| 1107 | w->halt = h; |
| 1108 | w->halted = true; /* in force before any disk work */ |
| 1109 | w->halt.durable = halt_mark_write(w); |
| 1110 | } |
| 1111 | if (out) *out = w->halt; |
| 1112 | pthread_mutex_unlock(&w->callers_mu); |
| 1113 | pthread_mutex_unlock(&w->mu); |
| 1114 | return rc; |
| 1115 | } |
| 1116 | |
| 1117 | int rx_world_emergency_resume(RxWorld *w, uint32_t subject, const RxCallerCred *cred, |
| 1118 | RxCapRef cap, RxHaltStatus *out) { |
| 1119 | if (!w) return RX_ERR_ARG; |
| 1120 | pthread_mutex_lock(&w->mu); |
| 1121 | pthread_mutex_lock(&w->callers_mu); |
| 1122 | int rc = halt_authorize(w, subject, cred, cap); |
| 1123 | if (rc == RX_OK && !w->halted) rc = RX_HALT_NOT_STOPPED; |
| 1124 | if (rc == RX_OK && w->halt_dir[0]) { |
| 1125 | /* The stop record is kept, never deleted: its bytes, then the resume, |
| 1126 | * sealed together under a name no later resume can take; only then is |
| 1127 | * the mark removed. Any failure leaves the world stopped. */ |
| 1128 | RxHaltStatus disk; |
| 1129 | char raw[600]; |
| 1130 | size_t raw_len = 0; |
| 1131 | int mr = halt_mark_read(w->halt_dir, &disk, raw, sizeof raw, &raw_len); |
| 1132 | if (mr == RX_ERR_IO) rc = RX_ERR_IO; |
| 1133 | else if (mr != 0) { |
| 1134 | char buf[1200], name[160]; |
| 1135 | uint64_t t = realtime_ns(); |
| 1136 | int n = snprintf(buf, sizeof buf, "%s%sresumed_by %u\nresume_cap %u %llu\nresume_t_ns %llu\n", |
| 1137 | raw, raw_len && raw[raw_len - 1] != '\n' ? "\n" : "", subject, |
| 1138 | cap.cap_id, (unsigned long long)cap.generation, (unsigned long long)t); |
| 1139 | if (n < 0 || (size_t)n >= sizeof buf || (n = seal_append(buf, (size_t)n, sizeof buf)) < 0) |
| 1140 | rc = RX_ERR_IO; |
| 1141 | snprintf(name, sizeof name, "%s.resumed.%llu.%llu", RX_GEN_HALT_MARK, |
| 1142 | (unsigned long long)w->halt.seq, (unsigned long long)t); |
| 1143 | if (rc == RX_OK && durable_write(w->halt_dir, name, buf, (size_t)n, true) != 0) |
| 1144 | rc = RX_ERR_IO; |
| 1145 | char mark[512]; |
| 1146 | snprintf(mark, sizeof mark, "%s/%s", w->halt_dir, RX_GEN_HALT_MARK); |
| 1147 | if (rc == RX_OK && (unlink(mark) != 0 || fsync_dir(w->halt_dir) != 0)) rc = RX_ERR_IO; |
| 1148 | } |
| 1149 | } |
| 1150 | if (rc == RX_OK) { |
| 1151 | halt_crumb(w, RX_CRUMB_OPERATOR_RESUME, cap, 0, w->halt.crumb); |
| 1152 | w->halted = false; |
| 1153 | w->halt.halted = false; |
| 1154 | w->halt.restored = false; |
| 1155 | pthread_cond_broadcast(&w->work_cv); |
| 1156 | } |
| 1157 | if (out) *out = w->halt; |
| 1158 | pthread_mutex_unlock(&w->callers_mu); |
| 1159 | pthread_mutex_unlock(&w->mu); |
| 1160 | return rc; |
| 1161 | } |
| 1162 | |
| 1163 | int rx_world_operator_authorize(RxWorld *w, uint32_t subject, const RxCallerCred *cred, RxCapRef cap) { |
| 1164 | if (!w) return RX_ERR_ARG; |
| 1165 | pthread_mutex_lock(&w->mu); |
| 1166 | pthread_mutex_lock(&w->callers_mu); |
| 1167 | int rc = halt_authorize(w, subject, cred, cap); |
| 1168 | pthread_mutex_unlock(&w->callers_mu); |
| 1169 | pthread_mutex_unlock(&w->mu); |
| 1170 | return rc; |
| 1171 | } |
| 1172 | |
| 1173 | void rx_world_halt_status(RxWorld *w, RxHaltStatus *out) { |
| 1174 | if (!w || !out) return; |
| 1175 | pthread_mutex_lock(&w->mu); |
| 1176 | *out = w->halt; |
| 1177 | out->halted = w->halted; |
| 1178 | pthread_mutex_unlock(&w->mu); |
| 1179 | } |
| 1180 | |
| 1181 | static int validate_caps(const RxWorld *w, const RxReactionDesc *d, int *first_err) { |
| 1182 | /* R16 C5: the subject the capabilities are checked against is the one |
| 1183 | * this reaction was admitted under, and that admission still stands. */ |
| 1184 | if (w->callers_bound) { |
| 1185 | int irc = caller_still_live(w, d->subject, d->caller.generation); |
| 1186 | if (irc != RX_CALLER_OK) { if (first_err) *first_err = RX_ERR_IDENTITY; return -1; } |
| 1187 | } |
| 1188 | for (uint32_t i = 0; i < d->n_caps; i++) { |
| 1189 | int rc = rx_world_validate_cap(w, need_ref(w, d, i), d->subject, |
| 1190 | d->caps[i].resource, d->caps[i].rights, NULL); |
| 1191 | if (rc != RX_CAP_OK) { |
| 1192 | if (first_err) *first_err = rc; |
| 1193 | return -1; |
| 1194 | } |
| 1195 | } |
| 1196 | return 0; |
| 1197 | } |
| 1198 | |
| 1199 | /* Static coverage: every object read needs a READ capability need on its |
| 1200 | * resource and every object written a WRITE one. */ |
| 1201 | static bool covered(const RxWorld *w, const RxReactionDesc *d, RxObjRef o, uint32_t right) { |
| 1202 | uint64_t res = w->objects[o.id].resource; |
| 1203 | for (uint32_t i = 0; i < d->n_caps; i++) |
| 1204 | if (d->caps[i].resource == res && (d->caps[i].rights & right) == right) return true; |
| 1205 | return false; |
| 1206 | } |
| 1207 | |
| 1208 | /* Collect triggers + reads into one deduplicated dependency list. */ |
| 1209 | static uint32_t gather_deps(const RxReactionDesc *d, RxDep out[RX_MAX_DEPS]) { |
| 1210 | uint32_t n = 0; |
| 1211 | for (uint32_t pass = 0; pass < 2; pass++) { |
| 1212 | uint32_t cnt = pass ? d->n_reads : d->n_triggers; |
| 1213 | const RxDep *src = pass ? d->reads : d->triggers; |
| 1214 | for (uint32_t i = 0; i < cnt; i++) { |
| 1215 | uint32_t j; |
| 1216 | for (j = 0; j < n; j++) |
| 1217 | if (out[j].obj.id == src[i].obj.id && out[j].obj.generation == src[i].obj.generation) { |
| 1218 | out[j].mask |= src[i].mask; |
| 1219 | break; |
| 1220 | } |
| 1221 | if (j == n && n < RX_MAX_DEPS) out[n++] = src[i]; |
| 1222 | } |
| 1223 | } |
| 1224 | return n; |
| 1225 | } |
| 1226 | |
| 1227 | /* ---- publication -------------------------------------------------------- */ |
| 1228 | |
| 1229 | typedef struct { |
| 1230 | RxObjRef obj; |
| 1231 | uint64_t changed; |
| 1232 | uint64_t proposed; /* every field the publication named */ |
| 1233 | uint64_t value[RX_MAX_FIELDS]; |
| 1234 | } PendingWrite; |
| 1235 | |
| 1236 | /* Apply mutations atomically (caller holds mu). Returns the number of objects |
| 1237 | * written into pw/n_pw, or a negative error with nothing applied. */ |
| 1238 | static int stage_mutations(RxWorld *w, const RxMutation *m, uint32_t n, |
| 1239 | const RxDep *write_set, uint32_t n_ws, |
| 1240 | PendingWrite pw[RX_MAX_WRITES], uint32_t *n_pw) { |
| 1241 | *n_pw = 0; |
| 1242 | for (uint32_t i = 0; i < n; i++) { |
| 1243 | if (m[i].field >= RX_MAX_FIELDS) return RX_ERR_WRITE_SET; |
| 1244 | if (!ref_live(w, m[i].obj)) return RX_ERR_STALE_GEN; |
| 1245 | if (write_set) { |
| 1246 | bool ok = false; |
| 1247 | for (uint32_t k = 0; k < n_ws; k++) |
| 1248 | if (write_set[k].obj.id == m[i].obj.id && |
| 1249 | write_set[k].obj.generation == m[i].obj.generation && |
| 1250 | (write_set[k].mask & RX_FIELD(m[i].field))) ok = true; |
| 1251 | if (!ok) return RX_ERR_WRITE_SET; |
| 1252 | } |
| 1253 | uint32_t j; |
| 1254 | for (j = 0; j < *n_pw; j++) |
| 1255 | if (pw[j].obj.id == m[i].obj.id) break; |
| 1256 | if (j == *n_pw) { |
| 1257 | if (*n_pw >= RX_MAX_WRITES) return RX_ERR_FULL; |
| 1258 | pw[j].obj = m[i].obj; |
| 1259 | pw[j].changed = 0; |
| 1260 | pw[j].proposed = 0; |
| 1261 | memcpy(pw[j].value, w->objects[m[i].obj.id].field, sizeof(pw[j].value)); |
| 1262 | w->stats.stage_bytes += sizeof(pw[j].value); |
| 1263 | (*n_pw)++; |
| 1264 | } |
| 1265 | pw[j].value[m[i].field] = m[i].value; |
| 1266 | pw[j].proposed |= RX_FIELD(m[i].field); |
| 1267 | } |
| 1268 | for (uint32_t j = 0; j < *n_pw; j++) { |
| 1269 | const RxObject *o = &w->objects[pw[j].obj.id]; |
| 1270 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 1271 | if (pw[j].value[f] != o->field[f]) pw[j].changed |= RX_FIELD(f); |
| 1272 | } |
| 1273 | return RX_OK; |
| 1274 | } |
| 1275 | |
| 1276 | /* ---- COMPOSITION-2 commit binder ---------------------------------------- */ |
| 1277 | |
| 1278 | int rx_world_set_binder(RxWorld *w, RxBindCheckFn check, RxBindFn bind, RxBindAbortFn abort_fn, |
| 1279 | void *ctx) { |
| 1280 | if (!w || !check || !bind) return RX_ERR_ARG; |
| 1281 | pthread_mutex_lock(&w->mu); |
| 1282 | int rc = RX_ERR_FULL, free_at = -1; |
| 1283 | for (uint32_t i = 0; i < RX_MAX_BINDERS; i++) { |
| 1284 | if (w->binder[i].check && w->binder[i].ctx == ctx) { free_at = -2; break; } |
| 1285 | if (!w->binder[i].check && free_at == -1) free_at = (int)i; |
| 1286 | } |
| 1287 | if (free_at == -2) rc = RX_ERR_EXISTS; |
| 1288 | else if (free_at >= 0) { |
| 1289 | w->binder[free_at].check = check; |
| 1290 | w->binder[free_at].bind = bind; |
| 1291 | w->binder[free_at].abort_fn = abort_fn; |
| 1292 | w->binder[free_at].ctx = ctx; |
| 1293 | w->n_binders++; |
| 1294 | rc = RX_OK; |
| 1295 | } |
| 1296 | pthread_mutex_unlock(&w->mu); |
| 1297 | return rc; |
| 1298 | } |
| 1299 | |
| 1300 | static int binder_of(const RxWorld *w, const void *ctx) { |
| 1301 | for (uint32_t i = 0; i < RX_MAX_BINDERS; i++) |
| 1302 | if (w->binder[i].check && w->binder[i].ctx == ctx) return (int)i; |
| 1303 | return -1; |
| 1304 | } |
| 1305 | |
| 1306 | int rx_world_bind_field(RxWorld *w, void *ctx, RxObjRef obj, uint32_t field) { |
| 1307 | if (!w || field >= RX_MAX_FIELDS) return RX_ERR_ARG; |
| 1308 | pthread_mutex_lock(&w->mu); |
| 1309 | int b = binder_of(w, ctx); |
| 1310 | int rc = b < 0 ? RX_ERR_NOT_FOUND : !ref_live(w, obj) ? RX_ERR_STALE_GEN : RX_OK; |
| 1311 | if (rc == RX_OK && w->bind_mask[obj.id] && w->bind_owner[obj.id] != (uint8_t)b) |
| 1312 | rc = RX_ERR_EXISTS; /* one owner per object */ |
| 1313 | if (rc == RX_OK) { |
| 1314 | w->bind_mask[obj.id] |= (uint8_t)(1u << field); |
| 1315 | w->bind_owner[obj.id] = (uint8_t)b; |
| 1316 | } |
| 1317 | pthread_mutex_unlock(&w->mu); |
| 1318 | return rc; |
| 1319 | } |
| 1320 | |
| 1321 | int rx_world_clear_binder(RxWorld *w, void *ctx) { |
| 1322 | if (!w) return RX_ERR_ARG; |
| 1323 | pthread_mutex_lock(&w->mu); |
| 1324 | int rc = RX_ERR_NOT_FOUND; |
| 1325 | int b = binder_of(w, ctx); |
| 1326 | if (b >= 0) { |
| 1327 | memset(&w->binder[b], 0, sizeof w->binder[b]); |
| 1328 | w->n_binders--; |
| 1329 | for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) |
| 1330 | if (w->bind_mask[i] && w->bind_owner[i] == (uint8_t)b) { |
| 1331 | w->bind_mask[i] = 0; |
| 1332 | w->bind_owner[i] = 0; |
| 1333 | } |
| 1334 | rc = RX_OK; |
| 1335 | } |
| 1336 | pthread_mutex_unlock(&w->mu); |
| 1337 | return rc; |
| 1338 | } |
| 1339 | |
| 1340 | uint32_t rx_world_binder_count(RxWorld *w) { |
| 1341 | if (!w) return 0; |
| 1342 | pthread_mutex_lock(&w->mu); |
| 1343 | uint32_t n = w->n_binders; |
| 1344 | pthread_mutex_unlock(&w->mu); |
| 1345 | return n; |
| 1346 | } |
| 1347 | |
| 1348 | /* Caller holds mu; pw[] is staged and passed every other check. RX_OK when |
| 1349 | * nothing is bound or every bound value was checked and bound by the binder |
| 1350 | * that owns it; otherwise RX_ERR_BINDING and every proposed bound value went |
| 1351 | * to its own binder's abort(). */ |
| 1352 | static int bind_writes(RxWorld *w, const PendingWrite *pw, uint32_t n_pw, uint32_t subject) { |
| 1353 | if (!w->n_binders) return RX_OK; |
| 1354 | uint32_t n_bound = 0; |
| 1355 | int rc = RX_OK; |
| 1356 | for (int phase = 0; phase < 2 && rc == RX_OK; phase++) |
| 1357 | for (uint32_t j = 0; j < n_pw && rc == RX_OK; j++) { |
| 1358 | const RxObject *o = &w->objects[pw[j].obj.id]; |
| 1359 | uint64_t m = pw[j].changed & w->bind_mask[pw[j].obj.id]; |
| 1360 | if (!m) continue; |
| 1361 | const __typeof__(w->binder[0]) *b = &w->binder[w->bind_owner[pw[j].obj.id]]; |
| 1362 | for (uint32_t f = 0; f < RX_MAX_FIELDS && rc == RX_OK; f++) { |
| 1363 | if (!(m & RX_FIELD(f))) continue; |
| 1364 | rc = phase == 0 ? b->check(b->ctx, pw[j].obj, f, o->field[f], pw[j].value[f], |
| 1365 | subject) |
| 1366 | : b->bind(b->ctx, pw[j].obj, f, o->field[f], pw[j].value[f], |
| 1367 | subject); |
| 1368 | if (rc == RX_OK && phase == 1) n_bound++; |
| 1369 | } |
| 1370 | } |
| 1371 | if (rc == RX_OK) return RX_OK; |
| 1372 | /* Refused: hand every proposed bound value back, saying which were bound |
| 1373 | * (bound values precede the refused one in the same iteration order). */ |
| 1374 | uint32_t seen = 0; |
| 1375 | for (uint32_t j = 0; j < n_pw; j++) { |
| 1376 | uint64_t m = pw[j].changed & w->bind_mask[pw[j].obj.id]; |
| 1377 | if (!m) continue; |
| 1378 | const __typeof__(w->binder[0]) *b = &w->binder[w->bind_owner[pw[j].obj.id]]; |
| 1379 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { |
| 1380 | if (!(m & RX_FIELD(f))) continue; |
| 1381 | if (b->abort_fn) |
| 1382 | b->abort_fn(b->ctx, pw[j].obj, f, pw[j].value[f], subject, seen < n_bound); |
| 1383 | seen++; |
| 1384 | } |
| 1385 | } |
| 1386 | return RX_ERR_BINDING; |
| 1387 | } |
| 1388 | |
| 1389 | static void commit_writes(RxWorld *w, PendingWrite *pw, uint32_t n_pw, RxCrumb *k) { |
| 1390 | k->n_outputs = 0; |
| 1391 | for (uint32_t j = 0; j < n_pw; j++) { |
| 1392 | if (!pw[j].changed) continue; |
| 1393 | RxObject *o = &w->objects[pw[j].obj.id]; |
| 1394 | o->version++; |
| 1395 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { |
| 1396 | if (!(pw[j].changed & RX_FIELD(f))) continue; |
| 1397 | o->field[f] = pw[j].value[f]; |
| 1398 | o->field_version[f] = o->version; |
| 1399 | } |
| 1400 | object_digest(o); |
| 1401 | rx_coherent_project(w, pw[j].obj.id); |
| 1402 | k->outputs[k->n_outputs].obj = pw[j].obj; |
| 1403 | k->outputs[k->n_outputs].version = o->version; |
| 1404 | k->outputs[k->n_outputs].mask = pw[j].changed; |
| 1405 | k->n_outputs++; |
| 1406 | } |
| 1407 | } |
| 1408 | |
| 1409 | /* After the crumb id is known: stamp writers, then wake subscribers. |
| 1410 | * With stamp_proposed, a field the publication named but did not change is |
| 1411 | * stamped too (on an object it did change), so the whole record is this |
| 1412 | * commit's. Only changed fields wake anyone. */ |
| 1413 | static void finish_writes(RxWorld *w, PendingWrite *pw, uint32_t n_pw, uint64_t cid, |
| 1414 | bool stamp_proposed) { |
| 1415 | for (uint32_t j = 0; j < n_pw; j++) { |
| 1416 | if (!pw[j].changed) continue; |
| 1417 | RxObject *o = &w->objects[pw[j].obj.id]; |
| 1418 | uint64_t mask = stamp_proposed ? pw[j].changed | pw[j].proposed : pw[j].changed; |
| 1419 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 1420 | if (mask & RX_FIELD(f)) o->field_writer[f] = cid; |
| 1421 | } |
| 1422 | for (uint32_t j = 0; j < n_pw; j++) { |
| 1423 | if (!pw[j].changed) continue; |
| 1424 | rx_coherent_publish(w, pw[j].obj.id, cid); |
| 1425 | propagate(w, pw[j].obj.id, pw[j].changed, cid); |
| 1426 | } |
| 1427 | } |
| 1428 | |
| 1429 | |
| 1430 | /* ---- I11: merge an upstream writer's wake ------------------------------- */ |
| 1431 | |
| 1432 | /* Is another activation running (fn called, not yet published) that may write |
| 1433 | * a field rid triggers on or reads? With one worker this is never true when a |
| 1434 | * worker pops rid: the only worker is the one popping, and the sequential |
| 1435 | * reference never pops. With several workers it is true exactly when rid was |
| 1436 | * popped while such a writer was still computing; run now, rid would read the |
| 1437 | * pre-publication value, commit on it, and then be woken again by the writer: |
| 1438 | * one extra commit per stimulus that a single worker merges (I11, omega.risk |
| 1439 | * behind aien.hypothesis). Deferred and graphics-seat activations do not |
| 1440 | * hold anyone: their completion is not bounded by this world's workers. |
| 1441 | * Caller holds mu. */ |
| 1442 | static bool upstream_running(const RxWorld *w, uint32_t rid) { |
| 1443 | #ifdef RX_WORLD_MUTATE_NO_UPSTREAM_HOLD |
| 1444 | (void)w; |
| 1445 | (void)rid; |
| 1446 | return false; |
| 1447 | #else |
| 1448 | RxDep deps[RX_MAX_DEPS]; |
| 1449 | uint32_t n = gather_deps(&w->reactions[rid].desc, deps); |
| 1450 | for (uint32_t j = 0; j < w->n_reactions; j++) { |
| 1451 | if (j == rid) continue; |
| 1452 | const RxReaction *u = &w->reactions[j]; |
| 1453 | if (u->state != RX_RUNNING && u->state != RX_PUBLISHING) continue; |
| 1454 | if (u->deferred || u->resident_seat || u->removed) continue; |
| 1455 | for (uint32_t a = 0; a < u->desc.n_writes; a++) { |
| 1456 | const RxDep *wd = &u->desc.writes[a]; |
| 1457 | for (uint32_t b = 0; b < n; b++) |
| 1458 | if (wd->obj.id == deps[b].obj.id && wd->obj.generation == deps[b].obj.generation && |
| 1459 | (wd->mask & deps[b].mask)) |
| 1460 | return true; |
| 1461 | } |
| 1462 | } |
| 1463 | return false; |
| 1464 | #endif |
| 1465 | } |
| 1466 | |
| 1467 | /* Put every held activation whose writers have all finished back on its ready |
| 1468 | * ring, lowest reaction id first. It is still admitted (slot charged, counted |
| 1469 | * in in_flight), so it is not admitted again. Caller holds mu. */ |
| 1470 | static void release_upstream_held(RxWorld *w) { |
| 1471 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 1472 | RxReaction *r = &w->reactions[i]; |
| 1473 | if (!r->upstream_held || upstream_running(w, i)) continue; |
| 1474 | r->upstream_held = false; |
| 1475 | uint32_t p = r->desc.priority; |
| 1476 | if (p >= RX_PRIORITY_CLASSES) p = RX_PRIO_BACKGROUND; |
| 1477 | uint32_t tail = (w->ready_head[p] + w->ready_len[p]) % RX_MAX_REACTIONS; |
| 1478 | w->ready_q[p][tail] = i; |
| 1479 | w->ready_len[p]++; |
| 1480 | if (w->timing) r->t_ready = now_ns(); |
| 1481 | pthread_cond_signal(&w->work_cv); |
| 1482 | } |
| 1483 | } |
| 1484 | /* ---- worker ------------------------------------------------------------- */ |
| 1485 | |
| 1486 | static void arm_backoff(RxReaction *r) { |
| 1487 | uint32_t n = r->yield_left ? r->yield_left * 2u : 1u; |
| 1488 | if (n < r->yield_left || n > 8u) n = 8u; |
| 1489 | r->yield_left = n; |
| 1490 | } |
| 1491 | |
| 1492 | static void note_conflict(RxWorld *w, RxReaction *r) { |
| 1493 | r->conflict_streak++; |
| 1494 | w->stats.churn++; |
| 1495 | arm_backoff(r); |
| 1496 | if (w->stability.conflict_limit && r->conflict_streak >= w->stability.conflict_limit && |
| 1497 | !r->quarantined) { |
| 1498 | r->quarantined = true; |
| 1499 | w->stats.quarantines++; |
| 1500 | r->contain_pending = RX_CONTAIN_CONFLICT; |
| 1501 | } |
| 1502 | } |
| 1503 | |
| 1504 | static void note_value(RxWorld *w, RxReaction *r, int progressed, uint64_t value) { |
| 1505 | if (!progressed) { |
| 1506 | r->noop_streak++; |
| 1507 | w->stats.churn++; |
| 1508 | arm_backoff(r); |
| 1509 | if (w->stability.livelock_limit && r->noop_streak >= w->stability.livelock_limit && |
| 1510 | !r->quarantined) { |
| 1511 | r->quarantined = true; |
| 1512 | w->stats.quarantines++; |
| 1513 | w->stats.livelock_trips++; |
| 1514 | r->contain_pending = RX_CONTAIN_LIVELOCK; |
| 1515 | } |
| 1516 | return; |
| 1517 | } |
| 1518 | r->noop_streak = 0; |
| 1519 | r->conflict_streak = 0; |
| 1520 | int flipped = r->have_two && value == r->prev_out && value != r->last_out; |
| 1521 | if (flipped && r->desc.loop_kind == RX_LOOP_PERIODIC) { |
| 1522 | r->osc_streak = 0; |
| 1523 | r->yield_left = 0; |
| 1524 | w->stats.periodic_commits++; |
| 1525 | w->stats.useful_commits++; |
| 1526 | } else if (flipped) { |
| 1527 | r->osc_streak++; |
| 1528 | w->stats.churn++; |
| 1529 | arm_backoff(r); |
| 1530 | } else { |
| 1531 | r->osc_streak = 0; |
| 1532 | r->yield_left = 0; |
| 1533 | w->stats.useful_commits++; |
| 1534 | } |
| 1535 | if (r->have_last) { |
| 1536 | r->prev_out = r->last_out; |
| 1537 | r->have_two = true; |
| 1538 | } |
| 1539 | r->last_out = value; |
| 1540 | r->have_last = true; |
| 1541 | if (w->stability.oscillation_limit && r->osc_streak >= w->stability.oscillation_limit && |
| 1542 | !r->quarantined) { |
| 1543 | r->quarantined = true; |
| 1544 | w->stats.quarantines++; |
| 1545 | w->stats.oscillation_trips++; |
| 1546 | r->contain_pending = RX_CONTAIN_OSCILLATION; |
| 1547 | } |
| 1548 | } |
| 1549 | |
| 1550 | static bool others_busy(const RxWorld *w, uint32_t self) { |
| 1551 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 1552 | if (i == self) continue; |
| 1553 | RxState s = w->reactions[i].state; |
| 1554 | if (s == RX_BLOCKED_RESOURCE || s == RX_READY || s == RX_RUNNING || s == RX_PUBLISHING) |
| 1555 | return true; |
| 1556 | } |
| 1557 | return false; |
| 1558 | } |
| 1559 | |
| 1560 | static void release_parked(RxWorld *w) { |
| 1561 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 1562 | RxReaction *r = &w->reactions[i]; |
| 1563 | if (!r->parked) continue; |
| 1564 | bool busy = others_busy(w, i); |
| 1565 | if (r->yield_left && busy) continue; |
| 1566 | r->parked = false; |
| 1567 | r->yield_left = 0; |
| 1568 | uint64_t cause = r->wake_cause; |
| 1569 | demand(w, i, cause); |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | static void tick_parked(RxWorld *w) { |
| 1574 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 1575 | RxReaction *r = &w->reactions[i]; |
| 1576 | if (!r->parked || r->yield_left == 0) continue; |
| 1577 | r->yield_left--; |
| 1578 | } |
| 1579 | release_parked(w); |
| 1580 | } |
| 1581 | |
| 1582 | static void record_timing(RxWorld *w, RxReaction *r, uint32_t rid) { |
| 1583 | uint64_t i = w->n_timing++; |
| 1584 | if (i >= w->timing_cap) return; |
| 1585 | const RxCrumb *k = r->last_crumb ? &w->crumbs[r->last_crumb - 1] : NULL; |
| 1586 | RxTiming *t = &w->timing[i]; |
| 1587 | t->reaction = rid; |
| 1588 | t->outcome = k && k->reaction == rid ? (uint32_t)k->kind : 0; |
| 1589 | t->cause = k && k->reaction == rid ? k->wake_cause : 0; |
| 1590 | t->t_demand = r->t_demand; |
| 1591 | t->t_ready = r->t_ready; |
| 1592 | t->t_run = r->t_run; |
| 1593 | t->t_fn_end = r->t_fn_end; |
| 1594 | t->t_visible = now_ns(); |
| 1595 | t->sched_ns = r->sched_ns; |
| 1596 | t->sched_cpu_ns = r->sched_cpu_ns; |
| 1597 | r->t_demand = r->t_ready = r->t_run = r->t_fn_end = r->sched_ns = r->sched_cpu_ns = 0; |
| 1598 | } |
| 1599 | |
| 1600 | static void end_activation_inner(RxWorld *w, uint32_t rid); |
| 1601 | |
| 1602 | /* Everything after the timing record is scheduling work for other reactions |
| 1603 | * (release, admission, deferred and parked wakes): it counts toward the |
| 1604 | * world's scheduler totals, once, however deeply it nests. */ |
| 1605 | static void end_activation(RxWorld *w, uint32_t rid) { |
| 1606 | if (!w->timing) { end_activation_inner(w, rid); return; } |
| 1607 | record_timing(w, &w->reactions[rid], rid); |
| 1608 | uint64_t c0 = thread_cpu_ns(); |
| 1609 | uint64_t t0 = now_ns(); |
| 1610 | bool outer = w->sched_nest++ == 0; |
| 1611 | end_activation_inner(w, rid); |
| 1612 | w->sched_nest--; |
| 1613 | if (outer) { |
| 1614 | w->stats.sched_wall_ns += now_ns() - t0; |
| 1615 | w->stats.sched_cpu_ns += thread_cpu_ns() - c0; |
| 1616 | } |
| 1617 | } |
| 1618 | |
| 1619 | static void end_activation_inner(RxWorld *w, uint32_t rid) { |
| 1620 | RxReaction *r = &w->reactions[rid]; |
| 1621 | /* A limit engaged during this activation: recorded after its crumb. */ |
| 1622 | if (r->contain_pending) { |
| 1623 | contain(w, rid, r->contain_pending, r->last_crumb); |
| 1624 | r->contain_pending = 0; |
| 1625 | } |
| 1626 | tick_parked(w); |
| 1627 | uncharge(w, r); |
| 1628 | if (r->quarantined) r->rearm = false; |
| 1629 | set_state(w, r, RX_DORMANT); |
| 1630 | if (w->in_flight) w->in_flight--; |
| 1631 | /* I11: this activation published (or gave up); a dependent held behind |
| 1632 | * it may run now, after its wake, if any, has merged. */ |
| 1633 | release_upstream_held(w); |
| 1634 | if (r->rearm && r->yield_left && others_busy(w, rid)) { |
| 1635 | r->yield_left--; |
| 1636 | r->parked = true; |
| 1637 | r->rearm = false; |
| 1638 | w->stats.backoffs++; |
| 1639 | try_admit(w); |
| 1640 | } else if (r->rearm) { |
| 1641 | uint64_t cause = r->wake_cause; |
| 1642 | r->rearm = false; |
| 1643 | demand(w, rid, cause); |
| 1644 | } else { |
| 1645 | try_admit(w); |
| 1646 | } |
| 1647 | if (w->deferred_len) { |
| 1648 | uint32_t quota = w->stability.fanout_limit ? w->stability.fanout_limit : w->deferred_len; |
| 1649 | drain_deferred(w, quota); |
| 1650 | } |
| 1651 | if (w->in_flight == 0) { |
| 1652 | release_parked(w); |
| 1653 | if (w->in_flight == 0 && w->deferred_len == 0) |
| 1654 | pthread_cond_broadcast(&w->idle_cv); |
| 1655 | } |
| 1656 | } |
| 1657 | |
| 1658 | static void stamp_cap(RxWorld *w, RxCrumb *k, uint32_t i, RxCapRef ref) { |
| 1659 | k->caps[i] = ref; |
| 1660 | k->cap_issuer[i] = 0; |
| 1661 | RxCapEntry e; |
| 1662 | if (rx_world_inspect_cap(w, ref, &e) == RX_CAP_OK) |
| 1663 | k->cap_issuer[i] = e.minted_by_id ? e.minted_by_id : e.issuer; |
| 1664 | } |
| 1665 | |
| 1666 | static void fill_inputs(RxCrumb *k, const RxCtx *ctx, const RxDep *deps, uint32_t n) { |
| 1667 | k->n_inputs = n; |
| 1668 | for (uint32_t i = 0; i < n; i++) { |
| 1669 | k->inputs[i].obj = deps[i].obj; |
| 1670 | k->inputs[i].version = ctx ? ctx->in[i].version : 0; |
| 1671 | k->inputs[i].mask = deps[i].mask; |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | static void resume_locked(RxWorld *w, uint32_t rid); |
| 1676 | |
| 1677 | static void run_one(RxWorld *w, uint32_t rid, uint32_t worker) { |
| 1678 | RxReaction *r = &w->reactions[rid]; |
| 1679 | const RxReactionDesc *d = &r->desc; |
| 1680 | RxCrumb k; |
| 1681 | memset(&k, 0, sizeof(k)); |
| 1682 | k.reaction = rid; |
| 1683 | k.faculty = d->faculty; |
| 1684 | k.worker = worker; |
| 1685 | k.wake_cause = r->wake_cause; |
| 1686 | k.coalesced_wakes = r->coalesced; |
| 1687 | k.t_start_ns = now_ns(); |
| 1688 | r->t_run = k.t_start_ns; |
| 1689 | w->stats.activations++; |
| 1690 | k.n_caps = d->n_caps; |
| 1691 | for (uint32_t i = 0; i < d->n_caps; i++) stamp_cap(w, &k, i, need_ref(w, d, i)); |
| 1692 | add_parent(&k, r->wake_cause); |
| 1693 | r->activations++; |
| 1694 | r->episode_activations++; |
| 1695 | |
| 1696 | RxDep deps[RX_MAX_DEPS]; |
| 1697 | uint32_t n_deps = gather_deps(d, deps); |
| 1698 | |
| 1699 | /* Semantic readiness: required inputs exist. */ |
| 1700 | for (uint32_t i = 0; i < n_deps; i++) { |
| 1701 | if (!ref_live(w, deps[i].obj)) { |
| 1702 | set_state(w, r, RX_INVALIDATED); |
| 1703 | fill_inputs(&k, NULL, deps, n_deps); |
| 1704 | k.kind = RX_CRUMB_INVALIDATED; |
| 1705 | k.reason = RX_ERR_STALE_GEN; |
| 1706 | k.t_end_ns = now_ns(); |
| 1707 | crumb_append(w, &k); |
| 1708 | w->stats.invalidations++; |
| 1709 | note_conflict(w, r); |
| 1710 | end_activation(w, rid); |
| 1711 | return; |
| 1712 | } |
| 1713 | } |
| 1714 | /* Required authority exists. */ |
| 1715 | int cap_err = 0; |
| 1716 | if (validate_caps(w, d, &cap_err) != 0) { |
| 1717 | set_state(w, r, RX_BLOCKED_AUTHORITY); |
| 1718 | fill_inputs(&k, NULL, deps, n_deps); |
| 1719 | k.kind = RX_CRUMB_BLOCKED_AUTHORITY; |
| 1720 | k.reason = cap_err; |
| 1721 | k.t_end_ns = now_ns(); |
| 1722 | crumb_append(w, &k); |
| 1723 | w->stats.blocked_authority++; |
| 1724 | end_activation(w, rid); |
| 1725 | return; |
| 1726 | } |
| 1727 | |
| 1728 | set_state(w, r, RX_RUNNING); |
| 1729 | if (d->need.accelerator_features & RX_ACCEL_BLACKWELL) { |
| 1730 | uint32_t in = d->triggers[0].obj.id; |
| 1731 | uint32_t id = d->writes[0].obj.id; |
| 1732 | const RxObject *a = &w->objects[in]; |
| 1733 | const RxObject *o = &w->objects[id]; |
| 1734 | if (!w->resident_enabled || !a->placed || !a->live || !o->placed || !o->live || |
| 1735 | a->generation != d->triggers[0].obj.generation || |
| 1736 | o->generation != d->writes[0].obj.generation) { |
| 1737 | set_state(w, r, RX_INVALIDATED); |
| 1738 | fill_inputs(&k, NULL, deps, n_deps); |
| 1739 | k.kind = RX_CRUMB_INVALIDATED; |
| 1740 | k.reason = w->resident_enabled ? RX_ERR_UNPLACED : RX_ERR_ARG; |
| 1741 | k.t_end_ns = now_ns(); |
| 1742 | crumb_append(w, &k); |
| 1743 | w->stats.invalidations++; |
| 1744 | end_activation(w, rid); |
| 1745 | return; |
| 1746 | } |
| 1747 | /* R8: an object whose authority this reaction reads from a slot is |
| 1748 | * claimed under what the slot holds now, which validate_caps just |
| 1749 | * accepted. A renewal revokes the reference bound earlier. */ |
| 1750 | for (uint32_t i = 0; i < d->n_caps; i++) { |
| 1751 | if (!d->cap_slotted[i]) continue; |
| 1752 | if (d->caps[i].resource == w->objects[in].resource) |
| 1753 | w->objects[in].cap = need_ref(w, d, i); |
| 1754 | if (d->caps[i].resource == w->objects[id].resource) |
| 1755 | w->objects[id].cap = need_ref(w, d, i); |
| 1756 | } |
| 1757 | uint64_t seq = 0; |
| 1758 | int pr = rx_resident_post_claim(w, in, id, r->wake_cause, &seq); |
| 1759 | if (pr != RX_OK) { |
| 1760 | set_state(w, r, RX_FAILED); |
| 1761 | fill_inputs(&k, NULL, deps, n_deps); |
| 1762 | k.kind = RX_CRUMB_FAILED; |
| 1763 | k.reason = pr; |
| 1764 | k.t_end_ns = now_ns(); |
| 1765 | crumb_append(w, &k); |
| 1766 | w->stats.failed++; |
| 1767 | end_activation(w, rid); |
| 1768 | return; |
| 1769 | } |
| 1770 | r->resident_seat = true; |
| 1771 | r->resident_seq = seq; |
| 1772 | r->resident_parent = r->wake_cause; |
| 1773 | pthread_cond_broadcast(&w->claim_cv); |
| 1774 | release_upstream_held(w); /* a seat activation holds no one (I11) */ |
| 1775 | return; |
| 1776 | } |
| 1777 | RxCtx ctx; |
| 1778 | memset(&ctx, 0, sizeof(ctx)); |
| 1779 | ctx.user = d->user; |
| 1780 | ctx.worker = worker; |
| 1781 | ctx.n_in = n_deps; |
| 1782 | for (uint32_t i = 0; i < n_deps; i++) { |
| 1783 | const RxObject *o = &w->objects[deps[i].obj.id]; |
| 1784 | ctx.in[i].obj = deps[i].obj; |
| 1785 | ctx.in[i].mask = deps[i].mask; |
| 1786 | ctx.in[i].version = o->version; |
| 1787 | memcpy(ctx.in[i].field, o->field, sizeof(o->field)); |
| 1788 | memcpy(ctx.in[i].field_version, o->field_version, sizeof(o->field_version)); |
| 1789 | memcpy(ctx.in[i].field_writer, o->field_writer, sizeof(o->field_writer)); |
| 1790 | } |
| 1791 | w->stats.snapshot_bytes += (uint64_t)n_deps * sizeof(RxSnapshotDep); |
| 1792 | |
| 1793 | /* Compute against the snapshot, outside the world lock. */ |
| 1794 | pthread_mutex_unlock(&w->mu); |
| 1795 | int frc = d->fn(&ctx); |
| 1796 | pthread_mutex_lock(&w->mu); |
| 1797 | if (w->timing) r->t_fn_end = now_ns(); |
| 1798 | if (frc == RX_FN_DEFER) { |
| 1799 | if (w->sequential) { |
| 1800 | frc = RX_ERR_ARG; |
| 1801 | } else { |
| 1802 | /* The effect is on the durable executor. Keep the admission, free |
| 1803 | * the worker; rx_world_resume runs this activation again. */ |
| 1804 | r->deferred = true; |
| 1805 | w->n_deferred++; |
| 1806 | w->stats.deferrals++; |
| 1807 | if (r->resume_pending) resume_locked(w, rid); |
| 1808 | release_upstream_held(w); /* a deferred activation holds no one (I11) */ |
| 1809 | return; |
| 1810 | } |
| 1811 | } |
| 1812 | |
| 1813 | fill_inputs(&k, &ctx, deps, n_deps); |
| 1814 | /* Data ancestry: whoever last wrote each field this reaction read. */ |
| 1815 | for (uint32_t i = 0; i < n_deps; i++) |
| 1816 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 1817 | if (deps[i].mask & RX_FIELD(f)) add_parent(&k, ctx.in[i].field_writer[f]); |
| 1818 | |
| 1819 | if (frc < 0) { |
| 1820 | set_state(w, r, RX_FAILED); |
| 1821 | k.kind = RX_CRUMB_FAILED; |
| 1822 | k.reason = frc; |
| 1823 | k.t_end_ns = now_ns(); |
| 1824 | crumb_append(w, &k); |
| 1825 | w->stats.failed++; |
| 1826 | end_activation(w, rid); |
| 1827 | return; |
| 1828 | } |
| 1829 | |
| 1830 | /* HD-09 resource contract v0, first enforcement cut (aien-architecture |
| 1831 | * docs/hardening/resource-contract-v0.md section 5): a declared deadline |
| 1832 | * is enforced before publishing. Same comparison as charge(): strictly |
| 1833 | * greater than the logical tick. The proposals in ctx.out are never |
| 1834 | * staged, so nothing late is published; end_activation refunds the |
| 1835 | * charge once. A function that never returns is not covered here. */ |
| 1836 | if (d->need.deadline && w->budget.logical_tick > d->need.deadline) { |
| 1837 | set_state(w, r, RX_CANCELLED); |
| 1838 | k.kind = RX_CRUMB_CANCELLED; |
| 1839 | k.reason = RX_ERR_DEADLINE; |
| 1840 | k.t_end_ns = now_ns(); |
| 1841 | crumb_append(w, &k); |
| 1842 | w->stats.deadline_cancelled++; |
| 1843 | end_activation(w, rid); |
| 1844 | return; |
| 1845 | } |
| 1846 | |
| 1847 | /* R16 G6 operator emergency stop: the stop was taken while this |
| 1848 | * activation computed. Nothing it proposed is published; it runs again |
| 1849 | * on resume, against the state then (rearm keeps its admission path). */ |
| 1850 | if (w->halted) { |
| 1851 | set_state(w, r, RX_CANCELLED); |
| 1852 | k.kind = RX_CRUMB_CANCELLED; |
| 1853 | k.reason = RX_ERR_HALTED; |
| 1854 | k.t_end_ns = now_ns(); |
| 1855 | crumb_append(w, &k); |
| 1856 | w->halt.refused++; |
| 1857 | w->halt.cancelled++; |
| 1858 | /* A refused activation is not spent: it must not count toward the |
| 1859 | * episode budget, or the re-run could be quarantined instead. */ |
| 1860 | if (r->episode_activations) r->episode_activations--; |
| 1861 | r->rearm = true; |
| 1862 | end_activation(w, rid); |
| 1863 | return; |
| 1864 | } |
| 1865 | |
| 1866 | set_state(w, r, RX_PUBLISHING); |
| 1867 | /* 1. Versioned reads still valid? */ |
| 1868 | bool stale = false; |
| 1869 | for (uint32_t i = 0; i < n_deps && !stale; i++) { |
| 1870 | const RxObject *o = &w->objects[deps[i].obj.id]; |
| 1871 | if (!ref_live(w, deps[i].obj)) { stale = true; break; } |
| 1872 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 1873 | if ((deps[i].mask & RX_FIELD(f)) && o->field_version[f] != ctx.in[i].field_version[f]) { |
| 1874 | stale = true; |
| 1875 | break; |
| 1876 | } |
| 1877 | } |
| 1878 | if (stale) { |
| 1879 | set_state(w, r, RX_INVALIDATED); |
| 1880 | k.kind = RX_CRUMB_INVALIDATED; |
| 1881 | k.reason = RX_ERR_STALE_GEN; |
| 1882 | k.t_end_ns = now_ns(); |
| 1883 | crumb_append(w, &k); |
| 1884 | w->stats.invalidations++; |
| 1885 | note_conflict(w, r); |
| 1886 | /* The wake this activation answered is still unanswered. A change to a |
| 1887 | * trigger has already re-armed it; a change to a read-only input has |
| 1888 | * not, and would otherwise drop the stimulus. Run again on a fresh |
| 1889 | * snapshot under the same cause. Conflict limits still apply. */ |
| 1890 | r->rearm = true; |
| 1891 | end_activation(w, rid); |
| 1892 | return; |
| 1893 | } |
| 1894 | /* 2. Authority still valid (revocation during the run must not execute). */ |
| 1895 | if (validate_caps(w, d, &cap_err) != 0) { |
| 1896 | set_state(w, r, RX_REJECTED); |
| 1897 | k.kind = RX_CRUMB_REJECTED; |
| 1898 | k.reason = cap_err; |
| 1899 | k.t_end_ns = now_ns(); |
| 1900 | crumb_append(w, &k); |
| 1901 | w->stats.rejected++; |
| 1902 | note_conflict(w, r); |
| 1903 | end_activation(w, rid); |
| 1904 | return; |
| 1905 | } |
| 1906 | /* 3. Mutations inside the declared write set, targets not stale. */ |
| 1907 | PendingWrite pw[RX_MAX_WRITES]; |
| 1908 | uint32_t n_pw = 0; |
| 1909 | int src = stage_mutations(w, ctx.out, ctx.n_out, d->writes, d->n_writes, pw, &n_pw); |
| 1910 | if (src != RX_OK) { |
| 1911 | set_state(w, r, RX_REJECTED); |
| 1912 | k.kind = RX_CRUMB_REJECTED; |
| 1913 | k.reason = src; |
| 1914 | k.t_end_ns = now_ns(); |
| 1915 | crumb_append(w, &k); |
| 1916 | w->stats.rejected++; |
| 1917 | note_conflict(w, r); |
| 1918 | end_activation(w, rid); |
| 1919 | return; |
| 1920 | } |
| 1921 | /* 3b. COMPOSITION-2: every changed bound field accepted and bound by its |
| 1922 | * store (rx_world_set_binder). Refusal leaves nothing visible. */ |
| 1923 | src = bind_writes(w, pw, n_pw, d->subject); |
| 1924 | if (src != RX_OK) { |
| 1925 | set_state(w, r, RX_REJECTED); |
| 1926 | k.kind = RX_CRUMB_REJECTED; |
| 1927 | k.reason = src; |
| 1928 | k.t_end_ns = now_ns(); |
| 1929 | crumb_append(w, &k); |
| 1930 | w->stats.rejected++; |
| 1931 | note_conflict(w, r); |
| 1932 | end_activation(w, rid); |
| 1933 | return; |
| 1934 | } |
| 1935 | /* 4. Atomic publish. */ |
| 1936 | commit_writes(w, pw, n_pw, &k); |
| 1937 | k.kind = k.n_outputs ? RX_CRUMB_COMMIT : RX_CRUMB_NOOP; |
| 1938 | if (k.n_outputs) { |
| 1939 | uint64_t sample = 0; |
| 1940 | uint64_t mask = k.outputs[0].mask; |
| 1941 | const RxObject *o = &w->objects[k.outputs[0].obj.id]; |
| 1942 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 1943 | if (mask & RX_FIELD(f)) { sample = o->field[f]; break; } |
| 1944 | note_value(w, r, 1, sample); |
| 1945 | } else { |
| 1946 | note_value(w, r, 0, 0); |
| 1947 | } |
| 1948 | k.t_end_ns = now_ns(); |
| 1949 | uint64_t cid = crumb_append(w, &k); |
| 1950 | set_state(w, r, RX_COMMITTED); |
| 1951 | if (k.n_outputs) { |
| 1952 | w->stats.commits++; |
| 1953 | r->commits++; |
| 1954 | } else { |
| 1955 | w->stats.noops++; |
| 1956 | } |
| 1957 | finish_writes(w, pw, n_pw, cid, d->stamp_proposed); |
| 1958 | end_activation(w, rid); |
| 1959 | } |
| 1960 | |
| 1961 | /* Caller holds mu. The activation is still admitted (slot charged, counted in |
| 1962 | * in_flight): put it back on its ready ring without admitting it again. */ |
| 1963 | static void resume_locked(RxWorld *w, uint32_t rid) { |
| 1964 | RxReaction *r = &w->reactions[rid]; |
| 1965 | r->resume_pending = false; |
| 1966 | r->deferred = false; |
| 1967 | if (w->n_deferred) w->n_deferred--; |
| 1968 | uint32_t p = r->desc.priority; |
| 1969 | if (p >= RX_PRIORITY_CLASSES) p = RX_PRIO_BACKGROUND; |
| 1970 | uint32_t tail = (w->ready_head[p] + w->ready_len[p]) % RX_MAX_REACTIONS; |
| 1971 | w->ready_q[p][tail] = rid; |
| 1972 | w->ready_len[p]++; |
| 1973 | set_state(w, r, RX_READY); |
| 1974 | if (w->timing) r->t_ready = now_ns(); |
| 1975 | pthread_cond_signal(&w->work_cv); |
| 1976 | if (w->n_deferred == 0) pthread_cond_broadcast(&w->idle_cv); |
| 1977 | } |
| 1978 | |
| 1979 | int rx_world_resume(RxWorld *w, uint32_t reaction) { |
| 1980 | if (!w) return RX_ERR_ARG; |
| 1981 | pthread_mutex_lock(&w->mu); |
| 1982 | if (reaction >= w->n_reactions) { |
| 1983 | pthread_mutex_unlock(&w->mu); |
| 1984 | return RX_ERR_ARG; |
| 1985 | } |
| 1986 | RxReaction *r = &w->reactions[reaction]; |
| 1987 | if (r->deferred) resume_locked(w, reaction); |
| 1988 | else r->resume_pending = true; |
| 1989 | pthread_mutex_unlock(&w->mu); |
| 1990 | return RX_OK; |
| 1991 | } |
| 1992 | |
| 1993 | static void *worker_main(void *arg) { |
| 1994 | RxWorld *w = arg; |
| 1995 | pthread_mutex_lock(&w->mu); |
| 1996 | uint32_t me = UINT32_MAX; |
| 1997 | for (uint32_t i = 0; i < w->n_workers; i++) |
| 1998 | if (pthread_equal(w->workers[i], pthread_self())) me = i; |
| 1999 | for (;;) { |
| 2000 | uint32_t rid; |
| 2001 | uint64_t t0 = w->timing ? now_ns() : 0; |
| 2002 | uint64_t c0 = w->timing ? thread_cpu_ns() : 0; |
| 2003 | #if RX_ARGUS |
| 2004 | int argus_parked = 0; |
| 2005 | #endif |
| 2006 | /* R16 G6: under an operator stop no work is taken; resume broadcasts. */ |
| 2007 | while (!w->stopping && (w->halted || !pop_ready(w, &rid))) { |
| 2008 | #if RX_ARGUS |
| 2009 | /* ARGUS: before the first wait of a park, flush this worker's use table |
| 2010 | * and publish idle. The flush touches only this thread's own ARGUS slot, |
| 2011 | * so it runs outside w->mu (speed2: under the lock it lengthened every |
| 2012 | * hold that submitters wait on). Only when a flush is due, once per park; |
| 2013 | * after relocking, re-check stopping/work before waiting. */ |
| 2014 | if (!argus_parked) { |
| 2015 | argus_parked = 1; |
| 2016 | if (rx_argus_idle_pending()) { |
| 2017 | pthread_mutex_unlock(&w->mu); |
| 2018 | rx_argus_idle(); |
| 2019 | pthread_mutex_lock(&w->mu); |
| 2020 | continue; |
| 2021 | } |
| 2022 | } |
| 2023 | #endif |
| 2024 | pthread_cond_wait(&w->work_cv, &w->mu); |
| 2025 | t0 = w->timing ? now_ns() : 0; |
| 2026 | c0 = w->timing ? thread_cpu_ns() : 0; |
| 2027 | } |
| 2028 | if (w->stopping) break; |
| 2029 | if (upstream_running(w, rid)) { |
| 2030 | /* I11: a writer of its inputs is still computing. Hold the |
| 2031 | * activation (admitted, READY, off the ring) so that writer's |
| 2032 | * wake coalesces into it, as one worker would. */ |
| 2033 | w->reactions[rid].upstream_held = true; |
| 2034 | continue; |
| 2035 | } |
| 2036 | if (w->timing) { |
| 2037 | uint64_t c1 = thread_cpu_ns(); |
| 2038 | uint64_t t1 = now_ns(); |
| 2039 | RxReaction *r = &w->reactions[rid]; |
| 2040 | r->sched_ns += t1 - t0; |
| 2041 | r->sched_cpu_ns += c1 - c0; |
| 2042 | w->stats.sched_wall_ns += t1 - t0; |
| 2043 | w->stats.sched_cpu_ns += c1 - c0; |
| 2044 | } |
| 2045 | run_one(w, rid, me); |
| 2046 | } |
| 2047 | pthread_mutex_unlock(&w->mu); |
| 2048 | return NULL; |
| 2049 | } |
| 2050 | |
| 2051 | /* ---- public API ---------------------------------------------------------- */ |
| 2052 | |
| 2053 | int rx_world_init(RxWorld *w, RxCapRoot *root, uint32_t n_workers, uint64_t crumb_cap) { |
| 2054 | if (!root) return RX_ERR_ARG; |
| 2055 | return rx_world_init_with_auth(w, root, NULL, NULL, NULL, n_workers, crumb_cap); |
| 2056 | } |
| 2057 | |
| 2058 | static int init_common(RxWorld *w, RxCapRoot *root, const void *auth_ctx, |
| 2059 | RxAuthValidateFn validate, RxAuthInspectFn inspect, |
| 2060 | uint32_t n_workers, uint64_t crumb_cap, bool sequential); |
| 2061 | |
| 2062 | int rx_world_init_with_auth(RxWorld *w, RxCapRoot *root, const void *auth_ctx, |
| 2063 | RxAuthValidateFn validate, RxAuthInspectFn inspect, |
| 2064 | uint32_t n_workers, uint64_t crumb_cap) { |
| 2065 | if (n_workers == 0) return RX_ERR_ARG; |
| 2066 | return init_common(w, root, auth_ctx, validate, inspect, n_workers, crumb_cap, false); |
| 2067 | } |
| 2068 | |
| 2069 | /* The R15 sequential reference: the same world with no workers. Only |
| 2070 | * rx_seq_reference.c drives it. Never a production configuration. */ |
| 2071 | int rx_world_init_sequential_reference(RxWorld *w, const void *auth_ctx, |
| 2072 | RxAuthValidateFn validate, RxAuthInspectFn inspect, |
| 2073 | uint64_t crumb_cap) { |
| 2074 | return init_common(w, NULL, auth_ctx, validate, inspect, 0, crumb_cap, true); |
| 2075 | } |
| 2076 | |
| 2077 | void rx_world_set_timing(RxWorld *w, RxTiming *buf, uint64_t cap) { |
| 2078 | pthread_mutex_lock(&w->mu); |
| 2079 | w->timing = buf; |
| 2080 | w->timing_cap = buf ? cap : 0; |
| 2081 | w->n_timing = 0; |
| 2082 | pthread_mutex_unlock(&w->mu); |
| 2083 | } |
| 2084 | |
| 2085 | int rx_world_timing_status(RxWorld *w, uint64_t *stored, uint64_t *attempted) { |
| 2086 | if (!w) return RX_ERR_ARG; |
| 2087 | pthread_mutex_lock(&w->mu); |
| 2088 | uint64_t n = w->n_timing, cap = w->timing_cap; |
| 2089 | pthread_mutex_unlock(&w->mu); |
| 2090 | if (stored) *stored = n < cap ? n : cap; |
| 2091 | if (attempted) *attempted = n; |
| 2092 | return n > cap ? RX_ERR_FULL : RX_OK; |
| 2093 | } |
| 2094 | |
| 2095 | static int init_common(RxWorld *w, RxCapRoot *root, const void *auth_ctx, |
| 2096 | RxAuthValidateFn validate, RxAuthInspectFn inspect, |
| 2097 | uint32_t n_workers, uint64_t crumb_cap, bool sequential) { |
| 2098 | if (!w || n_workers > RX_MAX_WORKERS || crumb_cap == 0 || (n_workers == 0) != sequential) |
| 2099 | return RX_ERR_ARG; |
| 2100 | if (!root && !validate) return RX_ERR_ARG; |
| 2101 | memset(w, 0, sizeof(*w)); |
| 2102 | w->root = root; |
| 2103 | pthread_mutex_init(&w->callers_mu, NULL); |
| 2104 | w->sequential = sequential; |
| 2105 | w->auth_ctx = auth_ctx; |
| 2106 | w->auth_validate = validate; |
| 2107 | w->auth_inspect = inspect; |
| 2108 | w->crumbs = crumb_log_map(crumb_cap); |
| 2109 | if (!w->crumbs) return RX_ERR_FULL; |
| 2110 | w->deferred = calloc(RX_DEFERRED_INITIAL, sizeof(*w->deferred)); |
| 2111 | if (!w->deferred) { |
| 2112 | crumb_log_unmap(w->crumbs, crumb_cap); |
| 2113 | w->crumbs = NULL; |
| 2114 | return RX_ERR_FULL; |
| 2115 | } |
| 2116 | w->deferred_cap = RX_DEFERRED_INITIAL; |
| 2117 | w->crumb_cap = crumb_cap; |
| 2118 | if (rx_coherent_format(w) != RX_OK) { |
| 2119 | free(w->deferred); |
| 2120 | crumb_log_unmap(w->crumbs, crumb_cap); |
| 2121 | w->deferred = NULL; |
| 2122 | w->crumbs = NULL; |
| 2123 | return RX_ERR_FULL; |
| 2124 | } |
| 2125 | w->budget.slots = RX_MAX_REACTIONS; |
| 2126 | w->budget.memory_bytes = UINT64_MAX; |
| 2127 | w->budget.energy_budget = UINT64_MAX; |
| 2128 | w->budget.offered_locality = UINT32_MAX; |
| 2129 | w->budget.offered_accel = UINT32_MAX; |
| 2130 | w->budget.compute_mask = UINT32_MAX; |
| 2131 | pthread_mutex_init(&w->mu, NULL); |
| 2132 | pthread_cond_init(&w->work_cv, NULL); |
| 2133 | pthread_cond_init(&w->idle_cv, NULL); |
| 2134 | pthread_cond_init(&w->claim_cv, NULL); |
| 2135 | pthread_mutex_lock(&w->mu); |
| 2136 | w->n_workers = n_workers; |
| 2137 | for (uint32_t i = 0; i < n_workers; i++) |
| 2138 | pthread_create(&w->workers[i], NULL, worker_main, w); |
| 2139 | pthread_mutex_unlock(&w->mu); |
| 2140 | return RX_OK; |
| 2141 | } |
| 2142 | |
| 2143 | void rx_world_set_resources(RxWorld *w, const RxResourceBudget *budget) { |
| 2144 | if (!w || !budget) return; |
| 2145 | pthread_mutex_lock(&w->mu); |
| 2146 | /* The setter is exact. Zero is a real zero-resource condition, not |
| 2147 | * shorthand for unlimited. rx_world_init installs the permissive default. */ |
| 2148 | w->budget = *budget; |
| 2149 | try_admit(w); |
| 2150 | if (w->in_flight == 0) pthread_cond_broadcast(&w->idle_cv); |
| 2151 | pthread_mutex_unlock(&w->mu); |
| 2152 | } |
| 2153 | |
| 2154 | void rx_world_set_stability(RxWorld *w, const RxStabilityBudget *stability) { |
| 2155 | if (!w || !stability) return; |
| 2156 | pthread_mutex_lock(&w->mu); |
| 2157 | w->stability = *stability; |
| 2158 | pthread_mutex_unlock(&w->mu); |
| 2159 | } |
| 2160 | |
| 2161 | void rx_world_destroy(RxWorld *w) { |
| 2162 | pthread_mutex_lock(&w->mu); |
| 2163 | /* A deferred activation's executor will still call rx_world_resume: let |
| 2164 | * it land before the world goes away. */ |
| 2165 | while (w->n_deferred) pthread_cond_wait(&w->idle_cv, &w->mu); |
| 2166 | w->stopping = true; |
| 2167 | pthread_cond_broadcast(&w->work_cv); |
| 2168 | pthread_mutex_unlock(&w->mu); |
| 2169 | for (uint32_t i = 0; i < w->n_workers; i++) pthread_join(w->workers[i], NULL); |
| 2170 | if (w->recorder_release) w->recorder_release(w->recorder_ctx); |
| 2171 | w->recorder = NULL; |
| 2172 | w->recorder_release = NULL; |
| 2173 | w->recorder_ctx = NULL; |
| 2174 | for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) free(w->subs[i]); |
| 2175 | rx_coherent_free(w); |
| 2176 | free(w->deferred); |
| 2177 | crumb_log_unmap(w->crumbs, w->crumb_cap); |
| 2178 | w->crumbs = NULL; |
| 2179 | pthread_cond_destroy(&w->work_cv); |
| 2180 | pthread_cond_destroy(&w->idle_cv); |
| 2181 | pthread_cond_destroy(&w->claim_cv); |
| 2182 | pthread_mutex_destroy(&w->mu); |
| 2183 | pthread_mutex_destroy(&w->callers_mu); |
| 2184 | } |
| 2185 | |
| 2186 | int rx_world_create(RxWorld *w, uint32_t type, RxPersist persist, uint64_t resource, |
| 2187 | const uint64_t init[RX_MAX_FIELDS], RxObjRef *out) { |
| 2188 | pthread_mutex_lock(&w->mu); |
| 2189 | if (w->halted) { /* R16 G6: nothing new commits under a stop */ |
| 2190 | w->halt.refused++; |
| 2191 | pthread_mutex_unlock(&w->mu); |
| 2192 | return RX_ERR_HALTED; |
| 2193 | } |
| 2194 | for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) { |
| 2195 | RxObject *o = &w->objects[i]; |
| 2196 | if (o->live) continue; |
| 2197 | o->live = true; |
| 2198 | o->type = type; |
| 2199 | o->persist = persist; |
| 2200 | o->resource = resource; |
| 2201 | o->placed = false; |
| 2202 | o->window = 0; |
| 2203 | o->region_offset = 0; |
| 2204 | o->size_bytes = 0; |
| 2205 | o->placement = 0; |
| 2206 | o->locality = 0; |
| 2207 | o->coherency = 0; |
| 2208 | o->cap = (RxCapRef){ 0, 0 }; |
| 2209 | w->bind_mask[i] = 0; |
| 2210 | w->bind_owner[i] = 0; |
| 2211 | o->version = 1; |
| 2212 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) { |
| 2213 | o->field[f] = init ? init[f] : 0; |
| 2214 | o->field_version[f] = 1; |
| 2215 | } |
| 2216 | object_digest(o); |
| 2217 | RxCrumb k; |
| 2218 | memset(&k, 0, sizeof(k)); |
| 2219 | k.kind = RX_CRUMB_CREATE; |
| 2220 | k.reaction = UINT32_MAX; |
| 2221 | k.faculty = RX_FACULTY_EXTERNAL; |
| 2222 | k.n_outputs = 1; |
| 2223 | k.outputs[0].obj = (RxObjRef){ i, o->generation }; |
| 2224 | k.outputs[0].version = 1; |
| 2225 | k.outputs[0].mask = RX_ALL_FIELDS; |
| 2226 | k.t_start_ns = k.t_end_ns = now_ns(); |
| 2227 | uint64_t cid = crumb_append(w, &k); |
| 2228 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) o->field_writer[f] = cid; |
| 2229 | rx_coherent_project(w, i); |
| 2230 | out->id = i; |
| 2231 | out->generation = o->generation; |
| 2232 | pthread_mutex_unlock(&w->mu); |
| 2233 | return RX_OK; |
| 2234 | } |
| 2235 | pthread_mutex_unlock(&w->mu); |
| 2236 | return RX_ERR_FULL; |
| 2237 | } |
| 2238 | |
| 2239 | int rx_world_retire(RxWorld *w, RxObjRef ref) { |
| 2240 | pthread_mutex_lock(&w->mu); |
| 2241 | if (w->halted) { /* R16 G6: nothing new commits under a stop */ |
| 2242 | w->halt.refused++; |
| 2243 | pthread_mutex_unlock(&w->mu); |
| 2244 | return RX_ERR_HALTED; |
| 2245 | } |
| 2246 | if (!ref_live(w, ref)) { |
| 2247 | pthread_mutex_unlock(&w->mu); |
| 2248 | return RX_ERR_STALE_GEN; |
| 2249 | } |
| 2250 | RxObject *o = &w->objects[ref.id]; |
| 2251 | /* Object generations stay 32 bits: an exhausted one retires the slot |
| 2252 | * rather than wrap, the same rule capability generations follow. */ |
| 2253 | if (o->generation == UINT32_MAX) { |
| 2254 | pthread_mutex_unlock(&w->mu); |
| 2255 | return RX_ERR_FULL; |
| 2256 | } |
| 2257 | uint32_t next_gen = o->generation + 1u; |
| 2258 | o->live = false; |
| 2259 | o->generation = next_gen; |
| 2260 | o->cap = (RxCapRef){ 0, 0 }; |
| 2261 | rx_coherent_project(w, ref.id); |
| 2262 | RxCrumb k; |
| 2263 | memset(&k, 0, sizeof(k)); |
| 2264 | k.kind = RX_CRUMB_RETIRE; |
| 2265 | k.reaction = UINT32_MAX; |
| 2266 | k.n_inputs = 1; |
| 2267 | k.inputs[0].obj = ref; |
| 2268 | k.inputs[0].version = o->version; |
| 2269 | k.inputs[0].mask = RX_ALL_FIELDS; |
| 2270 | k.t_start_ns = k.t_end_ns = now_ns(); |
| 2271 | crumb_append(w, &k); |
| 2272 | pthread_mutex_unlock(&w->mu); |
| 2273 | return RX_OK; |
| 2274 | } |
| 2275 | |
| 2276 | int rx_world_add_reaction(RxWorld *w, const RxReactionDesc *d, uint32_t *out_id) { |
| 2277 | int seat = d && (d->need.accelerator_features & RX_ACCEL_BLACKWELL) != 0; |
| 2278 | if (!d || (!d->fn && !seat) || d->priority >= RX_PRIORITY_CLASSES || d->n_triggers == 0 || |
| 2279 | d->n_triggers > RX_MAX_DEPS || d->n_reads > RX_MAX_DEPS || |
| 2280 | d->n_writes > RX_MAX_WRITES || d->n_caps > RX_MAX_CAPS) |
| 2281 | return RX_ERR_ARG; |
| 2282 | /* The seat reads one object and writes field 0 of a different one. */ |
| 2283 | /* A seat still has one data input. R8 may add one capability-slot wake |
| 2284 | * so a blocked seat can resume when a real grant appears. That wake is |
| 2285 | * authority state, never a second GPU operand. */ |
| 2286 | int seat_slot_wake = seat && d->n_triggers == 2 && |
| 2287 | d->triggers[1].mask == (RX_FIELD(0) | RX_FIELD(1) | RX_FIELD(2)) && |
| 2288 | d->triggers[1].obj.id != d->triggers[0].obj.id && |
| 2289 | d->triggers[1].obj.id != d->writes[0].obj.id; |
| 2290 | int slot_matches = 0; |
| 2291 | if (seat_slot_wake) |
| 2292 | for (uint32_t i = 0; i < d->n_caps; i++) |
| 2293 | if (d->cap_slotted[i] && |
| 2294 | d->cap_slot[i].id == d->triggers[1].obj.id && |
| 2295 | d->cap_slot[i].generation == d->triggers[1].obj.generation) |
| 2296 | slot_matches = 1; |
| 2297 | if (seat && (d->n_writes != 1 || d->writes[0].mask != RX_FIELD(0) || |
| 2298 | (d->n_triggers != 1 && (!seat_slot_wake || !slot_matches)) || |
| 2299 | d->triggers[0].obj.id == d->writes[0].obj.id || |
| 2300 | (d->triggers[0].mask & ~(RX_FIELD(0) | RX_FIELD(1))) != 0 || |
| 2301 | d->triggers[0].mask == 0)) |
| 2302 | return RX_ERR_ARG; |
| 2303 | pthread_mutex_lock(&w->mu); |
| 2304 | int rc = RX_OK; |
| 2305 | /* R16 C5: the subject is the caller's own only with its credential. |
| 2306 | * C7: an unbound world checks a named credential too, so a guessed |
| 2307 | * generation never survives binding; a reaction that names none is kept |
| 2308 | * as unauthenticated (generation 0), which bind refuses. */ |
| 2309 | if (w->callers_bound || d->caller.generation != 0) { |
| 2310 | pthread_mutex_lock(&w->callers_mu); |
| 2311 | int irc = caller_check_locked(w, d->subject, &d->caller); |
| 2312 | pthread_mutex_unlock(&w->callers_mu); |
| 2313 | if (irc != RX_CALLER_OK) { rc = RX_ERR_IDENTITY; goto out; } |
| 2314 | } |
| 2315 | /* A removed slot of the same subject and faculty is reused before the |
| 2316 | * table grows (rx_world_remove_reaction): crumbs naming the slot keep |
| 2317 | * naming the same principal. */ |
| 2318 | int reuse = -1; |
| 2319 | for (uint32_t i = 0; i < w->n_reactions && reuse < 0; i++) |
| 2320 | if (w->reactions[i].removed && w->reactions[i].desc.subject == d->subject && |
| 2321 | w->reactions[i].desc.faculty == d->faculty) |
| 2322 | reuse = (int)i; |
| 2323 | if (reuse < 0 && w->n_reactions >= RX_MAX_REACTIONS) { rc = RX_ERR_FULL; goto out; } |
| 2324 | /* Declared dependencies must exist now, and every read and write must be |
| 2325 | * covered by a declared capability need on that object's resource. The |
| 2326 | * needs themselves are only validated against the root at run time. */ |
| 2327 | for (uint32_t i = 0; i < d->n_triggers; i++) |
| 2328 | if (!ref_live(w, d->triggers[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } |
| 2329 | for (uint32_t i = 0; i < d->n_reads; i++) |
| 2330 | if (!ref_live(w, d->reads[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } |
| 2331 | for (uint32_t i = 0; i < d->n_writes; i++) |
| 2332 | if (!ref_live(w, d->writes[i].obj)) { rc = RX_ERR_STALE_GEN; goto out; } |
| 2333 | for (uint32_t i = 0; i < d->n_triggers; i++) |
| 2334 | if (!covered(w, d, d->triggers[i].obj, RX_RIGHT_READ)) { rc = RX_ERR_AUTHORITY; goto out; } |
| 2335 | for (uint32_t i = 0; i < d->n_reads; i++) |
| 2336 | if (!covered(w, d, d->reads[i].obj, RX_RIGHT_READ)) { rc = RX_ERR_AUTHORITY; goto out; } |
| 2337 | for (uint32_t i = 0; i < d->n_writes; i++) |
| 2338 | if (!covered(w, d, d->writes[i].obj, RX_RIGHT_WRITE)) { rc = RX_ERR_AUTHORITY; goto out; } |
| 2339 | /* Index triggers only: a read-only dependency is observed, not a wake. */ |
| 2340 | for (uint32_t i = 0; i < d->n_triggers; i++) { |
| 2341 | uint32_t o = d->triggers[i].obj.id; |
| 2342 | if (!w->subs[o]) { |
| 2343 | w->subs[o] = calloc(RX_MAX_SUBS, sizeof(RxSub)); |
| 2344 | if (!w->subs[o]) { rc = RX_ERR_FULL; goto out; } |
| 2345 | } |
| 2346 | if (w->n_subs[o] >= RX_MAX_SUBS) { rc = RX_ERR_FULL; goto out; } |
| 2347 | } |
| 2348 | uint32_t rid = reuse >= 0 ? (uint32_t)reuse : w->n_reactions++; |
| 2349 | RxReaction *r = &w->reactions[rid]; |
| 2350 | memset(r, 0, sizeof(*r)); |
| 2351 | r->desc = *d; |
| 2352 | /* Keep the admitted generation, never the secret. */ |
| 2353 | for (size_t i = 0; i < sizeof r->desc.caller.secret; i++) |
| 2354 | ((volatile uint8_t *)r->desc.caller.secret)[i] = 0; |
| 2355 | r->state = RX_DORMANT; |
| 2356 | /* Sequential reference: changes before registration are not work. */ |
| 2357 | for (uint32_t i = 0; i < d->n_triggers; i++) { |
| 2358 | const RxObject *o = &w->objects[d->triggers[i].obj.id]; |
| 2359 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 2360 | if ((d->triggers[i].mask & RX_FIELD(f)) && o->field_version[f] > r->seq_seen[i]) |
| 2361 | r->seq_seen[i] = o->field_version[f]; |
| 2362 | } |
| 2363 | for (uint32_t i = 0; i < d->n_triggers; i++) { |
| 2364 | uint32_t o = d->triggers[i].obj.id; |
| 2365 | w->subs[o][w->n_subs[o]++] = (RxSub){ rid, d->triggers[i].obj.generation, d->triggers[i].mask }; |
| 2366 | } |
| 2367 | if (out_id) *out_id = rid; |
| 2368 | out: |
| 2369 | pthread_mutex_unlock(&w->mu); |
| 2370 | return rc; |
| 2371 | } |
| 2372 | |
| 2373 | int rx_world_remove_reaction(RxWorld *w, uint32_t rid) { |
| 2374 | if (!w) return RX_ERR_ARG; |
| 2375 | pthread_mutex_lock(&w->mu); |
| 2376 | int rc = RX_OK; |
| 2377 | RxReaction *r = rid < w->n_reactions ? &w->reactions[rid] : NULL; |
| 2378 | if (!r || r->removed) { |
| 2379 | rc = RX_ERR_NOT_FOUND; |
| 2380 | goto out; |
| 2381 | } |
| 2382 | if (r->state != RX_DORMANT || r->rearm || r->parked || r->deferred || r->resume_pending || |
| 2383 | r->holding || r->seq_pending) { |
| 2384 | rc = RX_ERR_BUSY; |
| 2385 | goto out; |
| 2386 | } |
| 2387 | for (uint32_t j = 0; j < w->deferred_len; j++) |
| 2388 | if (w->deferred[w->deferred_head + j].reaction == rid) { |
| 2389 | rc = RX_ERR_BUSY; |
| 2390 | goto out; |
| 2391 | } |
| 2392 | /* Out of the dependency index: no publication can name it again. */ |
| 2393 | for (uint32_t i = 0; i < r->desc.n_triggers; i++) { |
| 2394 | uint32_t o = r->desc.triggers[i].obj.id; |
| 2395 | if (o >= RX_MAX_OBJECTS || !w->subs[o]) continue; |
| 2396 | uint32_t k = 0; |
| 2397 | for (uint32_t s = 0; s < w->n_subs[o]; s++) |
| 2398 | if (w->subs[o][s].reaction != rid) w->subs[o][k++] = w->subs[o][s]; |
| 2399 | w->n_subs[o] = k; |
| 2400 | } |
| 2401 | r->removed = true; |
| 2402 | r->quarantined = false; |
| 2403 | r->desc.fn = NULL; /* nothing of the old owner stays callable */ |
| 2404 | r->desc.user = NULL; |
| 2405 | out: |
| 2406 | pthread_mutex_unlock(&w->mu); |
| 2407 | return rc; |
| 2408 | } |
| 2409 | |
| 2410 | void rx_world_footprint(RxWorld *w, RxFootprint *out) { |
| 2411 | memset(out, 0, sizeof *out); |
| 2412 | if (!w) return; |
| 2413 | pthread_mutex_lock(&w->mu); |
| 2414 | out->reaction_slots = w->n_reactions; |
| 2415 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 2416 | if (w->reactions[i].removed) out->reactions_removed++; |
| 2417 | else out->reactions_active++; |
| 2418 | } |
| 2419 | for (uint32_t o = 0; o < RX_MAX_OBJECTS; o++) { |
| 2420 | out->subscriptions += w->n_subs[o]; |
| 2421 | if (w->objects[o].live) out->objects_live++; |
| 2422 | for (uint32_t f = 0; f < RX_MAX_FIELDS; f++) |
| 2423 | if (w->bind_mask[o] & (1u << f)) out->bound_fields++; |
| 2424 | } |
| 2425 | out->binders = w->n_binders; |
| 2426 | out->in_flight = w->in_flight; |
| 2427 | out->fanout_backlog = w->deferred_len; |
| 2428 | out->deferred = w->n_deferred; |
| 2429 | out->used_slots = w->used_slots; |
| 2430 | out->used_memory = w->used_memory; |
| 2431 | out->used_energy = w->used_energy; |
| 2432 | pthread_mutex_unlock(&w->mu); |
| 2433 | } |
| 2434 | |
| 2435 | int rx_world_add_reaction_keyed(RxWorld *w, const RxCallerKeyring *keys, |
| 2436 | const RxReactionDesc *d, uint32_t *out_id) { |
| 2437 | if (!d) return RX_ERR_ARG; |
| 2438 | RxReactionDesc k = *d; |
| 2439 | const RxCallerCred *c = rx_caller_find(keys, d->subject); |
| 2440 | if (c) k.caller = *c; |
| 2441 | int rc = rx_world_add_reaction(w, &k, out_id); |
| 2442 | rx_caller_wipe(&k.caller); |
| 2443 | return rc; |
| 2444 | } |
| 2445 | |
| 2446 | int64_t rx_world_publish_external(RxWorld *w, RxCapRef cap, const RxMutation *muts, uint32_t n) { |
| 2447 | if (!muts || n == 0 || n > RX_MAX_MUTATIONS) return RX_ERR_ARG; |
| 2448 | pthread_mutex_lock(&w->mu); |
| 2449 | if (w->halted) { /* R16 G6: nothing outside publishes */ |
| 2450 | w->halt.refused++; |
| 2451 | pthread_mutex_unlock(&w->mu); |
| 2452 | return RX_ERR_HALTED; |
| 2453 | } |
| 2454 | for (uint32_t i = 0; i < n; i++) { |
| 2455 | if (!ref_live(w, muts[i].obj)) { pthread_mutex_unlock(&w->mu); return RX_ERR_STALE_GEN; } |
| 2456 | int rc = rx_world_validate_cap(w, cap, w->external_subject, |
| 2457 | w->objects[muts[i].obj.id].resource, RX_RIGHT_WRITE, NULL); |
| 2458 | if (rc != RX_CAP_OK) { pthread_mutex_unlock(&w->mu); return RX_ERR_AUTHORITY; } |
| 2459 | } |
| 2460 | PendingWrite pw[RX_MAX_WRITES]; |
| 2461 | uint32_t n_pw = 0; |
| 2462 | int rc = stage_mutations(w, muts, n, NULL, 0, pw, &n_pw); |
| 2463 | if (rc != RX_OK) { pthread_mutex_unlock(&w->mu); return rc; } |
| 2464 | rc = bind_writes(w, pw, n_pw, w->external_subject); |
| 2465 | if (rc != RX_OK) { pthread_mutex_unlock(&w->mu); return rc; } |
| 2466 | RxCrumb k; |
| 2467 | memset(&k, 0, sizeof(k)); |
| 2468 | w->stats.externals++; |
| 2469 | k.kind = RX_CRUMB_EXTERNAL; |
| 2470 | k.reaction = UINT32_MAX; |
| 2471 | k.faculty = RX_FACULTY_EXTERNAL; |
| 2472 | k.n_caps = 1; |
| 2473 | stamp_cap(w, &k, 0, cap); |
| 2474 | k.t_start_ns = now_ns(); |
| 2475 | commit_writes(w, pw, n_pw, &k); |
| 2476 | k.t_end_ns = now_ns(); |
| 2477 | uint64_t cid = crumb_append(w, &k); |
| 2478 | finish_writes(w, pw, n_pw, cid, false); |
| 2479 | pthread_mutex_unlock(&w->mu); |
| 2480 | return (int64_t)cid; |
| 2481 | } |
| 2482 | |
| 2483 | static uint64_t read_u64(const uint8_t *p) { |
| 2484 | uint64_t v = 0; |
| 2485 | for (int i = 0; i < 8; i++) v |= (uint64_t)p[i] << (8 * i); |
| 2486 | return v; |
| 2487 | } |
| 2488 | |
| 2489 | static uint32_t read_u32(const uint8_t *p) { |
| 2490 | return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | |
| 2491 | ((uint32_t)p[3] << 24); |
| 2492 | } |
| 2493 | |
| 2494 | static int find_seat(const RxWorld *w, uint32_t seq) { |
| 2495 | for (uint32_t i = 0; i < w->n_reactions; i++) { |
| 2496 | const RxReaction *r = &w->reactions[i]; |
| 2497 | if (r->resident_seat && r->state == RX_RUNNING && (uint32_t)r->resident_seq == seq) |
| 2498 | return (int)i; |
| 2499 | } |
| 2500 | return -1; |
| 2501 | } |
| 2502 | |
| 2503 | static void seat_fail(RxWorld *w, uint32_t rid, RxCrumb *k, RxCrumbKind kind, int reason) { |
| 2504 | RxReaction *r = &w->reactions[rid]; |
| 2505 | if (r->state == RX_RUNNING) set_state(w, r, RX_PUBLISHING); |
| 2506 | if (kind == RX_CRUMB_INVALIDATED) set_state(w, r, RX_INVALIDATED); |
| 2507 | else if (kind == RX_CRUMB_REJECTED) set_state(w, r, RX_REJECTED); |
| 2508 | else set_state(w, r, RX_FAILED); |
| 2509 | k->kind = kind; |
| 2510 | k->reason = reason; |
| 2511 | k->t_end_ns = now_ns(); |
| 2512 | crumb_append(w, k); |
| 2513 | r->resident_seat = false; |
| 2514 | w->stats.resident_closed++; |
| 2515 | if (kind == RX_CRUMB_INVALIDATED) w->stats.invalidations++; |
| 2516 | else if (kind == RX_CRUMB_REJECTED) w->stats.rejected++; |
| 2517 | else w->stats.failed++; |
| 2518 | end_activation(w, rid); |
| 2519 | } |
| 2520 | |
| 2521 | int rx_resident_accept(RxWorld *w) { |
| 2522 | if (!w || !w->coherent) return RX_ERR_ARG; |
| 2523 | pthread_mutex_lock(&w->mu); |
| 2524 | OmegaSharedWorldDesc d; |
| 2525 | int tr = rx_resident_take_result(w, &d); |
| 2526 | if (tr == RX_ERR_NOT_FOUND || tr == RX_ERR_ARG) { |
| 2527 | pthread_mutex_unlock(&w->mu); |
| 2528 | return tr; |
| 2529 | } |
| 2530 | /* A result from a seat that was declared lost. Its claims already ended; |
| 2531 | * nothing it wrote may publish. */ |
| 2532 | if (d.producer_generation != w->seat_generation) { |
| 2533 | w->stats.desc_rejected++; |
| 2534 | pthread_mutex_unlock(&w->mu); |
| 2535 | return RX_ERR_STALE_GEN; |
| 2536 | } |
| 2537 | int rid = find_seat(w, d.arg_b); |
| 2538 | if (rid < 0) { |
| 2539 | pthread_mutex_unlock(&w->mu); |
| 2540 | return tr == RX_OK ? RX_ERR_NOT_FOUND : tr; |
| 2541 | } |
| 2542 | RxReaction *r = &w->reactions[rid]; |
| 2543 | const RxReactionDesc *desc = &r->desc; |
| 2544 | RxCrumb k; |
| 2545 | memset(&k, 0, sizeof(k)); |
| 2546 | k.reaction = (uint32_t)rid; |
| 2547 | k.faculty = desc->faculty; |
| 2548 | k.worker = RX_SEAT_BLACKWELL; |
| 2549 | k.wake_cause = r->resident_parent; |
| 2550 | k.t_start_ns = now_ns(); |
| 2551 | k.n_caps = desc->n_caps; |
| 2552 | for (uint32_t i = 0; i < desc->n_caps; i++) stamp_cap(w, &k, i, need_ref(w, desc, i)); |
| 2553 | add_parent(&k, r->resident_parent); |
| 2554 | uint32_t in = desc->triggers[0].obj.id; |
| 2555 | uint32_t id = desc->writes[0].obj.id; |
| 2556 | RxObject *a = &w->objects[in]; |
| 2557 | RxObject *o = &w->objects[id]; |
| 2558 | k.n_inputs = 1; |
| 2559 | k.inputs[0].obj = desc->triggers[0].obj; |
| 2560 | k.inputs[0].version = a->version; |
| 2561 | k.inputs[0].mask = RX_FIELD(0) | RX_FIELD(1); |
| 2562 | if (a->live) { |
| 2563 | add_parent(&k, a->field_writer[0]); |
| 2564 | add_parent(&k, a->field_writer[1]); |
| 2565 | } |
| 2566 | |
| 2567 | /* R16 G6 operator emergency stop: a seat result that lands while the |
| 2568 | * world is stopped is not published. The image is re-projected from the |
| 2569 | * world, the activation ends CANCELLED and runs again on resume. */ |
| 2570 | if (w->halted) { |
| 2571 | if (o->placed) rx_coherent_project(w, id); |
| 2572 | if (r->state == RX_RUNNING) set_state(w, r, RX_CANCELLED); |
| 2573 | k.kind = RX_CRUMB_CANCELLED; |
| 2574 | k.reason = RX_ERR_HALTED; |
| 2575 | k.t_end_ns = now_ns(); |
| 2576 | crumb_append(w, &k); |
| 2577 | r->resident_seat = false; |
| 2578 | w->stats.resident_closed++; |
| 2579 | w->stats.resident_halted++; |
| 2580 | w->halt.refused++; |
| 2581 | w->halt.cancelled++; |
| 2582 | if (r->episode_activations) r->episode_activations--; /* not spent */ |
| 2583 | r->rearm = true; |
| 2584 | end_activation(w, (uint32_t)rid); |
| 2585 | pthread_mutex_unlock(&w->mu); |
| 2586 | return RX_ERR_HALTED; |
| 2587 | } |
| 2588 | if (tr != RX_OK) { |
| 2589 | if (o->placed) rx_coherent_project(w, id); |
| 2590 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_REJECTED, tr); |
| 2591 | pthread_mutex_unlock(&w->mu); |
| 2592 | return tr; |
| 2593 | } |
| 2594 | uint32_t out_id = UINT32_MAX, out_gen = 0; |
| 2595 | if (d.payload_len >= 40) { |
| 2596 | out_id = read_u32(d.payload + 24); |
| 2597 | out_gen = read_u32(d.payload + 28); |
| 2598 | } |
| 2599 | /* A fault notice, or any object that moved since the claim, is stale. */ |
| 2600 | if (d.msg_type == RX_RING_FAULT || d.object_id != in || out_id != id || |
| 2601 | !a->live || !o->live || !a->placed || !o->placed || |
| 2602 | d.object_generation != a->generation || out_gen != o->generation || |
| 2603 | a->generation != desc->triggers[0].obj.generation || |
| 2604 | o->generation != desc->writes[0].obj.generation) { |
| 2605 | if (o->placed) rx_coherent_project(w, id); |
| 2606 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_INVALIDATED, RX_ERR_STALE_GEN); |
| 2607 | pthread_mutex_unlock(&w->mu); |
| 2608 | return RX_ERR_STALE_GEN; |
| 2609 | } |
| 2610 | /* Authority is checked again at publication. The notice must echo the |
| 2611 | * capabilities bound at claim time, and both must still validate. */ |
| 2612 | int cap_err = 0; |
| 2613 | RxCapRef in_cap = { UINT32_MAX, 0 }, out_cap = { UINT32_MAX, 0 }; |
| 2614 | if (d.payload_len >= RX_CAP_PAYLOAD) { |
| 2615 | in_cap = (RxCapRef){ read_u32(d.payload), |
| 2616 | read_u32(d.payload + 4) | |
| 2617 | (uint64_t)read_u32(d.payload + RX_CAP_GEN_HI_A) << 32 }; |
| 2618 | out_cap = (RxCapRef){ read_u32(d.payload + 32), |
| 2619 | read_u32(d.payload + 36) | |
| 2620 | (uint64_t)read_u32(d.payload + RX_CAP_GEN_HI_B) << 32 }; |
| 2621 | } |
| 2622 | if (in_cap.cap_id != a->cap.cap_id || in_cap.generation != a->cap.generation || |
| 2623 | out_cap.cap_id != o->cap.cap_id || out_cap.generation != o->cap.generation || |
| 2624 | validate_caps(w, desc, &cap_err) != 0 || |
| 2625 | rx_world_validate_cap(w, in_cap, desc->subject, a->resource, RX_RIGHT_READ, NULL) != |
| 2626 | RX_CAP_OK || |
| 2627 | rx_world_validate_cap(w, out_cap, desc->subject, o->resource, RX_RIGHT_WRITE, NULL) != |
| 2628 | RX_CAP_OK) { |
| 2629 | rx_coherent_project(w, id); |
| 2630 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_REJECTED, RX_ERR_AUTHORITY); |
| 2631 | pthread_mutex_unlock(&w->mu); |
| 2632 | return RX_ERR_AUTHORITY; |
| 2633 | } |
| 2634 | /* The chip finishing is not the commit. The input window must still |
| 2635 | * match the canonical input, and the output window must hold exactly the |
| 2636 | * sum in field 0 and the canonical values everywhere else. */ |
| 2637 | uint64_t parent = read_u64(d.payload + 16); |
| 2638 | const uint8_t *ain = w->coherent + a->region_offset; |
| 2639 | const uint8_t *win = w->coherent + o->region_offset; |
| 2640 | uint64_t f1 = (uint64_t)((uint32_t)a->field[0] + (uint32_t)a->field[1]); |
| 2641 | int torn = parent != r->resident_parent || read_u64(d.payload + 8) != a->version || |
| 2642 | read_u64(win) != f1; |
| 2643 | for (uint32_t f = 0; f < RX_MAX_FIELDS && !torn; f++) |
| 2644 | if (read_u64(ain + f * 8u) != a->field[f]) torn = 1; |
| 2645 | for (uint32_t f = 1; f < RX_MAX_FIELDS && !torn; f++) |
| 2646 | if (read_u64(win + f * 8u) != o->field[f]) torn = 1; |
| 2647 | if (torn) { |
| 2648 | rx_coherent_project(w, id); |
| 2649 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_REJECTED, RX_ERR_TORN); |
| 2650 | pthread_mutex_unlock(&w->mu); |
| 2651 | return RX_ERR_TORN; |
| 2652 | } |
| 2653 | RxMutation mut = { desc->writes[0].obj, 0, f1 }; |
| 2654 | PendingWrite pw[RX_MAX_WRITES]; |
| 2655 | uint32_t n_pw = 0; |
| 2656 | int src = stage_mutations(w, &mut, 1, desc->writes, desc->n_writes, pw, &n_pw); |
| 2657 | if (src != RX_OK) { |
| 2658 | rx_coherent_project(w, id); |
| 2659 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_REJECTED, src); |
| 2660 | pthread_mutex_unlock(&w->mu); |
| 2661 | return src; |
| 2662 | } |
| 2663 | src = bind_writes(w, pw, n_pw, desc->subject); |
| 2664 | if (src != RX_OK) { |
| 2665 | rx_coherent_project(w, id); |
| 2666 | seat_fail(w, (uint32_t)rid, &k, RX_CRUMB_REJECTED, src); |
| 2667 | pthread_mutex_unlock(&w->mu); |
| 2668 | return src; |
| 2669 | } |
| 2670 | set_state(w, r, RX_PUBLISHING); |
| 2671 | commit_writes(w, pw, n_pw, &k); |
| 2672 | o->coherency = RX_COHERENCY_SEAT; |
| 2673 | k.kind = RX_CRUMB_COMMIT; |
| 2674 | k.t_end_ns = now_ns(); |
| 2675 | note_value(w, r, 1, f1); |
| 2676 | uint64_t cid = crumb_append(w, &k); |
| 2677 | set_state(w, r, RX_COMMITTED); |
| 2678 | w->stats.commits++; |
| 2679 | r->commits++; |
| 2680 | r->resident_seat = false; |
| 2681 | w->stats.resident_closed++; |
| 2682 | finish_writes(w, pw, n_pw, cid, false); |
| 2683 | end_activation(w, (uint32_t)rid); |
| 2684 | pthread_mutex_unlock(&w->mu); |
| 2685 | return RX_OK; |
| 2686 | } |
| 2687 | |
| 2688 | static void ring_discard(RxWorld *w, uint64_t off) { |
| 2689 | OmegaSharedWorldRing *ring = (OmegaSharedWorldRing *)(w->coherent + off); |
| 2690 | uint64_t t = __atomic_load_n(&ring->tail, __ATOMIC_ACQUIRE); |
| 2691 | __atomic_store_n(&ring->head, t, __ATOMIC_RELEASE); |
| 2692 | } |
| 2693 | |
| 2694 | int rx_resident_seat_lost(RxWorld *w, int retry) { |
| 2695 | if (!w || !w->coherent) return RX_ERR_ARG; |
| 2696 | pthread_mutex_lock(&w->mu); |
| 2697 | /* The old seat's notices go with it. Nothing it left unread is taken by |
| 2698 | * the next seat, and nothing it wrote is accepted. */ |
| 2699 | ring_discard(w, rx_world_off_c2g()); |
| 2700 | ring_discard(w, rx_world_off_g2c()); |
| 2701 | w->seat_generation++; |
| 2702 | w->stats.seat_losses++; |
| 2703 | |
| 2704 | int lost = 0; |
| 2705 | for (uint32_t rid = 0; rid < w->n_reactions; rid++) { |
| 2706 | RxReaction *r = &w->reactions[rid]; |
| 2707 | if (!r->resident_seat || r->state != RX_RUNNING) continue; |
| 2708 | const RxReactionDesc *desc = &r->desc; |
| 2709 | uint32_t in = desc->triggers[0].obj.id; |
| 2710 | uint32_t out = desc->writes[0].obj.id; |
| 2711 | RxCrumb k; |
| 2712 | memset(&k, 0, sizeof(k)); |
| 2713 | k.reaction = rid; |
| 2714 | k.faculty = desc->faculty; |
| 2715 | k.worker = RX_SEAT_BLACKWELL; |
| 2716 | k.wake_cause = r->resident_parent; |
| 2717 | k.t_start_ns = now_ns(); |
| 2718 | k.n_caps = desc->n_caps; |
| 2719 | for (uint32_t i = 0; i < desc->n_caps; i++) stamp_cap(w, &k, i, need_ref(w, desc, i)); |
| 2720 | add_parent(&k, r->resident_parent); |
| 2721 | k.n_inputs = 1; |
| 2722 | k.inputs[0].obj = desc->triggers[0].obj; |
| 2723 | k.inputs[0].version = w->objects[in].version; |
| 2724 | k.inputs[0].mask = RX_FIELD(0) | RX_FIELD(1); |
| 2725 | /* Whatever the chip left in the output window is not the object. */ |
| 2726 | if (w->objects[out].placed) rx_coherent_project(w, out); |
| 2727 | set_state(w, r, RX_FAILED); |
| 2728 | k.kind = RX_CRUMB_FAILED; |
| 2729 | k.reason = RX_ERR_SEAT_LOST; |
| 2730 | k.t_end_ns = now_ns(); |
| 2731 | uint64_t fid = crumb_append(w, &k); |
| 2732 | r->resident_seat = false; |
| 2733 | w->stats.resident_closed++; |
| 2734 | w->stats.failed++; |
| 2735 | /* A newer wake already asks for another run; keep its cause. */ |
| 2736 | if (retry && !r->rearm) { |
| 2737 | r->rearm = true; |
| 2738 | r->wake_cause = fid; |
| 2739 | } |
| 2740 | end_activation(w, rid); |
| 2741 | lost++; |
| 2742 | } |
| 2743 | pthread_mutex_unlock(&w->mu); |
| 2744 | return lost; |
| 2745 | } |
| 2746 | |
| 2747 | int rx_resident_wait_outstanding(RxWorld *w, int timeout_ms) { |
| 2748 | struct timespec dl; |
| 2749 | clock_gettime(CLOCK_REALTIME, &dl); |
| 2750 | dl.tv_sec += timeout_ms / 1000; |
| 2751 | dl.tv_nsec += (long)(timeout_ms % 1000) * 1000000L; |
| 2752 | if (dl.tv_nsec >= 1000000000L) { dl.tv_sec++; dl.tv_nsec -= 1000000000L; } |
| 2753 | pthread_mutex_lock(&w->mu); |
| 2754 | int rc = RX_OK; |
| 2755 | while (w->stats.resident_claims <= w->stats.resident_closed && !w->stopping) { |
| 2756 | if (pthread_cond_timedwait(&w->claim_cv, &w->mu, &dl) == ETIMEDOUT) { |
| 2757 | rc = RX_ERR_TIMEOUT; |
| 2758 | break; |
| 2759 | } |
| 2760 | } |
| 2761 | pthread_mutex_unlock(&w->mu); |
| 2762 | return rc; |
| 2763 | } |
| 2764 | |
| 2765 | /* R15 sequential reference only (rx_seq_reference.c). Caller holds mu. Runs |
| 2766 | * one activation of `rid` on the calling thread through the same wake |
| 2767 | * accounting, admission, validation, snapshot, publication and crumb as a |
| 2768 | * worker would. Refused unless the world is the sequential reference. |
| 2769 | * Returns 1 if it ran (a graphics claim may still be outstanding), 0 if the |
| 2770 | * wake was suppressed or does not fit the budget now, negative on error. */ |
| 2771 | int rx_world_seq_activate_timed_locked(RxWorld *w, uint32_t rid, uint64_t cause, |
| 2772 | uint64_t poll_start, uint64_t poll_wall, |
| 2773 | uint64_t poll_cpu); |
| 2774 | int rx_world_seq_activate_locked(RxWorld *w, uint32_t rid, uint64_t cause) { |
| 2775 | return rx_world_seq_activate_timed_locked(w, rid, cause, 0, 0, 0); |
| 2776 | } |
| 2777 | |
| 2778 | /* As above, with the orchestrator's readiness poll for this stage (wall |
| 2779 | * start, wall and thread-CPU duration) carried into the activation's |
| 2780 | * scheduler time, so SEQ's polling is priced as RES's wake path is. */ |
| 2781 | int rx_world_seq_activate_timed_locked(RxWorld *w, uint32_t rid, uint64_t cause, |
| 2782 | uint64_t poll_start, uint64_t poll_wall, |
| 2783 | uint64_t poll_cpu) { |
| 2784 | if (!w || !w->sequential || rid >= w->n_reactions) return RX_ERR_ARG; |
| 2785 | RxReaction *r = &w->reactions[rid]; |
| 2786 | if (r->state != RX_DORMANT || r->removed) return RX_ERR_ARG; /* removed: never demanded */ |
| 2787 | if (w->halted) return RX_ERR_HALTED; /* R16 G6 operator emergency stop */ |
| 2788 | r->seq_pending = false; |
| 2789 | demand(w, rid, cause); /* R6 budgets and quarantine, unchanged */ |
| 2790 | if (!r->seq_pending) return 0; |
| 2791 | if (r->quarantined || !res_fits(w, r)) return 0; |
| 2792 | uint64_t c0 = w->timing ? thread_cpu_ns() : 0; |
| 2793 | uint64_t t0 = w->timing ? now_ns() : 0; |
| 2794 | if (w->timing) { |
| 2795 | /* The poll that found it ready is SEQ's wake: world totals already |
| 2796 | * hold every poll (rx_seq_pulse); this attributes this one. */ |
| 2797 | r->t_demand = poll_start; |
| 2798 | r->sched_ns += poll_wall; |
| 2799 | r->sched_cpu_ns += poll_cpu; |
| 2800 | } |
| 2801 | r->seq_pending = false; |
| 2802 | w->stats.wakes_accepted++; |
| 2803 | set_state(w, r, RX_BLOCKED_RESOURCE); |
| 2804 | r->wake_cause = cause; |
| 2805 | r->coalesced = 0; |
| 2806 | r->wait_seq = ++w->admit_seq; |
| 2807 | w->stats.blocked_resource++; |
| 2808 | set_state(w, r, RX_READY); |
| 2809 | charge(w, r); |
| 2810 | w->in_flight++; |
| 2811 | if (w->timing) { |
| 2812 | /* Admission is scheduling work, as it is for a worker. */ |
| 2813 | uint64_t t1 = now_ns(); |
| 2814 | uint64_t c1 = thread_cpu_ns(); |
| 2815 | r->t_ready = t1; |
| 2816 | r->sched_ns += t1 - t0; |
| 2817 | r->sched_cpu_ns += c1 - c0; |
| 2818 | w->stats.sched_wall_ns += t1 - t0; |
| 2819 | w->stats.sched_cpu_ns += c1 - c0; |
| 2820 | } |
| 2821 | run_one(w, rid, RX_SEQ_WORKER); |
| 2822 | return 1; |
| 2823 | } |
| 2824 | |
| 2825 | int rx_world_wait_quiescent(RxWorld *w, int timeout_ms) { |
| 2826 | struct timespec dl; |
| 2827 | clock_gettime(CLOCK_REALTIME, &dl); |
| 2828 | dl.tv_sec += timeout_ms / 1000; |
| 2829 | dl.tv_nsec += (long)(timeout_ms % 1000) * 1000000L; |
| 2830 | if (dl.tv_nsec >= 1000000000L) { dl.tv_sec++; dl.tv_nsec -= 1000000000L; } |
| 2831 | pthread_mutex_lock(&w->mu); |
| 2832 | int rc = RX_OK; |
| 2833 | /* Sequential reference: quiescent means a whole pulse that began after |
| 2834 | * this call found nothing ready. */ |
| 2835 | uint64_t started = w->seq_pulse_started; |
| 2836 | while (w->in_flight != 0 || w->deferred_len != 0 || |
| 2837 | (w->sequential && w->seq_idle_start <= started)) { |
| 2838 | if (pthread_cond_timedwait(&w->idle_cv, &w->mu, &dl) == ETIMEDOUT) { |
| 2839 | rc = RX_ERR_TIMEOUT; |
| 2840 | break; |
| 2841 | } |
| 2842 | } |
| 2843 | pthread_mutex_unlock(&w->mu); |
| 2844 | return rc; |
| 2845 | } |
| 2846 | |
| 2847 | int rx_world_read(RxWorld *w, RxObjRef ref, RxObject *out) { |
| 2848 | pthread_mutex_lock(&w->mu); |
| 2849 | int rc = ref_live(w, ref) ? RX_OK : RX_ERR_STALE_GEN; |
| 2850 | if (rc == RX_OK) *out = w->objects[ref.id]; |
| 2851 | pthread_mutex_unlock(&w->mu); |
| 2852 | return rc; |
| 2853 | } |
| 2854 | |
| 2855 | uint64_t rx_world_explain(RxWorld *w, RxObjRef ref, uint32_t field) { |
| 2856 | pthread_mutex_lock(&w->mu); |
| 2857 | uint64_t id = (ref_live(w, ref) && field < RX_MAX_FIELDS) |
| 2858 | ? w->objects[ref.id].field_writer[field] : 0; |
| 2859 | pthread_mutex_unlock(&w->mu); |
| 2860 | return id; |
| 2861 | } |
| 2862 | |
| 2863 | void rx_world_digest(RxWorld *w, uint8_t out[32]) { |
| 2864 | pthread_mutex_lock(&w->mu); |
| 2865 | sha256_ctx c; |
| 2866 | sha256_init(&c); |
| 2867 | sha256_update(&c, (const uint8_t *)"AIEN_RX_WORLD_V1", 16); |
| 2868 | for (uint32_t i = 0; i < RX_MAX_OBJECTS; i++) { |
| 2869 | const RxObject *o = &w->objects[i]; |
| 2870 | if (!o->live) continue; |
| 2871 | put32(&c, o->id); |
| 2872 | put32(&c, o->generation); |
| 2873 | sha256_update(&c, o->digest, 32); |
| 2874 | } |
| 2875 | sha256_final(&c, out); |
| 2876 | pthread_mutex_unlock(&w->mu); |
| 2877 | } |