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                        match managed.try_wait() {
674                            Ok(Some(status)) => break Err(managed.exit_failure(status)),
675                            Ok(None) => {}
676                            Err(error) => break Err(error),
677                        }
678                    }
679                    thread::sleep(STARTUP_POLL_INTERVAL);
680                }
681                Err(source) => break Err(command_error(source)),
682            }
683        };
684        match result {
685            Err(error) => Err(finalize_failure(error, Some(&mut owned_child), server)),
686            Ok(status) => {
687                if let Some(server) = server {
688                    let (output, cleanup) = server.terminate_and_capture();
689                    if let Some(cleanup) = cleanup {
690                        return Err(PocketIcStartupError::new(
691                            PocketIcStartupFailure::ServerCleanup {
692                                command_status: status,
693                            },
694                        )
695                        .with_cleanup(None, Some((output, Some(cleanup)))));
696                    }
697                }
698                Ok(status)
699            }
700        }
701    }
702
703    fn validate(&self) -> Result<(), PocketIcStartupError> {
704        if self.timeout().is_zero() {
705            return Err(PocketIcStartupError::new(
706                PocketIcStartupFailure::InvalidConfiguration {
707                    message: "PocketIC startup timeout must be greater than zero".to_owned(),
708                },
709            ));
710        }
711        if let Self::Spawn {
712            server_hard_ttl,
713            server_idle_ttl,
714            ..
715        } = self
716        {
717            for (ttl, message) in [
718                (
719                    server_hard_ttl,
720                    "PocketIC server hard TTL must be at least one second",
721                ),
722                (
723                    server_idle_ttl,
724                    "PocketIC server idle TTL must be at least one second",
725                ),
726            ] {
727                if ttl.is_some_and(|ttl| ttl.as_secs() == 0) {
728                    return Err(PocketIcStartupError::new(
729                        PocketIcStartupFailure::InvalidConfiguration {
730                            message: message.to_owned(),
731                        },
732                    ));
733                }
734            }
735        }
736        Ok(())
737    }
738}
739
740impl PocketIcManagedServer {
741    /// OS process ID of the owned server child, for caller-managed monitoring.
742    ///
743    /// This identifies the server process, not its descendants, and does not
744    /// establish that it is still running. The OS may reuse the ID after the
745    /// child exits and is reaped. Dropping this handle terminates and waits for
746    /// the child; retaining the ID does not retain server ownership.
747    #[must_use]
748    pub fn process_id(&self) -> u32 {
749        self.server.child.id()
750    }
751
752    /// Loopback URL published by the managed server.
753    #[must_use]
754    pub fn url(&self) -> &str {
755        &self.url
756    }
757
758    /// Current bounded stdout and stderr captured from the managed server.
759    ///
760    /// This reads at most the first 16 KiB from each retained output file,
761    /// renders it as lossy UTF-8, and adds an omitted-byte suffix when truncated.
762    /// The diagnostic read is bounded; files can grow while the server runs.
763    #[must_use]
764    pub fn output(&self) -> PocketIcManagedServerOutput {
765        self.server.files.capture()
766    }
767}
768
769impl PocketIcManagedServerOutput {
770    /// Bounded lossy UTF-8 standard output.
771    #[must_use]
772    pub fn stdout(&self) -> &str {
773        &self.stdout
774    }
775
776    /// Bounded lossy UTF-8 standard error.
777    #[must_use]
778    pub fn stderr(&self) -> &str {
779        &self.stderr
780    }
781}
782
783struct StartupDeadline {
784    started: Instant,
785    timeout: Duration,
786    deadline: Instant,
787}
788
789impl StartupDeadline {
790    fn new(config: &PocketIcStartupConfig) -> Result<Self, PocketIcStartupError> {
791        config.validate()?;
792        let started = Instant::now();
793        let timeout = config.timeout();
794        Ok(Self {
795            started,
796            timeout,
797            deadline: startup_deadline(started, timeout)?,
798        })
799    }
800
801    fn check_instance_deadline(
802        &self,
803        server: &mut Option<ManagedServer>,
804    ) -> Result<Instant, PocketIcStartupError> {
805        let now = Instant::now();
806        if now >= self.deadline {
807            return Err(finalize_failure(
808                PocketIcStartupError::new(PocketIcStartupFailure::InstanceCreationTimeout {
809                    timeout: self.timeout,
810                }),
811                None,
812                server.take(),
813            ));
814        }
815        Ok(now)
816    }
817
818    fn wait_interval(&self, now: Instant, monitor_server: bool) -> Duration {
819        let remaining = self.deadline.saturating_duration_since(now);
820        if monitor_server {
821            remaining.min(STARTUP_POLL_INTERVAL)
822        } else {
823            remaining
824        }
825    }
826
827    fn admit_instance<T>(
828        &self,
829        instance: T,
830        server_url: &str,
831        server: &mut Option<ManagedServer>,
832    ) -> Result<PocketIcInstance<T>, PocketIcStartupError> {
833        self.check_instance_deadline(server)?;
834        check_server(server)?;
835        Ok(PocketIcInstance {
836            instance,
837            server: server.take().map(|server| PocketIcManagedServer {
838                server,
839                url: server_url.to_owned(),
840            }),
841        })
842    }
843}
844
845fn startup_deadline(started: Instant, timeout: Duration) -> Result<Instant, PocketIcStartupError> {
846    started.checked_add(timeout).ok_or_else(|| {
847        PocketIcStartupError::new(PocketIcStartupFailure::InvalidConfiguration {
848            message: "PocketIC startup timeout exceeds the platform clock range".to_owned(),
849        })
850    })
851}
852
853fn build_bounded(
854    builder: PocketIcBuilder,
855    server_url: &str,
856    startup: &StartupDeadline,
857    mut server: Option<ManagedServer>,
858) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
859    let builder = configured_builder(builder, server_url)
860        .map_err(|error| finalize_failure(error, None, server.take()))?;
861    let (sender, receiver) = mpsc::sync_channel(1);
862    if let Err(source) = thread::Builder::new()
863        .name("ic-testkit-pocket-ic-startup".to_owned())
864        .spawn(move || {
865            let result = transport::capture_operation(|| builder.build());
866            let _ = sender.send(result);
867        })
868    {
869        return Err(finalize_failure(
870            PocketIcStartupError::new(PocketIcStartupFailure::BuilderThreadSpawn { source }),
871            None,
872            server,
873        ));
874    }
875    await_builder(receiver, server_url, startup, &mut server)
876}
877
878#[expect(
879    clippy::needless_pass_by_value,
880    reason = "consume the receiver so failed startup disconnects late builders"
881)]
882fn await_builder(
883    receiver: mpsc::Receiver<Result<PocketIc, super::PocketIcOperationError>>,
884    server_url: &str,
885    startup: &StartupDeadline,
886    server: &mut Option<ManagedServer>,
887) -> Result<PocketIcInstance<PocketIc>, PocketIcStartupError> {
888    loop {
889        let now = startup.check_instance_deadline(server)?;
890        let wait = startup.wait_interval(now, server.is_some());
891        match receiver.recv_timeout(wait) {
892            Ok(Ok(pocket_ic)) => {
893                return startup.admit_instance(pocket_ic, server_url, server);
894            }
895            Ok(Err(source)) => {
896                return Err(finalize_failure(
897                    PocketIcStartupError::new(PocketIcStartupFailure::BuilderPanicked { source }),
898                    None,
899                    server.take(),
900                ));
901            }
902            Err(RecvTimeoutError::Disconnected) => {
903                return Err(finalize_failure(
904                    PocketIcStartupError::new(PocketIcStartupFailure::BuilderDisconnected),
905                    None,
906                    server.take(),
907                ));
908            }
909            Err(RecvTimeoutError::Timeout) => {
910                check_server(server)?;
911            }
912        }
913    }
914}
915
916fn configured_builder(
917    builder: PocketIcBuilder,
918    server_url: &str,
919) -> Result<PocketIcBuilder, PocketIcStartupError> {
920    server_url
921        .parse()
922        .map(|url| builder.with_server_url(url))
923        .map_err(|error| {
924            PocketIcStartupError::new(PocketIcStartupFailure::InvalidServerUrl {
925                server_url: server_url.to_owned(),
926                message: error.to_string(),
927            })
928        })
929}
930
931fn check_server(server: &mut Option<ManagedServer>) -> Result<(), PocketIcStartupError> {
932    if let Some(managed) = server.as_mut() {
933        let error = match managed.try_wait() {
934            Ok(Some(status)) => Some(managed.exit_failure(status)),
935            Ok(None) => None,
936            Err(error) => Some(error),
937        };
938        if let Some(error) = error {
939            return Err(finalize_failure(error, None, server.take()));
940        }
941    }
942    Ok(())
943}
944
945async fn build_async_bounded(
946    builder: PocketIcBuilder,
947    server_url: &str,
948    startup: &StartupDeadline,
949    mut server: Option<ManagedServer>,
950) -> Result<PocketIcInstance<ic_platform::pocket_ic::nonblocking::PocketIc>, PocketIcStartupError> {
951    let builder = configured_builder(builder, server_url)
952        .map_err(|error| finalize_failure(error, None, server.take()))?;
953    let mut construction = std::pin::pin!(builder.build_async());
954    let mut construction = std::pin::pin!(std::future::poll_fn(|context| {
955        match transport::capture_operation(|| construction.as_mut().poll(context)) {
956            Ok(poll) => poll.map(Ok),
957            Err(source) => std::task::Poll::Ready(Err(PocketIcStartupError::new(
958                PocketIcStartupFailure::BuilderPanicked { source },
959            ))),
960        }
961    }));
962    // Drop this local before the pending upstream future on cancellation.
963    let mut server = server;
964    loop {
965        let now = startup.check_instance_deadline(&mut server)?;
966        check_server(&mut server)?;
967        let next_check = now + startup.wait_interval(now, server.is_some());
968        match tokio::time::timeout_at(next_check.into(), construction.as_mut()).await {
969            Ok(Ok(instance)) => {
970                return startup.admit_instance(instance, server_url, &mut server);
971            }
972            Ok(Err(error)) => return Err(finalize_failure(error, None, server)),
973            Err(_) => {}
974        }
975    }
976}
977
978/// Finalize an owned operation once, preserving the primary failure.
979fn finalize_failure(
980    error: PocketIcStartupError,
981    command: Option<&mut OwnedChild>,
982    server: Option<ManagedServer>,
983) -> PocketIcStartupError {
984    error.with_cleanup(
985        command.and_then(|child| child.terminate().err()),
986        server.map(ManagedServer::terminate_and_capture),
987    )
988}
989
990struct ManagedServer {
991    child: OwnedChild,
992    binary: PathBuf,
993    files: StartupFiles,
994    started: Instant,
995}
996
997enum PortFileState {
998    Pending,
999    Ready(u16),
1000    Invalid(String),
1001}
1002
1003impl ManagedServer {
1004    fn wait_ready(
1005        mut self,
1006        startup: &StartupDeadline,
1007    ) -> Result<(Self, String), PocketIcStartupError> {
1008        loop {
1009            match self.poll_ready(startup) {
1010                Ok(Some(url)) => return Ok((self, url)),
1011                Ok(None) => thread::sleep(startup.wait_interval(Instant::now(), true)),
1012                Err(error) => return Err(finalize_failure(error, None, Some(self))),
1013            }
1014        }
1015    }
1016
1017    fn spawn(
1018        binary: PathBuf,
1019        hard_ttl: Option<Duration>,
1020        idle_ttl: Option<Duration>,
1021        output_files: Option<(PathBuf, PathBuf)>,
1022        started: Instant,
1023    ) -> Result<Self, PocketIcStartupError> {
1024        let (files, stdout, stderr) = StartupFiles::create(output_files)?;
1025        let mut command = Command::new(&binary);
1026        if let Some(hard_ttl) = hard_ttl {
1027            command
1028                .arg("--hard-ttl")
1029                .arg(hard_ttl.as_secs().to_string());
1030        }
1031        if let Some(idle_ttl) = idle_ttl {
1032            command.arg("--ttl").arg(idle_ttl.as_secs().to_string());
1033        }
1034        command
1035            .arg("--port-file")
1036            .arg(&files.port)
1037            .stdout(Stdio::from(stdout))
1038            .stderr(Stdio::from(stderr));
1039        let child =
1040            OwnedChild::spawn(&mut command, CleanupPolicy::KillAndWait).map_err(|source| {
1041                PocketIcStartupError::new(PocketIcStartupFailure::ServerSpawn {
1042                    server_binary: binary.clone(),
1043                    source,
1044                })
1045            })?;
1046        Ok(Self {
1047            child,
1048            binary,
1049            files,
1050            started,
1051        })
1052    }
1053
1054    fn poll_ready(
1055        &mut self,
1056        startup: &StartupDeadline,
1057    ) -> Result<Option<String>, PocketIcStartupError> {
1058        if let Some(status) = self.try_wait()? {
1059            return Err(self.exit_failure(status));
1060        }
1061        if Instant::now() >= startup.deadline {
1062            return Err(PocketIcStartupError::new(
1063                PocketIcStartupFailure::ReadinessTimeout {
1064                    server_binary: self.binary.clone(),
1065                    timeout: startup.timeout,
1066                },
1067            ));
1068        }
1069        match self.files.read_port()? {
1070            PortFileState::Pending => Ok(None),
1071            PortFileState::Ready(port) => Ok(Some(format!("http://127.0.0.1:{port}/"))),
1072            PortFileState::Invalid(value) => Err(PocketIcStartupError::new(
1073                PocketIcStartupFailure::InvalidServerPort {
1074                    server_binary: self.binary.clone(),
1075                    value,
1076                },
1077            )),
1078        }
1079    }
1080
1081    fn try_wait(&mut self) -> Result<Option<ExitStatus>, PocketIcStartupError> {
1082        self.child.try_wait().map_err(|source| {
1083            PocketIcStartupError::new(PocketIcStartupFailure::Io {
1084                operation: "inspect PocketIC server child",
1085                path: self.binary.clone(),
1086                source,
1087            })
1088        })
1089    }
1090
1091    fn exit_failure(&self, status: ExitStatus) -> PocketIcStartupError {
1092        PocketIcStartupError::new(PocketIcStartupFailure::ServerExited {
1093            server_binary: self.binary.clone(),
1094            status,
1095            elapsed: self.started.elapsed(),
1096        })
1097    }
1098
1099    fn terminate_and_capture(self) -> (PocketIcManagedServerOutput, Option<CleanupError>) {
1100        let Self {
1101            mut child, files, ..
1102        } = self;
1103        let cleanup = child.terminate().err();
1104        // Finish the child's Drop cleanup before reading the final diagnostics.
1105        drop(child);
1106        (files.capture(), cleanup)
1107    }
1108}
1109
1110struct StartupFiles {
1111    #[cfg_attr(
1112        not(test),
1113        expect(
1114            dead_code,
1115            reason = "retains directory ownership until cleanup or drop"
1116        )
1117    )]
1118    directory: OwnedDirectory,
1119    port: PathBuf,
1120    stdout: PathBuf,
1121    stderr: PathBuf,
1122}
1123
1124impl StartupFiles {
1125    fn read_port(&self) -> Result<PortFileState, PocketIcStartupError> {
1126        let port_path = &self.port;
1127        let mut contents = String::new();
1128        match ic_host_fs::read::open_regular_file(port_path)
1129            .map_err(|error| match error {
1130                ic_host_artifacts::artifact::ArtifactError::Io(source) => source,
1131                error => io::Error::new(io::ErrorKind::InvalidData, error),
1132            })
1133            .and_then(|file| {
1134                file.take((SERVER_PORT_FILE_LIMIT + 1) as u64)
1135                    .read_to_string(&mut contents)
1136            }) {
1137            Ok(_) => {}
1138            Err(error) if error.kind() == io::ErrorKind::NotFound => {
1139                return Ok(PortFileState::Pending);
1140            }
1141            Err(source) => {
1142                return Err(PocketIcStartupError::new(PocketIcStartupFailure::Io {
1143                    operation: "read PocketIC server port file",
1144                    path: port_path.clone(),
1145                    source,
1146                }));
1147            }
1148        }
1149        if contents.len() > SERVER_PORT_FILE_LIMIT {
1150            return Ok(PortFileState::Invalid(format!(
1151                "{} (port file exceeds {SERVER_PORT_FILE_LIMIT} bytes)",
1152                contents.trim()
1153            )));
1154        }
1155        if !contents.contains('\n') {
1156            return Ok(PortFileState::Pending);
1157        }
1158        let value = contents.trim().to_owned();
1159        match value.parse::<u16>() {
1160            Ok(port) if port != 0 => Ok(PortFileState::Ready(port)),
1161            _ => Ok(PortFileState::Invalid(value)),
1162        }
1163    }
1164
1165    fn capture(&self) -> PocketIcManagedServerOutput {
1166        PocketIcManagedServerOutput {
1167            stdout: read_bounded_lossy(&self.stdout),
1168            stderr: read_bounded_lossy(&self.stderr),
1169        }
1170    }
1171
1172    fn create(
1173        output_files: Option<(PathBuf, PathBuf)>,
1174    ) -> Result<(Self, File, File), PocketIcStartupError> {
1175        let output_files = output_files
1176            .map(|(stdout, stderr)| {
1177                Ok::<_, PocketIcStartupError>((
1178                    std::path::absolute(&stdout)
1179                        .map_err(|source| startup_file_error("resolve", &stdout, source))?,
1180                    std::path::absolute(&stderr)
1181                        .map_err(|source| startup_file_error("resolve", &stderr, source))?,
1182                ))
1183            })
1184            .transpose()?;
1185        let directory = OwnedDirectory::new(
1186            create_unique_directory(
1187                &std::env::temp_dir(),
1188                "ic-testkit-pocket-ic-startup",
1189                0o700,
1190                None,
1191            )
1192            .map_err(|source| startup_file_error("create", &std::env::temp_dir(), source))?,
1193        );
1194        let base = directory.path();
1195        let (stdout_path, stderr_path) =
1196            output_files.unwrap_or_else(|| (base.join("stdout"), base.join("stderr")));
1197        let files = Self {
1198            port: base.join("port"),
1199            stdout: stdout_path,
1200            stderr: stderr_path,
1201            directory,
1202        };
1203        let stdout = create_new_file(&files.stdout)
1204            .map_err(|source| startup_file_error("create", &files.stdout, source))?;
1205        let stderr = create_new_file(&files.stderr)
1206            .map_err(|source| startup_file_error("create", &files.stderr, source))?;
1207        Ok((files, stdout, stderr))
1208    }
1209}
1210
1211fn create_new_file(path: &Path) -> io::Result<File> {
1212    let mut options = OpenOptions::new();
1213    options.write(true).create_new(true);
1214    #[cfg(unix)]
1215    options.mode(0o600);
1216    options.open(path)
1217}
1218
1219fn startup_file_error(
1220    operation: &'static str,
1221    path: &Path,
1222    source: io::Error,
1223) -> PocketIcStartupError {
1224    PocketIcStartupError::new(PocketIcStartupFailure::Io {
1225        operation,
1226        path: path.to_owned(),
1227        source,
1228    })
1229}
1230
1231fn read_bounded_lossy(path: &Path) -> String {
1232    let Ok((bytes, length)) = ic_host_fs::read::read_file_prefix(path, SERVER_OUTPUT_LIMIT) else {
1233        return String::new();
1234    };
1235    let mut output = String::from_utf8_lossy(&bytes).into_owned();
1236    let omitted = length.saturating_sub(bytes.len() as u64);
1237    if omitted > 0 {
1238        let _ = write!(output, "\n<truncated {omitted} bytes>");
1239    }
1240    output
1241}
1242
1243impl std::fmt::Display for PocketIcStartupError {
1244    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1245        std::fmt::Display::fmt(self.failure.as_ref(), formatter)?;
1246        if !self.output.stdout.is_empty() {
1247            write!(formatter, "; server stdout: {}", self.output.stdout)?;
1248        }
1249        if !self.output.stderr.is_empty() {
1250            write!(formatter, "; server stderr: {}", self.output.stderr)?;
1251        }
1252        for (owner, cleanup) in [
1253            ("command", self.command_cleanup()),
1254            ("server", self.server_cleanup()),
1255        ] {
1256            if let Some(error) = cleanup {
1257                write!(formatter, "; {owner} cleanup also failed: {error}")?;
1258            }
1259        }
1260        Ok(())
1261    }
1262}
1263
1264impl std::error::Error for PocketIcStartupError {
1265    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1266        std::error::Error::source(self.failure.as_ref())
1267    }
1268}
1269
1270#[cfg(test)]
1271mod tests {
1272    mod instances;
1273
1274    use std::{
1275        fs,
1276        path::PathBuf,
1277        time::{Duration, Instant},
1278    };
1279
1280    use super::{
1281        OwnedDirectory, PocketIcStartupConfig, PocketIcStartupError, PocketIcStartupFailure,
1282        StartupFiles, create_unique_directory,
1283    };
1284    use ic_platform::pocket_ic::PocketIcBuilder;
1285
1286    #[cfg(unix)]
1287    use ic_host_process::testing::write_executable_script;
1288    #[cfg(unix)]
1289    use std::{
1290        io::Write as _,
1291        os::unix::fs::{OpenOptionsExt as _, PermissionsExt as _},
1292        process::Command,
1293        sync::mpsc,
1294    };
1295
1296    #[test]
1297    fn completed_instances_must_still_meet_the_startup_deadline() {
1298        let started = Instant::now();
1299        let startup = super::StartupDeadline {
1300            started,
1301            timeout: Duration::from_secs(60),
1302            deadline: started + Duration::from_secs(60),
1303        };
1304        let mut server = None;
1305        let instance = startup
1306            .admit_instance(7_u8, "http://localhost/", &mut server)
1307            .unwrap();
1308        assert_eq!(*instance.instance(), 7);
1309        assert!(server.is_none());
1310        let expired = super::StartupDeadline {
1311            deadline: started,
1312            ..startup
1313        };
1314        let error = expired
1315            .admit_instance(7_u8, "http://localhost/", &mut server)
1316            .err()
1317            .expect("completed instance after the deadline must refuse admission");
1318        assert!(
1319            matches!(error.failure(), PocketIcStartupFailure::InstanceCreationTimeout { timeout } if *timeout == Duration::from_secs(60))
1320        );
1321        assert!(server.is_none());
1322    }
1323
1324    #[test]
1325    fn original_failure_output_and_both_typed_cleanup_reports_survive_projection() {
1326        use std::error::Error as _;
1327        for failure in [
1328            PocketIcStartupFailure::ReadinessTimeout {
1329                server_binary: "server".into(),
1330                timeout: Duration::from_secs(1),
1331            },
1332            PocketIcStartupFailure::InstanceCreationTimeout {
1333                timeout: Duration::from_secs(1),
1334            },
1335            PocketIcStartupFailure::InvalidServerPort {
1336                server_binary: "server".into(),
1337                value: "invalid".into(),
1338            },
1339            PocketIcStartupFailure::BuilderPanicked {
1340                source: super::super::PocketIcOperationError::new("original-panic"),
1341            },
1342            PocketIcStartupFailure::BuilderDisconnected,
1343            PocketIcStartupFailure::BuilderThreadSpawn {
1344                source: std::io::Error::from_raw_os_error(9),
1345            },
1346            PocketIcStartupFailure::Io {
1347                operation: "original-io",
1348                path: "port".into(),
1349                source: std::io::Error::from_raw_os_error(9),
1350            },
1351        ] {
1352            let primary_text = failure.to_string();
1353            let output = super::PocketIcManagedServerOutput {
1354                stdout: "original-stdout".into(),
1355                stderr: "original-stderr".into(),
1356            };
1357            let command = super::CleanupError {
1358                status: None,
1359                group_error: None,
1360                term_error: Some(std::io::Error::from_raw_os_error(4)),
1361                kill_error: Some(std::io::Error::from_raw_os_error(5)),
1362                wait_error: None,
1363            };
1364            let server = super::CleanupError {
1365                status: None,
1366                group_error: Some(std::io::Error::from_raw_os_error(1)),
1367                term_error: None,
1368                kill_error: None,
1369                wait_error: Some(std::io::Error::from_raw_os_error(10)),
1370            };
1371            let error = PocketIcStartupError::new(failure)
1372                .with_cleanup(Some(command), Some((output, Some(server))));
1373            assert_eq!(error.failure().to_string(), primary_text);
1374            assert_eq!(error.output().stdout(), "original-stdout");
1375            assert_eq!(error.output().stderr(), "original-stderr");
1376            let command = error.command_cleanup().unwrap();
1377            let server = error.server_cleanup().unwrap();
1378            assert_eq!(command.kill_error.as_ref().unwrap().raw_os_error(), Some(5));
1379            assert_eq!(command.term_error.as_ref().unwrap().raw_os_error(), Some(4));
1380            assert_eq!(server.group_error.as_ref().unwrap().raw_os_error(), Some(1));
1381            assert_eq!(server.wait_error.as_ref().unwrap().raw_os_error(), Some(10));
1382            if matches!(
1383                error.failure(),
1384                PocketIcStartupFailure::Io { .. }
1385                    | PocketIcStartupFailure::BuilderThreadSpawn { .. }
1386            ) {
1387                assert_eq!(
1388                    error
1389                        .source()
1390                        .unwrap()
1391                        .downcast_ref::<std::io::Error>()
1392                        .unwrap()
1393                        .raw_os_error(),
1394                    Some(9)
1395                );
1396            }
1397            if let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() {
1398                assert_eq!(
1399                    error
1400                        .source()
1401                        .unwrap()
1402                        .downcast_ref::<super::super::PocketIcOperationError>(),
1403                    Some(source)
1404                );
1405            }
1406            let displayed = error.to_string();
1407            assert!(displayed.starts_with(&primary_text));
1408            for marker in [
1409                "original-stdout",
1410                "original-stderr",
1411                "command cleanup also failed",
1412                "server cleanup also failed",
1413            ] {
1414                assert!(displayed.contains(marker));
1415            }
1416        }
1417        let error = PocketIcStartupError::new(PocketIcStartupFailure::NotConfigured);
1418        assert_eq!(error.to_string(), error.failure().to_string());
1419        assert!(error.command_cleanup().is_none());
1420        assert!(error.server_cleanup().is_none());
1421    }
1422
1423    #[cfg(unix)]
1424    #[test]
1425    fn builder_failures_finalize_the_owned_server_and_keep_output() {
1426        for disconnected in [false, true] {
1427            let script = TestServerScript::new(
1428                "builder-failure",
1429                "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'builder-diagnostic' >&2\nprintf '34567\n' > \"$2\"\nexec sleep 30\n",
1430            );
1431            let managed = script
1432                .config(Duration::from_secs(2))
1433                .start_managed_server()
1434                .unwrap();
1435            let pid = managed.process_id();
1436            let directory = managed.server.files.directory.path().to_path_buf();
1437            let (sender, receiver) = mpsc::channel();
1438            if !disconnected {
1439                sender
1440                    .send(Err(super::super::PocketIcOperationError::new(
1441                        "original-builder-panic",
1442                    )))
1443                    .unwrap();
1444            }
1445            drop(sender);
1446            let error = super::await_builder(
1447                receiver,
1448                "http://127.0.0.1:34567/",
1449                &super::StartupDeadline {
1450                    started: Instant::now(),
1451                    deadline: Instant::now() + Duration::from_secs(2),
1452                    timeout: Duration::from_secs(2),
1453                },
1454                &mut Some(managed.server),
1455            )
1456            .err()
1457            .unwrap();
1458            assert!(matches!(
1459                (disconnected, error.failure()),
1460                (true, PocketIcStartupFailure::BuilderDisconnected)
1461                    | (false, PocketIcStartupFailure::BuilderPanicked { .. })
1462            ));
1463            assert_eq!(error.output().stderr(), "builder-diagnostic");
1464            assert!(error.server_cleanup().is_none());
1465            assert!(!directory.exists());
1466            assert_eq!(process_state(pid), None);
1467        }
1468    }
1469
1470    #[cfg(unix)]
1471    #[test]
1472    fn port_io_and_command_spawn_failures_finalize_the_owned_server() {
1473        for port_io in [true, false] {
1474            let port = if port_io {
1475                "mkfifo \"$2\""
1476            } else {
1477                "printf '34567\n' > \"$2\""
1478            };
1479            let script = TestServerScript::new(
1480                "owned-io-failure",
1481                &format!(
1482                    "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$2\"\nprintf 'original-server-diagnostic' >&2\n{port}\nexec sleep 30\n"
1483                ),
1484            );
1485            let config = script.config(Duration::from_secs(2));
1486            let error = if port_io {
1487                config.start_managed_server().err().unwrap()
1488            } else {
1489                config
1490                    .run_command(&mut Command::new("/missing/ic-testkit-command"), || false)
1491                    .unwrap_err()
1492            };
1493            let PocketIcStartupFailure::Io { source, .. } = error.failure() else {
1494                panic!("expected original IO failure: {error:?}");
1495            };
1496            assert_eq!(
1497                source.kind(),
1498                if port_io {
1499                    std::io::ErrorKind::InvalidData
1500                } else {
1501                    std::io::ErrorKind::NotFound
1502                }
1503            );
1504            assert_eq!(error.output().stderr(), "original-server-diagnostic");
1505            let mut lines = error.output().stdout().lines();
1506            let pid = lines.next().unwrap().parse().unwrap();
1507            let port = PathBuf::from(lines.next().unwrap());
1508            assert_eq!(process_state(pid), None);
1509            assert!(!port.parent().unwrap().exists());
1510            assert!(error.server_cleanup().is_none());
1511        }
1512    }
1513
1514    #[cfg(unix)]
1515    #[test]
1516    fn command_cancellation_before_startup_has_no_spawn_effects() {
1517        let error = PocketIcStartupConfig::Spawn {
1518            server_binary: ("/missing/server").into(),
1519            timeout: Duration::from_secs(1),
1520            server_hard_ttl: None,
1521            server_idle_ttl: None,
1522            server_output_files: None,
1523        }
1524        .run_command(&mut Command::new("/missing/command"), || true)
1525        .unwrap_err();
1526        assert!(
1527            matches!(error.failure(), PocketIcStartupFailure::CommandRun { source, .. } if source.kind() == std::io::ErrorKind::Interrupted)
1528        );
1529        assert_eq!(error.output().stdout(), "");
1530        assert_eq!(error.output().stderr(), "");
1531        assert!(error.command_cleanup().is_none());
1532        assert!(error.server_cleanup().is_none());
1533    }
1534
1535    #[cfg(unix)]
1536    #[test]
1537    fn cancellation_callback_panic_still_reaps_the_owned_command() {
1538        let script = TestServerScript::new(
1539            "cancel-panic",
1540            "#!/bin/sh\nprintf '%s' \"$$\" > \"$1\"\nexec sleep 30\n",
1541        );
1542        let pid_file = script.path().with_extension("pid");
1543        let result = std::panic::catch_unwind(|| {
1544            PocketIcStartupConfig::Connect {
1545                server_url: ("http://127.0.0.1:12345/").into(),
1546                timeout: Duration::from_secs(1),
1547            }
1548            .run_command(Command::new(script.path()).arg(&pid_file), || {
1549                assert!(
1550                    !fs::read_to_string(&pid_file).is_ok_and(|value| !value.is_empty()),
1551                    "caller cancellation failed"
1552                );
1553                false
1554            })
1555        });
1556        assert!(result.is_err());
1557        let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1558        assert!(process_state(pid).is_none_or(|state| state == 'Z'));
1559        fs::remove_file(pid_file).unwrap();
1560    }
1561
1562    #[cfg(unix)]
1563    #[test]
1564    fn environment_selection_prefers_urls_and_fails_closed() {
1565        use std::os::unix::ffi::OsStringExt as _;
1566
1567        let timeout = Duration::from_secs(1);
1568        let config = PocketIcStartupConfig::from_environment(timeout, |name| {
1569            Some(
1570                if name == "IC_TESTKIT_POCKET_IC_URL" {
1571                    "http://127.0.0.1:12345/"
1572                } else {
1573                    "/missing/server"
1574                }
1575                .into(),
1576            )
1577        })
1578        .unwrap();
1579        assert!(
1580            matches!(config, PocketIcStartupConfig::Connect { ref server_url, .. } if server_url == "http://127.0.0.1:12345/")
1581        );
1582        assert!(matches!(
1583            PocketIcStartupConfig::from_environment(timeout, |_| None)
1584                .as_ref()
1585                .map_err(PocketIcStartupError::failure),
1586            Err(PocketIcStartupFailure::NotConfigured)
1587        ));
1588        assert!(matches!(
1589            PocketIcStartupConfig::from_environment(timeout, |_| Some("".into()))
1590                .as_ref()
1591                .map_err(PocketIcStartupError::failure),
1592            Err(PocketIcStartupFailure::InvalidEnvironment {
1593                variable: "IC_TESTKIT_POCKET_IC_URL"
1594            })
1595        ));
1596        assert!(matches!(
1597            PocketIcStartupConfig::from_environment(timeout, |_| Some("bad URL".into()))
1598                .as_ref()
1599                .map_err(PocketIcStartupError::failure),
1600            Err(PocketIcStartupFailure::InvalidServerUrl { .. })
1601        ));
1602        assert!(matches!(
1603            PocketIcStartupConfig::from_environment(timeout, |_| Some(
1604                std::ffi::OsString::from_vec(vec![0xff])
1605            ))
1606            .as_ref()
1607            .map_err(PocketIcStartupError::failure),
1608            Err(PocketIcStartupFailure::InvalidEnvironment { .. })
1609        ));
1610    }
1611
1612    #[cfg(unix)]
1613    #[test]
1614    fn version_capture_cleans_wrapper_descendants_on_exit_and_timeout() {
1615        for timeout in [false, true] {
1616            let qualified = format!(
1617                "printf 'pocket-ic-server {}\\n'",
1618                crate::pic::POCKET_IC_SERVER_VERSION
1619            );
1620            let ending = if timeout { "wait" } else { &qualified };
1621            let script = TestServerScript::new(
1622                "version-group",
1623                &format!(
1624                    "#!/bin/sh\nsleep 30 >/dev/null 2>&1 &\nprintf '%s' \"$!\" > \"$0.pid\"\n{ending}\n"
1625                ),
1626            );
1627            let result = PocketIcStartupConfig::from_environment(Duration::from_secs(1), |name| {
1628                (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1629            });
1630            if timeout {
1631                assert!(matches!(
1632                    result.as_ref().map_err(PocketIcStartupError::failure),
1633                    Err(PocketIcStartupFailure::ServerVersionProbe { .. })
1634                ));
1635            } else {
1636                assert!(result.is_ok());
1637            }
1638            let pid_file = script.path().with_extension("pid");
1639            let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1640            let deadline = Instant::now() + Duration::from_secs(3);
1641            while process_state(pid).is_some_and(|state| state != 'Z') {
1642                assert!(
1643                    Instant::now() < deadline,
1644                    "version wrapper descendant remained alive"
1645                );
1646                std::thread::sleep(Duration::from_millis(20));
1647            }
1648            fs::remove_file(pid_file).unwrap();
1649        }
1650    }
1651
1652    #[cfg(unix)]
1653    #[test]
1654    fn owned_builder_panic_retains_server_output_and_reaps_child() {
1655        let script = TestServerScript::new(
1656            "builder-panic",
1657            "#!/bin/sh\nprintf '%s' \"$$\" > \"$0.pid\"\nprintf 'builder stdout'\nprintf 'builder stderr' >&2\nprintf '34567\\n' > \"$2\"\nexec sleep 30\n",
1658        );
1659        let error = script
1660            .config(Duration::from_secs(2))
1661            .build_instance(PocketIcBuilder::new())
1662            .err()
1663            .unwrap();
1664        let PocketIcStartupFailure::BuilderPanicked { source } = error.failure() else {
1665            panic!("expected builder failure, got {error:?}");
1666        };
1667        assert_ne!(source.message(), "");
1668        assert_eq!(
1669            std::error::Error::source(&error)
1670                .unwrap()
1671                .downcast_ref::<super::super::PocketIcOperationError>(),
1672            Some(source)
1673        );
1674        assert_eq!(error.output().stdout(), "builder stdout");
1675        assert_eq!(error.output().stderr(), "builder stderr");
1676        assert!(error.server_cleanup().is_none());
1677        let pid_file = script.path().with_extension("pid");
1678        let pid = fs::read_to_string(&pid_file).unwrap().parse().unwrap();
1679        assert_eq!(process_state(pid), None);
1680        fs::remove_file(pid_file).unwrap();
1681    }
1682
1683    #[cfg(unix)]
1684    #[test]
1685    fn environment_binary_selection_uses_bounded_shared_version_capture() {
1686        let qualified = format!(
1687            "printf 'pocket-ic-server {}\\n'",
1688            crate::pic::POCKET_IC_SERVER_VERSION
1689        );
1690        let failed = format!("{qualified}; exit 23");
1691        for (label, body, expected) in [
1692            ("qualified", qualified.as_str(), 0),
1693            ("compatible-16.0", "printf 'pocket-ic-server 16.0.0\\n'", 0),
1694            ("compatible-patch", "printf 'pocket-ic-server 16.0.1\\n'", 0),
1695            ("wrong-version", "printf 'pocket-ic-server 15.0.0\\n'", 1),
1696            ("future-major", "printf 'pocket-ic-server 17.0.0\\n'", 1),
1697            ("malformed-version", "printf 'pocket-ic-server 16.1\\n'", 1),
1698            ("failed-version", failed.as_str(), 2),
1699            ("invalid-utf8", "printf '\\377'", 1),
1700            ("version-timeout", "exec sleep 30", 2),
1701        ] {
1702            let script = TestServerScript::new(
1703                label,
1704                &format!("#!/bin/sh\n[ \"$1\" = --version ] || exit 99\n{body}\n"),
1705            );
1706            // A successful process launch needs scheduling headroom on loaded CI
1707            // hosts; only the deliberately stalled probe needs a short deadline.
1708            let timeout = if label == "version-timeout" {
1709                Duration::from_millis(200)
1710            } else {
1711                Duration::from_secs(5)
1712            };
1713            let result = PocketIcStartupConfig::from_environment(timeout, |name| {
1714                (name == "POCKET_IC_BIN").then(|| script.path().into_os_string())
1715            });
1716            match (
1717                expected,
1718                result.as_ref().map_err(PocketIcStartupError::failure),
1719            ) {
1720                (0, Ok(config)) => {
1721                    let binary = script.path().canonicalize().unwrap();
1722                    assert!(
1723                        matches!(config, PocketIcStartupConfig::Spawn { server_binary, .. } if server_binary == &binary)
1724                    );
1725                }
1726                (1, Err(PocketIcStartupFailure::ServerVersionMismatch { .. }))
1727                | (2, Err(PocketIcStartupFailure::ServerVersionProbe { .. })) => {}
1728                (_, result) => panic!("unexpected {label} result: {result:?}"),
1729            }
1730        }
1731    }
1732
1733    #[cfg(unix)]
1734    fn process_state(pid: u32) -> Option<char> {
1735        ic_host_process::testing::process_state(pid).expect("inspect managed test process state")
1736    }
1737
1738    #[cfg(unix)]
1739    #[test]
1740    fn reading_large_sparse_server_output_is_bounded() {
1741        let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1742        let mut file = fs::File::create(&files.stdout).expect("create sparse log");
1743        file.write_all(b"server started\n").expect("write prefix");
1744        let size = 8_u64 * 1024 * 1024 * 1024;
1745        file.set_len(size).expect("extend sparse log");
1746        let output = super::read_bounded_lossy(&files.stdout);
1747        assert!(output.starts_with("server started\n"));
1748        assert!(output.ends_with(&format!(
1749            "<truncated {} bytes>",
1750            size - super::SERVER_OUTPUT_LIMIT as u64
1751        )));
1752        assert!(output.len() < super::SERVER_OUTPUT_LIMIT + 100);
1753    }
1754
1755    #[cfg(unix)]
1756    #[test]
1757    fn startup_readers_reject_fifos_without_waiting_for_a_writer() {
1758        let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1759        drop((stdout, stderr));
1760        fs::remove_file(&files.stdout).unwrap();
1761        fs::remove_file(&files.stderr).unwrap();
1762        assert!(
1763            Command::new("mkfifo")
1764                .args([&files.port, &files.stdout, &files.stderr])
1765                .status()
1766                .expect("create FIFO startup files")
1767                .success()
1768        );
1769        for path in [&files.port, &files.stdout, &files.stderr] {
1770            // A delayed writer bounds a blocked read and records whether the
1771            // reader needed it. Completion cancels the writer; with no reader,
1772            // a nonblocking open fails and is retried if the reader starts late.
1773            let fifo = path.clone();
1774            let (stop_writer, stopped) = mpsc::channel();
1775            let writer = std::thread::spawn(move || {
1776                loop {
1777                    match stopped.recv_timeout(Duration::from_millis(200)) {
1778                        Ok(()) | Err(mpsc::RecvTimeoutError::Disconnected) => return false,
1779                        Err(mpsc::RecvTimeoutError::Timeout) => {}
1780                    }
1781                    if fs::OpenOptions::new()
1782                        .write(true)
1783                        .custom_flags(libc::O_NONBLOCK)
1784                        .open(&fifo)
1785                        .is_ok()
1786                    {
1787                        return true;
1788                    }
1789                }
1790            });
1791            let result = if path == &files.port {
1792                Some(files.read_port())
1793            } else {
1794                assert_eq!(super::read_bounded_lossy(path), "");
1795                None
1796            };
1797            let _ = stop_writer.send(());
1798            assert!(
1799                !writer.join().expect("join delayed FIFO writer"),
1800                "startup reader waited for a writer: {}",
1801                path.display(),
1802            );
1803            if let Some(result) = result {
1804                assert!(matches!(
1805                    result.as_ref().map_err(PocketIcStartupError::failure),
1806                    Err(PocketIcStartupFailure::Io { source, .. })
1807                        if source.kind() == std::io::ErrorKind::InvalidData
1808                ));
1809            }
1810        }
1811    }
1812
1813    #[test]
1814    fn port_file_readiness_preserves_partial_writes_and_rejects_oversized_contents() {
1815        let (files, _, _) = StartupFiles::create(None).expect("allocate startup files");
1816        assert!(matches!(
1817            files.read_port().unwrap(),
1818            super::PortFileState::Pending
1819        ));
1820        for contents in ["", "34567"] {
1821            fs::write(&files.port, contents).unwrap();
1822            assert!(matches!(
1823                files.read_port().unwrap(),
1824                super::PortFileState::Pending
1825            ));
1826        }
1827        for (contents, expected) in [("1\n", 1), ("65535\n", 65535), (" 34567\r\n", 34567)] {
1828            fs::write(&files.port, contents).unwrap();
1829            assert!(matches!(
1830                files.read_port().unwrap(),
1831                super::PortFileState::Ready(port) if port == expected
1832            ));
1833        }
1834        for contents in ["0\n", "65536\n", "invalid\n", "1\n2\n"] {
1835            fs::write(&files.port, contents).unwrap();
1836            assert!(matches!(
1837                files.read_port().unwrap(),
1838                super::PortFileState::Invalid(_)
1839            ));
1840        }
1841        fs::write(&files.port, [0xff, b'\n']).unwrap();
1842        assert!(matches!(
1843            files.read_port().as_ref().map_err(PocketIcStartupError::failure),
1844            Err(PocketIcStartupFailure::Io { source, .. })
1845                if source.kind() == std::io::ErrorKind::InvalidData
1846        ));
1847        for contents in ["1\n".to_owned() + &" ".repeat(128), "0".repeat(128)] {
1848            fs::write(&files.port, contents).unwrap();
1849            assert!(
1850                matches!(files.read_port().unwrap(), super::PortFileState::Invalid(_)),
1851                "oversized port contents must fail even without a newline",
1852            );
1853        }
1854        // A large backing file must not enlarge the returned diagnostic.
1855        fs::File::options()
1856            .write(true)
1857            .open(&files.port)
1858            .unwrap()
1859            .set_len(1024 * 1024)
1860            .unwrap();
1861        assert!(matches!(
1862            files.read_port().unwrap(),
1863            super::PortFileState::Invalid(value) if value.len() < 256
1864        ));
1865    }
1866
1867    #[test]
1868    fn startup_config_requires_positive_bounds() {
1869        let config = PocketIcStartupConfig::Spawn {
1870            server_binary: "pocket-ic".into(),
1871            timeout: Duration::from_secs(1),
1872            server_hard_ttl: None,
1873            server_idle_ttl: Some(Duration::from_millis(1)),
1874            server_output_files: None,
1875        };
1876        assert!(matches!(
1877            config.validate().unwrap_err().failure(),
1878            PocketIcStartupFailure::InvalidConfiguration { .. }
1879        ));
1880        let error = PocketIcStartupConfig::Connect {
1881            server_url: ("http://127.0.0.1:1/").into(),
1882            timeout: Duration::ZERO,
1883        }
1884        .validate()
1885        .expect_err("zero startup timeout must fail");
1886        assert!(matches!(
1887            error.failure(),
1888            PocketIcStartupFailure::InvalidConfiguration { .. }
1889        ));
1890
1891        let error = PocketIcStartupConfig::Spawn {
1892            server_binary: ("pocket-ic").into(),
1893            timeout: Duration::from_secs(1),
1894            server_hard_ttl: Some(Duration::from_millis(1)),
1895            server_idle_ttl: None,
1896            server_output_files: None,
1897        }
1898        .validate()
1899        .expect_err("subsecond server hard TTL must fail");
1900        assert!(matches!(
1901            error.failure(),
1902            PocketIcStartupFailure::InvalidConfiguration { .. }
1903        ));
1904    }
1905
1906    #[test]
1907    fn startup_files_leave_the_server_owned_port_path_absent() {
1908        let (files, stdout, stderr) = StartupFiles::create(None).expect("allocate startup files");
1909        let directory = files.directory.path().to_path_buf();
1910
1911        assert!(directory.is_dir());
1912        assert!(!files.port.exists());
1913        assert!(files.stdout.is_file());
1914        assert!(files.stderr.is_file());
1915        #[cfg(unix)]
1916        {
1917            let mode = fs::metadata(&directory)
1918                .expect("inspect private startup directory")
1919                .permissions()
1920                .mode();
1921            assert_eq!(mode & 0o077, 0);
1922        }
1923
1924        drop(stdout);
1925        drop(stderr);
1926        drop(files);
1927        assert!(!directory.exists());
1928    }
1929
1930    #[cfg(unix)]
1931    #[test]
1932    fn caller_output_files_survive_startup_command_and_cancellation_cleanup() {
1933        for outcome in [
1934            "timeout",
1935            "startup-exit",
1936            "server-exit",
1937            "command-exit",
1938            "cancel",
1939            "success",
1940        ] {
1941            let (owner, _, _) = StartupFiles::create(None).unwrap();
1942            let stdout = owner.directory.path().join("retained-stdout");
1943            let stderr = owner.directory.path().join("retained-stderr");
1944            let ending = match outcome {
1945                "timeout" => "exec sleep 30",
1946                "startup-exit" => "exit 41",
1947                "server-exit" => {
1948                    "printf '34567\\n' > \"$2\"; while [ ! -s \"$0.command\" ]; do sleep 0.02; done; exit 42"
1949                }
1950                _ => "printf '34567\\n' > \"$2\"; exec sleep 30",
1951            };
1952            let script = TestServerScript::new(
1953                outcome,
1954                &format!(
1955                    "#!/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"
1956                ),
1957            );
1958            let pid_file = script.path().with_extension("pid");
1959            let command_file = script.path().with_extension("command");
1960            let config = PocketIcStartupConfig::Spawn {
1961                server_binary: script.path(),
1962                timeout: Duration::from_millis(if outcome == "timeout" { 1000 } else { 2000 }),
1963                server_hard_ttl: None,
1964                server_idle_ttl: None,
1965                server_output_files: Some(((&stdout).into(), (&stderr).into())),
1966            };
1967            if outcome == "timeout" || outcome == "startup-exit" {
1968                let error = config.start_managed_server().err().unwrap();
1969                match (outcome, error.failure()) {
1970                    ("timeout", PocketIcStartupFailure::ReadinessTimeout { .. }) => {
1971                        assert!(error.output().stdout().contains("truncated"));
1972                        assert!(!error.output().stderr().contains("raw-stderr-end"));
1973                    }
1974                    ("startup-exit", PocketIcStartupFailure::ServerExited { status, .. }) => {
1975                        assert_eq!(status.code(), Some(41));
1976                    }
1977                    (_, error) => panic!("unexpected startup result: {error:?}"),
1978                }
1979            } else {
1980                let command_end = match outcome {
1981                    "command-exit" => "exit 37",
1982                    "success" => "exit 0",
1983                    _ => "exec sleep 30",
1984                };
1985                let result = config.run_command(
1986                    Command::new("/bin/sh")
1987                        .args([
1988                            "-c",
1989                            &format!("printf '%s' \"$$\" > \"$1\"; {command_end}"),
1990                            "fixture",
1991                        ])
1992                        .arg(&command_file),
1993                    || {
1994                        outcome == "cancel"
1995                            && fs::metadata(&command_file).is_ok_and(|m| m.len() > 0)
1996                    },
1997                );
1998                let result = result.as_ref().map_err(PocketIcStartupError::failure);
1999                match (outcome, result) {
2000                    ("command-exit", Ok(status)) => assert_eq!(status.code(), Some(37)),
2001                    ("success", Ok(status)) => assert!(status.success()),
2002                    ("server-exit", Err(PocketIcStartupFailure::ServerExited { status, .. })) => {
2003                        assert_eq!(status.code(), Some(42));
2004                    }
2005                    ("cancel", Err(PocketIcStartupFailure::CommandRun { source, .. })) => {
2006                        assert_eq!(source.kind(), std::io::ErrorKind::Interrupted);
2007                    }
2008                    (_, result) => panic!("unexpected command result: {result:?}"),
2009                }
2010                let pid = fs::read_to_string(&command_file).unwrap().parse().unwrap();
2011                assert!(process_state(pid).is_none_or(|state| state == 'Z'));
2012            }
2013            for (path, suffix) in [(&stdout, b"raw-stdout-end"), (&stderr, b"raw-stderr-end")] {
2014                let bytes = fs::read(path).unwrap();
2015                assert_eq!(bytes.len(), 20 * 1024 + suffix.len());
2016                assert!(bytes.ends_with(suffix));
2017                assert_eq!(
2018                    fs::metadata(path).unwrap().permissions().mode() & 0o777,
2019                    0o600
2020                );
2021            }
2022            let report = fs::read_to_string(&pid_file).unwrap();
2023            let mut lines = report.lines();
2024            assert_eq!(process_state(lines.next().unwrap().parse().unwrap()), None);
2025            assert!(
2026                !PathBuf::from(lines.next().unwrap())
2027                    .parent()
2028                    .unwrap()
2029                    .exists()
2030            );
2031            fs::remove_file(pid_file).unwrap();
2032        }
2033    }
2034
2035    #[cfg(unix)]
2036    #[test]
2037    fn caller_output_files_refuse_existing_entries_and_keep_partial_preparation() {
2038        use std::os::unix::fs::symlink;
2039
2040        let (owner, _, _) = StartupFiles::create(None).unwrap();
2041        let stdout = owner.directory.path().join("retained-stdout");
2042        let stderr = owner.directory.path().join("retained-stderr");
2043        let unrelated = owner.directory.path().join("unrelated");
2044        fs::write(&unrelated, b"original").unwrap();
2045        symlink(&unrelated, &stderr).unwrap();
2046        let error = StartupFiles::create(Some((stdout.clone(), stderr.clone())))
2047            .err()
2048            .unwrap();
2049        assert!(
2050            matches!(error.failure(), PocketIcStartupFailure::Io { source, .. } if source.kind() == std::io::ErrorKind::AlreadyExists)
2051        );
2052        assert!(stdout.is_file());
2053        assert_eq!(fs::read(&unrelated).unwrap(), b"original");
2054        fs::write(&stdout, b"retained attempt").unwrap();
2055        assert!(StartupFiles::create(Some((stdout.clone(), stderr.clone()))).is_err());
2056        assert_eq!(fs::read(&stdout).unwrap(), b"retained attempt");
2057        fs::remove_file(stderr.clone()).unwrap();
2058        assert!(
2059            Command::new("mkfifo")
2060                .arg(&stderr)
2061                .status()
2062                .unwrap()
2063                .success()
2064        );
2065        fs::remove_file(stdout.clone()).unwrap();
2066        assert!(StartupFiles::create(Some((stdout.clone(), stderr))).is_err());
2067        assert!(stdout.is_file());
2068    }
2069
2070    #[cfg(unix)]
2071    #[test]
2072    fn managed_startup_reports_an_exited_server_with_bounded_output() {
2073        let script = TestServerScript::new(
2074            "exit",
2075            "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nprintf 'synthetic server stdout'\nprintf 'synthetic bind failure' >&2\nexit 23\n",
2076        );
2077
2078        let result = script
2079            .config(Duration::from_secs(2))
2080            .build_instance(PocketIcBuilder::new().with_application_subnet());
2081
2082        let error = result.err().unwrap();
2083        let PocketIcStartupFailure::ServerExited {
2084            server_binary,
2085            status,
2086            ..
2087        } = error.failure()
2088        else {
2089            panic!("expected a structured server exit, got {error:?}");
2090        };
2091        assert_eq!(server_binary, &script.path());
2092        assert_eq!(status.code(), Some(23));
2093        assert_eq!(error.output().stdout(), "synthetic server stdout");
2094        assert_eq!(error.output().stderr(), "synthetic bind failure");
2095    }
2096
2097    #[cfg(unix)]
2098    #[test]
2099    fn managed_startup_rejects_oversized_port_files_and_cleans_up() {
2100        let script = TestServerScript::new(
2101            "oversized-port",
2102            "#!/bin/sh\nprintf '%s\\n%s\\n' \"$$\" \"$2\"\nprintf '34567\\n%064s' '' > \"$2.pending\"\nmv \"$2.pending\" \"$2\"\nexec sleep 30\n",
2103        );
2104        let result = script.config(Duration::from_secs(2)).start_managed_server();
2105        let error = result.err().unwrap();
2106        let PocketIcStartupFailure::InvalidServerPort { value, .. } = error.failure() else {
2107            panic!("oversized port publication must fail readiness");
2108        };
2109        assert!(value.contains("port file exceeds"));
2110        assert!(value.len() < 256);
2111        let mut lines = error.output().stdout().lines();
2112        let pid = lines.next().unwrap().parse::<u32>().unwrap();
2113        let port_path = PathBuf::from(lines.next().unwrap());
2114        assert!(!port_path.parent().unwrap().exists());
2115        assert_eq!(process_state(pid), None, "failed server must be reaped");
2116    }
2117
2118    #[cfg(unix)]
2119    #[test]
2120    fn managed_startup_terminates_a_server_that_never_becomes_ready() {
2121        let script = TestServerScript::new(
2122            "timeout",
2123            "#!/bin/sh\nif [ \"$1\" != \"--port-file\" ] || [ -e \"$2\" ]; then exit 97; fi\nexec sleep 30\n",
2124        );
2125        let timeout = Duration::from_millis(100);
2126        let started = Instant::now();
2127
2128        let result = script
2129            .config(timeout)
2130            .build_instance(PocketIcBuilder::new().with_application_subnet());
2131
2132        assert!(
2133            started.elapsed() < Duration::from_secs(2),
2134            "bounded startup should not wait for the sleeping child"
2135        );
2136        let error = result.err().unwrap();
2137        assert!(
2138            matches!(error.failure(), PocketIcStartupFailure::ReadinessTimeout {
2139            server_binary, timeout: actual_timeout,
2140        } if server_binary == &script.path() && *actual_timeout == timeout)
2141        );
2142        assert!(error.server_cleanup().is_none());
2143    }
2144
2145    #[cfg(unix)]
2146    #[test]
2147    fn managed_server_handle_exposes_process_id_url_output_and_raii_ownership() {
2148        let script = TestServerScript::new(
2149            "handle",
2150            "#!/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",
2151        );
2152
2153        let server = script
2154            .config(Duration::from_secs(2))
2155            .start_managed_server()
2156            .expect("start caller-owned managed server");
2157
2158        assert_eq!(server.url(), "http://127.0.0.1:34567/");
2159        assert_eq!(
2160            server.output().stdout(),
2161            format!("managed server ready: {}", server.process_id())
2162        );
2163        assert_eq!(server.output().stderr(), "");
2164        let pid = server.process_id();
2165        assert!(process_state(pid).is_some_and(|state| state != 'Z'));
2166        drop(server);
2167        assert_eq!(process_state(pid), None, "owned server must be reaped");
2168    }
2169
2170    #[cfg(unix)]
2171    #[test]
2172    fn managed_server_cleans_descendants_on_drop_timeout_and_exit() {
2173        for mode in ["drop", "timeout", "exit"] {
2174            let publish = if mode == "drop" {
2175                "printf '34567\\n' > \"$2\"\n"
2176            } else {
2177                ""
2178            };
2179            let finish = if mode == "exit" {
2180                "sleep 0.03\nexit 23\n"
2181            } else {
2182                "exec sleep 30\n"
2183            };
2184            let script = TestServerScript::new(
2185                mode,
2186                &format!("#!/bin/sh\nsleep 30 &\nprintf '%s' \"$!\"\n{publish}{finish}"),
2187            );
2188            let result = script
2189                .config(Duration::from_millis(300))
2190                .start_managed_server();
2191            let output = match result {
2192                Ok(server) => {
2193                    let output = server.output().stdout().to_owned();
2194                    drop(server);
2195                    output
2196                }
2197                Err(error) => {
2198                    match error.failure() {
2199                        PocketIcStartupFailure::ReadinessTimeout { .. } => {
2200                            assert_eq!(mode, "timeout");
2201                            assert!(error.server_cleanup().is_none());
2202                        }
2203                        PocketIcStartupFailure::ServerExited { status, .. } => {
2204                            assert_eq!(mode, "exit");
2205                            assert_eq!(status.code(), Some(23));
2206                        }
2207                        _ => panic!("unexpected {mode} startup result: {error}"),
2208                    }
2209                    error.output().stdout().to_owned()
2210                }
2211            };
2212            let pid = output
2213                .parse::<u32>()
2214                .expect("server published its descendant PID");
2215            let deadline = Instant::now() + Duration::from_secs(2);
2216            while process_state(pid).is_some_and(|state| state != 'Z') {
2217                assert!(
2218                    Instant::now() < deadline,
2219                    "{mode} left its descendant running"
2220                );
2221                std::thread::sleep(Duration::from_millis(10));
2222            }
2223        }
2224    }
2225
2226    #[cfg(unix)]
2227    #[test]
2228    fn managed_server_passes_an_explicit_hard_ttl() {
2229        let script = TestServerScript::new(
2230            "hard-ttl",
2231            "#!/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",
2232        );
2233
2234        let server = PocketIcStartupConfig::Spawn {
2235            server_binary: script.path(),
2236            timeout: Duration::from_secs(2),
2237            server_hard_ttl: Some(Duration::from_secs(17)),
2238            server_idle_ttl: None,
2239            server_output_files: None,
2240        }
2241        .start_managed_server()
2242        .expect("start managed server with an explicit hard TTL");
2243
2244        assert_eq!(server.url(), "http://127.0.0.1:34567/");
2245    }
2246
2247    #[cfg(unix)]
2248    #[test]
2249    #[ignore = "requires POCKET_IC_BIN=<caller-provided PocketIC server binary>"]
2250    fn caller_provided_server_publishes_port_constructs_instance_and_cleans_up() {
2251        let binary = std::env::var_os("POCKET_IC_BIN")
2252            .map(PathBuf::from)
2253            .expect("set POCKET_IC_BIN to the exact server binary");
2254        // Observe this exact child's port path without inspecting other startup
2255        // directories created concurrently.
2256        let wrapper = TestServerScript::new(
2257            "real-owned-instance",
2258            "#!/bin/sh\nprintf '%s\n%s\n' \"$$\" \"$4\" > \"$0.record\"\nexec \"$POCKET_IC_BIN\" \"$@\"\n",
2259        );
2260        let owned = PocketIcStartupConfig::Spawn {
2261            server_binary: wrapper.path(),
2262            timeout: Duration::from_secs(30),
2263            server_hard_ttl: Some(Duration::from_secs(60)),
2264            server_idle_ttl: None,
2265            server_output_files: None,
2266        }
2267        .build_instance(PocketIcBuilder::new().with_application_subnet())
2268        .expect("owned managed spawn must construct an instance");
2269        let record_file = wrapper.path().with_extension("record");
2270        let record = fs::read_to_string(&record_file).unwrap();
2271        let mut fields = record.lines();
2272        let pid = fields.next().unwrap().parse().unwrap();
2273        let port_path = PathBuf::from(fields.next().unwrap());
2274        let startup_directory = port_path.parent().unwrap();
2275        drop(owned);
2276        assert!(!startup_directory.exists());
2277        assert_eq!(process_state(pid), None);
2278        fs::remove_file(record_file).unwrap();
2279
2280        let server = PocketIcStartupConfig::Spawn {
2281            server_binary: (&binary).into(),
2282            timeout: Duration::from_secs(30),
2283            server_hard_ttl: Some(Duration::from_secs(60)),
2284            server_idle_ttl: None,
2285            server_output_files: None,
2286        }
2287        .start_managed_server()
2288        .expect("caller-provided PocketIC server must publish its port");
2289        let files = &server.server.files;
2290        let startup_directory = files.directory.path().to_path_buf();
2291
2292        assert!(files.port.is_file());
2293        let pocket_ic = PocketIcStartupConfig::Connect {
2294            server_url: (server.url()).into(),
2295            timeout: Duration::from_secs(30),
2296        }
2297        .build_instance(PocketIcBuilder::new().with_application_subnet())
2298        .expect("construct instance through caller-provided server");
2299
2300        drop(pocket_ic);
2301        drop(server);
2302        assert!(!startup_directory.exists());
2303    }
2304
2305    #[cfg(unix)]
2306    struct TestServerScript {
2307        path: PathBuf,
2308        #[expect(
2309            dead_code,
2310            reason = "retains directory ownership until cleanup or drop"
2311        )]
2312        directory: OwnedDirectory,
2313    }
2314
2315    #[cfg(unix)]
2316    impl TestServerScript {
2317        fn new(label: &str, contents: &str) -> Self {
2318            let directory = OwnedDirectory::new(
2319                create_unique_directory(
2320                    &std::env::temp_dir(),
2321                    &format!("ic-testkit-pocket-ic-{label}"),
2322                    0o700,
2323                    None,
2324                )
2325                .expect("create test server directory"),
2326            );
2327            let path = directory.path().join("server");
2328            write_executable_script(&path, contents).expect("write executable test script");
2329            Self { path, directory }
2330        }
2331
2332        fn path(&self) -> PathBuf {
2333            self.path.clone()
2334        }
2335
2336        fn config(&self, timeout: Duration) -> PocketIcStartupConfig {
2337            PocketIcStartupConfig::Spawn {
2338                server_binary: self.path(),
2339                timeout,
2340                server_hard_ttl: None,
2341                server_idle_ttl: None,
2342                server_output_files: None,
2343            }
2344        }
2345    }
2346}