euv-core 0.46.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// Builder and accessor methods for `BusinessCommand`.
impl BusinessCommand {
    /// Returns the optional expected optimistic concurrency revision.
    ///
    /// # Returns
    ///
    /// - `Option<u64>` - Expected entity revision if set.
    #[must_use]
    pub fn expected_revision_value(&self) -> Option<u64> {
        let Self {
            expected_revision, ..
        } = *self;
        expected_revision
    }

    /// Attaches an optimistic concurrency expected revision to this command.
    ///
    /// # Arguments
    ///
    /// - `u64` - Expected live entity revision.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated command.
    #[must_use]
    pub fn with_expected_revision(mut self, revision: u64) -> Self {
        self.set_expected_revision(Some(revision));
        self
    }

    /// Attaches a caller-supplied idempotency key for deduplication across retries.
    ///
    /// # Arguments
    ///
    /// - `String` - Stable idempotency key.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated command.
    #[must_use]
    pub fn with_idempotency_key(mut self, key: String) -> Self {
        self.set_idempotency_key(key);
        self
    }

    /// Records the release generation active on the originating route when this command was issued.
    ///
    /// # Arguments
    ///
    /// - `u64` - Originating release generation identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated command.
    #[must_use]
    pub fn with_origin_generation(mut self, generation: u64) -> Self {
        self.set_origin_generation(generation);
        self
    }
}

/// Accessor helper for `InFlightOperation`.
impl InFlightOperation {
    /// Returns the optional expected revision captured when this operation started.
    ///
    /// # Returns
    ///
    /// - `Option<u64>` - Expected revision if set.
    #[must_use]
    pub fn expected_revision_value(&self) -> Option<u64> {
        let Self {
            expected_revision, ..
        } = *self;
        expected_revision
    }
}

/// Default empty `BusinessStateStore`.
impl Default for BusinessStateStore {
    /// Creates a `BusinessStateStore` with `DEFAULT_STATE_DELTA_HISTORY_CAP`.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty authoritative business state store.
    fn default() -> Self {
        Self::new(DEFAULT_STATE_DELTA_HISTORY_CAP)
    }
}

/// Authoritative business state orchestration on `BusinessStateStore`.
impl BusinessStateStore {
    /// Creates a new `BusinessStateStore` retaining up to `delta_cap` historical deltas per entity.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum per-entity delta history length.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized authoritative store.
    #[must_use]
    pub fn new(delta_cap: usize) -> Self {
        let inner: BusinessStateStoreInner = BusinessStateStoreInner {
            delta_cap: delta_cap.max(1),
            next_op_id: 1,
            next_sub_id: 1,
            global_revision: 0,
            entities: BTreeMap::new(),
            idempotency_cache: HashMap::new(),
            in_flight: BTreeMap::new(),
            subscriptions: BTreeMap::new(),
        };
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }

    /// Seeds or initializes an authoritative entity at revision `1` if absent and returns its revision.
    ///
    /// # Arguments
    ///
    /// - `&str` - Entity identifier.
    /// - `Value` - Initial authoritative state.
    ///
    /// # Returns
    ///
    /// - `Result<u64, DynamicReleaseError>` - Entity revision after seeding.
    pub fn seed_entity(&self, entity_id: &str, state: Value) -> Result<u64, DynamicReleaseError> {
        let trimmed: &str = entity_id.trim();
        if trimmed.is_empty() {
            return Err(DynamicReleaseError::StorageError(
                ERR_EMPTY_ENTITY_ID.to_string(),
            ));
        }
        let Self { inner } = self;
        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
            .lock()
            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
        if let Some(existing) = guard.entities.get(trimmed) {
            return Ok(existing.revision);
        }
        guard.global_revision = guard.global_revision.saturating_add(1);
        let record: EntityStateRecord = EntityStateRecord {
            revision: 1,
            state,
            deltas: VecDeque::with_capacity(guard.delta_cap.min(32)),
        };
        let _: Option<EntityStateRecord> = guard.entities.insert(trimmed.to_string(), record);
        Ok(1)
    }

    /// Reads the current authoritative `(revision, state)` pair for `entity_id`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Entity identifier.
    ///
    /// # Returns
    ///
    /// - `Option<(u64, Value)>` - Revision and cloned authoritative state if present.
    #[must_use]
    pub fn read_entity(&self, entity_id: &str) -> Option<(u64, Value)> {
        let Self { inner } = self;
        let guard: MutexGuard<'_, BusinessStateStoreInner> = inner.lock().ok()?;
        guard
            .entities
            .get(entity_id)
            .map(|rec: &EntityStateRecord| (rec.revision, rec.state.clone()))
    }

    /// Returns the monotonic global store revision across all entities.
    ///
    /// # Returns
    ///
    /// - `u64` - Global authoritative revision number.
    #[must_use]
    pub fn global_revision(&self) -> u64 {
        let Self { inner } = self;
        inner
            .lock()
            .map(|g: MutexGuard<'_, BusinessStateStoreInner>| g.global_revision)
            .unwrap_or(0)
    }

    /// Captures a read-only snapshot of all entities and the global revision `R`.
    ///
    /// # Returns
    ///
    /// - `(u64, BTreeMap<String, (u64, Value)>)` - Global revision `R` paired with per-entity snapshots.
    #[must_use]
    pub fn capture_entity_snapshots(&self) -> (u64, BTreeMap<String, (u64, Value)>) {
        let Self { inner } = self;
        let Ok(guard) = inner.lock() else {
            return (0, BTreeMap::new());
        };
        let mut snaps: BTreeMap<String, (u64, Value)> = BTreeMap::new();
        for (entity_id, rec) in guard.entities.iter() {
            let _: Option<(u64, Value)> =
                snaps.insert(entity_id.clone(), (rec.revision, rec.state.clone()));
        }
        (guard.global_revision, snaps)
    }

    /// Registers a field-filtered subscriber for `entity_id` owned by `generation_id`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Target entity identifier.
    /// - `u64` - Owning release generation identifier.
    /// - `Vec<String>` - Subset of watched fields (empty watches all changes).
    ///
    /// # Returns
    ///
    /// - `Result<u64, DynamicReleaseError>` - Assigned subscription identifier.
    pub fn subscribe_entity(
        &self,
        entity_id: &str,
        generation_id: u64,
        watched_fields: Vec<String>,
    ) -> Result<u64, DynamicReleaseError> {
        let Self { inner } = self;
        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
            .lock()
            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
        let sub_id: u64 = guard.next_sub_id;
        guard.next_sub_id = guard.next_sub_id.saturating_add(1);
        let mut sub: StateSubscription =
            StateSubscription::new(sub_id, entity_id.to_string(), generation_id, watched_fields);
        sub.set_active(true);
        let _: Option<StateSubscription> = guard.subscriptions.insert(sub_id, sub);
        Ok(sub_id)
    }

    /// Cancels all subscriptions belonging to `generation_id` so destroyed instances never receive callbacks.
    ///
    /// # Arguments
    ///
    /// - `u64` - Retired release generation identifier.
    pub fn cancel_generation_subscriptions(&self, generation_id: u64) {
        let Self { inner } = self;
        if let Ok(mut guard) = inner.lock() {
            for sub in guard.subscriptions.values_mut() {
                if sub.get_generation_id() == generation_id {
                    sub.set_active(false);
                }
            }
        }
    }

    /// Returns the list of revisions delivered to subscription `subscription_id`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Subscription identifier.
    ///
    /// # Returns
    ///
    /// - `Vec<u64>` - Delivered entity revision numbers.
    #[must_use]
    pub fn delivered_revisions(&self, subscription_id: u64) -> Vec<u64> {
        let Self { inner } = self;
        inner
            .lock()
            .ok()
            .and_then(|g: MutexGuard<'_, BusinessStateStoreInner>| {
                g.subscriptions
                    .get(&subscription_id)
                    .map(|s: &StateSubscription| s.get_delivered_revisions().clone())
            })
            .unwrap_or_default()
    }

    /// Accepts an asynchronous business command into host-owned in-flight tracking, returning its `OperationId`.
    ///
    /// # Arguments
    ///
    /// - `BusinessCommand` - Command submitted by a page or dynamic component.
    ///
    /// # Returns
    ///
    /// - `Result<CommandOutcome, DynamicReleaseError>` - `Pending` or deduplicated `Committed` / `Rejected*` outcome.
    pub fn begin_operation(
        &self,
        command: BusinessCommand,
    ) -> Result<CommandOutcome, DynamicReleaseError> {
        let entity_id: String = command.get_entity_id().trim().to_string();
        if entity_id.is_empty() {
            return Err(DynamicReleaseError::StorageError(
                ERR_EMPTY_ENTITY_ID.to_string(),
            ));
        }
        let Self { inner } = self;
        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
            .lock()
            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
        let idem: String = command.get_idempotency_key().clone();
        if !idem.is_empty()
            && let Some(cached) = guard
                .idempotency_cache
                .get(&(entity_id.clone(), idem.clone()))
        {
            if let CommandOutcome::Committed {
                operation_id,
                entity_id: eid,
                revision,
                state,
                ..
            } = cached
            {
                return Ok(CommandOutcome::Committed {
                    operation_id: *operation_id,
                    entity_id: eid.clone(),
                    revision: *revision,
                    state: state.clone(),
                    deduplicated: true,
                });
            }
            return Ok(cached.clone());
        }
        let op_id: OperationId = OperationId::new(guard.next_op_id);
        guard.next_op_id = guard.next_op_id.saturating_add(1);
        let live_rev: u64 = guard
            .entities
            .get(&entity_id)
            .map(|rec: &EntityStateRecord| rec.revision)
            .unwrap_or(0);
        if let Some(expected) = command.expected_revision_value()
            && expected != live_rev
        {
            return Ok(CommandOutcome::RejectedRevisionConflict {
                operation_id: op_id,
                expected,
                actual: live_rev,
            });
        }
        let op: InFlightOperation = InFlightOperation::new(
            op_id,
            entity_id.clone(),
            command.get_command_name().clone(),
            idem,
            command.get_origin_generation(),
            command.expected_revision_value(),
            false,
        );
        let _: Option<InFlightOperation> = guard.in_flight.insert(op_id, op);
        Ok(CommandOutcome::Pending {
            operation_id: op_id,
            entity_id,
            submitted_revision: live_rev,
        })
    }

    /// Completes a previously accepted host-owned in-flight operation regardless of component hot-swaps.
    ///
    /// # Arguments
    ///
    /// - `OperationId` - Host-assigned operation identifier returned by `begin_operation`.
    /// - `Value` - Authoritative post-operation entity state.
    /// - `Vec<String>` - Field names mutated by this completion.
    ///
    /// # Returns
    ///
    /// - `Result<CommandOutcome, DynamicReleaseError>` - Committed outcome or conflict error.
    pub fn complete_operation(
        &self,
        operation_id: OperationId,
        next_state: Value,
        changed_fields: Vec<String>,
    ) -> Result<CommandOutcome, DynamicReleaseError> {
        let Self { inner } = self;
        let mut guard: MutexGuard<'_, BusinessStateStoreInner> = inner
            .lock()
            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
        let Some(mut op) = guard.in_flight.remove(&operation_id) else {
            return Err(DynamicReleaseError::StorageError(format!(
                "{ERR_UNKNOWN_OPERATION}: {}",
                operation_id.get_raw()
            )));
        };
        let entity_id: String = op.get_entity_id().clone();
        let live_rev: u64 = guard
            .entities
            .get(&entity_id)
            .map(|rec: &EntityStateRecord| rec.revision)
            .unwrap_or(0);
        if let Some(expected) = op.expected_revision_value()
            && expected != live_rev
        {
            return Ok(CommandOutcome::RejectedRevisionConflict {
                operation_id,
                expected,
                actual: live_rev,
            });
        }
        let next_rev: u64 = live_rev.saturating_add(1);
        guard.global_revision = guard.global_revision.saturating_add(1);
        let delta_cap: usize = guard.delta_cap;
        let delta: BusinessStateDelta = BusinessStateDelta::new(
            entity_id.clone(),
            next_rev,
            operation_id,
            changed_fields.clone(),
            next_state.clone(),
        );
        let entry: &mut EntityStateRecord =
            guard
                .entities
                .entry(entity_id.clone())
                .or_insert_with(|| EntityStateRecord {
                    revision: 0,
                    state: Value::Null,
                    deltas: VecDeque::with_capacity(delta_cap.min(32)),
                });
        entry.revision = next_rev;
        entry.state = next_state.clone();
        if entry.deltas.len() >= delta_cap {
            let _: Option<BusinessStateDelta> = entry.deltas.pop_front();
        }
        entry.deltas.push_back(delta);
        for sub in guard.subscriptions.values_mut() {
            if !sub.get_active() || sub.get_entity_id() != &entity_id {
                continue;
            }
            let matches_field: bool = sub.get_watched_fields().is_empty()
                || changed_fields.is_empty()
                || sub
                    .get_watched_fields()
                    .iter()
                    .any(|f: &String| changed_fields.contains(f));
            if matches_field {
                sub.get_mut_delivered_revisions().push(next_rev);
            }
        }
        op.set_completed(true);
        let outcome: CommandOutcome = CommandOutcome::Committed {
            operation_id,
            entity_id: entity_id.clone(),
            revision: next_rev,
            state: next_state,
            deduplicated: false,
        };
        let idem: String = op.get_idempotency_key().clone();
        if !idem.is_empty() {
            let _: Option<CommandOutcome> = guard
                .idempotency_cache
                .insert((entity_id, idem), outcome.clone());
        }
        Ok(outcome)
    }

    /// Synchronously validates, commits, and deduplicates a typed command in a single atomic host step.
    ///
    /// # Arguments
    ///
    /// - `BusinessCommand` - Typed mutation command.
    /// - `Value` - Resulting authoritative entity state.
    /// - `Vec<String>` - Mutated field names.
    ///
    /// # Returns
    ///
    /// - `Result<CommandOutcome, DynamicReleaseError>` - Committed or rejected outcome.
    pub fn commit_command(
        &self,
        command: BusinessCommand,
        next_state: Value,
        changed_fields: Vec<String>,
    ) -> Result<CommandOutcome, DynamicReleaseError> {
        match self.begin_operation(command)? {
            CommandOutcome::Pending { operation_id, .. } => {
                self.complete_operation(operation_id, next_state, changed_fields)
            }
            terminal => Ok(terminal),
        }
    }

    /// Returns all authoritative deltas strictly newer than `base_revision` for `entity_id`, or `StateCatchUpConflict` if history wrapped.
    ///
    /// # Arguments
    ///
    /// - `&str` - Entity identifier.
    /// - `u64` - Snapshot baseline revision `R`.
    ///
    /// # Returns
    ///
    /// - `Result<Vec<BusinessStateDelta>, DynamicReleaseError>` - Ordered catch-up deltas from `R+1` to `R+n`.
    pub fn deltas_since(
        &self,
        entity_id: &str,
        base_revision: u64,
    ) -> Result<Vec<BusinessStateDelta>, DynamicReleaseError> {
        let Self { inner } = self;
        let guard: MutexGuard<'_, BusinessStateStoreInner> = inner
            .lock()
            .map_err(|_| DynamicReleaseError::StorageError(ERR_STATE_STORE_POISONED.to_string()))?;
        let Some(rec) = guard.entities.get(entity_id) else {
            return Ok(Vec::new());
        };
        if base_revision == rec.revision {
            return Ok(Vec::new());
        }
        if base_revision > rec.revision {
            return Err(DynamicReleaseError::StateCatchUpConflict {
                base_revision,
                live_revision: rec.revision,
            });
        }
        let earliest_delta_rev: u64 = rec
            .deltas
            .front()
            .map(BusinessStateDelta::get_revision)
            .unwrap_or(u64::MAX);
        if earliest_delta_rev > base_revision.saturating_add(1) {
            return Err(DynamicReleaseError::StateCatchUpConflict {
                base_revision,
                live_revision: rec.revision,
            });
        }
        let out: Vec<BusinessStateDelta> = rec
            .deltas
            .iter()
            .filter(|d: &&BusinessStateDelta| d.get_revision() > base_revision)
            .cloned()
            .collect();
        Ok(out)
    }

    /// Returns the number of currently active host-owned in-flight operations.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of pending in-flight operations.
    #[must_use]
    pub fn active_in_flight_count(&self) -> usize {
        let Self { inner } = self;
        inner
            .lock()
            .map(|g: MutexGuard<'_, BusinessStateStoreInner>| g.in_flight.len())
            .unwrap_or(0)
    }
}

/// Construction, formatting, and parsing helpers for `StableAddress`.
impl StableAddress {
    /// Creates a new `StableAddress` from route instance, ancestor business keys, slot key, and optional child key.
    ///
    /// # Arguments
    ///
    /// - `String` - Route instance key (e.g. `"A#tab-1"`).
    /// - `Vec<String>` - Ancestor logical business keys.
    /// - `String` - Logical slot identifier.
    /// - `Option<String>` - Optional child business ID key.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed stable address.
    #[must_use]
    pub fn new(
        route_instance: String,
        ancestor_keys: Vec<String>,
        slot_key: String,
        child_key: Option<String>,
    ) -> Self {
        Self {
            route_instance,
            ancestor_keys,
            slot_key,
            child_key,
        }
    }

    /// Returns the optional child business key.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Child key if present.
    #[must_use]
    pub fn child_key_str(&self) -> Option<&str> {
        let Self { child_key, .. } = self;
        child_key.as_deref()
    }

    /// Formats this stable address as a canonical slash-delimited string (`route#tab/entity/slot[/child]`).
    ///
    /// # Returns
    ///
    /// - `String` - Canonical stable address key.
    #[must_use]
    pub fn canonical(&self) -> String {
        let mut parts: Vec<&str> = Vec::with_capacity(self.get_ancestor_keys().len() + 3);
        parts.push(self.get_route_instance().as_str());
        for ancestor in self.get_ancestor_keys().iter() {
            parts.push(ancestor.as_str());
        }
        parts.push(self.get_slot_key().as_str());
        if let Some(child) = self.child_key_str() {
            parts.push(child);
        }
        parts.join("/")
    }

    /// Parses a canonical slash-delimited `StableAddress` string (`route#tab/[ancestors.../]slot`).
    ///
    /// # Arguments
    ///
    /// - `&str` - Canonical address string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, DynamicReleaseError>` - Parsed stable address or error.
    pub fn parse(raw: &str) -> Result<Self, DynamicReleaseError> {
        let segments: Vec<&str> = raw
            .split(STABLE_ADDR_SEP)
            .filter(|s: &&str| !s.is_empty())
            .collect();
        if segments.len() < 2 {
            return Err(DynamicReleaseError::StateMigrationFailed(
                ERR_INVALID_STABLE_ADDRESS.to_string(),
            ));
        }
        let route_instance: String = segments[0].to_string();
        let slot_key: String = segments[segments.len() - 1].to_string();
        let ancestor_keys: Vec<String> = segments[1..segments.len() - 1]
            .iter()
            .map(|s: &&str| (*s).to_string())
            .collect();
        Ok(Self {
            route_instance,
            ancestor_keys,
            slot_key,
            child_key: None,
        })
    }
}

/// Accessor and builder helpers for `ComponentUiStateSnapshot`.
impl ComponentUiStateSnapshot {
    /// Returns the optional scroll anchor business key.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Scroll anchor key if set.
    #[must_use]
    pub fn scroll_anchor(&self) -> Option<&str> {
        let Self {
            scroll_anchor_key, ..
        } = self;
        scroll_anchor_key.as_deref()
    }

    /// Returns the optional focused logical node key.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Focused node key if set.
    #[must_use]
    pub fn focused_node(&self) -> Option<&str> {
        let Self {
            focused_node_key, ..
        } = self;
        focused_node_key.as_deref()
    }

    /// Sets the scroll anchor business key and pixel offset on this snapshot.
    ///
    /// # Arguments
    ///
    /// - `String` - Business anchor key.
    /// - `f32` - Logical scroll Y offset.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated snapshot.
    #[must_use]
    pub fn with_scroll(mut self, anchor_key: String, offset_y: f32) -> Self {
        self.set_scroll_anchor_key(Some(anchor_key))
            .set_scroll_offset_y(offset_y);
        self
    }

    /// Sets the focused logical node key on this snapshot.
    ///
    /// # Arguments
    ///
    /// - `String` - Focused node key.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated snapshot.
    #[must_use]
    pub fn with_focus(mut self, node_key: String) -> Self {
        self.set_focused_node_key(Some(node_key));
        self
    }

    /// Inserts a form draft field into this snapshot.
    ///
    /// # Arguments
    ///
    /// - `String` - Draft field name.
    /// - `String` - Draft field value.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated snapshot.
    #[must_use]
    pub fn with_draft_field(mut self, key: String, value: String) -> Self {
        let _: Option<String> = self.get_mut_form_draft().insert(key, value);
        self
    }
}

/// Configuration helpers for `DefaultStateMigrator`.
impl DefaultStateMigrator {
    /// Registers an explicit field rename mapping between `from_schema` and `to_schema`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Source schema version.
    /// - `u32` - Target schema version.
    /// - `String` - Old form draft field name.
    /// - `String` - New form draft field name.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable migrator reference for chaining.
    pub fn add_field_rename(
        &mut self,
        from_schema: u32,
        to_schema: u32,
        old_key: String,
        new_key: String,
    ) -> &mut Self {
        let _: Option<String> = self
            .get_mut_field_renames()
            .entry((from_schema, to_schema))
            .or_default()
            .insert(old_key, new_key);
        self
    }

    /// Registers a default field added when upgrading from `from_schema` to `to_schema`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Source schema version.
    /// - `u32` - Target schema version.
    /// - `String` - Added field name.
    /// - `String` - Default value for the newly added field.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable migrator reference for chaining.
    pub fn add_default_field(
        &mut self,
        from_schema: u32,
        to_schema: u32,
        field_key: String,
        default_val: String,
    ) -> &mut Self {
        let _: Option<String> = self
            .get_mut_default_additions()
            .entry((from_schema, to_schema))
            .or_default()
            .insert(field_key, default_val);
        self
    }
}

/// Pure background migration logic for `DefaultStateMigrator`.
impl StateMigrator for DefaultStateMigrator {
    /// Purely transforms `snapshot` from `from_schema` to `to_schema`, refusing to drop unmapped user drafts.
    ///
    /// # Arguments
    ///
    /// - `u32` - Source schema version.
    /// - `u32` - Target schema version.
    /// - `&ComponentUiStateSnapshot` - Source immutable UI state snapshot.
    ///
    /// # Returns
    ///
    /// - `Result<ComponentUiStateSnapshot, DynamicReleaseError>` - Migrated state snapshot or failure.
    fn migrate(
        &self,
        from_schema: u32,
        to_schema: u32,
        snapshot: &ComponentUiStateSnapshot,
    ) -> Result<ComponentUiStateSnapshot, DynamicReleaseError> {
        if from_schema == to_schema {
            return Ok(snapshot.clone());
        }
        let renames: Option<&BTreeMap<String, String>> =
            self.get_field_renames().get(&(from_schema, to_schema));
        let additions: Option<&BTreeMap<String, String>> =
            self.get_default_additions().get(&(from_schema, to_schema));
        if renames.is_none()
            && additions.is_none()
            && !snapshot.get_form_draft().is_empty()
            && to_schema > from_schema.saturating_add(1)
        {
            return Err(DynamicReleaseError::StateMigrationFailed(format!(
                "{ERR_INCOMPATIBLE_SCHEMA_DRAFT}: v{from_schema} -> v{to_schema}"
            )));
        }
        let mut next: ComponentUiStateSnapshot = snapshot.clone();
        next.set_schema_version(to_schema);
        if let Some(rename_map) = renames {
            let mut remapped: BTreeMap<String, String> = BTreeMap::new();
            for (k, v) in snapshot.get_form_draft().iter() {
                let target_k: String = rename_map.get(k).cloned().unwrap_or_else(|| k.clone());
                let _: Option<String> = remapped.insert(target_k, v.clone());
            }
            next.set_form_draft(remapped);
        }
        if let Some(add_map) = additions {
            for (k, v) in add_map.iter() {
                if !next.get_form_draft().contains_key(k) {
                    let _: Option<String> = next.get_mut_form_draft().insert(k.clone(), v.clone());
                }
            }
        }
        Ok(next)
    }
}

/// Safe default `InteractionSafePoint` representing an idle frame boundary with ample budget.
impl Default for InteractionSafePoint {
    /// Creates an idle `InteractionSafePoint` with full frame budget.
    ///
    /// # Returns
    ///
    /// - `Self` - Safe frame boundary descriptor.
    fn default() -> Self {
        Self {
            active_gesture: false,
            ime_composing: false,
            active_transition: false,
            blocking_in_flight_tx: 0,
            frame_budget_remaining_us: 8_000,
        }
    }
}

/// Frame-boundary safety checks on `InteractionSafePoint`.
impl InteractionSafePoint {
    /// Returns `true` when swapping the UI subtree will not disrupt gestures, IME, transitions, blocking tx, or frame budget.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether atomic hot-swap is safe at this boundary.
    #[must_use]
    pub fn is_safe_to_swap(&self) -> bool {
        self.defer_reason().is_none()
    }

    /// Returns the human-readable reason why a swap must be deferred, or `None` if safe.
    ///
    /// # Returns
    ///
    /// - `Option<&'static str>` - Deferral reason if unsafe.
    #[must_use]
    pub fn defer_reason(&self) -> Option<&'static str> {
        if self.get_active_gesture() {
            return Some(DEFER_REASON_GESTURE);
        }
        if self.get_ime_composing() {
            return Some(DEFER_REASON_IME);
        }
        if self.get_active_transition() {
            return Some(DEFER_REASON_TRANSITION);
        }
        if self.get_blocking_in_flight_tx() > 0 {
            return Some(DEFER_REASON_TX);
        }
        if self.get_frame_budget_remaining_us() < DEFAULT_SWAP_MIN_FRAME_BUDGET_US {
            return Some(DEFER_REASON_BUDGET);
        }
        None
    }
}