Skip to main content

euv_core/dynamic/wasm/
impl.rs

1use super::*;
2
3/// Human-readable diagnostic formatting for `WasmDynamicError`.
4impl fmt::Display for WasmDynamicError {
5    /// Formats a descriptive error string for logs and UI error boundaries.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Error variant reference.
10    /// - `&mut Formatter<'_>` - Output formatter.
11    ///
12    /// # Returns
13    ///
14    /// - `fmt::Result` - Formatting result.
15    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
16        match self {
17            Self::InvalidUrl(url) => write!(f, "invalid wasm URL: {url}"),
18            Self::NetworkOffline(url) => write!(f, "network offline while fetching {url}"),
19            Self::HttpStatus { status, url } => write!(f, "HTTP {status} downloading {url}"),
20            Self::Timeout { url, timeout_ms } => {
21                write!(f, "download timed out after {timeout_ms}ms for {url}")
22            }
23            Self::Cancelled { request_id } => write!(f, "wasm request #{request_id} was cancelled"),
24            Self::StaleResponse {
25                request_id,
26                active_request_id,
27            } => write!(
28                f,
29                "discarded stale wasm response #{request_id} (active #{active_request_id})"
30            ),
31            Self::BinaryTooLarge { actual, limit } => {
32                write!(f, "wasm binary {actual} bytes exceeds limit {limit}")
33            }
34            Self::InvalidWasmBinary(msg) => write!(f, "invalid wasm binary: {msg}"),
35            Self::ChecksumMismatch { expected, actual } => {
36                write!(
37                    f,
38                    "wasm checksum mismatch: expected {expected:#018x}, got {actual:#018x}"
39                )
40            }
41            Self::SignatureInvalid { expected, actual } => {
42                write!(
43                    f,
44                    "wasm signature invalid: expected {expected}, got {actual}"
45                )
46            }
47            Self::AbiMismatch { expected, actual } => {
48                write!(f, "wasm ABI mismatch: host v{expected}, module v{actual}")
49            }
50            Self::MissingExport(name) => write!(f, "wasm module missing required export `{name}`"),
51            Self::VersionRegression { current, incoming } => {
52                write!(
53                    f,
54                    "wasm version regression blocked: active v{current}, incoming v{incoming}"
55                )
56            }
57            Self::MemoryLimitExceeded { requested, limit } => {
58                write!(f, "wasm memory {requested} bytes exceeds limit {limit}")
59            }
60            Self::MemoryOutOfBounds {
61                addr,
62                len,
63                memory_size,
64            } => write!(
65                f,
66                "wasm memory out of bounds: [{addr}..+{len}] > {memory_size}"
67            ),
68            Self::OutOfFuel { limit } => {
69                write!(f, "wasm execution exceeded fuel budget ({limit} ops)")
70            }
71            Self::ExecutionTrap(msg) => write!(f, "wasm runtime trap: {msg}"),
72            Self::InvalidUiPayload(msg) => write!(f, "invalid wasm native UI payload: {msg}"),
73            Self::NoRollbackSnapshot => write!(f, "no prior verified wasm snapshot to roll back"),
74        }
75    }
76}
77
78/// Standard `Error` marker implementation for `WasmDynamicError`.
79impl Error for WasmDynamicError {}
80
81/// Safe production defaults for `WasmSandboxConfig`.
82impl Default for WasmSandboxConfig {
83    /// Returns balanced production sandbox ceilings (8 MiB binary, 4 MiB memory, 100k fuel, 2 retries, offline cache on).
84    ///
85    /// # Returns
86    ///
87    /// - `Self` - Default `WasmSandboxConfig`.
88    fn default() -> Self {
89        Self {
90            max_binary_bytes: WASM_DEFAULT_MAX_BINARY_BYTES,
91            max_memory_bytes: WASM_DEFAULT_MAX_MEMORY_BYTES,
92            max_fuel: WASM_DEFAULT_MAX_FUEL,
93            timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
94            max_retries: WASM_DEFAULT_MAX_RETRIES,
95            allow_offline_cache: true,
96            require_signature: false,
97        }
98    }
99}
100
101/// Scope key formatting helpers for `WasmDynamicScope`.
102impl WasmDynamicScope {
103    /// Returns a stable unique registry key identifying this scope.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Scope reference.
108    ///
109    /// # Returns
110    ///
111    /// - `String` - Scope registry key.
112    #[must_use]
113    pub fn key(&self) -> String {
114        match self {
115            Self::Partial { slot_id } => format!("partial:{slot_id}"),
116            Self::Global => "global".to_string(),
117        }
118    }
119}
120
121/// Fluent builder helpers for `WasmDownloadRequest`.
122impl WasmDownloadRequest {
123    /// Creates a scoped partial-slot `.wasm` download request.
124    ///
125    /// # Arguments
126    ///
127    /// - `String` - Source `.wasm` URL.
128    /// - `String` - Target partial slot ID.
129    /// - `u64` - Release version number.
130    ///
131    /// # Returns
132    ///
133    /// - `Self` - Configured partial download request.
134    #[must_use]
135    pub fn partial(url: String, slot_id: String, version: u64) -> Self {
136        Self::new(url, WasmDynamicScope::Partial { slot_id }, version)
137    }
138
139    /// Creates a global full-app `.wasm` download request.
140    ///
141    /// # Arguments
142    ///
143    /// - `String` - Source `.wasm` URL.
144    /// - `u64` - Release version number.
145    ///
146    /// # Returns
147    ///
148    /// - `Self` - Configured global download request.
149    #[must_use]
150    pub fn global(url: String, version: u64) -> Self {
151        Self::new(url, WasmDynamicScope::Global, version)
152    }
153
154    /// Attaches an expected FNV-1a checksum for integrity verification.
155    ///
156    /// # Arguments
157    ///
158    /// - `Self` - Source request.
159    /// - `u64` - Expected checksum.
160    ///
161    /// # Returns
162    ///
163    /// - `Self` - Updated request.
164    #[must_use]
165    pub fn with_checksum(mut self, checksum: u64) -> Self {
166        self.set_expected_checksum(checksum);
167        self
168    }
169
170    /// Attaches an expected signature tag for authenticated verification.
171    ///
172    /// # Arguments
173    ///
174    /// - `Self` - Source request.
175    /// - `String` - Expected signature string.
176    ///
177    /// # Returns
178    ///
179    /// - `Self` - Updated request.
180    #[must_use]
181    pub fn with_signature(mut self, signature: String) -> Self {
182        self.set_expected_signature(signature);
183        self
184    }
185
186    /// Allows installing a version lower than or equal to the currently mounted version.
187    ///
188    /// # Arguments
189    ///
190    /// - `Self` - Source request.
191    /// - `bool` - Downgrade permission flag.
192    ///
193    /// # Returns
194    ///
195    /// - `Self` - Updated request.
196    #[must_use]
197    pub fn with_allow_downgrade(mut self, allow: bool) -> Self {
198        self.set_allow_downgrade(allow);
199        self
200    }
201
202    /// Resolves the effective cache lookup key (`cache_key` if non-empty, otherwise `url`).
203    ///
204    /// # Arguments
205    ///
206    /// - `&Self` - Request reference.
207    ///
208    /// # Returns
209    ///
210    /// - `&str` - Effective cache key.
211    #[must_use]
212    pub fn resolved_cache_key(&self) -> &str {
213        if self.get_cache_key().is_empty() {
214            self.get_url().as_str()
215        } else {
216            self.get_cache_key().as_str()
217        }
218    }
219}
220
221/// Accessor helpers for `WasmExecutionOutput`.
222impl WasmExecutionOutput {
223    /// Returns the optional emitted partial `DynamicNodeSpec`.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Execution output reference.
228    ///
229    /// # Returns
230    ///
231    /// - `Option<&DynamicNodeSpec>` - Emitted spec reference.
232    #[must_use]
233    pub fn emitted_spec(&self) -> Option<&DynamicNodeSpec> {
234        let Self { emitted_spec, .. } = self;
235        emitted_spec.as_ref()
236    }
237
238    /// Returns the optional emitted global `DynamicUpdateBundle`.
239    ///
240    /// # Arguments
241    ///
242    /// - `&Self` - Execution output reference.
243    ///
244    /// # Returns
245    ///
246    /// - `Option<&DynamicUpdateBundle>` - Emitted bundle reference.
247    #[must_use]
248    pub fn emitted_bundle(&self) -> Option<&DynamicUpdateBundle> {
249        let Self { emitted_bundle, .. } = self;
250        emitted_bundle.as_ref()
251    }
252}
253
254/// Accessor helpers for `WasmMountedSnapshot`.
255impl WasmMountedSnapshot {
256    /// Returns the mounted partial spec if present.
257    ///
258    /// # Arguments
259    ///
260    /// - `&Self` - Snapshot reference.
261    ///
262    /// # Returns
263    ///
264    /// - `Option<&DynamicNodeSpec>` - Mounted spec reference.
265    #[must_use]
266    pub fn spec_ref(&self) -> Option<&DynamicNodeSpec> {
267        let Self { spec, .. } = self;
268        spec.as_ref()
269    }
270
271    /// Returns the mounted global bundle if present.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Snapshot reference.
276    ///
277    /// # Returns
278    ///
279    /// - `Option<&DynamicUpdateBundle>` - Mounted bundle reference.
280    #[must_use]
281    pub fn bundle_ref(&self) -> Option<&DynamicUpdateBundle> {
282        let Self { bundle, .. } = self;
283        bundle.as_ref()
284    }
285}
286
287/// Spec-compliant WebAssembly binary encoder methods for `WasmModuleBuilder`.
288impl WasmModuleBuilder {
289    /// Starts building a partial-slot `.wasm` module emitting `spec` through `env::euv_emit_ui`.
290    ///
291    /// # Arguments
292    ///
293    /// - `&DynamicNodeSpec` - Primary native UI subtree specification.
294    ///
295    /// # Returns
296    ///
297    /// - `Self` - Configured `.wasm` builder.
298    #[must_use]
299    pub fn partial_spec(spec: &DynamicNodeSpec) -> Self {
300        let json: String = to_string(spec).unwrap_or_else(|_| "{}".to_string());
301        Self {
302            abi_version: WASM_ABI_VERSION,
303            export_render: true,
304            is_global_bundle: false,
305            ui_payload_json: json,
306            alt_ui_payload_json: String::new(),
307            log_message: String::new(),
308            fault: WasmFaultKind::None,
309            custom_meta: Vec::new(),
310        }
311    }
312
313    /// Starts building a global full-app `.wasm` module emitting `bundle` through `env::euv_emit_bundle`.
314    ///
315    /// # Arguments
316    ///
317    /// - `&DynamicUpdateBundle` - Full-app dynamic bundle specification.
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Configured global `.wasm` builder.
322    #[must_use]
323    pub fn global_bundle(bundle: &DynamicUpdateBundle) -> Self {
324        let json: String = to_string(bundle).unwrap_or_else(|_| "{}".to_string());
325        Self {
326            abi_version: WASM_ABI_VERSION,
327            export_render: true,
328            is_global_bundle: true,
329            ui_payload_json: json,
330            alt_ui_payload_json: String::new(),
331            log_message: String::new(),
332            fault: WasmFaultKind::None,
333            custom_meta: Vec::new(),
334        }
335    }
336
337    /// Attaches an alternate interactive UI spec rendered whenever `euv_render(state)` receives a non-zero state.
338    ///
339    /// # Arguments
340    ///
341    /// - `Self` - Source builder.
342    /// - `&DynamicNodeSpec` - Alternate interactive state UI spec.
343    ///
344    /// # Returns
345    ///
346    /// - `Self` - Updated builder.
347    #[must_use]
348    pub fn with_alt_spec(mut self, alt: &DynamicNodeSpec) -> Self {
349        let json: String = to_string(alt).unwrap_or_else(|_| "{}".to_string());
350        self.set_alt_ui_payload_json(json);
351        self
352    }
353
354    /// Attaches an alternate global `DynamicUpdateBundle` JSON payload emitted when `euv_on_event` toggles state.
355    ///
356    /// # Arguments
357    ///
358    /// - `Self` - Source builder.
359    /// - `&DynamicUpdateBundle` - Alternate global bundle for odd state ticks.
360    ///
361    /// # Returns
362    ///
363    /// - `Self` - Updated builder.
364    #[must_use]
365    pub fn with_alt_bundle(mut self, bundle: &DynamicUpdateBundle) -> Self {
366        let json: String = bundle.to_json().unwrap_or_default();
367        self.set_alt_ui_payload_json(json);
368        self
369    }
370
371    /// Attaches a diagnostic log message emitted via `env::euv_log` during render.
372    ///
373    /// # Arguments
374    ///
375    /// - `Self` - Source builder.
376    /// - `String` - Log line text.
377    ///
378    /// # Returns
379    ///
380    /// - `Self` - Updated builder.
381    #[must_use]
382    pub fn with_log(mut self, message: String) -> Self {
383        self.set_log_message(message);
384        self
385    }
386
387    /// Overrides the reported ABI version (used to test ABI mismatch rejection).
388    ///
389    /// # Arguments
390    ///
391    /// - `Self` - Source builder.
392    /// - `u32` - ABI version returned by `euv_abi_version`.
393    ///
394    /// # Returns
395    ///
396    /// - `Self` - Updated builder.
397    #[must_use]
398    pub fn with_abi_version(mut self, abi: u32) -> Self {
399        self.set_abi_version(abi);
400        self
401    }
402
403    /// Omits the `euv_render` export (used to test missing export rejection).
404    ///
405    /// # Arguments
406    ///
407    /// - `Self` - Source builder.
408    ///
409    /// # Returns
410    ///
411    /// - `Self` - Updated builder.
412    #[must_use]
413    pub fn without_render_export(mut self) -> Self {
414        self.set_export_render(false);
415        self
416    }
417
418    /// Compiles a deterministic sandbox fault (`InfiniteLoopOutOfFuel` / `ExecutionTrap`) into `euv_render`.
419    ///
420    /// # Arguments
421    ///
422    /// - `Self` - Source builder.
423    /// - `WasmFaultKind` - Fault behavior to compile.
424    ///
425    /// # Returns
426    ///
427    /// - `Self` - Updated builder.
428    #[must_use]
429    pub fn with_fault(mut self, fault: WasmFaultKind) -> Self {
430        self.set_fault(fault);
431        self
432    }
433
434    /// Appends a WebAssembly section with length prefix into `out`.
435    ///
436    /// # Arguments
437    ///
438    /// - `&mut Vec<u8>` - Destination binary stream.
439    /// - `u8` - WASM section ID.
440    /// - `&[u8]` - Encoded section payload bytes.
441    fn push_section(out: &mut Vec<u8>, sec_id: u8, payload: &[u8]) {
442        out.push(sec_id);
443        write_uleb128(out, payload.len() as u32);
444        out.extend_from_slice(payload);
445    }
446
447    /// Encodes a UTF-8 WASM identifier name into `out`.
448    ///
449    /// # Arguments
450    ///
451    /// - `&mut Vec<u8>` - Destination byte vector.
452    /// - `&str` - Identifier text.
453    fn push_name(out: &mut Vec<u8>, name: &str) {
454        write_uleb128(out, name.len() as u32);
455        out.extend_from_slice(name.as_bytes());
456    }
457
458    /// Emits a complete spec-compliant executable `.wasm` binary buffer.
459    ///
460    /// # Arguments
461    ///
462    /// - `&Self` - Configured builder.
463    ///
464    /// # Returns
465    ///
466    /// - `Vec<u8>` - Valid WebAssembly MVP binary bytes (`\0asm\x01\0\0\0...`).
467    #[must_use]
468    pub fn build(&self) -> Vec<u8> {
469        let mut out: Vec<u8> = Vec::with_capacity(512);
470        out.extend_from_slice(WASM_BINARY_MAGIC);
471        out.extend_from_slice(WASM_BINARY_VERSION);
472        let mut type_sec: Vec<u8> = Vec::new();
473        write_uleb128(&mut type_sec, 3);
474        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 2, WASM_VALTYPE_I32, WASM_VALTYPE_I32, 0]);
475        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 1, WASM_VALTYPE_I32, 1, WASM_VALTYPE_I32]);
476        type_sec.extend_from_slice(&[WASM_FUNCTYPE_TAG, 0, 1, WASM_VALTYPE_I32]);
477        Self::push_section(&mut out, WASM_SEC_TYPE, &type_sec);
478        let mut imp_sec: Vec<u8> = Vec::new();
479        write_uleb128(&mut imp_sec, 2);
480        let emit_name: &str = if self.get_is_global_bundle() {
481            WASM_IMPORT_EMIT_BUNDLE
482        } else {
483            WASM_IMPORT_EMIT_UI
484        };
485        Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
486        Self::push_name(&mut imp_sec, emit_name);
487        imp_sec.push(0x00);
488        write_uleb128(&mut imp_sec, 0);
489        Self::push_name(&mut imp_sec, WASM_IMPORT_MODULE_ENV);
490        Self::push_name(&mut imp_sec, WASM_IMPORT_LOG);
491        imp_sec.push(0x00);
492        write_uleb128(&mut imp_sec, 0);
493        Self::push_section(&mut out, WASM_SEC_IMPORT, &imp_sec);
494        let mut func_sec: Vec<u8> = Vec::new();
495        write_uleb128(&mut func_sec, 3);
496        write_uleb128(&mut func_sec, 1);
497        write_uleb128(&mut func_sec, 1);
498        write_uleb128(&mut func_sec, 2);
499        Self::push_section(&mut out, WASM_SEC_FUNCTION, &func_sec);
500        let payload1: &[u8] = self.get_ui_payload_json().as_bytes();
501        let payload2: &[u8] = self.get_alt_ui_payload_json().as_bytes();
502        let log_bytes: &[u8] = self.get_log_message().as_bytes();
503        let ptr1: i32 = 256;
504        let ptr2: i32 = ptr1 + (payload1.len() as i32) + 16;
505        let ptr_log: i32 = ptr2 + (payload2.len() as i32) + 16;
506        let total_mem_needed: usize = (ptr_log as usize) + log_bytes.len() + 256;
507        let min_pages: u32 = ((total_mem_needed / WASM_PAGE_BYTES) as u32) + 1;
508        let mut mem_sec: Vec<u8> = Vec::new();
509        write_uleb128(&mut mem_sec, 1);
510        mem_sec.push(0x00);
511        write_uleb128(&mut mem_sec, min_pages);
512        Self::push_section(&mut out, WASM_SEC_MEMORY, &mem_sec);
513        let mut exp_sec: Vec<u8> = Vec::new();
514        let exp_count: u32 = if self.get_export_render() { 3 } else { 2 };
515        write_uleb128(&mut exp_sec, exp_count);
516        if self.get_export_render() {
517            Self::push_name(&mut exp_sec, WASM_EXPORT_RENDER);
518            exp_sec.push(0x00);
519            write_uleb128(&mut exp_sec, 2);
520        }
521        Self::push_name(&mut exp_sec, WASM_EXPORT_ON_EVENT);
522        exp_sec.push(0x00);
523        write_uleb128(&mut exp_sec, 3);
524        Self::push_name(&mut exp_sec, WASM_EXPORT_ABI);
525        exp_sec.push(0x00);
526        write_uleb128(&mut exp_sec, 4);
527        Self::push_section(&mut out, WASM_SEC_EXPORT, &exp_sec);
528        let mut render_body: Vec<u8> = vec![0x00];
529        match self.get_fault() {
530            WasmFaultKind::InfiniteLoopOutOfFuel => {
531                render_body.push(OP_LOOP);
532                render_body.push(0x40);
533                render_body.push(OP_BR);
534                write_uleb128(&mut render_body, 0);
535                render_body.push(OP_END);
536                render_body.push(OP_I32_CONST);
537                write_sleb128(&mut render_body, 0);
538                render_body.push(OP_END);
539            }
540            WasmFaultKind::ExecutionTrap => {
541                render_body.push(OP_UNREACHABLE);
542                render_body.push(OP_END);
543            }
544            _ => {
545                if !payload2.is_empty() {
546                    render_body.push(OP_LOCAL_GET);
547                    write_uleb128(&mut render_body, 0);
548                    render_body.push(OP_IF);
549                    render_body.push(0x40);
550                    render_body.push(OP_I32_CONST);
551                    write_sleb128(&mut render_body, ptr2);
552                    render_body.push(OP_I32_CONST);
553                    write_sleb128(&mut render_body, payload2.len() as i32);
554                    render_body.push(OP_CALL);
555                    write_uleb128(&mut render_body, 0);
556                    render_body.push(OP_ELSE);
557                    render_body.push(OP_I32_CONST);
558                    write_sleb128(&mut render_body, ptr1);
559                    render_body.push(OP_I32_CONST);
560                    write_sleb128(&mut render_body, payload1.len() as i32);
561                    render_body.push(OP_CALL);
562                    write_uleb128(&mut render_body, 0);
563                    render_body.push(OP_END);
564                } else {
565                    render_body.push(OP_I32_CONST);
566                    write_sleb128(&mut render_body, ptr1);
567                    render_body.push(OP_I32_CONST);
568                    write_sleb128(&mut render_body, payload1.len() as i32);
569                    render_body.push(OP_CALL);
570                    write_uleb128(&mut render_body, 0);
571                }
572                if !log_bytes.is_empty() {
573                    render_body.push(OP_I32_CONST);
574                    write_sleb128(&mut render_body, ptr_log);
575                    render_body.push(OP_I32_CONST);
576                    write_sleb128(&mut render_body, log_bytes.len() as i32);
577                    render_body.push(OP_CALL);
578                    write_uleb128(&mut render_body, 1);
579                }
580                render_body.push(OP_I32_CONST);
581                write_sleb128(&mut render_body, 1);
582                render_body.push(OP_END);
583            }
584        }
585        let mut event_body: Vec<u8> = vec![0x00];
586        event_body.push(OP_LOCAL_GET);
587        write_uleb128(&mut event_body, 0);
588        event_body.push(OP_I32_CONST);
589        write_sleb128(&mut event_body, 1);
590        event_body.push(OP_I32_ADD);
591        event_body.push(OP_END);
592        let mut abi_body: Vec<u8> = vec![0x00];
593        abi_body.push(OP_I32_CONST);
594        write_sleb128(&mut abi_body, self.get_abi_version() as i32);
595        abi_body.push(OP_END);
596        let mut code_sec: Vec<u8> = Vec::new();
597        write_uleb128(&mut code_sec, 3);
598        for body in [&render_body, &event_body, &abi_body] {
599            write_uleb128(&mut code_sec, body.len() as u32);
600            code_sec.extend_from_slice(body);
601        }
602        Self::push_section(&mut out, WASM_SEC_CODE, &code_sec);
603        let mut data_sec: Vec<u8> = Vec::new();
604        let mut seg_count: u32 = 1;
605        if !payload2.is_empty() {
606            seg_count += 1;
607        }
608        if !log_bytes.is_empty() {
609            seg_count += 1;
610        }
611        write_uleb128(&mut data_sec, seg_count);
612        Self::push_data_segment(&mut data_sec, ptr1, payload1);
613        if !payload2.is_empty() {
614            Self::push_data_segment(&mut data_sec, ptr2, payload2);
615        }
616        if !log_bytes.is_empty() {
617            Self::push_data_segment(&mut data_sec, ptr_log, log_bytes);
618        }
619        Self::push_section(&mut out, WASM_SEC_DATA, &data_sec);
620        if !self.get_custom_meta().is_empty() {
621            let mut custom_sec: Vec<u8> = Vec::new();
622            Self::push_name(&mut custom_sec, WASM_CUSTOM_META_SECTION);
623            custom_sec.extend_from_slice(self.get_custom_meta().as_slice());
624            Self::push_section(&mut out, WASM_SEC_CUSTOM, &custom_sec);
625        }
626        out
627    }
628
629    /// Appends one active WASM linear memory data segment into `out`.
630    ///
631    /// # Arguments
632    ///
633    /// - `&mut Vec<u8>` - Data section accumulator.
634    /// - `i32` - Linear memory base offset.
635    /// - `&[u8]` - Data bytes to initialize.
636    fn push_data_segment(out: &mut Vec<u8>, offset: i32, data: &[u8]) {
637        write_uleb128(out, 0);
638        out.push(OP_I32_CONST);
639        write_sleb128(out, offset);
640        out.push(OP_END);
641        write_uleb128(out, data.len() as u32);
642        out.extend_from_slice(data);
643    }
644}
645
646/// Registry management methods for `RegistryWasmFetcher`.
647impl RegistryWasmFetcher {
648    /// Registers a `.wasm` payload under `url` with an ETag and optional fault behavior.
649    ///
650    /// # Arguments
651    ///
652    /// - `&Self` - Registry fetcher reference.
653    /// - `String` - Target bundle URL.
654    /// - `Vec<u8>` - Raw `.wasm` bytes.
655    /// - `String` - ETag identifier.
656    /// - `WasmFaultKind` - Fault mode (`WasmFaultKind::None` for healthy delivery).
657    pub fn register(&self, url: String, bytes: Vec<u8>, etag: String, fault: WasmFaultKind) {
658        let Self { records, .. } = self;
659        if let Ok(mut guard) = records.try_borrow_mut() {
660            let _: Option<RegistryWasmRecord> =
661                guard.insert(url, RegistryWasmRecord::new(bytes, etag, fault));
662        }
663    }
664
665    /// Toggles simulated global network offline state.
666    ///
667    /// # Arguments
668    ///
669    /// - `&Self` - Registry fetcher reference.
670    /// - `bool` - When `true`, all fetch calls return `NetworkOffline`.
671    pub fn set_offline(&self, is_offline: bool) {
672        let Self { offline, .. } = self;
673        if let Ok(mut guard) = offline.try_borrow_mut() {
674            *guard = is_offline;
675        }
676    }
677
678    /// Returns whether simulated offline mode is currently enabled.
679    ///
680    /// # Arguments
681    ///
682    /// - `&Self` - Registry fetcher reference.
683    ///
684    /// # Returns
685    ///
686    /// - `bool` - Offline flag.
687    #[must_use]
688    pub fn is_offline(&self) -> bool {
689        let Self { offline, .. } = self;
690        offline
691            .try_borrow()
692            .map(|g: Ref<'_, bool>| *g)
693            .unwrap_or(false)
694    }
695}
696
697/// `WasmFetcher` implementation serving verified `.wasm` payloads and deterministic fault cases across all 7 platforms.
698impl WasmFetcher for RegistryWasmFetcher {
699    /// Fetches a registered `.wasm` module with realistic chunked progress notifications and fault injection.
700    ///
701    /// # Arguments
702    ///
703    /// - `&Self` - Registry fetcher reference.
704    /// - `&WasmDownloadRequest` - Download request.
705    /// - `u32` - Retry attempt number.
706    /// - `&mut dyn FnMut(u64, u64)` - Streaming progress callback.
707    ///
708    /// # Returns
709    ///
710    /// - `Result<WasmFetchedPayload, WasmDynamicError>` - Downloaded payload or injected transport error.
711    fn fetch(
712        &self,
713        request: &WasmDownloadRequest,
714        attempt: u32,
715        on_progress: &mut dyn FnMut(u64, u64),
716    ) -> Result<WasmFetchedPayload, WasmDynamicError> {
717        if self.is_offline() {
718            return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
719        }
720        let url_str: &str = request.get_url().as_str();
721        if url_str.starts_with(WASM_SCHEME_HTTP) || url_str.starts_with(WASM_SCHEME_FILE) {
722            return HttpWasmFetcher::default().fetch(request, attempt, on_progress);
723        }
724        let Self { records, .. } = self;
725        let rec_opt: Result<(Vec<u8>, String, WasmFaultKind), WasmDynamicError> = {
726            let guard: Ref<'_, HashMap<String, RegistryWasmRecord>> = records
727                .try_borrow()
728                .map_err(|_| WasmDynamicError::HttpStatus {
729                    status: 404,
730                    url: request.get_url().clone(),
731                })?;
732            let rec: &RegistryWasmRecord =
733                guard
734                    .get(request.get_url())
735                    .ok_or_else(|| WasmDynamicError::HttpStatus {
736                        status: 404,
737                        url: request.get_url().clone(),
738                    })?;
739            match rec.get_fault() {
740                WasmFaultKind::NetworkOffline => {
741                    return Err(WasmDynamicError::NetworkOffline(request.get_url().clone()));
742                }
743                WasmFaultKind::TimeoutOnceThenSucceed if attempt == 0 => {
744                    return Err(WasmDynamicError::Timeout {
745                        url: request.get_url().clone(),
746                        timeout_ms: WASM_DEFAULT_TIMEOUT_MS,
747                    });
748                }
749                WasmFaultKind::Http500 => {
750                    return Err(WasmDynamicError::HttpStatus {
751                        status: 500,
752                        url: request.get_url().clone(),
753                    });
754                }
755                fault => Ok((rec.get_bytes().clone(), rec.get_etag().clone(), fault)),
756            }
757        };
758        let (mut bytes, etag, fault): (Vec<u8>, String, WasmFaultKind) = rec_opt?;
759        if fault == WasmFaultKind::TamperedChecksum && !bytes.is_empty() {
760            let last_idx: usize = bytes.len() - 1;
761            bytes[last_idx] ^= 0xFF;
762        }
763        let total: u64 = bytes.len() as u64;
764        on_progress(total / 2, total);
765        on_progress(total, total);
766        let mut payload: WasmFetchedPayload = WasmFetchedPayload::new(bytes);
767        payload.set_etag(etag);
768        Ok(payload)
769    }
770}
771
772/// Pure-std `http://` and `file://` transport implementation for `HttpWasmFetcher`.
773impl WasmFetcher for HttpWasmFetcher {
774    /// Downloads a `.wasm` binary over real TCP HTTP or local `file://` path with socket timeout and progress streaming.
775    ///
776    /// # Arguments
777    ///
778    /// - `&Self` - HTTP fetcher reference.
779    /// - `&WasmDownloadRequest` - Target download descriptor.
780    /// - `u32` - Retry attempt counter.
781    /// - `&mut dyn FnMut(u64, u64)` - Byte progress callback.
782    ///
783    /// # Returns
784    ///
785    /// - `Result<WasmFetchedPayload, WasmDynamicError>` - Downloaded bytes or typed transport error.
786    fn fetch(
787        &self,
788        request: &WasmDownloadRequest,
789        _attempt: u32,
790        on_progress: &mut dyn FnMut(u64, u64),
791    ) -> Result<WasmFetchedPayload, WasmDynamicError> {
792        let url: &str = request.get_url().as_str();
793        #[cfg(not(target_arch = "wasm32"))]
794        {
795            if let Some(path) = url.strip_prefix(WASM_SCHEME_FILE) {
796                let bytes: Vec<u8> = fs::read(path).map_err(|_| WasmDynamicError::HttpStatus {
797                    status: 404,
798                    url: url.to_string(),
799                })?;
800                let total: u64 = bytes.len() as u64;
801                on_progress(total, total);
802                return Ok(WasmFetchedPayload::new(bytes));
803            }
804            if let Some(rest) = url.strip_prefix(WASM_SCHEME_HTTP) {
805                let (host_port, req_path): (&str, String) = match rest.find('/') {
806                    Some(idx) => (&rest[..idx], rest[idx..].to_string()),
807                    None => (rest, "/".to_string()),
808                };
809                let connect_target: String = if host_port.contains(':') {
810                    host_port.to_string()
811                } else {
812                    format!("{host_port}:80")
813                };
814                let timeout_ms: u64 = self.get_timeout_ms().max(1_000);
815                let dur: Duration = Duration::from_millis(timeout_ms);
816                let addr: SocketAddr = match connect_target.to_socket_addrs() {
817                    Ok(mut it) => it.next(),
818                    Err(_) => None,
819                }
820                .ok_or_else(|| WasmDynamicError::NetworkOffline(url.to_string()))?;
821                let mut stream: TcpStream =
822                    TcpStream::connect_timeout(&addr, dur).map_err(|_| {
823                        WasmDynamicError::Timeout {
824                            url: url.to_string(),
825                            timeout_ms,
826                        }
827                    })?;
828                let _: Result<(), io::Error> = stream.set_read_timeout(Some(dur));
829                let _: Result<(), io::Error> = stream.set_write_timeout(Some(dur));
830                let req_str: String = format!(
831                    "GET {req_path} HTTP/1.1\r\nHost: {host_port}\r\nConnection: close\r\nAccept: application/wasm\r\n\r\n"
832                );
833                stream
834                    .write_all(req_str.as_bytes())
835                    .map_err(|_| WasmDynamicError::NetworkOffline(url.to_string()))?;
836                let mut raw: Vec<u8> = Vec::new();
837                let mut chunk: [u8; 4096] = [0; 4096];
838                loop {
839                    match stream.read(&mut chunk) {
840                        Ok(0) => break,
841                        Ok(n) => {
842                            raw.extend_from_slice(&chunk[..n]);
843                            on_progress(raw.len() as u64, 0);
844                        }
845                        Err(_) => {
846                            return Err(WasmDynamicError::Timeout {
847                                url: url.to_string(),
848                                timeout_ms,
849                            });
850                        }
851                    }
852                }
853                let sep_pos: usize = raw
854                    .windows(4)
855                    .position(|w: &[u8]| w == b"\r\n\r\n")
856                    .ok_or_else(|| {
857                        WasmDynamicError::InvalidWasmBinary("malformed HTTP response".to_string())
858                    })?;
859                let header_str: &str = from_utf8(&raw[..sep_pos]).unwrap_or("");
860                let status_code: u16 = header_str
861                    .lines()
862                    .next()
863                    .and_then(|line: &str| line.split_whitespace().nth(1))
864                    .and_then(|code: &str| code.parse::<u16>().ok())
865                    .unwrap_or(500);
866                if !(200..300).contains(&status_code) {
867                    return Err(WasmDynamicError::HttpStatus {
868                        status: status_code,
869                        url: url.to_string(),
870                    });
871                }
872                let body: Vec<u8> = raw[sep_pos + 4..].to_vec();
873                on_progress(body.len() as u64, body.len() as u64);
874                return Ok(WasmFetchedPayload::new(body));
875            }
876            Err(WasmDynamicError::InvalidUrl(url.to_string()))
877        }
878        #[cfg(target_arch = "wasm32")]
879        {
880            let _: &mut dyn FnMut(u64, u64) = on_progress;
881            Err(WasmDynamicError::NetworkOffline(url.to_string()))
882        }
883    }
884}
885
886/// Complete partial & global dynamic `.wasm` lifecycle orchestration for `WasmDynamicManager`.
887impl WasmDynamicManager {
888    /// Creates a `WasmDynamicManager` bound to `hub` and `fetcher` with `config`.
889    ///
890    /// # Arguments
891    ///
892    /// - `DynamicUpdateHub` - Target native scene dynamic update hub.
893    /// - `Rc<dyn WasmFetcher>` - Transport fetcher for `.wasm` downloads.
894    /// - `WasmSandboxConfig` - Sandbox limits and retry/cache configuration.
895    ///
896    /// # Returns
897    ///
898    /// - `Self` - Initialized dynamic WASM manager.
899    #[must_use]
900    pub fn new(
901        hub: DynamicUpdateHub,
902        fetcher: Rc<dyn WasmFetcher>,
903        config: WasmSandboxConfig,
904    ) -> Self {
905        Self {
906            inner: Rc::new(RefCell::new(WasmDynamicManagerState {
907                hub,
908                fetcher,
909                config,
910                next_request_id: 0,
911                active_request_ids: HashMap::new(),
912                cache: HashMap::new(),
913                parsed_cache: HashMap::new(),
914                partial_stacks: HashMap::new(),
915                global_stack: Vec::new(),
916                state_signals: HashMap::new(),
917                global_version_signal: Signal::new_detached(0),
918                telemetry_signal: Signal::new_detached(WasmDynamicTelemetry::default()),
919                last_logs: Signal::new_detached(Vec::new()),
920            })),
921        }
922    }
923
924    /// Returns the reactive `WasmLoadState` signal for `scope`.
925    ///
926    /// # Arguments
927    ///
928    /// - `&Self` - Manager reference.
929    /// - `&WasmDynamicScope` - Target partial slot or global scope.
930    ///
931    /// # Returns
932    ///
933    /// - `Signal<WasmLoadState>` - Live reactive lifecycle signal.
934    #[must_use]
935    pub fn state_signal(&self, scope: &WasmDynamicScope) -> Signal<WasmLoadState> {
936        let key: String = scope.key();
937        let Self { inner } = self;
938        if let Ok(mut guard) = inner.try_borrow_mut() {
939            return *guard
940                .state_signals
941                .entry(key)
942                .or_insert_with(|| Signal::new_detached(WasmLoadState::Idle));
943        }
944        Signal::new_detached(WasmLoadState::Idle)
945    }
946
947    /// Returns the reactive global WASM active version signal (`0` = built-in native shell).
948    ///
949    /// # Arguments
950    ///
951    /// - `&Self` - Manager reference.
952    ///
953    /// # Returns
954    ///
955    /// - `Signal<u64>` - Global active version signal.
956    #[must_use]
957    pub fn global_version_signal(&self) -> Signal<u64> {
958        let Self { inner } = self;
959        inner
960            .try_borrow()
961            .map(|g: Ref<'_, WasmDynamicManagerState>| g.global_version_signal)
962            .unwrap_or_else(|_| Signal::new_detached(0))
963    }
964
965    /// Returns the reactive `WasmDynamicTelemetry` signal.
966    ///
967    /// # Arguments
968    ///
969    /// - `&Self` - Manager reference.
970    ///
971    /// # Returns
972    ///
973    /// - `Signal<WasmDynamicTelemetry>` - Cumulative telemetry signal.
974    #[must_use]
975    pub fn telemetry(&self) -> Signal<WasmDynamicTelemetry> {
976        let Self { inner } = self;
977        inner
978            .try_borrow()
979            .map(|g: Ref<'_, WasmDynamicManagerState>| g.telemetry_signal)
980            .unwrap_or_else(|_| Signal::new_detached(WasmDynamicTelemetry::default()))
981    }
982
983    /// Returns the reactive signal carrying diagnostic logs from the last executed WASM module.
984    ///
985    /// # Arguments
986    ///
987    /// - `&Self` - Manager reference.
988    ///
989    /// # Returns
990    ///
991    /// - `Signal<Vec<String>>` - Diagnostic log lines signal.
992    #[must_use]
993    pub fn last_logs(&self) -> Signal<Vec<String>> {
994        let Self { inner } = self;
995        inner
996            .try_borrow()
997            .map(|g: Ref<'_, WasmDynamicManagerState>| g.last_logs)
998            .unwrap_or_else(|_| Signal::new_detached(Vec::new()))
999    }
1000
1001    /// Returns the number of verified cached `.wasm` entries.
1002    ///
1003    /// # Arguments
1004    ///
1005    /// - `&Self` - Manager reference.
1006    ///
1007    /// # Returns
1008    ///
1009    /// - `usize` - Cached module count.
1010    #[must_use]
1011    pub fn cache_len(&self) -> usize {
1012        let Self { inner } = self;
1013        inner
1014            .try_borrow()
1015            .map(|g: Ref<'_, WasmDynamicManagerState>| g.cache.len())
1016            .unwrap_or(0)
1017    }
1018
1019    /// Cancels any active request for `scope`, advancing its generation ID so stale responses are discarded.
1020    ///
1021    /// # Arguments
1022    ///
1023    /// - `&Self` - Manager reference.
1024    /// - `&WasmDynamicScope` - Scope to cancel.
1025    ///
1026    /// # Returns
1027    ///
1028    /// - `u64` - Newly allocated cancellation generation ID.
1029    pub fn cancel_scope(&self, scope: &WasmDynamicScope) -> u64 {
1030        let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1031        let key: String = scope.key();
1032        let Self { inner } = self;
1033        let next_id: u64 = if let Ok(mut guard) = inner.try_borrow_mut() {
1034            guard.next_request_id = guard.next_request_id.saturating_add(1);
1035            let id: u64 = guard.next_request_id;
1036            let _: Option<u64> = guard.active_request_ids.insert(key, id);
1037            id
1038        } else {
1039            0
1040        };
1041        let _: bool = state_sig.set(WasmLoadState::Failed(WasmDynamicError::Cancelled {
1042            request_id: next_id,
1043        }));
1044        next_id
1045    }
1046
1047    /// Downloads, verifies, compiles, executes in sandbox, and natively mounts a partial or global `.wasm` module.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// - `&Self` - Manager reference.
1052    /// - `WasmDownloadRequest` - Target URL, scope, version, checksum, and signature policy.
1053    /// - `&str` - Signing key used when verifying `expected_signature`.
1054    ///
1055    /// # Returns
1056    ///
1057    /// - `Result<u64, WasmDynamicError>` - Mounted version number on success, or typed error (with automatic global LKG rollback).
1058    pub fn load_and_mount(
1059        &self,
1060        request: WasmDownloadRequest,
1061        signing_key: &str,
1062    ) -> Result<u64, WasmDynamicError> {
1063        let url_str: &str = request.get_url().trim();
1064        let valid_scheme: bool = url_str.starts_with("https://")
1065            || url_str.starts_with(WASM_SCHEME_HTTP)
1066            || url_str.starts_with("euv-cdn://")
1067            || url_str.starts_with(WASM_SCHEME_FILE);
1068        if url_str.is_empty() || !valid_scheme {
1069            let err: WasmDynamicError = WasmDynamicError::InvalidUrl(request.get_url().clone());
1070            self.record_failure(request.get_scope(), &err);
1071            return Err(err);
1072        }
1073        let scope: WasmDynamicScope = request.get_scope().clone();
1074        let scope_key: String = scope.key();
1075        let (req_id, config, fetcher, active_ver, state_sig): (
1076            u64,
1077            WasmSandboxConfig,
1078            Rc<dyn WasmFetcher>,
1079            u64,
1080            Signal<WasmLoadState>,
1081        ) = {
1082            let Self { inner } = self;
1083            let mut guard: RefMut<'_, WasmDynamicManagerState> = inner
1084                .try_borrow_mut()
1085                .map_err(|_| WasmDynamicError::ExecutionTrap("manager re-entrancy".to_string()))?;
1086            let sig: Signal<WasmLoadState> = *guard
1087                .state_signals
1088                .entry(scope_key.clone())
1089                .or_insert_with(|| Signal::new_detached(WasmLoadState::Idle));
1090            guard.next_request_id = guard.next_request_id.saturating_add(1);
1091            let id: u64 = guard.next_request_id;
1092            let _: Option<u64> = guard.active_request_ids.insert(scope_key.clone(), id);
1093            let cur_v: u64 = match &scope {
1094                WasmDynamicScope::Partial { slot_id } => guard
1095                    .partial_stacks
1096                    .get(slot_id)
1097                    .and_then(|s: &Vec<WasmMountedSnapshot>| s.last())
1098                    .map(WasmMountedSnapshot::get_version)
1099                    .unwrap_or(0),
1100                WasmDynamicScope::Global => guard
1101                    .global_stack
1102                    .last()
1103                    .map(WasmMountedSnapshot::get_version)
1104                    .unwrap_or(0),
1105            };
1106            let _: bool = guard
1107                .telemetry_signal
1108                .update(|t: &mut WasmDynamicTelemetry| {
1109                    t.downloads_started = t.downloads_started.saturating_add(1);
1110                });
1111            (id, guard.config, guard.fetcher.clone(), cur_v, sig)
1112        };
1113        if !request.get_allow_downgrade() && active_ver > 0 && request.get_version() <= active_ver {
1114            let err: WasmDynamicError = WasmDynamicError::VersionRegression {
1115                current: active_ver,
1116                incoming: request.get_version(),
1117            };
1118            self.record_failure(&scope, &err);
1119            return Err(err);
1120        }
1121        if state_sig.has_subscribers() {
1122            let _: bool = state_sig.set(WasmLoadState::Downloading {
1123                received_bytes: 0,
1124                total_bytes: 0,
1125            });
1126        }
1127        let (fetched, cached_parsed_opt): (WasmFetchedShare, Option<Rc<WasmParsedModule>>) =
1128            match self.fetch_with_retry(&request, config, &fetcher, state_sig) {
1129                Ok(res) => res,
1130                Err(err) => {
1131                    self.record_failure(&scope, &err);
1132                    return Err(err);
1133                }
1134            };
1135        let current_active_id: u64 = self.active_request_id(&scope_key);
1136        if current_active_id != req_id {
1137            let err: WasmDynamicError = WasmDynamicError::StaleResponse {
1138                request_id: req_id,
1139                active_request_id: current_active_id,
1140            };
1141            return Err(err);
1142        }
1143        if state_sig.has_subscribers() {
1144            let _: bool = state_sig.set(WasmLoadState::Verifying);
1145        }
1146        let raw_bytes: &[u8] = fetched.bytes.as_slice();
1147        if raw_bytes.len() > config.get_max_binary_bytes() {
1148            let err: WasmDynamicError = WasmDynamicError::BinaryTooLarge {
1149                actual: raw_bytes.len(),
1150                limit: config.get_max_binary_bytes(),
1151            };
1152            self.record_failure(&scope, &err);
1153            return Err(err);
1154        }
1155        let computed_checksum: u64 = compute_wasm_checksum(raw_bytes);
1156        if request.get_expected_checksum() != 0
1157            && computed_checksum != request.get_expected_checksum()
1158        {
1159            let err: WasmDynamicError = WasmDynamicError::ChecksumMismatch {
1160                expected: request.get_expected_checksum(),
1161                actual: computed_checksum,
1162            };
1163            self.record_failure(&scope, &err);
1164            return Err(err);
1165        }
1166        if config.get_require_signature() || !request.get_expected_signature().is_empty() {
1167            let computed_sig: String =
1168                compute_wasm_signature(raw_bytes, request.get_version(), signing_key);
1169            if computed_sig != *request.get_expected_signature() {
1170                let err: WasmDynamicError = WasmDynamicError::SignatureInvalid {
1171                    expected: request.get_expected_signature().clone(),
1172                    actual: computed_sig,
1173                };
1174                self.record_failure(&scope, &err);
1175                return Err(err);
1176            }
1177        }
1178        if state_sig.has_subscribers() {
1179            let _: bool = state_sig.set(WasmLoadState::Compiling);
1180        }
1181        let cached_module: Option<Rc<WasmParsedModule>> = cached_parsed_opt.or_else(|| {
1182            self.lookup_cached_parsed_module(
1183                request.resolved_cache_key(),
1184                request.get_url().as_str(),
1185                computed_checksum,
1186            )
1187        });
1188        let parsed: Rc<WasmParsedModule> = match cached_module {
1189            Some(hit) => hit,
1190            None => match parse_wasm_binary(raw_bytes, &config) {
1191                Ok(m) => Rc::new(m),
1192                Err(err) => {
1193                    self.record_failure(&scope, &err);
1194                    return Err(err);
1195                }
1196            },
1197        };
1198        if parsed.get_exports().contains_key(WASM_EXPORT_ABI) {
1199            let abi_res: Result<WasmExecutionOutput, WasmDynamicError> =
1200                execute_wasm_export(parsed.as_ref(), WASM_EXPORT_ABI, &[], &config);
1201            match abi_res {
1202                Ok(abi_out) => {
1203                    let mod_abi: u32 = abi_out.get_return_value().max(0) as u32;
1204                    if mod_abi != WASM_ABI_VERSION {
1205                        let err: WasmDynamicError = WasmDynamicError::AbiMismatch {
1206                            expected: WASM_ABI_VERSION,
1207                            actual: mod_abi,
1208                        };
1209                        self.record_failure(&scope, &err);
1210                        return Err(err);
1211                    }
1212                }
1213                Err(err) => {
1214                    self.record_failure(&scope, &err);
1215                    return Err(err);
1216                }
1217            }
1218        }
1219        if state_sig.has_subscribers() {
1220            let _: bool = state_sig.set(WasmLoadState::Executing);
1221        }
1222        let exec_out: WasmExecutionOutput =
1223            match execute_wasm_export(parsed.as_ref(), WASM_EXPORT_RENDER, &[0], &config) {
1224                Ok(out) => out,
1225                Err(err) => {
1226                    self.record_failure(&scope, &err);
1227                    return Err(err);
1228                }
1229            };
1230        self.commit_mounted_output(
1231            &request,
1232            fetched,
1233            computed_checksum,
1234            parsed,
1235            exec_out,
1236            state_sig,
1237        )
1238    }
1239
1240    /// Executes an interactive click/event inside a mounted WASM module (`euv_on_event`), re-rendering native UI live.
1241    ///
1242    /// # Arguments
1243    ///
1244    /// - `&Self` - Manager reference.
1245    /// - `&WasmDynamicScope` - Mounted partial or global WASM scope.
1246    /// - `i32` - Action code passed into `euv_on_event`.
1247    ///
1248    /// # Returns
1249    ///
1250    /// - `Result<i32, WasmDynamicError>` - Updated WASM module state value or sandbox error.
1251    pub fn dispatch_wasm_event(
1252        &self,
1253        scope: &WasmDynamicScope,
1254        action_code: i32,
1255    ) -> Result<i32, WasmDynamicError> {
1256        let (config, hub, snap_version, snap_state, snap_module): (
1257            WasmSandboxConfig,
1258            DynamicUpdateHub,
1259            u64,
1260            i32,
1261            Rc<WasmParsedModule>,
1262        ) = {
1263            let Self { inner } = self;
1264            let guard: Ref<'_, WasmDynamicManagerState> = inner.try_borrow().map_err(|_| {
1265                WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1266            })?;
1267            let snap: &WasmMountedSnapshot = match scope {
1268                WasmDynamicScope::Partial { slot_id } => guard
1269                    .partial_stacks
1270                    .get(slot_id)
1271                    .and_then(|s: &Vec<WasmMountedSnapshot>| s.last())
1272                    .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1273                WasmDynamicScope::Global => guard
1274                    .global_stack
1275                    .last()
1276                    .ok_or(WasmDynamicError::NoRollbackSnapshot)?,
1277            };
1278            (
1279                guard.config,
1280                guard.hub.clone(),
1281                snap.get_version(),
1282                snap.get_state_value(),
1283                Rc::clone(snap.get_module()),
1284            )
1285        };
1286        let next_state: i32 = if snap_module.get_exports().contains_key(WASM_EXPORT_ON_EVENT) {
1287            let ev_out: WasmExecutionOutput = execute_wasm_export(
1288                snap_module.as_ref(),
1289                WASM_EXPORT_ON_EVENT,
1290                &[snap_state],
1291                &config,
1292            )?;
1293            let _: i32 = action_code;
1294            ev_out.get_return_value() % 2
1295        } else {
1296            (snap_state + 1) % 2
1297        };
1298        let render_out: WasmExecutionOutput = execute_wasm_export(
1299            snap_module.as_ref(),
1300            WASM_EXPORT_RENDER,
1301            &[next_state],
1302            &config,
1303        )?;
1304        let WasmExecutionOutput {
1305            emitted_spec,
1306            emitted_bundle,
1307            ..
1308        } = render_out;
1309        match scope {
1310            WasmDynamicScope::Partial { slot_id } => {
1311                if let Some(spec) = emitted_spec {
1312                    let mut upd: DynamicComponentUpdate =
1313                        DynamicComponentUpdate::new(slot_id.clone(), snap_version, spec);
1314                    upd.set_allow_downgrade(true);
1315                    upd.sign();
1316                    let _: Result<u64, DynamicUpdateError> = hub.apply_component(upd);
1317                }
1318            }
1319            WasmDynamicScope::Global => {
1320                if let Some(mut patched) = emitted_bundle {
1321                    for comp in patched.get_mut_components().iter_mut() {
1322                        comp.set_allow_downgrade(true);
1323                        comp.sign();
1324                    }
1325                    for page in patched.get_mut_pages().iter_mut() {
1326                        page.set_allow_downgrade(true);
1327                        page.sign();
1328                    }
1329                    let _: Result<DynamicTelemetry, DynamicUpdateError> = hub.apply_bundle(patched);
1330                }
1331            }
1332        }
1333        let Self { inner } = self;
1334        if let Ok(mut guard) = inner.try_borrow_mut() {
1335            match scope {
1336                WasmDynamicScope::Partial { slot_id } => {
1337                    if let Some(stack) = guard.partial_stacks.get_mut(slot_id)
1338                        && let Some(top) = stack.last_mut()
1339                    {
1340                        top.set_state_value(next_state);
1341                    }
1342                }
1343                WasmDynamicScope::Global => {
1344                    if let Some(top) = guard.global_stack.last_mut() {
1345                        top.set_state_value(next_state);
1346                    }
1347                }
1348            }
1349            let _: bool = guard
1350                .telemetry_signal
1351                .update(|t: &mut WasmDynamicTelemetry| {
1352                    t.events_handled = t.events_handled.saturating_add(1);
1353                });
1354        }
1355        Ok(next_state)
1356    }
1357
1358    /// Rolls back a partial slot to its previous verified WASM version or compiled native fallback.
1359    ///
1360    /// # Arguments
1361    ///
1362    /// - `&Self` - Manager reference.
1363    /// - `&str` - Target partial slot ID.
1364    /// - `&str` - Human-readable rollback reason.
1365    ///
1366    /// # Returns
1367    ///
1368    /// - `Result<u64, WasmDynamicError>` - Active version after rollback (`0` = compiled fallback).
1369    pub fn rollback_partial(&self, slot_id: &str, reason: &str) -> Result<u64, WasmDynamicError> {
1370        let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1371            slot_id: slot_id.to_string(),
1372        };
1373        let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1374        let (hub, next_ver): (DynamicUpdateHub, u64) = {
1375            let Self { inner } = self;
1376            let mut guard: RefMut<'_, WasmDynamicManagerState> =
1377                inner.try_borrow_mut().map_err(|_| {
1378                    WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1379                })?;
1380            let stack: &mut Vec<WasmMountedSnapshot> = guard
1381                .partial_stacks
1382                .get_mut(slot_id)
1383                .ok_or(WasmDynamicError::NoRollbackSnapshot)?;
1384            if stack.pop().is_none() {
1385                return Err(WasmDynamicError::NoRollbackSnapshot);
1386            }
1387            let ver: u64 = stack
1388                .last()
1389                .map(WasmMountedSnapshot::get_version)
1390                .unwrap_or(0);
1391            let _: bool = guard
1392                .telemetry_signal
1393                .update(|t: &mut WasmDynamicTelemetry| {
1394                    t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1395                });
1396            (guard.hub.clone(), ver)
1397        };
1398        let _: Result<u64, DynamicUpdateError> = hub.rollback_component(slot_id);
1399        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1400            active_version: next_ver,
1401            reason: reason.to_string(),
1402        });
1403        Ok(next_ver)
1404    }
1405
1406    /// Unmounts a partial WASM slot completely, freeing its snapshot stack and restoring the compiled native fallback.
1407    ///
1408    /// # Arguments
1409    ///
1410    /// - `&Self` - Manager reference.
1411    /// - `&str` - Target partial slot ID.
1412    pub fn unmount_partial(&self, slot_id: &str) {
1413        let scope: WasmDynamicScope = WasmDynamicScope::Partial {
1414            slot_id: slot_id.to_string(),
1415        };
1416        let state_sig: Signal<WasmLoadState> = self.state_signal(&scope);
1417        let hub: Option<DynamicUpdateHub> = {
1418            let Self { inner } = self;
1419            if let Ok(mut guard) = inner.try_borrow_mut() {
1420                let _: Option<Vec<WasmMountedSnapshot>> = guard.partial_stacks.remove(slot_id);
1421                Some(guard.hub.clone())
1422            } else {
1423                None
1424            }
1425        };
1426        if let Some(h) = hub {
1427            while h.rollback_component(slot_id).is_ok() {}
1428        }
1429        let _: bool = state_sig.set(WasmLoadState::Idle);
1430    }
1431
1432    /// Rolls back the global full-app WASM shell to the previous LKG snapshot (or built-in native shell when empty).
1433    ///
1434    /// # Arguments
1435    ///
1436    /// - `&Self` - Manager reference.
1437    /// - `&str` - Rollback reason string.
1438    ///
1439    /// # Returns
1440    ///
1441    /// - `Result<u64, WasmDynamicError>` - Remaining global version (`0` = built-in native shell).
1442    pub fn rollback_global(&self, reason: &str) -> Result<u64, WasmDynamicError> {
1443        let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1444        let (hub, global_sig, next_ver): (DynamicUpdateHub, Signal<u64>, u64) = {
1445            let Self { inner } = self;
1446            let mut guard: RefMut<'_, WasmDynamicManagerState> =
1447                inner.try_borrow_mut().map_err(|_| {
1448                    WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string())
1449                })?;
1450            if guard.global_stack.pop().is_none() {
1451                return Err(WasmDynamicError::NoRollbackSnapshot);
1452            }
1453            let ver: u64 = guard
1454                .global_stack
1455                .last()
1456                .map(WasmMountedSnapshot::get_version)
1457                .unwrap_or(0);
1458            let _: bool = guard
1459                .telemetry_signal
1460                .update(|t: &mut WasmDynamicTelemetry| {
1461                    t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1462                });
1463            (guard.hub.clone(), guard.global_version_signal, ver)
1464        };
1465        let _: Result<u64, DynamicUpdateError> = hub.rollback_component(WASM_GLOBAL_ROOT_SLOT);
1466        let _: bool = global_sig.set_if_changed(next_ver);
1467        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1468            active_version: next_ver,
1469            reason: reason.to_string(),
1470        });
1471        Ok(next_ver)
1472    }
1473
1474    /// Restores the built-in compiled native application shell, clearing all global WASM overlays cleanly.
1475    ///
1476    /// # Arguments
1477    ///
1478    /// - `&Self` - Manager reference.
1479    pub fn restore_native_global(&self) {
1480        let state_sig: Signal<WasmLoadState> = self.state_signal(&WasmDynamicScope::Global);
1481        let pair: Option<(DynamicUpdateHub, Signal<u64>)> = {
1482            let Self { inner } = self;
1483            if let Ok(mut guard) = inner.try_borrow_mut() {
1484                guard.global_stack.clear();
1485                let _: bool = guard
1486                    .telemetry_signal
1487                    .update(|t: &mut WasmDynamicTelemetry| {
1488                        t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1489                    });
1490                Some((guard.hub.clone(), guard.global_version_signal))
1491            } else {
1492                None
1493            }
1494        };
1495        if let Some((hub, global_sig)) = pair {
1496            while hub.rollback_component(WASM_GLOBAL_ROOT_SLOT).is_ok() {}
1497            let _: bool = global_sig.set_if_changed(0);
1498        }
1499        let _: bool = state_sig.set(WasmLoadState::RolledBack {
1500            active_version: 0,
1501            reason: "restored built-in native shell".to_string(),
1502        });
1503    }
1504
1505    /// Returns the currently active request generation ID for `scope_key`.
1506    ///
1507    /// # Arguments
1508    ///
1509    /// - `&Self` - Manager reference.
1510    /// - `&str` - Scope registry key.
1511    ///
1512    /// # Returns
1513    ///
1514    /// - `u64` - Active request ID.
1515    #[must_use]
1516    fn active_request_id(&self, scope_key: &str) -> u64 {
1517        let Self { inner } = self;
1518        inner
1519            .try_borrow()
1520            .ok()
1521            .and_then(|g: Ref<'_, WasmDynamicManagerState>| {
1522                g.active_request_ids.get(scope_key).copied()
1523            })
1524            .unwrap_or(0)
1525    }
1526
1527    /// Looks up a previously validated `Rc<WasmParsedModule>` matching `(url, checksum)` without re-parsing binary bytes.
1528    ///
1529    /// # Arguments
1530    ///
1531    /// - `&Self` - Manager reference.
1532    /// - `&str` - Resolved cache key.
1533    /// - `&str` - Source module URL.
1534    /// - `u64` - Verified FNV-1a checksum of the incoming bytes.
1535    ///
1536    /// # Returns
1537    ///
1538    /// - `Option<Rc<WasmParsedModule>>` - Shared cached parsed module if `(url, checksum)` already validated.
1539    #[must_use]
1540    fn lookup_cached_parsed_module(
1541        &self,
1542        cache_key: &str,
1543        url: &str,
1544        checksum: u64,
1545    ) -> Option<Rc<WasmParsedModule>> {
1546        let Self { inner } = self;
1547        let guard: Ref<'_, WasmDynamicManagerState> = inner.try_borrow().ok()?;
1548        if let Some(entry) = guard.cache.get(cache_key)
1549            && entry.get_checksum() == checksum
1550            && entry.get_url().as_str() == url
1551        {
1552            return Some(Rc::clone(entry.get_parsed()));
1553        }
1554        if guard.parsed_cache.is_empty() {
1555            return None;
1556        }
1557        guard
1558            .parsed_cache
1559            .get(&(url.to_string(), checksum))
1560            .map(Rc::clone)
1561    }
1562
1563    /// Executes the download with exponential retry on transient failures and zero-clone verified offline cache fallback.
1564    ///
1565    /// # Arguments
1566    ///
1567    /// - `&Self` - Manager reference.
1568    /// - `&WasmDownloadRequest` - Target download request.
1569    /// - `WasmSandboxConfig` - Retry and offline cache settings.
1570    /// - `&Rc<dyn WasmFetcher>` - Transport implementation.
1571    /// - `Signal<WasmLoadState>` - Live progress signal.
1572    ///
1573    /// # Returns
1574    ///
1575    /// - `Result<(WasmFetchedShare, Option<Rc<WasmParsedModule>>), WasmDynamicError>` - Shared payload bundle and optional cached parsed module.
1576    fn fetch_with_retry(
1577        &self,
1578        request: &WasmDownloadRequest,
1579        config: WasmSandboxConfig,
1580        fetcher: &Rc<dyn WasmFetcher>,
1581        state_sig: Signal<WasmLoadState>,
1582    ) -> Result<(WasmFetchedShare, Option<Rc<WasmParsedModule>>), WasmDynamicError> {
1583        let mut last_err: WasmDynamicError =
1584            WasmDynamicError::NetworkOffline(request.get_url().clone());
1585        let max_attempts: u32 = config.get_max_retries().saturating_add(1);
1586        for attempt in 0..max_attempts {
1587            if attempt > 0 {
1588                let Self { inner } = self;
1589                if let Ok(guard) = inner.try_borrow() {
1590                    let _: bool = guard
1591                        .telemetry_signal
1592                        .update(|t: &mut WasmDynamicTelemetry| {
1593                            t.retries_performed = t.retries_performed.saturating_add(1);
1594                        });
1595                }
1596            }
1597            match fetcher.fetch(request, attempt, &mut |received: u64, total: u64| {
1598                if state_sig.has_subscribers() {
1599                    let _: bool = state_sig.set(WasmLoadState::Downloading {
1600                        received_bytes: received,
1601                        total_bytes: total,
1602                    });
1603                }
1604            }) {
1605                Ok(payload) => {
1606                    let WasmFetchedPayload {
1607                        bytes,
1608                        etag,
1609                        from_cache,
1610                    } = payload;
1611                    let shared: WasmFetchedShare = WasmFetchedShare {
1612                        bytes: Rc::new(bytes),
1613                        etag,
1614                        from_cache,
1615                    };
1616                    return Ok((shared, None));
1617                }
1618                Err(err) => {
1619                    let retryable: bool = matches!(
1620                        err,
1621                        WasmDynamicError::Timeout { .. }
1622                            | WasmDynamicError::HttpStatus {
1623                                status: 500..=599,
1624                                ..
1625                            }
1626                    );
1627                    last_err = err;
1628                    if !retryable {
1629                        break;
1630                    }
1631                }
1632            }
1633        }
1634        if config.get_allow_offline_cache() {
1635            let Self { inner } = self;
1636            let hit: Option<(WasmFetchedShare, Rc<WasmParsedModule>)> = if let Ok(guard) =
1637                inner.try_borrow()
1638            {
1639                if let Some(cached) = guard.cache.get(request.resolved_cache_key()) {
1640                    let _: bool = guard
1641                        .telemetry_signal
1642                        .update(|t: &mut WasmDynamicTelemetry| {
1643                            t.cache_hits = t.cache_hits.saturating_add(1);
1644                        });
1645                    let shared: WasmFetchedShare = WasmFetchedShare {
1646                        bytes: Rc::clone(cached.get_bytes()),
1647                        etag: cached.get_etag().clone(),
1648                        from_cache: true,
1649                    };
1650                    Some((shared, Rc::clone(cached.get_parsed())))
1651                } else {
1652                    None
1653                }
1654            } else {
1655                None
1656            };
1657            if let Some((shared, parsed)) = hit {
1658                return Ok((shared, Some(parsed)));
1659            }
1660        }
1661        Err(last_err)
1662    }
1663
1664    /// Commits a verified executed WASM output into `DynamicUpdateHub`, updates cache & rollback stacks, and emits telemetry.
1665    ///
1666    /// # Arguments
1667    ///
1668    /// - `&Self` - Manager reference.
1669    /// - `&WasmDownloadRequest` - Origin request.
1670    /// - `WasmFetchedShare` - Shared verified `.wasm` payload bundle.
1671    /// - `u64` - Verified FNV-1a checksum.
1672    /// - `Rc<WasmParsedModule>` - Shared validated `.wasm` module.
1673    /// - `WasmExecutionOutput` - Executed render output.
1674    /// - `Signal<WasmLoadState>` - Live scope status signal.
1675    ///
1676    /// # Returns
1677    ///
1678    /// - `Result<u64, WasmDynamicError>` - Mounted version number.
1679    fn commit_mounted_output(
1680        &self,
1681        request: &WasmDownloadRequest,
1682        fetched: WasmFetchedShare,
1683        checksum: u64,
1684        parsed: Rc<WasmParsedModule>,
1685        exec_out: WasmExecutionOutput,
1686        state_sig: Signal<WasmLoadState>,
1687    ) -> Result<u64, WasmDynamicError> {
1688        let WasmFetchedShare {
1689            bytes: fetched_bytes,
1690            etag: fetched_etag,
1691            from_cache,
1692        } = fetched;
1693        let ver: u64 = request.get_version();
1694        let WasmExecutionOutput {
1695            fuel_used,
1696            emitted_spec,
1697            emitted_bundle,
1698            logs,
1699            ..
1700        } = exec_out;
1701        let hub: DynamicUpdateHub = {
1702            let Self { inner } = self;
1703            inner
1704                .try_borrow()
1705                .map(|g: Ref<'_, WasmDynamicManagerState>| g.hub.clone())
1706                .map_err(|_| WasmDynamicError::ExecutionTrap(WASM_ERR_MANAGER_BORROW.to_string()))?
1707        };
1708        let (spec_opt, bundle_opt): (Option<DynamicNodeSpec>, Option<DynamicUpdateBundle>) =
1709            match request.get_scope() {
1710                WasmDynamicScope::Partial { slot_id } => {
1711                    let spec: DynamicNodeSpec = emitted_spec.ok_or_else(|| {
1712                        WasmDynamicError::InvalidUiPayload(
1713                            "partial wasm did not call env::euv_emit_ui".to_string(),
1714                        )
1715                    })?;
1716                    let mut upd: DynamicComponentUpdate =
1717                        DynamicComponentUpdate::new(slot_id.clone(), ver, spec.clone());
1718                    upd.set_allow_downgrade(request.get_allow_downgrade());
1719                    upd.sign();
1720                    hub.apply_component(upd).map_err(|e: DynamicUpdateError| {
1721                        WasmDynamicError::InvalidUiPayload(e.to_string())
1722                    })?;
1723                    (Some(spec), None)
1724                }
1725                WasmDynamicScope::Global => {
1726                    let bundle: DynamicUpdateBundle = emitted_bundle.ok_or_else(|| {
1727                        WasmDynamicError::InvalidUiPayload(
1728                            "global wasm did not call env::euv_emit_bundle".to_string(),
1729                        )
1730                    })?;
1731                    let mut patched: DynamicUpdateBundle = bundle.clone();
1732                    if request.get_allow_downgrade() {
1733                        for comp in patched.get_mut_components().iter_mut() {
1734                            comp.set_allow_downgrade(true);
1735                        }
1736                        for page in patched.get_mut_pages().iter_mut() {
1737                            page.set_allow_downgrade(true);
1738                        }
1739                    }
1740                    let _: DynamicTelemetry =
1741                        hub.apply_bundle(patched).map_err(|e: DynamicUpdateError| {
1742                            WasmDynamicError::InvalidUiPayload(e.to_string())
1743                        })?;
1744                    (None, Some(bundle))
1745                }
1746            };
1747        let snap: WasmMountedSnapshot = WasmMountedSnapshot {
1748            version: ver,
1749            url: request.get_url().clone(),
1750            checksum,
1751            module: Rc::clone(&parsed),
1752            state_value: 0,
1753            spec: spec_opt,
1754            bundle: bundle_opt,
1755        };
1756        let Self { inner } = self;
1757        if let Ok(mut guard) = inner.try_borrow_mut() {
1758            let cache_key: &str = request.resolved_cache_key();
1759            let same_cached: bool =
1760                guard
1761                    .cache
1762                    .get(cache_key)
1763                    .is_some_and(|e: &WasmCachedEntry| {
1764                        e.get_checksum() == checksum && e.get_url() == request.get_url()
1765                    });
1766            if same_cached {
1767                if let Some(existing) = guard.cache.get_mut(cache_key) {
1768                    existing.set_version(ver);
1769                    existing.set_etag(fetched_etag);
1770                }
1771            } else {
1772                let cache_entry: WasmCachedEntry = WasmCachedEntry::new(
1773                    request.get_url().clone(),
1774                    ver,
1775                    checksum,
1776                    fetched_bytes,
1777                    Rc::clone(&parsed),
1778                    fetched_etag,
1779                );
1780                let _: Option<WasmCachedEntry> =
1781                    guard.cache.insert(cache_key.to_string(), cache_entry);
1782                let _: Option<Rc<WasmParsedModule>> = guard
1783                    .parsed_cache
1784                    .insert((request.get_url().clone(), checksum), parsed);
1785            }
1786            match request.get_scope() {
1787                WasmDynamicScope::Partial { slot_id } => {
1788                    guard
1789                        .partial_stacks
1790                        .entry(slot_id.clone())
1791                        .or_default()
1792                        .push(snap);
1793                }
1794                WasmDynamicScope::Global => {
1795                    guard.global_stack.push(snap);
1796                    let _: bool = guard.global_version_signal.set_if_changed(ver);
1797                }
1798            }
1799            let _: bool = guard.last_logs.set_if_changed(logs);
1800            let _: bool = guard
1801                .telemetry_signal
1802                .update(|t: &mut WasmDynamicTelemetry| {
1803                    t.downloads_succeeded = t.downloads_succeeded.saturating_add(1);
1804                });
1805        }
1806        let _: bool = state_sig.set(WasmLoadState::Mounted {
1807            version: ver,
1808            from_cache,
1809            fuel_used,
1810        });
1811        Ok(ver)
1812    }
1813
1814    /// Records telemetry counters and updates scope state (with automatic Global LKG rollback signaling).
1815    ///
1816    /// # Arguments
1817    ///
1818    /// - `&Self` - Manager reference.
1819    /// - `&WasmDynamicScope` - Failing scope.
1820    /// - `&WasmDynamicError` - Typed error.
1821    fn record_failure(&self, scope: &WasmDynamicScope, err: &WasmDynamicError) {
1822        let state_sig: Signal<WasmLoadState> = self.state_signal(scope);
1823        let mut active_global_lkg: u64 = 0;
1824        let Self { inner } = self;
1825        if let Ok(guard) = inner.try_borrow() {
1826            let _: bool = guard
1827                .telemetry_signal
1828                .update(|t: &mut WasmDynamicTelemetry| match err {
1829                    WasmDynamicError::OutOfFuel { .. } => {
1830                        t.fuel_exhaustions_caught = t.fuel_exhaustions_caught.saturating_add(1);
1831                    }
1832                    WasmDynamicError::ExecutionTrap(_)
1833                    | WasmDynamicError::MemoryOutOfBounds { .. }
1834                    | WasmDynamicError::MemoryLimitExceeded { .. } => {
1835                        t.sandbox_traps_caught = t.sandbox_traps_caught.saturating_add(1);
1836                    }
1837                    WasmDynamicError::ChecksumMismatch { .. }
1838                    | WasmDynamicError::SignatureInvalid { .. }
1839                    | WasmDynamicError::InvalidWasmBinary(_)
1840                    | WasmDynamicError::AbiMismatch { .. }
1841                    | WasmDynamicError::MissingExport(_)
1842                    | WasmDynamicError::BinaryTooLarge { .. }
1843                    | WasmDynamicError::VersionRegression { .. } => {
1844                        t.integrity_rejections = t.integrity_rejections.saturating_add(1);
1845                    }
1846                    _ => {}
1847                });
1848            if *scope == WasmDynamicScope::Global {
1849                active_global_lkg = guard
1850                    .global_stack
1851                    .last()
1852                    .map(WasmMountedSnapshot::get_version)
1853                    .unwrap_or(0);
1854            }
1855        }
1856        if *scope == WasmDynamicScope::Global && active_global_lkg > 0 {
1857            let Self { inner } = self;
1858            if let Ok(guard) = inner.try_borrow() {
1859                let _: bool = guard
1860                    .telemetry_signal
1861                    .update(|t: &mut WasmDynamicTelemetry| {
1862                        t.rollbacks_executed = t.rollbacks_executed.saturating_add(1);
1863                    });
1864            }
1865            let _: bool = state_sig.set(WasmLoadState::RolledBack {
1866                active_version: active_global_lkg,
1867                reason: format!("auto-kept LKG v{active_global_lkg} after error: {err}"),
1868            });
1869        } else {
1870            let _: bool = state_sig.set(WasmLoadState::Failed(err.clone()));
1871        }
1872    }
1873}