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>.clients.consumes.<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.{}.clients.consumes.{}` 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 `clients.consumes.<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 the [`ConsumerWiring`] for `owner`'s client of `dep` from
2377/// `gears.<owner>.clients` ([`crate::clients_config::consumer_wiring`]).
2378///
2379/// `Ok(None)` when absent (the dep keeps discovery). A *present* entry that cannot
2380/// be read is an `Err` that aborts proxy-wiring, as on the provider side.
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    crate::clients_config::consumer_wiring(cfg, owner_gear, dep_gear)
2387}
2388
2389#[cfg(test)]
2390#[cfg(feature = "bootstrap")]
2391#[cfg_attr(coverage_nightly, coverage(off))]
2392#[path = "host_runtime_oop_tests.rs"]
2393mod host_runtime_oop_tests;
2394
2395#[cfg(test)]
2396#[cfg_attr(coverage_nightly, coverage(off))]
2397mod tests {
2398    use super::*;
2399    use crate::context::GearCtx;
2400    use crate::contracts::{Gear, RunnableCapability, SystemCapability};
2401    use crate::registry::RegistryBuilder;
2402    use std::sync::Arc;
2403    use std::sync::atomic::{AtomicUsize, Ordering};
2404    use tokio::sync::Mutex;
2405
2406    #[derive(Default)]
2407    #[allow(dead_code)]
2408    struct DummyCore;
2409    #[async_trait::async_trait]
2410    impl Gear for DummyCore {
2411        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2412            Ok(())
2413        }
2414    }
2415
2416    struct StopOrderTracker {
2417        my_order: usize,
2418        stop_order: Arc<AtomicUsize>,
2419    }
2420
2421    impl StopOrderTracker {
2422        fn new(counter: &Arc<AtomicUsize>, stop_order: Arc<AtomicUsize>) -> Self {
2423            let my_order = counter.fetch_add(1, Ordering::SeqCst);
2424            Self {
2425                my_order,
2426                stop_order,
2427            }
2428        }
2429    }
2430
2431    #[async_trait::async_trait]
2432    impl Gear for StopOrderTracker {
2433        async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2434            Ok(())
2435        }
2436    }
2437
2438    #[async_trait::async_trait]
2439    impl RunnableCapability for StopOrderTracker {
2440        async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2441            Ok(())
2442        }
2443        async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2444            let order = self.stop_order.fetch_add(1, Ordering::SeqCst);
2445            tracing::info!(my_order = self.my_order, stop_order = order, "Gear stopped");
2446            Ok(())
2447        }
2448    }
2449
2450    #[tokio::test]
2451    async fn test_stop_phase_reverse_order() {
2452        let counter = Arc::new(AtomicUsize::new(0));
2453        let stop_order = Arc::new(AtomicUsize::new(0));
2454
2455        let gear_a = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2456        let gear_b = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2457        let gear_c = Arc::new(StopOrderTracker::new(&counter, stop_order.clone()));
2458
2459        let mut builder = RegistryBuilder::default();
2460        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2461        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2462        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2463
2464        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2465        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2466        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2467
2468        let registry = builder.build_topo_sorted().unwrap();
2469
2470        // Verify gear order is a -> b -> c
2471        let gear_names: Vec<_> = registry.gears().iter().map(|m| m.name).collect();
2472        assert_eq!(gear_names, vec!["a", "b", "c"]);
2473
2474        let client_hub = Arc::new(ClientHub::new());
2475        let cancel = CancellationToken::new();
2476        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2477
2478        let runtime = HostRuntime::new(
2479            registry,
2480            config_provider,
2481            DbOptions::None,
2482            client_hub,
2483            cancel.clone(),
2484            Uuid::new_v4(),
2485            None,
2486        );
2487
2488        // Run stop phase
2489        runtime.run_start_phase().await.unwrap();
2490        runtime.run_stop_phase().await.unwrap();
2491
2492        // Verify gears stopped in reverse order: c (stop_order=0), b (stop_order=1), a (stop_order=2)
2493        // Gear order is: a=0, b=1, c=2
2494        // Stop order should be: c=0, b=1, a=2
2495        assert_eq!(stop_order.load(Ordering::SeqCst), 3);
2496    }
2497
2498    #[tokio::test]
2499    async fn test_stop_phase_continues_on_error() {
2500        struct FailingGear {
2501            should_fail: bool,
2502            stopped: Arc<AtomicUsize>,
2503        }
2504
2505        #[async_trait::async_trait]
2506        impl Gear for FailingGear {
2507            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
2508                Ok(())
2509            }
2510        }
2511
2512        #[async_trait::async_trait]
2513        impl RunnableCapability for FailingGear {
2514            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2515                Ok(())
2516            }
2517            async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
2518                self.stopped.fetch_add(1, Ordering::SeqCst);
2519                if self.should_fail {
2520                    anyhow::bail!("Intentional failure")
2521                }
2522                Ok(())
2523            }
2524        }
2525
2526        let stopped = Arc::new(AtomicUsize::new(0));
2527        let gear_a = Arc::new(FailingGear {
2528            should_fail: false,
2529            stopped: stopped.clone(),
2530        });
2531        let gear_b = Arc::new(FailingGear {
2532            should_fail: true,
2533            stopped: stopped.clone(),
2534        });
2535        let gear_c = Arc::new(FailingGear {
2536            should_fail: false,
2537            stopped: stopped.clone(),
2538        });
2539
2540        let mut builder = RegistryBuilder::default();
2541        builder.register_core_with_meta("a", &[], gear_a.clone() as Arc<dyn Gear>);
2542        builder.register_core_with_meta("b", &["a"], gear_b.clone() as Arc<dyn Gear>);
2543        builder.register_core_with_meta("c", &["b"], gear_c.clone() as Arc<dyn Gear>);
2544
2545        builder.register_stateful_with_meta("a", gear_a.clone() as Arc<dyn RunnableCapability>);
2546        builder.register_stateful_with_meta("b", gear_b.clone() as Arc<dyn RunnableCapability>);
2547        builder.register_stateful_with_meta("c", gear_c.clone() as Arc<dyn RunnableCapability>);
2548
2549        let registry = builder.build_topo_sorted().unwrap();
2550
2551        let client_hub = Arc::new(ClientHub::new());
2552        let cancel = CancellationToken::new();
2553        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
2554
2555        let runtime = HostRuntime::new(
2556            registry,
2557            config_provider,
2558            DbOptions::None,
2559            client_hub,
2560            cancel.clone(),
2561            Uuid::new_v4(),
2562            None,
2563        );
2564
2565        // Run stop phase - should not fail even though gear_b fails
2566        runtime.run_start_phase().await.unwrap();
2567        runtime.run_stop_phase().await.unwrap();
2568
2569        // All gears should have attempted to stop
2570        assert_eq!(stopped.load(Ordering::SeqCst), 3);
2571    }
2572
2573    struct EmptyConfigProvider;
2574    impl ConfigProvider for EmptyConfigProvider {
2575        fn get_gear_config(&self, _gear_name: &str) -> Option<&serde_json::Value> {
2576            None
2577        }
2578    }
2579
2580    /// Serves one config blob for owner gear `orders` (the owner every
2581    /// `read_consumer_wiring` test uses) and nothing for anything else.
2582    struct OrdersCfg(serde_json::Value);
2583    impl ConfigProvider for OrdersCfg {
2584        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2585            (gear == "orders").then_some(&self.0)
2586        }
2587    }
2588
2589    /// Serves config blobs by owner-gear name (for tests wiring several gears).
2590    struct MapCfg(std::collections::HashMap<String, serde_json::Value>);
2591    impl ConfigProvider for MapCfg {
2592        fn get_gear_config(&self, gear: &str) -> Option<&serde_json::Value> {
2593            self.0.get(gear)
2594        }
2595    }
2596
2597    /// Extract just the static-endpoint override from a `clients.consumes` entry.
2598    fn endpoint_override(cfg: &dyn ConfigProvider, owner: &str, dep: &str) -> Option<String> {
2599        super::read_consumer_wiring(cfg, owner, dep)
2600            .expect("clients.consumes must not error for a valid/absent endpoint")
2601            .and_then(|w| w.into_parts().0)
2602    }
2603
2604    #[test]
2605    fn static_endpoint_override_reads_the_clients_consumes_entry() {
2606        let mut map = std::collections::HashMap::new();
2607        map.insert(
2608            "orders".to_owned(),
2609            serde_json::json!({
2610                "clients": {
2611                    "consumes": { "billing": { "endpoint": "http://localhost:8081" } }
2612                }
2613            }),
2614        );
2615        let cfg = MapCfg(map);
2616
2617        // Present override is read from `clients.consumes.<dep>.endpoint`.
2618        assert_eq!(
2619            endpoint_override(&cfg, "orders", "billing").as_deref(),
2620            Some("http://localhost:8081")
2621        );
2622        // Absent dep / owner → None (falls through to directory resolution).
2623        assert_eq!(endpoint_override(&cfg, "orders", "inventory"), None);
2624        assert_eq!(endpoint_override(&cfg, "warehouse", "billing"), None);
2625        assert_eq!(
2626            endpoint_override(&EmptyConfigProvider, "orders", "billing"),
2627            None
2628        );
2629    }
2630
2631    /// The object form yields both the `endpoint` override and the flattened
2632    /// `ClientTuning`.
2633    #[test]
2634    fn consumer_wiring_object_form_yields_endpoint_and_tuning() {
2635        let cfg = OrdersCfg(serde_json::json!({
2636            "clients": {
2637                "consumes": {
2638                    "billing": {
2639                        "endpoint": "http://billing:8080",
2640                        "timeout": "5s",
2641                        "max_concurrent_requests": 256,
2642                        "pool_max_idle_per_host": 256
2643                    }
2644                }
2645            }
2646        }));
2647
2648        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2649            .expect("wiring must parse")
2650            .expect("wiring present")
2651            .into_parts();
2652        assert_eq!(endpoint.as_deref(), Some("http://billing:8080"));
2653        assert_eq!(tuning.timeout, Some(std::time::Duration::from_secs(5)));
2654        assert_eq!(tuning.max_concurrent_requests, Some(256));
2655        assert_eq!(tuning.pool_max_idle_per_host, Some(256));
2656    }
2657
2658    /// Omitting `endpoint` keeps discovery while still applying the tuning.
2659    #[test]
2660    fn consumer_wiring_object_without_endpoint_keeps_discovery() {
2661        let cfg = OrdersCfg(serde_json::json!({
2662            "clients": {
2663                "consumes": { "billing": { "max_concurrent_requests": 1 } }
2664            }
2665        }));
2666
2667        let (endpoint, tuning) = super::read_consumer_wiring(&cfg, "orders", "billing")
2668            .expect("wiring must parse")
2669            .expect("wiring present")
2670            .into_parts();
2671        assert_eq!(endpoint, None, "omitted endpoint must keep discovery");
2672        assert_eq!(tuning.max_concurrent_requests, Some(1));
2673    }
2674
2675    /// A present-but-unparseable entry (wrong shape or wrong-typed tuning) is a
2676    /// boot error, matching the provider side's `clients.provides` — not a silent
2677    /// downgrade to discovery.
2678    #[test]
2679    fn consumer_wiring_malformed_entry_is_an_error() {
2680        let malformed = [
2681            // Not a ConsumerWiring object at all.
2682            serde_json::json!([1, 2, 3]),
2683            // A wrong-typed tuning value: a string where a count is expected, and
2684            // a bare number where a humantime duration string is expected.
2685            serde_json::json!({ "max_concurrent_requests": "lots" }),
2686            serde_json::json!({ "timeout": 5 }),
2687            // The same, even alongside an otherwise-valid endpoint override: the
2688            // whole entry fails, so the override is not silently honoured untuned.
2689            serde_json::json!({ "endpoint": "http://billing:8080", "timeout": 5 }),
2690        ];
2691        for entry in malformed {
2692            let cfg = OrdersCfg(serde_json::json!({
2693                "clients": { "consumes": { "billing": entry.clone() } }
2694            }));
2695            assert!(
2696                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2697                "a malformed entry (`{entry}`) must be a boot error, not silently dropped"
2698            );
2699        }
2700    }
2701
2702    /// A present-but-invalid `endpoint` is surfaced as an error, not downgraded to
2703    /// discovery — the operator asked for a specific endpoint that can't be honoured.
2704    #[test]
2705    fn consumer_wiring_invalid_endpoint_is_an_error() {
2706        for bad in ["", "billing", "/path/only"] {
2707            let cfg = OrdersCfg(serde_json::json!({
2708                "clients": { "consumes": { "billing": { "endpoint": bad } } }
2709            }));
2710            assert!(
2711                super::read_consumer_wiring(&cfg, "orders", "billing").is_err(),
2712                "a present-but-invalid endpoint (`{bad}`) must be a hard error, not survived"
2713            );
2714        }
2715    }
2716
2717    /// One record of what a test wired the phase with. The phase tests share this
2718    /// collector and run in parallel, so each finds its own entry by a unique
2719    /// tuning value.
2720    #[derive(Clone)]
2721    struct WiredCall {
2722        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2723        max_concurrent_requests: Option<usize>,
2724        /// A dropped credential is otherwise invisible — the only runtime symptom
2725        /// is a missing `X-ToolKit-Internal-Token` on every Profile 2/3 call.
2726        has_credential: bool,
2727    }
2728    static WIRED: std::sync::Mutex<Vec<WiredCall>> = std::sync::Mutex::new(Vec::new());
2729
2730    /// Stands in for the `#[toolkit::consumes]`-generated wire fn: records the
2731    /// resolver and tuning it was handed, then reports a remote binding.
2732    #[allow(
2733        clippy::unnecessary_wraps,
2734        clippy::needless_pass_by_value,
2735        reason = "must match the ConsumerRegistration::wire signature the macro emits"
2736    )]
2737    fn record_wire(
2738        _hub: &ClientHub,
2739        resolver: Arc<dyn crate::discovery::EndpointResolver>,
2740        tuning: toolkit_contract::wiring::ClientTuning,
2741    ) -> anyhow::Result<crate::discovery::WireOutcome> {
2742        WIRED.lock().unwrap().push(WiredCall {
2743            resolver,
2744            max_concurrent_requests: tuning.max_concurrent_requests,
2745            has_credential: tuning.internal_token_provider.is_some(),
2746        });
2747        Ok(crate::discovery::WireOutcome::Remote)
2748    }
2749
2750    /// A consumer registration for the phase tests, wired directly so it never
2751    /// enters the link-time-global `inventory` set (which would leak onto other
2752    /// tests in this binary).
2753    fn test_registration() -> crate::discovery::ConsumerRegistration {
2754        crate::discovery::ConsumerRegistration {
2755            owner_gear: "orders",
2756            dep_gear: "billing",
2757            wire: record_wire,
2758        }
2759    }
2760
2761    /// Static-endpoint arm: an `endpoint` wires a `StaticEndpointResolver` pinned
2762    /// to it, threads the entry's tuning through, and marks the dep resolved
2763    /// immediately (no probe loop).
2764    #[tokio::test]
2765    async fn proxy_wiring_static_override_uses_static_resolver_and_marks_ready() {
2766        let mut map = std::collections::HashMap::new();
2767        map.insert(
2768            "orders".to_owned(),
2769            serde_json::json!({
2770                "clients": {
2771                    "consumes": {
2772                        "billing": {
2773                            "endpoint": "http://localhost:8081",
2774                            "max_concurrent_requests": 7
2775                        }
2776                    }
2777                }
2778            }),
2779        );
2780
2781        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2782        let runtime = HostRuntime::new(
2783            registry,
2784            Arc::new(MapCfg(map)),
2785            DbOptions::None,
2786            Arc::new(ClientHub::new()),
2787            CancellationToken::new(),
2788            Uuid::new_v4(),
2789            None,
2790        );
2791
2792        let reg = test_registration();
2793        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2794
2795        // Find *the* entry whose resolver yields the configured endpoint and
2796        // assert that same entry's tuning — OR-ing two flags independently across
2797        // every WIRED entry would pass even if the endpoint and the tuning had
2798        // arrived on two different wire calls.
2799        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2800        let mut matched = None;
2801        for call in &calls {
2802            if let Ok(Some(ep)) = call.resolver.resolve_endpoint("billing").await
2803                && ep == "http://localhost:8081"
2804            {
2805                matched = Some(call.clone());
2806                break;
2807            }
2808        }
2809        let matched = matched
2810            .expect("static override must wire a resolver pinned to the configured endpoint");
2811        assert_eq!(
2812            matched.max_concurrent_requests,
2813            Some(7),
2814            "the tuning on the same wire call as the static endpoint must be the configured one"
2815        );
2816
2817        // A static endpoint is resolvable by construction: the dep must be
2818        // resolved immediately rather than left gating /readyz.
2819        assert_eq!(
2820            runtime.dep_checker.unresolved_deps(),
2821            [crate::runtime::PREPARATION_GATE],
2822            "only the not yet started application group gates readiness"
2823        );
2824    }
2825
2826    /// An in-process provider that forgot to register its local impl must fail
2827    /// startup rather than silently wiring a self-pointing proxy: here both the
2828    /// consumer `orders` and provider `billing` are registered gears, but the
2829    /// consumer's wiring reports `Remote`.
2830    #[tokio::test]
2831    async fn proxy_wiring_in_process_provider_wired_remote_is_a_hard_error() {
2832        // Register the consumer `orders` and the provider `billing`, where billing
2833        // never provides its client (no local impl, no REST).
2834        let mut b = crate::registry::RegistryBuilder::default();
2835        b.register_core_with_meta("orders", &[], Arc::new(DummyCore));
2836        b.register_core_with_meta("billing", &[], Arc::new(DummyCore));
2837        let registry = b.build_topo_sorted().unwrap();
2838
2839        let runtime = HostRuntime::new(
2840            registry,
2841            Arc::new(MapCfg(std::collections::HashMap::new())),
2842            DbOptions::None,
2843            Arc::new(ClientHub::new()),
2844            CancellationToken::new(),
2845            Uuid::new_v4(),
2846            None,
2847        );
2848
2849        // `test_registration()` is owner=orders, dep=billing, and `record_wire`
2850        // reports `Remote` without registering a local impl — the bug scenario.
2851        let reg = test_registration();
2852        let err = runtime
2853            .wire_consumer_registrations(&[&reg])
2854            .expect_err("an in-process provider wired Remote must fail startup");
2855        let msg = err.to_string();
2856        assert!(
2857            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
2858            "expected a ProxyWiring error for the consumer gear, got: {msg}"
2859        );
2860        // Display must surface the source, so both the consumer and provider gear
2861        // names appear in the rendered message.
2862        assert!(
2863            msg.contains("orders") && msg.contains("billing"),
2864            "displayed error must name both consumer and provider, got: {msg}"
2865        );
2866    }
2867
2868    /// Tuning-only entry (no `endpoint`, the production shape): keeps the shared
2869    /// discovery resolver and leaves the dep gating readiness — a remote dep with
2870    /// no directory stays unresolved.
2871    #[tokio::test]
2872    async fn proxy_wiring_tuning_only_entry_keeps_discovery_and_gates_readiness() {
2873        let mut map = std::collections::HashMap::new();
2874        // A unique tuning value so this test can find its own WIRED entry among
2875        // the link-time-global registrations.
2876        map.insert(
2877            "orders".to_owned(),
2878            serde_json::json!({
2879                "clients": {
2880                    "consumes": { "billing": { "max_concurrent_requests": 4343 } }
2881                }
2882            }),
2883        );
2884
2885        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2886        let runtime = HostRuntime::new(
2887            registry,
2888            Arc::new(MapCfg(map)),
2889            DbOptions::None,
2890            Arc::new(ClientHub::new()),
2891            CancellationToken::new(),
2892            Uuid::new_v4(),
2893            None,
2894        );
2895
2896        let reg = test_registration();
2897        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2898
2899        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2900        let ours = calls
2901            .iter()
2902            .find(|c| c.max_concurrent_requests == Some(4343))
2903            .expect("our tuning-only wire call must have been recorded");
2904        assert!(
2905            matches!(ours.resolver.resolve_endpoint("billing").await, Ok(None)),
2906            "a tuning-only entry must keep discovery -- the resolver must not be pinned to a \
2907             static endpoint"
2908        );
2909
2910        // No directory + a remote dep → it must stay unresolved and gate /readyz.
2911        assert!(!runtime.dep_checker.all_resolved());
2912        assert!(
2913            runtime
2914                .dep_checker
2915                .unresolved_deps()
2916                .contains(&"billing".to_owned()),
2917            "a discovery-wired dep with no directory must gate readiness"
2918        );
2919    }
2920
2921    /// The process's platform-plane credential must ride on the tuning handed to
2922    /// the wire fn (Profile 2/3), else every inter-gear call ships without
2923    /// `X-ToolKit-Internal-Token`.
2924    #[tokio::test]
2925    async fn proxy_wiring_threads_platform_credential_onto_tuning() {
2926        use toolkit_contract::runtime::config::{CredentialState, InternalTokenProvider};
2927
2928        let mut map = std::collections::HashMap::new();
2929        map.insert(
2930            "orders".to_owned(),
2931            serde_json::json!({
2932                "clients": {
2933                    "consumes": { "billing": { "max_concurrent_requests": 4242 } }
2934                }
2935            }),
2936        );
2937
2938        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2939        let provider = InternalTokenProvider::new(|| CredentialState::NotConfigured);
2940        let runtime = HostRuntime::new(
2941            registry,
2942            Arc::new(MapCfg(map)),
2943            DbOptions::None,
2944            Arc::new(ClientHub::new()),
2945            CancellationToken::new(),
2946            Uuid::new_v4(),
2947            None,
2948        )
2949        .with_internal_token_provider(Some(provider));
2950
2951        let reg = test_registration();
2952        runtime.wire_consumer_registrations(&[&reg]).unwrap();
2953
2954        let calls: Vec<WiredCall> = WIRED.lock().unwrap().clone();
2955        let ours = calls
2956            .iter()
2957            .find(|c| c.max_concurrent_requests == Some(4242))
2958            .expect("our wire call must have been recorded");
2959        assert!(
2960            ours.has_credential,
2961            "the process credential must be threaded onto the tuning handed to the wire fn"
2962        );
2963    }
2964
2965    /// Phase-level: a non-absolute `endpoint` aborts proxy-wiring with
2966    /// `RegistryError::ProxyWiring` rather than silently downgrading to discovery
2967    /// (which would mark the dep resolved while every call fails).
2968    #[tokio::test]
2969    async fn proxy_wiring_invalid_endpoint_is_a_hard_error() {
2970        let mut map = std::collections::HashMap::new();
2971        map.insert(
2972            "orders".to_owned(),
2973            serde_json::json!({
2974                "clients": {
2975                    "consumes": {
2976                        "billing": { "endpoint": "", "max_concurrent_requests": 4444 }
2977                    }
2978                }
2979            }),
2980        );
2981
2982        let registry = RegistryBuilder::default().build_topo_sorted().unwrap();
2983        let runtime = HostRuntime::new(
2984            registry,
2985            Arc::new(MapCfg(map)),
2986            DbOptions::None,
2987            Arc::new(ClientHub::new()),
2988            CancellationToken::new(),
2989            Uuid::new_v4(),
2990            None,
2991        );
2992
2993        let reg = test_registration();
2994        let err = runtime
2995            .wire_consumer_registrations(&[&reg])
2996            .expect_err("an invalid static endpoint must abort proxy-wiring");
2997        assert!(
2998            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "orders"),
2999            "expected a ProxyWiring error for the owning gear, got {err:?}"
3000        );
3001    }
3002
3003    /// The override is keyed by the kebab *gear name* (`owner_gear`), not the
3004    /// struct ident. Regression guard: the macro once emitted
3005    /// `stringify!(StructIdent)`, so the lookup could never fire.
3006    #[test]
3007    fn static_endpoint_override_is_keyed_by_kebab_gear_name() {
3008        let mut map = std::collections::HashMap::new();
3009        map.insert(
3010            "api-contracts-consumer".to_owned(),
3011            serde_json::json!({
3012                "clients": {
3013                    "consumes": {
3014                        "api-contracts": { "endpoint": "http://localhost:9099" }
3015                    }
3016                }
3017            }),
3018        );
3019        let cfg = MapCfg(map);
3020
3021        assert_eq!(
3022            endpoint_override(&cfg, "api-contracts-consumer", "api-contracts").as_deref(),
3023            Some("http://localhost:9099"),
3024        );
3025        // The pre-fix value — the Rust struct ident — must NOT resolve.
3026        assert_eq!(
3027            endpoint_override(&cfg, "ApiContractsConsumer", "api-contracts"),
3028            None,
3029        );
3030    }
3031
3032    /// What a consumer's proxy was built from, for the per-consumer tests.
3033    trait ShippingApi: Send + Sync {
3034        fn wiring(&self) -> &ShippingProxy;
3035    }
3036
3037    struct ShippingProxy {
3038        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3039        timeout: Option<std::time::Duration>,
3040        max_attempts: Option<u32>,
3041        require_tls: Option<bool>,
3042    }
3043
3044    impl ShippingApi for ShippingProxy {
3045        fn wiring(&self) -> &ShippingProxy {
3046            self
3047        }
3048    }
3049
3050    /// The body `#[toolkit::consumes]` emits, with a proxy that keeps its
3051    /// resolver and tuning.
3052    fn wire_shipping(
3053        hub: &ClientHub,
3054        resolver: Arc<dyn crate::discovery::EndpointResolver>,
3055        tuning: toolkit_contract::wiring::ClientTuning,
3056    ) -> anyhow::Result<crate::discovery::WireOutcome> {
3057        if hub.try_get_local::<dyn ShippingApi>().is_some() {
3058            return Ok(crate::discovery::WireOutcome::Local);
3059        }
3060        if hub.has_remote_proxy::<dyn ShippingApi>() {
3061            if let Some(owner) = hub.owner() {
3062                anyhow::bail!("gear `{owner}` declares #[toolkit::consumes] more than once");
3063            }
3064            return Ok(crate::discovery::WireOutcome::Remote);
3065        }
3066        hub.register_remote_proxy::<dyn ShippingApi>(Arc::new(ShippingProxy {
3067            resolver,
3068            timeout: tuning.timeout,
3069            max_attempts: tuning.retry.and_then(|r| r.max_attempts),
3070            require_tls: tuning.require_tls,
3071        }));
3072        Ok(crate::discovery::WireOutcome::Remote)
3073    }
3074
3075    fn shipping_registration(owner_gear: &'static str) -> crate::discovery::ConsumerRegistration {
3076        crate::discovery::ConsumerRegistration {
3077            owner_gear,
3078            dep_gear: "shipping",
3079            wire: wire_shipping,
3080        }
3081    }
3082
3083    /// A runtime hosting consumer gears `a` and `b` (shipping is remote).
3084    fn shipping_runtime(config: serde_json::Value) -> HostRuntime {
3085        let mut b = crate::registry::RegistryBuilder::default();
3086        b.register_core_with_meta("a", &[], Arc::new(DummyCore));
3087        b.register_core_with_meta("b", &[], Arc::new(DummyCore));
3088        let registry = b.build_topo_sorted().unwrap();
3089        let map = serde_json::from_value(config).unwrap();
3090        HostRuntime::new(
3091            registry,
3092            Arc::new(MapCfg(map)),
3093            DbOptions::None,
3094            Arc::new(ClientHub::new()),
3095            CancellationToken::new(),
3096            Uuid::new_v4(),
3097            None,
3098        )
3099    }
3100
3101    /// Issue #5686: two gears consuming one contract each get a proxy built
3102    /// from their own `clients.consumes` entry, whichever wires first.
3103    #[tokio::test]
3104    async fn each_consumer_gets_a_proxy_with_its_own_wiring() {
3105        let config = serde_json::json!({
3106            "a": { "clients": { "consumes": { "shipping": {
3107                "endpoint": "http://shipping-for-a:8080",
3108                "timeout": "1s",
3109                "retry": { "max_attempts": 2 },
3110                "require_tls": false
3111            } } } },
3112            "b": { "clients": { "consumes": { "shipping": {
3113                "endpoint": "http://shipping-for-b:8080",
3114                "timeout": "10s",
3115                "retry": { "max_attempts": 5 },
3116                "require_tls": true
3117            } } } }
3118        });
3119        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3120
3121        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3122            let runtime = shipping_runtime(config.clone());
3123            runtime.wire_consumer_registrations(&order).unwrap();
3124
3125            let hub = &runtime.client_hub;
3126            let a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3127            let b = hub.for_gear("b").get::<dyn ShippingApi>().unwrap();
3128            assert!(!Arc::ptr_eq(&a, &b));
3129            assert!(
3130                hub.try_get::<dyn ShippingApi>().is_none(),
3131                "a gear's proxy is not process-wide"
3132            );
3133
3134            let (a, b) = (a.wiring(), b.wiring());
3135            assert_eq!(
3136                a.resolver
3137                    .resolve_endpoint("shipping")
3138                    .await
3139                    .unwrap()
3140                    .as_deref(),
3141                Some("http://shipping-for-a:8080")
3142            );
3143            assert_eq!(
3144                b.resolver
3145                    .resolve_endpoint("shipping")
3146                    .await
3147                    .unwrap()
3148                    .as_deref(),
3149                Some("http://shipping-for-b:8080")
3150            );
3151            assert_eq!(a.timeout, Some(std::time::Duration::from_secs(1)));
3152            assert_eq!(b.timeout, Some(std::time::Duration::from_secs(10)));
3153            assert_eq!((a.max_attempts, b.max_attempts), (Some(2), Some(5)));
3154            assert_eq!((a.require_tls, b.require_tls), (Some(false), Some(true)));
3155        }
3156    }
3157
3158    /// An owner that is not a gear in this process (an SDK-level registration)
3159    /// wires a process-wide proxy that every gear's view can read.
3160    #[tokio::test]
3161    async fn an_unknown_owner_wires_a_process_wide_proxy() {
3162        let runtime = shipping_runtime(serde_json::json!({}));
3163        let reg = shipping_registration("shipping-sdk");
3164        runtime.wire_consumer_registrations(&[&reg]).unwrap();
3165
3166        let hub = &runtime.client_hub;
3167        let shared = hub.get::<dyn ShippingApi>().unwrap();
3168        let seen_by_a = hub.for_gear("a").get::<dyn ShippingApi>().unwrap();
3169        assert!(Arc::ptr_eq(&shared, &seen_by_a));
3170    }
3171
3172    /// With one consumer on a static endpoint and another on discovery, the dep
3173    /// stays unresolved: the second consumer's provider is not found yet.
3174    #[tokio::test]
3175    async fn a_static_consumer_does_not_resolve_a_dep_another_consumer_discovers() {
3176        let config = serde_json::json!({
3177            "a": { "clients": { "consumes": { "shipping": {
3178                "endpoint": "http://shipping:8080"
3179            } } } }
3180        });
3181        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3182
3183        for order in [[&reg_a, &reg_b], [&reg_b, &reg_a]] {
3184            let runtime = shipping_runtime(config.clone());
3185            runtime.wire_consumer_registrations(&order).unwrap();
3186
3187            assert!(
3188                runtime
3189                    .dep_checker
3190                    .unresolved_deps()
3191                    .contains(&"shipping".to_owned()),
3192                "the discovery consumer must keep the dep gating readiness"
3193            );
3194        }
3195    }
3196
3197    /// Same mix with a directory: the dep stays unresolved until the provider
3198    /// is advertised, then the probe resolves it.
3199    #[tokio::test]
3200    async fn a_mixed_dep_resolves_once_the_provider_is_advertised() {
3201        let config = serde_json::json!({
3202            "a": { "clients": { "consumes": { "shipping": {
3203                "endpoint": "http://shipping:8080"
3204            } } } }
3205        });
3206        let runtime = shipping_runtime(config);
3207        let gears = Arc::new(crate::runtime::GearManager::new());
3208        runtime
3209            .client_hub
3210            .register::<dyn crate::DirectoryClient>(Arc::new(
3211                crate::directory::LocalDirectoryClient::new(Arc::clone(&gears)),
3212            ));
3213        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3214        runtime
3215            .wire_consumer_registrations(&[&reg_a, &reg_b])
3216            .unwrap();
3217
3218        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3219        assert!(
3220            runtime
3221                .dep_checker
3222                .unresolved_deps()
3223                .contains(&"shipping".to_owned()),
3224            "no provider is advertised yet"
3225        );
3226
3227        gears
3228            .register_instance(Arc::new(
3229                crate::runtime::GearInstance::new("shipping", Uuid::new_v4())
3230                    .with_rest_endpoint(crate::runtime::Endpoint::http("shipping", 8080)),
3231            ))
3232            .unwrap();
3233        tokio::time::timeout(std::time::Duration::from_secs(5), async {
3234            while runtime
3235                .dep_checker
3236                .unresolved_deps()
3237                .contains(&"shipping".to_owned())
3238            {
3239                tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3240            }
3241        })
3242        .await
3243        .expect("the probe must resolve the dep once the provider is advertised");
3244        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3245        runtime.owned.cancel();
3246    }
3247
3248    /// Both consumers on static endpoints: resolved at wiring time.
3249    #[tokio::test]
3250    async fn static_consumers_resolve_the_dep() {
3251        let entry = serde_json::json!({ "clients": { "consumes": { "shipping": {
3252            "endpoint": "http://shipping:8080"
3253        } } } });
3254        let runtime = shipping_runtime(serde_json::json!({ "a": entry, "b": entry }));
3255        let (reg_a, reg_b) = (shipping_registration("a"), shipping_registration("b"));
3256        runtime
3257            .wire_consumer_registrations(&[&reg_a, &reg_b])
3258            .unwrap();
3259
3260        assert_eq!(runtime.dep_checker.unresolved_deps(), [PREPARATION_GATE]);
3261    }
3262
3263    /// One gear consuming the same contract twice is a boot error naming it.
3264    #[tokio::test]
3265    async fn a_gear_consuming_a_contract_twice_fails_wiring() {
3266        let runtime = shipping_runtime(serde_json::json!({}));
3267        let reg = shipping_registration("a");
3268        let duplicate = shipping_registration("a");
3269        let err = runtime
3270            .wire_consumer_registrations(&[&reg, &duplicate])
3271            .expect_err("a duplicate consumer must fail wiring");
3272        assert!(
3273            matches!(err, RegistryError::ProxyWiring { gear, .. } if gear == "a"),
3274            "got {err:?}"
3275        );
3276    }
3277
3278    #[tokio::test]
3279    async fn test_post_init_runs_after_all_init_for_every_gear_system_group_first() {
3280        #[derive(Clone)]
3281        struct TrackHooks {
3282            name: &'static str,
3283            events: Arc<Mutex<Vec<String>>>,
3284        }
3285
3286        #[async_trait::async_trait]
3287        impl Gear for TrackHooks {
3288            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3289                self.events.lock().await.push(format!("init:{}", self.name));
3290                Ok(())
3291            }
3292
3293            async fn post_init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3294                self.events
3295                    .lock()
3296                    .await
3297                    .push(format!("post_init:{}", self.name));
3298                Ok(())
3299            }
3300        }
3301
3302        impl SystemCapability for TrackHooks {}
3303
3304        let events = Arc::new(Mutex::new(Vec::<String>::new()));
3305        let sys_a = Arc::new(TrackHooks {
3306            name: "sys_a",
3307            events: events.clone(),
3308        });
3309        let user_b = Arc::new(TrackHooks {
3310            name: "user_b",
3311            events: events.clone(),
3312        });
3313        let user_c = Arc::new(TrackHooks {
3314            name: "user_c",
3315            events: events.clone(),
3316        });
3317
3318        let mut builder = RegistryBuilder::default();
3319        builder.register_core_with_meta("sys_a", &[], sys_a.clone() as Arc<dyn Gear>);
3320        builder.register_core_with_meta("user_b", &["sys_a"], user_b.clone() as Arc<dyn Gear>);
3321        builder.register_core_with_meta("user_c", &["user_b"], user_c.clone() as Arc<dyn Gear>);
3322        builder.register_system_with_meta("sys_a", sys_a.clone() as Arc<dyn SystemCapability>);
3323
3324        let registry = builder.build_topo_sorted().unwrap();
3325
3326        let client_hub = Arc::new(ClientHub::new());
3327        let cancel = CancellationToken::new();
3328        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3329
3330        let runtime = HostRuntime::new(
3331            registry,
3332            config_provider,
3333            DbOptions::None,
3334            client_hub,
3335            cancel,
3336            Uuid::new_v4(),
3337            None,
3338        );
3339
3340        // Run init phase for all gears, then post_init as a separate barrier phase.
3341        runtime.run_init_phase().await.unwrap();
3342        runtime.run_post_init_phase().await.unwrap();
3343
3344        let events = events.lock().await.clone();
3345        let first_post_init = events
3346            .iter()
3347            .position(|e| e.starts_with("post_init:"))
3348            .expect("expected post_init events");
3349        assert!(
3350            events[..first_post_init]
3351                .iter()
3352                .all(|e| e.starts_with("init:")),
3353            "expected all init events before post_init, got: {events:?}"
3354        );
3355
3356        // The system group first, each group in topological order.
3357        assert_eq!(
3358            events,
3359            vec![
3360                "init:sys_a",
3361                "init:user_b",
3362                "init:user_c",
3363                "post_init:sys_a",
3364                "post_init:user_b",
3365                "post_init:user_c",
3366            ]
3367        );
3368    }
3369
3370    /// The force-exit watchdog (shared by init and stop) fires only when it is
3371    /// never disarmed within the deadline. The decision is split from
3372    /// `process::exit` into `watchdog_verdict` so it is unit-testable without
3373    /// killing the test process; these cover the hung case and both disarm cases.
3374    #[test]
3375    fn watchdog_times_out_when_not_disarmed() {
3376        let (_tx, rx) = std::sync::mpsc::channel::<()>();
3377        // Hold the sender; never signal → the deadline elapses → TimedOut.
3378        assert_eq!(
3379            watchdog_verdict(&rx, std::time::Duration::from_millis(20)),
3380            WatchdogVerdict::TimedOut
3381        );
3382    }
3383
3384    #[test]
3385    fn init_watchdog_subprocess() {
3386        const CHILD_MODE: &str = "TOOLKIT_INIT_WATCHDOG_TEST_MODE";
3387        struct WatchdogGear(String);
3388
3389        #[async_trait::async_trait]
3390        impl Gear for WatchdogGear {
3391            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3392                match self.0.as_str() {
3393                    "success" => (),
3394                    // Async hang: the async timeout observes it → recoverable error.
3395                    "async-hang" | "cancelled" => {
3396                        std::future::pending::<()>().await;
3397                    }
3398                    // Synchronous block: no async timer can fire; only the
3399                    // OS-thread watchdog catches it → force-exit.
3400                    "blocking" | "blocking-no-tracing" => {
3401                        std::thread::sleep(std::time::Duration::from_secs(3600));
3402                    }
3403                    "error" => anyhow::bail!("init failed"),
3404                    other => panic!("unexpected watchdog test mode: {other}"),
3405                }
3406                Ok(())
3407            }
3408        }
3409
3410        let Ok(mode) = std::env::var(CHILD_MODE) else {
3411            for (mode, expected_code) in [
3412                ("success", 0),
3413                ("async-hang", 0),
3414                ("blocking", 1),
3415                ("blocking-no-tracing", 1),
3416                ("error", 0),
3417                ("cancelled", 0),
3418            ] {
3419                let mut child = std::process::Command::new(std::env::current_exe().unwrap())
3420                    .args([
3421                        "--exact",
3422                        "runtime::host_runtime::tests::init_watchdog_subprocess",
3423                        "--nocapture",
3424                    ])
3425                    .env(CHILD_MODE, mode)
3426                    .stdout(std::process::Stdio::piped())
3427                    .stderr(std::process::Stdio::piped())
3428                    .spawn()
3429                    .unwrap();
3430                let limit = std::time::Instant::now() + std::time::Duration::from_secs(5);
3431                while child.try_wait().unwrap().is_none() {
3432                    if std::time::Instant::now() >= limit {
3433                        child.kill().unwrap();
3434                        let output = child.wait_with_output().unwrap();
3435                        panic!("watchdog subprocess {mode} hung: {output:?}");
3436                    }
3437                    std::thread::sleep(std::time::Duration::from_millis(10));
3438                }
3439                let output = child.wait_with_output().unwrap();
3440                assert_eq!(
3441                    output.status.code(),
3442                    Some(expected_code),
3443                    "{mode}: {output:?}"
3444                );
3445                if mode.starts_with("blocking") {
3446                    // One line must carry ERROR + message + gear name (holds even
3447                    // with tracing OFF, where only the stderr fallback is emitted).
3448                    let logs = String::from_utf8_lossy(&output.stderr);
3449                    assert!(
3450                        logs.lines().any(|line| line.contains("ERROR")
3451                            && line.contains("init timed out")
3452                            && line.contains("watchdog-test")),
3453                        "{logs}"
3454                    );
3455                }
3456            }
3457            return;
3458        };
3459
3460        tracing_subscriber::fmt()
3461            .with_ansi(false)
3462            .with_max_level(if mode == "blocking-no-tracing" {
3463                tracing::level_filters::LevelFilter::OFF
3464            } else {
3465                tracing::level_filters::LevelFilter::INFO
3466            })
3467            .with_writer(std::io::stderr)
3468            .try_init()
3469            .unwrap();
3470        tokio::runtime::Builder::new_current_thread()
3471            .enable_all()
3472            .build()
3473            .unwrap()
3474            .block_on(async {
3475                let mut builder = RegistryBuilder::default();
3476                builder.register_core_with_meta(
3477                    "watchdog-test",
3478                    &[],
3479                    Arc::new(WatchdogGear(mode.clone())) as Arc<dyn Gear>,
3480                );
3481                let runtime = HostRuntime::new(
3482                    builder.build_topo_sorted().unwrap(),
3483                    Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3484                    DbOptions::None,
3485                    Arc::new(ClientHub::new()),
3486                    CancellationToken::new(),
3487                    Uuid::new_v4(),
3488                    None,
3489                )
3490                .with_init_deadline(std::time::Duration::from_millis(200));
3491
3492                #[allow(
3493                    clippy::match_same_arms,
3494                    reason = "`success` returns normally; in `blocking*` the same call never returns and the watchdog force-exits"
3495                )]
3496                match mode.as_str() {
3497                    "cancelled" => {
3498                        // Dropping the phase future disarms the watchdog: no exit.
3499                        assert!(
3500                            tokio::time::timeout(
3501                                std::time::Duration::from_millis(20),
3502                                runtime.run_init_phase(),
3503                            )
3504                            .await
3505                            .is_err()
3506                        );
3507                    }
3508                    "success" => {
3509                        runtime.run_init_phase().await.unwrap();
3510                    }
3511                    "async-hang" => {
3512                        // Recoverable error, not a force-exit.
3513                        let err = runtime.run_init_phase().await.unwrap_err();
3514                        assert!(matches!(
3515                            err,
3516                            RegistryError::InitTimeout {
3517                                gear: "watchdog-test",
3518                                ..
3519                            }
3520                        ));
3521                    }
3522                    "error" => {
3523                        let err = runtime.run_init_phase().await.unwrap_err();
3524                        assert!(matches!(
3525                            err,
3526                            RegistryError::Init {
3527                                gear: "watchdog-test",
3528                                ..
3529                            }
3530                        ));
3531                    }
3532                    // Never returns; the OS-thread watchdog force-exits instead.
3533                    "blocking" | "blocking-no-tracing" => {
3534                        runtime.run_init_phase().await.unwrap();
3535                    }
3536                    other => panic!("unexpected watchdog test mode: {other}"),
3537                }
3538                tokio::time::sleep(std::time::Duration::from_millis(400)).await;
3539            });
3540    }
3541
3542    #[test]
3543    fn watchdog_disarms_when_signalled() {
3544        let (tx, rx) = std::sync::mpsc::channel::<()>();
3545        tx.send(()).unwrap();
3546        // A generous deadline proves we return on the signal, not by timing out.
3547        assert_eq!(
3548            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
3549            WatchdogVerdict::Disarmed
3550        );
3551    }
3552
3553    #[test]
3554    fn watchdog_disarms_when_sender_is_dropped() {
3555        let (tx, rx) = std::sync::mpsc::channel::<()>();
3556        drop(tx); // guarded future dropped before it finished
3557        assert_eq!(
3558            watchdog_verdict(&rx, std::time::Duration::from_secs(30)),
3559            WatchdogVerdict::Disarmed
3560        );
3561    }
3562
3563    /// When `GearContextBuilder::for_gear` fails (here: the gear's database
3564    /// config references a global server that does not exist), the init phase
3565    /// must surface it as `RegistryError::Init` naming the gear — not hang or
3566    /// force-exit.
3567    #[cfg(feature = "db")]
3568    #[tokio::test]
3569    async fn init_ctx_failure_surfaces_as_init_error() {
3570        use figment::{Figment, providers::Serialized};
3571
3572        struct NeedsDbGear;
3573
3574        #[async_trait::async_trait]
3575        impl Gear for NeedsDbGear {
3576            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3577                Ok(())
3578            }
3579        }
3580
3581        let mut builder = RegistryBuilder::default();
3582        builder.register_core_with_meta("needsdb", &[], Arc::new(NeedsDbGear) as Arc<dyn Gear>);
3583        let registry = builder.build_topo_sorted().unwrap();
3584
3585        let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
3586            "gears": {
3587                "needsdb": {
3588                    "database": { "server": "does-not-exist" }
3589                }
3590            }
3591        })));
3592        let db_manager =
3593            toolkit_db::DbManager::from_figment(figment, std::path::PathBuf::from("/tmp/test"))
3594                .unwrap();
3595
3596        let runtime = HostRuntime::new(
3597            registry,
3598            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3599            DbOptions::Manager(Arc::new(db_manager)),
3600            Arc::new(ClientHub::new()),
3601            CancellationToken::new(),
3602            Uuid::new_v4(),
3603            None,
3604        );
3605
3606        let err = runtime.run_init_phase().await.unwrap_err();
3607        assert!(
3608            matches!(err, RegistryError::Init { gear, .. } if gear == "needsdb"),
3609            "expected RegistryError::Init for needsdb, got {err:?}"
3610        );
3611    }
3612
3613    /// A REST gear opting out of directory advertisement is served but not
3614    /// advertised (nor deregistered) as a REST provider.
3615    #[test]
3616    fn a_rest_gear_can_opt_out_of_directory_advertisement() {
3617        struct Rest {
3618            advertised: bool,
3619        }
3620        #[async_trait::async_trait]
3621        impl Gear for Rest {
3622            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3623                Ok(())
3624            }
3625        }
3626        impl crate::contracts::RestApiCapability for Rest {
3627            fn register_rest(
3628                &self,
3629                _ctx: &GearCtx,
3630                router: axum::Router,
3631                _openapi: &dyn crate::api::OpenApiRegistry,
3632            ) -> anyhow::Result<axum::Router> {
3633                Ok(router)
3634            }
3635            fn advertised_in_directory(&self) -> bool {
3636                self.advertised
3637            }
3638        }
3639
3640        let mut builder = RegistryBuilder::default();
3641        for (name, advertised) in [("advertised", true), ("hidden", false)] {
3642            let gear = Arc::new(Rest { advertised });
3643            builder.register_core_with_meta(name, &[], gear.clone() as Arc<dyn Gear>);
3644            builder.register_rest_with_meta(
3645                name,
3646                gear as Arc<dyn crate::contracts::RestApiCapability>,
3647            );
3648        }
3649        let runtime = HostRuntime::new(
3650            builder.build_topo_sorted().unwrap(),
3651            Arc::new(EmptyConfigProvider) as Arc<dyn ConfigProvider>,
3652            DbOptions::None,
3653            Arc::new(ClientHub::new()),
3654            CancellationToken::new(),
3655            Uuid::new_v4(),
3656            None,
3657        );
3658
3659        assert_eq!(runtime.rest_provider_gears(), vec!["advertised"]);
3660    }
3661
3662    #[tokio::test]
3663    async fn test_stop_phase_provides_fresh_deadline_token() {
3664        use std::sync::atomic::AtomicBool;
3665
3666        struct TokenCheckGear {
3667            stop_was_called: AtomicBool,
3668            token_was_cancelled_on_entry: AtomicBool,
3669        }
3670
3671        #[async_trait::async_trait]
3672        impl Gear for TokenCheckGear {
3673            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3674                Ok(())
3675            }
3676        }
3677
3678        #[async_trait::async_trait]
3679        impl RunnableCapability for TokenCheckGear {
3680            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3681                Ok(())
3682            }
3683            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3684                // Record that stop() was called
3685                self.stop_was_called.store(true, Ordering::SeqCst);
3686                // Record whether the token was already cancelled when stop() was called
3687                self.token_was_cancelled_on_entry
3688                    .store(deadline_token.is_cancelled(), Ordering::SeqCst);
3689                Ok(())
3690            }
3691        }
3692
3693        let gear = Arc::new(TokenCheckGear {
3694            stop_was_called: AtomicBool::new(false),
3695            // Default to true to detect if stop() was never called
3696            token_was_cancelled_on_entry: AtomicBool::new(true),
3697        });
3698
3699        let mut builder = RegistryBuilder::default();
3700        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3701        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3702
3703        let registry = builder.build_topo_sorted().unwrap();
3704        let client_hub = Arc::new(ClientHub::new());
3705        let cancel = CancellationToken::new();
3706        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3707
3708        let runtime = HostRuntime::new(
3709            registry,
3710            config_provider,
3711            DbOptions::None,
3712            client_hub,
3713            cancel.clone(),
3714            Uuid::new_v4(),
3715            None,
3716        );
3717
3718        // Run stop phase - the deadline token should NOT be cancelled
3719        runtime.run_start_phase().await.unwrap();
3720        runtime.run_stop_phase().await.unwrap();
3721
3722        // First, verify stop() was actually called (guards against silent registration failures)
3723        assert!(
3724            gear.stop_was_called.load(Ordering::SeqCst),
3725            "stop() was never called - gear may not have been registered correctly"
3726        );
3727
3728        // The token should NOT have been cancelled when stop() was called
3729        // This is the key fix: gears get a fresh token, not the already-cancelled root token
3730        assert!(
3731            !gear.token_was_cancelled_on_entry.load(Ordering::SeqCst),
3732            "deadline_token should NOT be cancelled when stop() is called - this enables graceful shutdown"
3733        );
3734    }
3735
3736    #[tokio::test]
3737    async fn test_stop_phase_graceful_shutdown_completes_before_deadline() {
3738        use std::sync::atomic::AtomicBool;
3739        use std::time::Duration;
3740
3741        struct GracefulGear {
3742            graceful_completed: AtomicBool,
3743            deadline_fired: AtomicBool,
3744        }
3745
3746        #[async_trait::async_trait]
3747        impl Gear for GracefulGear {
3748            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3749                Ok(())
3750            }
3751        }
3752
3753        #[async_trait::async_trait]
3754        impl RunnableCapability for GracefulGear {
3755            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3756                Ok(())
3757            }
3758            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3759                // Simulate graceful shutdown that completes quickly (10ms)
3760                tokio::select! {
3761                    () = tokio::time::sleep(Duration::from_millis(10)) => {
3762                        self.graceful_completed.store(true, Ordering::SeqCst);
3763                    }
3764                    () = deadline_token.cancelled() => {
3765                        self.deadline_fired.store(true, Ordering::SeqCst);
3766                    }
3767                }
3768                Ok(())
3769            }
3770        }
3771
3772        let gear = Arc::new(GracefulGear {
3773            graceful_completed: AtomicBool::new(false),
3774            deadline_fired: AtomicBool::new(false),
3775        });
3776
3777        let mut builder = RegistryBuilder::default();
3778        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3779        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3780
3781        let registry = builder.build_topo_sorted().unwrap();
3782        let client_hub = Arc::new(ClientHub::new());
3783        let cancel = CancellationToken::new();
3784        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3785
3786        // Use a long deadline (5s) - gear should complete gracefully before this
3787        let runtime = HostRuntime::new(
3788            registry,
3789            config_provider,
3790            DbOptions::None,
3791            client_hub,
3792            cancel.clone(),
3793            Uuid::new_v4(),
3794            None,
3795        )
3796        .with_shutdown_deadline(Duration::from_secs(5));
3797
3798        runtime.run_start_phase().await.unwrap();
3799        runtime.run_stop_phase().await.unwrap();
3800
3801        // Graceful shutdown should have completed
3802        assert!(
3803            gear.graceful_completed.load(Ordering::SeqCst),
3804            "graceful shutdown should complete"
3805        );
3806        // Deadline should NOT have fired (gear finished before deadline)
3807        assert!(
3808            !gear.deadline_fired.load(Ordering::SeqCst),
3809            "deadline should not fire when graceful shutdown completes quickly"
3810        );
3811    }
3812
3813    #[tokio::test]
3814    async fn test_stop_phase_deadline_fires_for_slow_gear() {
3815        use std::sync::atomic::AtomicBool;
3816        use std::time::Duration;
3817
3818        struct SlowGear {
3819            graceful_completed: AtomicBool,
3820            deadline_fired: AtomicBool,
3821        }
3822
3823        #[async_trait::async_trait]
3824        impl Gear for SlowGear {
3825            async fn init(&self, _ctx: &GearCtx) -> anyhow::Result<()> {
3826                Ok(())
3827            }
3828        }
3829
3830        #[async_trait::async_trait]
3831        impl RunnableCapability for SlowGear {
3832            async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
3833                Ok(())
3834            }
3835            async fn stop(&self, deadline_token: CancellationToken) -> anyhow::Result<()> {
3836                // Simulate slow graceful shutdown (would take 10s, but deadline is 100ms)
3837                tokio::select! {
3838                    () = tokio::time::sleep(Duration::from_secs(10)) => {
3839                        self.graceful_completed.store(true, Ordering::SeqCst);
3840                    }
3841                    () = deadline_token.cancelled() => {
3842                        self.deadline_fired.store(true, Ordering::SeqCst);
3843                    }
3844                }
3845                Ok(())
3846            }
3847        }
3848
3849        let gear = Arc::new(SlowGear {
3850            graceful_completed: AtomicBool::new(false),
3851            deadline_fired: AtomicBool::new(false),
3852        });
3853
3854        let mut builder = RegistryBuilder::default();
3855        builder.register_core_with_meta("test", &[], gear.clone() as Arc<dyn Gear>);
3856        builder.register_stateful_with_meta("test", gear.clone() as Arc<dyn RunnableCapability>);
3857
3858        let registry = builder.build_topo_sorted().unwrap();
3859        let client_hub = Arc::new(ClientHub::new());
3860        let cancel = CancellationToken::new();
3861        let config_provider: Arc<dyn ConfigProvider> = Arc::new(EmptyConfigProvider);
3862
3863        // Use a short deadline (100ms) - gear should be interrupted by deadline
3864        let runtime = HostRuntime::new(
3865            registry,
3866            config_provider,
3867            DbOptions::None,
3868            client_hub,
3869            cancel.clone(),
3870            Uuid::new_v4(),
3871            None,
3872        )
3873        .with_shutdown_deadline(Duration::from_millis(100));
3874
3875        runtime.run_start_phase().await.unwrap();
3876        runtime.run_stop_phase().await.unwrap();
3877
3878        // Graceful shutdown should NOT have completed (deadline fired first)
3879        assert!(
3880            !gear.graceful_completed.load(Ordering::SeqCst),
3881            "graceful shutdown should not complete when deadline fires first"
3882        );
3883        // Deadline should have fired
3884        assert!(
3885            gear.deadline_fired.load(Ordering::SeqCst),
3886            "deadline should fire for slow gears"
3887        );
3888    }
3889}
3890
3891#[cfg(test)]
3892#[cfg_attr(coverage_nightly, coverage(off))]
3893#[path = "host_runtime_preparation_tests.rs"]
3894mod host_runtime_preparation_tests;
3895
3896#[cfg(test)]
3897#[cfg_attr(coverage_nightly, coverage(off))]
3898#[path = "host_runtime_rest_bootstrap_tests.rs"]
3899mod host_runtime_rest_bootstrap_tests;