hisi-rf-core 0.1.0-alpha.24

Chip-neutral async radio controller contracts for HiSilicon embedded Rust
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
//! Allocation-free, secret-free diagnostics for the public radio facade.

use core::fmt;

use crate::{BackendError, BackendErrorClass, Error};

/// Versioned machine-readable diagnostic schema.
pub const DIAGNOSTIC_SCHEMA: &str = "hisi-rf-error/v3";

/// Maximum number of backend trace entries retained by one public error.
pub const DIAGNOSTIC_TRACE_CAPACITY: usize = 4;

/// Stable identity for a public RF failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticCode {
    /// The caller tried to claim an already-owned radio state.
    AlreadyInitialized,
    /// A backend initialization step failed.
    BackendInitialize,
    /// Another operation currently owns the backend.
    BackendBusy,
    /// The end-to-end protocol operation timeout elapsed.
    OperationTimeout,
    /// A bounded backend operation timed out.
    BackendTimeout,
    /// A requested operation was cancelled before completion.
    OperationCancelled,
    /// A bounded runtime or profile resource was unavailable.
    ResourceUnavailable,
    /// The selected security mode is unsupported by this build or target.
    UnsupportedSecurity,
    /// Association or authorization failed.
    ConnectionFailed,
    /// A backend-specific failure has no more specific stable classification.
    BackendOther,
    /// The runner observed an invalid command/completion sequence.
    Protocol,
}

impl DiagnosticCode {
    /// Stable identifier used by JSON output, logs, and support tooling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::AlreadyInitialized => "radio.already_initialized",
            Self::BackendInitialize => "backend.initialize",
            Self::BackendBusy => "backend.busy",
            Self::OperationTimeout => "operation.timeout",
            Self::BackendTimeout => "backend.timeout",
            Self::OperationCancelled => "operation.cancelled",
            Self::ResourceUnavailable => "resource.unavailable",
            Self::UnsupportedSecurity => "wifi.unsupported_security",
            Self::ConnectionFailed => "wifi.connection_failed",
            Self::BackendOther => "backend.other",
            Self::Protocol => "radio.protocol",
        }
    }
}

/// Stable stage at which a public RF failure was reported.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticStage {
    /// Radio/backend construction and initialization.
    Initialize,
    /// Radio ownership or runner command/completion handling.
    ControlPlane,
    /// Wi-Fi association or authorization.
    Connect,
    /// Wi-Fi scan and BSS discovery.
    Scan,
    /// 802.11 authentication management exchange.
    Authenticate,
    /// 802.11 association exchange.
    Associate,
    /// WPA3 SAE external-auth exchange.
    Sae,
    /// WPA EAPOL key exchange.
    Eapol,
    /// Protected-management-frame negotiation or recovery.
    Pmf,
    /// Explicit disconnect/deauthentication handling.
    Disconnect,
    /// Runtime scheduling, wait, or IPC service.
    Runtime,
    /// A bounded backend operation whose protocol-specific stage is unknown.
    Operation,
    /// A backend-specific stage not represented by the current schema.
    Backend,
}

impl DiagnosticStage {
    /// Stable machine-readable stage name.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Initialize => "initialize",
            Self::ControlPlane => "control_plane",
            Self::Connect => "connect",
            Self::Scan => "scan",
            Self::Authenticate => "authenticate",
            Self::Associate => "associate",
            Self::Sae => "sae",
            Self::Eapol => "eapol",
            Self::Pmf => "pmf",
            Self::Disconnect => "disconnect",
            Self::Runtime => "runtime",
            Self::Operation => "operation",
            Self::Backend => "backend",
        }
    }
}

/// Stable identity for one bounded backend trace value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiagnosticTraceKind {
    /// Raw status returned by the backend or protocol engine.
    BackendStatus,
    /// Raw status returned by a chip vendor driver or firmware ABI.
    VendorStatus,
    /// IEEE 802.11 status code from authentication/association.
    IeeeStatus,
    /// Raw signed status returned by the pinned upstream hostap port.
    HostapStatus,
    /// Wi-Fi disconnect reason.
    DisconnectReason,
    /// Upstream hostap context state snapshot.
    SupplicantContext,
    /// WS63 driver/port state snapshot.
    DriverContext,
    /// Runtime service error code.
    RuntimeCode,
    /// Amount of a bounded resource required by the selected profile.
    ResourceRequired,
    /// Amount of a bounded resource available before initialization.
    ResourceAvailable,
    /// Stable composition-defined owner of a failing resource child.
    ResourceOwner,
    /// Largest contiguous payload allocation available at admission failure.
    LargestContiguous,
}

impl DiagnosticTraceKind {
    /// Stable machine-readable trace field name.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::BackendStatus => "backend_status",
            Self::VendorStatus => "vendor_status",
            Self::IeeeStatus => "ieee_status",
            Self::HostapStatus => "hostap_status",
            Self::DisconnectReason => "disconnect_reason",
            Self::SupplicantContext => "supplicant_context",
            Self::DriverContext => "driver_context",
            Self::RuntimeCode => "runtime_code",
            Self::ResourceRequired => "resource_required",
            Self::ResourceAvailable => "resource_available",
            Self::ResourceOwner => "resource_owner",
            Self::LargestContiguous => "largest_contiguous",
        }
    }
}

/// One numeric, secret-free backend trace entry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DiagnosticTraceEntry {
    kind: DiagnosticTraceKind,
    value: u32,
}

impl DiagnosticTraceEntry {
    /// Stable identity of this value.
    pub const fn kind(self) -> DiagnosticTraceKind {
        self.kind
    }

    /// Lossless numeric value.
    pub const fn value(self) -> u32 {
        self.value
    }
}

/// Fixed-capacity trace attached to one backend error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DiagnosticTrace {
    entries: [Option<DiagnosticTraceEntry>; DIAGNOSTIC_TRACE_CAPACITY],
    len: u8,
    truncated: bool,
}

impl DiagnosticTrace {
    /// Create an empty trace.
    pub const fn new() -> Self {
        Self {
            entries: [None; DIAGNOSTIC_TRACE_CAPACITY],
            len: 0,
            truncated: false,
        }
    }

    /// Number of retained entries.
    pub const fn len(self) -> usize {
        self.len as usize
    }

    /// Whether no trace entry is present.
    pub const fn is_empty(self) -> bool {
        self.len == 0
    }

    /// Whether additional backend entries were dropped at the fixed limit.
    pub const fn is_truncated(self) -> bool {
        self.truncated
    }

    /// Return an entry by index.
    pub const fn get(self, index: usize) -> Option<DiagnosticTraceEntry> {
        if index < self.len as usize {
            self.entries[index]
        } else {
            None
        }
    }

    pub(crate) fn push(&mut self, kind: DiagnosticTraceKind, value: u32) {
        let index = self.len as usize;
        if index < DIAGNOSTIC_TRACE_CAPACITY {
            self.entries[index] = Some(DiagnosticTraceEntry { kind, value });
            self.len += 1;
        } else {
            self.truncated = true;
        }
    }
}

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

/// Action a caller or operator can take after a failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RecoveryAction {
    /// Keep using the controller that already owns the supplied state.
    UseExistingController,
    /// Recreate the radio controller and reinitialize the backend.
    Reinitialize,
    /// Wait for the current operation to finish before retrying.
    WaitAndRetry,
    /// Retry the bounded operation; repeated failures require deeper inspection.
    RetryOperation,
    /// Increase the declared resources or select a smaller validated profile.
    ProvideResources,
    /// Select a security profile supported by the target and build.
    SelectSupportedSecurity,
    /// Inspect network status and the lossless backend code before retrying.
    InspectNetworkAndRetry,
    /// Preserve and report the backend code with target/profile information.
    InspectBackendCode,
    /// Recreate the controller and report a repeated protocol failure.
    RecreateController,
}

impl RecoveryAction {
    /// Stable machine-readable action name.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::UseExistingController => "use_existing_controller",
            Self::Reinitialize => "reinitialize",
            Self::WaitAndRetry => "wait_and_retry",
            Self::RetryOperation => "retry_operation",
            Self::ProvideResources => "provide_resources",
            Self::SelectSupportedSecurity => "select_supported_security",
            Self::InspectNetworkAndRetry => "inspect_network_and_retry",
            Self::InspectBackendCode => "inspect_backend_code",
            Self::RecreateController => "recreate_controller",
        }
    }
}

/// Allocation-free diagnostic view of a public RF [`Error`].
///
/// The view intentionally contains no SSID, passphrase, key material, or
/// arbitrary backend text. Unknown chip failures retain their numeric code so
/// agent and support tooling can identify them without losing information.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Diagnostic {
    code: DiagnosticCode,
    stage: DiagnosticStage,
    action: RecoveryAction,
    backend_code: Option<u32>,
    profile_revision: Option<&'static str>,
    trace: DiagnosticTrace,
}

impl Diagnostic {
    /// Schema used by [`Self::write_json`].
    pub const fn schema(self) -> &'static str {
        DIAGNOSTIC_SCHEMA
    }

    /// Stable error identity.
    pub const fn code(self) -> DiagnosticCode {
        self.code
    }

    /// Stable operation stage.
    pub const fn stage(self) -> DiagnosticStage {
        self.stage
    }

    /// Recommended next action.
    pub const fn action(self) -> RecoveryAction {
        self.action
    }

    /// Lossless chip/backend-specific code, when the failure came from a backend.
    pub const fn backend_code(self) -> Option<u32> {
        self.backend_code
    }

    /// Backend/profile revision that produced this failure.
    pub const fn profile_revision(self) -> Option<&'static str> {
        self.profile_revision
    }

    /// Bounded, numeric backend trace.
    pub const fn trace(self) -> DiagnosticTrace {
        self.trace
    }

    /// Stable documentation fragment for this diagnostic.
    pub const fn docs_anchor(self) -> &'static str {
        match self.code {
            DiagnosticCode::AlreadyInitialized => "errors-radio-already-initialized",
            DiagnosticCode::BackendInitialize => "errors-backend-initialize",
            DiagnosticCode::BackendBusy => "errors-backend-busy",
            DiagnosticCode::OperationTimeout => "errors-operation-timeout",
            DiagnosticCode::BackendTimeout => "errors-backend-timeout",
            DiagnosticCode::OperationCancelled => "errors-operation-cancelled",
            DiagnosticCode::ResourceUnavailable => "errors-resource-unavailable",
            DiagnosticCode::UnsupportedSecurity => "errors-wifi-unsupported-security",
            DiagnosticCode::ConnectionFailed => "errors-wifi-connection-failed",
            DiagnosticCode::BackendOther => "errors-backend-other",
            DiagnosticCode::Protocol => "errors-radio-protocol",
        }
    }

    /// Write one deterministic JSON object without allocation.
    pub fn write_json(self, output: &mut impl fmt::Write) -> fmt::Result {
        write!(
            output,
            "{{\"schema\":\"{}\",\"code\":\"{}\",\"stage\":\"{}\",\"action\":\"{}\",\"backend_code\":",
            self.schema(),
            self.code.as_str(),
            self.stage.as_str(),
            self.action.as_str(),
        )?;
        match self.backend_code {
            Some(code) => write!(output, "{code}"),
            None => output.write_str("null"),
        }?;
        output.write_str(",\"profile_revision\":")?;
        match self.profile_revision {
            Some(revision) => write_json_string(output, revision)?,
            None => output.write_str("null")?,
        }
        output.write_str(",\"trace\":[")?;
        for index in 0..self.trace.len() {
            if index != 0 {
                output.write_str(",")?;
            }
            let entry = self.trace.get(index).expect("trace length is bounded");
            write!(
                output,
                "{{\"kind\":\"{}\",\"value\":{}}}",
                entry.kind().as_str(),
                entry.value()
            )?;
        }
        write!(
            output,
            "],\"trace_truncated\":{},\"docs\":\"{}\"}}",
            self.trace.is_truncated(),
            self.docs_anchor()
        )
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{} at {}; next action: {}",
            self.code.as_str(),
            self.stage.as_str(),
            self.action.as_str(),
        )?;
        if let Some(code) = self.backend_code {
            write!(formatter, "; backend code: 0x{code:08x}")?;
        }
        Ok(())
    }
}

impl Error {
    /// Convert this error into the stable diagnostic schema.
    pub const fn diagnostic(self) -> Diagnostic {
        match self {
            Self::AlreadyInitialized => Diagnostic {
                code: DiagnosticCode::AlreadyInitialized,
                stage: DiagnosticStage::ControlPlane,
                action: RecoveryAction::UseExistingController,
                backend_code: None,
                profile_revision: None,
                trace: DiagnosticTrace::new(),
            },
            Self::Backend(error) => error.diagnostic(),
            Self::Protocol => Diagnostic {
                code: DiagnosticCode::Protocol,
                stage: DiagnosticStage::ControlPlane,
                action: RecoveryAction::RecreateController,
                backend_code: None,
                profile_revision: None,
                trace: DiagnosticTrace::new(),
            },
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.diagnostic().fmt(formatter)
    }
}

impl BackendError {
    /// Convert this backend error into the stable diagnostic schema.
    pub const fn diagnostic(self) -> Diagnostic {
        let (code, action) = match self.class() {
            BackendErrorClass::Initialize => (
                DiagnosticCode::BackendInitialize,
                RecoveryAction::Reinitialize,
            ),
            BackendErrorClass::Busy => (DiagnosticCode::BackendBusy, RecoveryAction::WaitAndRetry),
            BackendErrorClass::OperationTimeout => (
                DiagnosticCode::OperationTimeout,
                RecoveryAction::RetryOperation,
            ),
            BackendErrorClass::BackendTimeout => (
                DiagnosticCode::BackendTimeout,
                RecoveryAction::RetryOperation,
            ),
            BackendErrorClass::Cancelled => (
                DiagnosticCode::OperationCancelled,
                RecoveryAction::RetryOperation,
            ),
            BackendErrorClass::ResourceUnavailable => (
                DiagnosticCode::ResourceUnavailable,
                RecoveryAction::ProvideResources,
            ),
            BackendErrorClass::UnsupportedSecurity => (
                DiagnosticCode::UnsupportedSecurity,
                RecoveryAction::SelectSupportedSecurity,
            ),
            BackendErrorClass::Connect => (
                DiagnosticCode::ConnectionFailed,
                RecoveryAction::InspectNetworkAndRetry,
            ),
            BackendErrorClass::Other => (
                DiagnosticCode::BackendOther,
                RecoveryAction::InspectBackendCode,
            ),
        };
        Diagnostic {
            code,
            stage: self.stage(),
            action,
            backend_code: Some(self.code()),
            profile_revision: self.profile_revision(),
            trace: self.trace(),
        }
    }
}

fn write_json_string(output: &mut impl fmt::Write, value: &str) -> fmt::Result {
    output.write_str("\"")?;
    for character in value.chars() {
        match character {
            '\"' => output.write_str("\\\"")?,
            '\\' => output.write_str("\\\\")?,
            '\n' => output.write_str("\\n")?,
            '\r' => output.write_str("\\r")?,
            '\t' => output.write_str("\\t")?,
            control if control.is_control() => write!(output, "\\u{:04x}", control as u32)?,
            character => output.write_char(character)?,
        }
    }
    output.write_str("\"")
}

impl fmt::Display for BackendError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.diagnostic().fmt(formatter)
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use std::string::String;

    use super::*;

    #[test]
    fn unknown_backend_codes_remain_lossless_and_actionable() {
        let error = BackendError::new(BackendErrorClass::Other, 0xdeaf_0042);
        let diagnostic = error.diagnostic();

        assert_eq!(diagnostic.code(), DiagnosticCode::BackendOther);
        assert_eq!(diagnostic.stage(), DiagnosticStage::Backend);
        assert_eq!(diagnostic.action(), RecoveryAction::InspectBackendCode);
        assert_eq!(diagnostic.backend_code(), Some(0xdeaf_0042));
    }

    #[test]
    fn numeric_sources_remain_distinct_and_lossless() {
        let diagnostic = BackendError::new(BackendErrorClass::Connect, 0x5732_1234)
            .with_stage(DiagnosticStage::Associate)
            .with_trace(DiagnosticTraceKind::VendorStatus, 8_030)
            .with_trace(DiagnosticTraceKind::IeeeStatus, 30)
            .with_trace(DiagnosticTraceKind::HostapStatus, (-17_i32) as u32)
            .diagnostic();
        let mut json = String::new();
        diagnostic.write_json(&mut json).unwrap();

        assert!(json.contains("\"kind\":\"vendor_status\",\"value\":8030"));
        assert!(json.contains("\"kind\":\"ieee_status\",\"value\":30"));
        assert!(json.contains("\"kind\":\"hostap_status\",\"value\":4294967279"));
    }

    #[test]
    fn json_is_deterministic_and_contains_no_configuration_text() {
        let mut json = String::new();
        Error::Backend(BackendError::new(BackendErrorClass::BackendTimeout, 7))
            .diagnostic()
            .write_json(&mut json)
            .unwrap();

        assert_eq!(
            json,
            "{\"schema\":\"hisi-rf-error/v3\",\"code\":\"backend.timeout\",\"stage\":\"backend\",\"action\":\"retry_operation\",\"backend_code\":7,\"profile_revision\":null,\"trace\":[],\"trace_truncated\":false,\"docs\":\"errors-backend-timeout\"}"
        );
        assert!(!json.contains("ssid"));
        assert!(!json.contains("passphrase"));
        assert!(!json.contains("secret"));
    }

    #[test]
    fn local_errors_do_not_invent_backend_codes() {
        let diagnostic = Error::AlreadyInitialized.diagnostic();

        assert_eq!(diagnostic.backend_code(), None);
        assert_eq!(diagnostic.action(), RecoveryAction::UseExistingController);
        assert_eq!(diagnostic.docs_anchor(), "errors-radio-already-initialized");
    }

    #[test]
    fn backend_context_is_bounded_escaped_and_secret_free() {
        let diagnostic = BackendError::new(BackendErrorClass::Connect, 30)
            .with_stage(DiagnosticStage::Pmf)
            .with_profile_revision("ws63-\"profile")
            .with_trace(DiagnosticTraceKind::IeeeStatus, 30)
            .with_trace(DiagnosticTraceKind::SupplicantContext, 0x445)
            .diagnostic();
        let mut json = String::new();
        diagnostic.write_json(&mut json).unwrap();

        assert_eq!(diagnostic.stage(), DiagnosticStage::Pmf);
        assert_eq!(diagnostic.profile_revision(), Some("ws63-\"profile"));
        assert_eq!(diagnostic.trace().len(), 2);
        assert!(json.contains("ws63-\\\"profile"));
        assert!(json.contains("\"kind\":\"ieee_status\",\"value\":30"));
        assert!(!json.contains("ssid"));
        assert!(!json.contains("passphrase"));
    }

    #[test]
    fn trace_reports_capacity_truncation() {
        let diagnostic = BackendError::new(BackendErrorClass::Other, 9)
            .with_trace(DiagnosticTraceKind::BackendStatus, 1)
            .with_trace(DiagnosticTraceKind::BackendStatus, 2)
            .with_trace(DiagnosticTraceKind::BackendStatus, 3)
            .with_trace(DiagnosticTraceKind::BackendStatus, 4)
            .with_trace(DiagnosticTraceKind::BackendStatus, 5)
            .diagnostic();
        assert_eq!(diagnostic.trace().len(), DIAGNOSTIC_TRACE_CAPACITY);
        assert!(diagnostic.trace().is_truncated());
    }

    #[test]
    fn public_diagnostic_fixture_matrix_preserves_stage_class_and_context() {
        let fixtures = [
            (
                BackendError::new(BackendErrorClass::Connect, 30)
                    .with_stage(DiagnosticStage::Associate)
                    .with_trace(DiagnosticTraceKind::IeeeStatus, 30),
                DiagnosticCode::ConnectionFailed,
                DiagnosticStage::Associate,
                RecoveryAction::InspectNetworkAndRetry,
            ),
            (
                BackendError::new(BackendErrorClass::OperationTimeout, 0x45)
                    .with_stage(DiagnosticStage::Eapol),
                DiagnosticCode::OperationTimeout,
                DiagnosticStage::Eapol,
                RecoveryAction::RetryOperation,
            ),
            (
                BackendError::new(BackendErrorClass::BackendTimeout, 0x46),
                DiagnosticCode::BackendTimeout,
                DiagnosticStage::Backend,
                RecoveryAction::RetryOperation,
            ),
            (
                BackendError::new(BackendErrorClass::Cancelled, 0)
                    .with_stage(DiagnosticStage::ControlPlane),
                DiagnosticCode::OperationCancelled,
                DiagnosticStage::ControlPlane,
                RecoveryAction::RetryOperation,
            ),
            (
                BackendError::new(BackendErrorClass::ResourceUnavailable, 4)
                    .with_stage(DiagnosticStage::Runtime)
                    .with_trace(DiagnosticTraceKind::ResourceRequired, 7)
                    .with_trace(DiagnosticTraceKind::ResourceAvailable, 3),
                DiagnosticCode::ResourceUnavailable,
                DiagnosticStage::Runtime,
                RecoveryAction::ProvideResources,
            ),
            (
                BackendError::new(BackendErrorClass::BackendTimeout, 7)
                    .with_stage(DiagnosticStage::Runtime)
                    .with_trace(DiagnosticTraceKind::RuntimeCode, 7),
                DiagnosticCode::BackendTimeout,
                DiagnosticStage::Runtime,
                RecoveryAction::RetryOperation,
            ),
        ];

        for (error, code, stage, action) in fixtures {
            let diagnostic = error.diagnostic();
            assert_eq!(diagnostic.code(), code);
            assert_eq!(diagnostic.stage(), stage);
            assert_eq!(diagnostic.action(), action);
            assert_eq!(diagnostic.backend_code(), Some(error.code()));
        }

        let resource = fixtures[4].0.diagnostic().trace();
        assert_eq!(
            resource.get(0).map(DiagnosticTraceEntry::kind),
            Some(DiagnosticTraceKind::ResourceRequired)
        );
        assert_eq!(resource.get(0).map(DiagnosticTraceEntry::value), Some(7));
        assert_eq!(
            resource.get(1).map(DiagnosticTraceEntry::kind),
            Some(DiagnosticTraceKind::ResourceAvailable)
        );
        assert_eq!(resource.get(1).map(DiagnosticTraceEntry::value), Some(3));
    }
}