treeboot-spec 0.16.0

Executable language-agnostic conformance specification for Treeboot.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
use std::any::Any;
use std::num::NonZeroUsize;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::{Duration, Instant};

use thiserror::Error;

use crate::case::CaseDefinition;
use crate::cases::support::{CaseContext, ExecutionFailure, install_case_panic_hook, with_context};
use crate::{
    CaseMetadata, CaseOutcome, CaseRequirement, CaseResult, CommandTemplate, LocalProcessRunner,
    Runner, SuiteReport,
};

/// Selects the compatibility guarantees exercised by a suite run.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConformanceProfile {
    /// Runs functional behavior and exact specification identity cases.
    #[default]
    Full,
    /// Runs portable behavior while allowing specification-version drift.
    Functional,
}

impl ConformanceProfile {
    /// Returns the stable lowercase profile name used by the CLI and reports.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Full => "full",
            Self::Functional => "functional",
        }
    }

    fn selects(self, requirement: CaseRequirement) -> bool {
        self == Self::Full || requirement == CaseRequirement::Functional
    }
}

/// A synchronous progress event emitted while a suite runs.
#[derive(Debug)]
#[non_exhaustive]
pub enum SuiteEvent<'a> {
    /// The final case selection is known and execution is about to begin.
    SuiteStarted {
        /// Number of selected cases, including cases that will skip.
        selected_cases: usize,
    },
    /// A selected case is ready to run or report its static skip.
    ///
    /// Events from different cases may interleave when concurrency is greater
    /// than one.
    CaseStarted {
        /// One-based position in the selected case order.
        index: usize,
        /// Total number of selected cases.
        total: usize,
        /// Stable metadata for the selected case.
        case: CaseMetadata,
    },
    /// A selected case has produced its final result.
    CaseFinished {
        /// One-based position in the selected case order.
        index: usize,
        /// Total number of selected cases.
        total: usize,
        /// Final case result. The reference remains valid for this callback only.
        result: &'a CaseResult,
    },
}

/// Options controlling one suite execution.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RunOptions {
    /// Compatibility profile to execute.
    pub profile: ConformanceProfile,
    /// Optional substring matched against stable case identifiers.
    pub filter: Option<String>,
    /// Default timeout applied to each candidate invocation.
    pub invocation_timeout: Duration,
    /// Maximum number of conformance cases executed at once.
    ///
    /// The default is one so existing callers retain serial execution.
    pub concurrency: NonZeroUsize,
}

impl RunOptions {
    /// Returns options for the full profile with no filter, a 30-second timeout,
    /// and serial execution.
    pub const fn new() -> Self {
        Self {
            profile: ConformanceProfile::Full,
            filter: None,
            invocation_timeout: Duration::from_secs(30),
            concurrency: NonZeroUsize::MIN,
        }
    }

    /// Selects the compatibility profile to execute.
    #[must_use]
    pub const fn with_profile(mut self, profile: ConformanceProfile) -> Self {
        self.profile = profile;
        self
    }

    /// Restricts execution to case identifiers containing `filter`.
    #[must_use]
    pub fn with_filter(mut self, filter: impl Into<String>) -> Self {
        self.filter = Some(filter.into());
        self
    }

    /// Sets the default timeout applied to each candidate invocation.
    #[must_use]
    pub const fn with_invocation_timeout(mut self, timeout: Duration) -> Self {
        self.invocation_timeout = timeout;
        self
    }

    /// Sets the maximum number of conformance cases executed at once.
    #[must_use]
    pub const fn with_concurrency(mut self, concurrency: NonZeroUsize) -> Self {
        self.concurrency = concurrency;
        self
    }
}

impl Default for RunOptions {
    fn default() -> Self {
        Self::new()
    }
}

/// The case registry for one specification version.
#[derive(Debug, Clone, Copy, Default)]
pub struct Suite;

impl Suite {
    /// Returns the registry for the specification embedded in this crate.
    pub const fn current() -> Self {
        Self
    }

    /// Returns ordered metadata for every conformance case.
    pub fn cases(self) -> impl Iterator<Item = CaseMetadata> {
        crate::cases::definitions().map(|definition| definition.metadata)
    }

    /// Runs the suite using the default local-process runner.
    ///
    /// The command is resolved before any case changes its working directory.
    ///
    /// # Errors
    ///
    /// Returns [`SuiteError`] when a path-like candidate command cannot be
    /// resolved before execution.
    pub fn run(
        self,
        command: &CommandTemplate,
        options: RunOptions,
    ) -> Result<SuiteReport, SuiteError> {
        self.run_observed(command, options, |_| {})
    }

    /// Runs the suite through the local-process runner and synchronously reports progress.
    ///
    /// The observer runs on the suite thread. It must not retain borrowed event data.
    ///
    /// # Errors
    ///
    /// Returns [`SuiteError`] when a path-like candidate command cannot be
    /// resolved before execution.
    pub fn run_observed<F>(
        self,
        command: &CommandTemplate,
        options: RunOptions,
        observer: F,
    ) -> Result<SuiteReport, SuiteError>
    where
        F: FnMut(SuiteEvent<'_>),
    {
        let command = command
            .resolve()
            .map_err(|source| SuiteError::ResolveCandidate { source })?;
        Ok(self.run_with_observer(
            Arc::new(LocalProcessRunner::new(command)),
            options,
            observer,
        ))
    }

    /// Runs the same registry through a custom execution adapter.
    ///
    /// The adapter must make the candidate see fixture files and honor each
    /// invocation's native arguments, working directory, environment changes,
    /// input mode, and timeout.
    pub fn run_with(self, runner: Arc<dyn Runner>, options: RunOptions) -> SuiteReport {
        self.run_with_observer(runner, options, |_| {})
    }

    /// Runs the registry through a custom adapter and synchronously reports progress.
    ///
    /// Selection by case identifier and profile completes before the first event.
    /// The observer runs on the suite thread and must not retain borrowed event data.
    pub fn run_with_observer<F>(
        self,
        runner: Arc<dyn Runner>,
        options: RunOptions,
        mut observer: F,
    ) -> SuiteReport
    where
        F: FnMut(SuiteEvent<'_>),
    {
        install_case_panic_hook();
        let matching = crate::cases::definitions()
            .filter(|definition| {
                options
                    .filter
                    .as_ref()
                    .is_none_or(|filter| definition.metadata.id().contains(filter))
            })
            .collect::<Vec<_>>();
        let omitted_exact_case_count = matching
            .iter()
            .filter(|definition| !options.profile.selects(definition.metadata.requirement()))
            .count();
        let selected = matching
            .into_iter()
            .filter(|definition| options.profile.selects(definition.metadata.requirement()))
            .collect::<Vec<_>>();
        let total = selected.len();
        observer(SuiteEvent::SuiteStarted {
            selected_cases: total,
        });
        let results = if options.concurrency.get() == 1 || total < 2 {
            run_serial(
                &selected,
                &runner,
                options.invocation_timeout,
                &mut observer,
            )
        } else {
            run_concurrent(
                &selected,
                &runner,
                options.invocation_timeout,
                options.concurrency,
                &mut observer,
            )
        };

        SuiteReport {
            crate_version: env!("CARGO_PKG_VERSION"),
            specification_version: crate::SPEC_VERSION,
            host_platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH),
            candidate: runner.command().report(),
            cases: results,
            profile: options.profile,
            omitted_exact_case_count,
        }
    }
}

fn run_serial<F>(
    selected: &[&CaseDefinition],
    runner: &Arc<dyn Runner>,
    invocation_timeout: Duration,
    observer: &mut F,
) -> Vec<CaseResult>
where
    F: FnMut(SuiteEvent<'_>),
{
    let total = selected.len();
    selected
        .iter()
        .enumerate()
        .map(|(offset, definition)| {
            let index = offset + 1;
            observer(SuiteEvent::CaseStarted {
                index,
                total,
                case: definition.metadata,
            });
            let result = execute_case(definition, runner, invocation_timeout);
            observer(SuiteEvent::CaseFinished {
                index,
                total,
                result: &result,
            });
            result
        })
        .collect()
}

enum WorkerEvent {
    Started { offset: usize, case: CaseMetadata },
    Finished { offset: usize, result: CaseResult },
}

fn run_concurrent<F>(
    selected: &[&CaseDefinition],
    runner: &Arc<dyn Runner>,
    invocation_timeout: Duration,
    concurrency: NonZeroUsize,
    observer: &mut F,
) -> Vec<CaseResult>
where
    F: FnMut(SuiteEvent<'_>),
{
    let total = selected.len();
    let worker_count = concurrency.get().min(total);
    let next = AtomicUsize::new(0);
    let (sender, receiver) = mpsc::channel();
    let mut results = Vec::with_capacity(total);

    thread::scope(|scope| {
        for _ in 0..worker_count {
            let sender = sender.clone();
            let runner = Arc::clone(runner);
            let next = &next;
            scope.spawn(move || {
                loop {
                    let offset = next.fetch_add(1, Ordering::Relaxed);
                    let Some(definition) = selected.get(offset).copied() else {
                        break;
                    };
                    if sender
                        .send(WorkerEvent::Started {
                            offset,
                            case: definition.metadata,
                        })
                        .is_err()
                    {
                        break;
                    }
                    let result = execute_case(definition, &runner, invocation_timeout);
                    if sender
                        .send(WorkerEvent::Finished { offset, result })
                        .is_err()
                    {
                        break;
                    }
                }
            });
        }
        drop(sender);

        for event in receiver {
            match event {
                WorkerEvent::Started { offset, case } => observer(SuiteEvent::CaseStarted {
                    index: offset + 1,
                    total,
                    case,
                }),
                WorkerEvent::Finished { offset, result } => {
                    observer(SuiteEvent::CaseFinished {
                        index: offset + 1,
                        total,
                        result: &result,
                    });
                    results.push((offset, result));
                }
            }
        }
    });

    results.sort_unstable_by_key(|(offset, _)| *offset);
    results.into_iter().map(|(_, result)| result).collect()
}

fn execute_case(
    definition: &CaseDefinition,
    runner: &Arc<dyn Runner>,
    invocation_timeout: Duration,
) -> CaseResult {
    if let Some(reason) = definition.skip_reason {
        return CaseResult {
            case: definition.metadata,
            duration_ms: 0,
            outcome: CaseOutcome::Skipped {
                reason: reason.to_owned(),
            },
        };
    }

    let context = Arc::new(CaseContext::new(Arc::clone(runner), invocation_timeout));
    let started = Instant::now();
    let Some(run) = definition.run else {
        return CaseResult {
            case: definition.metadata,
            duration_ms: started.elapsed().as_millis().try_into().unwrap_or(u64::MAX),
            outcome: malformed_definition_outcome(definition.metadata),
        };
    };
    let execution = std::panic::catch_unwind(std::panic::AssertUnwindSafe({
        let context = Arc::clone(&context);
        move || with_context(context, run)
    }));
    let recorded = context.take_failure();
    let outcome = match (execution, recorded) {
        (Ok(()), None) => CaseOutcome::Passed,
        (_, Some(ExecutionFailure::Skipped(reason))) => CaseOutcome::Skipped { reason },
        (_, Some(ExecutionFailure::Runner(details))) => CaseOutcome::Error { details },
        (_, Some(ExecutionFailure::Fixture(details))) => CaseOutcome::Error {
            details: format!("fixture setup failed: {details}"),
        },
        (_, Some(ExecutionFailure::TimedOut(details))) => CaseOutcome::TimedOut { details },
        (Err(payload), None) if !context.candidate_invoked() => CaseOutcome::Error {
            details: format!("fixture setup failed: {}", panic_message(payload)),
        },
        (Err(payload), None) => CaseOutcome::Failed {
            details: panic_message(payload),
        },
    };
    CaseResult {
        case: definition.metadata,
        duration_ms: started.elapsed().as_millis().try_into().unwrap_or(u64::MAX),
        outcome,
    }
}

fn malformed_definition_outcome(metadata: CaseMetadata) -> CaseOutcome {
    CaseOutcome::Error {
        details: format!(
            "malformed conformance registry: case '{}' has neither a function nor a skip reason",
            metadata.id()
        ),
    }
}

fn panic_message(payload: Box<dyn Any + Send>) -> String {
    if let Some(message) = payload.downcast_ref::<String>() {
        return message.clone();
    }
    if let Some(message) = payload.downcast_ref::<&str>() {
        return (*message).to_owned();
    }
    "conformance assertion panicked without a message".to_owned()
}

/// Suite setup failure that occurs before any case executes.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SuiteError {
    /// A path-like candidate could not be resolved before fixture execution.
    #[error("failed to resolve candidate command: {source}")]
    ResolveCandidate {
        /// Candidate path resolution failure.
        #[source]
        source: std::io::Error,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    struct PassingRunner {
        command: CommandTemplate,
    }

    impl Runner for PassingRunner {
        fn command(&self) -> &CommandTemplate {
            &self.command
        }

        fn run(
            &self,
            _invocation: &crate::Invocation,
        ) -> Result<crate::InvocationResult, crate::RunnerError> {
            Ok(crate::InvocationResult::new(
                crate::Termination::Exited { code: 0 },
                Vec::new(),
                Vec::new(),
                Duration::from_millis(1),
            ))
        }
    }

    #[test]
    fn malformed_definition_should_be_an_infrastructure_error() {
        let metadata = CaseMetadata::closure("malformed.case", &["#test"]);

        let outcome = malformed_definition_outcome(metadata);

        assert!(matches!(outcome, CaseOutcome::Error { .. }));
    }

    #[test]
    fn fixture_failure_after_candidate_should_be_an_infrastructure_error() {
        let report = Suite::current().run_with(
            Arc::new(PassingRunner {
                command: CommandTemplate::new("test-candidate"),
            }),
            RunOptions {
                filter: Some("test.fixture-failure.after-candidate".to_owned()),
                ..RunOptions::default()
            },
        );

        assert_eq!(report.cases.len(), 1);
        assert!(matches!(
            &report.cases[0].outcome,
            CaseOutcome::Error { details } if details.starts_with("fixture setup failed:")
        ));
    }
}