diff --git a/OMEGA_SYSTEMS_CORE_CODE_AUDIT.md b/OMEGA_SYSTEMS_CORE_CODE_AUDIT.md new file mode 100644 index 000000000..5a88c9a36 --- /dev/null +++ b/OMEGA_SYSTEMS_CORE_CODE_AUDIT.md @@ -0,0 +1,659 @@ +# Omega Systems Core: code audit (OSC-0) and machine semantics freeze (OSC-0B) + +Status: **PROPOSED, awaiting review.** Nothing in this document changes production code. +Decision record: [docs/adr/OMEGA-SYSTEMS-CORE-0000.md](docs/adr/OMEGA-SYSTEMS-CORE-0000.md). +Evidence appendices (worker reports, reviewed and spot-checked): +[omega-runtime](docs/osc/audit/omega-runtime.md) (cited below as **[OR]**), +[aienos-physics](docs/osc/audit/aienos-physics.md) (**[AP]**), +[language-compiler](docs/osc/audit/language-compiler.md) (**[LC]**). + +Every claim carries one label: + +- **FACT**: what the current code does, with a file:line reference. +- **SETTLED**: an architecture decision already made in a spec or ADR. +- **PROPOSED**: the proposed OSC-0B ruling, which becomes frozen when this document is accepted. +- **OPEN**: a question that the code and the settled architecture cannot answer yet. An OPEN item must not be decided silently by whichever implementation lands first. + +Sequence (Drake, 2026-09-29): + +`OSC-0 audit → OSC-0B machine semantics freeze (hard gate) → OSC-1 smallest compiler slice → OSC-2 substrate + first real C migration` + +## Pins (reference truth) + +| Repo | Commit | Notes | +|---|---|---| +| omega | 193a7e7 (origin/main) | audited in place | +| aienos | 8706fb8 (origin/main) | `native/capability` is byte-identical to Omega's `aienos.lock` 4c21386 (git diff empty) | +| physics | fecbedb (origin/main) | equals Omega's `physics.lock` | +| aien-architecture | local checkout, may lag origin | ADR 0013, 0014, and doctrine cited by [AP] | + +FACT: the build does not enforce `aienos.lock`. The Makefile default is `AIENOS_R7_DIR ?= ../aienos-r9` (Makefile:185). On this host that checkout is at 187ecdf and has **no** `native/capability` directory, so a local R7 build needs an override. The audited authority is therefore the one pinned by the lock, not necessarily the one a local build links. + +--- + +# Part I: Audit (OSC-0) + +## I.1 Scope and size + +| Code | Lines | Source | +|---|---|---| +| Omega C (src, tests, tools; 212 files) | 87,486 | [OR] §1 | +| AIENOS C + asm, non-vendored | 1,268 | [AP] §1.1 | +| AIENOS Rust (14 crates; migration input only, No-Rust rule) | 57,841 | [AP] §1 | +| PHYSICS C + asm, non-vendored | 9,399 | [AP] §1.2 | +| Vendored (not audited) | ~631k Rust crates + NVIDIA 580.173.02 headers | [AP] §1 | + +## I.2 Classification (by lines, approximate) + +| Class | Omega | AIENOS + PHYSICS | +|---|---|---| +| A semantic code | ~17k | ~0 | +| B safe systems code | ~9k | ~960 | +| C physical realization | ~10k (C and D together) | ~2,450 | +| D unavoidable unsafe hardware boundary | (in the row above) | ~900 | +| E temporary bootstrap: test harnesses, tools, gate code | ~37k + ~2.4k of gate code living in src | ~2,600 | +| F obsolete, to retire | fixed-output stand-ins (self_host, realize_synth) | ~1,125: the M15 software model; the Rust aienos-capability(+ffi); the M3 trap collector | + +The per-file classification is in [OR] §1 and [AP] §1. + +## I.3 Hazard counts + +| Hazard | Omega | AIENOS + PHYSICS | +|---|---|---| +| malloc / calloc / realloc / free | 164 / 102 / 28 / 334 | 78 total, none in nvrm or m16 | +| `void*` | 312 | ~52 unsafe casts | +| Pointer arithmetic into mapped memory | 53 | see [AP] §2 | +| `goto` cleanup | 103 | 14 | +| `volatile` | 75 | see [AP] §3b | +| stdatomic / GCC atomic sites | 151 / 37 | authority: CAS plus pthread mutex | +| `dsb sy` | 18 | GPU submit path | +| Mutable globals | ~70 | 5 in nvrm.c, plus 1 function-local static | +| `_Static_assert` | 17 | **0** | +| Packed structs | 1 (SeatArgs, no asserts) | 0 | +| abort / assert / setjmp | 0 | 0 (PHYSICS asm panic-traps instead) | +| Separate generation / handle schemes | several (see I.5) | 8, in u32 and u64 widths | + +## I.4 Worst hazards (reviewed) + +For each hazard: where it is, what goes wrong, and what replaces it in Omega Systems Core. + +1. **Untracked grants to the GPU.** omega_accelerator_world.c:257-290 and :424-451 (spot-checked). + - `omega_world_resolve_buffer` checks epoch, generation, rights, and bounds correctly, then returns a raw CPU pointer and a GPU virtual address that nothing tracks. + - Revoke frees memory at once when no submission is in flight (:254). `scratch_reset` (:448) rewinds while slices may still be held. + - Replacement: a fence-scoped borrow (`slice` bounded by `own`), plus two-phase revocation (II.1). +2. **Free without device quiescence.** `nvrm_free` and `nvrm_channel_destroy` do not wait for the GPU (nvrm.c:674-706); capability revoke never unmaps or drains ([AP] §3f). + - This contradicts the SETTLED rule in native-frame-authority.md §6.4. + - Replacement: reclaim requires `own`. +3. **Completion read without acquire.** m16_native.c:97-108 (spot-checked). The poll uses a plain volatile read, so later reads of GPU results can be reordered before the marker read on AArch64. + - Replacement: `observe()` produces `own` (II.2). +4. **Shared function-local static in `uvm_map`.** nvrm.c:440 (spot-checked). Every `Nvrm` context shares it, so concurrent contexts race. + - Replacement: opaque `own`. Trivial C fix listed in I.8. +5. **Image moved under cached pointers.** rx_coherent.c:921-931 (spot-checked). `rx_world_bind_coherent` copies the coherent image and frees the old one; lock-free seat readers survive only because of call ordering ([OR] §3a). + - Replacement: the image is `pin`; moving it requires proof of no views and bumps the region generation (II.7). +6. **Live handles stored as durable identity.** rx_generation.c:560-565 (spot-checked) writes (slot id, generation, digest) rows to disk; crumb digests hash slot ids and generations (rx_world.c:139-156); `EffectPayload` embeds a live capability slot and generation inside a SemanticId payload (omega_types.h:160-167). + - Replacement: see II.6. +7. **Identity hashes depend on layout.** + - Whole-struct hashing: omega_program.c:276 (spot-checked; it also drops the last 32 bytes of the struct), omega_accelerator.c:83, omega_vector.c:23, omega_synthesis.c:98, and the M15 physics_accel.c:103,119. + - Canonical payloads memcpy host structs (omega_core.c:84 ff). + - Replacement: see II.3. +8. **Four memory-ordering idioms on one ABI** ([OR] §3a): + - `volatile` cast to `_Atomic`, which is formally undefined behaviour; + - GCC `__atomic` builtins; + - `volatile` plus `dsb sy`; + - a seqlock over a memfd. + + The seat flags (abort, marker_ok, sem_ok, lease_run) are `volatile`, not atomic. +9. **Unchecked construction and bounds.** + - pthread_create and mutex_init results are ignored (rx_world.c:1397-1405). + - `uint32_t pb[1024]` pushbuffers are filled without bounds checks (omega_blackwell_submit.c:131 ff). + - Silent truncation (rx_world.c:171-176; omega_accelerator_world.c:550). + - grow() doubles with no overflow check (rx_projection.c:143-152). +10. **Encoder silently masks immediates.** aarch64_encoder.c:114,122 (spot-checked). A misaligned or out-of-range offset is truncated instead of rejected, and SP and XZR share a register number in the API. + +## I.5 Existing mechanisms to preserve (FACT) + +- The pointer-free, offset-based shared world with epoch, generation, sequence, and checksum, and a hostile-input reader (omega_shared_world_abi.h:21-52; rx_coherent.c:287-398, 709-719). +- Generation checks that retire a saturated slot instead of wrapping (omega_accelerator_world.c:197-199, 248; aienos_capability.c:262-266). +- A handle epoch that is never reused (omega_accelerator_world.c:17-27); a capability restart floor above all earlier generations (aienos_capability.c:45-107). +- The `retiring` deferred free (omega_accelerator_world.c:84-93). CPU `mprotect(PROT_READ)` while the GPU owns a buffer, which is a hardware-enforced borrow (:659-665). +- Seat and producer generation fencing of a lost GPU engine (rx_world.c:1673-1680, 1814-1864). +- Snapshot-by-value reaction contexts (rx_world.h:185-222). +- Visor holds no runtime pointers (visor_world.h:60,73). +- Explicit-endian field encoders: + - big-endian in the graph and plan code (rx_graph.c:20-30); + - declared little-endian in the crumb and generation store (rx_world.c:44-66, 127-168; rx_generation.c:122-141). +- The capability rights model: + - 10 rights; privileged rights never delegable; delegation only narrows. + - Revoke cascades. + - Stale, revoked, epoch, expired, and chain errors all fail closed (aienos_capability.c:143-303). +- The M2 stackless trap collector (vector_table.s:161-268) as the reference for capture-and-halt. +- W^X JIT pages plus a sandbox with canaries (rx_omega.c:137-152, 400-460). +- Verification tiers V0/V1/V2 and the rx_contract publish gate ([LC] §5). + +## I.6 C ABI boundary that cannot disappear yet + +- The 19 `aienos_cap_*` functions (17 called by Omega), through Omega's hand-copied `aienos_cap.h`. Only size and two offsets are checked (rx_native_bind.c:10-16). +- `nvrm.c` and `m16_native.c` compiled into Omega. `Nvrm` field layout is a de facto ABI because Omega reads its fields. +- NVIDIA RM/UVM ioctl headers (vendored). +- libc on the semantic path: `memcpy memset memcmp strcmp strlen strstr snprintf calloc` ([LC] §7). Executing generated code needs `mmap mprotect munmap sysconf __builtin___clear_cache`. +- The two lock files. `physics.lock` is honoured; `aienos.lock` is not (see Pins). + +## I.7 Contradictions and rulings + +| # | Contradiction | Ruling | +|---|---|---| +| C1 | Capability generation width. The C authority and Omega runtime use u64 that never wraps. AIENOS ADR 0013, the Rust kernel, spec/type-system.md:35, EffectPayload, shared-world descriptor :130/132, and PHYSICS M2/M3/M15 use u32. rx_world.h:146-152 smuggles the high halves; rx_world.c:147 hashes only the low 32 bits. | **SETTLED for Omega effects after the pin:** omega#71 (main 8e7a445, spec/effect-cap64-migration.md, 5 OMEGA_EFFECT_CAP64 gates PASS) made `EffectPayload.capability_generation` u64 with an explicit 178-byte big-endian v2 encoder (canonical version byte 0x02 for EFFECT). v1 effect bytes are refused, never reinterpreted. The crumb_hash low-32 truncation and type-system.md:35 are being fixed on that session's branch fix/crumb-cap-gen64. **DECIDED (Drake, 2026-09-29) for the rest: u64 end to end**, slot retired at max. This amends AIENOS ADR 0013 (amendment note in docs/adr/OMEGA-SYSTEMS-CORE-0000.md; the AIENOS-side edit is follow-up work OSC-2) and covers the Rust kernel, the shared-world descriptor :130/132, src/omega_accelerator.h, and PHYSICS M2/M3/M15. Note that #71 still puts the live slot and generation inside the EFFECT canonical payload, so II.6 stays PROPOSED. | +| C2 | canonical-encoding.md says the payload is always big-endian; omega_core.c copies host little-endian structs. | Both SETTLED documents stand, but for different layers (II.3). Canonical SemanticId payloads must move to explicit big-endian encoders. This is a deliberate identity break with a version bump (OSC-2 follow-up). | +| C3 | Two digest byte orders coexist (big-endian rx_graph and plan; little-endian crumb and generation store). | Not a contradiction once declared: they are different **WireLayouts**. The rule is that every wire format declares its byte order and is written by an encoder. | +| C4 | Who owns authority: the PHYSICS README ("PHYSICS AUTHORIZES", SMMUv3) versus ADR 0014 (AIENOS owns interrupts, capabilities, and DMA confinement; FORGE/PHYSICS is realization only). | **SETTLED by ADR 0014.** The PHYSICS M3 ledger and effect broker are class F legacy evidence. The README claim is stale. | +| C5 | Release requires DMA quiescence (native-frame-authority.md §6.4) versus release paths that do not wait. | SETTLED rule; the code violates it. PROPOSED II.1 encodes it in types. | +| C6 | TRUST.md:260 "OOM panic, core" versus error-code OOM everywhere in the code. | Resolved by context (II.4). An OOM with no possible recovery (core init, trap or IRQ) traps; runtime allocation paths return a typed error. | +| C7 | The shared-world ABI says 64 objects (omega_shared_world_abi.h:254); rx_coherent.c writes 256. The ABI header claims to live in PHYSICS but lives in Omega. | **OPEN** (ABI v2 question, not language semantics). | +| C8 | README "OMEGA is not a programming language/compiler" versus spec/omega-language-v0.md and self-host.md. | **DECIDED (Drake, 2026-09-29).** The README doctrine is retired: Omega is the reaction runtime and the compiler for Omega Systems Core (README.md updated; recorded in OMEGA-SYSTEMS-CORE-0000). The M6 "C1==C2==C3" result is a self-copy quine and is never evidence of compilation ([LC] §3). | +| C9 | semantic-object.md:52 "fully relocatable" versus the pinned crumb log and the JsReal pointer graph. | The statement holds for **semantic** objects, not runtime realizations. II.7 makes the difference explicit. | +| C10 | The ABI comments say head/tail are atomics, but they are declared `volatile uint64_t`. | PROPOSED II.2: a `device>` type replaces the declaration. | +| C11 | Omega pins aienos 4c21386, but the default local build directory lacks the code. | FACT recorded. Enforcing the lock is a follow-up (I.8). | + +The full lists are in [OR] §8, [AP] §8, and [LC] "Contradictions". + +## I.8 Recommended follow-ups (not done here; production edits are out of scope for this stage) + +- nvrm.c:440: remove the function-local static. +- m16_native.c:103: make the successful marker read an acquire. +- omega_program.c:276: fix the SynthesisTask hash range. +- rx_world.c:1397-1405: check pthread results. +- Bound every `pb[n++]`. +- Remove `aienos_cap_force_generation` from the production ABI. +- `restart` must not revive a killed writer. +- Makefile: enforce `aienos.lock`. +- Put the shared-world ABI header in a single location. + +Each of these is a separate, small, reviewable change, to be scheduled after this freeze. + +## I.9 Candidate first real migration (OSC-2) + +1. **crumbline**, [OR] §6 (recommended first): + - `src/crumbline`, 1,216 lines, plus the learner tool. + - CPU-only, deterministic, pointer-plus-length buffers, existing tests, no PHYSICS link. + - Exercises `slice`, `own`, and `Result`. +2. **rx_cortex + rx_projection** (~1,300 lines). The main hazard is interior pointers invalidated by realloc, which is exactly what arenas and offset handles fix. +3. **visor_parse_command** (260 lines). The smallest first C ABI adapter. + +Do not migrate first: rx_world, rx_coherent, rx_resident_gpu, the accelerator world, and canonical/sha256. + +## I.10 Performance baseline + +Host-only, CPU-side. Captured by a Sonnet 5.5 worker and sample-verified by the orchestrator. Full data and method: [baseline](docs/osc/audit/baseline.md). + +Setup: +- gcc 13.3.0 at -O2 on aarch64, 20 cores. +- The machine was not quiet (load average 1–2.5). +- Build time is the median of 5 clean builds. +- Allocations are summed over every process a test starts. + +| Binary | Build (s) | Size text+data+bss | Peak RSS (kB) | Allocs | Frees | Live at exit | +|---|---|---|---|---|---|---| +| omegatool | 1.20 | 367,386 | not run | not run | not run | not run | +| rx_heartbeat_test (R3) | 1.85 | 198,215 | 5,568 | 396 | 386 | 13 | +| rx_action_graph_test | 2.08 | ~504k | 4,212 | 445 | 435 | 13 | +| rx_state_projection_test | 2.26 | 169,543 | 120,480 | 83,026 | 105,057* | 13 | +| rx_plan_reuse_test (informational) | 2.06 | ~627k | 5,584 | 199,695 | 199,683 | 15 | +| rx_capability_query_test | 2.13 | ~555k | 119,628 | 23,687 | 23,699* | 11 | +| rx_typed_results_test | 2.16 | 3,453,513 | 21,284 | 19,932 | 19,922 | 13 | +| crumbline decode | 0.36 | ~1.13M | 1,328 | 4 | 3 | 1 | + +\* Frees can exceed allocs because reallocations are counted separately. + +A floor of about 10–13 live blocks (~7 KB) at exit appears in almost every test and has not been attributed to a cause, so it is **not** evidence of leaks. + +**Not measured:** +- the GPU/accelerator workloads (silicon, R12–R15, M17); +- the R7–R11 targets, branch reuse, and the Visor targets; +- the M5–M19 gates; +- the crumbline conformance sweep; +- fragmentation beyond mallinfo2 at exit; +- throughput and latency (no host test prints them). + +These gaps must be filled on a quiet machine before any OSC-15 comparison. + +--- + +# Part II: Machine semantics freeze (OSC-0B) + +The core principle is that **the replacement for the pointer is an object relationship.** Every object has three properties, tracked independently: + +- **LIFETIME**: who keeps it alive; +- **AUTHORITY**: who may operate on it; +- **PLACEMENT**: where it is physically realized right now. + +C folds all three into one address. Item II.12 is the rule that keeps them apart. + +## II.1 Concurrency and publication (CPU, GPU, threads, interrupts) + +**FACT.** +- RxWorld mutates under one mutex with up to 16 workers, plus seat launch and lease threads (rx_world.c:1402; rx_resident_gpu.c:950-1071). +- CPU→GPU goes through SPSC rings: the CPU writes a slot, seals it with a CRC, issues a release fence, and release-stores the tail (rx_coherent.c:721-733). The reverse direction uses an acquire-load of the tail and then validates magic, epoch, and checksum (:885-897). +- The non-resident path uses a pushbuffer, a doorbell, and a polled marker. +- PHYSICS has **no interrupts**; every exception captures and halts ([AP] §3a). AIENOS's (Rust) kernel handles only the timer IRQ. + +**SETTLED.** +- The ring discipline: free-running u64 counters, release publish, fail-closed reader (omega_shared_world_abi.h:21-52; r12-resident-seat.md). +- Stale claims are refused after a seat or object generation moves (r12-resident-seat.md:34-70). +- Release requires DMA quiescence (native-frame-authority.md §6.4). +- AIENOS owns interrupts (ADR 0014). +- Cooperative "quit" instead of killing a channel (03d2820). + +**PROPOSED.** +1. **No data races in safe code, by construction.** A value is either shared and immutable, or held by exactly one mutable owner or borrow. Cross-participant sharing is only through types: `atomic`, `mutex`, `seqlock` (values out, bounded retry, dead-writer check), `ring` (SPSC), and `device` cells. Two engines can never both hold mutable access through addresses. +2. **Publication is a named pair.** A write becomes visible to another participant only through a *publish* (release semantics) matched by an *observe* (acquire semantics) on the same cell or ring. There is no other visibility guarantee, even on coherent memory. +3. **Completion is a value.** Device completion produces `own` only from an acquire observation of a marker or semaphore. Retiring ring entries, reusing pushbuffers, and reclaiming memory all consume a Fence. Polling without acquire is not expressible in safe code. +4. **Revocation is two-phase.** + - (a) *Revoke*: no new uses. Immediate; table state only. + - (b) *Reclaim* of memory, virtual addresses, frames, or channels: requires `own`, a proof that the device has drained (fence observed or channel torn down). On native hardware this also requires SMMU unmap, TLBI, and CMD_SYNC. + + Reclaim without the token is a type error. +5. **Generation change while a view is live.** Every borrow handed to another engine is scoped by a Fence. An object generation bump invalidates outstanding claims, records the event, and refuses late results (the r12 rule). A view does not survive a generation change. +6. **Interrupt context is an effect:** `ctx(irq)` and `ctx(trap)`. Code in these contexts cannot allocate, take a blocking lock, or call the authority's mutating API; the checker enforces this through the effect system. IRQ↔thread sharing only through atomics or IRQ-masked critical sections. +7. **Cancellation is cooperative.** It is a request observed at defined points, and it never tears memory away from a live view (generalizes 03d2820). + +**OPEN.** +- Whether `rx_world_relocate_physical` must refuse or invalidate while a resident claim is outstanding (rx_coherent.c:661-700). +- How finely the runtime is divided into fault domains (see II.4). + +## II.2 Atomics and memory ordering + +**FACT.** There are four coexisting idioms (I.4 #8). The authority uses a mutex plus acquire-release CAS; nvrm has no lock. `dsb sy` is stronger than needed but correct ([AP] §3b). + +**PROPOSED.** Omega owns its ordering vocabulary. Each operation is defined below, with its C11 equivalent and AArch64 lowering given for the bootstrap and for review. `volatile` is banned from safe code. + +| Omega operation | Guarantee | C11 equivalent | AArch64 lowering | +|---|---|---|---| +| `load_relaxed` / `store_relaxed` | atomic, no ordering | relaxed | LDR / STR | +| `load_acquire` | later accesses stay after it | acquire | LDAR | +| `store_release` | earlier accesses stay before it | release | STLR | +| `rmw_acq_rel` (CAS, fetch_add) | both | acq_rel | CASAL / LDAXR+STLXR | +| `seq_cst` operations | single total order | seq_cst | LDAR/STLR (+ DMB ISH where needed) | +| `fence_acquire` / `fence_release` | standalone fences | atomic_thread_fence | DMB ISHLD / DMB ISH | +| `publish_device(cell)` | CPU writes visible to the device before the cell | (none) | DMB OSHST, then store; DSB ST before a doorbell MMIO store | +| `observe_device(cell) -> Fence` | device writes visible after the observation | (none) | LDAR (or LDR + DMB OSHLD) | +| `mmio_read` / `mmio_write` | exactly once, in order, never merged | (volatile) | LDR/STR to Device memory, DSB where the device requires it | +| `isb` | instruction stream resynchronized | (none) | ISB | +| `cache_clean(range)` / `cache_invalidate(range)` | non-coherent DMA visibility | (none) | DC CVAC / DC CIVAC + DSB | + +The bootstrap may keep the stronger `dsb sy` inside these primitives until measurement justifies weakening it. The four current idioms each map onto rows of this table. + +## II.3 Semantic, runtime, wire, and device layout + +**FACT.** +- Canonical payloads are memcpy'd host structs (omega_core.c:84 ff; [LC] §3). +- Several digests hash whole native structs (I.4 #7). +- `RxCapEntry` has implicit padding and is shared across processes (rx_caproot.h:120-133). +- The only packed struct, SeatArgs, has no asserts. +- AIENOS and PHYSICS have 0 `_Static_assert`. +- Hardware formats are built with shifts, in little-endian. + +**SETTLED.** +- canonical-encoding.md: big-endian canonical encoding for SemanticId. +- The shared world is little-endian "Zero Serialization" with fixed offsets (omega_shared_world_abi.h:30-38). +- AIENOS ADR 0013 and 0015 define explicit little-endian wire layouts. +- The V0 AST is disposable; identity attaches to the lowered form, never to syntax. + +**PROPOSED.** Four layouts, never mixed: + +- **SemanticLayout.** Abstract meaning; never observable. Identity comes only from its canonical encoding. +- **RuntimeLayout.** Chosen by the compiler; unobservable in safe code. No hashing, serialization, or foreign exposure of runtime-layout values. +- **WireLayout.** Every byte that is hashed, persisted, or put in a receipt comes from a generated encoder with a declared byte order. The SemanticId encoding is big-endian (SETTLED); evidence and store formats may be little-endian if declared. There is no implicit padding: reserved bytes are explicit and zero. Raw struct hashing is forbidden. +- **DeviceLayout.** Declared with explicit width, offsets, byte order, and alignment. Used for hardware formats, shared-world records, and C ABI structs. The compiler checks size and offsets, and generates C headers with `_Static_assert`. This replaces hand-copied headers such as `aienos_cap.h`. + +Enums and tagged unions have an explicit tag width wherever they appear in wire or device layouts. + +## II.4 Failure semantics + +**FACT.** +- There are no aborts or asserts; everything returns negative error codes ([OR] §3c, [AP] §3e). +- PHYSICS panic-traps on ingress and invariant failures, and returns 0 when frames run out. +- nvrm has a sticky `faulted` flag and quarantines virtual addresses. +- Device loss is seen only as a timeout, because the RM error notifier is never read (nvrm.c:629,635). + +**SETTLED.** +- Fail closed. +- "No action without evidence": a full crumb log refuses action (rx_world.c:179-183). +- Deterministic crash records (AIENOS ADR 0006). +- TRUST.md: OOM in the core is catastrophic. + +**PROPOSED.** No stack-unwinding exceptions. Expected failures are typed `Result` errors that the caller must handle. Invariant violations are deterministic **traps**. + +| Failure | Ordinary code | `ctx(trap)` / `ctx(irq)` / core init | +|---|---|---| +| Out of memory / exhaustion | `Err(NoMem)` / `Err(Exhausted)` | error value where a caller exists; trap only where no recovery path exists (core init) | +| Bounds, dynamic | `a[i]` traps; `a.get(i)` returns `Option` | trap | +| Integer overflow (default ops) | trap | trap | +| Stale generation / epoch | `Err(Stale{object, held_gen, current_gen})` | error value, fail closed | +| Device vanished | `Err(DeviceLost)`, sticky per device session, sourced from the error notifier *and* timeouts | trap if no session owner can record it | +| Failed construction | no object exists; fields already built are destroyed in reverse order | same | +| Cleanup failure | device release is an explicit must-use `Result`. A device object dropped without release goes to quarantine (retiring) and its owner is marked faulted. Never ignored | same | +| Invariant violation | trap plus an evidence record (crumb or fault mailbox) | stackless capture and halt (the M2 collector is the reference) | + +A **trap** is a deterministic fail-stop of the enclosing fault domain, recorded as evidence. In the bootstrap, that domain is the process. + +**OPEN.** Finer-grained fault domains: per reaction, per task, or per world. + +## II.5 Cyclic object graphs and weak references + +**FACT.** +- The only owning pointer graph is the refcounted JsReal DAG; its `refs` counter has no overflow check (rx_jspace.h:96-111). +- Capability chains, crumb parents, and cortex links are ids, and acyclic by construction. +- Back-pointers such as `RxGpuSeat.world` (rx_resident_gpu.c:59) are not tied to a lifetime: destroying the world before the seat is a use-after-free. + +**SETTLED.** The content-addressed graph model: relations by SemanticId (semantic-object.md). + +**PROPOSED.** +- **Ownership forms a forest.** No `own` cycle is expressible. +- Graph-shaped data is owned by a pool, arena, or graph store. Edges are `handle`, `weak`, or `SemanticId`, never owning. +- Reference counting exists only as an explicit `rc` inside a region, with checked counters and an acyclicity rule. It is never the default. +- A back-reference to an owner is a borrow with a lifetime tie. For example, the seat borrows the world, so destroying the world while the seat lives is a compile error. +- `weak` is fallible: resolving it returns `Option`, checked by generation. + +## II.6 Live handles versus persistent identity + +**FACT.** The distinct types already exist ([LC] §3): + +- `SemanticId`: content identity. +- `OmegaHandle{epoch, object_id, u32 generation, type, rights}`: live accelerator handle. +- `RxCapRef` / `AienosCapRef{id, u64 generation}`: live capability references. + +However, live handles *do* enter durable identity: in EffectPayload, in generation-store rows, and in crumb digests (I.4 #6). No CPU address or GPU virtual address was found in any durable record. + +**PROPOSED.** These are distinct, non-interchangeable types: + +| Type | Meaning | Durable? | +|---|---|---| +| `SemanticId` | identity across time, storage, and machines (hash of the canonical encoding) | yes | +| `PersistentRef` | resolvable after relocation or reboot (SemanticId or declared durable id, plus store generation) | yes | +| `Handle` | live identity inside a resident generation: {slot, u64 generation, world epoch, type, rights} | **no** | +| `&T` / `&mut T` | temporary access permission | no | +| `slice` | bounded temporary view | no | +| `pin` | intentionally fixed physical realization | no | +| `DeviceRef` | capability-bound physical resource | no | + +Rules: +- Non-durable types (handles, borrows, slices, pins, device references, addresses) are **statically rejected** by the canonical encoder and by every durable-store or receipt writer. +- The only conversion is an explicit `persist(h) -> SemanticId/PersistentRef`, which resolves the live object. +- A handle carries its world epoch, so a handle from an earlier boot fails closed (the existing epoch pattern). +- Generation width: see C1 (u64 end to end, DECIDED 2026-09-29). + +**DECIDED (Drake, 2026-09-29).** Migrating the existing on-disk R9 generation store, crumb digests, and EffectPayload is an identity break. It is scheduled for OSC-2, right after the compiler slice, as a versioned transition: a new canonical version byte, and old records are refused, never reinterpreted (the omega#71 effect-cap64 pattern). Constraint: TURING records hash omega_canonical_encode OMG0 bytes, so any OMG0 encoder change (including the C2 big-endian move) ships with a TURING record version bump and a verification path for existing golden digests. See OMEGA-SYSTEMS-CORE-0000, "Decisions 2026-09-29", item 4. + +## II.7 Relocation, compaction, and pinning + +**FACT.** +- The shared world uses offsets and is relocatable (omega_shared_world_abi.h:207). +- Pinned by design: the crumb log, RxWorld (embedded mutex), GPU memory at identity virtual addresses, JIT pages, and PHYSICS fixed regions. +- Relocations that break interior pointers: arena realloc (rx_projection.c:526), JsBranch units, and bind_coherent. + +**PROPOSED.** +- **Movable by default.** Long-lived objects are reached through handles, so the runtime may compact pools by rebinding slot→placement without changing the handles. +- **`pin` is rare, and created only in `unsafe physical`.** It is required for: + - memory shared with another engine; + - OS or hardware synchronization objects; + - fixed physical regions; + - executable pages; + - logs handed out by address. +- **Moving a pinned region** requires a proof of no outstanding views (all Fences observed, all borrows ended), and it bumps the region generation. +- **Arena growth** is a mutation of the arena, so it is a compile error while any borrow into the arena is live. Long-lived references into arenas are offsets or handles. + +## II.8 MMIO, DMA, volatile, interrupts, cache, and no-block contexts + +**FACT.** +- PHYSICS runs with the MMU off (Device memory), has no cache maintenance, and has no SMMU code; Linux owns the SMMU for now. +- GPU memory is coherent and snooped. +- GPU virtual address equals CPU virtual address by construction (nvrm.c:485-489, 433-437). +- Atlas hands off without an I-cache synchronization. +- The PL011 UART trap path busy-waits by design. + +**SETTLED.** +- AIENOS owns DMA confinement and devices (ADR 0014). +- Reclaim requires SMMU unmap, TLBI, and SYNC (native-frame-authority.md §6.4). +- On v1, the boot CPU alone owns the frame authority (§6.5). + +**PROPOSED.** +- **Physical code lives in `unsafe physical` blocks.** Every such block must declare: + - `requires capability<...>`, alignment, and range; + - `ensures ...`; + - an audit record, negative tests, and bounds, ownership, and capability documentation. +- **Registers** are `mmio`, accessed only through `mmio_read` / `mmio_write` (II.2). +- **DMA buffers** are `device` over `pin`, with placement recorded. Non-coherent placements require `cache_clean` before the device reads and `cache_invalidate` after the device writes. +- **No-block / no-allocate contexts** are the `ctx(irq)` / `ctx(trap)` effects (II.1). + +**OPEN.** +- Whether native GB10 system memory is coherent for every GPU engine (native-frame-authority.md §9 says "assumed"). +- Whether GPU-uncached allocations need CPU-side cache maintenance natively. +- The Atlas I-cache synchronization once caches are on natively (atlas_m2.s:130-134). +- That RM keeps pages pinned for the life of the memory object is an assumed NVIDIA contract, not verified. + +## II.9 Deterministic, reproducible compilation + +**FACT.** +- Build flags: `-std=gnu11 -O2 -Wall -Wextra -Werror`, with no `-ffile-prefix-map`, no SOURCE_DATE_EPOCH, and no build-twice check. +- Makefile:14 bakes in `OMEGA_PHYSICS_DIR`. +- Receipts embed wall time and the git sha by design. +- Capability generations seeded from boot time flow into crumb digests (rx_caproot.c:52-73; rx_world.c:145-149). +- M6 "C1==C2==C3" holds by self-copy, not by compilation (tests/run_m6_gates.sh:78-83). + +**PROPOSED.** +- Compiler output is a pure function of (source bytes, compiler identity digest, target profile, declared flags): + - no timestamps, paths, or environment in the output; + - no hash-iteration-order dependence (ordered containers only). +- The verified IR ("Flow IR", which does not exist yet; the name is free) has a canonical encoding and a digest. +- Every build writes a receipt with the compiler digest, input digests, and output digest. +- Required gates: + - **build twice, compare bytes**; + - a differential oracle (the C backend) whose output is never identity; + - **bootstrap equivalence**, defined as `compiler_n` built by `compiler_{n-1}` producing byte-identical outputs on a fixed test corpus. Self-copy is never evidence. +- Bootstrap C builds add `-ffile-prefix-map`. +- Nondeterministic inputs (boot-time generations, run ids) are excluded from semantic digests. + +## II.10 Minimal standard substrate + +**FACT.** On the semantic path, Omega leans only on `memcpy memset memcmp strcmp strlen strstr snprintf calloc`. SHA-256 is in-house. printf, fopen, qsort, and malloc live in gates and tools ([LC] §7). + +**PROPOSED.** The v0 substrate (so that production code has no reason to fall back to C): + +- `Option`, `Result`; +- checked, `wrap_`, `sat_`, and `overflowing_` integers; +- `slice`, `bytes`, `str` (validated UTF-8, bounded); +- `vec` (owned, growable, checked), fixed arrays, `ring`; +- `arena` / `region`, `pool` with `Handle`; +- an ordered map and a deterministic hash map (iteration order independent of hashing); +- total-order sort; +- SHA-256 and the canonical encoder/decoder; +- the II.2 atomics vocabulary, `mutex`, `seqlock`, `Fence`; +- formatted output for receipts; +- file I/O through a capability. + +It is built in C first as the bootstrap runtime, then ported. + +## II.11 Executable model of the memory rules + +**FACT.** No fuzzer or property generator exists in the language or core ([LC] §5). V1 differential testing (native versus `omega_eval`) is the existing oracle pattern. + +**PROPOSED.** A small executable reference model, in C, is the **OSC-0B exit gate** (it is not compiler work). It is a state machine over objects, slots, generations, regions, borrows, and publication. + +Object states: `unallocated → owned → {borrowed_shared(n) | borrowed_mut} → moved | released`. A slot moves `free(g) → live(g) → free(g+1)`, and at the maximum generation it becomes `retired`. Regions go `open → destroyed`. Cells go `written → published(release) → observed(acquire)`. + +Valid transitions are the ones this document allows. Named **invalid** transitions, each of which must be rejected deterministically: + +- use after move +- use after release +- double release +- stale-generation use +- generation wrap +- mutable alias (a second `&mut` or mixed `&`/`&mut`) +- borrow outlives owner +- arena escape (reference outlives its region) +- reclaim without `Quiesced` +- read of device data before `observe` +- publish without release +- forged rights (rights wider than the parent) +- live handle written to a durable encoder + +A seeded, deterministic random-sequence generator drives the model; later, OSC-1/2 compiler output is compared against it (V1 style). Launched only after this document is reviewed. + +## II.12 Lifetime, authority, and placement per object + +**FACT.** Today the three are tangled: a raw pointer grants all three. The current per-object tables are in [OR] §7 and [AP] §7. + +**PROPOSED.** The compiler and runtime track them independently: + +- **Lifetime** is in the type: inline, `own`, borrow, region, `Handle` pool, static, device, or persistent. +- **Authority** is in rights: `Handle` rights and capabilities. Delegation narrows only (SETTLED, aienos_capability.c:240-254). Mutability is authority. +- **Placement** is realization metadata, not type, unless the object is `pin` or `device`. PHYSICS may change placement without changing meaning. + +Example: + +``` +Tensor T: + identity: SemanticId 84A7... + lifetime: World generation 9182 (pool handle) + authority: CPU read; GPU read+mutate (capability 17 gen 5) + placement: unified physical region 31 (pinned while a GPU claim is live) + mutation epoch: GPU / generation 217 +``` + +--- + +# Part III: The OSC-0 contract + +## III.1 Reference and type taxonomy + +| Form | Meaning | +|---|---| +| `T` | value owned inline | +| `own` | unique dynamic ownership | +| `&T` / `&mut T` | shared or exclusive bounded borrow | +| `slice` | bounded contiguous view | +| `arena` / `region` | objects sharing one explicit lifetime epoch | +| `Handle` | live, generation-checked logical reference | +| `weak` | non-owning fallible reference | +| `SemanticId`, `PersistentRef` | durable identity (II.6) | +| `pin` | non-relocatable physical realization | +| `device`, `DeviceRef`, `mmio` | capability-controlled physical objects | +| `Fence`, `Quiesced` | linear proofs of completion and drain (II.1) | + +Safe code has no `T*`, `void*`, address arithmetic, arbitrary casts, manual `free`, array decay, null dereference, uninitialized reads, unbounded strings, silent overflow, implicit ownership transfer, or unrestricted mutable aliasing. + +## III.2 Ownership and lifetime rule + +Every live object has exactly one mechanically known lifetime strategy: stack, unique, region, generation pool, static, device, or persistent. Destruction is deterministic with the owner unless the object is explicitly moved into another domain. There is no default tracing GC. Preferred order: stack → own → arena → generation pool → content-addressed → persistent store → capability-controlled device. + +## III.3 Integers and aliasing + +- Default arithmetic is checked (trap on overflow). Explicit `wrap_add`, `sat_add`, and `overflowing_add` are available. There are no implicit promotions. +- The existing V0 unsigned `WRAP` stays for backward compatibility; the new signed types use `OVERFLOW_FAIL_CLOSED` (an existing enum value). +- Aliasing: many readers **or** one mutable. Mutability is authority. + +## III.4 Unsafe physical boundary + +The only place raw addresses exist is inside `unsafe physical { ... }` with the declarations required by II.8. Unsafe is the implementation surface for physical primitives (`pin`, `device`, `mmio`, DMA, fences), not a switch to turn the language off. + +## III.5 C ABI boundary + +Foreign declarations must state, per parameter: + +- borrowed or owned; +- nullable; +- length source; +- mutability; +- lifetime; +- thread safety. + +Unknown means unsafe. No unannotated C pointer enters safe code as a trusted reference. Layouts crossing the boundary are DeviceLayout, and the compiler generates the C headers with asserts. The first adapters are `aienos_cap_*` and `visor_parse_command`. + +## III.6 Compiler pipeline and backend + +1. lexer/parser, **extending V0's grammar**: V0 already reserves `i64 mut struct if while return unsafe cap`, so no competing grammar is invented ([LC] §1). +2. typed AST (disposable) +3. name/type resolution +4. ownership graph +5. borrow/lifetime analysis +6. effect/capability analysis (`ctx(...)`, `requires`, `effects`) +7. verified typed IR ("Flow IR", canonical encoding plus digest) +8. realization + +The backend is **direct AArch64 through the in-repo encoder**, after hardening: reject masked immediates, separate SP from XZR, and add ADDS/SUBS, LDP/STP, BL/BLR, SMULH, and stack frames, with every instruction mirrored in the verifier's decoder. Estimate: 4–7 worker-days. A **C-emitting backend compiled by system cc** is allowed only as a differential oracle, never as shipped output or semantics. + +Diagnostics must name the object, lifetime, borrow, conflicting access, generation, capability, origin, and the attempted transition. + +**DECIDED (Drake, 2026-09-29).** In OSC-1, `requires` / `ensures` are text only: recorded, not checked. Enforcement is OSC-2 and is MANDATORY. No production C migrates into Omega Systems Core until enforcement is on. + +## III.7 Migration order + +- **OSC-0** (this document) +- **OSC-0B** (Part II, plus the II.11 model as the exit gate) +- **OSC-1:** the smallest vertical slice. Source → parser → typed value → unique allocation → borrow → bounds check → deterministic destruction → native execution. It covers the scope of the original OSC-1 through OSC-3. +- **OSC-2:** the substrate (II.10), arenas, and generational handles. The first real migration is crumbline (I.9). Covers the original OSC-4, OSC-5, and OSC-9/10. +- **Later**, in their original meaning: + - unsafe-physical and capability effects (OSC-6/7); + - Flow IR lowering (OSC-8); + - accelerator registry / object world (OSC-11); + - remaining safe C (OSC-12); + - residual unsafe (OSC-13); + - self-host (OSC-14); + - qualification (OSC-15); + - canonical (OSC-16). + +A milestone never passes on source code existing alone. + +## III.8 Acceptance tests + +**OSC-1 slice** (in `tests/osc/`): +- A valid program runs natively. +- These are **compile** failures: + - use after move; + - mutable alias; + - borrow outlives owner; + - statically known out-of-bounds. +- Dynamic out-of-bounds is a **deterministic runtime trap**. +- Forgotten free is inexpressible in safe syntax. + +**Breaker lane:** additionally stale generation, arena escape, double release, integer overflow, forged rights, bad C ownership annotation, null FFI result, generation wrap, and cross-engine stale reference. + +Each negative test asserts the exact diagnostic fields from III.6. + +**OSC-0B exit:** the II.11 model rejects every named invalid transition across at least 10^6 seeded random sequences, with zero false accepts. The seed and counts are recorded in a receipt. + +--- + +## Checklist + +**§22 items (OSC-0 contract):** +1. live audit: Part I +2. hazard inventory: I.3, I.4, and the appendices +3. ownership model: III.2 +4. taxonomy: III.1, II.6 +5. unsafe boundary: III.4, II.8 +6. C ABI boundary: I.6, III.5 +7. pipeline: III.6 +8. migration order: III.7 +9. benchmark baseline: I.10 (host-only; GPU gaps listed) +10. acceptance tests: III.8 + +**OSC-0B items (Drake's 12):** +1. concurrency: II.1 +2. atomics: II.2 +3. layouts: II.3 +4. failures: II.4 +5. cycles: II.5 +6. live versus persistent: II.6 +7. relocation and pinning: II.7 +8. MMIO, DMA, and contexts: II.8 +9. determinism: II.9 +10. substrate: II.10 +11. executable model: II.11 +12. lifetime, authority, and placement: II.12 + +**Decisions taken by Drake, 2026-09-29 (freeze accepted; see OMEGA-SYSTEMS-CORE-0000):** +- C1: DECIDED. u64 generations end to end, slot retired at max; amends AIENOS ADR 0013 (AIENOS edit is OSC-2). +- C8: DECIDED. README non-compiler doctrine retired; Omega is the reaction runtime and the compiler for Omega Systems Core. +- III.6: DECIDED. Contracts are text only in OSC-1; enforcement in OSC-2 is mandatory before any production C migrates. +- II.6: DECIDED. Identity break in OSC-2 right after the compiler slice; versioned, old records refused; TURING version bump and golden-digest verification path required. diff --git a/README.md b/README.md index e0b27bef7..f0bf49c73 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Milestone 4 establishes the first executable semantic substrate of OMEGA: > **OMEGA DEFINES WHAT COMPUTATION MEANS WITHOUT COMMITTING THAT MEANING TO A PARTICULAR MACHINE REPRESENTATION.** -OMEGA is not a programming language, compiler, optimizer, model runtime, tensor engine, or AI system. It is the smallest sovereign semantic system capable of representing computation independently of the physical machine that will eventually realize it. +OMEGA is the reaction runtime and the compiler for Omega Systems Core. It is the smallest sovereign semantic system capable of representing computation independently of the physical machine that will eventually realize it, and it compiles Omega Systems Core programs into that machine. (Decided by Drake, 2026-09-29, in [OMEGA-SYSTEMS-CORE-0000](docs/adr/OMEGA-SYSTEMS-CORE-0000.md); this retires the earlier "not a programming language or compiler" doctrine. The Milestone 6 "self-host" result was a fixed-output self-copy check, not compilation.) ### The Sovereign Axioms - **`SMART ≠ TRUSTED`**: Trust is not earned through cognitive capability, model scale, or heuristic brilliance. Trust is binary and verified through auditable invariant enforcement. diff --git a/docs/adr/OMEGA-SYSTEMS-CORE-0000.md b/docs/adr/OMEGA-SYSTEMS-CORE-0000.md new file mode 100644 index 000000000..e1c8a8642 --- /dev/null +++ b/docs/adr/OMEGA-SYSTEMS-CORE-0000.md @@ -0,0 +1,53 @@ +# OMEGA-SYSTEMS-CORE-0000: Contract and machine semantics freeze (OSC-0 / OSC-0B) + +- Status: **Accepted 2026-09-29 (Drake). Frozen.** The four items that needed Drake are decided below ("Decisions 2026-09-29"). +- Date: 2026-09-29 +- Location: this ADR lives in Omega, next to the language it governs. The cross-repo doctrine ADRs stay in aien-architecture; this record points to them and does not duplicate them. +- Full text and evidence: [OMEGA_SYSTEMS_CORE_CODE_AUDIT.md](../../OMEGA_SYSTEMS_CORE_CODE_AUDIT.md), with appendices in [docs/osc/audit/](../osc/audit/). + +## Context + +Omega, PHYSICS, and AIENOS rely on about 98k lines of C and assembly whose safety depends on convention. Omega Systems Core is to replace them. The goal is C-class control without C's unsafe responsibility model. Drake set the sequence: audit, then a hard machine-semantics freeze, then the compiler slice, then the substrate and first migration. + +## Decision + +1. **The replacement for the pointer is an object relationship.** Lifetime, authority, and placement are tracked independently (audit II.12). +2. **The reference taxonomy is fixed.** `Handle` (live) and `SemanticId` / `PersistentRef` (durable) are distinct types. Live handles are statically barred from canonical and durable encoders (II.6). +3. **Concurrency.** No data races in safe code. Publication is only a release/acquire pair. Device completion is a linear `Fence` value, and reclaim requires a `Quiesced` proof (two-phase revocation) (II.1). +4. **Ordering.** Omega owns its ordering vocabulary, with explicit AArch64 lowerings. `volatile` is banned from safe code (II.2). +5. **Four layouts: Semantic, Runtime, Wire, Device.** Raw struct hashing is forbidden, and every hashed byte comes from a declared encoder (II.3). +6. **Failures.** Typed `Result` for expected failures; deterministic traps for invariant violations; no unwinding. A per-context table covers OOM, bounds, stale generations, device loss, failed construction, and cleanup (II.4). +7. **Ownership is a forest.** Graphs are owned by pools, and their edges are handles, weak references, or ids. Reference counting is never the default (II.5). +8. **Movable by default.** `pin` is rare and physical (II.7). MMIO, DMA, and cache visibility go through typed primitives inside declared `unsafe physical` blocks. The `ctx(irq)` / `ctx(trap)` contexts forbid allocation and blocking (II.8). +9. **Reproducible compiler.** Build twice and compare, and bootstrap equivalence is checked on a fixed corpus. The M6 self-copy is never evidence (II.9). +10. **Backend.** The syntax extends V0. The backend is direct AArch64 through the hardened in-repo encoder. C output compiled by system cc is only a differential oracle (III.6). +11. **Exit gate.** OSC-0B exits through an executable C reference model of the memory rules, driven by seeded random sequences (II.11). + +## Relation to settled records + +- **Follows:** ADR 0014, where authority lives in AIENOS and PHYSICS/FORGE does realization only. So the PHYSICS M3 ledger becomes legacy. +- **Follows:** native-frame-authority.md §6.4 (reclaim requires quiescence). +- **Follows:** canonical-encoding.md (big-endian identity) and the shared-world ABI (little-endian Zero Serialization) as two different layouts. +- **Records:** omega#71 (u64 effect generations, v2 encoder). +- **Amends (Drake, 2026-09-29):** + - AIENOS ADR 0013, u32 generations → u64 (decision 1; amendment note below); + - the README statement that Omega "is not a programming language/compiler" (decision 2; retired). + +## Decisions 2026-09-29 + +Drake accepted the recommendations on 2026-09-29. These close audit items C1, C8, III.6, and II.6. + +1. **C1, capability generation width: u64 end to end.** A slot whose generation reaches the maximum is retired, never wrapped. This covers the Rust kernel remnants, the shared-world descriptor (:130/132), `src/omega_accelerator.h`, and PHYSICS M2/M3/M15, on top of the Omega effects already moved by omega#71. + - **Amendment note to AIENOS ADR 0013.** ADR 0013 specifies u32 capability generations. This decision amends it to u64 end to end, slot retired at max. The edit to the AIENOS repository is follow-up work **OSC-2**; AIENOS is not changed by this ADR. +2. **C8, README doctrine: retired.** Omega is the reaction runtime **and** the compiler for Omega Systems Core. README.md now says so. The M6 "self-host" result was a fixed-output self-copy check, not compilation, and is never evidence of a compiler (II.9). +3. **III.6, `requires` / `ensures`: text only in OSC-1.** They are parsed and recorded, not checked. Enforcement is OSC-2 and is **MANDATORY**. **Rule: no production C migrates into Omega Systems Core until contract enforcement is on.** +4. **II.6, identity break: scheduled for OSC-2, right after the compiler slice.** It is a versioned transition: a new canonical version byte, and old records are refused, never reinterpreted (the omega#71 effect-cap64 pattern). + - **Constraint (TURING records).** TURING records (`src/turing`, domains `turing.contract.v0.provisional`, `turing.spec.v0`, `turing.evidence.v0`, `turing.decision.v1`, `turing.citeset.v0`) hash `omega_canonical_encode` OMG0 bytes. Therefore any OMG0 encoder change, including the C2 big-endian move, must ship together with a TURING record version bump and a verification path for existing golden digests: the `tests/turing` golden and rebuild tests must keep passing on old records. See TURING brief sections 9 and 49. + +**Additional rule (R16 ordering).** The OSC-1 compiler slice may not edit `src/runtime/` until the R16 gate is done. As of 2026-09-29, R16 is IN PROGRESS with only G1/G2 evidenced. + +## Consequences + +- There will be identity breaks: the canonical payloads, the R9 store rows, and the crumb digests. Each one gets a version bump and a separate reviewed change (OSC-2+). +- Small C fixes are listed in audit I.8 and are not done under this ADR. +- The OSC-1 slice may start only after this ADR is accepted and the II.11 model passes. diff --git a/docs/osc/audit/aienos-physics.md b/docs/osc/audit/aienos-physics.md new file mode 100644 index 000000000..ee90db754 --- /dev/null +++ b/docs/osc/audit/aienos-physics.md @@ -0,0 +1,310 @@ +> Appendix to OMEGA_SYSTEMS_CORE_CODE_AUDIT.md. Worker report (Opus, read-only), aienos 8706fb8 (native/capability byte-identical to Omega lock 4c21386), physics fecbedb. Reviewed: spot-checked nvrm.c:440 function-static UVM params, m16_native.c:97-108 poll without acquire, aienos_capability.h:7-10,77 u64 generation (all confirmed). Correction to its OPEN item 14: the Makefile default AIENOS_R7_DIR=../aienos-r9 on this host has no native/capability directory (checked 2026-09-29), so local R7 builds need an override; the build does not enforce aienos.lock. Not authoritative on its own; Part II of the main document rules. + +# OSC-0 / OSC-0B audit: AIENOS + PHYSICS C and assembly (read-only) + +Sources: AIENOS snapshot @ 8706fb8 (`aienos-snap/`), PHYSICS snapshot @ fecbedb (`physics-snap/`), +Omega link points in `omega/.claude/worktrees/osc-0` (Makefile, `.github/workflows/rx-host.yml`, +`src/runtime/aienos_cap.h`, `src/runtime/rx_native_bind.c`, a few `src/` call sites), +aien-architecture @ 873025c (local HEAD, 2026-09-27; may lag origin). +Nothing was built, run or modified. + +Labels: **[FACT]** code fact (file:line) · **[SETTLED]** decision already written down (doc cited) · +**[PROPOSED]** recommended OSC-0B decision · **[OPEN]** unresolved. + +Paths below are relative to the snapshot roots (`aienos-snap/…` = A:, `physics-snap/…` = P:, Omega worktree = O:). + +--- + +## 1. Inventory + +### 1.1 AIENOS C and assembly (non-vendored) — 1,268 lines total + +| Path | Lines | Purpose | Class | +|---|---|---|---| +| A:native/capability/aienos_capability.c | 580 | Native capability authority (slot table, 64-bit generations, rights, delegation, cascade revoke, epoch, lease clock, restart). **Omega links it** as `libaienos_capability.a`. | Table logic (`state_*`, lines 20-356) = **B**; hosted shell (pthread, calloc, `/dev/urandom`, `CLOCK_BOOTTIME`, lines 358-580) = **E** | +| A:native/capability/aienos_capability.h | 133 | Public C ABI of the authority (constants, `AienosCapRef/Entry/Mint`, 19 functions) | **B** (C ABI boundary) | +| A:native/capability/tests/capability_test.c | 323 | Rule tests | B (test) | +| A:native/capability/Makefile | — | `-std=gnu11 -O2 -Wall -Wextra -Werror -fstack-protector-strong` | — | +| A:crates/aienos-artifact-tool/fixtures/p2_6/p26seed/probe.S | 131 | EL0 test probe: requests one capability, checks allow/deny via `svc` | **A/B** test fixture (keep as asm; it is a test payload) | +| A:…/p2_5/p25exec/probe.S | 83 | EL0 execution probe (handle array, forged handle denial) | test fixture | +| A:…/p2_5/p25wx/probe.S | 12 | W^X probe: store to own code page must fault | test fixture | +| A:…/p2_5/p25spin/probe.S | 6 | Runaway loop; only timer IRQ budget can end it | test fixture | + +AIENOS Rust (to be rewritten under the no-Rust rule; line counts only), 57,841 lines in 14 crates: + +| Crate | Lines | Purpose | +|---|---|---| +| aienos-kernel | 37,976 | Bare-metal no_std AArch64 kernel: vectors, GIC, timer, page tables, SMMUv3, DMA gate, NVMe, store, caps, scheduler | +| aienos-boot | 4,580 | UEFI entry / handoff | +| aienos-artifact | 2,505 | Binary Artifact v0 parser + identity | +| aienos-accel | 2,218 | GB10 PCI/BAR0 discovery | +| aienos-aegis | 1,757 | Capability graph / effect intent pipeline | +| aienos-evidence | 1,728 | Host evidence capture/verify | +| aienos-agent-state | 1,440 | Persistent agent state ABI | +| aienos-artifact-tool | 1,319 | Host artifact tooling | +| aienos-capability | 1,001 | Rust capability authority (u32 generations). Currently the declared differential oracle (its Cargo.toml description). **F [PROPOSED]** under the no-Rust rule once the C authority is the only authority | +| aienos-crypto | 922 | no_std crypto primitives | +| aienos-cortex | 728 | Cortex provenance store | +| aienos-c1-tree | 721 | COW prefix tree | +| aienos-store-tool | 477 | Store v1 image tool | +| aienos-capability-ffi | 469 | C binding for the Rust authority (**F**, replaced by native C) | + +Vendored (list only): A:vendor/ — 58 Rust crates (~630k lines: syn, libc, uefi, uefi-raw, serde*, curve25519-dalek, ed25519-dalek, sha2, der, …). No vendored C. +P:third_party/nvidia-open-580.173.02 — NVIDIA open kernel module headers; Omega compiles against four of its include dirs (O:Makefile:10-13). + +### 1.2 PHYSICS C and assembly (non-vendored) — 9,399 lines total + +| Path | Lines | Purpose | Class | +|---|---|---|---| +| P:nvrm/nvrm.c | 810 | Native NVIDIA RM/UVM client: ioctls on `/dev/nvidiactl`, `/dev/nvidia0`, `/dev/nvidia-uvm`; memory alloc/free with GPU VA == CPU VA; channel group, GPFIFO, USERD, doorbell. **Omega compiles it into omegatool and R12/R-silicon tests.** | **D** (ioctl/mmap/doorbell) wrapped in **B** bookkeeping (live table, VA free list) | +| P:nvrm/nvrm.h | 119 | `Nvrm`, `NvrmMem`, `NvrmLiveAlloc`; 15 functions; `nvrm_mthd` inline | **D/B** C ABI | +| P:nvrm/lifecycle_gates.c | 350 | M19R hardware gates for nvrm_free / wait_marker_ge | test (E) | +| P:m16/m16_native.c | 112 | Thin wrapper: open, 64-slot legacy alloc table, channel + 4 KiB pushbuffer, semaphore-release method stream, marker poll | **C/D** | +| P:m16/m16_native.h | 54 | `M16NativeContext` (embeds whole `Nvrm`) | C ABI | +| P:m16/m16_concurrent.c | 135 | Two-channel causality test | test (E) | +| P:m16/m16_requalify.c | 132 | Single-channel causality test | test (E) | +| P:m15/physics_accel.c | 457 | **Software model** of SMMUv3 windows / queues / receipts (no MMIO, no ioctl) | **F** (or keep as spec only) | +| P:m15/physics_accel.h | 255 | Model structs: `EffectIntent` (64 B), `EffectReceipt` (192 B), `AcceleratorCapability` (u32 generation) | F / spec | +| P:m15/physics_accel_native.c/.h | 286 / 126 | sysfs probe of SMMU + GB10 (read-only files) + DMA "model" | F (sysfs probe = E) | +| P:m15/tools/m15tool.c | 701 | M15 host tool | E | +| P:tools/m2tool.c | 1,120 | M2 host qualification tool (sha256, hexfield, audit-verify, golden) | **E** | +| P:m3/tools/m3tool.c | 260 | M3 host tool | E | +| P:sha256_clean.c | 107 | Freestanding SHA-256 used by Atlas bootstrap image and host tools | **B** (keep) | +| P:physics.s | 336 | M2 PHYSICS entry: ingress validation, EL check, VBAR install, frame authority init, panic traps, polled PL011 UART | **C/D** | +| P:vector_table.s | 305 | M2 16-slot vector table + stackless trap capture → print → `wfe` halt | **D** | +| P:memory_alloc.s | 189 | M2 physical frame bitmap authority (grant only) | **C** | +| P:capability.s | 137 | M2 CAP_ROOT genesis + `validate_capability(ptr, op, addr, size)` | **C** | +| P:atlas_m2.s | 174 | Atlas M2 bootstrap seed: DAIF mask, descriptor, SHA-256 verify, `br` to PHYSICS | **E** (bootstrap) / D | +| P:m3/physics.s | 277 | M3 PHYSICS entry | C/D | +| P:m3/vector_table.s | 205 | M3 vectors (regressed vs M2, see §3a) | D (**F** once M2 collector is reused) | +| P:m3/capability.s | 533 | M3 32-slot capability ledger, u32 generation, derive/lookup/revoke, provenance SHA-256 | **C** | +| P:m3/memory_alloc.s | 222 | M3 frame bitmap: grant, grant-in-range, release | **C** | +| P:m3/effect_broker.s | 411 | M3 `submit_effect(intent_ptr)` 10-stage admission + receipt | **C** (semantics = A, should move up) | +| P:m3/receipt_ledger.s | 176 | Append-only 32-receipt hash chain | C | +| P:m3/replay_cache.s | 157 | 32-entry idempotency cache | C | +| P:m3/sha256_be.s | 85 | Big-endian SHA-256 in asm | C | +| P:m3/atlas_m3.s | 155 | Atlas M3 seed | E | +| P:m3/tests/test_m3_authority.s, sha256_kat.s, kat_stub.s | 843 / 163 / 7 | In-guest tests (sha256_kat enables SCTLR_EL1.A) | test | + +Class totals (C + asm lines, excluding tests/fixtures, approximate): +- **A semantic**: ~0 standalone (effect_broker admission rules are semantic logic living in C-class asm). +- **B safe systems**: ~960 (capability table logic ~360 + header 133; sha256_clean 107; nvrm bookkeeping ~350). +- **C physical realization**: ~2,450 (M2/M3 capability, frame, broker, ledger, replay, sha256_be, entry; m16_native). +- **D unavoidable hardware boundary**: ~900 (nvrm ioctl/mmap/doorbell ~460, vector tables 510, UART/entry parts). +- **E temporary bootstrap / host tooling**: ~2,600 (atlas_m2/m3, m2tool, m3tool, m15tool, cap shell ~220, tests). +- **F obsolete / retire**: ~1,125 C (M15 model) + Rust aienos-capability(+ffi) 1,470. + +--- + +## 2. Hazard counts (C files, non-vendored; asm listed separately) + +| Hazard | Count | Representative sites | +|---|---|---| +| malloc/calloc/realloc/free | 78 (m2tool 42, m3tool 20, aienos_capability.c 15, physics_accel_native 1); **0 in nvrm/m16** | A:native/capability/aienos_capability.c:423-425 (3× calloc), :363 free in `release`, :514 malloc in restart; P:m3/tools/m3tool.c:48,53 | +| Raw pointer fields in structs | 8 | P:nvrm/nvrm.h:27 `void *cpu`, :44 `void *cpu`, :59 `void *usermode_cpu`, :60 `volatile uint32_t *doorbell`; A:…/aienos_capability.c:37,41 `CapShared *shared` (admin and view share one) | +| Pointer arithmetic | ~90 | P:nvrm/nvrm.c:285 doorbell = mmio + offset; :717 `fifo.cpu + userd_off + offsetof`; P:m15/physics_accel.c:382 ring slot; all PHYSICS asm uses base+shift addressing (m3/capability.s:147-149) | +| NULL / 0 sentinels | ~35 C + asm | NvrmMem all-zero == "freed" (nvrm.c:547); `MAP_FAILED` vs NULL mix (nvrm.c:162,284); asm `allocate_frame` returns 0 = exhausted (memory_alloc.s:112); `lookup_capability` returns 0 ptr (m3/capability.s:217); `AIENOS_CAP_PARENT_NONE = UINT32_MAX` (aienos_capability.h:69) | +| ptr+len conventions | 12 APIs | Good: `nvrm_enqueue(pb, off, nwords)` (nvrm.c:720) checks span; `sha256_compute(data, len, scratch[128], out[8])`. **Missing length**: `aienos_cap_authorize(admin, presented)` reads 32 B (aienos_capability.c:572-580); `aienos_cap_cognition_mint(view, req, token)`; `m16_native_build_release(words, …)` writes 8 words (m16_native.c:52-66); asm `validate_capability(cap_ptr, …)` (capability.s:92); `submit_effect(intent_ptr)` (m3/effect_broker.s:82) | +| Flexible array members | 0 | — | +| Unsafe casts | 52 (m2tool 28, nvrm.c 8, m3tool 5, others) | nvrm.c:285 `(volatile uint32_t *)((uint8_t *)mmio + …)`; nvrm.c:485 `mmap((void *)va…)` integer→pointer; nvrm.c:729 `(volatile uint64_t *)rm->fifo.cpu`; `NV_PTR_TO_NvP64(params)` pointer→u64 into kernel (nvrm.c:73, 270, 293); O:src/runtime/rx_native_bind.c:21 `(AienosCapEntry *)out` type pun | +| goto cleanup | 14 (nvrm.c 7, m2tool 7) | nvrm.c:688-706 `goto failed` in channel_destroy | +| Global mutable state | nvrm.c: 5 (`g_va_counter`, `g_va_slots_lock`, `g_va_recycled[1024]`, `g_va_recycled_count` :183-186, **function-local `static UVM_MAP_EXTERNAL_ALLOCATION_PARAMS ma`** :442); aienos_capability.c: 1 (`last_boot_gen` :52); PHYSICS asm: all state is at fixed physical addresses (0x40205800.., 0x40206000, 0x40207000, M3 0x40209000/0x4020A000/0x4020C000) | +| Arenas / pools | 5 | Fixed tables: `Nvrm.live[4096]`, `Nvrm.free_list[4096]` (nvrm.h:64-67), `M16NativeContext.legacy_allocs[64]` (m16_native.h:18), `CapState.entries[256]` (aienos_capability.c:24), M3 cap table 32×128 B / receipts 32×192 B / replay 32×64 B | +| GPU VAs / CPU addresses in structs | 9 | `NvrmMem.va` + `.cpu` (identical by construction, nvrm.h:25-28); `NvrmVaRange`; `Nvrm.va_next/va_slot_base/channel_va`; M15 `DmaWindowDescriptor.iova_base/phys_base`; M2/M3 cap records `bound_base/bound_size` (physical) | +| Generation counters / handle IDs | 8 schemes | C authority u64 (aienos_capability.h:73-76); M2 cap u32 never checked (capability.s:37-41); M3 u32 (m3/capability.s:403-408); M15 u32 (physics_accel.h:88); RM handles `next_handle++` u32 from 0xcf000001, refuse at UINT32_MAX (nvrm.c:65-72); GPFIFO `put/retired` u32 wrap (nvrm.h:63-64); marker serial compare (m16_native.c:103); Rust caps u32 (kernel caps.rs:76, abi.rs:141) | +| Rights fields | 4 | `AIENOS_CAP_RIGHT_*` 10 bits (aienos_capability.h:43-60); M2/M3 `allowed_ops` u32 (capability.s:20); M15 `ACCEL_OP_*`; Omega `RX_RIGHT_*` re-declared (O:src/runtime/rx_caproot.h:67-80) | +| Stale-handle validation | 5 sites | aienos_capability.c:135-138, 143-167, 204; m3/capability.s:153-157, 183-195; nvrm_free live-table match (nvrm.c:553-563) | +| Serialization of native structs | 4 | M15 hashes raw `EffectIntent`/`EffectReceipt` bytes (physics_accel.c:103, 119-121); M3 broker builds receipt at fixed offsets (effect_broker.s:66-79); M3 derive hashes 80 B built at fixed offsets (m3/capability.s:412-436); `AienosCapEntry` copied across C ABI by value/pointer | +| MMIO | 3 | Usermode doorbell `*rm->doorbell = token` (nvrm.c:742-744); USERD GPPut store (nvrm.c:733); PL011 UART at 0x09000000 (physics.s:249-268) | +| ioctl / mmap | 19 in nvrm.c | nvrm.c:59 (all RM escapes), 145 (UVM), 177 (mmap RM memory), 485 (PROT_NONE reservation), 596 munmap | +| Page-table / SMMU code | 0 in C/asm | Only in Rust kernel (smmu.rs 1,392 lines, pagetable.rs 658) and M15 model. PHYSICS M2/M3 run with MMU off. | +| DMA code | GPU only | Coherent sysmem via RM `NV01_MEMORY_SYSTEM` + `RM_MAP_MEMORY_DMA` with `CACHE_SNOOP_ENABLE` (nvrm.c:434) + UVM external range (nvrm.c:417-450) | +| `_Static_assert` | **0 in AIENOS/PHYSICS**; 4 in Omega's shim (O:rx_native_bind.c:10-16) | — | +| packed / `__attribute__` layout | 0 packed; 3 `aligned(16)` scratch buffers | — | + +--- + +## 3. Machine-semantics evidence + +### (a) Interrupts, vectors, interrupt context +- [FACT] PHYSICS M2 has **no interrupt handling**: Atlas masks DAIF (`msr daifset,#0xf`, P:atlas_m2.s:56) and nothing unmasks it. All 16 vectors (P:vector_table.s:35-130) store the slot in x0 (after stashing x0 in TPIDR_EL1) and branch to `common_trap_entry`, which saves all GPRs + SP + ESR/ELR/SPSR/FAR to a fixed frame at 0x40205880 **without touching the stack**, writes magic `TRAPFRM1` last, `dsb sy`, switches to a known stack, prints, then `wfe` forever (:161-268). Every exception is terminal. Nothing in exception context can allocate (there is no allocator call) or block (it halts by design). +- [FACT] PHYSICS M3 vectors (P:m3/vector_table.s:32-35, 116-140) put the slot in x0 **before** saving x0 and load the frame base into x1 **before** saving x1 → original x0/x1 are lost; FAR is marked valid for EC 0x26 (SP alignment, FAR not architecturally valid) and FnV is not checked. M3 is a regression from M2. +- [FACT] The collector overwrites TPIDR_EL0/EL1 (vector_table.s:37,162); a nested fault overwrites the single frame. Acceptable because it never returns. +- [FACT] AIENOS C has no interrupt code. The AIENOS kernel (Rust) takes IRQs: `irq_dispatcher_inner` acknowledges GIC, handles only PPI 30 (timer) by reprogramming compare and calling a hook transmuted from an `AtomicUsize` (A:crates/aienos-kernel/src/thread.rs:229-248, fatal.rs:169-183). No allocation in that path. +- [SETTLED] aien-architecture ADR 0014 (873025c): AIENOS owns "boot continuation, address spaces, tasks, interrupts, capabilities, DMA confinement … native device ownership"; FORGE (ex-PHYSICS) is realization only. + +### (b) MMIO / volatile / barriers / cache / DMA / page tables / SMMU +- [FACT] GPU submission ordering: ring entry written via `volatile uint64_t*`, `dsb sy`, GPPut store, `dsb sy` (P:nvrm/nvrm.c:729-734); pushbuffer copied then `dsb sy` (m16_native.c:72-73). Doorbell store `*rm->doorbell = token` has **no barrier of its own and no NULL check** (nvrm.c:742-744); it relies on the trailing `dsb` in enqueue. `dsb sy` is stronger than needed (`dmb oshst`/`dsb st` would do) but correct. +- [FACT] Completion observation: `m16_native_wait_marker_ge` polls a `volatile uint32_t*` with `usleep(50)` + `yield` and **no acquire barrier** after success (m16_native.c:97-108). Subsequent reads of GPU-written results are not ordered after the marker read on AArch64. +- [FACT] No `dc`/`ic` cache maintenance anywhere in PHYSICS or AIENOS C. GPU memory is coherent system memory with `NVOS46_FLAGS_CACHE_SNOOP_ENABLE` (nvrm.c:434) and optionally GPU-uncached (`nvrm_alloc_gpu_uncached`, nvrm.c:473). PHYSICS M2/M3 run MMU-off (no MMU/TTBR/SCTLR.M code; only the KAT test sets SCTLR_EL1.A, m3/tests/sha256_kat.s:52-54), so all data accesses are Device-nGnRnE. +- [FACT] Atlas hands off with `br x19` and no `ic iallu`/`dsb`/`isb` (P:atlas_m2.s:130-134). Fine with caches off under QEMU; not fine natively once I-cache is on. +- [FACT] No page table, SMMU or IOMMU programming in any C/asm. SMMU on GB10 is owned by Linux (P:evidence/physics_accelerator_link_qualification_receipt.json:38 "takeover deferred"). The Rust kernel has host-testable SMMUv3 bring-up (GBPA.ABORT first, abort STEs by default, A:crates/aienos-kernel/src/smmu.rs:1-12) and a BME gate (dma_gate.rs:1-20), plus `dc cvac`/`dc civac` + `dsb` helpers (arch/aarch64.rs:262-337). +- [FACT] GPU VA == CPU VA by construction: PROT_NONE `MAP_FIXED_NOREPLACE` reservation at the chosen VA (nvrm.c:485-489), then `MAP_FIXED` RM mapping over it (nvrm.c:177), then `RM_MAP_MEMORY_DMA` with `DMA_OFFSET_FIXED` at the same VA (nvrm.c:433-437) and UVM external range (nvrm.c:419-450). +- [OPEN] That RM keeps the physical pages pinned for the life of the RM memory object is assumed (NVIDIA RM contract), not verified in the snapshot. + +### (c) Atomics and memory orderings +- [FACT] aienos_capability.c: `last_boot_gen` CAS acq_rel/relaxed (:66-78); `holders` refcount `fetch_sub` acq_rel (:361); all table state under `pthread_mutex` (LOCKED macro, :369-375, a GNU statement expression). +- [FACT] nvrm.c: `atomic_flag` spinlock acquire/release around `g_va_recycled` (:189-209); `g_va_counter` CAS relaxed (:193-200). `Nvrm` itself has **no lock**; each context is single-threaded by convention. The function-local `static UVM_MAP_EXTERNAL_ALLOCATION_PARAMS ma` (:442) is shared by every `Nvrm` → **data race** when two contexts allocate concurrently (m16_concurrent.c and Omega's threaded GPU seat O:src/runtime/rx_resident_gpu.c:47-60 do run multiple contexts). +- [FACT] M15 `atomic_thread_fence(seq_cst)` (physics_accel.c:386) orders ordinary struct memory in a software model; no device visibility effect. +- [FACT] PHYSICS asm: zero exclusives/atomics (no ldxr/stxr/ldar/stlr/cas); single boot CPU. [SETTLED] P:docs/native-frame-authority.md §6.5: boot CPU alone owns the frame authority in v1; one lock later, no per-CPU cache. +- [FACT] Rust kernel uses Release 50×, Acquire 31×, SeqCst 14×, Relaxed 13×, AcqRel 1×. + +### (d) Layout, hardware formats, endianness, hashing +- [FACT] No `packed` structs and **zero `_Static_assert`** in AIENOS/PHYSICS C. `AienosCapRef` {u32, u64} has 4 bytes of interior padding (size 16); `AienosCapEntry` has padding after `cap_id`, `parent_id`, `minted_by_id`. Omega re-declares both structs by hand (O:src/runtime/aienos_cap.h:18-47) and checks only size + two offsets (O:rx_native_bind.c:10-16). +- [FACT] M15 hashes raw struct bytes (`sizeof(EffectIntent)`, first 128 B of `EffectReceipt`, physics_accel.c:103, 119-121). By hand both are padding-free (64 B and 192 B) on LP64, but nothing enforces it. Receipts copy `out_receipt` including `length = sizeof(EffectReceipt)`. +- [FACT] Hardware formats done with shifts, not bitfields: GP entry (nvrm.c:712-714), method header `nvrm_mthd` (nvrm.h:111-113, `count` not masked to 13 bits), semaphore release stream (m16_native.c:56-65). Stores are native little-endian; correct only because host and GPU are both LE. +- [FACT] PHYSICS asm records and hash inputs are built at explicit byte offsets, little-endian (m3/capability.s:412-429; m3/effect_broker.s:66-79). `sha256_clean.c` writes the length big-endian explicitly (:91-95), reads input bytewise; output is native u32 words (callers convert). Contract declares `"endianness": "little"` (P:machine_contract.json). +- [SETTLED] AIENOS ADR 0013 (ABI v1) and ADR 0015 (Store v1) define explicit LE wire layouts with offsets (e.g. adr/0015:92-93, adr/0013:57). + +### (e) Failure handling +- [FACT] PHYSICS M2/M3 ingress and invariant failures are **fail-closed panic traps**: distinct string then `wfe` loop (P:physics.s:193-241). Frame exhaustion returns 0 (not a panic, memory_alloc.s:112, 158). Invalid capability returns 0/decision code (capability.s:125; m3/capability.s DEC_* codes). Any CPU exception = capture + halt. +- [FACT] AIENOS C authority: every failure is a negative error code (17 codes, aienos_capability.h:27-43); no abort/assert/exit anywhere in aienos_capability.c, nvrm.c or m16_native.c. OOM in `aienos_cap_start/restart` → `AIENOS_CAP_ERR_IO` (:426-430, :515). +- [FACT] nvrm: error code −1 + message in `rm->err[256]` + **sticky `rm->faulted`**; after any irreversible partial failure the allocation is quarantined (VA never reused) (nvrm.c:453-460, 575-600). Device loss has no dedicated path: the channel error notifier is allocated and registered (`hObjectError`, nvrm.c:629, 635) but **never read** by PHYSICS or Omega; a lost/faulted GPU shows up only as a marker-poll timeout (m16_native.c:102-108). +- [SETTLED] aien-architecture doctrine/TRUST.md:260 lists "OOM panic, core" under catastrophic failure; ADR 0006 (AIENOS) requires deterministic crash records. + +### (f) Capability authority generation / rights model +- [FACT] C authority (the one Omega links): reference = `{u32 cap_id, u64 generation}`; 256 slots; max delegation depth 8. Reclaim advances generation by 1 (`aienos_cap_generation_advance`, :80-84); a slot at `UINT64_MAX` is skipped as exhausted, never wrapped (:262-266). Restart starts every slot above `max(last start + 1, table_floor, CLOCK_BOOTTIME_ns << 8)` so references from an earlier table or process fail (:45-79, 97-107, 507-527). +- [FACT] Stale references fail closed: wrong generation → `ERR_STALE_GEN`; non-live → `ERR_REVOKED`; epoch mismatch → `ERR_EPOCH`; lease expired → `ERR_EXPIRED`; any ancestor stale/revoked/expired/wrong-epoch → `ERR_CHAIN` (:143-167). Revoke cascades to live descendants (:286-303). Admin ops additionally require `delivered[i]` (:201-215). +- [FACT] Rights: 10 bits (READ, WRITE, EFFECT, DELEGATE, MINT, REVOKE, RECLAIM, EPOCH, CLOCK, PROMOTE); privileged rights can never be delegated (:227-229, 249); delegation can only narrow rights, same resource, shorter-or-equal lease (:240-254). +- [FACT] Gaps: `restart` resets `writer_alive = true`, undoing `kill` (bootstrap :113); `aienos_cap_force_generation` is a test seam exported in the production ABI (:343-351); the office token is never checked by any operation (:572-580, header comment); `cognition_*` are hard-coded refusals (:540-557). +- [FACT] PHYSICS M3: `{u32 slot, u32 generation}`, 32 slots; on wrap to 0 the slot is skipped (fail closed, m3/capability.s:403-408); revoke does **not** cascade but lookup walks ancestors (≤8) on every use (:167-195); `lookup_capability` returns a **raw pointer** into the table (:211). +- [FACT] PHYSICS M2: `validate_capability` takes a record pointer, checks state/ops/bounds with overflow check, **never checks generation** (capability.s:92-127). +- **No coupling between capability revocation and device views** [FACT]: revoking a capability in the C authority does not unmap any GPU VA, drain any channel, or invalidate any SMMU/TLB entry. `nvrm_free` does not check that the GPU has finished with the buffer, and `nvrm_channel_destroy` does not check `put == retired` before unregistering and freeing (nvrm.c:674-706). The only fence-like guard is `nvrm_enqueue` refusing to overrun unretired ring entries, and `nvrm_retire` trusts the caller (nvrm.c:726-740). Omega calls `nvrm_retire(&rm, rm.put)` directly (O:src/omega_accelerator_world.c:984, 1204). + +--- + +## 4. Per-site hazard table (top 30) + +repository/path | function/type | hazard | current ownership model | current lifetime model | proposed Omega replacement | migration difficulty | required compatibility boundary +---|---|---|---|---|---|---|--- +physics/nvrm/nvrm.c:543-612 | `nvrm_free` | Frees RM memory + unmaps while GPU work may still reference it; other `NvrmMem` copies dangle | Caller holds `NvrmMem` by value; `Nvrm.live[]` is the real owner | Manual; "freed" = all-zero struct; no GPU fence | `handle` owned by an `arena/region` per channel; free requires a completion token (`own`) | High | RM/UVM ioctl ABI (C ABI adapter) +physics/nvrm/nvrm.c:674-706 | `nvrm_channel_destroy` | Tears down channel with in-flight GP entries (no `put==retired` check) | `Nvrm` owns channel handles | Manual, ordered frees with `goto failed` | `own` whose drop requires drained state; typestate | Medium | RM free order (C ABI adapter) +physics/nvrm/nvrm.c:442 | `uvm_map` `static … ma` | Hidden global shared by all contexts → data race | Function-local static | Process lifetime | Stack `T inline` (it is ~ a few KB) or per-context field | Low | none +physics/nvrm/nvrm.c:726-740 | `nvrm_retire` | Trusts caller that entries completed; no GPGet | Caller asserts completion | Monotonic u32 counters, wrap by subtraction | `own` produced only by observed marker; retire consumes it | Medium | Omega calls (omega_accelerator_world.c:984) +physics/m16/m16_native.c:97-108 | `m16_native_wait_marker_ge` | Volatile poll with no acquire barrier; data read after may be stale | Borrowed `volatile u32*` | Caller-guaranteed | `device` with `load_acquire`; returns `own` | Low | none +physics/nvrm/nvrm.c:742-744 | `nvrm_ring` | MMIO store with no NULL check, no own barrier | `Nvrm.doorbell` raw ptr into RM mmap | Lives until `munmap(usermode_cpu)` in close | `device` (MMIO typed handle), `unsafe physical block` for the store | Low | usermode MMIO mapping +physics/m16/m16_native.c:69-75 | `m16_native_enqueue_methods` | Rewrites single 4 KiB pushbuffer at offset 0 while earlier entries may be unconsumed | `M16NativeContext.pb_mem` | Reused every submit | `arena/region` ring of pushbuffer slices tied to GP entries; `slice` | Medium | GPFIFO entry format +physics/nvrm/nvrm.h:24-29 | `NvrmMem` | Copyable struct with raw `cpu` pointer + VA; aliasing and dangling copies | Value type, no owner | None | `handle` (gen-checked) + `&[u8]`/`slice` view borrowed from it | Medium | Omega struct field access +physics/nvrm/nvrm.h:40-84 | `Nvrm` (~225 KiB) | Huge, stack-allocated by Omega (omega_blackwell_submit.c:44); fields read directly by Omega | Caller-owned storage | Scope of caller | `own` heap/region; opaque type with accessors | Medium | Omega reads `.put/.retired/.faulted/.entries/.root/.device/.vaspace` +physics/nvrm/nvrm.c:161-181, 485 | `map_to_cpu`, `alloc_with_cacheability` | int→pointer casts, `MAP_FIXED` over reservation | Kernel mapping owned by `Nvrm.live[]` | Until `munmap` | `pin` (pinned, identity VA) produced by an `unsafe physical block` | High | Linux mmap + RM ABI +physics/nvrm/nvrm.c:64-80 | `rm_alloc` | `NV_PTR_TO_NvP64(params)` passes user pointer to kernel as u64 | Stack param blocks | Duration of ioctl | C ABI adapter taking `&mut T` | Low | NVIDIA ioctl structs (third_party headers) +physics/nvrm/nvrm.c:183-209 | VA slot globals | Process-global mutable state + spinlock; recycled list silently drops when >1024 | Process | Process | `arena/region` VA allocator object owned by a device-session root | Low | none +physics/nvrm/nvrm.c:629-635 | channel error notifier | Allocated, never read → device fault/loss invisible | `Nvrm.notifier` | Channel | `device` checked on every wait; explicit `DeviceLost` error | Medium | RM notifier layout +physics/nvrm/nvrm.h:111-113 | `nvrm_mthd` | `count` not masked; overflows into opcode bits | pure fn | — | `T inline` bitfield type with checked constructor | Low | method header format +physics/m16/m16_native.c:52-66 | `m16_native_build_release` | Writes 8 words to buffer of unknown length | Caller buffer | — | returns `[u32; 8]` `T inline` or takes `&mut slice` | Low | none +physics/m16/m16_native.c:22-42 | legacy alloc table | Lookup by CPU pointer; 64-slot linear | Context-owned | Manual | `handle` | Low | Omega does not use it directly +aienos/native/capability/aienos_capability.c:420-449, 452-462 | `aienos_cap_start/stop` | Two heap handles share a refcounted `CapShared`; use after `stop` is UAF; double stop double-frees | Refcount (`holders`) | Manual `stop` | `own` + `own` sharing `Rc`-like region; or `SemanticId`-keyed singleton in a region | Medium | Omega calls `aienos_cap_stop` 27× +aienos/native/capability/aienos_capability.c:572-580 | `aienos_cap_authorize` | Reads 32 bytes from pointer with no length | Borrowed | Call | `&[u8; 32]` | Low | C ABI (unused by Omega) +aienos/native/capability/aienos_capability.c:343-351, 558-561 | `aienos_cap_force_generation` | Test seam exported in production ABI | Admin | — | Remove from production; test-only build | Low | 2 call sites in Omega src+tests +aienos/native/capability/aienos_capability.c:111-128 | `bootstrap` (via restart) | `restart` revives a killed writer (`writer_alive=true`) | Admin | — | Typestate: killed authority cannot restart without explicit revival right | Low | behaviour change visible to R-gates +aienos/native/capability/aienos_capability.c:369-375 | `LOCKED` macro | GNU statement expression; lock not held across multi-call sequences (validate then use = TOCTOU) | pthread mutex | Per call | `&T` view under a region lock; validated ref returns `handle` checked again at use | Medium | Omega rx_world validate→act pattern +omega/src/runtime/aienos_cap.h:18-47 + rx_native_bind.c:21 | header copy + `(AienosCapEntry *)out` | Hand-copied structs, no constants, padding-dependent, type pun between `RxCapEntry` and `AienosCapEntry` | Omega copy | Build | Single generated header; `SemanticId` = `{u32 idx, u64 gen}` with explicit layout + asserts | Low | the C ABI itself +physics/m3/capability.s:139-211 | `lookup_capability` | Returns raw pointer into cap table; caller may keep it past revoke | Table owns records | Until slot reused | `handle` returned; record accessed via `&T` scoped borrow | Medium (asm) | M3 gate receipts +physics/m3/capability.s:403-408 | derive generation | u32 generation; slot retired on wrap | Table | Fixed | u64 generation `SemanticId` | Medium | M3 receipts/hashes include u32 gen +physics/capability.s:92-127 | `validate_capability` (M2) | Takes record pointer, no generation check | Caller pointer | — | `handle` lookup | Low (M2 frozen) | M2 byte-identical image +physics/m3/memory_alloc.s:185-222 | `release_frame` | Releases any allocated frame without capability or DMA-quiescence proof (contradicts doc §6.4) | Bitmap | Manual | `own` consumed by release together with `own` receipt | Medium | frame-authority gates +physics/m3/effect_broker.s:82-135 | `submit_effect(intent_ptr)` | Pointer only, alignment checked, no range check against caller memory | Caller | Call | `&EffectIntent` (64 B `T inline`, explicit LE layout) | Medium | receipt format +physics/m3/vector_table.s:32-35, 116-140 | `common_trap` | Clobbers x0/x1 before save; FAR validity wrong for EC 0x26 | Fixed frame | Terminal | Reuse M2 collector (`unsafe physical block`) | Low | M3 gate expectations +physics/m15/physics_accel.c:85-127, 343-392 | receipt seal, `submit_command` | Hash over native struct bytes; ring tail overwrites without head check | Link struct | Manual | Explicit serializer to `[u8; N]`; model code retired | Low (retire) | none (not linked) +physics/atlas_m2.s:130-134 | handoff `br x19` | No `ic iallu; dsb; isb` before jumping to loaded image | Atlas | One-shot | `unsafe physical block` with mandatory I-cache sync | Low | Atlas byte-identical image (M2 frozen) + +--- + +## 5. C ABI dependencies that cannot immediately disappear + +**Omega → AIENOS capability authority** [FACT] O:Makefile:184-197 (and 210, 224, 242, 256, 282, 310, 329, 351): links `$(AIENOS_R7_DIR)/native/capability/out/libaienos_capability.a` (default dir `../aienos-r9`; CI checks out the commit in `aienos.lock` = 4c21386, O:.github/workflows/rx-host.yml:38-58). Header: Omega's own copy `src/runtime/aienos_cap.h` (no constants). Calls (count in src+tests): office 49, mint 30, stop 27, start 23, revoke 22, validate 15, inspect 7, clock 5, advance_clock 5, reclaim 4, cognition_mint 4, restart 3, cognition_admin 3, bump_epoch 3, kill 2, generation_advance 2, force_generation 2. +Pointer passing and implied ownership: +- `start(Admin **, View **)`: library allocates both; caller owns them and must call `stop` exactly once each (no double stop, no use after). +- `mint(Admin *, const Mint *, Ref *out)`, `validate/inspect(View *, Ref, …, Entry *out)`: borrowed in/out pointers for the call only; entries are copied out by value (no pointer into the table escapes — good). +- `View *` is handed to the reaction world as an opaque `void *ctx` (O:rx_native_bind.c:28-33); the world must not outlive the view. +- `authorize/cognition_mint(…, const uint8_t *token)`: 32-byte implied length. +- Layout contract: `AienosCapRef` (16 B with padding), `AienosCapEntry`, `AienosCapMint` passed by value/pointer; rights and error numbers are duplicated as literals on the Omega side (`RX_RIGHT_*`, O:src/runtime/rx_caproot.h:67-80). + +**Omega → PHYSICS NVRM/M16** [FACT] O:Makefile:3-24, 71-75, 316-331, 357: compiles `$(PHYSICS_DIR)/m16/m16_native.c` and `nvrm/nvrm.c` into omegatool and GPU tests; include paths `-I physics/m16 -I physics/nvrm` + four NVIDIA open-580.173.02 header dirs; pinned by `physics.lock` = fecbedb and a Makefile check (O:Makefile:47-60). Calls: nvrm_mthd 114, m16_native_close 56, nvrm_alloc 35, m16_native_submit_methods 6, wait_marker_ge 5, open 5, create_channel 5, nvrm_retire 4, wait_marker 3, nvrm_free 2, nvrm_enqueue 2, nvrm_channel/destroy 2 each, nvrm_ring 1, nvrm_alloc_gpu_uncached 1. +Pointer passing and implied ownership: +- `M16NativeContext *`/`Nvrm *`: caller-provided storage (stack or struct field); library fills it; caller must `close` exactly once. +- `nvrm_alloc(Nvrm *, size, NvrmMem *out)`: out is a *copy* of an identity; the `Nvrm` owns the memory; `cpu` pointer valid until `nvrm_free`/`nvrm_close`. +- `nvrm_enqueue(Nvrm *, const NvrmMem *pb, off, nwords)`: GPU reads `pb` asynchronously after the call returns → caller must keep `pb` alive and unmodified until a completion is observed (not enforced). +- `m16_native_wait_marker_ge(volatile uint32_t *marker, …)`: marker must point into a live coherent allocation. +- **De facto ABI beyond functions**: Omega reads `Nvrm` internals directly (`.entries`, `.faulted`, `.put`, `.retired`, `.root`, `.device`, `.vaspace`; O:src/omega_accelerator_world.c:112,159,670,732,984; omega_world_gates.c:122-124). The struct layout is part of the boundary. +- Below that, the NVIDIA RM/UVM ioctl ABI (driver 580.173.02 headers) is an unavoidable class-D boundary until AIENOS owns the GPU natively. + +**Not linked by Omega** [FACT]: PHYSICS M2/M3 asm images (QEMU-only, separate binaries), M15 model, tools. + +--- + +## 6. Existing good patterns worth keeping + +- [FACT] M2 stackless trap collector: saves every GPR before reuse, magic written last, `dsb sy`, then switches to a known stack (P:vector_table.s:161-237). +- [FACT] Fail-closed ingress with distinct panic strings, no state written before validation (P:physics.s:21-124, 193-241). +- [FACT] Frame allocator overflow guard and "0 is never a frame" sentinel documented (P:memory_alloc.s:40-50, 107-113). +- [FACT] M2 `validate_capability` address+size wrap check (P:capability.s:108-112); M3 generation wrap retires the slot (m3/capability.s:403-408). +- [FACT] C authority: 64-bit never-wrap generations, restart floor above every previously used generation + boot-time seed (A:…/aienos_capability.c:45-79, 97-107); ancestor chain checked on every use (:143-167); privileged rights non-delegable (:227-229); `delivered[]` gating (:204); checked add for clock/epoch/lease (:86-90); results copied out, no interior pointers escape (:529-547); constant-time token compare (:572-580). +- [FACT] nvrm_free staged release with per-stage flags; quarantine VA on any partial failure; stale/duplicate `NvrmMem` detection without touching the driver (P:nvrm/nvrm.c:543-612, 453-460). +- [FACT] `MAP_FIXED_NOREPLACE` PROT_NONE reservation before mapping device memory at a fixed VA (nvrm.c:485-489). +- [FACT] Sticky `faulted` bit that blocks further alloc/enqueue after unknown driver state (nvrm.c:478, 721). +- [FACT] `nvrm_enqueue` span + overflow checks and "never overrun unretired entries" (nvrm.c:720-728); RFC 1982 serial compare for markers (m16_native.c:103). +- [FACT] RM handles never reused within a client; refuse at `UINT32_MAX` (nvrm.c:65-72). +- [FACT] Explicit big-endian length encoding and caller-provided scratch in `sha256_clean.c:88-103` (no hidden static state; freestanding). +- [FACT] Rust kernel design rules worth carrying into the rewrite: SMMU GBPA.ABORT first and never cleared, abort STE default (smmu.rs:8-12); BME only after `dma_grant` (dma_gate.rs:1-20). + +--- + +## 7. OSC-0B items (hardware/kernel side) + +**1. Interrupt + device concurrency and publication** +- [FACT] PHYSICS: no interrupts; single CPU; all exceptions terminal (§3a). +- [FACT] GPU publication = ring write → `dsb sy` → GPPut → `dsb sy` → doorbell; completion = volatile poll without acquire (§3b). +- [FACT] Revocation while a device holds a view: nothing enforces it. Capability revoke is purely table state; `nvrm_free`/`nvrm_channel_destroy` do not wait for the GPU; there is no SMMU/TLBI step in C (§3f). +- [SETTLED] P:docs/native-frame-authority.md §6.4: release requires the revoked capability plus a receipt showing all SMMU mappings removed and `CMD_TLBI_*`+`CMD_SYNC` completed. Not implemented anywhere. +- [PROPOSED] Revocation is two-phase: (1) revoke = no new use (table state, immediate); (2) reclaim of any memory/VA/frame requires an `own` token proving the device drained (fence observed or channel torn down) and, natively, SMMU unmap + TLBI + sync. Reclaim without the token is a type error, not a runtime check. +**2. Atomics / barriers / ordering** — [PROPOSED] Omega exposes only: `load_acquire/store_release` on `device`, `dmb ish/oshst/oshld`, `dsb`, `isb`, and seq-cst RMW; no plain volatile in safe code; every device-completion read is acquire. +**3. Device layout / wire formats** — [PROPOSED] Every struct that crosses a device, a hash, a receipt or the C ABI is declared with explicit size, offsets and LE encoding and compiled with generated `_Static_assert`s; hashes are over a serializer output, never over native struct bytes. +**4. Failure semantics** — [FACT] PHYSICS: panic-trap for ingress/invariant, 0 for exhaustion; C authority and nvrm: error codes, no aborts; nvrm sticky `faulted`; device loss undetected except by timeout. [PROPOSED] Kernel/interrupt context: invariant violation → trap to a stackless capture + halt (M2 pattern); OOM/exhaustion → error value, never a panic; invalid/stale capability → error value (fail closed); device loss → explicit `DeviceLost` error, sticky per device session, sourced from the channel error notifier. +**7. Pinning / memory that must not move** — [FACT] Must not move: PHYSICS fixed regions (vector table 2 KiB-aligned 0x40201000, boot state, trap frame 0x40205880, cap table, bitmap; P:machine_contract.json disjoint_regions); GPU allocations at identity VA (nvrm.c:485); GPFIFO + USERD in one allocation at `entries*8` (nvrm.c:627-640); markers polled by resident GPU programs. [PROPOSED] These are `pin`/`device` objects created only in `unsafe physical block`s; safe code gets `slice` borrows whose lifetime is bounded by the pin. +**8. MMIO / DMA / volatile / cache / SMMU / no-block contexts** — [FACT] MMIO: PL011 UART (polled busy-wait on TXFF, physics.s:252-257 — blocks in trap path by design), GPU usermode doorbell. DMA: GPU coherent snooped sysmem only. Cache ops: none in C/asm. SMMU: Linux-owned for now. No-block contexts: PHYSICS trap path (halts), Rust IRQ path. [OPEN] whether native GB10 sysmem is coherent for all GPU engines (P:docs/native-frame-authority.md §9 says "assumed"). +**12. Authority model** — [FACT] see §3f. Main objects: + +| Object | Who keeps it alive | Who may touch | Where it lives | +|---|---|---|---| +| C capability table (`CapShared`) | refcount of Admin+View handles | Admin: mutate; View: validate/inspect; cognition: nothing | heap (calloc) in the Omega process | +| `Nvrm` / `M16NativeContext` | the Omega caller (stack or struct) | single owning thread by convention (no lock) | Omega stack/struct (~225 KiB) | +| GPU memory (`NvrmMem`) | `Nvrm.live[]` + RM object | anyone holding a copy of the pointer | Linux-RM sysmem at identity VA (pinning assumed, [OPEN]) | +| GPFIFO / USERD / doorbell | `Nvrm` | `nvrm_enqueue`/`nvrm_ring`, Omega reads counters directly | RM sysmem / usermode MMIO | +| PHYSICS cap table, bitmap, ledgers | the PHYSICS image forever | PHYSICS code only (MMU off, EL1, single CPU) | fixed physical addresses per contract | + +--- + +## 8. Contradictions (docs vs code, code vs code) + +1. **Generation width.** C authority: u64, never wraps, EXHAUSTED at max (A:native/capability/aienos_capability.h:8-10, .c:80-84). Omega header: u64 (O:src/runtime/aienos_cap.h:7-8). AIENOS ADR 0013 + Rust kernel: u32, retire at `u32::MAX` (A:docs/adr/0013-aienos-abi-v1.md:57, 83-94; A:crates/aienos-kernel/src/caps.rs:76, abi.rs:141). Rust aienos-capability crate: u32 (src lib :86-87). PHYSICS M3: u32 retire on wrap (m3/capability.s:403-408). M2: u32, unchecked. M15: u32 (physics_accel.h:88). +2. **Who owns authority.** PHYSICS README "Trusted Machine Authority … PHYSICS AUTHORIZES", governor of SMMUv3/devices (P:README.md:1-40). aien-architecture ADR 0013/0014 (873025c): PHYSICS→FORGE is realization only, "not a gatekeeper"; AIENOS owns interrupts, capabilities, DMA confinement (docs/adr/0014:5-10; doctrine/SOVEREIGNTY.md:383). The M3 capability ledger and effect broker in PHYSICS asm are authority code under the old model. +3. **Release requires DMA quiescence** (P:docs/native-frame-authority.md §6.4) vs M3 `release_frame` checks only the bitmap bit (P:m3/memory_alloc.s:185-222) and nvrm_free has no GPU completion check. +4. **README claims SMMUv3 DMA protection** (P:README.md:38) vs no SMMU code in PHYSICS; evidence says Linux programs the SMMU, "takeover deferred" (P:evidence/physics_accelerator_link_qualification_receipt.json:38-39). +5. **M2 cap comment vs code**: header says `resource_type = 0xFFFFFFFF` (P:capability.s:24) but code stores 1 (:47-49); contract says 1. +6. **Decision codes**: `DEC_REJECTED` and `DEC_REJECTED_STRUCTURAL` are both 2 (P:m15/physics_accel.h:33-35). +7. **"No Rust"** in A:native/capability/Makefile:1 vs aienos-capability + aienos-capability-ffi still workspace members (A:Cargo.toml:4-5). +8. **Omega pin vs snapshot**: Omega `aienos.lock` = 4c21386 and Makefile default dir `../aienos-r9`; this audit's snapshot is 8706fb8. [OPEN] which authority commit is actually linked in local builds. +9. **Header drift**: Omega's `aienos_cap.h` omits every constant; Omega re-declares rights (`RX_RIGHT_*`) with no compile-time tie to `AIENOS_CAP_RIGHT_*`. +10. **M3 vs M2 trap collector**: M2 preserves x0/x1 and checks FnV; M3 does neither (§3a). +11. **Name vs behaviour**: `m16_native_wait_marker` (equals) calls `_ge` (m16_native.c:93-95). +12. `nvrm.h` declares `nvrm_alloc_gpu_uncached` after `#endif` (P:nvrm/nvrm.h:117-119). + +--- + +## 9. Recommended OSC-0B decisions + +1. [PROPOSED] **One capability identity**: `SemanticId = { u32 index, u64 generation }`, explicit 16-byte LE layout, generation never wraps, slot retired at max, restart floor as in the C authority. Supersede ADR 0013's u32 generation and M3/M15 u32 (needs ADR amendment; Drake-visible). +2. [PROPOSED] **Two-phase revocation**: revoke is immediate for new uses; reclaim of memory, VA, frames or channels requires an `own` proof (observed fence or drained channel, and natively SMMU unmap + TLBI + CMD_SYNC). Encoded in types, matching native-frame-authority.md §6.4. +3. [PROPOSED] **Completion is a value**: GPU completion produces `own` only from an acquire-load of a marker; `nvrm_retire`, pushbuffer reuse and `nvrm_free` consume fences. Plain volatile polling without acquire is forbidden. +4. [PROPOSED] **Failure classes**: invariant violation in kernel/trap context → stackless capture + halt (M2 collector is the reference); exhaustion/OOM, invalid/stale capability, device loss → error values, fail closed, never silent. Device sessions carry a sticky `faulted/DeviceLost` state sourced from the RM error notifier. +5. [PROPOSED] **No-allocate/no-block contexts**: trap/IRQ code may not allocate, take a blocking lock, or call the capability authority's mutating API; the type system marks these contexts. +6. [PROPOSED] **Explicit layouts**: any struct crossing a device, hash, receipt, or C ABI is declared with offsets and LE encoding and emits `_Static_assert`s in generated C headers; hashes are computed over serializer output. Omega's hand-copied `aienos_cap.h` is replaced by one generated header. +7. [PROPOSED] **Opaque device sessions**: `Nvrm` becomes an opaque `own` (heap/region, not stack); Omega stops reading its fields and uses accessors. Remove the function-local static in `uvm_map` now (trivial C fix, independent of OSC). +8. [PROPOSED] **Pinned memory**: fixed-address PHYSICS regions and identity-VA GPU memory are `pin`/`device` created only in `unsafe physical block`s; everything above borrows `slice`. +9. [PROPOSED] **Minimal ordering vocabulary**: acquire/release on `device`, `dmb ish/oshld/oshst`, `dsb`, `isb`, cache clean/invalidate by range; nothing else in safe code. +10. [PROPOSED] **Retire/merge**: M15 model (F), Rust aienos-capability(+ffi) (F), M3 trap collector (replace with M2's). Keep sha256_clean.c pattern. Remove `aienos_cap_force_generation` from the production ABI; make `restart` unable to revive a killed writer without an explicit right. +11. [OPEN] Where authority lives long-term: C authority in AIENOS (current Omega link) vs PHYSICS M3 ledger (old doctrine). ADR 0014 points to AIENOS; PHYSICS M3 ledger is then legacy evidence. +12. [OPEN] Native GB10 coherence for all engines, and whether GPU-uncached allocations need CPU-side cache maintenance natively. +13. [OPEN] Atlas handoff I-cache sync requirement once caches are on natively (atlas_m2.s:130-134). +14. [OPEN] Which AIENOS commit Omega actually links (lock 4c21386 vs snapshot 8706fb8). diff --git a/docs/osc/audit/baseline.md b/docs/osc/audit/baseline.md new file mode 100644 index 000000000..a74880bd2 --- /dev/null +++ b/docs/osc/audit/baseline.md @@ -0,0 +1,106 @@ +> Appendix to OMEGA_SYSTEMS_CORE_CODE_AUDIT.md (I.10). The counting shim and aggregation script are committed in docs/osc/audit/baseline/ (the job-tmp paths below no longer exist). Reference snapshots are regenerable by SHA: `git -C archive 8706fb8 | tar -x -C ` and `git -C archive fecbedb | tar -x -C `. Worker report (Sonnet 5.5 trial), omega 193a7e7 built in an exported copy with PHYSICS_LOCK_CHECK=0 against the physics fecbedb / aienos 8706fb8 snapshots; machine not quiet. Orchestrator re-check: sizes of omegatool, rx_heartbeat_test, rx_state_projection_test, rx_typed_results_test match exactly; heartbeat peak RSS 5456 kB vs 5568 reported; heartbeat allocations 399 vs 396 reported. Note added by reviewer: allocation counts are SUMMED over every process a test starts (heartbeat runs 2); the report does not say so. Build times not re-measured. rx_plan_reuse_test uses a perf-event ioctl (CPU counter, not GPU), so treat its rows as informational. + +# Omega C baseline (commit 193a7e7 export), host-only, CPU-side + +Machine: aarch64, 20 cores, NOT quiet (other sessions share it). `test -e /home/drakestapleton/workspace/.spark-quiet` was checked before every build/run loop: never present. +uptime at start: `06:43:47 load average: 1.08, 0.95, 0.72`; runs start `06:46:55 load 2.33, 1.62, 1.02`; runs end `07:14:23 load 2.48, 1.92, 1.58`; final `07:14:29 load 2.18, 1.87, 1.56`. +Compiler: `cc` = gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 (`cc --version`). Flags (Makefile CFLAGS): `-std=gnu11 -Wall -Wextra -Werror -MMD -MP -D_GNU_SOURCE -O2 -Isrc` + physics include dirs + `-DOMEGA_PHYSICS_DIR=...`; test binaries add `-pthread`, most link `-lm` and libaienos_capability.a. No LTO/-march/strip. Binaries are dynamically linked, not stripped (`file build/rx_action_graph_test`). + +## Provenance caveats (read first) +- The working copy has no `../physics` or `../aienos-r9`. I built with `PHYSICS_DIR=/physics PHYSICS_LOCK_CHECK=0 AIENOS_R7_DIR=/aienos` (script: `bench-scratch/mk.sh`). physics = copy of tmp `physics-snap`; aienos = copy of tmp `aienos-snap/native/capability`. Neither was verified against physics.lock (`fecbedb1...`) / aienos.lock (`4c21386...`) (git not runnable there). Physics only affects `omegatool` (m16_native.c, nvrm.c); the test binaries here do not link it. The aienos capability lib was built once beforehand (`make` in native/capability: 0.113 s real) and is EXCLUDED from build times. +- `make -j4` was used, but each test binary is one `cc` invocation, so -j4 only helps `all` (39 objects). +- Timing via `/usr/bin/time -v` (exists at /usr/bin/time); wall clock has 10 ms resolution. 5 runs each; median / min / max. +- Tests write receipts under `omega-bench/build/qual-runs/` (inside the working copy only). +- `rx_plan_reuse_test` was run before I noticed the ioctl rule: its source `tests/runtime/rx_plan_reuse.c` contains `ioctl(g_perf, PERF_EVENT_IOC_ENABLE, 0)` (line 88) and `#include `, a Linux perf-event CPU counter, NOT /dev/nvidia and no GPU. Under the strict ioctl rule it should count as "skipped", so its rows are INFORMATIONAL; raw data in `bench-scratch/runs/rx_plan_reuse_test.*`. A grep for `/dev/nvidia|ioctl|nvrm` over the other test sources, `src/runtime`, `src/crumbline`, sha256/omega_evidence/omega_core/omega_canonical, rx_cog_engines.[ch], rx_sp_workloads.h found nothing. + +## 1. Clean build wall time (rm -rf build before each; 5 reps; seconds; `bench-scratch/buildtime.sh`, output `buildtimes.txt`) +Per rep: `rm -rf build; ./mk.sh ` (= `make -j4 PHYSICS_DIR=... PHYSICS_LOCK_CHECK=0 AIENOS_R7_DIR=...`) +| target | 5 reps | median | min/max | +|---|---|---|---| +| all (omegatool, 39 objs) | 1.228 1.189 1.201 1.220 1.164 | 1.201 | 1.164 / 1.228 | +| rx_heartbeat_test (test-r3) | 1.837 1.851 1.926 1.881 1.853 | 1.853 | 1.837 / 1.926 | +| rx_action_graph_test | 2.104 2.081 2.083 2.017 1.975 | 2.081 | 1.975 / 2.104 | +| rx_state_projection_test | 2.297 2.256 2.277 2.241 2.263 | 2.263 | 2.241 / 2.297 | +| rx_plan_reuse_test | 1.975 2.065 2.028 2.063 2.066 | 2.063 | 1.975 / 2.066 | +| rx_sem_incremental_test | 1.478 1.473 1.446 1.493 1.426 | 1.473 | 1.426 / 1.493 | +| crumbline-learner | 0.341 0.356 0.344 0.356 0.369 | 0.356 | 0.341 / 0.369 | +| rx_capability_query_test | 2.097 2.164 2.126 2.115 2.130 | 2.126 | 2.097 / 2.164 | +| rx_semantic_comm_test | 1.563 1.503 1.454 1.448 1.554 | 1.503 | 1.448 / 1.563 | +| rx_cognitive_routing_test | 1.089 1.052 1.075 1.094 1.080 | 1.080 | 1.052 / 1.094 | +| rx_workflow_fusion_test | 2.407 2.423 2.381 2.434 2.407 | 2.407 | 2.381 / 2.434 | +| rx_typed_results_test | 2.155 2.260 2.162 2.107 2.189 | 2.162 | 2.107 / 2.260 | + +## 2. Binary size (`size `; `stat -c%s`; `bench-scratch/sizes.sh`, `sizes.txt`) +| binary | text | data | bss | file bytes | +|---|---|---|---|---| +| omegatool | 329194 | 2512 | 35680 | 431472 | +| rx_heartbeat_test | 188775 | 1336 | 8104 | 215704 | +| rx_action_graph_test | 180269 | 1544 | 321984 | 219720 | +| rx_state_projection_test | 148603 | 1452 | 19488 | 217344 | +| rx_plan_reuse_test | 194430 | 1712 | 431168 | 287224 | +| rx_sem_incremental_test | 137871 | 1664 | 37432 | 214968 | +| crumbline-learner | 80235 | 1312 | 1048600 | 148888 | +| rx_capability_query_test | 194591 | 1680 | 358296 | 286752 | +| rx_semantic_comm_test | 129472 | 1416 | 6552 | 217440 | +| rx_cognitive_routing_test | 114475 | 1384 | 456576 | 148680 | +| rx_workflow_fusion_test | 230404 | 1856 | 14903376 | 291304 | +| rx_typed_results_test | 202185 | 1744 | 3249584 | 286136 | +Large bss (fusion 14.9 MB, typed_results 3.2 MB, crumbline 1.0 MB) is zero-fill static arrays; it counts toward RSS only when touched. + +## 3. Wall time and peak RSS (5 runs, `/usr/bin/time -v -o F >out 2>err`; `bench-scratch/runall.sh`, aggregated by `agg.sh` -> `agg.txt`; raw in `runs/`) +Format median / min / max. All 55 runs exit 0 (`runs/rc.txt`); each test printed PASS (`tail runs/*.out.1`). Args: `rx_typed_results_test 400`; crumbline = `build/crumbline-learner --decode tests/crumbline/vectors/v001.crb` (ONE decode, not the `test-crumbline` conformance sweep, which was not run). +| binary | wall s | peak RSS kB | user+sys s | +|---|---|---|---| +| rx_heartbeat_test | 1.73 / 1.72 / 1.76 | 5568 / 5272 / 6040 | 0.23 / 0.22 / 0.24 | +| rx_action_graph_test | 0.27 / 0.26 / 0.27 | 4212 / 4092 / 4456 | 0.40 / 0.40 / 0.41 | +| rx_state_projection_test | 19.85 / 19.78 / 19.88 | 120480 / 120224 / 121000 | 19.88 / 19.81 / 19.92 | +| rx_plan_reuse_test (ioctl note) | 11.96 / 11.93 / 11.98 | 5584 / 5552 / 5660 | 8.99 / 8.97 / 8.99 | +| rx_sem_incremental_test | 151.7 / 151.65 / 151.87 | 28580 / 28436 / 28592 | 83.78 / 83.76 / 83.87 | +| rx_capability_query_test | 0.50 / 0.50 / 0.51 | 119628 / 119520 / 119636 | 0.49 / 0.49 / 0.51 | +| rx_semantic_comm_test | 56.67 / 56.57 / 57.10 | 123512 / 123436 / 123612 | 55.98 / 55.77 / 56.35 | +| rx_cognitive_routing_test | 20.08 / 19.98 / 20.20 | 7192 / 7192 / 7192 | 19.16 / 19.11 / 19.17 | +| rx_workflow_fusion_test | 10.99 / 10.86 / 11.00 | 88376 / 78240 / 94980 | 3.82 / 3.61 / 3.87 | +| rx_typed_results_test | 0.61 / 0.56 / 1.20 | 21284 / 21028 / 21508 | 0.39 / 0.37 / 0.52 | +| crumbline-learner --decode v001 | <0.01 (below 10 ms resolution) | 1328 / 1320 / 1460 | <0.01 | +Several tests contain deliberate sleeps/timed windows (heartbeat, sem_incremental, fusion), so wall >> CPU there; some are multithreaded (action_graph CPU > wall). + +## 4/5. Allocation accounting (LD_PRELOAD shim `bench-scratch/shim.c` -> `shim.so`; one run per binary: `LD_PRELOAD=shim.so /usr/bin/time -v `) +The shim wraps malloc/calloc/realloc/free/memalign/posix_memalign/aligned_alloc via glibc `__libc_*`, tracks live bytes with `malloc_usable_size` (usable size: allocator rounding included, chunk headers not), and prints totals from a destructor. `free(NULL)` is counted separately and excluded from "free". The shim also loaded into `/usr/bin/time` itself, so each .shimerr has a second 3-malloc report; ignored (first group is the test). All binaries exit normally, so the destructor ran for all. +`allocs` = malloc + calloc + memalign (new blocks); `realloc` is listed separately. **Leak figure = live blocks at exit** (handles realloc(NULL,n) and realloc(p,0)). `allocs - frees` is unreliable with heavy realloc (negative for state_projection, semantic_comm) so is not used. Peak = maximum simultaneous live usable bytes (allocated, not necessarily touched, so it can exceed RSS, e.g. sem_incremental 194 MB peak vs 28 MB RSS). +| binary | malloc | calloc | realloc | memalign | free | free(NULL) | live blocks at exit (bytes) | peak live usable bytes | total requested bytes | +|---|---|---|---|---|---|---|---|---|---| +| rx_heartbeat_test | 21 | 301 | 3 | 74 | 386 | 23565 | 13 (7640) | 1575920 | 25134634 | +| rx_action_graph_test | 97 | 330 | 3 | 18 | 435 | 5619 | 13 (7704) | 563272 | 8337616 | +| rx_state_projection_test | 49973 | 33037 | 66772 | 16 | 105057 | 6458 | 13 (7656) | 117807416 | 8300594728 | +| rx_plan_reuse_test (ioctl note) | 190055 | 9357 | 4 | 283 | 199683 | 84545 | 15 (2596344) | 3553560 | 3829810447 | +| rx_sem_incremental_test | 479 | 369 | 3 | 92 | 933 | 25104 | 10 (6800) | 194344120 | 17879567066 | +| rx_capability_query_test | 19853 | 3833 | 80 | 1 | 23699 | 280 | 11 (7112) | 158911752 | 399263460 | +| rx_semantic_comm_test | 28326 | 124355 | 255535 | 13685 | 378767 | 7446606 | 14 (302424) | 115351552 | 231240883578 | +| rx_cognitive_routing_test | 1968 | 20 | 3 | 0 | 1977 | 199 | 14 (94944) | 5659632 | 12898804 | +| rx_workflow_fusion_test | 237 | 531 | 3 | 33 | 791 | 10137 | 13 (7704) | 1287200 | 14254883 | +| rx_typed_results_test | 19914 | 17 | 3 | 1 | 19922 | 258 | 13 (7704) | 496408 | 511398698 | +| crumbline-learner --decode | 3 | 1 | 0 | 0 | 3 | 0 | 1 (4104) | 12336 | 16896 | + +A floor of ~10-13 live blocks / ~7 KB at exit appears in nearly all tests; I did not attribute it (likely libc/stdio/thread internals; not investigated), so it is NOT proof of application leaks. Larger residuals worth a look, not confirmed leaks (may be deliberately retained until exit): plan_reuse 15 blocks / 2.6 MB (mallinfo2 hblkhd=2588672, one mmapped block), semantic_comm 302 KB, cognitive_routing 95 KB. + +Fragmentation (mallinfo2 at exit, main arena only; `malloc_stats()` NOT added, so other thread arenas are not covered). arena / in-use (uordblks) / free (fordblks) bytes: +heartbeat 720896/18720/702176; action_graph 679936/44592/635344; state_projection 16453632/90192/16363440; plan_reuse 172032/17936/154096 (+hblkhd 2588672); sem_incremental 18305024/16320/18288704; capability_query 30105600/58352/30047248; semantic_comm 23973888/160944/23812944; cognitive_routing 5799936/101472/5698464; workflow_fusion 1056768/53824/1002944; typed_results 704512/20032/684480; crumbline 135168/5248/129920. +keepcost (trimmable top chunk) shows most free space is contiguous in several (sem_incremental keepcost 18254784 of fordblks 18288704); state_projection keepcost is 134912 of 16363440 free, i.e. about 16 MB of free but non-returnable fragments at exit. This is exit-state only, not peak fragmentation. + +## 6. Throughput / latency numbers the existing tests already print (run 1 of 5, `runs/.out.1`; they vary run to run; found with `grep -HiE 'ns/|us/|ms/|per second|throughput|latency|speedup|p99|p50' runs/*.out.1`) +- rx_action_graph_test: `median run: 1 worker 12.27 ms, 4 workers 3.25 ms, speedup 3.78x (critical path 3000 us of 12000 us work)` +- rx_capability_query_test: `100 capabilities: query median 848 ns (compile 736 + lookup 96) p99 1200 ns`; `1000: median 880 ns p99 3136 ns`; `10000: median 912 ns p99 15088 ns`; `100000: median 1440 ns p99 2849 ns; full scan median 148497 ns` +- rx_typed_results_test 400: `constrained: ... p50 28496 ns`; `free: ... p50 18624 ns` +- rx_cognitive_routing_test: e.g. `engine 11 class 2: accuracy 0.8286 ece 0.0149 mean 16 ns p99 320 ns 223 nJ/call` ... `engine 23 class 6: ... mean 28026 ns p99 66544 ns 329031 nJ/call` (test's own figures; not re-validated) +- rx_sem_incremental_test: `FULL query 1729.3 ms runs 3900 p50 2216.0 us p99 2234.7 us`; `OBJECT query 37.9 ms runs 647 p50 8.5 us p99 2227.3 us`; `FIELD query 36.0 ms runs 647 p50 8.5 us`; `ENGINE query 33.6 ms runs 401 p50 6.8 us p99 2061.2 us`; it also prints package/CPU energy in joules (e.g. `saved median 66.931 J`), not interpreted here. +- rx_plan_reuse_test (ioctl note): `merge_two_towers_3_3: ops 26.6x (G1 PASS), cpu 28.4x ... end to end 1.05x (G6 PASS)` +- rx_workflow_fusion_test: `hybrid: median 279.7 -> 81.7 us, CPU 317.7 -> 194.4 us/run`; `parallel: median 1672.2 -> 3142.2 us`; `compiled: median 483.9 -> 587.5 us` (its energy line was cut off in my grep view and is not copied). +Other tests print only pass/fail counts. + +## 7. NOT MEASURED (gaps) +- Any GPU / accelerator workload: `omegatool` `--run-gates` / `--demonstrate-arithmetic`, `make test`, `test-m5`..`test-m19` (omegatool links nvrm.c and m16_native.c; built but never executed, so only its size and build time are recorded). All `*-silicon`, r12, r13, r14, r15 (instr/parity/g7), m17 targets. +- r7 (needs AIENOS native authority), r8, r9, r10, r11 (r11 known flaky under load), branch-reuse (`rx_branch_reuse`), visor targets in `mk/*.mk`, the `test-crumbline` conformance sweep (only one `--decode` measured): not run. +- Peak/steady-state fragmentation, per-thread arena stats (`malloc_stats()`), alternate allocators: not measured. +- Verification of physics/aienos snapshot versions against lock files: not done. +- Quiet-machine numbers: not obtained (shared machine, load 1-2.5 throughout). +- Per-object / link-only build time breakdown: not measured. diff --git a/docs/osc/audit/baseline/agg.sh b/docs/osc/audit/baseline/agg.sh new file mode 100755 index 000000000..6086b14a5 --- /dev/null +++ b/docs/osc/audit/baseline/agg.sh @@ -0,0 +1,19 @@ +#!/bin/bash +R=/home/drakestapleton/.claude/jobs/9d0b86f6/tmp/bench-scratch/runs +cd $R || exit 1 +sec() { awk -F: '{ if (NF==3) print $1*3600+$2*60+$3; else print $1*60+$2 }'; } +stat3() { sort -n | awk '{a[NR]=$1} END{printf "%s / %s / %s", a[int((NR+1)/2)], a[1], a[NR]}'; } +echo "name | wall_s med/min/max | maxRSS_kB med/min/max | user+sys_s med/min/max | n" +for n in rx_heartbeat_test rx_action_graph_test rx_state_projection_test rx_plan_reuse_test rx_sem_incremental_test rx_capability_query_test rx_semantic_comm_test rx_cognitive_routing_test rx_workflow_fusion_test rx_typed_results_test crumbline-learner-decode; do + w=$(grep -h 'Elapsed' $n.time.[1-5] | awk '{print $NF}' | sec | stat3) + m=$(grep -h 'Maximum resident' $n.time.[1-5] | awk '{print $NF}' | stat3) + c=$(for f in $n.time.[1-5]; do awk '/User time/{u=$NF}/System time/{s=$NF}END{print u+s}' $f; done | stat3) + k=$(ls $n.time.[1-5] 2>/dev/null | wc -l) + echo "$n | $w | $m | $c | $k" +done +echo; echo "SHIM results" +for n in rx_heartbeat_test rx_action_graph_test rx_state_projection_test rx_plan_reuse_test rx_sem_incremental_test rx_capability_query_test rx_semantic_comm_test rx_cognitive_routing_test rx_workflow_fusion_test rx_typed_results_test crumbline-learner-decode; do + echo "== $n (SHIM line groups: $(grep -c 'SHIM malloc=' $n.shimerr)) shimRSS_kB=$(grep 'Maximum resident' $n.shimtime | awk '{print $NF}')" + grep '^SHIM' $n.shimerr +done +echo; echo "exit codes not 0:"; grep -v 'rc=0' rc.txt diff --git a/docs/osc/audit/baseline/shim.c b/docs/osc/audit/baseline/shim.c new file mode 100644 index 000000000..0c11638d5 --- /dev/null +++ b/docs/osc/audit/baseline/shim.c @@ -0,0 +1,90 @@ +// LD_PRELOAD allocation counting shim. Counts malloc/calloc/realloc/free (+memalign family), +// tracks live bytes with malloc_usable_size, prints totals + mallinfo2 at exit to stderr. +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include + +extern void *__libc_malloc(size_t); +extern void *__libc_calloc(size_t, size_t); +extern void *__libc_realloc(void *, size_t); +extern void __libc_free(void *); +extern void *__libc_memalign(size_t, size_t); + +static atomic_ulong n_malloc, n_calloc, n_realloc, n_free, n_memalign, n_free_null; +static atomic_ulong req_bytes; // sum of requested bytes (malloc/calloc/realloc new size/memalign) +static atomic_long live, peak; // live usable bytes +static atomic_ulong peak_count_live, live_count; // live block count / peak +static atomic_long live_cnt_l, peak_cnt_l; + +static void add_live(void *p) { + if (!p) return; + long u = (long)malloc_usable_size(p); + long l = atomic_fetch_add(&live, u) + u; + long pk = atomic_load(&peak); + while (l > pk && !atomic_compare_exchange_weak(&peak, &pk, l)) {} + long c = atomic_fetch_add(&live_cnt_l, 1) + 1; + long pc = atomic_load(&peak_cnt_l); + while (c > pc && !atomic_compare_exchange_weak(&peak_cnt_l, &pc, c)) {} +} +static void sub_live(void *p) { + if (!p) return; + atomic_fetch_sub(&live, (long)malloc_usable_size(p)); + atomic_fetch_sub(&live_cnt_l, 1); +} + +void *malloc(size_t n) { + void *p = __libc_malloc(n); + atomic_fetch_add(&n_malloc, 1); atomic_fetch_add(&req_bytes, n); + add_live(p); return p; +} +void *calloc(size_t a, size_t b) { + void *p = __libc_calloc(a, b); + atomic_fetch_add(&n_calloc, 1); atomic_fetch_add(&req_bytes, a * b); + add_live(p); return p; +} +void *realloc(void *o, size_t n) { + atomic_fetch_add(&n_realloc, 1); atomic_fetch_add(&req_bytes, n); + if (o) sub_live(o); + void *p = __libc_realloc(o, n); + if (p) add_live(p); else if (o && n) add_live(o); /* failed: old block stays live */ + else if (o && n == 0) { /* realloc(p,0) frees */ } + return p; +} +void free(void *p) { + if (!p) { atomic_fetch_add(&n_free_null, 1); return; } + atomic_fetch_add(&n_free, 1); + sub_live(p); + __libc_free(p); +} +void *memalign(size_t al, size_t n) { + void *p = __libc_memalign(al, n); + atomic_fetch_add(&n_memalign, 1); atomic_fetch_add(&req_bytes, n); + add_live(p); return p; +} +int posix_memalign(void **out, size_t al, size_t n) { + void *p = __libc_memalign(al, n); + if (!p) return 12; + atomic_fetch_add(&n_memalign, 1); atomic_fetch_add(&req_bytes, n); + add_live(p); *out = p; return 0; +} +void *aligned_alloc(size_t al, size_t n) { return memalign(al, n); } + +__attribute__((destructor)) static void report(void) { + struct mallinfo2 m = mallinfo2(); + unsigned long a = atomic_load(&n_malloc), c = atomic_load(&n_calloc), r = atomic_load(&n_realloc), + f = atomic_load(&n_free), ma = atomic_load(&n_memalign); + // allocs = malloc+calloc+memalign (new blocks; realloc(NULL,n) counted in realloc); realloc reported separately + fprintf(stderr, + "SHIM malloc=%lu calloc=%lu realloc=%lu memalign=%lu free=%lu free_null=%lu\n" + "SHIM new_block_allocs(malloc+calloc+memalign)=%lu allocs_minus_frees=%ld\n" + "SHIM live_blocks_at_exit=%ld live_usable_bytes_at_exit=%ld peak_live_usable_bytes=%ld peak_live_blocks=%ld requested_bytes_total=%lu\n" + "SHIM mallinfo2 arena=%zu uordblks=%zu fordblks=%zu hblks=%zu hblkhd=%zu keepcost=%zu\n", + a, c, r, ma, f, atomic_load(&n_free_null), + a + c + ma, (long)(a + c + ma) - (long)f, + atomic_load(&live_cnt_l), atomic_load(&live), atomic_load(&peak), atomic_load(&peak_cnt_l), atomic_load(&req_bytes), + m.arena, m.uordblks, m.fordblks, m.hblks, m.hblkhd, m.keepcost); +} diff --git a/docs/osc/audit/language-compiler.md b/docs/osc/audit/language-compiler.md new file mode 100644 index 000000000..7028998c5 --- /dev/null +++ b/docs/osc/audit/language-compiler.md @@ -0,0 +1,168 @@ +> Appendix to OMEGA_SYSTEMS_CORE_CODE_AUDIT.md. Worker report (Opus, read-only), omega 193a7e7. Reviewed: spot-checked omega_program.c:276 raw-struct hash, aarch64_encoder.c:114,122 silent immediate truncation, absence of ADDS/BL/STP (confirmed). Correction: a SUBS-immediate emitter exists (aarch64_encoder.c:158); the report says there is no ADD/SUB immediate. Not authoritative on its own; Part II of the main document rules. + +# Omega language / IR / encoder / identity audit (OSC-0 / OSC-0B input) + +Repo: omega worktree `osc-0` at 193a7e7. Read-only audit plus one throwaway encoder probe +(`/home/drakestapleton/.claude/jobs/9d0b86f6/tmp/probe.c`). Other docs: aienos ADR 0012 read live +from GitHub, aienos main `d39dd5b`; local aien-architecture at `873025c` on branch +`feat/resident-semantic-store-boundary` (may lag origin). The Seed/Forge ADR 0012 lives in +**aienos**, not aien-architecture (aien-architecture's 0012 is "shell-dispatch-then-landing"). + +Labels: [FACT] code fact, [SETTLED] decided in a doc, [PROPOSED] recommended OSC-0B decision, [OPEN] unresolved. + +--- + +## 1. The Omega language as implemented (V0) + +[FACT] Code: `src/language/omega_lex.[ch]` (197 lines), `omega_parse.[ch]` (429), `omega_lower.[ch]` (487). +Test: `tests/language/test_language_v0.c` + `tests/language/golden/v0.txt` (27 golden rows). +[FACT] The spec `spec/omega-language-v0.md` matches the code closely (the EBNF there is accurate). + +### Grammar the parser actually accepts (one statement per LINE) +``` +line = [ stmt ] +stmt = "let" NAME ":" type "=" expr + | "fn" NAME "(" NAME ":" type ")" "->" type ["requires" clause] ["ensures" clause] "{" expr "}" + | expr [ ":" type ] +expr = or [cmp_op or] -- comparisons PARSE but lowering rejects them (-2) +or = and { "|" and } ; and = add { "&" add } ; add = mul { ("+"|"-") mul } ; mul = prim { ("*"|"/") prim } +prim = INT | "true" | "false" | NAME | "(" expr [":" type] ")" +type = u8 | u16 | u32 | u64 | bool (i8..i64 recognised, rejected -2) +INT = decimal | 0x.. | 0b.. (<= 64 bits, decoded in lexer) +comments = // ... | /* ... */ +``` +- [FACT] Keywords (`omega_lex.c:96-102`): `let fn requires ensures true false`. Tokens: `( ) { } : , -> = + - * / & | == != < <= > >= !`. Strings, chars, `[ ]` rejected in the lexer. +- [FACT] Reserved (rejected as names/values, -2), `omega_parse.c:44-56`: types `u8..u64 bool i8..i64`, `result`, `effect effects cap capability mint revoke grant publish promote authority admin syscall io print import extern unsafe asm`, `if else while for loop return match struct enum mut var const self rec`. This is a pre-planned keyword set for growth. +- [FACT] `fn`: exactly one param, must be `u64 -> u64` after lowering; body must be a constant-step chain `((x op c1) op c2)...` with op in `+ - * & |`, constants <= 0xFFFFFFFF; no calls, no recursion. Contract clauses are canonicalised TEXT only (never checked). +- [FACT] Arithmetic lowers with `OVERFLOW_WRAP` only. + +Real example that parses and lowers (per spec + golden file): +``` +let x: u64 = 7 +x * 2 + 1 +fn f(x: u64) -> u64 requires x < 100 ensures result > x { x * 2 + 1 } +``` + +### Spec/wished features NOT implemented +[FACT] No evaluator in the language; no comparisons/bool ops in lowering; no signed ints; no unary minus / `!`; no calls; no multi-param or non-u64 functions; no blocks, statements sequences, control flow, loops, mutation, structs/enums, slices, references, pointers, arrays, strings; no effects/authority; contracts not verified; programs not verified (`is_verified=false`). Multi-line source is not supported at all. + +### Data structures and memory +- [FACT] Lexer: `OmegaToken{kind,col,value,text[64]}`, caller-provided array, max 256 tokens, line <= 1024 bytes (`omega_lex.h`). +- [FACT] Parser: `OmegaAst` holds a fixed in-struct arena `nodes[128]` (index links `lhs/rhs`, no pointers), depth <= 32, precedence-climbing loops. **No heap allocation anywhere in `src/language/`** (libc used: `snprintf memcpy memset strcmp strlen strstr memcmp` only). +- [FACT] AST is declared DISPOSABLE: never hashed or stored (`omega_parse.h` header, spec "Purpose"). +- [FACT] Lowering goes into the existing `OmegaGraph` (fixed 256 objects) via `omega_build_*`, dedupes by SemanticId, and restores `object_count` on any error (transactional). +- [FACT] Error model: return codes -1 syntax / -2 unsupported / -3 capacity, message "column N: ...". + +## 2. Other IR / compiler machinery + +| Thing | File | What it really does | Reusable as typed AST / verified IR target? | +|---|---|---|---| +| Semantic object graph | `src/omega_core.c`, `omega_types.h`, `omega_canonical.c` | Content-addressed DAG of VALUE/TYPE/OPERATION/APPLY objects; ops ADD..COMPILE incl. SELECT, SLICE, EQUAL, LESS_THAN; overflow policy WRAP/SATURATE/FAIL_CLOSED in op payload | Good pure-expression IR; has type tags for SIGNED_INT, SEQUENCE, TUPLE, ADDRESS, RESOURCE, CAPABILITY_REF already. No statements, locals, control flow, memory. Fixed 256 objects. | +| Program model | `src/omega_program.c/.h` | `OmegaProgram` = name + contract text + cost + one `RealizationObject`; `build_unary_op` emits MOVZ/MOVK + one ALU op + RET; `compose` concatenates (drops RET). u64->u64 only | Not a general IR. `program_id` hashes name/contract/cost bytes, NOT code (spec admits). | +| Realize (M5) | `src/omega_realize.c` | Emits fixed patterns for `f_add_sub` and single pure binary ops | Pattern emitter only. | +| realize_synth | `src/omega_realize_synth.c:34-50` | **Ignores the program**: always emits `MOVZ x1,3; MUL; MOVZ 2; SUB` (x*3-2), two schedules by issue width | Fixed-output stand-in (same class as self-host). | +| Self-host (M6) | `src/omega_self_host.c` | **Confirmed fixed-output stand-in**: emitted "compiler" checks magic "OMGG", dispatches on object COUNT byte (8 -> writes 3 hard-coded words ADD/SUB/RET; 5 -> ADR self + copy-loop of its own instructions = quine). | Not a compiler. Its two-pass label scheme (`SET_LABEL`, `REL_IMM19`) is the only fixup machinery in repo. | +| Action graph IR | `src/runtime/rx_graph.[ch]`, spec `action-graph-ir.md` | Typed goal->node graph (nodes, data/guard/order edges, auth[], res[], effects[] in total order), validated, optimised, lowered onto resident reactions | Runtime orchestration IR, not a language IR. Its identity/effect-order discipline is a good model. | +| Plan IR | `src/runtime/rx_plan.[ch]` | Plan templates + verified plan cache; semantic_id over sorted predicate lists | Same: orchestration, not codegen. | +| State projection | `rx_cortex`, `rx_projection` | need -> minimal projection of Cortex store | Not relevant to codegen. | +| Visor | `src/visor/*` | `./omega` REPL session: graph, bindings, programs table (16), realization/verify/evidence commands; hosts language V0 | The front door the new language should plug into. | +| Flow IR | none | [FACT] Nothing named Flow IR. "flow" appears only as prose ("control flow", "flow control", `plan-reuse.md` §4 "Flow"). | Name is free. | + +## 3. Identity and determinism (OSC-0B items 3, 6) + +### How identity is computed +- [FACT] SemanticId = SHA-256(canonical encoding) (`omega_canonical.c`), header "OMG0", version, kind, attrs sorted by key, relations sorted, constraints sorted, then `payload_len` + payload. +- [FACT] **Payload is `memcpy` of host C structs** (`omega_core.c:84,96,109,122,135,148,162,174,188,212,232,247,262`), each `memset` to 0 first, so padding is zero and output is deterministic ON ONE ABI, but NOT layout/endianness independent: enums are native 4-byte, `uint16_t byte_len` etc. little-endian. Golden row for `7: u64` shows `...0800 00..07` = byte_len 8 stored LE, value bytes BE. [SETTLED] `omega-language-v0.md` "Golden vectors": "golden bytes are pinned to this ABI (aarch64/x86-64 LP64, 4-byte enums)". +- [FACT] `omega_program_compute_id` (`omega_program.c:41-67`) builds an explicit byte buffer (layout-independent) but omits code. +- [FACT] `omega_task_init` hashes the raw `SynthesisTask` struct: `sha256_hash(task, sizeof(SynthesisTask) - 32, ...)` (`omega_program.c:276`). `task_id` is the FIRST field, so this hashes the zeroed id and **drops the last 32 bytes (expected_outputs[12..15])** - a latent bug, plus ABI-bound. +- [FACT] Runtime IRs do it right: `rx_graph.c:20-30` `put32/put64` explicit big-endian into SHA; `rx_plan` uses `rx_plan_encode` + sort. Layout-independent. +- [FACT] Realization id: `omega_realize_compute_triple_id` = SHA(OMG0 | kind | profile | semantic id | machine id | code bytes). + +### Nondeterminism +- [FACT] No `__DATE__/__TIME__` in src. Receipts embed wall time + `git rev-parse` (`omega_evidence.c:41-45`) by design. `omega_library.c:193` stores `time(NULL)` in `timestamp_added` but the library digest (`:60-82`) excludes it. `clock_gettime` only in benchmarks/submit timing. +- [FACT] Build flags (`Makefile:1,8`, `mk/00-visor-core.mk:8`): `gcc -std=gnu11 -O2 -Wall -Wextra -Werror -D_GNU_SOURCE`; no `-ffile-prefix-map`, no `SOURCE_DATE_EPOCH`, no reproducible-build check of Omega's own binaries. +- [FACT] "C1 == C2 == C3" (`tests/run_m6_gates.sh:78-83`, `tools/omegatool.c:813-823`, `omega_self_host.c` bootstrap): the memcmp is real, but C2 is produced by C1's self-copy loop, so equality holds **by construction**; it proves the copy loop and determinism of C0's emitter, not compilation. The receipt also hard-codes `COMPILER_REALIZATION_ID` as a literal (`run_m6_gates.sh` ~line 57) and writes `"fixed_point_verified": true` as text (guarded only by `set -e` on earlier steps). + +### Live handle vs persistent identity (item 6) +- [FACT] Distinct types exist, not unified: + - `SemanticId{uint8_t[32]}` - content identity (`omega_types.h:25`). + - `OmegaHandle{world_epoch, object_id, object_generation(u32), object_type, permissions}` - live accelerator handle (`omega_accelerator_world.h:44-51`). + - `RxCapRef{cap_id, generation(u64)}` (`rx_caproot.h:117`), `AienosCapRef{cap_id, generation u64}` (`aienos_cap.h:21`) - live capability refs. + - `EffectPayload{capability_slot u32, capability_generation u32, capability_ref SemanticId}` (`omega_types.h:160-167`) - a live slot/generation **embedded in a hashed payload**, i.e. a live handle does enter a SemanticId today. +- [FACT] No type-level rule stops a live handle being serialised as durable identity. + +## 4. Machine-code emitters + +[FACT] `src/aarch64_encoder.c` (168 lines) is the only AArch64 encoder. Exact emittable instructions: +ADD/SUB/AND/ORR/EOR (shifted register, no shift), MUL (MADD with XZR), MOV (ORR XZR), MOVZ, MOVK (any hw), RET, B, B.cond, CBZ, CBNZ, ADR, LDR/STR unsigned-offset (W/X), LDRB/STRB unsigned-offset, LDR/STR post-index (W and X), SUBS immediate, SUBS register (so CMP via rd=XZR). +Users: `omega_matvec.c`, `omega_matvec_quad.c` (quad4 / M12 kinds), `omega_realize*.c`, `omega_program.c`, `omega_self_host.c`. (The Blackwell files emit GPU code, not AArch64.) + +Probe (compiled against the real encoder, all matched the ARM reference words): +``` +ADD X0,X0,X1 8B010000 OK | SUB X0,X0,X2 CB020000 OK | MUL X0,X0,X1 9B017C00 OK +MOVZ X0,#1 D2800020 OK | MOVK X0,#1,LSL16 F2A00020 OK | MOVZ LSL48 D2E00020 OK +LDR X0,[X1,#8] F9400420 OK | STR X0,[X1,#8] F9000420 OK +CMP X0,#1 F100041F OK | CMP X0,X1 EB01001F OK | B.EQ +2 54000040 OK | B.VS +2 54000046 OK +CBZ X0,+2 B4000040 OK | B -1 17FFFFFF OK | RET D65F03C0 OK | buffer-full -> rc=-1 OK +ADD rd=31 -> 8B0003FF (XZR, not SP) +LDR X0,[X1,#12] -> F9400420 == LDR [X1,#8] <-- SILENT MISENCODING (no alignment check) +``` + +| Capability | Yes/No | Evidence | +|---|---|---| +| LDR/STR immediate offset | YES (unsigned, scaled) | `aarch64_encoder.c:112-126`; misaligned offsets silently truncated; no range check (masked to 12 bits) | +| LDP/STP | NO | not in encoder or decoder | +| Register ALU ops | YES: ADD SUB AND ORR EOR MUL | `:13-61` | +| MOVZ/MOVK | YES | `:67-102` | +| CMP + B.cond / CBZ | YES (CMP = SUBS to XZR) | `:83-96,158-168` | +| ADDS + B.VS | NO ADDS (B.VS encodes; SUBS exists, so sub-overflow check is possible) | no adds emitter | +| Mul overflow (SMULH/UMULH) | NO | - | +| SDIV/UDIV | NO | - | +| BL / BLR | NO (RET only) | - | +| Stack frame (SUB SP / STP FP,LR) | NO: `REG_SP == REG_XZR == 31` (`aarch64_target.h:23-24`); shifted-register ADD/SUB cannot address SP; no ADD/SUB immediate; LDR/STR with rn=31 would address SP but SP can't be adjusted | probe | +| Branch range checks | NO (imm masked) | `:78-96` | +| Labels / fixups | only ad hoc two-pass in `omega_self_host.c` | - | + +Execution: [FACT] `omega_exec_native_f3` (`omega_exec.c:8-40`) mmap RW, memcpy, `__builtin___clear_cache`, mprotect RX, call as `uint64_t f(uint64_t,uint64_t,uint64_t)`, munmap. Same pattern inline in `omega_realize_synth.c` (~`:150`) and matvec. No ELF writer anywhere. Signature fixed to 3 u64 args. +[FACT] Verification gate: `omega_verify_v0_structural` calls `aarch64_validate_code_buffer` (`omega_verify.c:62`), which rejects any opcode not in the decoder allowlist (`aarch64_decoder.c`, "Undefined/unrecognized AArch64 opcode") and requires a final RET. **Every new emitter must be mirrored in the decoder**, and "last instruction must be RET" breaks with multi-function code or trap stubs after RET. + +Effort estimate for a tiny language backend (functions, stack locals, checked i64 arithmetic, bounds checks, calls to runtime alloc/free): +- Encoder + decoder additions (~15 forms: ADD/SUB immediate incl. SP form, ADDS/SUBS reg, SMULH, SDIV, STP/LDP pre/post/offset, BL, BLR, LDR/STR register-offset with LSL, CSET, BRK/UDF trap, plus alignment/range checks) with probe tests against known words: ~1-2 worker-days. +- Label/fixup assembler, frame layout, simple stack-slot codegen (no register allocator), trap-on-overflow/bounds via B.VS/B.HS to a trap block, BLR to C runtime alloc/free via MOVZ/MOVK absolute address, multi-function blob + entry table, exec harness generalised beyond f3: ~3-5 worker-days. +- Decoder "final insn must be RET" rule needs relaxing to a function table. + +## 5. Verification machinery to reuse / stay consistent with +- [FACT] `omega_validate_graph/object` (`omega_validate.h`): typing + DAG + reference resolution. +- [FACT] `omega_verify` tiers: V0 structural (graph typing + decoder allowlist + RET), V1 differential (native result vs reference `omega_eval` on input triples) - the existing oracle model, V2 fixed properties (commutativity, identity, WRAP overflow, width range). +- [FACT] Typed result constraints `rx_contract.[ch]`: `rc_check/rc_compile/rc_domain/rc_gate_register` - publish gate that refuses non-conforming results. +- [FACT] Capability checks: rx_world `validate_caps` twice per activation, generations + `RX_ERR_STALE_GEN`; action graph `auth[]`; `rx_graph.o` link check forbids `aienos_cap_*` admin symbols (Omega never mints) [SETTLED `action-graph-ir.md` Boundaries]. +- [FACT] Tests: shell gate runners `tests/run_m*_gates.sh`, canonicalization/identity/malformed shell suites, language golden vectors, hostile tests (`tests/visor/test_visor_authority.c`), runtime tests. **No fuzzer or property generator found** (no PRNG-driven test harness in language/core). + +## 6. Lifetime vs authority vs placement today (item 12) +- [FACT] Surface language: none of the three is expressible; the words are reserved. +- [FACT] IR: authority = `EffectPayload` cap slot/generation + `CAPABILITY_REF` type tag + action-graph `auth[]`; lifetime = object/capability generations and stale-generation refusal (runtime only), no static lifetime; placement = `RealizationObject.target_profile` + machine graph + triple realization id (semantic x machine x code). + +## 7. libc the substrate must replace (item 10) +- [FACT] Core semantic path (core, canonical, sha256, program, language): `memcpy memset memcmp strcmp strlen strstr snprintf` + one `calloc` (`omega_core.c:8`, graph allocation). SHA-256 is in-house (`src/sha256.c`). +- [FACT] Encoder/exec: `mmap mprotect munmap sysconf __builtin___clear_cache`. +- [FACT] Everything else (printf/fprintf/fopen/popen/getenv/time/strftime/qsort(1, `visor_evidence.c:477`)/malloc) is in receipts, gates, console, Blackwell/GPU code (36 mallocs in `omega_blackwell_gates.c`). ``/`` only in Blackwell and world gates, not the language path. + +## Contradictions (doc vs code) +1. `README.md:19` "OMEGA is not a programming language, compiler..." vs `spec/omega-language-v0.md` (a language exists) and `spec/self-host.md` ("self-hosting compiler"). +2. `spec/canonical-encoding.md` §2 rule 4 "payload always big-endian" vs `omega_core.c` memcpy of host LE structs; `omega-language-v0.md` admits the ABI pin. +3. `spec/type-system.md:35` CAPABILITY_REF `generation: u32` / `EffectPayload.capability_generation u32` vs runtime `RxCapRef/AienosCapRef generation u64` (also recorded in commit 8a7d95e). +4. `spec/self-host.md` "compiles itself" vs `omega_self_host.c` count-dispatch + self-copy quine. +5. `spec/realize_synth.md` machine-aware synthesis from a program vs `omega_realize_synth.c:34-50` fixed x*3-2 code. +6. `spec/program.md:21` "verified native code" vs language lowering leaving `is_verified=false` and `program_id` not covering code. + +## Recommended OSC-0B decisions (all [PROPOSED]) +1. **Syntax: extend V0, don't replace it.** Keep its lexer rules, literal typing rule (no guessed widths), precedence, `fn ... requires/ensures`, and reserved list; activate reserved words (`i8..i64`, `mut`, `struct`, `if/else/while/return`, `unsafe`) rather than inventing new ones. Add multi-line source with a per-function arena (lift the 1-line/256-token/128-node limits). +2. **Typed AST stays disposable** (as V0 settled); identity attaches to the lowered IR (call it Flow IR; name is free), never to syntax. +3. **Wire layout rule:** every hashed/serialised byte comes from an explicit big-endian writer (the `rx_graph put32/put64` pattern). No `memcpy` of structs into identity. Migrating the core payloads is a deliberate identity break (re-generate golden vectors once, with a version bump in the "OMG0" header), and fix the `SynthesisTask` hash range bug. +4. **Handle rule:** separate types for durable identity (`SemanticId`) vs live handles (`{id, generation}` refs); live handles are forbidden in any canonical encoder (checker rejects the type in hashed payloads). Migrate `EffectPayload` to reference capabilities by SemanticId only, and settle generation width at u64 in the spec. +5. **Checked arithmetic default:** new signed ints lower with `OVERFLOW_FAIL_CLOSED` (already an enum value) - trap, not wrap; V0 unsigned WRAP stays for back-compat. +6. **Backend for the slice: both, with roles.** (a) Direct AArch64 via the extended in-repo encoder is the real backend (matches founding principle + no-outside-deps; the encoder is correct where it exists, per probe). (b) Emit C compiled by system `cc` only as a **differential oracle** in the V1 style (same program, two backends, compare results + traps), never shipped. Pros (a): sovereign, reuses exec/verify; cons: 4-7 worker-days, needs decoder mirror + fixups + SP support. Pros (b): fast, catches codegen bugs; cons: depends on gcc semantics (UB) - acceptable only as an oracle since gcc already builds Omega. +7. **Encoder hardening first:** reject misaligned/out-of-range offsets and branch displacements (currently silently masked), distinguish SP from XZR in the API. +8. **Reproducible build check:** add `-ffile-prefix-map` and a build-twice-compare gate for the new compiler; do not reuse the M6 C1==C2==C3 claim as evidence of compilation. +9. [OPEN] Whether contracts (`requires/ensures`) become checked in the slice or stay text. +10. [OPEN] Whether the new IR lives inside `OmegaGraph` (256-object fixed cap) or a new store. diff --git a/docs/osc/audit/omega-runtime.md b/docs/osc/audit/omega-runtime.md new file mode 100644 index 000000000..89c97aa22 --- /dev/null +++ b/docs/osc/audit/omega-runtime.md @@ -0,0 +1,297 @@ +> Appendix to OMEGA_SYSTEMS_CORE_CODE_AUDIT.md. Worker report (Opus, read-only), omega 193a7e7. Reviewed by the OSC orchestrator: spot-checked omega_accelerator_world.c:257-290, rx_generation.c:560-565, rx_coherent.c:921-931 (all confirmed). Not authoritative on its own; Part II of the main document rules. + +# Omega C memory / ownership hazard map (OSC-0 / OSC-0B input) + +Repo: aien-dev/omega at 193a7e7 (worktree osc-0). Read-only audit; nothing built or run. +Scope: all C in src/**, tests/** (harness), tools/*.c = 87,486 lines in 212 files. +Labels: [FACT] code fact with file:line; [SETTLED] decided in a spec/doc (cited); [PROPOSED] recommended OSC-0B decision; [OPEN] unresolved. +Non-overlap: src/language, aarch64 encoder/decoder/emitters, canonical/SemanticId (omega_canonical, omega_codec, sha256), self-host and compiler determinism belong to another worker and are only inventoried here. PHYSICS (nvrm.c, m16_native.c, the NVIDIA-open headers) and AIENOS (libaienos_capability.a) belong to a third worker; only their boundary with Omega is noted. + +Counts are grep counts over src+tests+tools (*.c, *.h). They are "sites", not proven bugs. + +--- + +## 1. Inventory + +All rows [FACT] unless marked otherwise. + +Class key: A semantic / B safe systems / C physical realization / D unavoidable unsafe hardware boundary / E temporary bootstrap dependency / F obsolete, retire. + +| Subsystem (files) | Lines | Purpose | Class | +|---|---:|---|---| +| src/runtime rx-core: rx_world.c/.h, rx_coherent.c, rx_seq_reference.c/.h | 3,848 | Resident reaction runtime: object slots, reactions, scheduler/workers, causal crumb log, CPU image of the shared world, resident-seat ring protocol | B (rx_coherent ring part D) | +| src/runtime/omega_shared_world_abi.h, aienos_cap.h, rx_native_bind.c | 414 | Frozen OMEGA_SHARED_WORLD_V1 wire ABI; C view of AIENOS capability authority; layout asserts binding the two | D (ABI) | +| src/runtime/rx_caproot.c/.h | 891 | Linux host-reference capability root: separate process, sealed memfd table, seqlock readers | B, E (Linux oracle; to be replaced by AIENOS native root) | +| src/runtime/rx_resident_gpu.c/.h | 1,146 | Persistent Blackwell "seat": builds SASS program, launches via PHYSICS, heartbeat/lease threads, kill/relaunch | D | +| src/runtime/rx_generation.c/.h | 1,630 | R9 generation store on disk (candidate/active, rename flip, journal, receipts) | B | +| src/runtime rx-state: rx_jspace, rx_cortex, rx_projection, rx_semantic, rx_semcomm (.c/.h) | 4,684 | Branch-shared cognitive state (refcounted realizations, spill), Cortex append store, state projection, semantic reuse cache, semantic communication | A/B | +| src/runtime rx-planning: rx_graph, rx_contract, rx_capq, rx_route, rx_plan, rx_plan_arrange, rx_fusion | 8,982 | Action-graph IR, typed result contracts, capability query, cognitive routing, plan IR/cache, workflow fusion | A | +| src/runtime faculties: rx_aien, rx_omega, rx_aegis, rx_living | 3,181 | Reaction bodies for AIEN/OMEGA/AEGIS faculties; rx_omega JIT store + fork sandbox; living-system glue | A (rx_omega exec pages C) | +| src/omega_accelerator.c/.h, omega_accelerator_world.c/.h | 1,789 | M19 accelerator world: buffer/code registries, handles, scratch bump arena, in-flight submissions, channel-fault recovery, rolling digest | C/D | +| src/omega_blackwell_* (codegen, encoder, qmd, submit, matmul, realize, gates) | 4,485 | Blackwell IR->SASS codegen, QMD build, pushbuffer submission, M17/M18 gate suites | C/D (gates: E) | +| src/omega_world_gates.c/.h | 2,401 | M19 gate suite compiled into omegatool (global gate state) | E/F (test code living in src) | +| src/ semantic core: omega_types.h, omega_validate, omega_core, omega_program, omega_verify, omega_synthesis, omega_library, omega_discovery, omega_machine, omega_evidence, omega_vector | 3,523 | Semantic object graph, validation, interpreter, synthesis/discovery, library, machine graph, evidence receipts | A | +| src/ CPU realization: aarch64_encoder/decoder/target, omega_realize, omega_realize_synth, omega_exec, omega_self_host, omega_matvec(_quad) | 2,182 | AArch64 emit/decode, realization objects, in-process native exec, self-host quine, matvec | C (other worker owns encoder/self-host) | +| src/omega_canonical, omega_codec, sha256 | 659 | Canonical encoding, codec, SHA-256 | A/B (other worker) | +| src/language (lex/parse/lower) | 1,328 | Omega surface language V0 | A (other worker) | +| src/visor (+ rx/visor_world_rx.c) | 5,415 | Visor V1 console: parse, semantic/realization/machine/world/evidence/verify views, effect-request lane | A/B | +| src/crumbline (cl_common, cl_crumb, cl_program, cl_search) | 1,216 | Crumbline learner: crumb decode, program model, bounded search | A | +| tools/omegatool.c | 3,965 | M-gate driver (gates 1..19), demos, forged-receipt tests | E | +| tools/omega.c | 795 | Visor REPL binary (static view buffers) | B | +| tools/r15_reduce.c | 1,289 | R15 evidence reducer (file globals) | E | +| tools/crumbline_learner.c | 294 | Crumbline learner entry point | A | +| tests/runtime R7..R14 + heartbeat (10 files) | 12,241 | Host + silicon qualification of authority, barrier, resident seat, living, recovery; fork/threads/hostile attacks | E (harness) | +| tests/runtime Omega IR gates (14 files) | 14,281 | Action graph ... workflow fusion gates | E (harness) | +| tests/runtime R15 rig (r15_measure, r15_gpu_load, rx_r15_*) | 3,926 | Perf/PMU (perf_event ioctl), NVML via dlopen, load rig | E (NVML = outside dep, retire) | +| tests/visor, tests/language | 2,921 | Visor + language tests | E | +| research/m15/{spbm,pmu}/*.c,*.h (listed only) | n/a | aien_spbm_readonly.c, contract_test.c, contract.h, reduce.c, sample.c, load.c, pmu_probe.c | F/E (research) | + +[FACT] External deps (Makefile:3-25, 186-197): libc, pthread, libm; PHYSICS sources compiled in (`$(PHYSICS_DIR)/m16/m16_native.c`, `nvrm/nvrm.c`) plus NVIDIA open-kernel 580.173.02 headers (-I paths Makefile:9-13); AIENOS `libaienos_capability.a` (Makefile:186); NVML `libnvidia-ml.so.1` via dlopen in tests/runtime/r15_measure.c:195-203; perf_event ioctl (r15_measure.c:104-112, rx_plan_reuse.c:88). No libcuda. GPU entry points from Omega: nvrm_* / m16_native_* only in omega_blackwell_submit.c, rx_resident_gpu.c, omega_world_gates.c, omega_accelerator_world.c. + +--- + +## 2. Hazard counts and representative sites + +All rows [FACT] (grep counts at 193a7e7) unless marked otherwise. + +| Category | Count (sites / files) | Representative file:line | +|---|---|---| +| malloc / calloc / realloc / free | 164 / 102 / 28 / 334 (49 files free) | rx_jspace.c:174 calloc JsReal, :297 realloc chain; rx_world.c:535 realloc deferred ring, :1574 calloc subs; rx_resident_gpu.c:74,1007,1020; heaviest: omega_blackwell_gates.c (36 allocs), rx_jspace.c (24), rx_capq.c (16) | +| posix_memalign / aligned | 1 | rx_coherent.c:198 (coherent image) | +| raw pointer struct fields | ~200 decl lines (heaviest: visor_semantic.c 14, rx_jspace.h 11, rx_contract.h 11, visor_console.h 11) | rx_world.h:491-558 (root, auth_ctx, subs[], crumbs, coherent, timing); rx_jspace.h:96-111 (parent_realization, bytes, packed, index_next); omega_accelerator_world.h:63,75 (void *cpu_addr); rx_resident_gpu.c:48-64 (world, job, hb_watch) | +| pointer arithmetic (base+offset into mapped/shared memory) | 53 (src/tools) | rx_coherent.c:124-135 `w->coherent + off_*()`; omega_accelerator_world.c:283 `(uint8_t *)entry->cpu_addr + req_offset`; :440 scratch `mem.cpu + off`; rx_resident_gpu.c:775,881; rx_cortex.c:113 `s->arena + o->off` | +| NULL sentinels | `== / != NULL` 86 in 32 files; `return NULL` 127 in 39 files | rx_world.c:22-25 crumb_log_map returns NULL on overflow/MAP_FAILED; rx_jspace.c:140-143 index chain terminated by NULL; rx_world.c:231-233 rx_world_crumb NULL = not found | +| fixed MAX arrays (`#define *MAX* n`) | 140 defines / 51 files | rx_world.h:33-45 (256 objects, 1024 reactions, 16 workers, 1024 subs/object); omega_accelerator_world.h (128 buffers, 64 code, 256 in-flight); omega_shared_world_abi.h (1024 ring, 64 objects) | +| ptr+len conventions | pervasive; `uint8_t *buf; size_t len` | cl_common.h:24,40; rx_semcomm.h:176; rx_jspace.h:105-106 (packed/packed_len) | +| flexible array members | 0 | none | +| void* | 312 / 71 files | rx_world.h:206,290 `void *user`; rx_world.h:494 `const void *auth_ctx`; visor_console.h:57,98; cl_search.h:41,66 | +| data<->function pointer punning | 7+ | union {void*; Fn} rx_omega.c:177,456; omega_exec.c:28-33; omega_matvec.c:291-296; dlsym casts r15_measure.c:197-203 | +| volatile<->_Atomic punning | 4 helpers | rx_coherent.c:75-85 casts `volatile uint64_t*` to `_Atomic uint64_t*` | +| struct-typed pointer casts on raw memory | many | rx_coherent.c:124-135 `(OmegaSharedWorldRing *)(w->coherent + off)`; rx_world.c:1809; grow((void **)&p->arena ...) rx_projection.c:174 (T** -> void**) | +| uintptr_t | 0 | none (addresses kept as `void*` + `uint64_t va`) | +| goto cleanup | 103 / 16 files | rx_generation.c (20; e.g. :974-982 `goto done`), rx_coherent.c (14; :661-700 `goto out` with mutex unlock), rx_world.c (9) | +| manual multi-free cleanup ladders | several | rx_resident_gpu.c:1020-1085 (each failure path repeats m16_native_close/free(code)/free(s)); omega_matvec.c:331-334 | +| global mutable state (file-scope non-const statics) | 202 lines / 46 files (≈70 in src+tools) | rx_coherent.c:88-89 g_crc/g_crc_ready; rx_resident_gpu.c:137 emit_overflow; rx_fusion.c:675 g_bench, :899 g_blob; rx_capq.c:302 `__thread t_sort`; rx_generation.c:149 g_io_bytes/g_io_syncs; omega_evidence.c:36-37 g_run_id; visor_evidence.c:29-32,445-447 parser buffers; tools/omega.c:42-53 view buffers; omega_world_gates.c:19-34, 2169-2170 | +| arenas / bump / pools | 5 | OmegaScratchArena bump (omega_accelerator_world.c:424-451); CxStore arena (rx_cortex.h:79, grow rx_cortex.c:58); projection arena (rx_projection.c:143-179); crumb log (rx_world.c:21-26, MAP_NORESERVE reservation); fixed slot pools RxWorld.objects/reactions, accel buffers/code_entries | +| accelerator object registries | 2 | OmegaAcceleratorWorld.buffers[128]/code_entries[64]/in_flight[256] (omega_accelerator_world.h); RxWorld.objects[256] with physical windows (rx_world.h:293-316) | +| CPU addresses / GPU VAs as fields | gpu_va/.va 458 hits in 10 files (omega_blackwell_submit.c 42, omega_world_gates.c 28, omega_accelerator_world.c 19, rx_resident_gpu.c 14) | OmegaBufferEntry/CodeEntry `void *cpu_addr; uint64_t gpu_va; NvrmMem mem` (omega_accelerator_world.h:57-77); OmegaCompletionTracker `volatile uint32_t *cpu_marker; uint64_t gpu_va`; SeatArgs.region = image.va (rx_resident_gpu.c:35,1065) | +| generations / epochs / object IDs | "generation" 1010 / 85 files; epoch 234 / 37 | RxObjRef{id,generation} rx_world.h:172; RxCapRef{cap_id, u64 generation} rx_caproot.h:118; OmegaHandle{world_epoch,id,gen,type,perms} omega_accelerator_world.h:48; seat_generation rx_world.h:549; channel_generation; ABI world_epoch/object_generation/sequence | +| permission / rights fields | rights 319 / 52; authority 573 / 83 | RxCapEntry.rights (rx_caproot.h:127); OmegaHandle.permissions + entry.permissions; ABI OmegaSharedWorldObject.permissions (written 0, never authority: rx_coherent.c:6-7) | +| stale-handle validation | "stale" 200 / 30 | omega_accelerator_world.c:397-422, 257-290; rx_caproot.c:569-618; rx_coherent.c notice_intact :709-719, check_locked :287; rx_world.c RX_ERR_STALE_GEN | +| serialization / deserialization | canonical 179 hits / 79 files; OMGG 1 | Explicit LE encoders: rx_world.c:44-52 put32/put64, rx_generation.c:122-141, 251-290; rx_capq.c:202; frozen wire: omega_shared_world_abi.h; library "LIB1" (omega_library.c), "OMG0"/"OMG_R0" headers (omega_machine.c, omega_realize.c) [other worker] | +| mmap / munmap / mprotect | 18 / 24 / ~20 | rx_world.c:23 crumb log; rx_caproot.c:341,456 memfd table; rx_jspace.c:846; rx_omega.c:137 JIT page; omega_exec.c:15; omega_accelerator_world.c:659-664 output write-protect | +| ioctl | 4 (tests only, perf_event) | r15_measure.c:104-112 | +| MMIO / doorbell / semaphore | doorbell 9, semaphore 25 (in PHYSICS calls) | nvrm_ring / m16_native_submit_methods (omega_accelerator_world.c:688-694, rx_resident_gpu.c:844); host semaphores `volatile uint32_t *hsem` omega_blackwell_submit.c:125-126, omega_accelerator_world.c:899,1119 | +| inline asm | 23 (dsb sy ×18, yield ×4) | rx_resident_gpu.c:710-984; omega_blackwell_submit.c:128,340,571; omega_world_gates.c:673-753 | +| threads | pthread_create 22 (src: rx_world.c:1404, rx_resident_gpu.c ×3, rx_generation.c ×1) | fork 23 (src: rx_omega.c sandbox, rx_caproot.c root process, rx_jspace/rx_semantic "fork" = branch fork, not process) | +| atomics | stdatomic 151 hits/15 files; __atomic/__sync 37/9 | see §3a | +| packed / static_assert / offsetof | packed attr 1 (rx_resident_gpu.c:34); _Static_assert 17; offsetof 17 | omega_shared_world_abi.h:286-296; rx_coherent.c:30-35; rx_native_bind.c:10-15 | +| structs hashed by raw bytes | ≥6 in src | omega_accelerator.c:83; omega_program.c:276; omega_vector.c:23; omega_synthesis.c:98; rx_semcomm.c:616-631; omega_accelerator_world.c:530-563 (memcpy of native ints) | +| abort / assert / setjmp | 0 / 0 / 0 | failure is return codes everywhere | +| exit / _exit | 10 (src only rx_caproot.c ×8 in root child) | rx_caproot.c:338-339 | +| errno | 37 / 13 | rx_caproot.c:81 EINTR loop; rx_generation.c | +| time sources | 57 / 41 | rx_world.c:33-43; rx_caproot.c:52-58 CLOCK_BOOTTIME; omega_evidence.c:41-51 wall clock | +| qsort | 34 / 17 | comparators are total orders with id tiebreak rx_capq.c:290-299 | +| dlopen/dlsym | 6 (tests) | r15_measure.c:195-203 NVML | +| refcounts / parent links | refcount 4; parent 326 / 48 | JsReal.refs + parent_realization rx_jspace.h:96-99; RxCapEntry.parent_id chain rx_caproot.h:129; crumb parents[] (ids) rx_world.h:340 | + +--- + +## 3. Machine-semantics evidence (OSC-0B items 1-7) + +### 3a. Concurrency, atomics, publication (items 1, 2) + +- [FACT] Threads: RxWorld owns up to 16 worker pthreads created in rx_world_init (rx_world.c:1402-1405); every RxWorld mutation is under one `pthread_mutex_t mu` (rx_world.h:487; "Simple reference: one mutex" rx_semantic.c header). RxGpuSeat adds a launch thread and a lease thread (rx_resident_gpu.c:985, 950-964, 1071). rx_generation.c has one worker thread. rx_jspace is single-threaded by contract (rx_jspace.c:4). +- [FACT] Four distinct memory-model idioms coexist: + 1. C11 acquire/release + release fences on SPSC ring head/tail (rx_coherent.c:75-85, 238-244, 721-733, 444-468, 885-897), done by casting the ABI's `volatile uint64_t tail/head` (omega_shared_world_abi.h ring struct) to `_Atomic uint64_t*` — type punning, formally UB. + 2. GCC `__atomic_load_n/__atomic_store_n` ACQUIRE/RELEASE on the same fields (rx_world.c:1808-1811 ring_discard). + 3. `volatile` plain loads/stores + `__asm__ volatile("dsb sy")` for CPU<->GPU heartbeat, lease, hold, completion marker and semaphores (rx_resident_gpu.c:707-712, 860-864, 897-928, 945, 984; omega_blackwell_submit.c:125-128; omega_accelerator_world.c:135, 899, 1119; omega_world_gates.c:673-753). + 4. Seqlock across processes over a MAP_SHARED memfd: `_Atomic uint64_t seq` odd while writing, entries copied with plain memcpy between acquire load and acquire fence (rx_caproot.c:96-104, 569-618; rx_caproot.h:136-143). Entry reads are formally racy (seqlock pattern); readers spin unbounded while `seq` odd unless the writer is dead (rx_caproot.c:574-576). + Relaxed-only counters: rx_generation.c:151-203 (`__atomic_add_fetch RELAXED`), omega_accelerator_world.c:17-27 (handle epoch CAS relaxed), rx_caproot.c:50-73 (boot generation CAS acq_rel). +- [FACT] Cross-thread flags that are `volatile`, not atomic: RxGpuSeat.abort, marker_ok, sem_ok, lease_run (rx_resident_gpu.c:53-63). Data races by the C11 model; work in practice on AArch64 GCC. +- [FACT] Unsynchronized lazy global init: g_crc/g_crc_ready (rx_coherent.c:88-106) can be initialised concurrently by two workers (benign-in-practice race). `emit_overflow` static (rx_resident_gpu.c:137) makes seat program build non-reentrant. `static Bench g_bench` "verification is not re-entrant" (rx_fusion.c:675). `__thread RankCtx t_sort` for qsort context (rx_capq.c:302). +- [FACT] CPU->GPU publication today: CPU writes 128-byte descriptor into ring slot by memcpy, seals with CRC32C over bytes [0,0x3C)+payload (rx_coherent.c:109-122), release fence, release-store tail (rx_coherent.c:721-733). The ring memory is a GPU-uncached NvrmMem mapping when the seat is live (rx_resident_gpu.c:1036-1043). GPU->CPU: seat writes g2c ring; CPU acquire-loads tail, memcpys slot, release-stores head, then verifies magic/epoch/checksum (torn-write detection) (rx_coherent.c:709-719, 885-897). Liveness: heartbeat/lease words written with volatile+dsb (rx_resident_gpu.c:897-928). Non-resident dispatch: pushbuffer enqueue + nvrm_ring doorbell (omega_accelerator_world.c:666, 688-694), completion by polling a host-visible marker/semaphore (m16_native_wait_marker, omega_blackwell_submit.c:203; payload serial compare omega_accelerator_world.c:38-40). +- [SETTLED] The ring discipline (SPSC, free-running 64-bit counters, release-published, checksum as defence-in-depth, fail-closed reader) is frozen in omega_shared_world_abi.h:21-52, 159-167 (M20 Stage 1 design laws; ring head/tail at :163,:166) and r12-resident-seat.md. +- [FACT] Generation change while another engine holds a view: + - Object generation moves while chip holds a claim -> invalidated and recorded; stale claim refused by chip fault; seat loss moves `seat_generation`, not object generations; old-seat results refused by `producer_generation != seat_generation` (rx_world.c:1673-1680, 1814-1864; rx_resident_gpu.c:453). [SETTLED] r12-resident-seat.md:34-70. + - Accelerator world: revoke marks entry inactive and bumps generation immediately; memory freed only after no in-flight submission binds it (`retiring`), omega_accelerator_world.c:234-255, 84-93. Output buffer is mprotect(PROT_READ) on the CPU while the GPU owns it (omega_accelerator_world.c:659-665) and restored at completion/abandon (:500, 756, 810). + - [FACT] Raw pointers already handed out by omega_world_resolve_buffer (:257-290) and scratch slices (:424-446) are not tracked: revoke of a not-in-flight buffer frees memory immediately (:254) and `omega_world_scratch_reset` (:448-451) rewinds the bump pointer with no in-flight or outstanding-slice check. A caller's cached `cpu`/`gpu_va` then dangles or aliases. + - [OPEN] rx_world_relocate_physical (rx_coherent.c:661-700) moves an object's window without generation change and without checking for an outstanding resident claim on that object; r12 table covers "detach while chip holds claim" but not relocate. Whether the seat re-reads the table per claim is not verified here. + - [FACT] rx_world_bind_coherent (rx_coherent.c:921-931) memcpys the whole image into new memory and frees the old one under `mu`; rx_resident_take_result (:885-897) reads `w->coherent` without `mu`, but its only src caller holds `mu` (rx_world.c:1669-1673). Lock-free readers of `w->coherent` exist in the seat (hb_word_at rx_resident_gpu.c:880-882, lease thread :897-907); ordering of lease_stop before seat_return_image (:1085-1090) is what keeps them safe. + +### 3b. Layout (item 3: runtime vs wire layout) + +- [FACT] Wire/hardware-format structs with size/offset asserts: OmegaSharedWorldDesc 128 B, object record 32 B, fault mailbox 64 B, checksum at 0x3C, payload at 0x40 (omega_shared_world_abi.h:286-296; rx_coherent.c:30-35). Cache-line padding is by explicit `_pad` arrays, not `aligned` attributes (0 uses of aligned/_Alignas). +- [FACT] One `__attribute__((packed))` struct: SeatArgs (rx_resident_gpu.c:34-43), uploaded word-by-word into a GPU constant bank (:801) — a CPU/GPU-kernel ABI with no static_assert on size/offsets. +- [FACT] Cross-repo native layout coupling: AienosCapEntry must equal RxCapEntry in size and selected offsets (rx_native_bind.c:10-15). RxCapEntry has implicit padding (u32 before u64 at cap_id/generation, parent_id/parent_generation, minted_by_id/minted_by_generation — rx_caproot.h:120-133) and is shared across processes via memfd (rx_caproot.c:341, 456). +- [FACT] Digests depending on native layout or endianness: + - Whole-struct hash: omega_accelerator.c:83 (OmegaEffectIntent), omega_program.c:276 (SynthesisTask minus id; any padding bytes are hashed), omega_vector.c:23, omega_synthesis.c:98 (other worker's area for SemanticId; flagged only). + - Native-endian integer arrays hashed: rx_semcomm.c:616-631; rolling world digest memcpy of u32/u64 (omega_accelerator_world.c:530-563); `sha256_hash(semantic_words)` (:676-678). + - Contrast (good): explicit little-endian field encoders for RxObject digest and crumb digest (rx_world.c:44-66, 127-168), generation store (rx_generation.c:122-141, 251-290), capq (rx_capq.c:202-205). +- [SETTLED] The shared world is "Zero Serialization": native LE fixed-width, distinct from big-endian canonical semantic encoding (omega_shared_world_abi.h:30-38 ("Zero Serialization" :32); canonical-encoding.md). +- [FACT] Width mismatch: RxCapRef.generation is u64 but the frozen descriptor carries u32; the high halves are smuggled into payload bytes 40/44 (rx_world.h:146-152), and crumb_hash hashes only the low 32 bits of cap generations (`put32(&c, k->caps[i].generation)`, rx_world.c:147). + +### 3c. Failure handling (item 4) + +- [FACT] No abort, assert or setjmp anywhere (0 hits). All failures are negative return codes: RX_ERR_* (rx_world.h:107-121), RX_CAP_ERR_* (rx_caproot.h:96-114), OMEGA_WORLD_ERR_* (omega_accelerator_world.h), JS_ERR_NOMEM, plain -1. +- OOM: [FACT] mapped to RX_ERR_FULL (rx_world.c:1375-1389, 1574-1575), OMEGA_WORLD_ERR_NO_MEM, JS_ERR_NOMEM (rx_jspace.c:298, 306, 374), or -1/NULL. Some allocations unchecked for arithmetic overflow: grow() doubles `c` with no overflow check and `c * elem` unchecked (rx_projection.c:143-152, rx_cortex.c:58). +- Bounds: [FACT] fail-closed checks return *_ERR_BOUNDS (omega_accelerator_world.c:283-285; rx_coherent.c:548-558). Silent truncation exists: add_parent drops parents past RX_MAX_PARENTS (rx_world.c:171-176); rolling digest caps id/gen pairs at 64 bytes while hashing the full count (omega_accelerator_world.c:550-553); pushbuffer `uint32_t pb[1024]` stack arrays filled by `pb[n++]` with no bound check (omega_blackwell_submit.c:131, 343, 573; omega_accelerator_world.c:906, 1126) or a check only after writing (rx_resident_gpu.c:786, 839). +- Stale handle: [FACT] *_ERR_STALE_GEN / STALE_EPOCH everywhere; generation saturation retires the slot rather than wrapping (omega_accelerator_world.c:197-199, 248). +- Vanished device: [FACT] marker timeout -> m16_native_close and -1 (omega_blackwell_submit.c:203); accelerator channel fault -> destroy/rebuild channel, bump channel_generation, abandon uncommitted in-flight, restore output protection (omega_accelerator_world.c:461-511); sticky `faulted` flag refuses further work (:620). Seat loss -> rx_resident_seat_lost (rx_world.c:1814-1864). [SETTLED] r12-resident-seat.md:52-70. +- Failed construction: [FACT] partial cleanup ladders (rx_resident_gpu.c:1020-1085). rx_world_init ignores pthread_create / pthread_mutex_init return values (rx_world.c:1397-1405); a failed create leaves an uninitialised pthread_t that rx_world_destroy joins (:1435). +- Cleanup failure: [FACT] nvrm_free failure sets world->faulted and keeps the slot retiring (omega_accelerator_world.c:59-81); `(void)release_*` ignores the result in bulk release (:87-92); omega_matvec.c:338 ignores mprotect failure then executes. +- Invariant violation: [FACT] reported as return code plus crumb/fault mailbox (raise_fault rx_coherent.c:170-178; RX_CRUMB_FAILED); crumb log full refuses the publication (rx_world.c:179-183, "no action without evidence"). +- [PROPOSED] see §8. + +### 3d. Cycles and weak references (item 5) + +- [FACT] Refcounted DAG with raw back-links: JsReal.refs/holders, parent_realization pointer, cascading real_unref (rx_jspace.h:96-111; rx_jspace.c:158-168). `uint32_t refs` has no overflow check. Intrusive index chain `index_next` (rx_jspace.c:140-155). Manual weak ref: `s->cache_r` cleared when its target is freed (rx_jspace.c:161). +- [FACT] Capability parent chain by id, depth-bounded by RX_CAP_MAX_DEPTH (rx_caproot.c:106-110, 599-606) — no pointers. +- [FACT] Crumb causal graph by dense id (`parents[]`, `wake_cause`), parents always precede children (rx_world.c:160-165) — acyclic by construction. +- [FACT] Back-pointers without lifetime tie: RxGpuSeat.world (rx_resident_gpu.c:59) — seat_return_image writes into the world (:70-81), so rx_world_destroy before rx_gpu_seat_finish is a use-after-free; nothing enforces order. rx_living.h:124-137, rx_aegis.h:127, rx_aien.h:132, rx_omega.h:138, rx_capq.h:245 all hold `RxWorld *`. Cortex `links[CX_LINKS]` are ids (rx_cortex.h:65). +- [FACT] No ownership cycles found among heap objects other than JsReal (which is a DAG). + +### 3e. Relocation, compaction, pinning (item 7) + +- [FACT] Pinned by design: crumb log records "never move, so a crumb pointer stays valid for the life of the world" (rx_world.c:15-19), and rx_world_crumb returns a raw pointer without the lock (:231-233). +- [FACT] Pinned implicitly: RxWorld embeds pthread mutex/conds and worker threads hold `w` (rx_world.h:487-489, 533) — the struct must never be copied or moved after init. RxGpuSeat likewise. +- [FACT] Relocatable by offset: the shared world stores region-relative offsets, not VAs (omega_shared_world_abi.h:207-208, 272); Cortex and projection store arena offsets (rx_cortex.h:67, rx_projection.c:176). +- [FACT] Relocation that invalidates interior pointers: grow() realloc of arenas while projection items hold `it->w = p->arena + e->off` (rx_projection.c:526); JsBranch.units realloc (rx_jspace.c:443); coherent image moved by rx_world_bind_coherent (rx_coherent.c:921-931) — any cached `hb_watch` (rx_resident_gpu.c:861) or ring pointer becomes stale. +- [FACT] Window move: rx_world_relocate_physical copies 64 B to a spare window, keeping id/generation/version/digest (rx_coherent.c:661-700). +- [FACT] GPU-shared memory is pinned by PHYSICS allocation (NvrmMem cpu+va pairs); JIT pages are mmap'd, mprotect RX, never moved (rx_omega.c:137-152). + +### 3f. Determinism (and item 6: live handle vs persistent identity) + +- [FACT] Deliberately excluded from identity: timing and worker placement in crumb digests (rx_world.c:166-167); host addresses and time in the rolling world trace (omega_accelerator_world.c comment before :572). +- [FACT] Nondeterministic inputs: evidence run id from wall clock + git sha (omega_evidence.c:41-51); capability slot generations seeded from CLOCK_BOOTTIME<<8 (rx_caproot.c:52-73, 351, 430); getrandom tokens (rx_caproot.c:77-85). Because crumb_hash includes cap generations (rx_world.c:145-149), host-reference crumb digests differ between runs whenever caps are stamped. qsort comparators are total orders (rx_capq.c:290-299) so ordering is deterministic; no pointer values printed (%p: 0 hits). +- [FACT] Item 6 — live handles serialized as identity: runtime slot handles (object slot index + generation, cap_id + cap generation) are written into durable/hashed records: generation-store object rows `id, generation, digest` (rx_generation.c:560-565); receipt carries cap_id (rx_generation.c:515-531); crumb digests hash slot ids/generations (rx_world.c:139-156); world digest hashes (id, generation, content digest) (rx_world.h:627). No CPU address or GPU VA was found entering a durable digest or wire record; addresses appear only in live launch args (SeatArgs.region, rx_resident_gpu.c:1065), pushbuffer words, and registry entries. +- [FACT] Build-path leakage: Makefile:14 bakes `-DOMEGA_PHYSICS_DIR="$(PHYSICS_DIR)"` into the binary (compiler determinism otherwise owned by the other worker). +- [OPEN] Whether slot-index+generation is meant to be durable identity or must be replaced by SemanticId/content digest in persisted artifacts. + +--- + +## 4. Per-site hazard table (top 40) + +Hazard, ownership and lifetime columns are [FACT]; the "proposed replacement" column is [PROPOSED]. + +Format: repository/path | function/type | hazard | current ownership model | current lifetime model | proposed Omega replacement | migration difficulty | required compatibility boundary + +1. omega/src/omega_accelerator_world.c:257-290 | omega_world_resolve_buffer | returns raw `void*` + GPU VA with no borrow tracking; revoke (:254) frees immediately if not in flight | registry owns NvrmMem; caller gets untracked alias | until revoke/destroy; caller cannot know | `&T`/`&mut T` borrow scoped to registry + `device` view; revoke requires no live borrows | high | PHYSICS NvrmMem ABI (C ABI adapter) +2. omega/src/omega_accelerator_world.c:424-451 | omega_world_scratch_acquire / _reset | bump arena reset with no check of outstanding slices or in-flight GPU use | world owns arena | "until reset", unchecked | `arena/region` with region token; reset consumes token only when no in-flight fence | med | GPU VA handed to pushbuffer +3. omega/src/runtime/rx_coherent.c:75-85 | load_acquire_u64 etc. | casts `volatile uint64_t*` to `_Atomic uint64_t*` | ring memory owned by world or borrowed GPU mapping | lifetime of image | `device` atomic cell type in the ABI with declared ordering | med | frozen ABI header layout (omega_shared_world_abi.h) +4. omega/src/runtime/rx_resident_gpu.c:53-63 | RxGpuSeat.abort/marker_ok/sem_ok/lease_run | volatile cross-thread flags (data race) | seat struct | seat lifetime | atomic with acquire/release | low | none +5. omega/src/runtime/rx_resident_gpu.c:707-712, 897-928 | wait_marker_or_abort, lease_main | volatile + `dsb sy` CPU<->GPU publication, no formal model | image owned by PHYSICS mapping | seat lifetime | `unsafe physical block` with named publication primitive (e.g. publish_release/observe_acquire on device memory) | med | GPU SASS program side (membar semantics) +6. omega/src/runtime/rx_resident_gpu.c:59, 70-81 | RxGpuSeat.world | raw back-pointer; seat_return_image writes into world; no ordering with rx_world_destroy | seat borrows world | assumed world outlives seat | `&mut RxWorld` borrow held by seat / seat owned by world (`own` field) | med | none +7. omega/src/runtime/rx_coherent.c:921-931 | rx_world_bind_coherent | relocates image by memcpy + free; cached pointers (hb_watch :861) and lock-free readers dangle | world owns or borrows (`coherent_borrowed`) | until next bind/free | `pin` + ownership enum {Owned(own), Borrowed(device)}; rebind requires no outstanding views | high | PHYSICS NvrmMem, seat launch args +8. omega/src/runtime/rx_coherent.c:248-252 | rx_coherent_free | bool flag decides whether to free | flag-based conditional ownership | world lifetime | `own` vs `&T` in the type, not a flag | low | none +9. omega/src/runtime/rx_coherent.c:661-700 | rx_world_relocate_physical | window moved without generation bump or resident-claim check | world | object lifetime | window as `handle` with its own generation; move invalidates outstanding claims | med | frozen 32-byte object record +10. omega/src/runtime/rx_resident_gpu.c:34-43 | SeatArgs (packed) | hardware-format struct with no size/offset asserts; carries live GPU VA | stack, copied to cbank | one launch | `device` ABI struct with compiler-checked layout; VA as `device ptr` type, never serializable | low | SASS kernel argument layout +11. omega/src/omega_blackwell_submit.c:131,343,573; omega_accelerator_world.c:906,1126 | execute_* / dispatch_* | `uint32_t pb[1024]` stack array filled via `pb[n++]` without bound check | stack | call | `slice` builder with checked push | low | pushbuffer word format (PHYSICS) +12. omega/src/runtime/rx_resident_gpu.c:786-839 | launch_main | pushbuffer bound checked only after writes (`if (n > 1024)`) | stack | call | checked builder | low | same +13. omega/src/runtime/rx_caproot.c:569-618 | rx_caproot_inspect/validate | seqlock with plain memcpy of entries; unbounded spin while writer alive | root process owns table; readers map RO memfd | root process lifetime | `unsafe physical block` seqlock primitive with bounded retry; entries as `device`-like shared view | med | AIENOS cap entry layout (rx_native_bind.c) +14. omega/src/runtime/rx_caproot.h:120-133 | RxCapEntry | implicit padding in a cross-process, cross-repo layout | memfd | root lifetime | explicit fixed layout with reserved fields; layout asserted on both sides | low | AIENOS AienosCapEntry (C ABI adapter) +15. omega/src/runtime/rx_world.c:139-156 | crumb_hash | hashes slot ids/generations; cap generation truncated to 32 bits (:147) | world | world lifetime | hash `SemanticId` / full 64-bit generation via canonical encoder | low | existing crumb digests in evidence +16. omega/src/runtime/rx_world.h:146-152 | claim payload bytes 40/44 | u64 cap generation split across frozen u32 field + payload | ring | per message | ABI v2 with u64 generation field | med | frozen OMEGA_SHARED_WORLD_V1 +17. omega/src/runtime/rx_world.c:15-26, 231-233 | crumb_log_map / rx_world_crumb | raw pointer into MAP_NORESERVE log returned unlocked; relies on pinning | world | world lifetime | `handle` (dense id) + `&T` scoped borrow; log as `pin` | low | crumb ids in evidence +18. omega/src/runtime/rx_world.c:1397-1405 | rx_world_init | pthread_create / mutex_init results ignored; destroy joins garbage | world | world lifetime | constructor returns Result; partially built world not observable | low | none +19. omega/src/runtime/rx_world.h:486-567 | RxWorld | large value type (estimated ~1 MB from field counts; not built) with embedded mutex; stack-allocated in tests (e.g. tests/runtime/rx_r13_living.c:30) | caller | caller scope | `pin>` heap-only | low | public C API (rx_world_init takes RxWorld*) +20. omega/src/runtime/rx_world.c:525-545 | defer_wake | memmove + realloc ring; index arithmetic overflow guarded only by `next < cap` | world | world | `Vec`-like `own<[T]>` with checked growth | low | none +21. omega/src/runtime/rx_jspace.c:158-168 | real_unref | manual refcount cascade, u32 refs unchecked, raw parent pointers | JsSpace + refcount holders | until refs==0 | `arena/region` for JsReal with `handle` + counted edges, or `own` tree + `weak` cache | med | none (single-threaded) +22. omega/src/runtime/rx_jspace.h:179 / rx_jspace.c:161 | JsSpace.cache_r | hand-made weak ref cleared on free | space | ad hoc | `weak` | low | none +23. omega/src/runtime/rx_jspace.c:140-155 | index_insert/remove | intrusive singly-linked chain in owned objects | space | object lifetime | index keyed `SemanticId` -> `handle` map | low | none +24. omega/src/runtime/rx_projection.c:143-179, 526 | grow / pj items | realloc arena while items hold `arena + off` pointers; `c*=2` / `c*elem` unchecked | projection owns arena | until grow | `arena/region` with offset handles; `slice` borrows invalidated by type system | low | none +25. omega/src/runtime/rx_cortex.c:58, 113 | grow / cx_payload | same pattern (pointer into growable arena) | store | until grow | same | low | none +26. omega/src/runtime/rx_omega.c:137-152, 177, 456 | store_put / sandbox_run | data->function pointer punning on JIT page; page lifetime = faculty | faculty owns pages | faculty lifetime | `unsafe physical block` exec-page type (W^X enforced), callable only via typed thunk | med | AArch64 ABI of generated code +27. omega/src/omega_exec.c:8-40 | omega_exec_native_f3 | executes unverified generated code in-process (no fork sandbox) | function-local page | call | same as 26, sandbox or verifier gate | med | AArch64 calling convention +28. omega/src/omega_matvec.c:331-338 | benchmark path | mprotect result ignored; memcpy of code_len into a fixed 4096 page without len check | local | call | checked `slice` copy + Result | low | same +29. omega/src/omega_accelerator_world.c:234-255 | omega_world_revoke_buffer | generation bump + deferred free via `retiring` flag | registry | revoke or drain | `handle` + fence-tracked `device` deferred drop | med | PHYSICS nvrm_free +30. omega/src/omega_accelerator_world.c:612-685 | omega_world_submit | input digest computed after enqueue from raw cpu_addr; inputs not write-protected | registry | in-flight | `&T` shared borrow of inputs held until fence | med | pushbuffer +31. omega/src/omega_accelerator_world.c:461-511 | omega_world_recover_channel_fault | device-loss path mutates many slots; `(void)release_*` drops errors | world | world | typed fault state machine; errors aggregated | med | PHYSICS channel API +32. omega/src/omega_accelerator_world.h:57-77 | OmegaBufferEntry/CodeEntry | cpu_addr + gpu_va + NvrmMem duplicated address state | registry | slot | `device` pairing CPU view and GPU VA in one opaque value | med | NvrmMem +33. omega/src/omega_accelerator_world.c:398-421 | omega_world_validate_handle | permissions carried in caller-held handle and re-checked vs entry (good), but handle is plain struct (forgeable fields) | caller | value | `handle` opaque + rights as type/capability | low | handle wire in gates/evidence +34. omega/src/omega_accelerator.c:83; omega_program.c:276; omega_vector.c:23 | digest of whole native structs | padding/endianness enter digests | value | value | canonical encoder (other worker) | low | existing digests/receipts +35. omega/src/runtime/rx_semcomm.c:616-631 | rx_sem_view_digest | native-endian u64 arrays hashed | value | value | explicit LE encoder | low | view digests in evidence +36. omega/src/runtime/rx_coherent.c:88-106 | g_crc lazy init | racy global init | global | process | const table computed at compile time | low | none +37. omega/src/runtime/rx_resident_gpu.c:137 | emit_overflow | global error flag in codegen | global | process | Result from builder | low | none +38. omega/src/runtime/rx_fusion.c:675, 899 | g_bench, g_blob | non-reentrant globals | global | process | per-call `own` context | low | none +39. omega/src/runtime/rx_generation.c:560-565, 515-531 | generation blobs/receipt | persists runtime slot id+generation and cap_id as durable identity | store (disk) | across restarts | `SemanticId` / durable object id; slot handles stay runtime-only | high | on-disk R9 format v2 (ROOT_AUTH_GEN_HI etc.) +40. omega/src/visor/visor_evidence.c:29-32, 445-447; tools/omega.c:42-53 | JSON parser + REPL view buffers | large static mutable buffers, non-reentrant | global | process | `own` session context | low | Visor console API + +--- + +## 5. Existing good patterns worth keeping + +- [FACT] Pointer-free, offset-based, generation+epoch+sequence protected shared world with hostile-input reader: omega_shared_world_abi.h:21-52; notice_intact rx_coherent.c:709-719; check_locked :287-398; fault mailbox codes. +- [FACT] Generation checks with slot retirement on saturation (no wrap): omega_accelerator_world.c:197-199, 248; handle epoch never reused (:17-27). +- [FACT] Deferred free while GPU holds a reference (`retiring`): omega_accelerator_world.c:84-93, 250-253. +- [FACT] CPU write-protection of a buffer while the GPU owns it (mprotect PROT_READ): omega_accelerator_world.c:659-665 — a hardware-enforced borrow. +- [FACT] Seat generation / producer_generation fencing of a lost GPU engine: rx_world.c:1814-1864, 1673-1680. +- [FACT] Snapshots by value to reaction bodies (RxCtx carries values, not pointers): rx_world.h:185-222; rx_world_read copies out (rx_world.h:614). +- [FACT] Explicit little-endian field encoders for digests and disk formats: rx_world.c:44-66, 127-168; rx_generation.c:122-141, 251-290; rx_capq.c:202. +- [FACT] Crumb log bounded; full log refuses action (rx_world.c:179-183). +- [FACT] Authority split: runtime handle has no mint power (rx_caproot.h:145-151); separate non-dumpable root process (rx_caproot.c:1-9); constant-time token compare (:88-92). +- [FACT] W^X for JIT pages + fork sandbox with canaries for generated code (rx_omega.c:137-152, 400-460). +- [FACT] Visor views never hold pointers into the runtime (visor_world.h:60, 73-74; visor_world_rx.c header). +- [FACT] qsort comparators are total orders (rx_capq.c:290-299). +- [FACT] Hostile attack tests on mappings (writable remap of the RO cap table, tests/runtime/rx_heartbeat_test.c:987, 1292). + +--- + +## 6. Candidate first subsystems to migrate + +All three [PROPOSED]. + +1. src/crumbline (cl_common, cl_crumb, cl_program, cl_search; 1,216 lines) + tools/crumbline_learner.c. Linked without physics or gates (Makefile:31-40); CPU-only; ptr+len buffers and bounded search; deterministic by design. Tests exist (test-crumbline). Exercises slice, own, Result. +2. src/runtime/rx_cortex + rx_projection (≈1,300 lines incl. headers). Pure CPU, append-only store with id links and offset arenas; the only real hazard is realloc-invalidated interior pointers (§4 rows 24-25), exactly what arena/region + offset handles fix. Has gate tests (rx_state_projection). +3. src/visor/visor_parse_command.c/.h (260 lines, "no semantics", no authority). Smallest self-contained parser; good first C ABI adapter test against tools/omega.c. +Avoid first: rx_world/rx_coherent/rx_resident_gpu/accelerator_world (hardware coupled), sha256/canonical (other worker). + +--- + +## 7. Per-object lifetime / authority / placement (item 12, as the code does it today) + +All rows [FACT]. + +| Object kind | Who keeps it alive | Who may touch it | Where it physically lives | +|---|---|---|---| +| RxWorld | caller-allocated storage (stack/static/heap), rx_world_init (rx_world.c:1320, 1329, 1338) / rx_world_destroy (:1427-1445) | any thread holding `mu`; worker threads hold raw `w` | host heap/stack; must not move (embedded mutex) | +| RxObject (slot) | slot in RxWorld.objects[256]; retire bumps generation (rx_world.h:596) | writes only via reaction publication under `mu` after capability validation (auth_validate or caproot) | host struct + optional 64-B window in coherent image | +| RxReaction | slot in reactions[1024]; never removed | scheduler under `mu`; body gets value snapshot | host struct | +| RxCrumb | append-only log, world lifetime | appended under `mu`; readers get raw pointer | MAP_NORESERVE anonymous mapping, pinned | +| Coherent image (OMEGA_SHARED_WORLD_V1) | RxWorld if owned; PHYSICS mapping if `coherent_borrowed` (rx_resident_gpu.c:1036-1043) | CPU under `mu` for rings/table; seat GPU program; lease thread lock-free | posix_memalign host heap or GPU-uncached NvrmMem; moved by bind_coherent | +| RxGpuSeat | calloc in rx_gpu_seat_begin, freed in rx_gpu_seat_finish | owner thread + launch thread + lease thread | host heap; owns M16 context/channel and launch memory | +| RxCapTable / RxCapRoot | separate root process owns writable memfd | root writes under seqlock; runtime maps read-only | sealed memfd MAP_SHARED | +| OmegaBufferEntry / OmegaCodeEntry | registry slot + NvrmMem, freed on revoke or after drain | holder of OmegaHandle with matching epoch/gen/perms; GPU via VA while in flight | PHYSICS-allocated GPU-visible memory, CPU-mapped | +| Scratch arena slices | world; reset rewinds | anyone with the returned pointers | 2 MiB NvrmMem | +| JsReal / JsBranch | refcounts (branches, child recipes, index) | single thread | host heap; optional spill file / compressed buffer | +| CxStore objects | store (grow-realloc) | store owner | host heap arena | +| RxOmegaRealization exec pages | faculty store, faculty lifetime | faculty under its mutex; forked sandbox child executes | mmap RX pages | +| RxGenStore generation | on-disk files; active pointer file + rename flip | promotion only with native promotion right (r9 doc) | filesystem | + +--- + +## 8. Contradictions (code vs doc) + +1. omega_shared_world_abi.h:14-16 (text at :15) says the header "is placed in the PHYSICS repository so both compile against a single definition"; it lives at omega src/runtime/omega_shared_world_abi.h while Makefile:9 also puts `$(PHYSICS_DIR)` on the include path. Two copies can drift. [FACT] +2. Frozen ABI object table is OMEGA_SW_MAX_OBJECTS = 64 (omega_shared_world_abi.h:254; table offset field :231) but rx_coherent.c:23-28, 215-217 writes `count = RX_MAX_OBJECTS` (256) into a 256-entry RxProjectedTable at the frozen `off_object_table`. Acknowledged in rx_coherent.c:10-12. A consumer honouring the frozen ABI reads a different table size. [FACT] +3. omega_shared_world_abi.h describes head/tail as release-published atomics but declares them `volatile uint64_t` (omega_shared_world_abi.h:163, 166); code casts to `_Atomic` (rx_coherent.c:75-85) and elsewhere uses GCC builtins (rx_world.c:1810). [FACT] +4. spec/semantic-object.md:52 "fully relocatable ... without pointer patching or swizzling" vs pinned crumb log with raw pointers (rx_world.c:15-19) and JsReal pointer graph (rx_jspace.h:96-111). (Runtime realization vs semantic object; still a stated-property gap.) [FACT] +5. Frozen descriptor generations are u32 (omega_shared_world_abi.h:130 producer_generation, :132 object_generation) while capability generations are u64 (rx_caproot.h:118); workaround in payload bytes (rx_world.h:146-152) and 32-bit truncation in crumb hash (rx_world.c:147). Git log at 8a7d95e records "32-bit EffectPayload finding". [FACT] +6. ABI design law 1 (omega_shared_world_abi.h:21-28) "no field ever holds a ... GPU virtual address" is kept inside the shared world, but the packed SeatArgs launch record (rx_resident_gpu.c:34-43, 1065) carries the region's GPU VA; this is launch args, not the shared world, so not a violation — noted so the freeze wording scopes the law precisely. [FACT] + +--- + +## 9. Recommended OSC-0B decisions + +1. [PROPOSED] One memory model: Omega Systems Core adopts the C11/C++ model (relaxed/acquire/release/seq_cst) for CPU threads; `volatile` is banned for synchronization. Shared CPU/GPU cells are a distinct type (`device>`) whose ops lower to acquire/release + the required DSB/membar pair; `dsb sy` appears only inside one unsafe physical block primitive. Replaces idioms 1-3 in §3a. +2. [PROPOSED] Publication contract freeze: SPSC ring with free-running u64 counters, producer release-stores tail after full slot write, consumer acquire-loads tail, then validates magic/epoch/generation/sequence/checksum; checksum stays defence-in-depth. Heartbeat/lease/marker words get the same named primitive. [SETTLED basis: omega_shared_world_abi.h laws 3-5; r12-resident-seat.md] +3. [PROPOSED] Seqlock is a library primitive with bounded retry and a dead-writer check; entries read through it are values, not references. +4. [PROPOSED] Two layouts, never mixed: (a) runtime layout = compiler's choice, unobservable; (b) wire/hardware layout = explicit `repr(wire)` with fixed width, LE, explicit reserved fields, compiler-checked size/offset. No digest may hash a runtime-layout struct; all digests go through the canonical encoder. Fixes §3b whole-struct hashes and RxCapEntry padding. +5. [PROPOSED] Failure semantics: Result-typed errors everywhere (matches today's return codes); OOM is a recoverable error in runtime paths; bounds violation in safe code is a trap (not silent truncation); stale generation/epoch is a typed error; device loss is a typed fault that moves an engine generation (seat/channel) and abandons uncommitted work; failed construction yields no object; cleanup failure marks the owner faulted (sticky) and is reported, never ignored; invariant violation = fail-closed error + evidence record, never continue. +6. [PROPOSED] Cycles: no owning cycles; parent/back links are `handle` or `weak`; refcounts only inside an arena/region with checked counters. +7. [PROPOSED] Identity: live handles (slot index+generation, cap slot+generation, VA, CPU address) are runtime-only and not serializable by type; durable records and digests use SemanticId or an explicit durable id. [OPEN] migration of the R9 on-disk format and crumb digests that already embed slot handles. +8. [PROPOSED] Relocation: objects are movable by default; `pin` is required for anything shared with another engine or holding OS sync primitives; moving a pinned region (bind_coherent) requires proof of no outstanding views and bumps a region generation. Arena growth invalidates borrows by type. +9. [PROPOSED] Generations are u64 end to end; ABI v2 widens descriptor generation fields (ends the payload split). +10. [PROPOSED] Every raw-pointer grant to the GPU (resolve_buffer, scratch_acquire) becomes a fence-scoped borrow: the region cannot be revoked/reset until the fence recorded for its last submission has passed. +11. [OPEN] Whether relocate_physical must refuse or invalidate while a resident claim is outstanding (§3a). +12. [OPEN] Whether the frozen ABI's 64-object table or the runtime's 256-slot projection is authoritative (Contradiction 2), and where the single copy of the ABI header lives (Contradiction 1). diff --git a/spec/self-host.md b/spec/self-host.md index b0e742cf4..8f6d9e5b9 100644 --- a/spec/self-host.md +++ b/spec/self-host.md @@ -8,6 +8,8 @@ Target Substrate: Native AArch64 Machine Code Reproducing Compiler from Semantic Lineage: SILICON -> ATLAS (M1) -> PHYSICS (M2/M3) -> OMEGA (M4/M5/M6) -> AIEN ``` +> **Note (2026-09-29, OMEGA-SYSTEMS-CORE-0000):** the M6 implementation is a fixed-output self-copy check, not compilation; it is not evidence of a compiler. + --- ## 1. Executive Summary & Foundational Invariants