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