Skip to main content

ic_testkit/pic/server_assets/
mod.rs

1//! Explicit, release-bound `PocketIC` assets for Rust fixtures and the CLI.
2//!
3//! [`check`] is offline and never sets up a missing bundle. [`setup`] explicitly
4//! provisions it. Callers retain namespace custody and select the bundle root;
5//! managed startup and application safety remain separate responsibilities.
6
7use super::POCKET_IC_SERVER_VERSION;
8use ic_host_artifacts::artifact::{Sha256Digest, copy_gzip, hash_gzip, hash_reader};
9use ic_host_fs::path::validate_physical_directory_allow_missing;
10use ic_host_fs::{durable, read::read_file_no_follow};
11use ic_host_process::{
12    child::CleanupPolicy,
13    tool::{
14        AdmittedTool, ExecutionContext, OutputLimit, OutputLimits, VersionSpec,
15        capture_group_command_with_cancellation,
16    },
17};
18use std::{
19    error::Error,
20    ffi::OsString,
21    fs::{self, File},
22    io,
23    path::{Path, PathBuf},
24    process::{Command, Stdio},
25    sync::atomic::{AtomicU64, Ordering},
26    time::Duration,
27};
28
29type Result<T> = std::result::Result<T, Box<dyn Error>>;
30const ARCHIVE_LIMIT: usize = 80 * 1024 * 1024;
31const EXECUTABLE_LIMIT: usize = 512 * 1024 * 1024;
32static SEQUENCE: AtomicU64 = AtomicU64::new(0);
33/// Default bundle root used by `ic-testkit-server`.
34pub const DEFAULT_DIRECTORY: &str = ".tools/ic-testkit-server";
35
36struct Asset {
37    host: &'static str,
38    digest: Sha256Digest,
39}
40
41fn write_evidence(path: &Path, bytes: &[u8]) -> Result<()> {
42    durable::write_bytes(
43        path,
44        durable::WriteOptions {
45            mode: durable::PublicationMode::Replace,
46            permissions: 0o666,
47        },
48        bytes,
49    )?;
50    Ok(())
51}
52
53fn selected_asset() -> Result<Asset> {
54    // Official GitHub release asset digests, reviewed 2026-10-09.
55    let (host, digest) = match (std::env::consts::OS, std::env::consts::ARCH) {
56        ("linux", "x86_64") => (
57            "x86_64-linux",
58            "131219d90dcf9bf6f3ed8ee02d8f55504ea24a6db382f5680675b7bd6b7ed3bf",
59        ),
60        ("macos", "x86_64") => (
61            "x86_64-darwin",
62            "af9ad2d781530a43556ef2d1c8f93db99a2425c6cabdc78520f61922399ed530",
63        ),
64        ("macos", "aarch64") => (
65            "arm64-darwin",
66            "9ae843fbb7ae6c6eb30137671c8629a80ef53b3a3652eb85b344847ac39f9fcd",
67        ),
68        _ => return Err("no reviewed PocketIC server asset for this host".into()),
69    };
70    Ok(Asset {
71        host,
72        digest: digest.parse()?,
73    })
74}
75
76fn root_path(directory: &Path) -> Result<PathBuf> {
77    if directory.as_os_str().is_empty() {
78        return Err("server directory must not be empty".into());
79    }
80    let absolute = if directory.is_absolute() {
81        directory.to_owned()
82    } else {
83        std::env::current_dir()?.join(directory)
84    };
85    if absolute
86        .as_os_str()
87        .as_encoded_bytes()
88        .iter()
89        .any(|byte| matches!(byte, b'\n' | b'\r'))
90    {
91        return Err("server directory and its ancestors must not contain line breaks".into());
92    }
93    validate_physical_directory_allow_missing(&absolute)?;
94    Ok(absolute.components().collect())
95}
96
97fn bundle_path(root: &Path, asset: &Asset) -> PathBuf {
98    root.join(format!("{}-{}", POCKET_IC_SERVER_VERSION, asset.host))
99}
100
101fn authenticated_archive(archive: &Path, digest: Sha256Digest) -> Result<Vec<u8>> {
102    let bytes = read_file_no_follow(archive, ARCHIVE_LIMIT)?;
103    hash_reader(bytes.as_slice(), ARCHIVE_LIMIT as u64)?.verify(digest)?;
104    Ok(bytes)
105}
106
107fn admit(executable: &Path, digest: Sha256Digest) -> Result<()> {
108    let directory = executable.parent().ok_or("missing executable parent")?;
109    AdmittedTool::admit_no_follow(
110        &VersionSpec {
111            executable,
112            executable_bytes: EXECUTABLE_LIMIT as u64,
113            version_arguments: &[OsString::from("--version")],
114        },
115        digest,
116        &format!("pocket-ic-server {POCKET_IC_SERVER_VERSION}"),
117        &ExecutionContext {
118            current_dir: directory,
119            environment: &[],
120        },
121        OutputLimits {
122            stdout: OutputLimit::Terminate(4096),
123            stderr: OutputLimit::Terminate(4096),
124            timeout: Some(Duration::from_secs(10)),
125        },
126    )?;
127    Ok(())
128}
129
130fn check_bundle(bundle: &Path, asset: &Asset) -> Result<PathBuf> {
131    let metadata = fs::symlink_metadata(bundle)?;
132    if !metadata.is_dir() || metadata.is_symlink() {
133        return Err("PocketIC bundle must be a physical directory".into());
134    }
135    let bytes = authenticated_archive(&bundle.join("archive.gz"), asset.digest)?;
136    let digest = hash_gzip(&bytes, ARCHIVE_LIMIT, EXECUTABLE_LIMIT as u64)?.sha256;
137    drop(bytes);
138    let executable = bundle.join("pocket-ic");
139    admit(&executable, digest)?;
140    Ok(executable)
141}
142
143/// Admit an existing reviewed bundle without downloading or changing it.
144///
145/// Authenticates the bounded archive before decoding, compares the executable's
146/// exact bytes, then runs bounded `--version` admission with an empty environment.
147/// Returns the absolute executable path, not ongoing custody of its namespace.
148/// Callers must prevent replacement between admission and managed startup.
149///
150/// # Errors
151/// Rejects unsupported hosts, redirected paths, missing or modified bundles,
152/// invalid archives, or failed executable/version admission.
153pub fn check(directory: &Path) -> Result<PathBuf> {
154    let asset = selected_asset()?;
155    check_bundle(&bundle_path(&root_path(directory)?, &asset), &asset)
156}
157
158/// Explicitly prepare or admit the reviewed bundle, retaining failed attempts.
159///
160/// Downloads only when the selected bundle is absent. Cooperating setups share
161/// one lock; existing bundles must pass the same offline [`check`] admission.
162/// `interrupted` lets the caller request bounded downloader cancellation without
163/// this library installing process-global signal handlers.
164///
165/// # Errors
166/// Returns path, lock, download, authentication, decoding, publication or
167/// executable/version failures. Retained evidence is never automatically removed.
168pub fn setup(directory: &Path, mut interrupted: impl FnMut() -> bool) -> Result<PathBuf> {
169    let asset = selected_asset()?;
170    setup_with(directory, &asset, |archive| {
171        let url = format!(
172            "https://github.com/dfinity/pocketic/releases/download/{POCKET_IC_SERVER_VERSION}/pocket-ic-{}.gz",
173            asset.host
174        );
175        let mut command = Command::new("curl");
176        command
177            .args([
178                "--proto",
179                "=https",
180                "--proto-redir",
181                "=https",
182                "--tlsv1.2",
183                "--fail",
184                "--silent",
185                "--show-error",
186                "--location",
187                "--connect-timeout",
188                "15",
189                "--max-time",
190                "300",
191                "--max-filesize",
192                "83886080",
193                "--output",
194            ])
195            .arg(archive)
196            .arg(url)
197            .stdin(Stdio::null())
198            .stdout(Stdio::piped())
199            .stderr(Stdio::piped());
200        let outcome = capture_group_command_with_cancellation(
201            &mut command,
202            OutputLimits {
203                stdout: OutputLimit::Terminate(4096),
204                stderr: OutputLimit::Terminate(64 * 1024),
205                timeout: Some(Duration::from_secs(310)),
206            },
207            CleanupPolicy::KillAndWait,
208            None,
209            &mut interrupted,
210        )
211        .and_then(ic_host_process::tool::CompletedExecution::require_success);
212        let stderr = match &outcome {
213            Ok(completed) => Some(completed.stderr.as_slice()),
214            Err(error) => error.evidence().map(|evidence| evidence.stderr.as_slice()),
215        };
216        if let Some(stderr) = stderr
217            && let Err(record_error) = write_evidence(
218                &archive
219                    .parent()
220                    .ok_or("missing archive parent")?
221                    .join("download.stderr"),
222                stderr,
223            )
224        {
225            if outcome.is_ok() {
226                return Err(record_error);
227            }
228            // Recording evidence must not replace the failed download's cause.
229            eprintln!("could not record download stderr: {record_error}");
230        }
231        outcome?;
232        Ok(())
233    })
234}
235
236fn setup_with(
237    directory: &Path,
238    asset: &Asset,
239    download: impl FnOnce(&Path) -> Result<()>,
240) -> Result<PathBuf> {
241    let root = root_path(directory)?;
242    // Namespace custody remains with the caller. All cooperating setups serialize
243    // through Host's admitted regular lock; checks are read-only.
244    let lock = durable::open_regular_lock_file_with_parents(&root.join(".setup-v1.lock"))?;
245    durable::lock_exclusive(&lock)?;
246    let bundle = bundle_path(&root, asset);
247    let attempt = root.join(format!(
248        ".setup-v1-{}-{}",
249        std::process::id(),
250        SEQUENCE.fetch_add(1, Ordering::Relaxed)
251    ));
252    let staging_directory = match fs::symlink_metadata(&bundle) {
253        Ok(_) => {
254            check_bundle(&bundle, asset)?;
255            None
256        }
257        Err(error) if error.kind() == io::ErrorKind::NotFound => {
258            let held = durable::create_private_directory(&attempt)?;
259            eprintln!("PocketIC setup evidence: {}", attempt.display());
260            if let Err(error) = install(&attempt, asset, download) {
261                if let Err(record_error) =
262                    write_evidence(&attempt.join("failure.txt"), error.to_string().as_bytes())
263                {
264                    eprintln!("could not record setup failure: {record_error}");
265                }
266                return Err(error);
267            }
268            Some(held)
269        }
270        Err(error) => return Err(error.into()),
271    };
272    // Host owns no-replace publication and phase-aware durability failures.
273    // Fresh staging must retain its original directory identity. Recovery admits
274    // the installed bundle again before Host synchronizes its parent.
275    durable::commit_existing_directory_with(
276        &attempt,
277        &bundle,
278        |selected, path| -> io::Result<()> {
279            if let Some(held) = &staging_directory {
280                durable::admit_directory(path, held)?;
281            }
282            selected.sync_all()?;
283            Ok(())
284        },
285        |_, _| Ok(()),
286    )?;
287    eprintln!("PocketIC setup evidence retained: {}", bundle.display());
288    Ok(bundle.join("pocket-ic"))
289}
290
291fn install(
292    attempt: &Path,
293    asset: &Asset,
294    download: impl FnOnce(&Path) -> Result<()>,
295) -> Result<()> {
296    let archive = attempt.join("archive.gz");
297    download(&archive)?;
298    let bytes = authenticated_archive(&archive, asset.digest)?;
299    File::open(&archive)?.sync_all()?;
300    let executable = attempt.join("pocket-ic");
301    let identity = durable::write_with(
302        &executable,
303        durable::WriteOptions {
304            mode: durable::PublicationMode::CreateNew,
305            permissions: 0o755,
306        },
307        |file| copy_gzip(&bytes, file, ARCHIVE_LIMIT, EXECUTABLE_LIMIT as u64),
308    )?;
309    drop(bytes);
310    // PocketIC requires its canonical basename. The whole directory is private
311    // and unselected until this admission succeeds; no existing bundle is replaced.
312    if let Err(error) = admit(&executable, identity.sha256) {
313        if let Some(evidence) = error
314            .downcast_ref::<ic_host_process::tool::ToolError>()
315            .and_then(|error| error.evidence())
316        {
317            for (name, bytes) in [
318                ("version.stdout", &evidence.stdout),
319                ("version.stderr", &evidence.stderr),
320            ] {
321                if let Err(record_error) = write_evidence(&attempt.join(name), bytes) {
322                    eprintln!("could not record version evidence: {record_error}");
323                }
324            }
325        }
326        return Err(error);
327    }
328    Ok(())
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use ic_host_artifacts::artifact::encode_gzip;
335    use ic_host_process::{
336        child::OwnedChild,
337        tool::{SuccessfulExit, communicate_child},
338    };
339    use std::os::unix::fs::symlink;
340
341    fn run_in_subprocess() -> bool {
342        let current = std::thread::current();
343        let name = current.name().expect("registered asset test name");
344        if std::env::var("IC_TESTKIT_ASSET_CASE").as_deref() == Ok(name) {
345            return false;
346        }
347        // A library sibling's fork can retain a writable executable descriptor.
348        // Re-exec before writing fixtures so only this case owns their lifetime.
349        let mut child = OwnedChild::spawn(
350            Command::new(std::env::current_exe().expect("library test executable"))
351                .args(["--exact", name, "--nocapture"])
352                .env("IC_TESTKIT_ASSET_CASE", name)
353                .stdin(Stdio::null())
354                .stdout(Stdio::piped())
355                .stderr(Stdio::piped()),
356            CleanupPolicy::KillAndWait,
357        )
358        .expect("spawn isolated asset test");
359        let completed = communicate_child(
360            &mut child,
361            None,
362            OutputLimits {
363                stdout: OutputLimit::Terminate(64 * 1024),
364                stderr: OutputLimit::Terminate(64 * 1024),
365                timeout: Some(Duration::from_secs(120)),
366            },
367            SuccessfulExit::Cleanup,
368            &mut || false,
369        )
370        .expect("capture and reap isolated asset test");
371        assert!(
372            completed.status.success(),
373            "isolated asset test failed: stdout={} stderr={}",
374            String::from_utf8_lossy(&completed.stdout),
375            String::from_utf8_lossy(&completed.stderr),
376        );
377        true
378    }
379
380    struct Fixture {
381        root: ic_host_fs::testing::FixtureDirectory,
382    }
383    impl Fixture {
384        fn new() -> Self {
385            let root = ic_host_fs::testing::FixtureDirectory::new(
386                &std::env::temp_dir(),
387                "testkit-provision",
388            )
389            .unwrap();
390            Self { root }
391        }
392    }
393    fn archive(version: &str) -> (Asset, Vec<u8>) {
394        let script = format!("#!/bin/sh\nprintf 'pocket-ic-server {version}\\n'\n");
395        let mut bytes = Vec::new();
396        encode_gzip(script.as_bytes(), &mut bytes, 1, 65536).unwrap();
397        (
398            Asset {
399                host: "fixture",
400                digest: Sha256Digest::compute(&bytes),
401            },
402            bytes,
403        )
404    }
405
406    #[test]
407    fn authenticated_setup_reuses_offline_and_refuses_changed_bytes_before_execution() {
408        if run_in_subprocess() {
409            return;
410        }
411        let root = Fixture::new();
412        let (asset, bytes) = archive(POCKET_IC_SERVER_VERSION);
413        let executable = setup_with(root.root.path(), &asset, |path| {
414            fs::write(path, &bytes)?;
415            Ok(())
416        })
417        .unwrap();
418        let original = fs::read(&executable).unwrap();
419        assert_eq!(
420            setup_with(root.root.path(), &asset, |_| panic!(
421                "verified reuse must not download"
422            ))
423            .unwrap(),
424            executable
425        );
426        let entries = fs::read_dir(root.root.path()).unwrap().count();
427        assert_eq!(
428            check_bundle(&bundle_path(root.root.path(), &asset), &asset).unwrap(),
429            executable
430        );
431        assert_eq!(fs::read_dir(root.root.path()).unwrap().count(), entries);
432        let marker = root.root.path().join("executed");
433        fs::write(
434            &executable,
435            format!("#!/bin/sh\ntouch '{}'\n", marker.display()),
436        )
437        .unwrap();
438        assert!(check_bundle(&bundle_path(root.root.path(), &asset), &asset).is_err());
439        assert!(!marker.exists());
440        fs::write(&executable, original).unwrap();
441        assert!(check_bundle(&bundle_path(root.root.path(), &asset), &asset).is_ok());
442        let saved = root.root.path().join("saved");
443        fs::rename(&executable, &saved).unwrap();
444        symlink(&saved, &executable).unwrap();
445        assert!(check_bundle(&bundle_path(root.root.path(), &asset), &asset).is_err());
446    }
447
448    #[test]
449    fn offline_check_authenticates_before_decoding_and_rejects_invalid_gzip() {
450        use ic_host_artifacts::artifact::{ArtifactError, GzipError};
451
452        if run_in_subprocess() {
453            return;
454        }
455
456        let root = Fixture::new();
457        let (mut asset, original) = archive(POCKET_IC_SERVER_VERSION);
458        let executable = setup_with(root.root.path(), &asset, |path| {
459            fs::write(path, &original)?;
460            Ok(())
461        })
462        .unwrap();
463        let installed = fs::read(&executable).unwrap();
464        let bundle = bundle_path(root.root.path(), &asset);
465        let path = bundle.join("archive.gz");
466
467        // Both authentication and decoding would fail; authentication wins.
468        fs::write(&path, b"not gzip").unwrap();
469        let error = check_bundle(&bundle, &asset).unwrap_err();
470        assert!(matches!(
471            error.downcast_ref::<ArtifactError>(),
472            Some(ArtifactError::DigestMismatch { .. })
473        ));
474
475        let mut bad_crc = original.clone();
476        let crc = bad_crc.len() - 8;
477        bad_crc[crc] ^= 1;
478        let mut bad_length = original.clone();
479        let length = bad_length.len() - 4;
480        bad_length[length] ^= 1;
481        for bytes in [
482            b"not gzip".to_vec(),
483            original[..original.len() - 1].to_vec(),
484            bad_crc,
485            bad_length,
486            [original.as_slice(), b"trailing"].concat(),
487            [original.as_slice(), original.as_slice()].concat(),
488        ] {
489            fs::write(&path, &bytes).unwrap();
490            asset.digest = Sha256Digest::compute(&bytes);
491            let error = check_bundle(&bundle, &asset).unwrap_err();
492            // Gzip refusal occurs before executable admission/version execution.
493            assert!(error.downcast_ref::<GzipError>().is_some());
494            assert_eq!(fs::read(&executable).unwrap(), installed);
495            assert_eq!(fs::read(&path).unwrap(), bytes);
496        }
497        fs::write(&path, &original).unwrap();
498        asset.digest = Sha256Digest::compute(&original);
499        assert_eq!(check_bundle(&bundle, &asset).unwrap(), executable);
500    }
501
502    #[test]
503    fn setup_rejects_corrupt_payloads_without_execution_or_publication() {
504        use ic_host_artifacts::artifact::GzipError;
505
506        if run_in_subprocess() {
507            return;
508        }
509        let root = Fixture::new();
510        let marker = root.root.path().join("executed");
511        let script = format!("#!/bin/sh\nprintf executed > '{}'\n", marker.display());
512        let mut original = Vec::new();
513        encode_gzip(script.as_bytes(), &mut original, 1, 65536).unwrap();
514        let mut bad_crc = original.clone();
515        let crc = bad_crc.len() - 8;
516        bad_crc[crc] ^= 1;
517        for bytes in [
518            bad_crc,
519            original[..original.len() - 1].to_vec(),
520            [original.as_slice(), b"trailing"].concat(),
521        ] {
522            let asset = Asset {
523                host: "fixture",
524                digest: Sha256Digest::compute(&bytes),
525            };
526            let error = setup_with(root.root.path(), &asset, |path| {
527                fs::write(path, &bytes)?;
528                Ok(())
529            })
530            .unwrap_err();
531            assert!(matches!(
532                error.downcast_ref::<durable::NamedWriteError<GzipError>>(),
533                Some(durable::NamedWriteError::Producer { .. })
534            ));
535            assert!(!marker.exists());
536            assert!(!bundle_path(root.root.path(), &asset).exists());
537            assert!(fs::read_dir(root.root.path()).unwrap().any(|entry| {
538                let path = entry.unwrap().path();
539                path.join("failure.txt").is_file()
540                    && fs::read(path.join("archive.gz")).ok().as_deref() == Some(bytes.as_slice())
541            }));
542        }
543    }
544
545    #[test]
546    fn failed_setup_retains_evidence_and_previous_bundles_then_can_retry() {
547        if run_in_subprocess() {
548            return;
549        }
550        let root = Fixture::new();
551        let previous = root.root.path().join("previous-version");
552        fs::create_dir(&previous).unwrap();
553        fs::write(previous.join("pocket-ic"), b"previous bytes").unwrap();
554        let (asset, bytes) = archive(POCKET_IC_SERVER_VERSION);
555        assert!(
556            setup_with(root.root.path(), &asset, |path| {
557                fs::write(path, b"partial download")?;
558                Err("interrupted download".into())
559            })
560            .is_err()
561        );
562        assert!(!bundle_path(root.root.path(), &asset).exists());
563        let failed = fs::read_dir(root.root.path())
564            .unwrap()
565            .find_map(|entry| {
566                let path = entry.unwrap().path();
567                path.join("failure.txt").is_file().then_some(path)
568            })
569            .unwrap();
570        assert_eq!(
571            fs::read(failed.join("archive.gz")).unwrap(),
572            b"partial download"
573        );
574        assert!(
575            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
576                let _ = setup_with(root.root.path(), &asset, |path| {
577                    fs::write(path, b"interrupted candidate")?;
578                    panic!("injected interruption before admission");
579                });
580            }))
581            .is_err()
582        );
583        assert!(!bundle_path(root.root.path(), &asset).exists());
584        assert!(fs::read_dir(root.root.path()).unwrap().any(|entry| {
585            fs::read(entry.unwrap().path().join("archive.gz"))
586                .ok()
587                .as_deref()
588                == Some(b"interrupted candidate")
589        }));
590        assert!(
591            setup_with(root.root.path(), &asset, |path| {
592                fs::write(path, &bytes)?;
593                Ok(())
594            })
595            .is_ok()
596        );
597        assert!(failed.join("failure.txt").is_file());
598        assert_eq!(
599            fs::read(previous.join("pocket-ic")).unwrap(),
600            b"previous bytes"
601        );
602    }
603
604    #[test]
605    fn digest_decode_and_version_failures_never_publish() {
606        if run_in_subprocess() {
607            return;
608        }
609        for mode in [0, 1, 2] {
610            let root = Fixture::new();
611            let (mut asset, mut bytes) = archive("15.0.0");
612            if mode == 0 {
613                asset.digest = Sha256Digest::compute(b"wrong");
614            }
615            if mode == 1 {
616                bytes = b"not gzip".to_vec();
617                asset.digest = Sha256Digest::compute(&bytes);
618            }
619            assert!(
620                setup_with(root.root.path(), &asset, |path| {
621                    fs::write(path, &bytes)?;
622                    Ok(())
623                })
624                .is_err()
625            );
626            assert!(!bundle_path(root.root.path(), &asset).exists());
627        }
628    }
629
630    #[test]
631    fn redirected_paths_are_refused_without_touching_the_target() {
632        if run_in_subprocess() {
633            return;
634        }
635        let root = Fixture::new();
636        let (asset, _) = archive(POCKET_IC_SERVER_VERSION);
637        let target = root.root.path().join("target");
638        fs::create_dir(&target).unwrap();
639        let redirected = root.root.path().join("redirected");
640        symlink(&target, &redirected).unwrap();
641        assert!(
642            setup_with(&redirected.join("child"), &asset, |_| panic!(
643                "redirected ancestor reached downloader"
644            ))
645            .is_err()
646        );
647        assert_eq!(fs::read_dir(&target).unwrap().count(), 0);
648        symlink(&target, root.root.path().join(".setup-v1.lock")).unwrap();
649        assert!(
650            setup_with(root.root.path(), &asset, |_| panic!(
651                "redirected lock reached downloader"
652            ))
653            .is_err()
654        );
655    }
656
657    #[test]
658    fn replaced_staging_directory_is_not_published() {
659        if run_in_subprocess() {
660            return;
661        }
662        let root = Fixture::new();
663        let (asset, bytes) = archive(POCKET_IC_SERVER_VERSION);
664        let retained = root.root.path().join("retained-original-stage");
665        let error = setup_with(root.root.path(), &asset, |archive| {
666            fs::write(archive, &bytes)?;
667            let stage = archive.parent().unwrap();
668            fs::rename(stage, &retained)?;
669            fs::create_dir(stage)?;
670            fs::write(archive, &bytes)?;
671            Ok(())
672        })
673        .expect_err("replacement must not inherit the held directory claim");
674        assert!(matches!(
675            error.downcast_ref::<durable::DirectoryCommitError<io::Error>>(),
676            Some(durable::DirectoryCommitError::Prepare(source))
677                if source.kind() == io::ErrorKind::InvalidInput
678        ));
679        assert!(!bundle_path(root.root.path(), &asset).exists());
680        assert_eq!(fs::read(retained.join("archive.gz")).unwrap(), bytes);
681    }
682
683    #[test]
684    fn occupied_destination_preserves_both_bundle_and_verified_staging() {
685        if run_in_subprocess() {
686            return;
687        }
688        let root = Fixture::new();
689        let (asset, bytes) = archive(POCKET_IC_SERVER_VERSION);
690        let bundle = bundle_path(root.root.path(), &asset);
691        let mut attempt = None;
692        let error = setup_with(root.root.path(), &asset, |archive| {
693            fs::write(archive, &bytes)?;
694            attempt = archive.parent().map(Path::to_owned);
695            fs::create_dir(&bundle)?;
696            fs::write(bundle.join("unrelated"), b"retained destination")?;
697            Ok(())
698        })
699        .unwrap_err();
700        assert!(matches!(
701            error.downcast_ref::<durable::DirectoryCommitError<io::Error>>(),
702            Some(durable::DirectoryCommitError::Conflict)
703        ));
704        assert_eq!(
705            fs::read(bundle.join("unrelated")).unwrap(),
706            b"retained destination"
707        );
708        let attempt = attempt.unwrap();
709        assert_eq!(fs::read(attempt.join("archive.gz")).unwrap(), bytes);
710        assert!(attempt.join("pocket-ic").is_file());
711    }
712
713    #[test]
714    fn concurrent_setups_download_once_and_recheck_under_the_lock() {
715        if run_in_subprocess() {
716            return;
717        }
718        let root = Fixture::new();
719        let (asset, bytes) = archive(POCKET_IC_SERVER_VERSION);
720        let calls = AtomicU64::new(0);
721        std::thread::scope(|scope| {
722            let handles = (0..2)
723                .map(|_| {
724                    scope.spawn(|| {
725                        setup_with(root.root.path(), &asset, |path| {
726                            calls.fetch_add(1, Ordering::Relaxed);
727                            fs::write(path, &bytes)?;
728                            Ok(())
729                        })
730                        .unwrap()
731                    })
732                })
733                .collect::<Vec<_>>();
734            for handle in handles {
735                assert_eq!(
736                    handle.join().unwrap(),
737                    bundle_path(root.root.path(), &asset).join("pocket-ic")
738                );
739            }
740        });
741        assert_eq!(calls.load(Ordering::Relaxed), 1);
742    }
743}