interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / docs / AIEN_RUNTIME_ARCHITECTURE.md

225 lines · 15088 bytes Raw Blame History Rendered
1# AIEN Runtime Architecture Specification
2
3## 1. Foundational Thesis
4
5AIEN turns one AI machine into a persistent, branchable computational world where hundreds or thousands of agents can share context, memory, and inference state efficiently instead of behaving like hundreds or thousands of independent API requests.
6
7The runtime eliminates fragmented multi-daemon infrastructure. Agents are not OS processes. Sequences are not OS threads. Core runtime subsystems are not independent background daemons. AIEN runs as a single compiled native host on hardware silicon, managing sequence lifecycles, copy-on-write memory, and hardware-level tensor execution within a unified execution model.
8
9```text
10┌─────────────────────────────────────────────────────────────────────────┐
11│ AIEN RUNTIME │
12│ │
13│ ┌───────────────────────────────────────────────────────────────────┐ │
14│ │ Sequence Runtime (Single-Owner Scheduler Thread) │ │
15│ │ - SequenceArena: contiguous generational SequenceRecord slots │ │
16│ │ - Lifecycle: Created -> Prefill -> Decode -> BlockedOnTool -> Done│ │
17│ │ - Sub-microsecond fork, cancel, and watermark preemption │ │
18│ └───────────────────────────────────────────────────────────────────┘ │
19│ │ │
20│ ┌───────────────────────────────┴───────────────────────────────────┐ │
21│ │ Shared-State & Memory Runtime (aien-kv-cache / cortex-rs) │ │
22│ │ - Physical block COW page table (atomic refcounts per block) │ │
23│ │ - Token prefix radix tree (immutable ancestors, divergent leaves) │ │
24│ │ - Content-addressed World State (ObjectId, Version, Capabilities) │ │
25│ │ - In-process Cortex memory catalog and ContextComposer │ │
26│ └───────────────────────────────────────────────────────────────────┘ │
27│ │ │
28│ ┌───────────────────────────────┴───────────────────────────────────┐ │
29│ │ Native Inference Engine (aien-inference-abi / Blackwell GB10) │ │
30│ │ - BlackwellBatchPlan: ragged prefill rows + decode rows in one M │ │
31│ │ - Paged attention reading physical block table directly │ │
32│ │ - In-kernel GPU sampling returning compact token IDs │ │
33│ │ - Single completion fence per step without intermediate sync │ │
34│ └───────────────────────────────────────────────────────────────────┘ │
35│ │ │
36│ ┌───────────────────────────────┴───────────────────────────────────┐ │
37│ │ Autonomous Systems Optimizer (spark-rsi) │ │
38│ │ - Read-only telemetry consumption and workload replay │ │
39│ │ - 11-stage candidate lifecycle in container jails │ │
40│ │ - Cryptographic ledger verification (.rsi/ledger.db) │ │
41│ │ - Strict referee vs contestant separation │ │
42│ └───────────────────────────────────────────────────────────────────┘ │
43└──────────────────────────────────┬──────────────────────────────────────┘
44 │
45 NVIDIA DGX Spark (GB10 / Grace Blackwell)
46 128 GB Unified LPDDR5x Memory Substrate
47```
48
49---
50
51## 2. The Six Frozen Invariants
52
53### Invariant 1: Single Trusted Process Model with Strict Thread Ownership
54
551. Latency-critical state, `SequenceArena`, `Scheduler`, `KvManager`, `ModelRegistry`, `CortexRuntime`, and `CompletionRouter` execute inside a single process address space (`aien-runtime`).
562. `SequenceArena` has exactly one mutable owner: the Scheduler thread. No interior synchronization locks (`Arc<RwLock<SequenceRecord>>`) are permitted inside the hot path.
573. GPU tensor execution is owned by a dedicated GPU submission thread holding the CUDA context and streams.
584. Process boundaries are reserved strictly for untrusted tool execution, sandboxed code execution, third-party extensions, and legacy compatibility adapters. Communication with isolated workers occurs solely over capability-restricted IPC.
595. All internal command and event queues have finite capacity. Admission control rejects excess load before allocating sequence descriptors or physical KV blocks.
60
61### Invariant 2: Immutable World Manifests and Structural Sharing
62
631. A `World` is an immutable, content-addressed snapshot of logical perception, perception history, capabilities, and staged effects.
642. The `WorldManifest` binds persistent root pointers:
65 - `object_root`: root hash of the persistent radix/HAMT object index.
66 - `filesystem_root`: content-addressed snapshot of repository files.
67 - `token_root`: immutable `TokenChainId` lineage.
68 - `memory_root`: Cortex memory catalog reference.
69 - `capability_set`: granted capability identifiers.
70 - `effect_log`: journal of staged external mutations.
71 - `sequence_checkpoint`: optional logical sequence state snapshot.
723. Ephemeral accelerator state (`ExecutionAttachment` / KV tensor memory) sits outside the durable `World`. If GPU state is cleared, it is reconstructed from the immutable `TokenChainId`.
734. Branching duplicates root pointers in logarithmic time. Physical storage uses path-copying persistent trees on append-only NVMe segments.
745. External mutations (git push, network API calls, emails, deployments) are recorded in an `EffectJournal` as `EffectIntent` during speculative execution. Effects are committed only upon explicit branch selection and promotion.
756. Dropped branches are collected via reachability garbage collection, avoiding per-fork atomic reference count storms.
76
77### Invariant 3: Strict GPU Submit/Commit Boundary
78
791. The Rust runtime owns control-plane state and sequence lifecycle. The GPU owns tensor mathematics, activations, and sampling.
802. During an engine step, neither boundary inspects or mutates intermediate state of the other.
813. Zero host-visible synchronization is permitted between transformer layers in the production path. The complete forward pass and sampling execute on a single nonblocking CUDA stream, terminated by one completion event fence (`cudaEventRecord(step_done, stream)`).
824. Engine steps are transactional:
83 - Pre-submission: `kv.reserve(&batch)` allocates speculative physical blocks without advancing sequence logical token cursors.
84 - Post-completion: The fence signals, generational `SequenceId` tags are revalidated, `kv.commit(reservations)` finalizes block ownership, and sequence cursors advance.
85 - Error: `kv.rollback(reservations)` restores previous logical states and frees reserved blocks.
865. The GPU returns a compact `BatchResult` containing only `(SequenceId, Option<u32> token_id, Option<FinishReason>)`. Vocabulary logits buffers remain resident in GPU workspace.
876. A `SubmittedBatch` holds explicit resource leases over model weights, KV blocks, and reusable ring workspaces until the completion fence clears.
88
89### Invariant 4: In-Process Cortex via ContextComposer
90
911. `CortexRuntime` runs in-process inside `aien-runtime`. Localhost HTTP/REST communication is forbidden for agent memory retrieval.
922. Cortex operations return immutable handles (`RecallSet<MemoryId>`), never duplicated text buffers.
933. `ContextComposer` applies a `ContextPolicy` (budgeting, max items, minimum score) to select memory items and build an immutable `ContextRevision`.
944. Cortex recall never directly allocates physical KV blocks. The scheduler detects missing prefill spans (`PrefillSpan`) between the sequence cursor and the new `ContextRevision`, scheduling tensor prefill explicitly.
955. In-flight immutability: A submitted batch references one immutable `ContextRevision` per participating sequence. Discovered memories form a successor `ContextRevision` applied at the next scheduler step.
966. Reconstructibility doctrine: Logical memory objects are authoritative durable truth. Vector embeddings, search indexes, and KV blocks are disposable acceleration structures.
97
98### Invariant 5: RSI as an External Constrained Optimizer
99
1001. The Autonomous Systems Optimizer (`spark-rsi`) resides outside the live `aien-runtime` process.
1012. Invariant: RSI does not directly mutate live runtime state, live scheduler structures, or live executable memory.
1023. Bounded online tuning: Hyperparameters with defined ranges (chunk sizes, batch row limits, memory pressure watermarks) are validated by `runtime.validate_tuning()` and applied exclusively at safe step boundaries.
1034. Structural optimization: Code, kernel, allocator, and scheduler modifications execute through the 11-stage candidate lifecycle:
104 `OBSERVE -> IDENTIFY -> HYPOTHESIZE -> GENERATE -> BUILD (Jail 1) -> ORACLE -> CERTIFY (Jail 2) -> BENCHMARK -> EVALUATE -> SOAK -> CANARY -> PROMOTE`.
1055. Separation of referee and contestant: RSI may propose candidate code, but the benchmark oracle, certification suites, promotion policy, cryptographic ledger (`.rsi/ledger.db`), and TPM roots-of-trust sit in a separate capability domain that RSI cannot modify.
1066. Promotion uses clean process drain and cutover, never in-memory binary patching.
107
108### Invariant 6: Operator Control Plane via Typed Local Protocol
109
1101. Operators interact with `aien-runtime` via the `aien` CLI over a private local UNIX domain socket.
1112. The wire protocol uses strongly typed, versioned envelopes (`ControlEnvelope`, `ControlCommand`). The CLI never accesses runtime databases, KV files, or memory structures directly.
1123. Swarm operations are asynchronous. `LaunchSwarm` returns a `SwarmId` immediately; long-running operations are monitored through non-blocking inspection (`aien swarm inspect`) or filtered event subscriptions (`aien swarm watch`).
1134. All mutating commands carry an idempotent `OperationId` preventing duplicate execution upon network or shell reconnection.
1145. Subscriptions consume events from bounded ring buffers. Telemetry subscribers operate at lower priority than inference and cannot block scheduler steps.
1156. The control plane operates on stable domain entities: `SwarmId`, `WorldId`, `SequenceId`, `ObjectId`, `CapabilityId`.
116
117---
118
119## 3. Subsystem Interface Contracts
120
121### 3.1 Sequence Arena & Scheduler Descriptor
122
123```rust
124#[repr(C, align(64))]
125pub struct SequenceRecord {
126 pub id: SequenceId, // Index (u32) + Generation (u32)
127 pub parent_id: Option<SequenceId>,
128 pub world_id: WorldId,
129 pub priority: u8,
130 pub state: SequenceState, // Ready, Prefill, Decode, BlockedOnTool, Completed
131 pub context_id: ContextRevisionId,
132 pub block_table_id: u32,
133 pub prefill_cursor: usize,
134 pub generated_tokens: usize,
135 pub arrival_ticks: u64,
136 pub deadline_ticks: Option<u64>,
137}
138```
139
140### 3.2 Transformer Execution Submit/Commit Contract
141
142```rust
143pub trait TransformerBatchExecutor {
144 type Fence;
145
146 fn submit(
147 &mut self,
148 model: &ResidentModel,
149 plan: &BlackwellBatchPlan,
150 kv: &UnifiedKvTensorPool,
151 ) -> Result<SubmittedBatch<Self::Fence>, EngineError>;
152
153 fn poll(&mut self, fence: &Self::Fence) -> Result<FenceStatus, EngineError>;
154
155 fn complete(
156 &mut self,
157 submitted: SubmittedBatch<Self::Fence>,
158 ) -> Result<BatchResult, EngineError>;
159}
160```
161
162### 3.3 Memory and Context Composition Contract
163
164```rust
165pub trait MemoryRuntime: Send + Sync {
166 fn recall(&self, query: &RecallQuery) -> Result<RecallSet, MemoryError>;
167 fn get(&self, id: MemoryId) -> Result<MemoryObject, MemoryError>;
168 fn commit(&mut self, memory: NewMemory) -> Result<MemoryId, MemoryError>;
169}
170
171pub struct ContextRevision {
172 pub id: ContextRevisionId,
173 pub parent: Option<ContextRevisionId>,
174 pub segments: Arc<[ContextSegment]>,
175 pub total_tokens: usize,
176}
177```
178
179### 3.4 World Manifest Contract
180
181```rust
182pub struct WorldManifest {
183 pub id: WorldId,
184 pub parent: Option<WorldId>,
185 pub object_root: ObjectRoot,
186 pub filesystem_root: ObjectRoot,
187 pub token_root: TokenChainId,
188 pub memory_root: MemoryRoot,
189 pub capability_set: CapabilitySetId,
190 pub effect_log: EffectLogId,
191 pub sequence_checkpoint: Option<SequenceCheckpointId>,
192 pub created_at: u64,
193 pub provenance: ProvenanceId,
194}
195```
196
197### 3.5 Operator Control Envelope
198
199```rust
200pub struct ControlEnvelope {
201 pub protocol_version: u16,
202 pub request_id: u64,
203 pub operation_id: u128,
204 pub operator_session: u64,
205 pub command: ControlCommand,
206}
207```
208
209---
210
211## 4. Verification Gate: Runtime Integration Spine
212
213The integration spine milestone verifies that the six frozen boundaries operate in concert on physical hardware:
214
2151. **Workload Definition**:
216 - 1 root World initialized with 32,768 shared prefix tokens.
217 - Pinned reference weights: TinyLlama-1.1B BF16 / Qwen2.5-7B BF16.
218 - 500 child branches forked from root context.
219 - 32 decode tokens generated per branch.
2202. **Acceptance Criteria**:
221 - 500/500 branches complete successfully with verified token parity.
222 - Zero recorded fallback events on instrumented GPU operations. The current counter does not observe all CPU-executed operations; C1 is adding per-operation device provenance.
223 - Zero stale `SequenceId` completions committed.
224 - KV page physical sharing ratio $\ge 95\%$.
225 - Telemetry emitted to CLI and cryptographic receipt committed to `.rsi/ledger.db`.