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
use super::*;

/// No-op `Lifecycle` implementation allowing raw `NodeId` handles to participate seamlessly in `Component` APIs.
impl Lifecycle for NodeId {}

/// Zero-overhead `Component` implementation returning an already-mounted `NodeId` unchanged.
impl Component for NodeId {
    /// Returns this `NodeId` handle unchanged.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Already-mounted scene node handle.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Same scene node handle.
    fn render(&self) -> NodeId {
        *self
    }

    /// Returns this `NodeId` directly without heap allocation or duplicate lifecycle attachment.
    ///
    /// # Arguments
    ///
    /// - `Self` - Already-mounted scene node handle.
    ///
    /// # Returns
    ///
    /// - `NodeId` - Same scene node handle.
    fn mount(self) -> NodeId {
        self
    }
}

/// Default bounded cold-page retention policy (`4` frozen pages, `32 MiB` retained ceiling).
impl Default for PageBudgetPolicy {
    /// Creates the default bounded cold-page retention policy.
    ///
    /// # Returns
    ///
    /// - `Self` - Default page budget policy.
    fn default() -> Self {
        Self {
            max_frozen_pages: PAGE_DEFAULT_MAX_FROZEN,
            max_retained_bytes: PAGE_DEFAULT_MAX_RETAINED_BYTES,
            max_snapshot_bytes: PAGE_DEFAULT_MAX_SNAPSHOT_BYTES,
        }
    }
}

/// Builder helpers for versioned `PageSnapshot`.
impl PageSnapshot {
    /// Creates a schema-versioned `PageSnapshot` capturing scroll, focus, and optional unsaved draft state.
    ///
    /// # Arguments
    ///
    /// - `String` - Canonical route identifier.
    /// - `u64` - Source page generation.
    /// - `Point` - Saved primary scroll offset.
    /// - `Option<String>` - Optional focused element key.
    /// - `String` - Serialized draft payload (empty when no draft).
    /// - `(bool, bool)` - Tuple `(has_unsaved_draft, draft_persisted)` tracking unsaved draft protection status.
    /// - `u64` - Host state revision at capture time.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready versioned snapshot.
    #[must_use]
    pub fn capture(
        route_key: String,
        generation: u64,
        scroll_offset: Point,
        focus_key: Option<String>,
        draft_payload: String,
        unsaved_flags: (bool, bool),
        host_state_revision: u64,
    ) -> Self {
        let (has_unsaved_draft, draft_persisted): (bool, bool) = unsaved_flags;
        let (has_focus_key, focus_str): (bool, String) = match focus_key {
            Some(k) if !k.is_empty() => (true, k),
            _ => (false, String::new()),
        };
        let estimated_bytes: usize = 64_usize
            .saturating_add(route_key.len())
            .saturating_add(focus_str.len())
            .saturating_add(draft_payload.len());
        Self {
            schema_version: PAGE_SNAPSHOT_SCHEMA_VERSION,
            route_key,
            generation,
            scroll_offset,
            focus_key: focus_str,
            has_focus_key,
            draft_payload,
            has_unsaved_draft,
            draft_persisted,
            host_state_revision,
            estimated_bytes,
        }
    }
}

/// Default empty `PageLifecycleController` initialized with `PageBudgetPolicy::default()`.
impl Default for PageLifecycleController {
    /// Creates a new `PageLifecycleController` with default cold-page budgets.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized page lifecycle controller.
    fn default() -> Self {
        Self::with_budget(PageBudgetPolicy::default())
    }
}

/// Deterministic `Freeze`, `Resume`, `Evict`, `Destroy`, generation-guard, and boundary-event operations for `PageLifecycleController`.
impl PageLifecycleController {
    /// Creates a `PageLifecycleController` configured with explicit `budget` limits.
    ///
    /// # Arguments
    ///
    /// - `PageBudgetPolicy` - Cold-page count and retained-byte retention policy.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured page lifecycle controller.
    #[must_use]
    pub fn with_budget(budget: PageBudgetPolicy) -> Self {
        Self {
            budget,
            pages: HashMap::new(),
            next_page_id: 1,
            active_clock: 0,
            host_revision: 1,
            stale_callbacks_blocked: 0,
            os_background_events: 0,
            os_foreground_events: 0,
            surface_lost_events: 0,
            surface_recreated_events: 0,
            total_destroyed_pages: 0,
        }
    }

    /// Registers a newly active page or child sub-page and returns its initial `PageGenerationToken`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `String` - Canonical route identifier.
    /// - `PageRetention` - Retention strategy (`Freeze`, `Destroy`, `Alive`).
    /// - `Option<u64>` - Optional parent `page_id` for deterministic parent-child lifecycle propagation.
    /// - `usize` - Core retained state memory footprint in bytes.
    /// - `usize` - Reconstructible cache memory footprint in bytes (evicted before page eviction).
    ///
    /// # Returns
    ///
    /// - `PageGenerationToken` - Generation-guarded handle for async callbacks and ownership tracking.
    pub fn register_page(
        &mut self,
        route_key: String,
        retention: PageRetention,
        parent_page_id: Option<u64>,
        retained_bytes: usize,
        reconstructible_cache_bytes: usize,
    ) -> PageGenerationToken {
        let page_id: u64 = self.get_next_page_id();
        let next_tick: u64 = self.get_active_clock().wrapping_add(1);
        let host_rev: u64 = self.get_host_revision();
        let Self {
            pages,
            next_page_id,
            active_clock,
            ..
        } = self;
        *next_page_id = page_id.wrapping_add(1).max(1);
        *active_clock = next_tick;
        let (has_parent, pid): (bool, u64) = match parent_page_id {
            Some(p) => (true, p),
            None => (false, 0),
        };
        let entry: PageLifecycleEntry = PageLifecycleEntry {
            page_id,
            route_key,
            generation: 1,
            parent_page_id: pid,
            has_parent,
            phase: LifecyclePhase::Active,
            retention,
            retained_bytes,
            reconstructible_cache_bytes,
            last_active_tick: next_tick,
            freeze_count: 0,
            resume_count: 0,
            evict_count: 0,
            host_synced_revision: host_rev,
            snapshot: PageSnapshot::default(),
            has_snapshot: false,
            os_background_suspended: false,
            surface_lost_generation: 0,
            has_surface_lost: false,
        };
        let _: Option<PageLifecycleEntry> = pages.insert(page_id, entry);
        PageGenerationToken::new(page_id, 1)
    }

    /// Returns `true` when `token` matches the current live non-evicted, non-destroyed page generation.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Page lifecycle controller reference.
    /// - `PageGenerationToken` - Candidate generation token held by an async task or timer.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when writes from `token` are still authorized.
    #[must_use]
    pub fn is_token_current(&self, token: PageGenerationToken) -> bool {
        match self.get_pages().get(&token.get_page_id()) {
            Some(entry) => {
                entry.get_generation() == token.get_generation()
                    && !matches!(
                        entry.get_phase(),
                        LifecyclePhase::Evicted | LifecyclePhase::Destroyed
                    )
            }
            None => false,
        }
    }

    /// Runs `callback` ONLY when `token` belongs to a live `Active` page of the exact matching generation; otherwise blocks and counts it.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `PageGenerationToken` - Generation token captured when the async request started.
    /// - `F` - State commit closure executed only when `token` is still current and active.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the callback executed; `false` when rejected by the generation guard.
    pub fn try_commit_async_callback<F>(&mut self, token: PageGenerationToken, callback: F) -> bool
    where
        F: FnOnce(),
    {
        let allowed: bool =
            self.get_pages()
                .get(&token.get_page_id())
                .is_some_and(|entry: &PageLifecycleEntry| {
                    entry.get_generation() == token.get_generation()
                        && entry.get_phase() == LifecyclePhase::Active
                });
        if allowed {
            callback();
            true
        } else {
            let Self {
                stale_callbacks_blocked,
                ..
            } = self;
            *stale_callbacks_blocked = stale_callbacks_blocked.saturating_add(1);
            false
        }
    }

    /// Attaches or updates a versioned `PageSnapshot` (including persisted draft status) on `page_id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `u64` - Target page identifier.
    /// - `PageSnapshot` - Versioned snapshot payload.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if `page_id` exists and is not `Destroyed`.
    pub fn update_snapshot(&mut self, page_id: u64, snapshot: PageSnapshot) -> bool {
        let max_bytes: usize = self.get_budget().get_max_snapshot_bytes();
        let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
            return false;
        };
        if entry.get_phase() == LifecyclePhase::Destroyed {
            return false;
        }
        let mut bounded: PageSnapshot = snapshot;
        if bounded.get_estimated_bytes() > max_bytes {
            bounded.set_estimated_bytes(max_bytes);
        }
        entry.set_snapshot(bounded);
        entry.set_has_snapshot(true);
        true
    }

    /// Marks an unsaved draft on `page_id` durably persisted so cold eviction may proceed safely without data loss.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `u64` - Target page identifier.
    /// - `String` - Persisted draft payload stored inside the page snapshot.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the draft was persisted onto the page snapshot.
    pub fn persist_page_draft(&mut self, page_id: u64, draft_payload: String) -> bool {
        let Some(entry) = self.get_mut_pages().get_mut(&page_id) else {
            return false;
        };
        if entry.get_phase() == LifecyclePhase::Destroyed {
            return false;
        }
        let mut snap: PageSnapshot = if entry.get_has_snapshot() {
            entry.get_snapshot().clone()
        } else {
            PageSnapshot::capture(
                entry.get_route_key().clone(),
                entry.get_generation(),
                Point::default(),
                None,
                String::new(),
                (true, true),
                entry.get_host_synced_revision(),
            )
        };
        snap.set_draft_payload(draft_payload);
        snap.set_has_unsaved_draft(true);
        snap.set_draft_persisted(true);
        entry.set_snapshot(snap);
        entry.set_has_snapshot(true);
        true
    }

    /// Collects `root_id` followed by all descendant page IDs in deterministic breadth-first order.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Page lifecycle controller reference.
    /// - `u64` - Root page identifier.
    ///
    /// # Returns
    ///
    /// - `Vec<u64>` - Ordered list of `[root_id, ...descendants]`.
    #[must_use]
    fn collect_page_subtree(&self, root_id: u64) -> Vec<u64> {
        if !self.get_pages().contains_key(&root_id) {
            return Vec::new();
        }
        let mut ordered: Vec<u64> = vec![root_id];
        let mut cursor: usize = 0;
        while cursor < ordered.len() {
            let parent_id: u64 = ordered[cursor];
            cursor += 1;
            let mut children: Vec<u64> = self
                .get_pages()
                .values()
                .filter(|entry: &&PageLifecycleEntry| {
                    entry.get_has_parent() && entry.get_parent_page_id() == parent_id
                })
                .map(PageLifecycleEntry::get_page_id)
                .collect();
            children.sort_unstable();
            for cid in children.into_iter() {
                if !ordered.contains(&cid) {
                    ordered.push(cid);
                }
            }
        }
        ordered
    }

    /// Idempotently freezes `page_id` and its active descendants once without double-firing on already-frozen pages.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `u64` - Target page identifier to freeze.
    /// - `Option<PageSnapshot>` - Optional fresh versioned snapshot captured before freezing.
    ///
    /// # Returns
    ///
    /// - `Vec<u64>` - Page identifiers newly transitioned from `Active` to `Frozen`.
    pub fn freeze_page(&mut self, page_id: u64, snapshot: Option<PageSnapshot>) -> Vec<u64> {
        if let Some(snap) = snapshot {
            let _: bool = self.update_snapshot(page_id, snap);
        }
        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
        let mut newly_frozen: Vec<u64> = Vec::new();
        for pid in subtree.into_iter() {
            if let Some(entry) = self.get_mut_pages().get_mut(&pid)
                && entry.get_phase() == LifecyclePhase::Active
            {
                entry.set_phase(LifecyclePhase::Frozen);
                entry.set_freeze_count(entry.get_freeze_count().saturating_add(1));
                newly_frozen.push(pid);
            }
        }
        newly_frozen
    }

    /// Idempotently resumes `page_id` (and frozen descendants), restoring from `PageSnapshot` if previously `Evicted` and checking host-state synchronization.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `u64` - Target page identifier to resume.
    /// - `u64` - Current authoritative host/shared-store revision.
    ///
    /// # Returns
    ///
    /// - `Option<(PageGenerationToken, Option<PageSnapshot>, bool)>` - Active token, restored snapshot (when reconstructed or present), and `host_sync_required` flag.
    pub fn resume_page(
        &mut self,
        page_id: u64,
        current_host_revision: u64,
    ) -> Option<(PageGenerationToken, Option<PageSnapshot>, bool)> {
        self.set_host_revision(current_host_revision.max(self.get_host_revision()));
        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
        if subtree.is_empty() {
            return None;
        }
        let root_phase: LifecyclePhase = self.get_pages().get(&page_id)?.get_phase();
        if root_phase == LifecyclePhase::Destroyed {
            return None;
        }
        let next_tick: u64 = self.get_active_clock().wrapping_add(1);
        {
            let Self { active_clock, .. } = self;
            *active_clock = next_tick;
        }
        if root_phase == LifecyclePhase::Active {
            let entry: &mut PageLifecycleEntry = self.get_mut_pages().get_mut(&page_id)?;
            let host_dirty: bool = entry.get_host_synced_revision() != current_host_revision;
            entry.set_host_synced_revision(current_host_revision);
            entry.set_last_active_tick(next_tick);
            let token: PageGenerationToken =
                PageGenerationToken::new(entry.get_page_id(), entry.get_generation());
            return Some((token, None, host_dirty));
        }
        let mut root_token: PageGenerationToken = PageGenerationToken::default();
        let mut restored_snap: Option<PageSnapshot> = None;
        let mut root_host_dirty: bool = false;
        for pid in subtree.into_iter() {
            if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
                match entry.get_phase() {
                    LifecyclePhase::Frozen => {
                        let dirty: bool = entry.get_host_synced_revision() != current_host_revision;
                        entry.set_phase(LifecyclePhase::Active);
                        entry.set_resume_count(entry.get_resume_count().saturating_add(1));
                        entry.set_host_synced_revision(current_host_revision);
                        entry.set_last_active_tick(next_tick);
                        if pid == page_id {
                            root_token = PageGenerationToken::new(pid, entry.get_generation());
                            root_host_dirty = dirty;
                            if entry.get_has_snapshot() {
                                restored_snap = Some(entry.get_snapshot().clone());
                            }
                        }
                    }
                    LifecyclePhase::Evicted => {
                        let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
                        entry.set_generation(next_gen);
                        entry.set_phase(LifecyclePhase::Active);
                        entry.set_resume_count(entry.get_resume_count().saturating_add(1));
                        entry.set_host_synced_revision(current_host_revision);
                        entry.set_last_active_tick(next_tick);
                        if pid == page_id {
                            root_token = PageGenerationToken::new(pid, next_gen);
                            root_host_dirty = true;
                            if entry.get_has_snapshot() {
                                restored_snap = Some(entry.get_snapshot().clone());
                            }
                        }
                    }
                    LifecyclePhase::Active
                    | LifecyclePhase::Created
                    | LifecyclePhase::Mounted
                    | LifecyclePhase::Unmounted
                    | LifecyclePhase::Destroyed => {}
                }
            }
        }
        Some((root_token, restored_snap, root_host_dirty))
    }

    /// Enforces bounded cold-page budgets: FIRST drains reconstructible caches, THEN evicts oldest cold `Frozen` pages while protecting unpersisted unsaved drafts.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    ///
    /// # Returns
    ///
    /// - `PageEvictionReport` - Freed reconstructible bytes, evicted page IDs, and protected unsaved draft count.
    pub fn enforce_budget(&mut self) -> PageEvictionReport {
        let policy: PageBudgetPolicy = self.get_budget();
        let mut report: PageEvictionReport = PageEvictionReport::default();
        let mut frozen_list: Vec<(u64, u64)> = self
            .get_pages()
            .values()
            .filter(|e: &&PageLifecycleEntry| e.get_phase() == LifecyclePhase::Frozen)
            .map(|e: &PageLifecycleEntry| (e.get_last_active_tick(), e.get_page_id()))
            .collect();
        frozen_list.sort_unstable_by_key(|pair: &(u64, u64)| pair.0);
        let mut total_bytes: usize = self
            .get_pages()
            .values()
            .filter(|e: &&PageLifecycleEntry| e.get_phase() == LifecyclePhase::Frozen)
            .fold(0_usize, |acc: usize, e: &PageLifecycleEntry| {
                acc.saturating_add(e.get_retained_bytes())
                    .saturating_add(e.get_reconstructible_cache_bytes())
            });
        for &(_, pid) in frozen_list.iter() {
            if total_bytes <= policy.get_max_retained_bytes() {
                break;
            }
            if let Some(entry) = self.get_mut_pages().get_mut(&pid) {
                let cache_bytes: usize = entry.get_reconstructible_cache_bytes();
                if cache_bytes > 0 {
                    entry.set_reconstructible_cache_bytes(0);
                    total_bytes = total_bytes.saturating_sub(cache_bytes);
                    report.set_reconstructible_bytes_freed(
                        report
                            .get_reconstructible_bytes_freed()
                            .saturating_add(cache_bytes),
                    );
                }
            }
        }
        let mut frozen_count: usize = frozen_list.len();
        for (_, pid) in frozen_list.into_iter() {
            let over_count: bool = frozen_count > policy.get_max_frozen_pages();
            let over_bytes: bool = total_bytes > policy.get_max_retained_bytes();
            if !over_count && !over_bytes {
                break;
            }
            let Some(entry) = self.get_mut_pages().get_mut(&pid) else {
                continue;
            };
            if entry.get_phase() != LifecyclePhase::Frozen {
                continue;
            }
            let has_unpersisted_draft: bool = entry.get_has_snapshot()
                && entry.get_snapshot().get_has_unsaved_draft()
                && !entry.get_snapshot().get_draft_persisted();
            if has_unpersisted_draft {
                report.set_protected_unsaved_pages(
                    report.get_protected_unsaved_pages().saturating_add(1),
                );
                continue;
            }
            if !entry.get_has_snapshot() {
                let fallback_snap: PageSnapshot = PageSnapshot::capture(
                    entry.get_route_key().clone(),
                    entry.get_generation(),
                    Point::default(),
                    None,
                    String::new(),
                    (false, false),
                    entry.get_host_synced_revision(),
                );
                entry.set_snapshot(fallback_snap);
                entry.set_has_snapshot(true);
            }
            let freed_now: usize = entry
                .get_retained_bytes()
                .saturating_add(entry.get_reconstructible_cache_bytes());
            let snap_bytes: usize = entry
                .get_snapshot()
                .get_estimated_bytes()
                .min(policy.get_max_snapshot_bytes());
            let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
            entry.set_generation(next_gen);
            entry.set_phase(LifecyclePhase::Evicted);
            entry.set_retained_bytes(snap_bytes);
            entry.set_reconstructible_cache_bytes(0);
            entry.set_evict_count(entry.get_evict_count().saturating_add(1));
            total_bytes = total_bytes.saturating_sub(freed_now);
            frozen_count = frozen_count.saturating_sub(1);
            report.get_mut_evicted_page_ids().push(pid);
        }
        report
    }

    /// Explicitly destroys `page_id` and all descendants, bumping generation, dropping `PageSnapshot`, and blocking all stale async writes.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `u64` - Target page identifier to destroy permanently.
    ///
    /// # Returns
    ///
    /// - `Vec<PageGenerationToken>` - Destroyed `(page_id, prior_generation)` tokens for resource ownership accounting.
    pub fn destroy_page(&mut self, page_id: u64) -> Vec<PageGenerationToken> {
        let subtree: Vec<u64> = self.collect_page_subtree(page_id);
        let mut destroyed_tokens: Vec<PageGenerationToken> = Vec::new();
        for pid in subtree.into_iter() {
            if let Some(entry) = self.get_mut_pages().get_mut(&pid)
                && entry.get_phase() != LifecyclePhase::Destroyed
            {
                let old_token: PageGenerationToken =
                    PageGenerationToken::new(pid, entry.get_generation());
                let next_gen: u64 = entry.get_generation().wrapping_add(1).max(1);
                entry.set_generation(next_gen);
                entry.set_phase(LifecyclePhase::Destroyed);
                entry.set_retained_bytes(0);
                entry.set_reconstructible_cache_bytes(0);
                entry.set_snapshot(PageSnapshot::default());
                entry.set_has_snapshot(false);
                destroyed_tokens.push(old_token);
            }
        }
        let Self {
            total_destroyed_pages,
            ..
        } = self;
        *total_destroyed_pages =
            total_destroyed_pages.saturating_add(destroyed_tokens.len() as u64);
        destroyed_tokens
    }

    /// Processes a distinct OS background, surface-loss, or route-freeze boundary event without conflating their state transitions.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable page lifecycle controller.
    /// - `LifecycleBoundaryEvent` - Structured boundary event.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of page entries updated by this boundary event.
    pub fn apply_boundary_event(&mut self, event: LifecycleBoundaryEvent) -> usize {
        match event {
            LifecycleBoundaryEvent::OsBackground => {
                let Self {
                    pages,
                    os_background_events,
                    ..
                } = self;
                *os_background_events = os_background_events.saturating_add(1);
                let mut touched: usize = 0;
                for entry in pages.values_mut() {
                    if matches!(
                        entry.get_phase(),
                        LifecyclePhase::Active | LifecyclePhase::Frozen
                    ) && !entry.get_os_background_suspended()
                    {
                        entry.set_os_background_suspended(true);
                        touched += 1;
                    }
                }
                touched
            }
            LifecycleBoundaryEvent::OsForeground => {
                let Self {
                    pages,
                    os_foreground_events,
                    ..
                } = self;
                *os_foreground_events = os_foreground_events.saturating_add(1);
                let mut touched: usize = 0;
                for entry in pages.values_mut() {
                    if entry.get_os_background_suspended() {
                        entry.set_os_background_suspended(false);
                        touched += 1;
                    }
                }
                touched
            }
            LifecycleBoundaryEvent::SurfaceLost { surface_generation } => {
                let Self {
                    pages,
                    surface_lost_events,
                    ..
                } = self;
                *surface_lost_events = surface_lost_events.saturating_add(1);
                let mut touched: usize = 0;
                for entry in pages.values_mut() {
                    if entry.get_phase() != LifecyclePhase::Destroyed {
                        entry.set_has_surface_lost(true);
                        entry.set_surface_lost_generation(surface_generation);
                        touched += 1;
                    }
                }
                touched
            }
            LifecycleBoundaryEvent::SurfaceRecreated { surface_generation } => {
                let Self {
                    pages,
                    surface_recreated_events,
                    ..
                } = self;
                *surface_recreated_events = surface_recreated_events.saturating_add(1);
                let mut touched: usize = 0;
                for entry in pages.values_mut() {
                    if entry.get_has_surface_lost() {
                        entry.set_has_surface_lost(false);
                        entry.set_surface_lost_generation(surface_generation);
                        touched += 1;
                    }
                }
                touched
            }
            LifecycleBoundaryEvent::RouteFreeze { page_id } => {
                self.freeze_page(page_id, None).len()
            }
            LifecycleBoundaryEvent::RouteResume { page_id } => {
                let host_rev: u64 = self.get_host_revision();
                usize::from(self.resume_page(page_id, host_rev).is_some())
            }
        }
    }

    /// Returns aggregate page counts `(active, frozen, evicted, destroyed)` for resource accounting snapshots.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Page lifecycle controller reference.
    ///
    /// # Returns
    ///
    /// - `(usize, usize, usize, u64)` - Tuple `(active, frozen, evicted, total_destroyed)`.
    #[must_use]
    pub fn phase_counts(&self) -> (usize, usize, usize, u64) {
        let mut active: usize = 0;
        let mut frozen: usize = 0;
        let mut evicted: usize = 0;
        for entry in self.get_pages().values() {
            match entry.get_phase() {
                LifecyclePhase::Active | LifecyclePhase::Mounted | LifecyclePhase::Created => {
                    active += 1;
                }
                LifecyclePhase::Frozen => {
                    frozen += 1;
                }
                LifecyclePhase::Evicted => {
                    evicted += 1;
                }
                LifecyclePhase::Unmounted | LifecyclePhase::Destroyed => {}
            }
        }
        (active, frozen, evicted, self.get_total_destroyed_pages())
    }
}