Skip to main content

eggpack_core/
qualification.rs

1//! Typed qualification bindings, bounded native/QEMU execution, and candidate evidence.
2
3use crate::{
4    builder::{
5        run_qemu_process, run_qualification_process, CandidateArtifact, CommandSpec,
6        ProcessEvidence,
7    },
8    file_digest, BuildAttempt, BuildBindingsV1, BuildCancellation, DigestError,
9    FloorUnverifiedReason, FloorVerificationStatus, HostArch, HostOs, HostRequirement,
10    LogicalOutputSelector, PlannedTarget, Qualification, ReleasePlan, SupportTier,
11};
12use eggpack_contract::DistributionContract;
13use serde::{Deserialize, Serialize};
14use std::{
15    collections::BTreeMap,
16    fs::{self, File},
17    io::{Read, Seek, SeekFrom},
18    path::{Path, PathBuf},
19    time::Duration,
20};
21
22const MAX_TARGETS: usize = 256;
23const MAX_ARGS: usize = 128;
24const MAX_ARG_LEN: usize = 4096;
25const MAX_CAPTURE: usize = 256 * 1024;
26const MAX_BINARY_HEADER: u64 = 4096;
27
28/// Qualification binding validation or execution setup error.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct QualificationError(String);
31impl std::fmt::Display for QualificationError {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        f.write_str(&self.0)
34    }
35}
36impl std::error::Error for QualificationError {}
37fn qerr(message: &str) -> QualificationError {
38    QualificationError(message.to_owned())
39}
40
41/// One fixed-argument smoke invocation for an exact logical candidate.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(deny_unknown_fields)]
44pub struct CandidateSmokeBinding {
45    /// Exact contract logical output selector; never inferred as a primary output.
46    pub selector: LogicalOutputSelector,
47    /// Fixed arguments passed directly to the selected candidate, without a shell.
48    #[serde(default)]
49    pub argv: Vec<String>,
50    /// Per-process deadline in milliseconds (1..=86,400,000).
51    pub timeout_ms: u64,
52    /// Retained stdout bound (1..=262,144 bytes).
53    pub stdout_limit: usize,
54    /// Retained stderr bound (1..=262,144 bytes).
55    pub stderr_limit: usize,
56}
57
58/// Qualification settings for one canonical planned target.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
60#[serde(deny_unknown_fields)]
61pub struct TargetQualificationBinding {
62    /// One candidate smoke check; required by Native, DeferredNative, and Emulated.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub smoke: Option<CandidateSmokeBinding>,
65}
66
67/// Strict producer-side qualification bindings schema version 1.
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(deny_unknown_fields)]
70pub struct QualificationBindingsV1 {
71    /// Schema version, exactly 1.
72    pub schema_version: u32,
73    /// Settings keyed by canonical target triple.
74    pub targets: BTreeMap<String, TargetQualificationBinding>,
75}
76
77impl QualificationBindingsV1 {
78    /// Strictly parse TOML qualification bindings.
79    pub fn from_toml(text: &str) -> Result<Self, QualificationError> {
80        let value: Self = toml::from_str(text).map_err(|_| qerr("invalid qualification TOML"))?;
81        value.validate_shape()?;
82        Ok(value)
83    }
84
85    /// Validate exact selected-target coverage and smoke selectors against build bindings.
86    pub fn validate_for(
87        &self,
88        plan: &ReleasePlan,
89        build_bindings: &BuildBindingsV1,
90    ) -> Result<(), QualificationError> {
91        self.validate_shape()?;
92        if self.targets.len() != plan.targets.len()
93            || self
94                .targets
95                .keys()
96                .any(|target| !plan.targets.iter().any(|planned| &planned.target == target))
97        {
98            return Err(qerr(
99                "qualification target inventory differs from ReleasePlan",
100            ));
101        }
102        for target in &plan.targets {
103            let settings = self
104                .targets
105                .get(&target.target)
106                .ok_or_else(|| qerr("qualification target binding missing"))?;
107            let must_smoke = matches!(
108                target.policy.qualification,
109                Qualification::Native | Qualification::DeferredNative | Qualification::Emulated
110            );
111            if settings.smoke.is_some() != must_smoke {
112                return Err(qerr(
113                    "smoke binding does not match qualification classification",
114                ));
115            }
116            if let Some(smoke) = &settings.smoke {
117                let candidates = build_bindings
118                    .targets
119                    .get(&target.target)
120                    .ok_or_else(|| qerr("build target binding missing"))?;
121                if !candidates
122                    .iter()
123                    .any(|candidate| candidate.selector == smoke.selector)
124                {
125                    return Err(qerr("smoke selector is absent from build bindings"));
126                }
127            }
128            if target.policy.qualification == Qualification::DeferredNative
129                && target.policy.qualification_host.is_none()
130            {
131                return Err(qerr("DeferredNative requires qualification_host"));
132            }
133        }
134        Ok(())
135    }
136
137    fn validate_shape(&self) -> Result<(), QualificationError> {
138        if self.schema_version != 1 || self.targets.is_empty() || self.targets.len() > MAX_TARGETS {
139            return Err(qerr("unsupported version or invalid target count"));
140        }
141        for (target, binding) in &self.targets {
142            if target.is_empty()
143                || target.len() > 128
144                || !target
145                    .bytes()
146                    .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b))
147            {
148                return Err(qerr("invalid canonical target key"));
149            }
150            if let Some(smoke) = &binding.smoke {
151                if smoke.timeout_ms == 0
152                    || smoke.timeout_ms > 86_400_000
153                    || smoke.stdout_limit == 0
154                    || smoke.stdout_limit > MAX_CAPTURE
155                    || smoke.stderr_limit == 0
156                    || smoke.stderr_limit > MAX_CAPTURE
157                    || smoke.argv.len() > MAX_ARGS
158                    || smoke.argv.iter().any(|arg| {
159                        arg.len() > MAX_ARG_LEN
160                            || arg.contains('\0')
161                            || arg.bytes().any(|b| b.is_ascii_control())
162                    })
163                {
164                    return Err(qerr("smoke bounds or arguments are invalid"));
165                }
166            }
167        }
168        Ok(())
169    }
170}
171
172/// Bounded QEMU runtime input. The executable and flags are fixed by the target mapping.
173#[derive(Debug, Clone, PartialEq, Eq, Default)]
174pub struct QualificationRuntime {
175    /// Optional absolute QEMU user-mode sysroot directory used with `-L`.
176    pub qemu_sysroot: Option<PathBuf>,
177}
178
179/// Actual qualification method, distinct from requested policy.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(rename_all = "snake_case")]
182pub enum QualificationMethod {
183    /// Candidate was directly run on the matching native qualification host.
184    Native,
185    /// DeferredNative was inspected on a different host and remains pending.
186    Deferred,
187    /// DeferredNative candidate ran on its matching later native host.
188    DeferredNativeOnNativeHost,
189    /// Candidate ran through a finite QEMU Linux user-mode mapping.
190    QemuUser,
191    /// Candidate structure was checked but no execution occurred.
192    Structural,
193}
194
195/// Typed qualification outcome; a built candidate can never imply Passed by itself.
196#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(rename_all = "snake_case")]
198pub enum QualificationStatus {
199    /// Structural and any required execution checks passed.
200    Passed,
201    /// DeferredNative execution is pending on its required host.
202    Deferred,
203    /// Qualification failed for the bounded reason below.
204    Failed(QualificationFailure),
205}
206
207/// Bounded reason for failed qualification.
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(rename_all = "snake_case")]
210pub enum QualificationFailure {
211    /// Candidate format or architecture does not match the planned target.
212    StructuralMismatch,
213    /// Candidate bytes changed during qualification.
214    CandidateChanged,
215    /// The executing host does not match the required qualification host.
216    HostMismatch,
217    /// Candidate smoke exited unsuccessfully or could not be started.
218    SmokeFailed,
219    /// Candidate smoke exceeded its deadline.
220    SmokeTimedOut,
221    /// Candidate smoke exceeded its output bound.
222    OutputLimitExceeded,
223    /// Required finite QEMU executable was unavailable or failed preflight.
224    EmulatorUnavailable,
225    /// QEMU process failed or returned a non-zero exit status.
226    EmulatorFailed,
227    /// Candidate could not be safely read or its runtime preconditions failed.
228    InvalidRuntimeEnvironment,
229    /// The produced bytes require a newer runtime than the declared
230    /// compatibility floor, so the declared floor is false.
231    FloorNotSatisfied,
232}
233
234/// Supported executable file formats checked structurally.
235#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
236#[serde(rename_all = "snake_case")]
237pub enum CandidateFormat {
238    /// ELF executable.
239    Elf,
240    /// PE/COFF executable.
241    PeCoff,
242    /// Thin Mach-O executable.
243    MachO,
244}
245
246/// Supported executable CPU architectures.
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "snake_case")]
249pub enum CandidateArchitecture {
250    /// x86-64.
251    X86_64,
252    /// AArch64.
253    Aarch64,
254    /// 32-bit ARM.
255    Armv7,
256}
257
258/// Exact candidate byte and structural identity observed for qualification.
259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260#[serde(deny_unknown_fields)]
261pub struct QualifiedCandidateEvidence {
262    /// Contract logical output selector.
263    pub selector: LogicalOutputSelector,
264    /// Explicit M002 source package.
265    pub package: String,
266    /// Explicit M002 binary target.
267    pub binary: String,
268    /// Number of bytes observed.
269    pub size: u64,
270    /// SHA-256 of exact pre-qualification bytes.
271    pub sha256: String,
272    /// Detected executable format.
273    pub format: CandidateFormat,
274    /// Detected machine architecture.
275    pub architecture: CandidateArchitecture,
276}
277
278/// One bounded process result without output contents or environment values.
279#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(deny_unknown_fields)]
281pub struct QualificationProcessEvidence {
282    /// `candidate_smoke` or `qemu_preflight`.
283    pub purpose: String,
284    /// Candidate selector associated with execution, absent for QEMU preflight.
285    pub selector: Option<LogicalOutputSelector>,
286    /// Exit/deadline/cancellation/output-limit classification.
287    pub process: ProcessEvidence,
288}
289
290/// Complete bounded evidence for one release target qualification attempt.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(deny_unknown_fields)]
293pub struct QualificationEvidence {
294    /// Schema version, exactly 1.
295    pub schema_version: u32,
296    /// Release identity from ReleasePlan and BuildAttempt.
297    pub release_id: String,
298    /// Source revision from ReleasePlan and BuildAttempt.
299    pub source_revision: String,
300    /// Canonical target triple.
301    pub target: String,
302    /// Requested qualification classification.
303    pub planned_classification: Qualification,
304    /// Method actually applied.
305    pub method: QualificationMethod,
306    /// Actual host capability used for this attempt.
307    pub actual_host: HostRequirement,
308    /// Support tier, recorded without changing result semantics.
309    pub support: SupportTier,
310    /// Typed result.
311    pub status: QualificationStatus,
312    /// Verification status of the declared compatibility floor.
313    ///
314    /// The status is bound to the exact bytes this record describes: it is
315    /// computed from the inspected candidate, never from a smoke run, because
316    /// native execution is never floor proof (ADR-0005 ยง9). A document that
317    /// omits the field is read as `NotDeclared`, which is refused for any
318    /// target that declares a floor.
319    #[serde(default)]
320    pub floor: FloorVerificationStatus,
321    /// Per-candidate evidence ordered by logical selector.
322    pub candidates: Vec<QualifiedCandidateEvidence>,
323    /// Configured smoke selector, if this mode has a smoke check.
324    pub smoke_selector: Option<LogicalOutputSelector>,
325    /// Bounded process outcome summaries.
326    pub processes: Vec<QualificationProcessEvidence>,
327}
328
329impl QualificationEvidence {
330    /// Validate evidence identity, candidate inventory, classification, and bounded fields.
331    pub fn validate_for(
332        &self,
333        plan: &ReleasePlan,
334        target: &PlannedTarget,
335        attempt: &BuildAttempt,
336    ) -> Result<(), QualificationError> {
337        if self.schema_version != 1
338            || !plan.targets.iter().any(|planned| planned == target)
339            || self.release_id != plan.release_id
340            || self.source_revision != plan.source_revision
341            || attempt.release_id != plan.release_id
342            || attempt.source_revision != plan.source_revision
343            || self.target != target.target
344            || self.planned_classification != target.policy.qualification
345            || self.support != target.policy.support
346            || (!matches!(self.status, QualificationStatus::Failed(_))
347                && self.candidates.len() != attempt.candidates.len())
348            || self.candidates.len() > 256
349            || self.processes.len() > 1 + MAX_ARGS
350            || target.floor_status != crate::planned_floor_status(&target.policy)
351            || !crate::floor_status_admissible(
352                &target.policy.floor,
353                target.policy.strategy,
354                self.floor,
355            )
356            || (self.floor == FloorVerificationStatus::NotSatisfied)
357                != matches!(
358                    self.status,
359                    QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied)
360                )
361        {
362            return Err(qerr(
363                "qualification evidence identity or bounds are invalid",
364            ));
365        }
366        let mut expected_candidates = BTreeMap::new();
367        for candidate in &attempt.candidates {
368            if expected_candidates
369                .insert(candidate.selector.clone(), candidate)
370                .is_some()
371            {
372                return Err(qerr("BuildAttempt candidate selector is duplicated"));
373            }
374        }
375        for record in &self.candidates {
376            let candidate = expected_candidates
377                .get(&record.selector)
378                .ok_or_else(|| qerr("qualification evidence contains an unknown candidate"))?;
379            if record.selector != candidate.selector
380                || record.package != candidate.package
381                || record.binary != candidate.binary
382                || record.size != candidate.size
383                || crate::validate_sha256_hex(&record.sha256).is_err()
384            {
385                return Err(qerr("qualification evidence candidate identity is invalid"));
386            }
387        }
388        if self
389            .candidates
390            .windows(2)
391            .any(|pair| pair[0].selector >= pair[1].selector)
392            || self.processes.iter().any(|process| {
393                process.purpose.len() > 64
394                    || process.process.stdout_bytes > MAX_CAPTURE
395                    || process.process.stderr_bytes > MAX_CAPTURE
396            })
397        {
398            return Err(qerr(
399                "qualification evidence ordering or process bounds are invalid",
400            ));
401        }
402        let method_matches = matches!(
403            (target.policy.qualification, self.method),
404            (Qualification::Native, QualificationMethod::Native)
405                | (Qualification::DeferredNative, QualificationMethod::Deferred)
406                | (
407                    Qualification::DeferredNative,
408                    QualificationMethod::DeferredNativeOnNativeHost
409                )
410                | (Qualification::Emulated, QualificationMethod::QemuUser)
411                | (Qualification::Structural, QualificationMethod::Structural)
412        );
413        if !method_matches
414            || (self.status == QualificationStatus::Deferred
415                && (self.method != QualificationMethod::Deferred
416                    || !self.processes.is_empty()
417                    || target.policy.qualification_host.is_none()
418                    || target.policy.qualification_host == Some(self.actual_host)))
419            || (self.status == QualificationStatus::Passed
420                && self.method == QualificationMethod::Deferred)
421            || (self.method == QualificationMethod::Structural
422                && (!self.processes.is_empty() || self.smoke_selector.is_some()))
423            || (self.status == QualificationStatus::Passed
424                && matches!(
425                    target.policy.qualification,
426                    Qualification::Native | Qualification::DeferredNative | Qualification::Emulated
427                )
428                && self.smoke_selector.is_none())
429            || (self.status == QualificationStatus::Passed
430                && matches!(
431                    self.method,
432                    QualificationMethod::Native | QualificationMethod::DeferredNativeOnNativeHost
433                )
434                && !target_matches_host(&target.target, self.actual_host))
435            || (self.status == QualificationStatus::Passed
436                && target.policy.qualification == Qualification::Native
437                && target
438                    .policy
439                    .qualification_host
440                    .is_some_and(|required| required != self.actual_host))
441            || (self.status == QualificationStatus::Passed
442                && target.policy.qualification == Qualification::DeferredNative
443                && target
444                    .policy
445                    .qualification_host
446                    .is_some_and(|required| required != self.actual_host))
447            || (self.status == QualificationStatus::Passed
448                && target.policy.qualification == Qualification::Emulated
449                && target
450                    .policy
451                    .qualification_host
452                    .is_some_and(|required| required != self.actual_host))
453            || (self.status == QualificationStatus::Passed
454                && self
455                    .processes
456                    .iter()
457                    .any(|evidence| evidence.process.outcome != crate::CommandOutcome::Success))
458            || (self.status == QualificationStatus::Passed
459                && self.processes.iter().any(|evidence| {
460                    match (
461                        self.method,
462                        evidence.purpose.as_str(),
463                        evidence.selector.as_ref(),
464                    ) {
465                        (
466                            QualificationMethod::Native
467                            | QualificationMethod::DeferredNativeOnNativeHost,
468                            "candidate_smoke",
469                            Some(selector),
470                        ) => self.smoke_selector.as_ref() != Some(selector),
471                        (QualificationMethod::QemuUser, "qemu_preflight", None) => false,
472                        (QualificationMethod::QemuUser, "candidate_smoke", Some(selector)) => {
473                            self.smoke_selector.as_ref() != Some(selector)
474                        }
475                        _ => true,
476                    }
477                }))
478            || (self.status == QualificationStatus::Passed
479                && match self.method {
480                    QualificationMethod::Native
481                    | QualificationMethod::DeferredNativeOnNativeHost => self.processes.len() != 1,
482                    QualificationMethod::QemuUser => self.processes.len() != 2,
483                    QualificationMethod::Structural => !self.processes.is_empty(),
484                    QualificationMethod::Deferred => true,
485                })
486        {
487            return Err(qerr(
488                "qualification evidence method or status is inconsistent",
489            ));
490        }
491        Ok(())
492    }
493}
494
495/// All explicit producer-side inputs required to qualify one planned target.
496pub struct QualificationRequest<'a> {
497    /// Portable distribution identity authority.
498    pub contract: &'a DistributionContract,
499    /// Invocation release plan.
500    pub plan: &'a ReleasePlan,
501    /// One exact selected plan target.
502    pub target: &'a PlannedTarget,
503    /// Successful M002 candidate build attempt.
504    pub attempt: &'a BuildAttempt,
505    /// Exact package/binary to logical-slot bindings used by M002.
506    pub build_bindings: &'a BuildBindingsV1,
507    /// Exact qualification smoke policy.
508    pub qualification_bindings: &'a QualificationBindingsV1,
509    /// Optional explicitly supplied runtime-specific path inputs.
510    pub runtime: &'a QualificationRuntime,
511    /// Caller cancellation flag.
512    pub cancellation: &'a BuildCancellation,
513}
514
515/// Execute M003 qualification using actual local host facts.
516pub fn qualify_target(
517    request: QualificationRequest<'_>,
518) -> Result<QualificationEvidence, QualificationError> {
519    let QualificationRequest {
520        contract,
521        plan,
522        target,
523        attempt,
524        build_bindings,
525        qualification_bindings,
526        runtime,
527        cancellation,
528    } = request;
529    let host = actual_host()?;
530    qualify_target_for_host(
531        contract,
532        plan,
533        target,
534        attempt,
535        build_bindings,
536        qualification_bindings,
537        runtime,
538        cancellation,
539        host,
540    )
541}
542
543#[allow(clippy::too_many_arguments)]
544fn qualify_target_for_host(
545    contract: &DistributionContract,
546    plan: &ReleasePlan,
547    target: &PlannedTarget,
548    attempt: &BuildAttempt,
549    build_bindings: &BuildBindingsV1,
550    qualification_bindings: &QualificationBindingsV1,
551    runtime: &QualificationRuntime,
552    cancellation: &BuildCancellation,
553    host: HostRequirement,
554) -> Result<QualificationEvidence, QualificationError> {
555    let runner = |spec: &CommandSpec, qemu: bool| {
556        let result = if qemu {
557            run_qemu_process(spec, cancellation)
558        } else {
559            run_qualification_process(spec, cancellation)
560        };
561        result.map_err(|_| ())
562    };
563    qualify_target_for_host_with_runner(
564        contract,
565        plan,
566        target,
567        attempt,
568        build_bindings,
569        qualification_bindings,
570        runtime,
571        cancellation,
572        host,
573        &runner,
574    )
575}
576
577#[allow(clippy::too_many_arguments)]
578fn qualify_target_for_host_with_runner<F>(
579    contract: &DistributionContract,
580    plan: &ReleasePlan,
581    target: &PlannedTarget,
582    attempt: &BuildAttempt,
583    build_bindings: &BuildBindingsV1,
584    qualification_bindings: &QualificationBindingsV1,
585    runtime: &QualificationRuntime,
586    cancellation: &BuildCancellation,
587    host: HostRequirement,
588    runner: &F,
589) -> Result<QualificationEvidence, QualificationError>
590where
591    F: Fn(&CommandSpec, bool) -> Result<ProcessEvidence, ()>,
592{
593    if plan.schema_version != 1
594        || plan.release_id.is_empty()
595        || plan.source_revision.is_empty()
596        || !plan.targets.iter().any(|planned| planned == target)
597        || attempt.release_id != plan.release_id
598        || attempt.source_revision != plan.source_revision
599        || attempt.target != target.target
600        || attempt.strategy != target.policy.strategy
601        || attempt.process.outcome != crate::CommandOutcome::Success
602        || attempt.candidates.is_empty()
603        || attempt.candidates.len() > 256
604    {
605        return Err(qerr(
606            "BuildAttempt identity or result does not match ReleasePlan",
607        ));
608    }
609    build_bindings
610        .validate_for(contract, plan)
611        .map_err(|_| qerr("BuildBindings do not exactly cover ReleasePlan"))?;
612    qualification_bindings.validate_for(plan, build_bindings)?;
613    validate_runtime(runtime)?;
614    if target.policy.qualification != Qualification::Emulated && runtime.qemu_sysroot.is_some() {
615        return Err(qerr(
616            "QEMU sysroot is only valid for Emulated qualification",
617        ));
618    }
619
620    let target_builds = build_bindings
621        .targets
622        .get(&target.target)
623        .ok_or_else(|| qerr("build target binding missing"))?;
624    let mut expected = BTreeMap::new();
625    for binding in target_builds {
626        expected.insert(
627            binding.selector.clone(),
628            (binding.package.as_str(), binding.binary.as_str()),
629        );
630    }
631    let mut actual = BTreeMap::new();
632    for candidate in &attempt.candidates {
633        if candidate.target != target.target
634            || actual
635                .insert(
636                    candidate.selector.clone(),
637                    (
638                        candidate.package.as_str(),
639                        candidate.binary.as_str(),
640                        candidate,
641                    ),
642                )
643                .is_some()
644        {
645            return Err(qerr("candidate target or selector is duplicated"));
646        }
647    }
648    if expected.len() != actual.len()
649        || expected.iter().any(|(selector, (package, binary))| {
650            actual
651                .get(selector)
652                .is_none_or(|(actual_package, actual_binary, _)| {
653                    package != actual_package || binary != actual_binary
654                })
655        })
656    {
657        return Err(qerr(
658            "BuildAttempt candidate inventory differs from BuildBindings",
659        ));
660    }
661
662    let mut evidence_candidates = Vec::new();
663    let mut candidate_floors = Vec::new();
664    for (selector, (_, _, candidate)) in &actual {
665        match inspect_candidate(candidate, target) {
666            Ok(inspected) => {
667                candidate_floors.push(inspected.floor);
668                evidence_candidates.push(inspected.evidence);
669            }
670            Err(failure) => {
671                let method = match target.policy.qualification {
672                    Qualification::Native => QualificationMethod::Native,
673                    Qualification::DeferredNative => QualificationMethod::Deferred,
674                    Qualification::Emulated => QualificationMethod::QemuUser,
675                    Qualification::Structural => QualificationMethod::Structural,
676                };
677                return Ok(make_evidence(
678                    plan,
679                    target,
680                    host,
681                    method,
682                    QualificationStatus::Failed(failure),
683                    Vec::new(),
684                    None,
685                    Vec::new(),
686                    FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate),
687                ));
688            }
689        }
690        debug_assert_eq!(
691            evidence_candidates.last().map(|c| &c.selector),
692            Some(selector)
693        );
694    }
695    let floor = crate::floor::aggregate_floor_status(&candidate_floors);
696    let settings = qualification_bindings
697        .targets
698        .get(&target.target)
699        .expect("validated target qualification binding");
700    let smoke = settings.smoke.as_ref();
701    let selected_smoke = smoke.and_then(|binding| actual.get(&binding.selector).map(|v| v.2));
702    if smoke.is_some() && selected_smoke.is_none() {
703        return Err(qerr("smoke selector is absent from candidate inventory"));
704    }
705    // A declared floor that the produced bytes contradict is false, so it
706    // fails the qualification for this target before anything executes. It is
707    // never reported as merely unverified.
708    if floor == FloorVerificationStatus::NotSatisfied {
709        let method = match target.policy.qualification {
710            Qualification::Native => QualificationMethod::Native,
711            Qualification::DeferredNative => QualificationMethod::Deferred,
712            Qualification::Emulated => QualificationMethod::QemuUser,
713            Qualification::Structural => QualificationMethod::Structural,
714        };
715        return Ok(make_evidence(
716            plan,
717            target,
718            host,
719            method,
720            QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied),
721            evidence_candidates,
722            smoke.map(|s| s.selector.clone()),
723            Vec::new(),
724            floor,
725        ));
726    }
727
728    let (method, should_execute) = match target.policy.qualification {
729        Qualification::Structural => (QualificationMethod::Structural, false),
730        Qualification::Native => {
731            let required = target.policy.qualification_host.unwrap_or(HostRequirement {
732                os: target.policy.host_os,
733                arch: target.policy.host_arch,
734            });
735            if host != required || !target_matches_host(&target.target, host) {
736                return Ok(make_evidence(
737                    plan,
738                    target,
739                    host,
740                    QualificationMethod::Native,
741                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
742                    evidence_candidates,
743                    smoke.map(|s| s.selector.clone()),
744                    Vec::new(),
745                    floor,
746                ));
747            }
748            (QualificationMethod::Native, true)
749        }
750        Qualification::DeferredNative => {
751            let required = target
752                .policy
753                .qualification_host
754                .ok_or_else(|| qerr("DeferredNative requires qualification_host"))?;
755            if host != required {
756                return Ok(make_evidence(
757                    plan,
758                    target,
759                    host,
760                    QualificationMethod::Deferred,
761                    QualificationStatus::Deferred,
762                    evidence_candidates,
763                    smoke.map(|s| s.selector.clone()),
764                    Vec::new(),
765                    floor,
766                ));
767            }
768            if !target_matches_host(&target.target, host) {
769                return Ok(make_evidence(
770                    plan,
771                    target,
772                    host,
773                    QualificationMethod::DeferredNativeOnNativeHost,
774                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
775                    evidence_candidates,
776                    smoke.map(|s| s.selector.clone()),
777                    Vec::new(),
778                    floor,
779                ));
780            }
781            (QualificationMethod::DeferredNativeOnNativeHost, true)
782        }
783        Qualification::Emulated => {
784            if !target.target.contains("-linux-")
785                || evidence_candidates
786                    .iter()
787                    .any(|c| c.format != CandidateFormat::Elf)
788            {
789                return Ok(make_evidence(
790                    plan,
791                    target,
792                    host,
793                    QualificationMethod::QemuUser,
794                    QualificationStatus::Failed(QualificationFailure::StructuralMismatch),
795                    evidence_candidates,
796                    smoke.map(|s| s.selector.clone()),
797                    Vec::new(),
798                    floor,
799                ));
800            }
801            if target
802                .policy
803                .qualification_host
804                .is_some_and(|required| required != host)
805            {
806                return Ok(make_evidence(
807                    plan,
808                    target,
809                    host,
810                    QualificationMethod::QemuUser,
811                    QualificationStatus::Failed(QualificationFailure::HostMismatch),
812                    evidence_candidates,
813                    smoke.map(|s| s.selector.clone()),
814                    Vec::new(),
815                    floor,
816                ));
817            }
818            (QualificationMethod::QemuUser, true)
819        }
820    };
821    if !should_execute {
822        return Ok(make_evidence(
823            plan,
824            target,
825            host,
826            method,
827            QualificationStatus::Passed,
828            evidence_candidates,
829            None,
830            Vec::new(),
831            floor,
832        ));
833    }
834    let smoke = smoke.ok_or_else(|| qerr("execution qualification requires a smoke binding"))?;
835    let candidate = selected_smoke.expect("smoke selector was validated");
836    let mut processes = Vec::new();
837    if method == QualificationMethod::QemuUser {
838        let emulator =
839            qemu_for_target(&target.target).ok_or_else(|| qerr("unsupported QEMU target"))?;
840        let preflight = CommandSpec {
841            executable: emulator.into(),
842            args: vec!["--version".into()],
843            cwd: qualification_cwd(candidate)?,
844            env: BTreeMap::new(),
845            timeout: Duration::from_secs(10),
846            stdout_limit: 8192,
847            stderr_limit: 8192,
848            expected_stdout: None,
849            expected_stdout_exact: None,
850        };
851        let result = match runner(&preflight, true) {
852            Ok(result) => result,
853            Err(_) => {
854                return Ok(make_evidence(
855                    plan,
856                    target,
857                    host,
858                    method,
859                    QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable),
860                    evidence_candidates,
861                    Some(smoke.selector.clone()),
862                    processes,
863                    floor,
864                ))
865            }
866        };
867        let preflight_ok = result.outcome == crate::CommandOutcome::Success;
868        processes.push(QualificationProcessEvidence {
869            purpose: "qemu_preflight".into(),
870            selector: None,
871            process: result,
872        });
873        if !preflight_ok {
874            return Ok(make_evidence(
875                plan,
876                target,
877                host,
878                method,
879                QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable),
880                evidence_candidates,
881                Some(smoke.selector.clone()),
882                processes,
883                floor,
884            ));
885        }
886    }
887    if cancellation.is_cancelled() {
888        return Ok(make_evidence(
889            plan,
890            target,
891            host,
892            method,
893            QualificationStatus::Failed(QualificationFailure::SmokeFailed),
894            evidence_candidates,
895            Some(smoke.selector.clone()),
896            processes,
897            floor,
898        ));
899    }
900    let (command, is_qemu) = if method == QualificationMethod::QemuUser {
901        let command = CommandSpec {
902            executable: qemu_for_target(&target.target)
903                .expect("validated QEMU target")
904                .into(),
905            args: qemu_args(runtime, candidate, smoke),
906            cwd: qualification_cwd(candidate)?,
907            env: BTreeMap::new(),
908            timeout: Duration::from_millis(smoke.timeout_ms),
909            stdout_limit: smoke.stdout_limit,
910            stderr_limit: smoke.stderr_limit,
911            expected_stdout: None,
912            expected_stdout_exact: None,
913        };
914        (command, true)
915    } else {
916        let command = CommandSpec {
917            executable: candidate.path.to_string_lossy().into_owned(),
918            args: smoke.argv.clone(),
919            cwd: qualification_cwd(candidate)?,
920            env: BTreeMap::new(),
921            timeout: Duration::from_millis(smoke.timeout_ms),
922            stdout_limit: smoke.stdout_limit,
923            stderr_limit: smoke.stderr_limit,
924            expected_stdout: None,
925            expected_stdout_exact: None,
926        };
927        (command, false)
928    };
929    let process = match runner(&command, is_qemu) {
930        Ok(process) => process,
931        Err(_) => {
932            return Ok(make_evidence(
933                plan,
934                target,
935                host,
936                method,
937                QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
938                    QualificationFailure::EmulatorFailed
939                } else {
940                    QualificationFailure::SmokeFailed
941                }),
942                evidence_candidates,
943                Some(smoke.selector.clone()),
944                processes,
945                floor,
946            ))
947        }
948    };
949    let status = status_from_process(process.outcome, method);
950    processes.push(QualificationProcessEvidence {
951        purpose: "candidate_smoke".into(),
952        selector: Some(smoke.selector.clone()),
953        process,
954    });
955    let mut status = status;
956    if status == QualificationStatus::Passed {
957        for (selector, (_, _, candidate)) in &actual {
958            match inspect_candidate(candidate, target) {
959                Ok(after) => {
960                    let before = evidence_candidates
961                        .iter()
962                        .find(|evidence| &evidence.selector == selector)
963                        .expect("preflight candidate evidence");
964                    if after.evidence.size != before.size || after.evidence.sha256 != before.sha256
965                    {
966                        status =
967                            QualificationStatus::Failed(QualificationFailure::CandidateChanged);
968                        break;
969                    }
970                }
971                Err(_) => {
972                    status = QualificationStatus::Failed(QualificationFailure::CandidateChanged);
973                    break;
974                }
975            }
976        }
977    }
978    Ok(make_evidence(
979        plan,
980        target,
981        host,
982        method,
983        status,
984        evidence_candidates,
985        Some(smoke.selector.clone()),
986        processes,
987        floor,
988    ))
989}
990
991#[allow(clippy::too_many_arguments)]
992fn make_evidence(
993    plan: &ReleasePlan,
994    target: &PlannedTarget,
995    host: HostRequirement,
996    method: QualificationMethod,
997    status: QualificationStatus,
998    candidates: Vec<QualifiedCandidateEvidence>,
999    smoke_selector: Option<LogicalOutputSelector>,
1000    processes: Vec<QualificationProcessEvidence>,
1001    floor: FloorVerificationStatus,
1002) -> QualificationEvidence {
1003    QualificationEvidence {
1004        schema_version: 1,
1005        release_id: plan.release_id.clone(),
1006        source_revision: plan.source_revision.clone(),
1007        target: target.target.clone(),
1008        planned_classification: target.policy.qualification,
1009        method,
1010        actual_host: host,
1011        support: target.policy.support,
1012        status,
1013        floor,
1014        candidates,
1015        smoke_selector,
1016        processes,
1017    }
1018}
1019
1020fn status_from_process(
1021    outcome: crate::CommandOutcome,
1022    method: QualificationMethod,
1023) -> QualificationStatus {
1024    match outcome {
1025        crate::CommandOutcome::Success => QualificationStatus::Passed,
1026        crate::CommandOutcome::TimedOut => {
1027            QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
1028                QualificationFailure::EmulatorFailed
1029            } else {
1030                QualificationFailure::SmokeTimedOut
1031            })
1032        }
1033        crate::CommandOutcome::OutputLimitExceeded => {
1034            QualificationStatus::Failed(QualificationFailure::OutputLimitExceeded)
1035        }
1036        crate::CommandOutcome::Failed(_) | crate::CommandOutcome::Cancelled => {
1037            QualificationStatus::Failed(if method == QualificationMethod::QemuUser {
1038                QualificationFailure::EmulatorFailed
1039            } else {
1040                QualificationFailure::SmokeFailed
1041            })
1042        }
1043    }
1044}
1045
1046fn validate_runtime(runtime: &QualificationRuntime) -> Result<(), QualificationError> {
1047    if let Some(sysroot) = &runtime.qemu_sysroot {
1048        if !sysroot.is_absolute() {
1049            return Err(qerr("QEMU sysroot must be absolute"));
1050        }
1051        let metadata =
1052            fs::symlink_metadata(sysroot).map_err(|_| qerr("QEMU sysroot unavailable"))?;
1053        if metadata.file_type().is_symlink() || !metadata.is_dir() {
1054            return Err(qerr("QEMU sysroot must be a regular directory"));
1055        }
1056    }
1057    Ok(())
1058}
1059
1060fn qualification_cwd(candidate: &CandidateArtifact) -> Result<PathBuf, QualificationError> {
1061    let root = candidate
1062        .path
1063        .parent()
1064        .and_then(Path::parent)
1065        .ok_or_else(|| qerr("candidate qualification directory unavailable"))?;
1066    fs::canonicalize(root).map_err(|_| qerr("candidate qualification directory unavailable"))
1067}
1068
1069fn actual_host() -> Result<HostRequirement, QualificationError> {
1070    let os = match std::env::consts::OS {
1071        "linux" => HostOs::Linux,
1072        "macos" => HostOs::Macos,
1073        "windows" => HostOs::Windows,
1074        _ => return Err(qerr("unsupported qualification host OS")),
1075    };
1076    let arch = match std::env::consts::ARCH {
1077        "x86_64" => HostArch::X86_64,
1078        "aarch64" => HostArch::Aarch64,
1079        #[cfg(all(target_arch = "arm", target_feature = "v7"))]
1080        "arm" => HostArch::Armv7,
1081        _ => return Err(qerr("unsupported qualification host architecture")),
1082    };
1083    Ok(HostRequirement { os, arch })
1084}
1085
1086fn target_matches_host(target: &str, host: HostRequirement) -> bool {
1087    let os = match host.os {
1088        HostOs::Linux => target.contains("-linux-"),
1089        HostOs::Macos => target.ends_with("-apple-darwin"),
1090        HostOs::Windows => target.contains("-windows-"),
1091    };
1092    let arch = match host.arch {
1093        HostArch::X86_64 => target.starts_with("x86_64-"),
1094        HostArch::Aarch64 => target.starts_with("aarch64-"),
1095        HostArch::Armv7 => target.starts_with("armv7-"),
1096    };
1097    os && arch
1098}
1099
1100fn qemu_for_target(target: &str) -> Option<&'static str> {
1101    if !target.contains("-linux-") {
1102        return None;
1103    }
1104    match target.split('-').next()? {
1105        "x86_64" => Some("qemu-x86_64"),
1106        "aarch64" => Some("qemu-aarch64"),
1107        "armv7" => Some("qemu-arm"),
1108        _ => None,
1109    }
1110}
1111
1112fn qemu_args(
1113    runtime: &QualificationRuntime,
1114    candidate: &CandidateArtifact,
1115    smoke: &CandidateSmokeBinding,
1116) -> Vec<String> {
1117    let mut args = Vec::new();
1118    if let Some(sysroot) = runtime.qemu_sysroot.as_ref() {
1119        args.extend(["-L".to_owned(), sysroot.to_string_lossy().into_owned()]);
1120    }
1121    args.push(candidate.path.to_string_lossy().into_owned());
1122    args.extend(smoke.argv.clone());
1123    args
1124}
1125
1126fn target_identity(target: &str) -> Option<(CandidateFormat, CandidateArchitecture)> {
1127    let format = if target.contains("-linux-") {
1128        CandidateFormat::Elf
1129    } else if target.ends_with("-apple-darwin") {
1130        CandidateFormat::MachO
1131    } else if target.contains("-windows-") {
1132        CandidateFormat::PeCoff
1133    } else {
1134        return None;
1135    };
1136    let architecture = if target.starts_with("x86_64-") {
1137        CandidateArchitecture::X86_64
1138    } else if target.starts_with("aarch64-") {
1139        CandidateArchitecture::Aarch64
1140    } else if target.starts_with("armv7-") {
1141        CandidateArchitecture::Armv7
1142    } else {
1143        return None;
1144    };
1145    if architecture == CandidateArchitecture::Armv7 && format != CandidateFormat::Elf {
1146        return None;
1147    }
1148    Some((format, architecture))
1149}
1150
1151/// One inspected candidate: its byte and structural identity, plus the floor
1152/// status computed from the same bytes.
1153#[derive(Debug, PartialEq, Eq)]
1154struct CandidateInspection {
1155    /// Byte and structural identity of the candidate.
1156    evidence: QualifiedCandidateEvidence,
1157    /// Verification status of the declared compatibility floor.
1158    floor: FloorVerificationStatus,
1159}
1160
1161fn inspect_candidate(
1162    candidate: &CandidateArtifact,
1163    target: &PlannedTarget,
1164) -> Result<CandidateInspection, QualificationFailure> {
1165    let metadata = fs::symlink_metadata(&candidate.path)
1166        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
1167    if !candidate.path.is_absolute()
1168        || metadata.file_type().is_symlink()
1169        || !metadata.is_file()
1170        || metadata.len() == 0
1171    {
1172        return Err(QualificationFailure::InvalidRuntimeEnvironment);
1173    }
1174    if metadata.len() != candidate.size {
1175        return Err(QualificationFailure::CandidateChanged);
1176    }
1177    let canonical = fs::canonicalize(&candidate.path)
1178        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
1179    let target_dir = candidate
1180        .path
1181        .parent()
1182        .and_then(Path::parent)
1183        .ok_or(QualificationFailure::InvalidRuntimeEnvironment)?;
1184    let release_dir = candidate
1185        .path
1186        .parent()
1187        .ok_or(QualificationFailure::InvalidRuntimeEnvironment)?;
1188    for directory in [target_dir, release_dir] {
1189        let parent = fs::symlink_metadata(directory)
1190            .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
1191        if parent.file_type().is_symlink() || !parent.is_dir() {
1192            return Err(QualificationFailure::InvalidRuntimeEnvironment);
1193        }
1194    }
1195    let canonical_root = fs::canonicalize(target_dir)
1196        .map_err(|_| QualificationFailure::InvalidRuntimeEnvironment)?;
1197    if !canonical.starts_with(canonical_root) {
1198        return Err(QualificationFailure::InvalidRuntimeEnvironment);
1199    }
1200    let (expected_format, expected_arch) =
1201        target_identity(&target.target).ok_or(QualificationFailure::StructuralMismatch)?;
1202    let format_arch = parse_binary_header(&canonical, expected_format)
1203        .ok_or(QualificationFailure::StructuralMismatch)?;
1204    if format_arch != (expected_format, expected_arch) {
1205        return Err(QualificationFailure::StructuralMismatch);
1206    }
1207    // The declared floor is inspected against these exact bytes, never
1208    // against a smoke run: native execution is not floor proof (ADR-0005 ยง9).
1209    // The status therefore describes the same bytes the digest below records.
1210    let floor = crate::floor::inspect_candidate_floor(
1211        &canonical,
1212        &target.policy.floor,
1213        target.policy.strategy,
1214    );
1215    // The candidate bytes are digested by the crate's single file-digest
1216    // authority, so qualification evidence and the release manifest describe
1217    // the same bytes under the same rules.
1218    let (size, sha256) = file_digest(&canonical).map_err(|error| match error {
1219        DigestError::ChangedDuringRead => QualificationFailure::CandidateChanged,
1220        _ => QualificationFailure::InvalidRuntimeEnvironment,
1221    })?;
1222    let after = fs::symlink_metadata(&candidate.path)
1223        .map_err(|_| QualificationFailure::CandidateChanged)?;
1224    if size != metadata.len()
1225        || after.file_type().is_symlink()
1226        || !after.is_file()
1227        || after.len() != size
1228        || fs::canonicalize(&candidate.path).ok().as_ref() != Some(&canonical)
1229    {
1230        return Err(QualificationFailure::CandidateChanged);
1231    }
1232    Ok(CandidateInspection {
1233        evidence: QualifiedCandidateEvidence {
1234            selector: candidate.selector.clone(),
1235            package: candidate.package.clone(),
1236            binary: candidate.binary.clone(),
1237            size,
1238            sha256,
1239            format: expected_format,
1240            architecture: expected_arch,
1241        },
1242        floor,
1243    })
1244}
1245
1246fn parse_binary_header(
1247    path: &Path,
1248    format: CandidateFormat,
1249) -> Option<(CandidateFormat, CandidateArchitecture)> {
1250    let mut file = File::open(path).ok()?;
1251    let length = file.metadata().ok()?.len();
1252    match format {
1253        CandidateFormat::Elf => {
1254            let mut header = [0u8; 20];
1255            file.read_exact(&mut header).ok()?;
1256            if &header[..4] != b"\x7fELF" || header[5] != 1 {
1257                return None;
1258            }
1259            let architecture = match u16::from_le_bytes([header[18], header[19]]) {
1260                62 if header[4] == 2 => CandidateArchitecture::X86_64,
1261                183 if header[4] == 2 => CandidateArchitecture::Aarch64,
1262                40 if header[4] == 1 => CandidateArchitecture::Armv7,
1263                _ => return None,
1264            };
1265            Some((CandidateFormat::Elf, architecture))
1266        }
1267        CandidateFormat::PeCoff => {
1268            let mut dos = [0u8; 64];
1269            file.read_exact(&mut dos).ok()?;
1270            if &dos[..2] != b"MZ" {
1271                return None;
1272            }
1273            let offset = u32::from_le_bytes(dos[60..64].try_into().ok()?) as u64;
1274            if !(64..=MAX_BINARY_HEADER).contains(&offset) || offset.checked_add(6)? > length {
1275                return None;
1276            }
1277            file.seek(SeekFrom::Start(offset)).ok()?;
1278            let mut header = [0u8; 6];
1279            file.read_exact(&mut header).ok()?;
1280            if &header[..4] != b"PE\0\0" {
1281                return None;
1282            }
1283            let architecture = match u16::from_le_bytes([header[4], header[5]]) {
1284                0x8664 => CandidateArchitecture::X86_64,
1285                0xAA64 => CandidateArchitecture::Aarch64,
1286                0x01c4 => CandidateArchitecture::Armv7,
1287                _ => return None,
1288            };
1289            Some((CandidateFormat::PeCoff, architecture))
1290        }
1291        CandidateFormat::MachO => {
1292            let mut header = [0u8; 8];
1293            file.read_exact(&mut header).ok()?;
1294            let endian = match &header[..4] {
1295                [0xfe, 0xed, 0xfa, 0xcf] => false,
1296                [0xcf, 0xfa, 0xed, 0xfe] => true,
1297                _ => return None,
1298            };
1299            let cpu = if endian {
1300                u32::from_le_bytes(header[4..8].try_into().ok()?)
1301            } else {
1302                u32::from_be_bytes(header[4..8].try_into().ok()?)
1303            };
1304            let architecture = match cpu {
1305                0x01000007 => CandidateArchitecture::X86_64,
1306                0x0100000c => CandidateArchitecture::Aarch64,
1307                _ => return None,
1308            };
1309            Some((CandidateFormat::MachO, architecture))
1310        }
1311    }
1312}
1313
1314#[cfg(test)]
1315mod tests {
1316    use super::*;
1317    use crate::{
1318        BuildAttempt, BuildBindingsV1, BuildStrategy, CandidateArtifact, CommandOutcome,
1319        LogicalOutputSelector, PlannedAssetForm, PlannedTarget, ProcessEvidence, TargetPolicy,
1320        ToolchainRequirement,
1321    };
1322    use eggpack_contract::DistributionContract;
1323
1324    fn local_host() -> HostRequirement {
1325        let os = match std::env::consts::OS {
1326            "linux" => HostOs::Linux,
1327            "macos" => HostOs::Macos,
1328            "windows" => HostOs::Windows,
1329            _ => panic!("unsupported test host"),
1330        };
1331        let arch = match std::env::consts::ARCH {
1332            "x86_64" => HostArch::X86_64,
1333            "aarch64" => HostArch::Aarch64,
1334            "arm" => HostArch::Armv7,
1335            _ => panic!("unsupported test architecture"),
1336        };
1337        HostRequirement { os, arch }
1338    }
1339
1340    fn local_target() -> &'static str {
1341        match (std::env::consts::OS, std::env::consts::ARCH) {
1342            ("linux", "x86_64") => "x86_64-unknown-linux-gnu",
1343            ("linux", "aarch64") => "aarch64-unknown-linux-gnu",
1344            ("linux", "arm") => "armv7-unknown-linux-gnueabihf",
1345            ("macos", "x86_64") => "x86_64-apple-darwin",
1346            ("macos", "aarch64") => "aarch64-apple-darwin",
1347            ("windows", "x86_64") => "x86_64-pc-windows-msvc",
1348            ("windows", "aarch64") => "aarch64-pc-windows-msvc",
1349            _ => panic!("unsupported test target"),
1350        }
1351    }
1352
1353    fn contract(target: &str) -> DistributionContract {
1354        DistributionContract::parse_toml_str(&format!(
1355            "schema_version = 1\n[product]\nid = \"fixture\"\ndisplay_name = \"fixture\"\n[[targets]]\ntriple = \"{target}\"\naliases = []\n[targets.asset]\nkind = \"direct\"\nasset = \"{{product}}-{{version}}-{{target}}\"\ninstall = \"fixture\"\n[targets.checksum]\nsidecar = \"{{asset}}.sha256\"\n"
1356        ))
1357        .unwrap()
1358    }
1359
1360    fn candidate_path(root: &Path, target: &str) -> PathBuf {
1361        let mut path = root.join(target).join("release").join("fixture");
1362        if target.contains("windows") {
1363            path.set_extension("exe");
1364        }
1365        path
1366    }
1367
1368    fn fixture(
1369        classification: Qualification,
1370        candidate_bytes: &[u8],
1371    ) -> (
1372        DistributionContract,
1373        ReleasePlan,
1374        PlannedTarget,
1375        BuildAttempt,
1376        BuildBindingsV1,
1377        QualificationBindingsV1,
1378        PathBuf,
1379    ) {
1380        let target_name = local_target();
1381        let root = crate::test_temp_dir("qualification");
1382        let path = candidate_path(&root, target_name);
1383        fs::create_dir_all(path.parent().unwrap()).unwrap();
1384        fs::write(&path, candidate_bytes).unwrap();
1385        let host = local_host();
1386        let target = PlannedTarget {
1387            target: target_name.into(),
1388            policy: TargetPolicy {
1389                target: target_name.into(),
1390                strategy: BuildStrategy::NativeCargo,
1391                host_os: host.os,
1392                host_arch: host.arch,
1393                qualification_host: Some(host),
1394                toolchain: ToolchainRequirement {
1395                    rust: "stable".into(),
1396                    cargo_zigbuild: None,
1397                    zig: None,
1398                },
1399                floor: crate::CompatibilityFloor::None,
1400                qualification: classification,
1401                support: SupportTier::Required,
1402            },
1403            artifact_form: PlannedAssetForm::Direct,
1404            floor_status: crate::FloorVerificationStatus::NotDeclared,
1405        };
1406        let plan = ReleasePlan {
1407            schema_version: 1,
1408            release_id: "v1".into(),
1409            source_revision: "abc123".into(),
1410            targets: vec![target.clone()],
1411        };
1412        let build_bindings = BuildBindingsV1 {
1413            schema_version: 1,
1414            targets: [(
1415                target_name.into(),
1416                vec![crate::BuildBinding {
1417                    selector: LogicalOutputSelector::Direct,
1418                    package: "fixture".into(),
1419                    binary: "fixture".into(),
1420                }],
1421            )]
1422            .into_iter()
1423            .collect(),
1424        };
1425        let qualification_bindings = QualificationBindingsV1 {
1426            schema_version: 1,
1427            targets: [(
1428                target_name.into(),
1429                TargetQualificationBinding {
1430                    smoke: matches!(
1431                        classification,
1432                        Qualification::Native
1433                            | Qualification::DeferredNative
1434                            | Qualification::Emulated
1435                    )
1436                    .then(|| CandidateSmokeBinding {
1437                        selector: LogicalOutputSelector::Direct,
1438                        argv: vec![],
1439                        timeout_ms: 5000,
1440                        stdout_limit: 4096,
1441                        stderr_limit: 4096,
1442                    }),
1443                },
1444            )]
1445            .into_iter()
1446            .collect(),
1447        };
1448        let attempt = BuildAttempt {
1449            release_id: plan.release_id.clone(),
1450            source_revision: plan.source_revision.clone(),
1451            target: target_name.into(),
1452            strategy: BuildStrategy::NativeCargo,
1453            tool_summary: "rust stable".into(),
1454            process: ProcessEvidence {
1455                outcome: CommandOutcome::Success,
1456                stdout_bytes: 0,
1457                stderr_bytes: 0,
1458            },
1459            candidates: vec![CandidateArtifact {
1460                target: target_name.into(),
1461                selector: LogicalOutputSelector::Direct,
1462                package: "fixture".into(),
1463                binary: "fixture".into(),
1464                path,
1465                size: candidate_bytes.len() as u64,
1466            }],
1467        };
1468        (
1469            contract(target_name),
1470            plan,
1471            target,
1472            attempt,
1473            build_bindings,
1474            qualification_bindings,
1475            root,
1476        )
1477    }
1478
1479    fn elf(architecture: CandidateArchitecture) -> Vec<u8> {
1480        let mut bytes = vec![0u8; 64];
1481        bytes[..4].copy_from_slice(b"\x7fELF");
1482        bytes[5] = 1;
1483        let (class, machine) = match architecture {
1484            CandidateArchitecture::X86_64 => (2, 62u16),
1485            CandidateArchitecture::Aarch64 => (2, 183),
1486            CandidateArchitecture::Armv7 => (1, 40),
1487        };
1488        bytes[4] = class;
1489        bytes[18..20].copy_from_slice(&machine.to_le_bytes());
1490        bytes
1491    }
1492
1493    fn pe(architecture: CandidateArchitecture) -> Vec<u8> {
1494        let mut bytes = vec![0u8; 128 + 6];
1495        bytes[..2].copy_from_slice(b"MZ");
1496        bytes[60..64].copy_from_slice(&128u32.to_le_bytes());
1497        bytes[128..132].copy_from_slice(b"PE\0\0");
1498        let machine = match architecture {
1499            CandidateArchitecture::X86_64 => 0x8664u16,
1500            CandidateArchitecture::Aarch64 => 0xAA64,
1501            CandidateArchitecture::Armv7 => 0x01c4,
1502        };
1503        bytes[132..134].copy_from_slice(&machine.to_le_bytes());
1504        bytes
1505    }
1506
1507    fn macho(architecture: CandidateArchitecture) -> Vec<u8> {
1508        let mut bytes = vec![0u8; 32];
1509        bytes[..4].copy_from_slice(&[0xcf, 0xfa, 0xed, 0xfe]);
1510        let cpu = match architecture {
1511            CandidateArchitecture::X86_64 => 0x01000007u32,
1512            CandidateArchitecture::Aarch64 => 0x0100000c,
1513            CandidateArchitecture::Armv7 => 12,
1514        };
1515        bytes[4..8].copy_from_slice(&cpu.to_le_bytes());
1516        bytes
1517    }
1518
1519    #[test]
1520    fn structural_headers_cover_elf_pe_and_thin_macho_targets() {
1521        for arch in [
1522            CandidateArchitecture::X86_64,
1523            CandidateArchitecture::Aarch64,
1524            CandidateArchitecture::Armv7,
1525        ] {
1526            assert_header(
1527                &elf(arch),
1528                CandidateFormat::Elf,
1529                Some((CandidateFormat::Elf, arch)),
1530            );
1531            assert_header(
1532                &pe(arch),
1533                CandidateFormat::PeCoff,
1534                Some((CandidateFormat::PeCoff, arch)),
1535            );
1536        }
1537        for arch in [
1538            CandidateArchitecture::X86_64,
1539            CandidateArchitecture::Aarch64,
1540        ] {
1541            assert_header(
1542                &macho(arch),
1543                CandidateFormat::MachO,
1544                Some((CandidateFormat::MachO, arch)),
1545            );
1546        }
1547        assert_header(b"bad", CandidateFormat::Elf, None);
1548        let mut fat = macho(CandidateArchitecture::X86_64);
1549        fat[..4].copy_from_slice(&[0xca, 0xfe, 0xba, 0xbe]);
1550        assert_header(&fat, CandidateFormat::MachO, None);
1551        let mut bad_pe = pe(CandidateArchitecture::X86_64);
1552        bad_pe[60..64].copy_from_slice(&u32::MAX.to_le_bytes());
1553        assert_header(&bad_pe, CandidateFormat::PeCoff, None);
1554        assert_eq!(
1555            qemu_for_target("x86_64-unknown-linux-gnu"),
1556            Some("qemu-x86_64")
1557        );
1558        assert_eq!(
1559            qemu_for_target("aarch64-unknown-linux-gnu"),
1560            Some("qemu-aarch64")
1561        );
1562        assert_eq!(
1563            qemu_for_target("armv7-unknown-linux-gnueabihf"),
1564            Some("qemu-arm")
1565        );
1566        assert_eq!(qemu_for_target("x86_64-pc-windows-msvc"), None);
1567    }
1568
1569    fn assert_header(
1570        bytes: &[u8],
1571        format: CandidateFormat,
1572        expected: Option<(CandidateFormat, CandidateArchitecture)>,
1573    ) {
1574        let root = crate::test_temp_dir("header");
1575        let path = root.join("header");
1576        fs::write(&path, bytes).unwrap();
1577        assert_eq!(parse_binary_header(&path, format), expected);
1578        fs::remove_dir_all(root).unwrap();
1579    }
1580
1581    #[test]
1582    fn structural_classification_passes_without_execution() {
1583        let host = local_host();
1584        let target_name = local_target();
1585        let bytes = match target_identity(target_name).unwrap().0 {
1586            CandidateFormat::Elf => elf(host.arch.into()),
1587            CandidateFormat::PeCoff => pe(host.arch.into()),
1588            CandidateFormat::MachO => macho(host.arch.into()),
1589        };
1590        let (contract, plan, target, attempt, builds, quals, root) =
1591            fixture(Qualification::Structural, &bytes);
1592        let evidence = qualify_target_for_host(
1593            &contract,
1594            &plan,
1595            &target,
1596            &attempt,
1597            &builds,
1598            &quals,
1599            &QualificationRuntime::default(),
1600            &BuildCancellation::new(),
1601            host,
1602        )
1603        .unwrap();
1604        assert_eq!(evidence.status, QualificationStatus::Passed);
1605        assert_eq!(evidence.method, QualificationMethod::Structural);
1606        assert!(evidence.processes.is_empty());
1607        assert_eq!(evidence.candidates[0].sha256.len(), 64);
1608        fs::remove_dir_all(root).unwrap();
1609    }
1610
1611    impl From<HostArch> for CandidateArchitecture {
1612        fn from(value: HostArch) -> Self {
1613            match value {
1614                HostArch::X86_64 => Self::X86_64,
1615                HostArch::Aarch64 => Self::Aarch64,
1616                HostArch::Armv7 => Self::Armv7,
1617            }
1618        }
1619    }
1620
1621    #[test]
1622    fn build_and_qualification_release_identity_mismatch_is_rejected() {
1623        let host = local_host();
1624        let bytes = match target_identity(local_target()).unwrap().0 {
1625            CandidateFormat::Elf => elf(host.arch.into()),
1626            CandidateFormat::PeCoff => pe(host.arch.into()),
1627            CandidateFormat::MachO => macho(host.arch.into()),
1628        };
1629        let (contract, plan, target, mut attempt, builds, quals, root) =
1630            fixture(Qualification::Structural, &bytes);
1631        attempt.source_revision = "other".into();
1632        assert!(qualify_target_for_host(
1633            &contract,
1634            &plan,
1635            &target,
1636            &attempt,
1637            &builds,
1638            &quals,
1639            &QualificationRuntime::default(),
1640            &BuildCancellation::new(),
1641            host
1642        )
1643        .is_err());
1644        fs::remove_dir_all(root).unwrap();
1645    }
1646
1647    #[test]
1648    fn deferred_native_stays_pending_off_the_required_host() {
1649        let host = local_host();
1650        let bytes = match target_identity(local_target()).unwrap().0 {
1651            CandidateFormat::Elf => elf(host.arch.into()),
1652            CandidateFormat::PeCoff => pe(host.arch.into()),
1653            CandidateFormat::MachO => macho(host.arch.into()),
1654        };
1655        let (contract, plan, mut target, attempt, builds, quals, root) =
1656            fixture(Qualification::DeferredNative, &bytes);
1657        let other = HostRequirement {
1658            os: if host.os == HostOs::Linux {
1659                HostOs::Macos
1660            } else {
1661                HostOs::Linux
1662            },
1663            arch: host.arch,
1664        };
1665        target.policy.qualification_host = Some(other);
1666        let plan = ReleasePlan {
1667            targets: vec![target.clone()],
1668            ..plan
1669        };
1670        let evidence = qualify_target_for_host(
1671            &contract,
1672            &plan,
1673            &target,
1674            &attempt,
1675            &builds,
1676            &quals,
1677            &QualificationRuntime::default(),
1678            &BuildCancellation::new(),
1679            host,
1680        )
1681        .unwrap();
1682        assert_eq!(evidence.status, QualificationStatus::Deferred);
1683        assert!(evidence.processes.is_empty());
1684        fs::remove_dir_all(root).unwrap();
1685    }
1686
1687    #[test]
1688    fn qualification_bindings_are_strict_and_smoke_selector_is_exact() {
1689        let good = r#"schema_version = 1
1690[targets."x86_64-unknown-linux-gnu".smoke]
1691selector = { kind = "direct" }
1692argv = []
1693timeout_ms = 5000
1694stdout_limit = 1024
1695stderr_limit = 1024
1696"#;
1697        assert!(QualificationBindingsV1::from_toml(good).is_ok());
1698        assert!(QualificationBindingsV1::from_toml(
1699            &good.replace("schema_version = 1", "schema_version = 2")
1700        )
1701        .is_err());
1702        assert!(QualificationBindingsV1::from_toml(
1703            &good.replace("selector =", "extra = 1\nselector =")
1704        )
1705        .is_err());
1706    }
1707
1708    #[test]
1709    fn classification_requires_the_exact_smoke_and_host_configuration() {
1710        let bytes = elf(CandidateArchitecture::X86_64);
1711        let (_contract, plan, target, _attempt, builds, mut quals, root) =
1712            fixture(Qualification::Native, &bytes);
1713        quals.targets.get_mut(&target.target).unwrap().smoke = None;
1714        assert!(quals.validate_for(&plan, &builds).is_err());
1715        fs::remove_dir_all(root).unwrap();
1716
1717        let (contract, plan, target, attempt, builds, _quals, root) =
1718            fixture(Qualification::Structural, &bytes);
1719        let structural = QualificationBindingsV1 {
1720            schema_version: 1,
1721            targets: [(
1722                target.target.clone(),
1723                TargetQualificationBinding {
1724                    smoke: Some(CandidateSmokeBinding {
1725                        selector: LogicalOutputSelector::Direct,
1726                        argv: vec![],
1727                        timeout_ms: 1000,
1728                        stdout_limit: 1024,
1729                        stderr_limit: 1024,
1730                    }),
1731                },
1732            )]
1733            .into_iter()
1734            .collect(),
1735        };
1736        assert!(structural.validate_for(&plan, &builds).is_err());
1737        assert!(qualify_target_for_host(
1738            &contract,
1739            &plan,
1740            &target,
1741            &attempt,
1742            &builds,
1743            &structural,
1744            &QualificationRuntime::default(),
1745            &BuildCancellation::new(),
1746            local_host(),
1747        )
1748        .is_err());
1749        fs::remove_dir_all(root).unwrap();
1750    }
1751
1752    #[test]
1753    fn native_smoke_executes_the_exact_candidate_on_a_matching_host() {
1754        let host = local_host();
1755        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
1756        let (contract, plan, target, mut attempt, builds, mut quals, root) =
1757            fixture(Qualification::Native, &bytes);
1758        fs::copy(
1759            std::env::current_exe().unwrap(),
1760            &attempt.candidates[0].path,
1761        )
1762        .unwrap();
1763        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
1764        let smoke = quals
1765            .targets
1766            .get_mut(&target.target)
1767            .unwrap()
1768            .smoke
1769            .as_mut()
1770            .unwrap();
1771        smoke.argv = vec![
1772            "--exact".into(),
1773            "qualification::tests::qualification_child_target".into(),
1774            "--ignored".into(),
1775            "--nocapture".into(),
1776        ];
1777        let evidence = qualify_target_for_host(
1778            &contract,
1779            &plan,
1780            &target,
1781            &attempt,
1782            &builds,
1783            &quals,
1784            &QualificationRuntime::default(),
1785            &BuildCancellation::new(),
1786            host,
1787        )
1788        .unwrap();
1789        assert_eq!(evidence.status, QualificationStatus::Passed);
1790        assert_eq!(evidence.method, QualificationMethod::Native);
1791        assert_eq!(
1792            evidence.processes[0].process.outcome,
1793            CommandOutcome::Success
1794        );
1795        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
1796        let json = serde_json::to_string(&evidence).unwrap();
1797        assert!(!json.contains(&attempt.candidates[0].path.to_string_lossy().to_string()));
1798        assert_eq!(json, serde_json::to_string(&evidence).unwrap());
1799        fs::remove_dir_all(root).unwrap();
1800    }
1801
1802    /// Same executable candidate as `fixture`, but declared as the product of
1803    /// the cross-tool builder with an explicit compatibility floor. Cross tools
1804    /// change how bytes are produced, not which bytes are qualified.
1805    fn cross_tool_fixture(
1806        classification: Qualification,
1807        candidate_bytes: &[u8],
1808    ) -> (
1809        DistributionContract,
1810        ReleasePlan,
1811        PlannedTarget,
1812        BuildAttempt,
1813        BuildBindingsV1,
1814        QualificationBindingsV1,
1815        PathBuf,
1816    ) {
1817        let (contract, plan, mut target, mut attempt, builds, quals, root) =
1818            fixture(classification, candidate_bytes);
1819        target.policy.strategy = BuildStrategy::CargoZigbuild;
1820        target.policy.toolchain = ToolchainRequirement {
1821            rust: "1.89.0".into(),
1822            cargo_zigbuild: Some("0.23.3".into()),
1823            zig: Some("0.14.1".into()),
1824        };
1825        target.policy.floor = if target.target.contains("-linux-gnu") {
1826            crate::CompatibilityFloor::Glibc {
1827                major: 2,
1828                minor: 17,
1829            }
1830        } else {
1831            crate::CompatibilityFloor::None
1832        };
1833        // The plan states the status its declaration implies.
1834        target.floor_status = crate::planned_floor_status(&target.policy);
1835        attempt.strategy = BuildStrategy::CargoZigbuild;
1836        attempt.tool_summary = "rust 1.89.0 cargo-zigbuild 0.23.3 zig 0.14.1".into();
1837        let plan = ReleasePlan {
1838            targets: vec![target.clone()],
1839            ..plan
1840        };
1841        (contract, plan, target, attempt, builds, quals, root)
1842    }
1843
1844    #[test]
1845    fn cross_tool_built_candidate_qualifies_natively_on_the_matching_host() {
1846        let host = local_host();
1847        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
1848        let (contract, plan, target, mut attempt, builds, mut quals, root) =
1849            cross_tool_fixture(Qualification::Native, &bytes);
1850        fs::copy(
1851            std::env::current_exe().unwrap(),
1852            &attempt.candidates[0].path,
1853        )
1854        .unwrap();
1855        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
1856        assert_eq!(target.policy.strategy, BuildStrategy::CargoZigbuild);
1857        let smoke = quals
1858            .targets
1859            .get_mut(&target.target)
1860            .unwrap()
1861            .smoke
1862            .as_mut()
1863            .unwrap();
1864        smoke.argv = vec![
1865            "--exact".into(),
1866            "qualification::tests::qualification_child_target".into(),
1867            "--ignored".into(),
1868            "--nocapture".into(),
1869        ];
1870        // The exact cross-tool-built candidate executes natively and is recorded
1871        // as native qualification with executed process evidence.
1872        let evidence = qualify_target_for_host(
1873            &contract,
1874            &plan,
1875            &target,
1876            &attempt,
1877            &builds,
1878            &quals,
1879            &QualificationRuntime::default(),
1880            &BuildCancellation::new(),
1881            host,
1882        )
1883        .unwrap();
1884        assert_eq!(evidence.status, QualificationStatus::Passed);
1885        assert_eq!(evidence.method, QualificationMethod::Native);
1886        assert_eq!(evidence.processes.len(), 1);
1887        assert_eq!(evidence.processes[0].purpose, "candidate_smoke");
1888        assert_eq!(
1889            evidence.processes[0].process.outcome,
1890            CommandOutcome::Success
1891        );
1892        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
1893        // The public entry point, using the observed local host, reaches the
1894        // same native result for the same cross-tool-built candidate.
1895        let runtime = QualificationRuntime::default();
1896        let cancellation = BuildCancellation::new();
1897        let observed = qualify_target(QualificationRequest {
1898            contract: &contract,
1899            plan: &plan,
1900            target: &target,
1901            attempt: &attempt,
1902            build_bindings: &builds,
1903            qualification_bindings: &quals,
1904            runtime: &runtime,
1905            cancellation: &cancellation,
1906        })
1907        .unwrap();
1908        assert_eq!(observed.status, QualificationStatus::Passed);
1909        assert_eq!(observed.method, QualificationMethod::Native);
1910        assert_eq!(observed.processes.len(), 1);
1911        assert_eq!(
1912            observed.processes[0].process.outcome,
1913            CommandOutcome::Success
1914        );
1915        assert_eq!(observed.actual_host, host);
1916        // A non-matching host is still a failed HostMismatch record, never a
1917        // pass and never a skip, and never an executed smoke.
1918        let other_arch = HostRequirement {
1919            os: host.os,
1920            arch: match host.arch {
1921                HostArch::X86_64 => HostArch::Aarch64,
1922                _ => HostArch::X86_64,
1923            },
1924        };
1925        let mismatched = qualify_target_for_host(
1926            &contract,
1927            &plan,
1928            &target,
1929            &attempt,
1930            &builds,
1931            &quals,
1932            &QualificationRuntime::default(),
1933            &BuildCancellation::new(),
1934            other_arch,
1935        )
1936        .unwrap();
1937        assert_eq!(
1938            mismatched.status,
1939            QualificationStatus::Failed(QualificationFailure::HostMismatch)
1940        );
1941        assert_eq!(mismatched.method, QualificationMethod::Native);
1942        assert!(mismatched.processes.is_empty());
1943        // The failed record is itself valid evidence: it describes exactly what
1944        // happened on the observed host.
1945        assert!(mismatched.validate_for(&plan, &target, &attempt).is_ok());
1946        // Native qualification still requires a bounded smoke binding.
1947        let mut without_smoke = quals.clone();
1948        without_smoke.targets.get_mut(&target.target).unwrap().smoke = None;
1949        assert!(without_smoke.validate_for(&plan, &builds).is_err());
1950        assert!(qualify_target_for_host(
1951            &contract,
1952            &plan,
1953            &target,
1954            &attempt,
1955            &builds,
1956            &without_smoke,
1957            &QualificationRuntime::default(),
1958            &BuildCancellation::new(),
1959            host,
1960        )
1961        .is_err());
1962        fs::remove_dir_all(root).unwrap();
1963    }
1964
1965    #[test]
1966    fn candidate_inventory_and_structural_architecture_must_match() {
1967        let host = local_host();
1968        let wrong_arch = match host.arch {
1969            HostArch::X86_64 => CandidateArchitecture::Aarch64,
1970            _ => CandidateArchitecture::X86_64,
1971        };
1972        let bytes = match target_identity(local_target()).unwrap().0 {
1973            CandidateFormat::Elf => elf(wrong_arch),
1974            CandidateFormat::PeCoff => pe(wrong_arch),
1975            CandidateFormat::MachO => macho(wrong_arch),
1976        };
1977        let (contract, plan, target, mut attempt, builds, quals, root) =
1978            fixture(Qualification::Structural, &bytes);
1979        let result = qualify_target_for_host(
1980            &contract,
1981            &plan,
1982            &target,
1983            &attempt,
1984            &builds,
1985            &quals,
1986            &QualificationRuntime::default(),
1987            &BuildCancellation::new(),
1988            host,
1989        )
1990        .unwrap();
1991        assert_eq!(
1992            result.status,
1993            QualificationStatus::Failed(QualificationFailure::StructuralMismatch)
1994        );
1995        attempt.candidates.clear();
1996        assert!(qualify_target_for_host(
1997            &contract,
1998            &plan,
1999            &target,
2000            &attempt,
2001            &builds,
2002            &quals,
2003            &QualificationRuntime::default(),
2004            &BuildCancellation::new(),
2005            host,
2006        )
2007        .is_err());
2008        fs::remove_dir_all(root).unwrap();
2009    }
2010
2011    #[test]
2012    fn native_host_mismatch_is_a_failure_and_never_runs_smoke() {
2013        let host = local_host();
2014        let bytes = match target_identity(local_target()).unwrap().0 {
2015            CandidateFormat::Elf => elf(host.arch.into()),
2016            CandidateFormat::PeCoff => pe(host.arch.into()),
2017            CandidateFormat::MachO => macho(host.arch.into()),
2018        };
2019        let (contract, plan, mut target, attempt, builds, quals, root) =
2020            fixture(Qualification::Native, &bytes);
2021        let other = HostRequirement {
2022            os: if host.os == HostOs::Linux {
2023                HostOs::Macos
2024            } else {
2025                HostOs::Linux
2026            },
2027            arch: host.arch,
2028        };
2029        target.policy.qualification_host = Some(other);
2030        let plan = ReleasePlan {
2031            targets: vec![target.clone()],
2032            ..plan
2033        };
2034        let evidence = qualify_target_for_host(
2035            &contract,
2036            &plan,
2037            &target,
2038            &attempt,
2039            &builds,
2040            &quals,
2041            &QualificationRuntime::default(),
2042            &BuildCancellation::new(),
2043            host,
2044        )
2045        .unwrap();
2046        assert_eq!(
2047            evidence.status,
2048            QualificationStatus::Failed(QualificationFailure::HostMismatch)
2049        );
2050        assert!(evidence.processes.is_empty());
2051        fs::remove_dir_all(root).unwrap();
2052    }
2053
2054    #[test]
2055    fn deferred_native_matching_host_executes_and_wrong_host_stays_deferred() {
2056        let host = local_host();
2057        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
2058        let (contract, plan, mut target, mut attempt, builds, mut quals, root) =
2059            fixture(Qualification::DeferredNative, &bytes);
2060        fs::copy(
2061            std::env::current_exe().unwrap(),
2062            &attempt.candidates[0].path,
2063        )
2064        .unwrap();
2065        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
2066        let smoke = quals
2067            .targets
2068            .get_mut(&target.target)
2069            .unwrap()
2070            .smoke
2071            .as_mut()
2072            .unwrap();
2073        smoke.argv = vec![
2074            "--exact".into(),
2075            "qualification::tests::qualification_child_target".into(),
2076            "--ignored".into(),
2077            "--nocapture".into(),
2078        ];
2079        let other = HostRequirement {
2080            os: if host.os == HostOs::Linux {
2081                HostOs::Macos
2082            } else {
2083                HostOs::Linux
2084            },
2085            arch: host.arch,
2086        };
2087        target.policy.qualification_host = Some(other);
2088        let deferred_plan = ReleasePlan {
2089            targets: vec![target.clone()],
2090            ..plan.clone()
2091        };
2092        let deferred = qualify_target_for_host(
2093            &contract,
2094            &deferred_plan,
2095            &target,
2096            &attempt,
2097            &builds,
2098            &quals,
2099            &QualificationRuntime::default(),
2100            &BuildCancellation::new(),
2101            host,
2102        )
2103        .unwrap();
2104        assert_eq!(deferred.status, QualificationStatus::Deferred);
2105        assert!(deferred.processes.is_empty());
2106
2107        target.policy.qualification_host = Some(host);
2108        let matching_plan = ReleasePlan {
2109            targets: vec![target.clone()],
2110            ..plan
2111        };
2112        let passed = qualify_target_for_host(
2113            &contract,
2114            &matching_plan,
2115            &target,
2116            &attempt,
2117            &builds,
2118            &quals,
2119            &QualificationRuntime::default(),
2120            &BuildCancellation::new(),
2121            host,
2122        )
2123        .unwrap();
2124        assert_eq!(passed.status, QualificationStatus::Passed);
2125        assert_eq!(
2126            passed.method,
2127            QualificationMethod::DeferredNativeOnNativeHost
2128        );
2129        fs::remove_dir_all(root).unwrap();
2130    }
2131
2132    #[test]
2133    fn qemu_command_mapping_is_fixed_and_uses_only_the_declared_sysroot() {
2134        let sysroot = PathBuf::from("/fixture/sysroot");
2135        let runtime = QualificationRuntime {
2136            qemu_sysroot: Some(sysroot),
2137        };
2138        let candidate = CandidateArtifact {
2139            target: "x86_64-unknown-linux-gnu".into(),
2140            selector: LogicalOutputSelector::Direct,
2141            package: "fixture".into(),
2142            binary: "fixture".into(),
2143            path: PathBuf::from("/private/candidate"),
2144            size: 1,
2145        };
2146        let smoke = CandidateSmokeBinding {
2147            selector: LogicalOutputSelector::Direct,
2148            argv: vec!["--smoke".into()],
2149            timeout_ms: 1000,
2150            stdout_limit: 1024,
2151            stderr_limit: 1024,
2152        };
2153        let args = qemu_args(&runtime, &candidate, &smoke);
2154        assert_eq!(
2155            qemu_for_target("x86_64-unknown-linux-gnu"),
2156            Some("qemu-x86_64")
2157        );
2158        assert_eq!(
2159            args,
2160            vec!["-L", "/fixture/sysroot", "/private/candidate", "--smoke"]
2161        );
2162        assert_eq!(qemu_for_target("aarch64-apple-darwin"), None);
2163    }
2164
2165    #[test]
2166    fn emulated_linux_path_uses_injected_finite_qemu_runner() {
2167        let target_name = "x86_64-unknown-linux-gnu";
2168        let contract = contract(target_name);
2169        let host = local_host();
2170        let target = PlannedTarget {
2171            target: target_name.into(),
2172            policy: TargetPolicy {
2173                target: target_name.into(),
2174                strategy: BuildStrategy::CargoZigbuild,
2175                host_os: host.os,
2176                host_arch: host.arch,
2177                qualification_host: None,
2178                toolchain: ToolchainRequirement {
2179                    rust: "stable".into(),
2180                    cargo_zigbuild: Some("0.20.0".into()),
2181                    zig: Some("0.14.1".into()),
2182                },
2183                floor: crate::CompatibilityFloor::None,
2184                qualification: Qualification::Emulated,
2185                support: SupportTier::NonGating,
2186            },
2187            artifact_form: PlannedAssetForm::Direct,
2188            floor_status: crate::FloorVerificationStatus::NotDeclared,
2189        };
2190        let plan = ReleasePlan {
2191            schema_version: 1,
2192            release_id: "v2".into(),
2193            source_revision: "def456".into(),
2194            targets: vec![target.clone()],
2195        };
2196        let root = crate::test_temp_dir("qemu-fixture");
2197        let path = candidate_path(&root, target_name);
2198        fs::create_dir_all(path.parent().unwrap()).unwrap();
2199        let bytes = elf(CandidateArchitecture::X86_64);
2200        fs::write(&path, &bytes).unwrap();
2201        let builds = BuildBindingsV1 {
2202            schema_version: 1,
2203            targets: [(
2204                target_name.into(),
2205                vec![crate::BuildBinding {
2206                    selector: LogicalOutputSelector::Direct,
2207                    package: "fixture".into(),
2208                    binary: "fixture".into(),
2209                }],
2210            )]
2211            .into_iter()
2212            .collect(),
2213        };
2214        let quals = QualificationBindingsV1 {
2215            schema_version: 1,
2216            targets: [(
2217                target_name.into(),
2218                TargetQualificationBinding {
2219                    smoke: Some(CandidateSmokeBinding {
2220                        selector: LogicalOutputSelector::Direct,
2221                        argv: vec!["--smoke".into()],
2222                        timeout_ms: 2000,
2223                        stdout_limit: 1024,
2224                        stderr_limit: 1024,
2225                    }),
2226                },
2227            )]
2228            .into_iter()
2229            .collect(),
2230        };
2231        let attempt = BuildAttempt {
2232            release_id: plan.release_id.clone(),
2233            source_revision: plan.source_revision.clone(),
2234            target: target_name.into(),
2235            strategy: BuildStrategy::CargoZigbuild,
2236            tool_summary: "rust stable cargo-zigbuild 0.20.0".into(),
2237            process: ProcessEvidence {
2238                outcome: CommandOutcome::Success,
2239                stdout_bytes: 0,
2240                stderr_bytes: 0,
2241            },
2242            candidates: vec![CandidateArtifact {
2243                target: target_name.into(),
2244                selector: LogicalOutputSelector::Direct,
2245                package: "fixture".into(),
2246                binary: "fixture".into(),
2247                path: path.clone(),
2248                size: bytes.len() as u64,
2249            }],
2250        };
2251        let commands = std::sync::Mutex::new(Vec::new());
2252        let runner = |spec: &CommandSpec, qemu: bool| {
2253            assert!(qemu);
2254            commands.lock().unwrap().push(spec.clone());
2255            Ok(ProcessEvidence {
2256                outcome: CommandOutcome::Success,
2257                stdout_bytes: 10,
2258                stderr_bytes: 0,
2259            })
2260        };
2261        let evidence = qualify_target_for_host_with_runner(
2262            &contract,
2263            &plan,
2264            &target,
2265            &attempt,
2266            &builds,
2267            &quals,
2268            &QualificationRuntime::default(),
2269            &BuildCancellation::new(),
2270            host,
2271            &runner,
2272        )
2273        .unwrap();
2274        assert_eq!(evidence.status, QualificationStatus::Passed);
2275        assert_eq!(evidence.method, QualificationMethod::QemuUser);
2276        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2277        let commands = commands.into_inner().unwrap();
2278        assert_eq!(commands.len(), 2);
2279        assert_eq!(commands[0].executable, "qemu-x86_64");
2280        assert_eq!(commands[0].args, ["--version"]);
2281        assert_eq!(commands[1].executable, "qemu-x86_64");
2282        assert_eq!(
2283            commands[1].args,
2284            vec![path.to_string_lossy().into_owned(), "--smoke".into()]
2285        );
2286        let unavailable_runner = |spec: &CommandSpec, qemu: bool| {
2287            assert!(qemu);
2288            assert_eq!(spec.args, ["--version"]);
2289            Ok(ProcessEvidence {
2290                outcome: CommandOutcome::Failed(127),
2291                stdout_bytes: 0,
2292                stderr_bytes: 0,
2293            })
2294        };
2295        let unavailable = qualify_target_for_host_with_runner(
2296            &contract,
2297            &plan,
2298            &target,
2299            &attempt,
2300            &builds,
2301            &quals,
2302            &QualificationRuntime::default(),
2303            &BuildCancellation::new(),
2304            host,
2305            &unavailable_runner,
2306        )
2307        .unwrap();
2308        assert_eq!(
2309            unavailable.status,
2310            QualificationStatus::Failed(QualificationFailure::EmulatorUnavailable)
2311        );
2312        assert_eq!(unavailable.processes.len(), 1);
2313        assert_eq!(unavailable.processes[0].purpose, "qemu_preflight");
2314        fs::remove_dir_all(root).unwrap();
2315    }
2316
2317    #[test]
2318    fn qualification_evidence_validation_reconciles_plan_and_candidates() {
2319        let host = local_host();
2320        let bytes = match target_identity(local_target()).unwrap().0 {
2321            CandidateFormat::Elf => elf(host.arch.into()),
2322            CandidateFormat::PeCoff => pe(host.arch.into()),
2323            CandidateFormat::MachO => macho(host.arch.into()),
2324        };
2325        let (contract, plan, target, attempt, builds, quals, root) =
2326            fixture(Qualification::Structural, &bytes);
2327        let evidence = qualify_target_for_host(
2328            &contract,
2329            &plan,
2330            &target,
2331            &attempt,
2332            &builds,
2333            &quals,
2334            &QualificationRuntime::default(),
2335            &BuildCancellation::new(),
2336            host,
2337        )
2338        .unwrap();
2339        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2340        let json = serde_json::to_string(&evidence).unwrap();
2341        let roundtrip: QualificationEvidence = serde_json::from_str(&json).unwrap();
2342        assert_eq!(roundtrip, evidence);
2343        assert!(roundtrip.validate_for(&plan, &target, &attempt).is_ok());
2344        let mut corrupted = roundtrip;
2345        corrupted.release_id = "other-release".into();
2346        assert!(corrupted.validate_for(&plan, &target, &attempt).is_err());
2347        fs::remove_dir_all(root).unwrap();
2348    }
2349
2350    #[test]
2351    fn candidate_digest_changes_when_same_size_bytes_change() {
2352        let host = local_host();
2353        let bytes = match target_identity(local_target()).unwrap().0 {
2354            CandidateFormat::Elf => elf(host.arch.into()),
2355            CandidateFormat::PeCoff => pe(host.arch.into()),
2356            CandidateFormat::MachO => macho(host.arch.into()),
2357        };
2358        let (_contract, _plan, target, attempt, _builds, _quals, root) =
2359            fixture(Qualification::Structural, &bytes);
2360        let before = inspect_candidate(&attempt.candidates[0], &target).unwrap();
2361        let mut changed = bytes.clone();
2362        // Keep the structural header intact on all host formats. The final
2363        // byte in the minimal PE fixture is part of its COFF machine field.
2364        changed[20] ^= 1;
2365        fs::write(&attempt.candidates[0].path, &changed).unwrap();
2366        let after = inspect_candidate(&attempt.candidates[0], &target).unwrap();
2367        assert_eq!(before.evidence.size, after.evidence.size);
2368        assert_ne!(before.evidence.sha256, after.evidence.sha256);
2369        fs::remove_dir_all(root).unwrap();
2370    }
2371
2372    #[cfg(unix)]
2373    #[test]
2374    fn candidate_symlink_and_relative_paths_are_rejected() {
2375        use std::os::unix::fs::symlink;
2376
2377        let host = local_host();
2378        let bytes = elf(host.arch.into());
2379        let (_contract, _plan, target, mut attempt, _builds, _quals, root) =
2380            fixture(Qualification::Structural, &bytes);
2381        let candidate = &mut attempt.candidates[0];
2382        let original = candidate.path.with_extension("original");
2383        fs::rename(&candidate.path, &original).unwrap();
2384        symlink(&original, &candidate.path).unwrap();
2385        assert_eq!(
2386            inspect_candidate(candidate, &target),
2387            Err(QualificationFailure::InvalidRuntimeEnvironment)
2388        );
2389        fs::remove_file(&candidate.path).unwrap();
2390        fs::rename(original, &candidate.path).unwrap();
2391        candidate.path = PathBuf::from("relative-candidate");
2392        assert_eq!(
2393            inspect_candidate(candidate, &target),
2394            Err(QualificationFailure::InvalidRuntimeEnvironment)
2395        );
2396        fs::remove_dir_all(root).unwrap();
2397    }
2398
2399    // Not standalone coverage: these four are the child process fixtures that
2400    // `run_native_child` re-executes in this test binary to exercise the
2401    // bounded runner. `#[ignore]` keeps a normal `cargo test` run from hanging
2402    // for 30s, flooding output, or exiting the harness nonzero; each is
2403    // invoked deliberately, and only through that helper.
2404    #[test]
2405    #[ignore]
2406    fn qualification_child_target() {}
2407
2408    /// Child fixture: outruns the caller's timeout to prove process-group kill.
2409    #[test]
2410    #[ignore]
2411    fn qualification_child_sleep() {
2412        std::thread::sleep(Duration::from_secs(30));
2413    }
2414
2415    /// Child fixture: overruns the retained-output bound.
2416    #[test]
2417    #[ignore]
2418    fn qualification_child_output() {
2419        print!("{}", "x".repeat(16 * 1024));
2420    }
2421
2422    /// Child fixture: exits nonzero to prove nonzero classification.
2423    #[test]
2424    #[ignore]
2425    fn qualification_child_nonzero() {
2426        std::process::exit(7);
2427    }
2428
2429    fn run_native_child(
2430        child: &str,
2431        timeout_ms: u64,
2432        stdout_limit: usize,
2433        cancel_after: Option<Duration>,
2434    ) -> QualificationEvidence {
2435        let host = local_host();
2436        let bytes = fs::read(std::env::current_exe().unwrap()).unwrap();
2437        let (contract, plan, target, mut attempt, builds, mut quals, root) =
2438            fixture(Qualification::Native, &bytes);
2439        fs::copy(
2440            std::env::current_exe().unwrap(),
2441            &attempt.candidates[0].path,
2442        )
2443        .unwrap();
2444        attempt.candidates[0].size = fs::metadata(&attempt.candidates[0].path).unwrap().len();
2445        let smoke = quals
2446            .targets
2447            .get_mut(&target.target)
2448            .unwrap()
2449            .smoke
2450            .as_mut()
2451            .unwrap();
2452        smoke.argv = vec![
2453            "--exact".into(),
2454            format!("qualification::tests::{child}"),
2455            "--ignored".into(),
2456            "--nocapture".into(),
2457        ];
2458        smoke.timeout_ms = timeout_ms;
2459        smoke.stdout_limit = stdout_limit;
2460        let cancellation = BuildCancellation::new();
2461        let cancel_thread = cancel_after.map(|delay| {
2462            let cancellation = cancellation.clone();
2463            std::thread::spawn(move || {
2464                std::thread::sleep(delay);
2465                cancellation.cancel();
2466            })
2467        });
2468        let evidence = qualify_target_for_host(
2469            &contract,
2470            &plan,
2471            &target,
2472            &attempt,
2473            &builds,
2474            &quals,
2475            &QualificationRuntime::default(),
2476            &cancellation,
2477            host,
2478        )
2479        .unwrap();
2480        if let Some(thread) = cancel_thread {
2481            thread.join().unwrap();
2482        }
2483        fs::remove_dir_all(root).unwrap();
2484        evidence
2485    }
2486
2487    #[test]
2488    fn native_smoke_failure_timeout_cancellation_and_output_limit_are_typed() {
2489        let failed = run_native_child("qualification_child_nonzero", 5_000, 4096, None);
2490        assert_eq!(
2491            failed.status,
2492            QualificationStatus::Failed(QualificationFailure::SmokeFailed)
2493        );
2494        let timed_out = run_native_child("qualification_child_sleep", 100, 4096, None);
2495        assert_eq!(
2496            timed_out.status,
2497            QualificationStatus::Failed(QualificationFailure::SmokeTimedOut)
2498        );
2499        let cancelled = run_native_child(
2500            "qualification_child_sleep",
2501            5_000,
2502            4096,
2503            Some(Duration::from_millis(100)),
2504        );
2505        assert_eq!(
2506            cancelled.status,
2507            QualificationStatus::Failed(QualificationFailure::SmokeFailed)
2508        );
2509        let limited = run_native_child("qualification_child_output", 5_000, 1024, None);
2510        assert_eq!(
2511            limited.status,
2512            QualificationStatus::Failed(QualificationFailure::OutputLimitExceeded)
2513        );
2514    }
2515
2516    #[test]
2517    fn structural_inspection_covers_pe_and_macho_targets_independent_of_host() {
2518        for (target_name, bytes, format, architecture) in [
2519            (
2520                "x86_64-pc-windows-msvc",
2521                pe(CandidateArchitecture::X86_64),
2522                CandidateFormat::PeCoff,
2523                CandidateArchitecture::X86_64,
2524            ),
2525            (
2526                "aarch64-pc-windows-msvc",
2527                pe(CandidateArchitecture::Aarch64),
2528                CandidateFormat::PeCoff,
2529                CandidateArchitecture::Aarch64,
2530            ),
2531            (
2532                "x86_64-apple-darwin",
2533                macho(CandidateArchitecture::X86_64),
2534                CandidateFormat::MachO,
2535                CandidateArchitecture::X86_64,
2536            ),
2537            (
2538                "aarch64-apple-darwin",
2539                macho(CandidateArchitecture::Aarch64),
2540                CandidateFormat::MachO,
2541                CandidateArchitecture::Aarch64,
2542            ),
2543        ] {
2544            let root = crate::test_temp_dir("cross-structure");
2545            let path = candidate_path(&root, target_name);
2546            fs::create_dir_all(path.parent().unwrap()).unwrap();
2547            fs::write(&path, &bytes).unwrap();
2548            let candidate = CandidateArtifact {
2549                target: target_name.into(),
2550                selector: LogicalOutputSelector::Direct,
2551                package: "fixture".into(),
2552                binary: "fixture".into(),
2553                path,
2554                size: bytes.len() as u64,
2555            };
2556            let planned = PlannedTarget {
2557                target: target_name.into(),
2558                policy: TargetPolicy {
2559                    target: target_name.into(),
2560                    strategy: BuildStrategy::NativeCargo,
2561                    host_os: HostOs::Linux,
2562                    host_arch: HostArch::X86_64,
2563                    qualification_host: None,
2564                    toolchain: ToolchainRequirement {
2565                        rust: "stable".into(),
2566                        cargo_zigbuild: None,
2567                        zig: None,
2568                    },
2569                    floor: crate::CompatibilityFloor::None,
2570                    qualification: Qualification::Structural,
2571                    support: SupportTier::Required,
2572                },
2573                artifact_form: PlannedAssetForm::Direct,
2574                floor_status: crate::FloorVerificationStatus::NotDeclared,
2575            };
2576            let inspection = inspect_candidate(&candidate, &planned).unwrap();
2577            assert_eq!(inspection.evidence.format, format);
2578            assert_eq!(inspection.evidence.architecture, architecture);
2579            fs::remove_dir_all(root).unwrap();
2580        }
2581    }
2582
2583    #[test]
2584    fn structural_candidate_inventory_supports_direct_bundle_and_archive() {
2585        let direct = DistributionContract::parse_toml_str(include_str!(
2586            "../../eggpack-contract/tests/fixtures/simple-direct.toml"
2587        ))
2588        .unwrap();
2589        let bundle = DistributionContract::parse_toml_str(include_str!(
2590            "../../eggpack-contract/tests/fixtures/codegg-bundle.toml"
2591        ))
2592        .unwrap();
2593        let archive = DistributionContract::parse_toml_str(include_str!(
2594            "../../eggpack-contract/tests/fixtures/egress-archive.toml"
2595        ))
2596        .unwrap();
2597        let linux = "x86_64-unknown-linux-gnu";
2598        for (contract, selectors, form) in [
2599            (
2600                direct,
2601                vec![LogicalOutputSelector::Direct],
2602                PlannedAssetForm::Direct,
2603            ),
2604            (
2605                bundle,
2606                (0..3)
2607                    .map(|index| LogicalOutputSelector::BundleEntry { index })
2608                    .collect(),
2609                PlannedAssetForm::Bundle,
2610            ),
2611            (
2612                archive,
2613                vec![
2614                    LogicalOutputSelector::ArchiveMember {
2615                        source: "egress".into(),
2616                    },
2617                    LogicalOutputSelector::ArchiveMember {
2618                        source: "bin/egress-helper".into(),
2619                    },
2620                ],
2621                PlannedAssetForm::Archive,
2622            ),
2623        ] {
2624            let root = crate::test_temp_dir("layout-structure");
2625            let host = local_host();
2626            let planned = PlannedTarget {
2627                target: linux.into(),
2628                policy: TargetPolicy {
2629                    target: linux.into(),
2630                    strategy: BuildStrategy::NativeCargo,
2631                    host_os: host.os,
2632                    host_arch: host.arch,
2633                    qualification_host: None,
2634                    toolchain: ToolchainRequirement {
2635                        rust: "stable".into(),
2636                        cargo_zigbuild: None,
2637                        zig: None,
2638                    },
2639                    floor: crate::CompatibilityFloor::None,
2640                    qualification: Qualification::Structural,
2641                    support: SupportTier::Required,
2642                },
2643                artifact_form: form,
2644                floor_status: crate::FloorVerificationStatus::NotDeclared,
2645            };
2646            let plan = ReleasePlan {
2647                schema_version: 1,
2648                release_id: "v1".into(),
2649                source_revision: "abc".into(),
2650                targets: vec![planned.clone()],
2651            };
2652            let mut bindings = Vec::new();
2653            let mut candidates = Vec::new();
2654            for (index, selector) in selectors.into_iter().enumerate() {
2655                let binary = format!("fixture-{index}");
2656                bindings.push(crate::BuildBinding {
2657                    selector: selector.clone(),
2658                    package: "fixture".into(),
2659                    binary: binary.clone(),
2660                });
2661                let path = root.join(linux).join("release").join(&binary);
2662                fs::create_dir_all(path.parent().unwrap()).unwrap();
2663                fs::write(&path, elf(CandidateArchitecture::X86_64)).unwrap();
2664                candidates.push(CandidateArtifact {
2665                    target: linux.into(),
2666                    selector,
2667                    package: "fixture".into(),
2668                    binary,
2669                    path,
2670                    size: 64,
2671                });
2672            }
2673            let builds = BuildBindingsV1 {
2674                schema_version: 1,
2675                targets: [(linux.into(), bindings)].into_iter().collect(),
2676            };
2677            let quals = QualificationBindingsV1 {
2678                schema_version: 1,
2679                targets: [(linux.into(), TargetQualificationBinding::default())]
2680                    .into_iter()
2681                    .collect(),
2682            };
2683            let attempt = BuildAttempt {
2684                release_id: plan.release_id.clone(),
2685                source_revision: plan.source_revision.clone(),
2686                target: linux.into(),
2687                strategy: BuildStrategy::NativeCargo,
2688                tool_summary: "rust stable".into(),
2689                process: ProcessEvidence {
2690                    outcome: CommandOutcome::Success,
2691                    stdout_bytes: 0,
2692                    stderr_bytes: 0,
2693                },
2694                candidates,
2695            };
2696            let evidence = qualify_target_for_host(
2697                &contract,
2698                &plan,
2699                &planned,
2700                &attempt,
2701                &builds,
2702                &quals,
2703                &QualificationRuntime::default(),
2704                &BuildCancellation::new(),
2705                host,
2706            )
2707            .unwrap();
2708            assert_eq!(evidence.status, QualificationStatus::Passed);
2709            assert_eq!(evidence.candidates.len(), builds.targets[linux].len());
2710            assert!(evidence.validate_for(&plan, &planned, &attempt).is_ok());
2711            fs::remove_dir_all(root).unwrap();
2712        }
2713    }
2714
2715    /// A GNU/Linux target that declares a compatibility floor, with a
2716    /// candidate that carries the given symbol version requirements.
2717    ///
2718    /// The target triple is pinned rather than host-adaptive: a glibc floor
2719    /// only applies to a GNU/Linux triple, so the fixture must name one on
2720    /// every host.
2721    fn floor_fixture(
2722        candidate_bytes: &[u8],
2723        floor: crate::CompatibilityFloor,
2724    ) -> (
2725        DistributionContract,
2726        ReleasePlan,
2727        PlannedTarget,
2728        BuildAttempt,
2729        BuildBindingsV1,
2730        QualificationBindingsV1,
2731        PathBuf,
2732    ) {
2733        let target_name = "x86_64-unknown-linux-gnu";
2734        let root = crate::test_temp_dir("floor-qualification");
2735        let path = candidate_path(&root, target_name);
2736        fs::create_dir_all(path.parent().unwrap()).unwrap();
2737        fs::write(&path, candidate_bytes).unwrap();
2738        let policy = TargetPolicy {
2739            target: target_name.into(),
2740            strategy: BuildStrategy::NativeCargo,
2741            host_os: HostOs::Linux,
2742            host_arch: HostArch::X86_64,
2743            qualification_host: None,
2744            toolchain: ToolchainRequirement {
2745                rust: "stable".into(),
2746                cargo_zigbuild: None,
2747                zig: None,
2748            },
2749            floor,
2750            qualification: Qualification::Structural,
2751            support: SupportTier::Required,
2752        };
2753        let floor_status = crate::planned_floor_status(&policy);
2754        let target = PlannedTarget {
2755            target: target_name.into(),
2756            policy,
2757            artifact_form: PlannedAssetForm::Direct,
2758            floor_status,
2759        };
2760        let plan = ReleasePlan {
2761            schema_version: 1,
2762            release_id: "v1".into(),
2763            source_revision: "abc123".into(),
2764            targets: vec![target.clone()],
2765        };
2766        let build_bindings = BuildBindingsV1 {
2767            schema_version: 1,
2768            targets: [(
2769                target_name.into(),
2770                vec![crate::BuildBinding {
2771                    selector: LogicalOutputSelector::Direct,
2772                    package: "fixture".into(),
2773                    binary: "fixture".into(),
2774                }],
2775            )]
2776            .into_iter()
2777            .collect(),
2778        };
2779        let qualification_bindings = QualificationBindingsV1 {
2780            schema_version: 1,
2781            targets: [(
2782                target_name.into(),
2783                TargetQualificationBinding { smoke: None },
2784            )]
2785            .into_iter()
2786            .collect(),
2787        };
2788        let attempt = BuildAttempt {
2789            release_id: plan.release_id.clone(),
2790            source_revision: plan.source_revision.clone(),
2791            target: target_name.into(),
2792            strategy: BuildStrategy::NativeCargo,
2793            tool_summary: "rust stable".into(),
2794            process: ProcessEvidence {
2795                outcome: CommandOutcome::Success,
2796                stdout_bytes: 0,
2797                stderr_bytes: 0,
2798            },
2799            candidates: vec![CandidateArtifact {
2800                target: target_name.into(),
2801                selector: LogicalOutputSelector::Direct,
2802                package: "fixture".into(),
2803                binary: "fixture".into(),
2804                path,
2805                size: candidate_bytes.len() as u64,
2806            }],
2807        };
2808        (
2809            contract(target_name),
2810            plan,
2811            target,
2812            attempt,
2813            build_bindings,
2814            qualification_bindings,
2815            root,
2816        )
2817    }
2818
2819    fn glibc_floor(major: u16, minor: u16) -> crate::CompatibilityFloor {
2820        crate::CompatibilityFloor::Glibc { major, minor }
2821    }
2822
2823    fn floor_candidate(versions: &[&str]) -> Vec<u8> {
2824        crate::floor::test_support::ElfBuilder::new(true, true)
2825            .versions(versions)
2826            .build()
2827    }
2828
2829    fn qualify_floor_fixture(
2830        bytes: &[u8],
2831        floor: crate::CompatibilityFloor,
2832    ) -> (
2833        QualificationEvidence,
2834        ReleasePlan,
2835        PlannedTarget,
2836        BuildAttempt,
2837        PathBuf,
2838    ) {
2839        let (contract, plan, target, attempt, builds, quals, root) = floor_fixture(bytes, floor);
2840        let evidence = qualify_target_for_host(
2841            &contract,
2842            &plan,
2843            &target,
2844            &attempt,
2845            &builds,
2846            &quals,
2847            &QualificationRuntime::default(),
2848            &BuildCancellation::new(),
2849            local_host(),
2850        )
2851        .unwrap();
2852        (evidence, plan, target, attempt, root)
2853    }
2854
2855    #[test]
2856    fn a_native_glibc_floor_is_verified_against_the_inspected_bytes() {
2857        let bytes = floor_candidate(&["GLIBC_2.17"]);
2858        let (evidence, plan, target, attempt, root) =
2859            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
2860        assert_eq!(evidence.floor, FloorVerificationStatus::Verified);
2861        assert_eq!(evidence.status, QualificationStatus::Passed);
2862        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2863        fs::remove_dir_all(root).unwrap();
2864    }
2865
2866    #[test]
2867    fn a_glibc_floor_contradicted_by_the_bytes_fails_the_qualification() {
2868        let bytes = floor_candidate(&["GLIBC_2.34"]);
2869        let (evidence, plan, target, attempt, root) =
2870            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
2871        // The declared floor is false, so the qualification fails closed. It is
2872        // never reported as merely unverified.
2873        assert_eq!(
2874            evidence.status,
2875            QualificationStatus::Failed(QualificationFailure::FloorNotSatisfied)
2876        );
2877        assert_eq!(evidence.floor, FloorVerificationStatus::NotSatisfied);
2878        assert!(!matches!(
2879            evidence.floor,
2880            FloorVerificationStatus::Unverified(_)
2881        ));
2882        assert!(evidence.processes.is_empty());
2883        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2884        fs::remove_dir_all(root).unwrap();
2885    }
2886
2887    #[test]
2888    fn a_candidate_without_a_version_requirement_records_that_specifically() {
2889        let bytes = floor_candidate(&[]);
2890        let (evidence, plan, target, attempt, root) =
2891            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
2892        // Compatible with any floor, but not a confirmation of one: the
2893        // status says so specifically and is not a generic pass.
2894        assert_eq!(
2895            evidence.floor,
2896            FloorVerificationStatus::Unverified(FloorUnverifiedReason::NoVersionRequirement)
2897        );
2898        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
2899        // An unverifiable floor is a recorded status, not a failed release.
2900        assert_eq!(evidence.status, QualificationStatus::Passed);
2901        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2902        fs::remove_dir_all(root).unwrap();
2903    }
2904
2905    #[test]
2906    fn a_malformed_candidate_is_never_floor_verified() {
2907        // A well-formed ELF header with a truncated dynamic table: the
2908        // structural inspection still passes, the floor inspection cannot.
2909        let mut bytes = floor_candidate(&["GLIBC_2.17"]);
2910        bytes.truncate(bytes.len() - 8);
2911        let (evidence, plan, target, attempt, root) =
2912            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
2913        assert_eq!(
2914            evidence.floor,
2915            FloorVerificationStatus::Unverified(FloorUnverifiedReason::MalformedCandidate)
2916        );
2917        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
2918        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2919        fs::remove_dir_all(root).unwrap();
2920
2921        // A candidate that is not an ELF image at all.
2922        let (evidence, plan, target, attempt, root) =
2923            qualify_floor_fixture(b"not an elf image", glibc_floor(2, 17));
2924        assert_eq!(
2925            evidence.floor,
2926            FloorVerificationStatus::Unverified(FloorUnverifiedReason::UnreadableCandidate)
2927        );
2928        assert_ne!(evidence.floor, FloorVerificationStatus::Verified);
2929        assert_eq!(
2930            evidence.status,
2931            QualificationStatus::Failed(QualificationFailure::StructuralMismatch)
2932        );
2933        assert!(evidence.validate_for(&plan, &target, &attempt).is_ok());
2934        fs::remove_dir_all(root).unwrap();
2935    }
2936
2937    #[test]
2938    fn a_plan_that_declares_a_floor_without_a_status_is_rejected() {
2939        let bytes = floor_candidate(&["GLIBC_2.17"]);
2940        let (_contract, plan, _target, _attempt, _builds, _quals, root) =
2941            floor_fixture(&bytes, glibc_floor(2, 17));
2942        assert_eq!(
2943            plan.targets[0].policy.floor,
2944            glibc_floor(2, 17),
2945            "the declared floor must survive into the plan"
2946        );
2947        assert!(plan.validate().is_ok());
2948        // A document that omits the status is read as `NotDeclared`, which is
2949        // refused for a target that declares a floor.
2950        let mut document =
2951            serde_json::from_str::<serde_json::Value>(&plan.to_json().unwrap()).unwrap();
2952        document["targets"][0]
2953            .as_object_mut()
2954            .unwrap()
2955            .remove("floor_status");
2956        let parsed: ReleasePlan = serde_json::from_value(document).unwrap();
2957        assert_eq!(
2958            parsed.targets[0].floor_status,
2959            FloorVerificationStatus::NotDeclared
2960        );
2961        assert!(parsed.validate().is_err());
2962        assert!(parsed.to_json().is_err());
2963        fs::remove_dir_all(root).unwrap();
2964    }
2965
2966    #[test]
2967    fn evidence_that_contradicts_the_plan_floor_is_rejected() {
2968        let bytes = floor_candidate(&["GLIBC_2.17"]);
2969        let (mut evidence, plan, target, attempt, root) =
2970            qualify_floor_fixture(&bytes, glibc_floor(2, 17));
2971        // The plan declares a floor, so the evidence cannot claim that no
2972        // floor was declared.
2973        evidence.floor = FloorVerificationStatus::NotDeclared;
2974        assert!(evidence.validate_for(&plan, &target, &attempt).is_err());
2975        // A contradiction is only admissible together with the matching
2976        // failure, so a contradiction claimed with a passing record is
2977        // refused too.
2978        evidence.floor = FloorVerificationStatus::NotSatisfied;
2979        assert!(evidence.validate_for(&plan, &target, &attempt).is_err());
2980        fs::remove_dir_all(root).unwrap();
2981    }
2982}