ctb_formats_dcstring/converters/
wasm.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Zero-table assembler from Dc-WASM (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
21//! and `wasm_routine`) to standard binary WebAssembly (`.wasm`).
22
23#[allow(
24    unused_imports,
25    clippy::wildcard_imports,
26    reason = "Standard workspace module prelude"
27)]
28use crate::utilities::*;
29
30use crate::dc_number::read_dc_number_from_reader_with_resolver;
31use crate::navigator::{
32    BootstrapKernelVersion, tokens_match_named_construct_with_resolver,
33};
34use crate::{
35    DCMM_HEADER_LEN, DCMM_MAGIC, DCMM_UUID, DcChar, DcCharExt,
36    DcDocumentNavigator, DcMstr, DcMstring, DcProjectionPolicy, DcStr,
37    DcString, Integer,
38};
39use anyhow::{Context, Result, anyhow, bail, ensure};
40use ctb_formats_dcdata::dc::{
41    DC_WASM_FB_START, DC_WASM_FC_START, DC_WASM_FD_PAGE0_START,
42    DC_WASM_FD_PAGE1_START, DC_WASM_START,
43};
44use ctb_formats_dcdata::syntax::{
45    CharTarget, DcRole, Quantifier, SyntaxElement, SyntaxPattern,
46    SyntaxRuleResolver, SyntaxTerm, default_syntax_resolver,
47};
48use ctb_formats_dcdata::tinywasm::interpreter::TinyWasmValue;
49use ctb_formats_dcdata::tinywasm::types::ExternVal;
50use ctb_formats_dcdata::tinywasm::{
51    Extern, FuncContext, Imports, MemoryRefMut, Module, ModuleInstance, Store,
52};
53use ctb_utilities::format_id::FormatId;
54use ctb_wasm_substitute_rt::{
55    SubstituteVm, WasmLinearMemory, WasmSubstituteDescriptor,
56    WasmSubstituteHost, WasmSubstituteInstance, WasmTrap, lookup_substitute,
57    lookup_substitute_by_graph_revision,
58};
59use sha2::{Digest, Sha256};
60
61pub use super::wasm_quota::{
62    CTB_CAPABILITY_YIELD_EXPORT, CTB_EXHAUSTED_EXPORT,
63    CTB_HOST_CAPABILITY_IMPORT_NAME, CTB_HOST_IMPORT_MODULE,
64    CTB_HOST_SUSPEND_IMPORT_NAME, CTB_INTERRUPTED_OP_EXPORT,
65    CTB_MAX_MEM_PAGES_EXPORT, CTB_MAX_TABLE_ELEMS_EXPORT,
66    CTB_OP_ORDINAL_EXPORT, CTB_PHYS_MAX_MEM_PAGES_EXPORT,
67    CTB_PHYS_MAX_TABLE_ELEMS_EXPORT, CTB_QUOTA_CONSUMED_EXPORT,
68    CTB_QUOTA_REMAINING_EXPORT, CTB_REQUIRED_COST_EXPORT,
69    CTB_RESUME_TARGET_OP_EXPORT, CTB_TOTAL_MEM_PAGES_EXPORT,
70    CTB_TOTAL_TABLE_ELEMS_EXPORT, CTB_WASM_START_EXPORT,
71    InstrumentedWasmModule, SharedWasmTaskQuota, SharedWasmTaskQuotaState,
72    instrument_wasm_module_bytes,
73};
74
75/// Linear-memory byte offset (`0..4`) holding the `u32` little-endian input slice pointer.
76pub const DC_WASM_MAILBOX_INPUT_PTR: u32 = 0;
77
78/// Linear-memory byte offset (`4..8`) holding the `u32` little-endian input slice byte length.
79pub const DC_WASM_MAILBOX_INPUT_LEN: u32 = 4;
80
81/// Linear-memory byte offset (`8..12`) holding the `u32` little-endian output slice pointer.
82pub const DC_WASM_MAILBOX_OUTPUT_PTR: u32 = 8;
83
84/// Linear-memory byte offset (`12..16`) holding the `u32` little-endian output slice byte length.
85pub const DC_WASM_MAILBOX_OUTPUT_LEN: u32 = 12;
86
87/// Linear-memory byte offset (`16..32`) holding the `u128` little-endian
88/// `Dc 641 "Global graph system block most recent node ID at time of document creation"`.
89pub const DC_WASM_MAILBOX_MOST_RECENT_NODE_ID: u32 = 16;
90
91/// Total byte length (`32`) of the standard linear-memory mailbox header at `0..32`.
92pub const DC_WASM_MAILBOX_HEADER_LEN: u32 = 32;
93
94/// Minimum default linear-memory byte offset (`256`) where the host places input/output slices,
95/// leaving `0..32` for the mailbox header and `32..256` for scratch state or small data segments.
96pub const DC_WASM_MIN_IO_BUFFER_OFFSET: usize = 256;
97
98/// `step()` return status code `0`: execution or conversion completed.
99pub const WASM_STEP_STATUS_COMPLETE: i32 = 0;
100
101/// `step()` return status code `1`: streaming frame yielded; call `step()` again to continue.
102pub const WASM_STEP_STATUS_YIELD_FRAME: i32 = 1;
103
104/// `step()` return status code `2`: capability requested; provide response and call `step()` again.
105pub const WASM_STEP_STATUS_REQUEST_CAPABILITY: i32 = 2;
106
107/// Default maximum number of `step()` quanta allowed in a one-shot pure conversion.
108pub const DEFAULT_MAX_PURE_CONVERSION_STEPS: usize = 1024;
109
110const WASM_MAGIC_AND_VERSION: [u8; 8] =
111    [0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00];
112
113const WASM_SECTION_TYPE: u8 = 1;
114const WASM_SECTION_FUNCTION: u8 = 3;
115const WASM_SECTION_MEMORY: u8 = 5;
116const WASM_SECTION_GLOBAL: u8 = 6;
117const WASM_SECTION_EXPORT: u8 = 7;
118const WASM_SECTION_CODE: u8 = 10;
119const WASM_SECTION_DATA: u8 = 11;
120const WASM_SECTION_DATA_COUNT: u8 = 12;
121
122const WASM_VALTYPE_I32: u8 = 0x7F;
123const WASM_VALTYPE_I64: u8 = 0x7E;
124const WASM_VALTYPE_F32: u8 = 0x7D;
125const WASM_VALTYPE_F64: u8 = 0x7C;
126const WASM_VALTYPE_V128: u8 = 0x7B;
127const WASM_VALTYPE_FUNCREF: u8 = 0x70;
128const WASM_BLOCKTYPE_EMPTY: u8 = 0x40;
129
130const WASM_OPCODE_BLOCK: u32 = 0x02;
131const WASM_OPCODE_LOOP: u32 = 0x03;
132const WASM_OPCODE_IF: u32 = 0x04;
133const WASM_OPCODE_ELSE: u32 = 0x05;
134const WASM_OPCODE_END: u32 = 0x0B;
135const WASM_OPCODE_BR_TABLE: u32 = 0x0E;
136const WASM_OPCODE_CALL: u32 = 0x10;
137const WASM_OPCODE_RETURN_CALL: u32 = 0x12;
138const WASM_OPCODE_SELECT_T: u32 = 0x1C;
139const WASM_OPCODE_TRY_TABLE: u32 = 0x1F;
140const WASM_OPCODE_GLOBAL_GET: u32 = 0x23;
141const WASM_OPCODE_GLOBAL_SET: u32 = 0x24;
142const WASM_OPCODE_I32_CONST: u32 = 0x41;
143const WASM_OPCODE_I64_CONST: u32 = 0x42;
144const WASM_OPCODE_F32_CONST: u32 = 0x43;
145const WASM_OPCODE_F64_CONST: u32 = 0x44;
146const WASM_OPCODE_REF_FUNC: u32 = 0xD2;
147
148const WASM_FD_V128_CONST: u32 = 0x0C;
149const WASM_FD_I8X16_SHUFFLE: u32 = 0x0D;
150const WASM_FD_LANE_FIRST: u32 = 0x15;
151const WASM_FD_LANE_LAST: u32 = 0x22;
152
153#[derive(Debug, Clone, PartialEq, Eq)]
154struct WasmFuncSignature {
155    params: Vec<u8>,
156    results: Vec<u8>,
157}
158
159#[derive(Debug, Clone)]
160struct WasmRoutineDef {
161    name: String,
162    signature: WasmFuncSignature,
163    locals: Vec<u8>,
164    body_bytes: Vec<u8>,
165}
166
167#[derive(Debug, Clone)]
168struct WasmGlobalDef {
169    name: String,
170    valtype: u8,
171    mutable: bool,
172    init_val: i64,
173}
174
175#[derive(Debug, Clone)]
176struct WasmDataDef {
177    offset: u32,
178    bytes: Vec<u8>,
179}
180
181#[derive(Debug, Clone)]
182enum ParsedKeyType {
183    None,
184    ValueType(u8),
185    Routine(WasmFuncSignature),
186}
187
188struct TokenCursor<'a> {
189    tokens: &'a [DcChar],
190    pos: usize,
191    resolver: &'a dyn SyntaxRuleResolver,
192}
193
194impl<'a> TokenCursor<'a> {
195    fn new(tokens: &'a [DcChar], resolver: &'a dyn SyntaxRuleResolver) -> Self {
196        Self {
197            tokens,
198            pos: 0,
199            resolver,
200        }
201    }
202
203    fn is_eof(&self) -> bool {
204        self.pos >= self.tokens.len()
205    }
206
207    fn peek(&self) -> Option<DcChar> {
208        self.tokens.get(self.pos).copied()
209    }
210
211    fn next(&mut self) -> Result<DcChar> {
212        let ch = self
213            .tokens
214            .get(self.pos)
215            .copied()
216            .context("Unexpected end of Dc-WASM token stream")?;
217        self.pos = self.pos.saturating_add(1);
218        Ok(ch)
219    }
220
221    fn token_fills_role(&self, ch: DcChar, role: DcRole) -> bool {
222        self.resolver.token_fills_role(ch.to_u128(), role)
223    }
224
225    fn read_number(&mut self) -> Result<Integer> {
226        let resolver = self.resolver;
227        read_dc_number_from_reader_with_resolver(|| self.next(), resolver)
228    }
229
230    fn emit_blocktype(&mut self, out: &mut Vec<u8>) -> Result<()> {
231        let token = self.peek().context("Missing WASM block type")?;
232        if self.token_fills_role(token, DcRole::OptionalAbsent) {
233            let _ = self.next()?;
234            out.push(WASM_BLOCKTYPE_EMPTY);
235        } else if self.token_fills_role(token, DcRole::BeginNumber) {
236            let index = u32::try_from(&self.read_number()?)
237                .map_err(|error| anyhow!("WASM block type index out of u32 range: {error:?}"))?;
238            push_sleb128_i64(i64::from(index), out);
239        } else {
240            out.push(self.read_valtype()?);
241        }
242        Ok(())
243    }
244
245    fn read_valtype(&mut self) -> Result<u8> {
246        let tok = self.next()?;
247        if self.token_fills_role(tok, DcRole::BeginTypeDef) {
248            let inner = self.next()?;
249            let vtype = if self.token_fills_role(inner, DcRole::TypeRoutine) {
250                let mut depth = 1usize;
251                while let Some(peek_tok) = self.peek() {
252                    if self.token_fills_role(peek_tok, DcRole::BeginTypeDef) {
253                        let _ = self.next()?;
254                        depth = depth.saturating_add(1);
255                    } else if self.token_fills_role(peek_tok, DcRole::EndTypeDef)
256                    {
257                        if depth == 1 {
258                            break;
259                        }
260                        let _ = self.next()?;
261                        depth = depth.saturating_sub(1);
262                    } else {
263                        let _ = self.next()?;
264                    }
265                }
266                WASM_VALTYPE_FUNCREF
267            } else {
268                map_format_token_to_valtype(inner, self.resolver)?
269            };
270            let closer = self.next()?;
271            ensure!(
272                self.token_fills_role(closer, DcRole::EndTypeDef),
273                "Expected Dc 263 (End type definition) closing value type, found {closer}"
274            );
275            Ok(vtype)
276        } else {
277            map_format_token_to_valtype(tok, self.resolver)
278        }
279    }
280
281    fn read_routine_signature_after_280(
282        &mut self,
283    ) -> Result<Option<WasmFuncSignature>> {
284        let Some(peek) = self.peek() else {
285            bail!("Unexpected end of stream inside Dc 280 Routine type definition");
286        };
287        if self.token_fills_role(peek, DcRole::EndTypeDef) {
288            let _ = self.next()?;
289            return Ok(None);
290        }
291
292        let results = if self.token_fills_role(peek, DcRole::OptionalAbsent) {
293            let _ = self.next()?;
294            Vec::new()
295        } else {
296            vec![self.read_valtype()?]
297        };
298
299        let mut params = Vec::new();
300        if let Some(next_peek) = self.peek()
301            && self.token_fills_role(next_peek, DcRole::BeginList)
302        {
303            let _ = self.next()?;
304            if let Some(len_peek) = self.peek()
305                && self.token_fills_role(len_peek, DcRole::BeginNumber)
306            {
307                let _ = self.read_number()?;
308            }
309            // Consume list element type header (`*` or `[type]`)
310            let elem_hdr = self.next()?;
311            if self.token_fills_role(elem_hdr, DcRole::BeginTypeDef) {
312                let mut depth = 1usize;
313                while depth > 0 {
314                    let t = self.next()?;
315                    if self.token_fills_role(t, DcRole::BeginTypeDef) {
316                        depth = depth.saturating_add(1);
317                    } else if self.token_fills_role(t, DcRole::EndTypeDef) {
318                        depth = depth.saturating_sub(1);
319                    }
320                }
321            }
322            while let Some(item_peek) = self.peek() {
323                if self.token_fills_role(item_peek, DcRole::EndList) {
324                    let _ = self.next()?;
325                    break;
326                }
327                if self.token_fills_role(item_peek, DcRole::ListElementSeparator)
328                {
329                    let _ = self.next()?;
330                    continue;
331                }
332                let param_open = self.next()?;
333                ensure!(
334                    self.token_fills_role(param_open, DcRole::BeginIdentifier),
335                    "Expected Dc 270 (Begin identifier) for routine parameter, found {param_open}"
336                );
337                let param_ty = self.read_valtype()?;
338                params.push(param_ty);
339                while let Some(name_ch) = self.peek() {
340                    let _ = self.next()?;
341                    if self.token_fills_role(name_ch, DcRole::EndIdentifier) {
342                        break;
343                    }
344                    if self.token_fills_role(name_ch, DcRole::Escape)
345                        || self.token_fills_role(
346                            name_ch,
347                            DcRole::QuoteFollowingDcAsAtom,
348                        )
349                    {
350                        let _ = self.next()?;
351                    }
352                }
353            }
354        }
355
356        let closer = self.next()?;
357        ensure!(
358            self.token_fills_role(closer, DcRole::EndTypeDef),
359            "Expected Dc 263 (End type definition) after Dc 280 Routine signature, found {closer}"
360        );
361        Ok(Some(WasmFuncSignature { params, results }))
362    }
363
364    fn read_identifier_with_type(
365        &mut self,
366    ) -> Result<(String, ParsedKeyType)> {
367        let open = self.next()?;
368        ensure!(
369            self.token_fills_role(open, DcRole::BeginIdentifier),
370            "Expected Dc 270 (Begin identifier), found {open}"
371        );
372        let key_type = if let Some(first) = self.peek() {
373            if self.token_fills_role(first, DcRole::BeginTypeDef) {
374                let _ = self.next()?;
375                let inner = self.next()?;
376                if self.token_fills_role(inner, DcRole::TypeRoutine) {
377                    if let Some(sig) =
378                        self.read_routine_signature_after_280()?
379                    {
380                        ParsedKeyType::Routine(sig)
381                    } else {
382                        // Bare `Dc 280` without an inline signature in the key identifier
383                        // leaves the signature unspecified at the key level so the routine
384                        // literal's header (or void->void default) supplies it.
385                        ParsedKeyType::None
386                    }
387                } else {
388                    let vt = map_format_token_to_valtype(inner, self.resolver)?;
389                    let close = self.next()?;
390                    ensure!(
391                        self.token_fills_role(close, DcRole::EndTypeDef),
392                        "Expected Dc 263 (End type definition), found {close}"
393                    );
394                    ParsedKeyType::ValueType(vt)
395                }
396            } else if FormatId::from_dc_id(
397                self.resolver.canonical_token(first.to_u128()),
398            )
399            .is_some()
400            {
401                let _ = self.next()?;
402                ParsedKeyType::ValueType(map_format_token_to_valtype(
403                    first,
404                    self.resolver,
405                )?)
406            } else {
407                ParsedKeyType::None
408            }
409        } else {
410            ParsedKeyType::None
411        };
412
413        let mut name = String::new();
414        let mut closed = false;
415        while !self.is_eof() {
416            let mut ch = self.next()?;
417            if self.token_fills_role(ch, DcRole::EndIdentifier) {
418                closed = true;
419                break;
420            }
421            let mut suppress_expand = false;
422            if self.token_fills_role(ch, DcRole::QuoteFollowingDcAsAtom) {
423                suppress_expand = true;
424                ch = self.next()?;
425                if self.token_fills_role(ch, DcRole::Escape) {
426                    ch = self.next()?;
427                }
428            } else if self.token_fills_role(ch, DcRole::Escape) {
429                suppress_expand = true;
430                ch = self.next()?;
431            }
432            if !suppress_expand
433                && let ctb_storage_minimal::shorthand::DcShorthand::Long(node_id) =
434                    ctb_storage_minimal::shorthand::DcShorthand::from_global_id(
435                        ch.to_u128(),
436                    )
437                && let Some(sg) = self.resolver.seed_graph()
438                && let Some(s) = sg.get_string(
439                    ctb_storage_minimal::shorthand::DcShorthand::Long(node_id),
440                )
441            {
442                name.push_str(s);
443                continue;
444            }
445            let cp = ch.to_unicode().with_context(|| {
446                format!(
447                    "WASM identifier name character {ch} is not a Unicode codepoint"
448                )
449            })?;
450            let c = char::from_u32(cp).with_context(|| {
451                format!("Invalid Unicode scalar U+{cp:04X} in WASM identifier")
452            })?;
453            name.push(c);
454        }
455        ensure!(closed, "Unclosed Dc 270 (Begin identifier)");
456        ensure!(!name.is_empty(), "WASM identifier name cannot be empty");
457        Ok((name, key_type))
458    }
459
460    fn read_number_list(&mut self) -> Result<Vec<Integer>> {
461        self.read_list(Self::read_number)
462    }
463
464    fn read_type_list(&mut self) -> Result<Vec<u8>> {
465        self.read_list(Self::read_valtype)
466    }
467
468    fn read_catch(&mut self) -> Result<Vec<u8>> {
469        let fields = self.read_number_list()?;
470        let kind = u8::try_from(fields.first().context("Missing WASM catch kind")?)
471            .map_err(|error| anyhow!("WASM catch kind out of u8 range: {error:?}"))?;
472        let expected_len = match kind {
473            0 | 1 => 3,
474            2 | 3 => 2,
475            _ => bail!("Invalid WASM catch kind {kind}"),
476        };
477        ensure!(
478            fields.len() == expected_len,
479            "WASM catch kind {kind} requires {expected_len} fields, found {}",
480            fields.len()
481        );
482        let mut encoded = vec![kind];
483        for field in fields.iter().skip(1) {
484            let index = u32::try_from(field)
485                .map_err(|error| anyhow!("WASM catch index out of u32 range: {error:?}"))?;
486            push_uleb128_u32(index, &mut encoded);
487        }
488        Ok(encoded)
489    }
490
491    fn read_list<T>(
492        &mut self,
493        mut read_item: impl FnMut(&mut Self) -> Result<T>,
494    ) -> Result<Vec<T>> {
495        let open = self.next()?;
496        ensure!(
497            self.token_fills_role(open, DcRole::BeginList),
498            "Expected Dc 310 (Begin list), found {open}"
499        );
500        let declared_len = if let Some(peek) = self.peek()
501            && self.token_fills_role(peek, DcRole::BeginNumber)
502        {
503            Some(usize::try_from(&self.read_number()?)
504                .map_err(|error| anyhow!("WASM list length out of usize range: {error:?}"))?)
505        } else {
506            None
507        };
508        // Consume element type header (`*` or `[type]`)
509        let elem_hdr = self.next()?;
510        if self.token_fills_role(elem_hdr, DcRole::BeginTypeDef) {
511            let mut depth = 1usize;
512            while depth > 0 {
513                let t = self.next()?;
514                if self.token_fills_role(t, DcRole::BeginTypeDef) {
515                    depth = depth.saturating_add(1);
516                } else if self.token_fills_role(t, DcRole::EndTypeDef) {
517                    depth = depth.saturating_sub(1);
518                }
519            }
520        }
521        let mut items = Vec::new();
522        while let Some(peek) = self.peek() {
523            if self.token_fills_role(peek, DcRole::EndList) {
524                let _ = self.next()?;
525                if let Some(length) = declared_len {
526                    ensure!(length == items.len(), "WASM list declares {length} items, found {}", items.len());
527                }
528                return Ok(items);
529            }
530            if self.token_fills_role(peek, DcRole::ListElementSeparator) {
531                let _ = self.next()?;
532                continue;
533            }
534            items.push(read_item(self)?);
535        }
536        bail!("Unclosed Dc 310 (Begin list) in WASM immediate operand")
537    }
538
539    fn read_encapsulated_data(&mut self) -> Result<Vec<u8>> {
540        let start_pos = self.pos;
541        let open = self.next()?;
542        ensure!(
543            self.token_fills_role(open, DcRole::StartEncapsulationBinary),
544            "Expected Dc 203 (Start of encapsulated data — binary), found {open}"
545        );
546        let mut depth = 1usize;
547        while depth > 0 {
548            let tok = self.next()?;
549            if self.token_fills_role(tok, DcRole::Escape) {
550                let _ = self.next()?;
551                continue;
552            }
553            if self.token_fills_role(tok, DcRole::StartEncapsulationBinary) {
554                depth = depth.saturating_add(1);
555            } else if self.token_fills_role(tok, DcRole::EndEncapsulationBinary)
556            {
557                depth = depth.saturating_sub(1);
558            }
559        }
560        let slice = self
561            .tokens
562            .get(start_pos..self.pos)
563            .context("Invalid encapsulated data token slice")?;
564        let mut dc_str = DcString::new();
565        for &ch in slice {
566            dc_str.push(ch);
567        }
568        let (_, bytes, _) =
569            crate::encapsulation::parse_text_with_policy_and_resolver(
570                &dc_str,
571                &DcProjectionPolicy::strict(),
572                self.resolver,
573            )?;
574        Ok(bytes)
575    }
576}
577
578fn map_format_token_to_valtype(
579    tok: DcChar,
580    resolver: &dyn SyntaxRuleResolver,
581) -> Result<u8> {
582    let canonical = resolver.canonical_token(tok.to_u128());
583    let Some(fid) = FormatId::from_dc_id(canonical) else {
584        bail!("Token {tok} is not a recognized WebAssembly value type format");
585    };
586    match fid {
587        FormatId::I32
588        | FormatId::U32
589        | FormatId::I16
590        | FormatId::U16
591        | FormatId::I8
592        | FormatId::U8
593        | FormatId::Boolean
594        | FormatId::Integer
595        | FormatId::Natural0
596        | FormatId::Natural1
597        | FormatId::Positive
598        | FormatId::Negative => Ok(WASM_VALTYPE_I32),
599        FormatId::I64 | FormatId::U64 => Ok(WASM_VALTYPE_I64),
600        FormatId::Float => Ok(WASM_VALTYPE_F32),
601        FormatId::FloatIeee754 => Ok(WASM_VALTYPE_F64),
602        FormatId::I128 | FormatId::U128 => Ok(WASM_VALTYPE_V128),
603        other => bail!(
604            "Format {} ({}) does not map to a WebAssembly value type",
605            other.shorthand(),
606            other.ident()
607        ),
608    }
609}
610
611/// Decodes a canonical `.WASM` instruction Dc into `(prefix_byte_opt, subopcode)`
612/// using zero-table arithmetic from the five 256-entry range start constants.
613fn decode_wasm_opcode(
614    tok: DcChar,
615    resolver: &dyn SyntaxRuleResolver,
616) -> Option<(Option<u8>, u32)> {
617    let canonical = resolver.canonical_token(tok.to_u128());
618    let start_00 = DC_WASM_START.to_u128();
619    let start_fb = DC_WASM_FB_START.to_u128();
620    let start_fc = DC_WASM_FC_START.to_u128();
621    let start_fd0 = DC_WASM_FD_PAGE0_START.to_u128();
622    let start_fd1 = DC_WASM_FD_PAGE1_START.to_u128();
623    let end_fd1 = start_fd1.saturating_add(256);
624
625    if canonical >= start_00 && canonical < start_fb {
626        let sub = u32::try_from(canonical.saturating_sub(start_00)).ok()?;
627        Some((None, sub))
628    } else if canonical >= start_fb && canonical < start_fc {
629        let sub = u32::try_from(canonical.saturating_sub(start_fb)).ok()?;
630        Some((Some(0xFB), sub))
631    } else if canonical >= start_fc && canonical < start_fd0 {
632        let sub = u32::try_from(canonical.saturating_sub(start_fc)).ok()?;
633        Some((Some(0xFC), sub))
634    } else if canonical >= start_fd0 && canonical < start_fd1 {
635        let sub = u32::try_from(canonical.saturating_sub(start_fd0)).ok()?;
636        Some((Some(0xFD), sub))
637    } else if canonical >= start_fd1 && canonical < end_fd1 {
638        let sub = u32::try_from(canonical.saturating_sub(start_fd1))
639            .ok()?
640            .checked_add(256)?;
641        Some((Some(0xFD), sub))
642    } else {
643        None
644    }
645}
646
647#[allow(
648    clippy::expect_used,
649    reason = "Bitmask `val & 0x7F` is provably in 0..=127 and always fits in u8"
650)]
651fn push_uleb128_u64(mut val: u64, out: &mut Vec<u8>) {
652    loop {
653        let mut byte =
654            u8::try_from(val & 0x7F).expect("7-bit mask fits in u8");
655        val >>= 7;
656        if val != 0 {
657            byte |= 0x80;
658        }
659        out.push(byte);
660        if val == 0 {
661            break;
662        }
663    }
664}
665
666fn push_uleb128_u32(val: u32, out: &mut Vec<u8>) {
667    push_uleb128_u64(u64::from(val), out);
668}
669
670#[allow(
671    clippy::expect_used,
672    reason = "Bitmask `val & 0x7F` is provably in 0..=127 and always fits in u8"
673)]
674fn push_sleb128_i64(mut val: i64, out: &mut Vec<u8>) {
675    loop {
676        let byte = u8::try_from(val & 0x7F).expect("7-bit mask fits in u8");
677        val >>= 7;
678        let sign_bit_set = (byte & 0x40) != 0;
679        if (val == 0 && !sign_bit_set) || (val == -1 && sign_bit_set) {
680            out.push(byte);
681            break;
682        }
683        out.push(byte | 0x80);
684    }
685}
686
687fn push_sleb128_i32(val: i32, out: &mut Vec<u8>) {
688    push_sleb128_i64(i64::from(val), out);
689}
690
691fn emit_memarg(
692    memidx_int: &Integer,
693    align_int: &Integer,
694    offset_int: &Integer,
695    out: &mut Vec<u8>,
696) -> Result<()> {
697    let memidx = u32::try_from(memidx_int)
698        .map_err(|e| anyhow!("WASM memarg memidx out of u32 range: {e:?}"))?;
699    let align = u32::try_from(align_int)
700        .map_err(|e| anyhow!("WASM memarg align out of u32 range: {e:?}"))?;
701    let offset = u64::try_from(offset_int)
702        .map_err(|e| anyhow!("WASM memarg offset out of u64 range: {e:?}"))?;
703    ensure!(align < 64, "WASM memarg align exponent must be < 64");
704    if memidx == 0 {
705        push_uleb128_u32(align, out);
706        push_uleb128_u64(offset, out);
707    } else {
708        push_uleb128_u32(align | 0x40, out);
709        push_uleb128_u32(memidx, out);
710        push_uleb128_u64(offset, out);
711    }
712    Ok(())
713}
714
715#[derive(Debug, Default)]
716struct WasmSymbolTable {
717    func_by_name: std::collections::HashMap<String, u32>,
718    global_by_name: std::collections::HashMap<String, u32>,
719}
720
721fn syntax_term_allows_identifier(term: &SyntaxTerm) -> bool {
722    match term {
723        SyntaxTerm::NamedConstruct { name, .. } => name == "identifier",
724        SyntaxTerm::Group(SyntaxPattern::Alternation(branches)) => {
725            branches.iter().any(|branch| match branch {
726                SyntaxPattern::Sequence(elems) if elems.len() == 1 => elems
727                    .first()
728                    .is_some_and(|e| syntax_term_allows_identifier(&e.term)),
729                _ => false,
730            })
731        }
732        SyntaxTerm::Group(SyntaxPattern::Sequence(elems))
733            if elems.len() == 1 =>
734        {
735            elems
736                .first()
737                .is_some_and(|e| syntax_term_allows_identifier(&e.term))
738        }
739        _ => false,
740    }
741}
742
743fn read_index_or_symbol_u32(
744    cursor: &mut TokenCursor<'_>,
745    instr_dc: DcChar,
746    allows_ident: bool,
747    sym_table: &std::collections::HashMap<String, u32>,
748    target_kind: &str,
749) -> Result<u32> {
750    let peek = cursor
751        .peek()
752        .with_context(|| format!("Missing {target_kind} target after {instr_dc}"))?;
753    if cursor.token_fills_role(peek, DcRole::BeginNumber) {
754        let num = cursor.read_number()?;
755        u32::try_from(&num).map_err(|_| {
756            anyhow!("WASM {target_kind} index {num} for {instr_dc} out of u32 range")
757        })
758    } else if allows_ident
759        && cursor.token_fills_role(peek, DcRole::BeginIdentifier)
760    {
761        let (sym_name, key_ty) = cursor.read_identifier_with_type()?;
762        ensure!(
763            matches!(key_ty, ParsedKeyType::None),
764            "Symbolic WASM {target_kind} target '{sym_name}' on {instr_dc} cannot carry an inline type header"
765        );
766        sym_table.get(&sym_name).copied().with_context(|| {
767            format!(
768                "Unknown symbolic WASM {target_kind} target '{sym_name}' on {instr_dc}"
769            )
770        })
771    } else {
772        bail!(
773            "Expected numeric index{} after {instr_dc}, found {peek}",
774            if allows_ident {
775                " or symbolic Dc 270..271 identifier"
776            } else {
777                ""
778            }
779        );
780    }
781}
782
783#[allow(
784    clippy::too_many_lines,
785    reason = "Dispatches structured control flow and immediate encodings across all WebAssembly opcodes"
786)]
787fn assemble_instruction_sequence(
788    cursor: &mut TokenCursor<'_>,
789    stop_predicate: fn(&TokenCursor<'_>, DcChar) -> bool,
790    allow_else: bool,
791    enforce_kernel_v1_gate: bool,
792    syms: &WasmSymbolTable,
793    out: &mut Vec<u8>,
794) -> Result<DcChar> {
795    let mut seen_else = false;
796    while let Some(peek) = cursor.peek() {
797        if stop_predicate(cursor, peek) {
798            return cursor.next();
799        }
800        let instr_dc = cursor.next()?;
801        let Some((prefix_opt, subopcode)) =
802            decode_wasm_opcode(instr_dc, cursor.resolver)
803        else {
804            bail!(
805                "Unexpected non-WASM instruction token {instr_dc} in WASM instruction stream"
806            );
807        };
808
809        if prefix_opt.is_none() && subopcode == WASM_OPCODE_END {
810            bail!(
811                "Unexpected WASM end (Dc 658) without matching block/loop/if/try_table opener"
812            );
813        }
814        if prefix_opt.is_none() && subopcode == WASM_OPCODE_ELSE {
815            ensure!(
816                allow_else && !seen_else,
817                "Unexpected or repeated WASM else (Dc 652) in instruction sequence"
818            );
819            seen_else = true;
820            out.push(0x05);
821            continue;
822        }
823
824        ensure!(
825            cursor.resolver.matches_named_type_starter(
826                "wasm_instr",
827                cursor.resolver.canonical_token(instr_dc.to_u128()),
828            ),
829            "Token {instr_dc} is not a defined WebAssembly instruction"
830        );
831        if enforce_kernel_v1_gate {
832            BootstrapKernelVersion::V1
833                .ensure_wasm_opcode_supported(prefix_opt, subopcode)?;
834        }
835
836        // Emit opcode byte(s)
837        if let Some(prefix) = prefix_opt {
838            out.push(prefix);
839            push_uleb128_u32(subopcode, out);
840        } else {
841            let op_byte = u8::try_from(subopcode).context(
842                "Single-byte WASM opcode out of u8 range",
843            )?;
844            out.push(op_byte);
845        }
846
847        // Structured control-flow instructions (`block`, `loop`, `if`, `try_table`)
848        if prefix_opt.is_none()
849            && matches!(
850                subopcode,
851                WASM_OPCODE_BLOCK
852                    | WASM_OPCODE_LOOP
853                    | WASM_OPCODE_IF
854                    | WASM_OPCODE_TRY_TABLE
855            )
856        {
857            cursor.emit_blocktype(out)?;
858
859            if subopcode == WASM_OPCODE_TRY_TABLE {
860                let catches = cursor.read_list(TokenCursor::read_catch)?;
861                let catch_len = u32::try_from(catches.len())?;
862                push_uleb128_u32(catch_len, out);
863                for catch in &catches {
864                    out.extend_from_slice(catch);
865                }
866            }
867
868            let is_if = subopcode == WASM_OPCODE_IF;
869            let _end_dc = assemble_instruction_sequence(
870                cursor,
871                |cur, ch| {
872                    decode_wasm_opcode(ch, cur.resolver)
873                        == Some((None, WASM_OPCODE_END))
874                },
875                is_if,
876                enforce_kernel_v1_gate,
877                syms,
878                out,
879            )?;
880            out.push(0x0B);
881            continue;
882        }
883
884        // Inspect the instruction's syntax rule in the seed graph for immediate operands
885        let canonical = cursor.resolver.canonical_token(instr_dc.to_u128());
886        let Some(target) = CharTarget::from_u128(canonical) else {
887            continue;
888        };
889        let Some(rule) = cursor.resolver.resolve_rule(&target) else {
890            continue;
891        };
892        let SyntaxPattern::Sequence(elements) = &rule.pattern else {
893            continue;
894        };
895        let operand_elems: Vec<&SyntaxElement> = elements
896            .iter()
897            .skip_while(|el| matches!(el.term, SyntaxTerm::SelfChar))
898            .collect();
899
900        if operand_elems.is_empty() {
901            continue;
902        }
903
904        // Special immediate encodings determined by standard WebAssembly opcode + rule shape
905        match (prefix_opt, subopcode, operand_elems.len()) {
906            (
907                None,
908                WASM_OPCODE_CALL | WASM_OPCODE_RETURN_CALL | WASM_OPCODE_REF_FUNC,
909                1,
910            ) => {
911                let allows_ident = operand_elems
912                    .first()
913                    .is_some_and(|el| syntax_term_allows_identifier(&el.term));
914                let idx = read_index_or_symbol_u32(
915                    cursor,
916                    instr_dc,
917                    allows_ident,
918                    &syms.func_by_name,
919                    "function",
920                )?;
921                push_uleb128_u32(idx, out);
922            }
923            (None, WASM_OPCODE_GLOBAL_GET | WASM_OPCODE_GLOBAL_SET, 1) => {
924                let allows_ident = operand_elems
925                    .first()
926                    .is_some_and(|el| syntax_term_allows_identifier(&el.term));
927                let idx = read_index_or_symbol_u32(
928                    cursor,
929                    instr_dc,
930                    allows_ident,
931                    &syms.global_by_name,
932                    "global",
933                )?;
934                push_uleb128_u32(idx, out);
935            }
936            (None, WASM_OPCODE_I32_CONST, 1) => {
937                let num = cursor.read_number()?;
938                let val = i32::try_from(&num).or_else(|_| {
939                    u32::try_from(&num).map(i32::from_ne_bytes_of_u32)
940                }).map_err(|_| {
941                    anyhow!("i32.const immediate {num} out of 32-bit range")
942                })?;
943                push_sleb128_i32(val, out);
944            }
945            (None, WASM_OPCODE_I64_CONST, 1) => {
946                let num = cursor.read_number()?;
947                let val = i64::try_from(&num).or_else(|_| {
948                    u64::try_from(&num).map(i64::from_ne_bytes_of_u64)
949                }).map_err(|_| {
950                    anyhow!("i64.const immediate {num} out of 64-bit range")
951                })?;
952                push_sleb128_i64(val, out);
953            }
954            (None, WASM_OPCODE_F32_CONST, 1) => {
955                let num = cursor.read_number()?;
956                let bits = u32::try_from(&num).map_err(|_| {
957                    anyhow!(
958                        "f32.const immediate {num} must be a 32-bit IEEE-754 bit pattern (u32)"
959                    )
960                })?;
961                out.extend_from_slice(&bits.to_le_bytes());
962            }
963            (None, WASM_OPCODE_F64_CONST, 1) => {
964                let num = cursor.read_number()?;
965                let bits = u64::try_from(&num).map_err(|_| {
966                    anyhow!(
967                        "f64.const immediate {num} must be a 64-bit IEEE-754 bit pattern (u64)"
968                    )
969                })?;
970                out.extend_from_slice(&bits.to_le_bytes());
971            }
972            (Some(0xFD), WASM_FD_V128_CONST, 1) => {
973                let num = cursor.read_number()?;
974                let bytes = if let Ok(u) = u128::try_from(&num) {
975                    u.to_le_bytes()
976                } else if let Ok(i) = i128::try_from(&num) {
977                    i.to_le_bytes()
978                } else {
979                    bail!("v128.const immediate {num} out of 128-bit range");
980                };
981                out.extend_from_slice(&bytes);
982            }
983            (Some(0xFD), WASM_FD_I8X16_SHUFFLE, 1) => {
984                let lanes = cursor.read_number_list()?;
985                ensure!(
986                    lanes.len() == 16,
987                    "i8x16.shuffle requires a list of exactly 16 lane indices, found {}",
988                    lanes.len()
989                );
990                for lane in &lanes {
991                    let b = u8::try_from(lane).map_err(|_| {
992                        anyhow!("i8x16.shuffle lane index {lane} out of u8 range")
993                    })?;
994                    out.push(b);
995                }
996            }
997            (Some(0xFD), op, 1)
998                if (WASM_FD_LANE_FIRST..=WASM_FD_LANE_LAST).contains(&op) =>
999            {
1000                let lane = cursor.read_number()?;
1001                let b = u8::try_from(&lane).map_err(|_| {
1002                    anyhow!("SIMD lane index {lane} out of u8 range")
1003                })?;
1004                out.push(b);
1005            }
1006            (None, WASM_OPCODE_BR_TABLE, 2) => {
1007                let labels = cursor.read_number_list()?;
1008                let default_lbl = cursor.read_number()?;
1009                let len = u32::try_from(labels.len())?;
1010                push_uleb128_u32(len, out);
1011                for lbl in &labels {
1012                    let idx = u32::try_from(lbl).map_err(|_| {
1013                        anyhow!("br_table label index {lbl} out of u32 range")
1014                    })?;
1015                    push_uleb128_u32(idx, out);
1016                }
1017                let def_idx = u32::try_from(&default_lbl).map_err(|_| {
1018                    anyhow!(
1019                        "br_table default label index {default_lbl} out of u32 range"
1020                    )
1021                })?;
1022                push_uleb128_u32(def_idx, out);
1023            }
1024            (None, WASM_OPCODE_SELECT_T, 1) => {
1025                let vt = cursor.read_valtype()?;
1026                out.push(0x01);
1027                out.push(vt);
1028            }
1029            (_, _, 3)
1030                if operand_elems.iter().all(|el| {
1031                    matches!(
1032                        &el.term,
1033                        SyntaxTerm::NamedConstruct { name, .. } if name == "number"
1034                    )
1035                }) =>
1036            {
1037                let memidx = cursor.read_number()?;
1038                let align = cursor.read_number()?;
1039                let offset = cursor.read_number()?;
1040                emit_memarg(&memidx, &align, &offset, out)?;
1041            }
1042            (_, _, 4)
1043                if operand_elems.iter().all(|el| {
1044                    matches!(
1045                        &el.term,
1046                        SyntaxTerm::NamedConstruct { name, .. } if name == "number"
1047                    )
1048                }) =>
1049            {
1050                let memidx = cursor.read_number()?;
1051                let align = cursor.read_number()?;
1052                let offset = cursor.read_number()?;
1053                let lane = cursor.read_number()?;
1054                emit_memarg(&memidx, &align, &offset, out)?;
1055                let lane_b = u8::try_from(&lane).map_err(|_| {
1056                    anyhow!("SIMD lane index {lane} out of u8 range")
1057                })?;
1058                out.push(lane_b);
1059            }
1060            _ => {
1061                for el in operand_elems {
1062                    match &el.term {
1063                        SyntaxTerm::NamedConstruct { name, .. }
1064                            if name == "number" =>
1065                        {
1066                            let num = cursor.read_number()?;
1067                            let val = u32::try_from(&num).map_err(|_| {
1068                                anyhow!(
1069                                    "WASM immediate {num} for {instr_dc} out of u32 range"
1070                                )
1071                            })?;
1072                            push_uleb128_u32(val, out);
1073                        }
1074                        SyntaxTerm::NamedConstruct { name, .. }
1075                            if name == "type" =>
1076                        {
1077                            let vt = cursor.read_valtype()?;
1078                            out.push(vt);
1079                        }
1080                        other => bail!(
1081                            "Unsupported immediate syntax term {other:?} on WASM instruction {instr_dc}"
1082                        ),
1083                    }
1084                }
1085            }
1086        }
1087    }
1088    bail!("Unclosed WASM instruction sequence (missing closing delimiter)")
1089}
1090
1091trait FromNeBytesExt {
1092    fn from_ne_bytes_of_u32(v: u32) -> i32 {
1093        i32::from_le_bytes(v.to_le_bytes())
1094    }
1095    fn from_ne_bytes_of_u64(v: u64) -> i64 {
1096        i64::from_le_bytes(v.to_le_bytes())
1097    }
1098}
1099impl FromNeBytesExt for i32 {}
1100impl FromNeBytesExt for i64 {}
1101
1102#[derive(Debug, Clone, Copy)]
1103struct RoutineHeaderToken {
1104    token: DcChar,
1105    optional: bool,
1106}
1107
1108#[derive(Debug, Clone)]
1109struct RoutineHeaderLayout {
1110    prefix_tokens: Vec<RoutineHeaderToken>,
1111    post_sig_tokens: Vec<RoutineHeaderToken>,
1112    custom_routine_rule: bool,
1113}
1114
1115impl RoutineHeaderLayout {
1116    fn token_starts_routine(
1117        &self,
1118        tok: DcChar,
1119        resolver: &dyn SyntaxRuleResolver,
1120    ) -> bool {
1121        for hdr in &self.prefix_tokens {
1122            if tok == hdr.token
1123                || resolver.is_equivalent_to(tok.to_u128(), hdr.token.to_u128())
1124            {
1125                return true;
1126            }
1127            if !hdr.optional {
1128                return false;
1129            }
1130        }
1131        resolver.token_fills_role(tok.to_u128(), DcRole::BeginLiteral)
1132    }
1133}
1134
1135fn extract_header_token_element(
1136    el: &SyntaxElement,
1137) -> Option<RoutineHeaderToken> {
1138    let outer_optional = match el.quantifier {
1139        Quantifier::ExactOne => false,
1140        Quantifier::Optional => true,
1141        _ => return None,
1142    };
1143    match &el.term {
1144        SyntaxTerm::CharRef(target) => Some(RoutineHeaderToken {
1145            token: DcChar::from_u128(target.to_u128()),
1146            optional: outer_optional,
1147        }),
1148        SyntaxTerm::Group(SyntaxPattern::Sequence(inner))
1149            if inner.len() == 1 =>
1150        {
1151            let first = inner.first()?;
1152            let mut tok = extract_header_token_element(first)?;
1153            tok.optional = tok.optional || outer_optional;
1154            Some(tok)
1155        }
1156        _ => None,
1157    }
1158}
1159
1160fn extract_pattern_routine_header_tokens(
1161    pattern: &SyntaxPattern,
1162    construct_name: &str,
1163    resolver: &dyn SyntaxRuleResolver,
1164) -> Result<(Vec<RoutineHeaderToken>, Vec<RoutineHeaderToken>)> {
1165    if let SyntaxPattern::Alternation(branches) = pattern {
1166        let mut last_err = None;
1167        for branch in branches {
1168            match extract_pattern_routine_header_tokens(
1169                branch,
1170                construct_name,
1171                resolver,
1172            ) {
1173                Ok(tokens) => return Ok(tokens),
1174                Err(err) => last_err = Some(err),
1175            }
1176        }
1177        if let Some(err) = last_err {
1178            return Err(err);
1179        }
1180        bail!(
1181            "Active graph grammar for '{construct_name}' alternation is empty"
1182        );
1183    }
1184    let SyntaxPattern::Sequence(elements) = pattern else {
1185        bail!(
1186            "Active graph grammar for '{construct_name}' must be a sequence pattern"
1187        );
1188    };
1189    if elements.len() == 1
1190        && let Some(SyntaxElement {
1191            term: SyntaxTerm::Group(inner),
1192            quantifier: Quantifier::ExactOne,
1193        }) = elements.first()
1194    {
1195        return extract_pattern_routine_header_tokens(
1196            inner,
1197            construct_name,
1198            resolver,
1199        );
1200    }
1201    let last_el = elements.last().with_context(|| {
1202        format!("Active graph grammar for '{construct_name}' is empty")
1203    })?;
1204    let is_end_literal = matches!(
1205        last_el,
1206        SyntaxElement {
1207            term: SyntaxTerm::CharRef(target),
1208            quantifier: Quantifier::ExactOne,
1209        } if resolver.token_fills_role(target.to_u128(), DcRole::EndLiteral)
1210    );
1211    ensure!(
1212        is_end_literal,
1213        "Active graph grammar for '{construct_name}' must end with Dc 261 (End literal value)"
1214    );
1215
1216    let mut header_start_idx = None;
1217    for idx in 0..elements.len() {
1218        if let (Some(e0), Some(e1), Some(e2), Some(e3)) = (
1219            elements.get(idx),
1220            elements.get(idx.saturating_add(1)),
1221            elements.get(idx.saturating_add(2)),
1222            elements.get(idx.saturating_add(3)),
1223        ) && matches!(
1224            e0,
1225            SyntaxElement {
1226                term: SyntaxTerm::CharRef(t0),
1227                quantifier: Quantifier::ExactOne,
1228            } if resolver.token_fills_role(t0.to_u128(), DcRole::BeginLiteral)
1229        ) && matches!(
1230            e1,
1231            SyntaxElement {
1232                term: SyntaxTerm::CharRef(t1),
1233                quantifier: Quantifier::ExactOne,
1234            } if resolver.token_fills_role(t1.to_u128(), DcRole::BeginTypeDef)
1235        ) && matches!(
1236            e2,
1237            SyntaxElement {
1238                term: SyntaxTerm::RuleRef { target: t2 },
1239                quantifier: Quantifier::ExactOne,
1240            } if resolver.token_fills_role(t2.to_u128(), DcRole::TypeRoutine)
1241        ) && matches!(
1242            e3,
1243            SyntaxElement {
1244                term: SyntaxTerm::CharRef(t3),
1245                quantifier: Quantifier::ExactOne,
1246            } if resolver.token_fills_role(t3.to_u128(), DcRole::EndTypeDef)
1247        ) {
1248            header_start_idx = Some(idx);
1249            break;
1250        }
1251    }
1252    let lit_idx = header_start_idx.with_context(|| {
1253        format!(
1254            "Active graph grammar for '{construct_name}' is missing canonical Dc 260..Dc 262 [280:] Dc 263 routine signature header"
1255        )
1256    })?;
1257
1258    let mut prefix_tokens = Vec::new();
1259    if let Some(prefix_slice) = elements.get(..lit_idx) {
1260        for el in prefix_slice {
1261            let hdr_tok = extract_header_token_element(el).with_context(|| {
1262                format!(
1263                    "Unsupported non-fixed prefix element in active graph grammar for '{construct_name}'"
1264                )
1265            })?;
1266            prefix_tokens.push(hdr_tok);
1267        }
1268    }
1269
1270    let mut post_sig_tokens = Vec::new();
1271    let after_sig_idx = lit_idx.saturating_add(4);
1272    let end_idx = elements.len().saturating_sub(1);
1273    if let Some(after_sig_slice) = elements.get(after_sig_idx..end_idx) {
1274        for el in after_sig_slice {
1275            if let Some(hdr_tok) = extract_header_token_element(el) {
1276                post_sig_tokens.push(hdr_tok);
1277            } else {
1278                break;
1279            }
1280        }
1281    }
1282
1283    Ok((prefix_tokens, post_sig_tokens))
1284}
1285
1286fn extract_routine_header_layout(
1287    resolver: &dyn SyntaxRuleResolver,
1288) -> Result<RoutineHeaderLayout> {
1289    let routine_pattern = resolver
1290        .resolve_named_type("Routine")
1291        .context("Active syntax resolver does not define named construct 'Routine'")?;
1292    let wasm_routine_pattern = resolver
1293        .resolve_named_type("wasm_routine")
1294        .context("Active syntax resolver does not define named construct 'wasm_routine'")?;
1295    let (routine_prefix, routine_post_sig) =
1296        extract_pattern_routine_header_tokens(
1297            routine_pattern,
1298            "Routine",
1299            resolver,
1300        )?;
1301    let (wasm_prefix, wasm_post_sig) = extract_pattern_routine_header_tokens(
1302        wasm_routine_pattern,
1303        "wasm_routine",
1304        resolver,
1305    )?;
1306    let prefix_tokens = if !wasm_prefix.is_empty() {
1307        wasm_prefix
1308    } else {
1309        routine_prefix
1310    };
1311    let post_sig_tokens = if !wasm_post_sig.is_empty() {
1312        wasm_post_sig
1313    } else {
1314        routine_post_sig
1315    };
1316    let custom_routine_rule =
1317        !prefix_tokens.is_empty() || !post_sig_tokens.is_empty();
1318    Ok(RoutineHeaderLayout {
1319        prefix_tokens,
1320        post_sig_tokens,
1321        custom_routine_rule,
1322    })
1323}
1324
1325fn skip_wasm_routine_from_cursor(
1326    cursor: &mut TokenCursor<'_>,
1327    layout: &RoutineHeaderLayout,
1328) -> Result<(usize, usize)> {
1329    let start_pos = cursor.pos;
1330    for hdr in &layout.prefix_tokens {
1331        if hdr.optional {
1332            if let Some(peek) = cursor.peek()
1333                && (peek == hdr.token
1334                    || cursor.resolver.is_equivalent_to(
1335                        peek.to_u128(),
1336                        hdr.token.to_u128(),
1337                    ))
1338            {
1339                let _ = cursor.next()?;
1340            }
1341        } else {
1342            let actual = cursor.next()?;
1343            ensure!(
1344                actual == hdr.token
1345                    || cursor.resolver.is_equivalent_to(
1346                        actual.to_u128(),
1347                        hdr.token.to_u128(),
1348                    ),
1349                "Expected leading routine header token {} required by active graph grammar, found {actual}",
1350                hdr.token
1351            );
1352        }
1353    }
1354    let lit_open = cursor.next()?;
1355    ensure!(
1356        cursor.token_fills_role(lit_open, DcRole::BeginLiteral),
1357        "Expected Dc 260 (Begin literal value) starting wasm_routine, found {lit_open}"
1358    );
1359    let mut depth = 1usize;
1360    while depth > 0 {
1361        let tok = cursor.next()?;
1362        if cursor.token_fills_role(tok, DcRole::Escape) {
1363            let _ = cursor.next()?;
1364            continue;
1365        }
1366        if cursor.token_fills_role(tok, DcRole::BeginLiteral) {
1367            depth = depth.saturating_add(1);
1368        } else if cursor.token_fills_role(tok, DcRole::EndLiteral) {
1369            depth = depth.saturating_sub(1);
1370        }
1371    }
1372    Ok((start_pos, cursor.pos))
1373}
1374
1375fn parse_wasm_routine_from_cursor(
1376    cursor: &mut TokenCursor<'_>,
1377    name: String,
1378    external_sig: Option<WasmFuncSignature>,
1379    syms: &WasmSymbolTable,
1380) -> Result<WasmRoutineDef> {
1381    let routine_start = cursor.pos;
1382    let layout = extract_routine_header_layout(cursor.resolver)?;
1383    for hdr in &layout.prefix_tokens {
1384        if hdr.optional {
1385            if let Some(peek) = cursor.peek()
1386                && (peek == hdr.token
1387                    || cursor.resolver.is_equivalent_to(
1388                        peek.to_u128(),
1389                        hdr.token.to_u128(),
1390                    ))
1391            {
1392                let _ = cursor.next()?;
1393            }
1394        } else {
1395            let actual = cursor.next()?;
1396            ensure!(
1397                actual == hdr.token
1398                    || cursor.resolver.is_equivalent_to(
1399                        actual.to_u128(),
1400                        hdr.token.to_u128(),
1401                    ),
1402                "Expected leading routine header token {} required by active graph grammar, found {actual}",
1403                hdr.token
1404            );
1405        }
1406    }
1407
1408    let lit_open = cursor.next()?;
1409    ensure!(
1410        cursor.token_fills_role(lit_open, DcRole::BeginLiteral),
1411        "Expected Dc 260 (Begin literal value) starting wasm_routine, found {lit_open}"
1412    );
1413    let type_open = cursor.next()?;
1414    ensure!(
1415        cursor.token_fills_role(type_open, DcRole::BeginTypeDef),
1416        "Expected Dc 262 (Begin type definition) in wasm_routine header, found {type_open}"
1417    );
1418    let routine_tok = cursor.next()?;
1419    ensure!(
1420        cursor.token_fills_role(routine_tok, DcRole::TypeRoutine),
1421        "Expected Dc 280 (Built-in type identifier: Routine) in wasm_routine header, found {routine_tok}"
1422    );
1423    let inline_sig = cursor.read_routine_signature_after_280()?;
1424
1425    for hdr in &layout.post_sig_tokens {
1426        if hdr.optional {
1427            if let Some(peek) = cursor.peek()
1428                && (peek == hdr.token
1429                    || cursor.resolver.is_equivalent_to(
1430                        peek.to_u128(),
1431                        hdr.token.to_u128(),
1432                    ))
1433            {
1434                let _ = cursor.next()?;
1435            }
1436        } else {
1437            let actual = cursor.next()?;
1438            ensure!(
1439                actual == hdr.token
1440                    || cursor.resolver.is_equivalent_to(
1441                        actual.to_u128(),
1442                        hdr.token.to_u128(),
1443                    ),
1444                "Expected post-signature routine header token {} required by active graph grammar, found {actual}",
1445                hdr.token
1446            );
1447        }
1448    }
1449    let body_start_pos = cursor.pos;
1450
1451    let signature = match (external_sig, inline_sig) {
1452        (Some(ext), Some(inl)) => {
1453            ensure!(
1454                ext == inl,
1455                "Mismatched routine signature between identifier key ({ext:?}) and routine literal ({inl:?}) for '{name}'"
1456            );
1457            ext
1458        }
1459        (Some(ext), None) => ext,
1460        (None, Some(inl)) => inl,
1461        (None, None) => WasmFuncSignature {
1462            params: Vec::new(),
1463            results: Vec::new(),
1464        },
1465    };
1466
1467    let locals = if let Some(peek) = cursor.peek()
1468        && cursor.token_fills_role(peek, DcRole::BeginList)
1469    {
1470        cursor.read_type_list()?
1471    } else {
1472        Vec::new()
1473    };
1474
1475    let mut body_bytes = Vec::new();
1476    let _closer = assemble_instruction_sequence(
1477        cursor,
1478        |cur, ch| cur.token_fills_role(ch, DcRole::EndLiteral),
1479        false,
1480        true,
1481        syms,
1482        &mut body_bytes,
1483    )?;
1484    body_bytes.push(0x0B); // End of function body
1485
1486    let routine_end = cursor.pos;
1487    let routine_slice = cursor
1488        .tokens
1489        .get(routine_start..routine_end)
1490        .context("Invalid routine slice bounds in Dc-WASM stream")?;
1491    if layout.custom_routine_rule
1492        || body_start_pos.saturating_add(1) < routine_end
1493    {
1494        ensure!(
1495            tokens_match_named_construct_with_resolver(
1496                routine_slice,
1497                "Routine",
1498                cursor.resolver,
1499            )?,
1500            "Dc-WASM routine for '{name}' does not match active graph grammar rule 'Routine'"
1501        );
1502    }
1503
1504    Ok(WasmRoutineDef {
1505        name,
1506        signature,
1507        locals,
1508        body_bytes,
1509    })
1510}
1511
1512fn push_section(section_id: u8, payload: &[u8], out: &mut Vec<u8>) -> Result<()> {
1513    out.push(section_id);
1514    let len = u32::try_from(payload.len())
1515        .context("WASM section payload exceeds u32 max length")?;
1516    push_uleb128_u32(len, out);
1517    out.extend_from_slice(payload);
1518    Ok(())
1519}
1520
1521fn push_name(name: &str, out: &mut Vec<u8>) -> Result<()> {
1522    let len = u32::try_from(name.len())
1523        .context("WASM export name exceeds u32 max length")?;
1524    push_uleb128_u32(len, out);
1525    out.extend_from_slice(name.as_bytes());
1526    Ok(())
1527}
1528
1529fn encode_wasm_module(
1530    routines: &[WasmRoutineDef],
1531    globals: &[WasmGlobalDef],
1532    data_segments: &[WasmDataDef],
1533) -> Result<Vec<u8>> {
1534    ensure!(
1535        !routines.is_empty() || !globals.is_empty() || !data_segments.is_empty(),
1536        "WASM program must contain at least one routine, global, or data segment"
1537    );
1538
1539    let mut out = Vec::with_capacity(128);
1540    out.extend_from_slice(&WASM_MAGIC_AND_VERSION);
1541
1542    // Deduplicate function signatures for the Type section
1543    let mut unique_sigs: Vec<WasmFuncSignature> = Vec::new();
1544    let mut func_type_indices: Vec<u32> = Vec::with_capacity(routines.len());
1545    for r in routines {
1546        let idx = if let Some(pos) =
1547            unique_sigs.iter().position(|s| s == &r.signature)
1548        {
1549            u32::try_from(pos)?
1550        } else {
1551            let next_idx = u32::try_from(unique_sigs.len())?;
1552            unique_sigs.push(r.signature.clone());
1553            next_idx
1554        };
1555        func_type_indices.push(idx);
1556    }
1557
1558    // 1. Type Section
1559    if !unique_sigs.is_empty() {
1560        let mut sec = Vec::new();
1561        push_uleb128_u32(u32::try_from(unique_sigs.len())?, &mut sec);
1562        for sig in &unique_sigs {
1563            sec.push(0x60);
1564            push_uleb128_u32(u32::try_from(sig.params.len())?, &mut sec);
1565            sec.extend_from_slice(&sig.params);
1566            push_uleb128_u32(u32::try_from(sig.results.len())?, &mut sec);
1567            sec.extend_from_slice(&sig.results);
1568        }
1569        push_section(WASM_SECTION_TYPE, &sec, &mut out)?;
1570    }
1571
1572    // 3. Function Section
1573    if !func_type_indices.is_empty() {
1574        let mut sec = Vec::new();
1575        push_uleb128_u32(u32::try_from(func_type_indices.len())?, &mut sec);
1576        for &t_idx in &func_type_indices {
1577            push_uleb128_u32(t_idx, &mut sec);
1578        }
1579        push_section(WASM_SECTION_FUNCTION, &sec, &mut out)?;
1580    }
1581
1582    // 5. Memory Section (1 default linear memory sized to cover active data segments, min 1 page = 64 KiB)
1583    {
1584        let mut max_data_end = 0usize;
1585        for seg in data_segments {
1586            let off = usize::try_from(seg.offset)
1587                .context("Data segment offset overflow")?;
1588            let end = off
1589                .checked_add(seg.bytes.len())
1590                .context("Data segment end overflow")?;
1591            max_data_end = max_data_end.max(end);
1592        }
1593        let initial_pages =
1594            u32::try_from(max_data_end.div_ceil(65_536).max(1))
1595                .context("WASM initial linear memory page count overflow")?;
1596        let mut sec = Vec::with_capacity(6);
1597        sec.push(0x01);
1598        sec.push(0x00);
1599        push_uleb128_u32(initial_pages, &mut sec);
1600        push_section(WASM_SECTION_MEMORY, &sec, &mut out)?;
1601    }
1602
1603    // 6. Global Section
1604    if !globals.is_empty() {
1605        let mut sec = Vec::new();
1606        push_uleb128_u32(u32::try_from(globals.len())?, &mut sec);
1607        for g in globals {
1608            sec.push(g.valtype);
1609            sec.push(u8::from(g.mutable));
1610            if g.valtype == WASM_VALTYPE_I64 {
1611                sec.push(0x42); // i64.const
1612                push_sleb128_i64(g.init_val, &mut sec);
1613            } else {
1614                sec.push(0x41); // i32.const
1615                let v32 = i32::try_from(g.init_val).map_err(|_| {
1616                    anyhow!(
1617                        "Global '{}' initializer {} out of i32 range",
1618                        g.name,
1619                        g.init_val
1620                    )
1621                })?;
1622                push_sleb128_i32(v32, &mut sec);
1623            }
1624            sec.push(0x0B); // end
1625        }
1626        push_section(WASM_SECTION_GLOBAL, &sec, &mut out)?;
1627    }
1628
1629    // 7. Export Section (export "memory" + all routines + all globals)
1630    {
1631        let mut sec = Vec::new();
1632        let total_exports = 1usize
1633            .saturating_add(routines.len())
1634            .saturating_add(globals.len());
1635        push_uleb128_u32(u32::try_from(total_exports)?, &mut sec);
1636
1637        // Export linear memory 0 as "memory"
1638        push_name("memory", &mut sec)?;
1639        sec.push(0x02);
1640        push_uleb128_u32(0, &mut sec);
1641
1642        for (func_idx, r) in routines.iter().enumerate() {
1643            push_name(&r.name, &mut sec)?;
1644            sec.push(0x00);
1645            push_uleb128_u32(u32::try_from(func_idx)?, &mut sec);
1646        }
1647
1648        for (glob_idx, g) in globals.iter().enumerate() {
1649            push_name(&g.name, &mut sec)?;
1650            sec.push(0x03);
1651            push_uleb128_u32(u32::try_from(glob_idx)?, &mut sec);
1652        }
1653
1654        push_section(WASM_SECTION_EXPORT, &sec, &mut out)?;
1655    }
1656
1657    // 12. DataCount Section (if data segments exist)
1658    if !data_segments.is_empty() {
1659        let mut sec = Vec::new();
1660        push_uleb128_u32(u32::try_from(data_segments.len())?, &mut sec);
1661        push_section(WASM_SECTION_DATA_COUNT, &sec, &mut out)?;
1662    }
1663
1664    // 10. Code Section
1665    if !routines.is_empty() {
1666        let mut sec = Vec::new();
1667        push_uleb128_u32(u32::try_from(routines.len())?, &mut sec);
1668        for r in routines {
1669            let mut func_body = Vec::new();
1670            // Run-length encode adjacent identical local types
1671            let mut local_runs: Vec<(u32, u8)> = Vec::new();
1672            for &vt in &r.locals {
1673                if let Some(last) = local_runs.last_mut()
1674                    && last.1 == vt
1675                {
1676                    last.0 = last.0.saturating_add(1);
1677                } else {
1678                    local_runs.push((1, vt));
1679                }
1680            }
1681            push_uleb128_u32(u32::try_from(local_runs.len())?, &mut func_body);
1682            for (count, vt) in local_runs {
1683                push_uleb128_u32(count, &mut func_body);
1684                func_body.push(vt);
1685            }
1686            func_body.extend_from_slice(&r.body_bytes);
1687
1688            push_uleb128_u32(u32::try_from(func_body.len())?, &mut sec);
1689            sec.extend_from_slice(&func_body);
1690        }
1691        push_section(WASM_SECTION_CODE, &sec, &mut out)?;
1692    }
1693
1694    // 11. Data Section
1695    if !data_segments.is_empty() {
1696        let mut sec = Vec::new();
1697        push_uleb128_u32(u32::try_from(data_segments.len())?, &mut sec);
1698        for seg in data_segments {
1699            sec.push(0x00); // active segment in memory 0
1700            sec.push(0x41); // i32.const offset
1701            let off_i32 = i32::try_from(seg.offset).map_err(|_| {
1702                anyhow!("Data segment offset {} out of i32 range", seg.offset)
1703            })?;
1704            push_sleb128_i32(off_i32, &mut sec);
1705            sec.push(0x0B); // end
1706            push_uleb128_u32(u32::try_from(seg.bytes.len())?, &mut sec);
1707            sec.extend_from_slice(&seg.bytes);
1708        }
1709        push_section(WASM_SECTION_DATA, &sec, &mut out)?;
1710    }
1711
1712    Ok(out)
1713}
1714
1715/// Assembles a raw sequence of Dc-WASM instructions (`[wasm_instr]*`)
1716/// into WebAssembly instruction bytes (without a module header or trailing function `0x0B`).
1717///
1718/// # Errors
1719/// Returns an error if any instruction or immediate operand is malformed.
1720pub fn assemble_wasm_instructions(
1721    doc: &DcMstr,
1722    resolver: &dyn SyntaxRuleResolver,
1723) -> Result<Vec<u8>> {
1724    let dc_str = doc.to_dc_string_with_policy_and_resolver(
1725        &DcProjectionPolicy::strict(),
1726        resolver,
1727    )?;
1728    let mut tokens: Vec<DcChar> = dc_str.chars().collect();
1729    // Append sentinel `WASM end` (`Dc 658`) to terminate top-level sequence
1730    let end_dc = DcChar::from_u128(
1731        DC_WASM_START
1732            .to_u128()
1733            .saturating_add(u128::from(WASM_OPCODE_END)),
1734    );
1735    tokens.push(end_dc);
1736
1737    let mut cursor = TokenCursor::new(&tokens, resolver);
1738    let empty_syms = WasmSymbolTable::default();
1739    let mut out = Vec::new();
1740    let _ = assemble_instruction_sequence(
1741        &mut cursor,
1742        |cur, ch| {
1743            cur.pos.saturating_add(1) == cur.tokens.len()
1744                && decode_wasm_opcode(ch, cur.resolver)
1745                    == Some((None, WASM_OPCODE_END))
1746        },
1747        false,
1748        false,
1749        &empty_syms,
1750        &mut out,
1751    )?;
1752    ensure!(
1753        cursor.is_eof(),
1754        "Unconsumed trailing tokens in WASM instruction sequence"
1755    );
1756    Ok(out)
1757}
1758
1759/// Converts a Dc-WASM document (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
1760/// or a standalone `wasm_routine`) into a standard binary `.wasm` module using the default
1761/// system graph syntax resolver.
1762///
1763/// # Errors
1764/// Returns an error if the document fails strict syntax validation or contains invalid
1765/// WebAssembly instructions, types, or immediate arguments.
1766pub fn dcmstring_to_wasm(doc: &DcMstr) -> Result<Vec<u8>> {
1767    let resolver = default_syntax_resolver();
1768    dcmstring_to_wasm_with_resolver(doc, resolver.as_ref())
1769}
1770
1771/// Converts a Dc-WASM document (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
1772/// or a standalone `wasm_routine`) into a standard binary `.wasm` module using the supplied
1773/// [`SyntaxRuleResolver`].
1774///
1775/// # Errors
1776/// Returns an error if the document fails strict syntax validation or contains invalid
1777/// WebAssembly instructions, types, or immediate arguments.
1778pub fn dcmstring_to_wasm_with_resolver(
1779    doc: &DcMstr,
1780    resolver: &dyn SyntaxRuleResolver,
1781) -> Result<Vec<u8>> {
1782    let dc_str = doc.to_dc_string_with_policy_and_resolver(
1783        &DcProjectionPolicy::strict(),
1784        resolver,
1785    )?;
1786    dcstring_to_wasm_with_resolver(&dc_str, resolver)
1787}
1788
1789/// Converts a [`DcStr`] containing a Dc-WASM program or `wasm_routine` into a standard
1790/// binary `.wasm` module using the default system graph syntax resolver.
1791///
1792/// # Errors
1793/// Returns an error if the document fails strict syntax validation or contains invalid
1794/// WebAssembly instructions, types, or immediate arguments.
1795pub fn dcstring_to_wasm(doc: &DcStr) -> Result<Vec<u8>> {
1796    let resolver = default_syntax_resolver();
1797    dcstring_to_wasm_with_resolver(doc, resolver.as_ref())
1798}
1799
1800/// Converts a [`DcStr`] containing a Dc-WASM program or `wasm_routine` into a standard
1801/// binary `.wasm` module using the supplied [`SyntaxRuleResolver`].
1802///
1803/// # Errors
1804/// Returns an error if the document fails strict syntax validation or contains invalid
1805/// WebAssembly instructions, types, or immediate arguments.
1806pub fn dcstring_to_wasm_with_resolver(
1807    doc: &DcStr,
1808    resolver: &dyn SyntaxRuleResolver,
1809) -> Result<Vec<u8>> {
1810    let raw_tokens: Vec<DcChar> = doc.chars().collect();
1811    let first_raw = raw_tokens
1812        .first()
1813        .copied()
1814        .context("Empty Dc-WASM document")?;
1815
1816    let (pinned_resolver, body_raw_tokens) = if resolver.token_fills_role(
1817        first_raw.to_u128(),
1818        DcRole::GlobalGraphSystemBlockMostRecentNodeId,
1819    ) {
1820        let first_pin_tok = raw_tokens.get(1).copied().context(
1821            "Missing System-block node ID operand after Dc 641 in Dc-WASM document",
1822        )?;
1823        ensure!(
1824            !resolver.token_fills_role(first_pin_tok.to_u128(), DcRole::Escape),
1825            "Escaped operand after Dc 641 is not a valid System-block snapshot pin in Dc-WASM document"
1826        );
1827        let (pin_dc, pin_end_idx) = if resolver.token_fills_role(
1828            first_pin_tok.to_u128(),
1829            DcRole::QuoteFollowingDcAsAtom,
1830        ) {
1831            let quoted_pin = raw_tokens.get(2).copied().context(
1832                "Dangling Dc 2239 in Dc 641 pin_description in Dc-WASM document",
1833            )?;
1834            (quoted_pin, 3usize)
1835        } else {
1836            (first_pin_tok, 2usize)
1837        };
1838        let pinned = ctb_formats_dcdata::syntax::syntax_resolver_at_most_recent(
1839            pin_dc.to_u128(),
1840        )?;
1841        // Reason for fallback: an exhausted slice after the pin header yields an empty slice that fails validation below.
1842        let rest = raw_tokens.get(pin_end_idx..).unwrap_or(&[]);
1843        (Some(pinned), rest)
1844    } else {
1845        (None, raw_tokens.as_slice())
1846    };
1847    let active_resolver: &dyn SyntaxRuleResolver =
1848        if let Some(pinned) = &pinned_resolver {
1849            pinned.as_ref()
1850        } else {
1851            resolver
1852        };
1853
1854    let mut raw_shorthands = Vec::with_capacity(body_raw_tokens.len());
1855    for &ch in body_raw_tokens {
1856        let sh = ctb_storage_minimal::shorthand::DcShorthand::from_global_id(
1857            ch.to_u128(),
1858        );
1859        raw_shorthands.push(sh);
1860    }
1861    let mut expanded_mstr = DcMstring::new();
1862    expand_graph_wasm_shorthands(
1863        &raw_shorthands,
1864        active_resolver,
1865        &mut expanded_mstr,
1866    )?;
1867    let expanded_doc = expanded_mstr.to_dc_string_with_policy_and_resolver(
1868        &DcProjectionPolicy::strict(),
1869        active_resolver,
1870    )?;
1871
1872    let routine_layout = extract_routine_header_layout(active_resolver)?;
1873    let tokens: Vec<DcChar> = expanded_doc.chars().collect();
1874    let unwrapped_tokens = if let (Some(&first_tok), Some(&second_tok), Some(&last_tok)) =
1875        (tokens.first(), tokens.get(1), tokens.last())
1876        && active_resolver
1877            .token_fills_role(first_tok.to_u128(), DcRole::BeginWasmProgram)
1878        && routine_layout.token_starts_routine(second_tok, active_resolver)
1879        && active_resolver
1880            .token_fills_role(last_tok.to_u128(), DcRole::EndWasmProgram)
1881        && let Some(inner) = tokens.get(1..tokens.len().saturating_sub(1))
1882    {
1883        inner
1884    } else {
1885        tokens.as_slice()
1886    };
1887    let mut cursor = TokenCursor::new(unwrapped_tokens, active_resolver);
1888
1889    let first = cursor.peek().context("Empty Dc-WASM document")?;
1890
1891    // Case 1: Standalone `wasm_routine` literal (`Dc 260`..`Dc 261`)
1892    if routine_layout.token_starts_routine(first, active_resolver) {
1893        let mut syms = WasmSymbolTable::default();
1894        syms.func_by_name.insert("main".to_owned(), 0);
1895        let routine = parse_wasm_routine_from_cursor(
1896            &mut cursor,
1897            "main".to_owned(),
1898            None,
1899            &syms,
1900        )?;
1901        ensure!(
1902            cursor.is_eof(),
1903            "Trailing tokens after standalone wasm_routine literal"
1904        );
1905        return encode_wasm_module(&[routine], &[], &[]);
1906    }
1907
1908    // Validate top-level `Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"` document
1909    let mut nav = DcDocumentNavigator::from_dc_str(&expanded_doc);
1910    nav.validate_document_with_resolver(
1911        &DcProjectionPolicy::strict(),
1912        active_resolver,
1913    )?;
1914
1915    let prog_open = cursor.next()?;
1916    ensure!(
1917        cursor.token_fills_role(prog_open, DcRole::BeginWasmProgram),
1918        "Expected Dc 1927 (Begin WASM program) or wasm_routine literal, found {prog_open}"
1919    );
1920
1921    let body_first = cursor
1922        .peek()
1923        .context("Unexpected end of stream after Dc 1927 (Begin WASM program)")?;
1924
1925    let mut routines = Vec::new();
1926    let mut globals = Vec::new();
1927    let mut data_segments = Vec::new();
1928
1929    if cursor.token_fills_role(body_first, DcRole::BeginKvMap) {
1930        let _ = cursor.next()?;
1931        if let Some(len_peek) = cursor.peek()
1932            && cursor.token_fills_role(len_peek, DcRole::BeginNumber)
1933        {
1934            let _ = cursor.read_number()?;
1935        }
1936        // Consume keyType and valType headers of `Dc 559`
1937        for _ in 0..2 {
1938            let hdr_tok = cursor.next()?;
1939            if cursor.token_fills_role(hdr_tok, DcRole::BeginTypeDef) {
1940                let mut depth = 1usize;
1941                while depth > 0 {
1942                    let t = cursor.next()?;
1943                    if cursor.token_fills_role(t, DcRole::BeginTypeDef) {
1944                        depth = depth.saturating_add(1);
1945                    } else if cursor.token_fills_role(t, DcRole::EndTypeDef) {
1946                        depth = depth.saturating_sub(1);
1947                    }
1948                }
1949            }
1950        }
1951
1952        // Pass 1: Scan `Dc 559` entries to populate globals, data segments, and the complete
1953        // module-wide `WasmSymbolTable` (enabling forward and recursive symbolic calls).
1954        let mut syms = WasmSymbolTable::default();
1955        let mut pending_routines: Vec<(
1956            String,
1957            Option<WasmFuncSignature>,
1958            usize,
1959            usize,
1960        )> = Vec::new();
1961        let mut next_data_offset = DC_WASM_MAILBOX_HEADER_LEN;
1962        while let Some(pair_peek) = cursor.peek() {
1963            if cursor.token_fills_role(pair_peek, DcRole::EndKvMap) {
1964                let _ = cursor.next()?;
1965                break;
1966            }
1967            let pair_open = cursor.next()?;
1968            ensure!(
1969                cursor.token_fills_role(pair_open, DcRole::BeginKvPair),
1970                "Expected Dc 514 (Key-value pair) inside WASM program map, found {pair_open}"
1971            );
1972            let (name, key_type) = cursor.read_identifier_with_type()?;
1973            let sep = cursor.next()?;
1974            ensure!(
1975                cursor.token_fills_role(sep, DcRole::ListElementSeparator),
1976                "Expected Dc 312 (List element separator) after WASM member key '{name}', found {sep}"
1977            );
1978
1979            let val_peek = cursor
1980                .peek()
1981                .context("Missing value in WASM program key-value pair")?;
1982            if routine_layout.token_starts_routine(val_peek, active_resolver) {
1983                let ext_sig = match key_type {
1984                    ParsedKeyType::Routine(sig) => Some(sig),
1985                    ParsedKeyType::None => None,
1986                    ParsedKeyType::ValueType(_) => bail!(
1987                        "WASM routine member '{name}' has a non-Routine key type"
1988                    ),
1989                };
1990                let (r_start, r_end) =
1991                    skip_wasm_routine_from_cursor(&mut cursor, &routine_layout)?;
1992                let func_idx = u32::try_from(pending_routines.len())
1993                    .context("WASM routine count exceeds u32")?;
1994                ensure!(
1995                    syms.func_by_name.insert(name.clone(), func_idx).is_none(),
1996                    "Duplicate WASM routine member symbol '{name}'"
1997                );
1998                pending_routines.push((name, ext_sig, r_start, r_end));
1999            } else if cursor.token_fills_role(val_peek, DcRole::BeginNumber) {
2000                let num = cursor.read_number()?;
2001                let init_val = i64::try_from(&num).map_err(|_| {
2002                    anyhow!(
2003                        "WASM global '{name}' initializer {num} out of i64 range"
2004                    )
2005                })?;
2006                let valtype = match key_type {
2007                    ParsedKeyType::ValueType(vt) => vt,
2008                    ParsedKeyType::None => {
2009                        if i32::try_from(init_val).is_ok() {
2010                            WASM_VALTYPE_I32
2011                        } else {
2012                            WASM_VALTYPE_I64
2013                        }
2014                    }
2015                    ParsedKeyType::Routine(_) => bail!(
2016                        "WASM numeric global '{name}' cannot have a Routine key type"
2017                    ),
2018                };
2019                let glob_idx = u32::try_from(globals.len())
2020                    .context("WASM global count exceeds u32")?;
2021                ensure!(
2022                    syms.global_by_name.insert(name.clone(), glob_idx).is_none(),
2023                    "Duplicate WASM global/data member symbol '{name}'"
2024                );
2025                globals.push(WasmGlobalDef {
2026                    name,
2027                    valtype,
2028                    mutable: true,
2029                    init_val,
2030                });
2031            } else if cursor
2032                .token_fills_role(val_peek, DcRole::StartEncapsulationBinary)
2033            {
2034                let bytes = cursor.read_encapsulated_data()?;
2035                let seg_len = u32::try_from(bytes.len())
2036                    .context("WASM data segment exceeds u32 length")?;
2037                let offset = next_data_offset;
2038                next_data_offset = next_data_offset
2039                    .checked_add(seg_len)
2040                    .context("WASM data segment offset overflow")?;
2041                data_segments.push(WasmDataDef { offset, bytes });
2042                // Also export an immutable i32 global with the segment's base offset under `name`
2043                let offset_i64 = i64::from(offset);
2044                let glob_idx = u32::try_from(globals.len())
2045                    .context("WASM global count exceeds u32")?;
2046                ensure!(
2047                    syms.global_by_name.insert(name.clone(), glob_idx).is_none(),
2048                    "Duplicate WASM global/data member symbol '{name}'"
2049                );
2050                globals.push(WasmGlobalDef {
2051                    name,
2052                    valtype: WASM_VALTYPE_I32,
2053                    mutable: false,
2054                    init_val: offset_i64,
2055                });
2056            } else {
2057                bail!(
2058                    "Unsupported WASM member value starting with {val_peek} for key '{name}'; expected wasm_routine, number, or data"
2059                );
2060            }
2061
2062            let pair_close = cursor.next()?;
2063            ensure!(
2064                cursor.token_fills_role(pair_close, DcRole::EndKvPair),
2065                "Expected Dc 515 (End key-value pair) after WASM member '{pair_close}'"
2066            );
2067        }
2068
2069        let prog_close = cursor.next()?;
2070        ensure!(
2071            cursor.token_fills_role(prog_close, DcRole::EndWasmProgram),
2072            "Expected Dc 1928 (End WASM program), found {prog_close}"
2073        );
2074
2075        // Pass 2: Assemble all routine bodies with complete function and global symbol tables.
2076        routines.reserve(pending_routines.len());
2077        for (name, ext_sig, r_start, r_end) in pending_routines {
2078            let r_slice = unwrapped_tokens
2079                .get(r_start..r_end)
2080                .context("Invalid deferred routine slice bounds")?;
2081            let mut r_cursor = TokenCursor::new(r_slice, active_resolver);
2082            let routine = parse_wasm_routine_from_cursor(
2083                &mut r_cursor,
2084                name,
2085                ext_sig,
2086                &syms,
2087            )?;
2088            ensure!(
2089                r_cursor.is_eof(),
2090                "Unconsumed tokens inside deferred WASM routine"
2091            );
2092            routines.push(routine);
2093        }
2094    } else {
2095        // Direct sequence of instructions inside `Dc 1927`..`Dc 1928`
2096        let mut syms = WasmSymbolTable::default();
2097        syms.func_by_name.insert("main".to_owned(), 0);
2098        let mut body_bytes = Vec::new();
2099        let _prog_close = assemble_instruction_sequence(
2100            &mut cursor,
2101            |cur, ch| cur.token_fills_role(ch, DcRole::EndWasmProgram),
2102            false,
2103            true,
2104            &syms,
2105            &mut body_bytes,
2106        )?;
2107        body_bytes.push(0x0B);
2108        routines.push(WasmRoutineDef {
2109            name: "main".to_owned(),
2110            signature: WasmFuncSignature {
2111                params: Vec::new(),
2112                results: Vec::new(),
2113            },
2114            locals: Vec::new(),
2115            body_bytes,
2116        });
2117    }
2118
2119    ensure!(
2120        cursor.is_eof(),
2121        "Trailing tokens after Dc 1928 (End WASM program)"
2122    );
2123
2124    encode_wasm_module(&routines, &globals, &data_segments)
2125}
2126
2127/// Status code returned by a pure-compute WebAssembly `step()` quantum.
2128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2129pub enum WasmStepStatus {
2130    /// `0 = Complete`: Execution or conversion finished; the output region holds the converted Dc document.
2131    Complete,
2132    /// `1 = YieldFrame`: Streaming execution; the output region holds an emitted frame, and the
2133    /// instance's linear memory and globals remain intact for the next `step()` call.
2134    YieldFrame,
2135    /// `2 = RequestCapability`: Execution paused requesting a privileged capability; the output
2136    /// region holds the capability request Dc document.
2137    RequestCapability,
2138}
2139
2140impl WasmStepStatus {
2141    /// Converts a raw `i32` return value from `step()` into a [`WasmStepStatus`].
2142    ///
2143    /// # Errors
2144    /// Returns an error if `code` is not `0`, `1`, or `2`.
2145    pub fn from_i32(code: i32) -> Result<Self> {
2146        match code {
2147            WASM_STEP_STATUS_COMPLETE => Ok(Self::Complete),
2148            WASM_STEP_STATUS_YIELD_FRAME => Ok(Self::YieldFrame),
2149            WASM_STEP_STATUS_REQUEST_CAPABILITY => Ok(Self::RequestCapability),
2150            other => bail!(
2151                "Invalid WASM step() return status code {other}: expected 0 (Complete), 1 (YieldFrame), or 2 (RequestCapability)"
2152            ),
2153        }
2154    }
2155
2156    /// Returns the canonical `i32` status code (`0`, `1`, or `2`).
2157    #[must_use]
2158    pub const fn as_i32(self) -> i32 {
2159        match self {
2160            Self::Complete => WASM_STEP_STATUS_COMPLETE,
2161            Self::YieldFrame => WASM_STEP_STATUS_YIELD_FRAME,
2162            Self::RequestCapability => WASM_STEP_STATUS_REQUEST_CAPABILITY,
2163        }
2164    }
2165}
2166
2167/// Version identifier for the portable WebAssembly resource-accounting rule set.
2168pub const WASM_RESOURCE_ACCOUNTING_VERSION: u32 = 2;
2169
2170/// Default maximum number of portable WASM compute quota units permitted in a [`DcWasmSession`].
2171pub const DEFAULT_MAX_WASM_INSTRUCTIONS_PER_STEP: u64 = 10_000_000;
2172
2173/// Default maximum number of 64 KiB linear memory pages permitted for a [`DcWasmSession`] (16 MiB).
2174pub const DEFAULT_MAX_WASM_MEMORY_PAGES: usize = 256;
2175
2176/// Default maximum number of table elements permitted across a [`DcWasmSession`] store.
2177pub const DEFAULT_MAX_WASM_TABLE_ELEMENTS: usize = 65_536;
2178
2179/// Default maximum byte length permitted for a single step's output mailbox slice (4 MiB).
2180pub const DEFAULT_MAX_WASM_STEP_OUTPUT_BYTES: usize = 4 * 1024 * 1024;
2181
2182/// Default maximum cumulative output bytes permitted across a [`DcWasmSession`] (16 MiB).
2183pub const DEFAULT_MAX_WASM_SESSION_OUTPUT_BYTES: usize = 16 * 1024 * 1024;
2184
2185/// Default maximum byte length permitted for a single capability request or response payload (1 MiB).
2186pub const DEFAULT_MAX_WASM_CAPABILITY_PAYLOAD_BYTES: usize = 1024 * 1024;
2187
2188/// Default maximum cumulative byte length permitted for a retained execution trace buffer (16 MiB).
2189pub const DEFAULT_MAX_WASM_TRACE_BYTES: usize = 16 * 1024 * 1024;
2190
2191/// Emergency host watchdog bounds that protect the host process from runaway execution
2192/// or supervisor faults, distinct from the System supervisor's logical resource policy.
2193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2194pub struct DcWasmWatchdogLimits {
2195    /// Physical host cap on 64 KiB linear memory pages across the store.
2196    pub physical_max_memory_pages: usize,
2197    /// Physical host cap on table elements across the store.
2198    pub physical_max_table_elements: usize,
2199    /// Emergency upper bound on portable compute units per step.
2200    pub hard_max_instructions_per_step: u64,
2201    /// Emergency upper bound on cumulative session output bytes.
2202    pub hard_max_session_output_bytes: usize,
2203}
2204
2205impl Default for DcWasmWatchdogLimits {
2206    fn default() -> Self {
2207        Self::new()
2208    }
2209}
2210
2211impl DcWasmWatchdogLimits {
2212    /// Returns the default emergency host watchdog bounds.
2213    #[must_use]
2214    pub const fn new() -> Self {
2215        Self {
2216            physical_max_memory_pages: 4096, // 256 MiB host emergency ceiling
2217            physical_max_table_elements: 1_048_576,
2218            hard_max_instructions_per_step: 100_000_000,
2219            hard_max_session_output_bytes: 64 * 1024 * 1024,
2220        }
2221    }
2222
2223    /// Returns a copy with `physical_max_memory_pages` set to the given emergency page ceiling.
2224    #[must_use]
2225    pub const fn with_physical_max_memory_pages(
2226        mut self,
2227        physical_max_memory_pages: usize,
2228    ) -> Self {
2229        self.physical_max_memory_pages = physical_max_memory_pages;
2230        self
2231    }
2232
2233    /// Returns a copy with `physical_max_table_elements` set to the given emergency table ceiling.
2234    #[must_use]
2235    pub const fn with_physical_max_table_elements(
2236        mut self,
2237        physical_max_table_elements: usize,
2238    ) -> Self {
2239        self.physical_max_table_elements = physical_max_table_elements;
2240        self
2241    }
2242
2243    /// Returns a copy with `hard_max_instructions_per_step` set to the given emergency compute ceiling.
2244    #[must_use]
2245    pub const fn with_hard_max_instructions_per_step(
2246        mut self,
2247        hard_max_instructions_per_step: u64,
2248    ) -> Self {
2249        self.hard_max_instructions_per_step = hard_max_instructions_per_step;
2250        self
2251    }
2252
2253    /// Returns a copy with `hard_max_session_output_bytes` set to the given emergency output ceiling.
2254    #[must_use]
2255    pub const fn with_hard_max_session_output_bytes(
2256        mut self,
2257        hard_max_session_output_bytes: usize,
2258    ) -> Self {
2259        self.hard_max_session_output_bytes = hard_max_session_output_bytes;
2260        self
2261    }
2262}
2263
2264/// Resource budgets enforced on a [`DcWasmSession`] for portable compute quota,
2265/// linear memory growth, table element capacity, single-step output slice length,
2266/// cumulative session output bytes, capability request/response payloads, and trace retention.
2267#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2268pub struct DcWasmResourceLimits {
2269    /// Deterministic resource-accounting rule version (`WASM_RESOURCE_ACCOUNTING_VERSION`).
2270    pub accounting_version: u32,
2271    /// Maximum portable WASM compute quota units allowed before raising [`WasmResourceInterruption::ComputeQuotaExhausted`].
2272    pub max_instructions_per_step: u64,
2273    /// Logical maximum number of 64 KiB linear memory pages allowed across the session store.
2274    pub max_memory_pages: usize,
2275    /// Physical host allocation limit for 64 KiB linear memory pages (`usize::MAX` unless constrained).
2276    pub physical_max_memory_pages: usize,
2277    /// Logical maximum number of table elements allowed across the session store.
2278    pub max_table_elements: usize,
2279    /// Physical host allocation limit for table elements (`usize::MAX` unless constrained).
2280    pub physical_max_table_elements: usize,
2281    /// Maximum byte length allowed for a single step's output slice (`out_len` in the mailbox).
2282    pub max_step_output_bytes: usize,
2283    /// Maximum cumulative output bytes allowed across all steps in a session.
2284    pub max_session_output_bytes: usize,
2285    /// Maximum byte length allowed for a single capability request or response payload
2286    /// (separate from `max_session_output_bytes`).
2287    pub max_capability_payload_bytes: usize,
2288    /// Maximum cumulative byte length allowed for a retained execution trace buffer
2289    /// (separate from `max_session_output_bytes`).
2290    pub max_trace_bytes: usize,
2291}
2292
2293impl Default for DcWasmResourceLimits {
2294    fn default() -> Self {
2295        Self::new()
2296    }
2297}
2298
2299impl DcWasmResourceLimits {
2300    /// Returns the default resource budgets for a [`DcWasmSession`].
2301    #[must_use]
2302    pub const fn new() -> Self {
2303        Self {
2304            accounting_version: WASM_RESOURCE_ACCOUNTING_VERSION,
2305            max_instructions_per_step: DEFAULT_MAX_WASM_INSTRUCTIONS_PER_STEP,
2306            max_memory_pages: DEFAULT_MAX_WASM_MEMORY_PAGES,
2307            physical_max_memory_pages: usize::MAX,
2308            max_table_elements: DEFAULT_MAX_WASM_TABLE_ELEMENTS,
2309            physical_max_table_elements: usize::MAX,
2310            max_step_output_bytes: DEFAULT_MAX_WASM_STEP_OUTPUT_BYTES,
2311            max_session_output_bytes: DEFAULT_MAX_WASM_SESSION_OUTPUT_BYTES,
2312            max_capability_payload_bytes:
2313                DEFAULT_MAX_WASM_CAPABILITY_PAYLOAD_BYTES,
2314            max_trace_bytes: DEFAULT_MAX_WASM_TRACE_BYTES,
2315        }
2316    }
2317
2318    /// Returns a copy with `accounting_version` set to the given accounting version.
2319    #[must_use]
2320    pub const fn with_accounting_version(
2321        mut self,
2322        accounting_version: u32,
2323    ) -> Self {
2324        self.accounting_version = accounting_version;
2325        self
2326    }
2327
2328    /// Returns a copy with `max_instructions_per_step` set to the given compute quota allowance.
2329    #[must_use]
2330    pub const fn with_max_instructions_per_step(
2331        mut self,
2332        max_instructions_per_step: u64,
2333    ) -> Self {
2334        self.max_instructions_per_step = max_instructions_per_step;
2335        self
2336    }
2337
2338    /// Returns a copy with `max_memory_pages` set to the given logical 64 KiB page cap.
2339    #[must_use]
2340    pub const fn with_max_memory_pages(
2341        mut self,
2342        max_memory_pages: usize,
2343    ) -> Self {
2344        self.max_memory_pages = max_memory_pages;
2345        self
2346    }
2347
2348    /// Returns a copy with `physical_max_memory_pages` set to the given physical 64 KiB page cap.
2349    #[must_use]
2350    pub const fn with_physical_max_memory_pages(
2351        mut self,
2352        physical_max_memory_pages: usize,
2353    ) -> Self {
2354        self.physical_max_memory_pages = physical_max_memory_pages;
2355        self
2356    }
2357
2358    /// Returns a copy with `max_table_elements` set to the given logical table element cap.
2359    #[must_use]
2360    pub const fn with_max_table_elements(
2361        mut self,
2362        max_table_elements: usize,
2363    ) -> Self {
2364        self.max_table_elements = max_table_elements;
2365        self
2366    }
2367
2368    /// Returns a copy with `physical_max_table_elements` set to the given physical table element cap.
2369    #[must_use]
2370    pub const fn with_physical_max_table_elements(
2371        mut self,
2372        physical_max_table_elements: usize,
2373    ) -> Self {
2374        self.physical_max_table_elements = physical_max_table_elements;
2375        self
2376    }
2377
2378    /// Returns a copy with `max_step_output_bytes` set to the given single-step output cap.
2379    #[must_use]
2380    pub const fn with_max_step_output_bytes(
2381        mut self,
2382        max_step_output_bytes: usize,
2383    ) -> Self {
2384        self.max_step_output_bytes = max_step_output_bytes;
2385        self
2386    }
2387
2388    /// Returns a copy with `max_session_output_bytes` set to the given cumulative session output cap.
2389    #[must_use]
2390    pub const fn with_max_session_output_bytes(
2391        mut self,
2392        max_session_output_bytes: usize,
2393    ) -> Self {
2394        self.max_session_output_bytes = max_session_output_bytes;
2395        self
2396    }
2397
2398    /// Returns a copy with `max_capability_payload_bytes` set to the given capability payload cap.
2399    #[must_use]
2400    pub const fn with_max_capability_payload_bytes(
2401        mut self,
2402        max_capability_payload_bytes: usize,
2403    ) -> Self {
2404        self.max_capability_payload_bytes = max_capability_payload_bytes;
2405        self
2406    }
2407
2408    /// Returns a copy with `max_trace_bytes` set to the given retained trace buffer cap.
2409    #[must_use]
2410    pub const fn with_max_trace_bytes(mut self, max_trace_bytes: usize) -> Self {
2411        self.max_trace_bytes = max_trace_bytes;
2412        self
2413    }
2414
2415    /// Applies emergency host [`DcWasmWatchdogLimits`] on top of this logical supervisor policy.
2416    ///
2417    /// Physical memory and table ceilings are clamped to the watchdog's physical bounds
2418    /// (while preserving `max_memory_pages` and `max_table_elements` so physical exhaustion
2419    /// below logical quota interrupts externally rather than returning a normal `-1`).
2420    #[must_use]
2421    pub const fn apply_watchdog_bounds(
2422        mut self,
2423        watchdog: DcWasmWatchdogLimits,
2424    ) -> Self {
2425        if watchdog.physical_max_memory_pages < self.physical_max_memory_pages {
2426            self.physical_max_memory_pages = watchdog.physical_max_memory_pages;
2427        }
2428        if watchdog.physical_max_table_elements
2429            < self.physical_max_table_elements
2430        {
2431            self.physical_max_table_elements =
2432                watchdog.physical_max_table_elements;
2433        }
2434        if watchdog.hard_max_instructions_per_step
2435            < self.max_instructions_per_step
2436        {
2437            self.max_instructions_per_step =
2438                watchdog.hard_max_instructions_per_step;
2439        }
2440        if watchdog.hard_max_session_output_bytes
2441            < self.max_session_output_bytes
2442        {
2443            self.max_session_output_bytes =
2444                watchdog.hard_max_session_output_bytes;
2445        }
2446        self
2447    }
2448
2449    /// Serializes these compiled resource limits into a canonical 76-byte little-endian
2450    /// configuration snapshot for deterministic execution trace recording and replay.
2451    #[must_use]
2452    pub fn encode_canonical_config_bytes(&self) -> Vec<u8> {
2453        let mut out = Vec::with_capacity(76);
2454        out.extend_from_slice(&self.accounting_version.to_le_bytes());
2455        out.extend_from_slice(&self.max_instructions_per_step.to_le_bytes());
2456        // Reason for fallback: on hypothetical >64-bit platforms, usize caps saturate to u64::MAX.
2457        let u64_of = |v: usize| u64::try_from(v).unwrap_or(u64::MAX);
2458        out.extend_from_slice(&u64_of(self.max_memory_pages).to_le_bytes());
2459        out.extend_from_slice(
2460            &u64_of(self.physical_max_memory_pages).to_le_bytes(),
2461        );
2462        out.extend_from_slice(&u64_of(self.max_table_elements).to_le_bytes());
2463        out.extend_from_slice(
2464            &u64_of(self.physical_max_table_elements).to_le_bytes(),
2465        );
2466        out.extend_from_slice(
2467            &u64_of(self.max_step_output_bytes).to_le_bytes(),
2468        );
2469        out.extend_from_slice(
2470            &u64_of(self.max_session_output_bytes).to_le_bytes(),
2471        );
2472        out.extend_from_slice(
2473            &u64_of(self.max_capability_payload_bytes).to_le_bytes(),
2474        );
2475        out.extend_from_slice(&u64_of(self.max_trace_bytes).to_le_bytes());
2476        out
2477    }
2478
2479    /// Decodes a canonical 76-byte configuration snapshot produced by
2480    /// [`Self::encode_canonical_config_bytes`].
2481    ///
2482    /// # Errors
2483    /// Returns an error if `bytes.len() != 76` or if `accounting_version` is unsupported.
2484    pub fn decode_canonical_config_bytes(bytes: &[u8]) -> Result<Self> {
2485        ensure!(
2486            bytes.len() == 76,
2487            "Invalid canonical resource config byte length: expected 76 bytes, found {}",
2488            bytes.len()
2489        );
2490        let read_u32 = |offset: usize| -> Result<u32> {
2491            let slice = bytes
2492                .get(offset..offset.saturating_add(4))
2493                .context("Out-of-bounds u32 read in canonical config")?;
2494            let arr: [u8; 4] = slice.try_into()?;
2495            Ok(u32::from_le_bytes(arr))
2496        };
2497        let read_u64 = |offset: usize| -> Result<u64> {
2498            let slice = bytes
2499                .get(offset..offset.saturating_add(8))
2500                .context("Out-of-bounds u64 read in canonical config")?;
2501            let arr: [u8; 8] = slice.try_into()?;
2502            Ok(u64::from_le_bytes(arr))
2503        };
2504        let read_usize = |offset: usize| -> Result<usize> {
2505            let v = read_u64(offset)?;
2506            // Reason for fallback: u64::MAX represents an unbounded usize::MAX cap on 32/64-bit targets.
2507            Ok(usize::try_from(v).unwrap_or(usize::MAX))
2508        };
2509        let accounting_version = read_u32(0)?;
2510        ensure!(
2511            accounting_version == WASM_RESOURCE_ACCOUNTING_VERSION,
2512            "Unsupported WASM resource accounting version {accounting_version} (expected {WASM_RESOURCE_ACCOUNTING_VERSION})"
2513        );
2514        Ok(Self {
2515            accounting_version,
2516            max_instructions_per_step: read_u64(4)?,
2517            max_memory_pages: read_usize(12)?,
2518            physical_max_memory_pages: read_usize(20)?,
2519            max_table_elements: read_usize(28)?,
2520            physical_max_table_elements: read_usize(36)?,
2521            max_step_output_bytes: read_usize(44)?,
2522            max_session_output_bytes: read_usize(52)?,
2523            max_capability_payload_bytes: read_usize(60)?,
2524            max_trace_bytes: read_usize(68)?,
2525        })
2526    }
2527}
2528
2529/// External resource interruption raised when a [`DcWasmSession`] exceeds a compute or memory/output budget.
2530///
2531/// Resource metering is distinct from capability requests: when a compute quota or physical memory
2532/// limit interrupts execution, the host exposes and records this interruption as an external
2533/// resource event in the execution trace (`Privilege::ExcessiveCompute`).
2534#[derive(Debug, Clone, PartialEq, Eq)]
2535pub enum WasmResourceInterruption {
2536    /// Portable compute quota was exhausted before the next WebAssembly operation took effect.
2537    ComputeQuotaExhausted {
2538        /// Active compute quota limit that was exhausted.
2539        limit: u64,
2540    },
2541    /// Linear memory page allocation or physical growth exceeded the active page limit.
2542    MemoryLimitExceeded {
2543        /// Total 64 KiB pages requested or required.
2544        requested_pages: usize,
2545        /// Maximum 64 KiB pages permitted.
2546        max_pages: usize,
2547    },
2548    /// Table element allocation or physical growth exceeded the active element limit.
2549    TableLimitExceeded {
2550        /// Total table elements requested or required.
2551        requested_elements: usize,
2552        /// Maximum table elements permitted.
2553        max_elements: usize,
2554    },
2555    /// Single-step output slice (`out_len`) exceeded `max_step_output_bytes`.
2556    StepOutputSliceTooLarge {
2557        /// Byte length reported in the step's output mailbox (`out_len`).
2558        output_bytes: usize,
2559        /// Maximum single-step output byte length permitted.
2560        max_step_output_bytes: usize,
2561    },
2562    /// Cumulative output bytes across the session exceeded `max_session_output_bytes`.
2563    SessionOutputBudgetExceeded {
2564        /// Cumulative output bytes including the attempted step output.
2565        cumulative_output_bytes: usize,
2566        /// Maximum cumulative session output byte length permitted.
2567        max_session_output_bytes: usize,
2568    },
2569    /// Capability request or response payload exceeded `max_capability_payload_bytes`.
2570    CapabilityPayloadTooLarge {
2571        /// Byte length of the capability request or response payload.
2572        payload_bytes: usize,
2573        /// Maximum capability payload byte length permitted.
2574        max_capability_payload_bytes: usize,
2575    },
2576    /// Retained execution trace buffer exceeded `max_trace_bytes`.
2577    TraceBufferBudgetExceeded {
2578        /// Cumulative trace buffer byte length including the attempted event.
2579        cumulative_trace_bytes: usize,
2580        /// Maximum retained trace buffer byte length permitted.
2581        max_trace_bytes: usize,
2582    },
2583}
2584
2585impl std::fmt::Display for WasmResourceInterruption {
2586    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2587        match self {
2588            Self::ComputeQuotaExhausted { limit } => write!(
2589                f,
2590                "WASM compute quota exhausted (limit: {limit} compute units)"
2591            ),
2592            Self::MemoryLimitExceeded {
2593                requested_pages,
2594                max_pages,
2595            } => write!(
2596                f,
2597                "WASM linear memory limit exceeded: requested {requested_pages} pages (max: {max_pages} pages)"
2598            ),
2599            Self::TableLimitExceeded {
2600                requested_elements,
2601                max_elements,
2602            } => write!(
2603                f,
2604                "WASM table element limit exceeded: requested {requested_elements} elements (max: {max_elements} elements)"
2605            ),
2606            Self::StepOutputSliceTooLarge {
2607                output_bytes,
2608                max_step_output_bytes,
2609            } => write!(
2610                f,
2611                "WASM single-step output slice length {output_bytes} bytes exceeds limit ({max_step_output_bytes} bytes)"
2612            ),
2613            Self::SessionOutputBudgetExceeded {
2614                cumulative_output_bytes,
2615                max_session_output_bytes,
2616            } => write!(
2617                f,
2618                "WASM cumulative session output {cumulative_output_bytes} bytes exceeds budget ({max_session_output_bytes} bytes)"
2619            ),
2620            Self::CapabilityPayloadTooLarge {
2621                payload_bytes,
2622                max_capability_payload_bytes,
2623            } => write!(
2624                f,
2625                "WASM capability payload length {payload_bytes} bytes exceeds limit ({max_capability_payload_bytes} bytes)"
2626            ),
2627            Self::TraceBufferBudgetExceeded {
2628                cumulative_trace_bytes,
2629                max_trace_bytes,
2630            } => write!(
2631                f,
2632                "WASM execution trace buffer {cumulative_trace_bytes} bytes exceeds budget ({max_trace_bytes} bytes)"
2633            ),
2634        }
2635    }
2636}
2637
2638impl std::error::Error for WasmResourceInterruption {}
2639
2640/// Non-resource WebAssembly trap raised while executing the hoisted module `start` function.
2641#[derive(Debug, Clone, PartialEq, Eq)]
2642pub struct WasmStartSectionTrap {
2643    /// Diagnostic description of the trap raised during `start`.
2644    pub message: String,
2645}
2646
2647impl std::fmt::Display for WasmStartSectionTrap {
2648    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2649        f.write_str(&self.message)
2650    }
2651}
2652
2653impl std::error::Error for WasmStartSectionTrap {}
2654
2655/// Outcome of a single [`DcWasmSession::step`] invocation, pairing the [`WasmStepStatus`]
2656/// with the [`DcMstring`] decoded from the WASM instance's output slice in linear memory.
2657#[derive(Debug, Clone, PartialEq, Eq)]
2658pub enum WasmStepOutcome {
2659    /// `0 = Complete`: Conversion or execution finished with the output [`DcMstring`].
2660    Complete(DcMstring),
2661    /// `1 = YieldFrame`: Emitted a streaming frame [`DcMstring`]; call `step()` again to continue.
2662    YieldFrame(DcMstring),
2663    /// `2 = RequestCapability`: Paused requesting a capability described by [`DcMstring`];
2664    /// write the response via [`DcWasmSession::provide_input`] and call `step()` again to resume.
2665    RequestCapability(DcMstring),
2666}
2667
2668/// Execution backend selection for instantiating a [`DcWasmSession`].
2669#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2670pub enum DcWasmExecutionBackend {
2671    /// Automatically dispatch to a registered native safe-Rust substitute when
2672    /// `(WASM_RESOURCE_ACCOUNTING_VERSION, sha256(wasm))` matches, falling back
2673    /// cleanly to instrumented `tinywasm` otherwise.
2674    #[default]
2675    Auto,
2676    /// Force instrumented WebAssembly execution on `tinywasm`, bypassing native
2677    /// substitutes.
2678    ForceTinyWasm,
2679}
2680
2681#[derive(Debug, Clone, Copy)]
2682struct CtbGlobalAddrs {
2683    quota_rem: u32,
2684    quota_consumed: u32,
2685    exhausted: u32,
2686    interrupted_op: u32,
2687    required_cost: u32,
2688    op_ordinal: u32,
2689    total_mem_pages: u32,
2690    max_mem_pages: u32,
2691    phys_max_mem_pages: u32,
2692    total_table_elems: u32,
2693    max_table_elems: u32,
2694    phys_max_table_elems: u32,
2695    resume_target_op: u32,
2696}
2697
2698impl CtbGlobalAddrs {
2699    fn resolve(instance: &ModuleInstance) -> Result<Self> {
2700        let lookup = |name: &str| -> Result<u32> {
2701            match instance.export_addr(name) {
2702                Some(ExternVal::Global(addr)) => Ok(addr),
2703                other => bail!(
2704                    "Instrumented WASM module missing exported global '{name}' (found {other:?})"
2705                ),
2706            }
2707        };
2708        Ok(Self {
2709            quota_rem: lookup(CTB_QUOTA_REMAINING_EXPORT)?,
2710            quota_consumed: lookup(CTB_QUOTA_CONSUMED_EXPORT)?,
2711            exhausted: lookup(CTB_EXHAUSTED_EXPORT)?,
2712            interrupted_op: lookup(CTB_INTERRUPTED_OP_EXPORT)?,
2713            required_cost: lookup(CTB_REQUIRED_COST_EXPORT)?,
2714            op_ordinal: lookup(CTB_OP_ORDINAL_EXPORT)?,
2715            total_mem_pages: lookup(CTB_TOTAL_MEM_PAGES_EXPORT)?,
2716            max_mem_pages: lookup(CTB_MAX_MEM_PAGES_EXPORT)?,
2717            phys_max_mem_pages: lookup(CTB_PHYS_MAX_MEM_PAGES_EXPORT)?,
2718            total_table_elems: lookup(CTB_TOTAL_TABLE_ELEMS_EXPORT)?,
2719            max_table_elems: lookup(CTB_MAX_TABLE_ELEMS_EXPORT)?,
2720            phys_max_table_elems: lookup(CTB_PHYS_MAX_TABLE_ELEMS_EXPORT)?,
2721            resume_target_op: lookup(CTB_RESUME_TARGET_OP_EXPORT)?,
2722        })
2723    }
2724}
2725
2726type Reply<T> = std::sync::mpsc::Sender<T>;
2727
2728enum WorkerCommand {
2729    ConfigureLimits {
2730        limits: DcWasmResourceLimits,
2731        reply: Reply<()>,
2732    },
2733    ExportedGlobalI32 {
2734        name: String,
2735        reply: Reply<Option<i32>>,
2736    },
2737    ExportedGlobalI64 {
2738        name: String,
2739        reply: Reply<Option<i64>>,
2740    },
2741    ReadMemory {
2742        offset: usize,
2743        len: usize,
2744        reply: Reply<Result<Vec<u8>>>,
2745    },
2746    ReadOutputMailboxHeader {
2747        reply: Reply<Result<(usize, usize)>>,
2748    },
2749    ReadCurrentMemoryPages {
2750        reply: Reply<Result<usize>>,
2751    },
2752    ReadCurrentTableElements {
2753        reply: Reply<usize>,
2754    },
2755    ReadExportedMemoryPages {
2756        reply: Reply<Result<usize>>,
2757    },
2758    ReadQuotaConsumed {
2759        reply: Reply<u64>,
2760    },
2761    WriteInput {
2762        input_ptr: usize,
2763        payload: Vec<u8>,
2764        header: [u8; 32],
2765        required_mem_bytes: usize,
2766        total_store_pages: usize,
2767        other_mem_pages: usize,
2768        effective_max_pages: usize,
2769        reply: Reply<Result<()>>,
2770    },
2771    StartStep {
2772        entry_func_name: String,
2773        in_ptr_i32: i32,
2774        in_len_i32: i32,
2775        default_output_ptr: u32,
2776        quota_rem: u64,
2777        limits: DcWasmResourceLimits,
2778    },
2779    ResumeStep {
2780        quota_rem: u64,
2781        limits: DcWasmResourceLimits,
2782    },
2783    ResumeCapability {
2784        response_bytes: Vec<u8>,
2785        quota_rem: u64,
2786        limits: DcWasmResourceLimits,
2787    },
2788    Shutdown,
2789}
2790
2791enum WorkerEvent {
2792    StepPausedOnQuota {
2793        consumed: u64,
2794        remaining: u64,
2795        interrupted_op: u64,
2796        required_cost: u64,
2797    },
2798    StepPausedOnCapability {
2799        consumed: u64,
2800        remaining: u64,
2801        out_ptr: usize,
2802        out_len: usize,
2803    },
2804    StepFinished {
2805        call_res: std::result::Result<i32, String>,
2806        consumed: u64,
2807        remaining: u64,
2808        exhausted: i32,
2809        interrupted_op: u64,
2810        required_cost: u64,
2811    },
2812}
2813
2814struct WorkerInitSuccess {
2815    entry_func_name: String,
2816    base_io_offset: usize,
2817    remaining_compute_quota: u64,
2818    total_instructions_executed: u64,
2819}
2820
2821struct SessionWorkerHandle {
2822    cmd_tx: std::sync::mpsc::Sender<WorkerCommand>,
2823    evt_rx: std::sync::mpsc::Receiver<WorkerEvent>,
2824}
2825
2826impl std::fmt::Debug for SessionWorkerHandle {
2827    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2828        f.debug_struct("SessionWorkerHandle").finish_non_exhaustive()
2829    }
2830}
2831
2832impl Drop for SessionWorkerHandle {
2833    fn drop(&mut self) {
2834        let _ = self.cmd_tx.send(WorkerCommand::Shutdown);
2835    }
2836}
2837
2838/// Pure-compute WebAssembly execution state machine (`step() -> StatusCode`) backed by
2839/// either `tinywasm` (with portable bytecode compute-quota instrumentation) or a
2840/// bit-for-bit equivalent Guix-style compiled safe-Rust substitute.
2841///
2842/// Owns a persistent worker thread whose call stack, locals, linear memory, tables,
2843/// and globals survive across `step()` calls and mid-step compute-quota pauses without
2844/// re-executing earlier instructions.
2845#[derive(Debug)]
2846pub struct DcWasmSession {
2847    raw_wasm_bytes: Vec<u8>,
2848    instrumented_bytes: std::sync::OnceLock<Vec<u8>>,
2849    used_native_substitute: bool,
2850    worker: std::sync::Mutex<SessionWorkerHandle>,
2851    entry_func_name: String,
2852    base_io_offset: usize,
2853    current_input_ptr: u32,
2854    current_input_len: u32,
2855    default_output_ptr: u32,
2856    most_recent_node_id: Option<u128>,
2857    resource_limits: DcWasmResourceLimits,
2858    remaining_compute_quota: u64,
2859    current_compute_quota_limit: u64,
2860    cumulative_output_bytes: usize,
2861    last_step_instructions: u64,
2862    total_instructions_executed: u64,
2863    last_interrupted_op_ordinal: Option<u64>,
2864    last_interrupted_op_required_cost: Option<u64>,
2865    last_resource_interruption: Option<WasmResourceInterruption>,
2866    current_input_doc: DcMstring,
2867    paused_on_compute_quota: bool,
2868    paused_on_capability: bool,
2869    pending_capability_response: Option<Vec<u8>>,
2870    pending_quota_increase_since_pause: u64,
2871    shared_task_quota: Option<SharedWasmTaskQuota>,
2872}
2873
2874fn align_up_8(val: usize) -> Result<usize> {
2875    let rem = val & 7;
2876    if rem == 0 {
2877        Ok(val)
2878    } else {
2879        val.checked_add(8usize.saturating_sub(rem))
2880            .context("Linear memory offset overflow during 8-byte alignment")
2881    }
2882}
2883
2884fn decode_output_bytes_to_dcmstring(out_bytes: &[u8]) -> Result<DcMstring> {
2885    if out_bytes.len() >= DCMM_HEADER_LEN
2886        && out_bytes.get(0..5) == Some(DCMM_MAGIC.as_slice())
2887    {
2888        return DcMstring::from_slice(out_bytes).map_err(|e| {
2889            anyhow!(
2890                "WASM output buffer contains invalid DcMixed document: {e}"
2891            )
2892        });
2893    }
2894    let mut full =
2895        Vec::with_capacity(DCMM_HEADER_LEN.saturating_add(out_bytes.len()));
2896    full.extend_from_slice(&DCMM_MAGIC);
2897    full.extend_from_slice(&DCMM_UUID);
2898    full.extend_from_slice(out_bytes);
2899    match DcMstring::from_bytes(full) {
2900        Ok(mst) => Ok(mst),
2901        Err(mixed_err) => {
2902            if let Ok(dc_str) = DcStr::from_bytes(out_bytes)
2903                && let Ok(mst) = DcMstring::from_dc_str(dc_str)
2904            {
2905                return Ok(mst);
2906            }
2907            Err(anyhow!(
2908                "WASM output buffer contains invalid DcTF payload: {mixed_err}"
2909            ))
2910        }
2911    }
2912}
2913
2914fn read_store_global_u64(store: &Store, addr: u32) -> u64 {
2915    match store.get_global_val(addr) {
2916        TinyWasmValue::Value64(v) => v,
2917        TinyWasmValue::Value32(v) => u64::from(v),
2918        _ => 0,
2919    }
2920}
2921
2922fn read_store_global_i32(store: &Store, addr: u32) -> i32 {
2923    match store.get_global_val(addr) {
2924        TinyWasmValue::Value32(v) => i32::from_le_bytes(v.to_le_bytes()),
2925        TinyWasmValue::Value64(v) => {
2926            // Reason for fallback: callers reading i32 globals only pass i32-typed global addresses;
2927            // out-of-range i64 values cannot arise for valid i32 globals and safely saturate to 0.
2928            i32::try_from(i64::from_le_bytes(v.to_le_bytes())).unwrap_or(0)
2929        }
2930        _ => 0,
2931    }
2932}
2933
2934fn write_store_global_u64(store: &mut Store, addr: u32, val: u64) {
2935    store.set_global_val(addr, TinyWasmValue::Value64(val));
2936}
2937
2938fn write_store_global_i32(store: &mut Store, addr: u32, val: i32) {
2939    store.set_global_val(
2940        addr,
2941        TinyWasmValue::Value32(u32::from_le_bytes(val.to_le_bytes())),
2942    );
2943}
2944
2945fn configure_store_limits(
2946    store: &mut Store,
2947    addrs: &CtbGlobalAddrs,
2948    limits: &DcWasmResourceLimits,
2949) {
2950    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2951    // saturate to u64::MAX in the 64-bit WASM quota global.
2952    let max_mem = u64::try_from(limits.max_memory_pages).unwrap_or(u64::MAX);
2953    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2954    // saturate to u64::MAX in the 64-bit WASM quota global.
2955    let phys_max_mem =
2956        u64::try_from(limits.physical_max_memory_pages).unwrap_or(u64::MAX);
2957    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2958    // saturate to u64::MAX in the 64-bit WASM quota global.
2959    let max_tbl = u64::try_from(limits.max_table_elements).unwrap_or(u64::MAX);
2960    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2961    // saturate to u64::MAX in the 64-bit WASM quota global.
2962    let phys_max_tbl =
2963        u64::try_from(limits.physical_max_table_elements).unwrap_or(u64::MAX);
2964    write_store_global_u64(store, addrs.max_mem_pages, max_mem);
2965    write_store_global_u64(store, addrs.phys_max_mem_pages, phys_max_mem);
2966    write_store_global_u64(store, addrs.max_table_elems, max_tbl);
2967    write_store_global_u64(store, addrs.phys_max_table_elems, phys_max_tbl);
2968}
2969
2970fn configure_vm_limits(vm: &mut SubstituteVm, limits: &DcWasmResourceLimits) {
2971    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2972    // saturate to u64::MAX in the 64-bit VM resource ceiling.
2973    vm.max_mem_pages = u64::try_from(limits.max_memory_pages).unwrap_or(u64::MAX);
2974    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2975    // saturate to u64::MAX in the 64-bit VM resource ceiling.
2976    vm.phys_max_mem_pages =
2977        u64::try_from(limits.physical_max_memory_pages).unwrap_or(u64::MAX);
2978    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2979    // saturate to u64::MAX in the 64-bit VM resource ceiling.
2980    vm.max_table_elems =
2981        u64::try_from(limits.max_table_elements).unwrap_or(u64::MAX);
2982    // Reason for fallback: on hypothetical >64-bit usize platforms, values above u64::MAX
2983    // saturate to u64::MAX in the 64-bit VM resource ceiling.
2984    vm.phys_max_table_elems =
2985        u64::try_from(limits.physical_max_table_elements).unwrap_or(u64::MAX);
2986}
2987
2988trait HostLinearMemory {
2989    fn mem_page_count(&mut self) -> usize;
2990    fn mem_load(&self, offset: usize, len: usize) -> Result<Vec<u8>>;
2991    fn mem_store(&mut self, offset: usize, bytes: &[u8]) -> Result<()>;
2992    fn mem_grow(&mut self, delta: i32) -> Option<i32>;
2993}
2994
2995impl HostLinearMemory for MemoryRefMut<'_> {
2996    fn mem_page_count(&mut self) -> usize {
2997        self.page_count()
2998    }
2999
3000    fn mem_load(&self, offset: usize, len: usize) -> Result<Vec<u8>> {
3001        self.load(offset, len)
3002            .map(<[u8]>::to_vec)
3003            .map_err(|e| anyhow!("WASM memory load failed: {e:?}"))
3004    }
3005
3006    fn mem_store(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
3007        self.store(offset, bytes.len(), bytes)
3008            .map_err(|e| anyhow!("WASM memory store failed: {e:?}"))
3009    }
3010
3011    fn mem_grow(&mut self, delta: i32) -> Option<i32> {
3012        self.grow(delta)
3013    }
3014}
3015
3016impl HostLinearMemory for WasmLinearMemory {
3017    fn mem_page_count(&mut self) -> usize {
3018        self.page_count()
3019    }
3020
3021    fn mem_load(&self, offset: usize, len: usize) -> Result<Vec<u8>> {
3022        self.load_bytes(offset, len)
3023            .map(<[u8]>::to_vec)
3024            .map_err(|e| anyhow!("WASM substitute memory load failed: {e}"))
3025    }
3026
3027    fn mem_store(&mut self, offset: usize, bytes: &[u8]) -> Result<()> {
3028        self.store_bytes(offset, bytes)
3029            .map_err(|e| anyhow!("WASM substitute memory store failed: {e}"))
3030    }
3031
3032    fn mem_grow(&mut self, delta: i32) -> Option<i32> {
3033        let delta_u32 = u32::try_from(delta).ok()?;
3034        self.grow_host(delta_u32)
3035    }
3036}
3037
3038fn read_output_mailbox_header_from_mem<M: HostLinearMemory>(
3039    mem: &M,
3040) -> Result<(usize, usize)> {
3041    let hdr = mem.mem_load(8, 8).map_err(|e| {
3042        anyhow!("Failed to read WASM output mailbox header at 8..16: {e}")
3043    })?;
3044    let hdr_arr: [u8; 8] = hdr
3045        .try_into()
3046        .map_err(|_| anyhow!("WASM output mailbox header slice is not 8 bytes"))?;
3047    let out_ptr = usize::try_from(u32::from_le_bytes([
3048        hdr_arr[0], hdr_arr[1], hdr_arr[2], hdr_arr[3],
3049    ]))?;
3050    let out_len = usize::try_from(u32::from_le_bytes([
3051        hdr_arr[4], hdr_arr[5], hdr_arr[6], hdr_arr[7],
3052    ]))?;
3053    Ok((out_ptr, out_len))
3054}
3055
3056#[allow(
3057    clippy::too_many_arguments,
3058    reason = "Shared mailbox write and growth helper across WASM and substitute engines"
3059)]
3060fn write_input_on_memory<M: HostLinearMemory>(
3061    mem: &mut M,
3062    input_ptr: usize,
3063    payload: &[u8],
3064    header: &[u8; 32],
3065    required_mem_bytes: usize,
3066    total_store_pages: usize,
3067    other_mem_pages: usize,
3068    effective_max_pages: usize,
3069) -> Result<usize> {
3070    let current_pages = mem.mem_page_count();
3071    let current_bytes = current_pages.saturating_mul(65_536);
3072    let mut new_total_store_pages = total_store_pages;
3073    if required_mem_bytes > current_bytes {
3074        let missing_bytes = required_mem_bytes.saturating_sub(current_bytes);
3075        // Reason for fallback: 65_536 is a non-zero constant page divisor.
3076        let extra_pages = missing_bytes
3077            .saturating_add(65_535)
3078            .checked_div(65_536)
3079            .unwrap_or(1);
3080        let delta = i32::try_from(extra_pages)
3081            .context("WASM memory page growth exceeds i32")?;
3082        if mem.mem_grow(delta).is_none() {
3083            return Err(anyhow::Error::new(
3084                WasmResourceInterruption::MemoryLimitExceeded {
3085                    requested_pages: other_mem_pages
3086                        .saturating_add(current_pages)
3087                        .saturating_add(extra_pages),
3088                    max_pages: effective_max_pages,
3089                },
3090            ));
3091        }
3092        new_total_store_pages = other_mem_pages
3093            .saturating_add(current_pages.saturating_add(extra_pages));
3094    }
3095    if !payload.is_empty() {
3096        mem.mem_store(input_ptr, payload)?;
3097    }
3098    mem.mem_store(0, header)?;
3099    Ok(new_total_store_pages)
3100}
3101
3102fn apply_capability_response_on_memory<M: HostLinearMemory>(
3103    mem: &mut M,
3104    base_io_offset: usize,
3105    response_bytes: &[u8],
3106    heap_ptr: usize,
3107    total_store_pages: usize,
3108    max_allowed_pages: usize,
3109) -> std::result::Result<(Option<usize>, usize), Option<u64>> {
3110    let hdr = mem.mem_load(0, 16).map_err(|_| None)?;
3111    let [
3112        b0, b1, b2, b3, b4, b5, b6, b7,
3113        b8, b9, b10, b11, b12, b13, b14, b15,
3114    ]: [u8; 16] = hdr.try_into().map_err(|_| None)?;
3115    let prev_in_ptr =
3116        usize::try_from(u32::from_le_bytes([b0, b1, b2, b3])).map_err(|_| None)?;
3117    let prev_in_len =
3118        usize::try_from(u32::from_le_bytes([b4, b5, b6, b7])).map_err(|_| None)?;
3119    let prev_out_ptr =
3120        usize::try_from(u32::from_le_bytes([b8, b9, b10, b11])).map_err(|_| None)?;
3121    let prev_out_len =
3122        usize::try_from(u32::from_le_bytes([b12, b13, b14, b15])).map_err(|_| None)?;
3123    let prev_in_end = prev_in_ptr.saturating_add(prev_in_len);
3124    let prev_out_end = prev_out_ptr.saturating_add(prev_out_len);
3125    let resp_ptr = align_up_8(
3126        base_io_offset
3127            .max(prev_in_end)
3128            .max(prev_out_end)
3129            .max(heap_ptr),
3130    )
3131    .map_err(|_| None)?;
3132    let resp_len = response_bytes.len();
3133    let required_bytes = resp_ptr.checked_add(resp_len).ok_or(None)?;
3134    let current_pages = mem.mem_page_count();
3135    let current_bytes = current_pages.saturating_mul(65_536);
3136    let other_mem_pages = total_store_pages.saturating_sub(current_pages);
3137    let mut updated_total = None;
3138    if required_bytes > current_bytes {
3139        let missing = required_bytes.saturating_sub(current_bytes);
3140        // Reason for fallback: 65_536 is a non-zero constant page size divisor.
3141        let extra_pages = missing
3142            .saturating_add(65_535)
3143            .checked_div(65_536)
3144            .unwrap_or(1);
3145        let new_total = other_mem_pages
3146            .saturating_add(current_pages.saturating_add(extra_pages));
3147        if new_total > max_allowed_pages {
3148            return Err(Some(u64::try_from(new_total).map_err(|_| None)?));
3149        }
3150        let delta = i32::try_from(extra_pages).map_err(|_| None)?;
3151        if mem.mem_grow(delta).is_none() {
3152            return Err(Some(u64::try_from(new_total).map_err(|_| None)?));
3153        }
3154        updated_total = Some(new_total);
3155    }
3156    if !response_bytes.is_empty() {
3157        mem.mem_store(resp_ptr, response_bytes).map_err(|_| None)?;
3158    }
3159    let resp_ptr_u32 = u32::try_from(resp_ptr).map_err(|_| None)?;
3160    let resp_len_u32 = u32::try_from(resp_len).map_err(|_| None)?;
3161    let mut next_hdr = [0u8; 16];
3162    next_hdr[0..4].copy_from_slice(&resp_ptr_u32.to_le_bytes());
3163    next_hdr[4..8].copy_from_slice(&resp_len_u32.to_le_bytes());
3164    mem.mem_store(0, &next_hdr).map_err(|_| None)?;
3165    let aligned_end = align_up_8(required_bytes).map_err(|_| None)?;
3166    Ok((updated_total, aligned_end))
3167}
3168
3169fn reset_output_mailbox_on_mem<M: HostLinearMemory>(
3170    mem: &mut M,
3171    default_output_ptr: u32,
3172) {
3173    let mut out_reset = [0u8; 8];
3174    out_reset[0..4].copy_from_slice(&default_output_ptr.to_le_bytes());
3175    out_reset[4..8].copy_from_slice(&0u32.to_le_bytes());
3176    if let Ok(out_off) = usize::try_from(DC_WASM_MAILBOX_OUTPUT_PTR) {
3177        let _ = mem.mem_store(out_off, &out_reset);
3178    }
3179}
3180
3181fn last_nonzero_memory_end_on_slice(slice: &[u8]) -> usize {
3182    // Reason for fallback: an all-zero initial memory has 0 nonzero bytes written.
3183    slice
3184        .iter()
3185        .rposition(|&b| b != 0)
3186        .map_or(0, |idx| idx.saturating_add(1))
3187}
3188
3189fn map_start_section_error(
3190    exhausted: i32,
3191    interrupted_op: u64,
3192    limit: u64,
3193    effective_max_mem: usize,
3194    effective_max_tbl: usize,
3195    trap_desc: impl std::fmt::Display,
3196) -> anyhow::Error {
3197    match exhausted {
3198        1 => anyhow::Error::new(
3199            WasmResourceInterruption::ComputeQuotaExhausted { limit },
3200        ),
3201        2 => {
3202            // Reason for fallback: on 32-bit hosts, a 64-bit requested page count
3203            // exceeding usize::MAX saturates to usize::MAX in the diagnostic report.
3204            let requested_pages =
3205                usize::try_from(interrupted_op).unwrap_or(usize::MAX);
3206            anyhow::Error::new(WasmResourceInterruption::MemoryLimitExceeded {
3207                requested_pages,
3208                max_pages: effective_max_mem,
3209            })
3210        }
3211        3 => {
3212            // Reason for fallback: on 32-bit hosts, a 64-bit requested element count
3213            // exceeding usize::MAX saturates to usize::MAX in the diagnostic report.
3214            let requested_elements =
3215                usize::try_from(interrupted_op).unwrap_or(usize::MAX);
3216            anyhow::Error::new(WasmResourceInterruption::TableLimitExceeded {
3217                requested_elements,
3218                max_elements: effective_max_tbl,
3219            })
3220        }
3221        _ => anyhow::Error::new(WasmStartSectionTrap {
3222            message: format!(
3223                "Failed to execute WebAssembly start section: {trap_desc}"
3224            ),
3225        }),
3226    }
3227}
3228
3229fn tinywasm_handle_query(
3230    store: &mut Store,
3231    instance: &ModuleInstance,
3232    addrs: &CtbGlobalAddrs,
3233    cmd: WorkerCommand,
3234) -> Option<WorkerCommand> {
3235    match cmd {
3236        WorkerCommand::ConfigureLimits { limits, reply } => {
3237            configure_store_limits(store, addrs, &limits);
3238            let _ = reply.send(());
3239            None
3240        }
3241        WorkerCommand::ExportedGlobalI32 { name, reply } => {
3242            let val = if let Some(ExternVal::Global(addr)) =
3243                instance.export_addr(&name)
3244            {
3245                Some(read_store_global_i32(store, addr))
3246            } else {
3247                None
3248            };
3249            let _ = reply.send(val);
3250            None
3251        }
3252        WorkerCommand::ExportedGlobalI64 { name, reply } => {
3253            let val = if let Some(ExternVal::Global(addr)) =
3254                instance.export_addr(&name)
3255            {
3256                let u = read_store_global_u64(store, addr);
3257                Some(i64::from_le_bytes(u.to_le_bytes()))
3258            } else {
3259                None
3260            };
3261            let _ = reply.send(val);
3262            None
3263        }
3264        WorkerCommand::ReadMemory { offset, len, reply } => {
3265            let res = (|| -> Result<Vec<u8>> {
3266                let mem = instance
3267                    .exported_memory(store, "memory")
3268                    .map_err(|e| {
3269                        anyhow!("Failed to access WASM exported 'memory': {e:?}")
3270                    })?;
3271                mem.load_vec(offset, len).map_err(|e| {
3272                    anyhow!(
3273                        "Failed to read WASM memory at {offset}..{}: {e:?}",
3274                        offset.saturating_add(len)
3275                    )
3276                })
3277            })();
3278            let _ = reply.send(res);
3279            None
3280        }
3281        WorkerCommand::ReadOutputMailboxHeader { reply } => {
3282            let res = (|| -> Result<(usize, usize)> {
3283                let mut mem = instance
3284                    .exported_memory_mut(store, "memory")
3285                    .map_err(|e| {
3286                        anyhow!("Failed to access WASM exported 'memory': {e:?}")
3287                    })?;
3288                read_output_mailbox_header_from_mem(&mut mem)
3289            })();
3290            let _ = reply.send(res);
3291            None
3292        }
3293        WorkerCommand::ReadCurrentMemoryPages { reply } => {
3294            let res = (|| -> Result<usize> {
3295                let _mem = instance
3296                    .exported_memory(store, "memory")
3297                    .map_err(|e| {
3298                        anyhow!("Failed to access WASM exported 'memory': {e:?}")
3299                    })?;
3300                let total = read_store_global_u64(store, addrs.total_mem_pages);
3301                Ok(usize::try_from(total)?)
3302            })();
3303            let _ = reply.send(res);
3304            None
3305        }
3306        WorkerCommand::ReadCurrentTableElements { reply } => {
3307            let total = read_store_global_u64(store, addrs.total_table_elems);
3308            // Reason for fallback: on 32-bit hosts, a 64-bit table count exceeding usize::MAX
3309            // saturates to usize::MAX.
3310            let _ = reply.send(usize::try_from(total).unwrap_or(usize::MAX));
3311            None
3312        }
3313        WorkerCommand::ReadExportedMemoryPages { reply } => {
3314            let res = (|| -> Result<usize> {
3315                let mut mem = instance
3316                    .exported_memory_mut(store, "memory")
3317                    .map_err(|e| {
3318                        anyhow!("Failed to access WASM exported 'memory': {e:?}")
3319                    })?;
3320                Ok(mem.page_count())
3321            })();
3322            let _ = reply.send(res);
3323            None
3324        }
3325        WorkerCommand::ReadQuotaConsumed { reply } => {
3326            let _ = reply.send(read_store_global_u64(store, addrs.quota_consumed));
3327            None
3328        }
3329        WorkerCommand::WriteInput {
3330            input_ptr,
3331            payload,
3332            header,
3333            required_mem_bytes,
3334            total_store_pages,
3335            other_mem_pages,
3336            effective_max_pages,
3337            reply,
3338        } => {
3339            let res = (|| -> Result<()> {
3340                let mut mem = instance
3341                    .exported_memory_mut(store, "memory")
3342                    .map_err(|e| {
3343                        anyhow!("Failed to access WASM exported 'memory': {e:?}")
3344                    })?;
3345                let new_total_store_pages = write_input_on_memory(
3346                    &mut mem,
3347                    input_ptr,
3348                    &payload,
3349                    &header,
3350                    required_mem_bytes,
3351                    total_store_pages,
3352                    other_mem_pages,
3353                    effective_max_pages,
3354                )?;
3355                drop(mem);
3356                write_store_global_u64(
3357                    store,
3358                    addrs.total_mem_pages,
3359                    u64::try_from(new_total_store_pages)?,
3360                );
3361                Ok(())
3362            })();
3363            let _ = reply.send(res);
3364            None
3365        }
3366        other => Some(other),
3367    }
3368}
3369
3370fn read_vm_ctb_global_i32(vm: &SubstituteVm, name: &str) -> Option<i32> {
3371    if name == CTB_EXHAUSTED_EXPORT {
3372        Some(vm.exhausted)
3373    } else {
3374        None
3375    }
3376}
3377
3378fn read_vm_ctb_global_u64(vm: &SubstituteVm, name: &str) -> Option<u64> {
3379    match name {
3380        n if n == CTB_QUOTA_REMAINING_EXPORT => Some(vm.quota_remaining),
3381        n if n == CTB_QUOTA_CONSUMED_EXPORT => Some(vm.quota_consumed),
3382        n if n == CTB_INTERRUPTED_OP_EXPORT => Some(vm.interrupted_op),
3383        n if n == CTB_REQUIRED_COST_EXPORT => Some(vm.required_cost),
3384        n if n == CTB_OP_ORDINAL_EXPORT => Some(vm.op_ordinal),
3385        n if n == CTB_TOTAL_MEM_PAGES_EXPORT => Some(vm.total_mem_pages),
3386        n if n == CTB_MAX_MEM_PAGES_EXPORT => Some(vm.max_mem_pages),
3387        n if n == CTB_PHYS_MAX_MEM_PAGES_EXPORT => Some(vm.phys_max_mem_pages),
3388        n if n == CTB_TOTAL_TABLE_ELEMS_EXPORT => Some(vm.total_table_elems),
3389        n if n == CTB_MAX_TABLE_ELEMS_EXPORT => Some(vm.max_table_elems),
3390        n if n == CTB_PHYS_MAX_TABLE_ELEMS_EXPORT => Some(vm.phys_max_table_elems),
3391        n if n == CTB_RESUME_TARGET_OP_EXPORT => Some(vm.resume_target_op),
3392        _ => None,
3393    }
3394}
3395
3396fn native_vm_handle_query(
3397    vm: &mut SubstituteVm,
3398    mem_export_idx: Option<usize>,
3399    cmd: WorkerCommand,
3400) -> Option<WorkerCommand> {
3401    match cmd {
3402        WorkerCommand::ConfigureLimits { limits, reply } => {
3403            configure_vm_limits(vm, &limits);
3404            let _ = reply.send(());
3405            None
3406        }
3407        WorkerCommand::ExportedGlobalI32 { name, reply } => {
3408            let val = if let Some(v) = read_vm_ctb_global_i32(vm, &name) {
3409                Some(v)
3410            } else if name == "__heap_ptr" {
3411                vm.has_heap_ptr.then_some(vm.heap_ptr)
3412            } else {
3413                None
3414            };
3415            let _ = reply.send(val);
3416            None
3417        }
3418        WorkerCommand::ExportedGlobalI64 { name, reply } => {
3419            vm.sync_fast_budget();
3420            let val = read_vm_ctb_global_u64(vm, &name)
3421                .map(|u| i64::from_le_bytes(u.to_le_bytes()));
3422            let _ = reply.send(val);
3423            None
3424        }
3425        WorkerCommand::ReadMemory { offset, len, reply } => {
3426            let res = (|| -> Result<Vec<u8>> {
3427                let mem_idx = mem_export_idx.context(
3428                    "Failed to access WASM exported 'memory'",
3429                )?;
3430                let mem = vm.memory(mem_idx).context(
3431                    "WASM exported memory index out of bounds",
3432                )?;
3433                mem.load_bytes(offset, len)
3434                    .map(<[u8]>::to_vec)
3435                    .map_err(|e| {
3436                        anyhow!(
3437                            "Failed to read WASM memory at {offset}..{}: {e}",
3438                            offset.saturating_add(len)
3439                        )
3440                    })
3441            })();
3442            let _ = reply.send(res);
3443            None
3444        }
3445        WorkerCommand::ReadOutputMailboxHeader { reply } => {
3446            let res = (|| -> Result<(usize, usize)> {
3447                let mem_idx = mem_export_idx.context(
3448                    "Failed to access WASM exported 'memory'",
3449                )?;
3450                let mem = vm.memory(mem_idx).context(
3451                    "WASM exported memory index out of bounds",
3452                )?;
3453                read_output_mailbox_header_from_mem(mem)
3454            })();
3455            let _ = reply.send(res);
3456            None
3457        }
3458        WorkerCommand::ReadCurrentMemoryPages { reply } => {
3459            let res = (|| -> Result<usize> {
3460                let mem_idx = mem_export_idx.context(
3461                    "Failed to access WASM exported 'memory'",
3462                )?;
3463                let _ = vm.memory(mem_idx).context(
3464                    "WASM exported memory index out of bounds",
3465                )?;
3466                Ok(usize::try_from(vm.total_mem_pages)?)
3467            })();
3468            let _ = reply.send(res);
3469            None
3470        }
3471        WorkerCommand::ReadCurrentTableElements { reply } => {
3472            // Reason for fallback: on 32-bit hosts, a 64-bit table count exceeding usize::MAX
3473            // saturates to usize::MAX.
3474            let _ = reply.send(
3475                usize::try_from(vm.total_table_elems).unwrap_or(usize::MAX),
3476            );
3477            None
3478        }
3479        WorkerCommand::ReadExportedMemoryPages { reply } => {
3480            let res = (|| -> Result<usize> {
3481                let mem_idx = mem_export_idx.context(
3482                    "Failed to access WASM exported 'memory'",
3483                )?;
3484                let mem = vm.memory(mem_idx).context(
3485                    "WASM exported memory index out of bounds",
3486                )?;
3487                Ok(mem.page_count())
3488            })();
3489            let _ = reply.send(res);
3490            None
3491        }
3492        WorkerCommand::ReadQuotaConsumed { reply } => {
3493            vm.sync_fast_budget();
3494            let _ = reply.send(vm.quota_consumed);
3495            None
3496        }
3497        WorkerCommand::WriteInput {
3498            input_ptr,
3499            payload,
3500            header,
3501            required_mem_bytes,
3502            total_store_pages,
3503            other_mem_pages,
3504            effective_max_pages,
3505            reply,
3506        } => {
3507            let res = (|| -> Result<()> {
3508                let mem_idx = mem_export_idx.context(
3509                    "Failed to access WASM exported 'memory'",
3510                )?;
3511                let mem = vm.memory_mut(mem_idx).context(
3512                    "WASM exported memory index out of bounds",
3513                )?;
3514                let new_total_store_pages = write_input_on_memory(
3515                    mem,
3516                    input_ptr,
3517                    &payload,
3518                    &header,
3519                    required_mem_bytes,
3520                    total_store_pages,
3521                    other_mem_pages,
3522                    effective_max_pages,
3523                )?;
3524                vm.total_mem_pages = u64::try_from(new_total_store_pages)?;
3525                Ok(())
3526            })();
3527            let _ = reply.send(res);
3528            None
3529        }
3530        other => Some(other),
3531    }
3532}
3533
3534struct WorkerSubstituteHost<'a> {
3535    mem_export_idx: Option<usize>,
3536    base_io_offset: usize,
3537    allow_suspend: bool,
3538    shutdown_requested: &'a mut bool,
3539    cmd_rx: &'a std::sync::mpsc::Receiver<WorkerCommand>,
3540    evt_tx: &'a std::sync::mpsc::Sender<WorkerEvent>,
3541}
3542
3543impl WasmSubstituteHost for WorkerSubstituteHost<'_> {
3544    fn suspend_on_quota(
3545        &mut self,
3546        vm: &mut SubstituteVm,
3547    ) -> std::result::Result<(), WasmTrap> {
3548        if !self.allow_suspend || vm.exhausted != 1 {
3549            return Err(WasmTrap::HostAbort);
3550        }
3551        if self
3552            .evt_tx
3553            .send(WorkerEvent::StepPausedOnQuota {
3554                consumed: vm.quota_consumed,
3555                remaining: vm.quota_remaining,
3556                interrupted_op: vm.interrupted_op,
3557                required_cost: vm.required_cost,
3558            })
3559            .is_err()
3560        {
3561            *self.shutdown_requested = true;
3562            return Err(WasmTrap::HostAbort);
3563        }
3564        loop {
3565            let Ok(cmd) = self.cmd_rx.recv() else {
3566                *self.shutdown_requested = true;
3567                return Err(WasmTrap::HostAbort);
3568            };
3569            let Some(ctrl) =
3570                native_vm_handle_query(vm, self.mem_export_idx, cmd)
3571            else {
3572                continue;
3573            };
3574            match ctrl {
3575                WorkerCommand::ResumeStep { quota_rem, limits } => {
3576                    configure_vm_limits(vm, &limits);
3577                    vm.quota_remaining = quota_rem;
3578                    vm.exhausted = 0;
3579                    vm.interrupted_op = 0;
3580                    vm.required_cost = 0;
3581                    vm.resume_target_op = 0;
3582                    return Ok(());
3583                }
3584                WorkerCommand::Shutdown
3585                | WorkerCommand::StartStep { .. }
3586                | WorkerCommand::ResumeCapability { .. } => {
3587                    *self.shutdown_requested = true;
3588                    return Err(WasmTrap::HostAbort);
3589                }
3590                _ => {}
3591            }
3592        }
3593    }
3594
3595    fn request_capability(
3596        &mut self,
3597        vm: &mut SubstituteVm,
3598    ) -> std::result::Result<(), WasmTrap> {
3599        vm.sync_fast_budget();
3600        if !self.allow_suspend {
3601            return Err(WasmTrap::HostAbort);
3602        }
3603        let mem_idx = self.mem_export_idx.ok_or(WasmTrap::HostAbort)?;
3604        let (out_ptr, out_len) = {
3605            let mem = vm.memory(mem_idx).ok_or(WasmTrap::HostAbort)?;
3606            read_output_mailbox_header_from_mem(mem)
3607                .map_err(|_| WasmTrap::HostAbort)?
3608        };
3609        if self
3610            .evt_tx
3611            .send(WorkerEvent::StepPausedOnCapability {
3612                consumed: vm.quota_consumed,
3613                remaining: vm.quota_remaining,
3614                out_ptr,
3615                out_len,
3616            })
3617            .is_err()
3618        {
3619            *self.shutdown_requested = true;
3620            return Err(WasmTrap::HostAbort);
3621        }
3622        loop {
3623            let Ok(cmd) = self.cmd_rx.recv() else {
3624                *self.shutdown_requested = true;
3625                return Err(WasmTrap::HostAbort);
3626            };
3627            let Some(ctrl) =
3628                native_vm_handle_query(vm, self.mem_export_idx, cmd)
3629            else {
3630                continue;
3631            };
3632            match ctrl {
3633                WorkerCommand::ResumeCapability {
3634                    response_bytes,
3635                    quota_rem,
3636                    limits,
3637                } => {
3638                    configure_vm_limits(vm, &limits);
3639                    vm.quota_remaining = quota_rem;
3640                    vm.exhausted = 0;
3641                    vm.interrupted_op = 0;
3642                    vm.required_cost = 0;
3643                    vm.resume_target_op = 0;
3644                    let heap_ptr_usize = if vm.has_heap_ptr {
3645                        usize::try_from(vm.heap_ptr)
3646                            .map_err(|_| WasmTrap::HostAbort)?
3647                    } else {
3648                        0
3649                    };
3650                    let total_store_pages = usize::try_from(vm.total_mem_pages)
3651                        .map_err(|_| WasmTrap::HostAbort)?;
3652                    let max_allowed_pages = limits
3653                        .max_memory_pages
3654                        .min(limits.physical_max_memory_pages);
3655                    let mem = vm
3656                        .memory_mut(mem_idx)
3657                        .ok_or(WasmTrap::HostAbort)?;
3658                    let (new_total_pages_opt, resp_end_aligned) =
3659                        match apply_capability_response_on_memory(
3660                            mem,
3661                            self.base_io_offset,
3662                            &response_bytes,
3663                            heap_ptr_usize,
3664                            total_store_pages,
3665                            max_allowed_pages,
3666                        ) {
3667                            Ok(res) => res,
3668                            Err(Some(new_total)) => {
3669                                vm.exhausted = 2;
3670                                vm.interrupted_op = new_total;
3671                                return Err(WasmTrap::HostAbort);
3672                            }
3673                            Err(None) => return Err(WasmTrap::HostAbort),
3674                        };
3675                    if let Some(new_total) = new_total_pages_opt {
3676                        vm.total_mem_pages = u64::try_from(new_total)
3677                            .map_err(|_| WasmTrap::HostAbort)?;
3678                    }
3679                    if vm.has_heap_ptr {
3680                        vm.heap_ptr = i32::try_from(resp_end_aligned)
3681                            .map_err(|_| WasmTrap::HostAbort)?;
3682                    }
3683                    vm.rearm_fast_budget();
3684                    return Ok(());
3685                }
3686                WorkerCommand::Shutdown
3687                | WorkerCommand::StartStep { .. }
3688                | WorkerCommand::ResumeStep { .. } => {
3689                    *self.shutdown_requested = true;
3690                    return Err(WasmTrap::HostAbort);
3691                }
3692                _ => {}
3693            }
3694        }
3695    }
3696}
3697
3698enum WorkerInitBackend {
3699    TinyWasm {
3700        parsed_suspendable: ctb_formats_dcdata::tinywasm::types::TinyWasmModule,
3701        has_start_func: bool,
3702        static_data_end: usize,
3703    },
3704    NativeSubstitute(WasmSubstituteDescriptor),
3705}
3706
3707#[allow(
3708    clippy::too_many_lines,
3709    reason = "Coordinates unified continuation worker initialization across TinyWasm and NativeSubstitute backends"
3710)]
3711fn spawn_session_worker(
3712    backend_init: WorkerInitBackend,
3713    resource_limits: DcWasmResourceLimits,
3714    effective_max_mem: usize,
3715    effective_max_tbl: usize,
3716) -> Result<(SessionWorkerHandle, WorkerInitSuccess)> {
3717    let (cmd_tx, cmd_rx) = std::sync::mpsc::channel::<WorkerCommand>();
3718    let (evt_tx, evt_rx) = std::sync::mpsc::channel::<WorkerEvent>();
3719    let (init_tx, init_rx) =
3720        std::sync::mpsc::channel::<Result<WorkerInitSuccess>>();
3721
3722    const SESSION_WORKER_STACK_BYTES: usize = 16 * 1024 * 1024;
3723
3724    std::thread::Builder::new()
3725        .name("ctb-wasm-session".to_owned())
3726        .stack_size(SESSION_WORKER_STACK_BYTES)
3727        .spawn(move || {
3728            enum LiveEngine {
3729                TinyWasm {
3730                    store: Store,
3731                    instance: ModuleInstance,
3732                    addrs: CtbGlobalAddrs,
3733                    allow_suspend: std::rc::Rc<std::cell::Cell<bool>>,
3734                    shutdown_requested: std::rc::Rc<std::cell::Cell<bool>>,
3735                    cmd_rx: std::rc::Rc<std::sync::mpsc::Receiver<WorkerCommand>>,
3736                    evt_tx: std::rc::Rc<std::sync::mpsc::Sender<WorkerEvent>>,
3737                },
3738                NativeSubstitute {
3739                    inst: Box<dyn WasmSubstituteInstance>,
3740                    mem_export_idx: Option<usize>,
3741                    base_io_offset: usize,
3742                    cmd_rx: std::sync::mpsc::Receiver<WorkerCommand>,
3743                    evt_tx: std::sync::mpsc::Sender<WorkerEvent>,
3744                },
3745            }
3746
3747            let init_outcome = (|| -> Result<(LiveEngine, WorkerInitSuccess)> {
3748                match backend_init {
3749                    WorkerInitBackend::TinyWasm {
3750                        parsed_suspendable,
3751                        has_start_func,
3752                        static_data_end,
3753                    } => {
3754                        let allow_suspend =
3755                            std::rc::Rc::new(std::cell::Cell::new(false));
3756                        let shutdown_requested =
3757                            std::rc::Rc::new(std::cell::Cell::new(false));
3758                        let global_addrs_cell =
3759                            std::rc::Rc::new(std::cell::Cell::new(None::<CtbGlobalAddrs>));
3760                        let base_io_offset_cell = std::rc::Rc::new(
3761                            std::cell::Cell::new(DC_WASM_MIN_IO_BUFFER_OFFSET),
3762                        );
3763                        let cmd_rx_rc = std::rc::Rc::new(cmd_rx);
3764                        let evt_tx_rc = std::rc::Rc::new(evt_tx);
3765
3766                        let mut imports = Imports::new();
3767                        let allow_suspend_cb = std::rc::Rc::clone(&allow_suspend);
3768                        let shutdown_cb = std::rc::Rc::clone(&shutdown_requested);
3769                        let addrs_cb = std::rc::Rc::clone(&global_addrs_cell);
3770                        let cmd_rx_cb = std::rc::Rc::clone(&cmd_rx_rc);
3771                        let evt_tx_cb = std::rc::Rc::clone(&evt_tx_rc);
3772
3773                        let allow_suspend_cap = std::rc::Rc::clone(&allow_suspend);
3774                        let shutdown_cap = std::rc::Rc::clone(&shutdown_requested);
3775                        let addrs_cap = std::rc::Rc::clone(&global_addrs_cell);
3776                        let base_io_cap = std::rc::Rc::clone(&base_io_offset_cell);
3777                        let cmd_rx_cap = std::rc::Rc::clone(&cmd_rx_rc);
3778                        let evt_tx_cap = std::rc::Rc::clone(&evt_tx_rc);
3779
3780                        imports
3781                            .define(
3782                                CTB_HOST_IMPORT_MODULE,
3783                                CTB_HOST_SUSPEND_IMPORT_NAME,
3784                                Extern::typed_func(
3785                                    move |mut ctx: FuncContext<'_>, (): ()| -> std::result::Result<(), ctb_formats_dcdata::tinywasm::Error> {
3786                                        let Some(addrs) = addrs_cb.get() else {
3787                                            return Err(ctb_formats_dcdata::tinywasm::Error::Trap(
3788                                                ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3789                                            ));
3790                                        };
3791                                        let exhausted = read_store_global_i32(ctx.store(), addrs.exhausted);
3792                                        if !allow_suspend_cb.get() || exhausted != 1 {
3793                                            return Err(ctb_formats_dcdata::tinywasm::Error::Trap(
3794                                                ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3795                                            ));
3796                                        }
3797
3798                                        let consumed = read_store_global_u64(ctx.store(), addrs.quota_consumed);
3799                                        let remaining = read_store_global_u64(ctx.store(), addrs.quota_rem);
3800                                        let interrupted_op =
3801                                            read_store_global_u64(ctx.store(), addrs.interrupted_op);
3802                                        let required_cost =
3803                                            read_store_global_u64(ctx.store(), addrs.required_cost);
3804
3805                                        if evt_tx_cb
3806                                            .send(WorkerEvent::StepPausedOnQuota {
3807                                                consumed,
3808                                                remaining,
3809                                                interrupted_op,
3810                                                required_cost,
3811                                            })
3812                                            .is_err()
3813                                        {
3814                                            shutdown_cb.set(true);
3815                                            return Err(ctb_formats_dcdata::tinywasm::Error::Trap(
3816                                                ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3817                                            ));
3818                                        }
3819
3820                                        loop {
3821                                            let Ok(cmd) = cmd_rx_cb.recv() else {
3822                                                shutdown_cb.set(true);
3823                                                return Err(ctb_formats_dcdata::tinywasm::Error::Trap(
3824                                                    ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3825                                                ));
3826                                            };
3827                                            let inst = ctx.module();
3828                                            let Some(ctrl) = tinywasm_handle_query(ctx.store_mut(), &inst, &addrs, cmd) else {
3829                                                continue;
3830                                            };
3831                                            match ctrl {
3832                                                WorkerCommand::ResumeStep { quota_rem, limits } => {
3833                                                    configure_store_limits(ctx.store_mut(), &addrs, &limits);
3834                                                    write_store_global_u64(
3835                                                        ctx.store_mut(),
3836                                                        addrs.quota_rem,
3837                                                        quota_rem,
3838                                                    );
3839                                                    write_store_global_i32(
3840                                                        ctx.store_mut(),
3841                                                        addrs.exhausted,
3842                                                        0,
3843                                                    );
3844                                                    write_store_global_u64(
3845                                                        ctx.store_mut(),
3846                                                        addrs.interrupted_op,
3847                                                        0,
3848                                                    );
3849                                                    write_store_global_u64(
3850                                                        ctx.store_mut(),
3851                                                        addrs.required_cost,
3852                                                        0,
3853                                                    );
3854                                                    write_store_global_u64(
3855                                                        ctx.store_mut(),
3856                                                        addrs.resume_target_op,
3857                                                        0,
3858                                                    );
3859                                                    return Ok(());
3860                                                }
3861                                                WorkerCommand::Shutdown
3862                                                | WorkerCommand::StartStep { .. }
3863                                                | WorkerCommand::ResumeCapability { .. } => {
3864                                                    shutdown_cb.set(true);
3865                                                    return Err(ctb_formats_dcdata::tinywasm::Error::Trap(
3866                                                        ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3867                                                    ));
3868                                                }
3869                                                _ => {}
3870                                            }
3871                                        }
3872                                    },
3873                                ),
3874                            )
3875                            .map_err(|e| {
3876                                anyhow!("Failed to register __ctb_suspend_on_quota host import: {e:?}")
3877                            })?;
3878
3879                        imports
3880                            .define(
3881                                CTB_HOST_IMPORT_MODULE,
3882                                CTB_HOST_CAPABILITY_IMPORT_NAME,
3883                                Extern::typed_func(
3884                                    move |mut ctx: FuncContext<'_>, (): ()| -> std::result::Result<(), ctb_formats_dcdata::tinywasm::Error> {
3885                                        let trap = || {
3886                                            ctb_formats_dcdata::tinywasm::Error::Trap(
3887                                                ctb_formats_dcdata::tinywasm::Trap::Unreachable,
3888                                            )
3889                                        };
3890                                        let Some(addrs) = addrs_cap.get() else {
3891                                            return Err(trap());
3892                                        };
3893                                        if !allow_suspend_cap.get() {
3894                                            return Err(trap());
3895                                        }
3896                                        let (out_ptr, out_len) = {
3897                                            let mem = ctx
3898                                                .exported_memory_mut("memory")
3899                                                .map_err(|_| trap())?;
3900                                            read_output_mailbox_header_from_mem(&mem)
3901                                                .map_err(|_| trap())?
3902                                        };
3903                                        let consumed = read_store_global_u64(
3904                                            ctx.store(),
3905                                            addrs.quota_consumed,
3906                                        );
3907                                        let remaining = read_store_global_u64(
3908                                            ctx.store(),
3909                                            addrs.quota_rem,
3910                                        );
3911                                        if evt_tx_cap
3912                                            .send(WorkerEvent::StepPausedOnCapability {
3913                                                consumed,
3914                                                remaining,
3915                                                out_ptr,
3916                                                out_len,
3917                                            })
3918                                            .is_err()
3919                                        {
3920                                            shutdown_cap.set(true);
3921                                            return Err(trap());
3922                                        }
3923
3924                                        loop {
3925                                            let Ok(cmd) = cmd_rx_cap.recv() else {
3926                                                shutdown_cap.set(true);
3927                                                return Err(trap());
3928                                            };
3929                                            let inst = ctx.module();
3930                                            let Some(ctrl) = tinywasm_handle_query(ctx.store_mut(), &inst, &addrs, cmd) else {
3931                                                continue;
3932                                            };
3933                                            match ctrl {
3934                                                WorkerCommand::ResumeCapability {
3935                                                    response_bytes,
3936                                                    quota_rem,
3937                                                    limits,
3938                                                } => {
3939                                                    configure_store_limits(
3940                                                        ctx.store_mut(),
3941                                                        &addrs,
3942                                                        &limits,
3943                                                    );
3944                                                    write_store_global_u64(
3945                                                        ctx.store_mut(),
3946                                                        addrs.quota_rem,
3947                                                        quota_rem,
3948                                                    );
3949                                                    write_store_global_i32(
3950                                                        ctx.store_mut(),
3951                                                        addrs.exhausted,
3952                                                        0,
3953                                                    );
3954                                                    write_store_global_u64(
3955                                                        ctx.store_mut(),
3956                                                        addrs.interrupted_op,
3957                                                        0,
3958                                                    );
3959                                                    write_store_global_u64(
3960                                                        ctx.store_mut(),
3961                                                        addrs.required_cost,
3962                                                        0,
3963                                                    );
3964                                                    write_store_global_u64(
3965                                                        ctx.store_mut(),
3966                                                        addrs.resume_target_op,
3967                                                        0,
3968                                                    );
3969                                                    let inst = ctx.module();
3970                                                    let heap_global_addr = inst
3971                                                        .export_addr("__heap_ptr")
3972                                                        .and_then(|ev| match ev {
3973                                                            ExternVal::Global(addr) => {
3974                                                                Some(addr)
3975                                                            }
3976                                                            _ => None,
3977                                                        });
3978                                                    let heap_ptr = if let Some(addr) =
3979                                                        heap_global_addr
3980                                                    {
3981                                                        usize::try_from(
3982                                                            read_store_global_i32(
3983                                                                ctx.store(),
3984                                                                addr,
3985                                                            ),
3986                                                        )
3987                                                        .map_err(|_| trap())?
3988                                                    } else {
3989                                                        0
3990                                                    };
3991                                                    let total_store_pages = usize::try_from(
3992                                                        read_store_global_u64(
3993                                                            ctx.store(),
3994                                                            addrs.total_mem_pages,
3995                                                        ),
3996                                                    )
3997                                                    .map_err(|_| trap())?;
3998                                                    let max_allowed_pages = limits
3999                                                        .max_memory_pages
4000                                                        .min(limits.physical_max_memory_pages);
4001
4002                                                    let cap_outcome = {
4003                                                        let mut mem = ctx
4004                                                            .exported_memory_mut("memory")
4005                                                            .map_err(|_| trap())?;
4006                                                        apply_capability_response_on_memory(
4007                                                            &mut mem,
4008                                                            base_io_cap.get(),
4009                                                            &response_bytes,
4010                                                            heap_ptr,
4011                                                            total_store_pages,
4012                                                            max_allowed_pages,
4013                                                        )
4014                                                    };
4015                                                    let (new_total_pages_opt, resp_end_aligned) =
4016                                                        match cap_outcome {
4017                                                            Ok(res) => res,
4018                                                            Err(Some(new_total)) => {
4019                                                                write_store_global_i32(
4020                                                                    ctx.store_mut(),
4021                                                                    addrs.exhausted,
4022                                                                    2,
4023                                                                );
4024                                                                write_store_global_u64(
4025                                                                    ctx.store_mut(),
4026                                                                    addrs.interrupted_op,
4027                                                                    new_total,
4028                                                                );
4029                                                                return Err(trap());
4030                                                            }
4031                                                            Err(None) => return Err(trap()),
4032                                                        };
4033
4034                                                    if let Some(new_total) = new_total_pages_opt {
4035                                                        write_store_global_u64(
4036                                                            ctx.store_mut(),
4037                                                            addrs.total_mem_pages,
4038                                                            u64::try_from(new_total)
4039                                                                .map_err(|_| trap())?,
4040                                                        );
4041                                                    }
4042                                                    if let Some(addr) = heap_global_addr {
4043                                                        let end_i32 = i32::try_from(
4044                                                            resp_end_aligned,
4045                                                        )
4046                                                        .map_err(|_| trap())?;
4047                                                        write_store_global_i32(
4048                                                            ctx.store_mut(),
4049                                                            addr,
4050                                                            end_i32,
4051                                                        );
4052                                                    }
4053                                                    return Ok(());
4054                                                }
4055                                                WorkerCommand::Shutdown
4056                                                | WorkerCommand::StartStep { .. }
4057                                                | WorkerCommand::ResumeStep { .. } => {
4058                                                    shutdown_cap.set(true);
4059                                                    return Err(trap());
4060                                                }
4061                                                _ => {}
4062                                            }
4063                                        }
4064                                    },
4065                                ),
4066                            )
4067                            .map_err(|e| {
4068                                anyhow!(
4069                                    "Failed to register __ctb_request_capability host import: {e:?}"
4070                                )
4071                            })?;
4072
4073                        let module = Module::from(parsed_suspendable);
4074                        let mut store = Store::default();
4075                        let instance =
4076                            ModuleInstance::instantiate(&mut store, module, Some(imports))
4077                                .map_err(|e| {
4078                                    anyhow!(
4079                                        "Failed to instantiate WebAssembly module in tinywasm: {e:?}"
4080                                    )
4081                                })?;
4082                        let global_addrs = CtbGlobalAddrs::resolve(&instance)?;
4083                        global_addrs_cell.set(Some(global_addrs));
4084                        configure_store_limits(&mut store, &global_addrs, &resource_limits);
4085                        write_store_global_u64(
4086                            &mut store,
4087                            global_addrs.quota_rem,
4088                            resource_limits.max_instructions_per_step,
4089                        );
4090                        write_store_global_u64(&mut store, global_addrs.quota_consumed, 0);
4091                        write_store_global_i32(&mut store, global_addrs.exhausted, 0);
4092                        write_store_global_u64(&mut store, global_addrs.interrupted_op, 0);
4093                        write_store_global_u64(&mut store, global_addrs.required_cost, 0);
4094                        write_store_global_u64(&mut store, global_addrs.op_ordinal, 0);
4095                        write_store_global_u64(&mut store, global_addrs.resume_target_op, 0);
4096
4097                        let mut remaining_compute_quota =
4098                            resource_limits.max_instructions_per_step;
4099                        let mut total_instructions_executed = 0u64;
4100
4101                        if has_start_func {
4102                            let start_fn = instance
4103                                .exported_func::<(), ()>(&store, CTB_WASM_START_EXPORT)
4104                                .map_err(|e| {
4105                                    anyhow!(
4106                                        "Failed to resolve hoisted WASM start function: {e:?}"
4107                                    )
4108                                })?;
4109                            if let Err(e) = start_fn.call(&mut store, ()) {
4110                                let exhausted =
4111                                    read_store_global_i32(&store, global_addrs.exhausted);
4112                                let interrupted_op =
4113                                    read_store_global_u64(&store, global_addrs.interrupted_op);
4114                                return Err(map_start_section_error(
4115                                    exhausted,
4116                                    interrupted_op,
4117                                    resource_limits.max_instructions_per_step,
4118                                    effective_max_mem,
4119                                    effective_max_tbl,
4120                                    format_args!("{e:?}"),
4121                                ));
4122                            }
4123                            let start_consumed =
4124                                read_store_global_u64(&store, global_addrs.quota_consumed);
4125                            remaining_compute_quota =
4126                                read_store_global_u64(&store, global_addrs.quota_rem);
4127                            total_instructions_executed = start_consumed;
4128                        }
4129
4130                        let entry_func_name = if instance.export_addr("step").is_some() {
4131                            "step".to_owned()
4132                        } else if instance.export_addr("main").is_some() {
4133                            "main".to_owned()
4134                        } else {
4135                            bail!(
4136                                "WebAssembly module must export a 'step' or 'main' entry function"
4137                            );
4138                        };
4139
4140                        // Reason for fallback: modules without `__heap_base`/`__data_end` contribute 0.
4141                        let exported_heap_bound = ["__heap_base", "__data_end"]
4142                            .into_iter()
4143                            .filter_map(|name| {
4144                                if let Some(ExternVal::Global(addr)) =
4145                                    instance.export_addr(name)
4146                                {
4147                                    usize::try_from(read_store_global_i32(&store, addr))
4148                                        .ok()
4149                                } else {
4150                                    None
4151                                }
4152                            })
4153                            .max()
4154                            .unwrap_or(0);
4155                        let base_io_offset = {
4156                            let mut mem = instance
4157                                .exported_memory_mut(&mut store, "memory")
4158                                .map_err(|e| {
4159                                    anyhow!(
4160                                        "WebAssembly module is missing exported 'memory': {e:?}"
4161                                    )
4162                                })?;
4163                            let total_len = mem.page_count().saturating_mul(65_536);
4164                            let slice = mem.load(0, total_len).map_err(|e| {
4165                                anyhow!(
4166                                    "Failed to inspect initial WASM linear memory: {e:?}"
4167                                )
4168                            })?;
4169                            let last_nonzero_end = last_nonzero_memory_end_on_slice(slice);
4170                            let reserved_end = static_data_end
4171                                .max(exported_heap_bound)
4172                                .max(last_nonzero_end)
4173                                .max(DC_WASM_MIN_IO_BUFFER_OFFSET);
4174                            let base_io_offset = align_up_8(reserved_end)?;
4175                            base_io_offset_cell.set(base_io_offset);
4176                            base_io_offset
4177                        };
4178
4179                        Ok((
4180                            LiveEngine::TinyWasm {
4181                                store,
4182                                instance,
4183                                addrs: global_addrs,
4184                                allow_suspend,
4185                                shutdown_requested,
4186                                cmd_rx: cmd_rx_rc,
4187                                evt_tx: evt_tx_rc,
4188                            },
4189                            WorkerInitSuccess {
4190                                entry_func_name,
4191                                base_io_offset,
4192                                remaining_compute_quota,
4193                                total_instructions_executed,
4194                            },
4195                        ))
4196                    }
4197                    WorkerInitBackend::NativeSubstitute(desc) => {
4198                        let mut inst = (desc.instantiate)();
4199                        let meta = inst.meta();
4200                        let mem_export_idx = inst.exported_memory_index();
4201                        {
4202                            let vm = inst.vm_mut();
4203                            configure_vm_limits(vm, &resource_limits);
4204                            vm.quota_remaining =
4205                                resource_limits.max_instructions_per_step;
4206                            vm.quota_consumed = 0;
4207                            vm.exhausted = 0;
4208                            vm.interrupted_op = 0;
4209                            vm.required_cost = 0;
4210                            vm.op_ordinal = 0;
4211                            vm.resume_target_op = 0;
4212                        }
4213
4214                        let mut remaining_compute_quota =
4215                            resource_limits.max_instructions_per_step;
4216                        let mut total_instructions_executed = 0u64;
4217
4218                        if meta.has_start_func {
4219                            let mut start_shutdown = false;
4220                            let mut start_host = WorkerSubstituteHost {
4221                                mem_export_idx,
4222                                base_io_offset: DC_WASM_MIN_IO_BUFFER_OFFSET,
4223                                allow_suspend: false,
4224                                shutdown_requested: &mut start_shutdown,
4225                                cmd_rx: &cmd_rx,
4226                                evt_tx: &evt_tx,
4227                            };
4228                            if let Err(err) = inst.call_start(&mut start_host) {
4229                                let exhausted = inst.vm().exhausted;
4230                                let interrupted_op = inst.vm().interrupted_op;
4231                                return Err(map_start_section_error(
4232                                    exhausted,
4233                                    interrupted_op,
4234                                    resource_limits.max_instructions_per_step,
4235                                    effective_max_mem,
4236                                    effective_max_tbl,
4237                                    format_args!("{err}"),
4238                                ));
4239                            }
4240                            remaining_compute_quota = inst.vm().quota_remaining;
4241                            total_instructions_executed = inst.vm().quota_consumed;
4242                        }
4243
4244                        // Reason for fallback: modules without `__heap_base`/`__data_end` contribute 0.
4245                        let exported_heap_bound = ["__heap_base", "__data_end"]
4246                            .into_iter()
4247                            .filter_map(|name| {
4248                                inst.exported_global_i32(name)
4249                                    .and_then(|v| usize::try_from(v).ok())
4250                            })
4251                            .max()
4252                            .unwrap_or(0);
4253                        let base_io_offset = {
4254                            let mem_idx = mem_export_idx.context(
4255                                "WebAssembly module is missing exported 'memory'",
4256                            )?;
4257                            let mem = inst
4258                                .vm()
4259                                .memory(mem_idx)
4260                                .context("WASM exported memory index out of bounds")?;
4261                            let last_nonzero_end =
4262                                last_nonzero_memory_end_on_slice(mem.as_slice());
4263                            let reserved_end = meta
4264                                .static_data_end
4265                                .max(exported_heap_bound)
4266                                .max(last_nonzero_end)
4267                                .max(DC_WASM_MIN_IO_BUFFER_OFFSET);
4268                            align_up_8(reserved_end)?
4269                        };
4270
4271                        Ok((
4272                            LiveEngine::NativeSubstitute {
4273                                inst,
4274                                mem_export_idx,
4275                                base_io_offset,
4276                                cmd_rx,
4277                                evt_tx,
4278                            },
4279                            WorkerInitSuccess {
4280                                entry_func_name: meta.entry_func_name.to_owned(),
4281                                base_io_offset,
4282                                remaining_compute_quota,
4283                                total_instructions_executed,
4284                            },
4285                        ))
4286                    }
4287                }
4288            })();
4289
4290            let mut engine = match init_outcome {
4291                Ok((eng, info)) => {
4292                    if init_tx.send(Ok(info)).is_err() {
4293                        return;
4294                    }
4295                    eng
4296                }
4297                Err(err) => {
4298                    let _ = init_tx.send(Err(err));
4299                    return;
4300                }
4301            };
4302
4303            match &mut engine {
4304                LiveEngine::TinyWasm {
4305                    store,
4306                    instance,
4307                    addrs,
4308                    allow_suspend,
4309                    shutdown_requested,
4310                    cmd_rx: rx,
4311                    evt_tx: tx,
4312                } => {
4313                    while let Ok(cmd) = rx.recv() {
4314                        let Some(ctrl) = tinywasm_handle_query(store, instance, addrs, cmd) else {
4315                            continue;
4316                        };
4317                        match ctrl {
4318                            WorkerCommand::StartStep {
4319                                entry_func_name,
4320                                in_ptr_i32,
4321                                in_len_i32,
4322                                default_output_ptr,
4323                                quota_rem,
4324                                limits,
4325                            } => {
4326                                configure_store_limits(store, addrs, &limits);
4327                                if let Ok(mut mem) =
4328                                    instance.exported_memory_mut(store, "memory")
4329                                {
4330                                    reset_output_mailbox_on_mem(
4331                                        &mut mem,
4332                                        default_output_ptr,
4333                                    );
4334                                }
4335                                write_store_global_u64(store, addrs.quota_rem, quota_rem);
4336                                write_store_global_u64(store, addrs.quota_consumed, 0);
4337                                write_store_global_i32(store, addrs.exhausted, 0);
4338                                write_store_global_u64(store, addrs.interrupted_op, 0);
4339                                write_store_global_u64(store, addrs.required_cost, 0);
4340                                write_store_global_u64(store, addrs.resume_target_op, 0);
4341
4342                                allow_suspend.set(true);
4343                                let call_res = match DcWasmSession::call_entry_once(
4344                                    store,
4345                                    instance,
4346                                    &entry_func_name,
4347                                    in_ptr_i32,
4348                                    in_len_i32,
4349                                ) {
4350                                    Ok(Ok(code)) => Ok(code),
4351                                    Ok(Err(trap_err)) => Err(format!("{trap_err:?}")),
4352                                    Err(sig_err) => Err(format!("{sig_err}")),
4353                                };
4354                                allow_suspend.set(false);
4355                                if shutdown_requested.get() {
4356                                    break;
4357                                }
4358
4359                                let consumed =
4360                                    read_store_global_u64(store, addrs.quota_consumed);
4361                                let remaining =
4362                                    read_store_global_u64(store, addrs.quota_rem);
4363                                let exhausted =
4364                                    read_store_global_i32(store, addrs.exhausted);
4365                                let interrupted_op =
4366                                    read_store_global_u64(store, addrs.interrupted_op);
4367                                let required_cost =
4368                                    read_store_global_u64(store, addrs.required_cost);
4369                                if tx
4370                                    .send(WorkerEvent::StepFinished {
4371                                        call_res,
4372                                        consumed,
4373                                        remaining,
4374                                        exhausted,
4375                                        interrupted_op,
4376                                        required_cost,
4377                                    })
4378                                    .is_err()
4379                                {
4380                                    break;
4381                                }
4382                            }
4383                            WorkerCommand::ResumeStep { .. }
4384                            | WorkerCommand::ResumeCapability { .. }
4385                            | WorkerCommand::Shutdown => {
4386                                break;
4387                            }
4388                            _ => {}
4389                        }
4390                    }
4391                }
4392                LiveEngine::NativeSubstitute {
4393                    inst,
4394                    mem_export_idx,
4395                    base_io_offset,
4396                    cmd_rx: rx,
4397                    evt_tx: tx,
4398                } => {
4399                    while let Ok(cmd) = rx.recv() {
4400                        let ctrl_opt = match &cmd {
4401                            WorkerCommand::ExportedGlobalI32 { name, .. } => {
4402                                if let Some(v) = inst.exported_global_i32(name) {
4403                                    if let WorkerCommand::ExportedGlobalI32 {
4404                                        reply,
4405                                        ..
4406                                    } = cmd
4407                                    {
4408                                        let _ = reply.send(Some(v));
4409                                    }
4410                                    None
4411                                } else {
4412                                    native_vm_handle_query(
4413                                        inst.vm_mut(),
4414                                        *mem_export_idx,
4415                                        cmd,
4416                                    )
4417                                }
4418                            }
4419                            WorkerCommand::ExportedGlobalI64 { name, .. } => {
4420                                if let Some(v) = inst.exported_global_i64(name) {
4421                                    if let WorkerCommand::ExportedGlobalI64 {
4422                                        reply,
4423                                        ..
4424                                    } = cmd
4425                                    {
4426                                        let _ = reply.send(Some(v));
4427                                    }
4428                                    None
4429                                } else {
4430                                    native_vm_handle_query(
4431                                        inst.vm_mut(),
4432                                        *mem_export_idx,
4433                                        cmd,
4434                                    )
4435                                }
4436                            }
4437                            _ => native_vm_handle_query(
4438                                inst.vm_mut(),
4439                                *mem_export_idx,
4440                                cmd,
4441                            ),
4442                        };
4443                        let Some(ctrl) = ctrl_opt else {
4444                            continue;
4445                        };
4446                        match ctrl {
4447                            WorkerCommand::StartStep {
4448                                entry_func_name: _,
4449                                in_ptr_i32,
4450                                in_len_i32,
4451                                default_output_ptr,
4452                                quota_rem,
4453                                limits,
4454                            } => {
4455                                {
4456                                    let vm = inst.vm_mut();
4457                                    configure_vm_limits(vm, &limits);
4458                                    if let Some(mem_idx) = *mem_export_idx
4459                                        && let Some(mem) = vm.memory_mut(mem_idx)
4460                                    {
4461                                        reset_output_mailbox_on_mem(
4462                                            mem,
4463                                            default_output_ptr,
4464                                        );
4465                                    }
4466                                    vm.quota_remaining = quota_rem;
4467                                    vm.quota_consumed = 0;
4468                                    vm.exhausted = 0;
4469                                    vm.interrupted_op = 0;
4470                                    vm.required_cost = 0;
4471                                    vm.resume_target_op = 0;
4472                                }
4473
4474                                let mut shutdown_req = false;
4475                                let call_res = {
4476                                    let mut host = WorkerSubstituteHost {
4477                                        mem_export_idx: *mem_export_idx,
4478                                        base_io_offset: *base_io_offset,
4479                                        allow_suspend: true,
4480                                        shutdown_requested: &mut shutdown_req,
4481                                        cmd_rx: rx,
4482                                        evt_tx: tx,
4483                                    };
4484                                    inst.call_entry(in_ptr_i32, in_len_i32, &mut host)
4485                                        .map_err(|trap| format!("{trap:?}"))
4486                                };
4487                                if shutdown_req {
4488                                    break;
4489                                }
4490
4491                                let vm = inst.vm();
4492                                if tx
4493                                    .send(WorkerEvent::StepFinished {
4494                                        call_res,
4495                                        consumed: vm.quota_consumed,
4496                                        remaining: vm.quota_remaining,
4497                                        exhausted: vm.exhausted,
4498                                        interrupted_op: vm.interrupted_op,
4499                                        required_cost: vm.required_cost,
4500                                    })
4501                                    .is_err()
4502                                {
4503                                    break;
4504                                }
4505                            }
4506                            WorkerCommand::ResumeStep { .. }
4507                            | WorkerCommand::ResumeCapability { .. }
4508                            | WorkerCommand::Shutdown => {
4509                                break;
4510                            }
4511                            _ => {}
4512                        }
4513                    }
4514                }
4515            }
4516        })
4517        .map_err(|e| anyhow!("Failed to spawn WASM continuation worker: {e}"))?;
4518
4519    let init_info = init_rx
4520        .recv()
4521        .map_err(|_| anyhow!("WASM continuation worker exited during initialization"))??;
4522    Ok((SessionWorkerHandle { cmd_tx, evt_rx }, init_info))
4523}
4524
4525impl DcWasmSession {
4526    fn query_worker<R, F>(&self, build: F) -> Result<R>
4527    where
4528        F: FnOnce(Reply<R>) -> WorkerCommand,
4529    {
4530        let guard = self
4531            .worker
4532            .lock()
4533            .map_err(|_| anyhow!("WASM session worker mutex poisoned"))?;
4534        let (res_tx, res_rx) = std::sync::mpsc::channel::<R>();
4535        guard
4536            .cmd_tx
4537            .send(build(res_tx))
4538            .map_err(|_| {
4539                anyhow!("WASM session continuation worker exited unexpectedly")
4540            })?;
4541        res_rx.recv().map_err(|_| {
4542            anyhow!("WASM session continuation worker failed to respond")
4543        })
4544    }
4545
4546    /// Instantiates a pure-compute [`DcWasmSession`] from compiled `.wasm` module bytes,
4547    /// loading `initial_input` and `most_recent_node_id` (`Dc 641`) into linear memory
4548    /// using [`DcWasmResourceLimits::default()`].
4549    ///
4550    /// # Errors
4551    /// Returns an error if parsing, instrumenting, or instantiating the module fails,
4552    /// if the module exports neither `"step"` nor `"main"`, or if writing the initial
4553    /// input into linear memory fails.
4554    pub fn from_wasm_bytes(
4555        wasm_bytes: &[u8],
4556        initial_input: &DcMstr,
4557        most_recent_node_id: Option<u128>,
4558    ) -> Result<Self> {
4559        Self::from_wasm_bytes_with_limits(
4560            wasm_bytes,
4561            initial_input,
4562            most_recent_node_id,
4563            DcWasmResourceLimits::default(),
4564        )
4565    }
4566
4567    /// Instantiates a pure-compute [`DcWasmSession`] from compiled `.wasm` module bytes
4568    /// with explicit [`DcWasmResourceLimits`] using [`DcWasmExecutionBackend::Auto`].
4569    ///
4570    /// # Errors
4571    /// Returns an error if parsing, instrumenting, or instantiating the module fails,
4572    /// if initial memory exceeds `resource_limits.max_memory_pages`, if the module exports
4573    /// neither `"step"` nor `"main"`, or if writing the initial input into linear memory fails.
4574    pub fn from_wasm_bytes_with_limits(
4575        wasm_bytes: &[u8],
4576        initial_input: &DcMstr,
4577        most_recent_node_id: Option<u128>,
4578        resource_limits: DcWasmResourceLimits,
4579    ) -> Result<Self> {
4580        Self::from_wasm_bytes_with_limits_and_backend(
4581            wasm_bytes,
4582            initial_input,
4583            most_recent_node_id,
4584            resource_limits,
4585            DcWasmExecutionBackend::Auto,
4586        )
4587    }
4588
4589    /// Instantiates a pure-compute [`DcWasmSession`] from compiled `.wasm` module bytes
4590    /// with explicit [`DcWasmResourceLimits`] and [`DcWasmExecutionBackend`].
4591    ///
4592    /// # Errors
4593    /// Returns an error if parsing, instrumenting, or instantiating the module fails,
4594    /// if initial memory/tables exceed `resource_limits`, if the module exports neither
4595    /// `"step"` nor `"main"`, or if writing the initial input into linear memory fails.
4596    pub fn from_wasm_bytes_with_limits_and_backend(
4597        wasm_bytes: &[u8],
4598        initial_input: &DcMstr,
4599        most_recent_node_id: Option<u128>,
4600        resource_limits: DcWasmResourceLimits,
4601        backend: DcWasmExecutionBackend,
4602    ) -> Result<Self> {
4603        let effective_max_mem = resource_limits
4604            .max_memory_pages
4605            .min(resource_limits.physical_max_memory_pages);
4606        let effective_max_tbl = resource_limits
4607            .max_table_elements
4608            .min(resource_limits.physical_max_table_elements);
4609
4610        let raw_wasm_bytes = wasm_bytes.to_vec();
4611        let instrumented_bytes = std::sync::OnceLock::new();
4612
4613        let matched_desc = match backend {
4614            DcWasmExecutionBackend::Auto => {
4615                #[cfg(test)]
4616                ctb_wasm_substitutes::ensure_registered();
4617                let wasm_sha256: [u8; 32] = Sha256::digest(wasm_bytes).into();
4618                lookup_substitute(WASM_RESOURCE_ACCOUNTING_VERSION, &wasm_sha256)
4619            }
4620            DcWasmExecutionBackend::ForceTinyWasm => None,
4621        };
4622
4623        let (used_native_substitute, backend_init) = if let Some(desc) = matched_desc {
4624            if desc.meta.initial_memory_pages > effective_max_mem {
4625                return Err(anyhow::Error::new(
4626                    WasmResourceInterruption::MemoryLimitExceeded {
4627                        requested_pages: desc.meta.initial_memory_pages,
4628                        max_pages: effective_max_mem,
4629                    },
4630                ));
4631            }
4632            if desc.meta.initial_table_elements > effective_max_tbl {
4633                return Err(anyhow::Error::new(
4634                    WasmResourceInterruption::TableLimitExceeded {
4635                        requested_elements: desc.meta.initial_table_elements,
4636                        max_elements: effective_max_tbl,
4637                    },
4638                ));
4639            }
4640            (true, WorkerInitBackend::NativeSubstitute(desc))
4641        } else {
4642            let instrumented = instrument_wasm_module_bytes(wasm_bytes)?;
4643            if instrumented.initial_memory_pages > effective_max_mem {
4644                return Err(anyhow::Error::new(
4645                    WasmResourceInterruption::MemoryLimitExceeded {
4646                        requested_pages: instrumented.initial_memory_pages,
4647                        max_pages: effective_max_mem,
4648                    },
4649                ));
4650            }
4651            if instrumented.initial_table_elements > effective_max_tbl {
4652                return Err(anyhow::Error::new(
4653                    WasmResourceInterruption::TableLimitExceeded {
4654                        requested_elements: instrumented.initial_table_elements,
4655                        max_elements: effective_max_tbl,
4656                    },
4657                ));
4658            }
4659            let _ = instrumented_bytes.set(instrumented.wasm_bytes);
4660            (
4661                false,
4662                WorkerInitBackend::TinyWasm {
4663                    parsed_suspendable: instrumented.parsed_suspendable,
4664                    has_start_func: instrumented.has_start_func,
4665                    static_data_end: instrumented.static_data_end,
4666                },
4667            )
4668        };
4669
4670        let (worker, init_info) = spawn_session_worker(
4671            backend_init,
4672            resource_limits,
4673            effective_max_mem,
4674            effective_max_tbl,
4675        )?;
4676
4677        let mut session = Self {
4678            raw_wasm_bytes,
4679            instrumented_bytes,
4680            used_native_substitute,
4681            worker: std::sync::Mutex::new(worker),
4682            entry_func_name: init_info.entry_func_name,
4683            base_io_offset: init_info.base_io_offset,
4684            current_input_ptr: 0,
4685            current_input_len: 0,
4686            default_output_ptr: 0,
4687            most_recent_node_id,
4688            resource_limits,
4689            remaining_compute_quota: init_info.remaining_compute_quota,
4690            current_compute_quota_limit: resource_limits
4691                .max_instructions_per_step,
4692            cumulative_output_bytes: 0,
4693            last_step_instructions: 0,
4694            total_instructions_executed: init_info.total_instructions_executed,
4695            last_interrupted_op_ordinal: None,
4696            last_interrupted_op_required_cost: None,
4697            last_resource_interruption: None,
4698            current_input_doc: initial_input.to_owned(),
4699            paused_on_compute_quota: false,
4700            paused_on_capability: false,
4701            pending_capability_response: None,
4702            pending_quota_increase_since_pause: 0,
4703            shared_task_quota: None,
4704        };
4705        session.provide_input(initial_input)?;
4706        Ok(session)
4707    }
4708
4709    /// Instantiates a [`DcWasmSession`] directly from a pre-resolved native
4710    /// [`WasmSubstituteDescriptor`], skipping WebAssembly binary compilation and
4711    /// hashing when the graph revision closure already matches a linked substitute.
4712    ///
4713    /// # Errors
4714    /// Returns an error if initial memory or table counts exceed `resource_limits`,
4715    /// if the start section traps, or if writing `initial_input` into memory fails.
4716    pub fn from_substitute_descriptor_with_limits(
4717        desc: WasmSubstituteDescriptor,
4718        initial_input: &DcMstr,
4719        most_recent_node_id: Option<u128>,
4720        resource_limits: DcWasmResourceLimits,
4721    ) -> Result<Self> {
4722        let effective_max_mem = resource_limits
4723            .max_memory_pages
4724            .min(resource_limits.physical_max_memory_pages);
4725        let effective_max_tbl = resource_limits
4726            .max_table_elements
4727            .min(resource_limits.physical_max_table_elements);
4728
4729        if desc.meta.initial_memory_pages > effective_max_mem {
4730            return Err(anyhow::Error::new(
4731                WasmResourceInterruption::MemoryLimitExceeded {
4732                    requested_pages: desc.meta.initial_memory_pages,
4733                    max_pages: effective_max_mem,
4734                },
4735            ));
4736        }
4737        if desc.meta.initial_table_elements > effective_max_tbl {
4738            return Err(anyhow::Error::new(
4739                WasmResourceInterruption::TableLimitExceeded {
4740                    requested_elements: desc.meta.initial_table_elements,
4741                    max_elements: effective_max_tbl,
4742                },
4743            ));
4744        }
4745
4746        let (worker, init_info) = spawn_session_worker(
4747            WorkerInitBackend::NativeSubstitute(desc),
4748            resource_limits,
4749            effective_max_mem,
4750            effective_max_tbl,
4751        )?;
4752
4753        let mut session = Self {
4754            raw_wasm_bytes: Vec::new(),
4755            instrumented_bytes: std::sync::OnceLock::new(),
4756            used_native_substitute: true,
4757            worker: std::sync::Mutex::new(worker),
4758            entry_func_name: init_info.entry_func_name,
4759            base_io_offset: init_info.base_io_offset,
4760            current_input_ptr: 0,
4761            current_input_len: 0,
4762            default_output_ptr: 0,
4763            most_recent_node_id,
4764            resource_limits,
4765            remaining_compute_quota: init_info.remaining_compute_quota,
4766            current_compute_quota_limit: resource_limits
4767                .max_instructions_per_step,
4768            cumulative_output_bytes: 0,
4769            last_step_instructions: 0,
4770            total_instructions_executed: init_info.total_instructions_executed,
4771            last_interrupted_op_ordinal: None,
4772            last_interrupted_op_required_cost: None,
4773            last_resource_interruption: None,
4774            current_input_doc: initial_input.to_owned(),
4775            paused_on_compute_quota: false,
4776            paused_on_capability: false,
4777            pending_capability_response: None,
4778            pending_quota_increase_since_pause: 0,
4779            shared_task_quota: None,
4780        };
4781        session.provide_input(initial_input)?;
4782        Ok(session)
4783    }
4784
4785    /// Assembles a Dc-WASM document (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
4786    /// or `wasm_routine`) using the default syntax resolver and instantiates a [`DcWasmSession`].
4787    ///
4788    /// # Errors
4789    /// Returns an error if assembling or instantiating the Dc-WASM program fails.
4790    pub fn from_dc_wasm(
4791        wasm_doc: &DcMstr,
4792        initial_input: &DcMstr,
4793        most_recent_node_id: Option<u128>,
4794    ) -> Result<Self> {
4795        let resolver = default_syntax_resolver();
4796        Self::from_dc_wasm_with_resolver(
4797            wasm_doc,
4798            initial_input,
4799            most_recent_node_id,
4800            resolver.as_ref(),
4801        )
4802    }
4803
4804    /// Assembles a Dc-WASM document (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
4805    /// or `wasm_routine`) using `resolver` and instantiates a [`DcWasmSession`].
4806    ///
4807    /// # Errors
4808    /// Returns an error if assembling or instantiating the Dc-WASM program fails.
4809    pub fn from_dc_wasm_with_resolver(
4810        wasm_doc: &DcMstr,
4811        initial_input: &DcMstr,
4812        most_recent_node_id: Option<u128>,
4813        resolver: &dyn SyntaxRuleResolver,
4814    ) -> Result<Self> {
4815        Self::from_dc_wasm_with_limits(
4816            wasm_doc,
4817            initial_input,
4818            most_recent_node_id,
4819            resolver,
4820            DcWasmResourceLimits::default(),
4821        )
4822    }
4823
4824    /// Assembles a Dc-WASM document (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
4825    /// or `wasm_routine`) using `resolver` and instantiates a [`DcWasmSession`] with explicit
4826    /// [`DcWasmResourceLimits`].
4827    ///
4828    /// # Errors
4829    /// Returns an error if assembling or instantiating the Dc-WASM program fails.
4830    pub fn from_dc_wasm_with_limits(
4831        wasm_doc: &DcMstr,
4832        initial_input: &DcMstr,
4833        most_recent_node_id: Option<u128>,
4834        resolver: &dyn SyntaxRuleResolver,
4835        resource_limits: DcWasmResourceLimits,
4836    ) -> Result<Self> {
4837        let wasm_bytes = dcmstring_to_wasm_with_resolver(wasm_doc, resolver)?;
4838        Self::from_wasm_bytes_with_limits(
4839            &wasm_bytes,
4840            initial_input,
4841            most_recent_node_id,
4842            resource_limits,
4843        )
4844    }
4845
4846    /// Returns `true` if this session is backed by a registered native substitute.
4847    #[must_use]
4848    pub const fn used_native_substitute(&self) -> bool {
4849        self.used_native_substitute
4850    }
4851
4852    /// Returns the portable instrumented `.wasm` bytes executed by this session.
4853    ///
4854    /// Because compute-quota accounting is embedded in standard WebAssembly bytecode,
4855    /// running these bytes on any compliant WASM runtime (`tinywasm`, V8/Node `WebAssembly`,
4856    /// Wasmtime, etc.) produces identical interruption points and state transitions.
4857    #[must_use]
4858    pub fn instrumented_wasm_bytes(&self) -> &[u8] {
4859        self.instrumented_bytes.get_or_init(|| {
4860            match instrument_wasm_module_bytes(&self.raw_wasm_bytes) {
4861                Ok(m) => m.wasm_bytes,
4862                Err(err) => {
4863                    warn_fmt!(
4864                        "Lazy WASM quota instrumentation failed after native substitute instantiation: {err:#}"
4865                    );
4866                    Vec::new()
4867                }
4868            }
4869        })
4870    }
4871
4872    /// Returns the active [`DcWasmResourceLimits`] for this session.
4873    #[must_use]
4874    pub const fn resource_limits(&self) -> DcWasmResourceLimits {
4875        self.resource_limits
4876    }
4877
4878    /// Updates the [`DcWasmResourceLimits`] enforced by this session.
4879    pub fn set_resource_limits(&mut self, limits: DcWasmResourceLimits) {
4880        let new_rem = limits
4881            .max_instructions_per_step
4882            .saturating_sub(self.total_instructions_executed);
4883        if self.paused_on_compute_quota && new_rem > self.remaining_compute_quota
4884        {
4885            self.pending_quota_increase_since_pause = self
4886                .pending_quota_increase_since_pause
4887                .saturating_add(
4888                    new_rem.saturating_sub(self.remaining_compute_quota),
4889                );
4890        }
4891        self.resource_limits = limits;
4892        self.current_compute_quota_limit = limits.max_instructions_per_step;
4893        self.remaining_compute_quota = new_rem;
4894        let _ = self.query_worker(|reply| WorkerCommand::ConfigureLimits {
4895            limits,
4896            reply,
4897        });
4898    }
4899
4900    /// Builder-style method returning `self` with updated [`DcWasmResourceLimits`].
4901    #[must_use]
4902    pub fn with_resource_limits(mut self, limits: DcWasmResourceLimits) -> Self {
4903        self.set_resource_limits(limits);
4904        self
4905    }
4906
4907    /// Attaches a [`SharedWasmTaskQuota`] so that this session shares its compute and
4908    /// cumulative output quota with other sessions in the same evaluation task.
4909    ///
4910    /// # Errors
4911    /// Returns an error if the shared quota mutex is poisoned or if `start` already
4912    /// exceeded the shared task's remaining compute quota.
4913    pub fn set_shared_task_quota(
4914        &mut self,
4915        shared: SharedWasmTaskQuota,
4916    ) -> Result<()> {
4917        let start_used = self.total_instructions_executed;
4918        let interruption_opt = shared.with_lock(|state| {
4919            if start_used > state.remaining_compute_quota {
4920                let err = WasmResourceInterruption::ComputeQuotaExhausted {
4921                    limit: state.current_compute_quota_limit,
4922                };
4923                state.last_resource_interruption = Some(err.clone());
4924                return Some(err);
4925            }
4926            state.remaining_compute_quota =
4927                state.remaining_compute_quota.saturating_sub(start_used);
4928            state.total_instructions_executed = state
4929                .total_instructions_executed
4930                .saturating_add(start_used);
4931            self.remaining_compute_quota = state.remaining_compute_quota;
4932            self.current_compute_quota_limit = state.current_compute_quota_limit;
4933            self.cumulative_output_bytes = state.cumulative_output_bytes;
4934            self.resource_limits.max_session_output_bytes =
4935                state.max_session_output_bytes;
4936            None
4937        })?;
4938        if let Some(interruption) = interruption_opt {
4939            self.last_resource_interruption = Some(interruption.clone());
4940            return Err(anyhow::Error::new(interruption));
4941        }
4942        self.shared_task_quota = Some(shared);
4943        Ok(())
4944    }
4945
4946    /// Returns `true` if this session is attached to a [`SharedWasmTaskQuota`].
4947    #[must_use]
4948    pub const fn has_shared_task_quota(&self) -> bool {
4949        self.shared_task_quota.is_some()
4950    }
4951
4952    /// Returns a clone of the attached [`SharedWasmTaskQuota`], if any.
4953    #[must_use]
4954    pub fn shared_task_quota(&self) -> Option<SharedWasmTaskQuota> {
4955        self.shared_task_quota.clone()
4956    }
4957
4958    /// Builder-style method attaching a [`SharedWasmTaskQuota`].
4959    ///
4960    /// # Errors
4961    /// Returns an error if [`Self::set_shared_task_quota`] fails.
4962    pub fn with_shared_task_quota(
4963        mut self,
4964        shared: SharedWasmTaskQuota,
4965    ) -> Result<Self> {
4966        self.set_shared_task_quota(shared)?;
4967        Ok(self)
4968    }
4969
4970    /// Increases the session's compute quota allowance by `additional_units`.
4971    ///
4972    /// When called after a [`WasmResourceInterruption::ComputeQuotaExhausted`] pause,
4973    /// the next [`Self::step`] call resumes the paused computation with the increased
4974    /// quota without repeating earlier step side effects.
4975    pub fn increase_compute_quota(&mut self, additional_units: u64) {
4976        self.remaining_compute_quota = self
4977            .remaining_compute_quota
4978            .saturating_add(additional_units);
4979        self.current_compute_quota_limit = self
4980            .current_compute_quota_limit
4981            .saturating_add(additional_units);
4982        self.resource_limits.max_instructions_per_step =
4983            self.current_compute_quota_limit;
4984        if self.paused_on_compute_quota {
4985            self.pending_quota_increase_since_pause = self
4986                .pending_quota_increase_since_pause
4987                .saturating_add(additional_units);
4988        }
4989        if let Some(shared) = &self.shared_task_quota {
4990            let _ = shared.increase_compute_quota(additional_units);
4991        }
4992    }
4993
4994    /// Returns the remaining compute quota units currently available to this session.
4995    #[must_use]
4996    pub const fn remaining_compute_quota(&self) -> u64 {
4997        self.remaining_compute_quota
4998    }
4999
5000    /// Returns the active compute quota limit (initial allowance plus any granted increases).
5001    #[must_use]
5002    pub const fn current_compute_quota_limit(&self) -> u64 {
5003        self.current_compute_quota_limit
5004    }
5005
5006    /// Returns the 1-based ordinal of the operation that triggered the most recent
5007    /// [`WasmResourceInterruption::ComputeQuotaExhausted`], if any.
5008    #[must_use]
5009    pub const fn last_interrupted_op_ordinal(&self) -> Option<u64> {
5010        self.last_interrupted_op_ordinal
5011    }
5012
5013    /// Returns the compute unit cost required by the operation that triggered the most recent
5014    /// [`WasmResourceInterruption::ComputeQuotaExhausted`], if any.
5015    #[must_use]
5016    pub const fn last_interrupted_op_required_cost(&self) -> Option<u64> {
5017        self.last_interrupted_op_required_cost
5018    }
5019
5020    /// Returns the value of an exported `i32` global by name, if present.
5021    #[must_use]
5022    pub fn exported_global_i32(&self, name: &str) -> Option<i32> {
5023        let name_owned = name.to_owned();
5024        self.query_worker(|reply| WorkerCommand::ExportedGlobalI32 {
5025            name: name_owned,
5026            reply,
5027        })
5028        .ok()
5029        .flatten()
5030    }
5031
5032    /// Returns the value of an exported `i64` global by name, if present.
5033    #[must_use]
5034    pub fn exported_global_i64(&self, name: &str) -> Option<i64> {
5035        let name_owned = name.to_owned();
5036        self.query_worker(|reply| WorkerCommand::ExportedGlobalI64 {
5037            name: name_owned,
5038            reply,
5039        })
5040        .ok()
5041        .flatten()
5042    }
5043
5044    /// Reads `len` bytes starting at `offset` from exported `"memory"`.
5045    ///
5046    /// # Errors
5047    /// Returns an error if exported `"memory"` is missing or `offset..offset + len` is out of bounds.
5048    pub fn read_memory(&mut self, offset: usize, len: usize) -> Result<Vec<u8>> {
5049        self.query_worker(|reply| WorkerCommand::ReadMemory {
5050            offset,
5051            len,
5052            reply,
5053        })?
5054    }
5055
5056    /// Returns the number of portable compute units consumed during the most recent `step()` call.
5057    #[must_use]
5058    pub const fn last_step_instructions(&self) -> u64 {
5059        self.last_step_instructions
5060    }
5061
5062    /// Returns the cumulative number of portable compute units consumed across this session.
5063    #[must_use]
5064    pub const fn total_instructions_executed(&self) -> u64 {
5065        self.total_instructions_executed
5066    }
5067
5068    /// Returns the cumulative number of output bytes decoded across all `step()` calls in this session.
5069    #[must_use]
5070    pub const fn cumulative_output_bytes(&self) -> usize {
5071        self.cumulative_output_bytes
5072    }
5073
5074    /// Returns the most recent [`WasmResourceInterruption`] raised by this session, if any.
5075    #[must_use]
5076    pub const fn last_resource_interruption(
5077        &self,
5078    ) -> Option<&WasmResourceInterruption> {
5079        self.last_resource_interruption.as_ref()
5080    }
5081
5082    /// Returns the most recent input document provided to [`Self::provide_input`].
5083    #[must_use]
5084    pub fn current_input(&self) -> &DcMstr {
5085        &self.current_input_doc
5086    }
5087
5088    /// Returns the current number of 64 KiB pages allocated across the session store's linear memories.
5089    ///
5090    /// # Errors
5091    /// Returns an error if the exported `"memory"` cannot be accessed.
5092    pub fn current_memory_pages(&mut self) -> Result<usize> {
5093        self.query_worker(|reply| WorkerCommand::ReadCurrentMemoryPages { reply })?
5094    }
5095
5096    /// Returns the total number of table elements currently allocated across the session store.
5097    #[must_use]
5098    pub fn current_table_elements(&self) -> usize {
5099        // Reason for fallback: if the worker channel closed, 0 table elements remain accessible.
5100        self.query_worker(|reply| WorkerCommand::ReadCurrentTableElements {
5101            reply,
5102        })
5103        .unwrap_or(0)
5104    }
5105
5106    /// Returns the byte offset (`input_ptr`) where the host places the input payload in linear memory.
5107    #[must_use]
5108    pub const fn base_io_offset(&self) -> usize {
5109        self.base_io_offset
5110    }
5111
5112    const fn effective_max_memory_pages(&self) -> usize {
5113        if self.resource_limits.max_memory_pages
5114            < self.resource_limits.physical_max_memory_pages
5115        {
5116            self.resource_limits.max_memory_pages
5117        } else {
5118            self.resource_limits.physical_max_memory_pages
5119        }
5120    }
5121
5122    const fn effective_max_table_elements(&self) -> usize {
5123        if self.resource_limits.max_table_elements
5124            < self.resource_limits.physical_max_table_elements
5125        {
5126            self.resource_limits.max_table_elements
5127        } else {
5128            self.resource_limits.physical_max_table_elements
5129        }
5130    }
5131
5132    /// Writes a new input [`DcMstr`] payload into WASM linear memory and updates the
5133    /// 32-byte mailbox header at `0..32`.
5134    ///
5135    /// Used both for initial document loading and for supplying the response/mock Dc document
5136    /// before resuming after [`WasmStepOutcome::RequestCapability`].
5137    ///
5138    /// # Errors
5139    /// Returns an error if linear memory cannot grow to accommodate the input and output buffers
5140    /// within [`DcWasmResourceLimits::max_memory_pages`].
5141    pub fn provide_input(&mut self, input: &DcMstr) -> Result<()> {
5142        ensure!(
5143            !self.paused_on_capability && !self.paused_on_compute_quota,
5144            "Cannot reset input via provide_input while WASM session is suspended mid-step; use provide_capability_response"
5145        );
5146        let raw_bytes = input.as_bytes();
5147        // Strip the 21-byte `DcMM\0` + UUID file header so `input_ptr` points directly
5148        // to the DcTF character/encapsulation stream.
5149        // Reason for fallback: slices shorter than DCMM_HEADER_LEN are already raw payload slices.
5150        let payload_bytes =
5151            raw_bytes.get(DCMM_HEADER_LEN..).unwrap_or(raw_bytes);
5152        let input_ptr = self.base_io_offset;
5153        let input_len = payload_bytes.len();
5154        let after_input = input_ptr
5155            .checked_add(input_len)
5156            .context("WASM input buffer end offset overflow")?;
5157        let default_output_ptr = align_up_8(after_input)?;
5158        let min_output_reserve = input_len.saturating_mul(2).max(4096);
5159        let required_mem_bytes = default_output_ptr
5160            .checked_add(min_output_reserve)
5161            .context("WASM required linear memory size overflow")?;
5162        // Reason for fallback: 65_536 is a non-zero constant divisor.
5163        let required_pages = required_mem_bytes
5164            .saturating_add(65_535)
5165            .checked_div(65_536)
5166            .unwrap_or(1);
5167        let total_store_pages = self.current_memory_pages()?;
5168        let exported_pages = self.query_worker(|reply| {
5169            WorkerCommand::ReadExportedMemoryPages { reply }
5170        })??;
5171        let other_mem_pages = total_store_pages.saturating_sub(exported_pages);
5172        let required_total_pages =
5173            other_mem_pages.saturating_add(required_pages.max(exported_pages));
5174        let effective_max_pages = self.effective_max_memory_pages();
5175        if required_total_pages > effective_max_pages {
5176            let interruption = WasmResourceInterruption::MemoryLimitExceeded {
5177                requested_pages: required_total_pages,
5178                max_pages: effective_max_pages,
5179            };
5180            self.last_resource_interruption = Some(interruption.clone());
5181            return Err(anyhow::Error::new(interruption));
5182        }
5183
5184        let input_ptr_u32 = u32::try_from(input_ptr)
5185            .context("WASM input_ptr exceeds u32 address space")?;
5186        let input_len_u32 = u32::try_from(input_len)
5187            .context("WASM input_len exceeds u32 address space")?;
5188        let output_ptr_u32 = u32::try_from(default_output_ptr)
5189            .context("WASM default_output_ptr exceeds u32 address space")?;
5190        let payload_vec = payload_bytes.to_vec();
5191        // Reason for fallback: when no Dc 641 watermark is bound, the mailbox slot is 0.
5192        let watermark = self.most_recent_node_id.unwrap_or(0);
5193
5194        let mut header = [0u8; 32];
5195        header[0..4].copy_from_slice(&input_ptr_u32.to_le_bytes());
5196        header[4..8].copy_from_slice(&input_len_u32.to_le_bytes());
5197        header[8..12].copy_from_slice(&output_ptr_u32.to_le_bytes());
5198        header[12..16].copy_from_slice(&0u32.to_le_bytes());
5199        header[16..32].copy_from_slice(&watermark.to_le_bytes());
5200
5201        let write_res = self.query_worker(|reply| WorkerCommand::WriteInput {
5202            input_ptr,
5203            payload: payload_vec,
5204            header,
5205            required_mem_bytes,
5206            total_store_pages,
5207            other_mem_pages,
5208            effective_max_pages,
5209            reply,
5210        })?;
5211        if let Err(err) = write_res {
5212            if let Some(interruption) =
5213                err.downcast_ref::<WasmResourceInterruption>()
5214            {
5215                self.last_resource_interruption = Some(interruption.clone());
5216            }
5217            return Err(err);
5218        }
5219
5220        self.current_input_ptr = input_ptr_u32;
5221        self.current_input_len = input_len_u32;
5222        self.default_output_ptr = output_ptr_u32;
5223        self.current_input_doc = input.to_owned();
5224        Ok(())
5225    }
5226
5227    /// Validates and writes a capability response [`DcMstr`] into WASM linear memory,
5228    /// enforcing [`DcWasmResourceLimits::max_capability_payload_bytes`] **before**
5229    /// writing the response into the guest mailbox.
5230    ///
5231    /// # Errors
5232    /// Returns [`WasmResourceInterruption::CapabilityPayloadTooLarge`] if the capability
5233    /// response payload exceeds `max_capability_payload_bytes`, or an error if writing
5234    /// the payload into linear memory fails.
5235    pub fn provide_capability_response(
5236        &mut self,
5237        response: &DcMstr,
5238    ) -> Result<()> {
5239        let raw_bytes = response.as_bytes();
5240        // Reason for fallback: slices shorter than DCMM_HEADER_LEN are already raw payload slices.
5241        let payload_bytes =
5242            raw_bytes.get(DCMM_HEADER_LEN..).unwrap_or(raw_bytes);
5243        if payload_bytes.len()
5244            > self.resource_limits.max_capability_payload_bytes
5245        {
5246            let interruption =
5247                WasmResourceInterruption::CapabilityPayloadTooLarge {
5248                    payload_bytes: payload_bytes.len(),
5249                    max_capability_payload_bytes: self
5250                        .resource_limits
5251                        .max_capability_payload_bytes,
5252                };
5253            self.last_resource_interruption = Some(interruption.clone());
5254            if let Some(shared) = &self.shared_task_quota {
5255                let _ = shared.with_lock(|state| {
5256                    state.last_resource_interruption =
5257                        Some(interruption.clone());
5258                });
5259            }
5260            return Err(anyhow::Error::new(interruption));
5261        }
5262        if self.paused_on_capability {
5263            self.pending_capability_response = Some(payload_bytes.to_vec());
5264            return Ok(());
5265        }
5266        self.provide_input(response)
5267    }
5268
5269    fn record_step_compute_usage(
5270        &mut self,
5271        consumed_before_call: u64,
5272        consumed: u64,
5273        remaining: u64,
5274    ) -> Result<()> {
5275        let delta_consumed = consumed.saturating_sub(consumed_before_call);
5276        self.last_step_instructions = consumed;
5277        self.remaining_compute_quota = remaining;
5278        self.total_instructions_executed = self
5279            .total_instructions_executed
5280            .saturating_add(delta_consumed);
5281        if let Some(shared) = &self.shared_task_quota {
5282            shared.with_lock(|state| {
5283                state.remaining_compute_quota = remaining;
5284                state.total_instructions_executed = state
5285                    .total_instructions_executed
5286                    .saturating_add(delta_consumed);
5287            })?;
5288        }
5289        Ok(())
5290    }
5291
5292    fn read_and_decode_capability_request(
5293        &mut self,
5294        out_ptr: usize,
5295        out_len: usize,
5296    ) -> Result<DcMstring> {
5297        if out_len > self.resource_limits.max_capability_payload_bytes {
5298            let interruption =
5299                WasmResourceInterruption::CapabilityPayloadTooLarge {
5300                    payload_bytes: out_len,
5301                    max_capability_payload_bytes: self
5302                        .resource_limits
5303                        .max_capability_payload_bytes,
5304                };
5305            self.last_resource_interruption = Some(interruption.clone());
5306            if let Some(shared) = &self.shared_task_quota {
5307                let _ = shared.with_lock(|state| {
5308                    state.last_resource_interruption =
5309                        Some(interruption.clone());
5310                });
5311            }
5312            return Err(anyhow::Error::new(interruption));
5313        }
5314        let out_bytes = self.read_memory(out_ptr, out_len).map_err(|e| {
5315            anyhow!(
5316                "WASM capability request slice ({out_ptr}..{}) is out of linear memory bounds: {e}",
5317                out_ptr.saturating_add(out_len)
5318            )
5319        })?;
5320        decode_output_bytes_to_dcmstring(&out_bytes)
5321    }
5322
5323    fn call_entry_once(
5324        store: &mut Store,
5325        instance: &ModuleInstance,
5326        entry_func_name: &str,
5327        in_ptr_i32: i32,
5328        in_len_i32: i32,
5329    ) -> Result<std::result::Result<i32, ctb_formats_dcdata::tinywasm::Error>>
5330    {
5331        if let Ok(func) =
5332            instance.exported_func::<(), i32>(store, entry_func_name)
5333        {
5334            Ok(func.call(store, ()))
5335        } else if let Ok(func) =
5336            instance.exported_func::<(i32, i32), i32>(store, entry_func_name)
5337        {
5338            Ok(func.call(store, (in_ptr_i32, in_len_i32)))
5339        } else if let Ok(func) =
5340            instance.exported_func::<(), ()>(store, entry_func_name)
5341        {
5342            Ok(func.call(store, ()).map(|()| WASM_STEP_STATUS_COMPLETE))
5343        } else if let Ok(func) =
5344            instance.exported_func::<(i32, i32), ()>(store, entry_func_name)
5345        {
5346            Ok(func
5347                .call(store, (in_ptr_i32, in_len_i32))
5348                .map(|()| WASM_STEP_STATUS_COMPLETE))
5349        } else {
5350            bail!(
5351                "Exported WASM entry function '{entry_func_name}' must have signature () -> i32, (i32, i32) -> i32, () -> (), or (i32, i32) -> ()"
5352            )
5353        }
5354    }
5355
5356    /// Executes one pure-compute quantum by calling the module's exported `"step"` (or `"main"`)
5357    /// function (or resuming its live suspended continuation after a compute-quota increase)
5358    /// and decoding the output [`DcMstring`] from linear memory according to the returned
5359    /// [`WasmStepStatus`].
5360    ///
5361    /// # Errors
5362    /// Returns an error if the WASM function traps, exhausts its portable compute quota,
5363    /// returns an invalid status code, exceeds single-step or cumulative output byte budgets, or
5364    /// writes an out-of-bounds or malformed Dc output slice.
5365    #[allow(
5366        clippy::too_many_lines,
5367        reason = "Coordinates resumable compute quota, mailbox I/O, and shared task budgets"
5368    )]
5369    pub fn step(&mut self) -> Result<WasmStepOutcome> {
5370        self.last_resource_interruption = None;
5371
5372        if let Some(shared) = &self.shared_task_quota {
5373            let _ = shared.apply_staged_boundary_limits()?;
5374            let snap = shared.snapshot()?;
5375            if self.paused_on_compute_quota
5376                && snap.remaining_compute_quota > self.remaining_compute_quota
5377            {
5378                self.pending_quota_increase_since_pause = self
5379                    .pending_quota_increase_since_pause
5380                    .saturating_add(
5381                        snap.remaining_compute_quota
5382                            .saturating_sub(self.remaining_compute_quota),
5383                    );
5384            }
5385            self.resource_limits = snap.active_limits;
5386            self.remaining_compute_quota = snap.remaining_compute_quota;
5387            self.current_compute_quota_limit = snap.current_compute_quota_limit;
5388            self.cumulative_output_bytes = snap.cumulative_output_bytes;
5389            self.resource_limits.max_session_output_bytes =
5390                snap.max_session_output_bytes;
5391        }
5392
5393        if self.paused_on_compute_quota
5394            && self.pending_quota_increase_since_pause == 0
5395        {
5396            let interruption = WasmResourceInterruption::ComputeQuotaExhausted {
5397                limit: self.current_compute_quota_limit,
5398            };
5399            self.last_resource_interruption = Some(interruption.clone());
5400            return Err(anyhow::Error::new(interruption));
5401        }
5402
5403        let current_pages = self.current_memory_pages()?;
5404        let effective_max_pages = self.effective_max_memory_pages();
5405        if current_pages > effective_max_pages {
5406            let interruption = WasmResourceInterruption::MemoryLimitExceeded {
5407                requested_pages: current_pages,
5408                max_pages: effective_max_pages,
5409            };
5410            self.last_resource_interruption = Some(interruption.clone());
5411            return Err(anyhow::Error::new(interruption));
5412        }
5413        let current_table_elems = self.current_table_elements();
5414        let effective_max_elems = self.effective_max_table_elements();
5415        if current_table_elems > effective_max_elems {
5416            let interruption = WasmResourceInterruption::TableLimitExceeded {
5417                requested_elements: current_table_elems,
5418                max_elements: effective_max_elems,
5419            };
5420            self.last_resource_interruption = Some(interruption.clone());
5421            return Err(anyhow::Error::new(interruption));
5422        }
5423
5424        let (consumed_before_call, evt) = if self.paused_on_capability {
5425            let response_bytes = self
5426                .pending_capability_response
5427                .take()
5428                .context("WASM session paused on capability request without a response; call provide_capability_response first")?;
5429            let prev_consumed = self.query_worker(|reply| {
5430                WorkerCommand::ReadQuotaConsumed { reply }
5431            })?;
5432            let guard = self
5433                .worker
5434                .lock()
5435                .map_err(|_| anyhow!("WASM session worker mutex poisoned"))?;
5436            guard
5437                .cmd_tx
5438                .send(WorkerCommand::ResumeCapability {
5439                    response_bytes,
5440                    quota_rem: self.remaining_compute_quota,
5441                    limits: self.resource_limits,
5442                })
5443                .map_err(|_| {
5444                    anyhow!(
5445                        "WASM session continuation worker exited unexpectedly"
5446                    )
5447                })?;
5448            let evt = guard.evt_rx.recv().map_err(|_| {
5449                anyhow!("WASM session continuation worker failed to respond")
5450            })?;
5451            drop(guard);
5452            (prev_consumed, evt)
5453        } else if self.paused_on_compute_quota {
5454            let prev_consumed = self.query_worker(|reply| {
5455                WorkerCommand::ReadQuotaConsumed { reply }
5456            })?;
5457            self.pending_quota_increase_since_pause = 0;
5458            let guard = self
5459                .worker
5460                .lock()
5461                .map_err(|_| anyhow!("WASM session worker mutex poisoned"))?;
5462            guard
5463                .cmd_tx
5464                .send(WorkerCommand::ResumeStep {
5465                    quota_rem: self.remaining_compute_quota,
5466                    limits: self.resource_limits,
5467                })
5468                .map_err(|_| {
5469                    anyhow!(
5470                        "WASM session continuation worker exited unexpectedly"
5471                    )
5472                })?;
5473            let evt = guard.evt_rx.recv().map_err(|_| {
5474                anyhow!("WASM session continuation worker failed to respond")
5475            })?;
5476            drop(guard);
5477            (prev_consumed, evt)
5478        } else {
5479            let in_ptr_i32 =
5480                i32::from_le_bytes(self.current_input_ptr.to_le_bytes());
5481            let in_len_i32 =
5482                i32::from_le_bytes(self.current_input_len.to_le_bytes());
5483            let guard = self
5484                .worker
5485                .lock()
5486                .map_err(|_| anyhow!("WASM session worker mutex poisoned"))?;
5487            guard
5488                .cmd_tx
5489                .send(WorkerCommand::StartStep {
5490                    entry_func_name: self.entry_func_name.clone(),
5491                    in_ptr_i32,
5492                    in_len_i32,
5493                    default_output_ptr: self.default_output_ptr,
5494                    quota_rem: self.remaining_compute_quota,
5495                    limits: self.resource_limits,
5496                })
5497                .map_err(|_| {
5498                    anyhow!(
5499                        "WASM session continuation worker exited unexpectedly"
5500                    )
5501                })?;
5502            let evt = guard.evt_rx.recv().map_err(|_| {
5503                anyhow!("WASM session continuation worker failed to respond")
5504            })?;
5505            drop(guard);
5506            (0u64, evt)
5507        };
5508
5509        let raw_status = match evt {
5510            WorkerEvent::StepPausedOnCapability {
5511                consumed,
5512                remaining,
5513                out_ptr,
5514                out_len,
5515            } => {
5516                self.record_step_compute_usage(
5517                    consumed_before_call,
5518                    consumed,
5519                    remaining,
5520                )?;
5521                self.paused_on_compute_quota = false;
5522                self.paused_on_capability = true;
5523                self.pending_capability_response = None;
5524                let req_doc = self.read_and_decode_capability_request(
5525                    out_ptr, out_len,
5526                )?;
5527                return Ok(WasmStepOutcome::RequestCapability(req_doc));
5528            }
5529            WorkerEvent::StepPausedOnQuota {
5530                consumed,
5531                remaining,
5532                interrupted_op,
5533                required_cost,
5534            } => {
5535                self.record_step_compute_usage(
5536                    consumed_before_call,
5537                    consumed,
5538                    remaining,
5539                )?;
5540                self.paused_on_capability = false;
5541                self.paused_on_compute_quota = true;
5542                self.pending_quota_increase_since_pause = 0;
5543                self.last_interrupted_op_ordinal = Some(interrupted_op);
5544                self.last_interrupted_op_required_cost = Some(required_cost);
5545                let interruption =
5546                    WasmResourceInterruption::ComputeQuotaExhausted {
5547                        limit: self.current_compute_quota_limit,
5548                    };
5549                self.last_resource_interruption = Some(interruption.clone());
5550                if let Some(shared) = &self.shared_task_quota {
5551                    let _ = shared.with_lock(|state| {
5552                        state.last_resource_interruption =
5553                            Some(interruption.clone());
5554                    });
5555                }
5556                return Err(anyhow::Error::new(interruption));
5557            }
5558            WorkerEvent::StepFinished {
5559                call_res,
5560                consumed,
5561                remaining,
5562                exhausted,
5563                interrupted_op,
5564                required_cost,
5565            } => {
5566                self.record_step_compute_usage(
5567                    consumed_before_call,
5568                    consumed,
5569                    remaining,
5570                )?;
5571                self.paused_on_compute_quota = false;
5572                self.paused_on_capability = false;
5573                match call_res {
5574                    Ok(code) => {
5575                        self.last_interrupted_op_ordinal = None;
5576                        self.last_interrupted_op_required_cost = None;
5577                        code
5578                    }
5579                    Err(call_err) => match exhausted {
5580                        1 => {
5581                            self.last_interrupted_op_ordinal =
5582                                Some(interrupted_op);
5583                            self.last_interrupted_op_required_cost =
5584                                Some(required_cost);
5585                            let interruption =
5586                                WasmResourceInterruption::ComputeQuotaExhausted {
5587                                    limit: self.current_compute_quota_limit,
5588                                };
5589                            self.last_resource_interruption =
5590                                Some(interruption.clone());
5591                            if let Some(shared) = &self.shared_task_quota {
5592                                let _ = shared.with_lock(|state| {
5593                                    state.last_resource_interruption =
5594                                        Some(interruption.clone());
5595                                });
5596                            }
5597                            return Err(anyhow::Error::new(interruption));
5598                        }
5599                        2 => {
5600                            // Reason for fallback: on 32-bit hosts, a 64-bit requested page count
5601                            // exceeding usize::MAX saturates to usize::MAX in the diagnostic report.
5602                            let requested_pages =
5603                                usize::try_from(interrupted_op)
5604                                    .unwrap_or(usize::MAX);
5605                            let interruption =
5606                                WasmResourceInterruption::MemoryLimitExceeded {
5607                                    requested_pages,
5608                                    max_pages: effective_max_pages,
5609                                };
5610                            self.last_resource_interruption =
5611                                Some(interruption.clone());
5612                            if let Some(shared) = &self.shared_task_quota {
5613                                let _ = shared.with_lock(|state| {
5614                                    state.last_resource_interruption =
5615                                        Some(interruption.clone());
5616                                });
5617                            }
5618                            return Err(anyhow::Error::new(interruption));
5619                        }
5620                        3 => {
5621                            // Reason for fallback: on 32-bit hosts, a 64-bit requested element count
5622                            // exceeding usize::MAX saturates to usize::MAX in the diagnostic report.
5623                            let requested_elements =
5624                                usize::try_from(interrupted_op)
5625                                    .unwrap_or(usize::MAX);
5626                            let interruption =
5627                                WasmResourceInterruption::TableLimitExceeded {
5628                                    requested_elements,
5629                                    max_elements: effective_max_elems,
5630                                };
5631                            self.last_resource_interruption =
5632                                Some(interruption.clone());
5633                            if let Some(shared) = &self.shared_task_quota {
5634                                let _ = shared.with_lock(|state| {
5635                                    state.last_resource_interruption =
5636                                        Some(interruption.clone());
5637                                });
5638                            }
5639                            return Err(anyhow::Error::new(interruption));
5640                        }
5641                        _ => {
5642                            bail!(
5643                                "WASM execution trapped in '{}': {call_err}",
5644                                self.entry_func_name
5645                            );
5646                        }
5647                    },
5648                }
5649            }
5650        };
5651
5652        let status = WasmStepStatus::from_i32(raw_status)?;
5653
5654        let (out_ptr, out_len) = self.query_worker(|reply| {
5655            WorkerCommand::ReadOutputMailboxHeader { reply }
5656        })??;
5657
5658        if status == WasmStepStatus::RequestCapability {
5659            let req_doc =
5660                self.read_and_decode_capability_request(out_ptr, out_len)?;
5661            return Ok(WasmStepOutcome::RequestCapability(req_doc));
5662        }
5663
5664        if out_len > self.resource_limits.max_step_output_bytes {
5665            let interruption =
5666                WasmResourceInterruption::StepOutputSliceTooLarge {
5667                    output_bytes: out_len,
5668                    max_step_output_bytes: self
5669                        .resource_limits
5670                        .max_step_output_bytes,
5671                };
5672            self.last_resource_interruption = Some(interruption.clone());
5673            if let Some(shared) = &self.shared_task_quota {
5674                let _ = shared.with_lock(|state| {
5675                    state.last_resource_interruption =
5676                        Some(interruption.clone());
5677                });
5678            }
5679            return Err(anyhow::Error::new(interruption));
5680        }
5681
5682        let new_cumulative =
5683            self.cumulative_output_bytes.saturating_add(out_len);
5684        if new_cumulative > self.resource_limits.max_session_output_bytes {
5685            let interruption =
5686                WasmResourceInterruption::SessionOutputBudgetExceeded {
5687                    cumulative_output_bytes: new_cumulative,
5688                    max_session_output_bytes: self
5689                        .resource_limits
5690                        .max_session_output_bytes,
5691                };
5692            self.last_resource_interruption = Some(interruption.clone());
5693            if let Some(shared) = &self.shared_task_quota {
5694                let _ = shared.with_lock(|state| {
5695                    state.last_resource_interruption =
5696                        Some(interruption.clone());
5697                });
5698            }
5699            return Err(anyhow::Error::new(interruption));
5700        }
5701
5702        let out_bytes = self.read_memory(out_ptr, out_len).map_err(|e| {
5703            anyhow!(
5704                "WASM output slice ({out_ptr}..{}) is out of linear memory bounds: {e}",
5705                out_ptr.saturating_add(out_len)
5706            )
5707        })?;
5708
5709        let out_doc = decode_output_bytes_to_dcmstring(&out_bytes)?;
5710        self.cumulative_output_bytes = new_cumulative;
5711        if let Some(shared) = &self.shared_task_quota {
5712            shared.with_lock(|state| {
5713                state.cumulative_output_bytes = new_cumulative;
5714            })?;
5715        }
5716        Ok(match status {
5717            WasmStepStatus::Complete => WasmStepOutcome::Complete(out_doc),
5718            WasmStepStatus::YieldFrame => WasmStepOutcome::YieldFrame(out_doc),
5719            WasmStepStatus::RequestCapability => {
5720                unreachable!("handled immediately above")
5721            }
5722        })
5723    }
5724}
5725
5726/// Runs a pure-compute Dc-WASM conversion (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
5727/// or `wasm_routine`) over `input` using the default syntax resolver.
5728///
5729/// Any `2 = RequestCapability` status returned during a pure conversion is immediately denied with
5730/// an error. If the program emits streaming frames via `1 = YieldFrame`, they are concatenated in
5731/// order ahead of the final `0 = Complete` document.
5732///
5733/// # Errors
5734/// Returns an error if assembly or execution fails, if the program requests a privileged
5735/// capability during pure conversion, or if it exceeds [`DEFAULT_MAX_PURE_CONVERSION_STEPS`].
5736pub fn run_dc_wasm_pure_conversion(
5737    wasm_doc: &DcMstr,
5738    input: &DcMstr,
5739) -> Result<DcMstring> {
5740    let resolver = default_syntax_resolver();
5741    run_dc_wasm_pure_conversion_with_resolver(wasm_doc, input, resolver.as_ref())
5742}
5743
5744/// Runs a pure-compute Dc-WASM conversion (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
5745/// or `wasm_routine`) over `input` using the supplied [`SyntaxRuleResolver`].
5746///
5747/// # Errors
5748/// Returns an error if assembly or execution fails, if the program requests a privileged
5749/// capability during pure conversion, or if it exceeds [`DEFAULT_MAX_PURE_CONVERSION_STEPS`].
5750pub fn run_dc_wasm_pure_conversion_with_resolver(
5751    wasm_doc: &DcMstr,
5752    input: &DcMstr,
5753    resolver: &dyn SyntaxRuleResolver,
5754) -> Result<DcMstring> {
5755    run_dc_wasm_pure_conversion_with_resolver_and_quota(
5756        wasm_doc, input, resolver, None,
5757    )
5758}
5759
5760const MAX_MEMOIZED_PURE_WASM_MODULE_BYTES: usize = 8 * 1024 * 1024;
5761const MAX_MEMOIZED_PURE_INPUT_BYTES: usize = 256 * 1024;
5762const MAX_MEMOIZED_PURE_OUTPUT_BYTES: usize = 1024 * 1024;
5763const MAX_MEMOIZED_PURE_CACHE_ENTRIES: usize = 512;
5764
5765#[derive(Clone)]
5766struct CachedPureWasmConversion {
5767    output_doc_bytes: std::sync::Arc<Vec<u8>>,
5768    executed_instructions: u64,
5769    peak_memory_pages: usize,
5770    peak_table_elements: usize,
5771    max_step_output_bytes: usize,
5772    total_output_payload_bytes: usize,
5773}
5774
5775static PURE_WASM_CONVERSION_CACHE: std::sync::OnceLock<
5776    std::sync::Mutex<std::collections::HashMap<[u8; 32], CachedPureWasmConversion>>,
5777> = std::sync::OnceLock::new();
5778
5779fn hash_pure_wasm_conversion_key(
5780    wasm_sha256: &[u8; 32],
5781    most_recent: Option<u128>,
5782    input_bytes: &[u8],
5783) -> [u8; 32] {
5784    let mut hasher = Sha256::new();
5785    hasher.update(b"ctb-pure-wasm-conv-v1");
5786    hasher.update(WASM_RESOURCE_ACCOUNTING_VERSION.to_le_bytes());
5787    hasher.update(wasm_sha256);
5788    match most_recent {
5789        Some(pin) => {
5790            hasher.update([1u8]);
5791            hasher.update(pin.to_le_bytes());
5792        }
5793        None => hasher.update([0u8]),
5794    }
5795    hasher.update(input_bytes);
5796    hasher.finalize().into()
5797}
5798
5799fn try_charge_cached_pure_conversion(
5800    entry: &CachedPureWasmConversion,
5801    limits: &DcWasmResourceLimits,
5802    shared_quota: Option<&SharedWasmTaskQuota>,
5803) -> Result<Option<DcMstring>> {
5804    let eff_mem = limits.max_memory_pages.min(limits.physical_max_memory_pages);
5805    let eff_tbl = limits
5806        .max_table_elements
5807        .min(limits.physical_max_table_elements);
5808    if eff_mem < entry.peak_memory_pages
5809        || eff_tbl < entry.peak_table_elements
5810        || entry.max_step_output_bytes > limits.max_step_output_bytes
5811    {
5812        return Ok(None);
5813    }
5814    if let Some(shared) = shared_quota {
5815        let charged = shared.with_lock(|st| {
5816            let next_out = st
5817                .cumulative_output_bytes
5818                .saturating_add(entry.total_output_payload_bytes);
5819            if st.remaining_compute_quota >= entry.executed_instructions
5820                && next_out <= st.max_session_output_bytes
5821            {
5822                st.remaining_compute_quota = st
5823                    .remaining_compute_quota
5824                    .saturating_sub(entry.executed_instructions);
5825                st.total_instructions_executed = st
5826                    .total_instructions_executed
5827                    .saturating_add(entry.executed_instructions);
5828                st.cumulative_output_bytes = next_out;
5829                true
5830            } else {
5831                false
5832            }
5833        })?;
5834        if !charged {
5835            return Ok(None);
5836        }
5837    } else if limits.max_instructions_per_step < entry.executed_instructions
5838        || entry.total_output_payload_bytes > limits.max_session_output_bytes
5839    {
5840        return Ok(None);
5841    }
5842    Ok(Some(DcMstring {
5843        inner: (*entry.output_doc_bytes).clone(),
5844    }))
5845}
5846
5847fn run_pure_conversion_session_and_maybe_cache(
5848    mut session: DcWasmSession,
5849    shared_quota: Option<SharedWasmTaskQuota>,
5850    cache_key: Option<[u8; 32]>,
5851) -> Result<DcMstring> {
5852    if let Some(shared) = shared_quota {
5853        session.set_shared_task_quota(shared)?;
5854    }
5855    let mut accumulated = DcMstring::new();
5856    let mut max_step_out = 0usize;
5857    for _ in 0..DEFAULT_MAX_PURE_CONVERSION_STEPS {
5858        match session.step()? {
5859            WasmStepOutcome::Complete(doc) => {
5860                let step_payload_len =
5861                    doc.as_bytes().len().saturating_sub(DCMM_HEADER_LEN);
5862                max_step_out = max_step_out.max(step_payload_len);
5863                let final_doc = if accumulated.is_empty() {
5864                    doc
5865                } else {
5866                    if let Some(tail) = doc.as_bytes().get(DCMM_HEADER_LEN..) {
5867                        accumulated.inner.extend_from_slice(tail);
5868                    }
5869                    accumulated
5870                };
5871                if let Some(key) = cache_key
5872                    && final_doc.as_bytes().len() <= MAX_MEMOIZED_PURE_OUTPUT_BYTES
5873                    && let Ok(peak_mem) = session.current_memory_pages()
5874                {
5875                    let entry = CachedPureWasmConversion {
5876                        output_doc_bytes: std::sync::Arc::new(
5877                            final_doc.as_bytes().to_vec(),
5878                        ),
5879                        executed_instructions: session
5880                            .total_instructions_executed(),
5881                        peak_memory_pages: peak_mem,
5882                        peak_table_elements: session.current_table_elements(),
5883                        max_step_output_bytes: max_step_out,
5884                        total_output_payload_bytes: session
5885                            .cumulative_output_bytes(),
5886                    };
5887                    let map_lock = PURE_WASM_CONVERSION_CACHE.get_or_init(|| {
5888                        std::sync::Mutex::new(std::collections::HashMap::new())
5889                    });
5890                    if let Ok(mut guard) = map_lock.lock() {
5891                        if guard.len() >= MAX_MEMOIZED_PURE_CACHE_ENTRIES {
5892                            guard.clear();
5893                        }
5894                        guard.insert(key, entry);
5895                    }
5896                }
5897                return Ok(final_doc);
5898            }
5899            WasmStepOutcome::YieldFrame(frame) => {
5900                let step_payload_len =
5901                    frame.as_bytes().len().saturating_sub(DCMM_HEADER_LEN);
5902                max_step_out = max_step_out.max(step_payload_len);
5903                if let Some(tail) = frame.as_bytes().get(DCMM_HEADER_LEN..) {
5904                    accumulated.inner.extend_from_slice(tail);
5905                }
5906            }
5907            WasmStepOutcome::RequestCapability(req) => {
5908                bail!(
5909                    "Pure Dc-WASM conversion denied capability request: {req}"
5910                );
5911            }
5912        }
5913    }
5914    bail!(
5915        "Pure Dc-WASM conversion exceeded maximum step limit ({DEFAULT_MAX_PURE_CONVERSION_STEPS})"
5916    )
5917}
5918
5919fn run_substitute_descriptor_pure_conversion_with_quota(
5920    desc: WasmSubstituteDescriptor,
5921    input: &DcMstr,
5922    most_recent: Option<u128>,
5923    shared_quota: Option<SharedWasmTaskQuota>,
5924) -> Result<DcMstring> {
5925    let limits = if let Some(ref shared) = shared_quota {
5926        shared.active_limits()?
5927    } else {
5928        DcWasmResourceLimits::default()
5929    };
5930    let cache_key = (input.as_bytes().len() <= MAX_MEMOIZED_PURE_INPUT_BYTES)
5931        .then(|| {
5932            hash_pure_wasm_conversion_key(
5933                &desc.meta.wasm_sha256,
5934                most_recent,
5935                input.as_bytes(),
5936            )
5937        });
5938    if let Some(ref key) = cache_key {
5939        let map_lock = PURE_WASM_CONVERSION_CACHE
5940            .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
5941        let cached_opt = map_lock.lock().ok().and_then(|g| g.get(key).cloned());
5942        if let Some(entry) = cached_opt
5943            && let Some(hit) = try_charge_cached_pure_conversion(
5944                &entry,
5945                &limits,
5946                shared_quota.as_ref(),
5947            )?
5948        {
5949            return Ok(hit);
5950        }
5951    }
5952    let session = DcWasmSession::from_substitute_descriptor_with_limits(
5953        desc,
5954        input,
5955        most_recent,
5956        limits,
5957    )?;
5958    run_pure_conversion_session_and_maybe_cache(session, shared_quota, cache_key)
5959}
5960
5961/// Runs a pure-compute WebAssembly conversion from pre-assembled `.wasm` bytes over `input`
5962/// using an optional [`SharedWasmTaskQuota`].
5963///
5964/// # Errors
5965/// Returns an error if instantiation or execution fails, if the program requests a privileged
5966/// capability during pure conversion, or if it exhausts its compute/output quota or step limit.
5967pub fn run_wasm_bytes_pure_conversion_with_quota(
5968    wasm_bytes: &[u8],
5969    input: &DcMstr,
5970    most_recent: Option<u128>,
5971    shared_quota: Option<SharedWasmTaskQuota>,
5972) -> Result<DcMstring> {
5973    let limits = if let Some(ref shared) = shared_quota {
5974        shared.active_limits()?
5975    } else {
5976        DcWasmResourceLimits::default()
5977    };
5978    let cache_key = (wasm_bytes.len() <= MAX_MEMOIZED_PURE_WASM_MODULE_BYTES
5979        && input.as_bytes().len() <= MAX_MEMOIZED_PURE_INPUT_BYTES)
5980        .then(|| {
5981            let wasm_sha256: [u8; 32] = Sha256::digest(wasm_bytes).into();
5982            hash_pure_wasm_conversion_key(&wasm_sha256, most_recent, input.as_bytes())
5983        });
5984    if let Some(ref key) = cache_key {
5985        let map_lock = PURE_WASM_CONVERSION_CACHE
5986            .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
5987        let cached_opt = map_lock.lock().ok().and_then(|g| g.get(key).cloned());
5988        if let Some(entry) = cached_opt
5989            && let Some(hit) = try_charge_cached_pure_conversion(
5990                &entry,
5991                &limits,
5992                shared_quota.as_ref(),
5993            )?
5994        {
5995            return Ok(hit);
5996        }
5997    }
5998    let session = DcWasmSession::from_wasm_bytes_with_limits(
5999        wasm_bytes,
6000        input,
6001        most_recent,
6002        limits,
6003    )?;
6004    run_pure_conversion_session_and_maybe_cache(session, shared_quota, cache_key)
6005}
6006
6007/// Runs a pure-compute Dc-WASM conversion (`Dc 1927 "Begin WASM program"`..`Dc 1928 "End WASM program"`
6008/// or `wasm_routine`) over `input` using `resolver` and an optional [`SharedWasmTaskQuota`].
6009///
6010/// # Errors
6011/// Returns an error if assembly or execution fails, if the program requests a privileged
6012/// capability during pure conversion, or if it exhausts its compute/output quota or step limit.
6013pub fn run_dc_wasm_pure_conversion_with_resolver_and_quota(
6014    wasm_doc: &DcMstr,
6015    input: &DcMstr,
6016    resolver: &dyn SyntaxRuleResolver,
6017    shared_quota: Option<SharedWasmTaskQuota>,
6018) -> Result<DcMstring> {
6019    let most_recent = resolver
6020        .seed_graph()
6021        .and_then(ctb_formats_dcdata::seed_graph::SeedGraphIndex::system_block_most_recent_node_id);
6022    let wasm_bytes = dcmstring_to_wasm_with_resolver(wasm_doc, resolver)?;
6023    run_wasm_bytes_pure_conversion_with_quota(
6024        &wasm_bytes,
6025        input,
6026        most_recent,
6027        shared_quota,
6028    )
6029}
6030
6031fn strip_nested_wasm_program_delimiters<'a>(
6032    tokens: &'a [ctb_storage_minimal::shorthand::DcShorthand],
6033    wasm_prog_depth: usize,
6034    resolver: &dyn SyntaxRuleResolver,
6035) -> &'a [ctb_storage_minimal::shorthand::DcShorthand] {
6036    if wasm_prog_depth > 0
6037        && tokens.len() >= 2
6038        && let (Some(first), Some(last)) = (tokens.first(), tokens.last())
6039        && let (Ok(first_gid), Ok(last_gid)) =
6040            (first.to_global_id(), last.to_global_id())
6041        && resolver.token_fills_role(first_gid, DcRole::BeginWasmProgram)
6042        && resolver.token_fills_role(last_gid, DcRole::EndWasmProgram)
6043        && let Some(inner) = tokens.get(1..tokens.len().saturating_sub(1))
6044    {
6045        return inner;
6046    }
6047    tokens
6048}
6049
6050fn expand_graph_wasm_shorthands(
6051    shorthands: &[ctb_storage_minimal::shorthand::DcShorthand],
6052    resolver: &dyn SyntaxRuleResolver,
6053    out_doc: &mut DcMstring,
6054) -> Result<()> {
6055    use ctb_storage_minimal::shorthand::DcShorthand;
6056
6057    struct WasmExpansionFrame<'a> {
6058        iter: std::slice::Iter<'a, DcShorthand>,
6059        node_id: Option<u128>,
6060        shorthand: Option<DcShorthand>,
6061    }
6062
6063    let mut visited_nodes = std::collections::HashSet::new();
6064    let mut visited_shorthands = std::collections::HashSet::new();
6065    let mut wasm_prog_depth = 0usize;
6066    let mut expanded_dc_str =
6067        DcString::with_capacity(shorthands.len().saturating_mul(4));
6068    let mut frames = vec![WasmExpansionFrame {
6069        iter: shorthands.iter(),
6070        node_id: None,
6071        shorthand: None,
6072    }];
6073    while let Some(frame) = frames.last_mut() {
6074        let Some(&sh) = frame.iter.next() else {
6075            if let Some(popped) = frames.pop() {
6076                if let Some(node_id) = popped.node_id {
6077                    visited_nodes.remove(&node_id);
6078                }
6079                if let Some(short_tok) = popped.shorthand {
6080                    visited_shorthands.remove(&short_tok);
6081                }
6082            }
6083            continue;
6084        };
6085        let gid = sh
6086            .to_global_id()
6087            .map_err(|e| anyhow!("Invalid graph WASM shorthand {sh}: {e}"))?;
6088        if resolver.token_fills_role(gid, DcRole::Escape)
6089            || resolver.token_fills_role(gid, DcRole::QuoteFollowingDcAsAtom)
6090        {
6091            out_doc.push_char(DcChar::from_u128(gid));
6092            let escaped_sh = frame
6093                .iter
6094                .next()
6095                .copied()
6096                .context("Dangling escape or atom quote in graph WASM definition")?;
6097            let escaped_gid = escaped_sh.to_global_id().map_err(|e| {
6098                anyhow!(
6099                    "Invalid escaped graph WASM shorthand {escaped_sh}: {e}"
6100                )
6101            })?;
6102            out_doc.push_char(DcChar::from_u128(escaped_gid));
6103            continue;
6104        }
6105        if let DcShorthand::Long(node_id) = sh {
6106            if let Some(block_desc) = ctb_storage_minimal::global_graph_layout::unsupported_graph_block_description(node_id) {
6107                bail!(
6108                    "Graph WASM helper or value reference l{node_id} targets unsupported graph block ({block_desc})"
6109                );
6110            }
6111            let Some(sg) = resolver.seed_graph() else {
6112                bail!(
6113                    "Graph WASM helper or value reference l{node_id} requires a seed graph snapshot on the active SyntaxRuleResolver"
6114                );
6115            };
6116            if let Some(pin_id) = sg.system_block_most_recent_node_id()
6117                && node_id > pin_id
6118            {
6119                bail!(
6120                    "Graph WASM helper or value reference l{node_id} exceeds pinned System graph snapshot l{pin_id}"
6121                );
6122            }
6123            let Some(node) = sg.get_active_node(node_id) else {
6124                if sg.retracted_by(node_id).is_some() {
6125                    bail!(
6126                        "Graph WASM helper or value node l{node_id} was retracted in the active System graph snapshot"
6127                    );
6128                }
6129                bail!(
6130                    "Graph WASM helper or value node l{node_id} is not present or active in the System graph snapshot"
6131                );
6132            };
6133            if let Some(pin_id) = sg.system_block_most_recent_node_id()
6134                && node.id > pin_id
6135            {
6136                bail!(
6137                    "Graph WASM helper or value reference l{} exceeds pinned System graph snapshot l{pin_id}",
6138                    node.id
6139                );
6140            }
6141            if sg.get_entity_class(node_id).is_some() {
6142                if let Some((opt_node_id, helper_tokens)) =
6143                    sg.resolve_wasm_helper_shorthand(sh)?
6144                {
6145                    ensure!(
6146                        visited_shorthands.insert(sh),
6147                        "Cycle detected while expanding graph WASM helper shorthand {sh}"
6148                    );
6149                    if let Some(nid) = opt_node_id {
6150                        ensure!(
6151                            visited_nodes.insert(nid),
6152                            "Cycle detected while expanding graph WASM helper node l{nid}"
6153                        );
6154                    }
6155                    let child_tokens = strip_nested_wasm_program_delimiters(
6156                        helper_tokens,
6157                        wasm_prog_depth,
6158                        resolver,
6159                    );
6160                    frames.push(WasmExpansionFrame {
6161                        iter: child_tokens.iter(),
6162                        node_id: opt_node_id,
6163                        shorthand: Some(sh),
6164                    });
6165                    continue;
6166                }
6167                bail!(
6168                    "Graph entity l{node_id} has no active WASM decomposition in the System graph snapshot"
6169                );
6170            }
6171            ensure!(
6172                visited_nodes.insert(node.id),
6173                "Cycle detected while expanding graph WASM helper node l{}",
6174                node.id
6175            );
6176            let child_tokens = strip_nested_wasm_program_delimiters(
6177                &node.tokens,
6178                wasm_prog_depth,
6179                resolver,
6180            );
6181            frames.push(WasmExpansionFrame {
6182                iter: child_tokens.iter(),
6183                node_id: Some(node.id),
6184                shorthand: None,
6185            });
6186            continue;
6187        }
6188        if matches!(sh, DcShorthand::Short(_) | DcShorthand::Format(_))
6189            && !matches!(
6190                sh,
6191                DcShorthand::Short(
6192                    256
6193                        | 260
6194                        | 268
6195                        | 276
6196                        | 279
6197                        | 307
6198                        | 540
6199                        | 541
6200                        | 584
6201                        | 585
6202                        | 610
6203                        | 616
6204                        | 638
6205                        | 647..=1937
6206                )
6207            )
6208        {
6209            if let Some(sg) = resolver.seed_graph() {
6210                if let Some((opt_node_id, helper_tokens)) =
6211                    sg.resolve_wasm_helper_shorthand(sh)?
6212                {
6213                    ensure!(
6214                        visited_shorthands.insert(sh),
6215                        "Cycle detected while expanding graph WASM helper shorthand {sh}"
6216                    );
6217                    if let Some(nid) = opt_node_id {
6218                        ensure!(
6219                            visited_nodes.insert(nid),
6220                            "Cycle detected while expanding graph WASM helper node l{nid}"
6221                        );
6222                    }
6223                    let child_tokens = strip_nested_wasm_program_delimiters(
6224                        helper_tokens,
6225                        wasm_prog_depth,
6226                        resolver,
6227                    );
6228                    frames.push(WasmExpansionFrame {
6229                        iter: child_tokens.iter(),
6230                        node_id: opt_node_id,
6231                        shorthand: Some(sh),
6232                    });
6233                    continue;
6234                }
6235            } else if let Some(def_tokens) =
6236                resolver.resolve_wasm_definition_tokens(gid)
6237            {
6238                ensure!(
6239                    visited_shorthands.insert(sh),
6240                    "Cycle detected while expanding graph WASM helper shorthand {sh}"
6241                );
6242                let child_tokens = strip_nested_wasm_program_delimiters(
6243                    def_tokens,
6244                    wasm_prog_depth,
6245                    resolver,
6246                );
6247                frames.push(WasmExpansionFrame {
6248                    iter: child_tokens.iter(),
6249                    node_id: None,
6250                    shorthand: Some(sh),
6251                });
6252                continue;
6253            }
6254        }
6255        if resolver.token_fills_role(gid, DcRole::BeginWasmProgram)
6256            || resolver.token_fills_role(gid, DcRole::BeginLiteral)
6257        {
6258            wasm_prog_depth = wasm_prog_depth.saturating_add(1);
6259        } else if resolver.token_fills_role(gid, DcRole::EndWasmProgram)
6260            || resolver.token_fills_role(gid, DcRole::EndLiteral)
6261        {
6262            wasm_prog_depth = wasm_prog_depth.saturating_sub(1);
6263        }
6264        expanded_dc_str.push(DcChar::from_u128(gid));
6265    }
6266    let parsed_mstr = DcMstring::from_dc_str_with_policy_and_resolver(
6267        &expanded_dc_str,
6268        &DcProjectionPolicy::strict(),
6269        resolver,
6270    )?;
6271    if out_doc.is_empty() {
6272        *out_doc = parsed_mstr;
6273    } else {
6274        let mut combined = out_doc.to_dc_string_with_policy_and_resolver(
6275            &DcProjectionPolicy::strict(),
6276            resolver,
6277        )?;
6278        combined.push_dc_str(&expanded_dc_str);
6279        *out_doc = DcMstring::from_dc_str_with_policy_and_resolver(
6280            &combined,
6281            &DcProjectionPolicy::strict(),
6282            resolver,
6283        )?;
6284    }
6285    Ok(())
6286}
6287
6288/// Expands a slice of [`ctb_storage_minimal::shorthand::DcShorthand`] graph WASM tokens
6289/// (resolving nested helper shorthands and standalone `Routine` entities) into an executable
6290/// [`DcMstring`] Dc-WASM document.
6291///
6292/// # Errors
6293/// Returns an error if any helper shorthand or graph reference fails to resolve or forms a cycle.
6294pub fn expand_graph_wasm_shorthands_to_dcmstring(
6295    wasm_shorthands: &[ctb_storage_minimal::shorthand::DcShorthand],
6296    resolver: &dyn SyntaxRuleResolver,
6297) -> Result<DcMstring> {
6298    let mut wasm_doc = DcMstring::new();
6299    expand_graph_wasm_shorthands(wasm_shorthands, resolver, &mut wasm_doc)?;
6300    Ok(wasm_doc)
6301}
6302
6303/// Runs a pure-compute Dc-WASM conversion from a slice of [`ctb_storage_minimal::shorthand::DcShorthand`]
6304/// tokens (such as a `.WASM` definition stored in the system graph) over `input_tokens`.
6305///
6306/// # Errors
6307/// Returns an error if the shorthand tokens cannot be converted or if the WASM conversion fails.
6308pub fn run_graph_wasm_tokens_on_dc_slice(
6309    wasm_shorthands: &[ctb_storage_minimal::shorthand::DcShorthand],
6310    input_tokens: &[DcChar],
6311    resolver: &dyn SyntaxRuleResolver,
6312) -> Result<DcMstring> {
6313    run_graph_wasm_tokens_on_dc_slice_with_quota(
6314        wasm_shorthands,
6315        input_tokens,
6316        resolver,
6317        None,
6318    )
6319}
6320
6321fn lookup_cached_graph_target_substitute(
6322    sg: &ctb_formats_dcdata::seed_graph::SeedGraphIndex,
6323    target: &ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTarget,
6324) -> Result<Option<WasmSubstituteDescriptor>> {
6325    use ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTargetKind;
6326
6327    static TARGET_SUB_CACHE: std::sync::OnceLock<
6328        std::sync::Mutex<
6329            std::collections::HashMap<
6330                (u64, Option<u128>, u128, u8),
6331                WasmSubstituteDescriptor,
6332            >,
6333        >,
6334    > = std::sync::OnceLock::new();
6335
6336    #[cfg(test)]
6337    ctb_wasm_substitutes::ensure_registered();
6338
6339    let kind_tag = match target.kind {
6340        SystemWasmSubstituteTargetKind::SupervisorKernel => 1u8,
6341        SystemWasmSubstituteTargetKind::StandaloneWasm => 2u8,
6342        SystemWasmSubstituteTargetKind::StandaloneWasmValueNode { .. } => 3u8,
6343        SystemWasmSubstituteTargetKind::WasmConverter { .. } => 4u8,
6344        SystemWasmSubstituteTargetKind::StageLConverter { .. }
6345        | SystemWasmSubstituteTargetKind::StageLRoutineBytes => 5u8,
6346        SystemWasmSubstituteTargetKind::StageLRoutineDcs
6347        | SystemWasmSubstituteTargetKind::StageRRoutineDcs => 6u8,
6348        SystemWasmSubstituteTargetKind::StageRConverter { .. }
6349        | SystemWasmSubstituteTargetKind::StageRRoutineBytes => 7u8,
6350    };
6351    let key = (
6352        sg.instance_id(),
6353        sg.system_block_most_recent_node_id(),
6354        target.global_id,
6355        kind_tag,
6356    );
6357    let cache = TARGET_SUB_CACHE
6358        .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
6359    if let Ok(guard) = cache.lock()
6360        && let Some(&desc) = guard.get(&key)
6361    {
6362        return Ok(Some(desc));
6363    }
6364    let rev_sha256 = sg.compute_substitute_target_revision_sha256(target)?;
6365    let found = lookup_substitute_by_graph_revision(
6366        WASM_RESOURCE_ACCOUNTING_VERSION,
6367        target.global_id,
6368        &rev_sha256,
6369    );
6370    if let Some(desc) = found
6371        && let Ok(mut guard) = cache.lock()
6372    {
6373        if guard.len() >= 1024 {
6374            guard.clear();
6375        }
6376        guard.insert(key, desc);
6377    }
6378    Ok(found)
6379}
6380
6381/// Runs a pure-compute Dc-WASM conversion from a slice of [`ctb_storage_minimal::shorthand::DcShorthand`]
6382/// tokens over `input_tokens` using an optional [`SharedWasmTaskQuota`].
6383///
6384/// # Errors
6385/// Returns an error if the shorthand tokens cannot be converted or if the WASM conversion fails.
6386pub fn run_graph_wasm_tokens_on_dc_slice_with_quota(
6387    wasm_shorthands: &[ctb_storage_minimal::shorthand::DcShorthand],
6388    input_tokens: &[DcChar],
6389    resolver: &dyn SyntaxRuleResolver,
6390    shared_quota: Option<SharedWasmTaskQuota>,
6391) -> Result<DcMstring> {
6392    static GRAPH_WASM_SHORTHANDS_BYTECODE_CACHE: std::sync::OnceLock<
6393        std::sync::Mutex<
6394            std::collections::HashMap<
6395                (u64, Option<u128>, [u8; 32]),
6396                std::sync::Arc<Vec<u8>>,
6397            >,
6398        >,
6399    > = std::sync::OnceLock::new();
6400
6401    let mut input_doc = DcMstring::new();
6402    for &tok in input_tokens {
6403        input_doc.push_char(tok);
6404    }
6405
6406    if let Some(sg) = resolver.seed_graph() {
6407        let most_recent = sg.system_block_most_recent_node_id();
6408        let mut hasher = Sha256::new();
6409        hasher.update(b"ctb-graph-wasm-sh-v1");
6410        let mut all_valid = true;
6411        for sh in wasm_shorthands {
6412            if let Ok(gid) = sh.to_global_id() {
6413                hasher.update(gid.to_le_bytes());
6414            } else {
6415                all_valid = false;
6416                break;
6417            }
6418        }
6419        if all_valid {
6420            let sh_digest: [u8; 32] = hasher.finalize().into();
6421            let key = (sg.instance_id(), most_recent, sh_digest);
6422            let cache = GRAPH_WASM_SHORTHANDS_BYTECODE_CACHE.get_or_init(|| {
6423                std::sync::Mutex::new(std::collections::HashMap::new())
6424            });
6425            let cached_bytes =
6426                cache.lock().ok().and_then(|g| g.get(&key).cloned());
6427            if let Some(wasm_bytes) = cached_bytes {
6428                return run_wasm_bytes_pure_conversion_with_quota(
6429                    &wasm_bytes,
6430                    &input_doc,
6431                    most_recent,
6432                    shared_quota,
6433                );
6434            }
6435            let mut wasm_doc = DcMstring::new();
6436            expand_graph_wasm_shorthands(
6437                wasm_shorthands,
6438                resolver,
6439                &mut wasm_doc,
6440            )?;
6441            let assembled =
6442                std::sync::Arc::new(dcmstring_to_wasm_with_resolver(
6443                    &wasm_doc, resolver,
6444                )?);
6445            if let Ok(mut guard) = cache.lock() {
6446                if guard.len() >= 512 {
6447                    guard.clear();
6448                }
6449                guard.insert(key, std::sync::Arc::clone(&assembled));
6450            }
6451            return run_wasm_bytes_pure_conversion_with_quota(
6452                &assembled,
6453                &input_doc,
6454                most_recent,
6455                shared_quota,
6456            );
6457        }
6458    }
6459
6460    let mut wasm_doc = DcMstring::new();
6461    expand_graph_wasm_shorthands(
6462        wasm_shorthands,
6463        resolver,
6464        &mut wasm_doc,
6465    )?;
6466
6467    run_dc_wasm_pure_conversion_with_resolver_and_quota(
6468        &wasm_doc,
6469        &input_doc,
6470        resolver,
6471        shared_quota,
6472    )
6473}
6474
6475/// Executes a single [`ctb_formats_dcdata::seed_graph::ActiveConverterStep`] from `sg`
6476/// (either a Stage 0 `.WASM` converter or a Stage 1 StageL Token-Dc converter compiled
6477/// via the active StageL-to-WASM converter) on `input_tokens` under `shared_quota`.
6478///
6479/// When `shared_quota` is `None` (direct host document transformation outside a supervisor
6480/// session), a bounded converter-step [`SharedWasmTaskQuota`] is allocated so self-hosted
6481/// Stage 0 / Stage 1 compiler transforms have sufficient compute, memory, and output budget.
6482///
6483/// # Errors
6484/// Returns an error if dependency bundling, StageL-to-WASM compilation, or WASM execution fails.
6485pub fn run_active_converter_step_on_dc_slice_with_quota(
6486    step: &ctb_formats_dcdata::seed_graph::ActiveConverterStep,
6487    input_tokens: &[DcChar],
6488    sg: &ctb_formats_dcdata::seed_graph::SeedGraphIndex,
6489    resolver: &dyn SyntaxRuleResolver,
6490    shared_quota: Option<SharedWasmTaskQuota>,
6491) -> Result<DcMstring> {
6492    use ctb_formats_dcdata::seed_graph::ActiveConverterBody;
6493    use ctb_storage_minimal::shorthand::DcShorthand;
6494
6495    const DEFAULT_CONVERTER_MAX_INSTRUCTIONS: u64 = 4_000_000_000;
6496    const DEFAULT_CONVERTER_MAX_MEMORY_PAGES: usize = 8192;
6497    const DEFAULT_CONVERTER_MAX_STEP_OUTPUT_BYTES: usize = 32 * 1024 * 1024;
6498    const DEFAULT_CONVERTER_MAX_SESSION_OUTPUT_BYTES: usize = 64 * 1024 * 1024;
6499
6500    // Reason for fallback: Direct host document transformations without an enclosing
6501    // supervisor SharedWasmTaskQuota use a bounded compiler-step quota sufficient to
6502    // compile and run self-hosted Stage 0 / Stage 1 transformations (`f1680`, `f1681`).
6503    let shared_quota = Some(shared_quota.unwrap_or_else(|| {
6504        SharedWasmTaskQuota::new(
6505            DcWasmResourceLimits::default()
6506                .with_max_instructions_per_step(
6507                    DEFAULT_CONVERTER_MAX_INSTRUCTIONS,
6508                )
6509                .with_max_memory_pages(DEFAULT_CONVERTER_MAX_MEMORY_PAGES)
6510                .with_max_step_output_bytes(
6511                    DEFAULT_CONVERTER_MAX_STEP_OUTPUT_BYTES,
6512                )
6513                .with_max_session_output_bytes(
6514                    DEFAULT_CONVERTER_MAX_SESSION_OUTPUT_BYTES,
6515                ),
6516        )
6517    }));
6518
6519    let wasm_dst_sh = DcShorthand::from_global_id(
6520        ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
6521    );
6522    let stagel_src_sh = DcShorthand::from_global_id(
6523        ctb_formats_dcdata::dc::DC_BEGIN_MODULE.to_u128(),
6524    );
6525    let stager_src_sh = DcShorthand::from_global_id(
6526        ctb_formats_dcdata::dc::DC_BEGIN_STAGER_MODULE.to_u128(),
6527    );
6528
6529    let first_structural_tok = {
6530        let mut idx = 0usize;
6531        let mut found = None;
6532        while let Some(&tok) = input_tokens.get(idx) {
6533            let is_single = tok
6534                .fills_role_with(DcRole::BeginSingleLineComment, resolver)
6535                || tok.fills_role_with(
6536                    DcRole::BeginSingleLineCommentNewLine,
6537                    resolver,
6538                );
6539            let is_block = tok
6540                .fills_role_with(DcRole::BeginBlockComment, resolver)
6541                || tok.fills_role_with(
6542                    DcRole::BeginBlockCommentNewLine,
6543                    resolver,
6544                );
6545            if !is_single && !is_block {
6546                found = Some(tok);
6547                break;
6548            }
6549            let close_role = if is_single {
6550                DcRole::EndSingleLineComment
6551            } else {
6552                DcRole::EndBlockComment
6553            };
6554            idx = idx.saturating_add(1);
6555            while let Some(&inner) = input_tokens.get(idx) {
6556                idx = idx.saturating_add(1);
6557                if inner.fills_role_with(DcRole::Escape, resolver) {
6558                    idx = idx.saturating_add(1);
6559                    continue;
6560                }
6561                if inner.fills_role_with(close_role, resolver) {
6562                    break;
6563                }
6564            }
6565        }
6566        found
6567    };
6568
6569    let bundled_storage: Option<Vec<DcChar>> = if step.dst == wasm_dst_sh
6570        && first_structural_tok
6571            .is_some_and(|c| c.fills_role_with(DcRole::BeginModule, resolver))
6572    {
6573        Some(
6574            ctb_formats_dcdata::stagel3::seed_linker::bundle_dc_module_for_wasm_converter(
6575                input_tokens, sg, resolver,
6576            )?,
6577        )
6578    } else if step.src == stager_src_sh
6579        && first_structural_tok.is_some_and(|c| {
6580            c.fills_role_with(DcRole::BeginStagerModule, resolver)
6581                || c.fills_role_with(DcRole::BeginModule, resolver)
6582        })
6583    {
6584        Some(
6585            ctb_formats_dcdata::stagel3::seed_linker::bundle_dc_module_dependencies(
6586                input_tokens, sg,
6587            )?,
6588        )
6589    } else {
6590        None
6591    };
6592    let converter_input: &[DcChar] = if let Some(ref bundled) = bundled_storage
6593    {
6594        bundled.as_slice()
6595    } else {
6596        input_tokens
6597    };
6598
6599    match &step.body {
6600        ActiveConverterBody::Wasm(wasm_tokens) => {
6601            if let Ok(subject_gid) = step.subject.to_global_id() {
6602                let target =
6603                    ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTarget {
6604                        subject: step.subject,
6605                        global_id: subject_gid,
6606                        defining_node_id: 0,
6607                        chunk_prefix: String::new(),
6608                        kind: ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTargetKind::WasmConverter {
6609                            src: step.src,
6610                            dst: step.dst,
6611                        },
6612                    };
6613                if let Ok(Some(desc)) =
6614                    lookup_cached_graph_target_substitute(sg, &target)
6615                {
6616                    let mut input_doc = DcMstring::new();
6617                    for &tok in converter_input {
6618                        input_doc.push_char(tok);
6619                    }
6620                    return run_substitute_descriptor_pure_conversion_with_quota(
6621                        desc,
6622                        &input_doc,
6623                        sg.system_block_most_recent_node_id(),
6624                        shared_quota,
6625                    )
6626                    .with_context(|| {
6627                        format!(
6628                            "WASM converter step {} ({} -> {}) failed",
6629                            step.subject, step.src, step.dst
6630                        )
6631                    });
6632                }
6633            }
6634            run_graph_wasm_tokens_on_dc_slice_with_quota(
6635                wasm_tokens,
6636                converter_input,
6637                resolver,
6638                shared_quota,
6639            )
6640            .with_context(|| {
6641                format!(
6642                    "WASM converter step {} ({} -> {}) failed",
6643                    step.subject, step.src, step.dst
6644                )
6645            })
6646        }
6647        ActiveConverterBody::StageL(_) => {
6648            #[derive(Clone)]
6649            struct CachedStageLConverterWasm {
6650                wasm_bytes: std::sync::Arc<Vec<u8>>,
6651                compile_instructions: u64,
6652                compile_output_bytes: usize,
6653            }
6654
6655            static STAGEL_CONVERTER_CACHE: std::sync::OnceLock<
6656                std::sync::Mutex<
6657                    std::collections::HashMap<
6658                        [u8; 32],
6659                        CachedStageLConverterWasm,
6660                    >,
6661                >,
6662            > = std::sync::OnceLock::new();
6663            static STAGEL_CONVERTER_COMPILE_LOCK: std::sync::OnceLock<
6664                std::sync::Mutex<()>,
6665            > = std::sync::OnceLock::new();
6666
6667            let converter_dc = DcChar::from_u128(step.subject.to_global_id()?);
6668            let entry_module_tokens =
6669                ctb_formats_dcdata::stagel3::seed_linker::build_entry_module_for_graph_routine_dc(
6670                    converter_dc,
6671                    sg,
6672                )?;
6673            let bundled_converter_entry =
6674                ctb_formats_dcdata::stagel3::seed_linker::bundle_dc_module_for_wasm_converter(
6675                    &entry_module_tokens,
6676                    sg,
6677                    resolver,
6678                )?;
6679            let Some((_, stagel_to_wasm_tokens)) =
6680                sg.resolve_active_converter_routine(stagel_src_sh, wasm_dst_sh)?
6681            else {
6682                bail!(
6683                    "Cannot execute StageL converter {}: no active StageL-to-WASM converter ([Dc 302 {stagel_src_sh} {wasm_dst_sh}]) in System graph snapshot",
6684                    step.subject
6685                );
6686            };
6687            let most_recent = sg.system_block_most_recent_node_id();
6688            let cache_key = hash_stagel_converter_cache_key(
6689                stagel_to_wasm_tokens,
6690                &bundled_converter_entry,
6691            )?;
6692            let cache_map = STAGEL_CONVERTER_CACHE
6693                .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
6694            let try_use_cached =
6695                |entry: CachedStageLConverterWasm| -> Result<Option<std::sync::Arc<Vec<u8>>>> {
6696                    let Some(ref quota) = shared_quota else {
6697                        return Ok(Some(entry.wasm_bytes));
6698                    };
6699                    let charged = quota.with_lock(|st| {
6700                        let next_out = st
6701                            .cumulative_output_bytes
6702                            .saturating_add(entry.compile_output_bytes);
6703                        if st.remaining_compute_quota >= entry.compile_instructions
6704                            && entry.compile_output_bytes
6705                                <= st.active_limits.max_step_output_bytes
6706                            && next_out <= st.max_session_output_bytes
6707                            && st.active_limits.max_memory_pages >= 256
6708                            && st.active_limits.physical_max_memory_pages >= 256
6709                        {
6710                            st.remaining_compute_quota = st
6711                                .remaining_compute_quota
6712                                .saturating_sub(entry.compile_instructions);
6713                            st.total_instructions_executed = st
6714                                .total_instructions_executed
6715                                .saturating_add(entry.compile_instructions);
6716                            st.cumulative_output_bytes = next_out;
6717                            true
6718                        } else {
6719                            false
6720                        }
6721                    })?;
6722                    Ok(charged.then_some(entry.wasm_bytes))
6723                };
6724
6725            let maybe_cached_entry = cache_map
6726                .lock()
6727                .map_err(|_| anyhow!("STAGEL_CONVERTER_CACHE mutex poisoned"))?
6728                .get(&cache_key)
6729                .cloned();
6730            let mut converter_wasm_bytes = match maybe_cached_entry {
6731                Some(cached) => try_use_cached(cached)?,
6732                None => None,
6733            };
6734
6735            let wasm_bytes = if let Some(bytes) = converter_wasm_bytes {
6736                bytes
6737            } else {
6738                let _compile_guard = STAGEL_CONVERTER_COMPILE_LOCK
6739                    .get_or_init(|| std::sync::Mutex::new(()))
6740                    .lock()
6741                    .map_err(|_| {
6742                        anyhow!("STAGEL_CONVERTER_COMPILE_LOCK mutex poisoned")
6743                    })?;
6744                let recheck_entry = cache_map
6745                    .lock()
6746                    .map_err(|_| {
6747                        anyhow!("STAGEL_CONVERTER_CACHE mutex poisoned")
6748                    })?
6749                    .get(&cache_key)
6750                    .cloned();
6751                converter_wasm_bytes = match recheck_entry {
6752                    Some(cached) => try_use_cached(cached)?,
6753                    None => None,
6754                };
6755                if let Some(bytes) = converter_wasm_bytes {
6756                    bytes
6757                } else {
6758                    let before_snap = match shared_quota {
6759                        Some(ref q) => Some(q.snapshot()?),
6760                        None => None,
6761                    };
6762                    let raw_converter_wasm =
6763                        run_graph_wasm_tokens_on_dc_slice_with_quota(
6764                            stagel_to_wasm_tokens,
6765                            &bundled_converter_entry,
6766                            resolver,
6767                            shared_quota.clone(),
6768                        )
6769                        .with_context(|| {
6770                            format!(
6771                                "StageL-to-WASM compilation of converter {} ({} -> {}) failed",
6772                                step.subject, step.src, step.dst
6773                            )
6774                        })?;
6775                    let after_snap = match shared_quota {
6776                        Some(ref q) => Some(q.snapshot()?),
6777                        None => None,
6778                    };
6779                    let raw_wasm_chars: Vec<DcChar> =
6780                        raw_converter_wasm.to_dc_string()?.chars().collect();
6781                    let raw_wasm_shorthands: Vec<DcShorthand> = raw_wasm_chars
6782                        .iter()
6783                        .map(|c| DcShorthand::from_global_id(c.to_u128()))
6784                        .collect();
6785                    let compiled_converter_wasm =
6786                        expand_graph_wasm_shorthands_to_dcmstring(
6787                            &raw_wasm_shorthands,
6788                            resolver,
6789                        )?;
6790                    let assembled_bytes = std::sync::Arc::new(
6791                        dcmstring_to_wasm_with_resolver(
6792                            &compiled_converter_wasm,
6793                            resolver,
6794                        )?,
6795                    );
6796                    if let (Some(b), Some(a)) = (before_snap, after_snap) {
6797                        let compile_instructions = a
6798                            .total_instructions_executed
6799                            .saturating_sub(b.total_instructions_executed);
6800                        let compile_output_bytes = a
6801                            .cumulative_output_bytes
6802                            .saturating_sub(b.cumulative_output_bytes);
6803                        cache_map
6804                            .lock()
6805                            .map_err(|_| {
6806                                anyhow!(
6807                                    "STAGEL_CONVERTER_CACHE mutex poisoned"
6808                                )
6809                            })?
6810                            .insert(
6811                                cache_key,
6812                                CachedStageLConverterWasm {
6813                                    wasm_bytes: assembled_bytes.clone(),
6814                                    compile_instructions,
6815                                    compile_output_bytes,
6816                                },
6817                            );
6818                    }
6819                    assembled_bytes
6820                }
6821            };
6822
6823            let mut input_doc = DcMstring::new();
6824            for &tok in converter_input {
6825                input_doc.push_char(tok);
6826            }
6827            run_wasm_bytes_pure_conversion_with_quota(
6828                &wasm_bytes,
6829                &input_doc,
6830                most_recent,
6831                shared_quota,
6832            )
6833            .with_context(|| {
6834                format!(
6835                    "Executing compiled StageL converter {} ({} -> {}) failed",
6836                    step.subject, step.src, step.dst
6837                )
6838            })
6839        }
6840    }
6841}
6842
6843/// Executes an ordered multi-step chain of [`ctb_formats_dcdata::seed_graph::ActiveConverterStep`]s
6844/// sequentially on `input_tokens` under a shared [`SharedWasmTaskQuota`].
6845///
6846/// # Errors
6847/// Returns an error if `chain` is empty or if any step fails.
6848pub fn run_graph_converter_chain_on_dc_slice_with_quota(
6849    chain: &[ctb_formats_dcdata::seed_graph::ActiveConverterStep],
6850    input_tokens: &[DcChar],
6851    sg: &ctb_formats_dcdata::seed_graph::SeedGraphIndex,
6852    resolver: &dyn SyntaxRuleResolver,
6853    shared_quota: Option<SharedWasmTaskQuota>,
6854) -> Result<DcMstring> {
6855    ensure!(!chain.is_empty(), "Converter chain must not be empty");
6856    let mut current_tokens: Vec<DcChar> = input_tokens.to_vec();
6857    let mut last_doc = DcMstring::new();
6858    for (idx, step) in chain.iter().enumerate() {
6859        last_doc = run_active_converter_step_on_dc_slice_with_quota(
6860            step,
6861            &current_tokens,
6862            sg,
6863            resolver,
6864            shared_quota.clone(),
6865        )?;
6866        if idx.saturating_add(1) < chain.len() {
6867            current_tokens = last_doc.to_dc_string()?.chars().collect();
6868        }
6869    }
6870    Ok(last_doc)
6871}
6872
6873fn hash_dc_shorthand_slice(
6874    hasher: &mut sha2::Sha256,
6875    tokens: &[ctb_storage_minimal::shorthand::DcShorthand],
6876) -> Result<()> {
6877    use sha2::Digest;
6878
6879    hasher.update(
6880        u64::try_from(tokens.len())
6881            .map_err(|_| anyhow!("Token length overflows u64"))?
6882            .to_le_bytes(),
6883    );
6884    for &sh in tokens {
6885        hasher.update(sh.to_global_id()?.to_le_bytes());
6886    }
6887    Ok(())
6888}
6889
6890fn hash_dc_char_slice(
6891    hasher: &mut sha2::Sha256,
6892    tokens: &[DcChar],
6893) -> Result<()> {
6894    use sha2::Digest;
6895
6896    hasher.update(
6897        u64::try_from(tokens.len())
6898            .map_err(|_| anyhow!("DcChar length overflows u64"))?
6899            .to_le_bytes(),
6900    );
6901    for &ch in tokens {
6902        hasher.update(ch.to_u128().to_le_bytes());
6903    }
6904    Ok(())
6905}
6906
6907fn hash_stagel_converter_cache_key(
6908    stagel_to_wasm_tokens: &[ctb_storage_minimal::shorthand::DcShorthand],
6909    bundled_converter_entry: &[DcChar],
6910) -> Result<[u8; 32]> {
6911    use sha2::{Digest, Sha256};
6912
6913    let mut hasher = Sha256::new();
6914    hasher.update(b"stagel-converter-v1");
6915    hash_dc_shorthand_slice(&mut hasher, stagel_to_wasm_tokens)?;
6916    hash_dc_char_slice(&mut hasher, bundled_converter_entry)?;
6917    Ok(hasher.finalize().into())
6918}
6919
6920fn hash_stager_routine_cache_key(
6921    bundled_stager_entry: &[DcChar],
6922    chain: &[ctb_formats_dcdata::seed_graph::ActiveConverterStep],
6923) -> Result<[u8; 32]> {
6924    use ctb_formats_dcdata::seed_graph::ActiveConverterBody;
6925    use sha2::{Digest, Sha256};
6926
6927    let mut hasher = Sha256::new();
6928    hasher.update(b"stager-dcs-routine-v1");
6929    hash_dc_char_slice(&mut hasher, bundled_stager_entry)?;
6930    hasher.update(
6931        u64::try_from(chain.len())
6932            .map_err(|_| anyhow!("Converter chain length overflows u64"))?
6933            .to_le_bytes(),
6934    );
6935    for step in chain {
6936        hasher.update(step.subject.to_global_id()?.to_le_bytes());
6937        hasher.update(step.src.to_global_id()?.to_le_bytes());
6938        hasher.update(step.dst.to_global_id()?.to_le_bytes());
6939        match &step.body {
6940            ActiveConverterBody::Wasm(toks) => {
6941                hasher.update([0u8]);
6942                hash_dc_shorthand_slice(&mut hasher, toks)?;
6943            }
6944            ActiveConverterBody::StageL(toks) => {
6945                hasher.update([1u8]);
6946                hash_dc_char_slice(&mut hasher, toks)?;
6947            }
6948        }
6949    }
6950    Ok(hasher.finalize().into())
6951}
6952
6953fn compile_and_cache_graph_stager_dcs_routine_to_wasm_bytes(
6954    routine_dc: DcChar,
6955    sg: &ctb_formats_dcdata::seed_graph::SeedGraphIndex,
6956    resolver: &dyn SyntaxRuleResolver,
6957) -> Result<Option<std::sync::Arc<Vec<u8>>>> {
6958    use ctb_storage_minimal::shorthand::DcShorthand;
6959
6960    static GRAPH_STAGER_ROUTINE_WASM_CACHE: std::sync::OnceLock<
6961        std::sync::Mutex<std::collections::HashMap<[u8; 32], std::sync::Arc<Vec<u8>>>>,
6962    > = std::sync::OnceLock::new();
6963    static GRAPH_STAGER_ROUTINE_COMPILE_SHARDS: std::sync::OnceLock<
6964        [std::sync::Mutex<()>; 64],
6965    > = std::sync::OnceLock::new();
6966
6967    let routine_sh = DcShorthand::from_global_id(routine_dc.to_u128());
6968    if sg.resolve_stagel_decomposition_tokens(routine_sh)?.is_none() {
6969        return Ok(None);
6970    }
6971
6972    let entry_tokens =
6973        ctb_formats_dcdata::stagel3::seed_linker::build_stager_dcs_entry_module_for_graph_routine_dc(
6974            routine_dc,
6975            sg,
6976        )?;
6977    let bundled_stager_entry =
6978        ctb_formats_dcdata::stagel3::seed_linker::bundle_dc_module_dependencies(
6979            &entry_tokens,
6980            sg,
6981        )?;
6982
6983    let stager_src_sh = DcShorthand::from_global_id(
6984        ctb_formats_dcdata::dc::DC_BEGIN_STAGER_MODULE.to_u128(),
6985    );
6986    let wasm_dst_sh = DcShorthand::from_global_id(
6987        ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
6988    );
6989    let Some(chain) =
6990        sg.resolve_active_converter_chain(stager_src_sh, wasm_dst_sh)?
6991    else {
6992        bail!(
6993            "Cannot compile StageR 3 graph routine {routine_sh}: no active converter chain ([Dc 302 {stager_src_sh} ... {wasm_dst_sh}]) in System graph snapshot"
6994        );
6995    };
6996
6997    let cache_key = hash_stager_routine_cache_key(&bundled_stager_entry, &chain)?;
6998    let cache = GRAPH_STAGER_ROUTINE_WASM_CACHE
6999        .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
7000    if let Some(hit) = cache
7001        .lock()
7002        .map_err(|_| anyhow!("GRAPH_STAGER_ROUTINE_WASM_CACHE mutex poisoned"))?
7003        .get(&cache_key)
7004        .cloned()
7005    {
7006        return Ok(Some(hit));
7007    }
7008
7009    let shards = GRAPH_STAGER_ROUTINE_COMPILE_SHARDS
7010        .get_or_init(|| std::array::from_fn(|_| std::sync::Mutex::new(())));
7011    let shard_idx = usize::from(cache_key[0]) & 63;
7012    let shard_mutex = shards
7013        .get(shard_idx)
7014        .context("StageR compile shard index out of bounds")?;
7015    let _compile_guard = shard_mutex.lock().map_err(|_| {
7016        anyhow!("GRAPH_STAGER_ROUTINE_COMPILE_SHARDS mutex poisoned")
7017    })?;
7018    if let Some(hit) = cache
7019        .lock()
7020        .map_err(|_| anyhow!("GRAPH_STAGER_ROUTINE_WASM_CACHE mutex poisoned"))?
7021        .get(&cache_key)
7022        .cloned()
7023    {
7024        return Ok(Some(hit));
7025    }
7026
7027    // Bootstrap lowering of the System-graph Dc 2608 implementation uses the
7028    // dedicated compiler-step quota rather than charging user documents.
7029    let compiled_wasm_doc = run_graph_converter_chain_on_dc_slice_with_quota(
7030        &chain,
7031        &entry_tokens,
7032        sg,
7033        resolver,
7034        None,
7035    )
7036    .with_context(|| {
7037        format!(
7038            "System bootstrap compilation of StageR 3 graph routine {routine_sh} failed"
7039        )
7040    })?;
7041
7042    assemble_compiled_wasm_doc(&compiled_wasm_doc, resolver).map(|bytes| {
7043        let assembled = std::sync::Arc::new(bytes);
7044        if let Ok(mut guard) = cache.lock() {
7045            guard.insert(cache_key, std::sync::Arc::clone(&assembled));
7046        }
7047        Some(assembled)
7048    })
7049}
7050
7051fn assemble_compiled_wasm_doc(
7052    compiled_wasm_doc: &DcMstr,
7053    resolver: &dyn SyntaxRuleResolver,
7054) -> Result<Vec<u8>> {
7055    use ctb_storage_minimal::shorthand::DcShorthand;
7056
7057    let raw_chars: Vec<DcChar> =
7058        compiled_wasm_doc.to_dc_string()?.chars().collect();
7059    let raw_shorthands: Vec<DcShorthand> = raw_chars
7060        .iter()
7061        .map(|c| DcShorthand::from_global_id(c.to_u128()))
7062        .collect();
7063    let expanded =
7064        expand_graph_wasm_shorthands_to_dcmstring(&raw_shorthands, resolver)?;
7065    dcmstring_to_wasm_with_resolver(&expanded, resolver)
7066}
7067
7068fn default_substitute_compiler_quota() -> SharedWasmTaskQuota {
7069    SharedWasmTaskQuota::new(
7070        DcWasmResourceLimits::default()
7071            .with_max_instructions_per_step(4_000_000_000)
7072            .with_max_memory_pages(8192)
7073            .with_max_step_output_bytes(32 * 1024 * 1024)
7074            .with_max_session_output_bytes(64 * 1024 * 1024),
7075    )
7076}
7077
7078fn decode_dc_error_record_if_present(
7079    doc: &DcMstr,
7080    resolver: &dyn SyntaxRuleResolver,
7081) -> Result<Option<String>> {
7082    let chars: Vec<DcChar> = doc.to_dc_string()?.chars().collect();
7083    let Some(first) = chars.first().copied() else {
7084        return Ok(None);
7085    };
7086    if !first.fills_role_with(DcRole::BeginErrorRecord, resolver) {
7087        return Ok(None);
7088    }
7089    let mut msg = String::new();
7090    let mut idx = 1usize;
7091    while let Some(&ch) = chars.get(idx) {
7092        idx = idx.saturating_add(1);
7093        if ch.fills_role_with(DcRole::EndErrorRecord, resolver) {
7094            return Ok(Some(msg));
7095        }
7096        let actual = if ch.fills_role_with(DcRole::Escape, resolver) {
7097            let Some(next) = chars.get(idx).copied() else {
7098                bail!(
7099                    "Malformed Dc 552..Dc 553 error record: dangling escape token"
7100                );
7101            };
7102            idx = idx.saturating_add(1);
7103            next
7104        } else {
7105            ch
7106        };
7107        if let Some(uc) =
7108            u32::try_from(actual.to_u128()).ok().and_then(char::from_u32)
7109        {
7110            msg.push(uc);
7111        } else {
7112            msg.push_str(&format!("<Dc {actual}>"));
7113        }
7114    }
7115    Ok(Some(msg))
7116}
7117
7118/// Aggregated call statistics and return tokens recorded for a Dc routine invocation
7119/// when opt-in profiling ([`set_dc_routine_profiling_enabled`]) is active.
7120#[derive(Debug, Clone, PartialEq, Eq)]
7121pub struct DcRoutineProfileEntry {
7122    /// Invoked routine Document Character.
7123    pub routine_dc: DcChar,
7124    /// Active `Dc 641` System-block snapshot pin, if any.
7125    pub most_recent_node_id: Option<u128>,
7126    /// Exact input / call parameter tokens supplied to the routine.
7127    pub call_tokens: Vec<DcChar>,
7128    /// Deterministic return tokens emitted by the routine.
7129    pub return_tokens: Vec<DcChar>,
7130    /// Number of invocations observed with these exact inputs.
7131    pub call_count: u64,
7132    /// Cumulative wall-clock execution time in nanoseconds across all observed calls.
7133    pub total_duration_ns: u128,
7134    /// Portable V2 compute units consumed by a single invocation, if known.
7135    pub executed_instructions: u64,
7136}
7137
7138static DC_ROUTINE_PROFILING_ENABLED: std::sync::atomic::AtomicBool =
7139    std::sync::atomic::AtomicBool::new(false);
7140
7141static DC_ROUTINE_PROFILE_MAP: std::sync::OnceLock<
7142    std::sync::Mutex<std::collections::HashMap<[u8; 32], DcRoutineProfileEntry>>,
7143> = std::sync::OnceLock::new();
7144
7145/// Enables or disables opt-in Dc routine invocation profiling for harvesting
7146/// frequent and expensive pure routine calls.
7147pub fn set_dc_routine_profiling_enabled(enabled: bool) {
7148    DC_ROUTINE_PROFILING_ENABLED
7149        .store(enabled, std::sync::atomic::Ordering::Relaxed);
7150}
7151
7152/// Returns `true` when opt-in Dc routine invocation profiling is enabled.
7153#[must_use]
7154pub fn is_dc_routine_profiling_enabled() -> bool {
7155    DC_ROUTINE_PROFILING_ENABLED.load(std::sync::atomic::Ordering::Relaxed)
7156}
7157
7158/// Drains and returns all recorded [`DcRoutineProfileEntry`] items sorted by
7159/// descending cumulative execution time (`total_duration_ns`).
7160#[must_use]
7161pub fn take_dc_routine_profile_snapshot() -> Vec<DcRoutineProfileEntry> {
7162    let Some(lock) = DC_ROUTINE_PROFILE_MAP.get() else {
7163        return Vec::new();
7164    };
7165    let Ok(mut guard) = lock.lock() else {
7166        return Vec::new();
7167    };
7168    let mut entries: Vec<DcRoutineProfileEntry> =
7169        guard.drain().map(|(_, v)| v).collect();
7170    entries.sort_by(|a, b| {
7171        b.total_duration_ns
7172            .cmp(&a.total_duration_ns)
7173            .then_with(|| b.call_count.cmp(&a.call_count))
7174    });
7175    entries
7176}
7177
7178/// Records a single Dc routine invocation into the opt-in profiler table.
7179pub fn record_dc_routine_invocation_profile(
7180    routine_dc: DcChar,
7181    most_recent_node_id: Option<u128>,
7182    call_tokens: &[DcChar],
7183    return_tokens: &[DcChar],
7184    duration_ns: u128,
7185    executed_instructions: u64,
7186) {
7187    if !is_dc_routine_profiling_enabled() {
7188        return;
7189    }
7190    let mut hasher = Sha256::new();
7191    hasher.update(b"ctb-dc-routine-prof-v1");
7192    hasher.update(routine_dc.to_u128().to_le_bytes());
7193    match most_recent_node_id {
7194        Some(pin) => {
7195            hasher.update([1u8]);
7196            hasher.update(pin.to_le_bytes());
7197        }
7198        None => hasher.update([0u8]),
7199    }
7200    for &tok in call_tokens {
7201        hasher.update(tok.to_u128().to_le_bytes());
7202    }
7203    let key: [u8; 32] = hasher.finalize().into();
7204    let map = DC_ROUTINE_PROFILE_MAP
7205        .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
7206    if let Ok(mut guard) = map.lock() {
7207        if let Some(existing) = guard.get_mut(&key) {
7208            existing.call_count = existing.call_count.saturating_add(1);
7209            existing.total_duration_ns =
7210                existing.total_duration_ns.saturating_add(duration_ns);
7211            if executed_instructions > 0 {
7212                existing.executed_instructions = executed_instructions;
7213            }
7214        } else if guard.len() < 4096 {
7215            guard.insert(
7216                key,
7217                DcRoutineProfileEntry {
7218                    routine_dc,
7219                    most_recent_node_id,
7220                    call_tokens: call_tokens.to_vec(),
7221                    return_tokens: return_tokens.to_vec(),
7222                    call_count: 1,
7223                    total_duration_ns: duration_ns,
7224                    executed_instructions,
7225                },
7226            );
7227        }
7228    }
7229}
7230
7231/// Executes a System-graph StageR 3 `(dcs -> dcs)` routine (`routine_dc`, such as
7232/// `Dc 2608 "Convert Dc string to WASM"` or `f19 "Semantic Dcs to text"`) via
7233/// [`DcWasmSession`] with Option B capability support (`Dc 1939` / `Dc 1940`),
7234/// charging runtime execution to `shared_quota`.
7235///
7236/// Returns `Ok(None)` when `resolver` carries no `SeedGraphIndex` snapshot or
7237/// the pinned snapshot predates `routine_dc` having an active StageR 3
7238/// decomposition, allowing callers to fall back strictly for pre-migration pins.
7239///
7240/// # Errors
7241/// Returns an error on bootstrap compilation failure, quota exhaustion
7242/// (`WasmResourceInterruption`), WASM runtime traps, or `Dc 552..Dc 553` error
7243/// records emitted by `routine_dc`.
7244pub fn run_graph_stager_dcs_routine_with_quota(
7245    routine_dc: DcChar,
7246    input_tokens: &[DcChar],
7247    resolver: &dyn SyntaxRuleResolver,
7248    shared_quota: Option<SharedWasmTaskQuota>,
7249) -> Result<Option<DcMstring>> {
7250    use ctb_storage_minimal::shorthand::DcShorthand;
7251
7252    static PURE_STAGER_DCS_ROUTINE_CACHE: std::sync::OnceLock<
7253        std::sync::Mutex<
7254            std::collections::HashMap<[u8; 32], CachedPureWasmConversion>,
7255        >,
7256    > = std::sync::OnceLock::new();
7257
7258    const DIRECT_STAGER_DCS_MAX_INSTRUCTIONS: u64 = 4_000_000_000;
7259    const DIRECT_STAGER_DCS_MAX_MEMORY_PAGES: usize = 8192;
7260    const DIRECT_STAGER_DCS_MAX_STEP_OUTPUT_BYTES: usize = 32 * 1024 * 1024;
7261    const DIRECT_STAGER_DCS_MAX_SESSION_OUTPUT_BYTES: usize = 64 * 1024 * 1024;
7262
7263    let Some(sg) = resolver.seed_graph() else {
7264        return Ok(None);
7265    };
7266    let routine_sh = DcShorthand::from_global_id(routine_dc.to_u128());
7267    if sg.resolve_stagel_decomposition_tokens(routine_sh)?.is_none() {
7268        return Ok(None);
7269    }
7270
7271    let prof_start = is_dc_routine_profiling_enabled()
7272        .then(std::time::Instant::now);
7273
7274    let mut input_doc = DcMstring::new();
7275    for &tok in input_tokens {
7276        input_doc.push_char(tok);
7277    }
7278    let most_recent = sg.system_block_most_recent_node_id();
7279    // Reason for fallback: Direct un-metered host calls allocate a bounded
7280    // routine-step quota sufficient for self-hosted `f1680`/`f1681` and `Dc 1939` queries.
7281    let active_quota = shared_quota.unwrap_or_else(|| {
7282        SharedWasmTaskQuota::new(
7283            DcWasmResourceLimits::default()
7284                .with_max_instructions_per_step(DIRECT_STAGER_DCS_MAX_INSTRUCTIONS)
7285                .with_max_memory_pages(DIRECT_STAGER_DCS_MAX_MEMORY_PAGES)
7286                .with_max_step_output_bytes(DIRECT_STAGER_DCS_MAX_STEP_OUTPUT_BYTES)
7287                .with_max_session_output_bytes(
7288                    DIRECT_STAGER_DCS_MAX_SESSION_OUTPUT_BYTES,
7289                )
7290                .with_max_capability_payload_bytes(
7291                    DIRECT_STAGER_DCS_MAX_STEP_OUTPUT_BYTES,
7292                ),
7293        )
7294    });
7295    let before_snap = active_quota.snapshot()?;
7296    let mut limits = before_snap.active_limits;
7297    limits.max_capability_payload_bytes =
7298        limits.max_capability_payload_bytes.max(limits.max_step_output_bytes);
7299
7300    let cache_key = (input_doc.as_bytes().len() <= MAX_MEMOIZED_PURE_INPUT_BYTES)
7301        .then(|| {
7302            let mut hasher = Sha256::new();
7303            hasher.update(b"ctb-stager-dcs-routine-v1");
7304            hasher.update(WASM_RESOURCE_ACCOUNTING_VERSION.to_le_bytes());
7305            hasher.update(sg.instance_id().to_le_bytes());
7306            match most_recent {
7307                Some(pin) => {
7308                    hasher.update([1u8]);
7309                    hasher.update(pin.to_le_bytes());
7310                }
7311                None => hasher.update([0u8]),
7312            }
7313            hasher.update(routine_dc.to_u128().to_le_bytes());
7314            hasher.update(input_doc.as_bytes());
7315            let key: [u8; 32] = hasher.finalize().into();
7316            key
7317        });
7318
7319    if let Some(ref key) = cache_key {
7320        let map_lock = PURE_STAGER_DCS_ROUTINE_CACHE
7321            .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
7322        let cached_opt = map_lock.lock().ok().and_then(|g| g.get(key).cloned());
7323        if let Some(entry) = cached_opt
7324            && let Some(hit) = try_charge_cached_pure_conversion(
7325                &entry,
7326                &limits,
7327                Some(&active_quota),
7328            )?
7329        {
7330            if let Some(t0) = prof_start
7331                && let Ok(ret_str) = hit.to_dc_string()
7332            {
7333                let ret_chars: Vec<DcChar> = ret_str.chars().collect();
7334                record_dc_routine_invocation_profile(
7335                    routine_dc,
7336                    most_recent,
7337                    input_tokens,
7338                    &ret_chars,
7339                    t0.elapsed().as_nanos(),
7340                    entry.executed_instructions,
7341                );
7342            }
7343            if let Some(err_msg) =
7344                decode_dc_error_record_if_present(&hit, resolver)?
7345            {
7346                if routine_dc
7347                    == ctb_formats_dcdata::dc::DC_CONVERT_DC_STRING_TO_WASM
7348                {
7349                    bail!("Dc 2608 Convert Dc string to WASM failed: {err_msg}");
7350                }
7351                bail!("StageR 3 graph routine {routine_sh} failed: {err_msg}");
7352            }
7353            return Ok(Some(hit));
7354        }
7355    }
7356
7357    let graph_target = ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTarget {
7358        subject: routine_sh,
7359        global_id: routine_dc.to_u128(),
7360        defining_node_id: 0,
7361        chunk_prefix: String::new(),
7362        kind: ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTargetKind::StageRRoutineDcs,
7363    };
7364    let mut session = if let Ok(Some(desc)) =
7365        lookup_cached_graph_target_substitute(sg, &graph_target)
7366    {
7367        DcWasmSession::from_substitute_descriptor_with_limits(
7368            desc,
7369            &input_doc,
7370            most_recent,
7371            limits,
7372        )?
7373    } else {
7374        let Some(wasm_bytes) =
7375            compile_and_cache_graph_stager_dcs_routine_to_wasm_bytes(
7376                routine_dc,
7377                sg,
7378                resolver,
7379            )?
7380        else {
7381            return Ok(None);
7382        };
7383        DcWasmSession::from_wasm_bytes_with_limits(
7384            wasm_bytes.as_slice(),
7385            &input_doc,
7386            most_recent,
7387            limits,
7388        )?
7389    };
7390    session.set_shared_task_quota(active_quota.clone())?;
7391    let output = super::run_wasm_session_pure_with_graph_capabilities(
7392        &mut session,
7393        resolver,
7394        Some(active_quota.clone()),
7395    )?;
7396    let after_snap = active_quota.snapshot()?;
7397    let delta_instructions = after_snap
7398        .total_instructions_executed
7399        .saturating_sub(before_snap.total_instructions_executed);
7400    let delta_output_bytes = after_snap
7401        .cumulative_output_bytes
7402        .saturating_sub(before_snap.cumulative_output_bytes);
7403    if let Some(key) = cache_key
7404        && output.as_bytes().len() <= MAX_MEMOIZED_PURE_OUTPUT_BYTES
7405        && let Ok(peak_mem) = session.current_memory_pages()
7406    {
7407        let out_payload_len =
7408            output.as_bytes().len().saturating_sub(DCMM_HEADER_LEN);
7409        let entry = CachedPureWasmConversion {
7410            output_doc_bytes: std::sync::Arc::new(output.as_bytes().to_vec()),
7411            executed_instructions: delta_instructions,
7412            peak_memory_pages: peak_mem.max(64),
7413            peak_table_elements: session.current_table_elements(),
7414            max_step_output_bytes: out_payload_len.max(delta_output_bytes),
7415            total_output_payload_bytes: delta_output_bytes,
7416        };
7417        let map_lock = PURE_STAGER_DCS_ROUTINE_CACHE
7418            .get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()));
7419        if let Ok(mut guard) = map_lock.lock() {
7420            if guard.len() >= MAX_MEMOIZED_PURE_CACHE_ENTRIES {
7421                guard.clear();
7422            }
7423            guard.insert(key, entry);
7424        }
7425    }
7426    if let Some(t0) = prof_start
7427        && let Ok(ret_str) = output.to_dc_string()
7428    {
7429        let ret_chars: Vec<DcChar> = ret_str.chars().collect();
7430        record_dc_routine_invocation_profile(
7431            routine_dc,
7432            most_recent,
7433            input_tokens,
7434            &ret_chars,
7435            t0.elapsed().as_nanos(),
7436            delta_instructions,
7437        );
7438    }
7439    if let Some(err_msg) =
7440        decode_dc_error_record_if_present(&output, resolver)?
7441    {
7442        if routine_dc == ctb_formats_dcdata::dc::DC_CONVERT_DC_STRING_TO_WASM {
7443            bail!("Dc 2608 Convert Dc string to WASM failed: {err_msg}");
7444        }
7445        bail!("StageR 3 graph routine {routine_sh} failed: {err_msg}");
7446    }
7447    Ok(Some(output))
7448}
7449
7450/// Executes the System-graph StageR 3 implementation of `Dc 2608`
7451/// (`Convert Dc string to WASM`) via [`DcWasmSession`] with Option B
7452/// capability support (`Dc 1939` / `Dc 1940`), charging runtime execution to
7453/// `shared_quota`.
7454///
7455/// Returns `Ok(None)` when `resolver` carries no `SeedGraphIndex` snapshot or
7456/// the pinned snapshot predates `Dc 2608` having an active StageR 3
7457/// decomposition, allowing callers to fall back strictly for pre-migration pins.
7458///
7459/// # Errors
7460/// Returns an error on bootstrap compilation failure, quota exhaustion
7461/// (`WasmResourceInterruption`), WASM runtime traps, or `Dc 552..Dc 553` error
7462/// records emitted by `Dc 2608`.
7463pub fn run_graph_stager_dc_2608_with_quota(
7464    call_tokens: &[DcChar],
7465    resolver: &dyn SyntaxRuleResolver,
7466    shared_quota: Option<SharedWasmTaskQuota>,
7467) -> Result<Option<DcMstring>> {
7468    run_graph_stager_dcs_routine_with_quota(
7469        ctb_formats_dcdata::dc::DC_CONVERT_DC_STRING_TO_WASM,
7470        call_tokens,
7471        resolver,
7472        shared_quota,
7473    )
7474}
7475
7476/// Lowers and assembles the uninstrumented canonical `.wasm` bytes for a
7477/// discovered [`ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTarget`].
7478///
7479/// # Errors
7480/// Returns an error if `resolver` lacks a `SeedGraphIndex` or lowering/assembling
7481/// `target` fails.
7482pub fn compile_system_substitute_target_wasm_bytes(
7483    target: &ctb_formats_dcdata::seed_graph::SystemWasmSubstituteTarget,
7484    resolver: &dyn SyntaxRuleResolver,
7485) -> Result<Vec<u8>> {
7486    use ctb_formats_dcdata::seed_graph::{
7487        ActiveConverterBody, SystemWasmSubstituteTargetKind,
7488    };
7489    use ctb_storage_minimal::shorthand::DcShorthand;
7490
7491    let sg = resolver
7492        .seed_graph()
7493        .context("Active SyntaxRuleResolver has no SeedGraphIndex")?;
7494    let target_dc = DcChar::from_u128(target.global_id);
7495    match &target.kind {
7496        SystemWasmSubstituteTargetKind::SupervisorKernel => {
7497            let resolved = sg
7498                .resolve_trusted_system_supervisor_bootstrap_tokens(&[
7499                    target.subject,
7500                ])?;
7501            let mut sup_doc = DcMstring::new();
7502            for tok in &resolved.definition_tokens {
7503                sup_doc.push_char(DcChar::from_u128(tok.to_global_id()?));
7504            }
7505            dcmstring_to_wasm_with_resolver(&sup_doc, resolver)
7506        }
7507        SystemWasmSubstituteTargetKind::StandaloneWasm => {
7508            let (_, tokens) = sg
7509                .resolve_wasm_helper_shorthand(target.subject)?
7510                .with_context(|| {
7511                    format!(
7512                        "Target {} ({}) missing active standalone WASM decomposition",
7513                        target.subject, target.chunk_prefix
7514                    )
7515                })?;
7516            let doc =
7517                expand_graph_wasm_shorthands_to_dcmstring(tokens, resolver)?;
7518            dcmstring_to_wasm_with_resolver(&doc, resolver)
7519        }
7520        SystemWasmSubstituteTargetKind::StandaloneWasmValueNode { node_id } => {
7521            let node = sg.get_active_node(*node_id).with_context(|| {
7522                format!(
7523                    "Standalone WASM value node l{node_id} ({}) missing from snapshot",
7524                    target.chunk_prefix
7525                )
7526            })?;
7527            let doc = expand_graph_wasm_shorthands_to_dcmstring(
7528                &node.tokens,
7529                resolver,
7530            )?;
7531            dcmstring_to_wasm_with_resolver(&doc, resolver)
7532        }
7533        SystemWasmSubstituteTargetKind::WasmConverter { src, dst } => {
7534            let steps = sg.list_all_active_converter_steps()?;
7535            let step = steps
7536                .into_iter()
7537                .find(|s| s.subject == target.subject)
7538                .with_context(|| {
7539                    format!(
7540                        "WASM converter {} ({} -> {}, {}) missing from System graph",
7541                        target.subject, src, dst, target.chunk_prefix
7542                    )
7543                })?;
7544            let ActiveConverterBody::Wasm(tokens) = step.body else {
7545                bail!(
7546                    "Converter {} ({}) is not a .WASM implementation",
7547                    target.subject,
7548                    target.chunk_prefix
7549                );
7550            };
7551            let doc =
7552                expand_graph_wasm_shorthands_to_dcmstring(tokens, resolver)?;
7553            dcmstring_to_wasm_with_resolver(&doc, resolver)
7554        }
7555        SystemWasmSubstituteTargetKind::StageLConverter { .. }
7556        | SystemWasmSubstituteTargetKind::StageLRoutineBytes => {
7557            let stagel_src_sh = DcShorthand::from_global_id(
7558                ctb_formats_dcdata::dc::DC_BEGIN_MODULE.to_u128(),
7559            );
7560            let wasm_dst_sh = DcShorthand::from_global_id(
7561                ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
7562            );
7563            let entry_tokens =
7564                ctb_formats_dcdata::stagel3::seed_linker::build_entry_module_for_graph_routine_dc(
7565                    target_dc,
7566                    sg,
7567                )?;
7568            let bundled =
7569                ctb_formats_dcdata::stagel3::seed_linker::bundle_dc_module_for_wasm_converter(
7570                    &entry_tokens,
7571                    sg,
7572                    resolver,
7573                )?;
7574            let Some((_, stagel_to_wasm_tokens)) =
7575                sg.resolve_active_converter_routine(stagel_src_sh, wasm_dst_sh)?
7576            else {
7577                bail!(
7578                    "Missing active StageL -> WASM converter routine f1680 in System graph"
7579                );
7580            };
7581            let raw_wasm_doc = run_graph_wasm_tokens_on_dc_slice_with_quota(
7582                stagel_to_wasm_tokens,
7583                &bundled,
7584                resolver,
7585                Some(default_substitute_compiler_quota()),
7586            )?;
7587            assemble_compiled_wasm_doc(&raw_wasm_doc, resolver)
7588        }
7589        SystemWasmSubstituteTargetKind::StageRConverter { .. }
7590        | SystemWasmSubstituteTargetKind::StageRRoutineBytes => {
7591            let stager_src_sh = DcShorthand::from_global_id(
7592                ctb_formats_dcdata::dc::DC_BEGIN_STAGER_MODULE.to_u128(),
7593            );
7594            let wasm_dst_sh = DcShorthand::from_global_id(
7595                ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
7596            );
7597            let chain = sg
7598                .resolve_active_converter_chain(stager_src_sh, wasm_dst_sh)?
7599                .context(
7600                    "Missing active StageR 3 -> WASM converter chain in System graph",
7601                )?;
7602            let entry_tokens =
7603                ctb_formats_dcdata::stagel3::seed_linker::build_stager_bytes_entry_module_for_graph_routine_dc(
7604                    target_dc,
7605                    sg,
7606                )?;
7607            let raw_wasm_doc = run_graph_converter_chain_on_dc_slice_with_quota(
7608                &chain,
7609                &entry_tokens,
7610                sg,
7611                resolver,
7612                Some(default_substitute_compiler_quota()),
7613            )?;
7614            assemble_compiled_wasm_doc(&raw_wasm_doc, resolver)
7615        }
7616        SystemWasmSubstituteTargetKind::StageLRoutineDcs
7617        | SystemWasmSubstituteTargetKind::StageRRoutineDcs => {
7618            let compiled =
7619                compile_and_cache_graph_stager_dcs_routine_to_wasm_bytes(
7620                    target_dc,
7621                    sg,
7622                    resolver,
7623                )?
7624                .with_context(|| {
7625                    format!(
7626                        "Routine {} ({}) missing active decomposition in System graph",
7627                        target.subject, target.chunk_prefix
7628                    )
7629                })?;
7630            Ok(compiled.as_ref().clone())
7631        }
7632    }
7633}
7634
7635/// Lowers and assembles the uninstrumented canonical `.wasm` bytes for a
7636/// discovered [`ctb_formats_dcdata::seed_graph::GraphWasmSubstituteSnapshot`]
7637/// reconstructed at `snapshot.pin_node_id` from an ordered `LedgerNode` slice.
7638///
7639/// If `snapshot.is_head` is `false` and a superseded/retracted historical draft
7640/// fails compilation, logs a warning and returns `Ok(None)` rather than failing
7641/// the entire substitute bundle.
7642///
7643/// # Errors
7644/// Returns an error if `snapshot.is_head` fails compilation or if reconstructing
7645/// the base resolver fails.
7646pub fn compile_graph_substitute_snapshot_wasm_bytes(
7647    ordered_nodes: &[ctb_formats_dcdata::graph_ledger::LedgerNode],
7648    snapshot: &ctb_formats_dcdata::seed_graph::GraphWasmSubstituteSnapshot,
7649) -> Result<Option<Vec<u8>>> {
7650    let mut cache = std::collections::BTreeMap::new();
7651    compile_graph_substitute_snapshot_wasm_bytes_with_cache(
7652        ordered_nodes,
7653        snapshot,
7654        &mut cache,
7655    )
7656}
7657
7658/// Like [`compile_graph_substitute_snapshot_wasm_bytes`], reusing reconstructed
7659/// `SeedGraphIndex` + `DatasetRuleResolver` snapshots across calls that share `pin_node_id`.
7660///
7661/// # Errors
7662/// Returns an error if `snapshot.is_head` fails compilation or if reconstructing
7663/// the base resolver fails.
7664pub fn compile_graph_substitute_snapshot_wasm_bytes_with_cache(
7665    ordered_nodes: &[ctb_formats_dcdata::graph_ledger::LedgerNode],
7666    snapshot: &ctb_formats_dcdata::seed_graph::GraphWasmSubstituteSnapshot,
7667    resolver_cache: &mut std::collections::BTreeMap<
7668        u128,
7669        Option<std::sync::Arc<ctb_formats_dcdata::syntax::DatasetRuleResolver>>,
7670    >,
7671) -> Result<Option<Vec<u8>>> {
7672    use ctb_formats_dcdata::seed_graph::SeedGraphIndex;
7673    use ctb_formats_dcdata::syntax::DatasetRuleResolver;
7674    use ctb_storage_minimal::global_graph_layout::{
7675        SYSTEM_REGION_END, SYSTEM_REGION_START,
7676    };
7677
7678    let resolver_arc = if let Some(cached) =
7679        resolver_cache.get(&snapshot.pin_node_id)
7680    {
7681        match cached {
7682            Some(r) => std::sync::Arc::clone(r),
7683            None => return Ok(None),
7684        }
7685    } else {
7686        let prefix_end =
7687            ordered_nodes.partition_point(|n| n.id <= snapshot.pin_node_id);
7688        let prefix = ordered_nodes
7689            .get(..prefix_end)
7690            .context("Snapshot pin_node_id partition_point out of bounds")?
7691            .to_vec();
7692        let sg = if (SYSTEM_REGION_START..=SYSTEM_REGION_END)
7693            .contains(&snapshot.pin_node_id)
7694        {
7695            SeedGraphIndex::from_bundled_nodes_at_most_recent(
7696                prefix,
7697                snapshot.pin_node_id,
7698            )
7699        } else {
7700            SeedGraphIndex::from_nodes_at_most_recent(
7701                prefix,
7702                snapshot.pin_node_id,
7703            )
7704        };
7705        let sg_arc = std::sync::Arc::new(sg);
7706        let wasm_begin_sh =
7707            ctb_storage_minimal::shorthand::DcShorthand::from_global_id(
7708                ctb_formats_dcdata::dc::DC_BEGIN_WASM_PROGRAM.to_u128(),
7709            );
7710        let resolver_res: Result<DatasetRuleResolver> =
7711            match sg_arc.decode_syntax_rule_for_subject(wasm_begin_sh) {
7712                Ok(Some(_)) => DatasetRuleResolver::from_seed_graph_arc(
7713                    std::sync::Arc::clone(&sg_arc),
7714                ),
7715                Ok(None) => {
7716                    let mut base = DatasetRuleResolver::load_from_seed_graph()?;
7717                    base.set_seed_graph(std::sync::Arc::clone(&sg_arc));
7718                    Ok(base)
7719                }
7720                Err(err) => Err(err),
7721            };
7722        match resolver_res {
7723            Ok(r) => {
7724                let arc = std::sync::Arc::new(r);
7725                resolver_cache
7726                    .insert(snapshot.pin_node_id, Some(std::sync::Arc::clone(&arc)));
7727                arc
7728            }
7729            Err(err) if !snapshot.is_head => {
7730                warn_fmt!(
7731                    "Skipping historical substitute snapshot {} at l{} ({}): resolver build failed: {err:#}",
7732                    snapshot.target.subject,
7733                    snapshot.pin_node_id,
7734                    snapshot.target.chunk_prefix
7735                );
7736                resolver_cache.insert(snapshot.pin_node_id, None);
7737                return Ok(None);
7738            }
7739            Err(err) => return Err(err),
7740        }
7741    };
7742    match compile_system_substitute_target_wasm_bytes(
7743        &snapshot.target,
7744        resolver_arc.as_ref(),
7745    ) {
7746        Ok(bytes) => Ok(Some(bytes)),
7747        Err(err) if !snapshot.is_head => {
7748            warn_fmt!(
7749                "Skipping historical substitute snapshot {} at l{} ({}): {err:#}",
7750                snapshot.target.subject,
7751                snapshot.pin_node_id,
7752                snapshot.target.chunk_prefix
7753            );
7754            Ok(None)
7755        }
7756        Err(err) => Err(err),
7757    }
7758}
7759
7760/// Lowers and assembles the uninstrumented canonical `.wasm` bytes for a
7761/// System-graph substitute target identified by its [`ctb_storage_minimal::shorthand::DcShorthand`].
7762///
7763/// # Errors
7764/// Returns an error if `subject` is not a discovered runnable target in `resolver`,
7765/// `resolver` lacks a `SeedGraphIndex`, or lowering/assembling the target fails.
7766pub fn compile_system_subject_wasm_bytes(
7767    subject: ctb_storage_minimal::shorthand::DcShorthand,
7768    resolver: &dyn SyntaxRuleResolver,
7769) -> Result<Vec<u8>> {
7770    let sg = resolver
7771        .seed_graph()
7772        .context("Active SyntaxRuleResolver has no SeedGraphIndex")?;
7773    let targets = sg.discover_system_wasm_substitute_targets()?;
7774    let matched = targets
7775        .into_iter()
7776        .find(|t| t.subject == subject)
7777        .with_context(|| {
7778            format!("Unknown System WASM substitute subject {subject}")
7779        })?;
7780    compile_system_substitute_target_wasm_bytes(&matched, resolver)
7781}
7782
7783#[cfg(test)]
7784#[allow(
7785    clippy::panic,
7786    clippy::expect_used,
7787    clippy::unwrap_used,
7788    clippy::unwrap_in_result,
7789    clippy::panic_in_result_fn,
7790    clippy::indexing_slicing,
7791    clippy::arithmetic_side_effects,
7792    reason = "Standard repository test boilerplate"
7793)]
7794mod tests {
7795    use super::*;
7796    use crate::{DcMixedEncode, DcMstring};
7797    use ctb_formats_dcdata::DcShorthand;
7798    use ctb_formats_dcdata::tinywasm::{Module, Store};
7799
7800    fn i32_type_dc() -> DcChar {
7801        DcChar::from_u128(FormatId::I32.dc_id().unwrap())
7802    }
7803
7804    fn wasm_try_table_doc(catches: &[Vec<i64>]) -> Result<DcMstring> {
7805        let mut doc = DcMstring::new();
7806        for token in [678, 316, 310, 275] {
7807            doc.push_char(DcChar::from_short(token));
7808        }
7809        for (position, fields) in catches.iter().enumerate() {
7810            if position != 0 {
7811                doc.push_char(DcChar::from_short(312));
7812            }
7813            doc.push_char(DcChar::from_short(310));
7814            doc.push_char(DcChar::from_short(275));
7815            for (field_position, field) in fields.iter().enumerate() {
7816                if field_position != 0 {
7817                    doc.push_char(DcChar::from_short(312));
7818                }
7819                field.encode_dc_mixed(&mut doc)?;
7820            }
7821            doc.push_char(DcChar::from_short(311));
7822        }
7823        for token in [311, 648, 658] {
7824            doc.push_char(DcChar::from_short(token));
7825        }
7826        Ok(doc)
7827    }
7828
7829    #[crate::ctb_test]
7830    fn test_wasm_try_table_catch_records() -> Result<()> {
7831        let resolver = default_syntax_resolver();
7832        let doc = wasm_try_table_doc(&[
7833            vec![0, 128, 300],
7834            vec![1, 2, 3],
7835            vec![2, 4],
7836            vec![3, 5],
7837        ])?;
7838        DcDocumentNavigator::from_mstr(&doc).validate_document_strict()?;
7839        assert_eq!(
7840            assemble_wasm_instructions(&doc, resolver.as_ref())?,
7841            vec![0x1f, 0x40, 4, 0, 0x80, 1, 0xac, 2, 1, 2, 3, 2, 4, 3, 5, 1, 0x0b]
7842        );
7843        assert_eq!(
7844            assemble_wasm_instructions(&wasm_try_table_doc(&[])?, resolver.as_ref())?,
7845            vec![0x1f, 0x40, 0, 1, 0x0b]
7846        );
7847        for fields in [
7848            vec![],
7849            vec![4, 0],
7850            vec![0, 1],
7851            vec![1, 1, 2, 3],
7852            vec![2, 1, 2],
7853            vec![3],
7854            vec![0, -1, 0],
7855            vec![2, 4_294_967_296],
7856        ] {
7857            let malformed = wasm_try_table_doc(&[fields])?;
7858            assert!(DcDocumentNavigator::from_mstr(&malformed)
7859                .validate_document_strict().is_err());
7860            assert!(assemble_wasm_instructions(&malformed, resolver.as_ref()).is_err());
7861        }
7862        Ok(())
7863    }
7864
7865    #[crate::ctb_test]
7866    fn test_wasm_instruction_operand_grammar() -> Result<()> {
7867        let resolver = default_syntax_resolver();
7868        for opener in [649, 650, 651, 1927] {
7869            for operand_count in 0..=2 {
7870                let mut doc = DcMstring::new();
7871                doc.push_char(DcChar::from_short(opener));
7872                if opener != 1927 {
7873                    doc.push_char(DcChar::from_short(316));
7874                }
7875                doc.push_char(DcChar::from_short(679));
7876                for _ in 0..operand_count {
7877                    0u32.encode_dc_mixed(&mut doc)?;
7878                }
7879                let closer = if opener == 1927 { 1928 } else { 658 };
7880                doc.push_char(DcChar::from_short(closer));
7881                assert_eq!(
7882                    DcDocumentNavigator::from_mstr(&doc)
7883                        .validate_document_strict().is_ok(),
7884                    operand_count == 1,
7885                    "opener {opener}, operand count {operand_count}"
7886                );
7887            }
7888        }
7889        for sequence in [
7890            vec![653],
7891            vec![1158],
7892            vec![652],
7893            vec![649, 316, 652, 658],
7894            vec![650, 316, 652, 658],
7895            vec![651, 316, 652, 652, 658],
7896        ] {
7897            let mut doc = DcMstring::new();
7898            for token in sequence {
7899                doc.push_char(DcChar::from_short(token));
7900            }
7901            assert!(assemble_wasm_instructions(&doc, resolver.as_ref()).is_err());
7902        }
7903        let mut valid_if = DcMstring::new();
7904        for token in [651, 316, 648, 652, 648, 658] {
7905            valid_if.push_char(DcChar::from_short(token));
7906        }
7907        DcDocumentNavigator::from_mstr(&valid_if).validate_document_strict()?;
7908        assert_eq!(assemble_wasm_instructions(&valid_if, resolver.as_ref())?,
7909            vec![4, 0x40, 1, 5, 1, 0x0b]);
7910        assert!(resolver.matches_script(".WASM GC", DcChar::from_short(903).to_u128()));
7911        Ok(())
7912    }
7913
7914    #[crate::ctb_test]
7915    fn test_wasm_blocktype_indices() -> Result<()> {
7916        let resolver = default_syntax_resolver();
7917        for (index, expected) in [
7918            (0u32, vec![0x00]),
7919            (63, vec![0x3f]),
7920            (64, vec![0xc0, 0x00]),
7921            (127, vec![0xff, 0x00]),
7922            (u32::MAX, vec![0xff, 0xff, 0xff, 0xff, 0x0f]),
7923        ] {
7924            let mut doc = DcMstring::new();
7925            index.encode_dc_mixed(&mut doc)?;
7926            let dc_string = doc.to_dc_string_with_policy_and_resolver(
7927                &DcProjectionPolicy::strict(),
7928                resolver.as_ref(),
7929            )?;
7930            let tokens: Vec<_> = dc_string.chars().collect();
7931            let mut cursor = TokenCursor::new(&tokens, resolver.as_ref());
7932            let mut encoded = Vec::new();
7933            cursor.emit_blocktype(&mut encoded)?;
7934            assert_eq!(encoded, expected);
7935            assert!(cursor.is_eof());
7936            for (opener, opcode) in [(649, 2), (650, 3), (651, 4)] {
7937                let mut block = DcMstring::new();
7938                block.push_char(DcChar::from_short(opener));
7939                index.encode_dc_mixed(&mut block)?;
7940                block.push_char(DcChar::from_short(658));
7941                DcDocumentNavigator::from_mstr(&block).validate_document_strict()?;
7942                let mut expected_block = vec![opcode];
7943                expected_block.extend_from_slice(&expected);
7944                expected_block.push(0x0b);
7945                assert_eq!(assemble_wasm_instructions(&block, resolver.as_ref())?, expected_block);
7946            }
7947        }
7948        for index in [-1i64, 4_294_967_296] {
7949            let mut doc = DcMstring::new();
7950            index.encode_dc_mixed(&mut doc)?;
7951            let dc_string = doc.to_dc_string_with_policy_and_resolver(
7952                &DcProjectionPolicy::strict(),
7953                resolver.as_ref(),
7954            )?;
7955            let tokens: Vec<_> = dc_string.chars().collect();
7956            let mut cursor = TokenCursor::new(&tokens, resolver.as_ref());
7957            assert!(cursor.emit_blocktype(&mut Vec::new()).is_err());
7958        }
7959        Ok(())
7960    }
7961
7962    #[crate::ctb_test]
7963    fn test_zero_table_opcode_arithmetic_across_all_five_pages() -> Result<()> {
7964        let resolver = default_syntax_resolver();
7965
7966        // Page 0: Dc 647 (0x00 unreachable) .. Dc 753 (0x6A i32.add)
7967        assert_eq!(
7968            decode_wasm_opcode(DcChar::from_short(647), resolver.as_ref()),
7969            Some((None, 0x00))
7970        );
7971        assert_eq!(
7972            decode_wasm_opcode(DcChar::from_short(753), resolver.as_ref()),
7973            Some((None, 0x6A))
7974        );
7975
7976        // 0xFB page: Dc 903 (0xFB 0x00 struct.new)
7977        assert_eq!(
7978            decode_wasm_opcode(DcChar::from_short(903), resolver.as_ref()),
7979            Some((Some(0xFB), 0x00))
7980        );
7981
7982        // 0xFC page: Dc 1159 (0xFC 0x00 i32.trunc_sat_f32_s)
7983        assert_eq!(
7984            decode_wasm_opcode(DcChar::from_short(1159), resolver.as_ref()),
7985            Some((Some(0xFC), 0x00))
7986        );
7987
7988        // 0xFD page 0: Dc 1415 (0xFD 0x00 v128.load)
7989        assert_eq!(
7990            decode_wasm_opcode(DcChar::from_short(1415), resolver.as_ref()),
7991            Some((Some(0xFD), 0x00))
7992        );
7993
7994        // 0xFD page 1: Dc 1671 (0xFD 0x100 i8x16.relaxed_swizzle)
7995        assert_eq!(
7996            decode_wasm_opcode(DcChar::from_short(1671), resolver.as_ref()),
7997            Some((Some(0xFD), 0x100))
7998        );
7999
8000        // Non-WASM Dc returns None
8001        assert_eq!(
8002            decode_wasm_opcode(DcChar::from_short(1927), resolver.as_ref()),
8003            None
8004        );
8005        Ok(())
8006    }
8007
8008    #[crate::ctb_test]
8009    fn test_assemble_and_execute_wasm_program_in_tinywasm() -> Result<()> {
8010        let i32_dc = i32_type_dc();
8011
8012        // Build a key-value WASM program (Dc 1927..1928) with:
8013        // 1. Routine `sum(p1: i32, p2: i32) -> i32`:
8014        //      local.get 0
8015        //      local.get 1
8016        //      i32.add
8017        // 2. Routine `accumulate_to_mem(n: i32) -> i32` (with 1 local `acc: i32`):
8018        //      loop $L (void):
8019        //        local.get 0 (n)
8020        //        local.get 1 (acc)
8021        //        i32.add
8022        //        local.set 1 (acc)
8023        //        local.get 0 (n)
8024        //        i32.const 1
8025        //        i32.sub
8026        //        local.tee 0 (n)
8027        //        br_if 0 ($L)
8028        //      end
8029        //      i32.const 0 (addr)
8030        //      local.get 1 (acc)
8031        //      i32.store memidx=0 align=2 offset=0
8032        //      i32.const 0 (addr)
8033        //      i32.load memidx=0 align=2 offset=0
8034        let mut prog = DcMstring::new();
8035        prog.push_char(DcChar::from_short(1927)); // Begin WASM program
8036        prog.push_char(DcChar::from_short(559)); // Begin key-value array (ordered)
8037        prog.push_char(DcChar::from_short(275)); // keyType = *
8038        prog.push_char(DcChar::from_short(275)); // valType = *
8039
8040        // --- Pair 1: `sum` ---
8041        prog.push_char(DcChar::from_short(514)); // Begin key-value pair
8042        prog.push_char(DcChar::from_short(270)); // Begin identifier
8043        prog.push_char(DcChar::from_short(262)); // Begin type definition
8044        prog.push_char(DcChar::from_short(280)); // Routine
8045        prog.push_char(i32_dc); // returnType = i32
8046        prog.push_char(DcChar::from_short(310)); // Begin list (params)
8047        prog.push_char(DcChar::from_short(275));
8048        prog.push_char(DcChar::from_short(270));
8049        prog.push_char(i32_dc);
8050        prog.push_str("p1");
8051        prog.push_char(DcChar::from_short(271));
8052        prog.push_char(DcChar::from_short(312));
8053        prog.push_char(DcChar::from_short(270));
8054        prog.push_char(i32_dc);
8055        prog.push_str("p2");
8056        prog.push_char(DcChar::from_short(271));
8057        prog.push_char(DcChar::from_short(311)); // End list
8058        prog.push_char(DcChar::from_short(263)); // End type definition
8059        prog.push_str("sum");
8060        prog.push_char(DcChar::from_short(271)); // End identifier
8061        prog.push_char(DcChar::from_short(312)); // Separator
8062        // Routine body for `sum`
8063        prog.push_char(DcChar::from_short(260)); // Begin literal value
8064        prog.push_char(DcChar::from_short(262));
8065        prog.push_char(DcChar::from_short(280));
8066        prog.push_char(DcChar::from_short(263));
8067        prog.push_char(DcChar::from_short(679)); // local.get 0
8068        u32::encode_dc_mixed(&0, &mut prog)?;
8069        prog.push_char(DcChar::from_short(679)); // local.get 1
8070        u32::encode_dc_mixed(&1, &mut prog)?;
8071        prog.push_char(DcChar::from_short(753)); // i32.add
8072        prog.push_char(DcChar::from_short(261)); // End literal value
8073        prog.push_char(DcChar::from_short(515)); // End key-value pair
8074
8075        // --- Pair 2: `accumulate_to_mem` ---
8076        prog.push_char(DcChar::from_short(514)); // Begin key-value pair
8077        prog.push_char(DcChar::from_short(270)); // Begin identifier
8078        prog.push_char(DcChar::from_short(262));
8079        prog.push_char(DcChar::from_short(280));
8080        prog.push_char(i32_dc); // returnType = i32
8081        prog.push_char(DcChar::from_short(310)); // params: [i32/n]
8082        prog.push_char(DcChar::from_short(275));
8083        prog.push_char(DcChar::from_short(270));
8084        prog.push_char(i32_dc);
8085        prog.push_str("n");
8086        prog.push_char(DcChar::from_short(271));
8087        prog.push_char(DcChar::from_short(311));
8088        prog.push_char(DcChar::from_short(263));
8089        prog.push_str("accumulate_to_mem");
8090        prog.push_char(DcChar::from_short(271));
8091        prog.push_char(DcChar::from_short(312));
8092        // Routine body for `accumulate_to_mem`
8093        prog.push_char(DcChar::from_short(260));
8094        prog.push_char(DcChar::from_short(262));
8095        prog.push_char(DcChar::from_short(280));
8096        prog.push_char(DcChar::from_short(263));
8097        // Locals: [i32] (local index 1)
8098        prog.push_char(DcChar::from_short(310));
8099        prog.push_char(DcChar::from_short(275));
8100        prog.push_char(i32_dc);
8101        prog.push_char(DcChar::from_short(311));
8102        // loop (void)
8103        prog.push_char(DcChar::from_short(650)); // WASM loop
8104        prog.push_char(DcChar::from_short(316)); // Optional value absent (void)
8105        prog.push_char(DcChar::from_short(679)); // local.get 0
8106        u32::encode_dc_mixed(&0, &mut prog)?;
8107        prog.push_char(DcChar::from_short(679)); // local.get 1
8108        u32::encode_dc_mixed(&1, &mut prog)?;
8109        prog.push_char(DcChar::from_short(753)); // i32.add
8110        prog.push_char(DcChar::from_short(680)); // local.set 1
8111        u32::encode_dc_mixed(&1, &mut prog)?;
8112        prog.push_char(DcChar::from_short(679)); // local.get 0
8113        u32::encode_dc_mixed(&0, &mut prog)?;
8114        prog.push_char(DcChar::from_short(712)); // i32.const 1
8115        i32::encode_dc_mixed(&1, &mut prog)?;
8116        prog.push_char(DcChar::from_short(754)); // i32.sub
8117        prog.push_char(DcChar::from_short(681)); // local.tee 0
8118        u32::encode_dc_mixed(&0, &mut prog)?;
8119        prog.push_char(DcChar::from_short(660)); // br_if 0
8120        u32::encode_dc_mixed(&0, &mut prog)?;
8121        prog.push_char(DcChar::from_short(658)); // WASM end (loop)
8122        // Store result at linear memory address 0 and load it back
8123        prog.push_char(DcChar::from_short(712)); // i32.const 0
8124        i32::encode_dc_mixed(&0, &mut prog)?;
8125        prog.push_char(DcChar::from_short(679)); // local.get 1
8126        u32::encode_dc_mixed(&1, &mut prog)?;
8127        prog.push_char(DcChar::from_short(701)); // i32.store (memidx=0, align=2, offset=0)
8128        u32::encode_dc_mixed(&0, &mut prog)?;
8129        u32::encode_dc_mixed(&2, &mut prog)?;
8130        u32::encode_dc_mixed(&0, &mut prog)?;
8131        prog.push_char(DcChar::from_short(712)); // i32.const 0
8132        i32::encode_dc_mixed(&0, &mut prog)?;
8133        prog.push_char(DcChar::from_short(687)); // i32.load (memidx=0, align=2, offset=0)
8134        u32::encode_dc_mixed(&0, &mut prog)?;
8135        u32::encode_dc_mixed(&2, &mut prog)?;
8136        u32::encode_dc_mixed(&0, &mut prog)?;
8137        prog.push_char(DcChar::from_short(261)); // End literal value
8138        prog.push_char(DcChar::from_short(515)); // End key-value pair
8139
8140        prog.push_char(DcChar::from_short(560)); // End key-value array
8141        prog.push_char(DcChar::from_short(1928)); // End WASM program
8142
8143        let wasm_bytes = dcmstring_to_wasm(&prog)?;
8144
8145        // Parse and execute in TinyWasm
8146        let module = Module::parse_bytes(&wasm_bytes)
8147            .map_err(|e| anyhow!("tinywasm parse failed: {e:?}"))?;
8148        let mut store = Store::default();
8149        let instance = module
8150            .instantiate(&mut store, None)
8151            .map_err(|e| anyhow!("tinywasm instantiate failed: {e:?}"))?;
8152
8153        let sum_fn = instance
8154            .exported_func::<(i32, i32), i32>(&store, "sum")
8155            .map_err(|e| anyhow!("exported_func sum failed: {e:?}"))?;
8156        let sum_res = sum_fn
8157            .call(&mut store, (19, 23))
8158            .map_err(|e| anyhow!("call sum failed: {e:?}"))?;
8159        assert_eq!(sum_res, 42);
8160
8161        let acc_fn = instance
8162            .exported_func::<i32, i32>(&store, "accumulate_to_mem")
8163            .map_err(|e| {
8164                anyhow!("exported_func accumulate_to_mem failed: {e:?}")
8165            })?;
8166        // 10 + 9 + ... + 1 = 55
8167        let acc_res = acc_fn
8168            .call(&mut store, 10)
8169            .map_err(|e| anyhow!("call accumulate_to_mem failed: {e:?}"))?;
8170        assert_eq!(acc_res, 55);
8171
8172        let mem = instance
8173            .exported_memory(&mut store, "memory")
8174            .map_err(|e| anyhow!("exported_memory failed: {e:?}"))?;
8175        let stored_bytes = mem
8176            .load(0, 4)
8177            .map_err(|e| anyhow!("memory load failed: {e:?}"))?;
8178        assert_eq!(stored_bytes, &55i32.to_le_bytes());
8179
8180        Ok(())
8181    }
8182
8183    #[crate::ctb_test]
8184    fn test_standalone_wasm_routine_if_else_globals_and_data_segments_in_tinywasm()
8185    -> Result<()> {
8186        let i32_dc = i32_type_dc();
8187
8188        // 1. Standalone `wasm_routine`: `abs_val(x: i32) -> i32` using `if (result i32) .. else .. end`
8189        let mut routine_doc = DcMstring::new();
8190        routine_doc.push_char(DcChar::from_short(260)); // Begin literal value
8191        routine_doc.push_char(DcChar::from_short(262)); // Begin type definition
8192        routine_doc.push_char(DcChar::from_short(280)); // Routine
8193        routine_doc.push_char(i32_dc); // returnType = i32
8194        routine_doc.push_char(DcChar::from_short(310)); // params: [i32/x]
8195        routine_doc.push_char(DcChar::from_short(275));
8196        routine_doc.push_char(DcChar::from_short(270));
8197        routine_doc.push_char(i32_dc);
8198        routine_doc.push_str("x");
8199        routine_doc.push_char(DcChar::from_short(271));
8200        routine_doc.push_char(DcChar::from_short(311));
8201        routine_doc.push_char(DcChar::from_short(263)); // End type definition
8202
8203        // x < 0:
8204        routine_doc.push_char(DcChar::from_short(679)); // local.get 0
8205        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8206        routine_doc.push_char(DcChar::from_short(712)); // i32.const 0
8207        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8208        routine_doc.push_char(DcChar::from_short(723)); // i32.lt_s
8209        routine_doc.push_char(DcChar::from_short(651)); // WASM if
8210        routine_doc.push_char(i32_dc); // blocktype = i32
8211        // then: 0 - x
8212        routine_doc.push_char(DcChar::from_short(712)); // i32.const 0
8213        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8214        routine_doc.push_char(DcChar::from_short(679)); // local.get 0
8215        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8216        routine_doc.push_char(DcChar::from_short(754)); // i32.sub
8217        routine_doc.push_char(DcChar::from_short(652)); // WASM else
8218        // else: x
8219        routine_doc.push_char(DcChar::from_short(679)); // local.get 0
8220        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8221        routine_doc.push_char(DcChar::from_short(658)); // WASM end (if)
8222        routine_doc.push_char(DcChar::from_short(261)); // End literal value
8223
8224        let wasm_bytes = dcmstring_to_wasm(&routine_doc)?;
8225        let module = Module::parse_bytes(&wasm_bytes)
8226            .map_err(|e| anyhow!("tinywasm parse failed: {e:?}"))?;
8227        let mut store = Store::default();
8228        let instance = module
8229            .instantiate(&mut store, None)
8230            .map_err(|e| anyhow!("tinywasm instantiate failed: {e:?}"))?;
8231        let main_fn = instance
8232            .exported_func::<i32, i32>(&store, "main")
8233            .map_err(|e| anyhow!("exported_func main failed: {e:?}"))?;
8234        assert_eq!(main_fn.call(&mut store, -42).unwrap(), 42);
8235        assert_eq!(main_fn.call(&mut store, 17).unwrap(), 17);
8236
8237        // 2. Program with a global (`base_offset = 100`) and a routine using `global.get 0` + negative `i32.const -25`
8238        let mut prog = DcMstring::new();
8239        prog.push_char(DcChar::from_short(1927)); // Begin WASM program
8240        prog.push_char(DcChar::from_short(559)); // Begin key-value array
8241        prog.push_char(DcChar::from_short(275));
8242        prog.push_char(DcChar::from_short(275));
8243
8244        // Global member: `base = 100`
8245        prog.push_char(DcChar::from_short(514));
8246        prog.push_char(DcChar::from_short(270));
8247        prog.push_char(i32_dc);
8248        prog.push_str("base");
8249        prog.push_char(DcChar::from_short(271));
8250        prog.push_char(DcChar::from_short(312));
8251        i32::encode_dc_mixed(&100, &mut prog)?;
8252        prog.push_char(DcChar::from_short(515));
8253
8254        // Routine member: `compute() -> i32` = `global.get 0 + (-25)` = 75
8255        prog.push_char(DcChar::from_short(514));
8256        prog.push_char(DcChar::from_short(270));
8257        prog.push_char(DcChar::from_short(262));
8258        prog.push_char(DcChar::from_short(280));
8259        prog.push_char(i32_dc);
8260        prog.push_char(DcChar::from_short(263));
8261        prog.push_str("compute");
8262        prog.push_char(DcChar::from_short(271));
8263        prog.push_char(DcChar::from_short(312));
8264        prog.push_char(DcChar::from_short(260));
8265        prog.push_char(DcChar::from_short(262));
8266        prog.push_char(DcChar::from_short(280));
8267        prog.push_char(DcChar::from_short(263));
8268        prog.push_char(DcChar::from_short(682)); // global.get 0
8269        u32::encode_dc_mixed(&0, &mut prog)?;
8270        prog.push_char(DcChar::from_short(712)); // i32.const -25
8271        i32::encode_dc_mixed(&-25, &mut prog)?;
8272        prog.push_char(DcChar::from_short(753)); // i32.add
8273        prog.push_char(DcChar::from_short(261));
8274        prog.push_char(DcChar::from_short(515));
8275
8276        prog.push_char(DcChar::from_short(560));
8277        prog.push_char(DcChar::from_short(1928));
8278
8279        let prog_wasm = dcmstring_to_wasm(&prog)?;
8280        let prog_mod = Module::parse_bytes(&prog_wasm)
8281            .map_err(|e| anyhow!("tinywasm parse failed: {e:?}"))?;
8282        let mut prog_store = Store::default();
8283        let prog_inst = prog_mod
8284            .instantiate(&mut prog_store, None)
8285            .map_err(|e| anyhow!("tinywasm instantiate failed: {e:?}"))?;
8286        let compute_fn = prog_inst
8287            .exported_func::<(), i32>(&prog_store, "compute")
8288            .map_err(|e| anyhow!("exported_func compute failed: {e:?}"))?;
8289        assert_eq!(compute_fn.call(&mut prog_store, ()).unwrap(), 75);
8290
8291        Ok(())
8292    }
8293
8294    #[crate::ctb_test]
8295    fn test_dc_wasm_session_pure_conversion_and_stage1_evaluator() -> Result<()>
8296    {
8297        use crate::{
8298            DcExpressionEvaluator, DefaultDcExpressionEvaluator,
8299            SyntaxRuntimeResolver, ValueRequirement,
8300        };
8301        use ctb_storage_minimal::shorthand::DcShorthand;
8302
8303        let i32_dc = i32_type_dc();
8304
8305        // Build a standalone `wasm_routine` `() -> i32` that performs a zero-copy slice:
8306        // skips the first 4-byte short Dc token at `input_ptr` (`0..4`):
8307        //   output_ptr (addr 8) = i32.load(0) + 4
8308        //   output_len (addr 12) = i32.load(4) - 4
8309        //   return 0 (WasmStepStatus::Complete)
8310        let mut routine_doc = DcMstring::new();
8311        routine_doc.push_char(DcChar::from_short(260)); // Begin literal value
8312        routine_doc.push_char(DcChar::from_short(262)); // Begin type definition
8313        routine_doc.push_char(DcChar::from_short(280)); // Routine
8314        routine_doc.push_char(i32_dc); // returnType = i32
8315        routine_doc.push_char(DcChar::from_short(263)); // End type definition
8316
8317        // addr 8 = i32.load(0) + 4
8318        routine_doc.push_char(DcChar::from_short(712)); // i32.const 8
8319        i32::encode_dc_mixed(&8, &mut routine_doc)?;
8320        routine_doc.push_char(DcChar::from_short(712)); // i32.const 0
8321        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8322        routine_doc.push_char(DcChar::from_short(687)); // i32.load (memidx=0, align=2, offset=0)
8323        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8324        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8325        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8326        routine_doc.push_char(DcChar::from_short(712)); // i32.const 4
8327        i32::encode_dc_mixed(&4, &mut routine_doc)?;
8328        routine_doc.push_char(DcChar::from_short(753)); // i32.add
8329        routine_doc.push_char(DcChar::from_short(701)); // i32.store (memidx=0, align=2, offset=0)
8330        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8331        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8332        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8333
8334        // addr 12 = i32.load(4) - 4
8335        routine_doc.push_char(DcChar::from_short(712)); // i32.const 12
8336        i32::encode_dc_mixed(&12, &mut routine_doc)?;
8337        routine_doc.push_char(DcChar::from_short(712)); // i32.const 4
8338        i32::encode_dc_mixed(&4, &mut routine_doc)?;
8339        routine_doc.push_char(DcChar::from_short(687)); // i32.load
8340        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8341        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8342        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8343        routine_doc.push_char(DcChar::from_short(712)); // i32.const 4
8344        i32::encode_dc_mixed(&4, &mut routine_doc)?;
8345        routine_doc.push_char(DcChar::from_short(754)); // i32.sub
8346        routine_doc.push_char(DcChar::from_short(701)); // i32.store
8347        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8348        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8349        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8350
8351        // return 0 (Complete)
8352        routine_doc.push_char(DcChar::from_short(712)); // i32.const 0
8353        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8354        routine_doc.push_char(DcChar::from_short(261)); // End literal value
8355
8356        // Input: [Dc 256,Dc 517] -> stripping the first 2-byte short Dc (256) yields [Dc 517]
8357        let mut input = DcMstring::new();
8358        input.push_char(DcChar::from_short(256));
8359        input.push_char(DcChar::from_short(517));
8360
8361        let output = run_dc_wasm_pure_conversion(&routine_doc, &input)?;
8362        let out_str = output.to_dc_string()?;
8363        let out_chars: Vec<DcChar> = out_str.chars().collect();
8364        assert_eq!(out_chars, vec![DcChar::from_short(517)]);
8365
8366        // Register this `.WASM` routine on a custom token in `SyntaxRuntimeResolver` and verify
8367        // Stage 1 evaluation in `DefaultDcExpressionEvaluator`.
8368        let mut resolver =
8369            SyntaxRuntimeResolver::new(default_syntax_resolver().clone());
8370        let routine_shorthands: Vec<DcShorthand> = routine_doc
8371            .to_dc_string()?
8372            .chars()
8373            .map(|ch| DcShorthand::from_global_id(ch.to_u128()))
8374            .collect();
8375        let custom_op = DcChar::from_short(3916);
8376        resolver.register_wasm_definition(
8377            custom_op.to_u128(),
8378            routine_shorthands.clone(),
8379        );
8380
8381        let evaluator = DefaultDcExpressionEvaluator;
8382        let call_tokens = vec![custom_op, DcChar::from_short(517)];
8383        let spliced = evaluator
8384            .eval_stream_splice(&call_tokens, &resolver)?
8385            .expect("Expected WASM splice evaluation");
8386        assert_eq!(spliced, vec![DcChar::from_short(517)]);
8387        assert!(resolver.is_splice_trigger_token(custom_op.to_u128()));
8388
8389        let say = DcChar::from_short(256);
8390        let say_alias = DcChar::from_short(3917);
8391        resolver.register_equivalence(say_alias.to_u128(), say.to_u128());
8392        resolver.register_wasm_definition(say.to_u128(), routine_shorthands);
8393        for token in [say, say_alias] {
8394            assert!(resolver.is_splice_trigger_token(token.to_u128()));
8395            let call = [token, DcChar::from_short(517)];
8396            assert_eq!(
8397                evaluator.eval_stream_splice(&call, &resolver)?
8398                    .context("Missing graph-defined output")?,
8399                vec![DcChar::from_short(517)]
8400            );
8401            let result = evaluator.eval_expression_for_requirement(
8402                &call,
8403                &ValueRequirement::NamedConstruct {
8404                    name: "boolean", subtype: None,
8405                },
8406                &resolver,
8407            )?.context("Missing graph-defined result")?;
8408            let crate::DcEvaluatedValue::Document(document) = result else {
8409                bail!("Expected an evaluated document result");
8410            };
8411            assert_eq!(document.to_dc_string()?.chars().collect::<Vec<_>>(),
8412                vec![DcChar::from_short(517)]);
8413        }
8414
8415        let eval_val = evaluator
8416            .eval_expression_for_requirement(
8417                &call_tokens,
8418                &ValueRequirement::NamedConstruct {
8419                    name: "boolean",
8420                    subtype: None,
8421                },
8422                &resolver,
8423            )?
8424            .expect("Expected WASM requirement evaluation");
8425        let crate::DcEvaluatedValue::Document(doc) = eval_val else {
8426            bail!("Expected DcEvaluatedValue::Document");
8427        };
8428        assert_eq!(
8429            doc.to_dc_string()?.chars().collect::<Vec<_>>(),
8430            vec![DcChar::from_short(517)]
8431        );
8432
8433        Ok(())
8434    }
8435
8436    #[crate::ctb_test]
8437    fn test_dc_wasm_session_yield_frame_and_capability_rejection() -> Result<()>
8438    {
8439        let i32_dc = i32_type_dc();
8440
8441        // Build a routine that checks a counter at address 64:
8442        // - If mem[64] == 0: sets mem[64] = 1, points output at input_ptr..input_ptr+input_len, returns 1 (YieldFrame)
8443        // - Else: points output at input_ptr..input_ptr+input_len, returns 0 (Complete)
8444        let mut routine_doc = DcMstring::new();
8445        routine_doc.push_char(DcChar::from_short(260));
8446        routine_doc.push_char(DcChar::from_short(262));
8447        routine_doc.push_char(DcChar::from_short(280));
8448        routine_doc.push_char(i32_dc);
8449        routine_doc.push_char(DcChar::from_short(263));
8450
8451        // Copy input_ptr (0) -> output_ptr (8) and input_len (4) -> output_len (12)
8452        routine_doc.push_char(DcChar::from_short(712));
8453        i32::encode_dc_mixed(&8, &mut routine_doc)?;
8454        routine_doc.push_char(DcChar::from_short(712));
8455        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8456        routine_doc.push_char(DcChar::from_short(687));
8457        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8458        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8459        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8460        routine_doc.push_char(DcChar::from_short(701));
8461        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8462        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8463        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8464
8465        routine_doc.push_char(DcChar::from_short(712));
8466        i32::encode_dc_mixed(&12, &mut routine_doc)?;
8467        routine_doc.push_char(DcChar::from_short(712));
8468        i32::encode_dc_mixed(&4, &mut routine_doc)?;
8469        routine_doc.push_char(DcChar::from_short(687));
8470        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8471        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8472        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8473        routine_doc.push_char(DcChar::from_short(701));
8474        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8475        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8476        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8477
8478        // Check mem[64] == 0 (`i32.eqz` = Dc 716 = 647 + 0x45)
8479        routine_doc.push_char(DcChar::from_short(712));
8480        i32::encode_dc_mixed(&64, &mut routine_doc)?;
8481        routine_doc.push_char(DcChar::from_short(687));
8482        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8483        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8484        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8485        routine_doc.push_char(DcChar::from_short(716)); // i32.eqz
8486        routine_doc.push_char(DcChar::from_short(651)); // WASM if (result i32)
8487        routine_doc.push_char(i32_dc);
8488        // then: mem[64] = 1; return 1 (YieldFrame)
8489        routine_doc.push_char(DcChar::from_short(712));
8490        i32::encode_dc_mixed(&64, &mut routine_doc)?;
8491        routine_doc.push_char(DcChar::from_short(712));
8492        i32::encode_dc_mixed(&1, &mut routine_doc)?;
8493        routine_doc.push_char(DcChar::from_short(701));
8494        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8495        u32::encode_dc_mixed(&2, &mut routine_doc)?;
8496        u32::encode_dc_mixed(&0, &mut routine_doc)?;
8497        routine_doc.push_char(DcChar::from_short(712));
8498        i32::encode_dc_mixed(&1, &mut routine_doc)?;
8499        routine_doc.push_char(DcChar::from_short(652)); // WASM else
8500        // else: return 0 (Complete)
8501        routine_doc.push_char(DcChar::from_short(712));
8502        i32::encode_dc_mixed(&0, &mut routine_doc)?;
8503        routine_doc.push_char(DcChar::from_short(658)); // WASM end
8504        routine_doc.push_char(DcChar::from_short(261));
8505
8506        let mut input = DcMstring::new();
8507        input.push_char(DcChar::from_short(517));
8508
8509        // Pure conversion concatenates the yielded frame and final Complete output: [517, 517]
8510        let combined = run_dc_wasm_pure_conversion(&routine_doc, &input)?;
8511        let chars: Vec<DcChar> = combined.to_dc_string()?.chars().collect();
8512        assert_eq!(
8513            chars,
8514            vec![DcChar::from_short(517), DcChar::from_short(517)]
8515        );
8516
8517        // Capability request (status = 2) must be rejected by pure conversion
8518        let mut cap_routine = DcMstring::new();
8519        cap_routine.push_char(DcChar::from_short(260));
8520        cap_routine.push_char(DcChar::from_short(262));
8521        cap_routine.push_char(DcChar::from_short(280));
8522        cap_routine.push_char(i32_dc);
8523        cap_routine.push_char(DcChar::from_short(263));
8524        cap_routine.push_char(DcChar::from_short(712)); // i32.const 2 (RequestCapability)
8525        i32::encode_dc_mixed(&2, &mut cap_routine)?;
8526        cap_routine.push_char(DcChar::from_short(261));
8527
8528        assert!(run_dc_wasm_pure_conversion(&cap_routine, &input).is_err());
8529        Ok(())
8530    }
8531
8532    #[crate::ctb_test]
8533    fn test_gate1_wasm_transitive_snapshot_isolation_and_supersedence()
8534    -> Result<()> {
8535        use ctb_formats_dcdata::ctbnbdl::LedgerNode;
8536        use ctb_formats_dcdata::seed_graph::SeedGraphIndex;
8537        use ctb_storage_minimal::shorthand::DcShorthand;
8538        use std::sync::Arc;
8539
8540        let i32_dc = i32_type_dc();
8541        // Build two WASM routines for `run_graph_wasm_tokens_on_dc_slice`:
8542        // - `routine_v1` sets `output_ptr = mem[0]` and `output_len = 0` (emits empty output), returning 0 (`Complete`).
8543        // - `routine_v2_doc` copies `input_ptr (mem[0]) -> output_ptr (mem[8])` and `input_len (mem[4]) -> output_len (mem[12])`
8544        //   (echoing the input slice `[518]`), returning 0 (`Complete`).
8545        let mut routine_v1 = DcMstring::new();
8546        routine_v1.push_char(DcChar::from_short(260));
8547        routine_v1.push_char(DcChar::from_short(262));
8548        routine_v1.push_char(DcChar::from_short(280));
8549        routine_v1.push_char(i32_dc);
8550        routine_v1.push_char(DcChar::from_short(263));
8551        // mem[8] = mem[0]
8552        routine_v1.push_char(DcChar::from_short(712));
8553        i32::encode_dc_mixed(&8, &mut routine_v1)?;
8554        routine_v1.push_char(DcChar::from_short(712));
8555        i32::encode_dc_mixed(&0, &mut routine_v1)?;
8556        routine_v1.push_char(DcChar::from_short(687));
8557        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8558        u32::encode_dc_mixed(&2, &mut routine_v1)?;
8559        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8560        routine_v1.push_char(DcChar::from_short(701));
8561        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8562        u32::encode_dc_mixed(&2, &mut routine_v1)?;
8563        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8564        // mem[12] = 0
8565        routine_v1.push_char(DcChar::from_short(712));
8566        i32::encode_dc_mixed(&12, &mut routine_v1)?;
8567        routine_v1.push_char(DcChar::from_short(712));
8568        i32::encode_dc_mixed(&0, &mut routine_v1)?;
8569        routine_v1.push_char(DcChar::from_short(701));
8570        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8571        u32::encode_dc_mixed(&2, &mut routine_v1)?;
8572        u32::encode_dc_mixed(&0, &mut routine_v1)?;
8573        // return 0 (Complete)
8574        routine_v1.push_char(DcChar::from_short(712));
8575        i32::encode_dc_mixed(&0, &mut routine_v1)?;
8576        routine_v1.push_char(DcChar::from_short(261));
8577
8578        let v1_shorthands: Vec<DcShorthand> = routine_v1
8579            .to_dc_string()?
8580            .chars()
8581            .map(|c| DcShorthand::from_global_id(c.to_u128()))
8582            .collect();
8583
8584        let mut routine_v2_doc = DcMstring::new();
8585        routine_v2_doc.push_char(DcChar::from_short(260));
8586        routine_v2_doc.push_char(DcChar::from_short(262));
8587        routine_v2_doc.push_char(DcChar::from_short(280));
8588        routine_v2_doc.push_char(i32_dc);
8589        routine_v2_doc.push_char(DcChar::from_short(263));
8590        // mem[8] = mem[0]
8591        routine_v2_doc.push_char(DcChar::from_short(712));
8592        i32::encode_dc_mixed(&8, &mut routine_v2_doc)?;
8593        routine_v2_doc.push_char(DcChar::from_short(712));
8594        i32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8595        routine_v2_doc.push_char(DcChar::from_short(687));
8596        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8597        u32::encode_dc_mixed(&2, &mut routine_v2_doc)?;
8598        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8599        routine_v2_doc.push_char(DcChar::from_short(701));
8600        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8601        u32::encode_dc_mixed(&2, &mut routine_v2_doc)?;
8602        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8603        // mem[12] = mem[4]
8604        routine_v2_doc.push_char(DcChar::from_short(712));
8605        i32::encode_dc_mixed(&12, &mut routine_v2_doc)?;
8606        routine_v2_doc.push_char(DcChar::from_short(712));
8607        i32::encode_dc_mixed(&4, &mut routine_v2_doc)?;
8608        routine_v2_doc.push_char(DcChar::from_short(687));
8609        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8610        u32::encode_dc_mixed(&2, &mut routine_v2_doc)?;
8611        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8612        routine_v2_doc.push_char(DcChar::from_short(701));
8613        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8614        u32::encode_dc_mixed(&2, &mut routine_v2_doc)?;
8615        u32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8616        // return 0 (Complete)
8617        routine_v2_doc.push_char(DcChar::from_short(712));
8618        i32::encode_dc_mixed(&0, &mut routine_v2_doc)?;
8619        routine_v2_doc.push_char(DcChar::from_short(261));
8620
8621        let v2_shorthands: Vec<DcShorthand> = routine_v2_doc
8622            .to_dc_string()?
8623            .chars()
8624            .map(|c| DcShorthand::from_global_id(c.to_u128()))
8625            .collect();
8626
8627        // System node IDs:
8628        // - `node_c_v1` (8_589_934_600): routine v1 (emits 517)
8629        // - `node_b` (8_589_934_601): transitive wrapper pointing to `Long(node_c_v1)`
8630        // - `node_a` (8_589_934_602): outer wrapper pointing to `Long(node_b)`
8631        // - `node_c_v2` (8_589_934_603): routine v2 (emits 518)
8632        // - `node_supersede_v1` (8_589_934_604): `591 l<node_c_v2> l<node_c_v1>` (`Supersedes`)
8633        // - `node_retracted` (8_589_934_605): routine v1
8634        // - `pin_id` (8_589_934_606): `592 615 l<node_retracted>` (`Retracts`)
8635        // - `node_c_v3` (8_589_934_607): routine v1 AFTER `pin_id`
8636        // - `node_supersede_v2` (8_589_934_608): `591 l<node_c_v3> l<node_c_v2>` AFTER `pin_id`
8637        let node_c_v1 = 8_589_934_600_u128;
8638        let node_b = 8_589_934_601_u128;
8639        let node_a = 8_589_934_602_u128;
8640        let node_c_v2 = 8_589_934_603_u128;
8641        let node_supersede_v1 = 8_589_934_604_u128;
8642        let node_retracted = 8_589_934_605_u128;
8643        let pin_id = 8_589_934_606_u128;
8644        let node_c_v3 = 8_589_934_607_u128;
8645        let node_supersede_v2 = 8_589_934_608_u128;
8646
8647        let nodes = vec![
8648            LedgerNode {
8649                id: node_c_v1,
8650                tokens: v1_shorthands.clone(),
8651                comment: String::new(),
8652                created_ns: None,
8653            },
8654            LedgerNode {
8655                id: node_b,
8656                tokens: vec![DcShorthand::Long(node_c_v1)],
8657                comment: String::new(),
8658                created_ns: None,
8659            },
8660            LedgerNode {
8661                id: node_a,
8662                tokens: vec![DcShorthand::Long(node_b)],
8663                comment: String::new(),
8664                created_ns: None,
8665            },
8666            LedgerNode {
8667                id: node_c_v2,
8668                tokens: v2_shorthands,
8669                comment: String::new(),
8670                created_ns: None,
8671            },
8672            LedgerNode {
8673                id: node_supersede_v1,
8674                tokens: vec![
8675                    DcShorthand::Short(591),
8676                    DcShorthand::Long(node_c_v2),
8677                    DcShorthand::Long(node_c_v1),
8678                ],
8679                comment: String::new(),
8680                created_ns: None,
8681            },
8682            LedgerNode {
8683                id: node_retracted,
8684                tokens: v1_shorthands.clone(),
8685                comment: String::new(),
8686                created_ns: None,
8687            },
8688            LedgerNode {
8689                id: pin_id,
8690                tokens: vec![
8691                    DcShorthand::Short(592),
8692                    DcShorthand::Short(615),
8693                    DcShorthand::Long(node_retracted),
8694                ],
8695                comment: String::new(),
8696                created_ns: None,
8697            },
8698            LedgerNode {
8699                id: node_c_v3,
8700                tokens: v1_shorthands,
8701                comment: String::new(),
8702                created_ns: None,
8703            },
8704            LedgerNode {
8705                id: node_supersede_v2,
8706                tokens: vec![
8707                    DcShorthand::Short(591),
8708                    DcShorthand::Long(node_c_v3),
8709                    DcShorthand::Long(node_c_v2),
8710                ],
8711                comment: String::new(),
8712                created_ns: None,
8713            },
8714        ];
8715
8716        let sg_pinned = Arc::new(SeedGraphIndex::from_nodes_at_most_recent(
8717            nodes,
8718            pin_id,
8719        ));
8720        let mut res_pinned =
8721            (**ctb_formats_dcdata::syntax::default_syntax_resolver()).clone();
8722        res_pinned.set_seed_graph(sg_pinned);
8723
8724        // 1. Transitive expansion `node_a -> node_b -> node_c_v1` resolves `node_c_v1`
8725        //    through `Dc 591 "Supersedes"` to `node_c_v2` (emitting 518) while ignoring
8726        //    `node_c_v3 > pin_id`.
8727        let input_slice = [DcChar::from_short(518)];
8728        let out = run_graph_wasm_tokens_on_dc_slice(
8729            &[DcShorthand::Long(node_a)],
8730            &input_slice,
8731            &res_pinned,
8732        )?;
8733        let out_chars: Vec<DcChar> = out.to_dc_string()?.chars().collect();
8734        assert_eq!(out_chars, vec![DcChar::from_short(518)]);
8735
8736        // 2. Referencing `node_c_v3` (`> pin_id`) fails with an explicit snapshot error.
8737        let err_future = run_graph_wasm_tokens_on_dc_slice(
8738            &[DcShorthand::Long(node_c_v3)],
8739            &[],
8740            &res_pinned,
8741        )
8742        .expect_err("Reference to node newer than pin must fail");
8743        assert!(
8744            err_future.to_string().contains(&format!("l{node_c_v3}"))
8745                && err_future.to_string().contains(&format!("l{pin_id}")),
8746            "Unexpected error for out-of-snapshot node: {err_future}"
8747        );
8748
8749        // 3. Referencing `node_retracted` (retracted at `pin_id`) fails with an explicit error.
8750        let err_retracted = run_graph_wasm_tokens_on_dc_slice(
8751            &[DcShorthand::Long(node_retracted)],
8752            &[],
8753            &res_pinned,
8754        )
8755        .expect_err("Reference to retracted node must fail");
8756        assert!(
8757            err_retracted
8758                .to_string()
8759                .contains(&format!("l{node_retracted}")),
8760            "Unexpected error for retracted node: {err_retracted}"
8761        );
8762
8763        // 4. Referencing unsupported graph blocks fails with an explicit unsupported-block error.
8764        for bad_block_id in [4_294_967_296_u128, 12_884_901_888_u128] {
8765            let err_block = run_graph_wasm_tokens_on_dc_slice(
8766                &[DcShorthand::Long(bad_block_id)],
8767                &[],
8768                &res_pinned,
8769            )
8770            .expect_err("Reference to unsupported block must fail");
8771            assert!(
8772                err_block.to_string().contains("unsupported graph block"),
8773                "Unexpected error for unsupported block {bad_block_id}: {err_block}"
8774            );
8775        }
8776
8777        let chain_start =
8778            ctb_storage_minimal::global_graph_layout::SYSTEM_REGION_START;
8779        let mut chain_nodes = Vec::new();
8780        for index in 0..4096_u128 {
8781            chain_nodes.push(LedgerNode {
8782                id: chain_start.saturating_add(index),
8783                tokens: if index == 4095 {
8784                    vec![DcShorthand::Unicode(65)]
8785                } else {
8786                    vec![DcShorthand::Long(
8787                        chain_start.saturating_add(index).saturating_add(1),
8788                    )]
8789                },
8790                comment: String::new(),
8791                created_ns: None,
8792            });
8793        }
8794        let mut chain_resolver = res_pinned.clone();
8795        chain_resolver.set_seed_graph(Arc::new(SeedGraphIndex::from_nodes(
8796            chain_nodes,
8797        )));
8798        let mut chain_output = DcMstring::new();
8799        expand_graph_wasm_shorthands(
8800            &[DcShorthand::Long(chain_start)],
8801            &chain_resolver,
8802            &mut chain_output,
8803        )?;
8804        assert_eq!(
8805            chain_output.to_dc_string()?.chars().collect::<Vec<_>>(),
8806            vec![DcChar::from_u128(65)],
8807        );
8808        assert!(
8809            expand_graph_wasm_shorthands(
8810                &[DcShorthand::Short(255)],
8811                &chain_resolver,
8812                &mut DcMstring::new(),
8813            )
8814            .is_err()
8815        );
8816
8817        Ok(())
8818    }
8819
8820    #[crate::ctb_test]
8821    fn test_gate2_wasm_intra_step_instruction_compute_quota_stops_tight_loop()
8822    -> Result<()> {
8823        let looping_start = [
8824            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
8825            0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
8826            0x03, 0x02, 0x01, 0x00,
8827            0x05, 0x03, 0x01, 0x00, 0x01,
8828            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
8829            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
8830            0x08, 0x01, 0x00,
8831            0x0a, 0x09, 0x01, 0x07, 0x00, 0x03, 0x40, 0x0c, 0x00, 0x0b, 0x0b,
8832        ];
8833        let start_error = DcWasmSession::from_wasm_bytes_with_limits(
8834            &looping_start,
8835            &DcMstring::new(),
8836            None,
8837            DcWasmResourceLimits::default().with_max_instructions_per_step(400),
8838        ).err().expect("Looping start function must exhaust bootstrap compute_quota");
8839        assert_eq!(
8840            start_error.downcast_ref::<WasmResourceInterruption>(),
8841            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 400 }),
8842        );
8843        let i32_dc = i32_type_dc();
8844        // Build a tight infinite loop inside a single `step()` call:
8845        // `loop (empty blocktype: Dc 316 = 0x40) br 0 end i32.const 0`
8846        let mut loop_doc = DcMstring::new();
8847        loop_doc.push_char(DcChar::from_short(260));
8848        loop_doc.push_char(DcChar::from_short(262));
8849        loop_doc.push_char(DcChar::from_short(280));
8850        loop_doc.push_char(i32_dc);
8851        loop_doc.push_char(DcChar::from_short(263));
8852        loop_doc.push_char(DcChar::from_short(650)); // WASM loop (0x03)
8853        loop_doc.push_char(DcChar::from_short(316)); // empty blocktype (Dc 316 -> 0x40)
8854        loop_doc.push_char(DcChar::from_short(659)); // WASM br (0x0C)
8855        u32::encode_dc_mixed(&0, &mut loop_doc)?;
8856        loop_doc.push_char(DcChar::from_short(658)); // WASM end (0x0B)
8857        loop_doc.push_char(DcChar::from_short(712)); // WASM i32.const 0
8858        i32::encode_dc_mixed(&0, &mut loop_doc)?;
8859        loop_doc.push_char(DcChar::from_short(261));
8860
8861        let input = DcMstring::new();
8862        let limits =
8863            DcWasmResourceLimits::default().with_max_instructions_per_step(400);
8864        let mut session = DcWasmSession::from_dc_wasm(&loop_doc, &input, None)?
8865            .with_resource_limits(limits);
8866
8867        let err = session
8868            .step()
8869            .expect_err("Tight infinite WASM loop must exhaust compute quota");
8870        let interruption = err
8871            .downcast_ref::<WasmResourceInterruption>()
8872            .expect("Error must downcast to WasmResourceInterruption");
8873        assert_eq!(
8874            interruption,
8875            &WasmResourceInterruption::ComputeQuotaExhausted { limit: 400 }
8876        );
8877        assert_eq!(
8878            session.last_resource_interruption(),
8879            Some(&WasmResourceInterruption::ComputeQuotaExhausted {
8880                limit: 400
8881            })
8882        );
8883        assert_eq!(session.last_step_instructions(), 400);
8884        Ok(())
8885    }
8886
8887    #[crate::ctb_test]
8888    fn test_gate2_wasm_start_section_runs_once_without_export_conventions()
8889    -> Result<()> {
8890        for has_start in [false, true] {
8891            let mut wasm = vec![
8892                0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
8893                0x01, 0x08, 0x02, 0x60, 0x00, 0x00, 0x60, 0x00, 0x01, 0x7f,
8894                0x03, 0x03, 0x02, 0x00, 0x01,
8895                0x05, 0x03, 0x01, 0x00, 0x01,
8896                0x06, 0x06, 0x01, 0x7f, 0x01, 0x41, 0x00, 0x0b,
8897                0x07, 0x1a, 0x03,
8898                0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
8899                0x04, b'm', b'a', b'i', b'n', 0x00, 0x01,
8900                0x06, b'_', b's', b't', b'a', b'r', b't', 0x00, 0x00,
8901            ];
8902            if has_start {
8903                wasm.extend_from_slice(&[0x08, 0x01, 0x00]);
8904            }
8905            wasm.extend_from_slice(&[
8906                0x0a, 0x19, 0x02,
8907                0x09, 0x00, 0x23, 0x00, 0x41, 0x01, 0x6a, 0x24, 0x00, 0x0b,
8908                0x0d, 0x00, 0x23, 0x00, 0x41,
8909            ]);
8910            wasm.push(u8::from(has_start));
8911            wasm.extend_from_slice(&[
8912                0x47, 0x04, 0x40, 0x00, 0x0b, 0x41, 0x00, 0x0b,
8913            ]);
8914            let mut session = DcWasmSession::from_wasm_bytes(
8915                &wasm, &DcMstring::new(), None,
8916            )?;
8917            assert!(matches!(session.step()?, WasmStepOutcome::Complete(_)));
8918        }
8919        Ok(())
8920    }
8921
8922    #[crate::ctb_test]
8923    fn test_gate2_wasm_memory_page_cap_on_provide_input_and_memory_grow()
8924    -> Result<()> {
8925        let i32_dc = i32_type_dc();
8926        // Routine that calls `memory.grow(4)` (Dc 711 = 0x40 `memory.grow 0x00`), stores the
8927        // returned page count (`-1` when capped) into `mem[64]`, and returns `0` (`Complete`).
8928        let mut grow_doc = DcMstring::new();
8929        grow_doc.push_char(DcChar::from_short(260));
8930        grow_doc.push_char(DcChar::from_short(262));
8931        grow_doc.push_char(DcChar::from_short(280));
8932        grow_doc.push_char(i32_dc);
8933        grow_doc.push_char(DcChar::from_short(263));
8934        // i32.const 64 (destination address for memory.grow result)
8935        grow_doc.push_char(DcChar::from_short(712));
8936        i32::encode_dc_mixed(&64, &mut grow_doc)?;
8937        // i32.const 4 (request 4 additional pages)
8938        grow_doc.push_char(DcChar::from_short(712));
8939        i32::encode_dc_mixed(&4, &mut grow_doc)?;
8940        // memory.grow 0 (Dc 711 = 647 + 0x40)
8941        grow_doc.push_char(DcChar::from_short(711));
8942        u8::encode_dc_mixed(&0, &mut grow_doc)?;
8943        // i32.store mem[64] = grow_result
8944        grow_doc.push_char(DcChar::from_short(701));
8945        u32::encode_dc_mixed(&0, &mut grow_doc)?;
8946        u32::encode_dc_mixed(&2, &mut grow_doc)?;
8947        u32::encode_dc_mixed(&0, &mut grow_doc)?;
8948        // Check that mem[64] == -1; if not, trap via unreachable (Dc 647)
8949        grow_doc.push_char(DcChar::from_short(712));
8950        i32::encode_dc_mixed(&64, &mut grow_doc)?;
8951        grow_doc.push_char(DcChar::from_short(687));
8952        u32::encode_dc_mixed(&0, &mut grow_doc)?;
8953        u32::encode_dc_mixed(&2, &mut grow_doc)?;
8954        u32::encode_dc_mixed(&0, &mut grow_doc)?;
8955        grow_doc.push_char(DcChar::from_short(712));
8956        i32::encode_dc_mixed(&-1, &mut grow_doc)?;
8957        grow_doc.push_char(DcChar::from_short(718)); // i32.ne (647 + 0x47)
8958        grow_doc.push_char(DcChar::from_short(651)); // if (empty blocktype: Dc 316 -> 0x40)
8959        grow_doc.push_char(DcChar::from_short(316));
8960        grow_doc.push_char(DcChar::from_short(647)); // unreachable
8961        grow_doc.push_char(DcChar::from_short(658)); // end
8962        // return 0 (Complete)
8963        grow_doc.push_char(DcChar::from_short(712));
8964        i32::encode_dc_mixed(&0, &mut grow_doc)?;
8965        grow_doc.push_char(DcChar::from_short(261));
8966
8967        let input = DcMstring::new();
8968        let limits = DcWasmResourceLimits::default().with_max_memory_pages(2);
8969        let mut session = DcWasmSession::from_dc_wasm(&grow_doc, &input, None)?
8970            .with_resource_limits(limits);
8971
8972        // 1. WASM `memory.grow(4)` is denied (returns -1) when max_memory_pages == 2
8973        let outcome = session.step()?;
8974        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
8975        assert_eq!(session.current_memory_pages()?, 1);
8976
8977        // 2. `provide_input` with an input requiring > 2 pages (128 KiB) fails with `MemoryLimitExceeded`
8978        let mut large_input = DcMstring::new();
8979        large_input.push_str(&"A".repeat(60_000));
8980        let err = session
8981            .provide_input(&large_input)
8982            .expect_err("Input exceeding max_memory_pages must be rejected");
8983        let interruption = err
8984            .downcast_ref::<WasmResourceInterruption>()
8985            .expect("Must downcast to WasmResourceInterruption");
8986        assert!(matches!(
8987            interruption,
8988            WasmResourceInterruption::MemoryLimitExceeded { max_pages: 2, .. }
8989        ));
8990        session.set_resource_limits(limits.with_max_memory_pages(0));
8991        let err = session.step().expect_err("Lowering the cap must reject existing over-budget memory");
8992        assert!(matches!(
8993            err.downcast_ref::<WasmResourceInterruption>(),
8994            Some(WasmResourceInterruption::MemoryLimitExceeded {
8995                requested_pages: 1, max_pages: 0,
8996            })
8997        ));
8998        Ok(())
8999    }
9000
9001    #[crate::ctb_test]
9002    fn test_gate2_wasm_step_output_slice_and_cumulative_session_output_budgets()
9003    -> Result<()> {
9004        let i32_dc = i32_type_dc();
9005        // Routine that echoes its input mailbox (0..8) to output mailbox (8..16) and returns 1 (`YieldFrame`).
9006        let mut yield_echo_doc = DcMstring::new();
9007        yield_echo_doc.push_char(DcChar::from_short(260));
9008        yield_echo_doc.push_char(DcChar::from_short(262));
9009        yield_echo_doc.push_char(DcChar::from_short(280));
9010        yield_echo_doc.push_char(i32_dc);
9011        yield_echo_doc.push_char(DcChar::from_short(263));
9012        // mem[8] = mem[0]
9013        yield_echo_doc.push_char(DcChar::from_short(712));
9014        i32::encode_dc_mixed(&8, &mut yield_echo_doc)?;
9015        yield_echo_doc.push_char(DcChar::from_short(712));
9016        i32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9017        yield_echo_doc.push_char(DcChar::from_short(687));
9018        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9019        u32::encode_dc_mixed(&2, &mut yield_echo_doc)?;
9020        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9021        yield_echo_doc.push_char(DcChar::from_short(701));
9022        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9023        u32::encode_dc_mixed(&2, &mut yield_echo_doc)?;
9024        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9025        // mem[12] = mem[4]
9026        yield_echo_doc.push_char(DcChar::from_short(712));
9027        i32::encode_dc_mixed(&12, &mut yield_echo_doc)?;
9028        yield_echo_doc.push_char(DcChar::from_short(712));
9029        i32::encode_dc_mixed(&4, &mut yield_echo_doc)?;
9030        yield_echo_doc.push_char(DcChar::from_short(687));
9031        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9032        u32::encode_dc_mixed(&2, &mut yield_echo_doc)?;
9033        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9034        yield_echo_doc.push_char(DcChar::from_short(701));
9035        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9036        u32::encode_dc_mixed(&2, &mut yield_echo_doc)?;
9037        u32::encode_dc_mixed(&0, &mut yield_echo_doc)?;
9038        // return 1 (YieldFrame)
9039        yield_echo_doc.push_char(DcChar::from_short(712));
9040        i32::encode_dc_mixed(&1, &mut yield_echo_doc)?;
9041        yield_echo_doc.push_char(DcChar::from_short(261));
9042
9043        let mut payload = DcMstring::new();
9044        payload.push_str("0123456789"); // 10 bytes of DcTF payload
9045
9046        // 1. Single-step output slice limit (`max_step_output_bytes = 5`)
9047        let step_limits =
9048            DcWasmResourceLimits::default().with_max_step_output_bytes(5);
9049        let mut step_session =
9050            DcWasmSession::from_dc_wasm(&yield_echo_doc, &payload, None)?
9051                .with_resource_limits(step_limits);
9052        let step_err = step_session
9053            .step()
9054            .expect_err("Step output exceeding max_step_output_bytes must fail");
9055        assert_eq!(
9056            step_err.downcast_ref::<WasmResourceInterruption>(),
9057            Some(&WasmResourceInterruption::StepOutputSliceTooLarge {
9058                output_bytes: 10,
9059                max_step_output_bytes: 5,
9060            })
9061        );
9062
9063        // 2. Cumulative session output budget (`max_step_output_bytes = 16`, `max_session_output_bytes = 25`)
9064        let session_limits = DcWasmResourceLimits::default()
9065            .with_max_step_output_bytes(16)
9066            .with_max_session_output_bytes(25);
9067        let mut cum_session =
9068            DcWasmSession::from_dc_wasm(&yield_echo_doc, &payload, None)?
9069                .with_resource_limits(session_limits);
9070        assert!(matches!(
9071            cum_session.step()?,
9072            WasmStepOutcome::YieldFrame(_)
9073        ));
9074        assert_eq!(cum_session.cumulative_output_bytes(), 10);
9075        assert!(matches!(
9076            cum_session.step()?,
9077            WasmStepOutcome::YieldFrame(_)
9078        ));
9079        assert_eq!(cum_session.cumulative_output_bytes(), 20);
9080        let cum_err = cum_session.step().expect_err(
9081            "3rd 10-byte step exceeding 25-byte cumulative session limit must fail",
9082        );
9083        assert_eq!(
9084            cum_err.downcast_ref::<WasmResourceInterruption>(),
9085            Some(&WasmResourceInterruption::SessionOutputBudgetExceeded {
9086                cumulative_output_bytes: 30,
9087                max_session_output_bytes: 25,
9088            })
9089        );
9090        Ok(())
9091    }
9092
9093    #[crate::ctb_test]
9094    fn test_gate2_bootstrap_kernel_version_selection_and_validation()
9095    -> Result<()> {
9096        use crate::navigator::{
9097            BootstrapKernelVersion, DcDocumentNavigator, DcProjectionPolicy,
9098        };
9099
9100        assert_eq!(
9101            BootstrapKernelVersion::CURRENT,
9102            BootstrapKernelVersion::V1
9103        );
9104        assert_eq!(BootstrapKernelVersion::V1.as_u32(), 1);
9105        assert_eq!(
9106            BootstrapKernelVersion::try_from_u32(1)?,
9107            BootstrapKernelVersion::V1
9108        );
9109        assert!(BootstrapKernelVersion::try_from_u32(0).is_err());
9110        assert!(BootstrapKernelVersion::try_from_u32(2).is_err());
9111
9112        let policy =
9113            DcProjectionPolicy::strict().try_with_kernel_version_number(1)?;
9114        assert_eq!(policy.kernel_version, BootstrapKernelVersion::V1);
9115        assert!(
9116            DcProjectionPolicy::strict()
9117                .try_with_kernel_version_number(99)
9118                .is_err()
9119        );
9120
9121        let mut doc = DcMstring::new();
9122        doc.push_char(DcChar::from_short(517));
9123        assert!(
9124            DcDocumentNavigator::try_from_mstr_with_kernel_version_number(
9125                &doc, 0
9126            )
9127            .is_err()
9128        );
9129        assert!(
9130            DcDocumentNavigator::try_from_mstr_with_kernel_version_number(
9131                &doc, 2
9132            )
9133            .is_err()
9134        );
9135        let mut nav =
9136            DcDocumentNavigator::try_from_mstr_with_kernel_version_number(
9137                &doc, 1,
9138            )?;
9139        assert_eq!(nav.kernel_version(), BootstrapKernelVersion::V1);
9140        assert_eq!(
9141            nav.select_bootstrap_kernel_version(1)?,
9142            BootstrapKernelVersion::V1
9143        );
9144        assert!(nav.select_bootstrap_kernel_version(2).is_err());
9145
9146        let dc_str = doc.to_dc_string()?;
9147        assert!(
9148            DcDocumentNavigator::try_from_dc_str_with_kernel_version_number(
9149                &dc_str, 99
9150            )
9151            .is_err()
9152        );
9153        let nav_str =
9154            DcDocumentNavigator::try_from_dc_str_with_kernel_version_number(
9155                &dc_str, 1,
9156            )?;
9157        assert_eq!(nav_str.kernel_version(), BootstrapKernelVersion::V1);
9158        Ok(())
9159    }
9160
9161    #[crate::ctb_test]
9162    fn test_gate2_zero_filled_static_data_segment_not_overwritten_by_mailbox_input()
9163    -> Result<()> {
9164        // Build a Dc-WASM program (`Dc 1927`..`Dc 1928`) with a 512-byte ALL-ZERO static data
9165        // segment (`zero_buf`) at offset 32..544, and a `step` routine that verifies
9166        // `mem[32]` and `mem[540]` are still `0` before echoing the input mailbox to output.
9167        let i32_dc = i32_type_dc();
9168        let mut prog = DcMstring::new();
9169        prog.push_char(DcChar::from_short(1927)); // Begin WASM program
9170        prog.push_char(DcChar::from_short(559)); // Begin key-value map
9171        prog.push_char(DcChar::from_short(275)); // keyType = *
9172        prog.push_char(DcChar::from_short(275)); // valType = *
9173
9174        // Pair 1: `zero_buf` -> 512-byte all-zero binary data segment (placed at 32..544)
9175        prog.push_char(DcChar::from_short(514));
9176        prog.push_char(DcChar::from_short(270));
9177        prog.push_str("zero_buf");
9178        prog.push_char(DcChar::from_short(271));
9179        prog.push_char(DcChar::from_short(312));
9180        crate::BinaryPayload(vec![0u8; 512]).encode_dc_mixed(&mut prog)?;
9181        prog.push_char(DcChar::from_short(515));
9182
9183        // Pair 2: `step` -> verifies mem[32] == 0 and mem[540] == 0, then echoes input -> output
9184        prog.push_char(DcChar::from_short(514));
9185        prog.push_char(DcChar::from_short(270));
9186        prog.push_str("step");
9187        prog.push_char(DcChar::from_short(271));
9188        prog.push_char(DcChar::from_short(312));
9189        prog.push_char(DcChar::from_short(260));
9190        prog.push_char(DcChar::from_short(262));
9191        prog.push_char(DcChar::from_short(280));
9192        prog.push_char(i32_dc);
9193        prog.push_char(DcChar::from_short(263));
9194        // If mem[32] != 0, trap (`unreachable`)
9195        prog.push_char(DcChar::from_short(712));
9196        i32::encode_dc_mixed(&32, &mut prog)?;
9197        prog.push_char(DcChar::from_short(687)); // i32.load
9198        u32::encode_dc_mixed(&0, &mut prog)?;
9199        u32::encode_dc_mixed(&2, &mut prog)?;
9200        u32::encode_dc_mixed(&0, &mut prog)?;
9201        prog.push_char(DcChar::from_short(651)); // if (empty blocktype Dc 316)
9202        prog.push_char(DcChar::from_short(316));
9203        prog.push_char(DcChar::from_short(647)); // unreachable
9204        prog.push_char(DcChar::from_short(658));
9205        // If mem[540] != 0, trap (`unreachable`)
9206        prog.push_char(DcChar::from_short(712));
9207        i32::encode_dc_mixed(&540, &mut prog)?;
9208        prog.push_char(DcChar::from_short(687)); // i32.load
9209        u32::encode_dc_mixed(&0, &mut prog)?;
9210        u32::encode_dc_mixed(&2, &mut prog)?;
9211        u32::encode_dc_mixed(&0, &mut prog)?;
9212        prog.push_char(DcChar::from_short(651));
9213        prog.push_char(DcChar::from_short(316));
9214        prog.push_char(DcChar::from_short(647));
9215        prog.push_char(DcChar::from_short(658));
9216        // Echo input mailbox (0..8) -> output mailbox (8..16)
9217        prog.push_char(DcChar::from_short(712));
9218        i32::encode_dc_mixed(&8, &mut prog)?;
9219        prog.push_char(DcChar::from_short(712));
9220        i32::encode_dc_mixed(&0, &mut prog)?;
9221        prog.push_char(DcChar::from_short(687));
9222        u32::encode_dc_mixed(&0, &mut prog)?;
9223        u32::encode_dc_mixed(&2, &mut prog)?;
9224        u32::encode_dc_mixed(&0, &mut prog)?;
9225        prog.push_char(DcChar::from_short(701));
9226        u32::encode_dc_mixed(&0, &mut prog)?;
9227        u32::encode_dc_mixed(&2, &mut prog)?;
9228        u32::encode_dc_mixed(&0, &mut prog)?;
9229        prog.push_char(DcChar::from_short(712));
9230        i32::encode_dc_mixed(&12, &mut prog)?;
9231        prog.push_char(DcChar::from_short(712));
9232        i32::encode_dc_mixed(&4, &mut prog)?;
9233        prog.push_char(DcChar::from_short(687));
9234        u32::encode_dc_mixed(&0, &mut prog)?;
9235        u32::encode_dc_mixed(&2, &mut prog)?;
9236        u32::encode_dc_mixed(&0, &mut prog)?;
9237        prog.push_char(DcChar::from_short(701));
9238        u32::encode_dc_mixed(&0, &mut prog)?;
9239        u32::encode_dc_mixed(&2, &mut prog)?;
9240        u32::encode_dc_mixed(&0, &mut prog)?;
9241        prog.push_char(DcChar::from_short(712));
9242        i32::encode_dc_mixed(&0, &mut prog)?;
9243        prog.push_char(DcChar::from_short(261));
9244        prog.push_char(DcChar::from_short(515));
9245
9246        prog.push_char(DcChar::from_short(560)); // End key-value map
9247        prog.push_char(DcChar::from_short(1928)); // End WASM program
9248
9249        let mut input = DcMstring::new();
9250        input.push_str("NONZERO_INPUT_PAYLOAD_KEEP_ZERO_BSS_INTACT");
9251
9252        let mut session = DcWasmSession::from_dc_wasm(&prog, &input, None)?;
9253        assert!(
9254            session.base_io_offset() >= 544,
9255            "base_io_offset ({}) must place input mailbox above zero-filled static data segment (32..544)",
9256            session.base_io_offset()
9257        );
9258        let outcome = session.step()?;
9259        assert_eq!(outcome, WasmStepOutcome::Complete(input));
9260        Ok(())
9261    }
9262
9263    #[crate::ctb_test]
9264    fn test_gate2_table_element_cap_and_multi_memory_aggregate_cap()
9265    -> Result<()> {
9266        // 1. Module with a funcref table of initial size 8, calling `table.grow(10)` in `main`
9267        //    and returning `table.grow` result (which must be -1 when `max_table_elements == 8`).
9268        let wasm_with_table_grow = [
9269            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
9270            // Type section: () -> i32
9271            0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f,
9272            // Function section: 1 func of type 0
9273            0x03, 0x02, 0x01, 0x00,
9274            // Table section: 1 table (funcref 0x70, initial 8, no max)
9275            0x04, 0x04, 0x01, 0x70, 0x00, 0x08,
9276            // Memory section: 1 memory of 1 page
9277            0x05, 0x03, 0x01, 0x00, 0x01,
9278            // Export section: "memory" + "main"
9279            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
9280            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
9281            // Code section: ref.null funcref (0xd0 0x70), i32.const 10 (0x41 0x0a),
9282            // table.grow 0 (0xfc 0x0f 0x00), i32.const -1 (0x41 0x7f), i32.ne (0x47),
9283            // if (0x04 0x40) unreachable (0x00) end (0x0b), i32.const 0 (0x41 0x00), end (0x0b)
9284            0x0a, 0x14, 0x01, 0x12, 0x00, 0xd0, 0x70, 0x41, 0x0a, 0xfc, 0x0f, 0x00,
9285            0x41, 0x7f, 0x47, 0x04, 0x40, 0x00, 0x0b, 0x41, 0x00, 0x0b,
9286        ];
9287        let input = DcMstring::new();
9288
9289        // Initial table size 8 > max_table_elements 4 -> fails with TableLimitExceeded
9290        let init_err = DcWasmSession::from_wasm_bytes_with_limits(
9291            &wasm_with_table_grow,
9292            &input,
9293            None,
9294            DcWasmResourceLimits::default().with_max_table_elements(4),
9295        )
9296        .expect_err("Initial table size 8 must exceed max_table_elements = 4");
9297        assert_eq!(
9298            init_err.downcast_ref::<WasmResourceInterruption>(),
9299            Some(&WasmResourceInterruption::TableLimitExceeded {
9300                requested_elements: 8,
9301                max_elements: 4,
9302            })
9303        );
9304
9305        // With max_table_elements = 12, initial table (8) succeeds, and `table.grow(10)`
9306        // is denied (`-1`) so `current_table_elements()` remains 8.
9307        let mut tbl_session = DcWasmSession::from_wasm_bytes_with_limits(
9308            &wasm_with_table_grow,
9309            &input,
9310            None,
9311            DcWasmResourceLimits::default().with_max_table_elements(12),
9312        )?;
9313        assert_eq!(tbl_session.current_table_elements(), 8);
9314        let outcome = tbl_session.step()?;
9315        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
9316        assert_eq!(tbl_session.current_table_elements(), 8);
9317
9318        // 2. Module with two linear memories (1 page each = 2 pages total in store):
9319        //    - Rejected when `max_memory_pages == 1`
9320        //    - Accepted when `max_memory_pages == 2`, and `memory.grow(1)` on memory 0 returns `-1`
9321        let wasm_two_memories = [
9322            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
9323            0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f,
9324            0x03, 0x02, 0x01, 0x00,
9325            // Memory section: 2 memories, each 1 initial page
9326            0x05, 0x05, 0x02, 0x00, 0x01, 0x00, 0x01,
9327            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
9328            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
9329            // Code section: i32.const 1, memory.grow 0 (0x40 0x00), i32.const -1, i32.ne,
9330            // if unreachable end, i32.const 0, end
9331            0x0a, 0x11, 0x01, 0x0f, 0x00, 0x41, 0x01, 0x40, 0x00, 0x41, 0x7f, 0x47,
9332            0x04, 0x40, 0x00, 0x0b, 0x41, 0x00, 0x0b,
9333        ];
9334        let mem_init_err = DcWasmSession::from_wasm_bytes_with_limits(
9335            &wasm_two_memories,
9336            &input,
9337            None,
9338            DcWasmResourceLimits::default().with_max_memory_pages(1),
9339        )
9340        .expect_err("2 memories of 1 page each must exceed store cap of 1 page");
9341        assert_eq!(
9342            mem_init_err.downcast_ref::<WasmResourceInterruption>(),
9343            Some(&WasmResourceInterruption::MemoryLimitExceeded {
9344                requested_pages: 2,
9345                max_pages: 1,
9346            })
9347        );
9348
9349        let mut two_mem_session = DcWasmSession::from_wasm_bytes_with_limits(
9350            &wasm_two_memories,
9351            &input,
9352            None,
9353            DcWasmResourceLimits::default().with_max_memory_pages(2),
9354        )?;
9355        assert_eq!(two_mem_session.current_memory_pages()?, 2);
9356        let outcome = two_mem_session.step()?;
9357        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
9358        assert_eq!(two_mem_session.current_memory_pages()?, 2);
9359        Ok(())
9360    }
9361
9362    #[crate::ctb_test]
9363    fn test_gate2_bootstrap_kernel_v1_conformance_suite() -> Result<()> {
9364        use ctb_formats_dcdata::graph_ledger::LedgerNode;
9365        use ctb_formats_dcdata::seed_graph::{
9366            SeedGraphIndex, compute_effective_inactive_ids,
9367        };
9368        use ctb_formats_dcdata::shorthand::DcShorthand;
9369
9370        // 1. DcTF (`f641`) 1..7-byte and `0xFF` 8..23-byte (`k = 0..=15`) canonical boundaries
9371        //    plus overlong/truncated rejection.
9372        let boundary_cases: &[(u128, usize)] = &[
9373            (0x0, 1),
9374            (0x7F, 1),
9375            (0x80, 2),
9376            (0x7FF, 2),
9377            (0x800, 3),
9378            (0xFFFF, 3),
9379            (0x1_0000, 4),
9380            (0x1F_FFFF, 4),
9381            (0x20_0000, 5),
9382            (0x3FF_FFFF, 5),
9383            (0x400_0000, 6),
9384            (0x7FFF_FFFF, 6),
9385            (0x8000_0000, 7),
9386            (0xF_FFFF_FFFF, 7),
9387            (0x10_0000_0000, 8), // 0xFF tier k = 0 (8 bytes total)
9388            (u128::MAX, 23),     // 0xFF tier k = 15 (23 bytes total)
9389        ];
9390        for &(val, expected_len) in boundary_cases {
9391            let mut buf = [0u8; ctb_formats_dctf::MAX_DCTF_LEN];
9392            let written = ctb_formats_dctf::encode_dctf_buf(&mut buf, val);
9393            assert_eq!(
9394                written, expected_len,
9395                "Canonical DcTF byte length mismatch for {val:#x}"
9396            );
9397            crate::validate_dctf(&buf[..written])?;
9398            let (decoded, consumed) =
9399                ctb_formats_dctf::decode_dctf_buf(&buf[..written]).with_context(
9400                    || format!("decode_dctf_buf failed for {val:#x}"),
9401                )?;
9402            assert_eq!(decoded, val);
9403            assert_eq!(consumed, written);
9404            // Truncating the last byte must fail decoding
9405            assert!(
9406                ctb_formats_dctf::decode_dctf_buf(&buf[..written - 1])
9407                    .is_none(),
9408                "Truncated DcTF sequence for {val:#x} must be rejected"
9409            );
9410            if written > 1 {
9411                assert!(
9412                    crate::validate_dctf(&buf[..written - 1]).is_err(),
9413                    "Truncated multi-byte DcTF sequence for {val:#x} must fail validate_dctf"
9414                );
9415            }
9416        }
9417        // Overlong encodings must be rejected:
9418        // - `0x7F` encoded in 2 bytes (`[0xC1, 0xBF]`)
9419        assert!(ctb_formats_dctf::decode_dctf_buf(&[0xC1, 0xBF]).is_none());
9420        assert!(crate::validate_dctf(&[0xC1, 0xBF]).is_err());
9421        // - `0xFF` tier `k = 0` carrying all-zero payload bits (`<= 0xF_FFFF_FFFF`)
9422        assert!(
9423            ctb_formats_dctf::decode_dctf_buf(&[
9424                0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81
9425            ])
9426            .is_none()
9427        );
9428        assert!(
9429            crate::validate_dctf(&[
9430                0xFF, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x81
9431            ])
9432            .is_err()
9433        );
9434
9435        // 2. `.dcmm` (`DcMixed2` `f643`) binary encapsulation (`type 0`, `type 2`, `type 3`)
9436        let mut doc_inline = DcMstring::new();
9437        crate::BinaryPayload(vec![0xAA; 16]).encode_dc_mixed(&mut doc_inline)?;
9438        crate::validate_dcmst(doc_inline.as_bytes())?;
9439
9440        let mut doc_type3 = DcMstring::new();
9441        crate::BinaryPayload(vec![0x55; 64]).encode_dc_mixed(&mut doc_type3)?;
9442        crate::validate_dcmst(doc_type3.as_bytes())?;
9443        // Corrupting the digest of a type 3 frame must fail validation
9444        let mut corrupted_type3 = doc_type3.as_bytes().to_vec();
9445        let last_idx = corrupted_type3.len() - 1;
9446        corrupted_type3[last_idx] ^= 0xFF;
9447        assert!(
9448            crate::validate_dcmst(&corrupted_type3).is_err(),
9449            "Corrupted digest in .dcmm type 3 binary frame must fail"
9450        );
9451
9452        // 3. `SeedGraphIndex` active triple lifecycle (`Dc 584`, `Dc 610`, `Dc 591`, `Dc 592`)
9453        //    including retracted retractions and retracted supersessions.
9454        let base_id = 8_589_934_592_u128;
9455        let n0 = LedgerNode {
9456            id: base_id,
9457            tokens: vec![
9458                DcShorthand::Short(584),
9459                DcShorthand::Short(517),
9460                DcShorthand::Short(572),
9461            ],
9462            comment: String::new(),
9463            created_ns: None,
9464        };
9465        let n1_old_val = LedgerNode {
9466            id: base_id + 1,
9467            tokens: vec![
9468                DcShorthand::Short(610),
9469                DcShorthand::Long(base_id),
9470                DcShorthand::Short(518),
9471            ],
9472            comment: String::new(),
9473            created_ns: None,
9474        };
9475        let n2_new_val = LedgerNode {
9476            id: base_id + 2,
9477            tokens: vec![
9478                DcShorthand::Short(610),
9479                DcShorthand::Long(base_id),
9480                DcShorthand::Short(517),
9481            ],
9482            comment: String::new(),
9483            created_ns: None,
9484        };
9485        let n3_supersede = LedgerNode {
9486            id: base_id + 3,
9487            tokens: vec![
9488                DcShorthand::Short(591),
9489                DcShorthand::Long(base_id + 2),
9490                DcShorthand::Long(base_id + 1),
9491            ],
9492            comment: String::new(),
9493            created_ns: None,
9494        };
9495        let n4_retract_supersede = LedgerNode {
9496            id: base_id + 4,
9497            tokens: vec![
9498                DcShorthand::Short(592),
9499                DcShorthand::Short(615),
9500                DcShorthand::Long(base_id + 3),
9501            ],
9502            comment: String::new(),
9503            created_ns: None,
9504        };
9505        let n5_retract_n0 = LedgerNode {
9506            id: base_id + 5,
9507            tokens: vec![
9508                DcShorthand::Short(592),
9509                DcShorthand::Short(615),
9510                DcShorthand::Long(base_id),
9511            ],
9512            comment: String::new(),
9513            created_ns: None,
9514        };
9515        let n6_retract_n5 = LedgerNode {
9516            id: base_id + 6,
9517            tokens: vec![
9518                DcShorthand::Short(592),
9519                DcShorthand::Short(615),
9520                DcShorthand::Long(base_id + 5),
9521            ],
9522            comment: String::new(),
9523            created_ns: None,
9524        };
9525
9526        // Snapshot at n3: n1 is superseded by n2
9527        let (inactive_at_n3, sup_at_n3, _) = compute_effective_inactive_ids(&[
9528            n0.clone(),
9529            n1_old_val.clone(),
9530            n2_new_val.clone(),
9531            n3_supersede.clone(),
9532        ]);
9533        assert!(inactive_at_n3.contains(&(base_id + 1)));
9534        assert_eq!(sup_at_n3.get(&(base_id + 1)), Some(&(base_id + 2)));
9535
9536        // Snapshot at n4: n3 (supersession) is retracted by n4 -> n1 is active again!
9537        let (inactive_at_n4, sup_at_n4, _) = compute_effective_inactive_ids(&[
9538            n0.clone(),
9539            n1_old_val.clone(),
9540            n2_new_val.clone(),
9541            n3_supersede.clone(),
9542            n4_retract_supersede.clone(),
9543        ]);
9544        assert!(
9545            !inactive_at_n4.contains(&(base_id + 1)),
9546            "Retracting a Supersedes statement must restore the superseded statement"
9547        );
9548        assert!(!sup_at_n4.contains_key(&(base_id + 1)));
9549
9550        // Snapshot at n6: n5 retracted n0, and n6 retracted n5 -> n0 is active again!
9551        let (inactive_at_n6, _, _) = compute_effective_inactive_ids(&[
9552            n0.clone(),
9553            n1_old_val.clone(),
9554            n2_new_val.clone(),
9555            n3_supersede.clone(),
9556            n4_retract_supersede.clone(),
9557            n5_retract_n0.clone(),
9558            n6_retract_n5.clone(),
9559        ]);
9560        assert!(
9561            !inactive_at_n6.contains(&base_id),
9562            "Retracting a Retracts statement must restore the retracted statement"
9563        );
9564        let index_at_n6 = SeedGraphIndex::from_nodes(vec![
9565            n0,
9566            n1_old_val,
9567            n2_new_val,
9568            n3_supersede,
9569            n4_retract_supersede,
9570            n5_retract_n0,
9571            n6_retract_n5,
9572        ]);
9573        assert_eq!(index_at_n6.resolve_latest_node_id(base_id), Some(base_id));
9574
9575        // 4. Dc-WASM numeric/trap semantics (`i32.div_s` divide-by-zero and `i32::MIN / -1` overflow)
9576        let i32_dc = i32_type_dc();
9577        for (lhs, rhs) in [(10_i32, 0_i32), (i32::MIN, -1_i32)] {
9578            let mut trap_doc = DcMstring::new();
9579            trap_doc.push_char(DcChar::from_short(260));
9580            trap_doc.push_char(DcChar::from_short(262));
9581            trap_doc.push_char(DcChar::from_short(280));
9582            trap_doc.push_char(i32_dc);
9583            trap_doc.push_char(DcChar::from_short(263));
9584            trap_doc.push_char(DcChar::from_short(712));
9585            i32::encode_dc_mixed(&lhs, &mut trap_doc)?;
9586            trap_doc.push_char(DcChar::from_short(712));
9587            i32::encode_dc_mixed(&rhs, &mut trap_doc)?;
9588            trap_doc.push_char(DcChar::from_short(756)); // i32.div_s (647 + 0x6D)
9589            trap_doc.push_char(DcChar::from_short(261));
9590            let mut trap_session =
9591                DcWasmSession::from_dc_wasm(&trap_doc, &DcMstring::new(), None)?;
9592            assert!(
9593                trap_session.step().is_err(),
9594                "i32.div_s({lhs}, {rhs}) must trap deterministically"
9595            );
9596        }
9597
9598        // 5. Active graph `<equiv>` (`Dc 597`) resolution and leading `Dc 641` pin discovery
9599        //    under `BootstrapKernelVersion::V1`.
9600        let resolver = default_syntax_resolver();
9601        // `Dc 296` ("Logical NOT") and Unicode `!` (`U+0021`) or `<equiv>` pairs resolve via `is_equivalent_to`:
9602        let canon_517 = resolver.canonical_token(DcChar::from_short(517).to_u128());
9603        assert!(
9604            resolver.is_equivalent_to(DcChar::from_short(517).to_u128(), canon_517)
9605        );
9606        let head_pin = SeedGraphIndex::shared()?
9607            .system_block_most_recent_node_id()
9608            .unwrap();
9609        let mut pinned_nav_doc = DcMstring::new();
9610        pinned_nav_doc.push_char(DcChar::from_short(641));
9611        pinned_nav_doc.push_char(DcChar::from_u128(head_pin));
9612        pinned_nav_doc.push_char(DcChar::from_short(517));
9613        let nav = crate::DcDocumentNavigator::from_mstr_with_policy(
9614            &pinned_nav_doc,
9615            &crate::DcProjectionPolicy::strict()
9616                .with_kernel_version(crate::BootstrapKernelVersion::V1),
9617        );
9618        assert_eq!(nav.kernel_version(), crate::BootstrapKernelVersion::V1);
9619        assert_eq!(nav.document_most_recent_node_id(), Some(head_pin));
9620
9621        // 6. `.Semantic:Pattern` operators (`parse_dc_syntax` / `SyntaxPattern`):
9622        //    - Choice and backtracking (`|` / `Dc 601 "Pattern alternative"`)
9623        //    - Capture scope (`(...)` / `Dc 603`..`Dc 604` + `=>` / `Dc 608`)
9624        //    - Recursive references (`[expr]`)
9625        //    - Range arity (`{min,max}` / `Dc 605`..`Dc 607` and `a..z` / `Dc 614`)
9626        //    - Malformed pattern diagnostics
9627        let choice_rule = ctb_formats_dcdata::syntax::parse_dc_syntax(
9628            ":~ ([number] 517 | [number] 518)",
9629        )
9630        .expect("Valid choice pattern must parse");
9631        assert!(matches!(
9632            choice_rule.pattern,
9633            ctb_formats_dcdata::syntax::SyntaxPattern::Sequence(_)
9634        ));
9635        let range_rule = ctb_formats_dcdata::syntax::parse_dc_syntax(
9636            ":~ [u61..u7a]{2,4} [string $x] : lang.say($x)",
9637        )
9638        .expect("Valid character range + bounded quantifier + capture replacement must parse");
9639        assert!(range_rule.action.is_some());
9640        if let ctb_formats_dcdata::syntax::SyntaxPattern::Sequence(elems) =
9641            &range_rule.pattern
9642        {
9643            assert_eq!(elems.len(), 3);
9644            assert_eq!(
9645                elems[1].quantifier,
9646                ctb_formats_dcdata::syntax::Quantifier::Range {
9647                    min: 2,
9648                    max: Some(4),
9649                }
9650            );
9651            assert!(matches!(
9652                &elems[2].term,
9653                ctb_formats_dcdata::syntax::SyntaxTerm::NamedConstruct {
9654                    capture_var: Some(c),
9655                    ..
9656                } if c == "x"
9657            ));
9658        } else {
9659            bail!("Expected sequence pattern for range_rule");
9660        }
9661        assert!(
9662            ctb_formats_dcdata::syntax::parse_dc_syntax(":~ (517").is_err(),
9663            "Unclosed capture group must be rejected as malformed pattern"
9664        );
9665
9666        // 7. `BootstrapKernelVersion::V1` opcode gating:
9667        //    Rejects `0xFB` GC (`Dc 903`..`Dc 1158`), exception-handling (`Dc 655` `throw`,
9668        //    `Dc 657` `throw_ref`, `Dc 678` `try_table`), and `0xFD` Relaxed SIMD (`Dc 1671`..`Dc 1926`)
9669        //    in both Dc-WASM lowering and raw WASM instrumentation.
9670        for gated_dc in [
9671            DcChar::from_short(655),  // WASM throw (0x08)
9672            DcChar::from_short(657),  // WASM throw_ref (0x0A)
9673            DcChar::from_short(678),  // WASM try_table (0x1F)
9674            DcChar::from_short(903),  // WASM struct.new (0xFB 0x00)
9675            DcChar::from_short(1158), // WASM Reserved 0xFB 0xFF 0x01
9676            DcChar::from_short(1671), // WASM i8x16.relaxed_swizzle (0xFD 0x100)
9677            DcChar::from_short(1926), // WASM Reserved 0xFD 0xFF 0x03
9678        ] {
9679            let mut gated_doc = DcMstring::new();
9680            gated_doc.push_char(DcChar::from_short(260));
9681            gated_doc.push_char(DcChar::from_short(262));
9682            gated_doc.push_char(DcChar::from_short(280));
9683            gated_doc.push_char(i32_dc);
9684            gated_doc.push_char(DcChar::from_short(263));
9685            gated_doc.push_char(gated_dc);
9686            gated_doc.push_char(DcChar::from_short(261));
9687            assert!(
9688                dcmstring_to_wasm_with_resolver(&gated_doc, resolver.as_ref())
9689                    .is_err(),
9690                "Gated opcode {gated_dc} must be rejected under BootstrapKernelVersion::V1"
9691            );
9692        }
9693        // Raw WASM binary with `0xFD 0x80 0x02` (`i8x16.relaxed_swizzle`, subopcode 256)
9694        // must also be rejected by `instrument_wasm_module_bytes`:
9695        let raw_relaxed_simd_wasm = [
9696            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
9697            0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f,
9698            0x03, 0x02, 0x01, 0x00,
9699            0x05, 0x03, 0x01, 0x00, 0x01,
9700            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
9701            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
9702            0x0a, 0x08, 0x01, 0x06, 0x00, 0xfd, 0x80, 0x02, 0x41, 0x00, 0x0b,
9703        ];
9704        assert!(
9705            super::super::wasm_quota::instrument_wasm_module_bytes(
9706                &raw_relaxed_simd_wasm
9707            )
9708            .is_err(),
9709            "Raw 0xFD Relaxed SIMD must be rejected by BootstrapKernelVersion::V1"
9710        );
9711        Ok(())
9712    }
9713
9714    #[crate::ctb_test]
9715    fn test_gate2_portable_compute_quota_boundaries_and_resumption()
9716    -> Result<()> {
9717        // Hand-crafted standard WASM module exercising:
9718        // - helper function calls (`call 0`)
9719        // - loops and conditional branches (`loop`, `br_if`)
9720        // - linear-memory side effects (`i32.load`, `i32.store` at mem[32])
9721        // - bulk memory (`memory.fill` of 16 bytes at mem[48..64])
9722        // - `memory.grow(1)`
9723        // Func 0 (`helper(x: i32) -> i32`): returns `x + 1`
9724        // Func 1 (`main() -> i32`):
9725        //   loops 5 times incrementing `mem[32]` via `helper(mem[32])`,
9726        //   then runs `memory.fill(48, 0x5A, 16)`,
9727        //   then runs `memory.grow(1)` and stores old pages at `mem[36]`,
9728        //   then returns `0` (`Complete`).
9729        let wasm: Vec<u8> = vec![
9730            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
9731            // Type section: 2 types: (i32) -> i32, () -> i32
9732            0x01, 0x0a, 0x02,
9733            0x60, 0x01, 0x7f, 0x01, 0x7f,
9734            0x60, 0x00, 0x01, 0x7f,
9735            // Function section: func 0 -> type 0, func 1 -> type 1
9736            0x03, 0x03, 0x02, 0x00, 0x01,
9737            // Memory section: 1 memory, min 1 page
9738            0x05, 0x03, 0x01, 0x00, 0x01,
9739            // Export section: "memory" (mem 0), "main" (func 1)
9740            0x07, 0x11, 0x02,
9741            0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
9742            0x04, b'm', b'a', b'i', b'n', 0x00, 0x01,
9743            // Code section: 1 + 8 + 53 = 62 bytes (0x3e)
9744            0x0a, 0x3e, 0x02,
9745            // Body 0 (helper): local.get 0, i32.const 1, i32.add, end (7 bytes)
9746            0x07, 0x00, 0x20, 0x00, 0x41, 0x01, 0x6a, 0x0b,
9747            // Body 1 (main): 1 local i32 (counter) (52 bytes = 0x34)
9748            0x34, 0x01, 0x01, 0x7f,
9749            0x03, 0x40, // loop
9750            0x41, 0x20, // i32.const 32
9751            0x41, 0x20, // i32.const 32
9752            0x28, 0x02, 0x00, // i32.load align=2 offset=0
9753            0x10, 0x00, // call 0 (helper)
9754            0x36, 0x02, 0x00, // i32.store align=2 offset=0
9755            0x20, 0x00, // local.get 0
9756            0x41, 0x01, // i32.const 1
9757            0x6a, // i32.add
9758            0x22, 0x00, // local.tee 0
9759            0x41, 0x05, // i32.const 5
9760            0x49, // i32.lt_u
9761            0x0d, 0x00, // br_if 0
9762            0x0b, // end loop
9763            // memory.fill(48, 0x5A, 16) (cost = 1 + 16 = 17)
9764            0x41, 0x30, // i32.const 48
9765            0x41, 0xda, 0x00, // i32.const 0x5A
9766            0x41, 0x10, // i32.const 16
9767            0xfc, 0x0b, 0x00, // memory.fill 0
9768            // mem[36] = memory.grow(1) (cost = 1 + 64 = 65)
9769            0x41, 0x24, // i32.const 36
9770            0x41, 0x01, // i32.const 1
9771            0x40, 0x00, // memory.grow 0
9772            0x36, 0x02, 0x00, // i32.store
9773            0x41, 0x00, // i32.const 0
9774            0x0b, // end
9775        ];
9776
9777        let mut compatibility_cases = Vec::new();
9778        for (quota, interrupted_op, required_cost, consumed, remaining) in [
9779            (0_u64, Some(1_u64), Some(1_u64), 0_u64, 0_u64),
9780            (1, Some(2), Some(1), 1, 0),
9781            (5, Some(6), Some(1), 5, 0),
9782            (11, Some(12), Some(17), 11, 0),
9783            (20, Some(12), Some(17), 11, 9),
9784            (35, Some(13), Some(65), 28, 7),
9785            (100, None, None, 93, 7),
9786        ] {
9787            let limits = DcWasmResourceLimits::default()
9788                .with_max_instructions_per_step(quota)
9789                .with_max_memory_pages(4);
9790            let mut session = DcWasmSession::from_wasm_bytes_with_limits(
9791                &wasm,
9792                &DcMstring::new(),
9793                None,
9794                limits,
9795            )?;
9796            let instrumented_bytes = session.instrumented_wasm_bytes().to_vec();
9797            let result = session.step();
9798            let exhausted = interrupted_op.is_some();
9799            if exhausted {
9800                let err = result.expect_err("Quota must interrupt this step");
9801                assert_eq!(
9802                    err.downcast_ref::<WasmResourceInterruption>(),
9803                    Some(&WasmResourceInterruption::ComputeQuotaExhausted {
9804                        limit: quota,
9805                    })
9806                );
9807            } else {
9808                assert!(matches!(result?, WasmStepOutcome::Complete(_)));
9809                assert_eq!(session.read_memory(32, 4)?, 5_i32.to_le_bytes());
9810                assert_eq!(session.read_memory(36, 4)?, 1_i32.to_le_bytes());
9811                assert_eq!(session.read_memory(48, 16)?, vec![0x5a; 16]);
9812            }
9813            assert_eq!(
9814                (
9815                    session.last_interrupted_op_ordinal(),
9816                    session.last_interrupted_op_required_cost(),
9817                    session.last_step_instructions(),
9818                    session.remaining_compute_quota(),
9819                ),
9820                (interrupted_op, required_cost, consumed, remaining),
9821                "Compute quota {quota} must stop before the expected operation"
9822            );
9823            compatibility_cases.push(serde_json::json!({
9824                "kind": "quota_boundary",
9825                "quota": quota,
9826                "wasm": instrumented_bytes,
9827                "max_mem_pages": 4,
9828                "max_table_elems": 1024,
9829                "state": {
9830                    "trapped": false,
9831                    "exhausted": exhausted,
9832                    "interrupted_op": interrupted_op.map(|value| value.to_string()),
9833                    "required_cost": required_cost.map(|value| value.to_string()),
9834                    "consumed": consumed.to_string(),
9835                    "remaining": remaining.to_string(),
9836                    "result": if exhausted { None } else { Some(0_i32) },
9837                    "memory": session.read_memory(32, 32)?,
9838                    "pages": session.current_memory_pages()?,
9839                },
9840            }));
9841        }
9842
9843        // 2. Trap fixtures (`i32.div_s` divide-by-zero `10 / 0` and overflow `i32::MIN / -1` after storing `7` at `mem[32]`):
9844        for (label, lhs, rhs) in [
9845            ("trap_div_zero", 10_i32, 0_i32),
9846            ("trap_div_overflow", i32::MIN, -1_i32),
9847        ] {
9848            let mut trap_doc = DcMstring::new();
9849            trap_doc.push_char(DcChar::from_short(260));
9850            trap_doc.push_char(DcChar::from_short(262));
9851            trap_doc.push_char(DcChar::from_short(280));
9852            trap_doc.push_char(i32_type_dc());
9853            trap_doc.push_char(DcChar::from_short(263));
9854            trap_doc.push_char(DcChar::from_short(712)); // i32.const 32
9855            i32::encode_dc_mixed(&32, &mut trap_doc)?;
9856            trap_doc.push_char(DcChar::from_short(712)); // i32.const 7
9857            i32::encode_dc_mixed(&7, &mut trap_doc)?;
9858            trap_doc.push_char(DcChar::from_short(701)); // i32.store
9859            u32::encode_dc_mixed(&0, &mut trap_doc)?;
9860            u32::encode_dc_mixed(&2, &mut trap_doc)?;
9861            u32::encode_dc_mixed(&0, &mut trap_doc)?;
9862            trap_doc.push_char(DcChar::from_short(712));
9863            i32::encode_dc_mixed(&lhs, &mut trap_doc)?;
9864            trap_doc.push_char(DcChar::from_short(712));
9865            i32::encode_dc_mixed(&rhs, &mut trap_doc)?;
9866            trap_doc.push_char(DcChar::from_short(756)); // i32.div_s
9867            trap_doc.push_char(DcChar::from_short(261));
9868
9869            let limits = DcWasmResourceLimits::default()
9870                .with_max_instructions_per_step(20)
9871                .with_max_memory_pages(4);
9872            let mut trap_session = DcWasmSession::from_dc_wasm(
9873                &trap_doc,
9874                &DcMstring::new(),
9875                None,
9876            )?
9877            .with_resource_limits(limits);
9878            let instrumented_bytes =
9879                trap_session.instrumented_wasm_bytes().to_vec();
9880            let err = trap_session
9881                .step()
9882                .expect_err("Division trap fixture must trap");
9883            assert!(
9884                err.downcast_ref::<WasmResourceInterruption>().is_none(),
9885                "Non-resource division trap must not report WasmResourceInterruption"
9886            );
9887            assert_eq!(trap_session.read_memory(32, 4)?, 7_i32.to_le_bytes());
9888            compatibility_cases.push(serde_json::json!({
9889                "kind": label,
9890                "quota": 20_u64,
9891                "wasm": instrumented_bytes,
9892                "max_mem_pages": 4,
9893                "max_table_elems": 1024,
9894                "state": {
9895                    "trapped": true,
9896                    "exhausted": false,
9897                    "interrupted_op": None::<String>,
9898                    "required_cost": None::<String>,
9899                    "consumed": trap_session.last_step_instructions().to_string(),
9900                    "remaining": trap_session.remaining_compute_quota().to_string(),
9901                    "result": None::<i32>,
9902                    "memory": trap_session.read_memory(32, 32)?,
9903                    "pages": trap_session.current_memory_pages()?,
9904                },
9905            }));
9906        }
9907
9908        // 3. Table growth & `call_indirect` fixture:
9909        //    Func 0 (`(i32) -> i32`): returns `local.get 0 + 42`
9910        //    Func 1 (`main () -> i32`):
9911        //      grows table 0 by 2 with `ref.func 0` (`cost = 1 + 2 * 8 = 17`),
9912        //      stores old table size at `mem[36]`,
9913        //      calls `call_indirect (type 0)` on table slot 1 with arg `10` -> `52`,
9914        //      stores `52` at `mem[32]`, returns `0`.
9915        let table_indirect_wasm: Vec<u8> = vec![
9916            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
9917            // Type section: type 0 = (i32) -> i32, type 1 = () -> i32
9918            0x01, 0x0a, 0x02,
9919            0x60, 0x01, 0x7f, 0x01, 0x7f,
9920            0x60, 0x00, 0x01, 0x7f,
9921            // Function section: func 0 -> type 0, func 1 -> type 1
9922            0x03, 0x03, 0x02, 0x00, 0x01,
9923            // Table section: 1 funcref table, min 1
9924            0x04, 0x04, 0x01, 0x70, 0x00, 0x01,
9925            // Memory section: 1 memory, min 1 page
9926            0x05, 0x03, 0x01, 0x00, 0x01,
9927            // Export section: "memory" (mem 0), "main" (func 1)
9928            0x07, 0x11, 0x02,
9929            0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
9930            0x04, b'm', b'a', b'i', b'n', 0x00, 0x01,
9931            // Element section: active segment on table 0 at offset 0 with [func 0]
9932            0x09, 0x07, 0x01, 0x00, 0x41, 0x00, 0x0b, 0x01, 0x00,
9933            // Code section:
9934            0x0a, 0x26, 0x02,
9935            // Body 0 (7 bytes): local.get 0, i32.const 42, i32.add, end
9936            0x07, 0x00, 0x20, 0x00, 0x41, 0x2a, 0x6a, 0x0b,
9937            // Body 1 (28 bytes = 0x1c):
9938            0x1c, 0x00,
9939            0x41, 0x24, // i32.const 36
9940            0xd2, 0x00, // ref.func 0
9941            0x41, 0x02, // i32.const 2
9942            0xfc, 0x0f, 0x00, // table.grow 0
9943            0x36, 0x02, 0x00, // i32.store (mem[36] = old table size = 1)
9944            0x41, 0x20, // i32.const 32
9945            0x41, 0x0a, // i32.const 10 (arg)
9946            0x41, 0x01, // i32.const 1 (table index 1, populated by table.grow)
9947            0x11, 0x00, 0x00, // call_indirect type 0, table 0
9948            0x36, 0x02, 0x00, // i32.store (mem[32] = 52)
9949            0x41, 0x00, // i32.const 0
9950            0x0b,
9951        ];
9952        for quota in [5_u64, 100_u64] {
9953            let limits = DcWasmResourceLimits::default()
9954                .with_max_instructions_per_step(quota)
9955                .with_max_memory_pages(4)
9956                .with_max_table_elements(16);
9957            let mut tbl_s = DcWasmSession::from_wasm_bytes_with_limits(
9958                &table_indirect_wasm,
9959                &DcMstring::new(),
9960                None,
9961                limits,
9962            )?;
9963            let instrumented_bytes = tbl_s.instrumented_wasm_bytes().to_vec();
9964            let res = tbl_s.step();
9965            let exhausted = res.is_err();
9966            if !exhausted {
9967                assert_eq!(tbl_s.read_memory(32, 4)?, 52_i32.to_le_bytes());
9968                assert_eq!(tbl_s.read_memory(36, 4)?, 1_i32.to_le_bytes());
9969            }
9970            compatibility_cases.push(serde_json::json!({
9971                "kind": "table_indirect",
9972                "quota": quota,
9973                "wasm": instrumented_bytes,
9974                "max_mem_pages": 4,
9975                "max_table_elems": 16,
9976                "init_table_elems": 1,
9977                "state": {
9978                    "trapped": false,
9979                    "exhausted": exhausted,
9980                    "interrupted_op": tbl_s.last_interrupted_op_ordinal().map(|v| v.to_string()),
9981                    "required_cost": tbl_s.last_interrupted_op_required_cost().map(|v| v.to_string()),
9982                    "consumed": tbl_s.last_step_instructions().to_string(),
9983                    "remaining": tbl_s.remaining_compute_quota().to_string(),
9984                    "result": if exhausted { None } else { Some(0_i32) },
9985                    "memory": tbl_s.read_memory(32, 32)?,
9986                    "pages": tbl_s.current_memory_pages()?,
9987                },
9988            }));
9989        }
9990
9991        // 4. Numeric edge cases (`i64.rotl`, `i32.trunc_sat_f64_s` on NaN / +Inf / -Inf):
9992        //    Stores:
9993        //      mem[32] = i32.wrap_i64(i64.rotl(0x8000_0000_0000_0001, 1)) == 3
9994        //      mem[36] = i32.trunc_sat_f64_s(NaN) == 0
9995        //      mem[40] = i32.trunc_sat_f64_s(1e20) == i32::MAX
9996        //      mem[44] = i32.trunc_sat_f64_s(-1e20) == i32::MIN
9997        let mut num_doc = DcMstring::new();
9998        num_doc.push_char(DcChar::from_short(260));
9999        num_doc.push_char(DcChar::from_short(262));
10000        num_doc.push_char(DcChar::from_short(280));
10001        num_doc.push_char(i32_type_dc());
10002        num_doc.push_char(DcChar::from_short(263));
10003        // mem[32] = i32.wrap_i64(i64.rotl(0x8000_0000_0000_0001_u64 as i64, 1))
10004        num_doc.push_char(DcChar::from_short(712));
10005        i32::encode_dc_mixed(&32, &mut num_doc)?;
10006        num_doc.push_char(DcChar::from_short(713)); // i64.const
10007        i64::encode_dc_mixed(&i64::from_le_bytes(0x8000_0000_0000_0001_u64.to_le_bytes()), &mut num_doc)?;
10008        num_doc.push_char(DcChar::from_short(713)); // i64.const 1
10009        i64::encode_dc_mixed(&1, &mut num_doc)?;
10010        num_doc.push_char(DcChar::from_short(784)); // i64.rotl (647 + 0x89 = 784)
10011        num_doc.push_char(DcChar::from_short(814)); // i32.wrap_i64 (647 + 0xA7 = 814)
10012        num_doc.push_char(DcChar::from_short(701)); // i32.store
10013        u32::encode_dc_mixed(&0, &mut num_doc)?;
10014        u32::encode_dc_mixed(&2, &mut num_doc)?;
10015        u32::encode_dc_mixed(&0, &mut num_doc)?;
10016        // mem[36] = i32.trunc_sat_f64_s(f64::NAN) -> 0 (Dc 1161 = 0xFC 0x02)
10017        num_doc.push_char(DcChar::from_short(712));
10018        i32::encode_dc_mixed(&36, &mut num_doc)?;
10019        num_doc.push_char(DcChar::from_short(715)); // f64.const
10020        u64::encode_dc_mixed(&0x7ff8_0000_0000_0000_u64, &mut num_doc)?;
10021        num_doc.push_char(DcChar::from_short(1161)); // i32.trunc_sat_f64_s
10022        num_doc.push_char(DcChar::from_short(701));
10023        u32::encode_dc_mixed(&0, &mut num_doc)?;
10024        u32::encode_dc_mixed(&2, &mut num_doc)?;
10025        u32::encode_dc_mixed(&0, &mut num_doc)?;
10026        // mem[40] = i32.trunc_sat_f64_s(1e20) -> i32::MAX
10027        num_doc.push_char(DcChar::from_short(712));
10028        i32::encode_dc_mixed(&40, &mut num_doc)?;
10029        num_doc.push_char(DcChar::from_short(715));
10030        u64::encode_dc_mixed(&(1e20_f64.to_bits()), &mut num_doc)?;
10031        num_doc.push_char(DcChar::from_short(1161));
10032        num_doc.push_char(DcChar::from_short(701));
10033        u32::encode_dc_mixed(&0, &mut num_doc)?;
10034        u32::encode_dc_mixed(&2, &mut num_doc)?;
10035        u32::encode_dc_mixed(&0, &mut num_doc)?;
10036        // mem[44] = i32.trunc_sat_f64_s(-1e20) -> i32::MIN
10037        num_doc.push_char(DcChar::from_short(712));
10038        i32::encode_dc_mixed(&44, &mut num_doc)?;
10039        num_doc.push_char(DcChar::from_short(715));
10040        u64::encode_dc_mixed(&((-1e20_f64).to_bits()), &mut num_doc)?;
10041        num_doc.push_char(DcChar::from_short(1161));
10042        num_doc.push_char(DcChar::from_short(701));
10043        u32::encode_dc_mixed(&0, &mut num_doc)?;
10044        u32::encode_dc_mixed(&2, &mut num_doc)?;
10045        u32::encode_dc_mixed(&0, &mut num_doc)?;
10046        num_doc.push_char(DcChar::from_short(712));
10047        i32::encode_dc_mixed(&0, &mut num_doc)?;
10048        num_doc.push_char(DcChar::from_short(261));
10049
10050        let mut num_session = DcWasmSession::from_dc_wasm(
10051            &num_doc,
10052            &DcMstring::new(),
10053            None,
10054        )?
10055        .with_resource_limits(
10056            DcWasmResourceLimits::default()
10057                .with_max_instructions_per_step(50)
10058                .with_max_memory_pages(4),
10059        );
10060        let num_instrumented = num_session.instrumented_wasm_bytes().to_vec();
10061        assert!(matches!(num_session.step()?, WasmStepOutcome::Complete(_)));
10062        assert_eq!(num_session.read_memory(32, 4)?, 3_i32.to_le_bytes());
10063        assert_eq!(num_session.read_memory(36, 4)?, 0_i32.to_le_bytes());
10064        assert_eq!(num_session.read_memory(40, 4)?, i32::MAX.to_le_bytes());
10065        assert_eq!(num_session.read_memory(44, 4)?, i32::MIN.to_le_bytes());
10066        compatibility_cases.push(serde_json::json!({
10067            "kind": "numeric_edge",
10068            "quota": 50_u64,
10069            "wasm": num_instrumented,
10070            "max_mem_pages": 4,
10071            "max_table_elems": 1024,
10072            "state": {
10073                "trapped": false,
10074                "exhausted": false,
10075                "interrupted_op": None::<String>,
10076                "required_cost": None::<String>,
10077                "consumed": num_session.last_step_instructions().to_string(),
10078                "remaining": num_session.remaining_compute_quota().to_string(),
10079                "result": Some(0_i32),
10080                "memory": num_session.read_memory(32, 32)?,
10081                "pages": num_session.current_memory_pages()?,
10082            },
10083        }));
10084
10085        // 5. Multi-quantum continuation resumption (`5 -> +15 (20) -> +80 (100)`) on a single
10086        //    live `DcWasmSession`, verifying every intermediate and final checkpoint matches V8!
10087        let limits = DcWasmResourceLimits::default()
10088            .with_max_instructions_per_step(5)
10089            .with_max_memory_pages(4);
10090        let mut session = DcWasmSession::from_wasm_bytes_with_limits(
10091            &wasm,
10092            &DcMstring::new(),
10093            None,
10094            limits,
10095        )?;
10096        let resume_wasm_bytes = session.instrumented_wasm_bytes().to_vec();
10097        // Quantum 1 (limit 5): pauses at checkpoint 6 (cost 1)
10098        let err1 = session
10099            .step()
10100            .expect_err("Quota 5 must pause mid-execution");
10101        assert_eq!(
10102            err1.downcast_ref::<WasmResourceInterruption>(),
10103            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 5 })
10104        );
10105        assert_eq!(session.last_interrupted_op_ordinal(), Some(6));
10106        assert_eq!(session.last_interrupted_op_required_cost(), Some(1));
10107        assert_eq!(session.total_instructions_executed(), 5);
10108        assert_eq!(session.remaining_compute_quota(), 0);
10109
10110        // Quantum 2 (+15 => limit 20): resumes in place and pauses right before `memory.fill` at checkpoint 12 (cost 17)
10111        session.increase_compute_quota(15);
10112        let err2 = session
10113            .step()
10114            .expect_err("Quota 20 must pause before memory.fill (cost 17)");
10115        assert_eq!(
10116            err2.downcast_ref::<WasmResourceInterruption>(),
10117            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 20 })
10118        );
10119        assert_eq!(session.last_interrupted_op_ordinal(), Some(12));
10120        assert_eq!(session.last_interrupted_op_required_cost(), Some(17));
10121        assert_eq!(session.total_instructions_executed(), 11);
10122        assert_eq!(session.remaining_compute_quota(), 9);
10123        assert_eq!(session.read_memory(32, 4)?, 5_i32.to_le_bytes());
10124
10125        // Quantum 3 (+80 => limit 100): resumes in place at `memory.fill`, runs `memory.grow(1)`, and completes!
10126        session.increase_compute_quota(80);
10127        let outcome = session.step()?;
10128        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
10129        assert_eq!(session.total_instructions_executed(), 93);
10130        assert_eq!(session.remaining_compute_quota(), 7);
10131        assert_eq!(session.current_memory_pages()?, 2);
10132        assert_eq!(session.read_memory(32, 4)?, 5_i32.to_le_bytes());
10133        assert_eq!(session.read_memory(36, 4)?, 1_i32.to_le_bytes());
10134        assert_eq!(session.read_memory(48, 16)?, vec![0x5a; 16]);
10135        compatibility_cases.push(serde_json::json!({
10136            "kind": "resumed_completion",
10137            "quota": 100_u64,
10138            "wasm": resume_wasm_bytes,
10139            "max_mem_pages": 4,
10140            "max_table_elems": 1024,
10141            "state": {
10142                "trapped": false,
10143                "exhausted": false,
10144                "interrupted_op": None::<String>,
10145                "required_cost": None::<String>,
10146                "consumed": session.total_instructions_executed().to_string(),
10147                "remaining": session.remaining_compute_quota().to_string(),
10148                "result": Some(0_i32),
10149                "memory": session.read_memory(32, 32)?,
10150                "pages": session.current_memory_pages()?,
10151            },
10152        }));
10153
10154        // 14. Mutual tail-call (`return_call`, opcode 0x12) parity with V8 across 2,000 frames
10155        //     (> `tinywasm`'s 1,024-frame non-tail call stack limit) with dead stack values unwound.
10156        let tail_wat = r#"
10157            (module
10158              (func $ping (param $n i32) (param $acc i32) (result i32)
10159                (if (result i32) (i32.le_s (local.get $n) (i32.const 0))
10160                  (then (local.get $acc))
10161                  (else
10162                    (block (result i32)
10163                      (i32.const 777)
10164                      (return_call $pong
10165                        (i32.sub (local.get $n) (i32.const 1))
10166                        (i32.add (local.get $acc) (i32.const 3)))))))
10167              (func $pong (param $n i32) (param $acc i32) (result i32)
10168                (if (result i32) (i32.le_s (local.get $n) (i32.const 0))
10169                  (then (local.get $acc))
10170                  (else
10171                    (return_call $ping
10172                      (i32.sub (local.get $n) (i32.const 1))
10173                      (i32.add (local.get $acc) (i32.const 1))))))
10174              (func (export "main") (result i32)
10175                (i32.store (i32.const 32) (call $ping (i32.const 2000) (i32.const 0)))
10176                (i32.store (i32.const 8) (i32.load (i32.const 0)))
10177                (i32.store (i32.const 12) (i32.load (i32.const 4)))
10178                (i32.const 0)))
10179        "#;
10180        let tail_wasm = crate::converters::wat::wat_to_wasm(tail_wat)?;
10181        let tail_limits = DcWasmResourceLimits::default()
10182            .with_max_instructions_per_step(50_000)
10183            .with_max_memory_pages(4);
10184        let mut tail_session = DcWasmSession::from_wasm_bytes_with_limits(
10185            &tail_wasm,
10186            &DcMstring::new(),
10187            None,
10188            tail_limits,
10189        )?;
10190        let tail_instrumented = tail_session.instrumented_wasm_bytes().to_vec();
10191        let tail_outcome = tail_session.step()?;
10192        assert!(matches!(tail_outcome, WasmStepOutcome::Complete(_)));
10193        assert_eq!(tail_session.read_memory(32, 4)?, 4_000_i32.to_le_bytes());
10194        compatibility_cases.push(serde_json::json!({
10195            "kind": "mutual_return_call_completion",
10196            "quota": 50_000_u64,
10197            "wasm": tail_instrumented,
10198            "max_mem_pages": 4,
10199            "max_table_elems": 1024,
10200            "state": {
10201                "trapped": false,
10202                "exhausted": false,
10203                "interrupted_op": None::<String>,
10204                "required_cost": None::<String>,
10205                "consumed": tail_session.total_instructions_executed().to_string(),
10206                "remaining": tail_session.remaining_compute_quota().to_string(),
10207                "result": Some(0_i32),
10208                "memory": tail_session.read_memory(32, 32)?,
10209                "pages": tail_session.current_memory_pages()?,
10210            },
10211        }));
10212
10213        println!(
10214            "CTB_WASM_COMPAT {}",
10215            serde_json::to_string(&compatibility_cases)?
10216        );
10217        Ok(())
10218    }
10219
10220    #[crate::ctb_test]
10221    fn test_gate2_physical_allocation_failure_below_logical_quota_and_shared_task_quota()
10222    -> Result<()> {
10223        let i32_dc = i32_type_dc();
10224        // Routine that calls `memory.grow(2)` and returns 0.
10225        let mut grow_doc = DcMstring::new();
10226        grow_doc.push_char(DcChar::from_short(260));
10227        grow_doc.push_char(DcChar::from_short(262));
10228        grow_doc.push_char(DcChar::from_short(280));
10229        grow_doc.push_char(i32_dc);
10230        grow_doc.push_char(DcChar::from_short(263));
10231        grow_doc.push_char(DcChar::from_short(712));
10232        i32::encode_dc_mixed(&2, &mut grow_doc)?;
10233        grow_doc.push_char(DcChar::from_short(711)); // memory.grow 0
10234        u8::encode_dc_mixed(&0, &mut grow_doc)?;
10235        grow_doc.push_char(DcChar::from_short(673)); // drop (647 + 0x1A)
10236        grow_doc.push_char(DcChar::from_short(712));
10237        i32::encode_dc_mixed(&0, &mut grow_doc)?;
10238        grow_doc.push_char(DcChar::from_short(261));
10239
10240        // Logical cap is 8 pages (so 1 + 2 = 3 pages is logically permitted),
10241        // but physical cap is 2 pages (simulating physical allocator exhaustion below logical quota).
10242        let limits = DcWasmResourceLimits::default()
10243            .with_max_memory_pages(8)
10244            .with_physical_max_memory_pages(2);
10245        let mut session = DcWasmSession::from_dc_wasm(
10246            &grow_doc,
10247            &DcMstring::new(),
10248            None,
10249        )?
10250        .with_resource_limits(limits);
10251        let err = session
10252            .step()
10253            .expect_err("Physical allocation failure below logical quota must interrupt externally");
10254        assert_eq!(
10255            err.downcast_ref::<WasmResourceInterruption>(),
10256            Some(&WasmResourceInterruption::MemoryLimitExceeded {
10257                requested_pages: 3,
10258                max_pages: 2,
10259            })
10260        );
10261
10262        // Verify shared task quota across multiple sessions (`SharedWasmTaskQuota`):
10263        // Under V2 structural checkpoints, `grow_doc` costs 130 compute units (1 entry + 129 for `memory.grow(2)`).
10264        // Two sessions sharing a 200-unit task quota allow the first session (130 units, 70 remaining)
10265        // and exhaust the quota on the second session.
10266        let shared = super::super::wasm_quota::SharedWasmTaskQuota::new(
10267            DcWasmResourceLimits::default().with_max_instructions_per_step(200),
10268        );
10269        let mut s1 = DcWasmSession::from_dc_wasm(
10270            &grow_doc,
10271            &DcMstring::new(),
10272            None,
10273        )?
10274        .with_shared_task_quota(shared.clone())?;
10275        assert!(matches!(s1.step()?, WasmStepOutcome::Complete(_)));
10276        let remaining_after_s1 = s1.remaining_compute_quota();
10277        assert_eq!(remaining_after_s1, 70);
10278
10279        let mut s2 = DcWasmSession::from_dc_wasm(
10280            &grow_doc,
10281            &DcMstring::new(),
10282            None,
10283        )?
10284        .with_shared_task_quota(shared)?;
10285        let err2 = s2
10286            .step()
10287            .expect_err("Second session sharing the same task quota must exhaust remaining allowance");
10288        assert!(matches!(
10289            err2.downcast_ref::<WasmResourceInterruption>(),
10290            Some(WasmResourceInterruption::ComputeQuotaExhausted { .. })
10291        ));
10292
10293        // Verify modules exporting reserved `__ctb_*` names are rejected during instrumentation.
10294        let reserved_export_wasm = [
10295            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
10296            0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7f,
10297            0x03, 0x02, 0x01, 0x00,
10298            0x05, 0x03, 0x01, 0x00, 0x01,
10299            0x07, 0x16, 0x02,
10300            0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
10301            0x0b, b'_', b'_', b'c', b't', b'b', b'_', b's', b'p', b'o', b'o', b'f', 0x00, 0x00,
10302            0x0a, 0x06, 0x01, 0x04, 0x00, 0x41, 0x00, 0x0b,
10303        ];
10304        assert!(
10305            DcWasmSession::from_wasm_bytes(
10306                &reserved_export_wasm,
10307                &DcMstring::new(),
10308                None,
10309            )
10310            .is_err(),
10311            "Module exporting reserved __ctb_* symbol must be rejected"
10312        );
10313        Ok(())
10314    }
10315
10316    #[crate::ctb_test]
10317    fn test_gate2_basic_block_batching_watchdog_capability_and_child_task_quotas()
10318    -> Result<()> {
10319        let i32_dc = i32_type_dc();
10320
10321        // 1. V2 structural checkpoints with mid-block trap safety and straight-line stride splitting:
10322        // Routine executes 5 pure ops, then `i32.const 0`, then `i32.div_s` (traps), plus trailing ops.
10323        // Under V2 checkpoints:
10324        // - checkpoint 1: function entry (`quota = 0` stops BEFORE entry with 0 consumed)
10325        // - `quota = 20`: `i32.div_s` traps consuming only 1 checkpoint unit (no pre-deduct past trap).
10326        // Additionally, a straight-line 300-`nop` routine tests the V2_MAX_STRAIGHT_LINE_OPS (256)
10327        // stride checkpoint (checkpoint 1 at entry, checkpoint 2 after 256 ordinary ops).
10328        let mut div_trap_doc = DcMstring::new();
10329        div_trap_doc.push_char(DcChar::from_short(260));
10330        div_trap_doc.push_char(DcChar::from_short(262));
10331        div_trap_doc.push_char(DcChar::from_short(280));
10332        div_trap_doc.push_char(i32_dc);
10333        div_trap_doc.push_char(DcChar::from_short(263));
10334        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 10
10335        i32::encode_dc_mixed(&10, &mut div_trap_doc)?;
10336        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 20
10337        i32::encode_dc_mixed(&20, &mut div_trap_doc)?;
10338        div_trap_doc.push_char(DcChar::from_short(753)); // i32.add
10339        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 5
10340        i32::encode_dc_mixed(&5, &mut div_trap_doc)?;
10341        div_trap_doc.push_char(DcChar::from_short(754)); // i32.sub
10342        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 0
10343        i32::encode_dc_mixed(&0, &mut div_trap_doc)?;
10344        div_trap_doc.push_char(DcChar::from_short(756)); // i32.div_s (traps on / 0!)
10345        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 99
10346        i32::encode_dc_mixed(&99, &mut div_trap_doc)?;
10347        div_trap_doc.push_char(DcChar::from_short(753)); // i32.add
10348        div_trap_doc.push_char(DcChar::from_short(673)); // drop
10349        div_trap_doc.push_char(DcChar::from_short(712)); // i32.const 0
10350        i32::encode_dc_mixed(&0, &mut div_trap_doc)?;
10351        div_trap_doc.push_char(DcChar::from_short(261));
10352
10353        let mut s0 = DcWasmSession::from_dc_wasm(
10354            &div_trap_doc,
10355            &DcMstring::new(),
10356            None,
10357        )?
10358        .with_resource_limits(
10359            DcWasmResourceLimits::default().with_max_instructions_per_step(0),
10360        );
10361        let err0 = s0
10362            .step()
10363            .expect_err("Quota 0 must exhaust at function entry before i32.div_s");
10364        assert_eq!(
10365            err0.downcast_ref::<WasmResourceInterruption>(),
10366            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 0 })
10367        );
10368        assert_eq!(s0.last_interrupted_op_ordinal(), Some(1));
10369        assert_eq!(s0.last_interrupted_op_required_cost(), Some(1));
10370        assert_eq!(s0.last_step_instructions(), 0);
10371        assert_eq!(s0.remaining_compute_quota(), 0);
10372
10373        // With quota = 20, `i32.div_s` traps with division by zero after consuming 1 V2 checkpoint.
10374        let mut trap_s = DcWasmSession::from_dc_wasm(
10375            &div_trap_doc,
10376            &DcMstring::new(),
10377            None,
10378        )?
10379        .with_resource_limits(
10380            DcWasmResourceLimits::default().with_max_instructions_per_step(20),
10381        );
10382        let trap_err = trap_s.step().expect_err("i32.div_s by zero must trap");
10383        assert!(
10384            trap_err
10385                .downcast_ref::<WasmResourceInterruption>()
10386                .is_none()
10387        );
10388        assert_eq!(trap_s.last_step_instructions(), 1);
10389        assert_eq!(trap_s.remaining_compute_quota(), 19);
10390
10391        // Verify straight-line > V2_MAX_STRAIGHT_LINE_OPS (256) inserts deterministic stride checkpoint 2.
10392        let mut stride_doc = DcMstring::new();
10393        stride_doc.push_char(DcChar::from_short(260));
10394        stride_doc.push_char(DcChar::from_short(262));
10395        stride_doc.push_char(DcChar::from_short(280));
10396        stride_doc.push_char(i32_dc);
10397        stride_doc.push_char(DcChar::from_short(263));
10398        for _ in 0..300 {
10399            stride_doc.push_char(DcChar::from_short(648)); // nop
10400        }
10401        stride_doc.push_char(DcChar::from_short(712)); // i32.const 0
10402        i32::encode_dc_mixed(&0, &mut stride_doc)?;
10403        stride_doc.push_char(DcChar::from_short(261));
10404
10405        let mut stride_pause = DcWasmSession::from_dc_wasm(
10406            &stride_doc,
10407            &DcMstring::new(),
10408            None,
10409        )?
10410        .with_resource_limits(
10411            DcWasmResourceLimits::default().with_max_instructions_per_step(1),
10412        );
10413        let stride_err = stride_pause
10414            .step()
10415            .expect_err("300-nop straight-line routine must pause at stride checkpoint 2 under quota 1");
10416        assert_eq!(
10417            stride_err.downcast_ref::<WasmResourceInterruption>(),
10418            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 1 })
10419        );
10420        assert_eq!(stride_pause.last_interrupted_op_ordinal(), Some(2));
10421        assert_eq!(stride_pause.last_interrupted_op_required_cost(), Some(1));
10422        assert_eq!(stride_pause.last_step_instructions(), 1);
10423        assert_eq!(stride_pause.remaining_compute_quota(), 0);
10424        stride_pause.increase_compute_quota(1);
10425        assert!(matches!(stride_pause.step()?, WasmStepOutcome::Complete(_)));
10426        assert_eq!(stride_pause.total_instructions_executed(), 2);
10427
10428        // 2. Canonical config byte round-trip and watchdog bounds clamping:
10429        let watchdog = DcWasmWatchdogLimits::default()
10430            .with_physical_max_memory_pages(4)
10431            .with_physical_max_table_elements(32)
10432            .with_hard_max_instructions_per_step(50_000)
10433            .with_hard_max_session_output_bytes(8192);
10434        let logical = DcWasmResourceLimits::default()
10435            .with_max_memory_pages(16)
10436            .with_max_table_elements(128)
10437            .with_max_instructions_per_step(100_000)
10438            .with_max_session_output_bytes(65_536)
10439            .with_max_capability_payload_bytes(64)
10440            .with_max_trace_bytes(2048);
10441        let effective = logical.apply_watchdog_bounds(watchdog);
10442        assert_eq!(effective.max_memory_pages, 16);
10443        assert_eq!(effective.physical_max_memory_pages, 4);
10444        assert_eq!(effective.max_table_elements, 128);
10445        assert_eq!(effective.physical_max_table_elements, 32);
10446        assert_eq!(effective.max_instructions_per_step, 50_000);
10447        assert_eq!(effective.max_session_output_bytes, 8192);
10448        let encoded_cfg = effective.encode_canonical_config_bytes();
10449        let decoded_cfg =
10450            DcWasmResourceLimits::decode_canonical_config_bytes(&encoded_cfg)?;
10451        assert_eq!(decoded_cfg, effective);
10452
10453        // 3. Separate capability request/response payload allowance (`max_capability_payload_bytes`):
10454        // Routine that copies input mailbox (0..8) -> output mailbox (8..16) and returns 2 (`RequestCapability`).
10455        let mut cap_echo_doc = DcMstring::new();
10456        cap_echo_doc.push_char(DcChar::from_short(260));
10457        cap_echo_doc.push_char(DcChar::from_short(262));
10458        cap_echo_doc.push_char(DcChar::from_short(280));
10459        cap_echo_doc.push_char(i32_dc);
10460        cap_echo_doc.push_char(DcChar::from_short(263));
10461        cap_echo_doc.push_char(DcChar::from_short(712));
10462        i32::encode_dc_mixed(&8, &mut cap_echo_doc)?;
10463        cap_echo_doc.push_char(DcChar::from_short(712));
10464        i32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10465        cap_echo_doc.push_char(DcChar::from_short(687));
10466        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10467        u32::encode_dc_mixed(&2, &mut cap_echo_doc)?;
10468        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10469        cap_echo_doc.push_char(DcChar::from_short(701));
10470        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10471        u32::encode_dc_mixed(&2, &mut cap_echo_doc)?;
10472        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10473        cap_echo_doc.push_char(DcChar::from_short(712));
10474        i32::encode_dc_mixed(&12, &mut cap_echo_doc)?;
10475        cap_echo_doc.push_char(DcChar::from_short(712));
10476        i32::encode_dc_mixed(&4, &mut cap_echo_doc)?;
10477        cap_echo_doc.push_char(DcChar::from_short(687));
10478        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10479        u32::encode_dc_mixed(&2, &mut cap_echo_doc)?;
10480        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10481        cap_echo_doc.push_char(DcChar::from_short(701));
10482        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10483        u32::encode_dc_mixed(&2, &mut cap_echo_doc)?;
10484        u32::encode_dc_mixed(&0, &mut cap_echo_doc)?;
10485        cap_echo_doc.push_char(DcChar::from_short(712));
10486        i32::encode_dc_mixed(&2, &mut cap_echo_doc)?;
10487        cap_echo_doc.push_char(DcChar::from_short(261));
10488
10489        let mut ten_byte_payload = DcMstring::new();
10490        ten_byte_payload.push_str("0123456789");
10491
10492        // When `max_capability_payload_bytes == 5`, the 10-byte capability request is rejected
10493        // before publication with `CapabilityPayloadTooLarge`.
10494        let mut cap_fail_session =
10495            DcWasmSession::from_dc_wasm(&cap_echo_doc, &ten_byte_payload, None)?
10496                .with_resource_limits(
10497                    DcWasmResourceLimits::default()
10498                        .with_max_capability_payload_bytes(5),
10499                );
10500        let cap_req_err = cap_fail_session
10501            .step()
10502            .expect_err("Oversized capability request must fail");
10503        assert_eq!(
10504            cap_req_err.downcast_ref::<WasmResourceInterruption>(),
10505            Some(&WasmResourceInterruption::CapabilityPayloadTooLarge {
10506                payload_bytes: 10,
10507                max_capability_payload_bytes: 5,
10508            })
10509        );
10510
10511        // When `max_capability_payload_bytes == 12`, the 10-byte capability request succeeds and
10512        // does NOT consume `cumulative_output_bytes` (which remains 0), while a 20-byte capability
10513        // response is rejected by `provide_capability_response`.
10514        let mut cap_ok_session =
10515            DcWasmSession::from_dc_wasm(&cap_echo_doc, &ten_byte_payload, None)?
10516                .with_resource_limits(
10517                    DcWasmResourceLimits::default()
10518                        .with_max_capability_payload_bytes(12),
10519                );
10520        assert!(matches!(
10521            cap_ok_session.step()?,
10522            WasmStepOutcome::RequestCapability(_)
10523        ));
10524        assert_eq!(cap_ok_session.cumulative_output_bytes(), 0);
10525        let mut twenty_byte_resp = DcMstring::new();
10526        twenty_byte_resp.push_str("01234567890123456789");
10527        let resp_err = cap_ok_session
10528            .provide_capability_response(&twenty_byte_resp)
10529            .expect_err("Oversized capability response must fail");
10530        assert_eq!(
10531            resp_err.downcast_ref::<WasmResourceInterruption>(),
10532            Some(&WasmResourceInterruption::CapabilityPayloadTooLarge {
10533                payload_bytes: 20,
10534                max_capability_payload_bytes: 12,
10535            })
10536        );
10537
10538        // 4. Staged boundary limit updates and deterministic child-task quota allocation/reclamation:
10539        let parent_quota = SharedWasmTaskQuota::new(
10540            DcWasmResourceLimits::default()
10541                .with_max_instructions_per_step(500)
10542                .with_max_session_output_bytes(100),
10543        );
10544        parent_quota.stage_boundary_limits(
10545            DcWasmResourceLimits::default()
10546                .with_max_instructions_per_step(400)
10547                .with_max_session_output_bytes(80),
10548        )?;
10549        // Staged limits do not alter `remaining_compute_quota` until `apply_staged_boundary_limits`
10550        assert_eq!(parent_quota.snapshot()?.remaining_compute_quota, 500);
10551        let (_, epoch_after_stage) = parent_quota
10552            .apply_staged_boundary_limits()?
10553            .expect("Expected staged limits");
10554        assert_eq!(epoch_after_stage, 1);
10555        assert_eq!(parent_quota.snapshot()?.remaining_compute_quota, 400);
10556
10557        let (child_quota, epoch_alloc) =
10558            parent_quota.allocate_child_task_quota(150, 30)?;
10559        assert_eq!(epoch_alloc, 2);
10560        assert_eq!(parent_quota.snapshot()?.remaining_compute_quota, 250);
10561        assert_eq!(child_quota.snapshot()?.remaining_compute_quota, 150);
10562
10563        // Simulate child consuming 60 compute units and 12 output bytes:
10564        child_quota.with_lock(|st| {
10565            st.remaining_compute_quota = 90;
10566            st.total_instructions_executed = 60;
10567            st.cumulative_output_bytes = 12;
10568        })?;
10569        let epoch_reclaim =
10570            parent_quota.reclaim_child_task_quota(&child_quota)?;
10571        assert_eq!(epoch_reclaim, 3);
10572        let parent_snap = parent_quota.snapshot()?;
10573        assert_eq!(parent_snap.remaining_compute_quota, 340); // 250 + 90 unused returned
10574        assert_eq!(parent_snap.total_instructions_executed, 60);
10575        assert_eq!(parent_snap.cumulative_output_bytes, 12);
10576        assert_eq!(child_quota.snapshot()?.remaining_compute_quota, 0);
10577
10578        Ok(())
10579    }
10580
10581    #[crate::ctb_test]
10582    fn test_gate1_transitive_short_and_long_wasm_helper_expansion_and_direct_lowering()
10583    -> Result<()> {
10584        use ctb_formats_dcdata::ctbnbdl::LedgerNode;
10585        use ctb_storage_minimal::shorthand::DcShorthand;
10586
10587        let i32_dc = i32_type_dc();
10588        let pin_id: u128 = 8_589_999_950;
10589
10590        // Build a leaf WASM routine node `l<leaf_node_id>` that writes 'Z' (90) at linear memory 64,
10591        // sets out_ptr = 64, out_len = 1, and returns 0 (Complete).
10592        let mut leaf_mstr = DcMstring::new();
10593        leaf_mstr.push_char(DcChar::from_short(260));
10594        leaf_mstr.push_char(DcChar::from_short(262));
10595        leaf_mstr.push_char(DcChar::from_short(280));
10596        leaf_mstr.push_char(i32_dc);
10597        leaf_mstr.push_char(DcChar::from_short(263));
10598        leaf_mstr.push_char(DcChar::from_short(712));
10599        i32::encode_dc_mixed(&64, &mut leaf_mstr)?;
10600        leaf_mstr.push_char(DcChar::from_short(712));
10601        i32::encode_dc_mixed(&90, &mut leaf_mstr)?;
10602        leaf_mstr.push_char(DcChar::from_short(705)); // i32.store8
10603        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10604        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10605        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10606        leaf_mstr.push_char(DcChar::from_short(712));
10607        i32::encode_dc_mixed(&8, &mut leaf_mstr)?;
10608        leaf_mstr.push_char(DcChar::from_short(712));
10609        i32::encode_dc_mixed(&64, &mut leaf_mstr)?;
10610        leaf_mstr.push_char(DcChar::from_short(701)); // i32.store
10611        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10612        u32::encode_dc_mixed(&2, &mut leaf_mstr)?;
10613        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10614        leaf_mstr.push_char(DcChar::from_short(712));
10615        i32::encode_dc_mixed(&12, &mut leaf_mstr)?;
10616        leaf_mstr.push_char(DcChar::from_short(712));
10617        i32::encode_dc_mixed(&1, &mut leaf_mstr)?;
10618        leaf_mstr.push_char(DcChar::from_short(701)); // i32.store
10619        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10620        u32::encode_dc_mixed(&2, &mut leaf_mstr)?;
10621        u32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10622        leaf_mstr.push_char(DcChar::from_short(712));
10623        i32::encode_dc_mixed(&0, &mut leaf_mstr)?;
10624        leaf_mstr.push_char(DcChar::from_short(261));
10625
10626        let leaf_tokens: Vec<DcShorthand> = leaf_mstr
10627            .to_dc_string()?
10628            .chars()
10629            .map(|c| DcShorthand::from_global_id(c.to_u128()))
10630            .collect();
10631
10632        let leaf_node_id = 8_589_999_941_u128;
10633        let mid_node_id = 8_589_999_944_u128;
10634        let retracted_node_id = 8_589_999_947_u128;
10635
10636        let mut nodes =
10637            ctb_formats_dcdata::seed_graph::SeedGraphIndex::shared()?
10638                .nodes()
10639                .to_vec();
10640        // 1. Leaf node `l<leaf_node_id>` (wasm_routine literal)
10641        nodes.push(LedgerNode {
10642            id: leaf_node_id,
10643            tokens: leaf_tokens.clone(),
10644            comment: String::new(),
10645            created_ns: None,
10646        });
10647        // 2. Short(3930) has Dc 611 "Canonical decomposition" -> l<leaf_node_id>
10648        nodes.push(LedgerNode {
10649            id: 8_589_999_942,
10650            tokens: vec![
10651                DcShorthand::Short(584),
10652                DcShorthand::Short(3930),
10653                DcShorthand::Short(611),
10654            ],
10655            comment: String::new(),
10656            created_ns: None,
10657        });
10658        nodes.push(LedgerNode {
10659            id: 8_589_999_943,
10660            tokens: vec![
10661                DcShorthand::Short(610),
10662                DcShorthand::Long(8_589_999_942),
10663                DcShorthand::Long(leaf_node_id),
10664            ],
10665            comment: String::new(),
10666            created_ns: None,
10667        });
10668        // 3. Mid node `l<mid_node_id>` wraps `1927 Short(3930) 1928`, and Short(3931) has Dc 611 -> l<mid_node_id>
10669        nodes.push(LedgerNode {
10670            id: mid_node_id,
10671            tokens: vec![
10672                DcShorthand::Short(1927),
10673                DcShorthand::Short(3930),
10674                DcShorthand::Short(1928),
10675            ],
10676            comment: String::new(),
10677            created_ns: None,
10678        });
10679        nodes.push(LedgerNode {
10680            id: 8_589_999_945,
10681            tokens: vec![
10682                DcShorthand::Short(584),
10683                DcShorthand::Short(3931),
10684                DcShorthand::Short(611),
10685            ],
10686            comment: String::new(),
10687            created_ns: None,
10688        });
10689        nodes.push(LedgerNode {
10690            id: 8_589_999_946,
10691            tokens: vec![
10692                DcShorthand::Short(610),
10693                DcShorthand::Long(8_589_999_945),
10694                DcShorthand::Long(mid_node_id),
10695            ],
10696            comment: String::new(),
10697            created_ns: None,
10698        });
10699        // 4. Short(3932) had Dc 611 -> l<retracted_node_id>, which was retracted via Dc 592 "Retracts"
10700        nodes.push(LedgerNode {
10701            id: retracted_node_id,
10702            tokens: leaf_tokens,
10703            comment: String::new(),
10704            created_ns: None,
10705        });
10706        nodes.push(LedgerNode {
10707            id: 8_589_999_948,
10708            tokens: vec![
10709                DcShorthand::Short(584),
10710                DcShorthand::Short(3932),
10711                DcShorthand::Short(611),
10712            ],
10713            comment: String::new(),
10714            created_ns: None,
10715        });
10716        nodes.push(LedgerNode {
10717            id: 8_589_999_949,
10718            tokens: vec![
10719                DcShorthand::Short(610),
10720                DcShorthand::Long(8_589_999_948),
10721                DcShorthand::Long(retracted_node_id),
10722            ],
10723            comment: String::new(),
10724            created_ns: None,
10725        });
10726        nodes.push(LedgerNode {
10727            id: pin_id,
10728            tokens: vec![
10729                DcShorthand::Short(592),
10730                DcShorthand::Short(615),
10731                DcShorthand::Long(retracted_node_id),
10732            ],
10733            comment: String::new(),
10734            created_ns: None,
10735        });
10736
10737        let sg = std::sync::Arc::new(
10738            ctb_formats_dcdata::seed_graph::SeedGraphIndex::from_nodes(nodes),
10739        );
10740        let mut resolver = (**default_syntax_resolver()).clone();
10741        resolver.set_seed_graph(sg);
10742        let resolver_arc = std::sync::Arc::new(resolver);
10743        ctb_formats_dcdata::syntax::register_historical_syntax_resolver(
10744            pin_id,
10745            std::sync::Arc::clone(&resolver_arc),
10746        );
10747
10748        // A. Transitive expansion via `run_graph_wasm_tokens_on_dc_slice_with_quota`:
10749        // `Short(3931)` -> `l<mid_node_id>` (`1927 Short(3930) 1928`) -> `Short(3930)` -> `l<leaf_node_id>`!
10750        let out_mstr = run_graph_wasm_tokens_on_dc_slice_with_quota(
10751            &[DcShorthand::Short(3931)],
10752            &[],
10753            resolver_arc.as_ref(),
10754            None,
10755        )?;
10756        assert_eq!(
10757            out_mstr.to_dc_string()?.chars().collect::<Vec<_>>(),
10758            vec![DcChar::from_u128(90)]
10759        );
10760
10761        // B. Calling `dcmstring_to_wasm_with_resolver` directly on a Dc-WASM document referencing
10762        //    both `Long(leaf_node_id)` and transitive `Short(3931)` (with and without leading `641 l<pin_id>`):
10763        let mut direct_long_doc = DcMstring::new();
10764        direct_long_doc.push_char(DcChar::from_short(1927));
10765        direct_long_doc.push_char(DcChar::from_long(leaf_node_id));
10766        direct_long_doc.push_char(DcChar::from_short(1928));
10767        let wasm_bytes_long = dcmstring_to_wasm_with_resolver(
10768            &direct_long_doc,
10769            resolver_arc.as_ref(),
10770        )?;
10771        let WasmStepOutcome::Complete(out_long) =
10772            DcWasmSession::from_wasm_bytes(
10773                &wasm_bytes_long,
10774                &DcMstring::new(),
10775                None,
10776            )?
10777            .step()?
10778        else {
10779            bail!("Expected Complete outcome from wasm_bytes_long");
10780        };
10781        assert_eq!(
10782            out_long.to_dc_string()?.chars().collect::<Vec<_>>(),
10783            vec![DcChar::from_u128(90)]
10784        );
10785
10786        let mut pinned_short_doc = DcMstring::new();
10787        pinned_short_doc.push_char(DcChar::from_short(641));
10788        pinned_short_doc.push_char(DcChar::from_long(pin_id));
10789        pinned_short_doc.push_char(DcChar::from_short(1927));
10790        pinned_short_doc.push_char(DcChar::from_short(3931));
10791        pinned_short_doc.push_char(DcChar::from_short(1928));
10792        let wasm_bytes_short = dcmstring_to_wasm_with_resolver(
10793            &pinned_short_doc,
10794            default_syntax_resolver().as_ref(),
10795        )?;
10796        let WasmStepOutcome::Complete(out_short) =
10797            DcWasmSession::from_wasm_bytes(
10798                &wasm_bytes_short,
10799                &DcMstring::new(),
10800                None,
10801            )?
10802            .step()?
10803        else {
10804            bail!("Expected Complete outcome from wasm_bytes_short");
10805        };
10806        assert_eq!(
10807            out_short.to_dc_string()?.chars().collect::<Vec<_>>(),
10808            vec![DcChar::from_u128(90)]
10809        );
10810
10811        // C. Retracted Short-Dc WASM helper `Short(3932)` must fail expansion with a retraction error:
10812        let mut retracted_doc = DcMstring::new();
10813        retracted_doc.push_char(DcChar::from_short(1927));
10814        retracted_doc.push_char(DcChar::from_short(3932));
10815        retracted_doc.push_char(DcChar::from_short(1928));
10816        let retracted_err = dcmstring_to_wasm_with_resolver(
10817            &retracted_doc,
10818            resolver_arc.as_ref(),
10819        )
10820        .expect_err("Retracted Short-Dc WASM helper must be rejected");
10821        assert!(
10822            retracted_err.to_string().contains("retracted"),
10823            "Unexpected error for retracted Short-Dc WASM helper: {retracted_err}"
10824        );
10825
10826        Ok(())
10827    }
10828
10829    #[crate::ctb_test]
10830    fn test_gate2_mid_step_continuation_preserves_shared_task_quota_and_start_trap()
10831    -> Result<()> {
10832        // 1. Module with a `start` function (`func 0`) that increments `mem[40]` by 1
10833        //    and a `main` function (`func 1`) that increments `mem[32]` 5 times in a loop.
10834        //    If mid-step resumption ever re-instantiated the module or re-ran the step prefix,
10835        //    `mem[40]` would become > 1 or `mem[32]` would exceed 5!
10836        //    Furthermore, while the parent session is paused mid-step on `ComputeQuotaExhausted`,
10837        //    we allocate a child `SharedWasmTaskQuota` from the parent task quota, run a child
10838        //    session consuming 6 compute units, reclaim the child task quota into the parent,
10839        //    grant additional quota to the parent, and resume the parent's mid-step continuation!
10840        let wasm_with_start_and_loop: Vec<u8> = vec![
10841            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
10842            // Type section: type 0 = () -> (), type 1 = () -> i32
10843            0x01, 0x08, 0x02,
10844            0x60, 0x00, 0x00,
10845            0x60, 0x00, 0x01, 0x7f,
10846            // Function section: func 0 -> type 0 (start), func 1 -> type 1 (main)
10847            0x03, 0x03, 0x02, 0x00, 0x01,
10848            // Memory section: 1 memory, min 1 page
10849            0x05, 0x03, 0x01, 0x00, 0x01,
10850            // Export section: "memory" (mem 0), "main" (func 1)
10851            0x07, 0x11, 0x02,
10852            0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
10853            0x04, b'm', b'a', b'i', b'n', 0x00, 0x01,
10854            // Start section: func 0
10855            0x08, 0x01, 0x00,
10856            // Code section: 1 + 16 + 35 = 52 bytes (0x34)
10857            0x0a, 0x34, 0x02,
10858            // Body 0 (start, 15 bytes = 0x0f): mem[40] = mem[40] + 1
10859            0x0f, 0x00,
10860            0x41, 0x28, // i32.const 40
10861            0x41, 0x28, // i32.const 40
10862            0x28, 0x02, 0x00, // i32.load
10863            0x41, 0x01, // i32.const 1
10864            0x6a, // i32.add
10865            0x36, 0x02, 0x00, // i32.store
10866            0x0b,
10867            // Body 1 (main, 34 bytes = 0x22): 1 local i32 (counter); loop 5x incrementing mem[32]
10868            0x22, 0x01, 0x01, 0x7f,
10869            0x03, 0x40, // loop
10870            0x41, 0x20, // i32.const 32
10871            0x41, 0x20, // i32.const 32
10872            0x28, 0x02, 0x00, // i32.load
10873            0x41, 0x01, // i32.const 1
10874            0x6a, // i32.add
10875            0x36, 0x02, 0x00, // i32.store
10876            0x20, 0x00, // local.get 0
10877            0x41, 0x01, // i32.const 1
10878            0x6a, // i32.add
10879            0x22, 0x00, // local.tee 0
10880            0x41, 0x05, // i32.const 5
10881            0x49, // i32.lt_u
10882            0x0d, 0x00, // br_if 0
10883            0x0b, // end loop
10884            0x41, 0x00, // i32.const 0
10885            0x0b,
10886        ];
10887
10888        // Start with parent shared task quota = 4 V2 checkpoint units:
10889        // - `start` consumes 1 unit (`remaining == 3`)
10890        // - `main` entry consumes 1 unit (`remaining == 2`)
10891        // - loop runs 2 iterations (1 unit each, `mem[32] == 2`) and pauses on iteration 3
10892        //   (`remaining == 0`, checkpoint 5).
10893        let parent_limits =
10894            DcWasmResourceLimits::default().with_max_instructions_per_step(4);
10895        let shared_parent = SharedWasmTaskQuota::new(parent_limits);
10896        let mut parent_session = DcWasmSession::from_wasm_bytes_with_limits(
10897            &wasm_with_start_and_loop,
10898            &DcMstring::new(),
10899            None,
10900            parent_limits,
10901        )?
10902        .with_shared_task_quota(shared_parent.clone())?;
10903        assert_eq!(parent_session.read_memory(40, 4)?, 1_i32.to_le_bytes());
10904
10905        let pause_err = parent_session
10906            .step()
10907            .expect_err("Parent session must pause mid-step at quota 4");
10908        assert_eq!(
10909            pause_err.downcast_ref::<WasmResourceInterruption>(),
10910            Some(&WasmResourceInterruption::ComputeQuotaExhausted { limit: 4 })
10911        );
10912        // Verify partial loop progress (`mem[32] == 2`) is live in memory while suspended:
10913        assert_eq!(parent_session.read_memory(32, 4)?, 2_i32.to_le_bytes());
10914
10915        // Grant +100 units to the shared parent quota, then while the parent is STILL paused
10916        // mid-step, allocate a 20-unit child task quota, run a small child helper session
10917        // (consuming 1 checkpoint unit), and reclaim the unused 19 units back into `shared_parent`!
10918        shared_parent.increase_compute_quota(100)?;
10919        let (child_quota, _) =
10920            shared_parent.allocate_child_task_quota(20, 64)?;
10921        let mut child_doc = DcMstring::new();
10922        child_doc.push_char(DcChar::from_short(260));
10923        child_doc.push_char(DcChar::from_short(262));
10924        child_doc.push_char(DcChar::from_short(280));
10925        child_doc.push_char(i32_type_dc());
10926        child_doc.push_char(DcChar::from_short(263));
10927        child_doc.push_char(DcChar::from_short(712)); // i32.const 0
10928        i32::encode_dc_mixed(&0, &mut child_doc)?;
10929        child_doc.push_char(DcChar::from_short(261));
10930        let mut child_session = DcWasmSession::from_dc_wasm(
10931            &child_doc,
10932            &DcMstring::new(),
10933            None,
10934        )?
10935        .with_shared_task_quota(child_quota.clone())?;
10936        assert!(matches!(child_session.step()?, WasmStepOutcome::Complete(_)));
10937        let child_used = child_session.total_instructions_executed();
10938        assert_eq!(child_used, 1);
10939        shared_parent.reclaim_child_task_quota(&child_quota)?;
10940        assert_eq!(
10941            shared_parent.snapshot()?.total_instructions_executed,
10942            4 + child_used
10943        );
10944
10945        // Now resume the paused parent session (`parent_session.step()`):
10946        // It must resume its live suspended continuation without re-running `start` (`mem[40] == 1`)
10947        // or repeating the first 2 loop iterations (`mem[32] == 5`), and preserve the child's
10948        // 3 consumed units in `shared_parent.snapshot()?.total_instructions_executed`!
10949        let outcome = parent_session.step()?;
10950        assert!(matches!(outcome, WasmStepOutcome::Complete(_)));
10951        assert_eq!(
10952            parent_session.read_memory(40, 4)?,
10953            1_i32.to_le_bytes(),
10954            "start section must NOT re-execute on mid-step continuation resume"
10955        );
10956        assert_eq!(
10957            parent_session.read_memory(32, 4)?,
10958            5_i32.to_le_bytes(),
10959            "loop prefix must NOT re-execute on mid-step continuation resume"
10960        );
10961        let final_parent_snap = shared_parent.snapshot()?;
10962        assert_eq!(
10963            final_parent_snap.total_instructions_executed,
10964            parent_session.total_instructions_executed() + child_used
10965        );
10966
10967        // 2. Module whose `start` section traps with `unreachable` (`0x00`) returns `WasmStartSectionTrap`:
10968        let start_trap_wasm = [
10969            0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
10970            0x01, 0x04, 0x01, 0x60, 0x00, 0x00,
10971            0x03, 0x02, 0x01, 0x00,
10972            0x05, 0x03, 0x01, 0x00, 0x01,
10973            0x07, 0x11, 0x02, 0x06, b'm', b'e', b'm', b'o', b'r', b'y', 0x02, 0x00,
10974            0x04, b'm', b'a', b'i', b'n', 0x00, 0x00,
10975            0x08, 0x01, 0x00,
10976            0x0a, 0x05, 0x01, 0x03, 0x00, 0x00, 0x0b,
10977        ];
10978        let start_err = DcWasmSession::from_wasm_bytes(
10979            &start_trap_wasm,
10980            &DcMstring::new(),
10981            None,
10982        )
10983        .expect_err("Non-resource trap in start section must fail instantiation");
10984        assert!(
10985            start_err.downcast_ref::<WasmStartSectionTrap>().is_some(),
10986            "Expected WasmStartSectionTrap, got {start_err:#}"
10987        );
10988        Ok(())
10989    }
10990
10991    fn build_lang_say_wasm_shorthands() -> Result<Vec<DcShorthand>> {
10992        let i32_dc = i32_type_dc();
10993        let mut doc = DcMstring::new();
10994        doc.push_char(DcChar::from_short(1927));
10995        doc.push_char(DcChar::from_short(260));
10996        doc.push_char(DcChar::from_short(262));
10997        doc.push_char(DcChar::from_short(280));
10998        doc.push_char(i32_dc);
10999        doc.push_char(DcChar::from_short(263));
11000
11001        // 7 i32 locals: 0=pos, 1=body_end, 2=dst, 3=out_start, 4=b0, 5=tok_len, 6=last_is_lf
11002        doc.push_char(DcChar::from_short(310));
11003        doc.push_char(DcChar::from_short(565));
11004        for idx in 0..7 {
11005            if idx > 0 {
11006                doc.push_char(DcChar::from_short(312));
11007            }
11008            doc.push_char(i32_dc);
11009        }
11010        doc.push_char(DcChar::from_short(311));
11011
11012        let emit_op = |out: &mut DcMstring, op: u32| {
11013            out.push_char(DcChar::from_short(op));
11014        };
11015        let emit_u32 = |out: &mut DcMstring, op: u32, val: u32| -> Result<()> {
11016            out.push_char(DcChar::from_short(op));
11017            val.encode_dc_mixed(out)
11018        };
11019        let emit_i32 = |out: &mut DcMstring, op: u32, val: i32| -> Result<()> {
11020            out.push_char(DcChar::from_short(op));
11021            val.encode_dc_mixed(out)
11022        };
11023        let emit_mem =
11024            |out: &mut DcMstring, op: u32, align: u32, offset: u32| -> Result<()> {
11025                out.push_char(DcChar::from_short(op));
11026                0u32.encode_dc_mixed(out)?;
11027                align.encode_dc_mixed(out)?;
11028                offset.encode_dc_mixed(out)
11029            };
11030        let emit_trap_if = |out: &mut DcMstring| {
11031            out.push_char(DcChar::from_short(651));
11032            out.push_char(DcChar::from_short(316));
11033            out.push_char(DcChar::from_short(647));
11034            out.push_char(DcChar::from_short(658));
11035        };
11036        let emit_dctf_len_at_pos = |out: &mut DcMstring| -> Result<()> {
11037            emit_u32(out, 679, 0)?; // local.get 0 (pos)
11038            emit_mem(out, 692, 0, 0)?; // i32.load8_u
11039            emit_u32(out, 681, 4)?; // local.tee 4 (b0)
11040            emit_i32(out, 712, 128)?;
11041            emit_op(out, 720); // i32.lt_u
11042            emit_op(out, 651); // if (result i32)
11043            out.push_char(i32_dc);
11044            emit_i32(out, 712, 1)?;
11045            emit_op(out, 652); // else
11046            emit_u32(out, 679, 4)?; // local.get 4 (b0)
11047            emit_i32(out, 712, 255)?;
11048            emit_op(out, 720); // i32.lt_u
11049            emit_op(out, 651); // if (result i32)
11050            out.push_char(i32_dc);
11051            emit_i32(out, 712, 255)?;
11052            emit_u32(out, 679, 4)?;
11053            emit_op(out, 754); // i32.sub
11054            emit_i32(out, 712, 24)?;
11055            emit_op(out, 763); // i32.shl
11056            emit_op(out, 750); // i32.clz
11057            emit_op(out, 652); // else
11058            emit_i32(out, 712, 8)?;
11059            emit_u32(out, 679, 0)?; // local.get 0 (pos)
11060            emit_mem(out, 692, 0, 1)?; // i32.load8_u offset=1
11061            emit_i32(out, 712, 2)?;
11062            emit_op(out, 765); // i32.shr_u
11063            emit_i32(out, 712, 15)?;
11064            emit_op(out, 760); // i32.and
11065            emit_op(out, 753); // i32.add
11066            emit_op(out, 658); // end inner if
11067            emit_op(out, 658); // end outer if
11068            emit_u32(out, 680, 5) // local.set 5 (tok_len)
11069        };
11070
11071        // 1. Check in_len >= 29
11072        emit_i32(&mut doc, 712, 4)?;
11073        emit_mem(&mut doc, 687, 2, 0)?;
11074        emit_u32(&mut doc, 681, 1)?; // local.tee 1 (in_len)
11075        emit_i32(&mut doc, 712, 29)?;
11076        emit_op(&mut doc, 720); // i32.lt_u
11077        emit_trap_if(&mut doc);
11078
11079        // 2. pos = in_ptr, out_start = dst = in_ptr + in_len, body_end = out_start - 8, mem[8] = out_start
11080        emit_i32(&mut doc, 712, 0)?;
11081        emit_mem(&mut doc, 687, 2, 0)?;
11082        emit_u32(&mut doc, 681, 0)?; // local.tee 0 (pos)
11083        emit_u32(&mut doc, 679, 1)?; // local.get 1 (in_len)
11084        emit_op(&mut doc, 753); // i32.add
11085        emit_u32(&mut doc, 681, 3)?; // local.tee 3 (out_start)
11086        emit_u32(&mut doc, 680, 2)?; // local.set 2 (dst)
11087        emit_u32(&mut doc, 679, 3)?;
11088        emit_i32(&mut doc, 712, 8)?;
11089        emit_op(&mut doc, 754); // i32.sub
11090        emit_u32(&mut doc, 680, 1)?; // local.set 1 (body_end)
11091        emit_i32(&mut doc, 712, 8)?;
11092        emit_u32(&mut doc, 679, 3)?;
11093        emit_mem(&mut doc, 701, 2, 0)?; // mem[8] = out_start
11094
11095        // 3. Skip token 0 (routine identifier)
11096        emit_dctf_len_at_pos(&mut doc)?;
11097        emit_u32(&mut doc, 679, 0)?;
11098        emit_u32(&mut doc, 679, 5)?;
11099        emit_op(&mut doc, 753);
11100        emit_u32(&mut doc, 680, 0)?;
11101
11102        // 4. Verify pos + 20 <=_u body_end
11103        emit_u32(&mut doc, 679, 0)?;
11104        emit_i32(&mut doc, 712, 20)?;
11105        emit_op(&mut doc, 753);
11106        emit_u32(&mut doc, 679, 1)?;
11107        emit_op(&mut doc, 722); // i32.gt_u
11108        emit_trap_if(&mut doc);
11109
11110        let dctf_i32 = |short_id: u32| -> Result<i32> {
11111            let mut s = DcMstring::new();
11112            s.push_char(DcChar::from_short(short_id));
11113            let dc_str = s.to_dc_string()?;
11114            let bytes: [u8; 4] = dc_str.as_bytes().try_into().map_err(|_| {
11115                anyhow!("Expected 4-byte DcTF for short Dc {short_id}")
11116            })?;
11117            Ok(i32::from_le_bytes(bytes))
11118        };
11119
11120        // 5. Verify header tokens 258, 260, 262, 264, 263 at pos + 0..16
11121        for (offset, short_id) in
11122            [(0u32, 258u32), (4, 260), (8, 262), (12, 264), (16, 263)]
11123        {
11124            emit_u32(&mut doc, 679, 0)?;
11125            emit_mem(&mut doc, 687, 0, offset)?;
11126            emit_i32(&mut doc, 712, dctf_i32(short_id)?)?;
11127            emit_op(&mut doc, 718); // i32.ne
11128            emit_trap_if(&mut doc);
11129        }
11130
11131        // 6. Verify closing tokens 261, 259 at body_end + 0..4
11132        for (offset, short_id) in [(0u32, 261u32), (4, 259)] {
11133            emit_u32(&mut doc, 679, 1)?;
11134            emit_mem(&mut doc, 687, 0, offset)?;
11135            emit_i32(&mut doc, 712, dctf_i32(short_id)?)?;
11136            emit_op(&mut doc, 718); // i32.ne
11137            emit_trap_if(&mut doc);
11138        }
11139
11140        // 7. pos += 20
11141        emit_u32(&mut doc, 679, 0)?;
11142        emit_i32(&mut doc, 712, 20)?;
11143        emit_op(&mut doc, 753);
11144        emit_u32(&mut doc, 680, 0)?;
11145
11146        // 8. Payload loop: block { loop { ... } }
11147        emit_op(&mut doc, 649);
11148        doc.push_char(DcChar::from_short(316));
11149        emit_op(&mut doc, 650);
11150        doc.push_char(DcChar::from_short(316));
11151
11152        emit_u32(&mut doc, 679, 0)?;
11153        emit_u32(&mut doc, 679, 1)?;
11154        emit_op(&mut doc, 717); // i32.eq
11155        emit_u32(&mut doc, 660, 1)?; // br_if 1
11156
11157        emit_u32(&mut doc, 679, 0)?;
11158        emit_u32(&mut doc, 679, 1)?;
11159        emit_op(&mut doc, 722); // i32.gt_u
11160        emit_trap_if(&mut doc);
11161
11162        // If pos + 4 <=_u body_end: check premature 261 and escape 255
11163        emit_u32(&mut doc, 679, 0)?;
11164        emit_i32(&mut doc, 712, 4)?;
11165        emit_op(&mut doc, 753);
11166        emit_u32(&mut doc, 679, 1)?;
11167        emit_op(&mut doc, 724); // i32.le_u
11168        emit_op(&mut doc, 651);
11169        doc.push_char(DcChar::from_short(316));
11170
11171        emit_u32(&mut doc, 679, 0)?;
11172        emit_mem(&mut doc, 687, 0, 0)?;
11173        emit_i32(&mut doc, 712, dctf_i32(261)?)?; // 261
11174        emit_op(&mut doc, 717);
11175        emit_trap_if(&mut doc);
11176
11177        emit_u32(&mut doc, 679, 0)?;
11178        emit_mem(&mut doc, 687, 0, 0)?;
11179        emit_i32(&mut doc, 712, dctf_i32(255)?)?; // 255
11180        emit_op(&mut doc, 717);
11181        emit_op(&mut doc, 651);
11182        doc.push_char(DcChar::from_short(316));
11183        emit_u32(&mut doc, 679, 0)?;
11184        emit_i32(&mut doc, 712, 4)?;
11185        emit_op(&mut doc, 753);
11186        emit_u32(&mut doc, 681, 0)?; // pos += 4
11187        emit_u32(&mut doc, 679, 1)?;
11188        emit_op(&mut doc, 726); // i32.ge_u
11189        emit_trap_if(&mut doc);
11190        emit_op(&mut doc, 658); // end if 255
11191
11192        emit_op(&mut doc, 658); // end if pos + 4 <= body_end
11193
11194        // Decode tok_len of payload token at pos
11195        emit_dctf_len_at_pos(&mut doc)?;
11196        emit_u32(&mut doc, 679, 0)?;
11197        emit_u32(&mut doc, 679, 5)?;
11198        emit_op(&mut doc, 753);
11199        emit_u32(&mut doc, 679, 1)?;
11200        emit_op(&mut doc, 722); // i32.gt_u
11201        emit_trap_if(&mut doc);
11202
11203        // Update last_is_lf = (tok_len == 1 && b0 == 10) || (tok_len == 4 && i32.load(pos) == Dc 120)
11204        emit_u32(&mut doc, 679, 5)?;
11205        emit_i32(&mut doc, 712, 1)?;
11206        emit_op(&mut doc, 717);
11207        emit_u32(&mut doc, 679, 4)?;
11208        emit_i32(&mut doc, 712, 10)?;
11209        emit_op(&mut doc, 717);
11210        emit_op(&mut doc, 760); // i32.and
11211        emit_u32(&mut doc, 679, 5)?;
11212        emit_i32(&mut doc, 712, 4)?;
11213        emit_op(&mut doc, 717);
11214        emit_u32(&mut doc, 679, 0)?;
11215        emit_mem(&mut doc, 687, 0, 0)?;
11216        emit_i32(&mut doc, 712, dctf_i32(120)?)?; // Dc 120 ("LF")
11217        emit_op(&mut doc, 717);
11218        emit_op(&mut doc, 760); // i32.and
11219        emit_op(&mut doc, 761); // i32.or
11220        emit_u32(&mut doc, 680, 6)?; // local.set 6 (last_is_lf)
11221
11222        // Copy tok_len bytes from pos to dst
11223        emit_op(&mut doc, 649);
11224        doc.push_char(DcChar::from_short(316));
11225        emit_op(&mut doc, 650);
11226        doc.push_char(DcChar::from_short(316));
11227        emit_u32(&mut doc, 679, 5)?;
11228        emit_op(&mut doc, 716); // i32.eqz
11229        emit_u32(&mut doc, 660, 1)?; // br_if 1
11230        emit_u32(&mut doc, 679, 2)?;
11231        emit_u32(&mut doc, 679, 0)?;
11232        emit_mem(&mut doc, 692, 0, 0)?;
11233        emit_mem(&mut doc, 705, 0, 0)?;
11234        emit_u32(&mut doc, 679, 0)?;
11235        emit_i32(&mut doc, 712, 1)?;
11236        emit_op(&mut doc, 753);
11237        emit_u32(&mut doc, 680, 0)?;
11238        emit_u32(&mut doc, 679, 2)?;
11239        emit_i32(&mut doc, 712, 1)?;
11240        emit_op(&mut doc, 753);
11241        emit_u32(&mut doc, 680, 2)?;
11242        emit_u32(&mut doc, 679, 5)?;
11243        emit_i32(&mut doc, 712, 1)?;
11244        emit_op(&mut doc, 754);
11245        emit_u32(&mut doc, 680, 5)?;
11246        emit_u32(&mut doc, 659, 0)?; // br 0
11247        emit_op(&mut doc, 658); // end inner loop
11248        emit_op(&mut doc, 658); // end inner block
11249
11250        emit_u32(&mut doc, 659, 0)?; // br 0 (outer payload loop)
11251        emit_op(&mut doc, 658); // end outer loop
11252        emit_op(&mut doc, 658); // end outer block
11253
11254        // 9. Append '\n' if last_is_lf == 0
11255        emit_u32(&mut doc, 679, 6)?;
11256        emit_op(&mut doc, 716); // i32.eqz
11257        emit_op(&mut doc, 651);
11258        doc.push_char(DcChar::from_short(316));
11259        emit_u32(&mut doc, 679, 2)?;
11260        emit_i32(&mut doc, 712, 10)?;
11261        emit_mem(&mut doc, 705, 0, 0)?;
11262        emit_u32(&mut doc, 679, 2)?;
11263        emit_i32(&mut doc, 712, 1)?;
11264        emit_op(&mut doc, 753);
11265        emit_u32(&mut doc, 680, 2)?;
11266        emit_op(&mut doc, 658);
11267
11268        // 10. mem[12] = dst - out_start; return 0
11269        emit_i32(&mut doc, 712, 12)?;
11270        emit_u32(&mut doc, 679, 2)?;
11271        emit_u32(&mut doc, 679, 3)?;
11272        emit_op(&mut doc, 754);
11273        emit_mem(&mut doc, 701, 2, 0)?;
11274        emit_i32(&mut doc, 712, 0)?;
11275
11276        doc.push_char(DcChar::from_short(261));
11277        doc.push_char(DcChar::from_short(1928));
11278
11279        Ok(doc
11280            .to_dc_string()?
11281            .chars()
11282            .map(|ch| DcShorthand::from_global_id(ch.to_u128()))
11283            .collect())
11284    }
11285
11286    fn build_supervisor_wasm_shorthands() -> Result<Vec<DcShorthand>> {
11287        let i32_dc = i32_type_dc();
11288        let mut doc = DcMstring::new();
11289        doc.push_char(DcChar::from_short(1927));
11290        doc.push_char(DcChar::from_short(260));
11291        doc.push_char(DcChar::from_short(262));
11292        doc.push_char(DcChar::from_short(280));
11293        doc.push_char(i32_dc);
11294        doc.push_char(DcChar::from_short(263));
11295
11296        // 5 i32 locals: 0=pos, 1=in_end, 2=idx, 3=b0, 4=dst
11297        doc.push_char(DcChar::from_short(310));
11298        doc.push_char(DcChar::from_short(565));
11299        for idx in 0..5 {
11300            if idx > 0 {
11301                doc.push_char(DcChar::from_short(312));
11302            }
11303            doc.push_char(i32_dc);
11304        }
11305        doc.push_char(DcChar::from_short(311));
11306
11307        let emit_op = |out: &mut DcMstring, op: u32| {
11308            out.push_char(DcChar::from_short(op));
11309        };
11310        let emit_u32 = |out: &mut DcMstring, op: u32, val: u32| -> Result<()> {
11311            out.push_char(DcChar::from_short(op));
11312            val.encode_dc_mixed(out)
11313        };
11314        let emit_i32 = |out: &mut DcMstring, op: u32, val: i32| -> Result<()> {
11315            out.push_char(DcChar::from_short(op));
11316            val.encode_dc_mixed(out)
11317        };
11318        let emit_i64 = |out: &mut DcMstring, op: u32, val: i64| -> Result<()> {
11319            out.push_char(DcChar::from_short(op));
11320            val.encode_dc_mixed(out)
11321        };
11322        let emit_mem =
11323            |out: &mut DcMstring, op: u32, align: u32, offset: u32| -> Result<()> {
11324                out.push_char(DcChar::from_short(op));
11325                0u32.encode_dc_mixed(out)?;
11326                align.encode_dc_mixed(out)?;
11327                offset.encode_dc_mixed(out)
11328            };
11329        let emit_trap_if = |out: &mut DcMstring| {
11330            out.push_char(DcChar::from_short(651));
11331            out.push_char(DcChar::from_short(316));
11332            out.push_char(DcChar::from_short(647));
11333            out.push_char(DcChar::from_short(658));
11334        };
11335
11336        // 1. pos = in_ptr, in_end = dst = in_ptr + in_len, mem[8] = dst
11337        emit_i32(&mut doc, 712, 0)?;
11338        emit_mem(&mut doc, 687, 2, 0)?;
11339        emit_u32(&mut doc, 681, 0)?; // local.tee 0 (pos)
11340        emit_i32(&mut doc, 712, 4)?;
11341        emit_mem(&mut doc, 687, 2, 0)?;
11342        emit_op(&mut doc, 753); // i32.add
11343        emit_u32(&mut doc, 681, 1)?; // local.tee 1 (in_end)
11344        emit_u32(&mut doc, 680, 4)?; // local.set 4 (dst)
11345        emit_i32(&mut doc, 712, 8)?;
11346        emit_u32(&mut doc, 679, 4)?;
11347        emit_mem(&mut doc, 701, 2, 0)?; // mem[8] = dst
11348
11349        // 2. If in_len == 0 (pos == in_end): synthesize default 76-byte config at mem[64..140]
11350        emit_u32(&mut doc, 679, 0)?;
11351        emit_u32(&mut doc, 679, 1)?;
11352        emit_op(&mut doc, 717); // i32.eq
11353        emit_op(&mut doc, 651); // if
11354        doc.push_char(DcChar::from_short(316));
11355
11356        emit_i32(&mut doc, 712, 64)?;
11357        emit_i32(&mut doc, 712, 2)?;
11358        emit_mem(&mut doc, 701, 2, 0)?; // accounting_version = 2
11359        for (addr, val) in [
11360            (68i32, 10_000_000_i64),
11361            (76, 256),
11362            (84, -1),
11363            (92, 65_536),
11364            (100, -1),
11365            (108, 4_194_304),
11366            (116, 16_777_216),
11367            (124, 1_048_576),
11368            (132, 16_777_216),
11369        ] {
11370            emit_i32(&mut doc, 712, addr)?;
11371            emit_i64(&mut doc, 713, val)?;
11372            emit_mem(&mut doc, 702, 0, 0)?;
11373        }
11374
11375        emit_op(&mut doc, 652); // else: decode UTF-8 bytes from pos..in_end into mem[64..140]
11376        emit_i32(&mut doc, 712, 0)?;
11377        emit_u32(&mut doc, 680, 2)?; // idx = 0
11378        emit_op(&mut doc, 649);
11379        doc.push_char(DcChar::from_short(316));
11380        emit_op(&mut doc, 650);
11381        doc.push_char(DcChar::from_short(316));
11382
11383        emit_u32(&mut doc, 679, 0)?;
11384        emit_u32(&mut doc, 679, 1)?;
11385        emit_op(&mut doc, 717);
11386        emit_u32(&mut doc, 660, 1)?; // br_if 1
11387
11388        emit_u32(&mut doc, 679, 2)?;
11389        emit_i32(&mut doc, 712, 76)?;
11390        emit_op(&mut doc, 726); // i32.ge_u
11391        emit_trap_if(&mut doc);
11392
11393        emit_u32(&mut doc, 679, 0)?;
11394        emit_mem(&mut doc, 692, 0, 0)?;
11395        emit_u32(&mut doc, 681, 3)?; // b0
11396        emit_i32(&mut doc, 712, 128)?;
11397        emit_op(&mut doc, 720); // i32.lt_u
11398        emit_op(&mut doc, 651);
11399        doc.push_char(DcChar::from_short(316));
11400        emit_u32(&mut doc, 679, 0)?;
11401        emit_i32(&mut doc, 712, 1)?;
11402        emit_op(&mut doc, 753);
11403        emit_u32(&mut doc, 680, 0)?;
11404        emit_op(&mut doc, 652); // else: 2-byte UTF-8
11405        emit_u32(&mut doc, 679, 0)?;
11406        emit_i32(&mut doc, 712, 2)?;
11407        emit_op(&mut doc, 753);
11408        emit_u32(&mut doc, 679, 1)?;
11409        emit_op(&mut doc, 722); // i32.gt_u
11410        emit_trap_if(&mut doc);
11411        emit_u32(&mut doc, 679, 3)?;
11412        emit_i32(&mut doc, 712, 254)?;
11413        emit_op(&mut doc, 760);
11414        emit_i32(&mut doc, 712, 194)?;
11415        emit_op(&mut doc, 718); // i32.ne
11416        emit_trap_if(&mut doc);
11417        emit_u32(&mut doc, 679, 3)?;
11418        emit_i32(&mut doc, 712, 3)?;
11419        emit_op(&mut doc, 760);
11420        emit_i32(&mut doc, 712, 6)?;
11421        emit_op(&mut doc, 763);
11422        emit_u32(&mut doc, 679, 0)?;
11423        emit_mem(&mut doc, 692, 0, 1)?;
11424        emit_i32(&mut doc, 712, 63)?;
11425        emit_op(&mut doc, 760);
11426        emit_op(&mut doc, 761);
11427        emit_u32(&mut doc, 680, 3)?;
11428        emit_u32(&mut doc, 679, 0)?;
11429        emit_i32(&mut doc, 712, 2)?;
11430        emit_op(&mut doc, 753);
11431        emit_u32(&mut doc, 680, 0)?;
11432        emit_op(&mut doc, 658); // end if b0 < 128
11433
11434        emit_u32(&mut doc, 679, 2)?;
11435        emit_u32(&mut doc, 679, 3)?;
11436        emit_mem(&mut doc, 705, 0, 64)?; // mem[64 + idx] = byte
11437        emit_u32(&mut doc, 679, 2)?;
11438        emit_i32(&mut doc, 712, 1)?;
11439        emit_op(&mut doc, 753);
11440        emit_u32(&mut doc, 680, 2)?;
11441        emit_u32(&mut doc, 659, 0)?; // br 0
11442        emit_op(&mut doc, 658); // end loop
11443        emit_op(&mut doc, 658); // end block
11444
11445        emit_u32(&mut doc, 679, 2)?;
11446        emit_i32(&mut doc, 712, 76)?;
11447        emit_op(&mut doc, 718); // i32.ne
11448        emit_trap_if(&mut doc);
11449
11450        emit_op(&mut doc, 658); // end if in_len == 0
11451
11452        // 3. Validate accounting_version == 2, max_instructions_per_step > 0, max_memory_pages > 0
11453        emit_i32(&mut doc, 712, 64)?;
11454        emit_mem(&mut doc, 687, 2, 0)?;
11455        emit_i32(&mut doc, 712, 2)?;
11456        emit_op(&mut doc, 718);
11457        emit_trap_if(&mut doc);
11458
11459        emit_i32(&mut doc, 712, 68)?;
11460        emit_mem(&mut doc, 688, 0, 0)?;
11461        emit_op(&mut doc, 727); // i64.eqz
11462        emit_trap_if(&mut doc);
11463
11464        emit_i32(&mut doc, 712, 76)?;
11465        emit_mem(&mut doc, 688, 0, 0)?;
11466        emit_op(&mut doc, 727); // i64.eqz
11467        emit_trap_if(&mut doc);
11468
11469        // 4. Encode mem[64..140] as 76 UTF-8 characters into dst
11470        emit_i32(&mut doc, 712, 0)?;
11471        emit_u32(&mut doc, 680, 2)?; // idx = 0
11472        emit_op(&mut doc, 649);
11473        doc.push_char(DcChar::from_short(316));
11474        emit_op(&mut doc, 650);
11475        doc.push_char(DcChar::from_short(316));
11476
11477        emit_u32(&mut doc, 679, 2)?;
11478        emit_i32(&mut doc, 712, 76)?;
11479        emit_op(&mut doc, 717);
11480        emit_u32(&mut doc, 660, 1)?; // br_if 1
11481
11482        emit_u32(&mut doc, 679, 2)?;
11483        emit_mem(&mut doc, 692, 0, 64)?;
11484        emit_u32(&mut doc, 681, 3)?; // b0
11485        emit_i32(&mut doc, 712, 128)?;
11486        emit_op(&mut doc, 720); // i32.lt_u
11487        emit_op(&mut doc, 651);
11488        doc.push_char(DcChar::from_short(316));
11489        emit_u32(&mut doc, 679, 4)?;
11490        emit_u32(&mut doc, 679, 3)?;
11491        emit_mem(&mut doc, 705, 0, 0)?;
11492        emit_u32(&mut doc, 679, 4)?;
11493        emit_i32(&mut doc, 712, 1)?;
11494        emit_op(&mut doc, 753);
11495        emit_u32(&mut doc, 680, 4)?;
11496        emit_op(&mut doc, 652); // else: 2-byte UTF-8
11497        emit_u32(&mut doc, 679, 4)?;
11498        emit_u32(&mut doc, 679, 3)?;
11499        emit_i32(&mut doc, 712, 6)?;
11500        emit_op(&mut doc, 765);
11501        emit_i32(&mut doc, 712, 192)?;
11502        emit_op(&mut doc, 761);
11503        emit_mem(&mut doc, 705, 0, 0)?;
11504        emit_u32(&mut doc, 679, 4)?;
11505        emit_u32(&mut doc, 679, 3)?;
11506        emit_i32(&mut doc, 712, 63)?;
11507        emit_op(&mut doc, 760);
11508        emit_i32(&mut doc, 712, 128)?;
11509        emit_op(&mut doc, 761);
11510        emit_mem(&mut doc, 705, 0, 1)?;
11511        emit_u32(&mut doc, 679, 4)?;
11512        emit_i32(&mut doc, 712, 2)?;
11513        emit_op(&mut doc, 753);
11514        emit_u32(&mut doc, 680, 4)?;
11515        emit_op(&mut doc, 658);
11516
11517        emit_u32(&mut doc, 679, 2)?;
11518        emit_i32(&mut doc, 712, 1)?;
11519        emit_op(&mut doc, 753);
11520        emit_u32(&mut doc, 680, 2)?;
11521        emit_u32(&mut doc, 659, 0)?; // br 0
11522        emit_op(&mut doc, 658); // end loop
11523        emit_op(&mut doc, 658); // end block
11524
11525        // 5. mem[12] = dst - in_end; return 0
11526        emit_i32(&mut doc, 712, 12)?;
11527        emit_u32(&mut doc, 679, 4)?;
11528        emit_u32(&mut doc, 679, 1)?;
11529        emit_op(&mut doc, 754);
11530        emit_mem(&mut doc, 701, 2, 0)?;
11531        emit_i32(&mut doc, 712, 0)?;
11532
11533        doc.push_char(DcChar::from_short(261));
11534        doc.push_char(DcChar::from_short(1928));
11535
11536        Ok(doc
11537            .to_dc_string()?
11538            .chars()
11539            .map(|ch| DcShorthand::from_global_id(ch.to_u128()))
11540            .collect())
11541    }
11542
11543    #[crate::ctb_test]
11544    fn test_builtin_graph_wasm_routines() -> Result<()> {
11545        let resolver = default_syntax_resolver();
11546        let lang_say_shorthands = build_lang_say_wasm_shorthands()?;
11547        let sup_shorthands = build_supervisor_wasm_shorthands()?;
11548
11549        // 1. Verify lang.say .WASM routine across all cases:
11550        for (payload, expected) in [
11551            (Vec::new(), vec![DcChar::from('\n')]),
11552            (
11553                vec![DcChar::from('A')],
11554                vec![DcChar::from('A'), DcChar::from('\n')],
11555            ),
11556            (
11557                vec![DcChar::from('A'), DcChar::from('\n')],
11558                vec![DcChar::from('A'), DcChar::from('\n')],
11559            ),
11560            (
11561                vec![DcChar::from('\r'), DcChar::from('\n')],
11562                vec![DcChar::from('\r'), DcChar::from('\n')],
11563            ),
11564            (
11565                vec![DcChar::from('\r')],
11566                vec![DcChar::from('\r'), DcChar::from('\n')],
11567            ),
11568            (vec![DcChar::from_short(120)], vec![DcChar::from_short(120)]),
11569            (
11570                vec![DcChar::from_short(255), DcChar::from_short(261)],
11571                vec![
11572                    DcChar::from_short(255),
11573                    DcChar::from_short(261),
11574                    DcChar::from('\n'),
11575                ],
11576            ),
11577        ] {
11578            let mut call = DcMstring::new();
11579            call.push_char(DcChar::from_short(256));
11580            call.push_char(DcChar::from_short(258));
11581            let text: DcMstring = payload.into_iter().collect();
11582            text.encode_dc_mixed(&mut call)?;
11583            call.push_char(DcChar::from_short(259));
11584            let call_tokens: Vec<DcChar> = call.to_dc_string()?.chars().collect();
11585            let out_doc = run_graph_wasm_tokens_on_dc_slice_with_quota(
11586                &lang_say_shorthands,
11587                &call_tokens,
11588                resolver.as_ref(),
11589                None,
11590            )?;
11591            let actual: Vec<DcChar> = out_doc.to_dc_string()?.chars().collect();
11592            assert_eq!(actual, expected);
11593
11594            // Missing trailing 259 must trap:
11595            assert!(
11596                run_graph_wasm_tokens_on_dc_slice_with_quota(
11597                    &lang_say_shorthands,
11598                    &call_tokens[..call_tokens.len() - 1],
11599                    resolver.as_ref(),
11600                    None,
11601                )
11602                .is_err()
11603            );
11604        }
11605
11606        // Non-string literal type (280) must trap:
11607        let non_string_tokens = [
11608            DcChar::from_short(256),
11609            DcChar::from_short(258),
11610            DcChar::from_short(260),
11611            DcChar::from_short(262),
11612            DcChar::from_short(280),
11613            DcChar::from_short(263),
11614            DcChar::from('A'),
11615            DcChar::from_short(261),
11616            DcChar::from_short(259),
11617        ];
11618        assert!(
11619            run_graph_wasm_tokens_on_dc_slice_with_quota(
11620                &lang_say_shorthands,
11621                &non_string_tokens,
11622                resolver.as_ref(),
11623                None,
11624            )
11625            .is_err()
11626        );
11627
11628        // 2. Verify supervisor .WASM routine (empty input -> default limits; valid config -> roundtrip; invalid -> trap):
11629        let empty_out = run_graph_wasm_tokens_on_dc_slice_with_quota(
11630            &sup_shorthands,
11631            &[],
11632            resolver.as_ref(),
11633            None,
11634        )?;
11635        let empty_bytes: Vec<u8> = empty_out
11636            .to_dc_string()?
11637            .chars()
11638            .map(|c| u8::try_from(c.to_unicode().unwrap()).unwrap())
11639            .collect();
11640        assert_eq!(
11641            DcWasmResourceLimits::decode_canonical_config_bytes(&empty_bytes)?,
11642            DcWasmResourceLimits::default()
11643        );
11644
11645        let custom_limits = DcWasmResourceLimits::default()
11646            .with_max_instructions_per_step(5_000)
11647            .with_max_memory_pages(32);
11648        let custom_tokens: Vec<DcChar> = custom_limits
11649            .encode_canonical_config_bytes()
11650            .into_iter()
11651            .map(|b| DcChar::from_unicode(u32::from(b)).unwrap())
11652            .collect();
11653        let custom_out = run_graph_wasm_tokens_on_dc_slice_with_quota(
11654            &sup_shorthands,
11655            &custom_tokens,
11656            resolver.as_ref(),
11657            None,
11658        )?;
11659        let custom_out_bytes: Vec<u8> = custom_out
11660            .to_dc_string()?
11661            .chars()
11662            .map(|c| u8::try_from(c.to_unicode().unwrap()).unwrap())
11663            .collect();
11664        assert_eq!(
11665            DcWasmResourceLimits::decode_canonical_config_bytes(
11666                &custom_out_bytes
11667            )?,
11668            custom_limits
11669        );
11670
11671        for invalid in [
11672            DcWasmResourceLimits {
11673                accounting_version: 1,
11674                ..DcWasmResourceLimits::default()
11675            },
11676            DcWasmResourceLimits {
11677                accounting_version: 3,
11678                ..DcWasmResourceLimits::default()
11679            },
11680            DcWasmResourceLimits::default().with_max_instructions_per_step(0),
11681            DcWasmResourceLimits::default().with_max_memory_pages(0),
11682        ] {
11683            let bad_tokens: Vec<DcChar> = invalid
11684                .encode_canonical_config_bytes()
11685                .into_iter()
11686                .map(|b| DcChar::from_unicode(u32::from(b)).unwrap())
11687                .collect();
11688            assert!(
11689                run_graph_wasm_tokens_on_dc_slice_with_quota(
11690                    &sup_shorthands,
11691                    &bad_tokens,
11692                    resolver.as_ref(),
11693                    None,
11694                )
11695                .is_err()
11696            );
11697        }
11698
11699        // Dc 256 (lang.say) belongs to Stage 2 (impls/) in the VSO language, so it has no Stage 0 .wat definition yet.
11700        assert_eq!(
11701            resolver
11702                .resolve_wasm_definition_tokens(DcChar::from_short(256).to_u128()),
11703            None,
11704            "Dc 256 (lang.say) belongs in Stage 2 (impls/), not Stage 0 (.wat)"
11705        );
11706        let sg = resolver
11707            .seed_graph()
11708            .expect("Default syntax resolver must expose SeedGraphIndex");
11709        assert_eq!(
11710            resolver
11711                .resolve_wasm_definition_tokens(DcChar::from_short(1936).to_u128())
11712                .map(|tokens| sg.expand_interned_string_nodes(tokens))
11713                .as_deref(),
11714            Some(sup_shorthands.as_slice()),
11715            "Dc 1936 (Dc document execution kernel) expanded graph .WASM definition must match build_supervisor_wasm_shorthands()"
11716        );
11717        assert_eq!(
11718            resolver
11719                .resolve_wasm_definition_tokens(DcChar::from_short(1937).to_u128())
11720                .map(|tokens| sg.expand_interned_string_nodes(tokens))
11721                .as_deref(),
11722            Some(sup_shorthands.as_slice()),
11723            "Dc 1937 (Collective Toolbox Workspace) expanded graph .WASM definition must match build_supervisor_wasm_shorthands()"
11724        );
11725        Ok(())
11726    }
11727
11728    #[crate::ctb_test]
11729    fn test_all_stage_0_wat_builtins_assemble_and_resolve_in_system_graph()
11730    -> Result<()> {
11731        use ctb_formats_dcdata::support::wat::{ImplStage, load_staged_dc_impls};
11732
11733        let data_src_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11734            .join("../dcdata/data-src");
11735        let (staged, _) = load_staged_dc_impls(&data_src_dir)?;
11736        let resolver = default_syntax_resolver();
11737
11738        let mut stage0_count = 0usize;
11739        for item in &staged {
11740            if item.stage != ImplStage::Stage0 {
11741                continue;
11742            }
11743            stage0_count = stage0_count.saturating_add(1);
11744
11745            let resolved = if item.context_tokens.is_empty() {
11746                resolver
11747                    .resolve_wasm_definition_tokens(item.target.to_global_id()?)
11748            } else {
11749                resolver.resolve_wasm_definition_tokens_in_context(
11750                    item.target.to_global_id()?,
11751                    &item.context_tokens,
11752                )
11753            }
11754            .with_context(|| {
11755                format!(
11756                    "Missing System graph .WASM entry for {} (target={}, ctx={:?})",
11757                    item.rel_path, item.target, item.context_tokens
11758                )
11759            })?;
11760
11761            let mut raw_doc = DcMstring::new();
11762            for tok in &item.tokens {
11763                raw_doc.push_char(DcChar::from_u128(tok.to_global_id()?));
11764            }
11765            let raw_wasm_bytes =
11766                dcmstring_to_wasm_with_resolver(&raw_doc, resolver.as_ref())
11767                    .with_context(|| {
11768                        format!(
11769                            "Failed to assemble raw Stage 0 .wat entry {} (ctx={:?})",
11770                            item.rel_path, item.context_tokens
11771                        )
11772                    })?;
11773
11774            let mut graph_doc = DcMstring::new();
11775            for tok in resolved {
11776                graph_doc.push_char(DcChar::from_u128(tok.to_global_id()?));
11777            }
11778            let wasm_bytes =
11779                dcmstring_to_wasm_with_resolver(&graph_doc, resolver.as_ref())
11780                    .with_context(|| {
11781                        format!(
11782                            "Failed to assemble System graph .WASM entry {} (ctx={:?})",
11783                            item.rel_path, item.context_tokens
11784                        )
11785                    })?;
11786            assert_eq!(
11787                wasm_bytes, raw_wasm_bytes,
11788                "Assembled .wasm mismatch between System graph and raw .wat for {} (ctx={:?})",
11789                item.rel_path, item.context_tokens
11790            );
11791            let _ = crate::converters::wasm_quota::instrument_wasm_module_bytes(
11792                &wasm_bytes,
11793            )
11794            .with_context(|| {
11795                format!(
11796                    "Quota instrumentation failed for {} (ctx={:?})",
11797                    item.rel_path, item.context_tokens
11798                )
11799            })?;
11800            let _ = ctb_formats_dcdata::tinywasm::Module::parse_bytes(&wasm_bytes)
11801                .map_err(|e| {
11802                    anyhow!(
11803                        "tinywasm parse failed for {} (ctx={:?}): {e:?}",
11804                        item.rel_path,
11805                        item.context_tokens
11806                    )
11807                })?;
11808        }
11809        assert!(
11810            stage0_count >= 170,
11811            "Expected >= 170 Stage 0 .wat entries across all 40 files, got {stage0_count}"
11812        );
11813
11814        // Verify wildcard prefix resolution (`275` `*`) for polymorphic sequence/nested-list ops.
11815        let len_l_u8 = resolver.resolve_wasm_definition_tokens_in_context(
11816            DcChar::from_short(2543).to_u128(),
11817            &[DcShorthand::Short(2576), DcShorthand::Format(203)],
11818        );
11819        assert!(
11820            len_l_u8.is_some(),
11821            "Dc 2543 (len) must resolve `2576 f203` via `2576 275` wildcard"
11822        );
11823        let get_nested_list = resolver.resolve_wasm_definition_tokens_in_context(
11824            DcChar::from_short(2544).to_u128(),
11825            &[
11826                DcShorthand::Short(2576),
11827                DcShorthand::Short(2576),
11828                DcShorthand::Format(208),
11829            ],
11830        );
11831        assert!(
11832            get_nested_list.is_some(),
11833            "Dc 2544 (get) must resolve `2576 2576 f208` via `2576 2576 275` wildcard"
11834        );
11835        Ok(())
11836    }
11837
11838    #[crate::ctb_test]
11839    fn test_dcmstring_to_wasm_rejects_stagel_types_in_wasm_valtype() -> Result<()> {
11840        // Routine `1927 260 262 280 262 2576 f208 263 263 712 6 f199 127 7 261 1928`
11841        // attempts to use StageL list type `2576` (`l/i32`) as a `.WASM` return type.
11842        // `.WASM` lowering must not depend on StageL Dcs (`2576`/`2577`).
11843        let resolver = default_syntax_resolver();
11844        for stagel_ty_short in [2576u32, 2577u32] {
11845            let shorthands = [
11846                DcShorthand::Short(1927),
11847                DcShorthand::Short(260),
11848                DcShorthand::Short(262),
11849                DcShorthand::Short(280),
11850                DcShorthand::Short(262),
11851                DcShorthand::Short(stagel_ty_short),
11852                DcShorthand::Format(208),
11853                DcShorthand::Short(263),
11854                DcShorthand::Short(263),
11855                DcShorthand::Short(712),
11856                DcShorthand::Short(6),
11857                DcShorthand::Format(199),
11858                DcShorthand::Short(127),
11859                DcShorthand::Short(7),
11860                DcShorthand::Short(261),
11861                DcShorthand::Short(1928),
11862            ];
11863            let mut mstr = DcMstring::new();
11864            for sh in shorthands {
11865                mstr.push_char(DcChar::from_u128(sh.to_global_id()?));
11866            }
11867            assert!(
11868                dcmstring_to_wasm_with_resolver(&mstr, resolver.as_ref()).is_err(),
11869                "dcmstring_to_wasm must reject StageL Dc {stagel_ty_short} inside .WASM valtype"
11870            );
11871        }
11872        Ok(())
11873    }
11874
11875    #[crate::ctb_test]
11876    fn test_option_b_mid_step_capability_yield_preserves_live_heap_and_quota()
11877    -> Result<()> {
11878        let mk_dcmst = |s: &str| -> DcMstring {
11879            let mut m = DcMstring::new();
11880            for ch in s.chars() {
11881                m.push_char(DcChar::from_char(ch));
11882            }
11883            m
11884        };
11885
11886        // Module with exported `__heap_ptr` and `__ctb_capability_yield`:
11887        // - Preserves live locals + heap data across two consecutive mid-step yields.
11888        // - Returns concatenation of (first half of initial input) + resp1 + resp2.
11889        let wat = r#"
11890            (module
11891              (memory (export "memory") 1)
11892              (global $__heap_ptr (export "__heap_ptr") (mut i32) (i32.const 256))
11893              (func $__ctb_capability_yield (export "__ctb_capability_yield"))
11894              (func (export "step") (result i32)
11895                (local $in_ptr i32)
11896                (local $in_len i32)
11897                (local $half i32)
11898                (local $heap_buf i32)
11899                (local $req1_ptr i32)
11900                (local $req2_ptr i32)
11901                (local $r1_ptr i32)
11902                (local $r1_len i32)
11903                (local $r2_ptr i32)
11904                (local $r2_len i32)
11905                (local $out_ptr i32)
11906                (local $out_total i32)
11907
11908                (local.set $in_ptr (i32.load (i32.const 0)))
11909                (local.set $in_len (i32.load (i32.const 4)))
11910                (local.set $half (i32.div_u (local.get $in_len) (i32.const 2)))
11911                ;; Ensure heap starts strictly above initial input slice (base_io_offset + in_len).
11912                (local.set $heap_buf (i32.add (local.get $in_ptr) (local.get $in_len)))
11913                (local.set $heap_buf (i32.and (i32.add (local.get $heap_buf) (i32.const 7)) (i32.const -8)))
11914                ;; Copy full initial input to $heap_buf as long-lived heap data across yields.
11915                (memory.copy (local.get $heap_buf) (local.get $in_ptr) (local.get $in_len))
11916                (local.set $req1_ptr (local.get $heap_buf))
11917                (local.set $req2_ptr (i32.add (local.get $heap_buf) (local.get $half)))
11918                (global.set $__heap_ptr (i32.add (local.get $heap_buf) (i32.const 64)))
11919
11920                ;; Yield 1: send first half of input.
11921                (i32.store (i32.const 8) (local.get $req1_ptr))
11922                (i32.store (i32.const 12) (local.get $half))
11923                (call $__ctb_capability_yield)
11924
11925                ;; After Resume 1: resp1 must be placed >= old $__heap_ptr ($heap_buf + 64).
11926                (local.set $r1_ptr (i32.load (i32.const 0)))
11927                (local.set $r1_len (i32.load (i32.const 4)))
11928                (if (i32.lt_u (local.get $r1_ptr) (i32.add (local.get $heap_buf) (i32.const 64)))
11929                  (then (unreachable)))
11930
11931                ;; Yield 2: send second half from preserved heap buffer.
11932                (i32.store (i32.const 8) (local.get $req2_ptr))
11933                (i32.store (i32.const 12) (i32.sub (local.get $in_len) (local.get $half)))
11934                (call $__ctb_capability_yield)
11935
11936                ;; After Resume 2: resp2 must not overwrite $heap_buf or $r1_ptr.
11937                (local.set $r2_ptr (i32.load (i32.const 0)))
11938                (local.set $r2_len (i32.load (i32.const 4)))
11939                (if (i32.lt_u (local.get $r2_ptr) (i32.add (local.get $r1_ptr) (local.get $r1_len)))
11940                  (then (unreachable)))
11941
11942                ;; Write combined output above $__heap_ptr: [req1][r1][r2].
11943                (local.set $out_ptr (global.get $__heap_ptr))
11944                (memory.copy (local.get $out_ptr) (local.get $req1_ptr) (local.get $half))
11945                (memory.copy (i32.add (local.get $out_ptr) (local.get $half)) (local.get $r1_ptr) (local.get $r1_len))
11946                (memory.copy
11947                  (i32.add (local.get $out_ptr) (i32.add (local.get $half) (local.get $r1_len)))
11948                  (local.get $r2_ptr)
11949                  (local.get $r2_len))
11950                (local.set $out_total
11951                  (i32.add (local.get $half) (i32.add (local.get $r1_len) (local.get $r2_len))))
11952                (i32.store (i32.const 8) (local.get $out_ptr))
11953                (i32.store (i32.const 12) (local.get $out_total))
11954                (i32.const 0)))
11955        "#;
11956        let wasm_bytes = crate::converters::wat::wat_to_wasm(wat)?;
11957        let shared = SharedWasmTaskQuota::new(
11958            DcWasmResourceLimits::default().with_max_instructions_per_step(50_000),
11959        );
11960        let init_doc = mk_dcmst("AABB");
11961        let mut session = DcWasmSession::from_wasm_bytes(
11962            &wasm_bytes,
11963            &init_doc,
11964            None,
11965        )?
11966        .with_shared_task_quota(shared.clone())?;
11967
11968        let WasmStepOutcome::RequestCapability(req1) = session.step()? else {
11969            bail!("Expected first mid-step capability request");
11970        };
11971        assert_eq!(req1, mk_dcmst("AA"));
11972        session.provide_capability_response(&mk_dcmst("R1"))?;
11973
11974        let WasmStepOutcome::RequestCapability(req2) = session.step()? else {
11975            bail!("Expected second mid-step capability request");
11976        };
11977        assert_eq!(req2, mk_dcmst("BB"));
11978        session.provide_capability_response(&mk_dcmst("R2"))?;
11979
11980        let WasmStepOutcome::Complete(final_doc) = session.step()? else {
11981            bail!("Expected completion after two capability resumes");
11982        };
11983        assert_eq!(final_doc, mk_dcmst("AAR1R2"));
11984        let snap = shared.snapshot()?;
11985        assert!(snap.total_instructions_executed > 0);
11986        assert_eq!(
11987            snap.total_instructions_executed,
11988            session.total_instructions_executed()
11989        );
11990
11991        // Reserved `__ctb_capability_yield` with wrong signature must be rejected.
11992        let bad_wat = r#"
11993            (module
11994              (func (export "__ctb_capability_yield") (param i32) (result i32)
11995                (local.get 0))
11996              (func (export "main") (result i32) (i32.const 0)))
11997        "#;
11998        let bad_wasm = crate::converters::wat::wat_to_wasm(bad_wat)?;
11999        assert!(
12000            instrument_wasm_module_bytes(&bad_wasm).is_err(),
12001            "__ctb_capability_yield with non-() signature must fail instrumentation"
12002        );
12003        Ok(())
12004    }
12005
12006    #[crate::ctb_test]
12007    fn test_symbolic_wasm_call_and_global_targets_forward_refs_and_unknown_error()
12008     -> Result<()> {
12009        // Forward-calling WAT module where `main` precedes `$forward_helper` and a data segment
12010        // precedes `$g_count` (testing both forward function resolution and data+global index order).
12011        let wat = r#"
12012            (module
12013              (memory (export "memory") 1)
12014              (data $banner "OK")
12015              (global $g_count (mut i32) (i32.const 5))
12016              (func (export "main") (result i32)
12017                (global.set $g_count (call $forward_helper (global.get $g_count)))
12018                (i32.store (i32.const 8) (i32.const 512))
12019                (if (i32.eq (global.get $g_count) (i32.const 42))
12020                  (then
12021                    (i32.store8 (i32.const 512) (i32.load8_u (i32.const 32)))
12022                    (i32.store8 (i32.const 513) (i32.load8_u (i32.const 33)))
12023                    (i32.store (i32.const 12) (i32.const 2)))
12024                  (else
12025                    (unreachable)))
12026                (i32.const 0))
12027              (func $forward_helper (param $x i32) (result i32)
12028                (i32.add (local.get $x) (i32.const 37))))
12029        "#;
12030        let mk_dcmst = |s: &str| -> DcMstring {
12031            let mut m = DcMstring::new();
12032            for ch in s.chars() {
12033                m.push_char(DcChar::from_unicode(u32::from(ch)).unwrap());
12034            }
12035            m
12036        };
12037        let wasm_bytes = crate::converters::wat::wat_to_wasm(wat)?;
12038        let mut sess =
12039            DcWasmSession::from_wasm_bytes(&wasm_bytes, &mk_dcmst(""), None)?;
12040        let WasmStepOutcome::Complete(out) = sess.step()? else {
12041            bail!("Expected Complete from symbolic forward-calling WAT test");
12042        };
12043        assert_eq!(out, mk_dcmst("OK"));
12044
12045        // Corrupt a symbolic call target to an unknown identifier and verify descriptive error.
12046        let mut shorthands =
12047            ctb_formats_dcdata::support::wat::wat_to_dc_shorthands(wat)?;
12048        // Replace Unicode 'f' (`u66`) in `forward_helper` call target inside `main` with 'z' (`u7a`).
12049        let first_f_pos = shorthands
12050            .iter()
12051            .position(|&t| t == ctb_storage_minimal::shorthand::DcShorthand::Unicode(u32::from(b'f')))
12052            .unwrap();
12053        shorthands[first_f_pos] =
12054            ctb_storage_minimal::shorthand::DcShorthand::Unicode(u32::from(b'z'));
12055        let mut bad_mstr = DcMstring::new();
12056        for sh in shorthands {
12057            bad_mstr.push_char(DcChar::from_u128(sh.to_global_id()?));
12058        }
12059        let err = dcmstring_to_wasm(&bad_mstr).unwrap_err();
12060        assert!(
12061            err.to_string()
12062                .contains("Unknown symbolic WASM function target 'zorward_helper'"),
12063            "Unexpected error: {err}"
12064        );
12065        Ok(())
12066    }
12067
12068    #[crate::ctb_test]
12069    fn test_pure_wasm_memoization_quota_fidelity_and_routine_profiler()
12070    -> Result<()> {
12071        let wat = r#"
12072            (module
12073              (memory (export "memory") 1)
12074              (func (export "step") (result i32)
12075                (local $i i32)
12076                (loop $l
12077                  (local.set $i (i32.add (local.get $i) (i32.const 1)))
12078                  (br_if $l (i32.lt_u (local.get $i) (i32.const 8))))
12079                (i32.store8 (i32.const 512) (i32.const 0x20))
12080                (i32.store8 (i32.const 513) (i32.const 0x41))
12081                (i32.store (i32.const 8) (i32.const 512))
12082                (i32.store (i32.const 12) (i32.const 2))
12083                (i32.const 0)))
12084        "#;
12085        let wasm_bytes = crate::converters::wat::wat_to_wasm(wat)?;
12086        let mut input = DcMstring::new();
12087        input.push_char(DcChar::from_unicode(u32::from(b'x'))?);
12088
12089        let q1 = SharedWasmTaskQuota::new(
12090            DcWasmResourceLimits::default().with_max_instructions_per_step(10_000),
12091        );
12092        let out1 = run_wasm_bytes_pure_conversion_with_quota(
12093            &wasm_bytes,
12094            &input,
12095            None,
12096            Some(q1.clone()),
12097        )?;
12098        let snap1 = q1.snapshot()?;
12099        assert!(snap1.total_instructions_executed > 1);
12100
12101        // Second call hits PURE_WASM_CONVERSION_CACHE and charges identical compute/output units.
12102        let q2 = SharedWasmTaskQuota::new(
12103            DcWasmResourceLimits::default().with_max_instructions_per_step(10_000),
12104        );
12105        let out2 = run_wasm_bytes_pure_conversion_with_quota(
12106            &wasm_bytes,
12107            &input,
12108            None,
12109            Some(q2.clone()),
12110        )?;
12111        let snap2 = q2.snapshot()?;
12112        assert_eq!(out1, out2);
12113        assert_eq!(
12114            snap1.total_instructions_executed,
12115            snap2.total_instructions_executed
12116        );
12117        assert_eq!(snap1.cumulative_output_bytes, snap2.cumulative_output_bytes);
12118
12119        // Tighter quota than cached cost falls through to VM execution and exhausts cleanly.
12120        let q_tight = SharedWasmTaskQuota::new(
12121            DcWasmResourceLimits::default().with_max_instructions_per_step(2),
12122        );
12123        assert!(
12124            run_wasm_bytes_pure_conversion_with_quota(
12125                &wasm_bytes,
12126                &input,
12127                None,
12128                Some(q_tight),
12129            )
12130            .is_err()
12131        );
12132
12133        // Verify opt-in Dc routine invocation profiler aggregation.
12134        let _ = take_dc_routine_profile_snapshot();
12135        set_dc_routine_profiling_enabled(true);
12136        let routine_dc = DcChar::from_short(2608);
12137        let params = vec![DcChar::from_unicode(u32::from(b'a'))?];
12138        let ret = vec![DcChar::from_unicode(u32::from(b'A'))?];
12139        record_dc_routine_invocation_profile(
12140            routine_dc,
12141            Some(8_589_934_592),
12142            &params,
12143            &ret,
12144            1_500,
12145            42,
12146        );
12147        record_dc_routine_invocation_profile(
12148            routine_dc,
12149            Some(8_589_934_592),
12150            &params,
12151            &ret,
12152            2_500,
12153            42,
12154        );
12155        set_dc_routine_profiling_enabled(false);
12156        let entries = take_dc_routine_profile_snapshot();
12157        assert_eq!(entries.len(), 1);
12158        assert_eq!(entries[0].call_count, 2);
12159        assert_eq!(entries[0].total_duration_ns, 4_000);
12160        assert_eq!(entries[0].executed_instructions, 42);
12161        Ok(())
12162    }
12163}