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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Pure Rust TraceLogging ETW telemetry for MXC.
//!
//! This crate provides the `Microsoft.MXC` ETW TraceLogging provider using the
//! [`tracelogging`](https://crates.io/crates/tracelogging) crate — no C++ shim
//! or WIL dependency required.
//!
//! # Platform behaviour
//!
//! - **Windows**: Events are emitted via the ETW `EventWriteTransfer` API.
//!   Each event includes a `COMMON_MXC_PARAMS` struct containing Version,
//!   Channel, IsDebugging, and `UTCReplace_AppSessionGuid`.
//! - **Non-Windows**: All functions are no-ops — the `tracelogging` crate
//!   compiles but produces no-op implementations on non-Windows targets.
//!
//! # Thread safety
//!
//! Provider state (version/channel strings) is stored in a `OnceLock` and is
//! immutable after first initialisation. The `tracelogging` provider is
//! internally synchronised.

// ---------------------------------------------------------------------------
// Windows provider implementation
// ---------------------------------------------------------------------------

#[cfg(target_os = "windows")]
mod provider {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Mutex;
    use std::sync::OnceLock;

    // Provider definition generated by build.rs — includes `id(...)` and
    // optionally `group_id(...)` for internal Microsoft builds.
    include!(concat!(env!("OUT_DIR"), "/provider_def.rs"));

    /// Privacy-approved WinExt product identifier for
    /// MXC (Microsoft Execution Containers).
    pub(crate) const PRIVACY_PRODUCT_MXC: u16 = 11;

    /// WinExt permits only Client Diagnostic Data.
    pub(crate) const PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA: u16 = 1;

    /// Cached provider state, set once at init and read on every event.
    struct ProviderState {
        version: String,
        channel: String,
    }

    static STATE: OnceLock<ProviderState> = OnceLock::new();

    /// Tracks whether the ETW provider is currently registered.
    ///
    /// A `Mutex` (rather than an `AtomicBool`) is used so the wrapper's view of
    /// registration is updated **under the same lock that serialises the
    /// underlying `register`/`unregister` ETW calls**. This prevents a
    /// concurrent `init`/`shutdown` race from leaving the wrapper flag and the
    /// provider's real state out of sync (e.g. flag set to registered after a
    /// `register()` that actually failed, or a double register/unregister).
    static REGISTERED: Mutex<usize> = Mutex::new(0);

    /// Lock-free "is the provider currently registered" flag.
    ///
    /// Mirrors [`REGISTERED`] but is readable without acquiring the mutex, so
    /// out-of-band emit paths that run in delicate contexts — the global panic
    /// hook (unwinding) and the console control handler (about to be torn down
    /// by the OS) — can cheaply skip work when telemetry is inactive without
    /// risking a mutex acquisition. It is written **inside** the `REGISTERED`
    /// critical section so the two never disagree about the final state.
    static ACTIVE: AtomicBool = AtomicBool::new(false);

    /// Returns `true` if the ETW provider is currently registered.
    ///
    /// Cheap and lock-free — intended for guarding best-effort emit paths such
    /// as [`emit_panic`](crate)-style hooks. May momentarily lag a concurrent
    /// `init`/`shutdown`, which is acceptable for best-effort telemetry.
    pub fn is_active() -> bool {
        ACTIVE.load(Ordering::Acquire)
    }

    /// Register the ETW provider and cache version/channel strings.
    ///
    /// Returns `true` if the provider is registered on return. A `true` return
    /// means the provider is registered — it does *not* guarantee an ETW
    /// session is actively listening. Returns `false` if the underlying
    /// `register()` call reported a non-zero Win32 status, in which case the
    /// provider is left unregistered so a later call may retry and callers
    /// treat telemetry as inactive.
    ///
    /// **Note:** Version and channel are captured on the **first** call only.
    /// Subsequent calls (even after [`shutdown`]) reuse the original values
    /// because the backing `OnceLock` cannot be reset.
    pub fn init(version: &str, channel: &str) -> bool {
        STATE.get_or_init(|| ProviderState {
            version: version.to_owned(),
            channel: channel.to_owned(),
        });

        let mut registered = REGISTERED.lock().unwrap_or_else(|e| e.into_inner());
        if *registered > 0 {
            // Already registered — the tracelogging crate panics on double
            // register, so retain a reference instead.
            *registered += 1;
            return true;
        }

        // SAFETY: MXC_PROVIDER is a process-lifetime static declared inside
        // this module (via `include!("provider_def.rs")`), so its storage
        // outlives every ETW callback the tracelogging runtime installs
        // against it. This function is however now called from library
        // contexts too (`crate::mxc_engine::spawn_execution_request` is compiled into
        // the `mxc_ffi` cdylib and the `mxc-sdk` library, both of which may be
        // dynamically loaded by a host). To keep the "callbacks always point at mapped
        // code" invariant, every `init` here is refcounted and paired with a
        // `shutdown` in the wrapper returned by `crate::mxc_engine::spawn_execution_request`
        // (see the `TelemetryProcess` `Drop` contract in `mxc_engine`), so
        // the ETW registration is released before the caller can dlclose /
        // FreeLibrary the containing module. Callers that unload the library
        // while a spawned handle is still live violate this precondition
        // (documented on `crate::mxc_engine::spawn_execution_request`) and can leave ETW holding
        // callbacks into unmapped memory.
        let status = unsafe { MXC_PROVIDER.register() };
        if status != 0 {
            // Registration failed; leave the reference count at zero so the wrapper
            // state matches reality and a later attempt can retry.
            return false;
        }

        *registered = 1;
        ACTIVE.store(true, Ordering::Release);
        true
    }

    /// Unregister the ETW provider.
    pub fn shutdown() {
        let mut registered = REGISTERED.lock().unwrap_or_else(|e| e.into_inner());
        if *registered > 1 {
            *registered -= 1;
        } else if *registered == 1 {
            MXC_PROVIDER.unregister();
            *registered = 0;
            ACTIVE.store(false, Ordering::Release);
        }
    }

    /// Emit an `MXC.Execution` ETW event.
    ///
    /// `phase` is the state-aware lifecycle phase that produced this event —
    /// one of `provision|start|exec|stop|deprovision`. It is empty for one-shot
    /// (non-state-aware) executions, which have no lifecycle phase.
    ///
    /// `correlation_vector` is the Microsoft Correlation Vector (MS-CV) for this
    /// event, emitted under the reserved TraceLogging field name `__TlgCV__` (the
    /// same field WIL TraceLogging uses). It is seeded from random bytes at
    /// `provision` and spun per phase, so `provision`→…→`deprovision` events can
    /// be joined across the separate `wxc-exec` processes that emit them (join on
    /// the shared base prefix). Carries no `sandbox_id` / UPN or other caller
    /// identity — privacy-safe by construction. Empty for one-shot executions
    /// (which are a single process already correlated by `AppSessionGuid`).
    #[allow(clippy::too_many_arguments)]
    pub fn log_execution(
        backend: &str,
        sandbox_kind: &str,
        exit_code: i32,
        outcome: &str,
        duration_ms: u64,
        failure_reason: &str,
        phase: &str,
        correlation_vector: &str,
    ) {
        let state = match STATE.get() {
            Some(s) => s,
            None => return,
        };

        // Compile-time flag — true for debug builds, false for release.
        // This is NOT a runtime IsDebuggerPresent() check; it mirrors
        // the MXC_CHANNEL logic for cross-platform consistency.
        let is_debug_build = cfg!(debug_assertions);

        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.Execution",
            // Informational: every completion (success or failure) is a routine
            // "what happened" record, not a fault. Severity is reserved for
            // MXC.Error (Warning) and any future provider malfunction.
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", &state.version),
                str8("Channel", &state.channel),
                bool8("IsDebugging", &is_debug_build),
                bool8("UTCReplace_AppSessionGuid", &true),
            }),
            str8("mxc.backend", backend),
            str8("mxc.sandbox_kind", sandbox_kind),
            i32("mxc.exit_code", &exit_code),
            str8("mxc.outcome", outcome),
            u64("mxc.duration_ms", &duration_ms),
            str8("mxc.failure_reason", failure_reason),
            // State-aware lifecycle phase (provision|start|exec|stop|
            // deprovision); empty for one-shot executions.
            str8("mxc.phase", phase),
            // Microsoft Correlation Vector (MS-CV), under WIL TraceLogging's
            // reserved `__TlgCV__` field. Seeded at provision and spun per phase;
            // share a base prefix across all phases of one state-aware lifecycle.
            // Empty for one-shot executions. Join on the base prefix to
            // reconstruct a full provision→…→deprovision timeline.
            str8("__TlgCV__", correlation_vector),
        );
    }

    /// Emit an `MXC.Error` ETW event.
    ///
    /// By design this event carries **no free-form error text** — only the
    /// bounded `error_type` category and the process `exit_code`. This keeps
    /// telemetry free of PII (paths, usernames, credentials) that error
    /// strings can contain.
    ///
    /// `phase` is the state-aware lifecycle phase that produced this event
    /// (`provision|start|exec|stop|deprovision`); empty for one-shot executions.
    ///
    /// `correlation_vector` is the Microsoft Correlation Vector (MS-CV), emitted
    /// under `__TlgCV__` (see [`log_execution`]); empty for one-shot executions.
    pub fn log_error(
        backend: &str,
        sandbox_kind: &str,
        error_type: &str,
        exit_code: i32,
        phase: &str,
        correlation_vector: &str,
    ) {
        let state = match STATE.get() {
            Some(s) => s,
            None => return,
        };

        let is_debug_build = cfg!(debug_assertions);

        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.Error",
            // Warning, not Error/Critical: this reports an expected operational
            // failure of a *sandboxed run* (e.g. the user's script failed, a
            // backend was unavailable, a missing/rejected config) — not a
            // defect in MXC itself. Downstream pipelines treat Error/Critical as
            // product faults that feed reliability alerting, so those levels are
            // reserved for genuine provider/telemetry malfunctions.
            level(Warning),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", &state.version),
                str8("Channel", &state.channel),
                bool8("IsDebugging", &is_debug_build),
                bool8("UTCReplace_AppSessionGuid", &true),
            }),
            str8("mxc.backend", backend),
            str8("mxc.sandbox_kind", sandbox_kind),
            str8("mxc.error_type", error_type),
            i32("mxc.exit_code", &exit_code),
            // State-aware lifecycle phase (provision|start|exec|stop|
            // deprovision); empty for one-shot executions.
            str8("mxc.phase", phase),
            // MS-CV under `__TlgCV__` (see MXC.Execution); empty for one-shot.
            str8("__TlgCV__", correlation_vector),
        );
    }

    /// Emit one independently parseable chunk of a Learning Mode verbose
    /// logging document.
    #[allow(clippy::too_many_arguments)]
    pub fn log_verbose(
        backend: &str,
        sandbox_kind: &str,
        phase: &str,
        correlation_vector: &str,
        document_id: &str,
        document_version: u32,
        chunk_index: u32,
        chunk_count: u32,
        document_bytes: u64,
        document_sha256: &str,
        content: &str,
        summary: &str,
    ) -> u32 {
        let state = match STATE.get() {
            Some(s) => s,
            None => return 0,
        };

        let is_debug_build = cfg!(debug_assertions);

        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.VerboseDenials",
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", &state.version),
                str8("Channel", &state.channel),
                bool8("IsDebugging", &is_debug_build),
                bool8("UTCReplace_AppSessionGuid", &true),
            }),
            str8("mxc.backend", backend),
            str8("mxc.sandbox_kind", sandbox_kind),
            str8("mxc.phase", phase),
            str8("__TlgCV__", correlation_vector),
            str8("mxc.document_id", document_id),
            u32("mxc.document_version", &document_version),
            u32("mxc.chunk_index", &chunk_index),
            u32("mxc.chunk_count", &chunk_count),
            u64("mxc.document_bytes", &document_bytes),
            str8("mxc.document_sha256", document_sha256),
            str8("mxc.content", content),
            str8("mxc.summary", summary),
        )
    }

    fn common_params(state: &ProviderState) -> (&str, &str, bool, bool) {
        (&state.version, &state.channel, cfg!(debug_assertions), true)
    }

    pub fn log_process_exited(identity: &str, process_id: u32, exit_code: i32) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.ProcessExited",
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            u32("mxc.process_id", &process_id),
            i32("mxc.exit_code", &exit_code),
        );
    }

    pub fn log_process_timed_out(identity: &str, process_id: u32, timeout_ms: u64) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.ProcessTimedOut",
            level(Warning),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            u32("mxc.process_id", &process_id),
            u64("mxc.timeout_ms", &timeout_ms),
        );
    }

    pub fn log_process_kill_failed(
        identity: &str,
        process_id: u32,
        error_type: &str,
        error_code: i32,
    ) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.ProcessKillFailed",
            level(Error),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            u32("mxc.process_id", &process_id),
            str8("mxc.error_type", error_type),
            i32("mxc.error_code", &error_code),
        );
    }

    pub fn log_enforcement_degraded(
        identity: &str,
        tier: &str,
        needs_dacl_augmentation: bool,
        degradation_reasons: &str,
        effective_enforcement_level: &str,
    ) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.EnforcementDegraded",
            level(Warning),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            str8("mxc.tier", tier),
            bool8("mxc.needs_dacl_augmentation", &needs_dacl_augmentation),
            str8("mxc.degradation_reasons", degradation_reasons),
            str8("mxc.effective_enforcement_level", effective_enforcement_level),
        );
    }

    pub fn log_policy_hash(identity: &str, policy_hash: &str, config_schema_version: &str) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.PolicyHash",
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            str8("mxc.policy_hash", policy_hash),
            str8("mxc.config_schema_version", config_schema_version),
        );
    }

    pub fn log_network_policy_applied(
        identity: &str,
        enforcement_mode: &str,
        default_policy: &str,
        proxy_port: u64,
    ) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.SandboxNetworkPolicyApplied",
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            str8("mxc.enforcement_mode", enforcement_mode),
            str8("mxc.default_policy", default_policy),
            u64("mxc.proxy_port", &proxy_port),
        );
    }

    pub fn log_sandbox_torn_down(identity: &str, status: &str, released_resources: &str) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.SandboxTornDown",
            level(Informational),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.identity", identity),
            str8("mxc.status", status),
            str8("mxc.released_resources", released_resources),
        );
    }

    pub fn log_config_rejected(
        correlation_id: &str,
        backend: &str,
        reason: &str,
        offending_field: &str,
        phase: &str,
    ) {
        let Some(state) = STATE.get() else { return };
        let (version, channel, debugging, app_session) = common_params(state);
        tracelogging::write_event!(
            MXC_PROVIDER,
            "MXC.ConfigRejected",
            level(Warning),
            keyword(MXC_EVENT_KEYWORD),
            u16("PartA_PrivacyProduct", &PRIVACY_PRODUCT_MXC),
            u16(
                "PartA_PrivacyDataCategory",
                &PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA,
            ),
            u64("PartA_PrivTags", &MXC_PRIVACY_TAG),
            struct("COMMON_MXC_PARAMS", {
                str8("Version", version),
                str8("Channel", channel),
                bool8("IsDebugging", &debugging),
                bool8("UTCReplace_AppSessionGuid", &app_session),
            }),
            str8("mxc.correlation_id", correlation_id),
            str8("mxc.backend", backend),
            str8("mxc.reason", reason),
            str8("mxc.offending_field", offending_field),
            str8("mxc.phase", phase),
        );
    }
}

// ---------------------------------------------------------------------------
// Non-Windows no-op stubs
// ---------------------------------------------------------------------------

#[cfg(not(target_os = "windows"))]
mod provider {
    /// Non-Windows builds never route to the Microsoft telemetry pipeline.
    pub const IS_UTC_ROUTED: bool = false;

    pub fn init(_version: &str, _channel: &str) -> bool {
        false
    }

    pub fn shutdown() {}

    pub fn is_active() -> bool {
        false
    }

    #[allow(clippy::too_many_arguments)]
    pub fn log_execution(
        _backend: &str,
        _sandbox_kind: &str,
        _exit_code: i32,
        _outcome: &str,
        _duration_ms: u64,
        _failure_reason: &str,
        _phase: &str,
        _correlation_vector: &str,
    ) {
    }

    pub fn log_error(
        _backend: &str,
        _sandbox_kind: &str,
        _error_type: &str,
        _exit_code: i32,
        _phase: &str,
        _correlation_vector: &str,
    ) {
    }
    #[allow(clippy::too_many_arguments)]
    pub fn log_verbose(
        _backend: &str,
        _sandbox_kind: &str,
        _phase: &str,
        _correlation_vector: &str,
        _document_id: &str,
        _document_version: u32,
        _chunk_index: u32,
        _chunk_count: u32,
        _document_bytes: u64,
        _document_sha256: &str,
        _content: &str,
        _summary: &str,
    ) -> u32 {
        0
    }
    pub fn log_process_exited(_identity: &str, _process_id: u32, _exit_code: i32) {}
    pub fn log_process_timed_out(_identity: &str, _process_id: u32, _timeout_ms: u64) {}
    pub fn log_process_kill_failed(
        _identity: &str,
        _process_id: u32,
        _error_type: &str,
        _error_code: i32,
    ) {
    }
    pub fn log_enforcement_degraded(
        _identity: &str,
        _tier: &str,
        _needs_dacl_augmentation: bool,
        _degradation_reasons: &str,
        _effective_enforcement_level: &str,
    ) {
    }
    pub fn log_policy_hash(_identity: &str, _policy_hash: &str, _config_schema_version: &str) {}
    pub fn log_network_policy_applied(
        _identity: &str,
        _enforcement_mode: &str,
        _default_policy: &str,
        _proxy_port: u64,
    ) {
    }
    pub fn log_sandbox_torn_down(_identity: &str, _status: &str, _released_resources: &str) {}
    pub fn log_config_rejected(
        _correlation_id: &str,
        _backend: &str,
        _reason: &str,
        _offending_field: &str,
        _phase: &str,
    ) {
    }
}

pub use provider::*;

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    /// The provider uses global state (`OnceLock`), so tests that call
    /// `init`/`shutdown` must not run concurrently.
    static TEST_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn event_names_preserve_collector_contract() {
        let source = include_str!("mod.rs");
        let provider_source = source
            .split("// Tests")
            .next()
            .expect("provider source precedes tests");
        assert!(
            provider_source.contains("\"MXC.Execution\","),
            "execution event identity changed"
        );
        assert!(
            provider_source.contains("\"MXC.Error\","),
            "error event identity changed"
        );
        assert!(
            provider_source.contains("\"MXC.VerboseDenials\","),
            "verbose event identity changed"
        );
        let error_section = provider_source
            .split("\"MXC.Error\",")
            .nth(1)
            .unwrap_or_default();
        assert!(
            error_section.contains("str8(\"mxc.backend\", backend)"),
            "MXC.Error must emit mxc.backend"
        );
        assert!(
            error_section.contains("str8(\"mxc.sandbox_kind\", sandbox_kind)"),
            "MXC.Error must emit mxc.sandbox_kind"
        );
    }

    #[test]
    fn winext_part_a_fields_preserve_privacy_contract() {
        let source = include_str!("mod.rs");
        let provider_source = source
            .split("// Tests")
            .next()
            .expect("provider source precedes tests");

        assert!(provider_source.contains("const PRIVACY_PRODUCT_MXC: u16 = 11;"));
        assert!(provider_source
            .contains("const PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA: u16 = 1;"));
        assert_eq!(
            provider_source
                .matches("u16(\"PartA_PrivacyProduct\", &PRIVACY_PRODUCT_MXC)")
                .count(),
            11,
            "every MXC event must carry privacy product 11"
        );
        assert_eq!(
            provider_source
                .matches("\"PartA_PrivacyDataCategory\"")
                .count(),
            11,
            "every MXC event must carry a privacy data category"
        );
        assert_eq!(
            provider_source
                .matches("&PRIVACY_DATA_CATEGORY_CLIENT_DIAGNOSTIC_DATA")
                .count(),
            11,
            "every MXC event must use Client Diagnostic Data category 1"
        );
        assert_eq!(
            provider_source
                .matches("u64(\"PartA_PrivTags\", &MXC_PRIVACY_TAG)")
                .count(),
            11,
            "every MXC event must retain its approved privacy tag"
        );
    }

    #[test]
    fn init_shutdown_roundtrip() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let ok = init("0.0.0-test", "dev");
        if cfg!(target_os = "windows") {
            assert!(ok, "init should succeed on Windows");
        } else {
            assert!(!ok, "init should be a no-op on non-Windows");
        }
        shutdown();
    }

    #[test]
    fn double_init_is_safe() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let first = init("0.0.0-test", "dev");
        let second = init("0.0.0-test", "dev");
        assert_eq!(second, first);
        shutdown();
        assert_eq!(
            is_active(),
            first,
            "one retained registration must remain active only when init succeeded"
        );
        shutdown();
        assert!(
            !is_active(),
            "the final release must leave the provider inactive"
        );
    }

    #[test]
    fn shutdown_without_init() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        shutdown();
    }

    #[test]
    fn is_active_tracks_registration() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let ok = init("0.0.0-test", "dev");
        // `is_active` reflects whether registration actually succeeded, which
        // matches `init`'s return on every platform (always false off Windows).
        assert_eq!(is_active(), ok);
        shutdown();
        assert!(!is_active(), "provider must be inactive after shutdown");
    }

    #[test]
    fn log_execution_after_init() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _ = init("0.0.0-test", "dev");
        log_execution(
            "test_backend",
            "test_backend",
            0,
            "success",
            100,
            "",
            "provision",
            "iso:wxc-abcd",
        );
        shutdown();
    }

    #[test]
    fn log_error_after_init() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _ = init("0.0.0-test", "dev");
        log_error(
            "test_backend",
            "test_backend",
            "config_error",
            1,
            "provision",
            "iso:wxc-abcd",
        );
        shutdown();
    }

    #[test]
    fn log_verbose_after_init() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _ = init("0.0.0-test", "dev");
        log_verbose(
            "processcontainer",
            "process",
            "",
            "",
            "0123456789abcdef0123456789abcdef",
            2,
            0,
            1,
            64,
            "abc",
            "[]",
            r#"{"totalOccurrences":0}"#,
        );
        shutdown();
    }

    #[test]
    fn log_without_init() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        log_execution(
            "test_backend",
            "test_backend",
            0,
            "success",
            50,
            "none",
            "",
            "",
        );
        log_error("test_backend", "test_backend", "unknown", 1, "", "");
        log_verbose("", "", "", "", "", 0, 0, 0, 0, "", "[]", "{}");
    }

    #[test]
    fn log_after_shutdown() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _ = init("0.0.0-test", "dev");
        shutdown();
        log_execution(
            "test_backend",
            "test_backend",
            1,
            "failure",
            200,
            "timeout",
            "exec",
            "iso:wxc-abcd",
        );
        log_error(
            "test_backend",
            "test_backend",
            "process_error",
            1,
            "exec",
            "iso:wxc-abcd",
        );
    }

    #[test]
    fn handles_empty_strings() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let _ = init("", "");
        log_execution("", "", 0, "", 0, "", "", "");
        log_error("", "", "", 0, "", "");
        log_verbose("", "", "", "", "", 0, 0, 0, 0, "", "[]", "{}");
        shutdown();
    }

    #[test]
    fn concurrent_init_shutdown_is_safe() {
        let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let results = std::thread::scope(|scope| {
            let handles: Vec<_> = (0..8)
                .map(|_| {
                    scope.spawn(|| {
                        let active = init("0.0.0-concurrent-test", "dev");
                        if active {
                            log_execution(
                                "test_backend",
                                "test_backend",
                                0,
                                "success",
                                0,
                                "",
                                "",
                                "",
                            );
                            shutdown();
                        }
                        active
                    })
                })
                .collect();
            handles
                .into_iter()
                .map(|handle| handle.join().unwrap())
                .collect::<Vec<_>>()
        });

        if cfg!(target_os = "windows") {
            assert!(results.iter().all(|active| *active));
            assert!(!is_active());
        } else {
            assert!(results.iter().all(|active| !*active));
        }
    }
}

// ---------------------------------------------------------------------------
// Provider code-generation tests
// ---------------------------------------------------------------------------
//
// The build script's GUID validation and `define_provider!` code generation
// live in `provider_codegen.rs`. Cargo never runs `#[cfg(test)]` modules inside
// a build script, so we `include!` the same source here to exercise it under
// `cargo test`.
#[cfg(test)]
mod provider_codegen_tests {
    include!("provider_codegen.rs");

    #[test]
    fn absent_guid_yields_plain_provider() {
        let def = generate_provider_def(None);
        assert!(def.contains("\"Microsoft.MXC\""));
        assert!(!def.contains("group_id"));
        assert!(def.contains("IS_UTC_ROUTED: bool = false"));
    }

    #[test]
    fn empty_guid_yields_plain_provider() {
        let def = generate_provider_def(Some(""));
        assert!(!def.contains("group_id"));
        assert!(def.contains("IS_UTC_ROUTED: bool = false"));
    }

    #[test]
    fn valid_guid_adds_group_id() {
        let def = generate_provider_def(Some("7f10def4-a258-5fea-510e-2c3bb976687f"));
        assert!(def.contains("group_id(\"7f10def4-a258-5fea-510e-2c3bb976687f\")"));
        assert!(def.contains("IS_UTC_ROUTED: bool = true"));
    }

    #[test]
    #[should_panic(expected = "not a valid GUID")]
    fn invalid_guid_panics() {
        let _ = generate_provider_def(Some("not-a-valid-guid"));
    }

    #[test]
    fn guid_validation_accepts_and_rejects() {
        assert!(is_valid_guid("7f10def4-a258-5fea-510e-2c3bb976687f"));
        // Missing dashes.
        assert!(!is_valid_guid("7f10def4a2585fea510e2c3bb976687f"));
        // Non-hex characters.
        assert!(!is_valid_guid("zzzzzzzz-zzzz-zzzz-zzzz-zzzzzzzzzzzz"));
        // Wrong segment lengths.
        assert!(!is_valid_guid("7f10def-a258-5fea-510e-2c3bb976687f"));
    }

    #[test]
    fn absent_guid_yields_local_only_event_metadata() {
        let constants = generate_event_metadata_consts(None);
        assert!(constants.contains("MXC_EVENT_KEYWORD: u64 = 0x1"));
        assert!(constants.contains("MXC_PRIVACY_TAG: u64 = 0x0"));
    }

    #[test]
    fn empty_guid_yields_local_only_event_metadata() {
        let constants = generate_event_metadata_consts(Some(""));
        assert!(constants.contains("MXC_EVENT_KEYWORD: u64 = 0x1"));
        assert!(constants.contains("MXC_PRIVACY_TAG: u64 = 0x0"));
    }

    #[test]
    fn valid_guid_yields_telemetry_event_metadata() {
        let constants =
            generate_event_metadata_consts(Some("7f10def4-a258-5fea-510e-2c3bb976687f"));
        assert!(constants.contains("MXC_EVENT_KEYWORD: u64 = 0x0000_4000_0000_0000"));
        assert!(constants.contains("MXC_PRIVACY_TAG: u64 = 0x0000_0000_0200_0000"));
    }
}