mxc-sdk 1.0.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Windows runtime FFI for the `processmodel.dll` Learning Mode trace exports.
//!
//! Availability is gated by `IsApiSetImplemented` for the Learning Mode trace
//! API set. The three official V2 exports are then resolved via
//! `LoadLibraryExW(LOAD_LIBRARY_SEARCH_SYSTEM32)` and `GetProcAddress`.
//! `processmodel.dll` is intentionally never freed: it is a system DLL that
//! stays resident for the process lifetime, so the module handle is used only to
//! resolve exports and then dropped without `FreeLibrary`.

use std::path::Path;
use std::ptr;
use std::sync::OnceLock;
use std::time::Duration;

use crate::mxc_common::api_set::is_api_set_implemented;
use crate::mxc_common::string_util;
use windows::Win32::Foundation::{
    GetLastError, ERROR_BUSY, ERROR_LOCK_VIOLATION, ERROR_RETRY, ERROR_SHARING_VIOLATION, HANDLE,
    HMODULE,
};
use windows::Win32::System::LibraryLoader::{
    GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32,
};
use windows_core::{HRESULT, PCSTR, PCWSTR};

use crate::learning_mode_windows::LearningModeError;

/// System DLL that hosts the flat Learning Mode trace exports.
const PROCESSMODEL_DLL: &str = "processmodel.dll";
/// API-set contract for the Learning Mode trace exports.
pub const LEARNING_MODE_API_SET: &core::ffi::CStr =
    c"api-win-appmodel-processmodel~learningmodetrace";

/// `HRESULT StartLearningModeTrace(HANDLE securityEnvironment, HLEARNINGMODE_TRACE* trace)`.
///
/// `HLEARNINGMODE_TRACE` is a `typedef HANDLE`; the export surfaces it through the
/// out-parameter.
type PfnStartLearningModeTrace = unsafe extern "system" fn(
    process_security_environment: HANDLE,
    trace_out: *mut HANDLE,
) -> HRESULT;

/// `HRESULT StopLearningModeTrace(HLEARNINGMODE_TRACE trace, LPCWSTR outputEtlPath)`.
///
/// A non-null `output_path` names a file the export opens under the caller's own
/// identity; the broker seals and copies the ETL into it. A null `output_path`
/// stops without delivery. The handle remains valid so the caller may retry
/// delivery until it closes the trace.
type PfnStopLearningModeTrace =
    unsafe extern "system" fn(trace: HANDLE, output_path: *const u16) -> HRESULT;

/// `void CloseLearningModeTrace(HLEARNINGMODE_TRACE trace)`.
type PfnCloseLearningModeTrace = unsafe extern "system" fn(trace: HANDLE);

/// Opaque handle to an in-progress Learning Mode trace (`HLEARNINGMODE_TRACE`).
///
/// Obtained from [`start_trace`] or [`LearningModeApi::start_trace`]. The handle
/// owns the stop and close entry points needed for the remainder of its lifecycle.
/// Dropping or explicitly closing it releases all broker state; closing without
/// stopping discards the trace.
pub struct LearningModeTraceHandle {
    raw: HANDLE,
    stop: PfnStopLearningModeTrace,
    close: PfnCloseLearningModeTrace,
}

impl LearningModeTraceHandle {
    const STOP_DELIVERY_ATTEMPTS: usize = 3;
    const STOP_RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(25), Duration::from_millis(75)];

    fn new(raw: HANDLE, stop: PfnStopLearningModeTrace, close: PfnCloseLearningModeTrace) -> Self {
        Self { raw, stop, close }
    }

    /// Stop the trace, sealing and copying the ETL into `output_path`. Passing
    /// `None` stops without delivery.
    pub fn stop(&self, output_path: Option<&Path>) -> Result<(), LearningModeError> {
        let wide_path = encode_output_path(output_path)?;
        let path_ptr = wide_path
            .as_deref()
            .map_or(ptr::null(), |path| path.as_ptr());

        // SAFETY: `stop` was resolved from the same API surface that created
        // `raw`; `path_ptr` is null or points to a live null-terminated buffer.
        let result = unsafe { (self.stop)(self.raw, path_ptr) };
        if result.is_err() {
            return Err(LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code: result.0,
            });
        }
        Ok(())
    }

    /// Stop and deliver the trace, retrying transient output-delivery failures.
    pub fn stop_with_retry(&self, output_path: Option<&Path>) -> Result<(), LearningModeError> {
        for attempt in 0..Self::STOP_DELIVERY_ATTEMPTS {
            match self.stop(output_path) {
                Err(error)
                    if attempt + 1 < Self::STOP_DELIVERY_ATTEMPTS
                        && is_retryable_stop_error(&error) =>
                {
                    std::thread::sleep(Self::STOP_RETRY_DELAYS[attempt]);
                }
                result => return result,
            }
        }
        unreachable!("STOP_DELIVERY_ATTEMPTS is non-zero")
    }

    /// Close the trace and release all service-managed state.
    pub fn close(mut self) {
        self.close_inner();
    }

    fn close_inner(&mut self) {
        if !self.raw.0.is_null() {
            // SAFETY: `raw` was returned by `StartLearningModeTrace`, and
            // `close` was resolved from the same processmodel.dll contract.
            unsafe { (self.close)(self.raw) };
            self.raw = HANDLE(ptr::null_mut());
        }
    }
}

impl std::fmt::Debug for LearningModeTraceHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("LearningModeTraceHandle")
            .field(&self.raw)
            .finish()
    }
}

impl Drop for LearningModeTraceHandle {
    fn drop(&mut self) {
        self.close_inner();
    }
}

/// Resolved Learning Mode trace exports from `processmodel.dll`.
///
/// Construct with [`LearningModeApi::load`]. Cloning is cheap (the struct holds three
/// function pointers into the resident system DLL).
#[derive(Clone, Copy)]
pub struct LearningModeApi {
    start: PfnStartLearningModeTrace,
    stop: PfnStopLearningModeTrace,
    close: PfnCloseLearningModeTrace,
}

impl std::fmt::Debug for LearningModeApi {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LearningModeApi")
            .field("start", &(self.start as *const ()))
            .field("stop", &(self.stop as *const ()))
            .field("close", &(self.close as *const ()))
            .finish()
    }
}

impl LearningModeApi {
    /// Load `processmodel.dll` and resolve the Learning Mode trace exports.
    ///
    /// The result — success or failure — is memoized for the lifetime of the
    /// process: `processmodel.dll` is a resident system DLL whose export set does
    /// not change while the process runs, so repeated probes would only repeat the
    /// same `LoadLibraryExW`/`GetProcAddress` work and return the same answer. The
    /// cached error is cloned (see [`LearningModeError`]), preserving the original
    /// diagnostic on every call.
    ///
    /// # Errors
    /// - [`LearningModeError::ApiSetUnavailable`] if Windows does not implement
    ///   the Learning Mode trace API-set contract.
    /// - [`LearningModeError::DllLoad`] if `processmodel.dll` cannot be loaded.
    /// - [`LearningModeError::ExportMissing`] if any export is absent. Requiring
    ///   `CloseLearningModeTrace` rejects builds that expose the incompatible
    ///   earlier two-export ABI.
    pub fn load() -> Result<Self, LearningModeError> {
        static CACHE: OnceLock<Result<LearningModeApi, LearningModeError>> = OnceLock::new();
        CACHE.get_or_init(Self::load_uncached).clone()
    }

    /// Perform the actual DLL load and export resolution, bypassing the cache.
    fn load_uncached() -> Result<Self, LearningModeError> {
        if !is_api_set_implemented(LEARNING_MODE_API_SET) {
            return Err(LearningModeError::ApiSetUnavailable {
                api: "Learning Mode trace",
                api_set: LEARNING_MODE_API_SET
                    .to_str()
                    .expect("API-set contract names must be UTF-8"),
            });
        }

        let dll = string_util::to_wide(PROCESSMODEL_DLL);

        // SAFETY: `dll` is a valid null-terminated wide string that outlives the call.
        // `LOAD_LIBRARY_SEARCH_SYSTEM32` restricts the search to System32, preventing
        // DLL-planting. The module handle is used only for `GetProcAddress` below and
        // is never freed (the DLL stays resident for the process lifetime). Each
        // resolved pointer is transmuted to a signature that matches the C
        // declaration of the corresponding export exactly.
        unsafe {
            let hmodule = LoadLibraryExW(PCWSTR(dll.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32)
                .map_err(|e| LearningModeError::DllLoad(e.to_string()))?;

            let start_proc = resolve_export(hmodule, START_NAME)?;
            let stop_proc = resolve_export(hmodule, STOP_NAME)?;
            let close_proc = resolve_export(hmodule, CLOSE_NAME)?;

            let start: PfnStartLearningModeTrace = std::mem::transmute(start_proc);
            let stop: PfnStopLearningModeTrace = std::mem::transmute(stop_proc);
            let close: PfnCloseLearningModeTrace = std::mem::transmute(close_proc);

            Ok(Self { start, stop, close })
        }
    }

    /// Construct an API surface directly from raw export pointers, bypassing the
    /// DLL load. Test-only: lets dependent backend crates inject fakes without
    /// going through the memoized [`load`](Self::load) path, so fakes never
    /// populate the process cache.
    #[cfg(any(test, feature = "test-support"))]
    #[doc(hidden)]
    pub fn from_raw_parts(
        start: PfnStartLearningModeTrace,
        stop: PfnStopLearningModeTrace,
        close: PfnCloseLearningModeTrace,
    ) -> Self {
        Self { start, stop, close }
    }

    /// Start a Learning Mode trace for the sandbox identified by
    /// `security_environment`.
    ///
    /// # Safety
    /// `security_environment` must be a live `HPROCESS_SECURITY_ENVIRONMENT` handle
    /// obtained from the sandbox launch path; the broker resolves it to the target
    /// AppContainer SID server-side.
    ///
    /// # Errors
    /// [`LearningModeError::HResultCall`] if the export returns a failing HRESULT.
    pub unsafe fn start_trace(
        &self,
        security_environment: HANDLE,
    ) -> Result<LearningModeTraceHandle, LearningModeError> {
        let mut trace = HANDLE(ptr::null_mut());
        // SAFETY: `self.start` was resolved from `processmodel.dll` and matches the
        // declared C signature; `trace` is a valid out-pointer. The caller upholds
        // the validity of `security_environment` per this method's safety contract.
        let result = (self.start)(security_environment, &mut trace);
        if result.is_err() {
            return Err(LearningModeError::HResultCall {
                function: "StartLearningModeTrace",
                code: result.0,
            });
        }
        if trace.0.is_null() {
            return Err(LearningModeError::HResultCall {
                function: "StartLearningModeTrace",
                code: windows::Win32::Foundation::E_UNEXPECTED.0,
            });
        }
        Ok(LearningModeTraceHandle::new(trace, self.stop, self.close))
    }

    /// Stop `trace`, sealing and copying the ETL into `output_path`. Passing `None`
    /// stops without delivery.
    ///
    /// The handle remains live after success or failure, so callers may retry with
    /// the same or a different output path before closing it.
    ///
    /// # Errors
    /// - [`LearningModeError::InvalidInput`] if `output_path` contains an embedded NUL.
    /// - [`LearningModeError::HResultCall`] if the export returns a failing HRESULT.
    pub fn stop_trace(
        &self,
        trace: &LearningModeTraceHandle,
        output_path: Option<&Path>,
    ) -> Result<(), LearningModeError> {
        trace.stop(output_path)
    }

    /// Stop and deliver the trace, retrying only transient output-delivery
    /// failures. The trace remains live throughout the attempts and is still
    /// owned by the caller when this method returns.
    pub fn stop_trace_with_retry(
        &self,
        trace: &LearningModeTraceHandle,
        output_path: Option<&Path>,
    ) -> Result<(), LearningModeError> {
        trace.stop_with_retry(output_path)
    }
}

/// Load the Learning Mode API and start a trace for `security_environment`.
///
/// # Safety
/// `security_environment` must be a live `HPROCESS_SECURITY_ENVIRONMENT`.
pub unsafe fn start_trace(
    security_environment: HANDLE,
) -> Result<LearningModeTraceHandle, LearningModeError> {
    LearningModeApi::load()?.start_trace(security_environment)
}

fn is_retryable_stop_error(error: &LearningModeError) -> bool {
    let LearningModeError::HResultCall {
        function: "StopLearningModeTrace",
        code,
    } = error
    else {
        return false;
    };

    [
        ERROR_SHARING_VIOLATION,
        ERROR_LOCK_VIOLATION,
        ERROR_BUSY,
        ERROR_RETRY,
    ]
    .into_iter()
    .any(|win32| *code == HRESULT::from_win32(win32.0).0)
}

fn encode_output_path(output_path: Option<&Path>) -> Result<Option<Vec<u16>>, LearningModeError> {
    output_path
        .map(|path| {
            string_util::os_str_to_wide(path.as_os_str()).map_err(|_| {
                LearningModeError::InvalidInput {
                    parameter: "output_path",
                    detail: "path contains an embedded NUL".to_string(),
                }
            })
        })
        .transpose()
}

/// Resolve a single export from an already-loaded module, mapping a missing symbol
/// to [`LearningModeError::ExportMissing`].
///
/// # Safety
/// `hmodule` must be a valid module handle.
unsafe fn resolve_export(
    hmodule: HMODULE,
    name: &'static std::ffi::CStr,
) -> Result<unsafe extern "system" fn() -> isize, LearningModeError> {
    // SAFETY: `name` is a valid null-terminated C string; `hmodule` is valid per the
    // caller's contract.
    match GetProcAddress(hmodule, PCSTR(name.as_ptr().cast())) {
        Some(proc) => Ok(proc),
        None => Err(LearningModeError::ExportMissing {
            api: "Learning Mode trace",
            export: name.to_str().unwrap_or("<non-utf8 export>"),
            detail: format!(
                "GetProcAddress returned NULL (GetLastError = {})",
                last_error()
            ),
        }),
    }
}

/// Capture `GetLastError` as a plain `u32`.
fn last_error() -> u32 {
    // SAFETY: `GetLastError` has no preconditions and no side effects beyond reading
    // the calling thread's last-error slot.
    unsafe { GetLastError().0 }
}

/// Undecorated names of the three Learning Mode trace exports, in the order the
/// 2-phase capture lifecycle uses them.
const START_NAME: &core::ffi::CStr = c"StartLearningModeTrace";
const STOP_NAME: &core::ffi::CStr = c"StopLearningModeTrace";
const CLOSE_NAME: &core::ffi::CStr = c"CloseLearningModeTrace";

/// Read-only capability probe for the Learning Mode trace API-set contract.
#[must_use]
pub fn is_learning_mode_api_available() -> bool {
    is_api_set_implemented(LEARNING_MODE_API_SET)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicI32, AtomicUsize, Ordering};
    use std::sync::Mutex;
    use windows::Win32::Foundation::{E_FAIL, S_FALSE, S_OK};

    static TEST_LOCK: Mutex<()> = Mutex::new(());
    static START_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
    static STOP_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
    static STOP_FAILURE_RESULT: AtomicI32 = AtomicI32::new(E_FAIL.0);
    static STOP_FAILURES_REMAINING: AtomicUsize = AtomicUsize::new(0);
    static STOP_CALLS: AtomicUsize = AtomicUsize::new(0);
    static CLOSE_CALLS: AtomicUsize = AtomicUsize::new(0);

    unsafe extern "system" fn fake_start(_: HANDLE, trace_out: *mut HANDLE) -> HRESULT {
        let result = HRESULT(START_RESULT.load(Ordering::SeqCst));
        if result.is_ok() {
            unsafe {
                *trace_out = HANDLE(std::ptr::dangling_mut::<std::ffi::c_void>());
            }
        }
        result
    }

    unsafe extern "system" fn fake_stop(_: HANDLE, _: *const u16) -> HRESULT {
        STOP_CALLS.fetch_add(1, Ordering::SeqCst);
        if STOP_FAILURES_REMAINING
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| {
                remaining.checked_sub(1)
            })
            .is_ok()
        {
            return HRESULT(STOP_FAILURE_RESULT.load(Ordering::SeqCst));
        }
        HRESULT(STOP_RESULT.load(Ordering::SeqCst))
    }

    unsafe extern "system" fn fake_close(_: HANDLE) {
        CLOSE_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn fake_api() -> LearningModeApi {
        LearningModeApi::from_raw_parts(fake_start, fake_stop, fake_close)
    }

    fn fake_environment() -> HANDLE {
        HANDLE(std::ptr::dangling_mut::<std::ffi::c_void>())
    }

    fn reset_fakes() {
        START_RESULT.store(S_OK.0, Ordering::SeqCst);
        STOP_RESULT.store(S_OK.0, Ordering::SeqCst);
        STOP_FAILURE_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        STOP_FAILURES_REMAINING.store(0, Ordering::SeqCst);
        STOP_CALLS.store(0, Ordering::SeqCst);
        CLOSE_CALLS.store(0, Ordering::SeqCst);
    }

    #[test]
    fn api_set_probe_does_not_panic() {
        let available = is_learning_mode_api_available();
        if !available {
            assert!(matches!(
                LearningModeApi::load(),
                Err(LearningModeError::ApiSetUnavailable { .. })
            ));
        }
    }

    #[test]
    fn load_failure_is_graceful_when_api_absent() {
        // Where the API is unavailable, `load()` must return a typed error rather
        // than panicking. Where it is available this is vacuously satisfied.
        match LearningModeApi::load() {
            Ok(api) => {
                // Smoke: the resolved struct is Debug-formattable.
                let _ = format!("{api:?}");
            }
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    matches!(
                        e,
                        LearningModeError::ApiSetUnavailable { .. }
                            | LearningModeError::DllLoad(_)
                            | LearningModeError::ExportMissing { .. }
                    ),
                    "unexpected error variant: {msg}"
                );
            }
        }
    }

    #[test]
    fn output_path_rejects_embedded_nul() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let path = PathBuf::from(OsString::from_wide(&['a' as u16, 0, 'b' as u16]));
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api
            .stop_trace(&trace, Some(&path))
            .expect_err("embedded NUL must be rejected");

        assert!(matches!(
            error,
            LearningModeError::InvalidInput {
                parameter: "output_path",
                ..
            }
        ));
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 0);
        drop(trace);
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn successful_hresult_starts_retryable_trace() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        START_RESULT.store(S_FALSE.0, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe {
            api.start_trace(fake_environment())
                .expect("non-failing HRESULT should succeed")
        };

        api.stop_trace(&trace, None).unwrap();
        api.stop_trace(&trace, None).unwrap();
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 2);

        trace.close();
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn failed_hresult_keeps_trace_live_until_close() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };
        STOP_RESULT.store(E_FAIL.0, Ordering::SeqCst);

        let error = api.stop_trace(&trace, None).unwrap_err();
        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));

        drop(trace);
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn transient_stop_failure_is_retried() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        STOP_FAILURE_RESULT.store(
            HRESULT::from_win32(ERROR_SHARING_VIOLATION.0).0,
            Ordering::SeqCst,
        );
        STOP_FAILURES_REMAINING.store(2, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        api.stop_trace_with_retry(&trace, None).unwrap();

        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 3);
        trace.close();
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn permanent_stop_failure_is_not_retried() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        STOP_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api.stop_trace_with_retry(&trace, None).unwrap_err();

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn exhausted_transient_stop_retries_preserve_hresult() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let retry_hresult = HRESULT::from_win32(ERROR_LOCK_VIOLATION.0).0;
        STOP_FAILURE_RESULT.store(retry_hresult, Ordering::SeqCst);
        STOP_FAILURES_REMAINING.store(3, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api.stop_trace_with_retry(&trace, None).unwrap_err();

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == retry_hresult
        ));
        assert_eq!(
            STOP_CALLS.load(Ordering::SeqCst),
            LearningModeTraceHandle::STOP_DELIVERY_ATTEMPTS
        );
    }

    #[test]
    fn failed_start_preserves_hresult_and_does_not_close() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        START_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        let api = fake_api();

        let error = unsafe { api.start_trace(fake_environment()).unwrap_err() };

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StartLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn explicit_close_is_exactly_once() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        trace.close();

        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn load_result_is_memoized_and_consistent() {
        // `load` memoizes success or failure for the process. Repeated calls
        // must agree and never panic regardless of host support.
        let first = LearningModeApi::load().is_ok();
        let second = LearningModeApi::load().is_ok();
        assert_eq!(first, second);
    }
}