euv-core 0.47.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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
use super::*;

/// Safe defaults and builder helpers on `UpdateClientConfig`.
impl UpdateClientConfig {
    /// Creates a production-configured `UpdateClientConfig` with default ABI, WasmComponent mode, and budgets.
    ///
    /// # Arguments
    ///
    /// - `String` - Base HTTP server URL.
    /// - `String` - Project identifier.
    /// - `String` - Channel name.
    /// - `Vec<u8>` - Trusted HMAC-SHA256 verification key.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured update client settings.
    #[must_use]
    pub fn with_defaults(
        base_url: String,
        project: String,
        channel: String,
        verify_key: Vec<u8>,
    ) -> Self {
        let mut cfg: Self = Self::new(base_url, project, channel, verify_key);
        cfg.set_host_abi(DYNAMIC_HOST_ABI_V1)
            .set_delivery_mode(DeliveryChannelMode::WasmComponent)
            .set_max_artifact_bytes(DEFAULT_MAX_ARTIFACT_BYTES)
            .set_mailbox_capacity(DEFAULT_CANDIDATE_MAILBOX_CAP)
            .set_reconnect_backoff_ms(DEFAULT_SSE_RECONNECT_MS)
            .set_http_timeout_ms(DEFAULT_UPDATE_HTTP_TIMEOUT_MS)
            .set_sandbox_config(WasmSandboxConfig::default());
        cfg
    }

    /// Returns the optional preferred compatibility track name.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Preferred track if set.
    #[must_use]
    pub fn preferred_track_str(&self) -> Option<&str> {
        let Self {
            preferred_track, ..
        } = self;
        preferred_track.as_deref()
    }

    /// Builds a `ClientNegotiation` descriptor from this client configuration.
    ///
    /// # Returns
    ///
    /// - `ClientNegotiation` - Protocol, ABI, delivery mode, and capability declaration.
    #[must_use]
    pub fn negotiation(&self) -> ClientNegotiation {
        let mut neg: ClientNegotiation = ClientNegotiation::new(
            DYNAMIC_PROTOCOL_VERSION_V1,
            self.get_host_abi(),
            self.get_delivery_mode(),
        )
        .with_capabilities(self.get_capabilities().clone());
        if let Some(track) = self.preferred_track_str() {
            neg = neg.with_preferred_track(track.to_string());
        }
        neg
    }
}

/// Real pure-std HTTP/1.1 manifest and range-resumable blob fetching on `HttpReleaseTransport`.
impl ReleaseTransport for HttpReleaseTransport {
    /// Fetches a signed `ReleaseManifest` from `/v1/projects/{project}/channels/{channel}/manifest`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Project identifier.
    /// - `&str` - Channel name.
    /// - `&ClientNegotiation` - Protocol, ABI, delivery mode, and track negotiation parameters.
    ///
    /// # Returns
    ///
    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Deserialized manifest or typed error.
    fn fetch_manifest(
        &self,
        project: &str,
        channel: &str,
        negotiation: &ClientNegotiation,
    ) -> Result<ReleaseManifest, DynamicReleaseError> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
            let base_prefix: String = if prefix.is_empty() {
                String::new()
            } else {
                format!("/{prefix}")
            };
            let mode_tok: &str = delivery_mode_query_token(negotiation.get_delivery_mode());
            let mut path: String = format!(
                "{base_prefix}/v1/projects/{project}/channels/{channel}/manifest?protocol={}&abi={}&mode={mode_tok}",
                negotiation.get_protocol_version(),
                negotiation.get_host_abi()
            );
            if let Some(track) = negotiation.preferred_track_str() {
                path.push_str(&format!("&track={track}"));
            }
            let (status, body): (u16, Vec<u8>) =
                http_get_once(authority, &path, &[], self.get_timeout_ms())?;
            if status == 409 {
                let reason: String = String::from_utf8_lossy(&body).into_owned();
                return Err(DynamicReleaseError::ProtocolIncompatible(reason));
            }
            if status != 200 {
                return Err(DynamicReleaseError::NetworkError(format!(
                    "{ERR_HTTP_NON_OK}: HTTP {status}"
                )));
            }
            let text: &str = from_utf8(&body).map_err(|_| {
                DynamicReleaseError::StorageError(ERR_MANIFEST_SERIALIZE.to_string())
            })?;
            match from_str::<ReleaseManifest>(text) {
                Ok(parsed) => Ok(parsed),
                Err(err) => Err(DynamicReleaseError::StorageError(format!(
                    "{ERR_MANIFEST_SERIALIZE}: {err}"
                ))),
            }
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _: (&str, &str, &ClientNegotiation) = (project, channel, negotiation);
            Err(DynamicReleaseError::NetworkError(
                ERR_WASM32_SYNC_HTTP.to_string(),
            ))
        }
    }

    /// Fetches immutable content-addressed blob bytes from `/v1/blobs/{sha256}` with optional byte-range resume.
    ///
    /// # Arguments
    ///
    /// - `&str` - Lowercase 64-character SHA-256 digest.
    /// - `u64` - Starting byte offset (`0` for full download).
    ///
    /// # Returns
    ///
    /// - `Result<Vec<u8>, DynamicReleaseError>` - Downloaded bytes from `range_start` to EOF.
    fn fetch_blob(&self, sha256: &str, range_start: u64) -> Result<Vec<u8>, DynamicReleaseError> {
        #[cfg(not(target_arch = "wasm32"))]
        {
            let (authority, prefix): (&str, &str) = parse_http_base_url(self.get_base_url())?;
            let base_prefix: String = if prefix.is_empty() {
                String::new()
            } else {
                format!("/{prefix}")
            };
            let path: String = format!("{base_prefix}/v1/blobs/{sha256}");
            let range_header: String = format!("bytes={range_start}-");
            let headers: Vec<(&str, &str)> = if range_start > 0 {
                vec![(HDR_RANGE, range_header.as_str())]
            } else {
                Vec::new()
            };
            let (status, body): (u16, Vec<u8>) =
                http_get_once(authority, &path, &headers, self.get_timeout_ms())?;
            if status == 404 {
                return Err(DynamicReleaseError::BlobMissing(sha256.to_string()));
            }
            if status != 200 && status != 206 {
                return Err(DynamicReleaseError::NetworkError(format!(
                    "{ERR_HTTP_NON_OK}: HTTP {status}"
                )));
            }
            Ok(body)
        }
        #[cfg(target_arch = "wasm32")]
        {
            let _: (&str, u64) = (sha256, range_start);
            Err(DynamicReleaseError::NetworkError(
                ERR_WASM32_SYNC_HTTP.to_string(),
            ))
        }
    }
}

/// Bounded non-blocking mailbox operations on `CandidateMailbox`.
impl CandidateMailbox {
    /// Creates a bounded `CandidateMailbox` rejecting any candidate older than or equal to `initial_seq`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Maximum number of buffered prepared candidates.
    /// - `u64` - Initial active release sequence baseline.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized mailbox.
    #[must_use]
    pub fn new(capacity: usize, initial_seq: u64) -> Self {
        let inner: CandidateMailboxInner = CandidateMailboxInner {
            capacity: capacity.max(1),
            highest_seen_seq: initial_seq,
            queue: VecDeque::with_capacity(capacity.max(1)),
        };
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }

    /// Pushes a prepared candidate into the mailbox, discarding stale releases and coalescing when full.
    ///
    /// # Arguments
    ///
    /// - `PreparedReleaseCandidate` - Verified, warmed candidate from `UpdateWorker`.
    pub fn push_candidate(&self, candidate: PreparedReleaseCandidate) {
        let Self { inner } = self;
        if let Ok(mut guard) = inner.lock() {
            let incoming_seq: u64 = candidate.get_manifest().get_release_seq();
            if incoming_seq <= guard.highest_seen_seq {
                return;
            }
            guard.highest_seen_seq = incoming_seq;
            while guard.queue.len() >= guard.capacity {
                let _: Option<PreparedReleaseCandidate> = guard.queue.pop_front();
            }
            guard.queue.push_back(candidate);
        }
    }

    /// Non-blockingly drains the mailbox on the UI thread and returns only the newest prepared candidate.
    ///
    /// # Returns
    ///
    /// - `Option<PreparedReleaseCandidate>` - Latest ready candidate, or `None` if empty or contended.
    #[must_use]
    pub fn try_recv_latest(&self) -> Option<PreparedReleaseCandidate> {
        let Self { inner } = self;
        let mut guard: MutexGuard<'_, CandidateMailboxInner> = inner.try_lock().ok()?;
        let mut latest: Option<PreparedReleaseCandidate> = None;
        while let Some(item) = guard.queue.pop_front() {
            latest = Some(item);
        }
        latest
    }

    /// Returns the number of candidates currently waiting in the mailbox without blocking.
    ///
    /// # Returns
    ///
    /// - `usize` - Pending candidate count.
    #[must_use]
    pub fn pending_count(&self) -> usize {
        let Self { inner } = self;
        inner
            .try_lock()
            .map(|g: MutexGuard<'_, CandidateMailboxInner>| g.queue.len())
            .unwrap_or(0)
    }
}

/// Control and entrypoints on `UpdateWorkerHandle` (Sec 11.2 / 11.8).
impl UpdateWorkerHandle {
    /// Checks and fetches the latest compatible signed manifest for `(project, channel)` (Sec 11.2).
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical project identifier.
    /// - `&str` - Channel name.
    ///
    /// # Returns
    ///
    /// - `Result<ReleaseManifest, DynamicReleaseError>` - Verified signed manifest or error.
    pub fn check_update(
        &self,
        project: &str,
        channel: &str,
    ) -> Result<ReleaseManifest, DynamicReleaseError> {
        let Self { shared, .. } = self;
        let transport: HttpReleaseTransport = HttpReleaseTransport::new(
            shared.config.get_base_url().clone(),
            shared.config.get_http_timeout_ms(),
        );
        let negotiation: ClientNegotiation = shared.config.negotiation();
        let manifest: ReleaseManifest = transport.fetch_manifest(project, channel, &negotiation)?;
        manifest.verify_signature(shared.config.get_verify_key())?;
        manifest.validate_for_host(
            shared.config.get_host_abi(),
            shared.config.get_capabilities(),
            shared.config.get_delivery_mode(),
            shared.config.get_max_artifact_bytes(),
        )?;
        Ok(manifest)
    }

    /// Prepares a release candidate using the worker's verified cache, incremental hash diff, and pure migrator (Sec 11.2).
    ///
    /// # Arguments
    ///
    /// - `ReleaseManifest` - Signed target release manifest.
    /// - `Option<NestedStateSnapshot>` - Optional captured route UI state snapshot at revision `R`.
    ///
    /// # Returns
    ///
    /// - `Result<PreparedReleaseCandidate, DynamicReleaseError>` - Ready candidate or typed error.
    pub fn prepare_release(
        &self,
        manifest: ReleaseManifest,
        snapshot: Option<NestedStateSnapshot>,
    ) -> Result<PreparedReleaseCandidate, DynamicReleaseError> {
        let Self { shared, .. } = self;
        let transport: HttpReleaseTransport = HttpReleaseTransport::new(
            shared.config.get_base_url().clone(),
            shared.config.get_http_timeout_ms(),
        );
        prepare_release_with_shared(shared, &transport, manifest, snapshot)
    }

    /// Seeds verified content-addressed blobs into the worker's local cache (for built-in/offline startup).
    ///
    /// # Arguments
    ///
    /// - `BTreeMap<String, Vec<u8>>` - Map of SHA-256 hex digest to verified blob bytes.
    pub fn seed_verified_blobs(&self, blobs: BTreeMap<String, Vec<u8>>) {
        let Self { shared, .. } = self;
        if let Ok(mut cache) = shared.blob_cache.lock() {
            for (sha, bytes) in blobs.into_iter() {
                let _: Option<Arc<Vec<u8>>> = cache.insert(sha, Arc::new(bytes));
            }
        }
    }

    /// Queues a captured route `NestedStateSnapshot` so the next background preparation migrates it off the UI thread.
    ///
    /// # Arguments
    ///
    /// - `NestedStateSnapshot` - Immutable snapshot captured at revision `R`.
    pub fn submit_ui_snapshot(&self, snapshot: NestedStateSnapshot) {
        let Self { shared, .. } = self;
        if let Ok(mut slot) = shared.pending_snapshot.lock() {
            *slot = Some(snapshot);
        }
    }

    /// Non-blockingly polls the bounded candidate mailbox from the UI thread.
    ///
    /// # Returns
    ///
    /// - `Option<PreparedReleaseCandidate>` - Latest prepared candidate ready for frame-boundary swap.
    #[must_use]
    pub fn try_take_ready_candidate(&self) -> Option<PreparedReleaseCandidate> {
        let Self { shared, .. } = self;
        shared.mailbox.try_recv_latest()
    }

    /// Requests an immediate manifest reconciliation on the background worker (e.g. on foreground resume).
    pub fn request_reconcile(&self) {
        let Self { shared, .. } = self;
        shared.reconcile_requested.store(true, Ordering::Release);
    }

    /// Returns the latest `Last-Event-ID` cursor accepted by the background SSE client.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Active `Last-Event-ID` cursor string.
    #[must_use]
    pub fn last_event_id(&self) -> Option<String> {
        let Self { shared, .. } = self;
        shared
            .last_event_id
            .lock()
            .ok()
            .and_then(|g: MutexGuard<'_, Option<String>>| g.clone())
    }

    /// Overrides the `Last-Event-ID` cursor (e.g. when restoring persisted resume state across restarts).
    ///
    /// # Arguments
    ///
    /// - `Option<String>` - Cursor string to send on the next SSE connection.
    pub fn set_last_event_id(&self, cursor: Option<String>) {
        let Self { shared, .. } = self;
        if let Ok(mut slot) = shared.last_event_id.lock() {
            *slot = cursor;
        }
    }

    /// Returns the chronological log of SHA-256 digests actually downloaded over HTTP by this worker.
    ///
    /// # Returns
    ///
    /// - `Vec<String>` - Downloaded blob SHA-256 digests.
    #[must_use]
    pub fn fetched_blob_hashes(&self) -> Vec<String> {
        let Self { shared, .. } = self;
        shared
            .fetched_hashes_log
            .lock()
            .map(|g: MutexGuard<'_, Vec<String>>| g.clone())
            .unwrap_or_default()
    }

    /// Returns the number of established SSE sessions (incremented on initial connect and reconnects).
    ///
    /// # Returns
    ///
    /// - `u64` - Total SSE connect count.
    #[must_use]
    pub fn sse_connect_count(&self) -> u64 {
        let Self { shared, .. } = self;
        shared.sse_connect_count.load(Ordering::Acquire)
    }

    /// Returns the most recent background error recorded without interrupting the live UI.
    ///
    /// # Returns
    ///
    /// - `Option<DynamicReleaseError>` - Last recorded error if any.
    #[must_use]
    pub fn last_error(&self) -> Option<DynamicReleaseError> {
        let Self { shared, .. } = self;
        shared
            .last_error
            .lock()
            .ok()
            .and_then(|g: MutexGuard<'_, Option<DynamicReleaseError>>| g.clone())
    }

    /// Signals the dedicated background `UpdateWorker` thread to stop and joins it cleanly.
    pub fn stop(&mut self) {
        let Self {
            shared,
            #[cfg(not(target_arch = "wasm32"))]
            worker_thread,
        } = self;
        shared.running.store(false, Ordering::Release);
        #[cfg(not(target_arch = "wasm32"))]
        if let Some(handle) = worker_thread.take() {
            let _: Result<(), Box<dyn Any + Send>> = handle.join();
        }
    }
}

/// Automatic worker shutdown when `UpdateWorkerHandle` is dropped.
impl Drop for UpdateWorkerHandle {
    /// Stops and joins the background worker thread on drop.
    fn drop(&mut self) {
        self.stop();
    }
}

/// Core per-route pinning, safe-point swapping, rollback, and GC orchestration on `DynamicReleaseRuntime`.
impl DynamicReleaseRuntime {
    /// Creates a new `DynamicReleaseRuntime` bound to `hub` and `business_store`.
    ///
    /// # Arguments
    ///
    /// - `DynamicUpdateHub` - Live UI dynamic update hub.
    /// - `BusinessStateStore` - Host-owned authoritative business state store.
    /// - `WasmSandboxConfig` - Sandbox limits applied when mounting dynamic Wasm modules.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized dynamic release runtime.
    #[must_use]
    pub fn new(
        hub: DynamicUpdateHub,
        business_store: BusinessStateStore,
        sandbox_config: WasmSandboxConfig,
    ) -> Self {
        Self {
            hub,
            business_store,
            sandbox_config,
            active_release_seq: 0,
            generations: BTreeMap::new(),
            open_routes: BTreeMap::new(),
            restored_ui_states: BTreeMap::new(),
            deferred_candidate: None,
            next_hub_revision: 1,
        }
    }

    /// Returns a reference to the host-owned `BusinessStateStore`.
    ///
    /// # Returns
    ///
    /// - `&BusinessStateStore` - Shared authoritative business state store.
    #[must_use]
    pub fn business_store(&self) -> &BusinessStateStore {
        let Self { business_store, .. } = self;
        business_store
    }

    /// Returns the currently active release sequence number (`0` before initial install).
    ///
    /// # Returns
    ///
    /// - `u64` - Active release sequence.
    #[must_use]
    pub fn active_release_seq(&self) -> u64 {
        let Self {
            active_release_seq, ..
        } = *self;
        active_release_seq
    }

    /// Returns the number of release generations currently retained in memory.
    ///
    /// # Returns
    ///
    /// - `usize` - Count of retained `ReleaseGeneration` records.
    #[must_use]
    pub fn retained_generation_count(&self) -> usize {
        let Self { generations, .. } = self;
        generations.len()
    }

    /// Returns whether a candidate is currently deferred awaiting a safe frame boundary.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when a deferred candidate is pending.
    #[must_use]
    pub fn has_deferred_candidate(&self) -> bool {
        let Self {
            deferred_candidate, ..
        } = self;
        deferred_candidate.is_some()
    }

    /// Returns the restored UI state snapshot for a canonical `StableAddress`, if any.
    ///
    /// # Arguments
    ///
    /// - `&str` - Canonical `StableAddress` string.
    ///
    /// # Returns
    ///
    /// - `Option<&ComponentUiStateSnapshot>` - Restored UI state snapshot.
    #[must_use]
    pub fn restored_ui_state(&self, canonical_address: &str) -> Option<&ComponentUiStateSnapshot> {
        let Self {
            restored_ui_states, ..
        } = self;
        restored_ui_states.get(canonical_address)
    }

    /// Installs an initial built-in or cached signed release generation synchronously at startup.
    ///
    /// # Arguments
    ///
    /// - `ReleaseManifest` - Verified initial manifest (e.g. generation `101`).
    /// - `&BTreeMap<String, Vec<u8>>` - Raw verified blob bytes keyed by SHA-256 hex digest.
    /// - `u32` - Running host ABI version.
    ///
    /// # Returns
    ///
    /// - `Result<u64, DynamicReleaseError>` - Installed generation sequence number.
    pub fn install_initial_release(
        &mut self,
        manifest: ReleaseManifest,
        blobs: &BTreeMap<String, Vec<u8>>,
        host_abi: u32,
    ) -> Result<u64, DynamicReleaseError> {
        let sandbox_cfg: WasmSandboxConfig = {
            let Self { sandbox_config, .. } = *self;
            sandbox_config
        };
        let mut warmed: BTreeMap<String, WarmedArtifact> = BTreeMap::new();
        for (art_key, artifact) in manifest.get_artifacts().iter() {
            let bytes: &Vec<u8> = blobs
                .get(artifact.get_sha256())
                .ok_or_else(|| DynamicReleaseError::BlobMissing(artifact.get_sha256().clone()))?;
            let item: WarmedArtifact =
                warm_verified_artifact(artifact, bytes.as_slice(), host_abi, &sandbox_cfg)?;
            let _: Option<WarmedArtifact> = warmed.insert(art_key.clone(), item);
        }
        let seq: u64 = manifest.get_release_seq();
        let generation: ReleaseGeneration = ReleaseGeneration {
            generation_id: seq,
            manifest,
            warmed_artifacts: warmed,
            active_route_pins: 0,
            active_in_flight_tasks: 0,
        };
        let Self {
            generations,
            active_release_seq,
            ..
        } = self;
        let _: Option<ReleaseGeneration> = generations.insert(seq, generation);
        *active_release_seq = seq;
        Ok(seq)
    }

    /// Opens a route instance pinned to the currently active release generation and mounts its slots into `DynamicUpdateHub`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Stable route instance key (e.g. `"A#tab-1"` or `"B#tab-1"`).
    /// - `&str` - Route path (e.g. `"/route-a"` or `"/route-b"`).
    ///
    /// # Returns
    ///
    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Pinned route handle.
    pub fn open_route(
        &mut self,
        route_instance_id: &str,
        route: &str,
    ) -> Result<RoutePinHandle, DynamicReleaseError> {
        DynamicFrameMetrics::record_manifest_lookup();
        let normalized_route: String = normalize_dynamic_route(route);
        let target_gen_id: u64 = self.active_release_seq();
        if target_gen_id == 0 {
            return Err(DynamicReleaseError::RouteNotFound(
                ERR_NO_ACTIVE_GENERATION.to_string(),
            ));
        }
        let (entry_module, slot_bindings): (String, BTreeMap<String, String>) = {
            let Self { generations, .. } = self;
            let gen_mut: &mut ReleaseGeneration = generations
                .get_mut(&target_gen_id)
                .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
            let route_manifest: &RouteManifest = gen_mut
                .get_manifest()
                .get_routes()
                .get(&normalized_route)
                .ok_or_else(|| DynamicReleaseError::RouteNotFound(normalized_route.clone()))?;
            let entry: String = route_manifest.get_entry_module().clone();
            let slots: BTreeMap<String, String> = route_manifest.get_slot_bindings().clone();
            gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_add(1));
            (entry, slots)
        };
        let handle: RoutePinHandle = RoutePinHandle {
            route_instance_id: route_instance_id.to_string(),
            route: normalized_route.clone(),
            generation_id: target_gen_id,
            entry_module,
            slot_bindings: slot_bindings.clone(),
            cancellation_token: Arc::new(AtomicBool::new(false)),
        };
        let Self { open_routes, .. } = self;
        let _: Option<RoutePinHandle> =
            open_routes.insert(route_instance_id.to_string(), handle.clone());
        self.apply_route_slots_to_hub(&normalized_route, target_gen_id, &slot_bindings)?;
        Ok(handle)
    }

    /// Closes an open route instance, cancels its token, decrements its generation pin, and runs GC.
    ///
    /// # Arguments
    ///
    /// - `&str` - Route instance identifier to close.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of unreachable old generations reclaimed by GC.
    pub fn close_route(&mut self, route_instance_id: &str) -> usize {
        let removed: Option<RoutePinHandle> = {
            let Self { open_routes, .. } = self;
            open_routes.remove(route_instance_id)
        };
        if let Some(pin) = removed {
            pin.get_cancellation_token().store(true, Ordering::Release);
            let gen_id: u64 = pin.get_generation_id();
            let Self { generations, .. } = self;
            if let Some(gen_mut) = generations.get_mut(&gen_id) {
                gen_mut.set_active_route_pins(gen_mut.get_active_route_pins().saturating_sub(1));
            }
        }
        self.gc_unreachable_generations()
    }

    /// Returns the currently pinned artifact key (`"card@1.0.0"`) for `slot_key` on an open route instance.
    ///
    /// # Arguments
    ///
    /// - `&str` - Open route instance identifier.
    /// - `&str` - Logical slot key.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Exact pinned artifact key if the route and slot exist.
    #[must_use]
    pub fn pinned_slot_artifact(&self, route_instance_id: &str, slot_key: &str) -> Option<String> {
        let Self { open_routes, .. } = self;
        open_routes
            .get(route_instance_id)
            .and_then(|pin: &RoutePinHandle| pin.get_slot_bindings().get(slot_key).cloned())
    }

    /// Returns the currently pinned release generation ID for an open route instance.
    ///
    /// # Arguments
    ///
    /// - `&str` - Open route instance identifier.
    ///
    /// # Returns
    ///
    /// - `Option<u64>` - Pinned release generation ID.
    #[must_use]
    pub fn pinned_generation_for_route(&self, route_instance_id: &str) -> Option<u64> {
        let Self { open_routes, .. } = self;
        open_routes
            .get(route_instance_id)
            .map(RoutePinHandle::get_generation_id)
    }

    /// Captures a `NestedStateSnapshot` at the current authoritative business revision `R` for `route`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Target route path.
    /// - `BTreeMap<String, ComponentUiStateSnapshot>` - Live per-instance UI states keyed by canonical `StableAddress`.
    ///
    /// # Returns
    ///
    /// - `NestedStateSnapshot` - Immutable snapshot ready to pass to the background worker.
    #[must_use]
    pub fn capture_nested_snapshot(
        &self,
        route: &str,
        ui_states: BTreeMap<String, ComponentUiStateSnapshot>,
    ) -> NestedStateSnapshot {
        let normalized: String = normalize_dynamic_route(route);
        let (rev, entity_snaps): (u64, BTreeMap<String, (u64, Value)>) =
            self.business_store().capture_entity_snapshots();
        let mut snap: NestedStateSnapshot =
            NestedStateSnapshot::new(normalized, self.active_release_seq(), rev);
        snap.set_entity_snapshots(entity_snaps)
            .set_ui_states(ui_states);
        snap
    }

    /// Atomically activates a prepared candidate at a safe frame boundary, swapping ONLY affected routes while keeping unaffected routes pinned (Sec 11.2, 11.4, 11.6, 11.8).
    ///
    /// # Arguments
    ///
    /// - `PreparedReleaseCandidate` - Candidate prepared off the UI thread.
    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
    ///
    /// # Returns
    ///
    /// - `Result<ActivationReport, DynamicReleaseError>` - Activation or deferral report.
    pub fn activate_release(
        &mut self,
        candidate: PreparedReleaseCandidate,
        boundary: &InteractionSafePoint,
    ) -> Result<ActivationReport, DynamicReleaseError> {
        let target_seq: u64 = candidate.get_manifest().get_release_seq();
        if target_seq <= self.active_release_seq() {
            return Err(DynamicReleaseError::NonMonotonicRelease {
                current: self.active_release_seq(),
                incoming: target_seq,
            });
        }
        if let Some(reason) = boundary.defer_reason() {
            let Self {
                deferred_candidate,
                open_routes,
                ..
            } = self;
            *deferred_candidate = Some(candidate);
            let unchanged: Vec<String> = open_routes.keys().cloned().collect();
            return Ok(ActivationReport::new(
                target_seq,
                Vec::new(),
                unchanged,
                true,
                reason.to_string(),
                0,
                0,
            ));
        }
        let mut caught_up_deltas: usize = 0;
        for (entity_id, base_rev) in candidate.get_snapshot_entity_revisions().iter() {
            let deltas: Vec<BusinessStateDelta> =
                self.business_store().deltas_since(entity_id, *base_rev)?;
            caught_up_deltas = caught_up_deltas.saturating_add(deltas.len());
        }
        let prev_manifest: Option<ReleaseManifest> = {
            let Self {
                generations,
                active_release_seq,
                ..
            } = self;
            generations
                .get(active_release_seq)
                .map(|g: &ReleaseGeneration| g.get_manifest().clone())
        };
        let authoritative_affected: Vec<String> = candidate
            .get_manifest()
            .affected_routes_since(prev_manifest.as_ref());
        let new_generation: ReleaseGeneration = ReleaseGeneration {
            generation_id: target_seq,
            manifest: candidate.get_manifest().clone(),
            warmed_artifacts: candidate.get_warmed_artifacts().clone(),
            active_route_pins: 0,
            active_in_flight_tasks: 0,
        };
        {
            let Self {
                generations,
                active_release_seq,
                restored_ui_states,
                deferred_candidate,
                ..
            } = self;
            let _: Option<ReleaseGeneration> = generations.insert(target_seq, new_generation);
            *active_release_seq = target_seq;
            for (addr, ui_state) in candidate.get_migrated_ui_states().iter() {
                let _: Option<ComponentUiStateSnapshot> =
                    restored_ui_states.insert(addr.clone(), ui_state.clone());
            }
            *deferred_candidate = None;
        }
        let mut swapped_routes: Vec<String> = Vec::new();
        let mut unchanged_pinned_routes: Vec<String> = Vec::new();
        let mut hub_updates: Vec<(String, BTreeMap<String, String>)> = Vec::new();
        let mut released_gens: Vec<u64> = Vec::new();
        {
            let Self {
                open_routes,
                generations,
                ..
            } = self;
            for (instance_id, pin) in open_routes.iter_mut() {
                let route_path: String = pin.get_route().clone();
                if authoritative_affected.contains(&route_path)
                    && let Some(next_route_manifest) =
                        candidate.get_manifest().get_routes().get(&route_path)
                {
                    let old_gen_id: u64 = pin.get_generation_id();
                    if let Some(old_gen) = generations.get_mut(&old_gen_id) {
                        old_gen.set_active_route_pins(
                            old_gen.get_active_route_pins().saturating_sub(1),
                        );
                        if old_gen.get_active_route_pins() == 0 {
                            released_gens.push(old_gen_id);
                        }
                    }
                    if let Some(new_gen) = generations.get_mut(&target_seq) {
                        new_gen.set_active_route_pins(
                            new_gen.get_active_route_pins().saturating_add(1),
                        );
                    }
                    pin.get_cancellation_token().store(true, Ordering::Release);
                    pin.set_generation_id(target_seq)
                        .set_entry_module(next_route_manifest.get_entry_module().clone())
                        .set_slot_bindings(next_route_manifest.get_slot_bindings().clone())
                        .set_cancellation_token(Arc::new(AtomicBool::new(false)));
                    swapped_routes.push(instance_id.clone());
                    hub_updates.push((route_path, next_route_manifest.get_slot_bindings().clone()));
                } else {
                    unchanged_pinned_routes.push(instance_id.clone());
                }
            }
        }
        for old_gen_id in released_gens.into_iter() {
            self.business_store()
                .cancel_generation_subscriptions(old_gen_id);
        }
        for (route_path, slot_bindings) in hub_updates.into_iter() {
            self.apply_route_slots_to_hub(&route_path, target_seq, &slot_bindings)?;
        }
        let gc_reclaimed: usize = self.gc_unreachable_generations();
        Ok(ActivationReport::new(
            target_seq,
            swapped_routes,
            unchanged_pinned_routes,
            false,
            String::new(),
            caught_up_deltas,
            gc_reclaimed,
        ))
    }

    /// Non-blockingly polls `worker` (or a previously deferred candidate) and activates at a safe frame boundary.
    ///
    /// # Arguments
    ///
    /// - `&UpdateWorkerHandle` - Running background update worker handle.
    /// - `&InteractionSafePoint` - Current frame-boundary safety probe.
    ///
    /// # Returns
    ///
    /// - `Result<Option<ActivationReport>, DynamicReleaseError>` - Report when a candidate was evaluated, or `None` when idle.
    pub fn poll_mailbox_and_activate(
        &mut self,
        worker: &UpdateWorkerHandle,
        boundary: &InteractionSafePoint,
    ) -> Result<Option<ActivationReport>, DynamicReleaseError> {
        let incoming: Option<PreparedReleaseCandidate> = worker.try_take_ready_candidate();
        let next_candidate: Option<PreparedReleaseCandidate> = match incoming {
            Some(fresh) => Some(fresh),
            None => {
                let Self {
                    deferred_candidate, ..
                } = self;
                deferred_candidate.take()
            }
        };
        let Some(candidate) = next_candidate else {
            return Ok(None);
        };
        let report: ActivationReport = self.activate_release(candidate, boundary)?;
        Ok(Some(report))
    }

    /// Dispatches a host-validated cross-route action, opening the target route pinned to its OWN dependency graph (Sec 11.2).
    ///
    /// # Arguments
    ///
    /// - `&CrossRouteAction` - Action carrying target route, action ID, origin generation, and cancellation token.
    /// - `&[String]` - Permitted host action IDs.
    /// - `&str` - Stable instance identifier for the opened target route.
    ///
    /// # Returns
    ///
    /// - `Result<RoutePinHandle, DynamicReleaseError>` - Target route's independent pinned handle.
    pub fn dispatch_cross_route_action(
        &mut self,
        action: &CrossRouteAction,
        allowed_actions: &[String],
        target_instance_id: &str,
    ) -> Result<RoutePinHandle, DynamicReleaseError> {
        if action.get_cancellation_token().load(Ordering::Acquire) {
            return Err(DynamicReleaseError::UnsafeSwapPoint(
                ERR_ACTION_CANCELLED.to_string(),
            ));
        }
        if !allowed_actions
            .iter()
            .any(|a: &String| a == action.get_action_id())
        {
            return Err(DynamicReleaseError::MissingCapability(format!(
                "{ERR_ACTION_DENIED}: {}",
                action.get_action_id()
            )));
        }
        self.open_route(target_instance_id, action.get_target_route())
    }

    /// Reclaims old release generations that are no longer active and have zero open route pins or in-flight tasks.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of reclaimed generations.
    pub fn gc_unreachable_generations(&mut self) -> usize {
        let Self {
            active_release_seq,
            generations,
            ..
        } = self;
        let active_seq: u64 = *active_release_seq;
        let to_remove: Vec<u64> = generations
            .iter()
            .filter(|(gid, gen_rec): &(&u64, &ReleaseGeneration)| {
                **gid != active_seq
                    && gen_rec.get_active_route_pins() == 0
                    && gen_rec.get_active_in_flight_tasks() == 0
            })
            .map(|(gid, _): (&u64, &ReleaseGeneration)| *gid)
            .collect();
        let removed_count: usize = to_remove.len();
        for gid in to_remove.into_iter() {
            let _: Option<ReleaseGeneration> = generations.remove(&gid);
        }
        removed_count
    }

    /// Applies a route's bound slot artifacts onto `DynamicUpdateHub` ONCE at mount or hot-swap boundary.
    ///
    /// # Arguments
    ///
    /// - `&str` - Normalized route path.
    /// - `u64` - Generation identifier holding the warmed artifacts.
    /// - `&BTreeMap<String, String>` - Logical slot key to pinned artifact key bindings.
    ///
    /// # Returns
    ///
    /// - `Result<(), DynamicReleaseError>` - `Ok(())` when every bound slot mounted cleanly.
    fn apply_route_slots_to_hub(
        &mut self,
        route: &str,
        generation_id: u64,
        slot_bindings: &BTreeMap<String, String>,
    ) -> Result<(), DynamicReleaseError> {
        let mut specs_to_apply: Vec<(String, DynamicNodeSpec)> =
            Vec::with_capacity(slot_bindings.len());
        {
            let Self {
                generations,
                sandbox_config,
                ..
            } = self;
            let gen_rec: &ReleaseGeneration = generations
                .get(&generation_id)
                .ok_or_else(|| DynamicReleaseError::RouteNotFound(route.to_string()))?;
            for (slot_key, artifact_key) in slot_bindings.iter() {
                let Some(warmed) = gen_rec.get_warmed_artifacts().get(artifact_key) else {
                    return Err(DynamicReleaseError::BrokenDependencyClosure(format!(
                        "{ERR_MISSING_SLOT_ARTIFACT}: {artifact_key}"
                    )));
                };
                let scoped_slot_id: String =
                    SlotKey::from_str_key(slot_key).scoped_for_route(route);
                let spec: DynamicNodeSpec = match warmed {
                    WarmedArtifact::Wasm(parsed) => {
                        DynamicFrameMetrics::record_module_call();
                        let entry: &str = gen_rec
                            .get_manifest()
                            .get_artifacts()
                            .get(artifact_key)
                            .map(|a: &BlobArtifact| {
                                if a.get_entrypoint().is_empty() {
                                    WASM_EXPORT_RENDER
                                } else {
                                    a.get_entrypoint().as_str()
                                }
                            })
                            .unwrap_or(WASM_EXPORT_RENDER);
                        let exec_out: WasmExecutionOutput =
                            execute_wasm_export(parsed, entry, &[0], sandbox_config).map_err(
                                |err: WasmDynamicError| {
                                    DynamicReleaseError::StorageError(err.to_string())
                                },
                            )?;
                        DynamicFrameMetrics::record_serialization();
                        exec_out.emitted_spec().cloned().ok_or_else(|| {
                            DynamicReleaseError::StorageError(ERR_DECLARATIVE_JSON.to_string())
                        })?
                    }
                    WarmedArtifact::Declarative(spec) => {
                        DynamicFrameMetrics::record_module_call();
                        spec.clone()
                    }
                    WarmedArtifact::Asset(_) => continue,
                };
                specs_to_apply.push((scoped_slot_id, spec));
            }
        }
        let Self {
            hub,
            next_hub_revision,
            ..
        } = self;
        for (scoped_slot_id, spec) in specs_to_apply.into_iter() {
            let rev: u64 = *next_hub_revision;
            *next_hub_revision = next_hub_revision.saturating_add(1);
            let mut upd: DynamicComponentUpdate =
                DynamicComponentUpdate::new(scoped_slot_id, rev, spec);
            upd.set_allow_downgrade(true);
            upd.sign();
            let _: u64 = hub
                .apply_component(upd)
                .map_err(|err: DynamicUpdateError| {
                    DynamicReleaseError::StorageError(err.to_string())
                })?;
        }
        Ok(())
    }
}