Skip to main content

ic_testkit/pic/
startup.rs

1use std::{
2    fmt::Write as _,
3    fs::{self, File, OpenOptions},
4    future::Future as _,
5    io::{self, Read as _},
6    path::{Path, PathBuf},
7    process::{Command, ExitStatus, Stdio},
8    sync::mpsc::{self, RecvTimeoutError},
9    thread,
10    time::{Duration, Instant},
11};
12
13#[cfg(unix)]
14use std::os::unix::fs::OpenOptionsExt as _;
15
16use ic_host_fs::{directory::create_unique_directory, owned_directory::OwnedDirectory};
17use ic_host_process::child::{CleanupError, CleanupPolicy, OwnedChild};
18use ic_platform::pocket_ic::{PocketIc, PocketIcBuilder};
19
20use super::transport;
21
22const STARTUP_POLL_INTERVAL: Duration = Duration::from_millis(20);
23const SERVER_OUTPUT_LIMIT: usize = 16 * 1024;
24// PocketIC publishes a decimal u16 and a newline. Leave whitespace room
25// without allowing readiness polling to read an arbitrary-size file.
26const SERVER_PORT_FILE_LIMIT: usize = 64;
27
28/// Explicit bounded source and policy for one `PocketIC` startup.
29///
30/// Spawn-only settings cannot be attached to a borrowed connection. Callers own
31/// binary admission, output retention and namespace custody.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub enum PocketIcStartupConfig {
34    /// Spawn and own one exact server executable.
35    Spawn {
36        /// Caller-selected, already prepared server binary.
37        server_binary: PathBuf,
38        /// Complete startup deadline; must be positive.
39        timeout: Duration,
40        /// Optional hard lifetime, in whole seconds; `None` disables it.
41        server_hard_ttl: Option<Duration>,
42        /// Optional operation-idle lifetime; `None` uses `PocketIC`'s default.
43        server_idle_ttl: Option<Duration>,
44        /// New caller-owned stdout/stderr files, or temporary output when absent.
45        /// Existing entries are refused. Created files survive failure and teardown.
46        server_output_files: Option<(PathBuf, PathBuf)>,
47    },
48    /// Borrow an existing server without claiming its process lifetime.
49    Connect {
50        /// Existing server URL, admitted by the upstream builder.
51        server_url: String,
52        /// Complete startup deadline; must be positive.
53        timeout: Duration,
54    },
55}
56
57/// Caller-owned `PocketIC` server process with bounded startup and output capture.
58///
59/// Dropping the handle terminates and waits for the managed child. On Unix,
60/// teardown also terminates descendants remaining in its owned process group.
61/// Callers may create several instances through [`Self::url`] and
62/// [`PocketIcStartupConfig::Connect`] while retaining explicit server ownership.
63/// The handle is process-local and does not coordinate ownership across Cargo
64/// or test-runner processes; use an externally owned server with bounded
65/// connect mode for that topology.
66/// The handle owns no binary discovery, download, cache, or compatibility policy.
67pub struct PocketIcManagedServer {
68    server: ManagedServer,
69    url: String,
70}
71
72/// An upstream instance together with the server owned by its construction.
73///
74/// Fields are ordered so a synchronous [`PocketIc`] is deleted before the server
75/// is terminated. Connect mode borrows the caller's server and returns `None`.
76/// Native `PocketIC` operations remain available through [`Self::instance`].
77/// [`Self::into_parts`] explicitly transfers teardown ordering to the caller.
78///
79/// `PocketIC` 16 synchronous deletion has no request deadline and can block drop.
80/// Its nonblocking instance has no automatic deletion: call
81/// [`Self::into_parts`], then `instance.drop().await` while retaining `server`,
82/// when deletion matters, especially with a borrowed server. Dropping an owned
83/// server stops all its instances.
84///
85/// Field projection cannot silently detach the client from its server:
86/// ```compile_fail
87/// use ic_testkit::pic::PocketIcInstance;
88/// fn detach<T>(owned: PocketIcInstance<T>) -> T {
89///     owned.instance
90/// }
91/// ```
92/// Nor can a client borrow outlive a temporary owner:
93/// ```compile_fail
94/// use ic_testkit::pic::PocketIcInstance;
95/// let client = PocketIcInstance::from_borrowed_server(String::new()).instance();
96/// assert!(client.is_empty());
97/// ```
98#[must_use]
99pub struct PocketIcInstance<T> {
100    instance: T,
101    server: Option<PocketIcManagedServer>,
102}
103
104impl<T> PocketIcInstance<T> {
105    /// Retain an existing client whose server lifetime is owned elsewhere.
106    ///
107    /// This creates no server or instance and claims no server process authority.
108    /// The client retains its upstream deletion behavior; its external server
109    /// must outlive it. Use a startup configuration for a managed server owner.
110    pub const fn from_borrowed_server(instance: T) -> Self {
111        Self {
112            instance,
113            server: None,
114        }
115    }
116
117    /// Borrow the client while retaining this record's managed-server ownership.
118    #[must_use]
119    pub const fn instance(&self) -> &T {
120        &self.instance
121    }
122
123    /// Mutably borrow the client while retaining managed-server ownership.
124    /// Supports client setup such as `PocketIc::make_live` without splitting the
125    /// owner. Replacing the client transfers responsibility for the old client's
126    /// server lifetime to the caller, just as with [`Self::into_parts`].
127    ///
128    /// The borrow cannot outlive the owner:
129    /// ```compile_fail
130    /// use ic_testkit::pic::PocketIcInstance;
131    /// let client = PocketIcInstance::from_borrowed_server(String::new()).instance_mut();
132    /// client.push_str("gateway");
133    /// ```
134    pub const fn instance_mut(&mut self) -> &mut T {
135        &mut self.instance
136    }
137
138    /// Borrow the exact managed server, or `None` for an externally owned server.
139    #[must_use]
140    pub const fn server(&self) -> Option<&PocketIcManagedServer> {
141        self.server.as_ref()
142    }
143
144    /// Transfer the client and optional server, without deleting or stopping either.
145    ///
146    /// The caller must retain the server until client deletion is complete. For
147    /// a nonblocking client, explicitly await `instance.drop()` before dropping
148    /// the returned server. No implicit asynchronous or blocking cleanup is added.
149    #[must_use]
150    pub fn into_parts(self) -> (T, Option<PocketIcManagedServer>) {
151        (self.instance, self.server)
152    }
153}
154
155/// Bounded lossy UTF-8 output captured from a managed `PocketIC` server.
156///
157/// Each stream retains at most the first 16 KiB. A textual suffix reports the
158/// number of omitted bytes when truncation occurred. Unreadable streams and
159/// paths replaced with non-regular files are omitted.
160#[derive(Clone, Debug, Default, Eq, PartialEq)]
161pub struct PocketIcManagedServerOutput {
162    stdout: String,
163    stderr: String,
164}
165
166/// Original startup failure, bounded server output and typed cleanup failures.
167///
168/// Match [`Self::failure`] to classify the original cause. Cleanup diagnostics
169/// never replace it, and command/server failures retain separate ownership.
170/// Output is an inert bounded snapshot; it grants no process authority.
171#[derive(Debug)]
172pub struct PocketIcStartupError {
173    failure: Box<PocketIcStartupFailure>,
174    output: PocketIcManagedServerOutput,
175    command_cleanup: Option<Box<CleanupError>>,
176    server_cleanup: Option<Box<CleanupError>>,
177}
178
179impl PocketIcStartupError {
180    fn new(failure: PocketIcStartupFailure) -> Self {
181        Self {
182            failure: Box::new(failure),
183            output: PocketIcManagedServerOutput::default(),
184            command_cleanup: None,
185            server_cleanup: None,
186        }
187    }
188
189    /// Original cause, unaffected by subsequent cleanup failure.
190    #[must_use]
191    pub fn failure(&self) -> &PocketIcStartupFailure {
192        &self.failure
193    }
194
195    /// Bounded output from the server owned by this operation, if any.
196    #[must_use]
197    pub const fn output(&self) -> &PocketIcManagedServerOutput {
198        &self.output
199    }
200
201    /// Failure cleaning the command's owned process group/direct child.
202    #[must_use]
203    pub fn command_cleanup(&self) -> Option<&CleanupError> {
204        self.command_cleanup.as_deref()
205    }
206
207    /// Failure cleaning the managed server's owned process group/direct child.
208    #[must_use]
209    pub fn server_cleanup(&self) -> Option<&CleanupError> {
210        self.server_cleanup.as_deref()
211    }
212
213    fn with_cleanup(
214        mut self,
215        command: Option<CleanupError>,
216        server: Option<(PocketIcManagedServerOutput, Option<CleanupError>)>,
217    ) -> Self {
218        self.command_cleanup = command.map(Box::new);
219        if let Some((output, cleanup)) = server {
220            self.output = output;
221            self.server_cleanup = cleanup.map(Box::new);
222        }
223        self
224    }
225}
226
227/// Original failure, independent of output capture and cleanup outcomes.
228#[non_exhaustive]
229#[derive(Debug, thiserror::Error)]
230pub enum PocketIcStartupFailure {
231    /// Neither the shared server URL nor an explicit executable was configured.
232    #[error(
233        "configure IC_TESTKIT_POCKET_IC_URL or POCKET_IC_BIN; prepare a verified binary with make install-server"
234    )]
235    NotConfigured,
236    /// A selected environment value was empty or was not valid Unicode.
237    #[error("invalid selected environment value: {variable}")]
238    InvalidEnvironment {
239        /// Selected environment variable name.
240        variable: &'static str,
241    },
242    /// The bounded version probe failed, including nonzero exit or timeout.
243    #[error("PocketIC version probe failed: {source}")]
244    ServerVersionProbe {
245        /// Underlying operation failure.
246        source: ic_host_process::tool::ToolError,
247    },
248    /// The selected executable does not report the qualified server identity.
249    #[error("PocketIC version mismatch: expected {expected:?}, observed {:?}", String::from_utf8_lossy(.observed))]
250    ServerVersionMismatch {
251        /// Required server identity.
252        expected: String,
253        /// Captured version-probe output.
254        observed: Vec<u8>,
255    },
256    /// Command execution failed.
257    #[error("command {} failed: {source}", .program.display())]
258    CommandRun {
259        /// Selected command executable.
260        program: PathBuf,
261        /// Underlying operation failure.
262        source: io::Error,
263    },
264    /// The caller supplied a zero timeout or unusable hard TTL.
265    #[error("{message}")]
266    InvalidConfiguration {
267        /// Configuration diagnostic.
268        message: String,
269    },
270    /// A caller-provided existing server URL could not be parsed.
271    #[error("invalid PocketIC server URL {server_url:?}: {message}")]
272    InvalidServerUrl {
273        /// Caller-provided server URL.
274        server_url: String,
275        /// Configuration diagnostic.
276        message: String,
277    },
278    /// Preparing or inspecting bounded startup files failed.
279    #[error("failed to {operation} at {}: {source}", .path.display())]
280    Io {
281        /// Failed filesystem operation.
282        operation: &'static str,
283        /// Affected filesystem path.
284        path: PathBuf,
285        /// Underlying operation failure.
286        source: io::Error,
287    },
288    /// The configured `PocketIC` server process could not be spawned.
289    #[error("failed to spawn PocketIC server {}: {source}", .server_binary.display())]
290    ServerSpawn {
291        /// Selected server executable.
292        server_binary: PathBuf,
293        /// Underlying operation failure.
294        source: io::Error,
295    },
296    /// The managed `PocketIC` server exited during construction or command execution.
297    #[error("PocketIC server {} exited with {status} after {elapsed:?}", .server_binary.display())]
298    ServerExited {
299        /// Selected server executable.
300        server_binary: PathBuf,
301        /// Observed server exit status.
302        status: ExitStatus,
303        /// Time spent before the server exited.
304        elapsed: Duration,
305    },
306    /// The managed server did not publish a usable port before the deadline.
307    #[error("PocketIC server {} was not ready within {timeout:?}", .server_binary.display())]
308    ReadinessTimeout {
309        /// Selected server executable.
310        server_binary: PathBuf,
311        /// Caller-selected deadline budget.
312        timeout: Duration,
313    },
314    /// The managed server published an invalid or oversized port-file value.
315    #[error("PocketIC server {} published invalid port {value:?}", .server_binary.display())]
316    InvalidServerPort {
317        /// Selected server executable.
318        server_binary: PathBuf,
319        /// Rejected port-file contents.
320        value: String,
321    },
322    /// `PocketIC` instance creation did not finish before the startup deadline.
323    #[error("PocketIC instance creation exceeded {timeout:?}")]
324    InstanceCreationTimeout {
325        /// Caller-selected deadline budget.
326        timeout: Duration,
327    },
328    /// Spawning the bounded builder worker failed.
329    #[error("failed to spawn PocketIC builder worker: {source}")]
330    BuilderThreadSpawn {
331        /// Underlying operation failure.
332        source: io::Error,
333    },
334    /// Upstream `PocketIC` construction panicked before returning an instance.
335    #[error("PocketIC startup panicked: {source}")]
336    BuilderPanicked {
337        /// Underlying operation failure.
338        source: super::PocketIcOperationError,
339    },
340    /// The bounded builder worker ended without returning a result.
341    #[error("PocketIC builder worker disconnected without a result")]
342    BuilderDisconnected,
343    /// The command completed, but the owned server could not be cleaned up.
344    #[error("PocketIC server cleanup failed after command exited with {command_status}")]
345    ServerCleanup {
346        /// Exit status of the completed command.
347        command_status: ExitStatus,
348    },
349}
350
351impl PocketIcStartupConfig {
352    /// Select the shared environment contract without discovery or downloads.
353    ///
354    /// `IC_TESTKIT_POCKET_IC_URL` takes precedence over `POCKET_IC_BIN`. An
355    /// explicitly empty or invalid selected value fails rather than falling
356    /// back. URL mode never launches a version probe or claims server ownership.
357    /// Binary mode resolves the explicit path and checks `--version` against
358    /// Testkit's supported protocol range using the shared bounded capture
359    /// engine. This is version qualification, not executable-byte admission;
360    /// prepare and verify the binary with `ic-testkit-server setup` / `check`.
361    /// The probe has its own `timeout`; subsequent startup has the same budget.
362    ///
363    /// # Errors
364    /// Rejects missing or invalid configuration and failed or incompatible version probes.
365    pub fn from_env(timeout: Duration) -> Result<Self, PocketIcStartupError> {
366        Self::from_environment(timeout, |name| std::env::var_os(name))
367    }
368
369    fn from_environment(
370        timeout: Duration,
371        mut variable: impl FnMut(&str) -> Option<std::ffi::OsString>,
372    ) -> Result<Self, PocketIcStartupError> {
373        if let Some(value) = variable("IC_TESTKIT_POCKET_IC_URL") {
374            let server_url = value
375                .into_string()
376                .ok()
377                .filter(|value| !value.is_empty())
378                .ok_or_else(|| {
379                    PocketIcStartupError::new(PocketIcStartupFailure::InvalidEnvironment {
380                        variable: "IC_TESTKIT_POCKET_IC_URL",
381                    })
382                })?;
383            let config = Self::Connect {
384                server_url: (&server_url).into(),
385                timeout,
386            };
387            config.validate()?;
388            let _ = configured_builder(PocketIcBuilder::new(), &server_url)?;
389            return Ok(config);
390        }
391        let value = variable("POCKET_IC_BIN")
392            .ok_or_else(|| PocketIcStartupError::new(PocketIcStartupFailure::NotConfigured))?;
393        if value.is_empty() {
394            return Err(PocketIcStartupError::new(
395                PocketIcStartupFailure::InvalidEnvironment {
396                    variable: "POCKET_IC_BIN",
397                },
398            ));
399        }
400        let path = PathBuf::from(value);
401        let binary = fs::canonicalize(&path).map_err(|source| {
402            PocketIcStartupError::new(PocketIcStartupFailure::Io {
403                operation: "resolve configured PocketIC executable",
404                path,
405                source,
406            })
407        })?;
408        let config = Self::Spawn {
409            server_binary: (&binary).into(),
410            timeout,
411            server_hard_ttl: None,
412            server_idle_ttl: None,
413            server_output_files: None,
414        };
415        config.validate()?;
416        let evidence = ic_host_process::tool::capture_group_command(
417            Command::new(&binary).arg("--version"),
418            ic_host_process::tool::OutputLimits {
419                stdout: ic_host_process::tool::OutputLimit::Terminate(SERVER_OUTPUT_LIMIT),
420                stderr: ic_host_process::tool::OutputLimit::Terminate(SERVER_OUTPUT_LIMIT),
421                timeout: Some(timeout),
422            },
423        )
424        .and_then(ic_host_process::tool::CompletedExecution::require_success)
425        .map_err(|source| {
426            PocketIcStartupError::new(PocketIcStartupFailure::ServerVersionProbe { source })
427        })?;
428        let expected = super::server::expected_server_version();
429        if !super::supports_pocket_ic_server(&evidence.stdout) {
430            return Err(PocketIcStartupError::new(
431                PocketIcStartupFailure::ServerVersionMismatch {
432                    expected,
433                    observed: evidence.stdout,
434                },
435            ));
436        }
437        Ok(config)
438    }
439
440    /// Complete startup deadline for either source.
441    #[must_use]
442    pub const fn timeout(&self) -> Duration {
443        match self {
444            Self::Spawn { timeout, .. } | Self::Connect { timeout, .. } => *timeout,
445        }
446    }
447
448    /// Construct a synchronous instance and retain its exact managed server.
449    ///
450    /// One deadline covers server readiness and instance creation. Topology,
451    /// state paths and request policy remain on the caller's builder. Spawn mode
452    /// terminates the server on failure and retains it on success; connect mode
453    /// never claims the external server. See [`PocketIcInstance`] for drop limits.
454    ///
455    /// ```no_run
456    /// use ic_platform::pocket_ic::PocketIcBuilder;
457    /// use ic_testkit::pic::PocketIcStartupConfig;
458    /// use std::{path::Path, time::Duration};
459    /// # fn run(binary: &Path) -> Result<(), ic_testkit::pic::PocketIcStartupError> {
460    /// let owned = PocketIcStartupConfig::Spawn { server_binary: binary.into(), timeout: Duration::from_secs(60), server_hard_ttl: None, server_idle_ttl: None, server_output_files: None }
461    ///     .build_instance(PocketIcBuilder::new().with_application_subnet())?;
462    /// let canister = owned.instance().create_canister();
463    /// assert!(owned.instance().canister_exists(canister));
464    /// // Drop deletes the instance, then terminates and reaps the owned server.
465    /// # Ok(())
466    /// # }
467    /// ```
468    ///
469    /// # Errors
470    /// Returns configuration, startup, deadline or instance-creation failures with cleanup evidence.
471    pub fn build_instance(
472        self,
473        builder: PocketIcBuilder,
474    ) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
475        let startup = StartupDeadline::new(&self)?;
476        let (server, url) = match self {
477            Self::Connect { server_url, .. } => (None, server_url),
478            spawn @ Self::Spawn { .. } => {
479                let (server, url) = spawn.spawn_server(startup.started)?.wait_ready(&startup)?;
480                (Some(server), url)
481            }
482        };
483        build_bounded(builder, &url, &startup, server)
484    }
485
486    /// Construct an upstream nonblocking instance on the caller's Tokio runtime.
487    ///
488    /// Uses the same deadline, readiness checks, typed panic/exit failures and
489    /// bounded output as [`Self::build_instance`], without running the synchronous
490    /// instance constructor. Requires a Tokio runtime with its time driver enabled.
491    /// Readiness and instance waits yield; process spawning and small file reads
492    /// remain synchronous, as does exact owned-child cleanup. The deadline cannot
493    /// preempt synchronous work inside an upstream future poll (such as copying
494    /// a read-only state directory); it is enforced when that poll returns.
495    ///
496    /// Dropping the future cancels local construction and terminates/reaps its
497    /// owned server, including during readiness. Cancellation has no returned error;
498    /// select output files to retain diagnostics. A borrowed server is untouched.
499    /// If a borrowed server created an instance before timeout or a lost reply, local
500    /// cancellation cannot identify or delete that instance; the caller owns this
501    /// reconciliation. The deadline covers construction, not subsequent deletion.
502    ///
503    /// ```no_run
504    /// use ic_platform::pocket_ic::PocketIcBuilder;
505    /// use ic_testkit::pic::PocketIcStartupConfig;
506    /// use std::{path::Path, time::Duration};
507    /// # async fn run(binary: &Path) -> Result<(), ic_testkit::pic::PocketIcStartupError> {
508    /// let owned = PocketIcStartupConfig::Spawn { server_binary: binary.into(), timeout: Duration::from_secs(60), server_hard_ttl: None, server_idle_ttl: None, server_output_files: None }
509    ///     .build_instance_async(PocketIcBuilder::new().with_application_subnet()).await?;
510    /// let canister = owned.instance().create_canister().await;
511    /// assert!(owned.instance().canister_exists(canister).await);
512    /// let (instance, server) = owned.into_parts();
513    /// instance.drop().await;
514    /// drop(server);
515    /// # Ok(())
516    /// # }
517    /// ```
518    ///
519    /// # Errors
520    /// Returns configuration, startup, deadline or instance-creation failures with cleanup evidence.
521    pub async fn build_instance_async(
522        self,
523        builder: PocketIcBuilder,
524    ) -> Result<PocketIcInstance<ic_platform::pocket_ic::nonblocking::PocketIc>, PocketIcStartupError>
525    {
526        let startup = StartupDeadline::new(&self)?;
527        let (server, server_url) = match self {
528            Self::Connect { server_url, .. } => (None, server_url),
529            spawn @ Self::Spawn { .. } => {
530                let mut server = spawn.spawn_server(startup.started)?;
531                let server_url = loop {
532                    match server.poll_ready(&startup) {
533                        Ok(Some(url)) => break url,
534                        Ok(None) => {
535                            tokio::time::sleep(startup.wait_interval(Instant::now(), true)).await;
536                        }
537                        Err(error) => return Err(finalize_failure(error, None, Some(server))),
538                    }
539                };
540                (Some(server), server_url)
541            }
542        };
543        build_async_bounded(builder, &server_url, &startup, server).await
544    }
545
546    /// Start a caller-owned managed server without constructing an instance.
547    ///
548    /// This requires a configuration created by [`Self::Spawn`]. Readiness is
549    /// bounded by [`Self::timeout`]. No hard TTL is passed by default; an
550    /// explicit `server_hard_ttl` value is passed to the child.
551    /// `server_idle_ttl` independently selects the operation-idle
552    /// lifetime; otherwise `PocketIC` retains its own idle default.
553    /// Readiness requires a nonzero decimal port followed by a newline in a
554    /// regular UTF-8 file of at most 64 bytes; oversized files fail with bounded
555    /// diagnostics. Non-regular port files fail with [`PocketIcStartupFailure::Io`]
556    /// and [`io::ErrorKind::InvalidData`] without waiting for a FIFO writer.
557    /// The returned handle terminates the child on drop; use its URL with
558    /// [`Self::Connect`] to construct bounded instances.
559    ///
560    /// # Errors
561    /// Rejects invalid configuration and server startup or readiness failures.
562    pub fn start_managed_server(self) -> Result<PocketIcManagedServer, PocketIcStartupError> {
563        if matches!(self, Self::Connect { .. }) {
564            self.validate()?;
565            return Err(PocketIcStartupError::new(
566                PocketIcStartupFailure::InvalidConfiguration {
567                    message: "starting a managed PocketIC server requires a spawn configuration"
568                        .to_owned(),
569                },
570            ));
571        }
572        let startup = StartupDeadline::new(&self)?;
573        let (server, url) = self.spawn_server(startup.started)?.wait_ready(&startup)?;
574        Ok(PocketIcManagedServer { server, url })
575    }
576
577    // Only validated spawn configurations reach this projection. Keeping it here
578    // gives sync, async and server-only construction the same spawn settings.
579    fn spawn_server(self, started: Instant) -> Result<ManagedServer, PocketIcStartupError> {
580        let Self::Spawn {
581            server_binary,
582            server_hard_ttl,
583            server_idle_ttl,
584            server_output_files,
585            ..
586        } = self
587        else {
588            unreachable!("connect configurations do not spawn a server")
589        };
590        ManagedServer::spawn(
591            server_binary,
592            server_hard_ttl,
593            server_idle_ttl,
594            server_output_files,
595            started,
596        )
597    }
598
599    /// Run a command with `IC_TESTKIT_POCKET_IC_URL` set to this server.
600    ///
601    /// Spawn mode retains the managed server until command completion; connect
602    /// mode borrows the external server and never terminates it. The command's
603    /// IO and other environment selections remain caller-owned. Cancellation
604    /// is polled after bounded startup and every 20 ms while the command runs.
605    /// It returns an [`io::ErrorKind::Interrupted`] error after cleanup.
606    /// If the owned server exits while the command is pending, the command is
607    /// terminated and the server's status and bounded diagnostics are returned
608    /// as [`PocketIcStartupFailure::ServerExited`]. External servers are not monitored.
609    ///
610    /// On Unix the command starts in a new owned process group. Completion,
611    /// cancellation and observation failures terminate remaining group members
612    /// before reaping the leader, using the same lifecycle engine as managed
613    /// servers. This does not impose a command deadline or sandbox descendants
614    /// that deliberately leave the owned group. Other hosts own the direct child.
615    ///
616    /// # Errors
617    /// Returns startup, command execution, cancellation or server cleanup failures.
618    pub fn run_command(
619        self,
620        command: &mut Command,
621        mut cancelled: impl FnMut() -> bool,
622    ) -> Result<ExitStatus, PocketIcStartupError> {
623        self.validate()?;
624        let program = PathBuf::from(command.get_program());
625        let command_error = |source| {
626            PocketIcStartupError::new(PocketIcStartupFailure::CommandRun {
627                program: program.clone(),
628                source,
629            })
630        };
631        if cancelled() {
632            return Err(command_error(io::Error::from(io::ErrorKind::Interrupted)));
633        }
634        let (server, url) = match self {
635            Self::Connect { server_url, .. } => (None, server_url),
636            spawn @ Self::Spawn { .. } => {
637                let server = spawn.start_managed_server()?;
638                let url = server.url().to_owned();
639                (Some(server.server), url)
640            }
641        };
642        let mut server = server;
643        if cancelled() {
644            return Err(finalize_failure(
645                command_error(io::Error::from(io::ErrorKind::Interrupted)),
646                None,
647                server,
648            ));
649        }
650        command.env("IC_TESTKIT_POCKET_IC_URL", url);
651        let mut owned_child = match OwnedChild::spawn(command, CleanupPolicy::KillAndWait) {
652            Ok(child) => child,
653            Err(source) => {
654                return Err(finalize_failure(
655                    PocketIcStartupError::new(PocketIcStartupFailure::Io {
656                        operation: "spawn command with PocketIC server",
657                        path: PathBuf::from(command.get_program()),
658                        source,
659                    }),
660                    None,
661                    server,
662                ));
663            }
664        };
665        let result = loop {
666            if cancelled() {
667                break Err(command_error(io::Error::from(io::ErrorKind::Interrupted)));
668            }
669            match owned_child.try_wait() {
670                Ok(Some(status)) => break Ok(status),
671                Ok(None) => {
672                    if let Some(managed) = server.as_mut()
673                        && let Err(error) = managed.check_running()
674                    {
675                        break Err(error);
676                    }
677                    thread::sleep(STARTUP_POLL_INTERVAL);
678                }
679                Err(source) => break Err(command_error(source)),
680            }
681        };
682        match result {
683            Err(error) => Err(finalize_failure(error, Some(&mut owned_child), server)),
684            Ok(status) => {
685                if let Some(server) = server {
686                    let (output, cleanup) = server.terminate_and_capture();
687                    if let Some(cleanup) = cleanup {
688                        return Err(PocketIcStartupError::new(
689                            PocketIcStartupFailure::ServerCleanup {
690                                command_status: status,
691                            },
692                        )
693                        .with_cleanup(None, Some((output, Some(cleanup)))));
694                    }
695                }
696                Ok(status)
697            }
698        }
699    }
700
701    fn validate(&self) -> Result<(), PocketIcStartupError> {
702        if self.timeout().is_zero() {
703            return Err(PocketIcStartupError::new(
704                PocketIcStartupFailure::InvalidConfiguration {
705                    message: "PocketIC startup timeout must be greater than zero".to_owned(),
706                },
707            ));
708        }
709        if let Self::Spawn {
710            server_hard_ttl,
711            server_idle_ttl,
712            ..
713        } = self
714        {
715            for (ttl, message) in [
716                (
717                    server_hard_ttl,
718                    "PocketIC server hard TTL must be at least one second",
719                ),
720                (
721                    server_idle_ttl,
722                    "PocketIC server idle TTL must be at least one second",
723                ),
724            ] {
725                if ttl.is_some_and(|ttl| ttl.as_secs() == 0) {
726                    return Err(PocketIcStartupError::new(
727                        PocketIcStartupFailure::InvalidConfiguration {
728                            message: message.to_owned(),
729                        },
730                    ));
731                }
732            }
733        }
734        Ok(())
735    }
736}
737
738impl PocketIcManagedServer {
739    /// OS process ID of the owned server child, for caller-managed monitoring.
740    ///
741    /// This identifies the server process, not its descendants, and does not
742    /// establish that it is still running. The OS may reuse the ID after the
743    /// child exits and is reaped. Dropping this handle terminates and waits for
744    /// the child; retaining the ID does not retain server ownership.
745    #[must_use]
746    pub fn process_id(&self) -> u32 {
747        self.server.child.id()
748    }
749
750    /// Loopback URL published by the managed server.
751    #[must_use]
752    pub fn url(&self) -> &str {
753        &self.url
754    }
755
756    /// Current bounded stdout and stderr captured from the managed server.
757    ///
758    /// This reads at most the first 16 KiB from each retained output file,
759    /// renders it as lossy UTF-8, and adds an omitted-byte suffix when truncated.
760    /// The diagnostic read is bounded; files can grow while the server runs.
761    #[must_use]
762    pub fn output(&self) -> PocketIcManagedServerOutput {
763        self.server.files.capture()
764    }
765}
766
767impl PocketIcManagedServerOutput {
768    /// Bounded lossy UTF-8 standard output.
769    #[must_use]
770    pub fn stdout(&self) -> &str {
771        &self.stdout
772    }
773
774    /// Bounded lossy UTF-8 standard error.
775    #[must_use]
776    pub fn stderr(&self) -> &str {
777        &self.stderr
778    }
779}
780
781struct StartupDeadline {
782    started: Instant,
783    timeout: Duration,
784    deadline: Instant,
785}
786
787impl StartupDeadline {
788    fn new(config: &PocketIcStartupConfig) -> Result<Self, PocketIcStartupError> {
789        config.validate()?;
790        let started = Instant::now();
791        let timeout = config.timeout();
792        Ok(Self {
793            started,
794            timeout,
795            deadline: startup_deadline(started, timeout)?,
796        })
797    }
798
799    fn check_instance_deadline(
800        &self,
801        server: &mut Option<ManagedServer>,
802    ) -> Result<Instant, PocketIcStartupError> {
803        let now = Instant::now();
804        if now >= self.deadline {
805            return Err(finalize_failure(
806                PocketIcStartupError::new(PocketIcStartupFailure::InstanceCreationTimeout {
807                    timeout: self.timeout,
808                }),
809                None,
810                server.take(),
811            ));
812        }
813        Ok(now)
814    }
815
816    fn wait_interval(&self, now: Instant, monitor_server: bool) -> Duration {
817        let remaining = self.deadline.saturating_duration_since(now);
818        if monitor_server {
819            remaining.min(STARTUP_POLL_INTERVAL)
820        } else {
821            remaining
822        }
823    }
824
825    fn admit_instance<T>(
826        &self,
827        instance: T,
828        server_url: &str,
829        server: &mut Option<ManagedServer>,
830    ) -> Result<PocketIcInstance<T>, PocketIcStartupError> {
831        self.check_instance_deadline(server)?;
832        check_server(server)?;
833        Ok(PocketIcInstance {
834            instance,
835            server: server.take().map(|server| PocketIcManagedServer {
836                server,
837                url: server_url.to_owned(),
838            }),
839        })
840    }
841}
842
843fn startup_deadline(started: Instant, timeout: Duration) -> Result<Instant, PocketIcStartupError> {
844    started.checked_add(timeout).ok_or_else(|| {
845        PocketIcStartupError::new(PocketIcStartupFailure::InvalidConfiguration {
846            message: "PocketIC startup timeout exceeds the platform clock range".to_owned(),
847        })
848    })
849}
850
851fn build_bounded(
852    builder: PocketIcBuilder,
853    server_url: &str,
854    startup: &StartupDeadline,
855    mut server: Option<ManagedServer>,
856) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
857    let builder = configured_builder(builder, server_url)
858        .map_err(|error| finalize_failure(error, None, server.take()))?;
859    let (sender, receiver) = mpsc::sync_channel(1);
860    if let Err(source) = thread::Builder::new()
861        .name("ic-testkit-pocket-ic-startup".to_owned())
862        .spawn(move || {
863            let result = transport::capture_operation(|| builder.build());
864            let _ = sender.send(result);
865        })
866    {
867        return Err(finalize_failure(
868            PocketIcStartupError::new(PocketIcStartupFailure::BuilderThreadSpawn { source }),
869            None,
870            server,
871        ));
872    }
873    await_builder(receiver, server_url, startup, &mut server)
874}
875
876#[expect(
877    clippy::needless_pass_by_value,
878    reason = "consume the receiver so failed startup disconnects late builders"
879)]
880fn await_builder(
881    receiver: mpsc::Receiver<Result<PocketIc, super::PocketIcOperationError>>,
882    server_url: &str,
883    startup: &StartupDeadline,
884    server: &mut Option<ManagedServer>,
885) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
886    loop {
887        let now = startup.check_instance_deadline(server)?;
888        let wait = startup.wait_interval(now, server.is_some());
889        match receiver.recv_timeout(wait) {
890            Ok(Ok(pocket_ic)) => {
891                return startup.admit_instance(pocket_ic, server_url, server);
892            }
893            Ok(Err(source)) => {
894                return Err(finalize_failure(
895                    PocketIcStartupError::new(PocketIcStartupFailure::BuilderPanicked { source }),
896                    None,
897                    server.take(),
898                ));
899            }
900            Err(RecvTimeoutError::Disconnected) => {
901                return Err(finalize_failure(
902                    PocketIcStartupError::new(PocketIcStartupFailure::BuilderDisconnected),
903                    None,
904                    server.take(),
905                ));
906            }
907            Err(RecvTimeoutError::Timeout) => {
908                check_server(server)?;
909            }
910        }
911    }
912}
913
914fn configured_builder(
915    builder: PocketIcBuilder,
916    server_url: &str,
917) -> Result<PocketIcBuilder, PocketIcStartupError> {
918    server_url
919        .parse()
920        .map(|url| builder.with_server_url(url))
921        .map_err(|error| {
922            PocketIcStartupError::new(PocketIcStartupFailure::InvalidServerUrl {
923                server_url: server_url.to_owned(),
924                message: error.to_string(),
925            })
926        })
927}
928
929fn check_server(server: &mut Option<ManagedServer>) -> Result<(), PocketIcStartupError> {
930    if let Some(managed) = server.as_mut()
931        && let Err(error) = managed.check_running()
932    {
933        return Err(finalize_failure(error, None, server.take()));
934    }
935    Ok(())
936}
937
938async fn build_async_bounded(
939    builder: PocketIcBuilder,
940    server_url: &str,
941    startup: &StartupDeadline,
942    mut server: Option<ManagedServer>,
943) -> Result<PocketIcInstance<ic_platform::pocket_ic::nonblocking::PocketIc>, PocketIcStartupError> {
944    let builder = configured_builder(builder, server_url)
945        .map_err(|error| finalize_failure(error, None, server.take()))?;
946    let mut construction = std::pin::pin!(builder.build_async());
947    let mut construction = std::pin::pin!(std::future::poll_fn(|context| {
948        match transport::capture_operation(|| construction.as_mut().poll(context)) {
949            Ok(poll) => poll.map(Ok),
950            Err(source) => std::task::Poll::Ready(Err(PocketIcStartupError::new(
951                PocketIcStartupFailure::BuilderPanicked { source },
952            ))),
953        }
954    }));
955    // Drop this local before the pending upstream future on cancellation.
956    let mut server = server;
957    loop {
958        let now = startup.check_instance_deadline(&mut server)?;
959        check_server(&mut server)?;
960        let next_check = now + startup.wait_interval(now, server.is_some());
961        match tokio::time::timeout_at(next_check.into(), construction.as_mut()).await {
962            Ok(Ok(instance)) => {
963                return startup.admit_instance(instance, server_url, &mut server);
964            }
965            Ok(Err(error)) => return Err(finalize_failure(error, None, server)),
966            Err(_) => {}
967        }
968    }
969}
970
971/// Finalize an owned operation once, preserving the primary failure.
972fn finalize_failure(
973    error: PocketIcStartupError,
974    command: Option<&mut OwnedChild>,
975    server: Option<ManagedServer>,
976) -> PocketIcStartupError {
977    error.with_cleanup(
978        command.and_then(|child| child.terminate().err()),
979        server.map(ManagedServer::terminate_and_capture),
980    )
981}
982
983struct ManagedServer {
984    child: OwnedChild,
985    binary: PathBuf,
986    files: StartupFiles,
987    started: Instant,
988}
989
990enum PortFileState {
991    Pending,
992    Ready(u16),
993    Invalid(String),
994}
995
996impl ManagedServer {
997    fn wait_ready(
998        mut self,
999        startup: &StartupDeadline,
1000    ) -> Result<(Self, String), PocketIcStartupError> {
1001        loop {
1002            match self.poll_ready(startup) {
1003                Ok(Some(url)) => return Ok((self, url)),
1004                Ok(None) => thread::sleep(startup.wait_interval(Instant::now(), true)),
1005                Err(error) => return Err(finalize_failure(error, None, Some(self))),
1006            }
1007        }
1008    }
1009
1010    fn spawn(
1011        binary: PathBuf,
1012        hard_ttl: Option<Duration>,
1013        idle_ttl: Option<Duration>,
1014        output_files: Option<(PathBuf, PathBuf)>,
1015        started: Instant,
1016    ) -> Result<Self, PocketIcStartupError> {
1017        let (files, stdout, stderr) = StartupFiles::create(output_files)?;
1018        let mut command = Command::new(&binary);
1019        if let Some(hard_ttl) = hard_ttl {
1020            command
1021                .arg("--hard-ttl")
1022                .arg(hard_ttl.as_secs().to_string());
1023        }
1024        if let Some(idle_ttl) = idle_ttl {
1025            command.arg("--ttl").arg(idle_ttl.as_secs().to_string());
1026        }
1027        command
1028            .arg("--port-file")
1029            .arg(&files.port)
1030            .stdout(Stdio::from(stdout))
1031            .stderr(Stdio::from(stderr));
1032        let child =
1033            OwnedChild::spawn(&mut command, CleanupPolicy::KillAndWait).map_err(|source| {
1034                PocketIcStartupError::new(PocketIcStartupFailure::ServerSpawn {
1035                    server_binary: binary.clone(),
1036                    source,
1037                })
1038            })?;
1039        Ok(Self {
1040            child,
1041            binary,
1042            files,
1043            started,
1044        })
1045    }
1046
1047    fn poll_ready(
1048        &mut self,
1049        startup: &StartupDeadline,
1050    ) -> Result<Option<String>, PocketIcStartupError> {
1051        self.check_running()?;
1052        if Instant::now() >= startup.deadline {
1053            return Err(PocketIcStartupError::new(
1054                PocketIcStartupFailure::ReadinessTimeout {
1055                    server_binary: self.binary.clone(),
1056                    timeout: startup.timeout,
1057                },
1058            ));
1059        }
1060        match self.files.read_port()? {
1061            PortFileState::Pending => Ok(None),
1062            PortFileState::Ready(port) => Ok(Some(format!("http://127.0.0.1:{port}/"))),
1063            PortFileState::Invalid(value) => Err(PocketIcStartupError::new(
1064                PocketIcStartupFailure::InvalidServerPort {
1065                    server_binary: self.binary.clone(),
1066                    value,
1067                },
1068            )),
1069        }
1070    }
1071
1072    fn check_running(&mut self) -> Result<(), PocketIcStartupError> {
1073        if let Some(status) = self.try_wait()? {
1074            return Err(self.exit_failure(status));
1075        }
1076        Ok(())
1077    }
1078
1079    fn try_wait(&mut self) -> Result<Option<ExitStatus>, PocketIcStartupError> {
1080        self.child.try_wait().map_err(|source| {
1081            PocketIcStartupError::new(PocketIcStartupFailure::Io {
1082                operation: "inspect PocketIC server child",
1083                path: self.binary.clone(),
1084                source,
1085            })
1086        })
1087    }
1088
1089    fn exit_failure(&self, status: ExitStatus) -> PocketIcStartupError {
1090        PocketIcStartupError::new(PocketIcStartupFailure::ServerExited {
1091            server_binary: self.binary.clone(),
1092            status,
1093            elapsed: self.started.elapsed(),
1094        })
1095    }
1096
1097    fn terminate_and_capture(self) -> (PocketIcManagedServerOutput, Option<CleanupError>) {
1098        let Self {
1099            mut child, files, ..
1100        } = self;
1101        let cleanup = child.terminate().err();
1102        // Finish the child's Drop cleanup before reading the final diagnostics.
1103        drop(child);
1104        (files.capture(), cleanup)
1105    }
1106}
1107
1108struct StartupFiles {
1109    #[cfg_attr(
1110        not(test),
1111        expect(
1112            dead_code,
1113            reason = "retains directory ownership until cleanup or drop"
1114        )
1115    )]
1116    directory: OwnedDirectory,
1117    port: PathBuf,
1118    stdout: PathBuf,
1119    stderr: PathBuf,
1120}
1121
1122impl StartupFiles {
1123    fn read_port(&self) -> Result<PortFileState, PocketIcStartupError> {
1124        let port_path = &self.port;
1125        let mut contents = String::new();
1126        match ic_host_fs::read::open_regular_file(port_path)
1127            .map_err(|error| match error {
1128                ic_host_artifacts::artifact::ArtifactError::Io(source) => source,
1129                error => io::Error::new(io::ErrorKind::InvalidData, error),
1130            })
1131            .and_then(|file| {
1132                file.take((SERVER_PORT_FILE_LIMIT + 1) as u64)
1133                    .read_to_string(&mut contents)
1134            }) {
1135            Ok(_) => {}
1136            Err(error) if error.kind() == io::ErrorKind::NotFound => {
1137                return Ok(PortFileState::Pending);
1138            }
1139            Err(source) => {
1140                return Err(PocketIcStartupError::new(PocketIcStartupFailure::Io {
1141                    operation: "read PocketIC server port file",
1142                    path: port_path.clone(),
1143                    source,
1144                }));
1145            }
1146        }
1147        if contents.len() > SERVER_PORT_FILE_LIMIT {
1148            return Ok(PortFileState::Invalid(format!(
1149                "{} (port file exceeds {SERVER_PORT_FILE_LIMIT} bytes)",
1150                contents.trim()
1151            )));
1152        }
1153        if !contents.contains('\n') {
1154            return Ok(PortFileState::Pending);
1155        }
1156        let value = contents.trim().to_owned();
1157        match value.parse::<u16>() {
1158            Ok(port) if port != 0 => Ok(PortFileState::Ready(port)),
1159            _ => Ok(PortFileState::Invalid(value)),
1160        }
1161    }
1162
1163    fn capture(&self) -> PocketIcManagedServerOutput {
1164        PocketIcManagedServerOutput {
1165            stdout: read_bounded_lossy(&self.stdout),
1166            stderr: read_bounded_lossy(&self.stderr),
1167        }
1168    }
1169
1170    fn create(
1171        output_files: Option<(PathBuf, PathBuf)>,
1172    ) -> Result<(Self, File, File), PocketIcStartupError> {
1173        let output_files = output_files
1174            .map(|(stdout, stderr)| {
1175                Ok::<_, PocketIcStartupError>((
1176                    std::path::absolute(&stdout)
1177                        .map_err(|source| startup_file_error("resolve", &stdout, source))?,
1178                    std::path::absolute(&stderr)
1179                        .map_err(|source| startup_file_error("resolve", &stderr, source))?,
1180                ))
1181            })
1182            .transpose()?;
1183        let directory = OwnedDirectory::new(
1184            create_unique_directory(
1185                &std::env::temp_dir(),
1186                "ic-testkit-pocket-ic-startup",
1187                0o700,
1188                None,
1189            )
1190            .map_err(|source| startup_file_error("create", &std::env::temp_dir(), source))?,
1191        );
1192        let base = directory.path();
1193        let (stdout_path, stderr_path) =
1194            output_files.unwrap_or_else(|| (base.join("stdout"), base.join("stderr")));
1195        let files = Self {
1196            port: base.join("port"),
1197            stdout: stdout_path,
1198            stderr: stderr_path,
1199            directory,
1200        };
1201        let stdout = create_new_file(&files.stdout)
1202            .map_err(|source| startup_file_error("create", &files.stdout, source))?;
1203        let stderr = create_new_file(&files.stderr)
1204            .map_err(|source| startup_file_error("create", &files.stderr, source))?;
1205        Ok((files, stdout, stderr))
1206    }
1207}
1208
1209fn create_new_file(path: &Path) -> io::Result<File> {
1210    let mut options = OpenOptions::new();
1211    options.write(true).create_new(true);
1212    #[cfg(unix)]
1213    options.mode(0o600);
1214    options.open(path)
1215}
1216
1217fn startup_file_error(
1218    operation: &'static str,
1219    path: &Path,
1220    source: io::Error,
1221) -> PocketIcStartupError {
1222    PocketIcStartupError::new(PocketIcStartupFailure::Io {
1223        operation,
1224        path: path.to_owned(),
1225        source,
1226    })
1227}
1228
1229fn read_bounded_lossy(path: &Path) -> String {
1230    let Ok((bytes, length)) = ic_host_fs::read::read_file_prefix(path, SERVER_OUTPUT_LIMIT) else {
1231        return String::new();
1232    };
1233    let mut output = String::from_utf8_lossy(&bytes).into_owned();
1234    let omitted = length.saturating_sub(bytes.len() as u64);
1235    if omitted > 0 {
1236        let _ = write!(output, "\n<truncated {omitted} bytes>");
1237    }
1238    output
1239}
1240
1241impl std::fmt::Display for PocketIcStartupError {
1242    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1243        std::fmt::Display::fmt(self.failure.as_ref(), formatter)?;
1244        if !self.output.stdout.is_empty() {
1245            write!(formatter, "; server stdout: {}", self.output.stdout)?;
1246        }
1247        if !self.output.stderr.is_empty() {
1248            write!(formatter, "; server stderr: {}", self.output.stderr)?;
1249        }
1250        for (owner, cleanup) in [
1251            ("command", self.command_cleanup()),
1252            ("server", self.server_cleanup()),
1253        ] {
1254            if let Some(error) = cleanup {
1255                write!(formatter, "; {owner} cleanup also failed: {error}")?;
1256            }
1257        }
1258        Ok(())
1259    }
1260}
1261
1262impl std::error::Error for PocketIcStartupError {
1263    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1264        std::error::Error::source(self.failure.as_ref())
1265    }
1266}
1267
1268#[cfg(test)]
1269mod tests {
1270    mod instances;
1271
1272    use std::{
1273        fs,
1274        path::PathBuf,
1275        time::{Duration, Instant},
1276    };
1277
1278    use super::{
1279        OwnedDirectory, PocketIcStartupConfig, PocketIcStartupError, PocketIcStartupFailure,
1280        StartupFiles, create_unique_directory,
1281    };
1282    use ic_platform::pocket_ic::PocketIcBuilder;
1283
1284    #[cfg(unix)]
1285    use ic_host_process::testing::write_executable_script;
1286    #[cfg(unix)]
1287    use std::{
1288        io::Write as _,
1289        os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _},
1290        process::Command,
1291        sync::mpsc,
1292    };
1293
1294    #[test]
1295    fn completed_instances_must_still_meet_the_startup_deadline() {
1296        let started = Instant::now();
1297        let startup = super::StartupDeadline {
1298            started,
1299            timeout: Duration::from_secs(60),
1300            deadline: started + Duration::from_secs(60),
1301        };
1302        let mut server = None;
1303        let instance = startup
1304            .admit_instance(7_u8, "http://localhost/", &mut server)
1305            .unwrap();
1306        assert_eq!(*instance.instance(), 7);
1307        assert!(server.is_none());
1308        let expired = super::StartupDeadline {
1309            deadline: started,
1310            ..startup
1311        };
1312        let error = expired
1313            .admit_instance(7_u8, "http://localhost/", &mut server)
1314            .err()
1315            .expect("completed instance after the deadline must refuse admission");
1316        assert!(
1317            matches!(error.failure(), PocketIcStartupFailure::InstanceCreationTimeout { timeout } if *timeout == Duration::from_secs(60))
1318        );
1319        assert!(server.is_none());
1320    }
1321
1322    #[test]
1323    fn original_failure_output_and_both_typed_cleanup_reports_survive_projection() {
1324        use std::error::Error as _;
1325        for failure in [
1326            PocketIcStartupFailure::ReadinessTimeout {
1327                server_binary: "server".into(),
1328                timeout: Duration::from_secs(1),
1329            },
1330            PocketIcStartupFailure::InstanceCreationTimeout {
1331                timeout: Duration::from_secs(1),
1332            },
1333            PocketIcStartupFailure::InvalidServerPort {
1334                server_binary: "server".into(),
1335                value: "invalid".into(),
1336            },
1337            PocketIcStartupFailure::BuilderPanicked {
1338                source: super::super::PocketIcOperationError::new("original-panic"),
1339            },
1340            PocketIcStartupFailure::BuilderDisconnected,
1341            PocketIcStartupFailure::BuilderThreadSpawn {
1342                source: std::io::Error::from_raw_os_error(9),
1343            },
1344            PocketIcStartupFailure::Io {
1345                operation: "original-io",
1346                path: "port".into(),
1347                source: std::io::Error::from_raw_os_error(9),
1348            },
1349        ] {
1350            let primary_text = failure.to_string();
1351            let output = super::PocketIcManagedServerOutput {
1352                stdout: "original-stdout".into(),
1353                stderr: "original-stderr".into(),
1354            };
1355            let command = super::CleanupError {
1356                status: None,
1357                group_error: None,
1358                term_error: Some(std::io::Error::from_raw_os_error(4)),
1359                kill_error: Some(std::io::Error::from_raw_os_error(5)),
1360                wait_error: None,
1361            };
1362            let server = super::CleanupError {
1363                status: None,
1364                group_error: Some(std::io::Error::from_raw_os_error(1)),
1365                term_error: None,
1366                kill_error: None,
1367                wait_error: Some(std::io::Error::from_raw_os_error(10)),
1368            };
1369            let error = PocketIcStartupError::new(failure)
1370                .with_cleanup(Some(command), Some((output, Some(server))));
1371            assert_eq!(error.failure().to_string(), primary_text);
1372            assert_eq!(error.output().stdout(), "original-stdout");
1373            assert_eq!(error.output().stderr(), "original-stderr");
1374            let command = error.command_cleanup().unwrap();
1375            let server = error.server_cleanup().unwrap();
1376            assert_eq!(command.kill_error.as_ref().unwrap().raw_os_error(), Some(5));
1377            assert_eq!(command.term_error.as_ref().unwrap().raw_os_error(), Some(4));
1378            assert_eq!(server.group_error.as_ref().unwrap().raw_os_error(), Some(1));
1379            assert_eq!(server.wait_error.as_ref().unwrap().raw_os_error(), Some(10));
1380            if matches!(
1381                error.failure(),
1382                PocketIcStartupFailure::Io { .. }
1383                    | PocketIcStartupFailure::BuilderThreadSpawn { .. }
1384            ) {
1385                assert_eq!(
1386                    error
1387                        .source()
1388                        .unwrap()
1389                        .downcast_ref::<std::io::Error>()
1390                        .unwrap()
1391                        .raw_os_error(),
1392                    Some(9)
1393                );
1394            }
1395            if let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() {
1396                assert_eq!(
1397                    error
1398                        .source()
1399                        .unwrap()
1400                        .downcast_ref::<super::super::PocketIcOperationError>(),
1401                    Some(source)
1402                );
1403            }
1404            let displayed = error.to_string();
1405            assert!(displayed.starts_with(&primary_text));
1406            for marker in [
1407                "original-stdout",
1408                "original-stderr",
1409                "command cleanup also failed",
1410                "server cleanup also failed",
1411            ] {
1412                assert!(displayed.contains(marker));
1413            }
1414        }
1415        let error = PocketIcStartupError::new(PocketIcStartupFailure::NotConfigured);
1416        assert_eq!(error.to_string(), error.failure().to_string());
1417        assert!(error.command_cleanup().is_none());
1418        assert!(error.server_cleanup().is_none());
1419    }
1420
1421    #[cfg(unix)]
1422    #[test]
1423    fn builder_failures_finalize_the_owned_server_and_keep_output() {
1424        for disconnected in [false, true] {
1425            let script = TestServerScript::new(
1426                "builder-failure",
1427                "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'builder-diagnostic' >&2\nprintf '34567\n' > \"$2\"\nexec sleep 30\n",
1428            );
1429            let managed = script
1430                .config(Duration::from_secs(2))
1431                .start_managed_server()
1432                .unwrap();
1433            let pid = managed.process_id();
1434            let directory = managed.server.files.directory.path().to_path_buf();
1435            let (sender, receiver) = mpsc::channel();
1436            if !disconnected {
1437                sender
1438                    .send(Err(super::super::PocketIcOperationError::new(
1439                        "original-builder-panic",
1440                    )))
1441                    .unwrap();
1442            }
1443            drop(sender);
1444            let error = super::await_builder(
1445                receiver,
1446                "http://127.0.0.1:34567/",
1447                &super::StartupDeadline {
1448                    started: Instant::now(),
1449                    deadline: Instant::now() + Duration::from_secs(2),
1450                    timeout: Duration::from_secs(2),
1451                },
1452                &mut Some(managed.server),
1453            )
1454            .err()
1455            .unwrap();
1456            assert!(matches!(
1457                (disconnected, error.failure()),
1458                (true, PocketIcStartupFailure::BuilderDisconnected)
1459                    | (false, PocketIcStartupFailure::BuilderPanicked { .. })
1460            ));
1461            assert_eq!(error.output().stderr(), "builder-diagnostic");
1462            assert!(error.server_cleanup().is_none());
1463            assert!(!directory.exists());
1464            assert_eq!(process_state(pid), None);
1465        }
1466    }
1467
1468    #[cfg(unix)]
1469    #[test]
1470    fn port_io_and_command_spawn_failures_finalize_the_owned_server() {
1471        for port_io in [true, false] {
1472            let port = if port_io {
1473                "mkfifo \"$2\""
1474            } else {
1475                "printf '34567\n' > \"$2\""
1476            };
1477            let script = TestServerScript::new(
1478                "owned-io-failure",
1479                &format!(
1480                    "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'original-server-diagnostic' >&2\n{port}\nexec sleep 30\n"
1481                ),
1482            );
1483            let config = script.config(Duration::from_secs(2));
1484            let error = if port_io {
1485                config.start_managed_server().err().unwrap()
1486            } else {
1487                config
1488                    .run_command(&mut Command::new("/missing/ic-testkit-command"), || false)
1489                    .unwrap_err()
1490            };
1491            let PocketIcStartupFailure::Io { source, .. } = error.failure() else {
1492                panic!("expected original IO failure: {error:?}");
1493            };
1494            assert_eq!(
1495                source.kind(),
1496                if port_io {
1497                    std::io::ErrorKind::InvalidData
1498                } else {
1499                    std::io::ErrorKind::NotFound
1500                }
1501            );
1502            assert_eq!(error.output().stderr(), "original-server-diagnostic");
1503            let mut lines = error.output().stdout().lines();
1504            let pid = lines.next().unwrap().parse().unwrap();
1505            let port = PathBuf::from(lines.next().unwrap());
1506            assert_eq!(process_state(pid), None);
1507            assert!(!port.parent().unwrap().exists());
1508            assert!(error.server_cleanup().is_none());
1509        }
1510    }
1511
1512    #[cfg(unix)]
1513    #[test]
1514    fn command_cancellation_before_startup_has_no_spawn_effects() {
1515        let error = PocketIcStartupConfig::Spawn {
1516            server_binary: ("/missing/server").into(),
1517            timeout: Duration::from_secs(1),
1518            server_hard_ttl: None,
1519            server_idle_ttl: None,
1520            server_output_files: None,
1521        }
1522        .run_command(&mut Command::new("/missing/command"), || true)
1523        .unwrap_err();
1524        assert!(
1525            matches!(error.failure(), PocketIcStartupFailure::CommandRun { source, .. } if source.kind() == std::io::ErrorKind::Interrupted)
1526        );
1527        assert_eq!(error.output().stdout(), "");
1528        assert_eq!(error.output().stderr(), "");
1529        assert!(error.command_cleanup().is_none());
1530        assert!(error.server_cleanup().is_none());
1531    }
1532
1533    #[cfg(unix)]
1534    #[test]
1535    fn cancellation_callback_panic_still_reaps_the_owned_command() {
1536        let script = TestServerScript::new(
1537            "cancel-panic",
1538            "#!/bin/sh\nprintf '%s' \"$$\" > \"$1\"\nexec sleep 30\n",
1539        );
1540        let pid_file = script.path().with_extension("pid");
1541        let result = std::panic::catch_unwind(|| {
1542            PocketIcStartupConfig::Connect {
1543                server_url: ("http://127.0.0.1:12345/").into(),
1544                timeout: Duration::from_secs(1),
1545            }
1546            .run_command(Command::new(script.path()).arg(&pid_file), || {
1547                assert!(
1548                    !fs::read_to_string(&pid_file).is_ok_and(|value| !value.is_empty()),
1549                    "caller cancellation failed"
1550                );
1551                false
1552            })
1553        });
1554        assert!(result.is_err());
1555        let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1556        assert!(process_state(pid).is_none_or(|state| state == 'Z'));
1557        fs::remove_file(pid_file).unwrap();
1558    }
1559
1560    #[cfg(unix)]
1561    #[test]
1562    fn environment_selection_prefers_urls_and_fails_closed() {
1563        use std::os::unix::ffi::OsStringExt as _;
1564
1565        let timeout = Duration::from_secs(1);
1566        let config = PocketIcStartupConfig::from_environment(timeout, |name| {
1567            Some(
1568                if name == "IC_TESTKIT_POCKET_IC_URL" {
1569                    "http://127.0.0.1:12345/"
1570                } else {
1571                    "/missing/server"
1572                }
1573                .into(),
1574            )
1575        })
1576        .unwrap();
1577        assert!(
1578            matches!(config, PocketIcStartupConfig::Connect { ref server_url, .. } if server_url == "http://127.0.0.1:12345/")
1579        );
1580        assert!(matches!(
1581            PocketIcStartupConfig::from_environment(timeout, |_| None)
1582                .as_ref()
1583                .map_err(PocketIcStartupError::failure),
1584            Err(PocketIcStartupFailure::NotConfigured)
1585        ));
1586        assert!(matches!(
1587            PocketIcStartupConfig::from_environment(timeout, |_| Some("".into()))
1588                .as_ref()
1589                .map_err(PocketIcStartupError::failure),
1590            Err(PocketIcStartupFailure::InvalidEnvironment {
1591                variable: "IC_TESTKIT_POCKET_IC_URL"
1592            })
1593        ));
1594        assert!(matches!(
1595            PocketIcStartupConfig::from_environment(timeout, |_| Some("bad URL".into()))
1596                .as_ref()
1597                .map_err(PocketIcStartupError::failure),
1598            Err(PocketIcStartupFailure::InvalidServerUrl { .. })
1599        ));
1600        assert!(matches!(
1601            PocketIcStartupConfig::from_environment(timeout, |_| Some(
1602                std::ffi::OsString::from_vec(vec![0xff])
1603            ))
1604            .as_ref()
1605            .map_err(PocketIcStartupError::failure),
1606            Err(PocketIcStartupFailure::InvalidEnvironment { .. })
1607        ));
1608    }
1609
1610    #[cfg(unix)]
1611    #[test]
1612    fn version_capture_cleans_wrapper_descendants_on_exit_and_timeout() {
1613        for timeout in [false, true] {
1614            let qualified = format!(
1615                "printf 'pocket-ic-server {}\\n'",
1616                crate::pic::POCKET_IC_SERVER_VERSION
1617            );
1618            let ending = if timeout { "wait" } else { &qualified };
1619            let script = TestServerScript::new(
1620                "version-group",
1621                &format!(
1622                    "#!/bin/sh\nsleep 30 >/dev/null 2>&1 &\nprintf '%s' \"$!\" > \"$0.pid\"\n{ending}\n"
1623                ),
1624            );
1625            let result = PocketIcStartupConfig::from_environment(Duration::from_secs(1), |name| {
1626                (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1627            });
1628            if timeout {
1629                assert!(matches!(
1630                    result.as_ref().map_err(PocketIcStartupError::failure),
1631                    Err(PocketIcStartupFailure::ServerVersionProbe { .. })
1632                ));
1633            } else {
1634                assert!(result.is_ok());
1635            }
1636            let pid_file = script.path().with_extension("pid");
1637            let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1638            let deadline = Instant::now() + Duration::from_secs(3);
1639            while process_state(pid).is_some_and(|state| state != 'Z') {
1640                assert!(
1641                    Instant::now() < deadline,
1642                    "version wrapper descendant remained alive"
1643                );
1644                std::thread::sleep(Duration::from_millis(20));
1645            }
1646            fs::remove_file(pid_file).unwrap();
1647        }
1648    }
1649
1650    #[cfg(unix)]
1651    #[test]
1652    fn owned_builder_panic_retains_server_output_and_reaps_child() {
1653        let script = TestServerScript::new(
1654            "builder-panic",
1655            "#!/bin/sh\nprintf '%s' \"$$\" > \"$0.pid\"\nprintf 'builder stdout'\nprintf 'builder stderr' >&2\nprintf '34567\\n' > \"$2\"\nexec sleep 30\n",
1656        );
1657        let error = script
1658            .config(Duration::from_secs(2))
1659            .build_instance(PocketIcBuilder::new())
1660            .err()
1661            .unwrap();
1662        let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() else {
1663            panic!("expected builder failure, got {error:?}");
1664        };
1665        assert_ne!(source.message(), "");
1666        assert_eq!(
1667            std::error::Error::source(&error)
1668                .unwrap()
1669                .downcast_ref::<super::super::PocketIcOperationError>(),
1670            Some(source)
1671        );
1672        assert_eq!(error.output().stdout(), "builder stdout");
1673        assert_eq!(error.output().stderr(), "builder stderr");
1674        assert!(error.server_cleanup().is_none());
1675        let pid_file = script.path().with_extension("pid");
1676        let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1677        assert_eq!(process_state(pid), None);
1678        fs::remove_file(pid_file).unwrap();
1679    }
1680
1681    #[cfg(unix)]
1682    #[test]
1683    fn environment_binary_selection_uses_bounded_shared_version_capture() {
1684        let qualified = format!(
1685            "printf 'pocket-ic-server {}\\n'",
1686            crate::pic::POCKET_IC_SERVER_VERSION
1687        );
1688        let failed = format!("{qualified}; exit 23");
1689        for (label, body, expected) in [
1690            ("qualified", qualified.as_str(), 0),
1691            ("compatible-16.0", "printf 'pocket-ic-server 16.0.0\\n'", 0),
1692            ("compatible-patch", "printf 'pocket-ic-server 16.0.1\\n'", 0),
1693            ("wrong-version", "printf 'pocket-ic-server 15.0.0\\n'", 1),
1694            ("future-major", "printf 'pocket-ic-server 17.0.0\\n'", 1),
1695            ("malformed-version", "printf 'pocket-ic-server 16.1\\n'", 1),
1696            ("failed-version", failed.as_str(), 2),
1697            ("invalid-utf8", "printf '\\377'", 1),
1698            ("version-timeout", "exec sleep 30", 2),
1699        ] {
1700            let script = TestServerScript::new(
1701                label,
1702                &format!("#!/bin/sh\n[ \"$1\" = --version ] || exit 99\n{body}\n"),
1703            );
1704            // A successful process launch needs scheduling headroom on loaded CI
1705            // hosts; only the deliberately stalled probe needs a short deadline.
1706            let timeout = if label == "version-timeout" {
1707                Duration::from_millis(200)
1708            } else {
1709                Duration::from_secs(5)
1710            };
1711            let result = PocketIcStartupConfig::from_environment(timeout, |name| {
1712                (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1713            });
1714            match (
1715                expected,
1716                result.as_ref().map_err(PocketIcStartupError::failure),
1717            ) {
1718                (0, Ok(config)) => {
1719                    let binary = script.path().canonicalize().unwrap();
1720                    assert!(
1721                        matches!(config, PocketIcStartupConfig::Spawn { server_binary, .. } if server_binary == &binary)
1722                    );
1723                }
1724                (1, Err(PocketIcStartupFailure::ServerVersionMismatch { .. }))
1725                | (2, Err(PocketIcStartupFailure::ServerVersionProbe { .. })) => {}
1726                (_, result) => panic!("unexpected {label} result: {result:?}"),
1727            }
1728        }
1729    }
1730
1731    #[cfg(unix)]
1732    fn process_state(pid: u32) -> Option<char> {
1733        ic_host_process::testing::process_state(pid).expect("inspect managed test process state")
1734    }
1735
1736    #[cfg(unix)]
1737    #[test]
1738    fn reading_large_sparse_server_output_is_bounded() {
1739        let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1740        let mut file = fs::File::create(&files.stdout).expect("create sparse log");
1741        file.write_all(b"server started\n").expect("write prefix");
1742        let size = 8_u64 * 1024 * 1024 * 1024;
1743        file.set_len(size).expect("extend sparse log");
1744        let output = super::read_bounded_lossy(&files.stdout);
1745        assert!(output.starts_with("server started\n"));
1746        assert!(output.ends_with(&format!(
1747            "<truncated {} bytes>",
1748            size - super::SERVER_OUTPUT_LIMIT as u64
1749        )));
1750        assert!(output.len() < super::SERVER_OUTPUT_LIMIT + 100);
1751    }
1752
1753    #[cfg(unix)]
1754    #[test]
1755    fn startup_readers_reject_fifos_without_waiting_for_a_writer() {
1756        let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1757        drop((stdout, stderr));
1758        fs::remove_file(&files.stdout).unwrap();
1759        fs::remove_file(&files.stderr).unwrap();
1760        assert!(
1761            Command::new("mkfifo")
1762                .args([&files.port, &files.stdout, &files.stderr])
1763                .status()
1764                .expect("create FIFO startup files")
1765                .success()
1766        );
1767        for path in [&files.port, &files.stdout, &files.stderr] {
1768            // A delayed writer bounds a blocked read and records whether the
1769            // reader needed it. Completion cancels the writer; with no reader,
1770            // a nonblocking open fails and is retried if the reader starts late.
1771            let fifo = path.clone();
1772            let (stop_writer, stopped) = mpsc::channel();
1773            let writer = std::thread::spawn(move || {
1774                loop {
1775                    match stopped.recv_timeout(Duration::from_millis(200)) {
1776                        Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => return false,
1777                        Err(mpsc::RecvTimeoutError::Timeout) => {}
1778                    }
1779                    if fs::OpenOptions::new()
1780                        .write(true)
1781                        .custom_flags(libc::O_NONBLOCK)
1782                        .open(&fifo)
1783                        .is_ok()
1784                    {
1785                        return true;
1786                    }
1787                }
1788            });
1789            let result = if path == &files.port {
1790                Some(files.read_port())
1791            } else {
1792                assert_eq!(super::read_bounded_lossy(path), "");
1793                None
1794            };
1795            let _ = stop_writer.send(());
1796            assert!(
1797                !writer.join().expect("join delayed FIFO writer"),
1798                "startup reader waited for a writer: {}",
1799                path.display(),
1800            );
1801            if let Some(result) = result {
1802                assert!(matches!(
1803                    result.as_ref().map_err(PocketIcStartupError::failure),
1804                    Err(PocketIcStartupFailure::Io { source, .. })
1805                        if source.kind() == std::io::ErrorKind::InvalidData
1806                ));
1807            }
1808        }
1809    }
1810
1811    #[test]
1812    fn port_file_readiness_preserves_partial_writes_and_rejects_oversized_contents() {
1813        let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1814        assert!(matches!(
1815            files.read_port().unwrap(),
1816            super::PortFileState::Pending
1817        ));
1818        for contents in ["", "34567"] {
1819            fs::write(&files.port, contents).unwrap();
1820            assert!(matches!(
1821                files.read_port().unwrap(),
1822                super::PortFileState::Pending
1823            ));
1824        }
1825        for (contents, expected) in [("1\n", 1), ("65535\n", 65535), (" 34567\r\n", 34567)] {
1826            fs::write(&files.port, contents).unwrap();
1827            assert!(matches!(
1828                files.read_port().unwrap(),
1829                super::PortFileState::Ready(port) if port == expected
1830            ));
1831        }
1832        for contents in ["0\n", "65536\n", "invalid\n", "1\n2\n"] {
1833            fs::write(&files.port, contents).unwrap();
1834            assert!(matches!(
1835                files.read_port().unwrap(),
1836                super::PortFileState::Invalid(_)
1837            ));
1838        }
1839        fs::write(&files.port, [0xff, b'\n']).unwrap();
1840        assert!(matches!(
1841            files.read_port().as_ref().map_err(PocketIcStartupError::failure),
1842            Err(PocketIcStartupFailure::Io { source, .. })
1843                if source.kind() == std::io::ErrorKind::InvalidData
1844        ));
1845        for contents in ["1\n".to_owned() + &" ".repeat(128), "0".repeat(128)] {
1846            fs::write(&files.port, contents).unwrap();
1847            assert!(
1848                matches!(files.read_port().unwrap(), super::PortFileState::Invalid(_)),
1849                "oversized port contents must fail even without a newline",
1850            );
1851        }
1852        // A large backing file must not enlarge the returned diagnostic.
1853        fs::File::options()
1854            .write(true)
1855            .open(&files.port)
1856            .unwrap()
1857            .set_len(1024 * 1024)
1858            .unwrap();
1859        assert!(matches!(
1860            files.read_port().unwrap(),
1861            super::PortFileState::Invalid(value) if value.len() < 256
1862        ));
1863    }
1864
1865    #[test]
1866    fn startup_config_requires_positive_bounds() {
1867        let config = PocketIcStartupConfig::Spawn {
1868            server_binary: "pocket-ic".into(),
1869            timeout: Duration::from_secs(1),
1870            server_hard_ttl: None,
1871            server_idle_ttl: Some(Duration::from_millis(1)),
1872            server_output_files: None,
1873        };
1874        assert!(matches!(
1875            config.validate().unwrap_err().failure(),
1876            PocketIcStartupFailure::InvalidConfiguration { .. }
1877        ));
1878        let error = PocketIcStartupConfig::Connect {
1879            server_url: ("http://127.0.0.1:1/").into(),
1880            timeout: Duration::ZERO,
1881        }
1882        .validate()
1883        .expect_err("zero startup timeout must fail");
1884        assert!(matches!(
1885            error.failure(),
1886            PocketIcStartupFailure::InvalidConfiguration { .. }
1887        ));
1888
1889        let error = PocketIcStartupConfig::Spawn {
1890            server_binary: ("pocket-ic").into(),
1891            timeout: Duration::from_secs(1),
1892            server_hard_ttl: Some(Duration::from_millis(1)),
1893            server_idle_ttl: None,
1894            server_output_files: None,
1895        }
1896        .validate()
1897        .expect_err("subsecond server hard TTL must fail");
1898        assert!(matches!(
1899            error.failure(),
1900            PocketIcStartupFailure::InvalidConfiguration { .. }
1901        ));
1902    }
1903
1904    #[test]
1905    fn startup_files_leave_the_server_owned_port_path_absent() {
1906        let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1907        let directory = files.directory.path().to_path_buf();
1908
1909        assert!(directory.is_dir());
1910        assert!(!files.port.exists());
1911        assert!(files.stdout.is_file());
1912        assert!(files.stderr.is_file());
1913        #[cfg(unix)]
1914        {
1915            let mode = fs::metadata(&directory)
1916                .expect("inspect private startup directory")
1917                .permissions()
1918                .mode();
1919            assert_eq!(mode & 0o077, 0);
1920        }
1921
1922        drop(stdout);
1923        drop(stderr);
1924        drop(files);
1925        assert!(!directory.exists());
1926    }
1927
1928    #[cfg(unix)]
1929    #[test]
1930    fn caller_output_files_survive_startup_command_and_cancellation_cleanup() {
1931        for outcome in [
1932            "timeout",
1933            "startup-exit",
1934            "server-exit",
1935            "command-exit",
1936            "cancel",
1937            "success",
1938        ] {
1939            let (owner, _, _) = StartupFiles::create(None).unwrap();
1940            let stdout = owner.directory.path().join("retained-stdout");
1941            let stderr = owner.directory.path().join("retained-stderr");
1942            let ending = match outcome {
1943                "timeout" => "exec sleep 30",
1944                "startup-exit" => "exit 41",
1945                "server-exit" => {
1946                    "printf '34567\\n' > \"$2\"; while [ ! -s \"$0.command\" ]; do sleep 0.02; done; exit 42"
1947                }
1948                _ => "printf '34567\\n' > \"$2\"; exec sleep 30",
1949            };
1950            let script = TestServerScript::new(
1951                outcome,
1952                &format!(
1953                    "#!/bin/sh\nprintf '%s\\n%s\\n' \"$$\" \"$2\" > \"$0.pid\"\ndd if=/dev/zero bs=1024 count=20 2>/dev/null\nprintf raw-stdout-end\ndd if=/dev/zero bs=1024 count=20 >&2 2>/dev/null\nprintf raw-stderr-end >&2\n{ending}\n"
1954                ),
1955            );
1956            let pid_file = script.path().with_extension("pid");
1957            let command_file = script.path().with_extension("command");
1958            let config = PocketIcStartupConfig::Spawn {
1959                server_binary: script.path(),
1960                timeout: Duration::from_millis(if outcome == "timeout" { 1000 } else { 2000 }),
1961                server_hard_ttl: None,
1962                server_idle_ttl: None,
1963                server_output_files: Some(((&stdout).into(), (&stderr).into())),
1964            };
1965            if outcome == "timeout" || outcome == "startup-exit" {
1966                let error = config.start_managed_server().err().unwrap();
1967                match (outcome, error.failure()) {
1968                    ("timeout", PocketIcStartupFailure::ReadinessTimeout { .. }) => {
1969                        assert!(error.output().stdout().contains("truncated"));
1970                        assert!(!error.output().stderr().contains("raw-stderr-end"));
1971                    }
1972                    ("startup-exit", PocketIcStartupFailure::ServerExited { status, .. }) => {
1973                        assert_eq!(status.code(), Some(41));
1974                    }
1975                    (_, error) => panic!("unexpected startup result: {error:?}"),
1976                }
1977            } else {
1978                let command_end = match outcome {
1979                    "command-exit" => "exit 37",
1980                    "success" => "exit 0",
1981                    _ => "exec sleep 30",
1982                };
1983                let result = config.run_command(
1984                    Command::new("/bin/sh")
1985                        .args([
1986                            "-c",
1987                            &format!("printf '%s' \"$$\" > \"$1\"; {command_end}"),
1988                            "fixture",
1989                        ])
1990                        .arg(&command_file),
1991                    || {
1992                        outcome == "cancel"
1993                            && fs::metadata(&command_file).is_ok_and(|m| m.len() > 0)
1994                    },
1995                );
1996                let result = result.as_ref().map_err(PocketIcStartupError::failure);
1997                match (outcome, result) {
1998                    ("command-exit", Ok(status)) => assert_eq!(status.code(), Some(37)),
1999                    ("success", Ok(status)) => assert!(status.success()),
2000                    ("server-exit", Err(PocketIcStartupFailure::ServerExited { status, .. })) => {
2001                        assert_eq!(status.code(), Some(42));
2002                    }
2003                    ("cancel", Err(PocketIcStartupFailure::CommandRun { source, .. })) => {
2004                        assert_eq!(source.kind(), std::io::ErrorKind::Interrupted);
2005                    }
2006                    (_, result) => panic!("unexpected command result: {result:?}"),
2007                }
2008                let pid = fs::read_to_string(&command_file).unwrap().parse().unwrap();
2009                assert!(process_state(pid).is_none_or(|state| state == 'Z'));
2010            }
2011            for (path, suffix) in [(&stdout, b"raw-stdout-end"), (&stderr, b"raw-stderr-end")] {
2012                let bytes = fs::read(path).unwrap();
2013                assert_eq!(bytes.len(), 20 * 1024 + suffix.len());
2014                assert!(bytes.ends_with(suffix));
2015                assert_eq!(
2016                    fs::metadata(path).unwrap().permissions().mode() & 0o777,
2017                    0o600
2018                );
2019            }
2020            let report = fs::read_to_string(&pid_file).unwrap();
2021            let mut lines = report.lines();
2022            assert_eq!(process_state(lines.next().unwrap().parse().unwrap()), None);
2023            assert!(
2024                !PathBuf::from(lines.next().unwrap())
2025                    .parent()
2026                    .unwrap()
2027                    .exists()
2028            );
2029            fs::remove_file(pid_file).unwrap();
2030        }
2031    }
2032
2033    #[cfg(unix)]
2034    #[test]
2035    fn caller_output_files_refuse_existing_entries_and_keep_partial_preparation() {
2036        use std::os::unix::fs::symlink;
2037
2038        let (owner, _, _) = StartupFiles::create(None).unwrap();
2039        let stdout = owner.directory.path().join("retained-stdout");
2040        let stderr = owner.directory.path().join("retained-stderr");
2041        let unrelated = owner.directory.path().join("unrelated");
2042        fs::write(&unrelated, b"original").unwrap();
2043        symlink(&unrelated, &stderr).unwrap();
2044        let error = StartupFiles::create(Some((stdout.clone(), stderr.clone())))
2045            .err()
2046            .unwrap();
2047        assert!(
2048            matches!(error.failure(), PocketIcStartupFailure::Io { source, .. } if source.kind() == std::io::ErrorKind::AlreadyExists)
2049        );
2050        assert!(stdout.is_file());
2051        assert_eq!(fs::read(&unrelated).unwrap(), b"original");
2052        fs::write(&stdout, b"retained attempt").unwrap();
2053        assert!(StartupFiles::create(Some((stdout.clone(), stderr.clone()))).is_err());
2054        assert_eq!(fs::read(&stdout).unwrap(), b"retained attempt");
2055        fs::remove_file(stderr.clone()).unwrap();
2056        assert!(
2057            Command::new("mkfifo")
2058                .arg(&stderr)
2059                .status()
2060                .unwrap()
2061                .success()
2062        );
2063        fs::remove_file(stdout.clone()).unwrap();
2064        assert!(StartupFiles::create(Some((stdout.clone(), stderr))).is_err());
2065        assert!(stdout.is_file());
2066    }
2067
2068    #[cfg(unix)]
2069    #[test]
2070    fn managed_startup_reports_an_exited_server_with_bounded_output() {
2071        let script = TestServerScript::new(
2072            "exit",
2073            "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nprintf 'synthetic server stdout'\nprintf 'synthetic bind failure' >&2\nexit 23\n",
2074        );
2075
2076        let result = script
2077            .config(Duration::from_secs(2))
2078            .build_instance(PocketIcBuilder::new().with_application_subnet());
2079
2080        let error = result.err().unwrap();
2081        let PocketIcStartupFailure::ServerExited {
2082            server_binary,
2083            status,
2084            ..
2085        } = error.failure()
2086        else {
2087            panic!("expected a structured server exit, got {error:?}");
2088        };
2089        assert_eq!(server_binary, &script.path());
2090        assert_eq!(status.code(), Some(23));
2091        assert_eq!(error.output().stdout(), "synthetic server stdout");
2092        assert_eq!(error.output().stderr(), "synthetic bind failure");
2093    }
2094
2095    #[cfg(unix)]
2096    #[test]
2097    fn managed_startup_rejects_oversized_port_files_and_cleans_up() {
2098        let script = TestServerScript::new(
2099            "oversized-port",
2100            "#!/bin/sh\nprintf '%s\\n%s\\n' \"$$\" \"$2\"\nprintf '34567\\n%064s' '' > \"$2.pending\"\nmv \"$2.pending\" \"$2\"\nexec sleep 30\n",
2101        );
2102        let result = script.config(Duration::from_secs(2)).start_managed_server();
2103        let error = result.err().unwrap();
2104        let PocketIcStartupFailure::InvalidServerPort { value, .. } = error.failure() else {
2105            panic!("oversized port publication must fail readiness");
2106        };
2107        assert!(value.contains("port file exceeds"));
2108        assert!(value.len() < 256);
2109        let mut lines = error.output().stdout().lines();
2110        let pid = lines.next().unwrap().parse::<u32>().unwrap();
2111        let port_path = PathBuf::from(lines.next().unwrap());
2112        assert!(!port_path.parent().unwrap().exists());
2113        assert_eq!(process_state(pid), None, "failed server must be reaped");
2114    }
2115
2116    #[cfg(unix)]
2117    #[test]
2118    fn managed_startup_terminates_a_server_that_never_becomes_ready() {
2119        let script = TestServerScript::new(
2120            "timeout",
2121            "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nexec sleep 30\n",
2122        );
2123        let timeout = Duration::from_millis(100);
2124        let started = Instant::now();
2125
2126        let result = script
2127            .config(timeout)
2128            .build_instance(PocketIcBuilder::new().with_application_subnet());
2129
2130        assert!(
2131            started.elapsed() < Duration::from_secs(2),
2132            "bounded startup should not wait for the sleeping child"
2133        );
2134        let error = result.err().unwrap();
2135        assert!(
2136            matches!(error.failure(), PocketIcStartupFailure::ReadinessTimeout {
2137            server_binary, timeout: actual_timeout,
2138        } if server_binary == &script.path() && *actual_timeout == timeout)
2139        );
2140        assert!(error.server_cleanup().is_none());
2141    }
2142
2143    #[cfg(unix)]
2144    #[test]
2145    fn managed_server_handle_exposes_process_id_url_output_and_raii_ownership() {
2146        let script = TestServerScript::new(
2147            "handle",
2148            "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then echo 'unexpected managed server arguments' >&2; exit 97; fi\nprintf 'managed server ready: %s' \"$$\"\nprintf '34567\\n' > \"$2\"\nexec sleep 30\n",
2149        );
2150
2151        let server = script
2152            .config(Duration::from_secs(2))
2153            .start_managed_server()
2154            .expect("start caller-owned managed server");
2155
2156        assert_eq!(server.url(), "http://127.0.0.1:34567/");
2157        assert_eq!(
2158            server.output().stdout(),
2159            format!("managed server ready: {}", server.process_id())
2160        );
2161        assert_eq!(server.output().stderr(), "");
2162        let pid = server.process_id();
2163        assert!(process_state(pid).is_some_and(|state| state != 'Z'));
2164        drop(server);
2165        assert_eq!(process_state(pid), None, "owned server must be reaped");
2166    }
2167
2168    #[cfg(unix)]
2169    #[test]
2170    fn managed_server_cleans_descendants_on_drop_timeout_and_exit() {
2171        for mode in ["drop", "timeout", "exit"] {
2172            let publish = if mode == "drop" {
2173                "printf '34567\\n' > \"$2\"\n"
2174            } else {
2175                ""
2176            };
2177            let finish = if mode == "exit" {
2178                "sleep 0.03\nexit 23\n"
2179            } else {
2180                "exec sleep 30\n"
2181            };
2182            let script = TestServerScript::new(
2183                mode,
2184                &format!("#!/bin/sh\nsleep 30 &\nprintf '%s' \"$!\"\n{publish}{finish}"),
2185            );
2186            let result = script
2187                .config(Duration::from_millis(300))
2188                .start_managed_server();
2189            let output = match result {
2190                Ok(server) => {
2191                    let output = server.output().stdout().to_owned();
2192                    drop(server);
2193                    output
2194                }
2195                Err(error) => {
2196                    match error.failure() {
2197                        PocketIcStartupFailure::ReadinessTimeout { .. } => {
2198                            assert_eq!(mode, "timeout");
2199                            assert!(error.server_cleanup().is_none());
2200                        }
2201                        PocketIcStartupFailure::ServerExited { status, .. } => {
2202                            assert_eq!(mode, "exit");
2203                            assert_eq!(status.code(), Some(23));
2204                        }
2205                        _ => panic!("unexpected {mode} startup result: {error}"),
2206                    }
2207                    error.output().stdout().to_owned()
2208                }
2209            };
2210            let pid = output
2211                .parse::<u32>()
2212                .expect("server published its descendant PID");
2213            let deadline = Instant::now() + Duration::from_secs(2);
2214            while process_state(pid).is_some_and(|state| state != 'Z') {
2215                assert!(
2216                    Instant::now() < deadline,
2217                    "{mode} left its descendant running"
2218                );
2219                std::thread::sleep(Duration::from_millis(10));
2220            }
2221        }
2222    }
2223
2224    #[cfg(unix)]
2225    #[test]
2226    fn managed_server_passes_an_explicit_hard_ttl() {
2227        let script = TestServerScript::new(
2228            "hard-ttl",
2229            "#!/bin/sh\nif [ \"$1\" != \"--hard-ttl\" ] || [ \"$2\" != \"17\" ] || [ \"$3\" != \"--port-file\" ] || [ -e \"$4\" ]; then exit 97; fi\nprintf '34567\\n' > \"$4\"\nexec sleep 30\n",
2230        );
2231
2232        let server = PocketIcStartupConfig::Spawn {
2233            server_binary: script.path(),
2234            timeout: Duration::from_secs(2),
2235            server_hard_ttl: Some(Duration::from_secs(17)),
2236            server_idle_ttl: None,
2237            server_output_files: None,
2238        }
2239        .start_managed_server()
2240        .expect("start managed server with an explicit hard TTL");
2241
2242        assert_eq!(server.url(), "http://127.0.0.1:34567/");
2243    }
2244
2245    #[cfg(unix)]
2246    #[test]
2247    #[ignore = "requires POCKET_IC_BIN=<caller-provided PocketIC server binary>"]
2248    fn caller_provided_server_publishes_port_constructs_instance_and_cleans_up() {
2249        let binary = std::env::var_os("POCKET_IC_BIN")
2250            .map(PathBuf::from)
2251            .expect("set POCKET_IC_BIN to the exact server binary");
2252        // Observe this exact child's port path without inspecting other startup
2253        // directories created concurrently.
2254        let wrapper = TestServerScript::new(
2255            "real-owned-instance",
2256            "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$4\" > \"$0.record\"\nexec \"$POCKET_IC_BIN\" \"$@\"\n",
2257        );
2258        let owned = PocketIcStartupConfig::Spawn {
2259            server_binary: wrapper.path(),
2260            timeout: Duration::from_secs(30),
2261            server_hard_ttl: Some(Duration::from_secs(60)),
2262            server_idle_ttl: None,
2263            server_output_files: None,
2264        }
2265        .build_instance(PocketIcBuilder::new().with_application_subnet())
2266        .expect("owned managed spawn must construct an instance");
2267        let record_file = wrapper.path().with_extension("record");
2268        let record = fs::read_to_string(&record_file).unwrap();
2269        let mut fields = record.lines();
2270        let pid = fields.next().unwrap().parse().unwrap();
2271        let port_path = PathBuf::from(fields.next().unwrap());
2272        let startup_directory = port_path.parent().unwrap();
2273        drop(owned);
2274        assert!(!startup_directory.exists());
2275        assert_eq!(process_state(pid), None);
2276        fs::remove_file(record_file).unwrap();
2277
2278        let server = PocketIcStartupConfig::Spawn {
2279            server_binary: (&binary).into(),
2280            timeout: Duration::from_secs(30),
2281            server_hard_ttl: Some(Duration::from_secs(60)),
2282            server_idle_ttl: None,
2283            server_output_files: None,
2284        }
2285        .start_managed_server()
2286        .expect("caller-provided PocketIC server must publish its port");
2287        let files = &server.server.files;
2288        let startup_directory = files.directory.path().to_path_buf();
2289
2290        assert!(files.port.is_file());
2291        let pocket_ic = PocketIcStartupConfig::Connect {
2292            server_url: (server.url()).into(),
2293            timeout: Duration::from_secs(30),
2294        }
2295        .build_instance(PocketIcBuilder::new().with_application_subnet())
2296        .expect("construct instance through caller-provided server");
2297
2298        drop(pocket_ic);
2299        drop(server);
2300        assert!(!startup_directory.exists());
2301    }
2302
2303    #[cfg(unix)]
2304    struct TestServerScript {
2305        path: PathBuf,
2306        #[expect(
2307            dead_code,
2308            reason = "retains directory ownership until cleanup or drop"
2309        )]
2310        directory: OwnedDirectory,
2311    }
2312
2313    #[cfg(unix)]
2314    impl TestServerScript {
2315        fn new(label: &str, contents: &str) -> Self {
2316            let directory = OwnedDirectory::new(
2317                create_unique_directory(
2318                    &std::env::temp_dir(),
2319                    &format!("ic-testkit-pocket-ic-{label}"),
2320                    0o700,
2321                    None,
2322                )
2323                .expect("create test server directory"),
2324            );
2325            let path = directory.path().join("server");
2326            write_executable_script(&path, contents).expect("write executable test script");
2327            Self { path, directory }
2328        }
2329
2330        fn path(&self) -> PathBuf {
2331            self.path.clone()
2332        }
2333
2334        fn config(&self, timeout: Duration) -> PocketIcStartupConfig {
2335            PocketIcStartupConfig::Spawn {
2336                server_binary: self.path(),
2337                timeout,
2338                server_hard_ttl: None,
2339                server_idle_ttl: None,
2340                server_output_files: None,
2341            }
2342        }
2343    }
2344}