Skip to main content

toolkit/runtime/
host_runtime.rs

1//! Host runtime lifecycle, shared by in-process and `OoP` execution.
2//!
3//! Startup order:
4//! 1. Build manifests and policies; check GTS ownership and wiring groups
5//!    before any gear runs or writes to the registry.
6//! 2. System group: runtime wiring, `pre_init`, migrations, `init`, client
7//!    wiring, `post_init`, initial gRPC services, `start`.
8//! 3. Application preparation: `pre_init`, migrations, registry-client wiring,
9//!    then concurrent GTS publication. All manifests must be admitted before
10//!    any application `init`; failed admission stops the process for restart.
11//! 4. Application `init`, remaining client wiring, legacy registry finalization,
12//!    `post_init`, REST composition, late gRPC installation, `start`.
13//! 5. In-process host: advertise REST providers, then spawn configured children
14//!    without waiting for readiness. Parent publication cannot depend on them.
15//!
16//! Hooks run once per gear, in topological order within each group. Migration-only
17//! mode runs runtime wiring, `pre_init` and migrations for all gears, system first.
18//! Shutdown stops applications before system gears, reversing each group's order.
19//! `oop_serve` owns HTTP serving, directory presence and drain in the `OoP` path;
20//! that path has no REST host, directory-register or child-spawn phases.
21//!
22//! # `deps` and `#[toolkit::consumes]`
23//!
24//! - `deps` orders same-process `init`s and requires linked gears; an unknown
25//!   dependency fails registry construction. It cannot order remote providers.
26//! - `#[toolkit::consumes(contract, from)]` wires a local client or a resolving
27//!   proxy and gates `/readyz`, without adding an ordering edge. Wiring precedes
28//!   `post_init` and `start` in both profiles.
29//!
30//! Prefer `consumes` for inter-gear calls; use `deps` for local init ordering.
31
32#[path = "host_runtime_rest.rs"]
33mod rest_bootstrap;
34
35#[path = "rest_advertiser.rs"]
36mod rest_advertiser;
37use rest_advertiser::RestAdvertiser;
38
39use axum::Router;
40use std::collections::HashSet;
41use std::sync::Arc;
42
43use tokio_util::sync::CancellationToken;
44use uuid::Uuid;
45
46use crate::backends::OopSpawnConfig;
47use crate::client_hub::ClientHub;
48use crate::config::ConfigProvider;
49use crate::context::{GearContextBuilder, GtsAdmittedManifests};
50use crate::gts_publication::{
51    GtsManifest, GtsPublicationDescriptor, GtsPublicationOptions, PreparedGtsPublication,
52};
53
54/// A publishing gear's manifest and policy, read once from the configuration before
55/// any gear runs.
56type GtsPublicationPlan = (
57    &'static GtsPublicationDescriptor,
58    Arc<GtsManifest>,
59    GtsPublicationOptions,
60);
61use crate::registry::{
62    ApiGatewayCap, GearEntry, GearRegistry, GrpcHubCap, GtsPublicationCap, RegistryError,
63    RestApiCap, RunnableCap, SystemCap,
64};
65use crate::runtime::{
66    GearManager, GrpcInstallerStore, OopSpawnOptions, PREPARATION_GATE, SystemContext,
67};
68
69#[cfg(feature = "db")]
70use crate::registry::DatabaseCap;
71
72/// How the runtime should provide DBs to gears.
73#[derive(Clone)]
74pub enum DbOptions {
75    /// No database integration. `GearCtx::db()` will be `None`, `db_required()` will error.
76    None,
77    /// Use a `DbManager` to handle database connections with Figment-based configuration.
78    #[cfg(feature = "db")]
79    Manager(Arc<toolkit_db::DbManager>),
80}
81
82/// Runtime execution mode that determines which phases to run.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum RunMode {
85    /// Run all phases and wait for shutdown signal (normal application mode).
86    Full,
87    /// Run only pre-init and DB migration phases, then exit (for cloud deployments).
88    MigrateOnly,
89}
90
91/// Environment variable name for passing directory endpoint to `OoP` gears.
92pub const TOOLKIT_DIRECTORY_ENDPOINT_ENV: &str = "TOOLKIT_DIRECTORY_ENDPOINT";
93
94/// Environment variable name for passing rendered gear config to `OoP` gears.
95pub const TOOLKIT_MODULE_CONFIG_ENV: &str = "TOOLKIT_MODULE_CONFIG";
96
97/// Default shutdown deadline for graceful gear stop (35 seconds).
98///
99/// This is intentionally 5 seconds longer than `WithLifecycle::stop_timeout` (30s default)
100/// to ensure deterministic behavior: the lifecycle's internal timeout fires first,
101/// and the runtime deadline acts as a hard backstop.
102pub const DEFAULT_SHUTDOWN_DEADLINE: std::time::Duration = std::time::Duration::from_secs(35);
103
104/// How long the runtime waits for the gRPC hub to install the late services
105/// of the application group on its running listener.
106const LATE_GRPC_INSTALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
107
108/// How the startup of the application group ended.
109#[derive(Debug)]
110enum AppStartup {
111    /// Every application gear initialized and started.
112    Started,
113    /// Publication failed before application init; cleanup precedes the error return.
114    Failed(RegistryError),
115    /// Shutdown came first.
116    Cancelled,
117}
118
119/// Log the preparation failure before cleanup and error return.
120fn startup_failure(outcome: AppStartup) -> Option<RegistryError> {
121    match outcome {
122        AppStartup::Failed(failure) => {
123            tracing::error!(
124                error = %failure,
125                "the application group did not start; stopping the process"
126            );
127            Some(failure)
128        }
129        AppStartup::Started | AppStartup::Cancelled => None,
130    }
131}
132
133/// Default per-gear init deadline (10 minutes); see [`HostRuntime::with_init_deadline`].
134pub const DEFAULT_INIT_DEADLINE: std::time::Duration = std::time::Duration::from_secs(600);
135
136/// Verdict of a force-exit watchdog's wait, kept free of `process::exit` so the
137/// decision is unit-testable.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139enum WatchdogVerdict {
140    /// Disarmed in time: the guarded work finished or its future was dropped.
141    Disarmed,
142    /// The deadline elapsed first; the caller must force-exit.
143    TimedOut,
144}
145
146/// Block until the watchdog is disarmed (`disarm_rx` signalled or dropped) or
147/// `deadline` elapses. Runs on an OS thread (see [`arm_force_exit_watchdog`]) so
148/// the bound holds even when the guarded code blocks a runtime worker
149/// synchronously, which an async timer cannot observe.
150fn watchdog_verdict(
151    disarm_rx: &std::sync::mpsc::Receiver<()>,
152    deadline: std::time::Duration,
153) -> WatchdogVerdict {
154    match disarm_rx.recv_timeout(deadline) {
155        Ok(()) | Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => WatchdogVerdict::Disarmed,
156        Err(std::sync::mpsc::RecvTimeoutError::Timeout) => WatchdogVerdict::TimedOut,
157    }
158}
159
160/// Grace the force-exit diagnostic gets before the process exits regardless.
161const FORCE_EXIT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);
162
163/// Log a force-exit diagnostic and terminate the process with code 1.
164///
165/// A backstop timer is armed *first* so a wedged writer (e.g. a full `stderr`
166/// pipe) can delay the message but not the exit. `message` is mirrored to
167/// `stderr` so it survives tracing being off or unflushed.
168fn force_exit(message: &str) -> ! {
169    std::thread::spawn(|| {
170        std::thread::sleep(FORCE_EXIT_GRACE);
171        std::process::exit(1);
172    });
173
174    tracing::error!("{message}");
175    {
176        use std::io::Write as _;
177        _ = writeln!(std::io::stderr().lock(), "ERROR {message}");
178    }
179
180    std::process::exit(1);
181}
182
183/// Arm a thread that [`force_exit`]s unless the returned sender is dropped within
184/// `deadline`. Dropping it (normal completion *or* the guarded future being
185/// cancelled) disarms the watchdog, so a cancelled phase never force-exits.
186/// Shared by the init and stop phases.
187#[must_use = "bind the returned sender for the guarded region; dropping it disarms the watchdog"]
188fn arm_force_exit_watchdog(
189    deadline: std::time::Duration,
190    message: String,
191) -> std::sync::mpsc::Sender<()> {
192    let (disarm_tx, disarm_rx) = std::sync::mpsc::channel::<()>();
193    std::thread::spawn(move || {
194        if watchdog_verdict(&disarm_rx, deadline) == WatchdogVerdict::TimedOut {
195            force_exit(&message);
196        }
197    });
198    disarm_tx
199}
200
201/// Owns the lifecycle orchestration for `ToolKit`: encapsulates all runtime
202/// state and drives gears through the full lifecycle (see gear docs).
203pub struct HostRuntime {
204    registry: GearRegistry,
205    ctx_builder: GearContextBuilder,
206    instance_id: Uuid,
207    gear_manager: Arc<GearManager>,
208    grpc_installers: Arc<GrpcInstallerStore>,
209    client_hub: Arc<ClientHub>,
210    /// Per-gear config, retained for the proxy-wiring phase to read a consumer's
211    /// static-endpoint override (dev/test escape hatch, ADR-0004).
212    gears_cfg: Arc<dyn ConfigProvider>,
213    /// Process-level dependency-resolution + draining signal, published in
214    /// `client_hub` for the `/readyz` probe and updated by the proxy-wiring
215    /// readiness loop + draining watcher. In-process, an
216    /// [`ReadinessHealthcheck`](super::readiness::ReadinessHealthcheck) leaf
217    /// bridges it into the gateway's healthcheck registry.
218    dep_checker: Arc<super::readiness::DependencyChecker>,
219    /// Admitted manifests, read by the contexts of application gears.
220    gts_admitted: GtsAdmittedManifests,
221    /// In-process REST provider advertisement. In `OoP` serving, presence +
222    /// deregister is owned by `oop_serve`, so it stays unused.
223    advertiser: Arc<RestAdvertiser>,
224    /// Gears whose `start` the runtime called: the ones the stop phase stops,
225    /// on shutdown and after a failed startup alike.
226    start_called: parking_lot::Mutex<HashSet<&'static str>>,
227    /// Consumer registrations already wired, by address: the registry
228    /// clients are wired early, the rest after application `init`, each once.
229    wired: parking_lot::Mutex<HashSet<usize>>,
230    /// Replaces the link-time `inventory` registrations in a test: a test
231    /// binary links none, and submitting one would wire it in every test.
232    #[cfg(test)]
233    consumer_registrations: Option<Vec<&'static crate::discovery::ConsumerRegistration>>,
234    cancel: CancellationToken,
235    /// Ends the runtime's own background tasks (readiness probes, the drain
236    /// watcher) when startup fails or the runtime is dropped, without
237    /// cancelling `cancel`, which the caller may share. A child of `cancel`.
238    owned: CancellationToken,
239    /// Cancels `owned` when the runtime is dropped — the lifecycle future
240    /// abandoned.
241    _owned_on_drop: tokio_util::sync::DropGuard,
242    #[allow(dead_code)]
243    db_options: DbOptions,
244    /// `OoP` gear spawn configuration and backend
245    oop_options: Option<OopSpawnOptions>,
246    /// Maximum time allowed for graceful shutdown before hard-stop signal is sent.
247    shutdown_deadline: std::time::Duration,
248    /// Per-gear deadline for context construction and [`Gear::init`](crate::contracts::Gear::init).
249    /// Expiry force-exits the process (see [`DEFAULT_INIT_DEADLINE`]).
250    init_deadline: std::time::Duration,
251}
252
253impl HostRuntime {
254    /// Create a new `HostRuntime` instance.
255    ///
256    /// This prepares all runtime components but does not start any lifecycle phases.
257    pub fn new(
258        registry: GearRegistry,
259        gears_cfg: Arc<dyn ConfigProvider>,
260        db_options: DbOptions,
261        client_hub: Arc<ClientHub>,
262        cancel: CancellationToken,
263        instance_id: Uuid,
264        oop_options: Option<OopSpawnOptions>,
265    ) -> Self {
266        // Create runtime-owned components for system gears
267        let gear_manager = Arc::new(GearManager::new());
268        let grpc_installers = Arc::new(GrpcInstallerStore::new());
269
270        // Process-level dependency/draining signal, published so the gateway's
271        // /readyz handler can fetch it (concrete-type key). Created before any
272        // phase runs.
273        let dep_checker = Arc::new(super::readiness::DependencyChecker::new());
274        client_hub.register::<super::readiness::DependencyChecker>(dep_checker.clone());
275
276        let owned = cancel.child_token();
277        let owned_on_drop = owned.clone().drop_guard();
278        dep_checker.register_dep(PREPARATION_GATE);
279
280        // Build the context builder that will resolve per-gear DbHandles
281        let ctx_builder = GearContextBuilder::new(
282            instance_id,
283            gears_cfg.clone(),
284            client_hub.clone(),
285            cancel.clone(),
286        );
287        let gts_admitted = ctx_builder.gts_admitted_manifests();
288        #[cfg(feature = "db")]
289        let ctx_builder = match &db_options {
290            DbOptions::Manager(mgr) => ctx_builder.with_db_manager(mgr.clone()),
291            DbOptions::None => ctx_builder,
292        };
293
294        Self {
295            registry,
296            ctx_builder,
297            instance_id,
298            gear_manager,
299            grpc_installers,
300            client_hub,
301            gears_cfg,
302            dep_checker,
303            gts_admitted,
304            advertiser: Arc::new(RestAdvertiser::new(instance_id, &owned)),
305            start_called: parking_lot::Mutex::new(HashSet::new()),
306            wired: parking_lot::Mutex::new(HashSet::new()),
307            #[cfg(test)]
308            consumer_registrations: None,
309            owned,
310            _owned_on_drop: owned_on_drop,
311            cancel,
312            db_options,
313            oop_options,
314            shutdown_deadline: DEFAULT_SHUTDOWN_DEADLINE,
315            init_deadline: DEFAULT_INIT_DEADLINE,
316        }
317    }
318
319    /// Set the per-gear deadline for context construction and [`Gear::init`](crate::contracts::Gear::init).
320    ///
321    /// A stuck `.await` returns [`RegistryError::InitTimeout`]; a synchronous
322    /// block force-exits the process. Defaults to [`DEFAULT_INIT_DEADLINE`].
323    #[must_use]
324    pub fn with_init_deadline(mut self, deadline: std::time::Duration) -> Self {
325        self.init_deadline = deadline;
326        self
327    }
328
329    #[cfg(test)]
330    pub(crate) fn init_deadline(&self) -> std::time::Duration {
331        self.init_deadline
332    }
333
334    /// Set a custom shutdown deadline for graceful gear stop.
335    ///
336    /// This is the maximum time the runtime will wait for each gear to stop gracefully
337    /// before sending the hard-stop signal (cancelling the deadline token).
338    ///
339    /// # Relationship with `WithLifecycle::stop_timeout`
340    ///
341    /// When using `WithLifecycle`, its `stop_timeout` (default 30s) races against this
342    /// `shutdown_deadline` (default [`DEFAULT_SHUTDOWN_DEADLINE`], 35s). To ensure
343    /// deterministic behavior:
344    ///
345    /// - `WithLifecycle::stop_timeout` should be **less than** `shutdown_deadline`
346    /// - This allows the lifecycle's internal timeout to trigger first for graceful cleanup
347    /// - The runtime's `deadline_token` then acts as a hard backstop
348    ///
349    /// Example: `stop_timeout = 30s`, `shutdown_deadline = 35s`
350    #[must_use]
351    pub fn with_shutdown_deadline(mut self, deadline: std::time::Duration) -> Self {
352        self.shutdown_deadline = deadline;
353        self
354    }
355
356    /// Set the process-wide platform-plane credential source, applied to every
357    /// [`GearCtx`](crate::context::GearCtx) this runtime builds so
358    /// `#[toolkit::provides]`-generated clients attach `X-ToolKit-Internal-Token`
359    /// on platform-plane methods. `None` (Profile 1 / in-process, or no
360    /// credential configured) attaches nothing.
361    #[must_use]
362    pub fn with_internal_token_provider(
363        mut self,
364        provider: Option<toolkit_contract::runtime::config::InternalTokenProvider>,
365    ) -> Self {
366        self.ctx_builder = self.ctx_builder.with_internal_token_provider(provider);
367        self
368    }
369
370    /// The system group (`system = true`) or the application group, in
371    /// topological order.
372    fn group(&self, system: bool) -> Vec<&GearEntry> {
373        self.registry
374            .gears()
375            .iter()
376            .filter(|entry| entry.is_system() == system)
377            .collect()
378    }
379
380    /// Every gear, the system group first, each group in topological order.
381    fn by_group(&self) -> Vec<&GearEntry> {
382        let mut gears = self.group(true);
383        gears.extend(self.group(false));
384        gears
385    }
386
387    /// The runtime internals handed to the system gears.
388    fn system_context(&self) -> SystemContext {
389        SystemContext::new(
390            self.instance_id,
391            Arc::clone(&self.gear_manager),
392            Arc::clone(&self.grpc_installers),
393        )
394    }
395
396    /// `PRE_INIT` phase over every gear, the system group first
397    /// (migration-only mode).
398    ///
399    /// # Errors
400    /// Returns `RegistryError` if runtime wiring or a `pre_init` fails.
401    pub async fn run_pre_init_phase(&self) -> Result<(), RegistryError> {
402        self.run_pre_init_phase_for(&self.by_group()).await
403    }
404
405    /// Wire system runtime internals, then run `entries`' `pre_init`s in order,
406    /// before their migrations. Contexts have no DB handle or admitted manifest.
407    async fn run_pre_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
408        tracing::info!(gears = entries.len(), "Phase: pre_init");
409
410        let sys_ctx = self.system_context();
411        for entry in entries {
412            if self.cancel.is_cancelled() {
413                tracing::warn!("Pre-init phase cancelled by signal");
414                return Err(RegistryError::Cancelled);
415            }
416            if let Some(system) = entry.caps.query::<SystemCap>() {
417                tracing::debug!(gear = entry.name, "Wiring runtime internals");
418                system
419                    .wire_runtime(&sys_ctx)
420                    .map_err(|e| RegistryError::PreInit {
421                        gear: entry.name,
422                        source: e.context("runtime wiring"),
423                    })?;
424            }
425        }
426
427        for entry in entries {
428            // Check for cancellation before processing each gear
429            if self.cancel.is_cancelled() {
430                tracing::warn!("Pre-init phase cancelled by signal");
431                return Err(RegistryError::Cancelled);
432            }
433            let ctx = self.ctx_builder.for_gear_before_migrations(entry.name);
434            entry
435                .core
436                .pre_init(&ctx)
437                .await
438                .map_err(|e| RegistryError::PreInit {
439                    gear: entry.name,
440                    source: e,
441                })?;
442        }
443
444        Ok(())
445    }
446
447    /// Helper: resolve context for a gear with error mapping.
448    #[cfg(feature = "db")]
449    async fn gear_context(
450        &self,
451        gear_name: &'static str,
452    ) -> Result<crate::context::GearCtx, RegistryError> {
453        self.ctx_builder
454            .for_gear(gear_name)
455            .await
456            .map_err(|e| RegistryError::DbMigrate {
457                gear: gear_name,
458                source: e,
459            })
460    }
461
462    /// Helper: extract DB handle and gear if both exist.
463    #[cfg(feature = "db")]
464    async fn db_migration_target(
465        &self,
466        gear_name: &'static str,
467        ctx: &crate::context::GearCtx,
468        db_gear: Option<Arc<dyn crate::contracts::DatabaseCapability>>,
469    ) -> Result<
470        Option<(
471            toolkit_db::Db,
472            Arc<dyn crate::contracts::DatabaseCapability>,
473        )>,
474        RegistryError,
475    > {
476        let Some(dbm) = db_gear else {
477            return Ok(None);
478        };
479
480        // Important: DB migrations require access to the underlying `Db`, not just `DBProvider`.
481        // `GearCtx` intentionally exposes only `DBProvider` for better DX and to reduce mistakes.
482        // So the runtime resolves the `Db` directly from its `DbManager`.
483        let db = match &self.db_options {
484            DbOptions::None => None,
485            #[cfg(feature = "db")]
486            DbOptions::Manager(mgr) => {
487                mgr.get(gear_name)
488                    .await
489                    .map_err(|e| RegistryError::DbMigrate {
490                        gear: gear_name,
491                        source: e.into(),
492                    })?
493            }
494        };
495
496        _ = ctx; // ctx is kept for parity/error context; DB is resolved from manager above.
497        Ok(db.map(|db| (db, dbm)))
498    }
499
500    /// Helper: run migrations for a single gear using the new migration runner.
501    ///
502    /// This collects migrations from the gear and executes them via the
503    /// runtime's privileged connection. Gears never see the raw connection.
504    #[cfg(feature = "db")]
505    async fn migrate_gear(
506        gear_name: &'static str,
507        db: &toolkit_db::Db,
508        db_gear: Arc<dyn crate::contracts::DatabaseCapability>,
509    ) -> Result<(), RegistryError> {
510        // Collect migrations from the gear
511        let migrations = db_gear.migrations();
512
513        if migrations.is_empty() {
514            tracing::debug!(gear = gear_name, "No migrations to run");
515            return Ok(());
516        }
517
518        tracing::debug!(
519            gear = gear_name,
520            count = migrations.len(),
521            "Running DB migrations"
522        );
523
524        // Execute migrations using the migration runner
525        let result =
526            toolkit_db::migration_runner::run_migrations_for_gear(db, gear_name, migrations)
527                .await
528                .map_err(|e| RegistryError::DbMigrate {
529                    gear: gear_name,
530                    source: anyhow::Error::new(e),
531                })?;
532
533        tracing::info!(
534            gear = gear_name,
535            applied = result.applied,
536            skipped = result.skipped,
537            "DB migrations completed"
538        );
539
540        Ok(())
541    }
542
543    /// DB MIGRATION phase over every gear, the system group first
544    /// (migration-only mode).
545    #[cfg(feature = "db")]
546    async fn run_db_phase(&self) -> Result<(), RegistryError> {
547        self.run_db_phase_for(&self.by_group()).await
548    }
549
550    /// DB MIGRATION phase: run migrations for `entries` with DB capability,
551    /// in the given order.
552    ///
553    /// Gears provide migrations via `DatabaseCapability::migrations()`.
554    /// The runtime executes them with a privileged connection that gears
555    /// never receive directly. Each gear gets a separate migration history
556    /// table, preventing cross-gear interference.
557    #[cfg(feature = "db")]
558    async fn run_db_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
559        tracing::info!(gears = entries.len(), "Phase: db (before init)");
560
561        for entry in entries {
562            // Check for cancellation before processing each gear
563            if self.cancel.is_cancelled() {
564                tracing::warn!("DB migration phase cancelled by signal");
565                return Err(RegistryError::Cancelled);
566            }
567
568            let ctx = self.gear_context(entry.name).await?;
569            let db_gear = entry.caps.query::<DatabaseCap>();
570
571            match self
572                .db_migration_target(entry.name, &ctx, db_gear.clone())
573                .await?
574            {
575                Some((db, dbm)) => {
576                    Self::migrate_gear(entry.name, &db, dbm).await?;
577                }
578                None if db_gear.is_some() => {
579                    tracing::debug!(
580                        gear = entry.name,
581                        "Gear has DbGear trait but no DB handle (no config)"
582                    );
583                }
584                None => {}
585            }
586        }
587
588        Ok(())
589    }
590
591    /// INIT phase over every gear, the system group first.
592    #[cfg(test)]
593    async fn run_init_phase(&self) -> Result<(), RegistryError> {
594        self.run_init_phase_for(&self.by_group()).await
595    }
596
597    /// INIT phase: initialize `entries` in the given order.
598    ///
599    /// Each gear's context construction and [`Gear::init`] share a force-exit
600    /// watchdog bounded by [`Self::init_deadline`] (see [`Self::init_gear`]).
601    async fn run_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
602        tracing::info!(gears = entries.len(), "Phase: init");
603
604        for entry in entries {
605            if self.cancel.is_cancelled() {
606                tracing::warn!("Init phase cancelled by signal");
607                return Err(RegistryError::Cancelled);
608            }
609            tracing::info!(gear = entry.name, "Initializing a gear...");
610            self.init_gear(entry).await?;
611            tracing::info!(gear = entry.name, "Initialized a gear.");
612        }
613
614        Ok(())
615    }
616
617    /// Run a single gear's context construction and `init()` under a two-tier
618    /// bound on [`Self::init_deadline`]:
619    ///
620    /// - An async `tokio::time::timeout` catches the common case (a stuck
621    ///   `.await`) and returns a recoverable [`RegistryError::InitTimeout`].
622    /// - An OS-thread force-exit watchdog, armed at a *longer* deadline, is the
623    ///   only thing that can catch init blocking a worker *synchronously* (where
624    ///   the async timer can never fire); it disarms when init finishes or this
625    ///   future is dropped.
626    async fn init_gear(&self, entry: &GearEntry) -> Result<(), RegistryError> {
627        let gear_name = entry.name;
628        let deadline = self.init_deadline;
629        // Longer than the async bound so the recoverable path wins when the timer
630        // can actually fire.
631        let backstop = deadline.saturating_mul(2);
632        let _watchdog = arm_force_exit_watchdog(
633            backstop,
634            format!(
635                "init timed out; the gear appears hung, force exiting gear={gear_name} timeout_secs={}",
636                backstop.as_secs()
637            ),
638        );
639
640        let init =
641            async {
642                let ctx = self.ctx_builder.for_gear(entry.name).await.map_err(|e| {
643                    RegistryError::Init {
644                        gear: entry.name,
645                        source: e,
646                    }
647                })?;
648
649                entry
650                    .core
651                    .init(&ctx)
652                    .await
653                    .map_err(|e| RegistryError::Init {
654                        gear: entry.name,
655                        source: e,
656                    })
657            };
658
659        match tokio::time::timeout(deadline, init).await {
660            Ok(result) => result,
661            Err(_elapsed) => {
662                tracing::error!(
663                    gear = gear_name,
664                    timeout_secs = deadline.as_secs(),
665                    "init timed out waiting on the gear; returning an error"
666                );
667                Err(RegistryError::InitTimeout {
668                    gear: gear_name,
669                    timeout: deadline,
670                })
671            }
672        }
673    }
674
675    /// Consumer proxy-wiring phase (eventual readiness).
676    ///
677    /// Runs after init (compile-time / local registrations) and before
678    /// post-init. Replays each `ConsumerRegistration` emitted by
679    /// `#[toolkit::consumes]`: if a compile-time impl is already in the
680    /// `ClientHub` it wins (the wiring closure short-circuits); otherwise a
681    /// directory-resolving REST client is registered under the contract trait.
682    ///
683    /// Non-blocking: endpoint discovery is lazy/per-call inside the resolving
684    /// client, so this phase never waits on provider availability (ADR-0007).
685    /// A no-op when no consumer is registered, preserving the phase-order
686    /// invariants relied on by existing tests.
687    #[cfg_attr(
688        not(test),
689        expect(clippy::unused_self, reason = "reads the test override in test builds")
690    )]
691    fn consumer_registrations(&self) -> Vec<&'static crate::discovery::ConsumerRegistration> {
692        #[cfg(test)]
693        if let Some(regs) = &self.consumer_registrations {
694            return regs.clone();
695        }
696        inventory::iter::<crate::discovery::ConsumerRegistration>
697            .into_iter()
698            .collect()
699    }
700
701    /// Wire `regs` instead of the linked registrations.
702    #[cfg(test)]
703    fn with_consumer_registrations(
704        mut self,
705        regs: Vec<&'static crate::discovery::ConsumerRegistration>,
706    ) -> Self {
707        self.consumer_registrations = Some(regs);
708        self
709    }
710
711    /// Wire registrations once, deduplicated by address so contracts sharing a
712    /// provider remain distinct. Registry clients may already be wired early.
713    /// Explicit `regs` let tests avoid process-wide inventory registrations.
714    /// Readiness probes are spawned, not awaited.
715    fn wire_consumer_registrations(
716        &self,
717        regs: &[&crate::discovery::ConsumerRegistration],
718    ) -> Result<Vec<crate::discovery::WireOutcome>, RegistryError> {
719        let regs = self.unwired_consumer_registrations(regs);
720        self.wire_untracked(&regs)
721    }
722
723    fn unwired_consumer_registrations<'a>(
724        &self,
725        regs: &[&'a crate::discovery::ConsumerRegistration],
726    ) -> Vec<&'a crate::discovery::ConsumerRegistration> {
727        let mut wired = self.wired.lock();
728        regs.iter()
729            .copied()
730            .filter(|reg| wired.insert(std::ptr::from_ref(*reg) as usize))
731            .collect()
732    }
733
734    /// Wire `regs` without deduplication; callers manage which registrations run.
735    fn wire_untracked(
736        &self,
737        regs: &[&crate::discovery::ConsumerRegistration],
738    ) -> Result<Vec<crate::discovery::WireOutcome>, RegistryError> {
739        use crate::discovery::{DirectoryEndpointResolver, NullEndpointResolver};
740        use toolkit_contract::runtime::resolving::EndpointResolver;
741
742        if regs.is_empty() {
743            return Ok(Vec::new());
744        }
745        tracing::info!(
746            count = regs.len(),
747            "Phase: proxy-wiring (consumer discovery)"
748        );
749
750        // Without a DirectoryClient we cannot resolve *remote* providers, but we
751        // must NOT silently skip wiring: co-located consumers still short-circuit
752        // to their local impl, and remote consumers must register as unresolved
753        // readiness gates so `/readyz` stays 503 (a misconfigured consumer must
754        // not report Ready). A null resolver makes every remote lookup `Ok(None)`
755        // so the loop below classifies deps correctly without a directory.
756        let (resolver, have_directory): (Arc<dyn EndpointResolver>, bool) =
757            if let Ok(dir) = self.client_hub.get::<dyn crate::DirectoryClient>() {
758                (Arc::new(DirectoryEndpointResolver::new(dir)), true)
759            } else {
760                tracing::error!(
761                    consumers = regs.len(),
762                    "proxy-wiring: no DirectoryClient in ClientHub; remote consumer \
763                     dependencies cannot be resolved and will gate /readyz (503). \
764                     Co-located (local) dependencies are unaffected."
765                );
766                (Arc::new(NullEndpointResolver), false)
767            };
768
769        // Wire each consumer contract. The outcome distinguishes a co-located
770        // local impl (hub short-circuit) from a directory-resolving REST client.
771        // Every dep is registered as a readiness gate; local ones are marked
772        // resolved once wiring is done, and only remote ones gate readiness + get
773        // the background directory-resolve loop (ADR-0007: startup-gating + sticky).
774        // `owner_gear` is set by `#[toolkit::consumes]` to the gear's declared
775        // `#[toolkit::gear(name = ...)]`, falling back to the kebab-case of the
776        // struct ident when that attribute is absent. It is used as the config key
777        // `gears.<owner_gear>.config.consumer_wiring.<dep>` and as the owner of the
778        // hub view the proxy is wired into. If it does not match any registered
779        // gear name, the proxy is wired process-wide and that config key silently
780        // resolves to nothing, so warn.
781        let known_gears: std::collections::HashSet<&str> =
782            self.registry.gears().iter().map(GearEntry::name).collect();
783        // In-process gears with no REST API: a `Remote` outcome for
784        // one of these is a self-pointing dead proxy (see the hard error below).
785        // Directory advertisement is a separate choice: a partial REST provider
786        // can opt out so other contracts resolve to a provider in another process.
787        let unreachable_in_process: std::collections::HashSet<&str> = self
788            .registry
789            .gears()
790            .iter()
791            .filter(|gear| !gear.caps.has::<RestApiCap>())
792            .map(GearEntry::name)
793            .collect();
794        for reg in regs {
795            if !known_gears.contains(reg.owner_gear) {
796                tracing::warn!(
797                    owner = reg.owner_gear,
798                    dep = reg.dep_gear,
799                    "proxy-wiring: consumer's owner gear name does not match any registered gear; \
800                     the `gears.{}.config.consumer_wiring.{}` static override will never resolve. \
801                     Ensure the consumer's `#[toolkit::gear(name = ...)]` matches its registered name.",
802                    reg.owner_gear,
803                    reg.dep_gear,
804                );
805            }
806        }
807
808        let mut outcomes = Vec::with_capacity(regs.len());
809        // A dep is resolved at wiring time only if no consumer of it needs the
810        // directory: with one consumer on a static endpoint and another on
811        // discovery, the dep waits for the probe.
812        let mut resolved_now: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
813        let mut remote_deps: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
814        for reg in regs {
815            // Read the consumer's `consumer_wiring.<dep>` entry (if any) and
816            // split it into an optional static-endpoint override and the
817            // per-deployment `ClientTuning` (timeout/retry/pool/concurrency).
818            let (endpoint_override, mut tuning) =
819                match read_consumer_wiring(self.gears_cfg.as_ref(), reg.owner_gear, reg.dep_gear)
820                    .map_err(|source| RegistryError::ProxyWiring {
821                        gear: reg.owner_gear,
822                        source,
823                    })? {
824                    Some(wiring) => wiring.into_parts(),
825                    None => (None, toolkit_contract::wiring::ClientTuning::default()),
826                };
827
828            // Thread the process's platform-plane credential onto the tuning so
829            // the wired (directory-resolving) client's platform-plane methods
830            // attach `X-ToolKit-Internal-Token` (`cpt-cf-adr-two-plane-auth`).
831            // This is the genuine remote inter-gear path (Profile 2/3); a
832            // co-located local impl short-circuits before the credential is used.
833            tuning = tuning
834                .with_internal_token_provider(self.ctx_builder.internal_token_provider().cloned());
835
836            // ADR-0004 static-endpoint override (dev/test escape hatch): a
837            // configured `endpoint` wires the dep directly via a
838            // `StaticEndpointResolver`, bypassing discovery. It was validated as an
839            // absolute URI at parse time (invalid ones aborted above) and is
840            // resolvable by construction, so no probe loop is needed. Warned — must
841            // not be used in production.
842            let is_static = endpoint_override.is_some();
843            let reg_resolver: Arc<dyn EndpointResolver> = if let Some(endpoint) = &endpoint_override
844            {
845                tracing::warn!(
846                    owner = reg.owner_gear,
847                    dep = reg.dep_gear,
848                    endpoint = %endpoint,
849                    "proxy-wiring: STATIC endpoint override in use (ADR-0004 dev/test \
850                     escape hatch) - bypasses service discovery; MUST NOT be used in \
851                     production"
852                );
853                Arc::new(crate::discovery::StaticEndpointResolver::new(
854                    endpoint.clone(),
855                ))
856            } else {
857                Arc::clone(&resolver)
858            };
859
860            // Each registered consumer wires into its own view, so its proxy carries
861            // its own settings. An owner that is not a gear here (an SDK-level
862            // registration such as cluster-sdk's, or a stray consumer) wires
863            // process-wide.
864            let hub = if known_gears.contains(reg.owner_gear) {
865                self.client_hub.for_gear(reg.owner_gear)
866            } else {
867                Arc::clone(&self.client_hub)
868            };
869            let outcome = (reg.wire)(&hub, reg_resolver, tuning).map_err(|source| {
870                RegistryError::ProxyWiring {
871                    gear: reg.owner_gear,
872                    source,
873                }
874            })?;
875            self.dep_checker.register_dep(reg.dep_gear.to_owned());
876            match outcome {
877                // Local impl won the hub short-circuit — resolved.
878                crate::discovery::WireOutcome::Local => {
879                    resolved_now.insert(reg.dep_gear);
880                }
881                // Static override → fixed endpoint, always resolvable — no probe.
882                crate::discovery::WireOutcome::Remote if is_static => {
883                    resolved_now.insert(reg.dep_gear);
884                }
885                // A registered consumer depends on an in-process dep with no local
886                // impl and no REST API: wiring fell to a self-pointing proxy that
887                // would gate `/readyz` forever. Gated on the owner being registered
888                // too, so a stray/unused consumer (owner not in this process) falls
889                // through to the normal remote path below instead of aborting.
890                crate::discovery::WireOutcome::Remote
891                    if known_gears.contains(reg.owner_gear)
892                        && unreachable_in_process.contains(reg.dep_gear) =>
893                {
894                    return Err(RegistryError::ProxyWiring {
895                        gear: reg.owner_gear,
896                        source: anyhow::anyhow!(
897                            "consumer '{}' depends on in-process gear '{}', which registered no \
898                             local impl and serves no REST API; the provider must register its \
899                             client in init() (#[toolkit::provides] wire_* or ClientHub::register) \
900                             or serve the contract over REST.",
901                            reg.owner_gear,
902                            reg.dep_gear,
903                        ),
904                    });
905                }
906                // Directory-resolved remote → gate readiness + background probe.
907                crate::discovery::WireOutcome::Remote => {
908                    remote_deps.insert(reg.dep_gear);
909                }
910            }
911            tracing::debug!(
912                owner = reg.owner_gear,
913                dep = reg.dep_gear,
914                outcome = ?outcome,
915                static_override = is_static,
916                "wired consumer contract"
917            );
918            outcomes.push(outcome);
919        }
920
921        for dep in resolved_now.difference(&remote_deps) {
922            self.dep_checker.mark_resolved(dep);
923        }
924
925        // Only remote deps need directory resolution; local wins are already
926        // resolved above. Without a directory the null resolver can never resolve
927        // them, so skip the probe entirely and leave those deps gating /readyz.
928        if !have_directory || remote_deps.is_empty() {
929            return Ok(outcomes);
930        }
931        let remote_deps: Vec<String> = remote_deps.into_iter().map(str::to_owned).collect();
932
933        let readiness = Arc::clone(&self.dep_checker);
934        let cancel = self.owned.clone();
935        tokio::spawn(async move {
936            const BASE: std::time::Duration = std::time::Duration::from_millis(100);
937            const MAX: std::time::Duration = std::time::Duration::from_secs(30);
938            let mut pending = remote_deps;
939            let mut backoff = BASE;
940            while !pending.is_empty() {
941                let mut still_pending = Vec::new();
942                for dep in pending {
943                    match resolver.resolve_endpoint(&dep).await {
944                        Ok(Some(_)) => {
945                            readiness.mark_resolved(&dep);
946                            tracing::info!(dep = %dep, "readiness: dependency resolved");
947                        }
948                        // No live instance yet — expected during startup churn.
949                        Ok(None) => still_pending.push(dep),
950                        // Genuine directory-backend failure: surface it (a stuck
951                        // Starting / 503 pod otherwise has no diagnostic trail).
952                        Err(e) => {
953                            tracing::warn!(dep = %dep, error = %e, "readiness: directory lookup failed");
954                            still_pending.push(dep);
955                        }
956                    }
957                }
958                pending = still_pending;
959                if pending.is_empty() {
960                    break;
961                }
962                tokio::select! {
963                    () = cancel.cancelled() => break,
964                    () = tokio::time::sleep(backoff) => {}
965                }
966                backoff = (backoff * 2).min(MAX);
967            }
968        });
969
970        Ok(outcomes)
971    }
972
973    /// Build manifests and policies once, checking ownership before any gear runs.
974    /// Application `init` reads the admitted manifest without rebuilding it.
975    fn build_gts_manifests(&self) -> Result<Vec<GtsPublicationPlan>, RegistryError> {
976        let mut manifests = Vec::new();
977        for entry in self.registry.gears() {
978            entry
979                .validate_gts_publication_config(self.gears_cfg.as_ref())
980                .map_err(|source| RegistryError::Publication {
981                    gear: entry.name,
982                    source,
983                })?;
984            let Some(publication) = entry.caps.query::<GtsPublicationCap>() else {
985                continue;
986            };
987            let descriptor = publication.descriptor();
988            let manifest = descriptor
989                .build_gts_manifest(self.gears_cfg.as_ref())
990                .map_err(|source| RegistryError::Publication {
991                    gear: entry.name,
992                    source,
993                })?;
994            let options = GtsPublicationOptions::from_config(entry.name, self.gears_cfg.as_ref())
995                .map_err(|source| RegistryError::Publication {
996                gear: entry.name,
997                source: crate::gts_publication::GtsPublicationError::Options {
998                    gear: descriptor.gear,
999                    source,
1000                }
1001                .into(),
1002            })?;
1003            manifests.push((descriptor, Arc::new(manifest), options));
1004        }
1005        crate::gts_publication::check_ownership(manifests.iter().map(|(_, m, _)| m.as_ref()))
1006            .map_err(|source| RegistryError::GtsOwnership { source })?;
1007        Ok(manifests)
1008    }
1009
1010    /// Before the GTS barrier, wire non-empty manifests' registry clients and
1011    /// consumed contracts of those providers. Prefer local clients; otherwise use
1012    /// resolving proxies with platform credentials. Other consumers wait for
1013    /// application `init` so proxies cannot shadow local application providers.
1014    /// Empty manifests need no publisher client or readiness dependency.
1015    ///
1016    /// Refuse a local advertised provider missing the contract: discovery would
1017    /// route publication back to itself (e.g. an embedded registry without a DB).
1018    fn wire_registry_clients(&self, manifests: &[GtsPublicationPlan]) -> Result<(), RegistryError> {
1019        self.wire_registry_clients_over(manifests, &self.consumer_registrations())
1020    }
1021
1022    /// [`Self::wire_registry_clients`] over the given consumer registrations.
1023    fn wire_registry_clients_over(
1024        &self,
1025        manifests: &[GtsPublicationPlan],
1026        all: &[&'static crate::discovery::ConsumerRegistration],
1027    ) -> Result<(), RegistryError> {
1028        let publications: Vec<crate::discovery::ConsumerRegistration> = manifests
1029            .iter()
1030            .filter(|(_, manifest, _)| !manifest.is_empty())
1031            .map(
1032                |(descriptor, _, _)| crate::discovery::ConsumerRegistration {
1033                    owner_gear: descriptor.gear,
1034                    dep_gear: descriptor.provider,
1035                    wire: descriptor.wire,
1036                },
1037            )
1038            .collect();
1039        if publications.is_empty() {
1040            return Ok(());
1041        }
1042        let providers: HashSet<&str> = publications.iter().map(|p| p.dep_gear).collect();
1043        let consumers: Vec<&crate::discovery::ConsumerRegistration> = all
1044            .iter()
1045            .copied()
1046            .filter(|reg| providers.contains(reg.dep_gear))
1047            .collect();
1048        // Explicit consumers reject duplicate contracts. Wire them first, then
1049        // let publication adapters reuse their proxies in the same gear view.
1050        // One batch keeps a static endpoint from resolving a dependency that
1051        // another consumer still needs to discover.
1052        let mut regs = self.unwired_consumer_registrations(&consumers);
1053        let consumer_count = regs.len();
1054        regs.extend(publications.iter());
1055        let outcomes = self.wire_untracked(&regs)?;
1056        for (publisher, outcome) in publications
1057            .iter()
1058            .zip(outcomes.into_iter().skip(consumer_count))
1059        {
1060            if outcome != crate::discovery::WireOutcome::Remote {
1061                continue;
1062            }
1063            self.check_child_registry_dependency(publisher.owner_gear, publisher.dep_gear)?;
1064            let advertised_here = self.registry.gears().iter().any(|entry| {
1065                entry.name == publisher.dep_gear
1066                    && entry
1067                        .caps
1068                        .query::<RestApiCap>()
1069                        .is_some_and(|rest| rest.advertised_in_directory())
1070            });
1071            if advertised_here {
1072                return Err(RegistryError::Publication {
1073                    gear: publisher.owner_gear,
1074                    source: anyhow::anyhow!(
1075                        "'{}' runs in this process and advertises itself, but does not provide \
1076                         the contract the publication needs here: publishing would call this \
1077                         process forever. Give it what it needs to provide the contract (an \
1078                         embedded types registry needs its database), or run it elsewhere",
1079                        publisher.dep_gear
1080                    ),
1081                });
1082            }
1083        }
1084        Ok(())
1085    }
1086
1087    /// Whether `gear` runs in this process, and in the system group.
1088    fn local_group(&self, gear: &str) -> Option<bool> {
1089        self.registry
1090            .gears()
1091            .iter()
1092            .find(|e| e.name == gear)
1093            .map(GearEntry::is_system)
1094    }
1095
1096    /// A remote publisher cannot discover its own unstarted child. An explicit
1097    /// endpoint may name an already-running external registry instead.
1098    fn check_child_registry_dependency(
1099        &self,
1100        publisher: &'static str,
1101        provider: &str,
1102    ) -> Result<(), RegistryError> {
1103        let child = self.oop_options.as_ref().is_some_and(|options| {
1104            options
1105                .gears
1106                .iter()
1107                .any(|child| child.gear_name == provider)
1108        });
1109        if !child {
1110            return Ok(());
1111        }
1112        let wiring = read_consumer_wiring(self.gears_cfg.as_ref(), publisher, provider).map_err(
1113            |source| RegistryError::Publication {
1114                gear: publisher,
1115                source,
1116            },
1117        )?;
1118        if wiring.is_some_and(|wiring| wiring.endpoint.is_some()) {
1119            return Ok(());
1120        }
1121        Err(RegistryError::Publication {
1122            gear: publisher,
1123            source: anyhow::anyhow!(
1124                "'{publisher}' publishes to child '{provider}', which starts only after parent \
1125                 preparation; use an in-process registry or an already-running external registry"
1126            ),
1127        })
1128    }
1129
1130    /// Reject early wiring to a local application provider before any gear runs:
1131    /// a system consumer or non-empty publication would cache a proxy before the
1132    /// provider registers its local client.
1133    fn check_wiring_groups(
1134        &self,
1135        manifests: &[GtsPublicationPlan],
1136        regs: &[&'static crate::discovery::ConsumerRegistration],
1137    ) -> Result<(), RegistryError> {
1138        let application = |gear: &str| self.local_group(gear) == Some(false);
1139        for reg in regs {
1140            if self.local_group(reg.owner_gear) == Some(true) && application(reg.dep_gear) {
1141                return Err(RegistryError::ProxyWiring {
1142                    gear: reg.owner_gear,
1143                    source: anyhow::anyhow!(
1144                        "system gear '{}' consumes '{}', an application gear of this \
1145                         process: its client is needed before that gear initializes",
1146                        reg.owner_gear,
1147                        reg.dep_gear
1148                    ),
1149                });
1150            }
1151        }
1152        for (descriptor, manifest, _) in manifests {
1153            if !manifest.is_empty() && application(descriptor.provider) {
1154                return Err(RegistryError::Publication {
1155                    gear: descriptor.gear,
1156                    source: anyhow::anyhow!(
1157                        "'{}' publishes to '{}', an application gear of this process: the \
1158                         publication precedes every application `init`",
1159                        descriptor.gear,
1160                        descriptor.provider
1161                    ),
1162                });
1163            }
1164            if !manifest.is_empty() && self.local_group(descriptor.provider).is_none() {
1165                self.check_child_registry_dependency(descriptor.gear, descriptor.provider)?;
1166            }
1167        }
1168        Ok(())
1169    }
1170
1171    /// After system `init`, wire registrations owned or provided by system gears.
1172    /// Local system clients now win over proxies and are ready for `post_init`.
1173    /// Others wait for application `init` to avoid shadowing its local providers.
1174    fn wire_system_clients(
1175        &self,
1176        all: &[&'static crate::discovery::ConsumerRegistration],
1177    ) -> Result<(), RegistryError> {
1178        let system = |gear: &str| self.local_group(gear) == Some(true);
1179        let regs: Vec<&crate::discovery::ConsumerRegistration> = all
1180            .iter()
1181            .copied()
1182            .filter(|reg| system(reg.owner_gear) || system(reg.dep_gear))
1183            .collect();
1184        self.wire_consumer_registrations(&regs).map(drop)
1185    }
1186
1187    /// `POST_INIT` phase over every gear, the system group first.
1188    #[cfg(test)]
1189    async fn run_post_init_phase(&self) -> Result<(), RegistryError> {
1190        self.run_post_init_phase_for(&self.by_group()).await
1191    }
1192
1193    /// `POST_INIT` phase: every gear's `post_init` of `entries`, after their
1194    /// group's `init` and proxy wiring, in the given order.
1195    async fn run_post_init_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
1196        tracing::info!(gears = entries.len(), "Phase: post_init");
1197
1198        for entry in entries {
1199            if self.cancel.is_cancelled() {
1200                tracing::warn!("Post-init phase cancelled by signal");
1201                return Err(RegistryError::Cancelled);
1202            }
1203            let ctx = self.ctx_builder.for_gear(entry.name).await.map_err(|e| {
1204                RegistryError::PostInit {
1205                    gear: entry.name,
1206                    source: e,
1207                }
1208            })?;
1209            entry
1210                .core
1211                .post_init(&ctx)
1212                .await
1213                .map_err(|e| RegistryError::PostInit {
1214                    gear: entry.name,
1215                    source: e,
1216                })?;
1217        }
1218
1219        Ok(())
1220    }
1221
1222    /// Finalize legacy in-memory registrations once, after all application `init`s
1223    /// and proxy wiring, before application `post_init`. Removed with ready mode.
1224    async fn run_legacy_finalization(&self) -> Result<(), RegistryError> {
1225        let sys_ctx = self.system_context();
1226        for entry in self.registry.gears() {
1227            if let Some(sys_mod) = entry.caps.query::<SystemCap>() {
1228                sys_mod
1229                    .legacy_finalize_after_application_init(&sys_ctx)
1230                    .await
1231                    .map_err(|e| RegistryError::PostInit {
1232                        gear: entry.name,
1233                        source: e.context("legacy finalization after application init"),
1234                    })?;
1235            }
1236        }
1237        Ok(())
1238    }
1239
1240    /// Await all manifests' admission concurrently, then store them for application contexts.
1241    /// Backend binding errors fail startup. Refusal or expiry returns
1242    /// [`AppStartup::Failed`] without application `init` or a startup retry.
1243    async fn run_gts_publication_barrier(
1244        &self,
1245        manifests: &[GtsPublicationPlan],
1246    ) -> Result<AppStartup, RegistryError> {
1247        let mut prepared = Vec::with_capacity(manifests.len());
1248        for (descriptor, manifest, options) in manifests {
1249            prepared.push(
1250                PreparedGtsPublication::bind(
1251                    descriptor,
1252                    Arc::clone(manifest),
1253                    *options,
1254                    &self.client_hub.for_gear(descriptor.gear),
1255                )
1256                .map_err(|e| RegistryError::Publication {
1257                    gear: descriptor.gear,
1258                    source: e.into(),
1259                })?,
1260            );
1261        }
1262        if prepared.iter().any(|p| !p.gts_manifest().is_empty()) {
1263            tracing::info!(
1264                publishers = prepared.len(),
1265                "Phase: GTS publication (application group waits for admission)"
1266            );
1267        }
1268        let results = crate::gts_publication::publish_all(
1269            &prepared,
1270            &self.cancel,
1271            Arc::new(|gear, detail: &str| {
1272                tracing::debug!(gear, detail, "GTS publication pending");
1273            }),
1274            true,
1275        )
1276        .await;
1277
1278        let failures: Vec<_> = results
1279            .into_iter()
1280            .filter_map(|(_, result)| match result {
1281                Ok(()) | Err(crate::gts_publication::GtsPublicationError::Cancelled { .. }) => None,
1282                Err(e) => Some(e),
1283            })
1284            .collect();
1285        if !failures.is_empty() {
1286            return Ok(AppStartup::Failed(
1287                RegistryError::ApplicationGroupNotStarted { failures },
1288            ));
1289        }
1290        if self.cancel.is_cancelled() {
1291            return Ok(AppStartup::Cancelled);
1292        }
1293        for publication in &prepared {
1294            self.gts_admitted.insert(publication.shared_gts_manifest());
1295        }
1296        Ok(AppStartup::Started)
1297    }
1298
1299    /// The host gear and its REST host capability, if any.
1300    fn rest_host(&self) -> Option<(&GearEntry, Arc<dyn crate::contracts::ApiGatewayCapability>)> {
1301        self.registry
1302            .gears()
1303            .iter()
1304            .find_map(|e| e.caps.query::<ApiGatewayCap>().map(|host| (e, host)))
1305    }
1306
1307    /// REST phase: compose the full router against the REST host.
1308    ///
1309    /// Prepares the host, registers every gear's routes, then finalizes with
1310    /// `OpenAPI` endpoints before the application group's REST host starts.
1311    async fn run_rest_phase(&self) -> Result<Router, RegistryError> {
1312        tracing::info!("Phase: rest (sync)");
1313
1314        // Find host(s) and whether any rest gears exist
1315        let host_count = self
1316            .registry
1317            .gears()
1318            .iter()
1319            .filter(|e| e.caps.has::<ApiGatewayCap>())
1320            .count();
1321
1322        match host_count {
1323            0 => {
1324                return if self
1325                    .registry
1326                    .gears()
1327                    .iter()
1328                    .any(|e| e.caps.has::<RestApiCap>())
1329                {
1330                    Err(RegistryError::RestRequiresHost)
1331                } else {
1332                    Ok(Router::new())
1333                };
1334            }
1335            1 => { /* proceed */ }
1336            _ => return Err(RegistryError::MultipleRestHosts),
1337        }
1338
1339        let (host_entry, host) = self
1340            .rest_host()
1341            .ok_or(RegistryError::RestHostNotFoundAfterValidation)?;
1342        let host_ctx = self
1343            .ctx_builder
1344            .for_gear(host_entry.name)
1345            .await
1346            .map_err(|e| RegistryError::RestPrepare {
1347                gear: host_entry.name,
1348                source: e,
1349            })?;
1350        let hc_registry = self.rest_health_registry();
1351        let router = host
1352            .rest_prepare(&host_ctx, Router::new(), Arc::clone(&hc_registry))
1353            .map_err(|source| RegistryError::RestPrepare {
1354                gear: host_entry.name,
1355                source,
1356            })?;
1357
1358        let all: Vec<_> = self.registry.gears().iter().collect();
1359        let router = self
1360            .add_rest_routes(router, &hc_registry, &all, host.as_registry())
1361            .await?;
1362
1363        // Host finalize: attach /openapi.json and /docs, persist Router if needed (no server start)
1364        host.rest_finalize(&host_ctx, router, hc_registry)
1365            .map_err(|source| RegistryError::RestFinalize {
1366                gear: host_entry.name,
1367                source,
1368            })
1369    }
1370
1371    /// Collect the gRPC installers of the service gears of the system group
1372    /// (`system = true`) or the application group, reject duplicate service
1373    /// names, and pin their owners.
1374    async fn collect_grpc_installers(
1375        &self,
1376        system: bool,
1377        seen: &mut HashSet<&'static str>,
1378    ) -> Result<Vec<crate::runtime::GearInstallers>, RegistryError> {
1379        let mut gears_data = Vec::new();
1380        // Compiled-in service_name -> owning-gear map, installed as
1381        // authoritative ownership below (see
1382        // `GearManager::merge_authoritative_grpc_service_owners`).
1383        let mut owners: std::collections::HashMap<String, String> =
1384            std::collections::HashMap::new();
1385        for (gear_name, service_gear) in &self.registry.grpc_services {
1386            let in_group = self
1387                .registry
1388                .gears()
1389                .iter()
1390                .any(|e| e.name == gear_name.as_str() && e.is_system() == system);
1391            if !in_group {
1392                continue;
1393            }
1394            let ctx = self.ctx_builder.for_gear(gear_name).await.map_err(|err| {
1395                RegistryError::GrpcRegister {
1396                    gear: gear_name.clone(),
1397                    source: err,
1398                }
1399            })?;
1400
1401            let installers = service_gear
1402                .get_grpc_services(&ctx)
1403                .await
1404                .map_err(|source| RegistryError::GrpcRegister {
1405                    gear: gear_name.clone(),
1406                    source,
1407                })?;
1408
1409            for reg in &installers {
1410                if !seen.insert(reg.service_name) {
1411                    return Err(RegistryError::GrpcRegister {
1412                        gear: gear_name.clone(),
1413                        source: anyhow::anyhow!(
1414                            "Duplicate gRPC service name: {}",
1415                            reg.service_name
1416                        ),
1417                    });
1418                }
1419                owners.insert(reg.service_name.to_owned(), gear_name.clone());
1420            }
1421
1422            gears_data.push(crate::runtime::GearInstallers {
1423                gear_name: gear_name.clone(),
1424                installers,
1425            });
1426        }
1427        if !owners.is_empty() {
1428            self.gear_manager
1429                .merge_authoritative_grpc_service_owners(owners);
1430        }
1431        Ok(gears_data)
1432    }
1433
1434    /// Whether gRPC is in play at all; an error when services exist without a hub.
1435    fn grpc_in_use(&self) -> Result<bool, RegistryError> {
1436        match (
1437            &self.registry.grpc_hub,
1438            self.registry.grpc_services.is_empty(),
1439        ) {
1440            (None, true) => Ok(false),
1441            (None, false) => Err(RegistryError::GrpcRequiresHub),
1442            (Some(_), _) => Ok(true),
1443        }
1444    }
1445
1446    /// Initial gRPC batch: the services of the system gears, for the
1447    /// hub to serve when it starts. Says whether application services follow.
1448    async fn run_grpc_initial_phase(
1449        &self,
1450        seen: &mut HashSet<&'static str>,
1451    ) -> Result<(), RegistryError> {
1452        if !self.grpc_in_use()? {
1453            return Ok(());
1454        }
1455        tracing::info!("Phase: grpc (initial services)");
1456        let gears = self.collect_grpc_installers(true, seen).await?;
1457        let more_batches = self.registry.grpc_services.iter().any(|(gear, _)| {
1458            self.registry
1459                .gears()
1460                .iter()
1461                .any(|e| e.name == gear.as_str() && !e.is_system())
1462        });
1463        let hub_name = self.registry.grpc_hub.clone().unwrap_or_default();
1464        self.grpc_installers
1465            .set(crate::runtime::GrpcInstallerData {
1466                gears,
1467                more_batches,
1468            })
1469            .map_err(|source| RegistryError::GrpcRegister {
1470                gear: hub_name,
1471                source,
1472            })
1473    }
1474
1475    /// Late gRPC batch: the application group's services, installed by the
1476    /// running hub on its listener. Returns once the hub acknowledged them.
1477    async fn run_grpc_late_phase(
1478        &self,
1479        seen: &mut HashSet<&'static str>,
1480    ) -> Result<(), RegistryError> {
1481        if !self.grpc_in_use()? {
1482            return Ok(());
1483        }
1484        let hub_name = self.registry.grpc_hub.clone().unwrap_or_default();
1485        let gears = self.collect_grpc_installers(false, seen).await?;
1486        if gears.is_empty() {
1487            self.grpc_installers.close();
1488            return Ok(());
1489        }
1490        tracing::info!(gears = gears.len(), "Phase: grpc (late services)");
1491        let hub_runs = self.start_called.lock().contains(hub_name.as_str());
1492        let installed = self.grpc_installers.publish_late(gears).map_err(|source| {
1493            RegistryError::GrpcRegister {
1494                gear: hub_name.clone(),
1495                source,
1496            }
1497        })?;
1498        self.grpc_installers.close();
1499        if !hub_runs {
1500            // The hub runs in the application group: it takes the late batch
1501            // when it starts.
1502            return Ok(());
1503        }
1504        let ack = tokio::select! {
1505            () = self.cancel.cancelled() => return Err(RegistryError::Cancelled),
1506            ack = tokio::time::timeout(LATE_GRPC_INSTALL_TIMEOUT, installed) => ack,
1507        };
1508        match ack {
1509            Ok(Ok(Ok(()))) => Ok(()),
1510            Ok(Ok(Err(source))) => Err(RegistryError::GrpcRegister {
1511                gear: hub_name,
1512                source,
1513            }),
1514            Ok(Err(_)) => Err(RegistryError::GrpcRegister {
1515                gear: hub_name,
1516                source: anyhow::anyhow!("the gRPC hub dropped the late services uninstalled"),
1517            }),
1518            Err(_) => Err(RegistryError::GrpcRegister {
1519                gear: hub_name,
1520                source: anyhow::anyhow!(
1521                    "the gRPC hub did not install the late services within {}s",
1522                    LATE_GRPC_INSTALL_TIMEOUT.as_secs()
1523                ),
1524            }),
1525        }
1526    }
1527
1528    /// START phase over every gear, the system group first.
1529    #[cfg(test)]
1530    async fn run_start_phase(&self) -> Result<(), RegistryError> {
1531        self.run_start_phase_for(&self.by_group()).await
1532    }
1533
1534    /// START phase: start the stateful gears of `entries` in order.
1535    async fn run_start_phase_for(&self, entries: &[&GearEntry]) -> Result<(), RegistryError> {
1536        tracing::info!(gears = entries.len(), "Phase: start");
1537
1538        for e in entries {
1539            if let Some(s) = e.caps.query::<RunnableCap>() {
1540                tracing::debug!(
1541                    gear = e.name,
1542                    is_system = e.is_system(),
1543                    "Starting stateful gear"
1544                );
1545                self.start_called.lock().insert(e.name);
1546                s.start(self.cancel.clone())
1547                    .await
1548                    .map_err(|source| RegistryError::Start {
1549                        gear: e.name,
1550                        source,
1551                    })?;
1552                tracing::info!(gear = e.name, "Started gear");
1553            }
1554        }
1555
1556        Ok(())
1557    }
1558
1559    /// Stop a single gear, logging errors but continuing execution.
1560    async fn stop_one_gear(entry: &GearEntry, cancel: CancellationToken) {
1561        if let Some(s) = entry.caps.query::<RunnableCap>() {
1562            match s.stop(cancel).await {
1563                Err(err) => {
1564                    tracing::warn!(gear =  entry.name, error = %err, "Failed to stop gear");
1565                }
1566                _ => {
1567                    tracing::info!(gear = entry.name, "Stopped gear");
1568                }
1569            }
1570        }
1571    }
1572
1573    /// STOP phase: stop all started gears: the application group, then the
1574    /// system group, each in reverse order.
1575    ///
1576    /// # Two-Phase Shutdown Contract
1577    ///
1578    /// This phase implements a proper two-phase shutdown for **each gear**:
1579    ///
1580    /// 1. **Graceful stop request**: Each gear's `stop(deadline_token)` is called with a
1581    ///    *fresh* cancellation token (not the already-cancelled root token). Gears should
1582    ///    interpret this as "please stop gracefully".
1583    ///
1584    /// 2. **Hard-stop deadline**: After `shutdown_deadline` expires **for that gear**,
1585    ///    its `deadline_token` is cancelled. Gears should interpret this as "abort immediately".
1586    ///
1587    /// Each gear gets its own independent deadline — if gear A takes 25s to stop,
1588    /// gear B still gets the full `shutdown_deadline` for its graceful shutdown.
1589    ///
1590    /// This allows gears to implement real graceful shutdown:
1591    /// - Request cooperative shutdown of child tasks
1592    /// - Wait for them to finish gracefully
1593    /// - If `deadline_token` fires, switch to hard-abort mode
1594    ///
1595    /// Errors are logged but do not fail the shutdown process.
1596    /// Note: `OoP` gears are stopped automatically by the backend when the
1597    /// cancellation token is triggered.
1598    async fn run_stop_phase(&self) -> Result<(), RegistryError> {
1599        tracing::info!("Phase: stop");
1600
1601        // Drop our REST providers from the directory first, so consumers stop
1602        // resolving an endpoint that is about to disappear.
1603        self.deregister_rest_providers().await;
1604
1605        let deadline = self.shutdown_deadline;
1606
1607        // The application group first: it may still use the system group.
1608        let in_reverse = self
1609            .registry
1610            .gears()
1611            .iter()
1612            .rev()
1613            .filter(|e| !e.is_system())
1614            .chain(self.registry.gears().iter().rev().filter(|e| e.is_system()));
1615        for e in in_reverse {
1616            let gear_name = e.name;
1617            // Only a gear whose `start` was called has anything to stop.
1618            if !self.start_called.lock().contains(gear_name) {
1619                continue;
1620            }
1621
1622            // Create a fresh deadline token for THIS gear
1623            // Each gear gets the full shutdown_deadline independently
1624            let deadline_token = CancellationToken::new();
1625            let deadline_token_for_timeout = deadline_token.clone();
1626
1627            // Spawn a task to cancel this gear's deadline token after shutdown_deadline
1628            let deadline_task = tokio::spawn(async move {
1629                tokio::time::sleep(deadline).await;
1630                tracing::warn!(
1631                    gear = gear_name,
1632                    deadline_secs = deadline.as_secs(),
1633                    "Gear shutdown deadline reached, sending hard-stop signal"
1634                );
1635                deadline_token_for_timeout.cancel();
1636            });
1637
1638            // Stop this gear with its own deadline token
1639            // The gear can observe the token transition from uncancelled→cancelled
1640            Self::stop_one_gear(e, deadline_token).await;
1641
1642            // Cancel the deadline task and await it to ensure full cleanup
1643            deadline_task.abort();
1644            #[allow(clippy::let_underscore_must_use)]
1645            let _ = deadline_task.await;
1646        }
1647
1648        Ok(())
1649    }
1650
1651    /// Run the stop phase under a force-exit watchdog so a stop that hangs on a
1652    /// blocking syscall cannot wedge shutdown. The watchdog disarms when the
1653    /// phase returns (success or failure) or if this future is dropped.
1654    async fn run_stop_phase_guarded(&self) -> Result<(), RegistryError> {
1655        let gear_count = u32::try_from(self.registry.gears().len().max(1)).unwrap_or(1);
1656        let stop_timeout = self
1657            .shutdown_deadline
1658            .checked_mul(gear_count)
1659            .and_then(|d| d.checked_add(std::time::Duration::from_secs(5)))
1660            .unwrap_or(self.shutdown_deadline);
1661
1662        let _watchdog = arm_force_exit_watchdog(
1663            stop_timeout,
1664            format!(
1665                "shutdown: stop phase timed out, force exiting timeout_secs={}",
1666                stop_timeout.as_secs()
1667            ),
1668        );
1669
1670        self.run_stop_phase().await
1671    }
1672
1673    /// End a pending preparation, the runtime's own tasks and the gRPC
1674    /// batches, stop and join the spawned children, then
1675    /// stop every started gear. Runs after a failed startup as at shutdown;
1676    /// it never cancels the caller's token.
1677    async fn shut_down(&self) -> Result<(), RegistryError> {
1678        self.dep_checker.set_draining(true);
1679        self.owned.cancel();
1680        // Stop discovery traffic before joining a potentially slow HTTP drain.
1681        if tokio::time::timeout(self.shutdown_deadline, self.deregister_rest_providers())
1682            .await
1683            .is_err()
1684        {
1685            tracing::warn!("REST provider deregistration timed out");
1686        }
1687        if let Some((entry, host)) = self.rest_host() {
1688            match tokio::time::timeout(self.shutdown_deadline, host.rest_shutdown_bootstrap()).await
1689            {
1690                Ok(Ok(())) => {}
1691                Ok(Err(error)) => {
1692                    tracing::warn!(gear = entry.name, %error, "REST bootstrap shutdown failed");
1693                }
1694                Err(_) => tracing::warn!(gear = entry.name, "REST bootstrap shutdown timed out"),
1695            }
1696        }
1697        self.grpc_installers.close();
1698        if let Some(oop) = &self.oop_options {
1699            // Bound child shutdown so in-process gears still stop if reaping hangs.
1700            // A timeout drops this wait; LocalProcessBackend's own shutdown task continues.
1701            // Other backends must also tolerate a dropped shutdown future.
1702            if tokio::time::timeout(self.shutdown_deadline, oop.backend.shutdown_all())
1703                .await
1704                .is_err()
1705            {
1706                tracing::warn!(
1707                    timeout_secs = self.shutdown_deadline.as_secs(),
1708                    "shutdown: OoP children did not stop in time; stopping the in-process gears"
1709                );
1710            }
1711        }
1712        self.run_stop_phase_guarded().await
1713    }
1714
1715    /// `OoP` SPAWN phase: spawn configured children after parent preparation,
1716    /// application start and REST provider registration. Children can use the
1717    /// parent's full API; parent publication must not depend on its children.
1718    /// Child readiness is not awaited.
1719    async fn run_oop_spawn_phase(&self) -> Result<(), RegistryError> {
1720        let oop_opts = match &self.oop_options {
1721            Some(opts) if !opts.gears.is_empty() => opts,
1722            _ => return Ok(()),
1723        };
1724
1725        tracing::info!("Phase: oop_spawn");
1726
1727        // Wait for grpc_hub to publish its endpoint (it runs async in start phase)
1728        let directory_endpoint = self.wait_for_grpc_hub_endpoint().await;
1729
1730        for gear_cfg in &oop_opts.gears {
1731            // Build environment with directory endpoint and rendered config
1732            // Note: User controls --config via execution.args in master config
1733            let mut env = gear_cfg.env.clone();
1734            env.insert(
1735                TOOLKIT_MODULE_CONFIG_ENV.to_owned(),
1736                gear_cfg.rendered_config_json.clone(),
1737            );
1738            if let Some(ref endpoint) = directory_endpoint {
1739                env.insert(TOOLKIT_DIRECTORY_ENDPOINT_ENV.to_owned(), endpoint.clone());
1740            }
1741
1742            // Use args from execution config as-is (user controls --config via args)
1743            let args = gear_cfg.args.clone();
1744
1745            let spawn_config = OopSpawnConfig {
1746                gear_name: gear_cfg.gear_name.clone(),
1747                binary: gear_cfg.binary.clone(),
1748                args,
1749                env,
1750                working_directory: gear_cfg.working_directory.clone(),
1751            };
1752
1753            oop_opts
1754                .backend
1755                .spawn(spawn_config)
1756                .await
1757                .map_err(|e| RegistryError::OopSpawn {
1758                    gear: gear_cfg.gear_name.clone(),
1759                    source: e,
1760                })?;
1761
1762            tracing::info!(
1763                gear =  %gear_cfg.gear_name,
1764                directory_endpoint = ?directory_endpoint,
1765                "Spawned OoP gear via backend"
1766            );
1767        }
1768
1769        Ok(())
1770    }
1771
1772    /// Wait for `grpc-hub` to publish its bound endpoint.
1773    ///
1774    /// Polls the `GrpcHubGear::bound_endpoint()` with a short interval until available or timeout.
1775    /// Returns None if no `grpc-hub` is running or if it times out.
1776    async fn wait_for_grpc_hub_endpoint(&self) -> Option<String> {
1777        const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
1778        const MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
1779
1780        // Find grpc_hub in registry
1781        let grpc_hub = self
1782            .registry
1783            .gears()
1784            .iter()
1785            .find_map(|e| e.caps.query::<GrpcHubCap>());
1786
1787        let Some(hub) = grpc_hub else {
1788            return None; // No grpc_hub registered
1789        };
1790
1791        let start = std::time::Instant::now();
1792
1793        loop {
1794            if let Some(endpoint) = hub.bound_endpoint() {
1795                tracing::debug!(
1796                    endpoint = %endpoint,
1797                    elapsed_ms = start.elapsed().as_millis(),
1798                    "gRPC hub endpoint available"
1799                );
1800                return Some(endpoint);
1801            }
1802
1803            if hub.serves_no_endpoint() {
1804                tracing::debug!("gRPC hub binds no endpoint");
1805                return None;
1806            }
1807            if start.elapsed() > MAX_WAIT {
1808                tracing::warn!("Timed out waiting for gRPC hub to bind");
1809                return None;
1810            }
1811
1812            tokio::time::sleep(POLL_INTERVAL).await;
1813        }
1814    }
1815
1816    /// Wait for the REST host gateway to publish its bound endpoint.
1817    ///
1818    /// The gateway binds its listener asynchronously in the start phase, so the
1819    /// bound endpoint may not be set the instant the start phase returns; poll
1820    /// with a short interval until available or timeout.
1821    async fn wait_for_rest_endpoint(
1822        &self,
1823        host: &Arc<dyn crate::contracts::ApiGatewayCapability>,
1824    ) -> Option<String> {
1825        const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(10);
1826        const MAX_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
1827
1828        let start = std::time::Instant::now();
1829        loop {
1830            if let Some(endpoint) = host.bound_endpoint() {
1831                return Some(endpoint);
1832            }
1833            if start.elapsed() > MAX_WAIT {
1834                tracing::warn!("Timed out waiting for REST host to bind");
1835                return None;
1836            }
1837            tokio::time::sleep(POLL_INTERVAL).await;
1838        }
1839    }
1840
1841    /// Advertise `entries`' REST providers by gear name at the shared gateway URL,
1842    /// after application/REST-host startup and before child spawning. Covers both
1843    /// groups, through the local or remote `DirectoryClient` in `ClientHub`.
1844    /// No-op without a REST host or REST providers.
1845    async fn run_directory_register_phase(
1846        &self,
1847        entries: &[&GearEntry],
1848    ) -> Result<(), RegistryError> {
1849        let rest_gears: Vec<&'static str> = self
1850            .rest_provider_gears()
1851            .into_iter()
1852            .filter(|gear| entries.iter().any(|e| e.name == *gear))
1853            .collect();
1854        if rest_gears.is_empty() {
1855            return Ok(());
1856        }
1857
1858        let Some((_, host)) = self.rest_host() else {
1859            return Ok(()); // no REST host serving the routes
1860        };
1861
1862        if !self.advertiser.is_enabled() {
1863            let Some(endpoint) = self.wait_for_rest_endpoint(&host).await else {
1864                tracing::warn!(
1865                    "directory-register: REST host endpoint unavailable; skipping REST provider registration"
1866                );
1867                return Ok(());
1868            };
1869
1870            let Ok(dir) = self.client_hub.get::<dyn crate::DirectoryClient>() else {
1871                tracing::debug!(
1872                    "directory-register: no DirectoryClient in ClientHub; skipping REST provider registration"
1873                );
1874                return Ok(());
1875            };
1876
1877            self.advertiser.enable(dir, endpoint);
1878        }
1879        for gear in rest_gears {
1880            self.advertiser.advertise(gear).await;
1881        }
1882        Ok(())
1883    }
1884
1885    /// Names of all gears that provide a REST API (have `RestApiCap`), excluding
1886    /// the REST host gateway itself (`ApiGatewayCap`) — the gateway is the
1887    /// transport, not a contract provider, so it must not be advertised in the
1888    /// directory under its own gear name.
1889    fn rest_provider_gears(&self) -> Vec<&'static str> {
1890        self.registry
1891            .gears()
1892            .iter()
1893            .filter(|e| {
1894                e.caps
1895                    .query::<RestApiCap>()
1896                    .is_some_and(|rest| rest.advertised_in_directory())
1897                    && !e.caps.has::<ApiGatewayCap>()
1898            })
1899            .map(|e| e.name)
1900            .collect()
1901    }
1902
1903    /// Deregister this process's REST providers from the directory on shutdown,
1904    /// so consumers stop resolving an endpoint that is going away. Best-effort.
1905    async fn deregister_rest_providers(&self) {
1906        self.advertiser.deregister_all().await;
1907    }
1908
1909    /// Run the full gear lifecycle (all phases).
1910    ///
1911    /// This is the standard entry point for normal application execution.
1912    /// It runs all phases from pre-init through shutdown.
1913    ///
1914    /// # Errors
1915    ///
1916    /// Returns an error if any gear phase fails during execution.
1917    pub async fn run_gear_phases(self) -> anyhow::Result<()> {
1918        self.run_phases_internal(RunMode::Full).await
1919    }
1920
1921    /// Run only the migration phases (pre-init + DB migration).
1922    ///
1923    /// This is designed for cloud deployment workflows where database migrations
1924    /// need to run as a separate step before starting the application.
1925    /// The process exits after migrations complete.
1926    ///
1927    /// # Errors
1928    ///
1929    /// Returns an error if pre-init or migration phases fail.
1930    pub async fn run_migration_phases(self) -> anyhow::Result<()> {
1931        self.run_phases_internal(RunMode::MigrateOnly).await
1932    }
1933
1934    /// Run full startup and wait for shutdown, or run only `pre_init` and migrations
1935    /// for every gear in migration-only mode. Shared by both public phase runners.
1936    async fn run_phases_internal(self, mode: RunMode) -> anyhow::Result<()> {
1937        // Log execution mode
1938        match mode {
1939            RunMode::Full => {
1940                tracing::info!("Running full lifecycle (all phases)");
1941            }
1942            RunMode::MigrateOnly => {
1943                tracing::info!("Running in migration mode (pre-init + db phases only)");
1944            }
1945        }
1946
1947        // Migration-only: pre-init and migrations of every gear, then exit.
1948        if mode == RunMode::MigrateOnly {
1949            self.run_pre_init_phase().await?;
1950            // DB migration phase (the system group first)
1951            #[cfg(feature = "db")]
1952            self.run_db_phase().await?;
1953            tracing::info!("Migration phases completed successfully");
1954            return Ok(());
1955        }
1956
1957        // A startup that fails leaves no started gear running:
1958        // gears started so far are stopped before the error returns.
1959        let outcome = match self.run_startup_phases().await {
1960            Ok(outcome) => outcome,
1961            Err(e) => {
1962                if let Err(stop) = self.shut_down().await {
1963                    tracing::warn!(error = %stop, "stop after a failed startup reported an error");
1964                }
1965                return Err(e);
1966            }
1967        };
1968        let failed = startup_failure(outcome);
1969
1970        // Return failed preparation to the supervisor after cleanup.
1971        if failed.is_none() {
1972            self.cancel.cancelled().await;
1973        }
1974
1975        // Stop phase with hard timeout. Blocking stop implementations are
1976        // guarded by a watchdog thread so a hang cannot block shutdown,
1977        // whether in the in-process or OoP path.
1978        let stopped = self.shut_down().await;
1979        match failed {
1980            Some(failure) => {
1981                if let Err(stop) = stopped {
1982                    tracing::warn!(error = %stop, "stop after a failed application group reported an error");
1983                }
1984                Err(failure.into())
1985            }
1986            None => Ok(stopped?),
1987        }
1988    }
1989
1990    /// Mark readiness Draining as soon as shutdown begins, before requests finish.
1991    /// Started first in both profiles; ends with the runtime's owned tasks.
1992    fn spawn_drain_watcher(&self) {
1993        let readiness = Arc::clone(&self.dep_checker);
1994        let cancel = self.cancel.clone();
1995        let owned = self.owned.clone();
1996        tokio::spawn(async move {
1997            tokio::select! {
1998                biased;
1999                () = cancel.cancelled() => {
2000                    readiness.set_draining(true);
2001                }
2002                () = owned.cancelled() => {}
2003            }
2004        });
2005    }
2006
2007    /// Everything from the manifests to the started application group.
2008    async fn run_startup_phases(&self) -> anyhow::Result<AppStartup> {
2009        let system = self.group(true);
2010        let app = self.group(false);
2011        self.spawn_drain_watcher();
2012
2013        // Local configuration first: a manifest that does not build, or a
2014        // client that would be wired before its provider, fails before any
2015        // gear runs or anything is written.
2016        let manifests = self.build_gts_manifests()?;
2017        let regs = self.consumer_registrations();
2018        self.check_wiring_groups(&manifests, &regs)?;
2019        let mut rest = self.bind_rest_bootstrap().await?;
2020
2021        // System group, complete: pre-init, migrations, init, its clients,
2022        // post-init.
2023        self.run_pre_init_phase_for(&system).await?;
2024        #[cfg(feature = "db")]
2025        self.run_db_phase_for(&system).await?;
2026        self.run_init_phase_for(&system).await?;
2027        self.wire_system_clients(&regs)?;
2028        self.run_post_init_phase_for(&system).await?;
2029
2030        // Serve system routes on the listener already hosting probes.
2031        let mut grpc_seen = HashSet::new();
2032        self.run_grpc_initial_phase(&mut grpc_seen).await?;
2033        self.run_start_phase_for(&system).await?;
2034        if let Some(composition) = &mut rest {
2035            self.publish_system_rest(composition, &system).await?;
2036        }
2037
2038        // Application group: pre-init, migrations, the registry clients, then
2039        // the GTS barrier.
2040        self.run_pre_init_phase_for(&app).await?;
2041        #[cfg(feature = "db")]
2042        self.run_db_phase_for(&app).await?;
2043        self.wire_registry_clients(&manifests)?;
2044        match self.run_gts_publication_barrier(&manifests).await? {
2045            AppStartup::Started => {}
2046            other => {
2047                self.grpc_installers.close();
2048                return Ok(other);
2049            }
2050        }
2051
2052        self.run_init_phase_for(&app).await?;
2053        self.wire_consumer_registrations(&regs)?;
2054        self.run_legacy_finalization().await?;
2055        self.run_post_init_phase_for(&app).await?;
2056
2057        // Attach the full REST/gRPC surface before starting applications.
2058        if let Some(composition) = rest {
2059            self.finish_rest_bootstrap(composition, &app).await?;
2060        } else {
2061            let _router = self.run_rest_phase().await?;
2062        }
2063        self.run_grpc_late_phase(&mut grpc_seen).await?;
2064        self.run_start_phase_for(&app).await?;
2065        let all: Vec<&GearEntry> = self.registry.gears().iter().collect();
2066        self.run_directory_register_phase(&all).await?;
2067        self.dep_checker.mark_resolved(PREPARATION_GATE);
2068
2069        // Children only start once the parent can serve them. Neither the
2070        // registry nor GTS prerequisites of this process may rely on a child.
2071        self.run_oop_spawn_phase().await?;
2072        Ok(AppStartup::Started)
2073    }
2074}
2075
2076#[cfg(test)]
2077#[cfg_attr(coverage_nightly, coverage(off))]
2078#[path = "rest_advertiser_tests.rs"]
2079mod rest_advertiser_tests;
2080
2081/// Composed `OoP` router, serialized `OpenAPI`, and auth policy from the same specs.
2082#[cfg(feature = "bootstrap")]
2083type ComposedOopRouter = (Router, String, toolkit_http_middleware::RouteAuthPolicy);
2084
2085/// The host-less `OoP` router composed so far: each gear's routes are
2086/// registered once, the system gears' before the application group.
2087#[cfg(feature = "bootstrap")]
2088#[derive(Default)]
2089struct OopComposition {
2090    registry: crate::api::OpenApiRegistryImpl,
2091    router: Router,
2092    composed: HashSet<&'static str>,
2093}
2094
2095/// Out-of-process HTTP serving lifecycle (`cpt-cf-component-oop-bootstrap`).
2096#[cfg(feature = "bootstrap")]
2097impl HostRuntime {
2098    /// Register the routes of the `RestApiCap` gears among `entries` not
2099    /// registered yet into the **host-less** `composition`, and return the
2100    /// router so far with its generated `OpenAPI` document (serialized JSON)
2101    /// and auth policy.
2102    ///
2103    /// Unlike [`run_rest_phase`](Self::run_rest_phase), this does not require an
2104    /// `ApiGatewayCap` host: `OoP` gears serve their own routes directly.
2105    async fn compose_oop_router(
2106        &self,
2107        options: &crate::runtime::OopServeOptions,
2108        hc_registry: &Arc<crate::healthcheck::RestHealthcheckRegistry>,
2109        entries: &[&GearEntry],
2110        composition: &mut OopComposition,
2111    ) -> anyhow::Result<ComposedOopRouter> {
2112        use crate::api::OpenApiInfo;
2113        use anyhow::Context as _;
2114
2115        for entry in self.registry.gears() {
2116            if !entries.iter().any(|e| e.name == entry.name) {
2117                continue;
2118            }
2119            let Some(rest) = entry.caps.query::<RestApiCap>() else {
2120                continue;
2121            };
2122            if !composition.composed.insert(entry.name) {
2123                continue;
2124            }
2125            let ctx = self
2126                .ctx_builder
2127                .for_gear(entry.name)
2128                .await
2129                .with_context(|| format!("OoP router: build context for '{}'", entry.name))?;
2130            let router = std::mem::take(&mut composition.router);
2131            composition.router = rest
2132                .register_rest(&ctx, router, &composition.registry)
2133                .with_context(|| format!("OoP router: register_rest for '{}'", entry.name))?;
2134
2135            // Register the gear's readiness healthcheck (the same mechanism
2136            // the api-gateway host uses), so /readyz reflects it identically
2137            // whether the gear runs in-process or OoP.
2138            if let Some(hc) = rest.healthcheck(&ctx) {
2139                hc_registry.register(entry.name, hc);
2140            }
2141        }
2142
2143        let info = OpenApiInfo {
2144            title: options.gear_name.clone(),
2145            version: options
2146                .version
2147                .clone()
2148                .unwrap_or_else(|| "0.0.0".to_owned()),
2149            description: None,
2150            servers: vec![],
2151        };
2152        let openapi = composition
2153            .registry
2154            .build_openapi(&info)
2155            .context("OoP router: build OpenAPI document")?;
2156        let json = serde_json::to_string(&openapi).context("OoP router: serialize OpenAPI")?;
2157        let route_auth =
2158            super::oop_serve::route_auth_policy(composition.registry.operation_specs.iter());
2159
2160        Ok((composition.router.clone(), json, route_auth))
2161    }
2162
2163    /// Run the full `OoP` gear lifecycle: phases (`pre_init` … `start`), then
2164    /// serve the composed router with framework probes, background
2165    /// self-registration, dependency resolution, and graceful drain, then the
2166    /// `stop` phase.
2167    ///
2168    /// The listener binds first. The system group's routes attach as
2169    /// soon as it started — platform-plane calls only, tenant-plane calls get
2170    /// `503` — and the process is present in the directory then if its
2171    /// advertised gear is a system gear. The application group's routes
2172    /// attach on the same listener once it started.
2173    ///
2174    /// # Errors
2175    /// Returns an error if any lifecycle phase or the HTTP server fails.
2176    pub async fn run_oop_serving(
2177        self,
2178        options: crate::runtime::OopServeOptions,
2179    ) -> anyhow::Result<()> {
2180        use crate::runtime::ReadinessState;
2181
2182        tracing::info!("Running OoP serving lifecycle");
2183
2184        // Make the directory client reachable to the proxy-wiring phase, which
2185        // resolves remote `#[toolkit::consumes]` providers through the
2186        // `ClientHub`. The `OoP` presence loop uses `options.directory`
2187        // directly; consumer wiring reads it here.
2188        if self.client_hub.get::<dyn crate::DirectoryClient>().is_err() {
2189            self.client_hub
2190                .register::<dyn crate::DirectoryClient>(Arc::clone(&options.directory));
2191        }
2192
2193        // Shared gear healthcheck registry (same mechanism as the api-gateway
2194        // host path). Seeded with the root cancellation token so in-flight
2195        // checks are aborted on shutdown. Populated during router composition.
2196        let hc_registry = Arc::new(
2197            crate::healthcheck::RestHealthcheckRegistry::with_cancellation(self.cancel.clone()),
2198        );
2199
2200        // Readiness gates on `#[toolkit::consumes]` dependencies only — the same
2201        // policy as the in-process host path — via the shared `DependencyChecker`
2202        // fed by the proxy-wiring phase below. `deps = [...]`-only declarations
2203        // remain for topo-sort ordering but do NOT gate `/readyz`. The
2204        // healthcheck registry supplies the per-gear readiness dimension; both
2205        // feed the `/readyz` aggregate.
2206        let readiness = ReadinessState::from_checker(
2207            Arc::clone(&self.dep_checker),
2208            Arc::clone(&hc_registry),
2209            options.healthcheck_timeout,
2210        );
2211
2212        // Bind the HTTP server and serve probes BEFORE the (possibly slow)
2213        // lifecycle phases, so the kubelet's liveness probe (`/healthz`) passes
2214        // immediately instead of getting connection-refused during `start()`.
2215        // Gear routes reply `503 starting` until attached below.
2216        let mut server = super::oop_serve::OopHttpServer::start(
2217            Arc::clone(&readiness),
2218            options,
2219            self.cancel.clone(),
2220        )
2221        .await?;
2222
2223        self.spawn_drain_watcher();
2224        let mut composition = OopComposition::default();
2225        let outcome = self
2226            .run_oop_startup(&mut server, &hc_registry, &mut composition)
2227            .await;
2228
2229        let serve_result = match outcome {
2230            Ok(outcome) => {
2231                let failed = startup_failure(outcome);
2232                // End failed preparation promptly so the supervisor can restart.
2233                if failed.is_some() {
2234                    self.cancel.cancel();
2235                }
2236                // Serve until cancelled, drain, then deregister.
2237                let joined = server.join().await;
2238                match failed {
2239                    Some(failure) => {
2240                        if let Err(e) = joined {
2241                            tracing::warn!(error = %e, "OoP server after a failed application group reported an error");
2242                        }
2243                        Err(failure.into())
2244                    }
2245                    None => joined,
2246                }
2247            }
2248            Err(e) => {
2249                tracing::error!(error = %e, "OoP startup failed before serving gear routes");
2250                // Tear down the probe server that is already bound.
2251                self.cancel.cancel();
2252                if let Err(join_err) = server.join().await {
2253                    tracing::warn!(error = %join_err, "OoP probe server teardown after startup failure errored");
2254                }
2255                Err(e)
2256            }
2257        };
2258
2259        // Served or failed to start: the runtime's tasks end and gears stop. Errors are
2260        // logged but do not fail the shutdown process (same contract as
2261        // run_stop_phase).
2262        if let Err(e) = self.shut_down().await {
2263            tracing::warn!(error = %e, "OoP stop phase reported an error");
2264        }
2265
2266        serve_result
2267    }
2268
2269    /// The `OoP` phases from the manifests to the attached application routes.
2270    async fn run_oop_startup(
2271        &self,
2272        server: &mut super::oop_serve::OopHttpServer,
2273        hc_registry: &Arc<crate::healthcheck::RestHealthcheckRegistry>,
2274        composition: &mut OopComposition,
2275    ) -> anyhow::Result<AppStartup> {
2276        let system = self.group(true);
2277        let app = self.group(false);
2278        let advertised = server.options().gear_name.clone();
2279        let advertised_is_system = system.iter().any(|e| e.name == advertised.as_str());
2280        let root_is_advertised = || {
2281            self.registry
2282                .gears()
2283                .iter()
2284                .find(|entry| entry.name == advertised.as_str())
2285                .and_then(|entry| entry.caps.query::<RestApiCap>())
2286                .is_none_or(|rest| rest.advertised_in_directory())
2287        };
2288
2289        let manifests = self.build_gts_manifests()?;
2290        let regs = self.consumer_registrations();
2291        self.check_wiring_groups(&manifests, &regs)?;
2292
2293        // System group, complete before the application group.
2294        self.run_pre_init_phase_for(&system).await?;
2295        #[cfg(feature = "db")]
2296        self.run_db_phase_for(&system).await?;
2297        self.run_init_phase_for(&system).await?;
2298        self.wire_system_clients(&regs)?;
2299        self.run_post_init_phase_for(&system).await?;
2300        let mut grpc_seen = HashSet::new();
2301        self.run_grpc_initial_phase(&mut grpc_seen).await?;
2302        self.run_start_phase_for(&system).await?;
2303
2304        // System routes on the bound listener: platform-plane calls
2305        // only until the application group attached its routes.
2306        if system.iter().any(|e| e.caps.has::<RestApiCap>()) {
2307            let (router, openapi, route_auth) = self
2308                .compose_oop_router(server.options(), hc_registry, &system, composition)
2309                .await?;
2310            server.publish_bootstrap_routes(router, openapi, route_auth);
2311            if advertised_is_system && root_is_advertised() {
2312                server.start_presence();
2313            }
2314            // Every co-hosted system provider is discoverable at once,
2315            // whatever the root gear: an external publisher must reach a
2316            // registry the application group here may be waiting for.
2317            for entry in &system {
2318                if entry.name != advertised.as_str()
2319                    && entry
2320                        .caps
2321                        .query::<RestApiCap>()
2322                        .is_some_and(|rest| rest.advertised_in_directory())
2323                {
2324                    server.start_provider_presence(entry.name.to_owned());
2325                }
2326            }
2327        }
2328
2329        // Application group: pre-init, migrations, the registry clients, then
2330        // the GTS barrier.
2331        self.run_pre_init_phase_for(&app).await?;
2332        #[cfg(feature = "db")]
2333        self.run_db_phase_for(&app).await?;
2334        self.wire_registry_clients(&manifests)?;
2335        match self.run_gts_publication_barrier(&manifests).await? {
2336            AppStartup::Started => {}
2337            other => {
2338                self.grpc_installers.close();
2339                return Ok(other);
2340            }
2341        }
2342        self.run_init_phase_for(&app).await?;
2343        // Proxy-wiring before start: a gear resolving a consumed contract
2344        // during `start` finds the client in the hub under both profiles.
2345        self.wire_consumer_registrations(&regs)?;
2346        self.run_legacy_finalization().await?;
2347        self.run_post_init_phase_for(&app).await?;
2348        self.run_grpc_late_phase(&mut grpc_seen).await?;
2349        self.run_start_phase_for(&app).await?;
2350
2351        // The gear lifecycle has populated the ClientHub. If an in-process
2352        // authn stack (e.g. a linked authn-resolver gear) registered a
2353        // DynBearerAuthenticator bridge, install the tenant plane now —
2354        // before the final routes layer security_context_middleware. (The
2355        // platform plane is built eagerly at bootstrap from
2356        // `oop_http.internal_auth`.)
2357        server.resolve_bearer_authenticator(&self.client_hub);
2358        let all: Vec<&GearEntry> = self.registry.gears().iter().collect();
2359        let (router, openapi, route_auth) = self
2360            .compose_oop_router(server.options(), hc_registry, &all, composition)
2361            .await?;
2362        // Publish the full routes (they go live), then start directory
2363        // presence of the advertised gear: the directory never advertises it
2364        // while its routes reply 503.
2365        server.attach(router, openapi, route_auth)?;
2366        // First presence of an application root; a system root's restarts
2367        // with the full `OpenAPI` document.
2368        if root_is_advertised() {
2369            server.start_presence();
2370        }
2371        self.dep_checker.mark_resolved(PREPARATION_GATE);
2372        Ok(AppStartup::Started)
2373    }
2374}
2375
2376/// Read `gears.<owner>.config.consumer_wiring.<dep>` as a [`ConsumerWiring`].
2377///
2378/// `Ok(None)` when absent (the dep keeps discovery). A *present* entry that cannot
2379/// be deserialized is an `Err` that aborts proxy-wiring — the same fail-at-boot
2380/// contract the provider side uses for `client_wiring` ([`crate::wiring::read_wiring`]).
2381fn read_consumer_wiring(
2382    cfg: &dyn ConfigProvider,
2383    owner_gear: &str,
2384    dep_gear: &str,
2385) -> Result<Option<toolkit_contract::wiring::ConsumerWiring>, anyhow::Error> {
2386    let Some(value) = cfg
2387        .get_gear_config(owner_gear)
2388        .and_then(|c| c.get("config"))
2389        .and_then(|c| c.get("consumer_wiring"))
2390        .and_then(|c| c.get(dep_gear))
2391    else {
2392        return Ok(None);
2393    };
2394    // A bare string is the legacy static-endpoint shape; the raw serde error
2395    // ("invalid type: string") would not hint at the fix, so name the object form.
2396    if let Some(s) = value.as_str() {
2397        anyhow::bail!(
2398            "gear `{owner_gear}`: `consumer_wiring.{dep_gear}` is a bare string; the \
2399             static-endpoint override now lives on the object form — write it as \
2400             `{{ \"endpoint\": \"{s}\" }}`"
2401        );
2402    }
2403    serde_json::from_value::<toolkit_contract::wiring::ConsumerWiring>(value.clone())
2404        .map(Some)
2405        .map_err(|e| {
2406            anyhow::anyhow!("gear `{owner_gear}`: invalid consumer_wiring.{dep_gear}: {e}")
2407        })
2408}
2409
2410#[cfg(test)]
2411#[cfg(feature = "bootstrap")]
2412#[cfg_attr(coverage_nightly, coverage(off))]
2413#[path = "host_runtime_oop_tests.rs"]
2414mod host_runtime_oop_tests;
2415
2416#[cfg(test)]
2417#[cfg_attr(coverage_nightly, coverage(off))]
2418mod tests {
2419    use super::*;
2420    use crate::context::GearCtx;
2421    use crate::contracts::{Gear, RunnableCapability, SystemCapability};
2422    use crate::registry::RegistryBuilder;
2423    use std::sync::Arc;
2424    use std::sync::atomic::{AtomicUsize, Ordering};
2425    use tokio::sync::Mutex;
2426
2427    #[derive(Default)]
2428    #[allow(dead_code)]
2429    struct DummyCore;
2430    #[async_trait::async_trait]
2431    impl Gear for DummyCore {
2432        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2433            Ok(())
2434        }
2435    }
2436
2437    struct StopOrderTracker {
2438        my_order: usize,
2439        stop_order: Arc<AtomicUsize>,
2440    }
2441
2442    impl StopOrderTracker {
2443        fn new(counter: &Arc<AtomicUsize>, stop_order: Arc<AtomicUsize>) -> Self {
2444            let my_order = counter.fetch_add(1, Ordering::SeqCst);
2445            Self {
2446                my_order,
2447                stop_order,
2448            }
2449        }
2450    }
2451
2452    #[async_trait::async_trait]
2453    impl Gear for StopOrderTracker {
2454        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2455            Ok(())
2456        }
2457    }
2458
2459    #[async_trait::async_trait]
2460    impl RunnableCapability for StopOrderTracker {
2461        async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2462            Ok(())
2463        }
2464        async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2465            let order = self.stop_order.fetch_add(1, Ordering::SeqCst);
2466            tracing::info!(my_order = self.my_order, stop_order = order, "Gear stopped");
2467            Ok(())
2468        }
2469    }
2470
2471    #[tokio::test]
2472    async fn test_stop_phase_reverse_order() {
2473        let counter = Arc::new(AtomicUsize::new(0));
2474        let stop_order = Arc::new(AtomicUsize::new(0));
2475
2476        let gear_a = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2477        let gear_b = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2478        let gear_c = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2479
2480        let mut builder = RegistryBuilder::default();
2481        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2482        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2483        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2484
2485        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2486        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2487        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2488
2489        let registry = builder.build_topo_sorted().unwrap();
2490
2491        // Verify gear order is a -> b -> c
2492        let gear_names: Vec<_> = registry.gears().iter().map(|m| m.name).collect();
2493        assert_eq!(gear_names, vec!["a", "b", "c"]);
2494
2495        let client_hub = Arc::new(ClientHub::new());
2496        let cancel = CancellationToken::new();
2497        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2498
2499        let runtime = HostRuntime::new(
2500            registry,
2501            config_provider,
2502            DbOptions::None,
2503            client_hub,
2504            cancel.clone(),
2505            Uuid::new_v4(),
2506            None,
2507        );
2508
2509        // Run stop phase
2510        runtime.run_start_phase().await.unwrap();
2511        runtime.run_stop_phase().await.unwrap();
2512
2513        // Verify gears stopped in reverse order: c (stop_order=0), b (stop_order=1), a (stop_order=2)
2514        // Gear order is: a=0, b=1, c=2
2515        // Stop order should be: c=0, b=1, a=2
2516        assert_eq!(stop_order.load(Ordering::SeqCst), 3);
2517    }
2518
2519    #[tokio::test]
2520    async fn test_stop_phase_continues_on_error() {
2521        struct FailingGear {
2522            should_fail: bool,
2523            stopped: Arc<AtomicUsize>,
2524        }
2525
2526        #[async_trait::async_trait]
2527        impl Gear for FailingGear {
2528            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2529                Ok(())
2530            }
2531        }
2532
2533        #[async_trait::async_trait]
2534        impl RunnableCapability for FailingGear {
2535            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2536                Ok(())
2537            }
2538            async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2539                self.stopped.fetch_add(1, Ordering::SeqCst);
2540                if self.should_fail {
2541                    anyhow::bail!("Intentional failure")
2542                }
2543                Ok(())
2544            }
2545        }
2546
2547        let stopped = Arc::new(AtomicUsize::new(0));
2548        let gear_a = Arc::new(FailingGear {
2549            should_fail: false,
2550            stopped: stopped.clone(),
2551        });
2552        let gear_b = Arc::new(FailingGear {
2553            should_fail: true,
2554            stopped: stopped.clone(),
2555        });
2556        let gear_c = Arc::new(FailingGear {
2557            should_fail: false,
2558            stopped: stopped.clone(),
2559        });
2560
2561        let mut builder = RegistryBuilder::default();
2562        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2563        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2564        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2565
2566        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2567        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2568        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2569
2570        let registry = builder.build_topo_sorted().unwrap();
2571
2572        let client_hub = Arc::new(ClientHub::new());
2573        let cancel = CancellationToken::new();
2574        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2575
2576        let runtime = HostRuntime::new(
2577            registry,
2578            config_provider,
2579            DbOptions::None,
2580            client_hub,
2581            cancel.clone(),
2582            Uuid::new_v4(),
2583            None,
2584        );
2585
2586        // Run stop phase - should not fail even though gear_b fails
2587        runtime.run_start_phase().await.unwrap();
2588        runtime.run_stop_phase().await.unwrap();
2589
2590        // All gears should have attempted to stop
2591        assert_eq!(stopped.load(Ordering::SeqCst), 3);
2592    }
2593
2594    struct EmptyConfigProvider;
2595    impl ConfigProvider for EmptyConfigProvider {
2596        fn get_gear_config(&self, _gear_name: &str) -> Option<&serde_json::Value> {
2597            None
2598        }
2599    }
2600
2601    /// Serves one config blob for owner gear `orders` (the owner every
2602    /// `read_consumer_wiring` test uses) and nothing for anything else.
2603    struct OrdersCfg(serde_json::Value);
2604    impl ConfigProvider for OrdersCfg {
2605        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2606            (gear == "orders").then_some(&self.0)
2607        }
2608    }
2609
2610    /// Serves config blobs by owner-gear name (for tests wiring several gears).
2611    struct MapCfg(std::collections::HashMap<String, serde_json::Value>);
2612    impl ConfigProvider for MapCfg {
2613        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2614            self.0.get(gear)
2615        }
2616    }
2617
2618    /// Extract just the static-endpoint override from a `consumer_wiring` entry.
2619    fn endpoint_override(cfg: &dyn ConfigProvider, owner: &str, dep: &str) -> Option<String> {
2620        super::read_consumer_wiring(cfg, owner, dep)
2621            .expect("consumer_wiring must not error for a valid/absent endpoint")
2622            .and_then(|w| w.into_parts().0)
2623    }
2624
2625    #[test]
2626    fn static_endpoint_override_reads_nested_consumer_wiring_key() {
2627        let mut map = std::collections::HashMap::new();
2628        map.insert(
2629            "orders".to_owned(),
2630            serde_json::json!({
2631                "config": {
2632                    "consumer_wiring": { "billing": { "endpoint": "http://localhost:8081" } }
2633                }
2634            }),
2635        );
2636        let cfg = MapCfg(map);
2637
2638        // Present override is read from `config.consumer_wiring.<dep>.endpoint`.
2639        assert_eq!(
2640            endpoint_override(&cfg, "orders", "billing").as_deref(),
2641            Some("http://localhost:8081")
2642        );
2643        // Absent dep / owner → None (falls through to directory resolution).
2644        assert_eq!(endpoint_override(&cfg, "orders", "inventory"), None);
2645        assert_eq!(endpoint_override(&cfg, "warehouse", "billing"), None);
2646        assert_eq!(
2647            endpoint_override(&EmptyConfigProvider, "orders", "billing"),
2648            None
2649        );
2650    }
2651
2652    /// The object form yields both the `endpoint` override and the flattened
2653    /// `ClientTuning`.
2654    #[test]
2655    fn consumer_wiring_object_form_yields_endpoint_and_tuning() {
2656        let cfg = OrdersCfg(serde_json::json!({
2657            "config": {
2658                "consumer_wiring": {
2659                    "billing": {
2660                        "endpoint": "http://billing:8080",
2661                        "timeout": "5s",
2662                        "max_concurrent_requests": 256,
2663                        "pool_max_idle_per_host": 256
2664                    }
2665                }
2666            }
2667        }));
2668
2669        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2670            .expect("wiring must parse")
2671            .expect("wiring present")
2672            .into_parts();
2673        assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
2674        assert_eq!(tuning.timeout, Some(std::time::Duration::from_secs(5)));
2675        assert_eq!(tuning.max_concurrent_requests, Some(256));
2676        assert_eq!(tuning.pool_max_idle_per_host, Some(256));
2677    }
2678
2679    /// Omitting `endpoint` keeps discovery while still applying the tuning.
2680    #[test]
2681    fn consumer_wiring_object_without_endpoint_keeps_discovery() {
2682        let cfg = OrdersCfg(serde_json::json!({
2683            "config": {
2684                "consumer_wiring": { "billing": { "max_concurrent_requests": 1 } }
2685            }
2686        }));
2687
2688        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2689            .expect("wiring must parse")
2690            .expect("wiring present")
2691            .into_parts();
2692        assert_eq!(endpoint, None, "omitted endpoint must keep discovery");
2693        assert_eq!(tuning.max_concurrent_requests, Some(1));
2694    }
2695
2696    /// A present-but-unparseable entry (wrong shape or wrong-typed tuning) is a
2697    /// boot error, matching the provider side's `client_wiring` — not a silent
2698    /// downgrade to discovery.
2699    #[test]
2700    fn consumer_wiring_malformed_entry_is_an_error() {
2701        let malformed = [
2702            // Not a ConsumerWiring object at all.
2703            serde_json::json!([1, 2, 3]),
2704            // A wrong-typed tuning value: a string where a count is expected, and
2705            // a bare number where a humantime duration string is expected.
2706            serde_json::json!({ "max_concurrent_requests": "lots" }),
2707            serde_json::json!({ "timeout": 5 }),
2708            // The same, even alongside an otherwise-valid endpoint override: the
2709            // whole entry fails, so the override is not silently honoured untuned.
2710            serde_json::json!({ "endpoint": "http://billing:8080", "timeout": 5 }),
2711        ];
2712        for entry in malformed {
2713            let cfg = OrdersCfg(serde_json::json!({
2714                "config": { "consumer_wiring": { "billing": entry.clone() } }
2715            }));
2716            assert!(
2717                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2718                "a malformed entry (`{entry}`) must be a boot error, not silently dropped"
2719            );
2720        }
2721    }
2722
2723    /// A legacy bare-string value is a hard error whose message names the object
2724    /// form (a migration hint, not an opaque serde "invalid type" error).
2725    #[test]
2726    fn consumer_wiring_legacy_bare_string_is_an_error_naming_the_object_form() {
2727        let cfg = OrdersCfg(serde_json::json!({
2728            "config": { "consumer_wiring": { "billing": "http://localhost:8081" } }
2729        }));
2730        let err = super::read_consumer_wiring(&cfg, "orders", "billing")
2731            .expect_err("a bare-string value is the legacy shape -> hard error")
2732            .to_string();
2733        assert!(
2734            err.contains("endpoint"),
2735            "the error must point the operator at the `{{ endpoint: ... }}` object form, got: {err}"
2736        );
2737    }
2738
2739    /// A present-but-invalid `endpoint` is surfaced as an error, not downgraded to
2740    /// discovery — the operator asked for a specific endpoint that can't be honoured.
2741    #[test]
2742    fn consumer_wiring_invalid_endpoint_is_an_error() {
2743        for bad in ["", "billing", "/path/only"] {
2744            let cfg = OrdersCfg(serde_json::json!({
2745                "config": { "consumer_wiring": { "billing": { "endpoint": bad } } }
2746            }));
2747            assert!(
2748                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2749                "a present-but-invalid endpoint (`{bad}`) must be a hard error, not survived"
2750            );
2751        }
2752    }
2753
2754    /// One record of what a test wired the phase with. The phase tests share this
2755    /// collector and run in parallel, so each finds its own entry by a unique
2756    /// tuning value.
2757    #[derive(Clone)]
2758    struct WiredCall {
2759        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2760        max_concurrent_requests: Option<usize>,
2761        /// A dropped credential is otherwise invisible — the only runtime symptom
2762        /// is a missing `X-ToolKit-Internal-Token` on every Profile 2/3 call.
2763        has_credential: bool,
2764    }
2765    static WIRED: std::sync::Mutex<Vec<WiredCall>> = std::sync::Mutex::new(Vec::new());
2766
2767    /// Stands in for the `#[toolkit::consumes]`-generated wire fn: records the
2768    /// resolver and tuning it was handed, then reports a remote binding.
2769    #[allow(
2770        clippy::unnecessary_wraps,
2771        clippy::needless_pass_by_value,
2772        reason = "must match the ConsumerRegistration::wire signature the macro emits"
2773    )]
2774    fn record_wire(
2775        _hub: &ClientHub,
2776        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2777        tuning: toolkit_contract::wiring::ClientTuning,
2778    ) -> anyhow::Result<crate::discovery::WireOutcome> {
2779        WIRED.lock().unwrap().push(WiredCall {
2780            resolver,
2781            max_concurrent_requests: tuning.max_concurrent_requests,
2782            has_credential: tuning.internal_token_provider.is_some(),
2783        });
2784        Ok(crate::discovery::WireOutcome::Remote)
2785    }
2786
2787    /// A consumer registration for the phase tests, wired directly so it never
2788    /// enters the link-time-global `inventory` set (which would leak onto other
2789    /// tests in this binary).
2790    fn test_registration() -> crate::discovery::ConsumerRegistration {
2791        crate::discovery::ConsumerRegistration {
2792            owner_gear: "orders",
2793            dep_gear: "billing",
2794            wire: record_wire,
2795        }
2796    }
2797
2798    /// Static-endpoint arm: an `endpoint` wires a `StaticEndpointResolver` pinned
2799    /// to it, threads the entry's tuning through, and marks the dep resolved
2800    /// immediately (no probe loop).
2801    #[tokio::test]
2802    async fn proxy_wiring_static_override_uses_static_resolver_and_marks_ready() {
2803        let mut map = std::collections::HashMap::new();
2804        map.insert(
2805            "orders".to_owned(),
2806            serde_json::json!({
2807                "config": {
2808                    "consumer_wiring": {
2809                        "billing": {
2810                            "endpoint": "http://localhost:8081",
2811                            "max_concurrent_requests": 7
2812                        }
2813                    }
2814                }
2815            }),
2816        );
2817
2818        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2819        let runtime = HostRuntime::new(
2820            registry,
2821            Arc::new(MapCfg(map)),
2822            DbOptions::None,
2823            Arc::new(ClientHub::new()),
2824            CancellationToken::new(),
2825            Uuid::new_v4(),
2826            None,
2827        );
2828
2829        let reg = test_registration();
2830        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2831
2832        // Find *the* entry whose resolver yields the configured endpoint and
2833        // assert that same entry's tuning — OR-ing two flags independently across
2834        // every WIRED entry would pass even if the endpoint and the tuning had
2835        // arrived on two different wire calls.
2836        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2837        let mut matched = None;
2838        for call in &calls {
2839            if let Ok(Some(ep)) = call.resolver.resolve_endpoint("billing").await
2840                && ep == "http://localhost:8081"
2841            {
2842                matched = Some(call.clone());
2843                break;
2844            }
2845        }
2846        let matched = matched
2847            .expect("static override must wire a resolver pinned to the configured endpoint");
2848        assert_eq!(
2849            matched.max_concurrent_requests,
2850            Some(7),
2851            "the tuning on the same wire call as the static endpoint must be the configured one"
2852        );
2853
2854        // A static endpoint is resolvable by construction: the dep must be
2855        // resolved immediately rather than left gating /readyz.
2856        assert_eq!(
2857            runtime.dep_checker.unresolved_deps(),
2858            [crate::runtime::PREPARATION_GATE],
2859            "only the not yet started application group gates readiness"
2860        );
2861    }
2862
2863    /// An in-process provider that forgot to register its local impl must fail
2864    /// startup rather than silently wiring a self-pointing proxy: here both the
2865    /// consumer `orders` and provider `billing` are registered gears, but the
2866    /// consumer's wiring reports `Remote`.
2867    #[tokio::test]
2868    async fn proxy_wiring_in_process_provider_wired_remote_is_a_hard_error() {
2869        // Register the consumer `orders` and the provider `billing`, where billing
2870        // never provides its client (no local impl, no REST).
2871        let mut b = crate::registry::RegistryBuilder::default();
2872        b.register_core_with_meta("orders", &[], Arc::new(DummyCore));
2873        b.register_core_with_meta("billing", &[], Arc::new(DummyCore));
2874        let registry = b.build_topo_sorted().unwrap();
2875
2876        let runtime = HostRuntime::new(
2877            registry,
2878            Arc::new(MapCfg(std::collections::HashMap::new())),
2879            DbOptions::None,
2880            Arc::new(ClientHub::new()),
2881            CancellationToken::new(),
2882            Uuid::new_v4(),
2883            None,
2884        );
2885
2886        // `test_registration()` is owner=orders, dep=billing, and `record_wire`
2887        // reports `Remote` without registering a local impl — the bug scenario.
2888        let reg = test_registration();
2889        let err = runtime
2890            .wire_consumer_registrations(&[&reg])
2891            .expect_err("an in-process provider wired Remote must fail startup");
2892        let msg = err.to_string();
2893        assert!(
2894            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
2895            "expected a ProxyWiring error for the consumer gear, got: {msg}"
2896        );
2897        // Display must surface the source, so both the consumer and provider gear
2898        // names appear in the rendered message.
2899        assert!(
2900            msg.contains("orders") && msg.contains("billing"),
2901            "displayed error must name both consumer and provider, got: {msg}"
2902        );
2903    }
2904
2905    /// Tuning-only entry (no `endpoint`, the production shape): keeps the shared
2906    /// discovery resolver and leaves the dep gating readiness — a remote dep with
2907    /// no directory stays unresolved.
2908    #[tokio::test]
2909    async fn proxy_wiring_tuning_only_entry_keeps_discovery_and_gates_readiness() {
2910        let mut map = std::collections::HashMap::new();
2911        // A unique tuning value so this test can find its own WIRED entry among
2912        // the link-time-global registrations.
2913        map.insert(
2914            "orders".to_owned(),
2915            serde_json::json!({
2916                "config": {
2917                    "consumer_wiring": { "billing": { "max_concurrent_requests": 4343 } }
2918                }
2919            }),
2920        );
2921
2922        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2923        let runtime = HostRuntime::new(
2924            registry,
2925            Arc::new(MapCfg(map)),
2926            DbOptions::None,
2927            Arc::new(ClientHub::new()),
2928            CancellationToken::new(),
2929            Uuid::new_v4(),
2930            None,
2931        );
2932
2933        let reg = test_registration();
2934        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2935
2936        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2937        let ours = calls
2938            .iter()
2939            .find(|c| c.max_concurrent_requests == Some(4343))
2940            .expect("our tuning-only wire call must have been recorded");
2941        assert!(
2942            matches!(ours.resolver.resolve_endpoint("billing").await, Ok(None)),
2943            "a tuning-only entry must keep discovery -- the resolver must not be pinned to a \
2944             static endpoint"
2945        );
2946
2947        // No directory + a remote dep → it must stay unresolved and gate /readyz.
2948        assert!(!runtime.dep_checker.all_resolved());
2949        assert!(
2950            runtime
2951                .dep_checker
2952                .unresolved_deps()
2953                .contains(&"billing".to_owned()),
2954            "a discovery-wired dep with no directory must gate readiness"
2955        );
2956    }
2957
2958    /// The process's platform-plane credential must ride on the tuning handed to
2959    /// the wire fn (Profile 2/3), else every inter-gear call ships without
2960    /// `X-ToolKit-Internal-Token`.
2961    #[tokio::test]
2962    async fn proxy_wiring_threads_platform_credential_onto_tuning() {
2963        use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
2964
2965        let mut map = std::collections::HashMap::new();
2966        map.insert(
2967            "orders".to_owned(),
2968            serde_json::json!({
2969                "config": {
2970                    "consumer_wiring": { "billing": { "max_concurrent_requests": 4242 } }
2971                }
2972            }),
2973        );
2974
2975        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2976        let provider = InternalTokenProvider::new(|| CredentialState::NotConfigured);
2977        let runtime = HostRuntime::new(
2978            registry,
2979            Arc::new(MapCfg(map)),
2980            DbOptions::None,
2981            Arc::new(ClientHub::new()),
2982            CancellationToken::new(),
2983            Uuid::new_v4(),
2984            None,
2985        )
2986        .with_internal_token_provider(Some(provider));
2987
2988        let reg = test_registration();
2989        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2990
2991        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2992        let ours = calls
2993            .iter()
2994            .find(|c| c.max_concurrent_requests == Some(4242))
2995            .expect("our wire call must have been recorded");
2996        assert!(
2997            ours.has_credential,
2998            "the process credential must be threaded onto the tuning handed to the wire fn"
2999        );
3000    }
3001
3002    /// Phase-level: a non-absolute `endpoint` aborts proxy-wiring with
3003    /// `RegistryError::ProxyWiring` rather than silently downgrading to discovery
3004    /// (which would mark the dep resolved while every call fails).
3005    #[tokio::test]
3006    async fn proxy_wiring_invalid_endpoint_is_a_hard_error() {
3007        let mut map = std::collections::HashMap::new();
3008        map.insert(
3009            "orders".to_owned(),
3010            serde_json::json!({
3011                "config": {
3012                    "consumer_wiring": {
3013                        "billing": { "endpoint": "", "max_concurrent_requests": 4444 }
3014                    }
3015                }
3016            }),
3017        );
3018
3019        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
3020        let runtime = HostRuntime::new(
3021            registry,
3022            Arc::new(MapCfg(map)),
3023            DbOptions::None,
3024            Arc::new(ClientHub::new()),
3025            CancellationToken::new(),
3026            Uuid::new_v4(),
3027            None,
3028        );
3029
3030        let reg = test_registration();
3031        let err = runtime
3032            .wire_consumer_registrations(&[&reg])
3033            .expect_err("an invalid static endpoint must abort proxy-wiring");
3034        assert!(
3035            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
3036            "expected a ProxyWiring error for the owning gear, got {err:?}"
3037        );
3038    }
3039
3040    /// The override is keyed by the kebab *gear name* (`owner_gear`), not the
3041    /// struct ident. Regression guard: the macro once emitted
3042    /// `stringify!(StructIdent)`, so the lookup could never fire.
3043    #[test]
3044    fn static_endpoint_override_is_keyed_by_kebab_gear_name() {
3045        let mut map = std::collections::HashMap::new();
3046        map.insert(
3047            "api-contracts-consumer".to_owned(),
3048            serde_json::json!({
3049                "config": {
3050                    "consumer_wiring": {
3051                        "api-contracts": { "endpoint": "http://localhost:9099" }
3052                    }
3053                }
3054            }),
3055        );
3056        let cfg = MapCfg(map);
3057
3058        assert_eq!(
3059            endpoint_override(&cfg, "api-contracts-consumer", "api-contracts").as_deref(),
3060            Some("http://localhost:9099"),
3061        );
3062        // The pre-fix value — the Rust struct ident — must NOT resolve.
3063        assert_eq!(
3064            endpoint_override(&cfg, "ApiContractsConsumer", "api-contracts"),
3065            None,
3066        );
3067    }
3068
3069    /// What a consumer's proxy was built from, for the per-consumer tests.
3070    trait ShippingApi: Send + Sync {
3071        fn wiring(&self) -> &ShippingProxy;
3072    }
3073
3074    struct ShippingProxy {
3075        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3076        timeout: Option<std::time::Duration>,
3077        max_attempts: Option<u32>,
3078        require_tls: Option<bool>,
3079    }
3080
3081    impl ShippingApi for ShippingProxy {
3082        fn wiring(&self) -> &ShippingProxy {
3083            self
3084        }
3085    }
3086
3087    /// The body `#[toolkit::consumes]` emits, with a proxy that keeps its
3088    /// resolver and tuning.
3089    fn wire_shipping(
3090        hub: &ClientHub,
3091        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3092        tuning: toolkit_contract::wiring::ClientTuning,
3093    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3094        if hub.try_get_local::<dyn ShippingApi>().is_some() {
3095            return Ok(crate::discovery::WireOutcome::Local);
3096        }
3097        if hub.has_remote_proxy::<dyn ShippingApi>() {
3098            if let Some(owner) = hub.owner() {
3099                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
3100            }
3101            return Ok(crate::discovery::WireOutcome::Remote);
3102        }
3103        hub.register_remote_proxy::<dyn ShippingApi>(Arc::new(ShippingProxy {
3104            resolver,
3105            timeout: tuning.timeout,
3106            max_attempts: tuning.retry.and_then(|r| r.max_attempts),
3107            require_tls: tuning.require_tls,
3108        }));
3109        Ok(crate::discovery::WireOutcome::Remote)
3110    }
3111
3112    fn shipping_registration(owner_gear: &'static str) -> crate::discovery::ConsumerRegistration {
3113        crate::discovery::ConsumerRegistration {
3114            owner_gear,
3115            dep_gear: "shipping",
3116            wire: wire_shipping,
3117        }
3118    }
3119
3120    /// A runtime hosting consumer gears `a` and `b` (shipping is remote).
3121    fn shipping_runtime(config: serde_json::Value) -> HostRuntime {
3122        let mut b = crate::registry::RegistryBuilder::default();
3123        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3124        b.register_core_with_meta("b", &[], Arc::new(DummyCore));
3125        let registry = b.build_topo_sorted().unwrap();
3126        let map = serde_json::from_value(config).unwrap();
3127        HostRuntime::new(
3128            registry,
3129            Arc::new(MapCfg(map)),
3130            DbOptions::None,
3131            Arc::new(ClientHub::new()),
3132            CancellationToken::new(),
3133            Uuid::new_v4(),
3134            None,
3135        )
3136    }
3137
3138    /// Issue #5686: two gears consuming one contract each get a proxy built
3139    /// from their own `consumer_wiring`, whichever wires first.
3140    #[tokio::test]
3141    async fn each_consumer_gets_a_proxy_with_its_own_wiring() {
3142        let config = serde_json::json!({
3143            "a": { "config": { "consumer_wiring": { "shipping": {
3144                "endpoint": "http://shipping-for-a:8080",
3145                "timeout": "1s",
3146                "retry": { "max_attempts": 2 },
3147                "require_tls": false
3148            } } } },
3149            "b": { "config": { "consumer_wiring": { "shipping": {
3150                "endpoint": "http://shipping-for-b:8080",
3151                "timeout": "10s",
3152                "retry": { "max_attempts": 5 },
3153                "require_tls": true
3154            } } } }
3155        });
3156        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3157
3158        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3159            let runtime = shipping_runtime(config.clone());
3160            runtime.wire_consumer_registrations(&order).unwrap();
3161
3162            let hub = &runtime.client_hub;
3163            let a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3164            let b = hub.for_gear("b").get::<dyn ShippingApi>().unwrap();
3165            assert!(!Arc::ptr_eq(&a, &b));
3166            assert!(
3167                hub.try_get::<dyn ShippingApi>().is_none(),
3168                "a gear's proxy is not process-wide"
3169            );
3170
3171            let (a, b) = (a.wiring(), b.wiring());
3172            assert_eq!(
3173                a.resolver
3174                    .resolve_endpoint("shipping")
3175                    .await
3176                    .unwrap()
3177                    .as_deref(),
3178                Some("http://shipping-for-a:8080")
3179            );
3180            assert_eq!(
3181                b.resolver
3182                    .resolve_endpoint("shipping")
3183                    .await
3184                    .unwrap()
3185                    .as_deref(),
3186                Some("http://shipping-for-b:8080")
3187            );
3188            assert_eq!(a.timeout, Some(std::time::Duration::from_secs(1)));
3189            assert_eq!(b.timeout, Some(std::time::Duration::from_secs(10)));
3190            assert_eq!((a.max_attempts, b.max_attempts), (Some(2), Some(5)));
3191            assert_eq!((a.require_tls, b.require_tls), (Some(false), Some(true)));
3192        }
3193    }
3194
3195    /// An owner that is not a gear in this process (an SDK-level registration)
3196    /// wires a process-wide proxy that every gear's view can read.
3197    #[tokio::test]
3198    async fn an_unknown_owner_wires_a_process_wide_proxy() {
3199        let runtime = shipping_runtime(serde_json::json!({}));
3200        let reg = shipping_registration("shipping-sdk");
3201        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3202
3203        let hub = &runtime.client_hub;
3204        let shared = hub.get::<dyn ShippingApi>().unwrap();
3205        let seen_by_a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3206        assert!(Arc::ptr_eq(&shared, &seen_by_a));
3207    }
3208
3209    /// With one consumer on a static endpoint and another on discovery, the dep
3210    /// stays unresolved: the second consumer's provider is not found yet.
3211    #[tokio::test]
3212    async fn a_static_consumer_does_not_resolve_a_dep_another_consumer_discovers() {
3213        let config = serde_json::json!({
3214            "a": { "config": { "consumer_wiring": { "shipping": {
3215                "endpoint": "http://shipping:8080"
3216            } } } }
3217        });
3218        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3219
3220        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3221            let runtime = shipping_runtime(config.clone());
3222            runtime.wire_consumer_registrations(&order).unwrap();
3223
3224            assert!(
3225                runtime
3226                    .dep_checker
3227                    .unresolved_deps()
3228                    .contains(&"shipping".to_owned()),
3229                "the discovery consumer must keep the dep gating readiness"
3230            );
3231        }
3232    }
3233
3234    /// Same mix with a directory: the dep stays unresolved until the provider
3235    /// is advertised, then the probe resolves it.
3236    #[tokio::test]
3237    async fn a_mixed_dep_resolves_once_the_provider_is_advertised() {
3238        let config = serde_json::json!({
3239            "a": { "config": { "consumer_wiring": { "shipping": {
3240                "endpoint": "http://shipping:8080"
3241            } } } }
3242        });
3243        let runtime = shipping_runtime(config);
3244        let gears = Arc::new(crate::runtime::GearManager::new());
3245        runtime
3246            .client_hub
3247            .register::<dyn crate::DirectoryClient>(Arc::new(
3248                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3249            ));
3250        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3251        runtime
3252            .wire_consumer_registrations(&[&reg_a, &reg_b])
3253            .unwrap();
3254
3255        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3256        assert!(
3257            runtime
3258                .dep_checker
3259                .unresolved_deps()
3260                .contains(&"shipping".to_owned()),
3261            "no provider is advertised yet"
3262        );
3263
3264        gears
3265            .register_instance(Arc::new(
3266                crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3267                    .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3268            ))
3269            .unwrap();
3270        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3271            while runtime
3272                .dep_checker
3273                .unresolved_deps()
3274                .contains(&"shipping".to_owned())
3275            {
3276                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3277            }
3278        })
3279        .await
3280        .expect("the probe must resolve the dep once the provider is advertised");
3281        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3282        runtime.owned.cancel();
3283    }
3284
3285    /// Both consumers on static endpoints: resolved at wiring time.
3286    #[tokio::test]
3287    async fn static_consumers_resolve_the_dep() {
3288        let entry = serde_json::json!({ "config": { "consumer_wiring": { "shipping": {
3289            "endpoint": "http://shipping:8080"
3290        } } } });
3291        let runtime = shipping_runtime(serde_json::json!({ "a": entry, "b": entry }));
3292        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3293        runtime
3294            .wire_consumer_registrations(&[&reg_a, &reg_b])
3295            .unwrap();
3296
3297        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3298    }
3299
3300    /// One gear consuming the same contract twice is a boot error naming it.
3301    #[tokio::test]
3302    async fn a_gear_consuming_a_contract_twice_fails_wiring() {
3303        let runtime = shipping_runtime(serde_json::json!({}));
3304        let reg = shipping_registration("a");
3305        let duplicate = shipping_registration("a");
3306        let err = runtime
3307            .wire_consumer_registrations(&[&reg, &duplicate])
3308            .expect_err("a duplicate consumer must fail wiring");
3309        assert!(
3310            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "a"),
3311            "got {err:?}"
3312        );
3313    }
3314
3315    #[tokio::test]
3316    async fn test_post_init_runs_after_all_init_for_every_gear_system_group_first() {
3317        #[derive(Clone)]
3318        struct TrackHooks {
3319            name: &'static str,
3320            events: Arc<Mutex<Vec<String>>>,
3321        }
3322
3323        #[async_trait::async_trait]
3324        impl Gear for TrackHooks {
3325            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3326                self.events.lock().await.push(format!("init:{}", self.name));
3327                Ok(())
3328            }
3329
3330            async fn post_init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3331                self.events
3332                    .lock()
3333                    .await
3334                    .push(format!("post_init:{}", self.name));
3335                Ok(())
3336            }
3337        }
3338
3339        impl SystemCapability for TrackHooks {}
3340
3341        let events = Arc::new(Mutex::new(Vec::<String>::new()));
3342        let sys_a = Arc::new(TrackHooks {
3343            name: "sys_a",
3344            events: events.clone(),
3345        });
3346        let user_b = Arc::new(TrackHooks {
3347            name: "user_b",
3348            events: events.clone(),
3349        });
3350        let user_c = Arc::new(TrackHooks {
3351            name: "user_c",
3352            events: events.clone(),
3353        });
3354
3355        let mut builder = RegistryBuilder::default();
3356        builder.register_core_with_meta("sys_a", &[], sys_a.clone() as Arc<dyn Gear>);
3357        builder.register_core_with_meta("user_b", &["sys_a"], user_b.clone() as Arc<dyn Gear>);
3358        builder.register_core_with_meta("user_c", &["user_b"], user_c.clone() as Arc<dyn Gear>);
3359        builder.register_system_with_meta("sys_a", sys_a.clone() as Arc<dyn SystemCapability>);
3360
3361        let registry = builder.build_topo_sorted().unwrap();
3362
3363        let client_hub = Arc::new(ClientHub::new());
3364        let cancel = CancellationToken::new();
3365        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3366
3367        let runtime = HostRuntime::new(
3368            registry,
3369            config_provider,
3370            DbOptions::None,
3371            client_hub,
3372            cancel,
3373            Uuid::new_v4(),
3374            None,
3375        );
3376
3377        // Run init phase for all gears, then post_init as a separate barrier phase.
3378        runtime.run_init_phase().await.unwrap();
3379        runtime.run_post_init_phase().await.unwrap();
3380
3381        let events = events.lock().await.clone();
3382        let first_post_init = events
3383            .iter()
3384            .position(|e| e.starts_with("post_init:"))
3385            .expect("expected post_init events");
3386        assert!(
3387            events[..first_post_init]
3388                .iter()
3389                .all(|e| e.starts_with("init:")),
3390            "expected all init events before post_init, got: {events:?}"
3391        );
3392
3393        // The system group first, each group in topological order.
3394        assert_eq!(
3395            events,
3396            vec![
3397                "init:sys_a",
3398                "init:user_b",
3399                "init:user_c",
3400                "post_init:sys_a",
3401                "post_init:user_b",
3402                "post_init:user_c",
3403            ]
3404        );
3405    }
3406
3407    /// The force-exit watchdog (shared by init and stop) fires only when it is
3408    /// never disarmed within the deadline. The decision is split from
3409    /// `process::exit` into `watchdog_verdict` so it is unit-testable without
3410    /// killing the test process; these cover the hung case and both disarm cases.
3411    #[test]
3412    fn watchdog_times_out_when_not_disarmed() {
3413        let (_tx, rx) = std::sync::mpsc::channel::<()>();
3414        // Hold the sender; never signal → the deadline elapses → TimedOut.
3415        assert_eq!(
3416            watchdog_verdict(&rx, std::time::Duration::from_millis(20)),
3417            WatchdogVerdict::TimedOut
3418        );
3419    }
3420
3421    #[test]
3422    fn init_watchdog_subprocess() {
3423        const CHILD_MODE: &str = "TOOLKIT_INIT_WATCHDOG_TEST_MODE";
3424        struct WatchdogGear(String);
3425
3426        #[async_trait::async_trait]
3427        impl Gear for WatchdogGear {
3428            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3429                match self.0.as_str() {
3430                    "success" => (),
3431                    // Async hang: the async timeout observes it → recoverable error.
3432                    "async-hang" | "cancelled" => {
3433                        std::future::pending::<()>().await;
3434                    }
3435                    // Synchronous block: no async timer can fire; only the
3436                    // OS-thread watchdog catches it → force-exit.
3437                    "blocking" | "blocking-no-tracing" => {
3438                        std::thread::sleep(std::time::Duration::from_secs(3600));
3439                    }
3440                    "error" => anyhow::bail!("init failed"),
3441                    other => panic!("unexpected watchdog test mode: {other}"),
3442                }
3443                Ok(())
3444            }
3445        }
3446
3447        let Ok(mode) = std::env::var(CHILD_MODE) else {
3448            for (mode, expected_code) in [
3449                ("success", 0),
3450                ("async-hang", 0),
3451                ("blocking", 1),
3452                ("blocking-no-tracing", 1),
3453                ("error", 0),
3454                ("cancelled", 0),
3455            ] {
3456                let mut child = std::process::Command::new(std::env::current_exe().unwrap())
3457                    .args([
3458                        "--exact",
3459                        "runtime::host_runtime::tests::init_watchdog_subprocess",
3460                        "--nocapture",
3461                    ])
3462                    .env(CHILD_MODE, mode)
3463                    .stdout(std::process::Stdio::piped())
3464                    .stderr(std::process::Stdio::piped())
3465                    .spawn()
3466                    .unwrap();
3467                let limit = std::time::Instant::now() + std::time::Duration::from_secs(5);
3468                while child.try_wait().unwrap().is_none() {
3469                    if std::time::Instant::now() >= limit {
3470                        child.kill().unwrap();
3471                        let output = child.wait_with_output().unwrap();
3472                        panic!("watchdog subprocess {mode} hung: {output:?}");
3473                    }
3474                    std::thread::sleep(std::time::Duration::from_millis(10));
3475                }
3476                let output = child.wait_with_output().unwrap();
3477                assert_eq!(
3478                    output.status.code(),
3479                    Some(expected_code),
3480                    "{mode}: {output:?}"
3481                );
3482                if mode.starts_with("blocking") {
3483                    // One line must carry ERROR + message + gear name (holds even
3484                    // with tracing OFF, where only the stderr fallback is emitted).
3485                    let logs = String::from_utf8_lossy(&output.stderr);
3486                    assert!(
3487                        logs.lines().any(|line| line.contains("ERROR")
3488                            && line.contains("init timed out")
3489                            && line.contains("watchdog-test")),
3490                        "{logs}"
3491                    );
3492                }
3493            }
3494            return;
3495        };
3496
3497        tracing_subscriber::fmt()
3498            .with_ansi(false)
3499            .with_max_level(if mode == "blocking-no-tracing" {
3500                tracing::level_filters::LevelFilter::OFF
3501            } else {
3502                tracing::level_filters::LevelFilter::INFO
3503            })
3504            .with_writer(std::io::stderr)
3505            .try_init()
3506            .unwrap();
3507        tokio::runtime::Builder::new_current_thread()
3508            .enable_all()
3509            .build()
3510            .unwrap()
3511            .block_on(async {
3512                let mut builder = RegistryBuilder::default();
3513                builder.register_core_with_meta(
3514                    "watchdog-test",
3515                    &[],
3516                    Arc::new(WatchdogGear(mode.clone())) as Arc<dyn Gear>,
3517                );
3518                let runtime = HostRuntime::new(
3519                    builder.build_topo_sorted().unwrap(),
3520                    Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3521                    DbOptions::None,
3522                    Arc::new(ClientHub::new()),
3523                    CancellationToken::new(),
3524                    Uuid::new_v4(),
3525                    None,
3526                )
3527                .with_init_deadline(std::time::Duration::from_millis(200));
3528
3529                #[allow(
3530                    clippy::match_same_arms,
3531                    reason = "`success` returns normally; in `blocking*` the same call never returns and the watchdog force-exits"
3532                )]
3533                match mode.as_str() {
3534                    "cancelled" => {
3535                        // Dropping the phase future disarms the watchdog: no exit.
3536                        assert!(
3537                            tokio::time::timeout(
3538                                std::time::Duration::from_millis(20),
3539                                runtime.run_init_phase(),
3540                            )
3541                            .await
3542                            .is_err()
3543                        );
3544                    }
3545                    "success" => {
3546                        runtime.run_init_phase().await.unwrap();
3547                    }
3548                    "async-hang" => {
3549                        // Recoverable error, not a force-exit.
3550                        let err = runtime.run_init_phase().await.unwrap_err();
3551                        assert!(matches!(
3552                            err,
3553                            RegistryError::InitTimeout {
3554                                gear: "watchdog-test",
3555                                ..
3556                            }
3557                        ));
3558                    }
3559                    "error" => {
3560                        let err = runtime.run_init_phase().await.unwrap_err();
3561                        assert!(matches!(
3562                            err,
3563                            RegistryError::Init {
3564                                gear: "watchdog-test",
3565                                ..
3566                            }
3567                        ));
3568                    }
3569                    // Never returns; the OS-thread watchdog force-exits instead.
3570                    "blocking" | "blocking-no-tracing" => {
3571                        runtime.run_init_phase().await.unwrap();
3572                    }
3573                    other => panic!("unexpected watchdog test mode: {other}"),
3574                }
3575                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
3576            });
3577    }
3578
3579    #[test]
3580    fn watchdog_disarms_when_signalled() {
3581        let (tx, rx) = std::sync::mpsc::channel::<()>();
3582        tx.send(()).unwrap();
3583        // A generous deadline proves we return on the signal, not by timing out.
3584        assert_eq!(
3585            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
3586            WatchdogVerdict::Disarmed
3587        );
3588    }
3589
3590    #[test]
3591    fn watchdog_disarms_when_sender_is_dropped() {
3592        let (tx, rx) = std::sync::mpsc::channel::<()>();
3593        drop(tx); // guarded future dropped before it finished
3594        assert_eq!(
3595            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
3596            WatchdogVerdict::Disarmed
3597        );
3598    }
3599
3600    /// When `GearContextBuilder::for_gear` fails (here: the gear's database
3601    /// config references a global server that does not exist), the init phase
3602    /// must surface it as `RegistryError::Init` naming the gear — not hang or
3603    /// force-exit.
3604    #[cfg(feature = "db")]
3605    #[tokio::test]
3606    async fn init_ctx_failure_surfaces_as_init_error() {
3607        use figment::{Figment, providers::Serialized};
3608
3609        struct NeedsDbGear;
3610
3611        #[async_trait::async_trait]
3612        impl Gear for NeedsDbGear {
3613            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3614                Ok(())
3615            }
3616        }
3617
3618        let mut builder = RegistryBuilder::default();
3619        builder.register_core_with_meta("needsdb", &[], Arc::new(NeedsDbGear) as Arc<dyn Gear>);
3620        let registry = builder.build_topo_sorted().unwrap();
3621
3622        let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
3623            "gears": {
3624                "needsdb": {
3625                    "database": { "server": "does-not-exist" }
3626                }
3627            }
3628        })));
3629        let db_manager =
3630            toolkit_db::DbManager::from_figment(figment, std::path::PathBuf::from("/tmp/test"))
3631                .unwrap();
3632
3633        let runtime = HostRuntime::new(
3634            registry,
3635            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3636            DbOptions::Manager(Arc::new(db_manager)),
3637            Arc::new(ClientHub::new()),
3638            CancellationToken::new(),
3639            Uuid::new_v4(),
3640            None,
3641        );
3642
3643        let err = runtime.run_init_phase().await.unwrap_err();
3644        assert!(
3645            matches!(err, RegistryError::Init { gear, .. } if gear == "needsdb"),
3646            "expected RegistryError::Init for needsdb, got {err:?}"
3647        );
3648    }
3649
3650    /// A REST gear opting out of directory advertisement is served but not
3651    /// advertised (nor deregistered) as a REST provider.
3652    #[test]
3653    fn a_rest_gear_can_opt_out_of_directory_advertisement() {
3654        struct Rest {
3655            advertised: bool,
3656        }
3657        #[async_trait::async_trait]
3658        impl Gear for Rest {
3659            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3660                Ok(())
3661            }
3662        }
3663        impl crate::contracts::RestApiCapability for Rest {
3664            fn register_rest(
3665                &self,
3666                _ctx: &GearCtx,
3667                router: axum::Router,
3668                _openapi: &dyn crate::api::OpenApiRegistry,
3669            ) -> anyhow::Result<axum::Router> {
3670                Ok(router)
3671            }
3672            fn advertised_in_directory(&self) -> bool {
3673                self.advertised
3674            }
3675        }
3676
3677        let mut builder = RegistryBuilder::default();
3678        for (name, advertised) in [("advertised", true), ("hidden", false)] {
3679            let gear = Arc::new(Rest { advertised });
3680            builder.register_core_with_meta(name, &[], gear.clone() as Arc<dyn Gear>);
3681            builder.register_rest_with_meta(
3682                name,
3683                gear as Arc<dyn crate::contracts::RestApiCapability>,
3684            );
3685        }
3686        let runtime = HostRuntime::new(
3687            builder.build_topo_sorted().unwrap(),
3688            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3689            DbOptions::None,
3690            Arc::new(ClientHub::new()),
3691            CancellationToken::new(),
3692            Uuid::new_v4(),
3693            None,
3694        );
3695
3696        assert_eq!(runtime.rest_provider_gears(), vec!["advertised"]);
3697    }
3698
3699    #[tokio::test]
3700    async fn test_stop_phase_provides_fresh_deadline_token() {
3701        use std::sync::atomic::AtomicBool;
3702
3703        struct TokenCheckGear {
3704            stop_was_called: AtomicBool,
3705            token_was_cancelled_on_entry: AtomicBool,
3706        }
3707
3708        #[async_trait::async_trait]
3709        impl Gear for TokenCheckGear {
3710            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3711                Ok(())
3712            }
3713        }
3714
3715        #[async_trait::async_trait]
3716        impl RunnableCapability for TokenCheckGear {
3717            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3718                Ok(())
3719            }
3720            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3721                // Record that stop() was called
3722                self.stop_was_called.store(true, Ordering::SeqCst);
3723                // Record whether the token was already cancelled when stop() was called
3724                self.token_was_cancelled_on_entry
3725                    .store(deadline_token.is_cancelled(), Ordering::SeqCst);
3726                Ok(())
3727            }
3728        }
3729
3730        let gear = Arc::new(TokenCheckGear {
3731            stop_was_called: AtomicBool::new(false),
3732            // Default to true to detect if stop() was never called
3733            token_was_cancelled_on_entry: AtomicBool::new(true),
3734        });
3735
3736        let mut builder = RegistryBuilder::default();
3737        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3738        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3739
3740        let registry = builder.build_topo_sorted().unwrap();
3741        let client_hub = Arc::new(ClientHub::new());
3742        let cancel = CancellationToken::new();
3743        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3744
3745        let runtime = HostRuntime::new(
3746            registry,
3747            config_provider,
3748            DbOptions::None,
3749            client_hub,
3750            cancel.clone(),
3751            Uuid::new_v4(),
3752            None,
3753        );
3754
3755        // Run stop phase - the deadline token should NOT be cancelled
3756        runtime.run_start_phase().await.unwrap();
3757        runtime.run_stop_phase().await.unwrap();
3758
3759        // First, verify stop() was actually called (guards against silent registration failures)
3760        assert!(
3761            gear.stop_was_called.load(Ordering::SeqCst),
3762            "stop() was never called - gear may not have been registered correctly"
3763        );
3764
3765        // The token should NOT have been cancelled when stop() was called
3766        // This is the key fix: gears get a fresh token, not the already-cancelled root token
3767        assert!(
3768            !gear.token_was_cancelled_on_entry.load(Ordering::SeqCst),
3769            "deadline_token should NOT be cancelled when stop() is called - this enables graceful shutdown"
3770        );
3771    }
3772
3773    #[tokio::test]
3774    async fn test_stop_phase_graceful_shutdown_completes_before_deadline() {
3775        use std::sync::atomic::AtomicBool;
3776        use std::time::Duration;
3777
3778        struct GracefulGear {
3779            graceful_completed: AtomicBool,
3780            deadline_fired: AtomicBool,
3781        }
3782
3783        #[async_trait::async_trait]
3784        impl Gear for GracefulGear {
3785            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3786                Ok(())
3787            }
3788        }
3789
3790        #[async_trait::async_trait]
3791        impl RunnableCapability for GracefulGear {
3792            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3793                Ok(())
3794            }
3795            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3796                // Simulate graceful shutdown that completes quickly (10ms)
3797                tokio::select! {
3798                    () = tokio::time::sleep(Duration::from_millis(10)) => {
3799                        self.graceful_completed.store(true, Ordering::SeqCst);
3800                    }
3801                    () = deadline_token.cancelled() => {
3802                        self.deadline_fired.store(true, Ordering::SeqCst);
3803                    }
3804                }
3805                Ok(())
3806            }
3807        }
3808
3809        let gear = Arc::new(GracefulGear {
3810            graceful_completed: AtomicBool::new(false),
3811            deadline_fired: AtomicBool::new(false),
3812        });
3813
3814        let mut builder = RegistryBuilder::default();
3815        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3816        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3817
3818        let registry = builder.build_topo_sorted().unwrap();
3819        let client_hub = Arc::new(ClientHub::new());
3820        let cancel = CancellationToken::new();
3821        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3822
3823        // Use a long deadline (5s) - gear should complete gracefully before this
3824        let runtime = HostRuntime::new(
3825            registry,
3826            config_provider,
3827            DbOptions::None,
3828            client_hub,
3829            cancel.clone(),
3830            Uuid::new_v4(),
3831            None,
3832        )
3833        .with_shutdown_deadline(Duration::from_secs(5));
3834
3835        runtime.run_start_phase().await.unwrap();
3836        runtime.run_stop_phase().await.unwrap();
3837
3838        // Graceful shutdown should have completed
3839        assert!(
3840            gear.graceful_completed.load(Ordering::SeqCst),
3841            "graceful shutdown should complete"
3842        );
3843        // Deadline should NOT have fired (gear finished before deadline)
3844        assert!(
3845            !gear.deadline_fired.load(Ordering::SeqCst),
3846            "deadline should not fire when graceful shutdown completes quickly"
3847        );
3848    }
3849
3850    #[tokio::test]
3851    async fn test_stop_phase_deadline_fires_for_slow_gear() {
3852        use std::sync::atomic::AtomicBool;
3853        use std::time::Duration;
3854
3855        struct SlowGear {
3856            graceful_completed: AtomicBool,
3857            deadline_fired: AtomicBool,
3858        }
3859
3860        #[async_trait::async_trait]
3861        impl Gear for SlowGear {
3862            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3863                Ok(())
3864            }
3865        }
3866
3867        #[async_trait::async_trait]
3868        impl RunnableCapability for SlowGear {
3869            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3870                Ok(())
3871            }
3872            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3873                // Simulate slow graceful shutdown (would take 10s, but deadline is 100ms)
3874                tokio::select! {
3875                    () = tokio::time::sleep(Duration::from_secs(10)) => {
3876                        self.graceful_completed.store(true, Ordering::SeqCst);
3877                    }
3878                    () = deadline_token.cancelled() => {
3879                        self.deadline_fired.store(true, Ordering::SeqCst);
3880                    }
3881                }
3882                Ok(())
3883            }
3884        }
3885
3886        let gear = Arc::new(SlowGear {
3887            graceful_completed: AtomicBool::new(false),
3888            deadline_fired: AtomicBool::new(false),
3889        });
3890
3891        let mut builder = RegistryBuilder::default();
3892        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3893        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3894
3895        let registry = builder.build_topo_sorted().unwrap();
3896        let client_hub = Arc::new(ClientHub::new());
3897        let cancel = CancellationToken::new();
3898        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3899
3900        // Use a short deadline (100ms) - gear should be interrupted by deadline
3901        let runtime = HostRuntime::new(
3902            registry,
3903            config_provider,
3904            DbOptions::None,
3905            client_hub,
3906            cancel.clone(),
3907            Uuid::new_v4(),
3908            None,
3909        )
3910        .with_shutdown_deadline(Duration::from_millis(100));
3911
3912        runtime.run_start_phase().await.unwrap();
3913        runtime.run_stop_phase().await.unwrap();
3914
3915        // Graceful shutdown should NOT have completed (deadline fired first)
3916        assert!(
3917            !gear.graceful_completed.load(Ordering::SeqCst),
3918            "graceful shutdown should not complete when deadline fires first"
3919        );
3920        // Deadline should have fired
3921        assert!(
3922            gear.deadline_fired.load(Ordering::SeqCst),
3923            "deadline should fire for slow gears"
3924        );
3925    }
3926}
3927
3928#[cfg(test)]
3929#[cfg_attr(coverage_nightly, coverage(off))]
3930#[path = "host_runtime_preparation_tests.rs"]
3931mod host_runtime_preparation_tests;
3932
3933#[cfg(test)]
3934#[cfg_attr(coverage_nightly, coverage(off))]
3935#[path = "host_runtime_rest_bootstrap_tests.rs"]
3936mod host_runtime_rest_bootstrap_tests;