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 / crates / aien-serve-http / src / main.rs

586 lines · 24518 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! `aien-serve-http`: OpenAI-compatible door on 127.0.0.1 for AIEN's own model engines
17//! (Qwen3.8-27B FP8 and the OWN-30B Qwen3-30B-A3B).
18//!
19//! aien-serve-http [--engine cpu|stub|omega] [--weights bf16|fp8-experts|fp8] [--spin-us N]
20//! [--whole-prompt on|off] [--prefill-device-host on|off]
21//! [--model-dir DIR] [--port 18091]
22//! [--bind 127.0.0.1] [--model-id ID] [--max-context N]
23//! [--max-tokens-cap N] [--stub-reply TEXT] [--thinking on|off|template]
24//! aien-serve-http --version
25//!
26//! `--model-dir` defaults to `$HOME/models/qwen3.8-27b-fp8-017b9c7a`. `--version` prints the
27//! build identity (commit, omega pin, native or stub engines) and exits without loading anything.
28//! `tools/serve-27b.sh` starts the 27B server with the flags the live server uses.
29//!
30//! `cpu` (default) loads the checkpoint into the CPU reference forward (slow, real).
31//! `omega` loads the checkpoint onto AIEN's own GPU engine (FP8 by default, spin 2000 us
32//! unless `--spin-us` or `AIEN_OMEGA_SPIN_US` says otherwise) and takes the shared chip lock
33//! only around each generation. Its prefill runs the whole prompt in one pass with the router
34//! and MoE combine on the chip (ON by default; `--whole-prompt off`, `--prefill-device-host off`
35//! or `AIEN_SERVE_WHOLE_PROMPT=0` / `AIEN_SERVE_WP_DEVICE_HOST=0` turn them off).
36//! Persistent KV (omega only, opt in): with `AIEN_KV_STORE_DIR` set (and `AIEN_KV_STORE_KEY`,
37//! e.g. `atlas-vault run AIEN_KV_STORE_KEY -- aien-serve-http ...`) the door parks each turn's KV
38//! in the sealed store and restores the longest stored prefix after a restart; any problem
39//! refuses with a startup line and the door runs plain. Unset: nothing changes.
40//! SIGTERM/SIGINT: stop accepting, finish the request in flight, drain the parks, exit 0.
41//! `AIEN_KV_TEST_FAULT` (chip acceptance checks only) stalls one store step; see `kv_persist`.
42//! `--thinking on|off|template` sets `enable_thinking` for requests that do not set it themselves
43//! (`chat_template_kwargs.enable_thinking`); `template` (the default) leaves the chat template's
44//! own default (Qwen3.8-27B and Qwen3.6-35B-A3B: on). Templates without a thinking switch ignore it.
45//! `stub` replays `--stub-reply` for every request, using the model directory's
46//! tokenizer when it exists (so Odysseus can be wired before the weights load).
47
48use std::net::IpAddr;
49use std::path::PathBuf;
50use std::process::ExitCode;
51use std::sync::Arc;
52
53use aien_inference_abi::qwen3_moe_omega::WeightFormat;
54use aien_serve_http::codec::{ByteCodec, Codec, HfCodec};
55use aien_serve_http::cpu_engine::CpuReferenceEngine;
56use aien_serve_http::engine::{Engine, StubEngine};
57use aien_serve_http::kv_persist;
58use aien_serve_http::omega_engine::{
59 parse_switch, OmegaDoor, PrefillMode, WHOLE_PROMPT_ENV, WP_DEVICE_HOST_ENV,
60};
61use aien_serve_http::qwen36_batch;
62use aien_serve_http::qwen38_engine;
63use aien_serve_http::server::{serve_until, ServerConfig};
64
65/// Default `--model-dir`, under `$HOME`: the Qwen3.8-27B FP8 checkpoint (Hugging Face
66/// `Qwen/Qwen3.8-27B-FP8`, revision 017b9c7a), the model the fast server serves.
67const DEFAULT_MODEL_DIR: &str = "models/qwen3.8-27b-fp8-017b9c7a";
68
69/// What this binary was built with: the commit, the omega pin and whether the real Omega GPU
70/// library and the Qwen3.8 engine are linked or only the CPU stubs. Printed by `--version`,
71/// which loads nothing and never touches the GPU, so installers can refuse a stub build.
72fn build_info() -> String {
73 let gpu = aien_omega_gpu::native_identity();
74 let native = |b: bool| {
75 if b {
76 "native"
77 } else {
78 "STUB (not usable with --engine omega)"
79 }
80 };
81 format!(
82 "aien-serve-http {}\n\
83 sovereign-core commit: {} (dirty {})\n\
84 omega.lock: {}\n\
85 omega gpu engine: {} (link {}, abi {}, digest {}, archive sha256 {})\n\
86 qwen38 engine: {} (prefill {})\n\
87 release-grade native identity: {}\n\
88 default model dir: $HOME/{}\n",
89 env!("CARGO_PKG_VERSION"),
90 env!("AIEN_SERVE_HTTP_GIT_COMMIT"),
91 env!("AIEN_SERVE_HTTP_GIT_DIRTY"),
92 env!("AIEN_SERVE_HTTP_OMEGA_LOCK"),
93 native(aien_omega_gpu::is_native()),
94 gpu.link,
95 gpu.abi,
96 gpu.digest,
97 gpu.archive_sha256,
98 native(aien_omega_q38::is_native()),
99 if aien_omega_q38::has_prefill() {
100 "linked"
101 } else {
102 "missing"
103 },
104 if gpu.qualifies() { "yes" } else { "no" },
105 DEFAULT_MODEL_DIR,
106 )
107}
108
109struct Args {
110 engine: String,
111 model_dir: PathBuf,
112 cfg: ServerConfig,
113 stub_reply: String,
114 weights: WeightFormat,
115 spin_us: Option<u32>,
116 whole_prompt: Option<bool>,
117 wp_device_host: Option<bool>,
118 prefill: PrefillMode,
119 /// Qwen3.6-35B-A3B only: conversations stacked on one beat (0: the one-at-a-time door).
120 batch_slots: usize,
121}
122
123fn usage() -> String {
124 "usage: aien-serve-http [--engine cpu|stub|omega] [--weights bf16|fp8-experts|fp8] [--spin-us N] \
125 [--model-dir DIR] [--port N] [--bind ADDR] [--model-id ID] [--max-context N] \
126 [--max-tokens-cap N] [--stub-reply TEXT] [--whole-prompt on|off] [--prefill-device-host on|off] \
127 [--thinking on|off|template] [--batch-slots N] [--version]"
128 .to_string()
129}
130
131fn parse_args() -> Result<Args, String> {
132 let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
133 let mut a = Args {
134 engine: "cpu".into(),
135 model_dir: PathBuf::from(home).join(DEFAULT_MODEL_DIR),
136 cfg: ServerConfig {
137 max_context_tokens: Some(32768),
138 ..ServerConfig::default()
139 },
140 stub_reply: "Hello from the AIEN stub engine.".into(),
141 weights: WeightFormat::Fp8All,
142 spin_us: None,
143 whole_prompt: None,
144 wp_device_host: None,
145 prefill: PrefillMode::default(),
146 batch_slots: 0,
147 };
148 let mut it = std::env::args().skip(1);
149 while let Some(flag) = it.next() {
150 let mut val = || {
151 it.next()
152 .ok_or_else(|| format!("{flag} needs a value\n{}", usage()))
153 };
154 match flag.as_str() {
155 "--engine" => a.engine = val()?,
156 "--model-dir" => a.model_dir = PathBuf::from(val()?),
157 "--port" => a.cfg.port = val()?.parse().map_err(|e| format!("--port: {e}"))?,
158 "--bind" => {
159 a.cfg.bind = val()?
160 .parse::<IpAddr>()
161 .map_err(|e| format!("--bind: {e}"))?
162 }
163 "--model-id" => a.cfg.model_id = val()?,
164 "--max-context" => {
165 a.cfg.max_context_tokens =
166 Some(val()?.parse().map_err(|e| format!("--max-context: {e}"))?)
167 }
168 "--max-tokens-cap" => {
169 a.cfg.max_new_tokens_cap = val()?
170 .parse()
171 .map_err(|e| format!("--max-tokens-cap: {e}"))?
172 }
173 "--stub-reply" => a.stub_reply = val()?,
174 "--thinking" => {
175 a.cfg.default_enable_thinking = match val()?.as_str() {
176 "on" => Some(true),
177 "off" => Some(false),
178 "template" => None,
179 other => {
180 return Err(format!(
181 "--thinking must be on, off or template, got {other}"
182 ))
183 }
184 }
185 }
186 "--weights" => {
187 a.weights = match val()?.as_str() {
188 "bf16" => WeightFormat::Bf16,
189 "fp8-experts" => WeightFormat::Fp8Experts,
190 "fp8" => WeightFormat::Fp8All,
191 other => {
192 return Err(format!(
193 "--weights must be bf16, fp8-experts or fp8, got {other}"
194 ))
195 }
196 }
197 }
198 "--spin-us" => a.spin_us = Some(val()?.parse().map_err(|e| format!("--spin-us: {e}"))?),
199 "--batch-slots" => {
200 a.batch_slots = val()?.parse().map_err(|e| format!("--batch-slots: {e}"))?
201 }
202 "--whole-prompt" => a.whole_prompt = Some(parse_switch("--whole-prompt", &val()?)?),
203 "--prefill-device-host" => {
204 a.wp_device_host = Some(parse_switch("--prefill-device-host", &val()?)?)
205 }
206 "-h" | "--help" => return Err(usage()),
207 other => return Err(format!("unknown flag {other}\n{}", usage())),
208 }
209 }
210 if !matches!(a.engine.as_str(), "cpu" | "stub" | "omega") {
211 return Err(format!(
212 "--engine must be cpu, stub or omega, got {}",
213 a.engine
214 ));
215 }
216 if a.spin_us.is_none() {
217 // Flag beats environment beats the omega default (2000 us, the cut 7 number).
218 let env = std::env::var("AIEN_OMEGA_SPIN_US").ok();
219 a.spin_us = Some(aien_omega_gpu::parse_spin_us(env.as_deref())?.unwrap_or(2000));
220 }
221 // Prefill path: flag beats environment beats the default (both on; see PrefillMode).
222 let env_wp = std::env::var(WHOLE_PROMPT_ENV).ok();
223 let env_dev = std::env::var(WP_DEVICE_HOST_ENV).ok();
224 a.prefill = PrefillMode::from_env(env_wp.as_deref(), env_dev.as_deref())?;
225 if let Some(v) = a.whole_prompt {
226 a.prefill.whole_prompt = v;
227 }
228 if let Some(v) = a.wp_device_host {
229 a.prefill.device_host = v;
230 }
231 a.cfg.bearer_token = std::env::var("AIEN_SERVE_HTTP_BEARER_TOKEN").map_err(|_| {
232 "AIEN_SERVE_HTTP_BEARER_TOKEN must be set to a nonempty private credential".to_string()
233 })?;
234 if a.cfg.bearer_token.is_empty() || !a.cfg.bearer_token.bytes().all(|b| b.is_ascii_graphic()) {
235 return Err("AIEN_SERVE_HTTP_BEARER_TOKEN must be nonempty printable ASCII".into());
236 }
237 Ok(a)
238}
239
240/// Sampling defaults from the checkpoint's `generation_config.json`, when present.
241fn apply_generation_defaults(cfg: &mut ServerConfig, model_dir: &std::path::Path) {
242 let path = model_dir.join("generation_config.json");
243 let text = match aien_serve_http::read_model_text(&path) {
244 Ok(text) => text,
245 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
246 Err(e) => {
247 eprintln!(
248 "aien-serve-http: {}: {e}; keeping built-in sampling defaults",
249 path.display()
250 );
251 return;
252 }
253 };
254 let Ok(v) = serde_json::from_str::<serde_json::Value>(&text) else {
255 eprintln!(
256 "aien-serve-http: {} is not valid JSON; keeping built-in sampling defaults",
257 path.display()
258 );
259 return;
260 };
261 if let Some(t) = v.get("temperature").and_then(|x| x.as_f64()) {
262 cfg.default_temperature = t as f32;
263 }
264 if let Some(p) = v.get("top_p").and_then(|x| x.as_f64()) {
265 cfg.default_top_p = p as f32;
266 }
267 if let Some(k) = v.get("top_k").and_then(|x| x.as_u64()) {
268 cfg.default_top_k = k as usize;
269 }
270}
271
272fn main() -> ExitCode {
273 if std::env::args()
274 .skip(1)
275 .any(|a| a == "--version" || a == "-V")
276 {
277 print!("{}", build_info());
278 return ExitCode::SUCCESS;
279 }
280 let mut args = match parse_args() {
281 Ok(a) => a,
282 Err(e) => {
283 eprintln!("{e}");
284 return ExitCode::from(2);
285 }
286 };
287 apply_generation_defaults(&mut args.cfg, &args.model_dir);
288 // Persistent KV (sc#505): settings only when AIEN_KV_STORE_DIR is set; the store key leaves
289 // the environment now, before any engine loads, set dir or not (sc#523): no child inherits it.
290 let persist_settings =
291 kv_persist::take_settings(|n| std::env::var(n).ok(), |k| std::env::remove_var(k));
292 // OWN-8B stage S negative controls: read once, refused outright without debug assertions.
293 match aien_serve_http::sampling::install_mutant_from_env() {
294 Ok(None) => {}
295 Ok(Some(m)) => {
296 for _ in 0..3 {
297 eprintln!(
298 "aien-serve-http: !!! SAMPLING MUTANT {} ACTIVE: this server samples WRONG on purpose (negative control) !!!",
299 m.name()
300 );
301 }
302 }
303 Err(e) => {
304 eprintln!("aien-serve-http: {e}");
305 return ExitCode::from(2);
306 }
307 }
308
309 let codec: Arc<dyn Codec> = if args.model_dir.join("tokenizer.json").exists() {
310 match HfCodec::from_model_dir(&args.model_dir) {
311 Ok(c) => {
312 eprintln!(
313 "aien-serve-http: tokenizer from {} (chat layout {}, stop ids {:?})",
314 args.model_dir.display(),
315 c.template_name(),
316 c.stop_token_ids()
317 );
318 Arc::new(c)
319 }
320 Err(e) => {
321 eprintln!("aien-serve-http: tokenizer load failed: {e}");
322 return ExitCode::from(1);
323 }
324 }
325 } else if args.engine == "stub" {
326 eprintln!(
327 "aien-serve-http: no tokenizer.json in {}; stub engine uses the byte codec",
328 args.model_dir.display()
329 );
330 Arc::new(ByteCodec)
331 } else {
332 eprintln!(
333 "aien-serve-http: no tokenizer.json in {}",
334 args.model_dir.display()
335 );
336 return ExitCode::from(1);
337 };
338 // Tools are rendered in the template's own format (Hermes JSON for Qwen3-2507, qwen3_coder
339 // XML for Qwen3.6/3.8), read from the same template sources as the tokenizer.
340 match aien_serve_http::tools::ToolFormat::from_model_dir(&args.model_dir) {
341 Ok(f) => {
342 eprintln!("aien-serve-http: tool format {f:?}");
343 args.cfg.tool_format = f;
344 }
345 Err(e) => {
346 eprintln!("aien-serve-http: chat template unreadable: {e}");
347 return ExitCode::from(1);
348 }
349 }
350
351 // Who holds the chip: this server, or (verified, not merely claimed) an ancestor such as
352 // an aien-test gb10 gate. A claim that does not verify never reaches the chip.
353 if args.engine == "omega" {
354 match aien_serve_http::chip_reservation::install() {
355 Ok(aien_serve_http::chip_reservation::ChipReservation::Own) => {}
356 Ok(aien_serve_http::chip_reservation::ChipReservation::Inherited { holder_pid }) => {
357 eprintln!(
358 "aien-serve-http: chip reservation inherited from ancestor pid {holder_pid} (verified in /proc/locks); taking no lock"
359 );
360 }
361 Err(e) => {
362 eprintln!("aien-serve-http: chip reservation: {e}");
363 return ExitCode::from(1);
364 }
365 }
366 }
367
368 let engine: Arc<dyn Engine> = if args.engine == "stub" {
369 let reply = match codec.encode(&args.stub_reply) {
370 Ok(r) => r,
371 Err(e) => {
372 eprintln!("aien-serve-http: cannot encode --stub-reply: {e}");
373 return ExitCode::from(1);
374 }
375 };
376 Arc::new(
377 StubEngine::new(reply).with_max_context(args.cfg.max_context_tokens.unwrap_or(4096)),
378 )
379 } else if args.engine == "omega" && qwen38_engine::is_qwen38_dir(&args.model_dir) {
380 // Qwen3.8-27B (config model_type qwen3_5): its own door; no persistent KV (DeltaNet state).
381 if let Some(us) = args.spin_us {
382 if let Err(e) = aien_omega_gpu::set_spin_us(us) {
383 eprintln!("aien-serve-http: spin: {e}");
384 return ExitCode::from(1);
385 }
386 }
387 if args.cfg.model_id == ServerConfig::default().model_id {
388 args.cfg.model_id = qwen38_engine::default_model_id(&args.model_dir).into();
389 }
390 if std::env::var_os("AIEN_KV_STORE_DIR").is_some() {
391 eprintln!(
392 "aien-serve-http: AIEN_KV_STORE_DIR ignored: the qwen38 door has no persistent KV"
393 );
394 }
395 eprintln!(
396 "aien-serve-http: loading Qwen3.8 (qwen3_5) onto the Omega engine from {}",
397 args.model_dir.display()
398 );
399 let max_context = args.cfg.max_context_tokens.unwrap_or(32768);
400 if args.batch_slots > 0 && !qwen38_engine::is_moe_dir(&args.model_dir) {
401 eprintln!("aien-serve-http: --batch-slots: this build batches the Qwen3.6-35B-A3B (qwen3_5_moe) only");
402 return ExitCode::from(2);
403 }
404 if args.batch_slots > 0 {
405 match qwen36_batch::Qwen36BatchDoor::load(
406 &args.model_dir,
407 max_context,
408 args.batch_slots,
409 ) {
410 Ok(door) => Arc::new(door),
411 Err(e) => {
412 eprintln!("aien-serve-http: qwen36-batch load failed: {e}");
413 return ExitCode::from(1);
414 }
415 }
416 } else {
417 match qwen38_engine::Qwen38Door::load(&args.model_dir, max_context) {
418 Ok(door) => Arc::new(door),
419 Err(e) => {
420 eprintln!("aien-serve-http: qwen38 load failed: {e}");
421 return ExitCode::from(1);
422 }
423 }
424 }
425 } else if args.engine == "omega" {
426 eprintln!(
427 "aien-serve-http: loading {:?} weights onto the Omega engine from {} (spin {:?} us)",
428 args.weights,
429 args.model_dir.display(),
430 args.spin_us
431 );
432 match OmegaDoor::load(
433 &args.model_dir,
434 args.cfg.max_context_tokens.unwrap_or(32768),
435 args.weights,
436 args.spin_us,
437 args.prefill,
438 ) {
439 Ok(mut door) => {
440 // Persistent KV (sc#505): only when AIEN_KV_STORE_DIR was set at startup.
441 if let Some(settings) = persist_settings {
442 let line = enable_persistence(&mut door, settings, &args);
443 eprintln!("aien-serve-http: {line}");
444 }
445 Arc::new(door)
446 }
447 Err(e) => {
448 eprintln!("aien-serve-http: omega load failed: {e}");
449 return ExitCode::from(1);
450 }
451 }
452 } else {
453 let t0 = std::time::Instant::now();
454 eprintln!(
455 "aien-serve-http: loading CPU reference weights from {} (this takes minutes)",
456 args.model_dir.display()
457 );
458 match CpuReferenceEngine::load(
459 &args.model_dir,
460 args.cfg.max_context_tokens.unwrap_or(32768),
461 ) {
462 Ok(e) => {
463 eprintln!(
464 "aien-serve-http: weights loaded in {:.1} s",
465 t0.elapsed().as_secs_f64()
466 );
467 Arc::new(e)
468 }
469 Err(e) => {
470 eprintln!("aien-serve-http: {e}");
471 return ExitCode::from(1);
472 }
473 }
474 };
475
476 let rt = match tokio::runtime::Runtime::new() {
477 Ok(rt) => rt,
478 Err(e) => {
479 eprintln!("aien-serve-http: runtime: {e}");
480 return ExitCode::from(1);
481 }
482 };
483 // The eight readers (sc L371): on by default for a batching engine.
484 match aien_serve_http::readers::ReadersConfig::from_env(
485 &args.cfg.model_id,
486 engine.concurrency() > 1,
487 ) {
488 Ok(r) => {
489 if let Some(r) = &r {
490 eprintln!(
491 "aien-serve-http: readers: model id {} reads inputs over {} tokens in {} parts at once (notes up to {} tokens)",
492 r.model_id, r.threshold_tokens, r.readers, r.note_tokens
493 );
494 }
495 args.cfg.readers = r;
496 }
497 Err(e) => {
498 eprintln!("aien-serve-http: {e}");
499 return ExitCode::from(2);
500 }
501 }
502 rt.block_on(async move {
503 let model_id = args.cfg.model_id.clone();
504 // SIGTERM or SIGINT: stop accepting, let the request in flight finish, then drop the
505 // engine, which drains the persistent KV parks before the process exits (sc#509).
506 let keep = Arc::clone(&engine);
507 // The handlers are installed here, before "serving" is printed, so an early SIGTERM drains too.
508 let signals = shutdown_signals();
509 match serve_until(args.cfg, engine, codec, signals).await {
510 Ok((addr, handle)) => {
511 eprintln!(
512 "aien-serve-http: serving {model_id} at http://{addr}/v1 (engine {})",
513 args.engine
514 );
515 let _ = handle.await;
516 let t0 = std::time::Instant::now();
517 eprintln!("aien-serve-http: shutting down: no new requests; finishing the one in flight and draining persistent KV");
518 while Arc::strong_count(&keep) > 1 && t0.elapsed() < std::time::Duration::from_secs(600) {
519 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
520 }
521 drop(keep);
522 eprintln!("aien-serve-http: shutdown complete in {} ms", t0.elapsed().as_millis());
523 ExitCode::SUCCESS
524 }
525 Err(e) => {
526 eprintln!("aien-serve-http: bind failed: {e}");
527 ExitCode::from(1)
528 }
529 }
530 })
531}
532
533/// Opens the persistent KV store for the loaded omega engine (the checkpoint digest reads every
534/// weight file once). Returns the startup line; any problem refuses and the door runs plain.
535fn enable_persistence(
536 door: &mut OmegaDoor,
537 settings: Result<aien_runtime::shared_kv::KvPersistSettings, String>,
538 args: &Args,
539) -> String {
540 let t0 = std::time::Instant::now();
541 let build = kv_persist::OmegaBuild::linked();
542 let env: Vec<(String, String)> = std::env::vars().collect();
543 let config = door.config();
544 let identity = settings.as_ref().map_err(|e| e.clone()).and_then(|s| {
545 // No digest (minutes of reading) when the key already refuses: `open` reports the key.
546 if !matches!(s.store_key, Some(Ok(_))) {
547 return Err("the store key refused".to_string());
548 }
549 let rope_scaling = kv_persist::config_has_rope_scaling(&args.model_dir)?;
550 let (sha, kind) = kv_persist::checkpoint_digest(&args.model_dir)?;
551 kv_persist::OmegaKvIdentity::new(&kv_persist::IdentityInputs {
552 model_id: &args.cfg.model_id,
553 model_sha256: sha,
554 model_digest_kind: kind,
555 config: &config,
556 rope_scaling,
557 weights: args.weights,
558 switches: door.kv_switches(),
559 build: &build,
560 env: &env,
561 })
562 });
563 let fault = kv_persist::TestFault::from_lookup(|n| std::env::var(n).ok());
564 let (state, line) = kv_persist::open_with_test_fault(settings, identity, fault);
565 door.set_persistence(state);
566 format!("{line} [identity in {:.1} s]", t0.elapsed().as_secs_f64())
567}
568
569/// Installs the SIGTERM and SIGINT handlers now; the returned future resolves on the first one.
570fn shutdown_signals() -> impl std::future::Future<Output = ()> + Send + 'static {
571 use tokio::signal::unix::{signal, SignalKind};
572 let handlers = (
573 signal(SignalKind::terminate()),
574 signal(SignalKind::interrupt()),
575 );
576 async move {
577 let (Ok(mut term), Ok(mut int)) = handlers else {
578 eprintln!("aien-serve-http: cannot install the shutdown signal handlers; SIGTERM kills without draining");
579 return std::future::pending().await;
580 };
581 tokio::select! {
582 _ = term.recv() => eprintln!("aien-serve-http: SIGTERM received"),
583 _ = int.recv() => eprintln!("aien-serve-http: SIGINT received"),
584 }
585 }
586}