Skip to main content

eggpack_core/
builder.rs

1//! Explicit Cargo build bindings, command descriptions, and bounded process execution.
2
3use crate::{BuildStrategy, CompatibilityFloor, ReleasePlan};
4use command_group::CommandGroup;
5use eggpack_contract::{DistributionContract, ExpandedAssets};
6use serde::{Deserialize, Serialize};
7use std::{
8    collections::{BTreeMap, BTreeSet},
9    ffi::OsString,
10    fs,
11    io::{Read, Write},
12    path::{Path, PathBuf},
13    process::{Command, Stdio},
14    sync::{Arc, Mutex},
15    thread,
16    time::{Duration, Instant},
17};
18
19/// Retained-output bound the builder commands request by default.
20const MAX_OUTPUT: usize = 256 * 1024;
21/// Ceiling for the retained-output bound of any bounded process.
22///
23/// This is the single output bound the shared runner enforces. The builder
24/// commands keep their tighter default (`MAX_OUTPUT`); the ceiling is wide
25/// enough to admit the consumer-validator case, whose configured bound is
26/// larger and is validated by its own owner.
27const MAX_PROCESS_OUTPUT: usize = 8 * 1024 * 1024;
28/// Wall-time bound for the sanitized `git rev-parse` verification spawn.
29const GIT_TIMEOUT: Duration = Duration::from_secs(30);
30/// Retained-output bound for the `git` verification spawn: a bare object name.
31const GIT_OUTPUT_LIMIT: usize = 4 * 1024;
32/// Floor on the post-reap drain budget.
33///
34/// On the timeout, cancellation, and output-limit paths the caller's deadline
35/// has already passed, but the killed process group's pipes still have to
36/// reach EOF, so the drain budget never collapses to zero.
37const MIN_DRAIN_GRACE: Duration = Duration::from_secs(1);
38/// Ceiling on the post-reap drain budget, so a generous caller deadline does
39/// not turn a parked reader into a long wait.
40///
41/// The group is killed on the failure paths, but a descendant that outlived a
42/// normally-exited child keeps its own pipe open, and a longer wait would not
43/// produce EOF. The pipes are either closed already or held open by a leaked
44/// descendant, so the run fails closed instead.
45const MAX_DRAIN_GRACE: Duration = Duration::from_secs(2);
46
47/// Restore POSIX exec bits on a transferred candidate before spawning it.
48///
49/// Artifact transfer between jobs strips exec bits; the recorded
50/// size/digest cover bytes only, so restoring mode cannot change identity.
51fn ensure_candidate_executable(path: &Path) -> Result<(), BuildError> {
52    #[cfg(unix)]
53    {
54        use std::os::unix::fs::PermissionsExt;
55        let meta =
56            fs::symlink_metadata(path).map_err(|_| build_err("candidate is not executable"))?;
57        if meta.file_type().is_symlink() || !meta.is_file() {
58            return Err(build_err("candidate is not executable"));
59        }
60        let mut permissions = meta.permissions();
61        permissions.set_mode(permissions.mode() | 0o111);
62        fs::set_permissions(path, permissions)
63            .map_err(|_| build_err("candidate is not executable"))?;
64        Ok(())
65    }
66    #[cfg(not(unix))]
67    {
68        let _ = path;
69        Ok(())
70    }
71}
72
73/// Contract logical location for one Cargo-produced executable.
74#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
75#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
76pub enum LogicalOutputSelector {
77    /// Direct artifact executable.
78    Direct,
79    /// Bundle entry by its contract order index.
80    BundleEntry {
81        /// Zero-based contract entry index.
82        index: usize,
83    },
84    /// Archive member by its exact contract source.
85    ArchiveMember {
86        /// Contract archive source.
87        source: String,
88    },
89}
90
91/// A Cargo package and binary target explicitly bound to a logical contract slot.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(deny_unknown_fields)]
94pub struct BuildBinding {
95    /// Logical contract output slot.
96    pub selector: LogicalOutputSelector,
97    /// Cargo package name.
98    pub package: String,
99    /// Cargo binary target name.
100    pub binary: String,
101}
102
103/// Strict producer-side BuildBindings schema version 1.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct BuildBindingsV1 {
107    /// Schema version, exactly 1.
108    pub schema_version: u32,
109    /// Bindings for canonical target triple.
110    pub targets: BTreeMap<String, Vec<BuildBinding>>,
111}
112
113/// Failure from producer build planning or execution.
114#[derive(Debug, Clone, PartialEq, Eq)]
115pub struct BuildError(pub(crate) String);
116impl std::fmt::Display for BuildError {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        f.write_str(&self.0)
119    }
120}
121impl std::error::Error for BuildError {}
122fn build_err(s: &str) -> BuildError {
123    BuildError(s.to_owned())
124}
125
126#[derive(Clone, Copy)]
127enum ExecutableAllowance {
128    Builder,
129    Candidate,
130    Qemu,
131    Git,
132    Interpreter,
133}
134
135/// Cancellation source observed by the bounded runner.
136///
137/// The runner polls it on the same cadence as the deadline, so a cancelled
138/// run ends promptly instead of at some later point.
139enum Cancellation<'a> {
140    /// No cancellation source; only the deadline applies.
141    None,
142    /// The builder's own cancellation flag.
143    Build(&'a BuildCancellation),
144    /// A caller-owned atomic flag.
145    Flag(&'a std::sync::atomic::AtomicBool),
146}
147
148impl Cancellation<'_> {
149    fn is_cancelled(&self) -> bool {
150        match self {
151            Cancellation::None => false,
152            Cancellation::Build(cancellation) => cancellation.is_cancelled(),
153            Cancellation::Flag(flag) => flag.load(std::sync::atomic::Ordering::SeqCst),
154        }
155    }
156}
157
158/// Explicit shell-free process command. Executable and argv are separate OS arguments.
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct CommandSpec {
161    /// Executable path or tool name.
162    pub executable: String,
163    /// Ordered arguments.
164    pub args: Vec<String>,
165    /// Working directory.
166    pub cwd: PathBuf,
167    /// Explicit environment overrides only.
168    pub env: BTreeMap<String, String>,
169    /// Maximum wall time.
170    pub timeout: Duration,
171    /// Maximum retained stdout bytes.
172    pub stdout_limit: usize,
173    /// Maximum retained stderr bytes.
174    pub stderr_limit: usize,
175    /// Optional tool version substring checked internally and never returned.
176    pub expected_stdout: Option<String>,
177    /// Optional exact trimmed-stdout match checked internally and never returned.
178    ///
179    /// Used where containment would be weaker than the invariant: the tool must
180    /// emit one exact value, not merely contain it among other output.
181    pub expected_stdout_exact: Option<String>,
182}
183
184/// Exact source command associated with a logical output.
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct BoundCommand {
187    /// Output selector.
188    pub selector: LogicalOutputSelector,
189    /// Cargo package.
190    pub package: String,
191    /// Cargo binary target.
192    pub binary: String,
193    /// Process description.
194    pub command: CommandSpec,
195}
196
197/// Explicit shell-free interpreter command for a bounded consumer-validator run.
198///
199/// The argument vector is OS-native so a validated absolute path reaches the
200/// interpreter byte-exact, and the executable stays inside the finite
201/// interpreter allowlist the shared runner enforces.
202#[derive(Debug, Clone, PartialEq, Eq)]
203pub struct InterpreterCommandSpec {
204    /// Interpreter executable name.
205    pub executable: String,
206    /// Ordered OS-native arguments.
207    pub args: Vec<OsString>,
208    /// Working directory.
209    pub cwd: PathBuf,
210    /// Explicit environment overrides only.
211    pub env: BTreeMap<String, String>,
212    /// Maximum wall time.
213    pub timeout: Duration,
214    /// Maximum retained stdout bytes.
215    pub stdout_limit: usize,
216    /// Maximum retained stderr bytes.
217    pub stderr_limit: usize,
218    /// Optional tool version substring checked internally and never returned.
219    pub expected_stdout: Option<String>,
220}
221
222/// Command exit classification.
223#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
224pub enum CommandOutcome {
225    /// Process exited with success.
226    Success,
227    /// Process exited nonzero.
228    Failed(i32),
229    /// Deadline exceeded; process group cleanup completed.
230    TimedOut,
231    /// Caller cancelled execution; process-group cleanup completed.
232    Cancelled,
233    /// Output exceeded a configured bound.
234    OutputLimitExceeded,
235}
236
237/// Cloneable caller cancellation flag for bounded builder work.
238#[derive(Debug, Clone, Default)]
239pub struct BuildCancellation(std::sync::Arc<std::sync::atomic::AtomicBool>);
240impl BuildCancellation {
241    /// Create an active cancellation flag.
242    pub fn new() -> Self {
243        Self::default()
244    }
245    /// Request cancellation; an active child process group is killed and waited for.
246    pub fn cancel(&self) {
247        self.0.store(true, std::sync::atomic::Ordering::SeqCst);
248    }
249    pub(crate) fn is_cancelled(&self) -> bool {
250        self.0.load(std::sync::atomic::Ordering::SeqCst)
251    }
252}
253
254/// Bounded process evidence with no environment dump.
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256pub struct ProcessEvidence {
257    /// Outcome classification.
258    pub outcome: CommandOutcome,
259    /// Number of retained stdout bytes.
260    pub stdout_bytes: usize,
261    /// Number of retained stderr bytes.
262    pub stderr_bytes: usize,
263}
264
265/// Candidate bytes produced for a declared logical output.
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub struct CandidateArtifact {
268    /// Canonical target triple.
269    pub target: String,
270    /// Logical output slot.
271    pub selector: LogicalOutputSelector,
272    /// Explicit source package.
273    pub package: String,
274    /// Explicit binary target.
275    pub binary: String,
276    /// Private candidate path.
277    pub path: PathBuf,
278    /// Candidate size in bytes.
279    pub size: u64,
280}
281
282/// Result of a single bounded build attempt.
283#[derive(Debug, Clone, PartialEq, Eq)]
284pub struct BuildAttempt {
285    /// Release identity from the supplied ReleasePlan.
286    pub release_id: String,
287    /// Source revision from the supplied ReleasePlan.
288    pub source_revision: String,
289    /// Canonical target triple.
290    pub target: String,
291    /// Selected strategy.
292    pub strategy: BuildStrategy,
293    /// Tool summary, without environment values.
294    pub tool_summary: String,
295    /// Bounded process evidence.
296    pub process: ProcessEvidence,
297    /// Validated candidate outputs.
298    pub candidates: Vec<CandidateArtifact>,
299}
300
301impl BuildBindingsV1 {
302    /// Strictly parse TOML bindings.
303    pub fn from_toml(text: &str) -> Result<Self, BuildError> {
304        let value: Self =
305            toml::from_str(text).map_err(|_| build_err("invalid BuildBindings TOML"))?;
306        value.validate_shape()?;
307        Ok(value)
308    }
309    fn validate_shape(&self) -> Result<(), BuildError> {
310        if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > 256 {
311            return Err(build_err("invalid BuildBindings version or target count"));
312        }
313        for (target, bindings) in &self.targets {
314            if target.is_empty() || bindings.is_empty() || bindings.len() > 256 {
315                return Err(build_err("invalid BuildBindings target or binding count"));
316            }
317            let mut slots = BTreeSet::new();
318            for b in bindings {
319                if !slots.insert(&b.selector)
320                    || !valid_identifier(&b.package)
321                    || !valid_identifier(&b.binary)
322                {
323                    return Err(build_err("duplicate slot or invalid Cargo identifier"));
324                }
325                if let LogicalOutputSelector::ArchiveMember { source } = &b.selector {
326                    if source.is_empty()
327                        || source.len() > 255
328                        || source.starts_with('/')
329                        || source
330                            .split('/')
331                            .any(|p| p.is_empty() || p == "." || p == "..")
332                    {
333                        return Err(build_err("invalid archive member source"));
334                    }
335                }
336            }
337        }
338        Ok(())
339    }
340    /// Validate that each plan target's bindings exactly cover Cargo executable contract slots.
341    pub fn validate_for(
342        &self,
343        contract: &DistributionContract,
344        plan: &ReleasePlan,
345    ) -> Result<(), BuildError> {
346        self.validate_shape()?;
347        for target in &plan.targets {
348            let bindings = self
349                .targets
350                .get(&target.target)
351                .ok_or_else(|| build_err("missing target bindings"))?;
352            let expanded = contract
353                .expand(&target.target, &plan.release_id)
354                .map_err(|_| build_err("contract target expansion failed"))?;
355            let expected: BTreeSet<LogicalOutputSelector> = match expanded.assets {
356                ExpandedAssets::Direct(_) => [LogicalOutputSelector::Direct].into_iter().collect(),
357                ExpandedAssets::Bundle(b) => (0..b.entries.len())
358                    .map(|index| LogicalOutputSelector::BundleEntry { index })
359                    .collect(),
360                ExpandedAssets::Archive(a) => a
361                    .members
362                    .into_iter()
363                    .map(|m| LogicalOutputSelector::ArchiveMember { source: m.source })
364                    .collect(),
365            };
366            let actual: BTreeSet<_> = bindings.iter().map(|b| b.selector.clone()).collect();
367            if actual != expected {
368                return Err(build_err(
369                    "bindings do not exactly cover contract Cargo slots",
370                ));
371            }
372        }
373        if self
374            .targets
375            .keys()
376            .any(|k| !plan.targets.iter().any(|t| &t.target == k))
377        {
378            return Err(build_err("bindings include target outside ReleasePlan"));
379        }
380        Ok(())
381    }
382}
383fn valid_identifier(s: &str) -> bool {
384    !s.is_empty()
385        && s.len() <= 128
386        && s.bytes()
387            .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.'))
388}
389
390/// Construct the only supported Cargo command for a planned logical output.
391pub fn cargo_command(
392    target: &crate::PlannedTarget,
393    binding: &BuildBinding,
394    cwd: &Path,
395    target_dir: &Path,
396    timeout: Duration,
397) -> Result<CommandSpec, BuildError> {
398    if !valid_identifier(&binding.package) || !valid_identifier(&binding.binary) {
399        return Err(build_err("invalid Cargo identifier"));
400    }
401    let rustup = target.policy.toolchain.rust.as_str();
402    // Built by named position rather than index: the target triple is written
403    // once and never patched afterwards, so inserting a flag can no longer
404    // leave the floor override pointing at an unrelated argument.
405    let mut args = vec!["+".to_owned() + rustup];
406    args.push(
407        match target.policy.strategy {
408            BuildStrategy::NativeCargo => "build",
409            BuildStrategy::CargoZigbuild => "zigbuild",
410        }
411        .into(),
412    );
413    args.extend(["--release".to_owned(), "--locked".to_owned()]);
414    if target.policy.strategy == BuildStrategy::CargoZigbuild {
415        let triple = match target.policy.floor {
416            CompatibilityFloor::Glibc { major, minor } => {
417                format!("{}.{major}.{minor}", target.target)
418            }
419            CompatibilityFloor::Macos { .. } => {
420                // The canonical floor rule owns this refusal: a macOS floor
421                // cannot be satisfied by a cargo-zigbuild build.
422                crate::validate_floor_applicability(
423                    &target.policy.floor,
424                    target.policy.strategy,
425                    &target.target,
426                )
427                .map_err(|_| build_err("macOS floor cannot use cargo-zigbuild"))?;
428                target.target.clone()
429            }
430            CompatibilityFloor::None => target.target.clone(),
431        };
432        args.extend(["--target".to_owned(), triple]);
433    } else {
434        args.extend(["--target".to_owned(), target.target.clone()]);
435    }
436    args.extend([
437        "--package".into(),
438        binding.package.clone(),
439        "--bin".into(),
440        binding.binary.clone(),
441    ]);
442    let mut env = BTreeMap::new();
443    env.insert(
444        "CARGO_TARGET_DIR".into(),
445        target_dir.to_string_lossy().into_owned(),
446    );
447    Ok(CommandSpec {
448        executable: "cargo".into(),
449        args,
450        cwd: cwd.to_path_buf(),
451        env,
452        timeout,
453        stdout_limit: MAX_OUTPUT,
454        stderr_limit: MAX_OUTPUT,
455        expected_stdout: None,
456        expected_stdout_exact: None,
457    })
458}
459
460/// Run a process with a deadline and caller cancellation, cleaning up its process group.
461pub fn run_bounded_cancellable(
462    spec: &CommandSpec,
463    cancellation: &BuildCancellation,
464) -> Result<ProcessEvidence, BuildError> {
465    run_bounded_inner(
466        spec,
467        Cancellation::Build(cancellation),
468        ExecutableAllowance::Builder,
469    )
470}
471
472/// Run a bounded consumer-validator interpreter process group.
473///
474/// The supervised interpreter is terminated as a whole process group (or job
475/// object) on every failure path, so no descendant outlives the run; the
476/// reader-thread joins are bounded by the run's own remaining deadline, so a
477/// descendant that inherited a pipe cannot park the run past its deadline;
478/// and the environment is cleared except for the shared allowlist. Captured
479/// output never crosses the boundary: the caller learns only the outcome and
480/// the retained byte counts.
481///
482/// The interpreter is restricted to the finite Python 3 interpreter names.
483/// A caller-supplied cancellation flag is observed on the same poll cadence
484/// as the deadline.
485pub fn run_interpreter_bounded(
486    spec: &InterpreterCommandSpec,
487    cancelled: Option<&std::sync::atomic::AtomicBool>,
488) -> Result<ProcessEvidence, BuildError> {
489    let cancellation = match cancelled {
490        Some(flag) => Cancellation::Flag(flag),
491        None => Cancellation::None,
492    };
493    let run = BoundedRun {
494        executable: spec.executable.as_str(),
495        args: &spec.args,
496        cwd: spec.cwd.as_path(),
497        env: &spec.env,
498        timeout: spec.timeout,
499        stdout_limit: spec.stdout_limit,
500        stderr_limit: spec.stderr_limit,
501        expected_stdout: spec.expected_stdout.as_deref(),
502        expected_stdout_exact: None,
503    };
504    run_bounded(&run, cancellation, ExecutableAllowance::Interpreter)
505}
506
507/// Run a bounded `git` process group that must echo exactly `expected` on stdout.
508///
509/// The only sanctioned `git` spawn in the workspace: bounded time and output,
510/// process-group cleanup, and a cleared environment. stdout is matched
511/// internally and never returned, so the caller learns only pass or fail.
512pub fn run_git_bounded(expected: &str, cwd: Option<&Path>) -> Result<ProcessEvidence, BuildError> {
513    run_git_resolve_bounded(
514        vec![
515            "rev-parse".into(),
516            "--verify".into(),
517            "HEAD^{commit}".into(),
518        ],
519        expected,
520        cwd,
521    )
522}
523
524/// Verify an exact local tag peels to the expected commit using bounded git.
525pub fn run_git_tag_bounded(
526    tag: &str,
527    expected: &str,
528    cwd: Option<&Path>,
529) -> Result<ProcessEvidence, BuildError> {
530    // The canonical exact-tag safety rule owns this refusal: it carries the
531    // union of the git-ref-path concerns and the shell-metacharacter concerns.
532    if crate::validate_exact_tag_safety(tag).is_err() {
533        return Err(build_err("invalid exact git tag"));
534    }
535    run_git_resolve_bounded(
536        vec![
537            "rev-parse".into(),
538            "--verify".into(),
539            format!("refs/tags/{tag}^{{commit}}"),
540        ],
541        expected,
542        cwd,
543    )
544}
545
546fn run_git_resolve_bounded(
547    args: Vec<String>,
548    expected: &str,
549    cwd: Option<&Path>,
550) -> Result<ProcessEvidence, BuildError> {
551    let cwd = match cwd {
552        Some(cwd) => cwd.to_path_buf(),
553        None => std::env::current_dir().map_err(|_| build_err("working directory unavailable"))?,
554    };
555    let spec = CommandSpec {
556        executable: "git".into(),
557        args,
558        cwd,
559        env: BTreeMap::new(),
560        timeout: GIT_TIMEOUT,
561        stdout_limit: GIT_OUTPUT_LIMIT,
562        stderr_limit: GIT_OUTPUT_LIMIT,
563        expected_stdout: None,
564        expected_stdout_exact: Some(expected.to_owned()),
565    };
566    run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Git)
567}
568
569pub(crate) fn run_qualification_process(
570    spec: &CommandSpec,
571    cancellation: &BuildCancellation,
572) -> Result<ProcessEvidence, BuildError> {
573    run_bounded_inner(
574        spec,
575        Cancellation::Build(cancellation),
576        ExecutableAllowance::Candidate,
577    )
578}
579
580pub(crate) fn run_qemu_process(
581    spec: &CommandSpec,
582    cancellation: &BuildCancellation,
583) -> Result<ProcessEvidence, BuildError> {
584    run_bounded_inner(
585        spec,
586        Cancellation::Build(cancellation),
587        ExecutableAllowance::Qemu,
588    )
589}
590
591/// Normalized bounded-run parameters, shared by every public entry point.
592///
593/// The runner has one implementation; the entry points differ only in the
594/// executable allowance, the argument representation, and the cancellation
595/// source they carry.
596struct BoundedRun<'a> {
597    executable: &'a str,
598    args: &'a [OsString],
599    cwd: &'a Path,
600    env: &'a BTreeMap<String, String>,
601    timeout: Duration,
602    stdout_limit: usize,
603    stderr_limit: usize,
604    expected_stdout: Option<&'a str>,
605    expected_stdout_exact: Option<&'a str>,
606}
607
608fn run_bounded_inner(
609    spec: &CommandSpec,
610    cancellation: Cancellation<'_>,
611    allowance: ExecutableAllowance,
612) -> Result<ProcessEvidence, BuildError> {
613    let args: Vec<OsString> = spec.args.iter().map(OsString::from).collect();
614    let run = BoundedRun {
615        executable: spec.executable.as_str(),
616        args: &args,
617        cwd: spec.cwd.as_path(),
618        env: &spec.env,
619        timeout: spec.timeout,
620        stdout_limit: spec.stdout_limit,
621        stderr_limit: spec.stderr_limit,
622        expected_stdout: spec.expected_stdout.as_deref(),
623        expected_stdout_exact: spec.expected_stdout_exact.as_deref(),
624    };
625    run_bounded(&run, cancellation, allowance)
626}
627
628/// Whether a failed group signal is resolved by the kernel or a safe retry.
629///
630/// `ESRCH` proves the group is absent. For another error, an exited leader
631/// must first be reaped and the whole group signalled again; only a successful
632/// retry or retry `ESRCH` establishes that termination is complete.
633///
634/// The initial error is not proof that the group is empty. In particular,
635/// macOS `EPERM` can mean a group member is unsignalable, not absent.
636/// `try_wait` reports only the supervised leader and cannot inventory the
637/// remaining process group.
638///
639/// The retry closure is lazy and runs only after the leader has exited and
640/// been reaped. It sends the same group signal again, so live descendants are
641/// still targeted. Any retry error other than `ESRCH` remains a hard failure.
642/// Pipe EOF is not group inventory: descendants may close inherited pipes
643/// and remain alive. This helper is used by each Unix termination path.
644#[cfg(unix)]
645fn group_signal_failure_is_benign(
646    error: &std::io::Error,
647    child_exited: bool,
648    retry_group_signal: impl FnOnce() -> std::io::Result<()>,
649) -> bool {
650    if error.raw_os_error() == Some(libc::ESRCH) {
651        return true;
652    }
653    if !child_exited {
654        return false;
655    }
656    match retry_group_signal() {
657        Ok(()) => true,
658        Err(retry_error) => retry_error.raw_os_error() == Some(libc::ESRCH),
659    }
660}
661
662/// Terminate the supervised process group, tolerating only proven completion.
663///
664/// On macOS, signalling a group containing an unreaped zombie can fail with
665/// `EPERM`; reaping the leader may make the group empty, but it may also leave
666/// live descendants. Therefore, after any non-`ESRCH` failure, the runner
667/// reaps an exited leader and retries the group signal. A successful retry
668/// reaches remaining members; retry `ESRCH` proves the group is empty. Every
669/// other retry error remains a hard failure.
670///
671/// The drain budget detects a descendant that keeps a pipe open, but a
672/// descendant that closes its pipes is not observable through that budget.
673/// Group termination, not pipe state or leader status, is the authority here.
674/// Existing timeout, cancellation, and output-limit classification is unchanged.
675fn terminate_process_group(
676    child: &mut command_group::GroupChild,
677    message: &str,
678) -> Result<(), BuildError> {
679    match child.kill() {
680        Ok(()) => Ok(()),
681        Err(error) => {
682            // Reap the leader before retrying; its exit alone says nothing
683            // about other members that may still be in the process group.
684            let child_wait = child.try_wait();
685            #[cfg(unix)]
686            let child_exited = child_wait.as_ref().is_ok_and(Option::is_some);
687            #[cfg(unix)]
688            if group_signal_failure_is_benign(&error, child_exited, || child.kill()) {
689                return Ok(());
690            }
691            #[cfg(not(unix))]
692            let _ = child_wait;
693            Err(build_err(message))
694        }
695    }
696}
697
698fn run_bounded(
699    run: &BoundedRun<'_>,
700    cancellation: Cancellation<'_>,
701    allowance: ExecutableAllowance,
702) -> Result<ProcessEvidence, BuildError> {
703    let executable_allowed = match allowance {
704        ExecutableAllowance::Builder => {
705            matches!(run.executable, "cargo" | "rustc" | "zig")
706        }
707        ExecutableAllowance::Candidate => Path::new(run.executable).is_absolute(),
708        ExecutableAllowance::Qemu => {
709            matches!(run.executable, "qemu-x86_64" | "qemu-aarch64" | "qemu-arm")
710        }
711        ExecutableAllowance::Git => run.executable == "git",
712        ExecutableAllowance::Interpreter => matches!(run.executable, "python3" | "python"),
713    };
714    if !executable_allowed
715        || run.timeout.is_zero()
716        || run.timeout > Duration::from_secs(86_400)
717        || run.stdout_limit == 0
718        || run.stderr_limit == 0
719        || run.stdout_limit > MAX_PROCESS_OUTPUT
720        || run.stderr_limit > MAX_PROCESS_OUTPUT
721    {
722        return Err(build_err("invalid process bounds or executable"));
723    }
724    // F10a: artifact transfer between jobs strips POSIX exec bits
725    // (upload-artifact documents 644 for all files). A transferred
726    // candidate must be executable again before its smoke spawns it;
727    // bytes (and therefore recorded size/digest) are unaffected by mode.
728    if matches!(allowance, ExecutableAllowance::Candidate)
729        && ensure_candidate_executable(Path::new(run.executable)).is_err()
730    {
731        return Err(build_err("candidate is not executable"));
732    }
733    let mut command = Command::new(run.executable);
734    command
735        .args(run.args)
736        .current_dir(run.cwd)
737        .env_clear()
738        .stdin(Stdio::null())
739        .stdout(Stdio::piped())
740        .stderr(Stdio::piped());
741    let environment = if matches!(allowance, ExecutableAllowance::Git) {
742        // git resolves its helpers and DLLs from PATH, and reads the global
743        // config from HOME/USERPROFILE; `safe.directory` is frequently set
744        // there, so both must survive the environment clear.
745        [
746            "PATH",
747            "HOME",
748            "USERPROFILE",
749            "SystemRoot",
750            "WINDIR",
751            "TEMP",
752            "TMP",
753        ]
754        .as_slice()
755    } else if !matches!(allowance, ExecutableAllowance::Builder) {
756        ["PATH", "SystemRoot", "WINDIR", "TEMP", "TMP"].as_slice()
757    } else {
758        [
759            "PATH",
760            "HOME",
761            "USERPROFILE",
762            "SystemRoot",
763            "WINDIR",
764            "TEMP",
765            "TMP",
766            "CARGO_HOME",
767            "RUSTUP_HOME",
768            "LIB",
769            "LIBPATH",
770            "INCLUDE",
771            "VCToolsInstallDir",
772            "VisualStudioVersion",
773            "VCINSTALLDIR",
774            "WindowsSdkDir",
775            "WindowsSDKVersion",
776            "UniversalCRTSdkDir",
777            "UCRTVersion",
778        ]
779        .as_slice()
780    };
781    for key in environment {
782        if let Some(value) = std::env::var_os(key) {
783            command.env(key, value);
784        }
785    }
786    #[cfg(windows)]
787    if let Some(vc_tools) = std::env::var_os("VCToolsInstallDir") {
788        let preferred_linker = PathBuf::from(vc_tools)
789            .join("bin")
790            .join("Hostx64")
791            .join("x64");
792        if let Some(path) = std::env::var_os("PATH") {
793            let path = std::iter::once(preferred_linker).chain(std::env::split_paths(&path));
794            if let Ok(path) = std::env::join_paths(path) {
795                command.env("PATH", path);
796            }
797        }
798    }
799    command.envs(run.env);
800    let mut child = command
801        .group_spawn()
802        .map_err(|_| build_err("process spawn failed"))?;
803    let stdout = child
804        .inner()
805        .stdout
806        .take()
807        .ok_or_else(|| build_err("stdout pipe unavailable"))?;
808    let stderr = child
809        .inner()
810        .stderr
811        .take()
812        .ok_or_else(|| build_err("stderr pipe unavailable"))?;
813    let out = Arc::new(Mutex::new((Vec::new(), false)));
814    let err = Arc::new(Mutex::new((Vec::new(), false)));
815    let out2 = out.clone();
816    let out_limit = run.stdout_limit;
817    let t1 = thread::spawn(move || drain(stdout, out2, out_limit));
818    let err2 = err.clone();
819    let err_limit = run.stderr_limit;
820    let t2 = thread::spawn(move || drain(stderr, err2, err_limit));
821    let until = Instant::now() + run.timeout;
822    let (timed_out, cancelled, over_limit) = loop {
823        if cancellation.is_cancelled() {
824            terminate_process_group(&mut child, "cancelled process-group termination failed")?;
825            child
826                .wait()
827                .map_err(|_| build_err("cancelled process-group wait failed"))?;
828            break (false, true, false);
829        }
830        if Instant::now() >= until {
831            terminate_process_group(&mut child, "process-group termination failed")?;
832            child
833                .wait()
834                .map_err(|_| build_err("process-group wait failed"))?;
835            break (true, false, false);
836        }
837        // Prompt output-limit detection: a reader that has already seen more
838        // than its bound ends the run now, at the moment of excess, instead
839        // of letting a chatty process run until its deadline.
840        if stream_over_limit(&out) || stream_over_limit(&err) {
841            terminate_process_group(&mut child, "output-limit process-group termination failed")?;
842            child
843                .wait()
844                .map_err(|_| build_err("output-limit process-group wait failed"))?;
845            break (false, false, true);
846        }
847        if child
848            .try_wait()
849            .map_err(|_| build_err("process wait failed"))?
850            .is_some()
851        {
852            break (false, false, false);
853        }
854        thread::sleep(Duration::from_millis(20));
855    };
856    // The child — and on the kill paths its whole process group — is reaped,
857    // but the deadline must still bound the whole run: a drain thread returns
858    // only at pipe EOF, which needs every write end closed, so a descendant
859    // that inherited stdout and outlived the child would park the join for
860    // that descendant's entire lifetime. The joins therefore get a bounded
861    // budget taken from what is left of the caller's own deadline, and a
862    // reader still parked at it is detached and failed closed below.
863    let drain_budget = until
864        .saturating_duration_since(Instant::now())
865        .clamp(MIN_DRAIN_GRACE, MAX_DRAIN_GRACE);
866    let drain_until = Instant::now() + drain_budget;
867    let drained = join_drained(t1, drain_until, "stdout reader failed")?
868        & join_drained(t2, drain_until, "stderr reader failed")?;
869    if !drained {
870        // A reader was still parked at its budget, so the write end it waits
871        // on is held by a descendant that outlived the supervised child. The
872        // run fails closed below, and the group is terminated here so that
873        // descendant does not outlive the run either.
874        let _ = child.kill();
875    }
876    let status = child
877        .try_wait()
878        .map_err(|_| build_err("process wait failed"))?
879        .ok_or_else(|| build_err("process cleanup incomplete"))?;
880    let (stdout, out_over) = out
881        .lock()
882        .map_err(|_| build_err("stdout state unavailable"))?
883        .clone();
884    let (stderr, err_over) = err
885        .lock()
886        .map_err(|_| build_err("stderr state unavailable"))?
887        .clone();
888    let expected_missing = run
889        .expected_stdout
890        .is_some_and(|expected| !String::from_utf8_lossy(&stdout).contains(expected))
891        || run
892            .expected_stdout_exact
893            .is_some_and(|expected| String::from_utf8_lossy(&stdout).trim() != expected);
894    let outcome = if timed_out {
895        CommandOutcome::TimedOut
896    } else if cancelled {
897        CommandOutcome::Cancelled
898    } else if over_limit || !drained || out_over || err_over {
899        CommandOutcome::OutputLimitExceeded
900    } else if expected_missing {
901        CommandOutcome::Failed(-1)
902    } else if status.success() {
903        CommandOutcome::Success
904    } else {
905        CommandOutcome::Failed(status.code().unwrap_or(-1))
906    };
907    Ok(ProcessEvidence {
908        outcome,
909        stdout_bytes: stdout.len(),
910        stderr_bytes: stderr.len(),
911    })
912}
913/// Join one drain thread, bounded by `drain_until`.
914///
915/// Returns `false` when the reader is still parked at the budget — the write
916/// end it is waiting on belongs to a process that outlived the supervised
917/// child. The handle is then dropped, which detaches the thread rather than
918/// blocking; the retained bytes are then incomplete and the caller reports
919/// the run as failed.
920fn join_drained(
921    handle: thread::JoinHandle<()>,
922    drain_until: Instant,
923    reader_error: &'static str,
924) -> Result<bool, BuildError> {
925    while !handle.is_finished() {
926        if Instant::now() >= drain_until {
927            return Ok(false);
928        }
929        thread::sleep(Duration::from_millis(10));
930    }
931    handle.join().map_err(|_| build_err(reader_error))?;
932    Ok(true)
933}
934
935/// Whether a drained stream has already passed its retained-output bound.
936///
937/// The bound is checked before the bytes are retained, so the accumulator
938/// never grows past its limit even transiently; this reads the same flag so
939/// the runner can end the run at the moment of excess.
940fn stream_over_limit(capture: &Arc<Mutex<(Vec<u8>, bool)>>) -> bool {
941    capture.lock().map(|state| state.1).unwrap_or(false)
942}
943
944fn drain<R: Read>(mut reader: R, capture: Arc<Mutex<(Vec<u8>, bool)>>, limit: usize) {
945    let mut buffer = [0; 8192];
946    loop {
947        match reader.read(&mut buffer) {
948            Ok(0) | Err(_) => break,
949            Ok(n) => {
950                if let Ok(mut state) = capture.lock() {
951                    let keep = n.min(limit.saturating_sub(state.0.len()));
952                    state.0.extend_from_slice(&buffer[..keep]);
953                    if keep < n {
954                        state.1 = true;
955                    }
956                }
957            }
958        }
959    }
960}
961
962/// Confirm configured Rust/cargo-zigbuild versions before build execution.
963fn preflight(
964    target: &crate::PlannedTarget,
965    cwd: &Path,
966    cancellation: &BuildCancellation,
967) -> Result<(), BuildError> {
968    let rust = run_bounded_cancellable(
969        &CommandSpec {
970            executable: "rustc".into(),
971            args: vec![
972                "+".to_owned() + &target.policy.toolchain.rust,
973                "--version".into(),
974            ],
975            cwd: cwd.into(),
976            env: BTreeMap::new(),
977            timeout: Duration::from_secs(10),
978            stdout_limit: 1024,
979            stderr_limit: 1024,
980            expected_stdout: None,
981            expected_stdout_exact: None,
982        },
983        cancellation,
984    )?;
985    if rust.outcome != CommandOutcome::Success {
986        return Err(build_err("configured Rust toolchain preflight failed"));
987    }
988    let cargo = run_bounded_cancellable(
989        &CommandSpec {
990            executable: "cargo".into(),
991            args: vec![
992                "+".to_owned() + &target.policy.toolchain.rust,
993                "--version".into(),
994            ],
995            cwd: cwd.into(),
996            env: BTreeMap::new(),
997            timeout: Duration::from_secs(10),
998            stdout_limit: 1024,
999            stderr_limit: 1024,
1000            expected_stdout: None,
1001            expected_stdout_exact: None,
1002        },
1003        cancellation,
1004    )?;
1005    if cargo.outcome != CommandOutcome::Success {
1006        return Err(build_err("configured Cargo toolchain preflight failed"));
1007    }
1008    if target.policy.strategy == BuildStrategy::CargoZigbuild {
1009        let expected = target
1010            .policy
1011            .toolchain
1012            .cargo_zigbuild
1013            .as_deref()
1014            .ok_or_else(|| build_err("cargo-zigbuild version missing"))?;
1015        let expected_zig = target
1016            .policy
1017            .toolchain
1018            .zig
1019            .as_deref()
1020            .ok_or_else(|| build_err("Zig version missing"))?;
1021        let actual = run_bounded_cancellable(
1022            &CommandSpec {
1023                executable: "cargo".into(),
1024                args: vec!["zigbuild".into(), "--version".into()],
1025                cwd: cwd.into(),
1026                env: BTreeMap::new(),
1027                timeout: Duration::from_secs(10),
1028                stdout_limit: 1024,
1029                stderr_limit: 1024,
1030                // Trimmed equality, not a substring test: a pin of `0.23.3`
1031                // must not be satisfied by a reported `0.23.30`.
1032                expected_stdout: None,
1033                expected_stdout_exact: Some(format!("cargo-zigbuild {expected}")),
1034            },
1035            cancellation,
1036        )?;
1037        if actual.outcome != CommandOutcome::Success {
1038            return Err(build_err("cargo-zigbuild version mismatch"));
1039        }
1040        let zig = run_bounded_cancellable(
1041            &CommandSpec {
1042                executable: "zig".into(),
1043                args: vec!["version".into()],
1044                cwd: cwd.into(),
1045                env: BTreeMap::new(),
1046                timeout: Duration::from_secs(10),
1047                stdout_limit: 1024,
1048                stderr_limit: 1024,
1049                // Same rule for Zig: the reported version must equal the pin.
1050                expected_stdout: None,
1051                expected_stdout_exact: Some(expected_zig.to_owned()),
1052            },
1053            cancellation,
1054        )?;
1055        if zig.outcome != CommandOutcome::Success {
1056            return Err(build_err("Zig version mismatch"));
1057        }
1058    }
1059    Ok(())
1060}
1061
1062/// Execute one target using explicit bindings, private target storage, and exact output discovery.
1063pub fn execute_target(
1064    plan: &ReleasePlan,
1065    target: &crate::PlannedTarget,
1066    bindings: &[BuildBinding],
1067    repository_root: &Path,
1068    work_root: &Path,
1069    invocation: &str,
1070) -> Result<BuildAttempt, BuildError> {
1071    execute_target_cancellable(
1072        plan,
1073        target,
1074        bindings,
1075        repository_root,
1076        work_root,
1077        invocation,
1078        &BuildCancellation::new(),
1079    )
1080}
1081
1082/// Execute a target with explicit caller cancellation and bounded cleanup.
1083pub fn execute_target_cancellable(
1084    plan: &ReleasePlan,
1085    target: &crate::PlannedTarget,
1086    bindings: &[BuildBinding],
1087    repository_root: &Path,
1088    work_root: &Path,
1089    invocation: &str,
1090    cancellation: &BuildCancellation,
1091) -> Result<BuildAttempt, BuildError> {
1092    if !plan.targets.iter().any(|planned| planned == target)
1093        || plan.schema_version != 1
1094        || plan.release_id.is_empty()
1095        || plan.source_revision.is_empty()
1096    {
1097        return Err(build_err(
1098            "target is not part of the supplied ReleasePlan identity",
1099        ));
1100    }
1101    if !repository_root.is_absolute() {
1102        return Err(build_err("repository root must be absolute"));
1103    }
1104    let repository =
1105        fs::canonicalize(repository_root).map_err(|_| build_err("repository root unavailable"))?;
1106    preflight(target, &repository, cancellation)?;
1107    let target_dir = private_target_dir(work_root, invocation, &target.target)?;
1108    fs::create_dir(&target_dir)
1109        .map_err(|_| build_err("private Cargo target directory creation failed"))?;
1110    let mut candidates = Vec::new();
1111    let mut last = ProcessEvidence {
1112        outcome: CommandOutcome::Success,
1113        stdout_bytes: 0,
1114        stderr_bytes: 0,
1115    };
1116    for binding in bindings {
1117        let spec = cargo_command(
1118            target,
1119            binding,
1120            &repository,
1121            &target_dir,
1122            Duration::from_secs(1800),
1123        )?;
1124        let evidence = run_bounded_cancellable(&spec, cancellation)?;
1125        if evidence.outcome != CommandOutcome::Success {
1126            return Ok(BuildAttempt {
1127                release_id: plan.release_id.clone(),
1128                source_revision: plan.source_revision.clone(),
1129                target: target.target.clone(),
1130                strategy: target.policy.strategy,
1131                tool_summary: format!("rust {}", target.policy.toolchain.rust),
1132                process: evidence,
1133                candidates: Vec::new(),
1134            });
1135        }
1136        let (path, size) = discover_candidate(&target_dir, &target.target, &binding.binary)?;
1137        candidates.push(CandidateArtifact {
1138            target: target.target.clone(),
1139            selector: binding.selector.clone(),
1140            package: binding.package.clone(),
1141            binary: binding.binary.clone(),
1142            path,
1143            size,
1144        });
1145        last = evidence;
1146    }
1147    if candidates.is_empty() {
1148        // A build that produced no candidate has produced nothing to finalize.
1149        // Reporting it as a success attempt with an empty candidate list would
1150        // leave the empty list as the only signal, so it fails closed here.
1151        return Err(build_err("build produced no candidates"));
1152    }
1153    Ok(BuildAttempt {
1154        release_id: plan.release_id.clone(),
1155        source_revision: plan.source_revision.clone(),
1156        target: target.target.clone(),
1157        strategy: target.policy.strategy,
1158        tool_summary: format!(
1159            "rust {}{}{}",
1160            target.policy.toolchain.rust,
1161            target
1162                .policy
1163                .toolchain
1164                .cargo_zigbuild
1165                .as_ref()
1166                .map(|v| format!(" cargo-zigbuild {v}"))
1167                .unwrap_or_default(),
1168            target
1169                .policy
1170                .toolchain
1171                .zig
1172                .as_ref()
1173                .map(|v| format!(" zig {v}"))
1174                .unwrap_or_default()
1175        ),
1176        process: last,
1177        candidates,
1178    })
1179}
1180
1181/// Establish a caller-owned absolute work root and a unique target directory.
1182pub fn private_target_dir(
1183    work_root: &Path,
1184    invocation: &str,
1185    target: &str,
1186) -> Result<PathBuf, BuildError> {
1187    if !work_root.is_absolute()
1188        || invocation.is_empty()
1189        || invocation.len() > 128
1190        || target.is_empty()
1191    {
1192        return Err(build_err("invalid private work root identity"));
1193    }
1194    if fs::symlink_metadata(work_root)
1195        .map_err(|_| build_err("work root must pre-exist"))?
1196        .file_type()
1197        .is_symlink()
1198    {
1199        return Err(build_err("symlink work root rejected"));
1200    }
1201    let canonical =
1202        fs::canonicalize(work_root).map_err(|_| build_err("work root canonicalization failed"))?;
1203    let name = format!("{}-{}", safe_component(invocation), safe_component(target));
1204    let path = canonical.join(name);
1205    match fs::create_dir(&path) {
1206        Ok(()) => (),
1207        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1208            return Err(build_err("private build directory already exists"))
1209        }
1210        Err(_) => return Err(build_err("private build directory creation failed")),
1211    }
1212    let check = fs::canonicalize(&path)
1213        .map_err(|_| build_err("private build path canonicalization failed"))?;
1214    if !check.starts_with(&canonical) {
1215        return Err(build_err("private build path escapes work root"));
1216    }
1217    let mut metadata = fs::File::create(path.join(".eggpack-owner"))
1218        .map_err(|_| build_err("ownership marker creation failed"))?;
1219    metadata
1220        .write_all(format!("1\n{}\n{}\n", invocation, target).as_bytes())
1221        .map_err(|_| build_err("ownership marker write failed"))?;
1222    Ok(path.join("target"))
1223}
1224fn safe_component(s: &str) -> String {
1225    s.chars()
1226        .map(|c| {
1227            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
1228                c
1229            } else {
1230                '_'
1231            }
1232        })
1233        .collect()
1234}
1235
1236/// Resolve and validate exactly the Cargo release output path.
1237pub fn discover_candidate(
1238    target_dir: &Path,
1239    target: &str,
1240    binary: &str,
1241) -> Result<(PathBuf, u64), BuildError> {
1242    if !valid_identifier(binary) {
1243        return Err(build_err("invalid binary name"));
1244    }
1245    let mut path = target_dir.join(target).join("release").join(binary);
1246    if target.contains("-windows-") {
1247        // Cargo appends the executable suffix to the full binary name; a binary
1248        // name containing `.` keeps it (`tool.cli` -> `tool.cli.exe`).
1249        path.set_file_name(format!("{binary}.exe"));
1250    }
1251    let metadata =
1252        fs::symlink_metadata(&path).map_err(|_| build_err("expected candidate missing"))?;
1253    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() || metadata.len() == 0 {
1254        return Err(build_err("candidate is not a non-empty regular file"));
1255    }
1256    let canonical_root =
1257        fs::canonicalize(target_dir).map_err(|_| build_err("target directory unavailable"))?;
1258    let canonical_file =
1259        fs::canonicalize(&path).map_err(|_| build_err("candidate canonicalization failed"))?;
1260    if !canonical_file.starts_with(&canonical_root) {
1261        return Err(build_err("candidate escapes private target directory"));
1262    }
1263    let release_dir = target_dir.join(target).join("release");
1264    let target_meta = fs::symlink_metadata(target_dir.join(target))
1265        .map_err(|_| build_err("target output directory missing"))?;
1266    let release_meta = fs::symlink_metadata(&release_dir)
1267        .map_err(|_| build_err("release output directory missing"))?;
1268    if target_meta.file_type().is_symlink()
1269        || !target_meta.is_dir()
1270        || release_meta.file_type().is_symlink()
1271        || !release_meta.is_dir()
1272    {
1273        return Err(build_err(
1274            "candidate parent directory is not private regular directory",
1275        ));
1276    }
1277    Ok((path, metadata.len()))
1278}
1279
1280#[cfg(test)]
1281mod tests {
1282    use super::*;
1283    use crate::{HostArch, HostOs, Qualification, SupportTier, TargetPolicy, ToolchainRequirement};
1284    use std::sync::Mutex;
1285
1286    static CARGO_FIXTURE_LOCK: Mutex<()> = Mutex::new(());
1287
1288    fn target() -> crate::PlannedTarget {
1289        crate::PlannedTarget {
1290            target: "x86_64-unknown-linux-gnu".into(),
1291            policy: TargetPolicy {
1292                target: "x86_64-unknown-linux-gnu".into(),
1293                strategy: BuildStrategy::NativeCargo,
1294                host_os: HostOs::Linux,
1295                host_arch: HostArch::X86_64,
1296                qualification_host: None,
1297                toolchain: ToolchainRequirement {
1298                    rust: "1.89.0".into(),
1299                    cargo_zigbuild: None,
1300                    zig: None,
1301                },
1302                floor: CompatibilityFloor::None,
1303                qualification: Qualification::Native,
1304                support: SupportTier::Required,
1305            },
1306            artifact_form: crate::PlannedAssetForm::Direct,
1307            floor_status: crate::FloorVerificationStatus::NotDeclared,
1308        }
1309    }
1310    #[test]
1311    fn command_is_explicit_and_never_shell_based() {
1312        let b = BuildBinding {
1313            selector: LogicalOutputSelector::Direct,
1314            package: "demo".into(),
1315            binary: "demo-bin".into(),
1316        };
1317        let c = cargo_command(
1318            &target(),
1319            &b,
1320            Path::new("/repo"),
1321            Path::new("/private/target"),
1322            Duration::from_secs(10),
1323        )
1324        .unwrap();
1325        assert_eq!(c.executable, "cargo");
1326        assert_eq!(
1327            c.args,
1328            [
1329                "+1.89.0",
1330                "build",
1331                "--release",
1332                "--locked",
1333                "--target",
1334                "x86_64-unknown-linux-gnu",
1335                "--package",
1336                "demo",
1337                "--bin",
1338                "demo-bin"
1339            ]
1340        );
1341        assert_eq!(c.env["CARGO_TARGET_DIR"], "/private/target");
1342        let mut arbitrary = c;
1343        arbitrary.executable = "sh".into();
1344        assert!(
1345            run_bounded_inner(&arbitrary, Cancellation::None, ExecutableAllowance::Builder)
1346                .is_err()
1347        );
1348    }
1349    #[test]
1350    fn zigbuild_floor_uses_only_gnu_target_syntax() {
1351        let mut t = target();
1352        t.policy.strategy = BuildStrategy::CargoZigbuild;
1353        t.policy.toolchain.cargo_zigbuild = Some("0.19.8".into());
1354        t.policy.toolchain.zig = Some("0.14.1".into());
1355        t.policy.floor = CompatibilityFloor::Glibc {
1356            major: 2,
1357            minor: 17,
1358        };
1359        let binding = BuildBinding {
1360            selector: LogicalOutputSelector::Direct,
1361            package: "demo".into(),
1362            binary: "demo".into(),
1363        };
1364        let command = cargo_command(
1365            &t,
1366            &binding,
1367            Path::new("/repo"),
1368            Path::new("/target"),
1369            Duration::from_secs(10),
1370        )
1371        .unwrap();
1372        assert_eq!(command.args[1], "zigbuild");
1373        assert_eq!(command.args[5], "x86_64-unknown-linux-gnu.2.17");
1374        t.policy.floor = CompatibilityFloor::Macos {
1375            major: 13,
1376            minor: 0,
1377        };
1378        assert!(cargo_command(
1379            &t,
1380            &binding,
1381            Path::new("/repo"),
1382            Path::new("/target"),
1383            Duration::from_secs(10)
1384        )
1385        .is_err());
1386    }
1387    /// The compatibility-floor build behaviour is unchanged by the floor
1388    /// verification status: the cargo-zigbuild triple rewrite is pinned
1389    /// byte-for-byte, and the macOS-under-zigbuild refusal keeps its exact
1390    /// message. Recording a floor status must never move the refusal from
1391    /// build-command time to declaration time.
1392    #[test]
1393    fn the_cargo_zigbuild_floor_rewrite_and_macos_refusal_are_unchanged() {
1394        let mut t = target();
1395        t.policy.strategy = BuildStrategy::CargoZigbuild;
1396        t.policy.toolchain.cargo_zigbuild = Some("0.23.3".into());
1397        t.policy.toolchain.zig = Some("0.14.1".into());
1398        t.policy.floor = CompatibilityFloor::Glibc {
1399            major: 2,
1400            minor: 17,
1401        };
1402        let binding = BuildBinding {
1403            selector: LogicalOutputSelector::Direct,
1404            package: "demo".into(),
1405            binary: "demo".into(),
1406        };
1407        let command = cargo_command(
1408            &t,
1409            &binding,
1410            Path::new("/repo"),
1411            Path::new("/target"),
1412            Duration::from_secs(10),
1413        )
1414        .unwrap();
1415        assert_eq!(
1416            command.args,
1417            vec![
1418                "+1.89.0",
1419                "zigbuild",
1420                "--release",
1421                "--locked",
1422                "--target",
1423                "x86_64-unknown-linux-gnu.2.17",
1424                "--package",
1425                "demo",
1426                "--bin",
1427                "demo",
1428            ]
1429        );
1430        // A macOS floor under cargo-zigbuild is refused at build-command time
1431        // with the unchanged message.
1432        t.policy.floor = CompatibilityFloor::Macos {
1433            major: 13,
1434            minor: 0,
1435        };
1436        let refusal = cargo_command(
1437            &t,
1438            &binding,
1439            Path::new("/repo"),
1440            Path::new("/target"),
1441            Duration::from_secs(10),
1442        )
1443        .unwrap_err();
1444        assert_eq!(refusal.to_string(), "macOS floor cannot use cargo-zigbuild");
1445        // The refusal is not moved to declaration time: the policy still
1446        // resolves, because only the canonical floor rule refuses it.
1447        assert_eq!(
1448            t.policy.floor,
1449            CompatibilityFloor::Macos {
1450                major: 13,
1451                minor: 0
1452            }
1453        );
1454    }
1455    #[test]
1456    fn binding_document_rejects_duplicate_and_unknown_fields() {
1457        let good = r#"schema_version = 1
1458[targets]
1459"x86_64-unknown-linux-gnu" = [{ selector = { kind = "direct" }, package = "demo", binary = "demo" }]
1460"#;
1461        assert!(BuildBindingsV1::from_toml(good).is_ok());
1462        assert!(BuildBindingsV1::from_toml(
1463            &good.replace("schema_version = 1", "schema_version = 2")
1464        )
1465        .is_err());
1466        assert!(
1467            BuildBindingsV1::from_toml(&good.replace("package =", "extra = 1, package =")).is_err()
1468        );
1469    }
1470    #[test]
1471    fn bindings_must_match_direct_contract_slots_exactly() {
1472        let contract = DistributionContract::parse_toml_str(include_str!(
1473            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
1474        ))
1475        .unwrap();
1476        let plan = crate::PackConfig {
1477            schema_version: 1,
1478            targets: vec![target().policy],
1479        }
1480        .resolve(&contract, "1.0", "abc", &["linux-x64".into()])
1481        .unwrap();
1482        let bindings = BuildBindingsV1 {
1483            schema_version: 1,
1484            targets: [(
1485                "x86_64-unknown-linux-gnu".into(),
1486                vec![BuildBinding {
1487                    selector: LogicalOutputSelector::Direct,
1488                    package: "demo".into(),
1489                    binary: "demo".into(),
1490                }],
1491            )]
1492            .into_iter()
1493            .collect(),
1494        };
1495        assert!(bindings.validate_for(&contract, &plan).is_ok());
1496        let mut invalid = bindings;
1497        invalid.targets.get_mut("x86_64-unknown-linux-gnu").unwrap()[0].selector =
1498            LogicalOutputSelector::BundleEntry { index: 0 };
1499        assert!(invalid.validate_for(&contract, &plan).is_err());
1500    }
1501    #[test]
1502    fn candidate_lookup_is_exact_regular_and_nonempty() {
1503        let root = crate::test_temp_dir("builder-test");
1504        let out = root.join("x86_64-unknown-linux-gnu/release");
1505        fs::create_dir_all(&out).unwrap();
1506        fs::write(out.join("demo"), b"binary").unwrap();
1507        assert_eq!(
1508            discover_candidate(&root, "x86_64-unknown-linux-gnu", "demo")
1509                .unwrap()
1510                .1,
1511            6
1512        );
1513        fs::write(out.join("empty"), b"").unwrap();
1514        assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "empty").is_err());
1515        assert!(discover_candidate(&root, "x86_64-unknown-linux-gnu", "other").is_err());
1516        fs::remove_dir_all(root).unwrap();
1517    }
1518    #[test]
1519    fn windows_candidate_appends_exe_and_preserves_dotted_names() {
1520        let root = crate::test_temp_dir("builder-exe-test");
1521        let target = "x86_64-pc-windows-msvc";
1522        let out = root.join(target).join("release");
1523        fs::create_dir_all(&out).unwrap();
1524        fs::write(out.join("demo.exe"), b"binary").unwrap();
1525        assert_eq!(discover_candidate(&root, target, "demo").unwrap().1, 6);
1526        fs::write(out.join("tool.cli.exe"), b"dotted").unwrap();
1527        // Cargo appends the suffix: a dotted name keeps its own extension
1528        // rather than having it replaced.
1529        let (path, size) = discover_candidate(&root, target, "tool.cli").unwrap();
1530        assert!(path.ends_with("tool.cli.exe"), "{path:?}");
1531        assert_eq!(size, 6);
1532        fs::remove_dir_all(root).unwrap();
1533
1534        // A replaced-extension lookup must not resolve: with only `tool.exe`
1535        // present, `tool.cli` is a miss rather than a truncation match.
1536        let root = crate::test_temp_dir("builder-exe-test-2");
1537        let out = root.join(target).join("release");
1538        fs::create_dir_all(&out).unwrap();
1539        fs::write(out.join("tool.exe"), b"truncated").unwrap();
1540        assert!(discover_candidate(&root, target, "tool.cli").is_err());
1541        fs::remove_dir_all(root).unwrap();
1542    }
1543    #[test]
1544    fn windows_candidate_matching_is_not_a_substring_heuristic() {
1545        let root = crate::test_temp_dir("builder-triple-test");
1546        let target = "x86_64-unknown-notwindowsish";
1547        let out = root.join(target).join("release");
1548        fs::create_dir_all(&out).unwrap();
1549        fs::write(out.join("demo"), b"binary").unwrap();
1550        assert!(discover_candidate(&root, target, "demo").is_ok());
1551        fs::remove_dir_all(root).unwrap();
1552    }
1553    #[test]
1554    fn git_verification_is_bounded_and_exact() {
1555        let root = crate::test_temp_dir("builder-git-test");
1556        let git = |args: &[&str]| {
1557            Command::new("git")
1558                .args(args)
1559                .current_dir(&root)
1560                .env("GIT_AUTHOR_NAME", "t")
1561                .env("GIT_AUTHOR_EMAIL", "t@example.invalid")
1562                .env("GIT_COMMITTER_NAME", "t")
1563                .env("GIT_COMMITTER_EMAIL", "t@example.invalid")
1564                .output()
1565        };
1566        if !git(&["init", "--quiet"]).is_ok_and(|o| o.status.success()) {
1567            fs::remove_dir_all(root).unwrap();
1568            return; // git unavailable: nothing to verify
1569        }
1570        fs::write(root.join("f"), b"x").unwrap();
1571        if !git(&["add", "f"]).is_ok_and(|o| o.status.success())
1572            || !git(&["commit", "--quiet", "-m", "c"]).is_ok_and(|o| o.status.success())
1573        {
1574            fs::remove_dir_all(root).unwrap();
1575            return;
1576        }
1577        let head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
1578            .unwrap()
1579            .trim()
1580            .to_owned();
1581        assert_eq!(head.len(), 40);
1582        assert!(git(&["tag", "v1.2.3"]).is_ok_and(|o| o.status.success()));
1583        assert_eq!(
1584            run_git_tag_bounded("v1.2.3", &head, Some(&root))
1585                .unwrap()
1586                .outcome,
1587            CommandOutcome::Success
1588        );
1589        assert_ne!(
1590            run_git_tag_bounded("v1.2.4", &head, Some(&root))
1591                .unwrap()
1592                .outcome,
1593            CommandOutcome::Success
1594        );
1595        assert!(run_git_tag_bounded("v../evil", &head, Some(&root)).is_err());
1596        assert!(run_git_tag_bounded("v1.2.3^{}", &head, Some(&root)).is_err());
1597        fs::write(root.join("f"), b"second commit").unwrap();
1598        assert!(git(&["add", "f"]).is_ok_and(|o| o.status.success()));
1599        assert!(git(&["commit", "--quiet", "-m", "second"]).is_ok_and(|o| o.status.success()));
1600        assert!(git(&["tag", "v1.2.9"]).is_ok_and(|o| o.status.success()));
1601        let second_head = String::from_utf8(git(&["rev-parse", "HEAD"]).unwrap().stdout)
1602            .unwrap()
1603            .trim()
1604            .to_owned();
1605        assert_ne!(
1606            run_git_tag_bounded("v1.2.9", &head, Some(&root))
1607                .unwrap()
1608                .outcome,
1609            CommandOutcome::Success,
1610            "another tag pointing at a different commit must fail"
1611        );
1612        assert_eq!(
1613            run_git_bounded(&second_head, Some(&root)).unwrap().outcome,
1614            CommandOutcome::Success
1615        );
1616        // The match is exact, not containment: surrounding noise fails closed.
1617        let noisy = format!(" {second_head} ");
1618        assert_ne!(
1619            run_git_bounded(&noisy, Some(&root)).unwrap().outcome,
1620            CommandOutcome::Success
1621        );
1622        assert_ne!(
1623            run_git_bounded(&second_head[..39], Some(&root))
1624                .unwrap()
1625                .outcome,
1626            CommandOutcome::Success
1627        );
1628        assert_ne!(
1629            run_git_bounded(&"0".repeat(40), Some(&root))
1630                .unwrap()
1631                .outcome,
1632            CommandOutcome::Success
1633        );
1634        // A non-repository working directory cannot resolve HEAD.
1635        let outside = crate::test_temp_dir("builder-git-outside");
1636        assert_ne!(
1637            run_git_bounded(&second_head, Some(&outside))
1638                .unwrap()
1639                .outcome,
1640            CommandOutcome::Success
1641        );
1642        fs::remove_dir_all(outside).unwrap();
1643        fs::remove_dir_all(root).unwrap();
1644    }
1645    #[test]
1646    fn private_workspace_rejects_relative_and_reused_invocations() {
1647        let root = crate::test_temp_dir("private-test");
1648        assert!(private_target_dir(Path::new("relative"), "run", "target").is_err());
1649        assert!(private_target_dir(&root, "run", "target").is_ok());
1650        assert!(private_target_dir(&root, "run", "target").is_err());
1651        fs::remove_dir_all(root).unwrap();
1652    }
1653    #[test]
1654    fn process_output_is_bounded_and_exit_status_explicit() {
1655        let spec = CommandSpec {
1656            executable: "rustc".into(),
1657            args: vec!["--version".into()],
1658            cwd: std::env::current_dir().unwrap(),
1659            env: BTreeMap::new(),
1660            timeout: Duration::from_secs(5),
1661            stdout_limit: 1024,
1662            stderr_limit: 1024,
1663            expected_stdout: None,
1664            expected_stdout_exact: None,
1665        };
1666        let result =
1667            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder).unwrap();
1668        assert_eq!(result.outcome, CommandOutcome::Success);
1669        assert!(result.stdout_bytes <= 1024);
1670    }
1671    /// A process group whose only member has already exited and been reaped
1672    /// holds no process, so terminating it is reported as "no such process
1673    /// group". That is not a failed termination — there is nothing left to
1674    /// terminate — and treating it as one turns a completed run into an
1675    /// error.
1676    ///
1677    /// Linux signals a zombie process group successfully while macOS refuses
1678    /// to signal a group that holds one and reports `EPERM` for the whole
1679    /// group, so the same run terminated cleanly on one platform and failed
1680    /// on the other, reporting an output-bound violation as a launch
1681    /// failure.
1682    #[cfg(unix)]
1683    #[test]
1684    fn terminating_an_already_exited_process_group_is_not_a_failure() {
1685        let mut command = Command::new("sh");
1686        command.args(["-c", "exit 0"]);
1687        let mut child = command.group_spawn().unwrap();
1688        // Reap the child: the group then holds no process at all.
1689        child.wait().unwrap();
1690        // The dependency reports the empty group as an error.
1691        assert!(child.kill().is_err());
1692        // The runner treats that as "nothing left to terminate".
1693        assert!(terminate_process_group(&mut child, "test termination").is_ok());
1694    }
1695    #[cfg(unix)]
1696    #[test]
1697    fn a_failed_group_signal_is_benign_only_after_recheck_proves_termination() {
1698        let no_such_group = std::io::Error::from_raw_os_error(libc::ESRCH);
1699        let not_permitted = std::io::Error::from_raw_os_error(libc::EPERM);
1700
1701        assert!(group_signal_failure_is_benign(
1702            &no_such_group,
1703            false,
1704            || { panic!("ESRCH must not trigger a retry") }
1705        ));
1706        assert!(!group_signal_failure_is_benign(
1707            &not_permitted,
1708            false,
1709            || { panic!("a live or unverified child must not trigger a retry") }
1710        ));
1711        assert!(group_signal_failure_is_benign(&not_permitted, true, || Ok(
1712            ()
1713        )));
1714        assert!(group_signal_failure_is_benign(&not_permitted, true, || {
1715            Err(std::io::Error::from_raw_os_error(libc::ESRCH))
1716        }));
1717        assert!(!group_signal_failure_is_benign(
1718            &not_permitted,
1719            true,
1720            || { Err(std::io::Error::from_raw_os_error(libc::EPERM)) }
1721        ));
1722    }
1723    #[cfg(unix)]
1724    #[test]
1725    fn terminating_an_exited_leader_still_signals_a_live_group_descendant() {
1726        let root = crate::test_temp_dir("group-descendant-termination");
1727        let started = root.join("descendant-started");
1728        let release = root.join("descendant-release");
1729        let survived = root.join("descendant-survived");
1730        let started_arg = started.to_string_lossy().into_owned();
1731        let release_arg = release.to_string_lossy().into_owned();
1732        let survived_arg = survived.to_string_lossy().into_owned();
1733        let mut command = Command::new("sh");
1734        command.args([
1735            "-c",
1736            "sh -c 'printf started > \"$1\"; while [ ! -e \"$2\" ]; do sleep 0.01; done; printf survived > \"$3\"' sh \"$1\" \"$2\" \"$3\" >/dev/null 2>&1 & while [ ! -e \"$1\" ]; do sleep 0.01; done; exit 0",
1737            "group-fixture",
1738            started_arg.as_str(),
1739            release_arg.as_str(),
1740            survived_arg.as_str(),
1741        ]);
1742        let mut child = command.group_spawn().unwrap();
1743
1744        let leader_deadline = Instant::now() + Duration::from_secs(3);
1745        let leader_status = loop {
1746            match child.try_wait() {
1747                Ok(Some(status)) => break Some(status),
1748                Ok(None) if Instant::now() < leader_deadline => {
1749                    thread::sleep(Duration::from_millis(10));
1750                }
1751                _ => break None,
1752            }
1753        };
1754        let descendant_deadline = Instant::now() + Duration::from_secs(1);
1755        while !started.is_file() && Instant::now() < descendant_deadline {
1756            thread::sleep(Duration::from_millis(10));
1757        }
1758
1759        let terminated = terminate_process_group(&mut child, "test termination").is_ok();
1760        if !terminated {
1761            let _ = child.kill();
1762        }
1763        // If a live descendant was incorrectly left behind, releasing it makes
1764        // it write a marker rather than relying on an arbitrary sleep duration.
1765        fs::write(&release, "release").unwrap();
1766        let survivor_deadline = Instant::now() + Duration::from_secs(1);
1767        while !survived.is_file() && Instant::now() < survivor_deadline {
1768            thread::sleep(Duration::from_millis(10));
1769        }
1770        let descendant_started = started.is_file();
1771        let descendant_survived = survived.exists();
1772        let leader_succeeded = leader_status.is_some_and(|status| status.success());
1773        fs::remove_dir_all(root).unwrap();
1774
1775        assert!(leader_succeeded, "the group leader must exit normally");
1776        assert!(descendant_started, "the live descendant fixture must start");
1777        assert!(terminated, "the process group must be terminated");
1778        assert!(
1779            !descendant_survived,
1780            "the descendant must not outlive group termination"
1781        );
1782    }
1783    #[test]
1784    fn nonzero_tool_exit_is_not_success() {
1785        let spec = CommandSpec {
1786            executable: "rustc".into(),
1787            args: vec!["--eggpack-invalid-option".into()],
1788            cwd: std::env::current_dir().unwrap(),
1789            env: BTreeMap::new(),
1790            timeout: Duration::from_secs(5),
1791            stdout_limit: 1024,
1792            stderr_limit: 1024,
1793            expected_stdout: None,
1794            expected_stdout_exact: None,
1795        };
1796        assert!(matches!(
1797            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1798                .unwrap()
1799                .outcome,
1800            CommandOutcome::Failed(_)
1801        ));
1802    }
1803    #[test]
1804    fn stdout_overflow_is_bounded_and_not_success() {
1805        let root = crate::test_temp_dir("output-bound");
1806        let source = root.join("many-errors.rs");
1807        let body = (0..200)
1808            .map(|i| format!("fn f{i}() {{ absent_symbol_{i}(); }}\n"))
1809            .collect::<String>();
1810        fs::write(&source, body).unwrap();
1811        let spec = CommandSpec {
1812            executable: "rustc".into(),
1813            args: vec![
1814                "--crate-type".into(),
1815                "lib".into(),
1816                source.to_string_lossy().into_owned(),
1817            ],
1818            cwd: root.clone(),
1819            env: BTreeMap::new(),
1820            timeout: Duration::from_secs(10),
1821            stdout_limit: 128,
1822            stderr_limit: 128,
1823            expected_stdout: None,
1824            expected_stdout_exact: None,
1825        };
1826        assert_eq!(
1827            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1828                .unwrap()
1829                .outcome,
1830            CommandOutcome::OutputLimitExceeded
1831        );
1832        fs::remove_dir_all(root).unwrap();
1833    }
1834    #[test]
1835    fn timeout_kills_and_waits_for_the_process_group() {
1836        let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
1837        let root = crate::test_temp_dir("timeout");
1838        fs::create_dir_all(root.join("src")).unwrap();
1839        fs::write(root.join("Cargo.toml"), "[package]\nname='timeout-fixture'\nversion='0.1.0'\nedition='2021'\nbuild='build.rs'\n").unwrap();
1840        fs::write(
1841            root.join("Cargo.lock"),
1842            "version = 3\n\n[[package]]\nname = \"timeout-fixture\"\nversion = \"0.1.0\"\n",
1843        )
1844        .unwrap();
1845        fs::write(
1846            root.join("build.rs"),
1847            "fn main() { println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_STARTED\"); println!(\"cargo:rerun-if-env-changed=EGGPACK_BUILD_SLEEP\"); if let Some(path) = std::env::var_os(\"EGGPACK_BUILD_STARTED\") { std::fs::write(path, b\"started\").unwrap(); } if std::env::var_os(\"EGGPACK_BUILD_SLEEP\").is_some() { std::thread::sleep(std::time::Duration::from_secs(30)); } }\n",
1848        )
1849        .unwrap();
1850        fs::write(root.join("src/lib.rs"), "pub fn fixture() {}\n").unwrap();
1851        let mut spec = CommandSpec {
1852            executable: "cargo".into(),
1853            args: vec![
1854                "build".into(),
1855                "--locked".into(),
1856                "--offline".into(),
1857                "--manifest-path".into(),
1858                root.join("Cargo.toml").to_string_lossy().into_owned(),
1859            ],
1860            cwd: root.clone(),
1861            env: BTreeMap::new(),
1862            timeout: Duration::from_secs(60),
1863            stdout_limit: 4096,
1864            stderr_limit: 4096,
1865            expected_stdout: None,
1866            expected_stdout_exact: None,
1867        };
1868        for iteration in 0..3 {
1869            spec.timeout = Duration::from_secs(60);
1870            spec.env.remove("EGGPACK_BUILD_SLEEP");
1871            let timeout_target = root.join(format!("cargo-target-timeout-{iteration}"));
1872            spec.env.insert(
1873                "CARGO_TARGET_DIR".into(),
1874                timeout_target.to_string_lossy().into_owned(),
1875            );
1876            let warm_timeout = root.join(format!("warm-timeout-{iteration}"));
1877            spec.env.insert(
1878                "EGGPACK_BUILD_STARTED".into(),
1879                warm_timeout.to_string_lossy().into_owned(),
1880            );
1881            assert_eq!(
1882                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1883                    .unwrap()
1884                    .outcome,
1885                CommandOutcome::Success
1886            );
1887            assert!(warm_timeout.is_file(), "timeout fixture warm-up failed");
1888            spec.timeout = Duration::from_secs(5);
1889            spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
1890            let timeout_started = root.join(format!("timeout-started-{iteration}"));
1891            spec.env.insert(
1892                "EGGPACK_BUILD_STARTED".into(),
1893                timeout_started.to_string_lossy().into_owned(),
1894            );
1895            assert_eq!(
1896                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1897                    .unwrap()
1898                    .outcome,
1899                CommandOutcome::TimedOut
1900            );
1901            assert!(timeout_started.is_file(), "build script never started");
1902
1903            spec.timeout = Duration::from_secs(60);
1904            spec.env.remove("EGGPACK_BUILD_SLEEP");
1905            let cancel_target = root.join(format!("cargo-target-cancel-{iteration}"));
1906            spec.env.insert(
1907                "CARGO_TARGET_DIR".into(),
1908                cancel_target.to_string_lossy().into_owned(),
1909            );
1910            let warm_cancel = root.join(format!("warm-cancel-{iteration}"));
1911            spec.env.insert(
1912                "EGGPACK_BUILD_STARTED".into(),
1913                warm_cancel.to_string_lossy().into_owned(),
1914            );
1915            assert_eq!(
1916                run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Builder)
1917                    .unwrap()
1918                    .outcome,
1919                CommandOutcome::Success
1920            );
1921            assert!(warm_cancel.is_file(), "cancellation fixture warm-up failed");
1922
1923            spec.timeout = Duration::from_secs(180);
1924            spec.env.insert("EGGPACK_BUILD_SLEEP".into(), "1".into());
1925            let cancellation = BuildCancellation::new();
1926            let request = cancellation.clone();
1927            let cancellation_started = root.join(format!("cancellation-started-{iteration}"));
1928            spec.env.insert(
1929                "EGGPACK_BUILD_STARTED".into(),
1930                cancellation_started.to_string_lossy().into_owned(),
1931            );
1932            let cancellation_started_by_thread = cancellation_started.clone();
1933            let canceller = thread::spawn(move || {
1934                let deadline = Instant::now() + Duration::from_secs(15);
1935                while !cancellation_started_by_thread.is_file() && Instant::now() < deadline {
1936                    thread::sleep(Duration::from_millis(10));
1937                }
1938                assert!(
1939                    cancellation_started_by_thread.is_file(),
1940                    "build script did not start before cancellation deadline"
1941                );
1942                request.cancel();
1943            });
1944            assert_eq!(
1945                run_bounded_cancellable(&spec, &cancellation)
1946                    .unwrap()
1947                    .outcome,
1948                CommandOutcome::Cancelled
1949            );
1950            canceller.join().unwrap();
1951            assert!(cancellation_started.is_file());
1952        }
1953        fs::remove_dir_all(root).unwrap();
1954    }
1955    // Not standalone coverage: this is a child fixture re-executed by
1956    // `parked_drain_reader_cannot_outlive_the_deadline` in this test binary.
1957    // It returns immediately after spawning a descendant that inherits the
1958    // stdout write end, so no EOF ever arrives on that pipe.
1959    #[test]
1960    #[ignore]
1961    // Detaching the grandchild is the behaviour under test: this fixture must
1962    // return while the descendant is still running, so waiting on it is exactly
1963    // what cannot happen here. The test harness exits immediately afterwards.
1964    #[allow(clippy::zombie_processes)]
1965    fn builder_child_leaves_parked_descendant() {
1966        std::process::Command::new(std::env::current_exe().unwrap())
1967            .args([
1968                "--exact",
1969                "builder::tests::builder_child_holds_stdout",
1970                "--ignored",
1971                "--nocapture",
1972            ])
1973            .spawn()
1974            .unwrap();
1975    }
1976
1977    /// Child fixture: outlives its parent, holding the inherited pipe open.
1978    #[test]
1979    #[ignore]
1980    fn builder_child_holds_stdout() {
1981        std::thread::sleep(Duration::from_secs(20));
1982    }
1983
1984    /// A child that exits normally while a descendant still holds its stdout
1985    /// write end must not park the runner. Pipe EOF never arrives, so the
1986    /// drain join has to be bounded and the run has to fail closed.
1987    #[test]
1988    fn parked_drain_reader_cannot_outlive_the_deadline() {
1989        let spec = CommandSpec {
1990            executable: std::env::current_exe()
1991                .unwrap()
1992                .to_string_lossy()
1993                .into_owned(),
1994            args: vec![
1995                "--exact".into(),
1996                "builder::tests::builder_child_leaves_parked_descendant".into(),
1997                "--ignored".into(),
1998                "--nocapture".into(),
1999            ],
2000            cwd: std::env::current_dir().unwrap(),
2001            env: BTreeMap::new(),
2002            timeout: Duration::from_secs(10),
2003            stdout_limit: 4096,
2004            stderr_limit: 4096,
2005            expected_stdout: None,
2006            expected_stdout_exact: None,
2007        };
2008        let started = Instant::now();
2009        let evidence =
2010            run_bounded_inner(&spec, Cancellation::None, ExecutableAllowance::Candidate).unwrap();
2011        assert_eq!(
2012            evidence.outcome,
2013            CommandOutcome::OutputLimitExceeded,
2014            "a parked drain reader must fail the run closed, not report success"
2015        );
2016        assert!(
2017            started.elapsed() < Duration::from_secs(15),
2018            "bounded run took {:?}; the parked reader defeated the deadline",
2019            started.elapsed()
2020        );
2021    }
2022    #[test]
2023    fn real_local_cargo_fixture_builds_a_direct_candidate() {
2024        let _cargo_guard = CARGO_FIXTURE_LOCK.lock().unwrap();
2025        let base = crate::test_temp_dir("cargo-smoke");
2026        let repo = base.join("repo");
2027        let work = base.join("work");
2028        fs::create_dir_all(repo.join("src")).unwrap();
2029        fs::create_dir_all(&work).unwrap();
2030        fs::write(
2031            repo.join("Cargo.toml"),
2032            "[package]\nname='smoke-fixture'\nversion='0.1.0'\nedition='2021'\n",
2033        )
2034        .unwrap();
2035        fs::write(
2036            repo.join("Cargo.lock"),
2037            "version = 3\n\n[[package]]\nname = \"smoke-fixture\"\nversion = \"0.1.0\"\n",
2038        )
2039        .unwrap();
2040        fs::write(repo.join("src/main.rs"), "fn main() {}\n").unwrap();
2041        let mut t = target();
2042        t.policy.toolchain.rust = "stable".into();
2043        let (triple, os, arch) = match (std::env::consts::OS, std::env::consts::ARCH) {
2044            ("windows", "x86_64") => ("x86_64-pc-windows-msvc", HostOs::Windows, HostArch::X86_64),
2045            ("macos", "x86_64") => ("x86_64-apple-darwin", HostOs::Macos, HostArch::X86_64),
2046            ("macos", "aarch64") => ("aarch64-apple-darwin", HostOs::Macos, HostArch::Aarch64),
2047            ("linux", "x86_64") => ("x86_64-unknown-linux-gnu", HostOs::Linux, HostArch::X86_64),
2048            ("linux", "aarch64") => (
2049                "aarch64-unknown-linux-gnu",
2050                HostOs::Linux,
2051                HostArch::Aarch64,
2052            ),
2053            other => panic!("unsupported hosted Cargo smoke platform: {other:?}"),
2054        };
2055        t.target = triple.into();
2056        t.policy.target = triple.into();
2057        t.policy.host_os = os;
2058        t.policy.host_arch = arch;
2059        let binding = BuildBinding {
2060            selector: LogicalOutputSelector::Direct,
2061            package: "smoke-fixture".into(),
2062            binary: "smoke-fixture".into(),
2063        };
2064        let plan = ReleasePlan {
2065            schema_version: 1,
2066            release_id: "test".into(),
2067            source_revision: "abc".into(),
2068            targets: vec![t.clone()],
2069        };
2070        let attempt = execute_target(&plan, &t, &[binding], &repo, &work, "smoke").unwrap();
2071        assert_eq!(attempt.process.outcome, CommandOutcome::Success);
2072        assert_eq!(attempt.release_id, plan.release_id);
2073        assert_eq!(attempt.source_revision, plan.source_revision);
2074        assert_eq!(attempt.candidates.len(), 1);
2075        assert!(attempt.candidates[0].size > 0);
2076        fs::remove_dir_all(base).unwrap();
2077    }
2078}