net-lattice-model 0.12.0

The domain model of operating system networking state (routes, interfaces, DNS, ...), with no operating-system dependency.
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
//! Typed, inspectable descriptions of imperative network mutations.
//!
//! These types describe work and its execution report. The model remains
//! operating-system independent; the facade's Stage 0.15 executor consumes a
//! [`MutationPlan`] only after the caller has inspected each operation's
//! preconditions and limits.

use std::time::Duration;

use crate::dns::DnsConfig;
use crate::dns::NewDnsConfig;
use crate::ifaddr::{InterfaceAddress, NewInterfaceAddress};
use crate::route::Route;
use net_lattice_core::Error;

/// One existing imperative network mutation expressed as data.
///
/// Operations deliberately use the same input types accepted by today's
/// provider methods. Stage 0.14 makes their current semantics inspectable;
/// later stages may add more specific intent types where an observed type is
/// still being used as a mutation input.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Mutation {
    /// Adds a route using the route's currently supported defining fields.
    AddRoute(Route),
    /// Removes a route according to the backend's current matching rules.
    RemoveRoute(Route),
    /// Assigns an interface address.
    AddAddress(NewInterfaceAddress),
    /// Removes an observed interface address.
    RemoveAddress(InterfaceAddress),
    /// Replaces the portable resolver configuration.
    SetDnsConfig(NewDnsConfig),
}

/// Observed state captured immediately before a mutation is submitted.
///
/// The snapshot is intentionally scoped to the mutation's domain. `None`
/// means that no matching route or interface address was observed; it is not
/// a promise that the object cannot appear concurrently.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MutationSnapshot {
    /// The matching route, if one was observed.
    Route(Option<Route>),
    /// The matching interface address, if one was observed.
    InterfaceAddress(Option<InterfaceAddress>),
    /// The resolver view observed before replacement.
    Dns(DnsConfig),
}

/// The broad effect an operation requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationKind {
    AddRoute,
    RemoveRoute,
    AddAddress,
    RemoveAddress,
    SetDnsConfig,
}

/// State that must hold for an operation to be meaningful.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationPrecondition {
    /// The target must not already exist.
    Absent,
    /// The target must exist and match the backend's removal rule.
    Present,
    /// The operation replaces configuration regardless of its previous value.
    Any,
}

/// Whether repeating an operation with the same input is expected to succeed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationIdempotency {
    /// Repetition is not a successful no-op: duplicate or absent-object
    /// errors remain observable.
    Strict,
    /// Repetition requests the same replacement state.
    Replace,
}

/// How much completion evidence the current imperative API returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationConfirmation {
    /// The native platform operation acknowledged the request.
    NativeAcknowledgement,
    /// Net Lattice re-read the corresponding observed state after mutation.
    ReadAfterWrite,
}

/// Privilege level required by the current native operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationPrivilege {
    /// The operation changes operating-system network configuration and
    /// requires the platform's elevated networking privilege.
    Elevated,
}

/// Whether an operation can be safely compensated without prior state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationReversibility {
    /// A compensating operation needs a captured prior observed state and is
    /// still subject to concurrent external changes.
    RequiresPriorState,
    /// The current primitive may affect multiple native settings or lose
    /// unmodelled state, so no rollback promise is made.
    NotGuaranteed,
}

/// Static metadata describing one [`Mutation`]'s current contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct MutationSemantics {
    /// The requested effect.
    pub kind: MutationKind,
    /// Required state before execution.
    pub precondition: MutationPrecondition,
    /// Repetition behavior.
    pub idempotency: MutationIdempotency,
    /// Privilege required to submit the operation.
    pub privilege: MutationPrivilege,
    /// How successful completion is confirmed.
    pub confirmation: MutationConfirmation,
    /// Whether rollback can be promised by this primitive.
    pub reversibility: MutationReversibility,
    /// Whether a failed operation may already have changed some state.
    pub may_partially_apply: bool,
}

impl Mutation {
    /// Returns the static contract of this operation in the current API.
    pub const fn semantics(&self) -> MutationSemantics {
        match self {
            Self::AddRoute(_) => MutationSemantics {
                kind: MutationKind::AddRoute,
                precondition: MutationPrecondition::Absent,
                idempotency: MutationIdempotency::Strict,
                privilege: MutationPrivilege::Elevated,
                confirmation: MutationConfirmation::NativeAcknowledgement,
                reversibility: MutationReversibility::RequiresPriorState,
                may_partially_apply: false,
            },
            Self::RemoveRoute(_) => MutationSemantics {
                kind: MutationKind::RemoveRoute,
                precondition: MutationPrecondition::Present,
                idempotency: MutationIdempotency::Strict,
                privilege: MutationPrivilege::Elevated,
                confirmation: MutationConfirmation::NativeAcknowledgement,
                reversibility: MutationReversibility::RequiresPriorState,
                may_partially_apply: false,
            },
            Self::AddAddress(_) => MutationSemantics {
                kind: MutationKind::AddAddress,
                precondition: MutationPrecondition::Absent,
                idempotency: MutationIdempotency::Strict,
                privilege: MutationPrivilege::Elevated,
                confirmation: MutationConfirmation::ReadAfterWrite,
                reversibility: MutationReversibility::RequiresPriorState,
                may_partially_apply: false,
            },
            Self::RemoveAddress(_) => MutationSemantics {
                kind: MutationKind::RemoveAddress,
                precondition: MutationPrecondition::Present,
                idempotency: MutationIdempotency::Strict,
                privilege: MutationPrivilege::Elevated,
                confirmation: MutationConfirmation::NativeAcknowledgement,
                reversibility: MutationReversibility::RequiresPriorState,
                may_partially_apply: false,
            },
            Self::SetDnsConfig(_) => MutationSemantics {
                kind: MutationKind::SetDnsConfig,
                precondition: MutationPrecondition::Any,
                idempotency: MutationIdempotency::Replace,
                privilege: MutationPrivilege::Elevated,
                confirmation: MutationConfirmation::ReadAfterWrite,
                reversibility: MutationReversibility::NotGuaranteed,
                may_partially_apply: true,
            },
        }
    }
}

/// An ordered, inspectable list of mutations.
///
/// Creating a plan has no side effects. Stage 0.15 executes it through a
/// backend and records outcomes, cancellation boundaries, and rollback status
/// in [`MutationPlanReport`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct MutationPlan {
    operations: Vec<Mutation>,
}

/// Static preflight facts derived from a [`MutationPlan`].
///
/// Preflight is deliberately backend-independent: it does not inspect the
/// operating system, capabilities, privileges, or current state. A plan can
/// pass this analysis and still fail when an executor submits it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MutationPreflight {
    prior_state_indices: Vec<usize>,
    partial_application_indices: Vec<usize>,
}

impl MutationPreflight {
    /// Returns plan-local indices whose compensation needs a prior snapshot.
    pub fn prior_state_indices(&self) -> &[usize] {
        &self.prior_state_indices
    }

    /// Returns plan-local indices whose operation may change state before an
    /// error is returned.
    pub fn partial_application_indices(&self) -> &[usize] {
        &self.partial_application_indices
    }

    /// Whether any operation requires a prior observed state for compensation.
    pub fn requires_prior_state(&self) -> bool {
        !self.prior_state_indices.is_empty()
    }

    /// Whether any operation carries a partial-application risk.
    pub fn may_partially_apply(&self) -> bool {
        !self.partial_application_indices.is_empty()
    }
}

/// The result recorded for one operation in an applied mutation plan.
///
/// These values describe an executor's report; constructing a plan or a
/// report never changes operating-system state. `Failed` deliberately keeps
/// whether the operation may have taken effect separate from the error so a
/// caller can decide whether a fresh read is required.
#[derive(Debug)]
#[non_exhaustive]
pub enum MutationOutcome {
    /// The backend acknowledged the operation according to its contract.
    Applied,
    /// The operation returned an error.
    Failed {
        /// Backend error returned by the operation.
        error: Error,
        /// Whether the operation may have changed state before failing.
        may_have_applied: bool,
    },
    /// The executor did not attempt this operation because an earlier
    /// operation failed or execution was cancelled.
    NotAttempted,
}

/// Status of compensation attempted after a plan failure.
#[derive(Debug)]
#[non_exhaustive]
pub enum RollbackStatus {
    /// No operation failed, so rollback was not needed.
    NotNeeded,
    /// A rollback boundary exists, but compensation was not attempted.
    NotAttempted,
    /// Compensation completed for the operations selected by the executor.
    Completed,
    /// Compensation itself failed.
    Failed {
        /// Index of the operation whose compensation failed.
        operation_index: usize,
        /// Error returned by the compensation attempt.
        error: Error,
    },
}

/// Execution phase associated with an operation report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationExecutionPhase {
    /// The plan or operation is being checked before submission.
    Validation,
    /// Prior state is being captured for an operation.
    Snapshot,
    /// The mutation is being submitted to the platform backend.
    Execution,
    /// An explicitly supplied compensator is being run.
    Compensation,
    /// Execution stopped at an operation boundary because cancellation was requested.
    Cancellation,
}

/// Why an operation or plan stopped progressing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MutationStopReason {
    /// Plan or operation preconditions were rejected.
    ValidationFailed,
    /// Prior-state capture failed before submission.
    SnapshotFailed,
    /// The platform backend rejected or could not complete the operation.
    ExecutionFailed,
    /// The caller requested cancellation before this operation was submitted.
    Cancelled,
    /// An explicitly supplied compensator failed.
    CompensationFailed,
}

/// Timing and phase metadata for one plan-local operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct MutationOperationReport {
    /// Last phase reached by this operation.
    pub phase: MutationExecutionPhase,
    /// Time spent in snapshot and native execution callbacks.
    pub duration: Duration,
    /// Why execution stopped at this operation, if it stopped abnormally.
    pub stop_reason: Option<MutationStopReason>,
}

impl MutationOperationReport {
    /// Returns metadata for an operation that was not submitted.
    pub const fn not_attempted() -> Self {
        Self {
            phase: MutationExecutionPhase::Validation,
            duration: Duration::ZERO,
            stop_reason: None,
        }
    }
}

/// Executor report for an ordered [`MutationPlan`].
///
/// A report is intentionally not called a transaction: operations may have
/// been partially applied, and rollback is reported separately rather than
/// implied. The outcome at index `n` corresponds to
/// `MutationPlan::operation(n)`. Callers should re-read affected state
/// whenever an outcome says that application was possible or rollback was not
/// completed.
#[derive(Debug)]
pub struct MutationPlanReport {
    outcomes: Vec<MutationOutcome>,
    rollback: RollbackStatus,
    operation_reports: Vec<MutationOperationReport>,
}

impl MutationPlanReport {
    /// Creates a report for outcomes in the plan's declared order.
    pub fn new(
        outcomes: impl IntoIterator<Item = MutationOutcome>,
        rollback: RollbackStatus,
    ) -> Self {
        let outcomes: Vec<_> = outcomes.into_iter().collect();
        Self {
            operation_reports: vec![MutationOperationReport::not_attempted(); outcomes.len()],
            outcomes,
            rollback,
        }
    }

    /// Creates a report with phase and timing metadata aligned to outcomes.
    pub fn with_operation_reports(
        outcomes: impl IntoIterator<Item = MutationOutcome>,
        rollback: RollbackStatus,
        operation_reports: impl IntoIterator<Item = MutationOperationReport>,
    ) -> Self {
        Self {
            outcomes: outcomes.into_iter().collect(),
            rollback,
            operation_reports: operation_reports.into_iter().collect(),
        }
    }

    /// Returns one outcome for each operation attempted or skipped.
    pub fn outcomes(&self) -> &[MutationOutcome] {
        &self.outcomes
    }

    /// Returns the outcome at a plan-local operation index, if present.
    pub fn outcome(&self, index: usize) -> Option<&MutationOutcome> {
        self.outcomes.get(index)
    }

    /// Returns the number of recorded outcomes.
    pub fn len(&self) -> usize {
        self.outcomes.len()
    }

    /// Whether no outcomes have been recorded.
    pub fn is_empty(&self) -> bool {
        self.outcomes.is_empty()
    }

    /// Returns the rollback status recorded by the executor.
    pub fn rollback(&self) -> &RollbackStatus {
        &self.rollback
    }

    /// Returns phase and timing metadata aligned with [`Self::outcomes`].
    pub fn operation_reports(&self) -> &[MutationOperationReport] {
        &self.operation_reports
    }

    /// Returns phase and timing metadata for one plan-local operation.
    pub fn operation_report(&self, index: usize) -> Option<&MutationOperationReport> {
        self.operation_reports.get(index)
    }

    /// Whether every recorded operation was applied successfully.
    pub fn is_success(&self) -> bool {
        self.outcomes
            .iter()
            .all(|outcome| matches!(outcome, MutationOutcome::Applied))
    }

    /// Number of operations recorded as applied.
    pub fn applied_count(&self) -> usize {
        self.outcomes
            .iter()
            .filter(|outcome| matches!(outcome, MutationOutcome::Applied))
            .count()
    }

    /// Number of operations the executor did not attempt.
    pub fn not_attempted_count(&self) -> usize {
        self.outcomes
            .iter()
            .filter(|outcome| matches!(outcome, MutationOutcome::NotAttempted))
            .count()
    }
}

impl MutationPlan {
    /// Creates an empty plan.
    pub const fn new() -> Self {
        Self {
            operations: Vec::new(),
        }
    }

    /// Creates a plan from operations in execution order.
    pub fn from_operations(operations: impl IntoIterator<Item = Mutation>) -> Self {
        Self {
            operations: operations.into_iter().collect(),
        }
    }

    /// Appends an operation after all existing operations.
    pub fn push(&mut self, operation: Mutation) {
        self.operations.push(operation);
    }

    /// Returns the operations in their declared order.
    pub fn operations(&self) -> &[Mutation] {
        &self.operations
    }

    /// Returns the operation at `index`, if present.
    ///
    /// Executors use this stable plan-local index to associate an operation
    /// with the corresponding entry in [`MutationPlanReport::outcomes`].
    pub fn operation(&self, index: usize) -> Option<&Mutation> {
        self.operations.get(index)
    }

    /// Computes backend-independent execution risks for this plan.
    ///
    /// This method has no side effects and does not validate capabilities,
    /// privileges, or current networking state. Those checks belong to the
    /// executor at submission time.
    pub fn preflight(&self) -> MutationPreflight {
        let mut prior_state_indices = Vec::new();
        let mut partial_application_indices = Vec::new();

        for (index, operation) in self.operations.iter().enumerate() {
            let semantics = operation.semantics();
            if matches!(
                semantics.reversibility,
                MutationReversibility::RequiresPriorState
            ) {
                prior_state_indices.push(index);
            }
            if semantics.may_partially_apply {
                partial_application_indices.push(index);
            }
        }

        MutationPreflight {
            prior_state_indices,
            partial_application_indices,
        }
    }

    /// Whether the plan has no operations.
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty()
    }

    /// Number of operations in the plan.
    pub fn len(&self) -> usize {
        self.operations.len()
    }
}

impl IntoIterator for MutationPlan {
    type Item = Mutation;
    type IntoIter = std::vec::IntoIter<Mutation>;

    fn into_iter(self) -> Self::IntoIter {
        self.operations.into_iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{IpAddress, Network};
    use net_lattice_ip::{Ipv4Address, Ipv4Network, Ipv4PrefixLength};

    fn network() -> Network {
        Network::from(Ipv4Network::new(
            Ipv4Address::new(192, 0, 2, 0),
            Ipv4PrefixLength::new(24).expect("valid prefix"),
        ))
    }

    #[test]
    fn dns_replacement_exposes_partial_application_risk() {
        let operation = Mutation::SetDnsConfig(NewDnsConfig::with(
            vec![IpAddress::from(Ipv4Address::new(1, 1, 1, 1))],
            Vec::new(),
        ));
        assert_eq!(
            operation.semantics().precondition,
            MutationPrecondition::Any
        );
        assert_eq!(
            operation.semantics().idempotency,
            MutationIdempotency::Replace
        );
        assert!(operation.semantics().may_partially_apply);
        assert_eq!(
            operation.semantics().confirmation,
            MutationConfirmation::ReadAfterWrite
        );
        assert_eq!(
            operation.semantics().reversibility,
            MutationReversibility::NotGuaranteed
        );
    }

    #[test]
    fn address_addition_has_an_observed_readback_contract() {
        let operation = Mutation::AddAddress(NewInterfaceAddress::new(
            crate::interface::InterfaceId::new(2),
            network(),
        ));
        assert_eq!(
            operation.semantics().confirmation,
            MutationConfirmation::ReadAfterWrite
        );
        assert_eq!(
            operation.semantics().precondition,
            MutationPrecondition::Absent
        );
        assert_eq!(
            operation.semantics().reversibility,
            MutationReversibility::RequiresPriorState
        );
        assert!(!operation.semantics().may_partially_apply);
    }

    #[test]
    fn plan_keeps_declared_order_without_executing_operations() {
        let first = Mutation::AddRoute(Route::new(crate::route::RouteId::new(1), network()));
        let second = Mutation::RemoveRoute(Route::new(crate::route::RouteId::new(2), network()));
        let plan = MutationPlan::from_operations([first.clone(), second.clone()]);
        assert_eq!(plan.operations(), [first, second]);
        assert!(plan.operation(0).is_some());
        assert!(plan.operation(2).is_none());
        assert_eq!(plan.len(), 2);
        assert!(!plan.is_empty());
    }

    #[test]
    fn route_operations_expose_strict_native_acknowledgement_contracts() {
        let route = Route::new(crate::route::RouteId::new(1), network());

        let added = Mutation::AddRoute(route.clone()).semantics();
        assert_eq!(added.kind, MutationKind::AddRoute);
        assert_eq!(added.precondition, MutationPrecondition::Absent);
        assert_eq!(added.idempotency, MutationIdempotency::Strict);
        assert_eq!(added.privilege, MutationPrivilege::Elevated);
        assert_eq!(
            added.confirmation,
            MutationConfirmation::NativeAcknowledgement
        );
        assert_eq!(
            added.reversibility,
            MutationReversibility::RequiresPriorState
        );
        assert!(!added.may_partially_apply);

        let removed = Mutation::RemoveRoute(route).semantics();
        assert_eq!(removed.kind, MutationKind::RemoveRoute);
        assert_eq!(removed.precondition, MutationPrecondition::Present);
        assert_eq!(removed.idempotency, MutationIdempotency::Strict);
        assert_eq!(removed.privilege, MutationPrivilege::Elevated);
        assert_eq!(
            removed.confirmation,
            MutationConfirmation::NativeAcknowledgement
        );
        assert_eq!(
            removed.reversibility,
            MutationReversibility::RequiresPriorState
        );
        assert!(!removed.may_partially_apply);
    }

    #[test]
    fn address_removal_exposes_its_observed_record_contract() {
        let address =
            InterfaceAddress::new(crate::ifaddr::InterfaceAddressId::new(1), 1, network());
        let semantics = Mutation::RemoveAddress(address).semantics();

        assert_eq!(semantics.kind, MutationKind::RemoveAddress);
        assert_eq!(semantics.precondition, MutationPrecondition::Present);
        assert_eq!(semantics.idempotency, MutationIdempotency::Strict);
        assert_eq!(semantics.privilege, MutationPrivilege::Elevated);
        assert_eq!(
            semantics.confirmation,
            MutationConfirmation::NativeAcknowledgement
        );
        assert_eq!(
            semantics.reversibility,
            MutationReversibility::RequiresPriorState
        );
        assert!(!semantics.may_partially_apply);
    }

    #[test]
    fn empty_plan_can_be_built_appended_and_consumed() {
        let mut plan = MutationPlan::new();
        assert!(plan.is_empty());
        assert_eq!(plan.len(), 0);

        let operation = Mutation::AddRoute(Route::new(crate::route::RouteId::new(1), network()));
        plan.push(operation.clone());
        assert_eq!(plan.operations(), std::slice::from_ref(&operation));
        assert_eq!(plan.into_iter().collect::<Vec<_>>(), vec![operation]);
    }

    #[test]
    fn plan_report_preserves_partial_failure_and_rollback_boundary() {
        let report = MutationPlanReport::new(
            [
                MutationOutcome::Applied,
                MutationOutcome::Failed {
                    error: Error::PermissionDenied,
                    may_have_applied: true,
                },
                MutationOutcome::NotAttempted,
            ],
            RollbackStatus::NotAttempted,
        );

        assert!(!report.is_success());
        assert_eq!(report.applied_count(), 1);
        assert_eq!(report.not_attempted_count(), 1);
        assert_eq!(report.len(), 3);
        assert_eq!(report.operation_reports().len(), 3);
        assert!(report.operation_report(2).is_some());
        assert!(!report.is_empty());
        assert!(report.outcome(3).is_none());
        assert!(matches!(report.rollback(), RollbackStatus::NotAttempted));
        assert!(matches!(
            &report.outcomes()[1],
            MutationOutcome::Failed {
                may_have_applied: true,
                ..
            }
        ));
    }

    #[test]
    fn preflight_identifies_snapshot_and_partial_application_risks() {
        let plan = MutationPlan::from_operations([
            Mutation::AddRoute(Route::new(crate::route::RouteId::new(1), network())),
            Mutation::SetDnsConfig(NewDnsConfig::new()),
        ]);
        let preflight = plan.preflight();

        assert_eq!(preflight.prior_state_indices(), &[0]);
        assert_eq!(preflight.partial_application_indices(), &[1]);
        assert!(preflight.requires_prior_state());
        assert!(preflight.may_partially_apply());
    }
}