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

GitHub aien-dev/aien-sovereign-core-mv#595 (code only)

closed derived 397929e6fa58c604 #595

Imported from GitHub aien-dev/aien-sovereign-core-mv#595 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 7a258a0a4ebd53c89c4356e3d085f0a1d1b31fa9 · Head 4c77044dd3759c11f72c59f053343ab5cce45a39

github-advanced-security[bot] commented on crates/aien-serve-http/tests/door_522.rs line 154 on 2026-10-16 15:35 UTC

github-advanced-security[bot] commented on crates/aien-serve-http/tests/door_522.rs line 200 on 2026-10-16 15:35 UTC

github-advanced-security[bot] commented on crates/aien-serve-http/tests/door_522.rs line 204 on 2026-10-16 15:35 UTC

github-advanced-security[bot] commented on crates/aien-serve-http/tests/door_522.rs line 207 on 2026-10-16 15:35 UTC

github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-16 15:35 UTC

drakestapleton reviewed (COMMENTED) on 2026-10-30 11:17 UTC

Triage: needs changes.

  • This PR needs a rebase: GitHub reports it as conflicting and not rebaseable.
  • Four inline code-scanning comments are still open.
  • The as_raw soundness commit needs a careful human look.

Hardware evidence: host-only.

Triage only; no approval or merge implied.

drakestapleton reviewed (COMMENTED) on 2026-10-30 13:36 UTC

Review at head 7cddaade: the code is mergeable on GitHub evidence and needs no Spark run. The body needs correcting first (needs-changes, body only).

  • What's left in the diff. It's 5 files, +343/−68.
    • server.rs (L193-226) adds ApiError::gpu_busy: a 503 in the OpenAI error envelope, with code: gpu_busy, Retry-After: 5, and the engine's reason in the message. It's used at L896 and L1435.
    • omega_engine.rs gets a doc comment.
    • tests/door_522.rs is a new test file.
    • docs/inference/own30b-omega-door.rs is a reading guide that isn't compiled.
    • .crumb is regenerated.
    • There's no unsafe code, no FFI, and no change to scheduling, the KV cache, the GPU lock or memory sizing.
  • Why no Spark gate. The busy-503 path is plain host logic, and it's covered by the BusyEngine test plus the existing assert_chip_busy tests. Status code and Retry-After are unchanged. The two hardware-adjacent pieces are gone: the as_raw(&mut self) FFI change was reverted in 3883728b, and no cfg(has_omega_*) code is touched. There are no performance or GB10 claims, and the body itself says "host only, no chip runs".
  • History. The last two refreshes are true 2-parent merges: 86a475d8 (with 7e457336) and 7cddaade (with 3fd55d0a). 7cddaade changes only .crumb plus main's own ADR 0003 patch. The compare against main shows 15 ahead and 0 behind, and the original commits are still in the chain. 15cae561 says "after rebase onto main", so there was an earlier rebase, around Oct 23-24.
  • CI. AIEN Checks (including crumb verify), CodeQL and all four Analyze jobs are green. AIEN Alpha was skipped because it only runs for tags. The PR is clean against 3fd55d0a.

Must-fix (PR body only):

  1. Item 5 (as_raw taking &mut self) is still listed as included. It was reverted in 3883728b because main's shared weight handles didn't compile with it. Please say it moved back to #522.
  2. Item 1 says this PR adds the spawn_blocking prompt render. Main already does that (server.rs L542/L596), so this PR now only adds the regression test. Please say so.
  3. The test counts and the "PREFILL-E2E-2 until #589" note are from before the refreshes. Please re-run the tests and update them, or mark them as stale. Workspace tests, clippy and fmt rest on your word; I couldn't run them.

Nits:

  • Six Oct 27 commits carry Signed-off-by: Claude Opus 5.5 (PRTrain): be4fb27c, 4c6d71df, 3883728b, 60eb30b6, ca156d6a and 05599c1a. Removing them would mean rewriting history, so I'm only flagging this for the maintainers; please don't force-push.
  • The busy 503 body changes from {"error": "…"} to the OpenAI envelope. Worth a changelog line for any client that reads error as a string.
  • docs/inference/own30b-omega-door.rs (around L20) still says "against main bdd58a2b".

Triage only; no approval or merge implied.

— Grokbot

drakestapleton reviewed (COMMENTED) on 2026-10-30 14:29 UTC

Refresh check, 7cddaade to 4c77044d: ready-to-merge on code. The body fixes from review 5713035372 are cleared. One small doc mismatch is left (below).

  • History. 4c77044d is a true 2-parent merge of 7cddaade and main 7a258a0a. Comparing 7cddaade...4c77044d gives 4 ahead and 0 behind: this merge plus main's own commits. The merge base is 7cddaade, so there was no force-push. The merge commit has no Signed-off-by (the older PRTrain trailers are noted, and a squash with a clean message would drop them).
  • Merge-only, verified by blob SHA. Against main 7a258a0a (16 ahead, 0 behind), the PR's four files are byte-identical to 7cddaade: server.rs 2483cac1, omega_engine.rs 3cfaa429, tests/door_522.rs 4e865e74 and docs/inference/own30b-omega-door.rs e8cd5fc8. Only the root .crumb changed, regenerated at 94fffbcf.
  • Body. All four must-fixes are cleared, and there's no duplicated text left:
    • Item 5 (as_raw) is struck through and marked REVERTED in 3883728b, moved to #522.
    • Item 1 says the spawn_blocking change is already on main and only the test remains.
    • The counts are marked superseded and the post-refresh runs NOT_RUN. The body correctly notes that AIEN Checks runs only the portable gates, not cargo test or clippy.
    • The 503 compatibility note is there.
  • CI and state. AIEN Checks, CodeQL and all four Analyze jobs are green. AIEN Alpha was skipped because it only runs for tags. It's not a draft, and it's clean against 7a258a0a.

Remaining mismatches (non-blocking, fix before or at squash):

  1. docs/inference/own30b-omega-door.rs L21 at this head still reads "Refreshed for sc#522 against main bdd58a2b". The blob is unchanged from 7cddaade, so the bdd58a2b-to-7a258a0a edit didn't land. Body item 4 says "signatures as on main 7a258a0a", so the body and the file now disagree. Either push the one-line edit or drop the claim from the body.
  2. The body's last line, "Description updated per review 5713035372. — Grokbot", carries my signature, but I didn't write it. Please remove the "— Grokbot" from the PR body; my signature belongs only on my own reviews. The evidence note's "head 7cddaade" is also now one merge behind.

Triage only; no approval or merge implied.

— Grokbot

Fetch it

A git bundle of the pull request's head, 32650 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/397929e6fa58c604.bundle -o 397929e6fa58c604.bundle
git fetch 397929e6fa58c604.bundle refs/pull/595/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
595
4c77044dd3759c11f72c59f053343ab5cce45a39
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":595,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/595","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:37:37Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/.crumb b/.crumb
index 3f0419ce..032bc833 100644
--- a/.crumb
+++ b/.crumb
@@ -83,7 +83,7 @@
         },
         {
           "digest": "98f74a2cafe04d7bd74bd814c74f6832d2a4141bf589576d3f53992338abde00",
-          "last_commit": "15b6c3bd",
+          "last_commit": "53beb962",
           "name": "crates/aien-cli",
           "purpose": ""
         },
@@ -125,14 +125,14 @@
         }
       ],
       "children_root": "sha256:73e08b2b223f0fe53b0b52e64cde675045f54c70cf305d4d2aa899d3051032e1",
-      "compiled_at": "2026-10-30T13:52:57Z",
+      "compiled_at": "2026-10-30T14:07:52Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:033491eab258c213ef32c76a3f17997846d40bc4d96ba91b13ebf23d1bf17914",
+      "digest": "sha256:eee842d9d363d9ff57e168738aabba507312774858b9e93d77fb83c9ee479e34",
       "evidence_files": 3602,
       "evidence_root": "sha256:1b8069934a4cc67803874ebd2ad5de32671fae5ccce1a3ea70aeb532fe8ea86b",
-      "files": 8109,
-      "generated_at_commit": "020835c88d8ea474eb3f8cefe30608082019c10e",
-      "source_tree": "sha256:68299e8b0fd7093960d8bd227bcdb82653aa5f7b399d13aef02fd4d18da37e15"
+      "files": 8110,
+      "generated_at_commit": "7cddaade335c8a331a2eaf62662e7a4649b79634",
+      "source_tree": "sha256:d9ccb90626cd3a4611ed18804ce0782d8e941f4df896cd9cbaa885088fb38d02"
     }
   },
   "history": [],
diff --git a/crates/aien-serve-http/src/omega_engine.rs b/crates/aien-serve-http/src/omega_engine.rs
index fe4e2933..3cfaa429 100644
--- a/crates/aien-serve-http/src/omega_engine.rs
+++ b/crates/aien-serve-http/src/omega_engine.rs
@@ -50,6 +50,19 @@ pub const LOAD_MIN_FREE_GB: f64 = 45.0;
 /// activation rounding. Off: `--whole-prompt off` / `AIEN_SERVE_WHOLE_PROMPT=0` (the chunked
 /// prefill of cut 10), `--prefill-device-host off` / `AIEN_SERVE_WP_DEVICE_HOST=0` (host routing
 /// and combine). The cached 30 GB weight copy and speculative decoding stay off.
+///
+/// Defaults differ by path (sc#522); this is documented, not aligned, because changing a chip
+/// tool's default would change what its past evidence means:
+/// - this door: both ON ([`Default`]; `--whole-prompt off` / `--prefill-device-host off`);
+/// - the engine itself (`Qwen3MoeOmegaEngine`): both OFF until `set_whole_prompt(true)` and
+///   `set_whole_prompt_device_host(true)`; its other callers (`own30b_ttft`, `own30b_wp_gate`)
+///   set the switch explicitly per leg;
+/// - `own30b_check`: both OFF unless the bare flags `--whole-prompt` and
+///   `--prefill-device-host` are passed.
+///
+/// A door run and a check run therefore use different prefill paths unless the check is given
+/// both flags (or the door both `off` switches); their tokens can differ by FP8 activation
+/// rounding. Compare like with like.
 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
 pub struct PrefillMode {
     pub whole_prompt: bool,
diff --git a/crates/aien-serve-http/src/server.rs b/crates/aien-serve-http/src/server.rs
index 123574d3..2483cac1 100644
--- a/crates/aien-serve-http/src/server.rs
+++ b/crates/aien-serve-http/src/server.rs
@@ -190,6 +190,20 @@ impl ApiError {
         }
     }
 
+    /// The engine could not get the shared chip in time (another job holds the GPU lock).
+    fn gpu_busy(detail: &str) -> Self {
+        let mut e = Self {
+            status: StatusCode::SERVICE_UNAVAILABLE,
+            body: ErrorBody::new(
+                "server_busy",
+                format!("GPU busy with another job, retry shortly: {detail}"),
+            ),
+            retry_after: Some(5),
+        };
+        e.body.error.code = Some("gpu_busy".into());
+        e
+    }
+
     fn internal(msg: impl Into<String>) -> Self {
         Self {
             status: StatusCode::INTERNAL_SERVER_ERROR,
@@ -866,18 +880,6 @@ fn run_readers(
     );
 }
 
-/// A busy chip: 503 with a plain body and `Retry-After: 5`.
-fn chip_busy() -> Response {
-    let mut resp = (
-        StatusCode::SERVICE_UNAVAILABLE,
-        Json(serde_json::json!({"error": "GPU busy with another job"})),
-    )
-        .into_response();
-    resp.headers_mut()
-        .insert(header::RETRY_AFTER, HeaderValue::from_static("5"));
-    resp
-}
-
 /// The response for a generation's events: the first decides the status (a busy chip is 503).
 async fn respond(
     mut rx: mpsc::Receiver<Ev>,
@@ -888,11 +890,11 @@ async fn respond(
     prompt_tokens: usize,
     tools: bool,
 ) -> Result<Response, ApiError> {
-    // The first event decides the status: a busy chip is a 503 with a plain body, before any
-    // headers go out (streaming included). Everything else is forwarded unchanged.
+    // The first event decides the status: a busy chip is a 503 in the OpenAI error envelope,
+    // before any headers go out (streaming included). Everything else is forwarded unchanged.
     let first = rx.recv().await;
-    if let Some(Ev::Busy(_)) = first {
-        return Ok(chip_busy());
+    if let Some(Ev::Busy(m)) = &first {
+        return Err(ApiError::gpu_busy(m));
     }
     let (ftx, frx) = mpsc::channel::<Ev>(64);
     tokio::spawn(async move {
@@ -1430,7 +1432,7 @@ async fn collect_response(
             Ev::Error(m) => return Err(ApiError::internal(m)),
             // Not the first event on the readers' path (`Ev::Readers` goes before the connect
             // generation); nothing has been sent yet, so it is the same 503 as a busy first event.
-            Ev::Busy(_) => return Ok(chip_busy()),
+            Ev::Busy(m) => return Err(ApiError::gpu_busy(&m)),
         }
     }
     Err(ApiError::internal("generation ended without a result"))
diff --git a/crates/aien-serve-http/tests/door_522.rs b/crates/aien-serve-http/tests/door_522.rs
new file mode 100644
index 00000000..4e865e74
--- /dev/null
+++ b/crates/aien-serve-http/tests/door_522.rs
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: Apache-2.0
+// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Host checks for the sc#522 review follow-ups of the HTTP door: request preparation
+//! (chat rendering and tokenizing) must not run on the async runtime, and a busy chip must
+//! answer in the same OpenAI error envelope as every other error.
+
+use std::io::{Read, Write};
+use std::net::{SocketAddr, TcpStream};
+use std::sync::{mpsc, Arc, Mutex};
+use std::time::Duration;
+
+use aien_serve_http::codec::{ByteCodec, Codec, CodecError};
+use aien_serve_http::engine::{Engine, EngineError, GenerateOutcome, GenerateParams, StubEngine};
+use aien_serve_http::server::{serve, ServerConfig};
+use serde_json::Value;
+
+/// The server refuses unauthenticated requests (main's bearer cutover); every request here sends it.
+const TOKEN: &str = "door-522-test-credential";
+
+const PROMPT: &str =
+    r#"{"model":"test-model","messages":[{"role":"user","content":"hi"}],"max_tokens":4}"#;
+
+/// Serves on a CURRENT-THREAD runtime driven by its own thread: anything that blocks the
+/// runtime thread stalls every other request, which is what the off-runtime test detects.
+fn start_single_thread(engine: Arc<dyn Engine>, codec: Arc<dyn Codec>) -> SocketAddr {
+    let (tx, rx) = mpsc::channel();
+    std::thread::spawn(move || {
+        let rt = tokio::runtime::Builder::new_current_thread()
+            .enable_all()
+            .build()
+            .expect("runtime");
+        rt.block_on(async move {
+            let cfg = ServerConfig {
+                port: 0,
+                model_id: "test-model".into(),
+                bearer_token: TOKEN.into(),
+                ..ServerConfig::default()
+            };
+            let (addr, handle) = serve(cfg, engine, codec).await.expect("bind loopback");
+            tx.send(addr).expect("report addr");
+            let _ = handle.await;
+        });
+    });
+    rx.recv_timeout(Duration::from_secs(10)).expect("server up")
+}
+
+struct Reply {
+    status: u16,
+    headers: String,
+    body: String,
+}
+
+/// One HTTP/1.1 exchange; `Err` when the server does not answer within `wait`.
+fn request(
+    addr: SocketAddr,
+    method: &str,
+    path: &str,
+    body: &str,
+    wait: Duration,
+) -> std::io::Result<Reply> {
+    let mut s = TcpStream::connect(addr)?;
+    s.set_read_timeout(Some(wait))?;
+    let req = format!(
+        "{method} {path} HTTP/1.1\r\nHost: localhost\r\nAuthorization: Bearer {TOKEN}\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
+        body.len()
+    );
+    s.write_all(req.as_bytes())?;
+    let mut raw = Vec::new();
+    s.read_to_end(&mut raw)?;
+    let split = raw
+        .windows(4)
+        .position(|w| w == b"\r\n\r\n")
+        .expect("header end");
+    let headers = String::from_utf8_lossy(&raw[..split]).to_string();
+    let status = headers
+        .split_whitespace()
+        .nth(1)
+        .and_then(|s| s.parse().ok())
+        .expect("status code");
+    Ok(Reply {
+        status,
+        headers,
+        body: String::from_utf8_lossy(&raw[split + 4..]).to_string(),
+    })
+}
+
+/// [`ByteCodec`] whose `encode` reports that it started, then blocks until released (or 20 s).
+struct GateCodec {
+    entered: Mutex<mpsc::Sender<()>>,
+    release: Mutex<mpsc::Receiver<()>>,
+}
+
+impl Codec for GateCodec {
+    fn render_chat(&self, turns: &[(&str, &str)]) -> Result<String, CodecError> {
+        ByteCodec.render_chat(turns)
+    }
+    fn encode(&self, text: &str) -> Result<Vec<u32>, CodecError> {
+        let _ = self.entered.lock().unwrap().send(());
+        let _ = self
+            .release
+            .lock()
+            .unwrap()
+            .recv_timeout(Duration::from_secs(20));
+        ByteCodec.encode(text)
+    }
+    fn decode(&self, tokens: &[u32]) -> Result<String, CodecError> {
+        ByteCodec.decode(tokens)
+    }
+    fn stop_token_ids(&self) -> Vec<u32> {
+        ByteCodec.stop_token_ids()
+    }
+}
+
+#[test]
+fn tokenizing_does_not_block_the_runtime() {
+    let (entered_tx, entered_rx) = mpsc::channel();
+    let (release_tx, release_rx) = mpsc::channel();
+    let codec = GateCodec {
+        entered: Mutex::new(entered_tx),
+        release: Mutex::new(release_rx),
+    };
+    let engine = StubEngine::new(b"ok".iter().map(|&b| u32::from(b)).collect());
+    let addr = start_single_thread(Arc::new(engine), Arc::new(codec));
+
+    let chat = std::thread::spawn(move || {
+        request(
+            addr,
+            "POST",
+            "/v1/chat/completions",
+            PROMPT,
+            Duration::from_secs(30),
+        )
+    });
+    entered_rx
+        .recv_timeout(Duration::from_secs(10))
+        .expect("encode started");
+    // The tokenizer is now blocked. With it on the runtime thread, /health cannot answer.
+    let health = request(addr, "GET", "/health", "", Duration::from_secs(3));
+    release_tx.send(()).expect("release encode");
+    let health = health.expect("/health answers while a prompt is being tokenized");
+    assert_eq!(health.status, 200, "{}", health.body);
+
+    let chat = chat.join().unwrap().expect("chat reply");
+    assert_eq!(chat.status, 200, "{}", chat.body);
+    let v: Value = serde_json::from_str(&chat.body).expect("json");
+    assert_eq!(v["choices"][0]["message"]["content"], "ok");
+}
+
+/// An engine whose chip is always held by another job.
+struct BusyEngine;
+
+impl Engine for BusyEngine {
+    fn kind(&self) -> &str {
+        "busy"
+    }
+    fn max_context_tokens(&self) -> usize {
+        4096
+    }
+    fn generate(
+        &self,
+        _prompt: &[u32],
+        _params: &GenerateParams,
+        _on_token: &mut dyn FnMut(u32) -> bool,
+    ) -> Result<GenerateOutcome, EngineError> {
+        Err(EngineError::Busy(
+            "GPU lock held by another job for 30 s".into(),
+        ))
+    }
+}
+
+#[test]
+fn gpu_busy_is_an_openai_error_envelope() {
+    let addr = start_single_thread(Arc::new(BusyEngine), Arc::new(ByteCodec));
+    for stream in [false, true] {
+        let body = PROMPT.replace(
+            "\"max_tokens\":4",
+            &format!("\"max_tokens\":4,\"stream\":{stream}"),
+        );
+        let r = request(
+            addr,
+            "POST",
+            "/v1/chat/completions",
+            &body,
+            Duration::from_secs(30),
+        )
+        .expect("reply");
+        assert_eq!(r.status, 503, "stream={stream}: {}", r.body);
+        assert!(
+            r.headers.to_ascii_lowercase().contains("retry-after: 5"),
+            "stream={stream}: {}",
+            r.headers
+        );
+        let v: Value = serde_json::from_str(&r.body)
+            .unwrap_or_else(|e| panic!("stream={stream}: not JSON ({e}): {}", r.body));
+        let err = &v["error"];
+        assert_eq!(err["type"], "server_busy", "stream={stream}: {v}");
+        assert_eq!(err["code"], "gpu_busy", "stream={stream}: {v}");
+        let msg = err["message"].as_str().expect("message string");
+        assert!(msg.contains("GPU busy"), "stream={stream}: {msg}");
+        assert!(
+            msg.contains("held by another job"),
+            "stream={stream}: {msg}"
+        );
+        assert!(err.get("param").is_some(), "stream={stream}: {v}");
+    }
+}
diff --git a/docs/inference/own30b-omega-door.rs b/docs/inference/own30b-omega-door.rs
index f82619c2..e8cd5fc8 100644
--- a/docs/inference/own30b-omega-door.rs
+++ b/docs/inference/own30b-omega-door.rs
@@ -13,71 +13,112 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-//! Omega engine behind H's `Engine` trait (OWN-30B cut 3 x cut 4 seam).
-//! Drop-in for `crates/aien-serve-http/src/omega_engine.rs`; in that crate replace
-//! `aien_omega_abi` with `aien_inference_abi` and add `--engine omega` in main.rs:
-//!     "omega" => Box::new(OmegaDoor::load(&args.model_dir, args.max_context)?)
-use std::path::Path;
+//! Reading guide: the Omega engine behind the HTTP door's `Engine` trait (OWN-30B).
+//!
+//! NOT COMPILED. The live code is `crates/aien-serve-http/src/omega_engine.rs`; when this
+//! sketch and that file disagree, that file wins. Refreshed for sc#522 against main bdd58a2b
+//! (the first version of this file was the cut 3 x cut 4 seam, before the GPU lock, sampling,
+//! whole-prompt prefill and persistent KV existed). Bodies are trimmed to the steps, in order.
+//!
+//! Wiring in `main.rs` (`--engine omega`):
+//!     let mut door = OmegaDoor::load(&model_dir, max_ctx, weights, spin_us, prefill)?;
+//!     if AIEN_KV_STORE_DIR is set { door.set_persistence(kv_persist::open_with_test_fault(..).0) }
+//!     Arc::new(door)  // the server's Arc<dyn Engine>
+use std::path::{Path, PathBuf};
+use std::sync::atomic::AtomicUsize;
+use std::time::Duration;
 
-use aien_omega_abi::qwen3_moe_omega::{self as omega, OmegaEngine};
-use crate::engine::{Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams};
+use aien_inference_abi::qwen3_moe_omega::{self as omega, OmegaEngine, WeightFormat};
 
-pub struct OmegaDoor(OmegaEngine);
+use crate::engine::{Engine, EngineError, GenerateOutcome, GenerateParams};
+use crate::kv_persist::PersistState;
+
+/// The hive's GPU lock: held only around a generation (and the load), never while idle.
+pub const GPU_LOCK_PATH: &str = "/tmp/aien-gb10.lock";
+/// How long `generate` waits for the GPU lock before answering `EngineError::Busy` (HTTP 503).
+pub const LOCK_WAIT: Duration = Duration::from_secs(30);
+/// Host memory the load needs free.
+pub const LOAD_MIN_FREE_GB: f64 = 45.0;
+
+/// Prefill path; both ON by default in the door (the engine and `own30b_check` default OFF:
+/// see the doc on `PrefillMode` in the live file).
+pub struct PrefillMode {
+    pub whole_prompt: bool,
+    pub device_host: bool,
+}
+
+pub struct OmegaDoor {
+    /// Declared first: a running store drains its parks before the engine goes.
+    persist: PersistState,
+    engine: OmegaEngine,
+    lock_wait: Duration,
+    lock_path: PathBuf,
+    /// Prompt tokens the last generation reused (RAM or restored prefix).
+    reused_last: AtomicUsize,
+}
 
 impl OmegaDoor {
-    /// Loads the checkpoint onto Omega (about 61 GB resident plus the KV pool). Blocks for the
-    /// load; `max_context` is the KV capacity in tokens (rounded up to 16-token blocks).
-    pub fn load(model_dir: &Path, max_context: usize) -> Result<Self, String> {
-        let engine = OmegaEngine::load(model_dir, max_context, &mut |what| eprintln!("omega load: {what}"))?;
-        let r = &engine.load_report;
-        eprintln!(
-            "omega engine ready: {:.1}s, resident {:.1} GB, host {:.1} GB, window_api={}",
-            r.seconds,
-            r.resident_bytes as f64 / 1e9,
-            r.host_bytes as f64 / 1e9,
-            r.window_api
-        );
-        Ok(Self(engine))
+    /// 1. refuse below LOAD_MIN_FREE_GB available, or when the binary carries the CPU stub of
+    ///    omega, or when FP8 experts are asked for without the FP8 GEMV linked;
+    /// 2. apply `spin_us`; take the GPU lock (LOCK_WAIT);
+    /// 3. `OmegaEngine::load_with(model_dir, max_context, format, progress)`;
+    /// 4. still under the lock: `set_whole_prompt(..)`, then `set_whole_prompt_device_host(..)`
+    ///    when whole-prompt is on (a refusal is fatal and names the `off` switch);
+    /// 5. log the load report and the paths in use; `from_parts(engine, GPU_LOCK_PATH, LOCK_WAIT)`.
+    pub fn load(
+        model_dir: &Path,
+        max_context: usize,
+        format: WeightFormat,
+        spin_us: Option<u32>,
+        prefill: PrefillMode,
+    ) -> Result<Self, String> {
+        unimplemented!("see omega_engine.rs")
+    }
+
+    /// A door over a built engine (tests: a private lock file and the host test engine).
+    /// Persistence starts `PersistState::Off`.
+    pub fn from_parts(engine: OmegaEngine, lock_path: PathBuf, lock_wait: Duration) -> Self {
+        unimplemented!("see omega_engine.rs")
+    }
+
+    /// Installs the persistence state, before the door is shared.
+    pub fn set_persistence(&mut self, state: PersistState) {
+        self.persist = state;
     }
 }
 
 impl Engine for OmegaDoor {
     fn kind(&self) -> &str {
-        self.0.kind()
+        self.engine.kind()
     }
 
     fn max_context_tokens(&self) -> usize {
-        self.0.max_context_tokens()
+        self.engine.max_context_tokens()
     }
 
+    /// 1. empty prompt -> `Failed`; prompt >= context -> `PromptTooLong`;
+    /// 2. map the params to `omega::GenerateParams`;
+    /// 3. persistent KV on with restore: fetch the longest stored prefix that beats the RAM
+    ///    prefix, WITHOUT the GPU lock;
+    /// 4. take the GPU lock at `lock_path` (wait `lock_wait`), else `EngineError::Busy`;
+    /// 5. restore the fetched K/V (all or nothing; on error the engine resets and prefills);
+    /// 6. `engine.generate_with(prompt, &q, &mut sampler, on_token)` with the server's own
+    ///    `SamplingObserver`, so CPU and Omega pick tokens the same way;
+    /// 7. persistent KV on: snapshot (park) under the lock; release the lock; then submit the
+    ///    park for writing;
+    /// 8. map the finish (`Constraint` reads as `Stop`) and return the sampling record.
     fn generate(
         &self,
         prompt: &[u32],
         p: &GenerateParams,
         on_token: &mut dyn FnMut(u32) -> bool,
     ) -> Result<GenerateOutcome, EngineError> {
-        let max = self.0.max_context_tokens();
-        if prompt.is_empty() || prompt.len() >= max {
-            return Err(EngineError::PromptTooLong { len: prompt.len(), max });
-        }
-        let q = omega::GenerateParams {
-            max_new_tokens: p.max_new_tokens,
-            temperature: p.temperature,
-            top_p: p.top_p,
-            top_k: p.top_k,
-            seed: p.seed,
-            stop_token_ids: p.stop_token_ids.clone(),
-        };
-        let o = self.0.generate(prompt, &q, on_token).map_err(EngineError::Failed)?;
-        Ok(GenerateOutcome {
-            emitted_tokens: o.emitted_tokens,
-            finish: match o.finish {
-                omega::FinishReason::Stop => FinishReason::Stop,
-                omega::FinishReason::Length => FinishReason::Length,
-                omega::FinishReason::Cancelled => FinishReason::Cancelled,
-            },
-            prefill_ms: o.prefill_ms,
-            decode_ms: o.decode_ms,
-        })
+        unimplemented!("see omega_engine.rs")
+    }
+
+    /// `/health` `persistent_kv`: absent when off, `refused` with the reason, or the store's
+    /// status when on.
+    fn persistence_status(&self) -> Option<serde_json::Value> {
+        unimplemented!("see omega_engine.rs")
     }
 }