aion_server/run.rs
1//! Run loop for the Aion workflow server: tracing initialization,
2//! configuration load, transport startup, and signal-driven graceful
3//! shutdown.
4//!
5//! This is the library entry point behind the `aion server` command. It
6//! preserves the operational contract of the former standalone
7//! `aion-server` binary: exit code 2 for configuration errors, the drain
8//! outcome's exit code on shutdown, and 130 when a second termination
9//! signal forces immediate exit.
10
11use std::{net::SocketAddr, process::ExitCode};
12
13use tokio::net::TcpListener;
14use tonic::transport::Server as TonicServer;
15use tracing::{error, info, warn};
16
17use std::sync::Arc;
18
19use crate::{
20 ServerConfig, ServerError, ServerState, api,
21 config::{CliOverrides, NamespaceMode, OutboxConfig, OutboxTransport, StoreBackend},
22 observability,
23 shutdown::{self, ShutdownOutcome},
24 worker::{
25 ActivityDispatcher, DeliveryGate, OutboxDeliveryCallback, OutboxDispatcher,
26 OutboxDispatcherConfig, OutboxReconciler, OutboxReconcilerConfig, OutboxRowDispatch,
27 ServerOutboxDeliveryCallback, WorkerOutboxDispatch,
28 },
29};
30
31/// Short TTL for the dispatcher's per-namespace placement cache (Control-Plane
32/// Phase 2, P2-P3). Kept small so an operator's `PUT /namespaces/{name}/placement`
33/// takes effect on the hot claim loop within a couple of seconds, while still
34/// collapsing a per-sweep quorum `get_namespace` into a cheap in-process lookup.
35/// A stale entry under `Prefer` only mis-prefers a worker for at most one window
36/// and self-corrects — it never affects correctness or replay.
37const PLACEMENT_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
38
39/// Short TTL for the dispatcher's per-namespace quota cache (Control-Plane Phase 2,
40/// P2-Q2). Kept small so an operator raising/lowering a tenant's
41/// `max_in_flight_activities` takes effect on the hot claim loop within a couple of
42/// seconds, while still collapsing a per-sweep quorum `get_namespace` into a cheap
43/// in-process lookup. A stale entry only over- or under-admits slightly for one
44/// window and self-corrects — backpressure never drops a row, so it cannot affect
45/// correctness or replay.
46const QUOTA_CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
47
48/// Cadence of the ops-console quota-state broadcaster (Control-Plane Phase 2,
49/// P2-Q3). Each tick samples every registry namespace's durable Claimed-row count
50/// and cluster-wide ceiling, then pushes one `NamespaceQuotaState` per namespace
51/// onto the cluster channel, so the console badge tracks live load. Kept at 1s:
52/// brisk enough that the badge visibly ticks as work flows, throttled enough that
53/// it is never a per-row firehose (in-flight changes on every claim/settle). It is
54/// a server-side push on a timer, NOT a client poll — the dashboard rule bans the
55/// latter, not a throttled server snapshot of REAL durable state.
56const QUOTA_BROADCAST_CADENCE: std::time::Duration = std::time::Duration::from_secs(1);
57
58/// Resolved keyed-backpressure inputs for the outbox dispatcher (Control-Plane
59/// Phase 2, P2-Q2): the generous platform-default ceiling and this node's
60/// owned-shard fraction of the cluster shard space.
61#[derive(Clone, Copy, Debug)]
62struct BackpressureSettings {
63 /// The `[namespaces] max_in_flight_activities` platform default, applied to any
64 /// namespace carrying no explicit per-tenant override.
65 platform_default: u32,
66 /// This node's owned-shard fraction of the cluster's virtual shard space,
67 /// derived from `[store] owned_shards` and `[store] shard_count`.
68 fraction: crate::worker::OwnedShardFraction,
69}
70
71impl BackpressureSettings {
72 /// Derive the backpressure inputs from the merged server config.
73 ///
74 /// An empty `[store] owned_shards` means own-all (the single-node default), so
75 /// the fraction is 1 and per-node ceilings equal the cluster-wide quota. A
76 /// declared owned set enforces the proportional per-node slice
77 /// `|owned| / shard_count` (CP-Phase-2 §3.6).
78 fn from_config(config: &ServerConfig) -> Self {
79 let total = u32::try_from(config.store.shard_count).unwrap_or(u32::MAX);
80 let fraction = if config.store.owned_shards.is_empty() {
81 crate::worker::OwnedShardFraction::own_all()
82 } else {
83 let owned = u32::try_from(config.store.owned_shards.len()).unwrap_or(u32::MAX);
84 crate::worker::OwnedShardFraction::new(owned, total)
85 };
86 Self {
87 platform_default: config.namespaces.max_in_flight_activities,
88 fraction,
89 }
90 }
91}
92
93/// Owns the liminal worker listener for the server's lifetime when the outbox is
94/// commissioned over the liminal transport.
95///
96/// The aion-server HOSTS the liminal listener that remote workers connect IN to;
97/// its inner [`ServerListener`](liminal_server::server::listener::ServerListener)
98/// owns the accept worker. Held as a local in [`run_server`] across the whole
99/// serve `select!`, so it is dropped exactly at server shutdown — and the
100/// listener's own `Drop` stops the accept worker cleanly (no leaked thread, no
101/// orphaned listener). Every non-liminal boot (the default) carries the `None`
102/// guard, which holds nothing and drops to a no-op, so behaviour is unchanged.
103#[derive(Debug, Default)]
104struct OutboxWorkerListener {
105 /// Held purely for its `Drop` side-effect (stopping the accept worker on
106 /// server shutdown); never read after construction, hence the leading
107 /// underscore.
108 #[cfg(feature = "liminal-transport")]
109 _inner: Option<liminal_server::server::listener::ServerListener>,
110}
111
112/// Run the Aion workflow server until it shuts down, returning the process
113/// exit code.
114///
115/// Initializes the JSON tracing subscriber, loads and validates the merged
116/// configuration (file, environment, then `overrides`), serves the gRPC and
117/// HTTP transports, and drains gracefully after the first termination
118/// signal. Every failure is logged through tracing and mapped to the exit
119/// code contract above; the caller only has to exit with the returned code.
120pub async fn run(overrides: CliOverrides) -> ExitCode {
121 match run_server(overrides).await {
122 Ok(code) => code,
123 Err(error) => {
124 error!(%error, "aion-server failed");
125 if error.is_config() {
126 ExitCode::from(2)
127 } else {
128 ExitCode::FAILURE
129 }
130 }
131 }
132}
133
134async fn run_server(cli: CliOverrides) -> Result<ExitCode, ServerError> {
135 observability::tracing::init()?;
136
137 let loaded = ServerConfig::load_resolved(&cli)?;
138 loaded.resolution.ensure_private_home()?;
139 loaded.resolution.log_startup();
140 let config = loaded.config;
141 reject_auth_without_feature(&config)?;
142 let store_backend = config.store.backend;
143 // Static shard assignment (SS-1): read the operator's pinned shard set from
144 // `[store] owned_shards`. Empty means own ALL shards (single-node default).
145 // The set is carried into `RuntimeConfig` by `into_parts` and applied to the
146 // `EngineBuilder` during state construction; surface it here so the boot
147 // banner records which shards this node serves. No election is performed.
148 let owned_shards = config.store.owned_shards.clone();
149 // Capture the outbox settings before `build` consumes `config`, so the
150 // (default-off) outbox dispatcher can be wired after state is up. The
151 // dispatcher shares the engine's already-opened libSQL store (one
152 // connection) via `state.outbox_store()`, so no store settings are needed.
153 let outbox_config = config.outbox.clone();
154 // Control-Plane Phase 2 (P2-Q2): capture the keyed-backpressure inputs — the
155 // generous platform-default ceiling and this node's owned-shard fraction —
156 // before `build` consumes `config`. On a single-node / own-all boot the fraction
157 // is 1, so per-node ceilings equal the cluster-wide quota and, with the generous
158 // default and no tenant override, the ceiling never engages (byte-identical claim).
159 let backpressure_settings = BackpressureSettings::from_config(&config);
160 // Capture the SS-5b failover supervisor knobs before `build` consumes config.
161 // Only a distributed haematite boot carries a `[store.cluster]` section; this
162 // is `None` for every single-node boot, so no supervisor is ever spawned.
163 #[cfg(feature = "haematite-backend")]
164 let cluster_config = config.store.cluster.clone();
165 // Capture the managed-worker supervision policy before `build` consumes
166 // `config`. Resolution already happened during config validation, so this
167 // cannot surprise an operator at boot; it is re-read here because the
168 // policy is COMMISSIONED onto the supervisor built into state below, and a
169 // server without the section supervises nothing.
170 let supervision_policy = config.worker_supervision.resolve()?;
171 let state = ServerState::build(config).await?;
172 reject_tls_until_supported(&state)?;
173
174 let runtime = state.runtime_config();
175 let grpc_address = runtime.listen.grpc;
176 let http_address = runtime.listen.http;
177 let workflow_packages: Vec<String> = runtime
178 .workflow_packages
179 .iter()
180 .map(|path| path.display().to_string())
181 .collect();
182 // The revision, not just the version. A crate version cannot distinguish
183 // two builds from different commits of the same version, and that is the
184 // distinction an operator needs when deciding whether a restart restores
185 // what was running or substitutes something else (#123). The endpoint
186 // answers this too, but a crashed server leaves only its log.
187 let build = crate::build_identity::BuildIdentity::current();
188 // #139: the server-resolved workspace root (the aion home's `clones/`
189 // directory) that declared bodies expand `{workspace_root}` with. Reported
190 // here so composition points (setup.sh today, the workspace verb later)
191 // READ the value from the server that will use it instead of re-deriving
192 // it. An unresolvable root is reported as exactly that — never fabricated;
193 // a placeholder-bearing dispatch will refuse terminally with this reason.
194 // The rendering itself is `WorkspaceRoot::banner_value`, pinned by its own
195 // two-case test, so the banner and the tests cannot drift apart.
196 let workspace_root = state.workspace_root().banner_value();
197 info!(
198 version = env!("CARGO_PKG_VERSION"),
199 build = %build.line(),
200 commit = build.commit,
201 grpc_address = %grpc_address,
202 http_address = %http_address,
203 default_namespace = %runtime.default_namespace,
204 namespace_mode = namespace_mode_label(&runtime.namespace.mode),
205 store_backend = store_backend_label(store_backend),
206 auth_enabled = runtime.auth.enabled,
207 deploy_enabled = runtime.deploy.enabled,
208 metrics_enabled = runtime.metrics.enabled,
209 workspace_root = %workspace_root,
210 workflow_package_count = workflow_packages.len(),
211 workflow_packages = ?workflow_packages,
212 owned_shards = ?owned_shards,
213 owns_all_shards = owned_shards.is_empty(),
214 "aion-server startup banner"
215 );
216 // #139 leg C: the assistant ships IN aion. The embedded document is
217 // installed here — after the engine has reloaded every persisted package,
218 // so the install can see what is already resident, and before the
219 // transports accept traffic, so the first caller finds it. It claims only a
220 // catalog holding no version of the assistant type; anything else is the
221 // operator's cut to make, and the outcome says so in the log either way.
222 crate::assistant::install_embedded_assistant_for_server(&state).await;
223 let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
224 // LSUB-4-1: a distributed haematite boot carries a `[store.cluster]` section.
225 // The single outbox dispatcher task is spawned in BOTH modes; the difference
226 // is only how ownership is enforced. Single-node (`None`) owns all shards by
227 // construction (`owned_shard_scope() == None`), so its claim sweeps see every
228 // row. Clustered (`Some`) relies on `claim_outbox_rows`' `owned_shard_scope()`
229 // filter — already seeded by `set_owned_shards` during `ServerState::build`,
230 // which runs before this point — so each node only ever claims rows on the
231 // shards it owns. Compute the flag here where the (feature-gated) cluster
232 // section is in scope; pass it to the gate so the boot banner records the mode.
233 #[cfg(feature = "haematite-backend")]
234 let outbox_clustered = cluster_config.is_some();
235 #[cfg(not(feature = "haematite-backend"))]
236 let outbox_clustered = false;
237 // Dormant by default: only when `outbox.enabled` is set does the
238 // non-replayed outbox dispatcher task start. With the flag off (the
239 // default) nothing here runs and server behaviour is unchanged.
240 // Hold the liminal worker listener (if any) for the server's lifetime: it is
241 // dropped at the end of `run_server`, after the serve `select!` completes, so
242 // its accept worker stops cleanly on shutdown via the listener's own `Drop`.
243 // #204/#253: rebuild the pause dispatch-hold and settle terminal
244 // workflows' stranded outbox rows BEFORE the dispatcher's first claim.
245 rebuild_outbox_boot_state(&state, &outbox_config).await;
246 let _outbox_worker_listener = maybe_spawn_outbox_dispatcher(
247 &state,
248 &outbox_config,
249 outbox_clustered,
250 backpressure_settings,
251 &shutdown_rx,
252 )?;
253 // SS-5b: a distributed boot whose peers declare owned shards runs the cluster
254 // supervisor — automatic failover detection. A single-node boot spawns
255 // nothing here (the method returns `false`), so default behaviour is
256 // unchanged.
257 #[cfg(feature = "haematite-backend")]
258 maybe_spawn_cluster_supervisor(&state, cluster_config.as_ref(), &shutdown_rx)?;
259 // #176: the worker heartbeat expiry sweeper is ALWAYS commissioned —
260 // dead-worker detection is a liveness correctness property, not an opt-in
261 // feature. It is the production caller of `fail_expired_workers`: a worker
262 // whose stream stays open while its process wedges (stops heartbeating
263 // without disconnecting) is expired, deregistered with the provable Timeout
264 // reason, and its in-flight tasks surface as TRANSPORT losses, re-dispatched
265 // attempt-neutrally rather than charged to the action's retry budget.
266 // Cadence derives from `worker.heartbeat_window` (quarter-window, clamped to
267 // [1s, window]; the default 30s window sweeps every 7.5s) — deliberately no
268 // separate config knob. It drains on the same shutdown watch as the
269 // transports; dropping the JoinHandle only detaches the task.
270 drop(state.spawn_heartbeat_sweeper(shutdown_rx.clone()));
271 commission_worker_supervision(&state, supervision_policy).await;
272 let mut grpc = tokio::spawn(serve_grpc(state.clone(), grpc_address, shutdown_rx.clone()));
273 let mut http = tokio::spawn(serve_http(state.clone(), http_address, shutdown_rx));
274
275 let outcome = tokio::select! {
276 result = &mut grpc => {
277 transport_result("gRPC", result)?;
278 state.shutdown()?;
279 ShutdownOutcome::Clean
280 },
281 result = &mut http => {
282 transport_result("HTTP", result)?;
283 state.shutdown()?;
284 ShutdownOutcome::Clean
285 },
286 result = shutdown_signal() => {
287 result?;
288 let _receiver_count = shutdown_tx.send(true);
289 let outcome = shutdown::drain_after_first_signal(state.clone(), async {
290 let _ = shutdown_signal().await;
291 }).await?;
292 if !matches!(outcome, ShutdownOutcome::Forced) {
293 transport_result("gRPC", grpc.await)?;
294 transport_result("HTTP", http.await)?;
295 }
296 outcome
297 },
298 };
299
300 Ok(outcome.exit_code())
301}
302
303/// Install the operator's supervision policy and converge the fleet.
304///
305/// Uncommissioned is a first-class but never SILENT state: a server with no
306/// `[worker_supervision]` section supervises nothing, and every deployment that
307/// wanted to be running is named in the warning, so the gap between "the
308/// operator deployed a worker" and "nothing is running it" is never quiet.
309async fn commission_worker_supervision(
310 state: &ServerState,
311 policy: Option<crate::worker::SupervisionPolicy>,
312) {
313 let supervisor = state.worker_supervisor();
314 let Some(policy) = policy else {
315 match supervisor.report().await {
316 Ok(report) => {
317 let wanted: Vec<&str> = report
318 .workers
319 .iter()
320 .filter(|worker| worker.desired == aion_store::DesiredState::Running)
321 .map(|worker| worker.name.as_str())
322 .collect();
323 if wanted.is_empty() {
324 info!("managed-worker supervision is not configured; no deployment wants it");
325 } else {
326 warn!(
327 deployments = wanted.join(", "),
328 remedy = crate::worker::supervisor::UNCOMMISSIONED_REMEDY,
329 "worker deployments want to be running but supervision is not configured"
330 );
331 }
332 }
333 Err(error) => error!(
334 %error,
335 "managed-worker supervision is not configured and the deployment records \
336 could not be read to say what that costs"
337 ),
338 }
339 return;
340 };
341 if !supervisor.commission(policy, crate::worker::ManagedExecutable::CurrentServer) {
342 error!("managed-worker supervision was already commissioned before boot completed");
343 return;
344 }
345 match supervisor.reconcile().await {
346 Ok(0) => info!("managed-worker supervision commissioned; no deployment wants to run"),
347 Ok(supervised) => info!(supervised, "managed-worker supervision commissioned"),
348 Err(error) => error!(%error, "managed-worker fleet could not be converged at boot"),
349 }
350}
351
352fn transport_result(
353 transport: &'static str,
354 result: Result<Result<(), ServerError>, tokio::task::JoinError>,
355) -> Result<(), ServerError> {
356 match result {
357 Ok(transport_outcome) => transport_outcome,
358 Err(join_error) => Err(ServerError::Transport {
359 transport,
360 message: join_error.to_string(),
361 }),
362 }
363}
364
365async fn serve_grpc(
366 state: ServerState,
367 address: SocketAddr,
368 shutdown: tokio::sync::watch::Receiver<bool>,
369) -> Result<(), ServerError> {
370 let workflow = api::grpc::workflow_service(state.clone());
371 let worker = api::worker_grpc::worker_service(state.clone());
372 let mut router = TonicServer::builder()
373 .add_service(workflow)
374 .add_service(worker);
375 // Dark by default: the deploy service joins the listener only when the
376 // operator commissioned it; otherwise the surface answers Unimplemented.
377 if state.runtime_config().deploy.enabled {
378 router = router.add_service(api::deploy_grpc::deploy_service(state)?);
379 }
380 router
381 .serve_with_shutdown(address, shutdown_requested(shutdown))
382 .await
383 .map_err(|source| transport_bind("grpc", address, source))?;
384 Ok(())
385}
386
387async fn serve_http(
388 state: ServerState,
389 address: SocketAddr,
390 shutdown: tokio::sync::watch::Receiver<bool>,
391) -> Result<(), ServerError> {
392 let listener = TcpListener::bind(address)
393 .await
394 .map_err(|source| transport_bind("http", address, source))?;
395 axum::serve(listener, api::http::http_router(state)?)
396 .with_graceful_shutdown(shutdown_requested(shutdown))
397 .await
398 .map_err(|source| transport_bind("http", address, source))?;
399 Ok(())
400}
401
402async fn shutdown_requested(mut shutdown: tokio::sync::watch::Receiver<bool>) {
403 while !*shutdown.borrow_and_update() {
404 if shutdown.changed().await.is_err() {
405 break;
406 }
407 }
408}
409
410async fn shutdown_signal() -> Result<(), ServerError> {
411 #[cfg(unix)]
412 {
413 use tokio::signal::unix::{SignalKind, signal};
414
415 let mut terminate = signal(SignalKind::terminate())
416 .map_err(|source| signal_listener("SIGTERM", &source))?;
417 let mut interrupt =
418 signal(SignalKind::interrupt()).map_err(|source| signal_listener("SIGINT", &source))?;
419 tokio::select! {
420 _ = terminate.recv() => Ok(()),
421 _ = interrupt.recv() => Ok(()),
422 }
423 }
424
425 #[cfg(not(unix))]
426 {
427 tokio::signal::ctrl_c()
428 .await
429 .map_err(|source| signal_listener("shutdown signal", &source))
430 }
431}
432
433fn signal_listener(listener: &'static str, source: &std::io::Error) -> ServerError {
434 ServerError::SignalListener {
435 listener,
436 message: source.to_string(),
437 }
438}
439
440fn reject_auth_without_feature(config: &ServerConfig) -> Result<(), ServerError> {
441 if cfg!(not(feature = "auth")) && config.auth.enabled {
442 return Err(ServerError::Config {
443 message: "auth.enabled=true but binary compiled without auth feature".to_owned(),
444 });
445 }
446 Ok(())
447}
448
449/// Rebuild the outbox-related boot state BEFORE the dispatcher's first claim,
450/// when (and only when) the outbox is commissioned:
451///
452/// - #204: repopulate the durable pause dispatch-hold from `list_paused`, so a
453/// run paused before a restart keeps its outbox rows held (never claimed)
454/// after recovery. A run projecting `Paused` is excluded from `list_active`
455/// respawn for free; this repopulates the hold that would otherwise be empty
456/// in memory after a crash.
457/// - #253: settle terminal workflows' stranded outbox rows. A workflow that
458/// reached a durable terminal without its rows being settled (a settle-hook
459/// failure, or a crash between the terminal append and the settle) must not
460/// have those rows re-armed and redelivered after restart — that is the
461/// zombie-round incident. A sweep error is loud but non-fatal: the
462/// settle-at-terminal hook and the reconciler's liveness gate remain as
463/// repair paths, and the residual window is one bounded dispatch whose
464/// completion drops unmatched, never a re-arm loop.
465async fn rebuild_outbox_boot_state(state: &ServerState, outbox_config: &OutboxConfig) {
466 if !outbox_config.enabled {
467 return;
468 }
469 let Ok(engine) = state.engine() else {
470 return;
471 };
472 if let Err(error) = engine.rebuild_paused_runs().await {
473 warn!(%error, "failed to rebuild paused-runs dispatch hold at startup");
474 }
475 let Some(outbox_store) = state.outbox_store() else {
476 return;
477 };
478 match crate::worker::settle_terminal_outbox_rows(engine.store().as_ref(), outbox_store.as_ref())
479 .await
480 {
481 Ok(settled) if settled.is_empty() => {}
482 Ok(settled) => {
483 info!(
484 settled = settled.len(),
485 "boot sweep settled stranded outbox rows for terminal workflows"
486 );
487 }
488 Err(error) => {
489 error!(
490 %error,
491 "boot sweep failed to settle terminal workflows' outbox rows; \
492 the reconciler liveness gate remains the backstop"
493 );
494 }
495 }
496}
497
498/// Spawn the durable-outbox fan-out dispatcher when, and only when, the
499/// operator commissioned it (`outbox.enabled = true`).
500///
501/// This is the single gate that keeps Phase 2 dormant: with the flag off (the
502/// default) the function returns immediately without spawning a task, so
503/// default server behaviour — and the live workflow dispatch path — is entirely
504/// unchanged. When commissioned, the dispatcher claims rows through the engine's
505/// own shared `Arc<LibSqlStore>` (one `libsql::Connection`), so its writes
506/// serialize with the engine's rather than contending across a second
507/// connection. The dispatcher shares the server's shutdown watch, so it drains
508/// on the same signal as the transports.
509///
510/// NOTE (Phase boundary): the spawned dispatcher dispatches claimed rows and
511/// records each row's terminal outbox state (done / retry / failed). Routing the
512/// worker completion back into workflow history through the Recorder is Phase 3
513/// and is not wired here.
514fn maybe_spawn_outbox_dispatcher(
515 state: &ServerState,
516 outbox_config: &OutboxConfig,
517 clustered: bool,
518 backpressure_settings: BackpressureSettings,
519 shutdown_rx: &tokio::sync::watch::Receiver<bool>,
520) -> Result<OutboxWorkerListener, ServerError> {
521 if !outbox_config.enabled {
522 return Ok(OutboxWorkerListener::default());
523 }
524 let dispatcher_config = resolve_outbox_config(outbox_config)?;
525 // Share the engine's already-opened store: one backing connection. The
526 // dispatcher's `claim_outbox_rows` writes then serialize against the engine's
527 // `append_with_outbox` on that single connection instead of contending across
528 // a second one. Both the libSQL and the haematite backends provide an
529 // `OutboxStore` (the haematite leaf is wired as the outbox store at boot); the
530 // in-memory backend has no outbox table, so `outbox_store()` is `None` and
531 // commissioning the dispatcher against it is a configuration error (LSUB-4-2).
532 let outbox_store = state.outbox_store().ok_or_else(|| ServerError::Config {
533 message: "outbox.enabled=true requires store.backend=libsql or store.backend=haematite: \
534 the durable outbox dispatcher claims rows from the store's outbox table, which \
535 the in-memory store does not provide"
536 .to_owned(),
537 })?;
538 let dispatcher_builder = OutboxDispatcher::new(Arc::clone(&outbox_store), dispatcher_config);
539 let delivery_gate = dispatcher_builder.delivery_gate();
540 let engine = state.engine()?;
541 let delivery_callback: Arc<dyn OutboxDeliveryCallback> =
542 Arc::new(ServerOutboxDeliveryCallback::new(engine));
543 let (row_dispatch, worker_listener) = select_outbox_row_dispatch(
544 state,
545 outbox_config,
546 shutdown_rx,
547 delivery_gate.clone(),
548 Arc::clone(&delivery_callback),
549 )?;
550 // LSUB-2: share the engine's advisory wake so the stage seam pulses this
551 // dispatcher the instant a fan-out row commits, dispatching in ~RTT instead of
552 // up to one poll interval. The wake is always-on and free; the interval poll is
553 // untouched, so it remains the correctness backstop for any lost wake.
554 // Control-Plane Phase 2 (P2-Q2): attach per-tenant keyed backpressure so each
555 // sweep claims per-namespace, round-robin, capped at each tenant's CLAIMED-only
556 // headroom (`per_node_ceiling − claimed`). The quota cache front-runs a per-sweep
557 // quorum `get_namespace`. With the generous platform default and no tenant
558 // override the ceiling never engages, so a default deployment's claim behaviour is
559 // byte-identical to the pre-Phase-2 single unscoped claim.
560 let quota_cache = crate::worker::QuotaCache::new(
561 Arc::clone(state.namespace_store()),
562 backpressure_settings.platform_default,
563 QUOTA_CACHE_TTL,
564 );
565 let backpressure =
566 crate::worker::Backpressure::new(quota_cache.clone(), backpressure_settings.fraction);
567 let mut dispatcher = dispatcher_builder
568 .with_dispatch(row_dispatch)
569 .with_delivery_callback(delivery_callback)
570 .with_wake(state.outbox_wake())
571 .with_backpressure(backpressure);
572 // #204: attach the engine's durable pause dispatch-hold so a held (paused)
573 // run's rows are never claimed. The hold set is rebuilt from `list_paused`
574 // BEFORE this spawn (see `run_server`), so the dispatcher's first claim
575 // already excludes pre-pause rows after a restart.
576 if let Ok(engine) = state.engine() {
577 dispatcher = dispatcher.with_paused_runs(engine.paused_runs());
578 }
579 tokio::spawn(dispatcher.run(shutdown_rx.clone()));
580 // Control-Plane Phase 2 (P2-Q3): commission the ops-console quota-state
581 // broadcaster on the SAME durable stores + quota cache the dispatcher enforces
582 // against, so the console badge is a faithful window onto the live per-tenant
583 // in-flight/ceiling the backpressure caps. It shares the shutdown watch, so it
584 // drains with the dispatcher. Only spawned alongside the (default-off)
585 // dispatcher: quota state is meaningless without the outbox fan-out path, and
586 // `in_flight` is the durable Claimed outbox count that path produces.
587 let quota_broadcaster = crate::worker::QuotaBroadcaster::new(
588 Arc::clone(state.namespace_store()),
589 Arc::clone(&outbox_store),
590 quota_cache,
591 state.cluster_publisher().clone(),
592 QUOTA_BROADCAST_CADENCE,
593 );
594 tokio::spawn(quota_broadcaster.run(shutdown_rx.clone()));
595 // LSUB-4-1: the single dispatcher task is spawned in both modes. In a
596 // single-node boot it owns all shards by construction; in an active-active
597 // clustered boot it claims ONLY the shards this node owns, enforced by
598 // `claim_outbox_rows`' owned-shard scope (already seeded before this point).
599 info!(
600 clustered,
601 "outbox dispatcher commissioned (active-active per-shard ownership enforced by claim scope \
602 when clustered; single-node owns all shards)"
603 );
604 // LSUB-4-4: the stale-claim reconciler is the in-flight recovery backstop. It
605 // is only configured when BOTH reconcile knobs are set, so on a clustered boot
606 // that left them unset, owner-kill in-flight recovery latency is bounded only
607 // by re-residency replay (a survivor adopting the shard re-residents from
608 // history and re-arms via `rearm_outbox_pending`), NOT by `stale_after`. Warn
609 // so the operator knows the backstop is absent.
610 if let Some(reconciler_config) = resolve_outbox_reconciler_config(outbox_config)? {
611 // #253: the reconciler's liveness gate projects each stale candidate's
612 // workflow status from the engine's event store before any re-arm, so
613 // a terminal workflow's stranded row settles instead of redelivering.
614 let event_store = state.engine()?.store();
615 let reconciler = OutboxReconciler::new(outbox_store, event_store, reconciler_config)
616 .with_delivery_gate(delivery_gate);
617 tokio::spawn(reconciler.run(shutdown_rx.clone()));
618 info!("outbox reconciler commissioned (terminal-workflow liveness gate active)");
619 } else if clustered {
620 warn!(
621 "outbox reconciler is UNCONFIGURED on a clustered boot (outbox.reconcile_interval_ms \
622 and outbox.reconcile_stale_after_ms are both unset): in-flight recovery after an \
623 owner is killed is then bounded only by re-residency replay on the adopting node, \
624 not by a stale-claim backstop; set both knobs to bound stale-claim recovery latency"
625 );
626 }
627 Ok(worker_listener)
628}
629
630/// Spawn the SS-5b cluster supervisor when, and only when, this is a distributed
631/// haematite boot whose `[store.cluster]` declared peers with owned shards.
632///
633/// Reads the failover cadence + debounce from the cluster config (or the
634/// documented defaults), then asks the state to spawn the supervisor over its
635/// retained concrete store and live engine. With no `[store.cluster]` section —
636/// or with no peer declaring `owned_shards` — nothing is spawned and behaviour
637/// is unchanged.
638#[cfg(feature = "haematite-backend")]
639fn maybe_spawn_cluster_supervisor(
640 state: &ServerState,
641 cluster_config: Option<&crate::config::ClusterConfig>,
642 shutdown_rx: &tokio::sync::watch::Receiver<bool>,
643) -> Result<(), ServerError> {
644 let Some(cluster) = cluster_config else {
645 return Ok(());
646 };
647 let poll_interval = std::time::Duration::from_millis(
648 cluster
649 .failover_poll_interval_ms
650 .unwrap_or(crate::config::DEFAULT_FAILOVER_POLL_INTERVAL_MS),
651 );
652 let confirmations = cluster
653 .failover_confirmations
654 .unwrap_or(crate::config::DEFAULT_FAILOVER_CONFIRMATIONS);
655 let supervisor_config = crate::cluster::SupervisorConfig {
656 poll_interval,
657 confirmations,
658 };
659 let spawned = state.spawn_cluster_supervisor(supervisor_config, shutdown_rx.clone())?;
660 if spawned {
661 info!(
662 poll_interval_ms = %poll_interval.as_millis(),
663 confirmations,
664 "SS-5b cluster supervisor commissioned (automatic peer-down failover)"
665 );
666 }
667 Ok(())
668}
669
670/// Select the outbox row-dispatch sink by the configured `outbox.transport`,
671/// returning the sink plus the worker listener whose lifetime the caller must
672/// hold.
673///
674/// `grpc` (the default) builds the unchanged [`WorkerOutboxDispatch`] over the
675/// connected-worker registry and carries the empty [`OutboxWorkerListener`], so a
676/// default server is byte-identical. `liminal` builds the cross-node
677/// [`RegistryLiminalDispatch`](crate::worker::RegistryLiminalDispatch) AND stands
678/// up the liminal worker listener the aion-server hosts (returned in the guard);
679/// it is only reachable when the `liminal-transport` feature is compiled in, and
680/// selecting it without that feature is a configuration error rather than a
681/// silent fall-through to gRPC.
682fn select_outbox_row_dispatch(
683 state: &ServerState,
684 outbox_config: &OutboxConfig,
685 shutdown_rx: &tokio::sync::watch::Receiver<bool>,
686 delivery_gate: DeliveryGate,
687 delivery_callback: Arc<dyn OutboxDeliveryCallback>,
688) -> Result<(Arc<dyn OutboxRowDispatch>, OutboxWorkerListener), ServerError> {
689 match outbox_config.transport {
690 OutboxTransport::Grpc => {
691 let push_dispatcher = ActivityDispatcher::new(state.worker_registry().clone())
692 .with_drain_state(state.drain_state().clone())
693 .with_completion_fences(state.pending_activities().completion_fences())
694 // Share the SAME queue-service seams the direct dispatch path
695 // uses, so a row parked on this leg reaches `GET
696 // /queues/unserved` and `describe`'s `unserved` list rather
697 // than being invisible to both.
698 .with_queue_service(
699 state.queue_declarations().clone(),
700 state.queue_service_state().clone(),
701 state.runtime_config().worker.queue_service.clone(),
702 );
703 // Control-Plane Phase 2 (P2-P3): attach the short-TTL placement cache
704 // so an unpinned row in a `Prefer{L}` namespace prefers an L-labelled
705 // worker (spilling to any live worker). The cache front-runs a per-row
706 // quorum `get_namespace` on the hot claim loop; a default-`Unplaced`
707 // deployment is byte-identical (every row falls through to any-worker).
708 let placement_cache = crate::worker::PlacementCache::new(
709 Arc::clone(state.namespace_store()),
710 PLACEMENT_CACHE_TTL,
711 );
712 let dispatch: Arc<dyn OutboxRowDispatch> = Arc::new(
713 WorkerOutboxDispatch::new(push_dispatcher).with_placement_cache(placement_cache),
714 );
715 Ok((dispatch, OutboxWorkerListener::default()))
716 }
717 OutboxTransport::Liminal => build_liminal_row_dispatch(
718 state,
719 outbox_config,
720 shutdown_rx,
721 delivery_gate,
722 delivery_callback,
723 ),
724 }
725}
726
727/// Build the production liminal row-dispatch sink and host the worker listener, or
728/// fail with the missing-feature error.
729///
730/// This lifts the tested cross-node wiring (the `lsub1`/`lsub5` e2e blueprint)
731/// into the production boot. The aion-server HOSTS the liminal listener that
732/// remote workers connect IN to, so its
733/// [`ConnectionSupervisor`](liminal_server::server::connection::ConnectionSupervisor)
734/// owns each worker's connection and can push a dispatch out on it. The
735/// constructor cycle resolves the notifier <-> supervisor dependency:
736///
737/// 1. Reuse the registry already in [`ServerState`] — gRPC and liminal workers
738/// share ONE registry and the same `select_worker`, so routing is identical.
739/// 2. Build the [`LiminalConnectionNotifier`] over that registry (no supervisor
740/// yet).
741/// 3. Build the [`LiminalConnectionServices`] from the liminal listen config.
742/// 4. Build the [`ConnectionSupervisor`] WITH the services + notifier.
743/// 5. Bind the supervisor back into the notifier (must succeed).
744/// 6. Bind the [`ServerListener`] on the configured listen address — workers
745/// connect IN here.
746/// 7. Reuse the SAME completion callback the gRPC completion path installs
747/// ([`ServerOutboxDeliveryCallback`] over the live engine), so a liminal
748/// completion re-enters aion through the identical terminal-recording seam.
749/// 8. Build the [`RegistryLiminalDispatch`] over the registry + callback (it
750/// constructs the [`LiminalCompletionSource`] internally).
751///
752/// The returned listener is held by the caller for the server's lifetime; its
753/// `Drop` stops the accept worker on shutdown.
754///
755/// [`LiminalConnectionServices`]: liminal_server::server::connection::LiminalConnectionServices
756/// [`ServerListener`]: liminal_server::server::listener::ServerListener
757/// [`ServerOutboxDeliveryCallback`]: crate::worker::ServerOutboxDeliveryCallback
758/// [`LiminalCompletionSource`]: crate::worker::LiminalCompletionSource
759/// [`LiminalConnectionNotifier`]: crate::worker::LiminalConnectionNotifier
760#[cfg(feature = "liminal-transport")]
761fn build_liminal_row_dispatch(
762 state: &ServerState,
763 outbox_config: &OutboxConfig,
764 shutdown_rx: &tokio::sync::watch::Receiver<bool>,
765 delivery_gate: DeliveryGate,
766 callback: Arc<dyn OutboxDeliveryCallback>,
767) -> Result<(Arc<dyn OutboxRowDispatch>, OutboxWorkerListener), ServerError> {
768 use liminal_server::config::ServerConfig as LiminalServerConfig;
769 use liminal_server::config::{LimitsConfig, ServicesConfig};
770 use liminal_server::server::connection::{ConnectionSupervisor, LiminalConnectionServices};
771 use liminal_server::server::listener::ServerListener;
772
773 use crate::worker::{LiminalConnectionNotifier, RegistryLiminalDispatch};
774
775 let listen_address = outbox_config
776 .liminal_listen_address
777 .as_ref()
778 .ok_or_else(|| ServerError::Config {
779 message: "outbox.transport=liminal requires outbox.liminal_listen_address \
780 (host:port the aion-server listens on for inbound liminal worker \
781 connections)"
782 .to_owned(),
783 })?;
784 let listen_address: SocketAddr =
785 listen_address
786 .parse()
787 .map_err(|error| ServerError::Config {
788 message: format!(
789 "outbox.liminal_listen_address must be a host:port socket address: {error}"
790 ),
791 })?;
792
793 // The liminal listener is the worker-connection front door only: it binds the
794 // wire listen address and serves the connection supervisor. `from_config` and
795 // `ServerListener::bind` read neither `health_listen_address` nor `channels`
796 // (the health probe is bound only by the standalone liminal server's full
797 // boot, not this embedded path), so no separate health port is bound here;
798 // it is set structurally to the listen address and never used.
799 let liminal_config = LiminalServerConfig {
800 listen_address,
801 health_listen_address: listen_address,
802 drain_timeout_ms: 30_000,
803 channels: Vec::new(),
804 routing_rules: Vec::new(),
805 persistence_path: None,
806 cluster: None,
807 // liminal 0.2.3 (H4) added an optional shared-token Connect gate. `None`
808 // keeps this embedded worker front door open at the liminal layer —
809 // identical to the pre-0.2.3 wire behavior; worker identity/authorization
810 // stays aion's job (x-aion-* registration metadata). Threading an
811 // operator-configured token through aion's outbox config is a separate
812 // feature decision, not part of the dependency alignment.
813 auth: None,
814 // liminal 0.2.4 (D2/§5): service profile + operational bounds. Defaults =
815 // full profile + the certifying-pair-signed caps — byte-equivalent to the
816 // 0.2.3 behaviour this embedded front door always had. A worker-front-door
817 // profile election here is a future feature decision, not this migration.
818 services: ServicesConfig::default(),
819 limits: LimitsConfig::default(),
820 // liminal 0.3.0 (LP-WS-TRANSPORT R1 / LP Part B): optional WebSocket
821 // acceptor and participant lifecycle activation. `None` for both starts
822 // no WebSocket listener and leaves the participant capability disabled —
823 // documented as byte-identical to the pre-0.3.0 build. Electing either
824 // for this embedded worker front door is a feature decision, not part of
825 // the dependency alignment.
826 websocket: None,
827 participant: None,
828 };
829
830 // (1) Reuse the registry already in ServerState: gRPC + liminal workers share
831 // ONE registry and the same `select_worker`.
832 let registry = state.worker_registry().clone();
833 // (2) Notifier over that registry (supervisor bound after it is built), with the
834 // NOI-5b transcript tap: a worker's observability publishes on the reserved
835 // channel drain into the SAME transcript sequencer the transcript socket serves,
836 // so a live agent's transcript is persisted + fanned out. (Captures the current
837 // runtime handle to bridge the sync connection callback onto the async append.)
838 let notifier = Arc::new(
839 LiminalConnectionNotifier::new(registry.clone())
840 .with_contract_catalog(state.engine()?)
841 .with_transcript_publisher(state.transcript_publisher().clone())
842 // The SAME per-task liveness tracker the engine-seam bridge tracks
843 // into: a liminal worker's automatic liveness beats refresh it, so
844 // the #176 expiry sweeper never falsely expires a healthy liminal
845 // worker running an activity longer than the heartbeat window.
846 .with_heartbeat_tracker(state.heartbeat_tracker().clone()),
847 );
848 // (3) Connection services from the liminal listen config.
849 let services = Arc::new(
850 LiminalConnectionServices::from_config(&liminal_config).map_err(|error| {
851 ServerError::Config {
852 message: format!("liminal connection services build failed: {error}"),
853 }
854 })?,
855 );
856 // (4) Supervisor WITH the services + notifier (the cycle's forward edge).
857 let supervisor = ConnectionSupervisor::with_services_and_notifier(services, notifier.clone())
858 .map_err(|error| ServerError::Config {
859 message: format!("liminal connection supervisor build failed: {error}"),
860 })?;
861 // (5) Bind the supervisor back into the notifier (the cycle's back edge); a
862 // failure here is a wiring bug, surfaced rather than silently ignored.
863 if !notifier.bind_supervisor(supervisor.clone()) {
864 return Err(ServerError::Config {
865 message: "liminal notifier supervisor handle was already bound during boot".to_owned(),
866 });
867 }
868 // (5b) Commission the connection dead-man switch over the SAME notifier. It
869 // pings every connected worker on a derived quarter-window cadence: the
870 // answers keep a healthy IDLE connection's lease alive (so the idle expiry
871 // cannot fire on a live worker), and the pings themselves are what a worker
872 // measures silence against (so a wedged half-open socket becomes a declared,
873 // logged death on the worker side instead of an unbounded blind wait). Not
874 // opt-in: liveness detection is a correctness property of this transport.
875 // The handle is detached — dropping a tokio `JoinHandle` never cancels the
876 // task — exactly as the heartbeat sweeper is spawned.
877 drop(state.spawn_liminal_liveness_probe(notifier.clone(), shutdown_rx.clone()));
878 // (6) Bind the listener on the configured address — workers connect IN here.
879 let listener =
880 ServerListener::bind(&liminal_config, supervisor).map_err(|error| ServerError::Config {
881 message: format!("liminal worker listener failed to bind {listen_address}: {error}"),
882 })?;
883 // (7) Reuse the SAME completion callback the gRPC completion path uses, over
884 // the live engine, so a liminal completion re-enters aion through the
885 // identical terminal-recording seam (`record_fan_out_completion`).
886 // (8) The registry-backed dispatch builds its LiminalCompletionSource from the
887 // shared callback internally. Attach the SAME short-TTL placement cache the
888 // gRPC arm installs (Control-Plane Phase 2, P2-P3), so an unpinned row in a
889 // `Prefer{L}` namespace prefers an L-labelled worker (spilling to any live
890 // worker) on the cross-node liminal transport too — the cluster-failover
891 // demo behaviour. A default-`Unplaced` deployment is byte-identical.
892 let placement_cache = crate::worker::PlacementCache::new(
893 Arc::clone(state.namespace_store()),
894 PLACEMENT_CACHE_TTL,
895 );
896 // NOI-6: install the SAME attempt-owner back-index the server's intervention
897 // router resolves through, so each dispatched agent attempt binds its owning
898 // worker and a pushed command reaches the worker this dispatcher sent it to.
899 let dispatch: Arc<dyn OutboxRowDispatch> = Arc::new(
900 RegistryLiminalDispatch::new(registry, callback, delivery_gate)
901 .with_placement_cache(placement_cache)
902 .with_attempt_owners(state.attempt_owners().clone()),
903 );
904
905 info!(
906 listen_address = %listen_address,
907 "liminal outbox worker listener commissioned (remote workers connect in and self-register)"
908 );
909 Ok((
910 dispatch,
911 OutboxWorkerListener {
912 _inner: Some(listener),
913 },
914 ))
915}
916
917/// Feature-off stub: selecting the liminal transport without the
918/// `liminal-transport` feature is a configuration error, never a silent
919/// fall-through to gRPC.
920#[cfg(not(feature = "liminal-transport"))]
921fn build_liminal_row_dispatch(
922 _state: &ServerState,
923 _outbox_config: &OutboxConfig,
924 _shutdown_rx: &tokio::sync::watch::Receiver<bool>,
925 _delivery_gate: DeliveryGate,
926 _delivery_callback: Arc<dyn OutboxDeliveryCallback>,
927) -> Result<(Arc<dyn OutboxRowDispatch>, OutboxWorkerListener), ServerError> {
928 Err(ServerError::Config {
929 message: "outbox.transport=liminal requires the aion-server `liminal-transport` \
930 Cargo feature, which is not enabled in this build"
931 .to_owned(),
932 })
933}
934
935/// Resolve the validated, all-present outbox knobs into the dispatcher's
936/// non-optional config. Validation already guaranteed each value is set and in
937/// range when `outbox.enabled` is true, so an absent value here is a defensive
938/// configuration error, not a default to invent.
939fn resolve_outbox_config(outbox: &OutboxConfig) -> Result<OutboxDispatcherConfig, ServerError> {
940 let poll_interval_ms = outbox.poll_interval_ms.ok_or_else(|| ServerError::Config {
941 message: crate::config::OUTBOX_POLL_INTERVAL_REQUIRED.to_owned(),
942 })?;
943 let batch_size = outbox.batch_size.ok_or_else(|| ServerError::Config {
944 message: crate::config::OUTBOX_BATCH_SIZE_REQUIRED.to_owned(),
945 })?;
946 let max_attempts = outbox.max_attempts.ok_or_else(|| ServerError::Config {
947 message: crate::config::OUTBOX_MAX_ATTEMPTS_REQUIRED.to_owned(),
948 })?;
949 let backoff_base_ms = outbox.backoff_base_ms.ok_or_else(|| ServerError::Config {
950 message: crate::config::OUTBOX_BACKOFF_BASE_REQUIRED.to_owned(),
951 })?;
952 let backoff_multiplier = outbox
953 .backoff_multiplier
954 .ok_or_else(|| ServerError::Config {
955 message: crate::config::OUTBOX_BACKOFF_MULTIPLIER_REQUIRED.to_owned(),
956 })?;
957 let backoff_max_ms = outbox.backoff_max_ms.ok_or_else(|| ServerError::Config {
958 message: crate::config::OUTBOX_BACKOFF_MAX_REQUIRED.to_owned(),
959 })?;
960 Ok(OutboxDispatcherConfig {
961 poll_interval: std::time::Duration::from_millis(poll_interval_ms),
962 batch_size,
963 max_attempts,
964 backoff_base: std::time::Duration::from_millis(backoff_base_ms),
965 backoff_multiplier,
966 backoff_max: std::time::Duration::from_millis(backoff_max_ms),
967 })
968}
969
970fn resolve_outbox_reconciler_config(
971 outbox: &OutboxConfig,
972) -> Result<Option<OutboxReconcilerConfig>, ServerError> {
973 let (Some(interval_ms), Some(stale_after_ms)) = (
974 outbox.reconcile_interval_ms,
975 outbox.reconcile_stale_after_ms,
976 ) else {
977 return Ok(None);
978 };
979 let batch_size = outbox.batch_size.ok_or_else(|| ServerError::Config {
980 message: crate::config::OUTBOX_BATCH_SIZE_REQUIRED.to_owned(),
981 })?;
982 Ok(Some(OutboxReconcilerConfig {
983 interval: std::time::Duration::from_millis(interval_ms),
984 stale_after: std::time::Duration::from_millis(stale_after_ms),
985 batch_size,
986 }))
987}
988
989fn reject_tls_until_supported(state: &ServerState) -> Result<(), ServerError> {
990 if state.runtime_config().tls.is_some() {
991 return Err(ServerError::Config {
992 message: "configured TLS material cannot be served until transport TLS is wired"
993 .to_owned(),
994 });
995 }
996 Ok(())
997}
998
999fn store_backend_label(backend: StoreBackend) -> &'static str {
1000 match backend {
1001 StoreBackend::Memory => "memory",
1002 StoreBackend::LibSql => "libsql",
1003 StoreBackend::Haematite => "haematite",
1004 }
1005}
1006
1007fn namespace_mode_label(mode: &NamespaceMode) -> &'static str {
1008 match mode {
1009 NamespaceMode::SharedEngine => "SharedEngine",
1010 NamespaceMode::SingleTenant { .. } => "SingleTenant",
1011 }
1012}
1013
1014fn transport_bind<E>(transport: &'static str, address: SocketAddr, source: E) -> ServerError
1015where
1016 E: std::error::Error,
1017{
1018 ServerError::TransportBind {
1019 transport,
1020 address,
1021 message: source.to_string(),
1022 }
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027 #![allow(clippy::expect_used)]
1028
1029 use super::{
1030 BackpressureSettings, OutboxConfig, OutboxTransport, maybe_spawn_outbox_dispatcher,
1031 resolve_outbox_reconciler_config,
1032 };
1033 use crate::ServerState;
1034 use crate::config::RuntimeConfig;
1035 use aion_store::InMemoryStore;
1036 use std::net::SocketAddr;
1037 use std::time::Duration;
1038
1039 /// Own-all, generous-default backpressure settings for the gate tests (the
1040 /// single-node default: fraction 1, so the ceiling never engages).
1041 fn test_backpressure_settings() -> BackpressureSettings {
1042 BackpressureSettings {
1043 platform_default: crate::config::DEFAULT_MAX_IN_FLIGHT_ACTIVITIES,
1044 fraction: crate::worker::OwnedShardFraction::own_all(),
1045 }
1046 }
1047
1048 /// A minimal `RuntimeConfig` for building an in-memory `ServerState` in unit
1049 /// tests (mirrors `state.rs`'s test `runtime_config`).
1050 fn runtime_config() -> RuntimeConfig {
1051 use crate::config::{
1052 AuthConfig, AuthoringConfig, DeployConfig, DevConfig, ListenConfig, MetricsConfig,
1053 NamespaceConfig, NamespaceMode, OpsConsoleAssetSource, OpsConsoleConfig,
1054 WebSocketConfig, WorkerConfig,
1055 };
1056 RuntimeConfig {
1057 listen: ListenConfig {
1058 grpc: SocketAddr::from(([127, 0, 0, 1], 50051)),
1059 http: SocketAddr::from(([127, 0, 0, 1], 8080)),
1060 },
1061 tls: None,
1062 auth: AuthConfig {
1063 enabled: false,
1064 jwks_url: None,
1065 jwks_refresh_seconds: 300,
1066 },
1067 ops_console: OpsConsoleConfig {
1068 source: OpsConsoleAssetSource::Embedded,
1069 },
1070 namespace: NamespaceConfig {
1071 mode: NamespaceMode::SharedEngine,
1072 },
1073 worker: WorkerConfig {
1074 heartbeat_window: Duration::from_secs(30),
1075 ..WorkerConfig::default()
1076 },
1077 websocket: WebSocketConfig {
1078 outbound_buffer_bound: 32,
1079 event_broadcast_capacity: Some(64),
1080 cluster_broadcast_capacity: Some(64),
1081 },
1082 workflow_packages: Vec::new(),
1083 deploy: DeployConfig::default(),
1084 authoring: AuthoringConfig::default(),
1085 dev: DevConfig::default(),
1086 outbox: OutboxConfig::default(),
1087 observability: crate::config::ObservabilityConfig::default(),
1088 mcp: crate::config::ResolvedMcpConfig::default(),
1089 scheduler_threads: 1,
1090 query_timeout: Some(Duration::from_secs(10)),
1091 default_namespace: "default".to_owned(),
1092 auto_create: crate::config::AutoCreate::Open,
1093 max_in_flight_activities: crate::config::DEFAULT_MAX_IN_FLIGHT_ACTIVITIES,
1094 drain_timeout: Duration::from_secs(30),
1095 metrics: MetricsConfig { enabled: true },
1096 owned_shards: Vec::new(),
1097 cors_allowed_origins: Vec::new(),
1098 }
1099 }
1100
1101 /// An `OutboxConfig` with `enabled = true` and every required knob present, so
1102 /// the only remaining gate is the store-backend / outbox-table availability.
1103 fn enabled_outbox_config() -> OutboxConfig {
1104 OutboxConfig {
1105 enabled: true,
1106 poll_interval_ms: Some(250),
1107 batch_size: Some(64),
1108 max_attempts: Some(5),
1109 backoff_base_ms: Some(100),
1110 backoff_multiplier: Some(2),
1111 backoff_max_ms: Some(30_000),
1112 reconcile_interval_ms: None,
1113 reconcile_stale_after_ms: None,
1114 transport: OutboxTransport::Grpc,
1115 liminal_listen_address: None,
1116 }
1117 }
1118
1119 /// LSUB-4-2 / LSUB-4-6 (Memory-backend guard): commissioning the outbox
1120 /// dispatcher against the in-memory backend (which has no outbox table, so
1121 /// `outbox_store()` is `None`) is a configuration error, and the message names
1122 /// BOTH supported backends (libsql / haematite), not just libsql.
1123 #[tokio::test]
1124 async fn outbox_enabled_on_memory_backend_is_a_config_error() {
1125 let state = ServerState::build_with_store(InMemoryStore::default(), runtime_config())
1126 .await
1127 .expect("build in-memory state");
1128 let (_tx, rx) = tokio::sync::watch::channel(false);
1129 let error = maybe_spawn_outbox_dispatcher(
1130 &state,
1131 &enabled_outbox_config(),
1132 false,
1133 test_backpressure_settings(),
1134 &rx,
1135 )
1136 .expect_err("outbox.enabled on the memory backend must be a config error");
1137 assert!(
1138 error.is_config(),
1139 "memory-backend outbox error must be Config"
1140 );
1141 let message = error.to_string();
1142 assert!(
1143 message.contains("libsql") && message.contains("haematite"),
1144 "corrected message must name both supported backends, got: {message}"
1145 );
1146 }
1147
1148 /// LSUB-4-1 (Fork-B fast path): with the outbox disabled (the default), the
1149 /// gate is a no-op even on a memory backend — nothing is spawned and no error
1150 /// is produced, so a default single-node boot is unchanged.
1151 #[tokio::test]
1152 async fn disabled_outbox_is_a_noop_on_any_backend() {
1153 let state = ServerState::build_with_store(InMemoryStore::default(), runtime_config())
1154 .await
1155 .expect("build in-memory state");
1156 let (_tx, rx) = tokio::sync::watch::channel(false);
1157 maybe_spawn_outbox_dispatcher(
1158 &state,
1159 &OutboxConfig::default(),
1160 false,
1161 test_backpressure_settings(),
1162 &rx,
1163 )
1164 .expect("disabled outbox gate must be an infallible no-op");
1165 }
1166
1167 /// LSUB-4-4: the reconciler config resolves to `None` unless BOTH knobs are
1168 /// set — the condition under which the clustered-boot WARN fires.
1169 #[test]
1170 fn reconciler_config_absent_unless_both_knobs_set() {
1171 let mut config = enabled_outbox_config();
1172 // Neither knob: absent.
1173 assert!(
1174 resolve_outbox_reconciler_config(&config)
1175 .expect("resolve")
1176 .is_none()
1177 );
1178 // Only interval: still absent (the silent-backstop-absent default).
1179 config.reconcile_interval_ms = Some(1_000);
1180 assert!(
1181 resolve_outbox_reconciler_config(&config)
1182 .expect("resolve")
1183 .is_none()
1184 );
1185 // Both set: present.
1186 config.reconcile_stale_after_ms = Some(60_000);
1187 assert!(
1188 resolve_outbox_reconciler_config(&config)
1189 .expect("resolve")
1190 .is_some()
1191 );
1192 }
1193
1194 /// LSUB-PROD (13-6): the liminal transport requires `liminal_listen_address`.
1195 /// Commissioning the dispatcher with `transport = liminal` but no listen
1196 /// address is a configuration error naming the missing knob, rather than a
1197 /// panic or a silent fall-through to gRPC. Built over the libSQL backend (so
1198 /// the outbox-store gate passes and the missing-address check is actually
1199 /// reached). (Feature-gated: the liminal arm of `build_liminal_row_dispatch`
1200 /// only exists with `liminal-transport` on; in a feature-off build the same
1201 /// selection is the missing-feature error instead, covered by the type system
1202 /// rather than this test.)
1203 // Also gated on `libsql-backend`: it boots a real libSQL-backed `ServerState`
1204 // to obtain an outbox-bearing store, and the libSQL connect path is now an
1205 // opt-in feature. The listen-address guard itself is backend-agnostic.
1206 #[cfg(all(feature = "liminal-transport", feature = "libsql-backend"))]
1207 #[tokio::test]
1208 async fn liminal_transport_requires_listen_address() {
1209 use crate::config::{
1210 RuntimeSection, ServerConfig, StoreBackend, StoreConfig, WebSocketConfig,
1211 };
1212
1213 let db_path = std::env::temp_dir().join(format!(
1214 "aion-lsub-prod-listen-guard-{}-{}.db",
1215 std::process::id(),
1216 std::time::SystemTime::now()
1217 .duration_since(std::time::UNIX_EPOCH)
1218 .map(|elapsed| elapsed.as_nanos())
1219 .unwrap_or_default()
1220 ));
1221 let mut outbox = enabled_outbox_config();
1222 outbox.transport = OutboxTransport::Liminal;
1223 outbox.liminal_listen_address = None;
1224 let config = ServerConfig {
1225 store: StoreConfig {
1226 backend: StoreBackend::LibSql,
1227 url: Some(db_path.to_string_lossy().into_owned()),
1228 ..StoreConfig::default()
1229 },
1230 runtime: RuntimeSection {
1231 scheduler_threads: 1,
1232 query_timeout_ms: Some(10_000),
1233 },
1234 websocket: WebSocketConfig {
1235 outbound_buffer_bound: 32,
1236 event_broadcast_capacity: Some(64),
1237 cluster_broadcast_capacity: Some(64),
1238 },
1239 outbox: outbox.clone(),
1240 ..ServerConfig::default()
1241 };
1242 let state = ServerState::build(config)
1243 .await
1244 .expect("build libsql state");
1245 let (_tx, rx) = tokio::sync::watch::channel(false);
1246
1247 let error = maybe_spawn_outbox_dispatcher(
1248 &state,
1249 &outbox,
1250 false,
1251 test_backpressure_settings(),
1252 &rx,
1253 )
1254 .expect_err("liminal transport without a listen address must be a config error");
1255 assert!(
1256 error.is_config(),
1257 "missing-listen-address error must be Config"
1258 );
1259 assert!(
1260 error.to_string().contains("liminal_listen_address"),
1261 "error must name the missing knob, got: {error}"
1262 );
1263 }
1264}
1265
1266/// LSUB-PROD (13-6): production-boot cross-node round-trip over the REAL wiring.
1267///
1268/// This is the proof that the production boot now does the full round-trip the
1269/// retired stub could not. It drives the EXACT production commissioning function
1270/// `run_server` calls — [`maybe_spawn_outbox_dispatcher`] — over a real
1271/// [`ServerState`] built with `outbox.enabled`, `transport = liminal`, and a
1272/// `liminal_listen_address`. That function lifts the full push wiring
1273/// (`build_liminal_row_dispatch`): it hosts the liminal worker listener, builds
1274/// [`RegistryLiminalDispatch`](crate::worker::RegistryLiminalDispatch) over the
1275/// SAME registry the gRPC path uses and the SAME
1276/// [`ServerOutboxDeliveryCallback`](crate::worker::ServerOutboxDeliveryCallback)
1277/// (over the live engine), and spawns the real [`OutboxDispatcher`].
1278///
1279/// A REAL remote [`LiminalActivityWorker`](aion_worker::LiminalActivityWorker)
1280/// connects IN to the listener and self-registers in-band. A `collect_four`
1281/// fan-out is started over the REAL HTTP transport, which stages four pending
1282/// outbox rows; the production-wired dispatcher claims and pushes each to the
1283/// worker, the worker executes it, and its completion re-enters aion through the
1284/// production engine callback — `record_fan_out_completion` — driving the
1285/// workflow to a recorded terminal. The proof asserts BOTH: the worker observably
1286/// executed the activities, AND the terminals were recorded in history (four
1287/// `ActivityCompleted` + one `WorkflowCompleted`), which the stub's
1288/// publish-and-mark-done path never achieved.
1289// Also gated on `libsql-backend`: this production-boot round-trip stands up a
1290// real libSQL-backed server (the durable outbox path it exercises), and the
1291// libSQL connect path is now an opt-in feature.
1292#[cfg(all(test, feature = "liminal-transport", feature = "libsql-backend"))]
1293mod lsub_prod_xnode_e2e {
1294 #![allow(clippy::expect_used)]
1295
1296 use std::net::SocketAddr;
1297 use std::path::PathBuf;
1298 use std::sync::Arc;
1299 use std::sync::atomic::{AtomicUsize, Ordering};
1300 use std::time::{Duration, Instant};
1301
1302 use aion_core::Event;
1303 use aion_package::{
1304 ActionContract, BeamModule, BeamSet, CURRENT_FORMAT_VERSION, DeclaredActivity, Manifest,
1305 ManifestVersion, PackageBuilder, PackageContract, WorkerContract,
1306 };
1307 use aion_store::ReadableEventStore;
1308 use aion_store_libsql::LibSqlStore;
1309 use aion_worker::{ActivityRegistry, LiminalActivityWorker, WorkerConfig};
1310 use axum::body;
1311 use axum::http::{Request, StatusCode};
1312 use serde_json::json;
1313 use tower::ServiceExt;
1314
1315 use super::{BackpressureSettings, maybe_spawn_outbox_dispatcher};
1316 use crate::ServerState;
1317 use crate::api::http::http_router;
1318 use crate::config::{
1319 OutboxConfig, OutboxTransport, RuntimeSection, ServerConfig, StoreBackend, StoreConfig,
1320 WebSocketConfig,
1321 };
1322
1323 type TestError = Box<dyn std::error::Error + Send + Sync>;
1324
1325 /// The `collect_four` fixture passes each member the JSON string `"in"` as
1326 /// activity input, so the worker handler decodes a [`String`], not a struct.
1327 type FanInput = String;
1328
1329 const NAMESPACE: &str = "default";
1330 const TASK_QUEUE: &str = "default";
1331 const OUTBOX_MODULE: &str = "aion_outbox_fixture";
1332 const OUTBOX_BEAM: &[u8] = include_bytes!("../tests/fixtures/aion_outbox_fixture.beam");
1333 const OUTBOX_SOURCE: &[u8] = include_bytes!("../tests/fixtures/aion_outbox_fixture.erl");
1334 const FAN_OUT: usize = 4;
1335 const FAN_ACTIVITY_TYPES: [&str; FAN_OUT] = ["fan:0", "fan:1", "fan:2", "fan:3"];
1336 const POLL_DEADLINE: Duration = Duration::from_secs(20);
1337
1338 fn test_error(message: impl std::fmt::Display) -> TestError {
1339 message.to_string().into()
1340 }
1341
1342 /// Reserve a loopback port and return it: the liminal listener binds this exact
1343 /// address (the production path binds the configured `liminal_listen_address`,
1344 /// so the test must commit to a concrete port the worker can also dial).
1345 fn reserve_loopback_port() -> Result<SocketAddr, TestError> {
1346 let listener = std::net::TcpListener::bind("127.0.0.1:0").map_err(test_error)?;
1347 let address = listener.local_addr().map_err(test_error)?;
1348 drop(listener);
1349 Ok(address)
1350 }
1351
1352 /// The fixture's queue-scoped `.v4` contract: the four `fan:N` activities
1353 /// `collect_four` schedules, declared on the queue its worker actually polls.
1354 ///
1355 /// Why the archive cannot just carry the manifest-derived record: by design
1356 /// `PackageContract::from_manifest` "never invents a queue", so a manifest's
1357 /// bare activity names land in `unscoped_activities` — and this server boots
1358 /// queue-routed, where an unscoped catalog is a terminal
1359 /// `NO_QUEUE_DECLARATION` at start admission
1360 /// (`aion::lifecycle::start_admission`). That refusal is EARNED: an unserved
1361 /// queue would otherwise wait silently forever. So the derived record is
1362 /// amended rather than bypassed — the same four names move out of
1363 /// `unscoped_activities` and onto the queue that serves them — and the
1364 /// package still loads through the production boot path with the `.v4`
1365 /// identity `PackageBuilder` stamps over this exact contract.
1366 ///
1367 /// The action schemas come from the SAME generator the worker's typed
1368 /// registry uses, for the SAME Rust types: `collect_four` passes each member
1369 /// the JSON string `"in"` and the handler returns a [`String`]. Deriving both
1370 /// sides from `activity_descriptor::<FanInput, String>` means the package's
1371 /// declaration and the worker's advertisement cannot drift apart, so
1372 /// registration admission (`WORKER_CONTRACT_MISMATCH`) compares two schemas
1373 /// with one source.
1374 fn fixture_contract(manifest: &Manifest) -> Result<PackageContract, TestError> {
1375 let mut actions = Vec::with_capacity(FAN_ACTIVITY_TYPES.len());
1376 for activity_type in FAN_ACTIVITY_TYPES {
1377 let descriptor = aion_worker::activity_descriptor::<FanInput, String>(activity_type)
1378 .map_err(test_error)?;
1379 actions.push(ActionContract {
1380 name: descriptor.name,
1381 input_schema: descriptor.input_schema,
1382 output_schema: descriptor.output_schema,
1383 node: None,
1384 timeout: None,
1385 retry: None,
1386 advisory: false,
1387 // A typed `String -> String` handler serves these, not an agent
1388 // harness — the fan fixture's shape merely coincides with an
1389 // agent seam's, and marking it would route it somewhere no
1390 // handler is.
1391 agent: false,
1392 // A connected worker serves this fixture's queue, so the
1393 // declaration carries no body of its own.
1394 body: None,
1395 });
1396 }
1397 let mut contract = PackageContract::from_manifest(manifest);
1398 contract.workers = vec![WorkerContract {
1399 task_queue: TASK_QUEUE.to_owned(),
1400 actions,
1401 }];
1402 contract.unscoped_activities.clear();
1403 Ok(contract)
1404 }
1405
1406 /// Build the `collect_four` package on disk so the production state-build path
1407 /// loads it exactly as it loads operator-supplied `workflow_packages`.
1408 fn write_package_archive(dir: &std::path::Path) -> Result<PathBuf, TestError> {
1409 let beams =
1410 BeamSet::new(vec![BeamModule::new(OUTBOX_MODULE, OUTBOX_BEAM)]).map_err(test_error)?;
1411 let manifest = Manifest {
1412 entry_module: OUTBOX_MODULE.to_owned(),
1413 entry_function: "collect_four".to_owned(),
1414 input_schema: json!({ "type": "object" }),
1415 output_schema: json!({}),
1416 timeout: Some(Duration::from_secs(30)),
1417 // The four ordinals `collect_four` actually fans out. This manifest
1418 // used to name one invented activity, `fixture_activity`, that the
1419 // fixture never schedules and no worker ever served.
1420 activities: FAN_ACTIVITY_TYPES
1421 .iter()
1422 .map(|activity_type| DeclaredActivity {
1423 activity_type: (*activity_type).to_owned(),
1424 })
1425 .collect(),
1426 version: ManifestVersion::new("stamped-by-builder"),
1427 format_version: CURRENT_FORMAT_VERSION,
1428 additional_workflows: Vec::new(),
1429 };
1430 let contract = fixture_contract(&manifest)?;
1431 let archive =
1432 PackageBuilder::with_source(manifest, beams, [(OUTBOX_MODULE, OUTBOX_SOURCE.to_vec())])
1433 .with_contract(contract)
1434 .write_to_bytes()
1435 .map_err(test_error)?;
1436 let path = dir.join("collect_four.aion");
1437 std::fs::write(&path, archive).map_err(test_error)?;
1438 Ok(path)
1439 }
1440
1441 /// A production-shaped `ServerConfig`: the libSQL backend (so the boot store
1442 /// path shares the leaf as the dispatcher's outbox store, exactly as
1443 /// `ServerState::build` does in production), `outbox.enabled`,
1444 /// `transport = liminal`, the reserved `liminal_listen_address`, and the
1445 /// `collect_four` package. Built through `ServerState::build` (not
1446 /// `build_with_store`), so this is the real boot store seam, not a test stand-in.
1447 fn server_config(
1448 db_path: &std::path::Path,
1449 package_path: PathBuf,
1450 listen_address: SocketAddr,
1451 ) -> ServerConfig {
1452 ServerConfig {
1453 store: StoreConfig {
1454 backend: StoreBackend::LibSql,
1455 url: Some(db_path.to_string_lossy().into_owned()),
1456 ..StoreConfig::default()
1457 },
1458 runtime: RuntimeSection {
1459 scheduler_threads: 1,
1460 query_timeout_ms: Some(10_000),
1461 },
1462 websocket: WebSocketConfig {
1463 outbound_buffer_bound: 32,
1464 event_broadcast_capacity: Some(64),
1465 cluster_broadcast_capacity: Some(64),
1466 },
1467 workflow_packages: vec![package_path],
1468 outbox: OutboxConfig {
1469 enabled: true,
1470 poll_interval_ms: Some(20),
1471 batch_size: Some(16),
1472 max_attempts: Some(5),
1473 backoff_base_ms: Some(50),
1474 backoff_multiplier: Some(2),
1475 backoff_max_ms: Some(1_000),
1476 reconcile_interval_ms: None,
1477 reconcile_stale_after_ms: None,
1478 transport: OutboxTransport::Liminal,
1479 liminal_listen_address: Some(listen_address.to_string()),
1480 },
1481 ..ServerConfig::default()
1482 }
1483 }
1484
1485 /// The remote worker self-describes for the fixture's pool `(default, default)`
1486 /// and registers a handler for every `fan:N` activity type, counting executions
1487 /// so the test proves it genuinely ran the pushed dispatches.
1488 fn worker_config() -> Result<WorkerConfig, TestError> {
1489 WorkerConfig::builder()
1490 .endpoint("unused-direct-address")
1491 .namespace(NAMESPACE)
1492 .task_queue(TASK_QUEUE)
1493 .identity("lsub-prod-worker")
1494 .max_concurrency(4)
1495 .reconnect_initial_backoff(Duration::from_millis(5))
1496 .reconnect_max_backoff(Duration::from_millis(20))
1497 .reconnect_max_attempts(3)
1498 .build()
1499 .map_err(test_error)
1500 }
1501
1502 fn worker_registry(executions: &Arc<AtomicUsize>) -> Result<Arc<ActivityRegistry>, TestError> {
1503 let mut registry = ActivityRegistry::new();
1504 for activity_type in FAN_ACTIVITY_TYPES {
1505 let executions = Arc::clone(executions);
1506 // `register_activity_with_contract`, not `register_activity`: the
1507 // bare form registers a handler with NO descriptor, so the worker
1508 // advertises four names and zero typed contracts, and admission —
1509 // which compares CONTRACTS — refuses the registration outright
1510 // (`WORKER_CONTRACT_MISMATCH`). Deriving the advertisement from
1511 // `<FanInput, String>` is what makes it the same source the
1512 // package's `fixture_contract` declares from, so the two sides
1513 // cannot drift.
1514 registry = registry
1515 .register_activity_with_contract(
1516 activity_type,
1517 move |_input: FanInput, _context| {
1518 let executions = Arc::clone(&executions);
1519 Box::pin(async move {
1520 executions.fetch_add(1, Ordering::SeqCst);
1521 Ok(activity_type.to_owned())
1522 })
1523 },
1524 )
1525 .map_err(test_error)?;
1526 }
1527 Ok(Arc::new(registry))
1528 }
1529
1530 /// Spawns the remote worker on its own OS thread with a current-thread runtime
1531 /// (the push receive is blocking), connecting IN to the production listener.
1532 struct WorkerThread {
1533 stop: Arc<std::sync::atomic::AtomicBool>,
1534 handle: Option<std::thread::JoinHandle<()>>,
1535 }
1536
1537 impl WorkerThread {
1538 fn spawn(address: String, config: WorkerConfig, registry: Arc<ActivityRegistry>) -> Self {
1539 let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
1540 let thread_stop = Arc::clone(&stop);
1541 let handle = std::thread::spawn(move || {
1542 let runtime = match tokio::runtime::Builder::new_current_thread()
1543 .enable_all()
1544 .build()
1545 {
1546 Ok(runtime) => runtime,
1547 Err(error) => {
1548 eprintln!("worker runtime build failed: {error}");
1549 return;
1550 }
1551 };
1552 runtime.block_on(async move {
1553 let worker = match LiminalActivityWorker::connect(&address, &config, registry) {
1554 Ok(worker) => worker,
1555 Err(error) => {
1556 eprintln!("worker connect failed: {error}");
1557 return;
1558 }
1559 };
1560 if let Err(error) = worker
1561 .serve_until(|| thread_stop.load(Ordering::SeqCst))
1562 .await
1563 {
1564 eprintln!("worker serve loop ended with error: {error}");
1565 }
1566 });
1567 });
1568 Self {
1569 stop,
1570 handle: Some(handle),
1571 }
1572 }
1573
1574 fn stop(mut self) {
1575 self.stop.store(true, Ordering::SeqCst);
1576 if let Some(handle) = self.handle.take() {
1577 handle.join().ok();
1578 }
1579 }
1580 }
1581
1582 fn count_completed(history: &[Event]) -> usize {
1583 history
1584 .iter()
1585 .filter(|event| matches!(event, Event::ActivityCompleted { .. }))
1586 .count()
1587 }
1588
1589 fn count_workflow_completed(history: &[Event]) -> usize {
1590 history
1591 .iter()
1592 .filter(|event| matches!(event, Event::WorkflowCompleted { .. }))
1593 .count()
1594 }
1595
1596 async fn wait_for_history<F>(
1597 store: &LibSqlStore,
1598 workflow_id: &aion_core::WorkflowId,
1599 description: &str,
1600 predicate: F,
1601 ) -> Result<Vec<Event>, TestError>
1602 where
1603 F: Fn(&[Event]) -> bool,
1604 {
1605 let deadline = Instant::now() + POLL_DEADLINE;
1606 loop {
1607 let history = store.read_history(workflow_id).await.map_err(test_error)?;
1608 if predicate(&history) {
1609 return Ok(history);
1610 }
1611 if Instant::now() > deadline {
1612 return Err(test_error(format!(
1613 "timed out waiting for {description}: {history:#?}"
1614 )));
1615 }
1616 tokio::time::sleep(Duration::from_millis(25)).await;
1617 }
1618 }
1619
1620 /// Start the loaded `collect_four` workflow over the REAL HTTP transport.
1621 async fn start_over_http(router: &axum::Router) -> Result<aion_core::WorkflowId, TestError> {
1622 let build_request = || -> Result<Request<body::Body>, TestError> {
1623 Request::builder()
1624 .uri("/workflows/start")
1625 .method("POST")
1626 .header("content-type", "application/json")
1627 .header("x-aion-subject", "ci")
1628 .header("x-aion-namespaces", NAMESPACE)
1629 .body(body::Body::from(
1630 serde_json::to_vec(&json!({
1631 "namespace": NAMESPACE,
1632 "workflow_type": OUTBOX_MODULE,
1633 "input": { "fixture": "input" },
1634 }))
1635 .map_err(test_error)?,
1636 ))
1637 .map_err(test_error)
1638 };
1639 let response = router
1640 .clone()
1641 .oneshot(build_request()?)
1642 .await
1643 .map_err(test_error)?;
1644 let status = response.status();
1645 let bytes = body::to_bytes(response.into_body(), usize::MAX)
1646 .await
1647 .map_err(test_error)?
1648 .to_vec();
1649 if status != StatusCode::OK {
1650 return Err(test_error(format!(
1651 "workflow start over HTTP must succeed, got {status}: {}",
1652 String::from_utf8_lossy(&bytes)
1653 )));
1654 }
1655 let body: serde_json::Value = serde_json::from_slice(&bytes).map_err(test_error)?;
1656 // The HTTP wire contract (`clean_dtos::StartWorkflowResponse`) serializes
1657 // `workflow_id` as a plain UUID string, not a nested `{ uuid }` object.
1658 let workflow_id = body["workflow_id"]
1659 .as_str()
1660 .ok_or_else(|| test_error("start response missing workflow id"))?
1661 .parse::<uuid::Uuid>()
1662 .map_err(test_error)?;
1663 Ok(aion_core::WorkflowId::new(workflow_id))
1664 }
1665
1666 #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
1667 async fn production_boot_dispatches_executes_and_records_over_liminal() -> Result<(), TestError>
1668 {
1669 let dir = crate::test_support::private_tempdir().map_err(test_error)?;
1670 let db_path = dir.path().join("aion.db");
1671 let package_path = write_package_archive(dir.path())?;
1672 // The production path binds the CONFIGURED listen address, so commit to a
1673 // concrete reserved loopback port the worker can also dial.
1674 let listen_address = reserve_loopback_port()?;
1675
1676 // (A) Build a real ServerState through the production boot path
1677 // (ServerState::build over a libSQL ServerConfig): outbox enabled,
1678 // transport = liminal, the listen address set, collect_four loaded. This
1679 // shares the libSQL leaf as the dispatcher's outbox store (the real boot
1680 // store seam) and installs the production ServerOutboxDeliveryCallback over
1681 // the live engine (gated on outbox.enabled).
1682 let config = server_config(&db_path, package_path, listen_address);
1683 let outbox_config = config.outbox.clone();
1684 let state = ServerState::build(config).await.map_err(test_error)?;
1685
1686 // (B) Drive the EXACT production commissioning function run_server calls:
1687 // it hosts the liminal listener, builds RegistryLiminalDispatch over the
1688 // shared registry + engine callback, and spawns the real OutboxDispatcher.
1689 // Hold the returned listener guard for the test's lifetime, exactly as
1690 // run_server holds it.
1691 let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false);
1692 // Own-all, generous-default backpressure (single-node e2e): fraction 1 and
1693 // the platform default, so the ceiling never engages — the claim behaves
1694 // exactly as before, proving the production path is byte-identical on default.
1695 let backpressure_settings = BackpressureSettings {
1696 platform_default: crate::config::DEFAULT_MAX_IN_FLIGHT_ACTIVITIES,
1697 fraction: crate::worker::OwnedShardFraction::own_all(),
1698 };
1699 let listener_guard = maybe_spawn_outbox_dispatcher(
1700 &state,
1701 &outbox_config,
1702 false,
1703 backpressure_settings,
1704 &shutdown_rx,
1705 )
1706 .map_err(test_error)?;
1707
1708 // (C) A REAL remote worker connects IN to the production listener and
1709 // self-registers in-band for the fixture's pool.
1710 let executions = Arc::new(AtomicUsize::new(0));
1711 let worker = WorkerThread::spawn(
1712 listen_address.to_string(),
1713 worker_config()?,
1714 worker_registry(&executions)?,
1715 );
1716
1717 // Wait until the in-band registration landed in the SAME registry the
1718 // dispatch path selects from (every fan-out activity type is eligible).
1719 let registry = state.worker_registry().clone();
1720 let deadline = Instant::now() + Duration::from_secs(5);
1721 loop {
1722 let ready = FAN_ACTIVITY_TYPES.iter().all(|activity_type| {
1723 registry
1724 .select_worker(NAMESPACE, TASK_QUEUE, activity_type, None)
1725 .ok()
1726 .flatten()
1727 .is_some()
1728 });
1729 if ready {
1730 break;
1731 }
1732 if Instant::now() > deadline {
1733 worker.stop();
1734 return Err(test_error("worker never registered in-band for the pool"));
1735 }
1736 tokio::time::sleep(Duration::from_millis(10)).await;
1737 }
1738
1739 // (D) Start collect_four over the REAL HTTP transport: the engine stages
1740 // four pending outbox rows; the production-wired dispatcher claims and
1741 // pushes each to the worker.
1742 let router = http_router(state.clone()).map_err(test_error)?;
1743 let workflow_id = start_over_http(&router).await?;
1744
1745 // (E) THE PROOF: the worker executed all four activities AND every terminal
1746 // was recorded through the production engine callback (record_fan_out_completion)
1747 // — four ActivityCompleted + one WorkflowCompleted in durable history. This
1748 // is the full round-trip the retired stub never achieved.
1749 let reader = LibSqlStore::open(db_path.clone())
1750 .await
1751 .map_err(test_error)?;
1752 let settled = wait_for_history(&reader, &workflow_id, "fan-out settled", |events| {
1753 count_completed(events) == FAN_OUT && count_workflow_completed(events) == 1
1754 })
1755 .await?;
1756 assert_eq!(
1757 count_completed(&settled),
1758 FAN_OUT,
1759 "every fan-out member must record a terminal through the production callback"
1760 );
1761 assert_eq!(
1762 count_workflow_completed(&settled),
1763 1,
1764 "the workflow must complete exactly once"
1765 );
1766 assert_eq!(
1767 executions.load(Ordering::SeqCst),
1768 FAN_OUT,
1769 "the remote worker must have executed every pushed dispatch exactly once"
1770 );
1771
1772 // Teardown: stop the dispatcher + worker, drop the listener guard (its Drop
1773 // stops the accept worker), shut the engine down so durable appends finish.
1774 shutdown_tx.send(true).ok();
1775 worker.stop();
1776 drop(listener_guard);
1777 state.shutdown().map_err(test_error)?;
1778 Ok(())
1779 }
1780}