Skip to main content

glrmask\runtime\commit/
mod.rs

1use crate::runtime::markers::{CommitObserver, NoMarkers};
2use crate::automata::lexer::Lexer;
3pub(crate) mod profile;
4pub(crate) mod bounded;
5pub(crate) mod forcing_reference;
6pub(crate) mod template_advance;
7pub(crate) mod push_suffixes;
8mod flat_template;
9pub(crate) mod simple_read_shift;
10pub(crate) mod push_dag;
11pub(crate) mod phase_dag;
12pub(crate) mod single_cursor;
13pub(crate) mod template_prepare;
14pub(crate) use template_advance::advance_stacks_template_dfa;
15pub(crate) mod tokenizer_scan;
16
17use std::borrow::Cow;
18use std::collections::{BTreeMap, BTreeSet};
19use std::sync::OnceLock;
20
21use crate::automata::lexer::tokenizer::{Tokenizer, TokenizerExecResult, TokenizerMatch, TokenizerStateSet};
22use crate::compiler::glr::accumulator::TerminalsDisallowed;
23use crate::compiler::glr::parser::{
24    ParserGSS,
25    apply_guarded_stack_shifts_fast,
26    advance_control_closed_stacks,
27    advance_control_closed_stacks_owned,
28    advance_stacks,
29    advance_stacks_profiled,
30    advance_stacks_owned,
31    advance_stacks_disjoint_top_terminals_bounded,
32    normalize_lookahead_invariant_reductions,
33    AdvanceProfile,
34    stack_may_advance_on,
35    stack_may_advance_on_control_closed,
36    stack_may_advance_on_any,
37    stack_may_advance_on_any_control_closed,
38    stack_may_advance_disjoint_top_terminals_bounded,
39    stack_admissible_terminals,
40};
41use crate::compiler::glr::table::{Action, AdmissionPolicy, GLRTable};
42use crate::compiler::glr::table::row::ActionRow;
43use crate::runtime::artifact::DynamicMaskVocab;
44use crate::runtime::constraint::Constraint;
45use crate::runtime::state::{
46    CommitBuffers, ConstraintState, INLINE_PARSER_STATE_CAPACITY, LINEAR_STACK_RESERVE,
47    ParserAdmissionCacheEntry, ParserRelativeMaskEqCacheEntry, ParserStateMap,
48    commit_scratch,
49};
50use rustc_hash::{FxHashMap, FxHashSet};
51use smallvec::SmallVec;
52use self::profile::{
53    apply_advance_profile,
54    fast_action_advance_profile,
55    CommitProfile,
56    PerAdvanceEntry,
57};
58use self::template_advance::advance_stacks_template_dfa_owned;
59pub(crate) use self::template_advance::TemplateAdvanceRuntime;
60use self::tokenizer_scan::{
61    execute_recursive_tokenizer_reusable, execute_tokenizer_from_state_small,
62    execute_tokenizer_reusable, execute_tokenizer_reusable_from_states, InitialCommitScan,
63};
64
65type ParserStatesByTokenizer = FxHashMap<u32, ParserGSS>;
66
67type SmallParserStates =
68    SmallVec<[(u32, ParserGSS); INLINE_PARSER_STATE_CAPACITY]>;
69
70const SMALL_LANGUAGE_QUEUE_CAPACITY: usize = 32;
71const LANGUAGE_QUEUE_MAX_INPUT_STACK_DEPTH: u32 = 512;
72const LANGUAGE_QUEUE_MIN_TOP_VALUES: usize = 3;
73const LANGUAGE_QUEUE_MIN_PATHS: usize = 32;
74const LANGUAGE_QUEUE_MIN_NODES: usize = 48;
75
76#[cold]
77#[inline(never)]
78fn try_terminal_observation_quotient_commit_reuse(
79    buffers: &mut CommitBuffers,
80    generation: u64,
81    vocab: &DynamicMaskVocab,
82    tokenizer: &Tokenizer,
83    left_source: u32,
84    right_source: u32,
85    admitted: &crate::ds::bitset::BitSet,
86    cache_left: u32,
87    cache_right: u32,
88    visited_nodes: usize,
89    byte_steps: usize,
90    started: Option<std::time::Instant>,
91) -> bool {
92    let Some(quotient_relevant) = vocab.terminal_observation_equivalent_for_live_admitted(
93        left_source,
94        right_source,
95        admitted,
96        tokenizer.matched_terminal_bitset(left_source),
97        tokenizer.possible_future_terminals(left_source),
98        tokenizer.matched_terminal_bitset(right_source),
99        tokenizer.possible_future_terminals(right_source),
100    ) else {
101        return false;
102    };
103
104    if let Some(started) = started {
105        eprintln!(
106            "[glrmask/profile][parser_relative_commit_reuse] generation={} result=terminal_observation_quotient left={} right={} admitted={} relevant={} nodes={} bytes={} elapsed_us={:.1}",
107            generation,
108            left_source,
109            right_source,
110            admitted.count_ones(),
111            quotient_relevant,
112            visited_nodes,
113            byte_steps,
114            started.elapsed().as_secs_f64() * 1e6,
115        );
116    }
117
118    const CACHE_CAPACITY: usize = 8;
119    if buffers.parser_relative_mask_eq_cache.len() == CACHE_CAPACITY {
120        buffers.parser_relative_mask_eq_cache.remove(0);
121    }
122    buffers
123        .parser_relative_mask_eq_cache
124        .push(ParserRelativeMaskEqCacheEntry {
125            left: cache_left,
126            right: cache_right,
127            admitted: admitted.clone(),
128        });
129    true
130}
131
132#[derive(Clone, Debug, PartialEq, Eq)]
133struct SmallLanguageParserState {
134    tokenizer_state: u32,
135    language: u32,
136    accumulator: TerminalsDisallowed,
137}
138
139type SmallLanguageParserStates = SmallVec<[SmallLanguageParserState; 16]>;
140
141#[derive(Debug)]
142pub(crate) struct SmallCommitQueueScratch {
143    processing: [SmallParserStates; 17],
144    pending: SmallParserStates,
145    language_processing: [SmallLanguageParserStates; 17],
146    language_pending: SmallLanguageParserStates,
147    prune_union_starts: SmallVec<[u32; 8]>,
148}
149
150impl Default for SmallCommitQueueScratch {
151    fn default() -> Self {
152        Self {
153            processing: std::array::from_fn(|_| SmallVec::new()),
154            pending: SmallVec::new(),
155            language_processing: std::array::from_fn(|_| SmallVec::new()),
156            language_pending: SmallVec::new(),
157            prune_union_starts: SmallVec::new(),
158        }
159    }
160}
161
162impl SmallCommitQueueScratch {
163    // Keep the fixed-array initialization frame outside callers which may be
164    // recursively evaluating masks on a default-size worker stack. Normal
165    // commit buffers call this at state construction, not at the first commit.
166    #[inline(never)]
167    pub(crate) fn boxed() -> Box<Self> {
168        Box::new(Self::default())
169    }
170
171    pub(crate) fn clear(&mut self) {
172        for bucket in &mut self.processing {
173            bucket.clear();
174        }
175        self.pending.clear();
176        for bucket in &mut self.language_processing {
177            bucket.clear();
178        }
179        self.language_pending.clear();
180        self.prune_union_starts.clear();
181    }
182}
183
184#[cfg(test)]
185#[test]
186fn mask_only_flat_frontier_keeps_empty_semantics_without_branch_allocations() {
187    let lean = FlatFrontierScratch::for_mask_only_shadow();
188    let commit = FlatFrontierScratch::with_preallocated_gss(0);
189    assert_eq!(lean.len, commit.len);
190    assert_eq!(lean.continuation_cache_len, commit.continuation_cache_len);
191    assert!(lean.gss_pool.is_empty() && commit.gss_pool.is_empty());
192    assert!(lean.retired_gss.is_empty() && commit.retired_gss.is_empty());
193    for (left, right) in lean.branches.iter().zip(&commit.branches) {
194        assert!(left.stack.is_empty() && right.stack.is_empty());
195        assert_eq!(left.stack.capacity(), 0);
196        assert!(right.stack.capacity() >= crate::runtime::state::LINEAR_STACK_RESERVE);
197        assert_eq!(left.offset, right.offset);
198        assert_eq!(left.tokenizer_state, right.tokenizer_state);
199        assert_eq!(left.processed, right.processed);
200        assert_eq!(left.initial_pruned, right.initial_pruned);
201        assert_eq!(left.acc, right.acc);
202    }
203}
204
205const FLAT_FRONTIER_MAX_BRANCHES: usize = 128;
206const FLAT_CONTINUATION_CACHE_CAPACITY: usize = 128;
207const FLAT_ACTION_MAX_BRANCHES: usize = 16;
208const FLAT_ACTION_MAX_STEPS: usize = 256;
209const FLAT_FRONTIER_PREALLOCATED_GSS: usize = FLAT_FRONTIER_GSS_POOL_CAPACITY;
210
211type FlatInlineStack = SmallVec<[u32; LINEAR_STACK_RESERVE]>;
212
213#[derive(Debug, Default)]
214struct FlatActionScratch {
215    pending: SmallVec<[FlatInlineStack; FLAT_ACTION_MAX_BRANCHES]>,
216    complete: SmallVec<[FlatInlineStack; FLAT_ACTION_MAX_BRANCHES]>,
217}
218
219impl FlatActionScratch {
220    fn clear(&mut self) {
221        self.pending.clear();
222        self.complete.clear();
223    }
224
225    fn push_pending(&mut self, stack: FlatInlineStack) -> bool {
226        if self.pending.iter().any(|existing| existing == &stack) {
227            return true;
228        }
229        if self.pending.len() == self.pending.capacity() {
230            return false;
231        }
232        self.pending.push(stack);
233        true
234    }
235
236    fn push_complete(&mut self, stack: FlatInlineStack) -> bool {
237        if self.complete.iter().any(|existing| existing == &stack) {
238            return true;
239        }
240        if self.complete.len() == self.complete.capacity() {
241            return false;
242        }
243        self.complete.push(stack);
244        true
245    }
246}
247// Keep a bounded reserve large enough for repeated handoffs between persistent
248// GSS states and the allocation-free flat frontier.  One object reserves a
249// 64-entry linear stack, so 256 spares cost about 65–75 KiB per active
250// constraint state while avoiding allocator cliffs on multi-thousand-token
251// JSON examples. The bound remains fixed; unsupported larger frontiers still
252// fall back to the general persistent-GSS path.
253const FLAT_FRONTIER_GSS_POOL_CAPACITY: usize = 256;
254const FLAT_FRONTIER_RETIRED_GSS_CAPACITY: usize = 256;
255
256#[derive(Debug)]
257struct FlatBranchScratch {
258    offset: usize,
259    tokenizer_state: u32,
260    stack: Vec<u32>,
261    acc: TerminalsDisallowed,
262    processed: bool,
263    initial_pruned: bool,
264}
265
266#[derive(Clone, Copy, Debug, Default)]
267struct FlatContinuationDecision {
268    offset: usize,
269    tokenizer_state: u32,
270    end_state: u32,
271    viable: bool,
272}
273
274impl Default for FlatBranchScratch {
275    fn default() -> Self {
276        Self::with_stack_capacity(crate::runtime::state::LINEAR_STACK_RESERVE)
277    }
278}
279
280impl FlatBranchScratch {
281    fn with_stack_capacity(stack_capacity: usize) -> Self {
282        Self {
283            offset: 0,
284            tokenizer_state: 0,
285            stack: Vec::with_capacity(stack_capacity),
286            acc: TerminalsDisallowed::new(),
287            processed: false,
288            initial_pruned: false,
289        }
290    }
291}
292
293#[derive(Debug)]
294pub(crate) struct FlatFrontierScratch {
295    branches: [FlatBranchScratch; FLAT_FRONTIER_MAX_BRANCHES],
296    len: usize,
297    action: FlatActionScratch,
298    continuation_cache: [FlatContinuationDecision; FLAT_CONTINUATION_CACHE_CAPACITY],
299    continuation_cache_len: usize,
300    // Double-buffered single-path GSS objects. Runtime commits write a small
301    // output frontier into these preallocated objects and then swap them with
302    // the active state. This permits branch creation/collapse without allocator
303    // activity. Old active entries are recycled here after the atomic swap.
304    gss_pool: SmallVec<[ParserGSS; FLAT_FRONTIER_GSS_POOL_CAPACITY]>,
305    // Non-segment single-path GSSs displaced by a successful flat commit are
306    // retained until the state is dropped. This prevents their destructors from
307    // running in the token hot path without allowing unbounded retention.
308    retired_gss: SmallVec<[ParserGSS; FLAT_FRONTIER_RETIRED_GSS_CAPACITY]>,
309}
310
311impl Default for FlatFrontierScratch {
312    fn default() -> Self {
313        Self::with_preallocated_gss(FLAT_FRONTIER_PREALLOCATED_GSS)
314    }
315}
316
317impl FlatFrontierScratch {
318    // Keep the large construction temporary out of state/FFI caller frames.
319    // Box::new alone does not guarantee that LLVM initializes in place.
320    #[inline(never)]
321    pub(crate) fn boxed_with_preallocated_gss(preallocated_gss: usize) -> Box<Self> {
322        Box::new(Self::with_preallocated_gss(preallocated_gss))
323    }
324
325    #[inline(never)]
326    pub(crate) fn boxed_for_mask_only_shadow() -> Box<Self> {
327        Box::new(Self::for_mask_only_shadow())
328    }
329
330    /// Read-only mask shadows never execute the flat commit frontier. Avoid
331    /// reserving 128 unused branch stacks as well as the already-omitted GSS
332    /// pool. Logical empty state is identical; ordinary commits keep their
333    /// original branch-stack reservations unchanged.
334    pub(crate) fn for_mask_only_shadow() -> Self {
335        Self::with_reservation_policy(0, 0)
336    }
337
338    pub(crate) fn with_preallocated_gss(preallocated_gss: usize) -> Self {
339        Self::with_reservation_policy(preallocated_gss, crate::runtime::state::LINEAR_STACK_RESERVE)
340    }
341
342    fn with_reservation_policy(preallocated_gss: usize, stack_capacity: usize) -> Self {
343        let mut gss_pool = SmallVec::new();
344        for _ in 0..preallocated_gss.min(FLAT_FRONTIER_GSS_POOL_CAPACITY) {
345            let mut gss = ParserGSS::from_single_stack(
346                vec![0],
347                TerminalsDisallowed::new(),
348            );
349            let reserved = gss.reserve_single_segment_capacity(
350                crate::runtime::state::LINEAR_STACK_RESERVE,
351            );
352            debug_assert!(reserved, "fresh flat-frontier GSS must be reservable");
353            gss_pool.push(gss);
354        }
355        Self {
356            branches: std::array::from_fn(|_| FlatBranchScratch::with_stack_capacity(stack_capacity)),
357            len: 0,
358            action: FlatActionScratch::default(),
359            continuation_cache: [FlatContinuationDecision::default();
360                FLAT_CONTINUATION_CACHE_CAPACITY],
361            continuation_cache_len: 0,
362            gss_pool,
363            retired_gss: SmallVec::new(),
364        }
365    }
366
367    pub(crate) fn clear(&mut self) {
368        self.len = 0;
369        self.action.clear();
370        self.continuation_cache_len = 0;
371    }
372
373    fn continuation_decision(
374        &self,
375        offset: usize,
376        tokenizer_state: u32,
377        end_state: u32,
378    ) -> Option<bool> {
379        self.continuation_cache[..self.continuation_cache_len]
380            .iter()
381            .find(|decision| {
382                decision.offset == offset
383                    && decision.tokenizer_state == tokenizer_state
384                    && decision.end_state == end_state
385            })
386            .map(|decision| decision.viable)
387    }
388
389    fn cache_continuation_decision(
390        &mut self,
391        offset: usize,
392        tokenizer_state: u32,
393        end_state: u32,
394        viable: bool,
395    ) {
396        if self.continuation_cache_len == self.continuation_cache.len() {
397            return;
398        }
399        self.continuation_cache[self.continuation_cache_len] = FlatContinuationDecision {
400            offset,
401            tokenizer_state,
402            end_state,
403            viable,
404        };
405        self.continuation_cache_len += 1;
406    }
407
408    fn enqueue(
409        &mut self,
410        offset: usize,
411        tokenizer_state: u32,
412        stack: &[u32],
413        acc: TerminalsDisallowed,
414    ) -> bool {
415        if !acc.is_inline() {
416            return false;
417        }
418        for branch in &mut self.branches[..self.len] {
419            if branch.offset == offset
420                && branch.tokenizer_state == tokenizer_state
421                && branch.stack.as_slice() == stack
422            {
423                let Some(merged) = branch.acc.try_merge_inline(&acc) else {
424                    return false;
425                };
426                branch.acc = merged;
427                return true;
428            }
429        }
430        if self.len == self.branches.len() {
431            return false;
432        }
433        let branch = &mut self.branches[self.len];
434        if stack.len() > branch.stack.capacity() {
435            return false;
436        }
437        branch.offset = offset;
438        branch.tokenizer_state = tokenizer_state;
439        branch.stack.clear();
440        branch.stack.extend_from_slice(stack);
441        branch.acc = acc;
442        branch.processed = false;
443        branch.initial_pruned = false;
444        self.len += 1;
445        true
446    }
447
448    fn can_recycle_old_state(&self, state: &ParserStateMap, selected_count: usize) -> bool {
449        let mut recyclable = 0usize;
450        let mut retired = 0usize;
451        for (_, gss) in &state.entries {
452            if gss.can_replace_single_path_state_in_place(&[0]) {
453                recyclable += 1;
454            } else {
455                retired += 1;
456            }
457        }
458        self.gss_pool.len().saturating_sub(selected_count) + recyclable
459            <= FLAT_FRONTIER_GSS_POOL_CAPACITY
460            && self.retired_gss.len() + retired <= FLAT_FRONTIER_RETIRED_GSS_CAPACITY
461    }
462
463    fn reclaim_retired_gss(&mut self) {
464        if self.retired_gss.is_empty() || self.gss_pool.len() == FLAT_FRONTIER_GSS_POOL_CAPACITY {
465            return;
466        }
467        let mut still_retired =
468            SmallVec::<[ParserGSS; FLAT_FRONTIER_RETIRED_GSS_CAPACITY]>::new();
469        for gss in self.retired_gss.drain(..) {
470            if self.gss_pool.len() < FLAT_FRONTIER_GSS_POOL_CAPACITY
471                && gss.can_replace_single_path_state_in_place(&[0])
472            {
473                self.gss_pool.push(gss);
474            } else {
475                still_retired.push(gss);
476            }
477        }
478        self.retired_gss = still_retired;
479    }
480
481    fn recycle_old_entries(&mut self, old_entries: impl IntoIterator<Item = (u32, ParserGSS)>) {
482        for (_, gss) in old_entries {
483            if gss.can_replace_single_path_state_in_place(&[0]) {
484                debug_assert!(self.gss_pool.len() < FLAT_FRONTIER_GSS_POOL_CAPACITY);
485                self.gss_pool.push(gss);
486            } else {
487                debug_assert!(self.retired_gss.len() < FLAT_FRONTIER_RETIRED_GSS_CAPACITY);
488                self.retired_gss.push(gss);
489            }
490        }
491        // The preflight reserved capacity for these active entries. Reclaim
492        // retired entries only after that reservation has been consumed;
493        // reclaiming first can fill the same slots and overflow the pool.
494        self.reclaim_retired_gss();
495    }
496
497    fn replace_state_with_shared_uniform_stack_keys(
498        &mut self,
499        state: &mut ParserStateMap,
500        keys: &[u32],
501        stack: &[u32],
502        acc: &TerminalsDisallowed,
503    ) -> bool {
504        // Include reclaimed spares in the capacity preflight, before an
505        // atomic replacement reserves space for the displaced active state.
506        self.reclaim_retired_gss();
507        if keys.is_empty()
508            || keys.windows(2).any(|pair| pair[0] >= pair[1])
509            || !self.can_recycle_old_state(state, 1)
510        {
511            return false;
512        }
513        let Some(pool_index) = self
514            .gss_pool
515            .iter()
516            .rposition(|gss| gss.can_replace_single_path_state_in_place(stack))
517        else {
518            return false;
519        };
520        let mut shared = self.gss_pool.swap_remove(pool_index);
521        if !shared.try_replace_single_path_state_in_place(stack, acc.clone()) {
522            self.gss_pool.push(shared);
523            return false;
524        }
525
526        let mut new_entries = std::mem::take(&mut state.entries);
527        self.recycle_old_entries(new_entries.drain(..));
528        new_entries.reserve(keys.len());
529        for &key in &keys[..keys.len() - 1] {
530            new_entries.push((key, shared.clone()));
531        }
532        new_entries.push((*keys.last().unwrap(), shared));
533        state.entries = new_entries;
534        true
535    }
536
537    fn replace_state_with_uniform_stack_keys(
538        &mut self,
539        state: &mut ParserStateMap,
540        keys: &[u32],
541        stack: &[u32],
542        acc: &TerminalsDisallowed,
543    ) -> bool {
544        if keys.is_empty()
545            || keys.len() > INLINE_PARSER_STATE_CAPACITY
546            || keys.windows(2).any(|pair| pair[0] >= pair[1])
547            || self.gss_pool.len() < keys.len()
548            || !self.can_recycle_old_state(state, keys.len())
549        {
550            return false;
551        }
552
553        let mut selected = SmallVec::<[ParserGSS; INLINE_PARSER_STATE_CAPACITY]>::new();
554        for _ in keys {
555            let Some(pool_index) = self
556                .gss_pool
557                .iter()
558                .rposition(|gss| gss.can_replace_single_path_state_in_place(stack))
559            else {
560                for gss in selected.drain(..) {
561                    self.gss_pool.push(gss);
562                }
563                return false;
564            };
565            selected.push(self.gss_pool.swap_remove(pool_index));
566        }
567
568        let mut new_entries = std::mem::take(&mut state.entries);
569        self.recycle_old_entries(new_entries.drain(..));
570        new_entries.reserve(keys.len());
571        for (mut gss, &key) in selected.into_iter().zip(keys) {
572            let replaced = gss.try_replace_single_path_state_in_place(stack, acc.clone());
573            debug_assert!(replaced, "uniform flat-frontier spare eligibility changed");
574            if !replaced {
575                unreachable!("uniform spare was validated before mutation");
576            }
577            new_entries.push((key, gss));
578        }
579
580        state.entries = new_entries;
581        true
582    }
583}
584
585const SMALL_NORMALIZED_MATCH_LINEAR_SCAN_MAX: usize = 16;
586
587#[derive(Clone, Copy)]
588struct NormalizedMatch {
589    terminal_id: u32,
590    width: usize,
591    ignored: bool,
592}
593
594const SINGLE_CONCRETE_STACK_EFFECT_MAX_DEPTH: usize = 256;
595static TEMPLATE_ADVANCE_ENABLED: OnceLock<bool> = OnceLock::new();
596static VALIDATE_TEMPLATE_ADVANCE_ENABLED: OnceLock<bool> = OnceLock::new();
597
598fn template_advance_enabled() -> bool {
599    *TEMPLATE_ADVANCE_ENABLED
600        .get_or_init(|| crate::env::var_os("GLRMASK_ENABLE_TEMPLATE_DFA_ADVANCE").is_some())
601}
602
603#[inline]
604fn template_advance_selected(constraint: &Constraint) -> bool {
605    constraint.has_template_parser()
606}
607
608fn validate_template_advance_enabled() -> bool {
609    *VALIDATE_TEMPLATE_ADVANCE_ENABLED
610        .get_or_init(|| crate::env::var_os("GLRMASK_VALIDATE_TEMPLATE_DFA_ADVANCE").is_some())
611}
612
613fn advance_parser_stacks(
614    constraint: &Constraint,
615    stack: &ParserGSS,
616    terminal: u32,
617) -> ParserGSS {
618    if let Some(parser) = &constraint.template_parser {
619        parser.record_advance();
620        return advance_stacks_template_dfa(constraint, stack, terminal)
621            .expect("complete template program must contain this terminal");
622    }
623
624    if let Some(advanced) = constraint.advance_compact_segmented_parser(stack, terminal) {
625        return advanced;
626    }
627    if let Some(cached) = constraint.direct_regular_cached_advance(stack, terminal) {
628        return cached;
629    }
630    if template_advance_selected(constraint)
631        && let Some(template_advanced) = advance_stacks_template_dfa(constraint, stack, terminal)
632    {
633        if validate_template_advance_enabled() {
634            let table_advanced = advance_stacks(&constraint.table, stack, terminal);
635            assert!(
636                template_advanced.semantically_eq(&table_advanced, 4_096).expect("template validation exceeded explicit stack limit"),
637                "template-DFA advance mismatch for terminal {terminal}; template={:?} table={:?}",
638                template_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
639                table_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
640            );
641        }
642        return template_advanced;
643    }
644
645    if !constraint.parser_has_controls() {
646        advance_stacks(&constraint.table, stack, terminal)
647    } else {
648        advance_control_closed_stacks(&constraint.table, stack, terminal)
649    }
650}
651
652fn advance_parser_stacks_owned(
653    constraint: &Constraint,
654    stack: ParserGSS,
655    terminal: u32,
656) -> ParserGSS {
657    if let Some(parser) = &constraint.template_parser {
658        parser.record_advance();
659        return advance_stacks_template_dfa_owned(constraint, stack, terminal)
660            .expect("complete template program must contain this terminal");
661    }
662
663    if let Some(advanced) = constraint.advance_compact_segmented_parser(&stack, terminal) {
664        return advanced;
665    }
666    if let Some(cached) = constraint.direct_regular_cached_advance(&stack, terminal) {
667        return cached;
668    }
669    if template_advance_selected(constraint)
670        && let Some(template_advanced) =
671            advance_stacks_template_dfa_owned(constraint, stack.clone(), terminal)
672    {
673        if validate_template_advance_enabled() {
674            let table_advanced = advance_stacks_owned(&constraint.table, stack, terminal);
675            assert!(
676                template_advanced.semantically_eq(&table_advanced, 4_096).expect("template validation exceeded explicit stack limit"),
677                "template-DFA advance mismatch for terminal {terminal}; template={:?} table={:?}",
678                template_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
679                table_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
680            );
681        }
682        return template_advanced;
683    }
684
685    if !constraint.parser_has_controls() {
686        advance_stacks_owned(&constraint.table, stack, terminal)
687    } else {
688        advance_control_closed_stacks_owned(&constraint.table, stack, terminal)
689    }
690}
691
692fn advance_parser_stacks_profiled(
693    constraint: &Constraint,
694    stack: &ParserGSS,
695    terminal: u32,
696) -> (ParserGSS, AdvanceProfile) {
697    if let Some(parser) = &constraint.template_parser {
698        parser.record_advance();
699        let advanced = advance_stacks_template_dfa(constraint, stack, terminal)
700            .expect("complete template program must contain this terminal");
701        return (advanced, AdvanceProfile::default());
702    }
703
704    let template_start = std::time::Instant::now();
705    if let Some(advanced) = constraint.advance_compact_segmented_parser(stack, terminal) {
706        let elapsed = template_start.elapsed().as_nanos() as u64;
707        return (
708            advanced,
709            AdvanceProfile {
710                total_ns: elapsed,
711                fast_path_ns: elapsed,
712                top_states: stack.top_value_count() as u32,
713                gss_depth: stack.max_depth(),
714                ..AdvanceProfile::default()
715            },
716        );
717    }
718    if let Some(cached) = constraint.direct_regular_cached_advance(stack, terminal) {
719        let elapsed = template_start.elapsed().as_nanos() as u64;
720        return (
721            cached,
722            AdvanceProfile {
723                total_ns: elapsed,
724                fast_path_ns: elapsed,
725                top_states: stack.top_value_count() as u32,
726                gss_depth: stack.max_depth(),
727                ..AdvanceProfile::default()
728            },
729        );
730    }
731    if template_advance_selected(constraint)
732        && let Some(template_advanced) = advance_stacks_template_dfa(constraint, stack, terminal)
733    {
734        let template_elapsed = template_start.elapsed().as_nanos() as u64;
735        if validate_template_advance_enabled() {
736            let (table_advanced, table_profile) =
737                advance_stacks_profiled(&constraint.table, stack, terminal);
738            assert!(
739                template_advanced.semantically_eq(&table_advanced, 4_096).expect("template validation exceeded explicit stack limit"),
740                "template-DFA advance mismatch for terminal {terminal}; template={:?} table={:?}",
741                template_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
742                table_advanced.to_stacks(4_096).expect("stack enumeration exceeded explicit limit"),
743            );
744            return (template_advanced, table_profile);
745        }
746        return (
747            template_advanced,
748            AdvanceProfile {
749                total_ns: template_elapsed,
750                fast_path_ns: template_elapsed,
751                top_states: stack.peek_values().len() as u32,
752                gss_depth: stack.max_depth(),
753                vstack_len: stack
754                    .try_virtual_stack()
755                    .map_or(0, |vstack| vstack.len() as u32),
756                ..AdvanceProfile::default()
757            },
758        );
759    }
760
761    advance_stacks_profiled(&constraint.table, stack, terminal)
762}
763
764/// Advance once when admission requires exact simulation. Row-presence tables
765/// retain their cheap precheck; exact-simulation tables must not execute the
766/// same reduction closure once for admission and again for the actual advance.
767#[inline]
768pub(crate) fn parser_may_advance_on(constraint: &Constraint, stack: &ParserGSS, terminal: u32) -> bool {
769    if let Some(parser) = &constraint.template_parser {
770        return parser.admits(stack, terminal);
771    }
772
773    if let Some(result) = constraint.compact_segmented_parser_may_advance_on(stack, terminal) {
774        return result;
775    }
776    constraint
777        .direct_regular_admissible_terminals(stack)
778        .map_or_else(
779            || {
780                if !constraint.parser_has_controls() {
781                    stack_may_advance_on(&constraint.table, stack, terminal)
782                } else {
783                    stack_may_advance_on_control_closed(&constraint.table, stack, terminal)
784                }
785            },
786            |terminals| terminals.contains(terminal as usize),
787        )
788}
789
790#[inline]
791fn bitset_prefix_intersects(
792    left: &crate::ds::bitset::BitSet,
793    right: &crate::ds::bitset::BitSet,
794) -> bool {
795    left.words()
796        .iter()
797        .zip(right.words())
798        .any(|(left, right)| (*left & *right) != 0)
799}
800
801#[inline]
802fn bitset_union_intersection_prefix(
803    dst: &mut crate::ds::bitset::BitSet,
804    left: &crate::ds::bitset::BitSet,
805    right: &crate::ds::bitset::BitSet,
806) {
807    for ((dst, left), right) in dst
808        .words_mut()
809        .iter_mut()
810        .zip(left.words())
811        .zip(right.words())
812    {
813        *dst |= *left & *right;
814    }
815}
816
817/// Return the sole candidate in `actions` that is requested by `terminals`
818/// and not already covered by the unconditional-advance row.  `Err(())`
819/// means there are at least two candidates, so the single-terminal bounded
820/// shortcut is not applicable.
821#[inline]
822fn single_conditional_candidate(
823    actions: &ActionRow,
824    unconditional: &crate::ds::bitset::BitSet,
825    terminals: &crate::ds::bitset::BitSet,
826) -> Result<Option<u32>, ()> {
827    let mut selected = None;
828    for (terminal, _action) in actions.iter() {
829        let bit = terminal as usize;
830        if bit >= terminals.len()
831            || !terminals.contains(bit)
832            || unconditional.contains(bit)
833        {
834            continue;
835        }
836        if selected.is_some() {
837            return Err(());
838        }
839        selected = Some(terminal);
840    }
841    Ok(selected)
842}
843
844fn exact_simulation_prefilter_may_advance_on_any(
845    constraint: &Constraint,
846    stack: &ParserGSS,
847    terminals: &crate::ds::bitset::BitSet,
848) -> Option<bool> {
849    if constraint.has_template_parser() { return None; }
850
851    if constraint.parser_admission_policy() != AdmissionPolicy::ExactSimulation
852        || constraint.parser_has_controls()
853        || constraint.table.unconditional_advance.len() != constraint.parser_symbol_count() as usize
854    {
855        return None;
856    }
857
858    let tops = stack.peek_values();
859    let mut any_relevant = false;
860    for &state in &tops {
861        let advance = constraint.table.advance.get(state as usize)?;
862        let unconditional = constraint.parser_unconditional_row(state)?;
863        if bitset_prefix_intersects(unconditional, terminals) {
864            return Some(true);
865        }
866        any_relevant |= bitset_prefix_intersects(advance, terminals);
867    }
868    if !any_relevant {
869        return Some(false);
870    }
871
872    // The unconditional portion is already known empty.  Try the bounded
873    // concrete-stack exact path when each current top has at most one remaining
874    // candidate terminal; otherwise fall through to the general exact closure.
875    let mut terminal_by_top = SmallVec::<[(u32, u32); 8]>::new();
876    let mut bounded_applicable = true;
877    'tops: for &top in &tops {
878        let actions = constraint.table.action.get(top as usize)?;
879        let unconditional = constraint.parser_unconditional_row(top)?;
880        let selected = match single_conditional_candidate(actions, unconditional, terminals) {
881            Ok(selected) => selected,
882            Err(()) => {
883                bounded_applicable = false;
884                break 'tops;
885            }
886        };
887        if let Some(terminal) = selected {
888            terminal_by_top.push((top, terminal));
889        }
890    }
891    if bounded_applicable
892        && !terminal_by_top.is_empty()
893        && let Some(result) = stack_may_advance_disjoint_top_terminals_bounded(
894            &constraint.table,
895            stack,
896            &terminal_by_top,
897        )
898    {
899        return Some(result);
900    }
901    Some(stack_may_advance_on_any(&constraint.table, stack, terminals))
902}
903
904#[inline]
905fn parser_may_advance_on_any(
906    constraint: &Constraint,
907    stack: &ParserGSS,
908    terminals: &crate::ds::bitset::BitSet,
909) -> bool {
910    if let Some(parser) = &constraint.template_parser {
911        return parser.admits_any(stack, terminals);
912    }
913
914    if let Some(result) = constraint.compact_segmented_parser_may_advance_on_any(stack, terminals) {
915        return result;
916    }
917    if let Some(result) = exact_simulation_prefilter_may_advance_on_any(
918        constraint,
919        stack,
920        terminals,
921    ) {
922        return result;
923    }
924    constraint
925        .direct_regular_admissible_terminals(stack)
926        .map_or_else(
927            || {
928                if !constraint.parser_has_controls() {
929                    stack_may_advance_on_any(&constraint.table, stack, terminals)
930                } else {
931                    stack_may_advance_on_any_control_closed(&constraint.table, stack, terminals)
932                }
933            },
934            |admitted| {
935                admitted
936                    .words()
937                    .iter()
938                    .zip(terminals.words())
939                    .any(|(left, right)| (*left & *right) != 0)
940            },
941        )
942}
943
944pub(crate) fn advance_parser_stacks_if_possible(
945    constraint: &Constraint,
946    stack: &ParserGSS,
947    terminal: u32,
948) -> Option<ParserGSS> {
949    if constraint.parser_admission_policy() == AdmissionPolicy::RowPresenceExact
950        && !parser_may_advance_on(constraint, stack, terminal)
951    {
952        return None;
953    }
954    let advanced = advance_parser_stacks(constraint, stack, terminal);
955    (!advanced.is_empty()).then_some(advanced)
956}
957
958/// Advance against the authoritative composed GLR table without consulting
959/// parser-DWA/direct-regular admission caches.
960///
961/// Segmented boundary B deliberately represents language that is absent from
962/// retained component/static A. After loading a hybrid, the constraint's
963/// parser DWA may therefore be exactly A; using the ordinary admission
964/// prefilter here would circularly reject B-only cross-component terminals.
965pub(crate) fn advance_parser_stacks_table_exact(
966    constraint: &Constraint,
967    stack: &ParserGSS,
968    terminal: u32,
969) -> Option<ParserGSS> {
970    if constraint.has_template_parser() {
971        return advance_parser_stacks_if_possible(constraint, stack, terminal);
972    }
973
974    if let Some(advanced) = constraint.advance_compact_segmented_parser(stack, terminal) {
975        return (!advanced.is_empty()).then_some(advanced);
976    }
977    let advanced = if !constraint.parser_has_controls() {
978        advance_stacks(&constraint.table, stack, terminal)
979    } else {
980        advance_control_closed_stacks(&constraint.table, stack, terminal)
981    };
982    (!advanced.is_empty()).then_some(advanced)
983}
984
985struct ProfiledAdvanceAttempt {
986    advanced: ParserGSS,
987    profile: AdvanceProfile,
988    may_ns: u64,
989    core_ns: u64,
990}
991
992fn advance_parser_stacks_profiled_if_possible(
993    constraint: &Constraint,
994    stack: &ParserGSS,
995    terminal: u32,
996) -> ProfiledAdvanceAttempt {
997    use std::time::Instant;
998
999    let mut may_ns = 0;
1000    if constraint.parser_admission_policy() == AdmissionPolicy::RowPresenceExact {
1001        let may_started_at = Instant::now();
1002        let admitted = parser_may_advance_on(constraint, stack, terminal);
1003        may_ns = may_started_at.elapsed().as_nanos() as u64;
1004        if !admitted {
1005            return ProfiledAdvanceAttempt {
1006                advanced: ParserGSS::empty(),
1007                profile: AdvanceProfile::default(),
1008                may_ns,
1009                core_ns: 0,
1010            };
1011        }
1012    }
1013
1014    let core_started_at = Instant::now();
1015    let (advanced, profile) = advance_parser_stacks_profiled(constraint, stack, terminal);
1016    let core_ns = core_started_at.elapsed().as_nanos() as u64;
1017    ProfiledAdvanceAttempt {
1018        advanced,
1019        profile,
1020        may_ns,
1021        core_ns,
1022    }
1023}
1024
1025/// Cache for `advance_stacks` results, keyed by (GSS pointer, terminal).
1026/// Stores the key GSS alongside the result to keep its Arc alive and prevent
1027/// address reuse (ABA problem) within a single `commit_bytes_impl` call.
1028type AdvanceResultCache = FxHashMap<(usize, u32), (ParserGSS, ParserGSS)>;
1029
1030fn state_has_nonempty_accumulators(state: &ParserStateMap) -> bool {
1031    state
1032        .values()
1033        .any(|gss| !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()))
1034}
1035
1036
1037fn parser_stacks_only(gss: &ParserGSS) -> Vec<Vec<u32>> {
1038    gss.to_stacks(4_096).expect("stack enumeration exceeded explicit limit").into_iter().map(|(stack, _)| stack).collect()
1039}
1040
1041
1042fn token_bytes_for_id(constraint: &Constraint, token_id: u32) -> Option<&[u8]> {
1043    constraint
1044        .token_bytes_dense
1045        .get(token_id as usize)
1046        .and_then(|bytes| bytes.as_deref())
1047        .or_else(|| constraint.token_bytes_for_id(token_id))
1048}
1049
1050const COMMIT_ASSERT_MASK_EQUIVALENCE: u8 = 1 << 0;
1051const COMMIT_ASSERT_FAST_PATH_EQUIVALENCE: u8 = 1 << 1;
1052
1053fn commit_assertion_flags() -> u8 {
1054    static FLAGS: OnceLock<u8> = OnceLock::new();
1055    *FLAGS.get_or_init(|| {
1056        let mut flags = 0;
1057        if cfg!(debug_assertions)
1058            || crate::env::var("GLRMASK_ASSERT_COMMIT_TOKEN_MASK_EQUIVALENCE")
1059                .map(|value| {
1060                    let normalized = value.trim().to_ascii_lowercase();
1061                    matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
1062                })
1063                .unwrap_or(false)
1064        {
1065            flags |= COMMIT_ASSERT_MASK_EQUIVALENCE;
1066        }
1067        if crate::env::var("GLRMASK_ASSERT_COMMIT_FAST_PATH_EQUIVALENCE")
1068            .map(|value| {
1069                let normalized = value.trim().to_ascii_lowercase();
1070                matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
1071            })
1072            .unwrap_or(false)
1073        {
1074            flags |= COMMIT_ASSERT_FAST_PATH_EQUIVALENCE;
1075        }
1076        flags
1077    })
1078}
1079
1080fn canonical_commit_state_for_equivalence_assert(
1081    state: &ParserStateMap,
1082) -> Vec<(u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>)> {
1083    let mut grouped = BTreeMap::<u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>>::new();
1084    for (&tokenizer_state, gss) in state.iter() {
1085        let out = grouped.entry(tokenizer_state).or_default();
1086        out.extend(
1087            gss.to_stacks(100_000)
1088                .expect("stack enumeration exceeded explicit limit")
1089                .into_iter()
1090                .map(|(stack, terminals_disallowed)| {
1091                    let disallowed = terminals_disallowed
1092                        .iter()
1093                        .map(|(&state, terminals)| {
1094                            (state, terminals.iter().copied().collect::<Vec<_>>())
1095                        })
1096                        .collect::<Vec<_>>();
1097                    (stack, disallowed)
1098                }),
1099        );
1100    }
1101    for stacks in grouped.values_mut() {
1102        stacks.sort();
1103        stacks.dedup();
1104    }
1105    grouped.into_iter().collect()
1106}
1107
1108fn profile_allow_fast_paths() -> bool {
1109    crate::env::var("GLRMASK_PROFILE_ALLOW_FAST_PATHS")
1110        .map(|value| {
1111            let normalized = value.trim().to_ascii_lowercase();
1112            matches!(normalized.as_str(), "1" | "true" | "yes" | "on")
1113        })
1114        .unwrap_or(false)
1115}
1116
1117pub(crate) fn initialize_runtime_config() {
1118    let _ = template_advance_enabled();
1119    let _ = validate_template_advance_enabled();
1120    let _ = commit_assertion_flags();
1121}
1122
1123fn token_in_mask(mask: &[u32], token_id: u32) -> bool {
1124    let word_idx = token_id as usize / 32;
1125    let bit_idx = token_id as usize % 32;
1126    word_idx < mask.len() && ((mask[word_idx] >> bit_idx) & 1) != 0
1127}
1128
1129fn snapshot_mask_membership(
1130    state: &ConstraintState,
1131    token_id: u32,
1132    assertion_flags: u8,
1133) -> Option<bool> {
1134    if assertion_flags & COMMIT_ASSERT_MASK_EQUIVALENCE == 0 {
1135        return None;
1136    }
1137    let mut mask = vec![0u32; state.constraint.mask_bit_len().div_ceil(32)];
1138    state.fill_mask(&mut mask);
1139    Some(token_in_mask(&mask, token_id))
1140}
1141
1142fn format_token_bytes(token_bytes: &[u8]) -> String {
1143    let mut escaped = String::new();
1144    for byte in token_bytes {
1145        for ch in std::ascii::escape_default(*byte) {
1146            escaped.push(ch as char);
1147        }
1148    }
1149    format!("b\"{}\"", escaped)
1150}
1151
1152fn format_optional_token_bytes(token_bytes: Option<&[u8]>) -> String {
1153    token_bytes
1154        .map(format_token_bytes)
1155        .unwrap_or_else(|| "<no vocabulary bytes>".to_owned())
1156}
1157
1158#[inline]
1159fn assert_commit_oracles(
1160    constraint: &Constraint,
1161    token_id: u32,
1162    token_bytes: Option<&[u8]>,
1163    was_in_mask: Option<bool>,
1164    fast_path_reference: Option<ParserStateMap>,
1165    actual_state: &ParserStateMap,
1166    commit_succeeded: bool,
1167) {
1168    if let Some(was_in_mask) = was_in_mask {
1169        assert!(
1170            commit_succeeded == was_in_mask,
1171            "commit/mask mismatch for token_id {} bytes {}: token_in_mask={} commit_succeeded={}",
1172            token_id,
1173            format_optional_token_bytes(token_bytes),
1174            was_in_mask,
1175            commit_succeeded,
1176        );
1177    }
1178    if let Some(reference_state) = fast_path_reference {
1179        assert_commit_fast_path_equivalence(
1180            constraint,
1181            reference_state,
1182            token_id,
1183            actual_state,
1184            commit_succeeded,
1185        );
1186    }
1187}
1188
1189// The read-only core of `advance_special_terminal_paths`: commit one
1190// zero-width special terminal from one reset-state entry, if it is admissible.
1191fn advance_single_special_terminal(
1192    constraint: &Constraint,
1193    tokenizer_state: u32,
1194    gss: &ParserGSS,
1195    terminal_id: u32,
1196) -> Option<ParserGSS> {
1197    let pruned = prune_single_initial_state_for_terminal(
1198        gss.clone(), tokenizer_state, terminal_id, None,
1199    );
1200    if pruned.is_empty() { return None; }
1201    advance_parser_stacks_if_possible(constraint, &pruned, terminal_id)
1202}
1203
1204fn special_terminal_admissible(
1205    constraint: &Constraint,
1206    tokenizer_state: u32,
1207    gss: &ParserGSS,
1208    terminal_id: u32,
1209) -> bool {
1210    advance_single_special_terminal(constraint, tokenizer_state, gss, terminal_id).is_some()
1211}
1212
1213pub(super) fn advance_special_terminal_paths(
1214    constraint: &Constraint,
1215    state: &ParserStateMap,
1216    terminal_id: u32,
1217) -> Option<ParserGSS> {
1218    let mut merged = None::<ParserGSS>;
1219    for (&initial_state, initial_gss) in state.iter() {
1220        if !runtime_tokenizer_is_reset_state(constraint, initial_state) { continue; }
1221        let Some(advanced) =
1222            advance_single_special_terminal(constraint, initial_state, initial_gss, terminal_id)
1223        else { continue; };
1224        merged = Some(match merged.take() {
1225            Some(existing) => existing.merge(&advanced),
1226            None => advanced,
1227        });
1228    }
1229    merged
1230}
1231
1232pub(super) fn advance_special_token_paths(
1233    constraint: &Constraint,
1234    state: &ParserStateMap,
1235    token_id: u32,
1236) -> Option<ParserGSS> {
1237    let mut merged = None::<ParserGSS>;
1238    for special in constraint.special_token_terminals.iter().filter(|special| special.contains(token_id)) {
1239        let Some(advanced) = advance_special_terminal_paths(constraint, state, special.terminal_id)
1240            else { continue; };
1241        merged = Some(match merged.take() {
1242            Some(existing) => existing.merge(&advanced),
1243            None => advanced,
1244        });
1245    }
1246    merged
1247}
1248
1249#[derive(Default)]
1250struct SpecialTokenAdvanceProfile {
1251    paths: Option<ParserGSS>,
1252    prune_ns: u64,
1253    may_check_ns: u64,
1254    advance_ns: u64,
1255    summary_ns: u64,
1256    advances: Vec<AdvanceProfile>,
1257}
1258
1259fn advance_special_token_paths_profiled(
1260    constraint: &Constraint,
1261    state: &ParserStateMap,
1262    token_id: u32,
1263    mut per_advance: Option<&mut Vec<PerAdvanceEntry>>,
1264) -> SpecialTokenAdvanceProfile {
1265    use std::time::Instant;
1266
1267    let mut result = SpecialTokenAdvanceProfile::default();
1268
1269    for (&initial_state, initial_gss) in state.iter() {
1270        if !runtime_tokenizer_is_reset_state(constraint, initial_state) {
1271            continue;
1272        }
1273        for special in constraint
1274            .special_token_terminals
1275            .iter()
1276            .filter(|special| special.contains(token_id))
1277        {
1278            let prune_started_at = Instant::now();
1279            let pruned = prune_single_initial_state_for_terminal(
1280                initial_gss.clone(),
1281                initial_state,
1282                special.terminal_id,
1283                None,
1284            );
1285            result.prune_ns += prune_started_at.elapsed().as_nanos() as u64;
1286            if pruned.is_empty() {
1287                continue;
1288            }
1289
1290            let attempt =
1291                advance_parser_stacks_profiled_if_possible(constraint, &pruned, special.terminal_id);
1292            result.may_check_ns += attempt.may_ns;
1293            result.advance_ns += attempt.core_ns;
1294            if attempt.advanced.is_empty() {
1295                continue;
1296            }
1297            let advanced = attempt.advanced;
1298            let advance_profile = attempt.profile;
1299
1300            if let Some(entries) = per_advance.as_deref_mut() {
1301                result.summary_ns += record_per_advance_entry(
1302                    entries,
1303                    initial_state,
1304                    special.terminal_id,
1305                    &pruned,
1306                    &advanced,
1307                    0,
1308                    0,
1309                    0,
1310                    &[],
1311                    advance_profile.clone(),
1312                );
1313            }
1314            result.advances.push(advance_profile);
1315            result.paths = Some(match result.paths.take() {
1316                Some(existing) => existing.merge(&advanced),
1317                None => advanced,
1318            });
1319        }
1320    }
1321
1322    result
1323}
1324
1325fn apply_special_token_advance_profile(
1326    profile: &mut CommitProfile,
1327    special: &SpecialTokenAdvanceProfile,
1328) {
1329    profile.prune_ns += special.prune_ns;
1330    profile.advance_may_check_ns += special.may_check_ns;
1331    profile.may_advance_ns += special.may_check_ns;
1332    profile.advance_core_ns += special.advance_ns;
1333    profile.advance_ns += special.advance_ns;
1334    profile.adv_summary_ns += special.summary_ns;
1335    profile.n_advances += special.advances.len() as u64;
1336    for advance in &special.advances {
1337        apply_advance_profile(profile, advance);
1338    }
1339}
1340
1341fn merge_special_token_paths(
1342    constraint: &Constraint,
1343    state: &mut ParserStateMap,
1344    special_paths: Option<ParserGSS>,
1345) -> Result<(), String> {
1346    let Some(gss) = special_paths.filter(|gss| !gss.is_empty()) else {
1347        return Ok(());
1348    };
1349    if !constraint.uses_compact_segmented_parser_runtime() {
1350        state.merge_insert(constraint.runtime_commit_initial_state(), gss);
1351        return Ok(());
1352    }
1353    let partitions = constraint
1354        .partition_recursive_parser_gss_by_active_leaf(&gss)
1355        .ok_or_else(|| "recursive special-token reset routing failed".to_owned())?;
1356    for (leaf_index, partition) in partitions {
1357        let reset_state = constraint
1358            .recursive_tokenizer_reset_state(leaf_index)
1359            .ok_or_else(|| {
1360                format!("recursive special-token leaf {leaf_index} has no tokenizer reset")
1361            })?;
1362        state.merge_insert(reset_state, partition);
1363    }
1364    Ok(())
1365}
1366
1367fn finish_token_commit(state: &ParserStateMap) -> Result<(), String> {
1368    if state.is_empty() {
1369        Err("commit rejected: no valid parser states remain".to_owned())
1370    } else {
1371        Ok(())
1372    }
1373}
1374
1375/// Restore the exact source-tokenizer coordinate before commit.
1376///
1377/// Invariant: all duplicate parser alternatives under one product key came
1378/// from the same source-state subset. The historical flat frontier decides
1379/// continuation viability from the union of alternatives sharing a lexer key,
1380/// then carries each alternative independently. Reconstruct exactly that
1381/// relation: compute one viable source subset from the merged group, and copy
1382/// every original alternative across that common subset.
1383fn expand_runtime_product_states(constraint: &Constraint, state: &mut ParserStateMap) {
1384    if constraint.uses_compact_segmented_parser_runtime() {
1385        // Recursive state keys are already exact disjoint-union leaf tokenizer
1386        // states, not product states from the transitional outer tokenizer.
1387        return;
1388    }
1389    let Some(source_offset) = constraint.runtime_source_state_offset() else {
1390        return;
1391    };
1392    if !state.keys().any(|&state| state < source_offset) {
1393        return;
1394    }
1395
1396    let debug = crate::env::var_os("GLRMASK_DEBUG_RUNTIME_PRODUCT").is_some();
1397    let old = std::mem::take(state).entries;
1398    let mut index = 0usize;
1399    while index < old.len() {
1400        let tokenizer_state = old[index].0;
1401        let group_end = old[index..]
1402            .partition_point(|(candidate, _)| *candidate == tokenizer_state)
1403            + index;
1404        let group = &old[index..group_end];
1405
1406        if tokenizer_state >= source_offset {
1407            for (_, gss) in group.iter().cloned() {
1408                state.insert_flat_alternative(tokenizer_state, gss);
1409            }
1410            index = group_end;
1411            continue;
1412        }
1413        // The reset state is still one historical scanner lane whose epsilon
1414        // closure happens to be represented deterministically. Other product
1415        // states denote a *set of current runtime lanes*. Even when that set is
1416        // also one raw state's epsilon closure, replacing the lanes by that raw
1417        // state changes per-start-state longest-match behavior.
1418        if tokenizer_state == constraint.tokenizer.initial_state()
1419            && let Some(source_state) =
1420                constraint.runtime_product_exact_source_state(tokenizer_state)
1421        {
1422            for (_, gss) in group.iter().cloned() {
1423                if debug {
1424                    eprintln!(
1425                        "[glrmask/debug][runtime_product_expand] product={} exact_source={} gss={}",
1426                        tokenizer_state,
1427                        source_state,
1428                        gss.ptr_key(),
1429                    );
1430                }
1431                state.insert_flat_alternative(source_offset + source_state, gss);
1432            }
1433            index = group_end;
1434            continue;
1435        }
1436
1437        debug_assert!(group
1438            .iter()
1439            .all(|(_, gss)| gss.all_accs_satisfy(|acc| acc.is_empty())));
1440        let Some(source_states) =
1441            constraint.runtime_product_source_states(tokenizer_state)
1442        else {
1443            for (_, gss) in group.iter().cloned() {
1444                state.insert_flat_alternative(tokenizer_state, gss);
1445            }
1446            index = group_end;
1447            continue;
1448        };
1449        if debug {
1450            eprintln!(
1451                "[glrmask/debug][runtime_product_expand] product={} sources={:?} alternatives={}",
1452                tokenizer_state,
1453                source_states,
1454                group.len(),
1455            );
1456        }
1457        for (_, gss) in group {
1458            for &source_state in source_states {
1459                state.insert_flat_alternative(source_offset + source_state, gss.clone());
1460            }
1461        }
1462        index = group_end;
1463    }
1464}
1465
1466/// Re-coalesce source states only when they carry the identical multiset of
1467/// parser alternatives.
1468///
1469/// For source subset `S` and alternatives `G`, the exact relation is then the
1470/// Cartesian product `S × G`, which duplicate entries under one product key
1471/// represent without loss. Grouping independently by GSS is insufficient:
1472/// distinct source groups can transition to the same product state while
1473/// carrying different alternative sets, erasing provenance on the next step.
1474fn coalesce_uniform_runtime_source_states(
1475    constraint: &Constraint,
1476    state: &mut ParserStateMap,
1477) {
1478    if constraint.uses_compact_segmented_parser_runtime() {
1479        return;
1480    }
1481    let Some(source_offset) = constraint.runtime_source_state_offset() else {
1482        return;
1483    };
1484    if !state.keys().any(|&state| state >= source_offset) {
1485        return;
1486    }
1487
1488    let debug = crate::env::var_os("GLRMASK_DEBUG_RUNTIME_PRODUCT").is_some();
1489    let old = std::mem::take(state).entries;
1490
1491    // Product states are a boundary-only representation. The whole source
1492    // frontier may therefore collapse exactly when every source key carries
1493    // the same multiset of existing parser alternatives: the relation is
1494    // `S × G`. Keep the representative GSS objects themselves so their
1495    // allocation-free in-place capacities and flat decomposition are retained.
1496    if old.is_empty() || old.iter().any(|(key, _)| *key < source_offset) {
1497        state.entries = old;
1498        return;
1499    }
1500
1501    let first_key = old[0].0;
1502    let first_end = old.partition_point(|(key, _)| *key == first_key);
1503    let representative = &old[..first_end];
1504    let mut source_states = vec![first_key - source_offset];
1505    let mut eligible = representative
1506        .iter()
1507        .all(|(_, gss)| gss.all_accs_satisfy(|acc| acc.is_empty()));
1508    let mut index = first_end;
1509    while eligible && index < old.len() {
1510        let key = old[index].0;
1511        let end = old[index..].partition_point(|(candidate, _)| *candidate == key) + index;
1512        let alternatives = &old[index..end];
1513        if alternatives.len() != representative.len()
1514            || alternatives
1515                .iter()
1516                .any(|(_, gss)| !gss.all_accs_satisfy(|acc| acc.is_empty()))
1517        {
1518            eligible = false;
1519            break;
1520        }
1521        let mut used = SmallVec::<[bool; INLINE_PARSER_STATE_CAPACITY]>::from_elem(false, alternatives.len());
1522        for (_, expected) in representative {
1523            let Some(match_index) = alternatives
1524                .iter()
1525                .enumerate()
1526                .position(|(candidate_index, (_, candidate))| {
1527                    !used[candidate_index]
1528                        && (expected.ptr_eq(candidate) || expected == candidate)
1529                })
1530            else {
1531                eligible = false;
1532                break;
1533            };
1534            used[match_index] = true;
1535        }
1536        if eligible {
1537            source_states.push(key - source_offset);
1538        }
1539        index = end;
1540    }
1541
1542    if eligible
1543        && let Some(product_state) =
1544            constraint.runtime_product_state_for_source_subset(&source_states)
1545    {
1546        if debug {
1547            eprintln!(
1548                "[glrmask/debug][runtime_product_coalesce] sources={:?} product={} alternatives={}",
1549                source_states,
1550                product_state,
1551                first_end,
1552            );
1553        }
1554        for (_, gss) in old.into_iter().take(first_end) {
1555            state.insert_flat_alternative(product_state, gss);
1556        }
1557    } else {
1558        if debug {
1559            eprintln!(
1560                "[glrmask/debug][runtime_product_keep_source] entries={} sources={:?}",
1561                old.len(),
1562                source_states,
1563            );
1564        }
1565        state.entries = old;
1566    }
1567}
1568
1569#[inline]
1570fn commit_token_impl(
1571    constraint: &Constraint,
1572    state: &mut ParserStateMap,
1573    buffers: &mut CommitBuffers,
1574    token_id: u32,
1575) -> Result<(), String> {
1576    commit_token_impl_observed(constraint, state, buffers, token_id, &mut NoMarkers)
1577}
1578
1579fn commit_token_impl_observed<O: CommitObserver>(
1580    constraint: &Constraint,
1581    state: &mut ParserStateMap,
1582    buffers: &mut CommitBuffers,
1583    token_id: u32,
1584    observer: &mut O,
1585) -> Result<(), String> {
1586    let bytes = token_bytes_for_id(constraint, token_id);
1587    let has_special = constraint.has_special_token_id(token_id);
1588    if bytes.is_none() && !has_special {
1589        return Err(format!(
1590            "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
1591        ));
1592    }
1593
1594    expand_runtime_product_states(constraint, state);
1595    let special_paths = has_special
1596        .then(|| advance_special_token_paths(constraint, state, token_id))
1597        .flatten();
1598    // Native, dynamic and composed masks admit an empty-spelled ID only through its
1599    // exact special-token action. Do not turn a rejected ordinary empty token
1600    // into a successful no-op commit; live special paths are merged below.
1601    let bytes = bytes.filter(|bytes| !bytes.is_empty()
1602        || !(constraint.has_template_parser() || constraint.uses_dynamic_runtime()
1603            || constraint.uses_compact_segmented_parser_runtime()));
1604    if let Some(bytes) = bytes {
1605        if commit_bytes_impl_observed(constraint, state, bytes, buffers, observer).is_err() {
1606            state.clear();
1607            buffers.reset_all();
1608        }
1609    } else {
1610        state.clear();
1611    }
1612    merge_special_token_paths(constraint, state, special_paths)?;
1613    if has_special { observer.frontier(constraint, state, bytes.map_or(0, |b| b.len())); }
1614    maybe_normalize_lookahead_invariant_reductions(constraint, state);
1615    coalesce_uniform_runtime_source_states(constraint, state);
1616    finish_token_commit(state)
1617}
1618
1619/// Exact one-token admission probe over an existing runtime state.
1620///
1621/// This is intentionally the ordinary authoritative commit implementation,
1622/// not a second recognizer. Recursive boundary-B masking uses it to validate
1623/// its small composition-owned candidate domain without translating the live
1624/// leaf-scoped tokenizer/parser state back into the transitional outer lexer
1625/// coordinate. `buffers` is reusable across probes; state-dependent caches are
1626/// reset between candidates while their allocated capacity is retained.
1627pub(crate) fn token_admissible_from_state_exact(
1628    constraint: &Constraint,
1629    source: &ParserStateMap,
1630    buffers: &mut CommitBuffers,
1631    token_id: u32,
1632) -> bool {
1633    buffers.reset_all();
1634    let mut probe = source.clone();
1635    commit_token_impl(constraint, &mut probe, buffers, token_id).is_ok()
1636}
1637
1638/// Advance an exact runtime state through one byte prefix without committing a
1639/// model-token boundary. Recursive composition masking retains the returned
1640/// frontier at vocabulary-trie nodes and reuses it for all child edges.
1641pub(crate) fn advance_bytes_from_state_exact(
1642    constraint: &Constraint,
1643    source: &ParserStateMap,
1644    buffers: &mut CommitBuffers,
1645    bytes: &[u8],
1646) -> Option<ParserStateMap> {
1647    if bytes.is_empty() {
1648        return Some(source.clone());
1649    }
1650    buffers.reset_all();
1651    let mut next = source.clone();
1652    commit_bytes_impl(constraint, &mut next, bytes, buffers).ok()?;
1653    (!next.is_empty()).then_some(next)
1654}
1655
1656/// Exact batched admission for ordinary byte-backed model tokens.
1657///
1658/// Candidates are sorted by byte string and evaluated as a radix tree.  Each
1659/// shared byte prefix is committed once through the ordinary authoritative
1660/// commit engine, then the resulting `ParserStateMap` is cheaply cloned for
1661/// its child branches.  A dead prefix rejects the complete subtree below it.
1662///
1663/// This helper deliberately handles byte semantics only.  Callers must keep
1664/// tokens with special-token semantics on `token_admissible_from_state_exact`,
1665/// because those tokens additionally fork parser paths that are not represented
1666/// by their byte spelling.
1667pub(crate) fn admissible_byte_token_candidates_from_state_exact(
1668    constraint: &Constraint,
1669    source: &ParserStateMap,
1670    buffers: &mut CommitBuffers,
1671    candidates: &mut Vec<(u32, &[u8])>,
1672    admitted: &mut Vec<u32>,
1673) {
1674    if candidates.is_empty() || source.is_empty() {
1675        return;
1676    }
1677    candidates.sort_unstable_by(|(left_id, left), (right_id, right)| {
1678        left.cmp(right).then_with(|| left_id.cmp(right_id))
1679    });
1680
1681    fn walk(
1682        constraint: &Constraint,
1683        source: &ParserStateMap,
1684        buffers: &mut CommitBuffers,
1685        entries: &[(u32, &[u8])],
1686        consumed: usize,
1687        admitted: &mut Vec<u32>,
1688    ) {
1689        let Some((_, first)) = entries.first() else {
1690            return;
1691        };
1692        let last = entries.last().expect("nonempty radix candidate group").1;
1693        let mut common_end = consumed;
1694        let common_limit = first.len().min(last.len());
1695        while common_end < common_limit && first[common_end] == last[common_end] {
1696            common_end += 1;
1697        }
1698
1699        let Some(frontier) = advance_bytes_from_state_exact(
1700            constraint,
1701            source,
1702            buffers,
1703            &first[consumed..common_end],
1704        ) else {
1705            return;
1706        };
1707
1708        // Every candidate ending at this prefix has exactly the byte language
1709        // already consumed into `frontier`.  Ordinary token commit rejects iff
1710        // that frontier is empty; token-end normalization is non-destructive in
1711        // the recursive runtime, and special-token alternatives are excluded by
1712        // the caller.
1713        let mut index = 0usize;
1714        while index < entries.len() && entries[index].1.len() == common_end {
1715            admitted.push(entries[index].0);
1716            index += 1;
1717        }
1718
1719        while index < entries.len() {
1720            debug_assert!(entries[index].1.len() > common_end);
1721            let branch_byte = entries[index].1[common_end];
1722            let mut end = index + 1;
1723            while end < entries.len()
1724                && entries[end].1.len() > common_end
1725                && entries[end].1[common_end] == branch_byte
1726            {
1727                end += 1;
1728            }
1729            walk(
1730                constraint,
1731                &frontier,
1732                buffers,
1733                &entries[index..end],
1734                common_end,
1735                admitted,
1736            );
1737            index = end;
1738        }
1739    }
1740
1741    walk(constraint, source, buffers, candidates, 0, admitted);
1742}
1743
1744#[cold]
1745pub(crate) fn prime_initial_commits(
1746    constraint: &Constraint,
1747    initial_state: &ParserStateMap,
1748    buffers: &mut CommitBuffers,
1749    token_ids: &[u32],
1750) {
1751    for &token_id in token_ids {
1752        let mut state = initial_state.clone();
1753        let _ = commit_token_impl(constraint, &mut state, buffers, token_id);
1754    }
1755}
1756
1757#[cold]
1758fn commit_token_no_fast_path_reference(
1759    constraint: &Constraint,
1760    state: &mut ParserStateMap,
1761    token_id: u32,
1762) -> Result<(), String> {
1763    let bytes = token_bytes_for_id(constraint, token_id);
1764    let has_special = constraint.has_special_token_id(token_id);
1765    if bytes.is_none() && !has_special {
1766        return Err(format!(
1767            "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
1768        ));
1769    }
1770
1771    expand_runtime_product_states(constraint, state);
1772    let special_paths = has_special
1773        .then(|| advance_special_token_paths(constraint, state, token_id))
1774        .flatten();
1775    if let Some(bytes) = bytes {
1776        let mut buffers = CommitBuffers::default();
1777        if commit_bytes_impl_profiled(
1778            constraint,
1779            state,
1780            bytes,
1781            &mut buffers,
1782            None,
1783            false,
1784        )
1785        .is_err()
1786        {
1787            state.clear();
1788        }
1789    } else {
1790        state.clear();
1791    }
1792    merge_special_token_paths(constraint, state, special_paths)?;
1793    coalesce_uniform_runtime_source_states(constraint, state);
1794    finish_token_commit(state)
1795}
1796
1797#[cold]
1798fn assert_commit_fast_path_equivalence(
1799    constraint: &Constraint,
1800    mut reference_state: ParserStateMap,
1801    token_id: u32,
1802    actual_state: &ParserStateMap,
1803    actual_succeeded: bool,
1804) {
1805    let reference_result =
1806        commit_token_no_fast_path_reference(constraint, &mut reference_state, token_id);
1807    assert_eq!(
1808        actual_succeeded,
1809        reference_result.is_ok(),
1810        "commit fast-path result mismatch for token_id {token_id}: actual_succeeded={} reference={:?}",
1811        actual_succeeded,
1812        reference_result,
1813    );
1814    let actual_canonical = canonical_commit_state_for_equivalence_assert(actual_state);
1815    let reference_canonical = canonical_commit_state_for_equivalence_assert(&reference_state);
1816    if actual_canonical != reference_canonical {
1817        // Bounded flat frontiers deliberately preserve lexer/parser
1818        // correlation that the map-only reference normalizes away. The fast
1819        // state can therefore be a strict internal refinement of the reference
1820        // without changing the accepted continuation language. Keep exact
1821        // state equality as the strongest oracle, but fall back to the public
1822        // semantic observations when the reference has merged correlations.
1823        let mut actual_semantic = constraint.start();
1824        actual_semantic.state = actual_state.clone();
1825        let mut reference_semantic = constraint.start();
1826        reference_semantic.state = reference_state;
1827        assert_eq!(
1828            actual_semantic.is_accepting(),
1829            reference_semantic.is_accepting(),
1830            "commit fast-path completion mismatch for token_id {token_id} bytes {}\nactual={actual_canonical:?}\nreference={reference_canonical:?}",
1831            format_optional_token_bytes(token_bytes_for_id(constraint, token_id)),
1832        );
1833        assert_eq!(
1834            actual_semantic.mask(),
1835            reference_semantic.mask(),
1836            "commit fast-path successor-mask mismatch for token_id {token_id} bytes {}\nactual={actual_canonical:?}\nreference={reference_canonical:?}",
1837            format_optional_token_bytes(token_bytes_for_id(constraint, token_id)),
1838        );
1839    }
1840}
1841
1842#[inline]
1843pub(crate) fn runtime_tokenizer_is_reset_state(constraint: &Constraint, state: u32) -> bool {
1844    if constraint.uses_compact_segmented_parser_runtime() {
1845        constraint.recursive_tokenizer_is_reset_state(state)
1846    } else {
1847        state == constraint.runtime_commit_initial_state()
1848    }
1849}
1850
1851#[inline]
1852fn runtime_tokenizer_future_terminals(
1853    constraint: &Constraint,
1854    state: u32,
1855) -> Option<Cow<'_, crate::ds::bitset::BitSet>> {
1856    if constraint.uses_compact_segmented_parser_runtime() {
1857        constraint.recursive_tokenizer_future_scoped_terminals(state)
1858    } else {
1859        Some(Cow::Borrowed(
1860            constraint.tokenizer.possible_future_terminals(state),
1861        ))
1862    }
1863}
1864
1865#[inline]
1866fn runtime_terminal_count(constraint: &Constraint) -> usize {
1867    constraint
1868        .uses_compact_segmented_parser_runtime()
1869        .then(|| constraint.recursive_runtime_terminal_count())
1870        .flatten()
1871        .unwrap_or(constraint.parser_terminal_count() as usize)
1872}
1873
1874/// An unfinished ignore lexeme is a valid byte prefix even though completing
1875/// it will not shift a parser terminal. Lexer-continuation tests must retain
1876/// that route independently of the parser's ordinary terminal admission.
1877#[inline]
1878fn runtime_future_contains_ignore(
1879    constraint: &Constraint,
1880    future: &crate::ds::bitset::BitSet,
1881) -> bool {
1882    if constraint.uses_compact_segmented_parser_runtime() {
1883        future.iter_ones().any(|terminal| {
1884            constraint.recursive_terminal_is_ignore(terminal as u32)
1885        })
1886    } else {
1887        constraint.ignore_terminal.is_some_and(|terminal| future.contains(terminal as usize))
1888    }
1889}
1890
1891#[inline]
1892fn end_state_may_advance(constraint: &Constraint, gss: &ParserGSS, end_state: u32) -> bool {
1893    if runtime_tokenizer_is_reset_state(constraint, end_state) {
1894        return true;
1895    }
1896    end_state_may_advance_exact(constraint, gss, end_state)
1897}
1898
1899// `end_state_may_advance` without the reset-state shortcut: can any terminal
1900// the lexer still matches from `end_state` advance the parser?
1901#[inline]
1902fn end_state_may_advance_exact(constraint: &Constraint, gss: &ParserGSS, end_state: u32) -> bool {
1903    let future = runtime_tokenizer_future_terminals(constraint, end_state)
1904        .expect("runtime tokenizer end state must belong to its active coordinate");
1905    parser_may_advance_on_any(constraint, gss, future.as_ref())
1906        || runtime_future_contains_ignore(constraint, future.as_ref())
1907}
1908
1909// Whether one frontier entry can still commit input: its lexer can extend, or
1910// a special token can be committed from it.
1911pub(crate) fn entry_can_continue(
1912    constraint: &Constraint,
1913    tokenizer_state: u32,
1914    gss: &ParserGSS,
1915) -> bool {
1916    if !runtime_tokenizer_is_reset_state(constraint, tokenizer_state) {
1917        // Commit admits a non-reset entry only after `end_state_may_advance`
1918        // and the exact-liveness post-pass, so it is already known to extend.
1919        return true;
1920    }
1921    if end_state_may_advance_exact(constraint, gss, tokenizer_state) {
1922        return true;
1923    }
1924    constraint.special_token_terminals.iter().any(|special| {
1925        !constraint.is_late_grammar_placeholder_terminal(special.terminal_id)
1926            && special_terminal_admissible(constraint, tokenizer_state, gss, special.terminal_id)
1927    })
1928}
1929
1930/// For a tokenizer execution that produced several end states against the same
1931/// parser GSS, compute exact parser admission once over the union of their
1932/// possible-future terminal sets.  Individual end-state viability is then an
1933/// intersection with this admitted set.
1934///
1935/// This is exactly equivalent to repeated `end_state_may_advance` because
1936///
1937///   exists t in F_i: can_advance(G, t)
1938///
1939/// iff `F_i` intersects the exact admitted set over `union_i F_i`.
1940///
1941/// Single non-initial end states deliberately keep the old boolean path: the
1942/// exact-set computation cannot beat its early-exit simulation in that case.
1943fn batched_end_state_admitted_terminals(
1944    constraint: &Constraint,
1945    gss: &ParserGSS,
1946    end_states: &[u32],
1947) -> Option<crate::ds::bitset::BitSet> {
1948    // Template admission is an existential domain query: its exact boolean
1949    // path can stop at a suffix-independent witness. Computing the full set
1950    // here would classify unrelated conditional terminals before intersecting
1951    // each lexer future, defeating that shortcut.
1952    if constraint.has_template_parser() { return None; }
1953    let mut candidates = crate::ds::bitset::BitSet::new(runtime_terminal_count(constraint));
1954    let mut non_initial = 0usize;
1955    for &end_state in end_states {
1956        if runtime_tokenizer_is_reset_state(constraint, end_state) {
1957            continue;
1958        }
1959        non_initial += 1;
1960        let future = runtime_tokenizer_future_terminals(constraint, end_state)?;
1961        candidates.union_with_prefix(future.as_ref());
1962    }
1963    if non_initial <= 1 {
1964        return None;
1965    }
1966    if let Some(admitted) = constraint.compact_segmented_parser_admitted_terminals(gss, &candidates) {
1967        return Some(admitted);
1968    }
1969    if let Some(direct) = constraint.direct_regular_admissible_terminals(gss) {
1970        let mut admitted = candidates;
1971        admitted.intersect_with(&direct);
1972        Some(admitted)
1973    } else {
1974        Some(exact_simulation_prefiltered_admitted_terminals(
1975            constraint,
1976            gss,
1977            &candidates,
1978        ))
1979    }
1980}
1981
1982
1983const PARSER_ADMISSION_CACHE_CAPACITY: usize = 8;
1984const PARSER_ADMISSION_BOOLEAN_CACHE_CAPACITY: usize = 8;
1985
1986fn exact_simulation_prefiltered_admitted_terminals(
1987    constraint: &Constraint,
1988    gss: &ParserGSS,
1989    candidates: &crate::ds::bitset::BitSet,
1990) -> crate::ds::bitset::BitSet {
1991    if let Some(parser) = &constraint.template_parser {
1992        return parser.admitted(gss, candidates);
1993    }
1994
1995    if constraint.parser_admission_policy() != AdmissionPolicy::ExactSimulation
1996        || constraint.parser_has_controls()
1997        || constraint.table.unconditional_advance.len() != constraint.parser_symbol_count() as usize
1998    {
1999        return stack_admissible_terminals(&constraint.table, gss, candidates);
2000    }
2001
2002    let mut guaranteed = crate::ds::bitset::BitSet::new(candidates.len());
2003    let mut unresolved = crate::ds::bitset::BitSet::new(candidates.len());
2004    for state in gss.peek_values() {
2005        let Some(advance) = constraint.table.advance.get(state as usize) else {
2006            return stack_admissible_terminals(&constraint.table, gss, candidates);
2007        };
2008        let Some(unconditional) = constraint.parser_unconditional_row(state) else {
2009            return stack_admissible_terminals(&constraint.table, gss, candidates);
2010        };
2011        bitset_union_intersection_prefix(&mut guaranteed, unconditional, candidates);
2012        bitset_union_intersection_prefix(&mut unresolved, advance, candidates);
2013    }
2014    for (unresolved_word, guaranteed_word) in unresolved
2015        .words_mut()
2016        .iter_mut()
2017        .zip(guaranteed.words())
2018    {
2019        *unresolved_word &= !*guaranteed_word;
2020    }
2021    if unresolved.is_empty() {
2022        return guaranteed;
2023    }
2024    let simulated = stack_admissible_terminals(&constraint.table, gss, &unresolved);
2025    guaranteed.union_with(&simulated);
2026    guaranteed
2027}
2028
2029#[inline]
2030pub(crate) fn exact_admitted_terminals_for_candidates(
2031    constraint: &Constraint,
2032    gss: &ParserGSS,
2033    candidates: &crate::ds::bitset::BitSet,
2034) -> crate::ds::bitset::BitSet {
2035    if let Some(parser) = &constraint.template_parser {
2036        return parser.admitted(gss, candidates);
2037    }
2038
2039    if let Some(admitted) = constraint.compact_segmented_parser_admitted_terminals(gss, candidates) {
2040        return admitted;
2041    }
2042    if let Some(direct) = constraint.direct_regular_admissible_terminals(gss) {
2043        let mut admitted = candidates.clone();
2044        admitted.intersect_with(&direct);
2045        admitted
2046    } else {
2047        exact_simulation_prefiltered_admitted_terminals(constraint, gss, candidates)
2048    }
2049}
2050
2051fn admission_cache_entry_index(
2052    cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
2053    gss: &ParserGSS,
2054    terminal_count: usize,
2055) -> usize {
2056    if let Some(index) = cache
2057        .iter()
2058        .position(|entry| entry.gss.ptr_eq(gss))
2059    {
2060        return index;
2061    }
2062    if cache.len() >= PARSER_ADMISSION_CACHE_CAPACITY {
2063        cache.remove(0);
2064    }
2065    cache.push(ParserAdmissionCacheEntry {
2066        gss: gss.clone(),
2067        tested: crate::ds::bitset::BitSet::new(terminal_count),
2068        admitted: crate::ds::bitset::BitSet::new(terminal_count),
2069        boolean_queries: SmallVec::new(),
2070    });
2071    cache.len() - 1
2072}
2073
2074fn try_local_row_presence_admission_words(
2075    constraint: &Constraint,
2076    gss: &ParserGSS,
2077    end_states: &[u32],
2078) -> Option<[u64; 32]> {
2079    const WORDS: usize = 32;
2080    if constraint.uses_compact_segmented_parser_runtime()
2081        || constraint.parser_admission_policy() != AdmissionPolicy::ExactSimulation
2082        || constraint.parser_has_controls()
2083        || constraint.tokenizer.num_terminals() as usize > WORDS * 64
2084        || (!constraint.has_template_parser()
2085            && (constraint.table.advance.len() != constraint.parser_symbol_count() as usize
2086                || constraint.table.unconditional_advance.len()
2087                    != constraint.parser_symbol_count() as usize))
2088    {
2089        return None;
2090    }
2091    let tops = gss.peek_values();
2092    if tops.is_empty() {
2093        return None;
2094    }
2095
2096    // Only terminals reachable from the tokenizer continuation matter. Both
2097    // backends provide a sound upper bound P and a suffix-independent lower
2098    // bound U. If (P - U) intersects none of these candidates, U is exact for
2099    // this query. Template rows are derived from the input-domain automata;
2100    // this shortcut neither reads an LR action nor materializes output stacks.
2101    let initial = constraint.runtime_commit_initial_state();
2102    let mut candidates = [0u64; WORDS];
2103    for &end_state in end_states {
2104        if end_state == initial {
2105            continue;
2106        }
2107        for (index, &word) in constraint
2108            .tokenizer
2109            .possible_future_terminals(end_state)
2110            .words()
2111            .iter()
2112            .enumerate()
2113        {
2114            if index >= WORDS {
2115                return None;
2116            }
2117            candidates[index] |= word;
2118        }
2119    }
2120
2121    let mut admitted = [0u64; WORDS];
2122    for state in tops {
2123        let advance = constraint.parser_advance_row(state)?;
2124        let unconditional = constraint.parser_unconditional_row(state)?;
2125        for index in 0..advance.words().len().min(WORDS) {
2126            let candidate_word = candidates[index];
2127            if candidate_word == 0 {
2128                continue;
2129            }
2130            let advance_word = advance.words()[index];
2131            let unconditional_word = unconditional.words().get(index).copied().unwrap_or(0);
2132            if (advance_word & !unconditional_word & candidate_word) != 0 {
2133                return None;
2134            }
2135            admitted[index] |= unconditional_word & candidate_word;
2136        }
2137    }
2138    Some(admitted)
2139}
2140
2141#[inline]
2142fn end_state_may_advance_from_row_words(
2143    constraint: &Constraint,
2144    end_state: u32,
2145    admitted_words: &[u64; 32],
2146) -> bool {
2147    if runtime_tokenizer_is_reset_state(constraint, end_state) {
2148        return true;
2149    }
2150    let future = runtime_tokenizer_future_terminals(constraint, end_state)
2151        .expect("runtime tokenizer end state must belong to its active coordinate");
2152    future
2153        .words()
2154        .iter()
2155        .zip(admitted_words.iter())
2156        .any(|(&future, admitted)| (future & *admitted) != 0)
2157        || runtime_future_contains_ignore(constraint, future.as_ref())
2158}
2159
2160/// Cached exact-set version of `batched_end_state_admitted_terminals`.
2161/// Returns the cache entry containing exact admission facts for every terminal
2162/// occurring in these end-state future sets. Single-end-state callers use the
2163/// cheaper boolean cache instead.
2164fn cached_batched_end_state_admission(
2165    constraint: &Constraint,
2166    gss: &ParserGSS,
2167    end_states: &[u32],
2168    cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
2169) -> Option<usize> {
2170    if constraint.has_template_parser() { return None; }
2171    let mut candidates = crate::ds::bitset::BitSet::new(runtime_terminal_count(constraint));
2172    let mut non_initial = 0usize;
2173    for &end_state in end_states {
2174        if runtime_tokenizer_is_reset_state(constraint, end_state) {
2175            continue;
2176        }
2177        non_initial += 1;
2178        let future = runtime_tokenizer_future_terminals(constraint, end_state)?;
2179        candidates.union_with_prefix(future.as_ref());
2180    }
2181    if non_initial <= 1 {
2182        return None;
2183    }
2184    let index = admission_cache_entry_index(cache, gss, candidates.len());
2185    let delta = candidates.difference(&cache[index].tested);
2186    if !delta.is_empty() {
2187        let newly_admitted = exact_admitted_terminals_for_candidates(constraint, gss, &delta);
2188        let entry = &mut cache[index];
2189        entry.tested.union_with(&delta);
2190        entry.admitted.union_with(&newly_admitted);
2191    }
2192    Some(index)
2193}
2194
2195/// Exact cached boolean admission for one tokenizer end state. If a prior
2196/// batched query has already classified all future terminals, answer directly
2197/// from the pointwise cache. Otherwise cache the old exact existential result
2198/// for this complete future set.
2199fn cached_single_end_state_may_advance(
2200    constraint: &Constraint,
2201    gss: &ParserGSS,
2202    end_state: u32,
2203    cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
2204) -> bool {
2205    if runtime_tokenizer_is_reset_state(constraint, end_state) {
2206        return true;
2207    }
2208    let Some(future) = runtime_tokenizer_future_terminals(constraint, end_state) else {
2209        return false;
2210    };
2211    let future = future.as_ref();
2212    let index = admission_cache_entry_index(cache, gss, future.len());
2213    {
2214        let entry = &cache[index];
2215        if future.is_subset_of_extended(&entry.tested) {
2216            return !future.is_disjoint(&entry.admitted)
2217                || runtime_future_contains_ignore(constraint, future);
2218        }
2219        if let Some((_, result)) = entry
2220            .boolean_queries
2221            .iter()
2222            .find(|(query, _)| query == future)
2223        {
2224            return *result;
2225        }
2226    }
2227    let result = parser_may_advance_on_any(constraint, gss, future)
2228        || runtime_future_contains_ignore(constraint, future);
2229    let entry = &mut cache[index];
2230    if entry.boolean_queries.len() >= PARSER_ADMISSION_BOOLEAN_CACHE_CAPACITY {
2231        entry.boolean_queries.remove(0);
2232    }
2233    entry.boolean_queries.push((future.clone(), result));
2234    result
2235}
2236
2237#[inline]
2238fn end_state_may_advance_from_cache_entry(
2239    constraint: &Constraint,
2240    end_state: u32,
2241    entry: &ParserAdmissionCacheEntry,
2242) -> bool {
2243    if runtime_tokenizer_is_reset_state(constraint, end_state) {
2244        return true;
2245    }
2246    let future = runtime_tokenizer_future_terminals(constraint, end_state)
2247        .expect("runtime tokenizer end state must belong to its active coordinate");
2248    !entry.admitted.is_disjoint_prefix(future.as_ref())
2249        || runtime_future_contains_ignore(constraint, future.as_ref())
2250}
2251
2252
2253#[inline]
2254fn end_state_may_advance_with_batch(
2255    constraint: &Constraint,
2256    gss: &ParserGSS,
2257    end_state: u32,
2258    admitted: Option<&crate::ds::bitset::BitSet>,
2259) -> bool {
2260    if runtime_tokenizer_is_reset_state(constraint, end_state) {
2261        return true;
2262    }
2263    match admitted {
2264        Some(admitted) => {
2265            let future = runtime_tokenizer_future_terminals(constraint, end_state)
2266                .expect("runtime tokenizer end state must belong to its active coordinate");
2267            !admitted.is_disjoint_prefix(future.as_ref())
2268                || runtime_future_contains_ignore(constraint, future.as_ref())
2269        }
2270        None => end_state_may_advance(constraint, gss, end_state),
2271    }
2272}
2273
2274#[inline]
2275fn wide_frontier_end_state_may_advance(
2276    constraint: &Constraint,
2277    summary: &crate::runtime::artifact::DirectRegularWideFrontierAcceptance,
2278    end_state: u32,
2279) -> bool {
2280    if end_state == constraint.tokenizer.initial_state() {
2281        return true;
2282    }
2283    summary
2284        .actionable_terminals
2285        .words()
2286        .iter()
2287        .zip(constraint.tokenizer.possible_future_terminals(end_state).words())
2288        .any(|(actionable, future)| (*actionable & *future) != 0)
2289        || runtime_future_contains_ignore(constraint, constraint.tokenizer.possible_future_terminals(end_state))
2290}
2291
2292enum ActionableTerminals {
2293    DirectDynamic(crate::ds::bitset::BitSet),
2294    SingleState(u32),
2295    WideFrontier(usize),
2296    ManyStates(SmallVec<[u32; 8]>),
2297}
2298
2299impl ActionableTerminals {
2300    fn from_gss(constraint: &Constraint, gss: &ParserGSS) -> Option<Self> {
2301        if constraint.uses_compact_segmented_parser_runtime() {
2302            return None;
2303        }
2304        if let Some(terminals) = constraint.direct_regular_admissible_terminals(gss) {
2305            return Some(Self::DirectDynamic(terminals));
2306        }
2307        if let Some(state_id) = gss.single_top_value() {
2308            return Some(Self::SingleState(state_id));
2309        }
2310        if let Some(index) = constraint.direct_regular_wide_frontier_index_for_gss(gss) {
2311            return Some(Self::WideFrontier(index));
2312        }
2313
2314        let states = gss.peek_values();
2315        if states.is_empty() {
2316            None
2317        } else {
2318            Some(Self::ManyStates(states))
2319        }
2320    }
2321
2322    fn bitset<'a>(&'a self, constraint: &'a Constraint) -> Option<&'a crate::ds::bitset::BitSet> {
2323        match self {
2324            Self::DirectDynamic(terminals) => Some(terminals),
2325            Self::SingleState(state_id) => constraint.parser_advance_row(*state_id),
2326            Self::WideFrontier(index) => constraint
2327                .direct_regular_wide_frontier_acceptance
2328                .get(*index)
2329                .map(|summary| &summary.actionable_terminals),
2330            Self::ManyStates(_) => None,
2331        }
2332    }
2333
2334    fn contains(&self, constraint: &Constraint, terminal: u32) -> bool {
2335        match self {
2336            Self::DirectDynamic(terminals) => terminals.contains(terminal as usize),
2337            Self::SingleState(state_id) => constraint.parser_advance_row_allows(*state_id, terminal),
2338            Self::WideFrontier(index) => constraint
2339                .direct_regular_wide_frontier_acceptance
2340                .get(*index)
2341                .is_some_and(|summary| summary.actionable_terminals.contains(terminal as usize)),
2342            Self::ManyStates(states) => states
2343                .iter()
2344                .any(|state_id| constraint.parser_advance_row_allows(*state_id, terminal)),
2345        }
2346    }
2347}
2348
2349impl InitialCommitScan {
2350    fn collect(
2351        constraint: &Constraint,
2352        state: &ParserStateMap,
2353        bytes: &[u8],
2354    ) -> Self {
2355        let mut exec_results = FxHashMap::default();
2356
2357        for &tokenizer_state in state.keys() {
2358            let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
2359            exec_results.insert(tokenizer_state, exec_result);
2360        }
2361
2362        Self { exec_results }
2363    }
2364
2365    fn take_exec_result(&mut self, tokenizer_state: u32) -> Option<TokenizerExecResult> {
2366        self.exec_results.remove(&tokenizer_state)
2367    }
2368}
2369
2370fn is_ignored_terminal(ignore_terminal: Option<u32>, terminal: u32) -> bool {
2371    Some(terminal) == ignore_terminal
2372}
2373
2374#[inline]
2375fn runtime_is_ignored_terminal(
2376    constraint: &Constraint,
2377    ignore_terminal: Option<u32>,
2378    terminal: u32,
2379) -> bool {
2380    if constraint.uses_compact_segmented_parser_runtime() {
2381        constraint.recursive_terminal_is_ignore(terminal)
2382    } else {
2383        is_ignored_terminal(ignore_terminal, terminal)
2384    }
2385}
2386
2387fn is_actionable_terminal(
2388    actionable_terminals: Option<&ActionableTerminals>,
2389    constraint: &Constraint,
2390    terminal: u32,
2391) -> bool {
2392    actionable_terminals.is_none_or(|actionable| actionable.contains(constraint, terminal))
2393}
2394
2395
2396fn for_each_relevant_matched_terminal(
2397    constraint: &Constraint,
2398    tokenizer_state: u32,
2399    actionable_terminals: Option<&ActionableTerminals>,
2400    mut visit: impl FnMut(u32, bool),
2401) {
2402    let matched = constraint.tokenizer.matched_terminal_bitset(tokenizer_state);
2403    if let Some(actionable) = actionable_terminals.and_then(|value| value.bitset(constraint)) {
2404        let ignored = constraint.ignore_terminal;
2405        for (word_index, (&matched_word, &actionable_word)) in
2406            matched.words().iter().zip(actionable.words()).enumerate()
2407        {
2408            let mut intersection = matched_word & actionable_word;
2409            while intersection != 0 {
2410                let bit = intersection.trailing_zeros() as usize;
2411                let terminal = (word_index * 64 + bit) as u32;
2412                if Some(terminal) != ignored {
2413                    visit(terminal, false);
2414                }
2415                intersection &= intersection - 1;
2416            }
2417        }
2418        if let Some(ignored) = ignored
2419            && matched.contains(ignored as usize)
2420        {
2421            visit(ignored, true);
2422        }
2423        return;
2424    }
2425
2426    for terminal in constraint.tokenizer.matched_terminals_iter(tokenizer_state) {
2427        let ignored = is_ignored_terminal(constraint.ignore_terminal, terminal);
2428        if ignored || is_actionable_terminal(actionable_terminals, constraint, terminal) {
2429            visit(terminal, ignored);
2430        }
2431    }
2432}
2433
2434fn scan_wide_frontier_lexer_only(
2435    constraint: &Constraint,
2436    bytes: &[u8],
2437    start_state: u32,
2438    summary: &crate::runtime::artifact::DirectRegularWideFrontierAcceptance,
2439) -> Option<u32> {
2440    if constraint.tokenizer_has_epsilon_transitions {
2441        return None;
2442    }
2443    let mut state = start_state;
2444    for &byte in bytes {
2445        state = constraint.tokenizer_fast_transitions.transition(
2446            &constraint.tokenizer,
2447            state,
2448            byte,
2449        );
2450        if state == u32::MAX {
2451            return None;
2452        }
2453        let matched = constraint.tokenizer.matched_terminal_bitset(state);
2454        if matched
2455            .words()
2456            .iter()
2457            .zip(summary.actionable_terminals.words())
2458            .any(|(left, right)| (*left & *right) != 0)
2459            || constraint
2460                .ignore_terminal
2461                .is_some_and(|terminal| matched.contains(terminal as usize))
2462        {
2463            return None;
2464        }
2465    }
2466    Some(state)
2467}
2468
2469fn advance_uniform_disallowed_interest_only(
2470    constraint: &Constraint,
2471    terminals_disallowed: &TerminalsDisallowed,
2472    bytes: &[u8],
2473) -> Option<TerminalsDisallowed> {
2474    if terminals_disallowed.is_empty() {
2475        return Some(TerminalsDisallowed::new());
2476    }
2477    if constraint.tokenizer_has_epsilon_transitions {
2478        return None;
2479    }
2480
2481    let mut remapped = BTreeMap::<u32, BTreeSet<u32>>::new();
2482    for (&continuation_state, disallowed) in terminals_disallowed.iter() {
2483        let mut state = continuation_state;
2484        let mut alive = true;
2485        for &byte in bytes {
2486            state = constraint.tokenizer_fast_transitions.transition(
2487                &constraint.tokenizer,
2488                state,
2489                byte,
2490            );
2491            if state == u32::MAX {
2492                alive = false;
2493                break;
2494            }
2495            let matched = constraint.tokenizer.matched_terminal_bitset(state);
2496            if disallowed
2497                .iter()
2498                .any(|terminal| matched.contains(*terminal as usize))
2499            {
2500                return None;
2501            }
2502        }
2503        if !alive {
2504            continue;
2505        }
2506        let future = constraint.tokenizer.possible_future_terminals(state);
2507        for &terminal in disallowed {
2508            if future.contains(terminal as usize) {
2509                remapped.entry(state).or_default().insert(terminal);
2510            }
2511        }
2512    }
2513    Some(TerminalsDisallowed::from_map(remapped))
2514}
2515
2516fn collect_unique_actionable_reusable_matches(
2517    constraint: &Constraint,
2518    actionable_terminals: Option<&ActionableTerminals>,
2519    ignore_terminal: Option<u32>,
2520    matches: &[TokenizerMatch],
2521) -> SmallVec<[NormalizedMatch; 16]> {
2522    // `execute_tokenizer_reusable*` canonicalizes to one record per terminal at
2523    // its longest width, so no second duplicate-removal pass is needed here.
2524    let mut normalized = SmallVec::<[NormalizedMatch; 16]>::new();
2525    for matched in matches {
2526        let ignored = runtime_is_ignored_terminal(constraint, ignore_terminal, matched.id);
2527        if !ignored && !is_actionable_terminal(actionable_terminals, constraint, matched.id) {
2528            continue;
2529        }
2530        normalized.push(NormalizedMatch {
2531            terminal_id: matched.id,
2532            width: matched.width,
2533            ignored,
2534        });
2535    }
2536    normalized
2537}
2538
2539fn collect_unique_actionable_matches(
2540    constraint: &Constraint,
2541    actionable_terminals: Option<&ActionableTerminals>,
2542    ignore_terminal: Option<u32>,
2543    matches: &[TokenizerMatch],
2544    reusable_seen_matches: Option<&mut FxHashSet<(usize, u32)>>,
2545) -> SmallVec<[NormalizedMatch; 16]> {
2546    let mut normalized = SmallVec::<[NormalizedMatch; 16]>::new();
2547
2548    if matches.len() <= SMALL_NORMALIZED_MATCH_LINEAR_SCAN_MAX {
2549        'matches: for matched in matches {
2550            let ignored = runtime_is_ignored_terminal(constraint, ignore_terminal, matched.id);
2551            if !ignored && !is_actionable_terminal(actionable_terminals, constraint, matched.id) {
2552                continue;
2553            }
2554            for existing in &normalized {
2555                if existing.width == matched.width && existing.terminal_id == matched.id {
2556                    continue 'matches;
2557                }
2558            }
2559            normalized.push(NormalizedMatch {
2560                terminal_id: matched.id,
2561                width: matched.width,
2562                ignored,
2563            });
2564        }
2565        return normalized;
2566    }
2567
2568    if let Some(seen_matches) = reusable_seen_matches {
2569        seen_matches.clear();
2570        for matched in matches {
2571            let ignored = runtime_is_ignored_terminal(constraint, ignore_terminal, matched.id);
2572            if !ignored && !is_actionable_terminal(actionable_terminals, constraint, matched.id) {
2573                continue;
2574            }
2575            if !seen_matches.insert((matched.width, matched.id)) {
2576                continue;
2577            }
2578            normalized.push(NormalizedMatch {
2579                terminal_id: matched.id,
2580                width: matched.width,
2581                ignored,
2582            });
2583        }
2584        return normalized;
2585    }
2586
2587    let mut seen_matches = FxHashSet::default();
2588    for matched in matches {
2589        let ignored = runtime_is_ignored_terminal(constraint, ignore_terminal, matched.id);
2590        if !ignored && !is_actionable_terminal(actionable_terminals, constraint, matched.id) {
2591            continue;
2592        }
2593        if !seen_matches.insert((matched.width, matched.id)) {
2594            continue;
2595        }
2596        normalized.push(NormalizedMatch {
2597            terminal_id: matched.id,
2598            width: matched.width,
2599            ignored,
2600        });
2601    }
2602    normalized
2603}
2604
2605fn prune_single_initial_state_for_exec(
2606    constraint: &Constraint,
2607    gss: ParserGSS,
2608    tokenizer_state: u32,
2609    exec_result: &TokenizerExecResult,
2610    bytes: &[u8],
2611) -> ParserGSS {
2612    prune_single_initial_state_for_parts(
2613        constraint,
2614        gss,
2615        tokenizer_state,
2616        &exec_result.end_state,
2617        &exec_result.matches,
2618        bytes,
2619    )
2620}
2621
2622fn advance_terminals_disallowed_over_bytes(
2623    constraint: &Constraint,
2624    terminals_disallowed: &TerminalsDisallowed,
2625    bytes: &[u8],
2626    reusable_execution: Option<(u32, &[u32], &[TokenizerMatch])>,
2627) -> Option<TerminalsDisallowed> {
2628    if terminals_disallowed.is_empty() {
2629        return Some(TerminalsDisallowed::new());
2630    }
2631
2632    let mut remapped = BTreeMap::new();
2633    for (&continuation_tokenizer_state, disallowed) in terminals_disallowed.iter() {
2634        let owned_execution;
2635        let (end_states, matches) = match reusable_execution {
2636            Some((state, end_states, matches)) if state == continuation_tokenizer_state => {
2637                (end_states, matches)
2638            }
2639            _ => {
2640                owned_execution = execute_tokenizer_from_state_small(
2641                    constraint,
2642                    bytes,
2643                    continuation_tokenizer_state,
2644                );
2645                (&owned_execution.end_state[..], &owned_execution.matches[..])
2646            }
2647        };
2648        if matches.iter()
2649            .any(|matched| disallowed.contains(&matched.id))
2650        {
2651            return None;
2652        }
2653        for &end_state in end_states {
2654            let future = runtime_tokenizer_future_terminals(constraint, end_state)?;
2655            for &terminal in disallowed.iter() {
2656                if future.contains(terminal as usize) {
2657                    remapped
2658                        .entry(end_state)
2659                        .or_insert_with(BTreeSet::new)
2660                        .insert(terminal);
2661                }
2662            }
2663        }
2664    }
2665    Some(TerminalsDisallowed::from_map(remapped))
2666}
2667
2668fn single_disallowed_pair(acc: &TerminalsDisallowed) -> Option<(u32, u32)> {
2669    if acc.len() != 1 {
2670        return None;
2671    }
2672    let mut states = acc.iter();
2673    let (state, terminals) = states.next()?;
2674    if states.next().is_some() || terminals.len() != 1 {
2675        return None;
2676    }
2677    Some((*state, *terminals.iter().next()?))
2678}
2679
2680fn try_prune_single_initial_state_batched_accumulators(
2681    constraint: &Constraint,
2682    gss: &ParserGSS,
2683    bytes: &[u8],
2684    scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
2685    cached_starts: &mut SmallVec<[u32; 8]>,
2686) -> Option<ParserGSS> {
2687    let mut accumulators = SmallVec::<[TerminalsDisallowed; 8]>::new();
2688    let mut overflow = false;
2689    gss.for_each_acc(|acc| {
2690        if overflow || acc.is_empty() || accumulators.contains(acc) {
2691            return;
2692        }
2693        if accumulators.len() == accumulators.capacity() {
2694            overflow = true;
2695            return;
2696        }
2697        accumulators.push(acc.clone());
2698    });
2699    if overflow || accumulators.len() < 2 {
2700        return None;
2701    }
2702
2703    let mut pairs = SmallVec::<[(u32, u32); 8]>::new();
2704    for acc in &accumulators {
2705        pairs.push(single_disallowed_pair(acc)?);
2706    }
2707    // Each logical exclusion must belong to a disjoint lexer lane.  Then one
2708    // union execution preserves lane-local longest-match semantics because no
2709    // terminal ID can be observed from two starts.
2710    for i in 0..pairs.len() {
2711        let left = constraint.tokenizer.possible_future_terminals(pairs[i].0);
2712        for &(right_state, _) in &pairs[..i] {
2713            if !left.is_disjoint(
2714                constraint.tokenizer.possible_future_terminals(right_state),
2715            ) {
2716                return None;
2717            }
2718        }
2719    }
2720    let starts = pairs
2721        .iter()
2722        .map(|&(state, _)| state)
2723        .collect::<SmallVec<[u32; 8]>>();
2724    if !execute_tokenizer_reusable_from_states(constraint, bytes, &starts, scratch) {
2725        return None;
2726    }
2727    cached_starts.clear();
2728    cached_starts.extend(starts.iter().copied());
2729
2730    let mut remapped = SmallVec::<[(TerminalsDisallowed, Option<TerminalsDisallowed>); 8]>::new();
2731    for (acc, &(_, terminal)) in accumulators.iter().zip(&pairs) {
2732        if scratch.matches.iter().any(|matched| matched.id == terminal) {
2733            remapped.push((acc.clone(), None));
2734            continue;
2735        }
2736        let mut next = TerminalsDisallowed::new();
2737        for &end_state in &scratch.states {
2738            if constraint
2739                .tokenizer
2740                .possible_future_terminals(end_state)
2741                .contains(terminal as usize)
2742            {
2743                next = next.with_insert(end_state, terminal);
2744            }
2745        }
2746        remapped.push((acc.clone(), Some(next)));
2747    }
2748
2749    Some(gss.apply_and_prune_no_promote(|acc| {
2750        if acc.is_empty() {
2751            return Some(TerminalsDisallowed::new());
2752        }
2753        remapped
2754            .iter()
2755            .find(|(source, _)| source == acc)
2756            .and_then(|(_, result)| result.clone())
2757    }))
2758}
2759
2760fn prune_single_initial_state_for_parts(
2761    constraint: &Constraint,
2762    gss: ParserGSS,
2763    tokenizer_state: u32,
2764    end_states: &[u32],
2765    matches: &[TokenizerMatch],
2766    bytes: &[u8],
2767) -> ParserGSS {
2768    gss.apply_and_prune_no_promote(|terminals_disallowed: &TerminalsDisallowed| {
2769        advance_terminals_disallowed_over_bytes(
2770            constraint,
2771            terminals_disallowed,
2772            bytes,
2773            Some((tokenizer_state, end_states, matches)),
2774        )
2775    })
2776}
2777
2778fn prune_single_initial_state_for_terminal(
2779    gss: ParserGSS,
2780    tokenizer_state: u32,
2781    terminal: u32,
2782    end_state: Option<u32>,
2783) -> ParserGSS {
2784    if end_state.is_none()
2785        && gss.all_accs_satisfy(|td: &TerminalsDisallowed| {
2786            td.get(&tokenizer_state)
2787                .is_none_or(|disallowed| !disallowed.contains(&terminal))
2788        })
2789    {
2790        return gss.apply(|_: &TerminalsDisallowed| TerminalsDisallowed::new());
2791    }
2792
2793    gss.apply_and_prune_no_promote(|terminals_disallowed: &TerminalsDisallowed| {
2794        if terminals_disallowed.is_empty() {
2795            return Some(TerminalsDisallowed::new());
2796        }
2797        if let Some(disallowed) = terminals_disallowed.get(&tokenizer_state)
2798            && disallowed.contains(&terminal) {
2799                return None;
2800            }
2801
2802        let mut remapped = BTreeMap::new();
2803        if let Some(end_state) = end_state
2804            && let Some(disallowed) = terminals_disallowed.get(&tokenizer_state) {
2805                remapped
2806                    .entry(end_state)
2807                    .or_insert_with(BTreeSet::new)
2808                    .extend(disallowed.iter().copied());
2809            }
2810        Some(TerminalsDisallowed::from_map(remapped))
2811    })
2812}
2813
2814fn merge_parser_state(
2815    states: &mut ParserStatesByTokenizer,
2816    tokenizer_state: u32,
2817    gss: ParserGSS,
2818) {
2819    states
2820        .entry(tokenizer_state)
2821        .and_modify(|existing| *existing = existing.merge(&gss))
2822        .or_insert(gss);
2823}
2824
2825fn queue_parser_state(
2826    processing_queue: &mut [ParserStatesByTokenizer],
2827    pending_state: &mut ParserStatesByTokenizer,
2828    new_offset: usize,
2829    total_len: usize,
2830    tokenizer_state: u32,
2831    gss: ParserGSS,
2832) {
2833    if new_offset == total_len {
2834        merge_parser_state(pending_state, tokenizer_state, gss);
2835    } else {
2836        merge_parser_state(&mut processing_queue[new_offset], tokenizer_state, gss);
2837    }
2838}
2839
2840fn queue_parser_reset_state(
2841    constraint: &Constraint,
2842    processing_queue: &mut [ParserStatesByTokenizer],
2843    pending_state: &mut ParserStatesByTokenizer,
2844    new_offset: usize,
2845    total_len: usize,
2846    gss: ParserGSS,
2847) -> bool {
2848    if !constraint.uses_compact_segmented_parser_runtime() {
2849        queue_parser_state(
2850            processing_queue,
2851            pending_state,
2852            new_offset,
2853            total_len,
2854            constraint.runtime_commit_initial_state(),
2855            gss,
2856        );
2857        return true;
2858    }
2859    let Some(partitions) = constraint.partition_recursive_parser_gss_by_active_leaf(&gss) else {
2860        return false;
2861    };
2862    for (leaf_index, partition) in partitions {
2863        let Some(reset_state) = constraint.recursive_tokenizer_reset_state(leaf_index) else {
2864            return false;
2865        };
2866        queue_parser_state(
2867            processing_queue,
2868            pending_state,
2869            new_offset,
2870            total_len,
2871            reset_state,
2872            partition,
2873        );
2874    }
2875    true
2876}
2877
2878fn queue_parser_ignored_reset_state(
2879    constraint: &Constraint,
2880    processing_queue: &mut [ParserStatesByTokenizer],
2881    pending_state: &mut ParserStatesByTokenizer,
2882    new_offset: usize,
2883    total_len: usize,
2884    gss: ParserGSS,
2885) -> bool {
2886    let gss = if constraint.uses_compact_segmented_parser_runtime() {
2887        constraint
2888            .close_compact_segmented_parser(&gss)
2889            .unwrap_or(gss)
2890    } else {
2891        gss
2892    };
2893    queue_parser_reset_state(
2894        constraint,
2895        processing_queue,
2896        pending_state,
2897        new_offset,
2898        total_len,
2899        gss,
2900    )
2901}
2902
2903fn finalize_pending_state(
2904    pending_state: &mut ParserStatesByTokenizer,
2905) -> ParserStateMap {
2906    match pending_state.len() {
2907        0 => ParserStateMap::default(),
2908        1 => {
2909            let (tokenizer_state, parser_state) = pending_state.drain().next().unwrap();
2910            let fused = parser_state.fuse(Some(1));
2911            if fused.is_empty() {
2912                ParserStateMap::default()
2913            } else {
2914                ParserStateMap::singleton(tokenizer_state, fused)
2915            }
2916        }
2917        _ => {
2918            let mut new_state: ParserStateMap = pending_state.drain().collect();
2919            for parser_state in new_state.values_mut() {
2920                *parser_state = parser_state.fuse(Some(1));
2921            }
2922            new_state.retain(|_, parser_state| !parser_state.is_empty());
2923            new_state
2924        }
2925    }
2926}
2927
2928fn apply_future_terminal_disallow(
2929    constraint: &Constraint,
2930    exec_result: &TokenizerExecResult,
2931    terminal: u32,
2932    gss: ParserGSS,
2933) -> ParserGSS {
2934    apply_future_terminal_disallow_for_states(
2935        constraint,
2936        &exec_result.end_state,
2937        terminal,
2938        gss,
2939    )
2940}
2941
2942fn apply_future_terminal_disallow_for_states(
2943    constraint: &Constraint,
2944    end_states: &[u32],
2945    terminal: u32,
2946    gss: ParserGSS,
2947) -> ParserGSS {
2948    if gss.is_empty() || end_states.is_empty() {
2949        return gss;
2950    }
2951    let relevant: SmallVec<[u32; INLINE_PARSER_STATE_CAPACITY]> = end_states
2952        .iter()
2953        .copied()
2954        .filter(|&end_state| {
2955            runtime_tokenizer_future_terminals(constraint, end_state)
2956                .is_some_and(|future| future.contains(terminal as usize))
2957        })
2958        .collect();
2959    if relevant.is_empty() {
2960        return gss;
2961    }
2962
2963    gss.apply(|terminals_disallowed: &TerminalsDisallowed| {
2964        let mut updated = terminals_disallowed.clone();
2965        for &end_state in &relevant {
2966            updated = updated.with_insert(end_state, terminal);
2967        }
2968        updated
2969    })
2970}
2971
2972#[inline]
2973fn try_apply_single_top_action_in_place(gss: &mut ParserGSS, action: &Action) -> bool {
2974    match action {
2975        Action::Skip => true,
2976        Action::Shift(target, replace) => {
2977            let pushes = [*target];
2978            gss.try_apply_single_segment_stack_effect_in_place(usize::from(*replace), &pushes)
2979        }
2980        Action::ReplaceShifts(targets) if targets.len() == 1 => {
2981            gss.try_apply_single_segment_stack_effect_in_place(1, targets)
2982        }
2983        Action::StackShifts(shifts) => {
2984            let [shift] = shifts.as_slice() else {
2985                return false;
2986            };
2987            gss.try_apply_single_segment_stack_effect_in_place(
2988                shift.pop as usize,
2989                &shift.pushes,
2990            )
2991        }
2992        _ => false,
2993    }
2994}
2995
2996#[inline]
2997fn apply_single_top_action_fast(
2998    constraint: &Constraint,
2999    gss: &ParserGSS,
3000    state: u32,
3001    terminal: u32,
3002    action: &Action,
3003) -> Option<ParserGSS> {
3004    if let Some(cached) = constraint.direct_regular_cached_advance(gss, terminal) {
3005        return Some(cached);
3006    }
3007    let table = &constraint.table;
3008    match action {
3009        Action::Skip => Some(gss.clone()),
3010        Action::Shift(target, is_replace) => {
3011            if let Some(mut stack) = gss.try_virtual_stack() {
3012                if *is_replace && stack.pop(1) != 0 {
3013                    return Some(gss.popn(1).push(*target));
3014                }
3015                stack.push(*target);
3016                Some(stack.into_gss())
3017            } else {
3018                Some(if *is_replace {
3019                    gss.popn(1).push(*target)
3020                } else {
3021                    gss.push(*target)
3022                })
3023            }
3024        }
3025        Action::ReplaceShifts(targets) => {
3026            let stack = gss.try_virtual_stack()?;
3027            stack.into_gss_after_popping_and_pushing_unique_single_branches(
3028                1,
3029                targets.iter(),
3030            )
3031        }
3032        Action::StackShifts(shifts) => {
3033            if let [shift] = shifts.as_slice() {
3034                let mut branch = gss.try_virtual_stack()?;
3035                if branch.pop(shift.pop as usize) != 0 {
3036                    return None;
3037                }
3038                for &target in &shift.pushes {
3039                    branch.push(target);
3040                }
3041                return Some(branch.into_gss());
3042            }
3043            if let Some(stack) = gss.try_virtual_stack()
3044                && let Some(first) = shifts.first()
3045                && !first.pushes.is_empty()
3046                && shifts
3047                    .iter()
3048                    .all(|shift| shift.pop == first.pop && !shift.pushes.is_empty())
3049                && let Some(shifted) = stack.into_gss_after_popping_and_pushing_branches(
3050                    first.pop as usize,
3051                    shifts.iter().map(|shift| shift.pushes.as_slice()),
3052                )
3053            {
3054                return Some(shifted);
3055            }
3056            if let Some(shifted) = gss.apply_stack_effects_to_single_concrete_path(
3057                shifts
3058                    .iter()
3059                    .map(|shift| (shift.pop as usize, shift.pushes.as_slice())),
3060                SINGLE_CONCRETE_STACK_EFFECT_MAX_DEPTH,
3061            ) {
3062                return Some(shifted);
3063            }
3064            if let Some(first) = shifts.first()
3065                && shifts
3066                    .iter()
3067                    .all(|shift| shift.pop == first.pop && shift.pushes.len() == 1)
3068                && let Some(shifted) = gss.apply_shared_pop_push_single_branches(
3069                    first.pop as usize,
3070                    shifts.iter().map(|shift| &shift.pushes[0]),
3071                )
3072            {
3073                return Some(shifted);
3074            }
3075            if let Some(first) = shifts.first()
3076                && !first.pushes.is_empty()
3077                && shifts
3078                    .iter()
3079                    .all(|shift| shift.pop == first.pop && !shift.pushes.is_empty())
3080                && let Some(shifted) = gss.apply_shared_pop_push_branches(
3081                    first.pop as usize,
3082                    shifts.iter().map(|shift| shift.pushes.as_slice()),
3083                )
3084            {
3085                return Some(shifted);
3086            }
3087
3088            let stack = gss.try_virtual_stack()?;
3089            let mut shifted = ParserGSS::empty();
3090            for shift in shifts {
3091                let mut branch = stack.clone();
3092                if branch.pop(shift.pop as usize) != 0 {
3093                    return None;
3094                }
3095                for &target in &shift.pushes {
3096                    branch.push(target);
3097                }
3098                let branch = branch.into_gss();
3099                shifted = if shifted.is_empty() {
3100                    branch
3101                } else {
3102                    shifted.merge(&branch)
3103                };
3104            }
3105            Some(shifted)
3106        }
3107        Action::GuardedStackShifts(shifts) => {
3108            apply_guarded_stack_shifts_fast(gss, shifts, table.guarded_shift_index(state, terminal))
3109        }
3110        Action::Reduce(..) => apply_single_path_reduce_chain_fast(table, gss, terminal),
3111        _ => None,
3112    }
3113}
3114
3115fn try_apply_action_to_carried_virtual_stack(
3116    stack: &mut crate::ds::leveled_gss::VirtualStack<u32, TerminalsDisallowed>,
3117    action: &Action,
3118) -> bool {
3119    match action {
3120        Action::Skip => true,
3121        Action::Shift(target, is_replace) => {
3122            if *is_replace {
3123                stack.replace_top(*target)
3124            } else {
3125                stack.push(*target);
3126                true
3127            }
3128        }
3129        Action::StackShifts(shifts) => {
3130            let [shift] = shifts.as_slice() else {
3131                return false;
3132            };
3133            let mut candidate = stack.clone();
3134            if candidate.pop(shift.pop as usize) != 0 {
3135                return false;
3136            }
3137            for &target in &shift.pushes {
3138                candidate.push(target);
3139            }
3140            if candidate.top().is_none() {
3141                // The next parser/top-row decision requires a concrete top
3142                // state. If the visible prefix has been exhausted, continuing
3143                // to carry this virtual stack would make the stale materialized
3144                // GSS an invalid proxy for the current parser frontier.
3145                return false;
3146            }
3147            *stack = candidate;
3148            true
3149        }
3150        _ => false,
3151    }
3152}
3153
3154/// Preserve a uniform reduction result's shared bottom-of-stack prefix.
3155/// Rebuilding the entire concrete-stack trie repeats work for each retained
3156/// value, although every output has the same accumulator and usually differs
3157/// only in its final one or two states. Mixed accumulators retain the general
3158/// builder: exclusions must never be detached from their particular paths.
3159fn materialize_reduce_chain_outputs(
3160    mut outputs: Vec<(Vec<u32>, TerminalsDisallowed)>,
3161) -> ParserGSS {
3162    if outputs.len() == 1 {
3163        let (stack, accumulator) = outputs.pop().unwrap();
3164        return ParserGSS::from_single_stack(stack, accumulator);
3165    }
3166    let Some((first, accumulator)) = outputs.first() else {
3167        return ParserGSS::empty();
3168    };
3169    if outputs.iter().any(|(_, other)| other != accumulator) {
3170        return ParserGSS::from_stacks(&outputs);
3171    }
3172    let mut shared = first.len();
3173    for (stack, _) in outputs.iter().skip(1) {
3174        shared = first[..shared].iter().zip(stack).take_while(|(a, b)| a == b).count();
3175    }
3176    if shared == 0 {
3177        return ParserGSS::from_stacks(&outputs);
3178    }
3179
3180    let base = ParserGSS::from_single_stack(first[..shared].to_vec(), accumulator.clone());
3181    let accepts_prefix = outputs.iter().any(|(stack, _)| stack.len() == shared);
3182    if outputs.iter().all(|(stack, _)| stack.len() == shared) {
3183        return base;
3184    }
3185    let branches = base.apply_shared_pop_push_branches(
3186        0,
3187        outputs.iter().filter(|(stack, _)| stack.len() > shared)
3188            .map(|(stack, _)| &stack[shared..]),
3189    ).expect("a nonempty single-stack prefix admits every nonempty suffix");
3190    if accepts_prefix { base.merge(&branches) } else { branches }
3191}
3192
3193fn apply_single_path_reduce_chain_fast(
3194    table: &GLRTable,
3195    gss: &ParserGSS,
3196    terminal: u32,
3197) -> Option<ParserGSS> {
3198    let (mut stack, acc) =
3199        gss.try_single_stack_bounded(SINGLE_CONCRETE_STACK_EFFECT_MAX_DEPTH)?;
3200
3201    loop {
3202        let state = *stack.last()?;
3203        match table.action(state, terminal)? {
3204            Action::Skip => {
3205                return Some(ParserGSS::from_single_stack(stack, acc));
3206            }
3207            Action::Reduce(nt, len) => {
3208                let rhs_len = *len as usize;
3209                if rhs_len >= stack.len() {
3210                    return None;
3211                }
3212                stack.truncate(stack.len() - rhs_len);
3213                let goto_from = *stack.last()?;
3214                let (target, is_replace) = table.goto_target(goto_from, *nt)?;
3215                if is_replace {
3216                    *stack.last_mut()? = target;
3217                } else {
3218                    stack.push(target);
3219                }
3220            }
3221            Action::Shift(target, is_replace) => {
3222                if *is_replace {
3223                    *stack.last_mut()? = *target;
3224                } else {
3225                    stack.push(*target);
3226                }
3227                return Some(ParserGSS::from_single_stack(stack, acc));
3228            }
3229            Action::StackShifts(shifts) => {
3230                return ParserGSS::from_single_stack(stack, acc)
3231                    .apply_stack_effects_to_single_concrete_path(
3232                        shifts
3233                            .iter()
3234                            .map(|shift| (shift.pop as usize, shift.pushes.as_slice())),
3235                        SINGLE_CONCRETE_STACK_EFFECT_MAX_DEPTH,
3236                    );
3237            }
3238            Action::Split {
3239                shift,
3240                reduces,
3241                accept: false,
3242            } => {
3243                let mut out: Vec<(Vec<u32>, TerminalsDisallowed)> = Vec::new();
3244
3245                if let Some((target, is_replace)) = shift {
3246                    let mut branch = stack.clone();
3247                    if *is_replace {
3248                        *branch.last_mut()? = *target;
3249                    } else {
3250                        branch.push(*target);
3251                    }
3252                    out.push((branch, acc.clone()));
3253                }
3254
3255                for &(nt, len) in reduces {
3256                    let mut branch = stack.clone();
3257                    let rhs_len = len as usize;
3258                    if rhs_len >= branch.len() {
3259                        return None;
3260                    }
3261                    branch.truncate(branch.len() - rhs_len);
3262                    let goto_from = *branch.last()?;
3263                    let (target, is_replace) = table.goto_target(goto_from, nt)?;
3264                    if is_replace {
3265                        *branch.last_mut()? = target;
3266                    } else {
3267                        branch.push(target);
3268                    }
3269
3270                    let follow_state = *branch.last()?;
3271                    match table.action(follow_state, terminal)? {
3272                        Action::Skip => {
3273                            out.push((branch, acc.clone()));
3274                        }
3275                        Action::Shift(target, is_replace) => {
3276                            if *is_replace {
3277                                *branch.last_mut()? = *target;
3278                            } else {
3279                                branch.push(*target);
3280                            }
3281                            out.push((branch, acc.clone()));
3282                        }
3283                        Action::StackShifts(shifts) => {
3284                            let shifted = ParserGSS::from_single_stack(branch, acc.clone())
3285                                .apply_stack_effects_to_single_concrete_path(
3286                                    shifts
3287                                        .iter()
3288                                        .map(|shift| (shift.pop as usize, shift.pushes.as_slice())),
3289                                    SINGLE_CONCRETE_STACK_EFFECT_MAX_DEPTH,
3290                                )?;
3291                            let shifted_stacks = shifted
3292                                .to_stacks(shifts.len())
3293                                .expect("stack-shift result exceeded its effect count");
3294                            out.extend(shifted_stacks);
3295                        }
3296                        _ => return None,
3297                    }
3298                }
3299
3300                return (!out.is_empty()).then(|| materialize_reduce_chain_outputs(out));
3301            }
3302            _ => return None,
3303        }
3304    }
3305}
3306
3307fn advance_terminal_match(
3308    constraint: &Constraint,
3309    gss_at_offset: &ParserGSS,
3310    terminal: u32,
3311    exec_result: &TokenizerExecResult,
3312    advance_result_cache: &mut AdvanceResultCache,
3313    terminal_result_cache: &mut FxHashMap<u32, ParserGSS>,
3314) -> Option<ParserGSS> {
3315    if let Some(cached) = terminal_result_cache.get(&terminal) {
3316        return (!cached.is_empty()).then(|| cached.clone());
3317    }
3318
3319    let advance_cache_key = (gss_at_offset.ptr_key(), terminal);
3320    let advanced = if let Some((_, cached)) = advance_result_cache.get(&advance_cache_key) {
3321        cached.clone()
3322    } else {
3323        let advanced = advance_parser_stacks(constraint, gss_at_offset, terminal);
3324        advance_result_cache.insert(advance_cache_key, (gss_at_offset.clone(), advanced.clone()));
3325        advanced
3326    };
3327
3328    let advanced = apply_future_terminal_disallow(constraint, exec_result, terminal, advanced);
3329    terminal_result_cache.insert(terminal, advanced.clone());
3330    (!advanced.is_empty()).then_some(advanced)
3331}
3332
3333/// Fast path for the common case: exactly 1 tokenizer state, the tokenizer
3334/// produces exactly 1 non-ignored terminal match that consumes all bytes,
3335/// and no pending end-state needs to be queued. This avoids:
3336/// - FxHashMap allocations (InitialCommitScan, seen_matches, caches)
3337/// - Processing queue allocation
3338/// - Prune iteration (when terminals_disallowed is empty)
3339///
3340/// Returns `Some(Ok(()))` on success, `Some(Err(...))` on rejection,
3341/// or `None` to fall through to the general path.
3342///
3343/// `exec_result` is the pre-computed tokenizer output for the single state.
3344#[inline]
3345fn commit_bytes_fast_path(
3346    constraint: &Constraint,
3347    state: &mut ParserStateMap,
3348    bytes: &[u8],
3349    tokenizer_state: u32,
3350    exec_result: &TokenizerExecResult,
3351) -> Option<Result<(), String>> {
3352    commit_bytes_fast_path_observed(constraint, state, bytes, tokenizer_state, exec_result, &mut NoMarkers)
3353}
3354
3355fn commit_bytes_fast_path_observed<O: CommitObserver>(
3356    constraint: &Constraint,
3357    state: &mut ParserStateMap,
3358    bytes: &[u8],
3359    tokenizer_state: u32,
3360    exec_result: &TokenizerExecResult,
3361    observer: &mut O,
3362) -> Option<Result<(), String>> {
3363    let marker_checkpoint = observer.checkpoint();
3364    let result = (|| {
3365    let gss = state.values().next().unwrap();
3366    let ignore_terminal = constraint.ignore_terminal;
3367    let has_linker_controls = constraint.parser_has_controls()
3368        || constraint.uses_compact_segmented_parser_runtime();
3369
3370    // Find exactly 1 non-ignored, actionable terminal match consuming all bytes
3371    let mut sole_terminal: Option<u32> = None;
3372    for matched in &exec_result.matches {
3373        if matched.width != bytes.len() {
3374            return None;
3375        }
3376        if is_ignored_terminal(ignore_terminal, matched.id) {
3377            return None;
3378        }
3379        if !parser_may_advance_on(constraint, gss, matched.id) {
3380            continue;
3381        }
3382        if sole_terminal.is_some() {
3383            return None;
3384        }
3385        sole_terminal = Some(matched.id);
3386    }
3387    let terminal = sole_terminal?;
3388
3389    let no_end_state = exec_result.end_state.is_empty();
3390    let accs_empty = gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty());
3391    // The stale-exclusion bug that originally required the epsilon guard only
3392    // exists when exclusions must be transported from one NFA configuration
3393    // to another.  With empty accumulators this routine is already fully
3394    // state-set aware: it advances the sole full-width terminal and preserves
3395    // every viable lexer continuation independently.
3396    if constraint.tokenizer_has_epsilon_transitions && !accs_empty {
3397        return None;
3398    }
3399    let all_accs_empty = no_end_state && accs_empty;
3400
3401    // Ultra-fast path: single Interface, empty accs, no end_state, pure shift.
3402    // Inlines the entire advance + prune + fuse to avoid all function call overhead.
3403    if !has_linker_controls && all_accs_empty && !template_advance_selected(constraint) {
3404        let top_state = gss.single_exclusive_top_value();
3405        if let Some(top_state) = top_state
3406            && let Some(action) = constraint.table.action(top_state, terminal) {
3407                if let Some(gss) = state.values_mut().next()
3408                    && try_apply_single_top_action_in_place(gss, action)
3409                {
3410                    return Some(Ok(()));
3411                }
3412                let gss = state.values().next().unwrap();
3413                if let Some(shifted) =
3414                    apply_single_top_action_fast(constraint, gss, top_state, terminal, action)
3415                {
3416                    state.clear();
3417                    state.insert(constraint.runtime_commit_initial_state(), shifted);
3418                    return Some(Ok(()));
3419                }
3420            }
3421    }
3422
3423    // Take ownership of the GSS for the standard fast path.
3424    // This allows advance_stacks_owned to avoid cloning the inner Arc.
3425    let (_, gss_owned) = state.pop_first().unwrap();
3426
3427    // Standard fast path: skip prune when accumulators are empty.
3428    let pruned_gss = if accs_empty {
3429        gss_owned
3430    } else {
3431        let pruned = prune_single_initial_state_for_exec(
3432            constraint,
3433            gss_owned,
3434            tokenizer_state,
3435            exec_result,
3436            bytes,
3437        );
3438
3439        if pruned.is_empty() {
3440            return Some(Err(
3441                "commit rejected: no valid parser states remain".to_string(),
3442            ));
3443        }
3444        pruned
3445    };
3446
3447    let end_states_to_keep: TokenizerStateSet = exec_result
3448        .end_state
3449        .iter()
3450        .copied()
3451        .filter(|&end_state| end_state_may_advance(constraint, &pruned_gss, end_state))
3452        .collect();
3453
3454    // The terminal and tokenizer end-state continuations are independent.
3455    // Preserve either branch if it produces viable parser state.
3456    let advanced = if !has_linker_controls
3457        && !template_advance_selected(constraint)
3458        && let Some(top_state) = pruned_gss.single_exclusive_top_value()
3459        && let Some(action) = constraint.table.action(top_state, terminal)
3460        && let Some(advanced) = apply_single_top_action_fast(
3461            constraint,
3462            &pruned_gss,
3463            top_state,
3464            terminal,
3465            action,
3466        )
3467    {
3468        advanced
3469    } else {
3470        advance_parser_stacks_owned(constraint, pruned_gss.clone(), terminal)
3471    };
3472    let mut produced_state = false;
3473    if !advanced.is_empty() {
3474        let advanced =
3475            apply_future_terminal_disallow(constraint, exec_result, terminal, advanced);
3476        if !advanced.is_empty() {
3477            let fused = advanced.fuse(Some(1));
3478            if !fused.is_empty() {
3479                state.insert(constraint.runtime_commit_initial_state(), fused);
3480                produced_state = true;
3481            }
3482        }
3483    }
3484
3485    if !end_states_to_keep.is_empty() {
3486        let fused = pruned_gss.fuse(Some(1));
3487        if !fused.is_empty() {
3488            for &end_state in &end_states_to_keep {
3489                state.merge_insert(end_state, fused.clone());
3490            }
3491            produced_state = true;
3492        }
3493    }
3494
3495    if !produced_state {
3496        return Some(Err(
3497            "commit rejected: no valid parser states remain".to_string(),
3498        ));
3499    }
3500    Some(Ok(()))
3501
3502    })();
3503    if result.is_none() { observer.rewind(marker_checkpoint); }
3504    result
3505}
3506
3507#[inline]
3508fn commit_bytes_full_width_fast_path(
3509    constraint: &Constraint,
3510    state: &mut ParserStateMap,
3511    bytes: &[u8],
3512) -> Option<Result<(), String>> {
3513    commit_bytes_full_width_fast_path_observed(constraint, state, bytes, &mut NoMarkers)
3514}
3515
3516fn commit_bytes_full_width_fast_path_observed<O: CommitObserver>(
3517    constraint: &Constraint,
3518    state: &mut ParserStateMap,
3519    bytes: &[u8],
3520    observer: &mut O,
3521) -> Option<Result<(), String>> {
3522    let marker_checkpoint = observer.checkpoint();
3523    let result = (|| {
3524    let has_linker_controls = constraint.parser_has_controls()
3525        || constraint.uses_compact_segmented_parser_runtime();
3526    if constraint.tokenizer_has_epsilon_transitions
3527        && state_has_nonempty_accumulators(state)
3528    {
3529        return None;
3530    }
3531    if state.len() > 2 {
3532        return None;
3533    }
3534    if state.len() > 1 && bytes.len() > 4 && state_has_nonempty_accumulators(state) {
3535        return None;
3536    }
3537
3538    let mut output = ParserStatesByTokenizer::default();
3539    for (&tokenizer_state, gss) in state.iter() {
3540        let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
3541        let actionable_terminals = (!has_linker_controls)
3542            .then(|| ActionableTerminals::from_gss(constraint, gss))
3543            .flatten();
3544        let mut terminal = None;
3545
3546        for matched in &exec_result.matches {
3547            if matched.width != bytes.len()
3548                || is_ignored_terminal(constraint.ignore_terminal, matched.id)
3549            {
3550                return None;
3551            }
3552            if !is_actionable_terminal(actionable_terminals.as_ref(), constraint, matched.id) {
3553                continue;
3554            }
3555            if terminal.is_some_and(|existing| existing != matched.id) {
3556                return None;
3557            }
3558            terminal = Some(matched.id);
3559        }
3560
3561        let pruned_gss = if gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()) {
3562            gss.clone()
3563        } else {
3564            let pruned = prune_single_initial_state_for_exec(
3565                constraint,
3566                gss.clone(),
3567                tokenizer_state,
3568                &exec_result,
3569                bytes,
3570            );
3571            if pruned.is_empty() {
3572                continue;
3573            }
3574            pruned
3575        };
3576
3577        if let Some(terminal) = terminal {
3578            let advanced = if !has_linker_controls
3579                && !template_advance_selected(constraint)
3580                && let Some(top_state) = pruned_gss.single_exclusive_top_value()
3581                && let Some(action) = constraint.table.action(top_state, terminal)
3582                && let Some(advanced) =
3583                    apply_single_top_action_fast(
3584                        constraint,
3585                        &pruned_gss,
3586                        top_state,
3587                        terminal,
3588                        action,
3589                    )
3590            {
3591                advanced
3592            } else {
3593                advance_parser_stacks_if_possible(constraint, &pruned_gss, terminal)?
3594            };
3595            if advanced.is_empty() {
3596                continue;
3597            }
3598            let advanced = apply_future_terminal_disallow(
3599                constraint,
3600                &exec_result,
3601                terminal,
3602                advanced,
3603            );
3604            if !advanced.is_empty() {
3605                merge_parser_state(
3606                    &mut output,
3607                    constraint.runtime_commit_initial_state(),
3608                    advanced,
3609                );
3610            }
3611        }
3612
3613        let admitted_end_state_terminals = batched_end_state_admitted_terminals(
3614            constraint,
3615            &pruned_gss,
3616            &exec_result.end_state,
3617        );
3618        for &end_state in &exec_result.end_state {
3619            if end_state_may_advance_with_batch(
3620                constraint,
3621                &pruned_gss,
3622                end_state,
3623                admitted_end_state_terminals.as_ref(),
3624            ) {
3625                merge_parser_state(&mut output, end_state, pruned_gss.clone());
3626            }
3627        }
3628    }
3629
3630    let new_state = finalize_pending_state(&mut output);
3631    if new_state.is_empty() {
3632        return Some(Err(
3633            "commit rejected: no valid parser states remain".to_string(),
3634        ));
3635    }
3636    *state = new_state;
3637    Some(Ok(()))
3638
3639    })();
3640    if result.is_none() { observer.rewind(marker_checkpoint); }
3641    result
3642}
3643
3644fn merge_small_parser_state(
3645    states: &mut SmallVec<[(u32, ParserGSS); INLINE_PARSER_STATE_CAPACITY]>,
3646    tokenizer_state: u32,
3647    gss: ParserGSS,
3648) {
3649    for (existing_state, existing_gss) in states.iter_mut() {
3650        if *existing_state == tokenizer_state {
3651            *existing_gss = existing_gss.merge(&gss);
3652            return;
3653        }
3654    }
3655    states.push((tokenizer_state, gss));
3656}
3657
3658fn merge_small_language_parser_state(
3659    runtime: &mut TemplateAdvanceRuntime,
3660    states: &mut SmallLanguageParserStates,
3661    tokenizer_state: u32,
3662    language: u32,
3663    accumulator: TerminalsDisallowed,
3664) -> bool {
3665    if language == 0 {
3666        return true;
3667    }
3668    for existing in states.iter_mut() {
3669        if existing.tokenizer_state == tokenizer_state && existing.accumulator == accumulator {
3670            existing.language = runtime.union_languages(existing.language, language);
3671            return !runtime.is_exhausted();
3672        }
3673    }
3674    if states.len() == SMALL_LANGUAGE_QUEUE_CAPACITY {
3675        return false;
3676    }
3677    states.push(SmallLanguageParserState {
3678        tokenizer_state,
3679        language,
3680        accumulator,
3681    });
3682    true
3683}
3684
3685fn actionable_terminals_from_language(
3686    runtime: &TemplateAdvanceRuntime,
3687    language: u32,
3688) -> Option<ActionableTerminals> {
3689    let states = runtime.language_top_states(language);
3690    match states.as_slice() {
3691        [] => None,
3692        [state] => Some(ActionableTerminals::SingleState(*state)),
3693        _ => Some(ActionableTerminals::ManyStates(states)),
3694    }
3695}
3696
3697fn prune_uniform_accumulator_for_parts(
3698    constraint: &Constraint,
3699    actionable_terminals: Option<&ActionableTerminals>,
3700    accumulator: &TerminalsDisallowed,
3701    tokenizer_state: u32,
3702    end_states: &[u32],
3703    matches: &[TokenizerMatch],
3704) -> Option<TerminalsDisallowed> {
3705    if accumulator.is_empty() {
3706        return Some(TerminalsDisallowed::new());
3707    }
3708
3709    let accepted_terminals = matches
3710        .iter()
3711        .filter(|matched| !is_ignored_terminal(constraint.ignore_terminal, matched.id))
3712        .filter(|matched| {
3713            is_actionable_terminal(actionable_terminals, constraint, matched.id)
3714        })
3715        .map(|matched| matched.id)
3716        .collect::<SmallVec<[u32; INLINE_PARSER_STATE_CAPACITY]>>();
3717
3718    if let Some(disallowed) = accumulator.get(&tokenizer_state)
3719        && !accepted_terminals.is_empty()
3720        && accepted_terminals
3721            .iter()
3722            .all(|terminal| disallowed.contains(terminal))
3723    {
3724        return None;
3725    }
3726
3727    if let Some(remapped) =
3728        accumulator.try_remap_single_state_inline(tokenizer_state, end_states)
3729    {
3730        return Some(remapped);
3731    }
3732
3733    let terminals = accumulator
3734        .get(&tokenizer_state)
3735        .map(|values| values.iter().copied().collect::<Vec<_>>())
3736        .unwrap_or_default();
3737    if terminals.is_empty() || end_states.is_empty() {
3738        return Some(TerminalsDisallowed::new());
3739    }
3740    let mut remapped = BTreeMap::<u32, BTreeSet<u32>>::new();
3741    for &end_state in end_states {
3742        remapped
3743            .entry(end_state)
3744            .or_default()
3745            .extend(terminals.iter().copied());
3746    }
3747    Some(TerminalsDisallowed::from_map(remapped))
3748}
3749
3750fn apply_future_terminal_disallow_to_accumulator(
3751    constraint: &Constraint,
3752    end_states: &[u32],
3753    terminal: u32,
3754    mut accumulator: TerminalsDisallowed,
3755) -> TerminalsDisallowed {
3756    for &end_state in end_states {
3757        if constraint
3758            .tokenizer
3759            .possible_future_terminals(end_state)
3760            .contains(terminal as usize)
3761        {
3762            accumulator = accumulator.with_insert(end_state, terminal);
3763        }
3764    }
3765    accumulator
3766}
3767
3768fn language_end_state_may_advance(
3769    constraint: &Constraint,
3770    runtime: &mut TemplateAdvanceRuntime,
3771    language: u32,
3772    end_state: u32,
3773) -> Option<bool> {
3774    if end_state == constraint.runtime_commit_initial_state() {
3775        return Some(true);
3776    }
3777    if runtime_future_contains_ignore(constraint, constraint.tokenizer.possible_future_terminals(end_state)) {
3778        return Some(true);
3779    }
3780    for terminal in constraint
3781        .tokenizer
3782        .possible_future_terminals(end_state)
3783        .iter_ones()
3784    {
3785        let terminal = u32::try_from(terminal).ok()?;
3786        let advanced = runtime.advance_language(constraint, terminal, language)?;
3787        if advanced != 0 {
3788            return Some(true);
3789        }
3790    }
3791    Some(false)
3792}
3793
3794fn language_queue_top_value_count_at_most(
3795    state: &ParserStateMap,
3796    limit: usize,
3797) -> usize {
3798    let mut count = 0usize;
3799    for (_, gss) in state.iter() {
3800        count = count.saturating_add(gss.top_value_count()).min(limit);
3801        if count == limit {
3802            break;
3803        }
3804    }
3805    count
3806}
3807
3808fn language_queue_path_count_at_most(state: &ParserStateMap, limit: usize) -> usize {
3809    let mut count = 0usize;
3810    for (_, gss) in state.iter() {
3811        count = count.saturating_add(gss.path_count_at_most(limit)).min(limit);
3812        if count == limit {
3813            break;
3814        }
3815    }
3816    count
3817}
3818
3819fn language_queue_node_count_at_most(state: &ParserStateMap, limit: usize) -> usize {
3820    let mut count = 0usize;
3821    for (_, gss) in state.iter() {
3822        count = count.saturating_add(gss.node_count_at_most(limit)).min(limit);
3823        if count == limit {
3824            break;
3825        }
3826    }
3827    count
3828}
3829
3830fn language_small_queue_enabled() -> bool {
3831    static ENABLED: OnceLock<bool> = OnceLock::new();
3832    *ENABLED.get_or_init(|| {
3833        let flag = |name: &str| {
3834            crate::env::var(name).ok().map(|value| {
3835                let normalized = value.trim().to_ascii_lowercase();
3836                !matches!(normalized.as_str(), "" | "0" | "false" | "no" | "off")
3837            })
3838        };
3839        if flag("GLRMASK_DISABLE_LANGUAGE_SMALL_QUEUE") == Some(true) {
3840            return false;
3841        }
3842        flag("GLRMASK_ENABLE_LANGUAGE_SMALL_QUEUE").unwrap_or(true)
3843    })
3844}
3845
3846fn language_queue_input_is_bounded(state: &ParserStateMap) -> bool {
3847    state
3848        .iter()
3849        .all(|(_, gss)| gss.max_depth() <= LANGUAGE_QUEUE_MAX_INPUT_STACK_DEPTH)
3850}
3851
3852/// Return whether one model token contains multiple parser-actionable,
3853/// non-ignored terminal completion boundaries at different byte offsets.
3854///
3855/// This is the structural case where the ordinary byte queue must materialize
3856/// and carry parser states at more than one offset inside the same token. The
3857/// language queue evaluates all such offset alternatives before reconstructing
3858/// a GSS once at token completion. Multiple terminals ending at the same byte
3859/// offset do not qualify: the ordinary queue already merges those without an
3860/// offset frontier split.
3861fn has_multiple_actionable_terminal_boundaries(
3862    constraint: &Constraint,
3863    state: &ParserStateMap,
3864    bytes: &[u8],
3865    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
3866) -> bool {
3867    for (&tokenizer_state, gss) in state.iter() {
3868        if !execute_tokenizer_reusable(
3869            constraint,
3870            bytes,
3871            tokenizer_state,
3872            tokenizer_scratch,
3873        ) {
3874            return false;
3875        }
3876        let actionable = ActionableTerminals::from_gss(constraint, gss);
3877        let matches = collect_unique_actionable_matches(
3878            constraint,
3879            actionable.as_ref(),
3880            constraint.ignore_terminal,
3881            &tokenizer_scratch.matches,
3882            None,
3883        );
3884        let mut widths = SmallVec::<[usize; 4]>::new();
3885        for matched in matches {
3886            if matched.ignored || widths.contains(&matched.width) {
3887                continue;
3888            }
3889            widths.push(matched.width);
3890            if widths.len() >= 2 {
3891                return true;
3892            }
3893        }
3894    }
3895    false
3896}
3897
3898#[derive(Default)]
3899struct LanguageCommitSimulationProfile {
3900    canonicalize_ns: u64,
3901    evaluate_ns: u64,
3902    continuation_reconstruct_ns: u64,
3903    continuation_check_ns: u64,
3904}
3905
3906#[inline]
3907fn simulate_language_commit(
3908    constraint: &Constraint,
3909    state: &ParserStateMap,
3910    bytes: &[u8],
3911    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
3912    queue_scratch: &mut SmallCommitQueueScratch,
3913    template_runtime: &mut TemplateAdvanceRuntime,
3914    profile: Option<&mut LanguageCommitSimulationProfile>,
3915) -> Option<Result<SmallLanguageParserStates, String>> {
3916    simulate_language_commit_observed(constraint, state, bytes, tokenizer_scratch, queue_scratch, template_runtime, profile, &mut NoMarkers)
3917}
3918
3919fn simulate_language_commit_observed<O: CommitObserver>(
3920    constraint: &Constraint,
3921    state: &ParserStateMap,
3922    bytes: &[u8],
3923    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
3924    queue_scratch: &mut SmallCommitQueueScratch,
3925    template_runtime: &mut TemplateAdvanceRuntime,
3926    mut profile: Option<&mut LanguageCommitSimulationProfile>,
3927    observer: &mut O,
3928) -> Option<Result<SmallLanguageParserStates, String>> {
3929    let marker_checkpoint = observer.checkpoint();
3930    let result = (|| {
3931    if bytes.is_empty() || bytes.len() > 8 || state.is_empty() || state.len() > 8 {
3932        return None;
3933    }
3934
3935    queue_scratch.clear();
3936    for (&tokenizer_state, gss) in state.iter() {
3937        let started = profile.is_some().then(std::time::Instant::now);
3938        let components = template_runtime.language_components_from_gss(gss)?;
3939        if let (Some(profile), Some(started)) = (profile.as_deref_mut(), started) {
3940            profile.canonicalize_ns += started.elapsed().as_nanos() as u64;
3941        }
3942        if template_runtime.is_exhausted() {
3943            return None;
3944        }
3945        for (language, accumulator) in components {
3946            if !merge_small_language_parser_state(
3947                template_runtime,
3948                &mut queue_scratch.language_processing[0],
3949                tokenizer_state,
3950                language,
3951                accumulator,
3952            ) {
3953                return None;
3954            }
3955        }
3956    }
3957
3958    let initial_tokenizer_state = constraint.runtime_commit_initial_state();
3959    let mut offset = 0usize;
3960    while offset <= bytes.len() {
3961        if queue_scratch.language_processing[offset].is_empty() {
3962            offset += 1;
3963            continue;
3964        }
3965
3966        let states_to_process =
3967            std::mem::take(&mut queue_scratch.language_processing[offset]);
3968        for mut entry in states_to_process {
3969            if !execute_tokenizer_reusable(
3970                constraint,
3971                &bytes[offset..],
3972                entry.tokenizer_state,
3973                tokenizer_scratch,
3974            ) {
3975                return None;
3976            }
3977
3978            let actionable_terminals =
3979                actionable_terminals_from_language(template_runtime, entry.language);
3980            if offset == 0 && !entry.accumulator.is_empty() {
3981                entry.accumulator = prune_uniform_accumulator_for_parts(
3982                    constraint,
3983                    actionable_terminals.as_ref(),
3984                    &entry.accumulator,
3985                    entry.tokenizer_state,
3986                    &tokenizer_scratch.states,
3987                    &tokenizer_scratch.matches,
3988                )?;
3989            }
3990
3991            let normalized_matches = collect_unique_actionable_matches(
3992                constraint,
3993                actionable_terminals.as_ref(),
3994                constraint.ignore_terminal,
3995                &tokenizer_scratch.matches,
3996                None,
3997            );
3998            let mut emitted = SmallVec::<[(usize, u32, TerminalsDisallowed); 4]>::new();
3999
4000            for matched in normalized_matches {
4001                let new_offset = offset + matched.width;
4002                if new_offset > bytes.len() {
4003                    return None;
4004                }
4005
4006                let (advanced_language, advanced_accumulator) = if matched.ignored {
4007                    (entry.language, entry.accumulator.clone())
4008                } else {
4009                    let started = profile.is_some().then(std::time::Instant::now);
4010                    let advanced = template_runtime.advance_language(
4011                        constraint,
4012                        matched.terminal_id,
4013                        entry.language,
4014                    )?;
4015                    if let (Some(profile), Some(started)) = (profile.as_deref_mut(), started) {
4016                        profile.evaluate_ns += started.elapsed().as_nanos() as u64;
4017                    }
4018                    if advanced == 0 {
4019                        continue;
4020                    }
4021                    (
4022                        advanced,
4023                        apply_future_terminal_disallow_to_accumulator(
4024                            constraint,
4025                            &tokenizer_scratch.states,
4026                            matched.terminal_id,
4027                            entry.accumulator.clone(),
4028                        ),
4029                    )
4030                };
4031
4032                if emitted.iter().any(|(emitted_offset, language, accumulator)| {
4033                    *emitted_offset == new_offset
4034                        && *language == advanced_language
4035                        && accumulator == &advanced_accumulator
4036                }) {
4037                    continue;
4038                }
4039                observer.language(constraint, template_runtime, advanced_language, &advanced_accumulator, new_offset);
4040                emitted.push((
4041                    new_offset,
4042                    advanced_language,
4043                    advanced_accumulator.clone(),
4044                ));
4045
4046                let destination = if new_offset == bytes.len() {
4047                    &mut queue_scratch.language_pending
4048                } else {
4049                    &mut queue_scratch.language_processing[new_offset]
4050                };
4051                if !merge_small_language_parser_state(
4052                    template_runtime,
4053                    destination,
4054                    initial_tokenizer_state,
4055                    advanced_language,
4056                    advanced_accumulator,
4057                ) {
4058                    return None;
4059                }
4060            }
4061
4062            if !tokenizer_scratch.states.is_empty() {
4063                let mut fallback_gss = None;
4064                for &end_state in &tokenizer_scratch.states {
4065                    let check_started = profile.is_some().then(std::time::Instant::now);
4066                    let language_viable = language_end_state_may_advance(
4067                        constraint,
4068                        template_runtime,
4069                        entry.language,
4070                        end_state,
4071                    );
4072                    if template_runtime.is_exhausted() {
4073                        return None;
4074                    }
4075                    let viable = match language_viable {
4076                        Some(viable) => viable,
4077                        None => {
4078                            let reconstruct_started =
4079                                profile.is_some().then(std::time::Instant::now);
4080                            let gss = fallback_gss.get_or_insert_with(|| {
4081                                template_runtime.gss_from_language(
4082                                    entry.language,
4083                                    entry.accumulator.clone(),
4084                                )
4085                            });
4086                            if let (Some(profile), Some(started)) =
4087                                (profile.as_deref_mut(), reconstruct_started)
4088                            {
4089                                profile.continuation_reconstruct_ns +=
4090                                    started.elapsed().as_nanos() as u64;
4091                            }
4092                            end_state_may_advance(constraint, gss, end_state)
4093                        }
4094                    };
4095                    if let (Some(profile), Some(started)) =
4096                        (profile.as_deref_mut(), check_started)
4097                    {
4098                        profile.continuation_check_ns +=
4099                            started.elapsed().as_nanos() as u64;
4100                    }
4101                    if viable
4102                        && !merge_small_language_parser_state(
4103                            template_runtime,
4104                            &mut queue_scratch.language_pending,
4105                            end_state,
4106                            entry.language,
4107                            entry.accumulator.clone(),
4108                        )
4109                    {
4110                        return None;
4111                    }
4112                }
4113            }
4114        }
4115        offset += 1;
4116    }
4117
4118    if template_runtime.is_exhausted() {
4119        return None;
4120    }
4121    if queue_scratch.language_pending.is_empty() {
4122        return Some(Err(
4123            "commit rejected: no valid parser states remain".to_string(),
4124        ));
4125    }
4126    Some(Ok(std::mem::take(
4127        &mut queue_scratch.language_pending,
4128    )))
4129
4130    })();
4131    if result.is_none() { observer.rewind(marker_checkpoint); }
4132    result
4133}
4134
4135#[inline]
4136fn commit_bytes_language_small_queue_fast_path(
4137    constraint: &Constraint,
4138    state: &mut ParserStateMap,
4139    bytes: &[u8],
4140    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4141    queue_scratch: &mut SmallCommitQueueScratch,
4142    template_runtime: &mut TemplateAdvanceRuntime,
4143    profitability_prechecked: bool,
4144) -> Option<Result<(), String>> {
4145    commit_bytes_language_small_queue_fast_path_observed(constraint, state, bytes, tokenizer_scratch, queue_scratch, template_runtime, profitability_prechecked, &mut NoMarkers)
4146}
4147
4148fn commit_bytes_language_small_queue_fast_path_observed<O: CommitObserver>(
4149    constraint: &Constraint,
4150    state: &mut ParserStateMap,
4151    bytes: &[u8],
4152    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4153    queue_scratch: &mut SmallCommitQueueScratch,
4154    template_runtime: &mut TemplateAdvanceRuntime,
4155    profitability_prechecked: bool,
4156    observer: &mut O,
4157) -> Option<Result<(), String>> {
4158    let marker_checkpoint = observer.checkpoint();
4159    let result = (|| {
4160    if !language_small_queue_enabled() || !(2..=8).contains(&bytes.len()) || state.len() > 2 {
4161        return None;
4162    }
4163
4164    let profile_enabled = crate::env::var_os("GLRMASK_PROFILE_LANGUAGE_SMALL_QUEUE").is_some();
4165    let top_values =
4166        language_queue_top_value_count_at_most(state, LANGUAGE_QUEUE_MIN_TOP_VALUES);
4167    if top_values < LANGUAGE_QUEUE_MIN_TOP_VALUES {
4168        if profile_enabled {
4169            eprintln!(
4170                "[glrmask/profile][language_small_queue_decline] reason=narrow_top_frontier bytes={} top_values={} min_top_values={}",
4171                format_token_bytes(bytes),
4172                top_values,
4173                LANGUAGE_QUEUE_MIN_TOP_VALUES,
4174            );
4175        }
4176        return None;
4177    }
4178
4179    if !profitability_prechecked
4180        && !has_multiple_actionable_terminal_boundaries(
4181            constraint,
4182            state,
4183            bytes,
4184            tokenizer_scratch,
4185        )
4186    {
4187        return None;
4188    }
4189
4190    let parser_paths = language_queue_path_count_at_most(state, LANGUAGE_QUEUE_MIN_PATHS);
4191    if parser_paths < LANGUAGE_QUEUE_MIN_PATHS {
4192        if profile_enabled {
4193            eprintln!(
4194                "[glrmask/profile][language_small_queue_decline] reason=insufficient_stack_ambiguity bytes={} parser_paths={} min_paths={}",
4195                format_token_bytes(bytes),
4196                parser_paths,
4197                LANGUAGE_QUEUE_MIN_PATHS,
4198            );
4199        }
4200        return None;
4201    }
4202    let parser_nodes = language_queue_node_count_at_most(state, LANGUAGE_QUEUE_MIN_NODES);
4203    if parser_nodes < LANGUAGE_QUEUE_MIN_NODES {
4204        if profile_enabled {
4205            eprintln!(
4206                "[glrmask/profile][language_small_queue_decline] reason=insufficient_compact_gss_work bytes={} parser_paths_at_least={} parser_nodes={} min_nodes={}",
4207                format_token_bytes(bytes),
4208                LANGUAGE_QUEUE_MIN_PATHS,
4209                parser_nodes,
4210                LANGUAGE_QUEUE_MIN_NODES,
4211            );
4212        }
4213        return None;
4214    }
4215    if profile_enabled {
4216        eprintln!(
4217            "[glrmask/profile][language_small_queue_dispatch] selected bytes={} state_entries={} parser_paths_at_least={} parser_nodes_at_least={}",
4218            format_token_bytes(bytes),
4219            state.len(),
4220            LANGUAGE_QUEUE_MIN_PATHS,
4221            LANGUAGE_QUEUE_MIN_NODES,
4222        );
4223    }
4224    if !language_queue_input_is_bounded(state) {
4225        if profile_enabled {
4226            eprintln!(
4227                "[glrmask/profile][language_small_queue_decline] reason=input_depth bytes={}",
4228                format_token_bytes(bytes),
4229            );
4230        }
4231        return None;
4232    }
4233
4234    let total_started = profile_enabled.then(std::time::Instant::now);
4235    let mut profile = LanguageCommitSimulationProfile::default();
4236    template_runtime.begin_commit();
4237    let simulation = simulate_language_commit_observed(
4238        constraint,
4239        state,
4240        bytes,
4241        tokenizer_scratch,
4242        queue_scratch,
4243        template_runtime,
4244        profile_enabled.then_some(&mut profile),
4245     observer);
4246    let Some(simulation) = simulation else {
4247        if profile_enabled {
4248            let reason = if template_runtime.is_exhausted() {
4249                "work_budget"
4250            } else {
4251                "simulation_bound_or_missing_template"
4252            };
4253            eprintln!(
4254                "[glrmask/profile][language_small_queue_decline] reason={} bytes={}",
4255                reason,
4256                format_token_bytes(bytes),
4257            );
4258        }
4259        return None;
4260    };
4261    let pending = match simulation {
4262        Ok(pending) => pending,
4263        // The language queue is an accelerator, not the authority for
4264        // rejection. Fall through to the established commit path so an
4265        // optimization bug cannot introduce a false negative.
4266        Err(_) => return None,
4267    };
4268
4269    if template_runtime.is_exhausted() {
4270        if profile_enabled {
4271            eprintln!(
4272                "[glrmask/profile][language_small_queue_decline] reason=work_budget_after_simulation bytes={}",
4273                format_token_bytes(bytes),
4274            );
4275        }
4276        return None;
4277    }
4278    let mut final_reconstruct_ns = 0u64;
4279    let mut new_state = ParserStateMap::default();
4280    for entry in pending {
4281        let started = profile_enabled.then(std::time::Instant::now);
4282        let gss = template_runtime.gss_from_language(entry.language, entry.accumulator);
4283        if let Some(started) = started {
4284            final_reconstruct_ns += started.elapsed().as_nanos() as u64;
4285        }
4286        new_state.merge_insert(entry.tokenizer_state, gss);
4287    }
4288    for parser_state in new_state.values_mut() {
4289        *parser_state = parser_state.fuse(Some(1));
4290    }
4291    new_state.retain(|_, parser_state| !parser_state.is_empty());
4292    if new_state.is_empty() {
4293        return None;
4294    }
4295    if profile_enabled {
4296        let (
4297            template_calls,
4298            template_memo_hits,
4299            template_memo_entries,
4300            template_products_started,
4301            semantic_nodes,
4302            semantic_lower_keys,
4303            semantic_upper_keys,
4304            semantic_union_entries,
4305        ) = template_runtime.work_summary();
4306        eprintln!(
4307            "[glrmask/profile][language_small_queue] bytes={} total_ns={} canonicalize_ns={} evaluate_ns={} continuation_reconstruct_ns={} continuation_check_ns={} final_reconstruct_ns={} template_calls={} template_memo_hits={} template_memo_entries={} template_products_started={} semantic_nodes={} semantic_lower_keys={} semantic_upper_keys={} semantic_union_entries={} final_summaries={:?}",
4308            format_token_bytes(bytes),
4309            total_started.expect("language queue profile start exists").elapsed().as_nanos(),
4310            profile.canonicalize_ns,
4311            profile.evaluate_ns,
4312            profile.continuation_reconstruct_ns,
4313            profile.continuation_check_ns,
4314            final_reconstruct_ns,
4315            template_calls,
4316            template_memo_hits,
4317            template_memo_entries,
4318            template_products_started,
4319            semantic_nodes,
4320            semantic_lower_keys,
4321            semantic_upper_keys,
4322            semantic_union_entries,
4323            new_state.values().map(ParserGSS::summary).collect::<Vec<_>>(),
4324        );
4325    }
4326    *state = new_state;
4327    Some(Ok(()))
4328
4329    })();
4330    if result.is_none() { observer.rewind(marker_checkpoint); }
4331    result
4332}
4333
4334fn try_advance_unique_actionable_top_fast(
4335    constraint: &Constraint,
4336    gss: &ParserGSS,
4337    terminal: u32,
4338) -> Option<ParserGSS> {
4339    if constraint.parser_has_controls() || template_advance_selected(constraint) {
4340        return None;
4341    }
4342    // If every nonempty path has this top, isolate(Some(top)) is precisely
4343    // the original immutable GSS. Avoid enumerating/copying the top set and
4344    // retaining an extra Arc. The caller must not retry a declined action:
4345    // repeating it on this same GSS cannot make the shortcut more applicable.
4346    if let Some(top) = gss.single_exclusive_top_value() {
4347        let action = constraint.table.action(top, terminal)?;
4348        return apply_single_top_action_fast(constraint, gss, top, terminal, action);
4349    }
4350    let mut selected = None;
4351    for top in gss.peek_values() {
4352        let Some(action) = constraint.table.action(top, terminal) else {
4353            continue;
4354        };
4355        if selected.is_some() {
4356            return None;
4357        }
4358        selected = Some((top, action));
4359    }
4360    let (top, action) = selected?;
4361    let isolated = gss.isolate(Some(top));
4362    (!isolated.is_empty())
4363        .then(|| apply_single_top_action_fast(constraint, &isolated, top, terminal, action))
4364        .flatten()
4365}
4366
4367fn try_batch_same_width_disjoint_alias_actions(
4368    constraint: &Constraint,
4369    gss: &ParserGSS,
4370    matches: &[NormalizedMatch],
4371    width: usize,
4372    continuation_states: &[u32],
4373) -> Option<ParserGSS> {
4374    if constraint.parser_has_controls() || template_advance_selected(constraint) {
4375        return None;
4376    }
4377    let group = matches
4378        .iter()
4379        .filter(|matched| matched.width == width && !matched.ignored)
4380        .collect::<SmallVec<[&NormalizedMatch; 16]>>();
4381    if group.len() < 2 {
4382        return None;
4383    }
4384    for matched in &group {
4385        if continuation_states.iter().any(|&state| {
4386            constraint
4387                .tokenizer
4388                .possible_future_terminals(state)
4389                .contains(matched.terminal_id as usize)
4390        }) {
4391            return None;
4392        }
4393    }
4394
4395    let mut terminal_by_top = SmallVec::<[(u32, u32); 8]>::new();
4396    for top in gss.peek_values() {
4397        let mut selected = None;
4398        for matched in &group {
4399            if constraint.table.action(top, matched.terminal_id).is_none() {
4400                continue;
4401            }
4402            if selected.is_some() {
4403                return None;
4404            }
4405            selected = Some(matched.terminal_id);
4406        }
4407        if let Some(terminal) = selected {
4408            terminal_by_top.push((top, terminal));
4409        }
4410    }
4411    if terminal_by_top.len() < 2 {
4412        return None;
4413    }
4414    advance_stacks_disjoint_top_terminals_bounded(
4415        &constraint.table,
4416        gss,
4417        &terminal_by_top,
4418    )
4419}
4420
4421fn try_batch_same_width_pure_matches(
4422    constraint: &Constraint,
4423    gss: &ParserGSS,
4424    matches: &[NormalizedMatch],
4425    width: usize,
4426    continuation_states: &[u32],
4427) -> Option<ParserGSS> {
4428    if constraint.has_template_parser() { return None; }
4429
4430    if constraint.parser_has_controls() {
4431        return None;
4432    }
4433    let group = matches
4434        .iter()
4435        .filter(|matched| matched.width == width && !matched.ignored)
4436        .collect::<SmallVec<[&NormalizedMatch; 16]>>();
4437    if group.len() < 2 {
4438        return None;
4439    }
4440
4441    // The historical per-terminal path adds delayed longest-match exclusions
4442    // only when that same logical terminal remains possible after the model
4443    // token. Batch only when that transform is identity for every member.
4444    for matched in &group {
4445        if continuation_states.iter().any(|&state| {
4446            constraint
4447                .tokenizer
4448                .possible_future_terminals(state)
4449                .contains(matched.terminal_id as usize)
4450        }) {
4451            return None;
4452        }
4453    }
4454
4455    let tops = gss.peek_values();
4456    let mut shifts = SmallVec::<[(u32, u32, bool); 32]>::new();
4457    for &top in &tops {
4458        for matched in &group {
4459            let Some(action) = constraint.table.action(top, matched.terminal_id) else {
4460                continue;
4461            };
4462            match action {
4463                Action::Shift(target, replace) => {
4464                    let edge = (top, *target, *replace);
4465                    if !shifts.contains(&edge) {
4466                        shifts.push(edge);
4467                    }
4468                }
4469                Action::ReplaceShifts(targets) => {
4470                    for &target in targets.iter() {
4471                        let edge = (top, target, true);
4472                        if !shifts.contains(&edge) {
4473                            shifts.push(edge);
4474                        }
4475                    }
4476                }
4477                Action::StackShifts(stack_shifts) => {
4478                    for shift in stack_shifts {
4479                        if shift.pushes.len() != 1 || shift.pop > 1 {
4480                            return None;
4481                        }
4482                        let edge = (top, shift.pushes[0], shift.pop == 1);
4483                        if !shifts.contains(&edge) {
4484                            shifts.push(edge);
4485                        }
4486                    }
4487                }
4488                _ => return None,
4489            }
4490        }
4491    }
4492    if shifts.is_empty() {
4493        return None;
4494    }
4495
4496    let advanced = if tops.len() == 1
4497        && shifts.iter().all(|(top, _, _)| *top == tops[0])
4498        && shifts
4499            .first()
4500            .is_some_and(|(_, _, replace)| shifts.iter().all(|(_, _, other)| other == replace))
4501        && shifts
4502            .iter()
4503            .enumerate()
4504            .all(|(index, (_, target, _))| {
4505                !shifts[..index]
4506                    .iter()
4507                    .any(|(_, prior_target, _)| prior_target == target)
4508            })
4509        && let Some(stack) = gss.try_virtual_stack()
4510    {
4511        let replace = shifts[0].2;
4512        stack
4513            .into_gss_after_popping_and_pushing_unique_single_branches(
4514                usize::from(replace),
4515                shifts.iter().map(|(_, target, _)| target),
4516            )
4517            .unwrap_or_else(|| gss.apply_top_pure_shifts(shifts.clone()))
4518    } else {
4519        gss.apply_top_pure_shifts(shifts)
4520    };
4521    (!advanced.is_empty()).then_some(advanced)
4522}
4523
4524#[inline]
4525fn commit_bytes_small_queue_fast_path(
4526    constraint: &Constraint,
4527    state: &mut ParserStateMap,
4528    bytes: &[u8],
4529    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4530    queue_scratch: &mut SmallCommitQueueScratch,
4531    admission_cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
4532    prune_tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4533) -> Option<Result<(), String>> {
4534    commit_bytes_small_queue_fast_path_observed(constraint, state, bytes, tokenizer_scratch, queue_scratch, admission_cache, prune_tokenizer_scratch, &mut NoMarkers)
4535}
4536
4537fn commit_bytes_small_queue_fast_path_observed<O: CommitObserver>(
4538    constraint: &Constraint,
4539    state: &mut ParserStateMap,
4540    bytes: &[u8],
4541    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4542    queue_scratch: &mut SmallCommitQueueScratch,
4543    admission_cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
4544    prune_tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
4545    observer: &mut O,
4546) -> Option<Result<(), String>> {
4547    let marker_checkpoint = observer.checkpoint();
4548    let result = (|| {
4549    let has_linker_controls = constraint.parser_has_controls()
4550        || constraint.uses_compact_segmented_parser_runtime();
4551    if bytes.len() > 16 || state.len() > 8 {
4552        return None;
4553    }
4554    queue_scratch.clear();
4555    for (&tokenizer_state, gss) in state.iter() {
4556        merge_small_parser_state(
4557            &mut queue_scratch.processing[0],
4558            tokenizer_state,
4559            gss.clone(),
4560        );
4561    }
4562
4563    let initial_tokenizer_state = constraint.runtime_commit_initial_state();
4564    let mut offset = 0usize;
4565    while offset <= bytes.len() {
4566        if queue_scratch.processing[offset].is_empty() {
4567            offset += 1;
4568            continue;
4569        }
4570
4571        let states_to_process = std::mem::take(&mut queue_scratch.processing[offset]);
4572        let mut groups = SmallVec::<[(ParserGSS, SmallVec<[u32; 8]>); 8]>::new();
4573        for (tokenizer_state, gss) in states_to_process {
4574            let can_group = gss.all_accs_satisfy(|acc: &TerminalsDisallowed| acc.is_empty());
4575            let mut grouped = false;
4576            if can_group {
4577                'groups: for (existing_gss, tokenizer_states) in &mut groups {
4578                    if !existing_gss.ptr_eq(&gss) {
4579                        continue;
4580                    }
4581                    let future = constraint.tokenizer.possible_future_terminals(tokenizer_state);
4582                    for &other_state in tokenizer_states.iter() {
4583                        if !future.is_disjoint(
4584                            constraint.tokenizer.possible_future_terminals(other_state),
4585                        ) {
4586                            continue 'groups;
4587                        }
4588                    }
4589                    tokenizer_states.push(tokenizer_state);
4590                    grouped = true;
4591                    break;
4592                }
4593            }
4594            if !grouped {
4595                groups.push((gss, smallvec::smallvec![tokenizer_state]));
4596            }
4597        }
4598
4599        for (mut gss_at_offset, tokenizer_states) in groups {
4600            let tokenizer_state = tokenizer_states[0];
4601            let reused_prune_scan = offset == 0
4602                && !queue_scratch.prune_union_starts.is_empty()
4603                && queue_scratch.prune_union_starts.as_slice() == tokenizer_states.as_slice();
4604            if reused_prune_scan {
4605                tokenizer_scratch.states.clear();
4606                tokenizer_scratch
4607                    .states
4608                    .extend(prune_tokenizer_scratch.states.iter().copied());
4609                tokenizer_scratch.matches.clear();
4610                tokenizer_scratch
4611                    .matches
4612                    .extend(prune_tokenizer_scratch.matches.iter().cloned());
4613            } else if !execute_tokenizer_reusable_from_states(
4614                constraint,
4615                &bytes[offset..],
4616                &tokenizer_states,
4617                tokenizer_scratch,
4618            ) {
4619                return None;
4620            }
4621
4622            if offset == 0
4623                && !gss_at_offset.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
4624            {
4625                gss_at_offset = try_prune_single_initial_state_batched_accumulators(
4626                    constraint,
4627                    &gss_at_offset,
4628                    bytes,
4629                    prune_tokenizer_scratch,
4630                    &mut queue_scratch.prune_union_starts,
4631                )
4632                .unwrap_or_else(|| {
4633                    prune_single_initial_state_for_parts(
4634                        constraint,
4635                        gss_at_offset,
4636                        tokenizer_state,
4637                        &tokenizer_scratch.states,
4638                        &tokenizer_scratch.matches,
4639                        bytes,
4640                    )
4641                });
4642                if gss_at_offset.is_empty() {
4643                    continue;
4644                }
4645            }
4646
4647            let (actionable_terminals, normalized_matches) =
4648                if tokenizer_scratch.matches.is_empty() {
4649                    (None, SmallVec::<[NormalizedMatch; 16]>::new())
4650                } else {
4651                    let actionable_terminals = (!has_linker_controls)
4652                        .then(|| ActionableTerminals::from_gss(constraint, &gss_at_offset))
4653                        .flatten();
4654                    let normalized_matches = collect_unique_actionable_reusable_matches(
4655                        constraint,
4656                        actionable_terminals.as_ref(),
4657                        constraint.ignore_terminal,
4658                        &tokenizer_scratch.matches,
4659                    );
4660                    (actionable_terminals, normalized_matches)
4661                };
4662            let mut emitted_terminal_outputs = SmallVec::<[(usize, ParserGSS); 4]>::new();
4663            let mut batched_widths = SmallVec::<[usize; 4]>::new();
4664            for matched in &normalized_matches {
4665                if matched.ignored || batched_widths.contains(&matched.width) {
4666                    continue;
4667                }
4668                let batched = try_batch_same_width_pure_matches(
4669                    constraint,
4670                    &gss_at_offset,
4671                    &normalized_matches,
4672                    matched.width,
4673                    &tokenizer_scratch.states,
4674                )
4675                .or_else(|| {
4676                    try_batch_same_width_disjoint_alias_actions(
4677                        constraint,
4678                        &gss_at_offset,
4679                        &normalized_matches,
4680                        matched.width,
4681                        &tokenizer_scratch.states,
4682                    )
4683                });
4684                if let Some(advanced) = batched {
4685                    let new_offset = offset + matched.width;
4686                    if new_offset > bytes.len() {
4687                        return None;
4688                    }
4689                    if emitted_terminal_outputs.iter().any(|(emitted_offset, emitted_gss)| {
4690                        *emitted_offset == new_offset && emitted_gss == &advanced
4691                    }) {
4692                        batched_widths.push(matched.width);
4693                        continue;
4694                    }
4695                    observer.stack(constraint, &advanced, new_offset);
4696                emitted_terminal_outputs.push((new_offset, advanced.clone()));
4697                    if new_offset == bytes.len() {
4698                        merge_small_parser_state(
4699                            &mut queue_scratch.pending,
4700                            initial_tokenizer_state,
4701                            advanced,
4702                        );
4703                    } else {
4704                        merge_small_parser_state(
4705                            &mut queue_scratch.processing[new_offset],
4706                            initial_tokenizer_state,
4707                            advanced,
4708                        );
4709                    }
4710                    batched_widths.push(matched.width);
4711                }
4712            }
4713
4714            for matched in normalized_matches {
4715                let new_offset = offset + matched.width;
4716                if !matched.ignored && batched_widths.contains(&matched.width) {
4717                    continue;
4718                }
4719                if new_offset > bytes.len() {
4720                    return None;
4721                }
4722
4723                if matched.ignored {
4724                    observer.stack(constraint, &gss_at_offset, new_offset);
4725                    if new_offset == bytes.len() {
4726                        merge_small_parser_state(
4727                            &mut queue_scratch.pending,
4728                            initial_tokenizer_state,
4729                            gss_at_offset.clone(),
4730                        );
4731                    } else {
4732                        merge_small_parser_state(
4733                            &mut queue_scratch.processing[new_offset],
4734                            initial_tokenizer_state,
4735                            gss_at_offset.clone(),
4736                        );
4737                    }
4738                    continue;
4739                }
4740
4741                let advanced = if !has_linker_controls
4742                    && !template_advance_selected(constraint)
4743                    && let Some(advanced) = try_advance_unique_actionable_top_fast(
4744                        constraint,
4745                        &gss_at_offset,
4746                        matched.terminal_id,
4747                    )
4748                {
4749                    advanced
4750                } else {
4751                    let Some(advanced) = advance_parser_stacks_if_possible(
4752                        constraint,
4753                        &gss_at_offset,
4754                        matched.terminal_id,
4755                    ) else {
4756                        continue;
4757                    };
4758                    advanced
4759                };
4760                let advanced = apply_future_terminal_disallow_for_states(
4761                    constraint,
4762                    &tokenizer_scratch.states,
4763                    matched.terminal_id,
4764                    advanced,
4765                );
4766                if advanced.is_empty() {
4767                    continue;
4768                }
4769                if emitted_terminal_outputs.iter().any(|(emitted_offset, emitted_gss)| {
4770                    *emitted_offset == new_offset && emitted_gss == &advanced
4771                }) {
4772                    continue;
4773                }
4774                observer.stack(constraint, &advanced, new_offset);
4775                emitted_terminal_outputs.push((new_offset, advanced.clone()));
4776                if new_offset == bytes.len() {
4777                    merge_small_parser_state(
4778                        &mut queue_scratch.pending,
4779                        initial_tokenizer_state,
4780                        advanced,
4781                    );
4782                } else {
4783                    merge_small_parser_state(
4784                        &mut queue_scratch.processing[new_offset],
4785                        initial_tokenizer_state,
4786                        advanced,
4787                    );
4788                }
4789            }
4790
4791            let local_row_admission = try_local_row_presence_admission_words(
4792                constraint,
4793                &gss_at_offset,
4794                &tokenizer_scratch.states,
4795            );
4796            let admission_cache_index = if local_row_admission.is_none() {
4797                cached_batched_end_state_admission(
4798                    constraint,
4799                    &gss_at_offset,
4800                    &tokenizer_scratch.states,
4801                    admission_cache,
4802                )
4803            } else {
4804                None
4805            };
4806            for &end_state in &tokenizer_scratch.states {
4807                let may_advance = if let Some(words) = local_row_admission.as_ref() {
4808                    end_state_may_advance_from_row_words(constraint, end_state, words)
4809                } else if let Some(index) = admission_cache_index {
4810                    end_state_may_advance_from_cache_entry(
4811                        constraint,
4812                        end_state,
4813                        &admission_cache[index],
4814                    )
4815                } else {
4816                    cached_single_end_state_may_advance(
4817                        constraint,
4818                        &gss_at_offset,
4819                        end_state,
4820                        admission_cache,
4821                    )
4822                };
4823                if may_advance {
4824                    merge_small_parser_state(
4825                        &mut queue_scratch.pending,
4826                        end_state,
4827                        gss_at_offset.clone(),
4828                    );
4829                }
4830            }
4831        }
4832        offset += 1;
4833    }
4834
4835    let mut new_state = ParserStateMap::default();
4836    let mut fused_by_source = SmallVec::<[(ParserGSS, ParserGSS); 8]>::new();
4837    for (tokenizer_state, parser_state) in queue_scratch.pending.drain(..) {
4838        let mut fused = fused_by_source
4839            .iter()
4840            .find(|(source, _)| source.ptr_eq(&parser_state))
4841            .map(|(_, fused)| fused.clone())
4842            .unwrap_or_else(|| {
4843                let source = parser_state.clone();
4844                let fused = parser_state.fuse(Some(1));
4845                fused_by_source.push((source, fused.clone()));
4846                fused
4847            });
4848        if let Some((_, canonical)) = fused_by_source
4849            .iter()
4850            .find(|(_, candidate)| *candidate == fused)
4851        {
4852            fused = canonical.clone();
4853        }
4854        if !fused.is_empty() {
4855            if let Some(_uniform) = fused.uniform_accumulator() {
4856                new_state.insert_flat_alternative(tokenizer_state, fused);
4857            } else {
4858                let mut accumulators = SmallVec::<[TerminalsDisallowed; 4]>::new();
4859                let mut overflow = false;
4860                fused.for_each_acc(|acc| {
4861                    if overflow || accumulators.contains(acc) {
4862                        return;
4863                    }
4864                    if accumulators.len() == accumulators.capacity() {
4865                        overflow = true;
4866                        return;
4867                    }
4868                    accumulators.push(acc.clone());
4869                });
4870                if overflow || accumulators.len() <= 1 {
4871                    new_state.insert_flat_alternative(tokenizer_state, fused);
4872                } else {
4873                    for acc in accumulators {
4874                        let part = fused.apply_and_prune_no_promote(|candidate| {
4875                            (candidate == &acc).then_some(candidate.clone())
4876                        });
4877                        if !part.is_empty() {
4878                            new_state.insert_flat_alternative(tokenizer_state, part);
4879                        }
4880                    }
4881                }
4882            }
4883        }
4884    }
4885    if new_state.is_empty() {
4886        return Some(Err("commit rejected: no valid parser states remain".to_string()));
4887    }
4888    *state = new_state;
4889    Some(Ok(()))
4890
4891    })();
4892    if result.is_none() { observer.rewind(marker_checkpoint); }
4893    result
4894}
4895
4896enum LinearFastPathResult {
4897    Complete(Result<ParserGSS, String>),
4898    Continue { gss: ParserGSS, offset: usize },
4899    Restart,
4900}
4901
4902struct DirectLinearStep {
4903    width: usize,
4904    terminal: u32,
4905    ignored: bool,
4906    end_state: Option<u32>,
4907}
4908
4909fn choose_direct_linear_step(
4910    constraint: &Constraint,
4911    gss: &ParserGSS,
4912    bytes: &[u8],
4913    start_state: u32,
4914    carried_top_state: Option<u32>,
4915) -> Option<DirectLinearStep> {
4916    let ignore_terminal = constraint.ignore_terminal;
4917    let mut tokenizer_state = start_state;
4918    let mut chosen: Option<(usize, u32, bool)> = None;
4919    let mut consumed_all = true;
4920    let mut actionable_terminals = carried_top_state.map(ActionableTerminals::SingleState);
4921
4922    for (index, &byte) in bytes.iter().enumerate() {
4923        let next_state = constraint.tokenizer_fast_transitions.transition(
4924            &constraint.tokenizer,
4925            tokenizer_state,
4926            byte,
4927        );
4928        if next_state == u32::MAX {
4929            consumed_all = false;
4930            break;
4931        };
4932        tokenizer_state = next_state;
4933        let width = index + 1;
4934        let mut chosen_at_width = false;
4935
4936        if actionable_terminals.is_none() {
4937            actionable_terminals = ActionableTerminals::from_gss(constraint, gss);
4938        }
4939        let mut conflict = false;
4940        for_each_relevant_matched_terminal(
4941            constraint,
4942            tokenizer_state,
4943            actionable_terminals.as_ref(),
4944            |terminal, ignored| {
4945                let candidate = (width, terminal, ignored);
4946                chosen_at_width = true;
4947                if let Some((_, existing_terminal, _)) = chosen {
4948                    if existing_terminal == terminal {
4949                        chosen = Some(candidate);
4950                    } else {
4951                        conflict = true;
4952                    }
4953                } else {
4954                    chosen = Some(candidate);
4955                }
4956            },
4957        );
4958        if conflict {
4959            return None;
4960        }
4961
4962        if chosen_at_width && chosen.is_some_and(|(_, _, ignored)| ignored) {
4963            return Some(DirectLinearStep {
4964                width,
4965                terminal: chosen.unwrap().1,
4966                ignored: true,
4967                end_state: None,
4968            });
4969        }
4970
4971        if chosen_at_width
4972            && chosen.is_some_and(|(_, _, ignored)| !ignored)
4973            && index + 1 < bytes.len()
4974        {
4975            let next_byte = bytes[index + 1];
4976            let next_state = constraint.tokenizer_fast_transitions.transition(
4977                &constraint.tokenizer,
4978                tokenizer_state,
4979                next_byte,
4980            );
4981            if next_state == u32::MAX {
4982                let (_, terminal, _) = chosen.unwrap();
4983                return Some(DirectLinearStep {
4984                    width,
4985                    terminal,
4986                    ignored: false,
4987                    end_state: None,
4988                });
4989            }
4990        }
4991    }
4992
4993    let (width, terminal, ignored) = chosen?;
4994    let end_state = consumed_all.then_some(tokenizer_state);
4995
4996    Some(DirectLinearStep {
4997        width,
4998        terminal,
4999        ignored,
5000        end_state,
5001    })
5002}
5003
5004#[inline]
5005fn commit_bytes_direct_linear_fast_path(
5006    constraint: &Constraint,
5007    start_gss: ParserGSS,
5008    bytes: &[u8],
5009    start_tokenizer_state: u32,
5010    profile: Option<&mut CommitProfile>,
5011) -> Option<LinearFastPathResult> {
5012    commit_bytes_direct_linear_fast_path_observed(constraint, start_gss, bytes, start_tokenizer_state, profile, &mut NoMarkers)
5013}
5014
5015fn commit_bytes_direct_linear_fast_path_observed<O: CommitObserver>(
5016    constraint: &Constraint,
5017    start_gss: ParserGSS,
5018    bytes: &[u8],
5019    start_tokenizer_state: u32,
5020    mut profile: Option<&mut CommitProfile>,
5021    observer: &mut O,
5022) -> Option<LinearFastPathResult> {
5023    let marker_checkpoint = observer.checkpoint();
5024    let result = (|| {
5025    if constraint.has_template_parser() { return None; }
5026
5027    let mut gss = start_gss;
5028    let mut carried_stack = gss.try_virtual_stack();
5029    let mut offset = 0usize;
5030    let mut tokenizer_state = start_tokenizer_state;
5031
5032    while offset < bytes.len() {
5033        let choose_start = profile.as_ref().map(|_| std::time::Instant::now());
5034        let carried_top_state = carried_stack.as_ref().and_then(|stack| stack.top().copied());
5035        let Some(step) = choose_direct_linear_step(
5036            constraint,
5037            &gss,
5038            &bytes[offset..],
5039            tokenizer_state,
5040            carried_top_state,
5041        ) else {
5042            if let Some(stack) = carried_stack.take() {
5043                let materialize_start = profile.as_ref().map(|_| std::time::Instant::now());
5044                gss = stack.into_gss();
5045                if let (Some(profile), Some(start)) = (profile.as_deref_mut(), materialize_start) {
5046                    profile.linear_fast_path_materialize_ns += start.elapsed().as_nanos() as u64;
5047                }
5048            }
5049            if offset > 0 && profile.is_none() {
5050                return Some(LinearFastPathResult::Continue { gss, offset });
5051            }
5052            return None;
5053        };
5054        if let (Some(profile), Some(start)) = (profile.as_deref_mut(), choose_start) {
5055            profile.linear_fast_path_match_scan_ns += start.elapsed().as_nanos() as u64;
5056            profile.linear_fast_path_steps += 1;
5057        }
5058
5059        let keep_carried = if let Some(end_state) = step.end_state
5060            && let Some(stack) = carried_stack.as_ref()
5061        {
5062            let carried_gate_start = profile.as_ref().map(|_| std::time::Instant::now());
5063            let keep_carried = stack.top().copied().is_some_and(|top_state| {
5064                end_state != constraint.runtime_commit_initial_state()
5065                    && !constraint.parser_advance_row_intersects(
5066                        top_state,
5067                        constraint.tokenizer.possible_future_terminals(end_state),
5068                    )
5069                    && !constraint
5070                        .tokenizer
5071                        .possible_future_terminals(end_state)
5072                        .contains(step.terminal as usize)
5073            });
5074            if let (Some(profile), Some(start)) = (profile.as_deref_mut(), carried_gate_start) {
5075                let elapsed = start.elapsed().as_nanos() as u64;
5076                profile.linear_fast_path_carried_gate_ns += elapsed;
5077                profile.linear_fast_path_end_state_check_ns += elapsed;
5078            }
5079            keep_carried
5080        } else {
5081            false
5082        };
5083        if step.end_state.is_some()
5084            && !keep_carried
5085                && let Some(stack) = carried_stack.take() {
5086                    let materialize_start = profile.as_ref().map(|_| std::time::Instant::now());
5087                    gss = stack.into_gss();
5088                    if let (Some(profile), Some(start)) = (profile.as_deref_mut(), materialize_start) {
5089                        profile.linear_fast_path_materialize_ns += start.elapsed().as_nanos() as u64;
5090                    }
5091                }
5092
5093        if let Some(end_state) = step.end_state {
5094            let carried_gate_start = profile.as_ref().map(|_| std::time::Instant::now());
5095            let should_restart = end_state_may_advance(constraint, &gss, end_state);
5096            if let (Some(profile), Some(start)) = (profile.as_deref_mut(), carried_gate_start) {
5097                let elapsed = start.elapsed().as_nanos() as u64;
5098                profile.linear_fast_path_carried_gate_ns += elapsed;
5099                profile.linear_fast_path_end_state_check_ns += elapsed;
5100            }
5101            if should_restart {
5102                if let Some(stack) = carried_stack.take() {
5103                    let materialize_start = profile.as_ref().map(|_| std::time::Instant::now());
5104                    gss = stack.into_gss();
5105                    if let (Some(profile), Some(start)) = (profile.as_deref_mut(), materialize_start) {
5106                        profile.linear_fast_path_materialize_ns += start.elapsed().as_nanos() as u64;
5107                    }
5108                }
5109                if offset > 0 && profile.is_none() {
5110                    return Some(LinearFastPathResult::Continue { gss, offset });
5111                }
5112                return None;
5113            }
5114        }
5115
5116        if !step.ignored {
5117            if offset == 0
5118                && !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()) {
5119                    // Delayed exclusions are keyed by continuation tokenizer states,
5120                    // not necessarily by the current tokenizer state. The
5121                    // general/flat paths execute every continuation state over
5122                    // the whole model token; this single-step shortcut lacks
5123                    // that information, so decline rather than applying the
5124                    // old current-state-only pruning rule.
5125                    return None;
5126                }
5127
5128            let mut shifted_carried_stack = false;
5129            let mut carried_apply_elapsed_ns = 0u64;
5130            let action_lookup_start = profile.as_ref().map(|_| std::time::Instant::now());
5131            let carried_action = if let Some(stack) = carried_stack.as_ref()
5132                && let Some(top_state) = stack.top().copied()
5133                && step.end_state.is_none_or(|end_state| {
5134                    end_state != constraint.runtime_commit_initial_state()
5135                        && !constraint.parser_advance_row_intersects(
5136                            top_state,
5137                            constraint.tokenizer.possible_future_terminals(end_state),
5138                        )
5139                        && !constraint
5140                            .tokenizer
5141                            .possible_future_terminals(end_state)
5142                            .contains(step.terminal as usize)
5143                })
5144            {
5145                constraint.table.action(top_state, step.terminal)
5146            } else {
5147                None
5148            };
5149            if let (Some(profile), Some(start)) = (profile.as_deref_mut(), action_lookup_start) {
5150                profile.linear_fast_path_action_lookup_ns += start.elapsed().as_nanos() as u64;
5151            }
5152            if let Some(action) = carried_action {
5153                let apply_action_start = profile.as_ref().map(|_| std::time::Instant::now());
5154                if !template_advance_selected(constraint)
5155                    && let Some(stack) = carried_stack.as_mut()
5156                {
5157                    shifted_carried_stack =
5158                        try_apply_action_to_carried_virtual_stack(stack, action);
5159                }
5160                if let (Some(profile), Some(start)) = (profile.as_deref_mut(), apply_action_start) {
5161                    carried_apply_elapsed_ns = start.elapsed().as_nanos() as u64;
5162                    profile.linear_fast_path_apply_action_wall_ns += carried_apply_elapsed_ns;
5163                }
5164            }
5165            if shifted_carried_stack {
5166                if let Some(profile) = profile.as_deref_mut() {
5167                    let bookkeeping_start = std::time::Instant::now();
5168                    let advance_profile = fast_action_advance_profile(
5169                        &gss,
5170                        carried_action.unwrap(),
5171                        carried_apply_elapsed_ns,
5172                    );
5173                    profile.advance_core_ns += advance_profile.total_ns;
5174                    profile.advance_ns += carried_apply_elapsed_ns;
5175                    profile.linear_fast_path_advance_ns += carried_apply_elapsed_ns;
5176                    profile.n_advances += 1;
5177                    apply_advance_profile(profile, &advance_profile);
5178                    profile.linear_fast_path_profile_bookkeeping_ns +=
5179                        bookkeeping_start.elapsed().as_nanos() as u64;
5180                }
5181
5182                offset += step.width;
5183                if let Some(stack) = carried_stack.as_ref() { observer.carried(constraint, stack, offset); }
5184                else { observer.stack(constraint, &gss, offset); }
5185                tokenizer_state = constraint.runtime_commit_initial_state();
5186                continue;
5187            }
5188
5189            if let Some(stack) = carried_stack.take() {
5190                let materialize_start = profile.as_ref().map(|_| std::time::Instant::now());
5191                gss = stack.into_gss();
5192                if let (Some(profile), Some(start)) = (profile.as_deref_mut(), materialize_start) {
5193                    profile.linear_fast_path_materialize_ns += start.elapsed().as_nanos() as u64;
5194                }
5195            }
5196            let advance_start = profile.as_ref().map(|_| std::time::Instant::now());
5197            let advanced = if !template_advance_selected(constraint)
5198                && let Some(top_state) = gss.single_exclusive_top_value()
5199                && let Some(action) = constraint.table.action(top_state, step.terminal)
5200                && let Some(advanced) =
5201                    apply_single_top_action_fast(
5202                        constraint,
5203                        &gss,
5204                        top_state,
5205                        step.terminal,
5206                        action,
5207                    )
5208            {
5209                advanced
5210            } else {
5211                if let Some(profile) = profile.as_deref_mut() {
5212                    let (advanced, advance_profile) =
5213                        advance_parser_stacks_profiled(constraint, &gss, step.terminal);
5214                    if advanced.is_empty() {
5215                        return None;
5216                    }
5217                    let bookkeeping_start = std::time::Instant::now();
5218                    profile.advance_core_ns += advance_profile.total_ns;
5219                    apply_advance_profile(profile, &advance_profile);
5220                    profile.linear_fast_path_profile_bookkeeping_ns +=
5221                        bookkeeping_start.elapsed().as_nanos() as u64;
5222                    advanced
5223                } else {
5224                    let advanced = advance_parser_stacks(constraint, &gss, step.terminal);
5225                    if advanced.is_empty() {
5226                        return None;
5227                    }
5228                    advanced
5229                }
5230            };
5231            if let (Some(profile), Some(start)) = (profile.as_deref_mut(), advance_start) {
5232                let elapsed = start.elapsed().as_nanos() as u64;
5233                profile.linear_fast_path_apply_action_wall_ns += elapsed;
5234                profile.advance_ns += elapsed;
5235                profile.linear_fast_path_advance_ns += elapsed;
5236                profile.n_advances += 1;
5237            }
5238            if advanced.is_empty() {
5239                return Some(LinearFastPathResult::Complete(Err(
5240                    "commit rejected: no valid parser states remain".to_string(),
5241                )));
5242            }
5243            let exec_result = TokenizerExecResult {
5244                end_state: step.end_state.into_iter().collect(),
5245                matches: Vec::new(),
5246            };
5247            let future_start = profile.as_ref().map(|_| std::time::Instant::now());
5248            gss = apply_future_terminal_disallow(
5249                constraint,
5250                &exec_result,
5251                step.terminal,
5252                advanced,
5253            );
5254            if let (Some(profile), Some(start)) = (profile.as_deref_mut(), future_start) {
5255                let elapsed = start.elapsed().as_nanos() as u64;
5256                profile.advance_future_disallow_ns += elapsed;
5257                profile.linear_fast_path_future_disallow_ns += elapsed;
5258                profile.linear_fast_path_advance_ns += elapsed;
5259            }
5260            if gss.is_empty() {
5261                return Some(LinearFastPathResult::Complete(Err(
5262                    "commit rejected: no valid parser states remain".to_string(),
5263                )));
5264            }
5265        }
5266
5267        offset += step.width;
5268                if let Some(stack) = carried_stack.as_ref() { observer.carried(constraint, stack, offset); }
5269                else { observer.stack(constraint, &gss, offset); }
5270        tokenizer_state = constraint.runtime_commit_initial_state();
5271    }
5272
5273    if let Some(stack) = carried_stack.take() {
5274        let materialize_start = profile.as_ref().map(|_| std::time::Instant::now());
5275        gss = stack.into_gss();
5276        if let (Some(profile), Some(start)) = (profile.as_deref_mut(), materialize_start) {
5277            profile.linear_fast_path_materialize_ns += start.elapsed().as_nanos() as u64;
5278        }
5279    }
5280    let fuse_start = profile.as_ref().map(|_| std::time::Instant::now());
5281    let fused = if constraint.direct_regular_wide_frontier_for_gss(&gss).is_some() {
5282        gss
5283    } else {
5284        gss.fuse(Some(1))
5285    };
5286    if let (Some(profile), Some(start)) = (profile, fuse_start) {
5287        let elapsed = start.elapsed().as_nanos() as u64;
5288        profile.linear_fast_path_fuse_ns += elapsed;
5289        profile.fuse_ns += elapsed;
5290    }
5291    if fused.is_empty() {
5292        return Some(LinearFastPathResult::Complete(Err(
5293            "commit rejected: no valid parser states remain".to_string(),
5294        )));
5295    }
5296    Some(LinearFastPathResult::Complete(Ok(fused)))
5297
5298    })();
5299    if result.is_none() || matches!(&result, Some(LinearFastPathResult::Restart)) { observer.rewind(marker_checkpoint); }
5300    result
5301}
5302
5303fn record_per_advance_entry(
5304    advances: &mut Vec<PerAdvanceEntry>,
5305    tokenizer_state: u32,
5306    terminal_id: u32,
5307    before_gss: &ParserGSS,
5308    after_gss: &ParserGSS,
5309    match_start: usize,
5310    match_end: usize,
5311    token_bound: usize,
5312    match_bytes: &[u8],
5313    profile: AdvanceProfile,
5314) -> u64 {
5315    use std::time::Instant;
5316
5317    let summary_start = Instant::now();
5318    let gss_stacks_before = parser_stacks_only(before_gss);
5319    let gss_stacks_after = parser_stacks_only(after_gss);
5320    let gss_summary_before = before_gss.summary();
5321    let gss_summary_after = after_gss.summary();
5322    let match_bytes = match_bytes.to_vec();
5323    let summary_ns = summary_start.elapsed().as_nanos() as u64;
5324    advances.push(PerAdvanceEntry {
5325        terminal_id,
5326        tokenizer_state,
5327        gss_stacks_before,
5328        gss_stacks_after,
5329        gss_summary_before,
5330        gss_summary_after,
5331        match_start,
5332        match_end,
5333        token_bound,
5334        match_bytes,
5335        profile,
5336        summary_ns,
5337    });
5338    summary_ns
5339}
5340
5341fn commit_bytes_fast_path_profiled(
5342    constraint: &Constraint,
5343    state: &mut ParserStateMap,
5344    bytes: &[u8],
5345    tokenizer_state: u32,
5346    exec_result: &TokenizerExecResult,
5347    advances: Option<&mut Vec<PerAdvanceEntry>>,
5348    profile: &mut CommitProfile,
5349) -> Option<Result<(), String>> {
5350    use std::time::Instant;
5351
5352    let total_start = Instant::now();
5353    let gss = state.values().next().unwrap();
5354    let ignore_terminal = constraint.ignore_terminal;
5355    if constraint.tokenizer_has_epsilon_transitions
5356        && !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
5357    {
5358        profile.failed_fast_path_probe_ns += total_start.elapsed().as_nanos() as u64;
5359        return None;
5360    }
5361
5362    let scan_start = Instant::now();
5363    let mut sole_terminal: Option<u32> = None;
5364    for matched in &exec_result.matches {
5365        if matched.width != bytes.len() {
5366            profile.failed_fast_path_probe_ns += total_start.elapsed().as_nanos() as u64;
5367            return None;
5368        }
5369        if is_ignored_terminal(ignore_terminal, matched.id) {
5370            profile.failed_fast_path_probe_ns += total_start.elapsed().as_nanos() as u64;
5371            return None;
5372        }
5373        if !parser_may_advance_on(constraint, gss, matched.id) {
5374            continue;
5375        }
5376        if sole_terminal.is_some() {
5377            profile.failed_fast_path_probe_ns += total_start.elapsed().as_nanos() as u64;
5378            return None;
5379        }
5380        sole_terminal = Some(matched.id);
5381    }
5382    profile.fast_path_match_scan_ns = scan_start.elapsed().as_nanos() as u64;
5383    let Some(terminal) = sole_terminal else {
5384        profile.failed_fast_path_probe_ns += total_start.elapsed().as_nanos() as u64;
5385        return None;
5386    };
5387
5388    let no_end_state = exec_result.end_state.is_empty();
5389    let all_accs_empty = no_end_state
5390        && gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty());
5391
5392    if all_accs_empty && !template_advance_selected(constraint)
5393        && let Some(top_state) = gss.single_exclusive_top_value() {
5394            if let Some(Action::Shift(target, is_replace)) = constraint.table.action(top_state, terminal) {
5395                let advance_start = Instant::now();
5396                let shifted = if *is_replace {
5397                    gss.popn(1).push(*target)
5398                } else {
5399                    gss.push(*target)
5400                };
5401                profile.fast_path_advance_ns = advance_start.elapsed().as_nanos() as u64;
5402                profile.advance_core_ns = profile.fast_path_advance_ns;
5403                profile.advance_ns = profile.fast_path_advance_ns;
5404                profile.n_advances = 1;
5405
5406                if let Some(advances) = advances {
5407                    profile.adv_summary_ns += record_per_advance_entry(
5408                        advances,
5409                        tokenizer_state,
5410                        terminal,
5411                        gss,
5412                        &shifted,
5413                        0,
5414                        bytes.len(),
5415                        bytes.len(),
5416                        bytes,
5417                        AdvanceProfile {
5418                            pure_shift: true,
5419                            fast_path_ns: profile.fast_path_advance_ns,
5420                            stack_shift_apply_ns: profile.fast_path_advance_ns,
5421                            total_ns: profile.fast_path_advance_ns,
5422                            top_states: gss.peek_values().len() as u32,
5423                            gss_depth: gss.max_depth(),
5424                            vstack_len: gss.try_virtual_stack().map_or(0, |vstack| vstack.len() as u32),
5425                            ..AdvanceProfile::default()
5426                        },
5427                    );
5428                }
5429
5430                let update_start = Instant::now();
5431                state.clear();
5432                state.insert(constraint.runtime_commit_initial_state(), shifted);
5433                profile.fast_path_state_update_ns = update_start.elapsed().as_nanos() as u64;
5434                profile.fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
5435                profile.total_ns = profile.fast_path_total_ns;
5436                profile.fast_path_tokenizer_exec_ns = profile.exec_ns;
5437                return Some(Ok(()));
5438            }
5439            if !template_advance_selected(constraint)
5440                && let Some(Action::StackShifts(shifts)) = constraint.table.action(top_state, terminal)
5441            {
5442                let advance_start = Instant::now();
5443                let (shifted, advance_profile) =
5444                    advance_parser_stacks_profiled(constraint, gss, terminal);
5445                profile.fast_path_advance_ns = advance_start.elapsed().as_nanos() as u64;
5446                profile.advance_core_ns = profile.fast_path_advance_ns;
5447                profile.advance_ns = profile.fast_path_advance_ns;
5448                profile.n_advances = 1;
5449                apply_advance_profile(profile, &advance_profile);
5450                if let Some(advances) = advances {
5451                    profile.adv_summary_ns += record_per_advance_entry(
5452                        advances,
5453                        tokenizer_state,
5454                        terminal,
5455                        gss,
5456                        &shifted,
5457                        0,
5458                        bytes.len(),
5459                        bytes.len(),
5460                        bytes,
5461                        advance_profile,
5462                    );
5463                }
5464
5465                let update_start = Instant::now();
5466                state.clear();
5467                state.insert(constraint.runtime_commit_initial_state(), shifted);
5468                profile.fast_path_state_update_ns = update_start.elapsed().as_nanos() as u64;
5469                profile.fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
5470                profile.total_ns = profile.fast_path_total_ns;
5471                profile.fast_path_tokenizer_exec_ns = profile.exec_ns;
5472                return Some(Ok(()));
5473            }
5474        }
5475
5476    let (_, gss_owned) = state.pop_first().unwrap();
5477
5478    let prune_start = Instant::now();
5479    let pruned_gss = if all_accs_empty {
5480        gss_owned
5481    } else {
5482        let pruned = prune_single_initial_state_for_exec(
5483            constraint,
5484            gss_owned,
5485            tokenizer_state,
5486            exec_result,
5487            bytes,
5488        );
5489
5490        if pruned.is_empty() {
5491            return Some(Err("commit rejected: no valid parser states remain".to_string()));
5492        }
5493        pruned
5494    };
5495    profile.fast_path_prune_ns = prune_start.elapsed().as_nanos() as u64;
5496    profile.prune_ns = profile.fast_path_prune_ns;
5497
5498    let end_state_check_start = Instant::now();
5499    let end_states_to_keep: TokenizerStateSet = exec_result
5500        .end_state
5501        .iter()
5502        .copied()
5503        .filter(|&end_state| end_state_may_advance(constraint, &pruned_gss, end_state))
5504        .collect();
5505    profile.fast_path_end_state_check_ns = end_state_check_start.elapsed().as_nanos() as u64;
5506
5507    let advance_start = Instant::now();
5508    let advanced = advance_parser_stacks_owned(constraint, pruned_gss.clone(), terminal);
5509    profile.fast_path_advance_ns = advance_start.elapsed().as_nanos() as u64;
5510    profile.advance_core_ns = profile.fast_path_advance_ns;
5511    profile.n_advances = 1;
5512
5513    if let Some(advances) = advances {
5514        let (after_for_entry, advance_profile) =
5515            advance_parser_stacks_profiled(constraint, &pruned_gss, terminal);
5516        profile.adv_summary_ns += record_per_advance_entry(
5517            advances,
5518            tokenizer_state,
5519            terminal,
5520            &pruned_gss,
5521            &after_for_entry,
5522            0,
5523            bytes.len(),
5524            bytes.len(),
5525            bytes,
5526            advance_profile.clone(),
5527        );
5528        apply_advance_profile(profile, &advance_profile);
5529    }
5530
5531    let mut produced_state = false;
5532    if !advanced.is_empty() {
5533        let future_start = Instant::now();
5534        let advanced = apply_future_terminal_disallow(constraint, exec_result, terminal, advanced);
5535        profile.fast_path_future_disallow_ns = future_start.elapsed().as_nanos() as u64;
5536        profile.advance_future_disallow_ns = profile.fast_path_future_disallow_ns;
5537        profile.advance_ns = profile.fast_path_advance_ns + profile.fast_path_future_disallow_ns;
5538
5539        if !advanced.is_empty() {
5540            let fuse_start = Instant::now();
5541            let fused = advanced.fuse(Some(1));
5542            profile.fast_path_fuse_ns = fuse_start.elapsed().as_nanos() as u64;
5543            profile.fuse_ns = profile.fast_path_fuse_ns;
5544
5545            if !fused.is_empty() {
5546                let update_start = Instant::now();
5547                state.insert(constraint.runtime_commit_initial_state(), fused);
5548                profile.fast_path_state_update_ns += update_start.elapsed().as_nanos() as u64;
5549                produced_state = true;
5550            }
5551        }
5552    } else {
5553        profile.advance_ns = profile.fast_path_advance_ns;
5554    }
5555
5556    if !end_states_to_keep.is_empty() {
5557        let fuse_start = Instant::now();
5558        let fused = pruned_gss.fuse(Some(1));
5559        let fuse_elapsed = fuse_start.elapsed().as_nanos() as u64;
5560        profile.fast_path_fuse_ns += fuse_elapsed;
5561        profile.fuse_ns += fuse_elapsed;
5562        if !fused.is_empty() {
5563            let update_start = Instant::now();
5564            for &end_state in &end_states_to_keep {
5565                state.merge_insert(end_state, fused.clone());
5566            }
5567            profile.fast_path_state_update_ns += update_start.elapsed().as_nanos() as u64;
5568            produced_state = true;
5569        }
5570    }
5571
5572    if !produced_state {
5573        return Some(Err("commit rejected: no valid parser states remain".to_string()));
5574    }
5575    profile.fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
5576    profile.total_ns = profile.fast_path_total_ns;
5577    profile.fast_path_tokenizer_exec_ns = profile.exec_ns;
5578    Some(Ok(()))
5579}
5580
5581fn commit_bytes_impl_profiled(
5582    constraint: &Constraint,
5583    state: &mut ParserStateMap,
5584    bytes: &[u8],
5585    bufs: &mut CommitBuffers,
5586    advances: Option<&mut Vec<PerAdvanceEntry>>,
5587    allow_fast_paths: bool,
5588) -> Result<CommitProfile, String> {
5589    expand_runtime_product_states(constraint, state);
5590    let result = commit_bytes_impl_profiled_inner(
5591        constraint,
5592        state,
5593        bytes,
5594        bufs,
5595        advances,
5596        allow_fast_paths,
5597    );
5598    if result.is_ok() {
5599        maybe_normalize_lookahead_invariant_reductions(constraint, state);
5600        coalesce_uniform_runtime_source_states(constraint, state);
5601    }
5602    result
5603}
5604
5605fn commit_bytes_impl_profiled_inner(
5606    constraint: &Constraint,
5607    state: &mut ParserStateMap,
5608    bytes: &[u8],
5609    bufs: &mut CommitBuffers,
5610    mut advances: Option<&mut Vec<PerAdvanceEntry>>,
5611    allow_fast_paths: bool,
5612) -> Result<CommitProfile, String> {
5613    // Profiling and the authoritative queue operate on the persistent map/GSS
5614    // representation, not the bounded duplicate-key flat frontier.
5615    state.normalize_duplicate_keys();
5616    use std::time::Instant;
5617
5618    let total_start = Instant::now();
5619    let mut profile = CommitProfile {
5620        n_tokenizer_states: state.len() as u64,
5621        ..CommitProfile::default()
5622    };
5623
5624    if bytes.is_empty() {
5625        profile.total_ns = total_start.elapsed().as_nanos() as u64;
5626        return Ok(profile);
5627    }
5628
5629    let ignore_terminal = constraint.ignore_terminal;
5630
5631    if allow_fast_paths
5632        && constraint.tokenizer_has_epsilon_transitions
5633        && state.len() == 1
5634    {
5635        let (&tokenizer_state, _) = state.iter().next().unwrap();
5636        let exec_start = Instant::now();
5637        let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
5638        let exec_elapsed = exec_start.elapsed().as_nanos() as u64;
5639        profile.initial_exec_ns = exec_elapsed;
5640        profile.exec_ns = exec_elapsed;
5641        profile.fast_path_tokenizer_exec_ns = exec_elapsed;
5642        if let Some(result) = commit_bytes_fast_path_profiled(
5643            constraint,
5644            state,
5645            bytes,
5646            tokenizer_state,
5647            &exec_result,
5648            advances.as_deref_mut(),
5649            &mut profile,
5650        ) {
5651            return result.map(|()| profile);
5652        }
5653    }
5654
5655    if allow_fast_paths && !constraint.tokenizer_has_epsilon_transitions && state.len() == 1 {
5656        let (&tokenizer_state, parser_gss) = state.iter().next().unwrap();
5657        if parser_gss.single_exclusive_top_value().is_some() {
5658            let direct_start = Instant::now();
5659            match commit_bytes_direct_linear_fast_path(
5660                constraint,
5661                parser_gss.clone(),
5662                bytes,
5663                tokenizer_state,
5664                Some(&mut profile),
5665            ) {
5666                Some(LinearFastPathResult::Complete(result)) => {
5667                    profile.linear_fast_path_total_ns = direct_start.elapsed().as_nanos() as u64;
5668                    let result = result.map(|final_gss| {
5669                        let update_start = Instant::now();
5670                        state.clear();
5671                        state.insert(constraint.runtime_commit_initial_state(), final_gss);
5672                        profile.linear_fast_path_state_update_ns +=
5673                            update_start.elapsed().as_nanos() as u64;
5674                        profile.total_ns = total_start.elapsed().as_nanos() as u64;
5675                        profile
5676                    });
5677                    return result;
5678                }
5679                Some(LinearFastPathResult::Continue { .. }) => {
5680                    unreachable!("direct linear fast path never returns Continue")
5681                }
5682                Some(LinearFastPathResult::Restart) | None => {
5683                    profile.failed_fast_path_probe_ns += direct_start.elapsed().as_nanos() as u64;
5684                }
5685            }
5686        }
5687
5688        let exec_start = Instant::now();
5689        let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
5690        let initial_exec_elapsed = exec_start.elapsed().as_nanos() as u64;
5691        profile.initial_exec_ns = initial_exec_elapsed;
5692        profile.exec_ns = initial_exec_elapsed;
5693        profile.fast_path_tokenizer_exec_ns = initial_exec_elapsed;
5694
5695        if allow_fast_paths {
5696            if let Some(result) = commit_bytes_fast_path_profiled(
5697                constraint,
5698                state,
5699                bytes,
5700                tokenizer_state,
5701                &exec_result,
5702                advances.as_deref_mut(),
5703                &mut profile,
5704            ) {
5705                let result = result.map(|()| profile);
5706                return result;
5707            }
5708
5709            let linear_eligibility_start = Instant::now();
5710            let linear_fast_path_eligible = !exec_result.end_state.iter().copied().any(|end_state| {
5711                    state
5712                        .values()
5713                        .next()
5714                        .is_some_and(|gss| end_state_may_advance(constraint, gss, end_state))
5715                });
5716            profile.linear_fast_path_eligibility_ns +=
5717                linear_eligibility_start.elapsed().as_nanos() as u64;
5718            if linear_fast_path_eligible {
5719                let linear_setup_start = Instant::now();
5720                let current_gss = state.values().next().unwrap();
5721                let start_gss = if current_gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()) {
5722                    current_gss.clone()
5723                } else {
5724                    prune_single_initial_state_for_exec(
5725                        constraint,
5726                        current_gss.clone(),
5727                        tokenizer_state,
5728                        &exec_result,
5729                        bytes,
5730                    )
5731                };
5732                if start_gss.is_empty() {
5733                    return Err("commit rejected: no valid parser states remain".to_string());
5734                }
5735                let mut linear_profile = profile.clone();
5736                let mut linear_advances = Vec::new();
5737                let linear_advances_sink = if advances.is_some() {
5738                    Some(&mut linear_advances)
5739                } else {
5740                    None
5741                };
5742                linear_profile.linear_fast_path_setup_ns +=
5743                    linear_setup_start.elapsed().as_nanos() as u64;
5744                match commit_bytes_linear_fast_path_profiled(
5745                    constraint,
5746                    start_gss,
5747                    bytes,
5748                    exec_result.clone(),
5749                    linear_advances_sink,
5750                    &mut linear_profile,
5751                ) {
5752                    LinearFastPathResult::Complete(result) => {
5753                        let result = result.map(|final_gss| {
5754                            if let Some(advances) = advances.as_deref_mut() {
5755                                advances.extend(linear_advances);
5756                            }
5757                            let update_start = Instant::now();
5758                            state.clear();
5759                            state.insert(constraint.runtime_commit_initial_state(), final_gss);
5760                            linear_profile.linear_fast_path_state_update_ns +=
5761                                update_start.elapsed().as_nanos() as u64;
5762                            linear_profile.total_ns = total_start.elapsed().as_nanos() as u64;
5763                            linear_profile
5764                        });
5765                        return result;
5766                    }
5767                    LinearFastPathResult::Continue { gss, offset } => {
5768                        profile = linear_profile;
5769                        if let Some(advances) = advances.as_deref_mut() {
5770                            advances.extend(linear_advances);
5771                        }
5772                        let update_start = Instant::now();
5773                        state.clear();
5774                        state.insert(constraint.runtime_commit_initial_state(), gss);
5775                        profile.linear_fast_path_state_update_ns +=
5776                            update_start.elapsed().as_nanos() as u64;
5777
5778                        let queue_start = Instant::now();
5779                        let needed_queue_len = bytes.len() + 1;
5780                        let mut pending_state = ParserStatesByTokenizer::default();
5781                        let mut processing_queue: Vec<ParserStatesByTokenizer> =
5782                            (0..needed_queue_len).map(|_| ParserStatesByTokenizer::default()).collect();
5783                        processing_queue[offset] = std::mem::take(state).into_iter().collect();
5784
5785                        let mut queue_offset = offset;
5786                        while queue_offset < needed_queue_len {
5787                            if processing_queue[queue_offset].is_empty() {
5788                                queue_offset += 1;
5789                                continue;
5790                            }
5791
5792                            let states_to_process = std::mem::take(&mut processing_queue[queue_offset]);
5793                            for (tokenizer_state, gss_at_offset) in states_to_process {
5794                                profile.n_queue_entries += 1;
5795
5796                                let actionable_start = Instant::now();
5797                                let actionable_terminals =
5798                                    ActionableTerminals::from_gss(constraint, &gss_at_offset);
5799                                profile.actionable_ns += actionable_start.elapsed().as_nanos() as u64;
5800
5801                                let exec_start = Instant::now();
5802                                let exec_result = execute_tokenizer_from_state_small(
5803                                    constraint,
5804                                    &bytes[queue_offset..],
5805                                    tokenizer_state,
5806                                );
5807                                let queue_exec_elapsed = exec_start.elapsed().as_nanos() as u64;
5808                                profile.queue_exec_ns += queue_exec_elapsed;
5809                                profile.exec_ns += queue_exec_elapsed;
5810
5811                                let match_start = Instant::now();
5812                                let normalized_matches = collect_unique_actionable_matches(
5813                                    constraint,
5814                                    actionable_terminals.as_ref(),
5815                                    ignore_terminal,
5816                                    &exec_result.matches,
5817                                    None,
5818                                );
5819                                profile.queue_match_ns += match_start.elapsed().as_nanos() as u64;
5820
5821                                for matched in normalized_matches {
5822                                    let new_offset = queue_offset + matched.width;
5823
5824                                    if matched.ignored {
5825                                        let enqueue_start = Instant::now();
5826                                        queue_parser_state(
5827                                            &mut processing_queue,
5828                                            &mut pending_state,
5829                                            new_offset,
5830                                            bytes.len(),
5831                                            constraint.runtime_commit_initial_state(),
5832                                            gss_at_offset.clone(),
5833                                        );
5834                                        profile.queue_enqueue_ns +=
5835                                            enqueue_start.elapsed().as_nanos() as u64;
5836                                        continue;
5837                                    }
5838
5839                                    let attempt = advance_parser_stacks_profiled_if_possible(
5840                                        constraint,
5841                                        &gss_at_offset,
5842                                        matched.terminal_id,
5843                                    );
5844                                    let may_elapsed = attempt.may_ns;
5845                                    let advance_core_elapsed = attempt.core_ns;
5846                                    profile.advance_may_check_ns += may_elapsed;
5847                                    profile.advance_core_ns += advance_core_elapsed;
5848                                    if attempt.advanced.is_empty() {
5849                                        continue;
5850                                    }
5851                                    let advanced_before_disallow = attempt.advanced;
5852                                    let advance_profile = attempt.profile;
5853                                    apply_advance_profile(&mut profile, &advance_profile);
5854
5855                                    if let Some(advances) = advances.as_deref_mut() {
5856                                        profile.adv_summary_ns += record_per_advance_entry(
5857                                            advances,
5858                                            tokenizer_state,
5859                                            matched.terminal_id,
5860                                            &gss_at_offset,
5861                                            &advanced_before_disallow,
5862                                            queue_offset,
5863                                            new_offset,
5864                                            bytes.len(),
5865                                            &bytes[queue_offset..new_offset],
5866                                            advance_profile.clone(),
5867                                        );
5868                                    }
5869
5870                                    let future_start = Instant::now();
5871                                    let advanced = apply_future_terminal_disallow(
5872                                        constraint,
5873                                        &exec_result,
5874                                        matched.terminal_id,
5875                                        advanced_before_disallow,
5876                                    );
5877                                    let future_elapsed = future_start.elapsed().as_nanos() as u64;
5878                                    profile.advance_future_disallow_ns += future_elapsed;
5879                                    profile.advance_ns +=
5880                                        may_elapsed + advance_core_elapsed + future_elapsed;
5881                                    profile.n_advances += 1;
5882
5883                                    if advanced.is_empty() {
5884                                        continue;
5885                                    }
5886
5887                                    let enqueue_start = Instant::now();
5888                                    queue_parser_state(
5889                                        &mut processing_queue,
5890                                        &mut pending_state,
5891                                        new_offset,
5892                                        bytes.len(),
5893                                        constraint.runtime_commit_initial_state(),
5894                                        advanced,
5895                                    );
5896                                    profile.queue_enqueue_ns += enqueue_start.elapsed().as_nanos() as u64;
5897                                }
5898
5899                                let may_start = Instant::now();
5900                                let admitted_end_state_terminals = batched_end_state_admitted_terminals(
5901                                    constraint,
5902                                    &gss_at_offset,
5903                                    &exec_result.end_state,
5904                                );
5905                                let batch_elapsed = may_start.elapsed().as_nanos() as u64;
5906                                profile.may_advance_ns += batch_elapsed;
5907                                for &end_state in &exec_result.end_state {
5908                                    let may_start = Instant::now();
5909                                    let may_advance = end_state_may_advance_with_batch(
5910                                        constraint,
5911                                        &gss_at_offset,
5912                                        end_state,
5913                                        admitted_end_state_terminals.as_ref(),
5914                                    );
5915                                    if admitted_end_state_terminals.is_none() {
5916                                        profile.may_advance_ns += may_start.elapsed().as_nanos() as u64;
5917                                    }
5918                                    if !may_advance {
5919                                        continue;
5920                                    }
5921
5922                                    let enqueue_start = Instant::now();
5923                                    queue_parser_state(
5924                                        &mut processing_queue,
5925                                        &mut pending_state,
5926                                        bytes.len(),
5927                                        bytes.len(),
5928                                        end_state,
5929                                        gss_at_offset.clone(),
5930                                    );
5931                                    profile.queue_enqueue_ns += enqueue_start.elapsed().as_nanos() as u64;
5932                                }
5933                            }
5934                            queue_offset += 1;
5935
5936                        }
5937
5938                        profile.queue_ns = queue_start.elapsed().as_nanos() as u64;
5939                        let queue_accounted_ns = profile
5940                            .actionable_ns
5941                            .saturating_add(profile.queue_exec_ns)
5942                            .saturating_add(profile.queue_match_ns)
5943                            .saturating_add(profile.advance_ns)
5944                            .saturating_add(profile.may_advance_ns)
5945                            .saturating_add(profile.queue_enqueue_ns);
5946                        profile.queue_bookkeeping_ns =
5947                            profile.queue_ns.saturating_sub(queue_accounted_ns);
5948
5949                        let fuse_start = Instant::now();
5950                        let new_state = finalize_pending_state(&mut pending_state);
5951                        profile.fuse_ns += fuse_start.elapsed().as_nanos() as u64;
5952
5953                        *state = new_state;
5954                        if state.is_empty() {
5955                            return Err("commit rejected: no valid parser states remain".to_string());
5956                        }
5957
5958                        profile.total_ns = total_start.elapsed().as_nanos() as u64;
5959                        return Ok(profile);
5960                    }
5961                    LinearFastPathResult::Restart => {
5962                        profile = linear_profile;
5963                    }
5964                }
5965            }
5966        }
5967    }
5968
5969    let scan_start = Instant::now();
5970    let mut initial_scan = InitialCommitScan::collect(constraint, state, bytes);
5971    profile.scan_ns = scan_start.elapsed().as_nanos() as u64;
5972
5973    let queue_start = Instant::now();
5974    let mut pending_state = ParserStatesByTokenizer::default();
5975    let mut processing_queue: Vec<ParserStatesByTokenizer> =
5976        (0..=bytes.len()).map(|_| ParserStatesByTokenizer::default()).collect();
5977    processing_queue[0] = std::mem::take(state).into_iter().collect();
5978
5979    let mut offset = 0usize;
5980    while offset < processing_queue.len() {
5981        if processing_queue[offset].is_empty() {
5982            offset += 1;
5983            continue;
5984        }
5985
5986        let states_to_process = std::mem::take(&mut processing_queue[offset]);
5987        for (tokenizer_state, mut gss_at_offset) in states_to_process {
5988            profile.n_queue_entries += 1;
5989
5990            let exec_start = Instant::now();
5991            let exec_result = if offset == 0 {
5992                initial_scan.take_exec_result(tokenizer_state).unwrap_or_else(|| {
5993                    execute_tokenizer_from_state_small(constraint, &bytes[offset..], tokenizer_state)
5994                })
5995            } else {
5996                execute_tokenizer_from_state_small(constraint, &bytes[offset..], tokenizer_state)
5997            };
5998            let queue_exec_elapsed = exec_start.elapsed().as_nanos() as u64;
5999            profile.queue_exec_ns += queue_exec_elapsed;
6000            profile.exec_ns += queue_exec_elapsed;
6001
6002            if offset == 0
6003                && !gss_at_offset
6004                    .all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
6005            {
6006                let prune_start = Instant::now();
6007                gss_at_offset = prune_single_initial_state_for_exec(
6008                    constraint,
6009                    gss_at_offset,
6010                    tokenizer_state,
6011                    &exec_result,
6012                    bytes,
6013                );
6014                profile.prune_ns += prune_start.elapsed().as_nanos() as u64;
6015                if gss_at_offset.is_empty() {
6016                    continue;
6017                }
6018            }
6019
6020            let actionable_start = Instant::now();
6021            let actionable_terminals = ActionableTerminals::from_gss(constraint, &gss_at_offset);
6022            profile.actionable_ns += actionable_start.elapsed().as_nanos() as u64;
6023
6024            let match_start = Instant::now();
6025            let normalized_matches = collect_unique_actionable_matches(
6026                constraint,
6027                actionable_terminals.as_ref(),
6028                ignore_terminal,
6029                &exec_result.matches,
6030                None,
6031            );
6032            profile.queue_match_ns += match_start.elapsed().as_nanos() as u64;
6033
6034            for matched in normalized_matches {
6035                let new_offset = offset + matched.width;
6036
6037                if matched.ignored {
6038                    let enqueue_start = Instant::now();
6039                    if !queue_parser_ignored_reset_state(
6040                        constraint,
6041                        &mut processing_queue,
6042                        &mut pending_state,
6043                        new_offset,
6044                        bytes.len(),
6045                        gss_at_offset.clone(),
6046                    ) {
6047                        panic!("recursive tokenizer reset routing failed");
6048                    }
6049                    profile.queue_enqueue_ns += enqueue_start.elapsed().as_nanos() as u64;
6050                    continue;
6051                }
6052
6053                let attempt = advance_parser_stacks_profiled_if_possible(
6054                    constraint,
6055                    &gss_at_offset,
6056                    matched.terminal_id,
6057                );
6058                let may_elapsed = attempt.may_ns;
6059                let advance_core_elapsed = attempt.core_ns;
6060                profile.advance_may_check_ns += may_elapsed;
6061                profile.advance_core_ns += advance_core_elapsed;
6062                if attempt.advanced.is_empty() {
6063                    continue;
6064                }
6065                let advanced_before_disallow = attempt.advanced;
6066                let advance_profile = attempt.profile;
6067                apply_advance_profile(&mut profile, &advance_profile);
6068
6069                if let Some(advances) = advances.as_deref_mut() {
6070                    profile.adv_summary_ns += record_per_advance_entry(
6071                        advances,
6072                        tokenizer_state,
6073                        matched.terminal_id,
6074                        &gss_at_offset,
6075                        &advanced_before_disallow,
6076                        offset,
6077                        new_offset,
6078                        bytes.len(),
6079                        &bytes[offset..new_offset],
6080                        advance_profile.clone(),
6081                    );
6082                }
6083
6084                let future_start = Instant::now();
6085                let advanced = apply_future_terminal_disallow(
6086                    constraint,
6087                    &exec_result,
6088                    matched.terminal_id,
6089                    advanced_before_disallow,
6090                );
6091                let future_elapsed = future_start.elapsed().as_nanos() as u64;
6092                profile.advance_future_disallow_ns += future_elapsed;
6093                profile.advance_ns += may_elapsed + advance_core_elapsed + future_elapsed;
6094                profile.n_advances += 1;
6095
6096                if advanced.is_empty() {
6097                    continue;
6098                }
6099
6100                let enqueue_start = Instant::now();
6101                if !queue_parser_reset_state(
6102                    constraint,
6103                    &mut processing_queue,
6104                    &mut pending_state,
6105                    new_offset,
6106                    bytes.len(),
6107                    advanced,
6108                ) {
6109                    panic!("recursive tokenizer reset routing failed");
6110                }
6111                profile.queue_enqueue_ns += enqueue_start.elapsed().as_nanos() as u64;
6112            }
6113
6114            let may_start = Instant::now();
6115            let admitted_end_state_terminals = batched_end_state_admitted_terminals(
6116                constraint,
6117                &gss_at_offset,
6118                &exec_result.end_state,
6119            );
6120            profile.may_advance_ns += may_start.elapsed().as_nanos() as u64;
6121            for &end_state in &exec_result.end_state {
6122                let may_start = Instant::now();
6123                let may_advance = end_state_may_advance_with_batch(
6124                    constraint,
6125                    &gss_at_offset,
6126                    end_state,
6127                    admitted_end_state_terminals.as_ref(),
6128                );
6129                if admitted_end_state_terminals.is_none() {
6130                    profile.may_advance_ns += may_start.elapsed().as_nanos() as u64;
6131                }
6132                if !may_advance {
6133                    continue;
6134                }
6135
6136                let enqueue_start = Instant::now();
6137                queue_parser_state(
6138                    &mut processing_queue,
6139                    &mut pending_state,
6140                    bytes.len(),
6141                    bytes.len(),
6142                    end_state,
6143                    gss_at_offset.clone(),
6144                );
6145                profile.queue_enqueue_ns += enqueue_start.elapsed().as_nanos() as u64;
6146            }
6147        }
6148        offset += 1;
6149    }
6150    profile.queue_ns = queue_start.elapsed().as_nanos() as u64;
6151    let queue_accounted_ns = profile
6152        .actionable_ns
6153        .saturating_add(profile.queue_exec_ns)
6154        .saturating_add(profile.queue_match_ns)
6155        .saturating_add(profile.advance_ns)
6156        .saturating_add(profile.may_advance_ns)
6157        .saturating_add(profile.queue_enqueue_ns);
6158    profile.queue_bookkeeping_ns = profile.queue_ns.saturating_sub(queue_accounted_ns);
6159
6160    let fuse_start = Instant::now();
6161
6162    let new_state = finalize_pending_state(&mut pending_state);
6163    profile.fuse_ns = fuse_start.elapsed().as_nanos() as u64;
6164
6165    *state = new_state;
6166    if state.is_empty() {
6167        return Err("commit rejected: no valid parser states remain".to_string());
6168    }
6169
6170    profile.total_ns = total_start.elapsed().as_nanos() as u64;
6171    Ok(profile)
6172}
6173
6174fn final_stacks(state: &ParserStateMap) -> Vec<(u32, Vec<Vec<u32>>)> {
6175    let mut grouped = BTreeMap::<u32, Vec<Vec<u32>>>::new();
6176    for (&tokenizer_state, gss) in state.iter() {
6177        grouped
6178            .entry(tokenizer_state)
6179            .or_default()
6180            .extend(parser_stacks_only(gss));
6181    }
6182    for stacks in grouped.values_mut() {
6183        stacks.sort();
6184        stacks.dedup();
6185    }
6186    grouped.into_iter().collect()
6187}
6188
6189fn clear_state_on_commit_error<T>(
6190    state: &mut ParserStateMap,
6191    result: Result<T, String>,
6192) -> Result<T, String> {
6193    if result.is_err() {
6194        state.clear();
6195    }
6196    result
6197}
6198
6199#[inline]
6200fn commit_bytes_linear_fast_path(
6201    constraint: &Constraint,
6202    start_gss: ParserGSS,
6203    bytes: &[u8],
6204    first_exec_result: TokenizerExecResult,
6205) -> LinearFastPathResult {
6206    commit_bytes_linear_fast_path_observed(constraint, start_gss, bytes, first_exec_result, &mut NoMarkers)
6207}
6208
6209fn commit_bytes_linear_fast_path_observed<O: CommitObserver>(
6210    constraint: &Constraint,
6211    start_gss: ParserGSS,
6212    bytes: &[u8],
6213    first_exec_result: TokenizerExecResult,
6214    observer: &mut O,
6215) -> LinearFastPathResult {
6216    let marker_checkpoint = observer.checkpoint();
6217    let result = (|| {
6218    let ignore_terminal = constraint.ignore_terminal;
6219    let mut gss = start_gss;
6220    let mut carried_stack = gss.try_virtual_stack();
6221    let mut offset = 0usize;
6222    let mut exec_result = first_exec_result;
6223
6224    loop {
6225        let actionable_terminals = if let Some(stack) = carried_stack.as_ref() {
6226            stack.top().copied().map(ActionableTerminals::SingleState)
6227        } else {
6228            ActionableTerminals::from_gss(constraint, &gss)
6229        };
6230        let mut chosen: Option<(usize, u32, bool)> = None;
6231
6232        for matched in &exec_result.matches {
6233            let ignored = is_ignored_terminal(ignore_terminal, matched.id);
6234            if !ignored
6235                && !is_actionable_terminal(
6236                    actionable_terminals.as_ref(),
6237                    constraint,
6238                    matched.id,
6239                )
6240            {
6241                continue;
6242            }
6243
6244            let candidate = (matched.width, matched.id, ignored);
6245            if let Some(existing) = chosen {
6246                if existing != candidate {
6247                    return if offset > 0 {
6248                        LinearFastPathResult::Continue { gss, offset }
6249                    } else {
6250                        LinearFastPathResult::Restart
6251                    };
6252                }
6253            } else {
6254                chosen = Some(candidate);
6255            }
6256        }
6257
6258        let Some((width, terminal, ignored)) = chosen else {
6259            return if offset > 0 {
6260                LinearFastPathResult::Continue { gss, offset }
6261            } else {
6262                LinearFastPathResult::Restart
6263            };
6264        };
6265
6266        if exec_result.end_state.len() > 1 {
6267            return if offset > 0 {
6268                LinearFastPathResult::Continue { gss, offset }
6269            } else {
6270                LinearFastPathResult::Restart
6271            };
6272        }
6273        if let Some(end_state) = exec_result.end_state.first().copied()
6274            && let Some(stack) = carried_stack.as_ref()
6275        {
6276            let keep_carried = stack.top().copied().is_some_and(|top_state| {
6277                end_state != constraint.runtime_commit_initial_state()
6278                    && !constraint.parser_advance_row_intersects(
6279                        top_state,
6280                        constraint.tokenizer.possible_future_terminals(end_state),
6281                    )
6282                    && !constraint
6283                        .tokenizer
6284                        .possible_future_terminals(end_state)
6285                        .contains(terminal as usize)
6286            });
6287            if !keep_carried {
6288                gss = carried_stack.take().unwrap().into_gss();
6289            }
6290        }
6291
6292        if let Some(end_state) = exec_result.end_state.first().copied()
6293            && end_state_may_advance(constraint, &gss, end_state) {
6294                return if offset > 0 {
6295                    LinearFastPathResult::Continue { gss, offset }
6296                } else {
6297                    LinearFastPathResult::Restart
6298                };
6299            }
6300
6301        if !ignored {
6302            let mut shifted_carried_stack = false;
6303            if !template_advance_selected(constraint)
6304                && let Some(stack) = carried_stack.as_mut()
6305                && let Some(top_state) = stack.top().copied()
6306                && let Some(Action::Shift(target, is_replace)) = constraint.table.action(top_state, terminal)
6307                && exec_result.end_state.iter().copied().all(|end_state| {
6308                    end_state != constraint.runtime_commit_initial_state()
6309                        && !constraint.parser_advance_row_intersects(
6310                            top_state,
6311                            constraint.tokenizer.possible_future_terminals(end_state),
6312                        )
6313                        && !constraint
6314                            .tokenizer
6315                            .possible_future_terminals(end_state)
6316                            .contains(terminal as usize)
6317                })
6318            {
6319                if *is_replace {
6320                    if stack.replace_top(*target) {
6321                        shifted_carried_stack = true;
6322                    }
6323                } else {
6324                    stack.push(*target);
6325                    shifted_carried_stack = true;
6326                }
6327            }
6328
6329            if shifted_carried_stack {
6330                offset += width;
6331                if let Some(stack) = carried_stack.as_ref() { observer.carried(constraint, stack, offset); }
6332                else { observer.stack(constraint, &gss, offset); }
6333                if offset == bytes.len() {
6334                    gss = carried_stack.take().unwrap().into_gss();
6335                    let fused = if constraint.direct_regular_wide_frontier_for_gss(&gss).is_some() {
6336                        gss
6337                    } else {
6338                        gss.fuse(Some(1))
6339                    };
6340                    if fused.is_empty() {
6341                        return LinearFastPathResult::Complete(Err(
6342                            "commit rejected: no valid parser states remain".to_string(),
6343                        ));
6344                    }
6345                    return LinearFastPathResult::Complete(Ok(fused));
6346                }
6347
6348                exec_result = execute_tokenizer_from_state_small(
6349                    constraint,
6350                    &bytes[offset..],
6351                    constraint.runtime_commit_initial_state(),
6352                );
6353                continue;
6354            }
6355
6356            if let Some(stack) = carried_stack.take() {
6357                gss = stack.into_gss();
6358            }
6359
6360            let fast_advanced = if !template_advance_selected(constraint)
6361                && let Some(top_state) = gss.single_exclusive_top_value()
6362                && let Some(action) = constraint.table.action(top_state, terminal)
6363            {
6364                apply_single_top_action_fast(
6365                    constraint,
6366                    &gss,
6367                    top_state,
6368                    terminal,
6369                    action,
6370                )
6371            } else {
6372                None
6373            };
6374
6375            let advanced = if let Some(advanced) = fast_advanced {
6376                advanced
6377            } else {
6378                let advanced = advance_parser_stacks(constraint, &gss, terminal);
6379                if advanced.is_empty() {
6380                    return if offset > 0 {
6381                        LinearFastPathResult::Continue { gss, offset }
6382                    } else {
6383                        LinearFastPathResult::Restart
6384                    };
6385                }
6386                advanced
6387            };
6388            if advanced.is_empty() {
6389                return LinearFastPathResult::Complete(Err(
6390                    "commit rejected: no valid parser states remain".to_string(),
6391                ));
6392            }
6393            gss = apply_future_terminal_disallow(constraint, &exec_result, terminal, advanced);
6394            if gss.is_empty() {
6395                return LinearFastPathResult::Complete(Err(
6396                    "commit rejected: no valid parser states remain".to_string(),
6397                ));
6398            }
6399        }
6400
6401        offset += width;
6402                if let Some(stack) = carried_stack.as_ref() { observer.carried(constraint, stack, offset); }
6403                else { observer.stack(constraint, &gss, offset); }
6404        if offset == bytes.len() {
6405            if let Some(stack) = carried_stack.take() {
6406                gss = stack.into_gss();
6407            }
6408            let fused = if constraint.direct_regular_wide_frontier_for_gss(&gss).is_some() {
6409                gss
6410            } else {
6411                gss.fuse(Some(1))
6412            };
6413            if fused.is_empty() {
6414                return LinearFastPathResult::Complete(Err(
6415                    "commit rejected: no valid parser states remain".to_string(),
6416                ));
6417            }
6418            return LinearFastPathResult::Complete(Ok(fused));
6419        }
6420
6421        exec_result = execute_tokenizer_from_state_small(
6422            constraint,
6423            &bytes[offset..],
6424            constraint.runtime_commit_initial_state(),
6425        );
6426    }
6427
6428    })();
6429    if matches!(&result, LinearFastPathResult::Restart) { observer.rewind(marker_checkpoint); }
6430    result
6431}
6432
6433fn commit_bytes_linear_fast_path_profiled(
6434    constraint: &Constraint,
6435    start_gss: ParserGSS,
6436    bytes: &[u8],
6437    first_exec_result: TokenizerExecResult,
6438    mut advances: Option<&mut Vec<PerAdvanceEntry>>,
6439    profile: &mut CommitProfile,
6440) -> LinearFastPathResult {
6441    use std::time::Instant;
6442
6443    let total_start = Instant::now();
6444    let ignore_terminal = constraint.ignore_terminal;
6445    let mut gss = start_gss;
6446    let mut offset = 0usize;
6447    let mut exec_result = first_exec_result;
6448    profile.linear_fast_path_exec_ns = profile.initial_exec_ns;
6449
6450    loop {
6451        profile.linear_fast_path_steps += 1;
6452
6453        let scan_start = Instant::now();
6454        let actionable_terminals = ActionableTerminals::from_gss(constraint, &gss);
6455        let mut chosen: Option<(usize, u32, bool)> = None;
6456        for matched in &exec_result.matches {
6457            let ignored = is_ignored_terminal(ignore_terminal, matched.id);
6458            if !ignored
6459                && !is_actionable_terminal(
6460                    actionable_terminals.as_ref(),
6461                    constraint,
6462                    matched.id,
6463                )
6464            {
6465                continue;
6466            }
6467
6468            let candidate = (matched.width, matched.id, ignored);
6469            if let Some(existing) = chosen {
6470                if existing != candidate {
6471                    let result = if offset > 0 {
6472                        LinearFastPathResult::Continue { gss, offset }
6473                    } else {
6474                        LinearFastPathResult::Restart
6475                    };
6476                    profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6477                    return result;
6478                }
6479            } else {
6480                chosen = Some(candidate);
6481            }
6482        }
6483        profile.linear_fast_path_match_scan_ns += scan_start.elapsed().as_nanos() as u64;
6484
6485        let Some((width, terminal, ignored)) = chosen else {
6486            let result = if offset > 0 {
6487                LinearFastPathResult::Continue { gss, offset }
6488            } else {
6489                LinearFastPathResult::Restart
6490            };
6491            profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6492            return result;
6493        };
6494
6495        let end_state_start = Instant::now();
6496        if exec_result.end_state.len() > 1 {
6497            profile.linear_fast_path_end_state_check_ns +=
6498                end_state_start.elapsed().as_nanos() as u64;
6499            profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6500            return if offset > 0 {
6501                LinearFastPathResult::Continue { gss, offset }
6502            } else {
6503                LinearFastPathResult::Restart
6504            };
6505        }
6506        if let Some(end_state) = exec_result.end_state.first().copied()
6507            && end_state_may_advance(constraint, &gss, end_state) {
6508                profile.linear_fast_path_end_state_check_ns +=
6509                    end_state_start.elapsed().as_nanos() as u64;
6510                let result = if offset > 0 {
6511                    LinearFastPathResult::Continue { gss, offset }
6512                } else {
6513                    LinearFastPathResult::Restart
6514                };
6515                profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6516                return result;
6517            }
6518        profile.linear_fast_path_end_state_check_ns +=
6519            end_state_start.elapsed().as_nanos() as u64;
6520
6521        if !ignored {
6522            let fast_start = Instant::now();
6523            let fast_advanced = if !template_advance_selected(constraint)
6524                && let Some(top_state) = gss.single_exclusive_top_value()
6525                && let Some(action) = constraint.table.action(top_state, terminal)
6526                && let Some(advanced) =
6527                    apply_single_top_action_fast(
6528                        constraint,
6529                        &gss,
6530                        top_state,
6531                        terminal,
6532                        action,
6533                    )
6534            {
6535                let elapsed = fast_start.elapsed().as_nanos() as u64;
6536                Some((advanced, fast_action_advance_profile(&gss, action, elapsed)))
6537            } else {
6538                None
6539            };
6540
6541            let (advanced, advance_profile, advance_elapsed) =
6542                if let Some((advanced, advance_profile)) = fast_advanced {
6543                    let advance_elapsed = advance_profile.total_ns;
6544                    (advanced, advance_profile, advance_elapsed)
6545                } else {
6546                    let advance_start = Instant::now();
6547                    let (advanced, advance_profile) =
6548                        advance_parser_stacks_profiled(constraint, &gss, terminal);
6549                    let advance_elapsed = advance_start.elapsed().as_nanos() as u64;
6550                    if advanced.is_empty() {
6551                        profile.advance_core_ns += advance_elapsed;
6552                        let result = if offset > 0 {
6553                            LinearFastPathResult::Continue { gss, offset }
6554                        } else {
6555                            LinearFastPathResult::Restart
6556                        };
6557                        profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6558                        return result;
6559                    }
6560                    (advanced, advance_profile, advance_elapsed)
6561                };
6562            profile.advance_core_ns += advance_profile.total_ns;
6563            profile.linear_fast_path_advance_ns += advance_profile.total_ns;
6564            apply_advance_profile(profile, &advance_profile);
6565
6566            if advanced.is_empty() {
6567                profile.advance_ns += advance_elapsed;
6568                profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6569                return LinearFastPathResult::Complete(Err(
6570                    "commit rejected: no valid parser states remain".to_string(),
6571                ));
6572            }
6573
6574            if let Some(advances) = advances.as_deref_mut() {
6575                let summary_ns = record_per_advance_entry(
6576                    advances,
6577                    constraint.runtime_commit_initial_state(),
6578                    terminal,
6579                    &gss,
6580                    &advanced,
6581                    offset,
6582                    offset + width,
6583                    bytes.len(),
6584                    &bytes[offset..offset + width],
6585                    advance_profile.clone(),
6586                );
6587                profile.adv_summary_ns += summary_ns;
6588            }
6589
6590            let future_start = Instant::now();
6591            gss = apply_future_terminal_disallow(constraint, &exec_result, terminal, advanced);
6592            let future_elapsed = future_start.elapsed().as_nanos() as u64;
6593            profile.advance_future_disallow_ns += future_elapsed;
6594            profile.linear_fast_path_future_disallow_ns += future_elapsed;
6595            profile.linear_fast_path_advance_ns += future_elapsed;
6596            profile.advance_ns += advance_elapsed + future_elapsed;
6597            profile.n_advances += 1;
6598            if gss.is_empty() {
6599                profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6600                return LinearFastPathResult::Complete(Err(
6601                    "commit rejected: no valid parser states remain".to_string(),
6602                ));
6603            }
6604        }
6605
6606        offset += width;
6607        if offset == bytes.len() {
6608            let fuse_start = Instant::now();
6609            let fused = gss.fuse(Some(1));
6610            profile.linear_fast_path_fuse_ns = fuse_start.elapsed().as_nanos() as u64;
6611            profile.fuse_ns = profile.linear_fast_path_fuse_ns;
6612            profile.linear_fast_path_total_ns = total_start.elapsed().as_nanos() as u64;
6613            if fused.is_empty() {
6614                return LinearFastPathResult::Complete(Err(
6615                    "commit rejected: no valid parser states remain".to_string(),
6616                ));
6617            }
6618            return LinearFastPathResult::Complete(Ok(fused));
6619        }
6620
6621        let exec_start = Instant::now();
6622        exec_result = execute_tokenizer_from_state_small(
6623            constraint,
6624            &bytes[offset..],
6625            constraint.runtime_commit_initial_state(),
6626        );
6627        let exec_elapsed = exec_start.elapsed().as_nanos() as u64;
6628        profile.linear_fast_path_exec_ns += exec_elapsed;
6629        profile.exec_ns += exec_elapsed;
6630    }
6631}
6632
6633fn apply_flat_reduce(
6634    constraint: &Constraint,
6635    stack: &mut FlatInlineStack,
6636    nonterminal: u32,
6637    len: u32,
6638) -> Option<bool> {
6639    let pop = len as usize;
6640    if pop >= stack.len() {
6641        return Some(false);
6642    }
6643    stack.truncate(stack.len() - pop);
6644    let goto_from = *stack.last()?;
6645    let (target, replace) = constraint.table.goto_target(goto_from, nonterminal)?;
6646    if replace {
6647        *stack.last_mut()? = target;
6648    } else {
6649        if stack.len() == LINEAR_STACK_RESERVE {
6650            return None;
6651        }
6652        stack.push(target);
6653    }
6654    Some(true)
6655}
6656
6657fn apply_flat_shift(
6658    stack: &mut FlatInlineStack,
6659    target: u32,
6660    replace: bool,
6661) -> Option<bool> {
6662    if replace {
6663        *stack.last_mut()? = target;
6664    } else {
6665        if stack.len() == LINEAR_STACK_RESERVE {
6666            return None;
6667        }
6668        stack.push(target);
6669    }
6670    Some(true)
6671}
6672
6673fn apply_flat_stack_effect(
6674    stack: &mut FlatInlineStack,
6675    pop: u32,
6676    pushes: &[u32],
6677) -> Option<bool> {
6678    let pop = pop as usize;
6679    // Stack effects are atomic: popping the final visible state is valid when
6680    // the same effect pushes a replacement. Only a true underflow is invalid.
6681    if pop > stack.len() {
6682        return Some(false);
6683    }
6684    let new_len = stack.len() - pop + pushes.len();
6685    if new_len > LINEAR_STACK_RESERVE {
6686        return None;
6687    }
6688    stack.truncate(stack.len() - pop);
6689    stack.extend_from_slice(pushes);
6690    Some(true)
6691}
6692
6693fn flat_guard_matches(stack: &[u32], guard: &crate::compiler::glr::table::StackShiftGuard) -> bool {
6694    let pop = guard.pop as usize;
6695    pop < stack.len()
6696        && guard
6697            .states
6698            .iter()
6699            .any(|state| *state == stack[stack.len() - 1 - pop])
6700}
6701
6702/// Apply one terminal to one concrete LR stack, retaining a bounded set of
6703/// exact concrete outcomes. This is the small-ambiguity counterpart to the
6704/// persistent GSS interpreter: no heap allocation is permitted, and any
6705/// capacity overflow or accept-state edge declines to the authoritative path.
6706fn apply_terminal_to_flat_stacks(
6707    constraint: &Constraint,
6708    terminal: u32,
6709    source: &[u32],
6710    scratch: &mut FlatActionScratch,
6711) -> Option<bool> {
6712    if let Some(parser) = constraint.template_parser.as_ref() {
6713        let fast = constraint.fast_template_dfas_by_terminal.get(terminal as usize)?.as_ref()?;
6714        let result = flat_template::apply(fast, source, scratch);
6715        if result.is_some() { parser.record_advance(); }
6716        return result;
6717    }
6718
6719    if source.is_empty() || source.len() > LINEAR_STACK_RESERVE {
6720        return None;
6721    }
6722    scratch.clear();
6723    let mut initial = FlatInlineStack::new();
6724    initial.extend_from_slice(source);
6725    if !scratch.push_pending(initial) {
6726        return None;
6727    }
6728
6729    let mut steps = 0usize;
6730    while let Some(mut stack) = scratch.pending.pop() {
6731        steps += 1;
6732        if steps > FLAT_ACTION_MAX_STEPS {
6733            return None;
6734        }
6735        let top = *stack.last()?;
6736        match constraint.table.action(top, terminal)? {
6737            Action::Skip => {
6738                if !scratch.push_complete(stack) {
6739                    return None;
6740                }
6741            }
6742            Action::Shift(target, replace) => {
6743                if apply_flat_shift(&mut stack, *target, *replace)?
6744                    && !scratch.push_complete(stack)
6745                {
6746                    return None;
6747                }
6748            }
6749            Action::ReplaceShifts(targets) => {
6750                for &target in targets.iter() {
6751                    let mut candidate = stack.clone();
6752                    if apply_flat_stack_effect(&mut candidate, 1, &[target])?
6753                        && !scratch.push_complete(candidate)
6754                    {
6755                        return None;
6756                    }
6757                }
6758            }
6759            Action::StackShifts(shifts) => {
6760                for shift in shifts {
6761                    let mut candidate = stack.clone();
6762                    if apply_flat_stack_effect(&mut candidate, shift.pop, &shift.pushes)?
6763                        && !scratch.push_complete(candidate)
6764                    {
6765                        return None;
6766                    }
6767                }
6768            }
6769            Action::GuardedStackShifts(shifts) => {
6770                for shift in shifts {
6771                    if !shift.guards.iter().all(|guard| flat_guard_matches(&stack, guard)) {
6772                        continue;
6773                    }
6774                    let mut candidate = stack.clone();
6775                    if apply_flat_stack_effect(&mut candidate, shift.pop, &shift.pushes)?
6776                        && !scratch.push_complete(candidate)
6777                    {
6778                        return None;
6779                    }
6780                }
6781            }
6782            Action::Reduce(nonterminal, len) => {
6783                if apply_flat_reduce(constraint, &mut stack, *nonterminal, *len)?
6784                    && !scratch.push_pending(stack)
6785                {
6786                    return None;
6787                }
6788            }
6789            Action::Split {
6790                shift,
6791                reduces,
6792                accept,
6793            } => {
6794                if *accept {
6795                    return None;
6796                }
6797                if let Some((target, replace)) = shift {
6798                    let mut candidate = stack.clone();
6799                    if apply_flat_shift(&mut candidate, *target, *replace)?
6800                        && !scratch.push_complete(candidate)
6801                    {
6802                        return None;
6803                    }
6804                }
6805                for &(nonterminal, len) in reduces {
6806                    let mut candidate = stack.clone();
6807                    if apply_flat_reduce(constraint, &mut candidate, nonterminal, len)?
6808                        && !scratch.push_pending(candidate)
6809                    {
6810                        return None;
6811                    }
6812                }
6813            }
6814            Action::Accept => return None,
6815        }
6816    }
6817    Some(!scratch.complete.is_empty())
6818}
6819
6820fn flat_stack_may_advance_on_any(
6821    constraint: &Constraint,
6822    stack: &[u32],
6823    terminals: &crate::ds::bitset::BitSet,
6824    scratch: &mut FlatActionScratch,
6825) -> Option<bool> {
6826    if let Some(parser) = constraint.template_parser.as_ref() {
6827        if runtime_future_contains_ignore(constraint, terminals) {
6828            return Some(true);
6829        }
6830        return Some(parser.admits_flat_any(stack, terminals));
6831    }
6832    let top = *stack.last()?;
6833    if runtime_future_contains_ignore(constraint, terminals) {
6834        return Some(true);
6835    }
6836    if constraint.parser_admission_policy() == AdmissionPolicy::RowPresenceExact {
6837        return Some(constraint.parser_advance_row_intersects(top, terminals));
6838    }
6839
6840    let mut unknown = false;
6841    for terminal in terminals.iter() {
6842        match apply_terminal_to_flat_stacks(constraint, terminal as u32, stack, scratch) {
6843            Some(true) => return Some(true),
6844            Some(false) => {}
6845            None => unknown = true,
6846        }
6847    }
6848    (!unknown).then_some(false)
6849}
6850
6851fn flat_frontier_group_may_advance_on_any(
6852    constraint: &Constraint,
6853    branches: &[FlatBranchScratch],
6854    offset: usize,
6855    tokenizer_state: u32,
6856    terminals: &crate::ds::bitset::BitSet,
6857    scratch: &mut FlatActionScratch,
6858) -> Option<bool> {
6859    let mut saw_branch = false;
6860    let mut unknown = false;
6861    for branch in branches {
6862        if branch.offset != offset || branch.tokenizer_state != tokenizer_state {
6863            continue;
6864        }
6865        saw_branch = true;
6866        match flat_stack_may_advance_on_any(
6867            constraint,
6868            &branch.stack,
6869            terminals,
6870            scratch,
6871        ) {
6872            Some(true) => return Some(true),
6873            Some(false) => {}
6874            None => unknown = true,
6875        }
6876    }
6877
6878    if !saw_branch {
6879        Some(false)
6880    } else if unknown {
6881        None
6882    } else {
6883        Some(false)
6884    }
6885}
6886
6887fn prune_flat_branch_acc(
6888    constraint: &Constraint,
6889    acc: &TerminalsDisallowed,
6890    tokenizer_state: u32,
6891    end_states: &[u32],
6892    matches: &[TokenizerMatch],
6893    bytes: &[u8],
6894) -> Option<Option<TerminalsDisallowed>> {
6895    if !acc.is_inline() {
6896        return None;
6897    }
6898    match advance_terminals_disallowed_over_bytes(
6899        constraint,
6900        acc,
6901        bytes,
6902        Some((tokenizer_state, end_states, matches)),
6903    ) {
6904        None => Some(None),
6905        Some(remapped) if remapped.is_inline() => Some(Some(remapped)),
6906        Some(_) => None,
6907    }
6908}
6909
6910fn apply_flat_future_disallow(
6911    constraint: &Constraint,
6912    acc: &TerminalsDisallowed,
6913    end_states: &[u32],
6914    terminal: u32,
6915) -> Option<TerminalsDisallowed> {
6916    let mut updated = acc.clone();
6917    for &end_state in end_states {
6918        if constraint
6919            .tokenizer
6920            .possible_future_terminals(end_state)
6921            .contains(terminal as usize)
6922        {
6923            updated = updated.try_with_insert_inline(end_state, terminal)?;
6924        }
6925    }
6926    Some(updated)
6927}
6928
6929/// Advance a bounded multi-state lexer frontier without rebuilding parser GSSs.
6930///
6931/// This covers tokens that only move the tokenizer while every parser stack and
6932/// accumulator remains unchanged.  The general queue used to materialize fresh
6933/// GSS objects for this case, even when a wide frontier merely carried shared
6934/// parser stacks under new tokenizer-state keys.  Reusing Arc-backed GSS values
6935/// is exact and allocation-free; duplicate tokenizer keys remain explicit until
6936/// a later map-only operation requests normalization.
6937fn try_commit_multi_state_lexer_only(
6938    constraint: &Constraint,
6939    state: &mut ParserStateMap,
6940    bytes: &[u8],
6941    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
6942    frontier: &mut FlatFrontierScratch,
6943    stack_scratch: &mut Vec<u32>,
6944    admission_cache: &mut SmallVec<[ParserAdmissionCacheEntry; 8]>,
6945) -> Option<Result<(), String>> {
6946    if state.len() <= 1
6947        || state.len() > INLINE_PARSER_STATE_CAPACITY
6948        || bytes.is_empty()
6949        || state_has_nonempty_accumulators(state)
6950    {
6951        return None;
6952    }
6953
6954    let mut output = SmallVec::<[(u32, usize); INLINE_PARSER_STATE_CAPACITY]>::new();
6955    // The answer depends on BOTH the parser language and the matches produced
6956    // by this lexer lane. Two lexer states can share one immutable GSS while
6957    // producing different terminal matches for the same bytes.
6958    let mut actionable_cache =
6959        SmallVec::<[(usize, u32, bool); INLINE_PARSER_STATE_CAPACITY]>::new();
6960    let mut input_index = 0usize;
6961    while input_index < state.entries.len() {
6962        let tokenizer_state = state.entries[input_index].0;
6963        let group_end = state.entries[input_index..]
6964            .partition_point(|(candidate, _)| *candidate == tokenizer_state)
6965            + input_index;
6966
6967        if !execute_tokenizer_reusable(
6968            constraint,
6969            bytes,
6970            tokenizer_state,
6971            tokenizer_scratch,
6972        ) {
6973            return None;
6974        }
6975
6976        if tokenizer_scratch
6977            .matches
6978            .iter()
6979            .any(|matched| is_ignored_terminal(constraint.ignore_terminal, matched.id))
6980        {
6981            return None;
6982        }
6983
6984        for (relative_index, (_, gss)) in state.entries[input_index..group_end].iter().enumerate() {
6985            let source_index = input_index + relative_index;
6986            let gss_key = gss.ptr_key();
6987            if !tokenizer_scratch.matches.is_empty() {
6988                let has_actionable_match = actionable_cache
6989                    .iter()
6990                    .find_map(|&(cached_gss, cached_lexer, cached_result)| {
6991                        (cached_gss == gss_key && cached_lexer == tokenizer_state)
6992                            .then_some(cached_result)
6993                    })
6994                    .unwrap_or_else(|| {
6995                        let actionable = ActionableTerminals::from_gss(constraint, gss);
6996                        let result = tokenizer_scratch.matches.iter().any(|matched| {
6997                            is_actionable_terminal(actionable.as_ref(), constraint, matched.id)
6998                        });
6999                        if actionable_cache.len() < actionable_cache.capacity() {
7000                            actionable_cache.push((gss_key, tokenizer_state, result));
7001                        }
7002                        result
7003                    });
7004                if has_actionable_match {
7005                    return None;
7006                }
7007            }
7008
7009            let admission_cache_index = cached_batched_end_state_admission(
7010                constraint,
7011                gss,
7012                &tokenizer_scratch.states,
7013                admission_cache,
7014            );
7015            for &end_state in &tokenizer_scratch.states {
7016                let may_advance = if let Some(index) = admission_cache_index {
7017                    end_state_may_advance_from_cache_entry(
7018                        constraint,
7019                        end_state,
7020                        &admission_cache[index],
7021                    )
7022                } else {
7023                    cached_single_end_state_may_advance(
7024                        constraint,
7025                        gss,
7026                        end_state,
7027                        admission_cache,
7028                    )
7029                };
7030                if !may_advance {
7031                    continue;
7032                }
7033                if output.len() == output.capacity() {
7034                    return None;
7035                }
7036                output.push((end_state, source_index));
7037            }
7038        }
7039
7040        input_index = group_end;
7041    }
7042
7043    if output.is_empty() {
7044        return Some(Err(
7045            "commit rejected: no valid parser states remain".to_string(),
7046        ));
7047    }
7048    output.sort_unstable_by_key(|(tokenizer_state, _)| *tokenizer_state);
7049    let mut remaining_uses = [0u8; INLINE_PARSER_STATE_CAPACITY];
7050    for &(_, source_index) in &output {
7051        remaining_uses[source_index] = remaining_uses[source_index].saturating_add(1);
7052    }
7053    frontier.reclaim_retired_gss();
7054    let mut remaining_for_assignment = remaining_uses;
7055    let mut used_pool = [false; FLAT_FRONTIER_GSS_POOL_CAPACITY];
7056    let mut pool_assignment =
7057        SmallVec::<[usize; INLINE_PARSER_STATE_CAPACITY]>::new();
7058    for &(_, source_index) in &output {
7059        if remaining_for_assignment[source_index] <= 1 {
7060            pool_assignment.push(usize::MAX);
7061            remaining_for_assignment[source_index] = 0;
7062            continue;
7063        }
7064        let source_gss = &state.entries[source_index].1;
7065        if !source_gss.copy_single_path_stack_into(stack_scratch) {
7066            return None;
7067        }
7068        source_gss.single_path_acc()?;
7069        let pool_index = frontier
7070            .gss_pool
7071            .iter()
7072            .enumerate()
7073            .position(|(pool_index, gss)| {
7074                !used_pool[pool_index]
7075                    && gss.can_replace_single_path_state_in_place(stack_scratch)
7076            })?;
7077        used_pool[pool_index] = true;
7078        pool_assignment.push(pool_index);
7079        remaining_for_assignment[source_index] -= 1;
7080    }
7081
7082    let mut old_entries = std::mem::take(&mut state.entries);
7083    let mut old_gss = SmallVec::<[Option<ParserGSS>; INLINE_PARSER_STATE_CAPACITY]>::new();
7084    old_gss.extend(old_entries.drain(..).map(|(_, gss)| Some(gss)));
7085    let mut available_pool = SmallVec::<
7086        [Option<ParserGSS>; FLAT_FRONTIER_GSS_POOL_CAPACITY],
7087    >::new();
7088    available_pool.extend(frontier.gss_pool.drain(..).map(Some));
7089    let mut new_entries = old_entries;
7090    for ((tokenizer_state, source_index), pool_index) in
7091        output.into_iter().zip(pool_assignment)
7092    {
7093        debug_assert!(remaining_uses[source_index] > 0);
7094        remaining_uses[source_index] -= 1;
7095        let gss = if pool_index == usize::MAX {
7096            old_gss[source_index]
7097                .take()
7098                .expect("lexer-only source GSS must be available on final use")
7099        } else {
7100            let source_gss = old_gss[source_index]
7101                .as_ref()
7102                .expect("lexer-only source GSS must remain available before final use");
7103            stack_scratch.clear();
7104            let copied = source_gss.copy_single_path_stack_into(stack_scratch);
7105            debug_assert!(copied);
7106            let acc = source_gss
7107                .single_path_acc()
7108                .expect("prevalidated lexer-only duplicate source must remain single-path");
7109            let mut gss = available_pool[pool_index]
7110                .take()
7111                .expect("prevalidated lexer-only pool assignment must remain available");
7112            let replaced = gss.try_replace_single_path_state_in_place(stack_scratch, acc);
7113            debug_assert!(replaced);
7114            gss
7115        };
7116        new_entries.push((tokenizer_state, gss));
7117    }
7118    frontier
7119        .gss_pool
7120        .extend(available_pool.into_iter().flatten());
7121    let mut unused_entries = SmallVec::<[(u32, ParserGSS); INLINE_PARSER_STATE_CAPACITY]>::new();
7122    for gss in old_gss.into_iter().flatten() {
7123        unused_entries.push((0, gss));
7124    }
7125    frontier.recycle_old_entries(unused_entries);
7126    state.entries = new_entries;
7127    Some(Ok(()))
7128}
7129
7130#[inline]
7131fn try_commit_flat_frontier_in_place(
7132    constraint: &Constraint,
7133    state: &mut ParserStateMap,
7134    bytes: &[u8],
7135    original: &mut Vec<u32>,
7136    work: &mut Vec<u32>,
7137    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
7138    frontier: &mut FlatFrontierScratch,
7139) -> Option<Result<(), String>> {
7140    try_commit_flat_frontier_in_place_observed(constraint, state, bytes, original, work, tokenizer_scratch, frontier, &mut NoMarkers)
7141}
7142
7143fn try_commit_flat_frontier_in_place_observed<O: CommitObserver>(
7144    constraint: &Constraint,
7145    state: &mut ParserStateMap,
7146    bytes: &[u8],
7147    original: &mut Vec<u32>,
7148    work: &mut Vec<u32>,
7149    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
7150    frontier: &mut FlatFrontierScratch,
7151    observer: &mut O,
7152) -> Option<Result<(), String>> {
7153    let marker_checkpoint = observer.checkpoint();
7154    let result = (|| {
7155    frontier.reclaim_retired_gss();
7156    macro_rules! flat_decline {
7157        ($reason:literal) => {{
7158            if crate::env::var_os("GLRMASK_DEBUG_COMMIT_PATH").is_some() {
7159                eprintln!("[glrmask/debug][commit_path] flat_frontier_decline reason={}", $reason);
7160            }
7161            return None;
7162        }};
7163    }
7164    if state.is_empty() || state.len() > FLAT_FRONTIER_MAX_BRANCHES || bytes.is_empty() {
7165        flat_decline!("input-shape");
7166    }
7167    frontier.clear();
7168    for (&tokenizer_state, gss) in state.iter() {
7169        if !gss.copy_single_path_stack_into(original) {
7170            flat_decline!("input-not-single-path");
7171        }
7172        let Some(acc) = gss.single_path_acc() else {
7173            flat_decline!("missing-single-acc");
7174        };
7175        if !frontier.enqueue(0, tokenizer_state, original, acc) {
7176            flat_decline!("initial-enqueue");
7177        }
7178    }
7179
7180    let initial_tokenizer_state = constraint.runtime_commit_initial_state();
7181    for offset in 0..bytes.len() {
7182        let mut index = 0usize;
7183        while index < frontier.len {
7184            if frontier.branches[index].processed
7185                || frontier.branches[index].offset != offset
7186            {
7187                index += 1;
7188                continue;
7189            }
7190
7191            let tokenizer_state = frontier.branches[index].tokenizer_state;
7192            if frontier.branches[index].stack.len() > original.capacity() {
7193                flat_decline!("copy-capacity");
7194            }
7195            original.clear();
7196            original.extend_from_slice(&frontier.branches[index].stack);
7197            let mut acc = frontier.branches[index].acc.clone();
7198            frontier.branches[index].processed = true;
7199
7200            if !execute_tokenizer_reusable(
7201                constraint,
7202                &bytes[offset..],
7203                tokenizer_state,
7204                tokenizer_scratch,
7205            ) || tokenizer_scratch.matches.len() > SMALL_NORMALIZED_MATCH_LINEAR_SCAN_MAX
7206            {
7207                flat_decline!("tokenizer-scratch-or-matches");
7208            }
7209            let top_state = *original.last()?;
7210            if offset == 0 {
7211                // Delayed exclusions are correlated with parser alternatives,
7212                // but tokenizer execution is shared by every alternative under
7213                // one lexer key. Prune the whole group once and persist the
7214                // exact remapped accumulators before deciding continuation
7215                // viability from the group. The former per-branch local copy
7216                // left stale nonempty accumulators in sibling branches and
7217                // forced a general-path fallback even when pruning discharged
7218                // every exclusion.
7219                if !frontier.branches[index].initial_pruned {
7220                    let group_len = frontier.len;
7221                    for prune_index in 0..group_len {
7222                        if frontier.branches[prune_index].offset != offset
7223                            || frontier.branches[prune_index].tokenizer_state != tokenizer_state
7224                            || frontier.branches[prune_index].initial_pruned
7225                        {
7226                            continue;
7227                        }
7228                        let result = prune_flat_branch_acc(
7229                            constraint,
7230                            &frontier.branches[prune_index].acc,
7231                            tokenizer_state,
7232                            &tokenizer_scratch.states,
7233                            &tokenizer_scratch.matches,
7234                            bytes,
7235                        );
7236                        match result {
7237                            None => flat_decline!("prune-acc-promotion"),
7238                            Some(Some(pruned)) => {
7239                                frontier.branches[prune_index].acc = pruned;
7240                                frontier.branches[prune_index].initial_pruned = true;
7241                            }
7242                            Some(None) => {
7243                                // Keep array indices stable while removing this
7244                                // alternative from all later offset/key groups.
7245                                frontier.branches[prune_index].offset = usize::MAX;
7246                                frontier.branches[prune_index].processed = true;
7247                                frontier.branches[prune_index].initial_pruned = true;
7248                            }
7249                        }
7250                    }
7251                }
7252                if frontier.branches[index].offset != offset {
7253                    index += 1;
7254                    continue;
7255                }
7256                acc = frontier.branches[index].acc.clone();
7257            }
7258
7259            let actionable = ActionableTerminals::SingleState(top_state);
7260            let normalized_matches = collect_unique_actionable_matches(
7261                constraint,
7262                Some(&actionable),
7263                constraint.ignore_terminal,
7264                &tokenizer_scratch.matches,
7265                None,
7266            );
7267            for matched in normalized_matches {
7268                let new_offset = offset + matched.width;
7269                if matched.width == 0 || new_offset > bytes.len() {
7270                    flat_decline!("invalid-match-width");
7271                }
7272                if matched.ignored {
7273                    observer.flat(constraint, original, new_offset);
7274                    if !frontier.enqueue(
7275                        new_offset,
7276                        initial_tokenizer_state,
7277                        original,
7278                        acc.clone(),
7279                    ) {
7280                        flat_decline!("ignored-enqueue");
7281                    }
7282                    continue;
7283                }
7284
7285                let parser_action_result = apply_terminal_to_flat_stacks(
7286                    constraint,
7287                    matched.terminal_id,
7288                    original,
7289                    &mut frontier.action,
7290                );
7291                match parser_action_result {
7292                    Some(true) => {}
7293                    Some(false) => continue,
7294                    None => flat_decline!("parser-action-capacity"),
7295                }
7296                let advanced_acc = apply_flat_future_disallow(
7297                    constraint,
7298                    &acc,
7299                    &tokenizer_scratch.states,
7300                    matched.terminal_id,
7301                )?;
7302                for action_index in 0..frontier.action.complete.len() {
7303                    work.clear();
7304                    work.extend_from_slice(&frontier.action.complete[action_index]);
7305                    observer.flat(constraint, work, new_offset);
7306                    if !frontier.enqueue(
7307                        new_offset,
7308                        initial_tokenizer_state,
7309                        work,
7310                        advanced_acc.clone(),
7311                    ) {
7312                        flat_decline!("advanced-enqueue");
7313                    }
7314                }
7315            }
7316
7317            for &end_state in &tokenizer_scratch.states {
7318                let viable = if end_state == initial_tokenizer_state {
7319                    true
7320                } else {
7321                    let branches = &frontier.branches[..frontier.len];
7322                    let mut group = branches.iter().filter(|branch| {
7323                        branch.offset == offset && branch.tokenizer_state == tokenizer_state
7324                    });
7325                    let Some(first) = group.next() else {
7326                        flat_decline!("missing-continuation-group");
7327                    };
7328                    let correlated = group.next().is_some();
7329                    let possible = constraint
7330                        .tokenizer
7331                        .possible_future_terminals(end_state);
7332                    if !correlated {
7333                        let Some(viable) = flat_stack_may_advance_on_any(
7334                            constraint,
7335                            &first.stack,
7336                            possible,
7337                            &mut frontier.action,
7338                        ) else {
7339                            flat_decline!("continuation-admission-ambiguous");
7340                        };
7341                        viable
7342                    } else if let Some(viable) = frontier.continuation_decision(
7343                        offset,
7344                        tokenizer_state,
7345                        end_state,
7346                    ) {
7347                        viable
7348                    } else {
7349                        let group_is_safe = offset > 0
7350                            || branches
7351                                .iter()
7352                                .filter(|branch| {
7353                                    branch.offset == offset
7354                                        && branch.tokenizer_state == tokenizer_state
7355                                })
7356                                .all(|branch| branch.acc.is_empty());
7357                        if !group_is_safe {
7358                            flat_decline!("initial-continuation-group-needs-pruning");
7359                        }
7360                        let Some(viable) = flat_frontier_group_may_advance_on_any(
7361                            constraint,
7362                            branches,
7363                            offset,
7364                            tokenizer_state,
7365                            possible,
7366                            &mut frontier.action,
7367                        ) else {
7368                            flat_decline!("continuation-admission-ambiguous");
7369                        };
7370                        frontier.cache_continuation_decision(
7371                            offset,
7372                            tokenizer_state,
7373                            end_state,
7374                            viable,
7375                        );
7376                        viable
7377                    }
7378                };
7379                if viable
7380                    && !frontier.enqueue(bytes.len(), end_state, original, acc.clone())
7381                {
7382                    flat_decline!("continuation-enqueue");
7383                }
7384            }
7385            index += 1;
7386        }
7387    }
7388
7389    let mut outputs = SmallVec::<[usize; INLINE_PARSER_STATE_CAPACITY]>::new();
7390    for index in 0..frontier.len {
7391        if frontier.branches[index].offset == bytes.len() {
7392            // The inline capacity is a performance tier, not a semantic limit.
7393            // SmallVec spills once for 65-128 outputs while retaining the exact
7394            // flat algorithm instead of restarting through the general queue.
7395            outputs.push(index);
7396        }
7397    }
7398    if outputs.is_empty() {
7399        return Some(Err(
7400            "commit rejected: no valid parser states remain".to_string(),
7401        ));
7402    }
7403    outputs.sort_unstable_by(|&left, &right| {
7404        frontier.branches[left]
7405            .tokenizer_state
7406            .cmp(&frontier.branches[right].tokenizer_state)
7407            .then_with(|| frontier.branches[left].stack.cmp(&frontier.branches[right].stack))
7408    });
7409
7410    // Use both preallocated spares and uniquely-owned active GSS objects for
7411    // the output double buffer. The old implementation required the spare pool
7412    // alone to cover every output, even when all active entries were exactly
7413    // recyclable. A seven-way lexer frontier could therefore decline with two
7414    // spares plus seven recyclable active entries and fall into the allocating
7415    // general path despite having nine usable objects for seven outputs.
7416    let recyclable_old = state
7417        .entries
7418        .iter()
7419        .filter(|(_, gss)| gss.can_replace_single_path_state_in_place(&[0]))
7420        .count();
7421    let retired_old = state.len() - recyclable_old;
7422    let available_count = frontier.gss_pool.len() + recyclable_old;
7423    if available_count < outputs.len()
7424        || available_count - outputs.len() > FLAT_FRONTIER_GSS_POOL_CAPACITY
7425        || frontier.retired_gss.len() + retired_old > FLAT_FRONTIER_RETIRED_GSS_CAPACITY
7426    {
7427        flat_decline!("gss-pool-capacity");
7428    }
7429
7430    // Verify a concrete one-to-one assignment before moving anything out of
7431    // the active state. Match the longest output stacks first so a larger spare
7432    // cannot be consumed by a short stack while a smaller spare remains.
7433    let assignments = {
7434        let mut candidates = SmallVec::<[&ParserGSS; 32]>::new();
7435        candidates.extend(frontier.gss_pool.iter());
7436        candidates.extend(
7437            state
7438                .entries
7439                .iter()
7440                .map(|(_, gss)| gss)
7441                .filter(|gss| gss.can_replace_single_path_state_in_place(&[0])),
7442        );
7443        debug_assert_eq!(candidates.len(), available_count);
7444
7445        let mut output_order = SmallVec::<[usize; INLINE_PARSER_STATE_CAPACITY]>::new();
7446        output_order.extend(0..outputs.len());
7447        output_order.sort_unstable_by_key(|&output_index| {
7448            std::cmp::Reverse(frontier.branches[outputs[output_index]].stack.len())
7449        });
7450
7451        let mut used =
7452            [false; FLAT_FRONTIER_GSS_POOL_CAPACITY + FLAT_FRONTIER_MAX_BRANCHES];
7453        let mut assignments = SmallVec::<[usize; INLINE_PARSER_STATE_CAPACITY]>::new();
7454        assignments.resize(outputs.len(), usize::MAX);
7455        for output_index in output_order {
7456            let stack = &frontier.branches[outputs[output_index]].stack;
7457            let Some(candidate_index) = candidates
7458                .iter()
7459                .enumerate()
7460                .position(|(candidate_index, gss)| {
7461                    !used[candidate_index]
7462                        && gss.can_replace_single_path_state_in_place(stack)
7463                })
7464            else {
7465                flat_decline!("gss-pool-shared-or-shape");
7466            };
7467            used[candidate_index] = true;
7468            assignments[output_index] = candidate_index;
7469        }
7470        assignments
7471    };
7472
7473    // Candidate order is stable: existing spares first, followed by recyclable
7474    // active entries. Non-recyclable active GSSs remain retained so dropping
7475    // shared persistent nodes never lands in the token hot path.
7476    let mut available = SmallVec::<[Option<ParserGSS>; 32]>::new();
7477    available.extend(frontier.gss_pool.drain(..).map(Some));
7478    let mut old_entries = std::mem::take(&mut state.entries);
7479    for (_, gss) in old_entries.drain(..) {
7480        if gss.can_replace_single_path_state_in_place(&[0]) {
7481            available.push(Some(gss));
7482        } else {
7483            frontier.retired_gss.push(gss);
7484        }
7485    }
7486    debug_assert_eq!(available.len(), available_count);
7487
7488    let mut new_entries = old_entries;
7489    for (output_index, &output) in outputs.iter().enumerate() {
7490        let mut gss = available[assignments[output_index]]
7491            .take()
7492            .expect("prevalidated flat-frontier GSS assignment must remain available");
7493        let branch = &frontier.branches[output];
7494        let replaced = gss.try_replace_single_path_state_in_place(
7495            &branch.stack,
7496            branch.acc.clone(),
7497        );
7498        debug_assert!(replaced, "flat-frontier spare eligibility changed");
7499        if !replaced {
7500            unreachable!("flat-frontier spare was validated before mutation");
7501        }
7502        new_entries.push((branch.tokenizer_state, gss));
7503    }
7504    for gss in available.into_iter().flatten() {
7505        frontier.gss_pool.push(gss);
7506    }
7507    debug_assert!(frontier.gss_pool.len() <= FLAT_FRONTIER_GSS_POOL_CAPACITY);
7508    state.entries = new_entries;
7509    Some(Ok(()))
7510
7511    })();
7512    if result.is_none() { observer.rewind(marker_checkpoint); }
7513    result
7514}
7515
7516#[inline]
7517fn try_commit_direct_linear_in_place(
7518    constraint: &Constraint,
7519    state: &mut ParserStateMap,
7520    bytes: &[u8],
7521    original: &mut Vec<u32>,
7522    work: &mut Vec<u32>,
7523    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
7524    frontier: &mut FlatFrontierScratch,
7525) -> Option<Result<(), String>> {
7526    try_commit_direct_linear_in_place_observed(constraint, state, bytes, original, work, tokenizer_scratch, frontier, &mut NoMarkers)
7527}
7528
7529fn try_commit_direct_linear_in_place_observed<O: CommitObserver>(
7530    constraint: &Constraint,
7531    state: &mut ParserStateMap,
7532    bytes: &[u8],
7533    original: &mut Vec<u32>,
7534    work: &mut Vec<u32>,
7535    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
7536    frontier: &mut FlatFrontierScratch,
7537    observer: &mut O,
7538) -> Option<Result<(), String>> {
7539    let marker_checkpoint = observer.checkpoint();
7540    let result = (|| {
7541    if constraint.has_template_parser() { return None; }
7542
7543    let debug_path = crate::env::var_os("GLRMASK_DEBUG_COMMIT_PATH").is_some();
7544    let (&start_tokenizer_state, gss) = state.iter().next()?;
7545    let acc = gss.single_path_acc()?;
7546    if !acc.is_empty()
7547        || !gss.copy_single_path_stack_into(original)
7548        || original.len() > work.capacity()
7549    {
7550        return None;
7551    }
7552    work.clear();
7553    work.extend_from_slice(original);
7554
7555    let initial_tokenizer_state = constraint.runtime_commit_initial_state();
7556    let mut tokenizer_state = start_tokenizer_state;
7557    let mut offset = 0usize;
7558    let final_keys: SmallVec<[u32; INLINE_PARSER_STATE_CAPACITY]> = loop {
7559        if offset == bytes.len() {
7560            break smallvec::smallvec![initial_tokenizer_state];
7561        }
7562        if !execute_tokenizer_reusable(
7563            constraint,
7564            &bytes[offset..],
7565            tokenizer_state,
7566            tokenizer_scratch,
7567        ) {
7568            return None;
7569        }
7570
7571        let top = *work.last()?;
7572        let actionable = ActionableTerminals::SingleState(top);
7573        let normalized_matches = collect_unique_actionable_reusable_matches(
7574            constraint,
7575            Some(&actionable),
7576            constraint.ignore_terminal,
7577            &tokenizer_scratch.matches,
7578        );
7579        if debug_path {
7580            eprintln!(
7581                "[glrmask/debug][direct_linear_step] offset={} tokenizer_state={} stack={:?} raw_matches={:?} normalized={:?} end_states={:?}",
7582                offset,
7583                tokenizer_state,
7584                work,
7585                tokenizer_scratch.matches,
7586                normalized_matches
7587                    .iter()
7588                    .map(|m| (m.terminal_id, m.width, m.ignored))
7589                    .collect::<Vec<_>>(),
7590                tokenizer_scratch.states,
7591            );
7592        }
7593        if normalized_matches.len() > 1 {
7594            return None;
7595        }
7596
7597        let mut viable_end_states = SmallVec::<[u32; INLINE_PARSER_STATE_CAPACITY]>::new();
7598        if tokenizer_scratch.states.len() > SMALL_NORMALIZED_MATCH_LINEAR_SCAN_MAX {
7599            // Wide lexer-only continuation after a parser action: reconstruct
7600            // the one current parser stack once, compute exact admission over
7601            // the union of all end-state futures, then classify each lexer
7602            // state by a cheap bitset intersection. This is the same exact
7603            // batching used by the authoritative queue path, but avoids one
7604            // parser query per raw lexer state.
7605            let probe_gss = ParserGSS::from_single_stack(work.to_vec(), acc.clone());
7606            let admitted = batched_end_state_admitted_terminals(
7607                constraint,
7608                &probe_gss,
7609                &tokenizer_scratch.states,
7610            );
7611            for &end_state in &tokenizer_scratch.states {
7612                if end_state_may_advance_with_batch(
7613                    constraint,
7614                    &probe_gss,
7615                    end_state,
7616                    admitted.as_ref(),
7617                ) {
7618                    viable_end_states.push(end_state);
7619                }
7620            }
7621        } else {
7622            for &end_state in &tokenizer_scratch.states {
7623                let viable = if end_state == initial_tokenizer_state {
7624                    true
7625                } else {
7626                    flat_stack_may_advance_on_any(
7627                        constraint,
7628                        work,
7629                        constraint.tokenizer.possible_future_terminals(end_state),
7630                        &mut frontier.action,
7631                    )?
7632                };
7633                if viable {
7634                    viable_end_states.push(end_state);
7635                }
7636            }
7637        }
7638
7639        let Some(matched) = normalized_matches.first() else {
7640            if viable_end_states.is_empty() {
7641                return Some(Err(
7642                    "commit rejected: no valid parser states remain".to_string(),
7643                ));
7644            }
7645            break viable_end_states;
7646        };
7647        if !viable_end_states.is_empty() {
7648            return None;
7649        }
7650
7651        let new_offset = offset + matched.width;
7652        if new_offset > bytes.len() || matched.width == 0 {
7653            return None;
7654        }
7655        if !matched.ignored {
7656            if tokenizer_scratch.states.iter().any(|&end_state| {
7657                constraint
7658                    .tokenizer
7659                    .possible_future_terminals(end_state)
7660                    .contains(matched.terminal_id as usize)
7661            }) {
7662                // The general path must attach a future-terminal exclusion.
7663                return None;
7664            }
7665            let applied = apply_terminal_to_flat_stacks(
7666                constraint,
7667                matched.terminal_id,
7668                work,
7669                &mut frontier.action,
7670            );
7671            if debug_path {
7672                eprintln!(
7673                    "[glrmask/debug][direct_linear_apply] terminal={} top_before={:?} table_action={:?} applied={:?} complete={:?}",
7674                    matched.terminal_id,
7675                    work.last().copied(),
7676                    work.last().and_then(|&top| constraint.table.action(top, matched.terminal_id)),
7677                    applied,
7678                    frontier.action.complete,
7679                );
7680            }
7681            match applied {
7682                Some(true) if frontier.action.complete.len() == 1 => {
7683                    work.clear();
7684                    work.extend_from_slice(&frontier.action.complete[0]);
7685                }
7686                Some(true) => return None,
7687                Some(false) => {
7688                    return Some(Err(
7689                        "commit rejected: no valid parser states remain".to_string(),
7690                    ));
7691                }
7692                None => return None,
7693            }
7694        }
7695        observer.flat(constraint, work, new_offset);
7696        offset = new_offset;
7697        tokenizer_state = initial_tokenizer_state;
7698    };
7699
7700    frontier
7701        .replace_state_with_shared_uniform_stack_keys(state, &final_keys, work, &acc)
7702        .then_some(Ok(()))
7703
7704    })();
7705    if result.is_none() { observer.rewind(marker_checkpoint); }
7706    result
7707}
7708
7709
7710#[inline]
7711fn maybe_normalize_lookahead_invariant_reductions(
7712    constraint: &Constraint,
7713    state: &mut ParserStateMap,
7714) {
7715    if constraint.has_template_parser() { return; }
7716
7717    if constraint.static_dynamic_overlay.is_none()
7718        || constraint.uses_compact_segmented_parser_runtime()
7719        || crate::env::var_os("GLRMASK_EXPERIMENT_EAGER_INVARIANT_REDUCTIONS").is_none()
7720    {
7721        return;
7722    }
7723    for gss in state.values_mut() {
7724        *gss = normalize_lookahead_invariant_reductions(&constraint.table, gss);
7725    }
7726}
7727
7728#[inline]
7729fn commit_bytes_impl(
7730    constraint: &Constraint,
7731    state: &mut ParserStateMap,
7732    bytes: &[u8],
7733    bufs: &mut CommitBuffers,
7734) -> Result<(), String> {
7735    commit_bytes_impl_observed(constraint, state, bytes, bufs, &mut NoMarkers)
7736}
7737
7738fn commit_bytes_impl_observed<O: CommitObserver>(
7739    constraint: &Constraint,
7740    state: &mut ParserStateMap,
7741    bytes: &[u8],
7742    bufs: &mut CommitBuffers,
7743    observer: &mut O,
7744) -> Result<(), String> {
7745    expand_runtime_product_states(constraint, state);
7746    commit_bytes_impl_inner_observed(constraint, state, bytes, bufs, observer)?;
7747
7748    // General symbolic residuals expose a conservative infallible future bit
7749    // during the inner commit so ordinary parser/lexer machinery can remain
7750    // unchanged. Before accepting the token, resolve every non-reset lexer key
7751    // through the bounded exact residual-liveness query. A hard Boolean case
7752    // that exceeds the work ceiling is an error, never a false live/dead bit.
7753    if constraint.tokenizer_requires_exact_liveness() {
7754        let mut dead = Vec::<u32>::new();
7755        for &tokenizer_state in state.keys() {
7756            // A recursive state belongs to its leaf lexer, not the outer
7757            // coordinator's superficially similar numeric state alphabet.
7758            if !constraint.exact_runtime_tokenizer_state_has_future(tokenizer_state)? {
7759                dead.push(tokenizer_state);
7760            }
7761        }
7762        if !dead.is_empty() {
7763            dead.sort_unstable();
7764            state.retain(|tokenizer_state, _| dead.binary_search(tokenizer_state).is_err());
7765        }
7766        if state.is_empty() {
7767            return Err("commit rejected: no valid parser states remain".to_owned());
7768        }
7769    }
7770
7771    observer.frontier(constraint, state, bytes.len());
7772    coalesce_uniform_runtime_source_states(constraint, state);
7773    Ok(())
7774}
7775
7776/// Exact single-lane lexer-only commit.
7777///
7778/// The parser GSS is left byte-for-byte unchanged. The shortcut applies only
7779/// when bounded tokenizer execution succeeds, there are no delayed exclusions,
7780/// and every terminal completed anywhere in `bytes` is both non-ignore and
7781/// parser-inadmissible. Therefore no parser action (including recursive
7782/// CALL/RETURN closure) can be skipped. Only viable tokenizer continuation
7783/// keys are substituted for the original key; every failure to prove those
7784/// conditions declines without mutating `state`.
7785fn try_commit_single_state_lexer_only(
7786    constraint: &Constraint,
7787    state: &mut ParserStateMap,
7788    bytes: &[u8],
7789    ignore_terminal: Option<u32>,
7790    tokenizer_scratch: &mut tokenizer_scan::ReusableTokenizerExecScratch,
7791    flat_frontier: &mut FlatFrontierScratch,
7792    stack_scratch: &mut Vec<u32>,
7793) -> bool {
7794    let [(start_tokenizer_state, gss)] = state.entries.as_slice() else {
7795        return false;
7796    };
7797    let start_tokenizer_state = *start_tokenizer_state;
7798    let gss = gss.clone();
7799    if !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()) {
7800        return false;
7801    }
7802    let recursive_runtime = constraint.uses_compact_segmented_parser_runtime();
7803    let tokenizer_executed = if recursive_runtime {
7804        execute_recursive_tokenizer_reusable(
7805            constraint,
7806            bytes,
7807            start_tokenizer_state,
7808            tokenizer_scratch,
7809        )
7810    } else {
7811        execute_tokenizer_reusable(constraint, bytes, start_tokenizer_state, tokenizer_scratch)
7812    };
7813    if !tokenizer_executed {
7814        return false;
7815    }
7816
7817    // Direct-regular wide-frontier summaries are monolithic-coordinate
7818    // accelerators. Recursive admission is already exact through the provider,
7819    // so deliberately do not consult those summaries here.
7820    let wide_frontier = (!recursive_runtime)
7821        .then(|| constraint.direct_regular_wide_frontier_for_gss(&gss))
7822        .flatten();
7823    if tokenizer_scratch.matches.iter().any(|matched| {
7824        runtime_is_ignored_terminal(constraint, ignore_terminal, matched.id)
7825            || wide_frontier.map_or_else(
7826                || parser_may_advance_on(constraint, &gss, matched.id),
7827                |summary| summary.actionable_terminals.contains(matched.id as usize),
7828            )
7829    }) {
7830        return false;
7831    }
7832
7833    tokenizer_scratch.states.retain(|end_state| {
7834        wide_frontier.map_or_else(
7835            || end_state_may_advance(constraint, &gss, *end_state),
7836            |summary| wide_frontier_end_state_may_advance(constraint, summary, *end_state),
7837        )
7838    });
7839
7840    // The parser frontier is unchanged. Re-key its existing Arc directly
7841    // instead of decomposing, rebuilding, and fusing the represented stack
7842    // language.
7843    if state.replace_single_keys(&tokenizer_scratch.states) {
7844        return true;
7845    }
7846    if let Some(acc) = gss.single_path_acc()
7847        && gss.copy_single_path_stack_into(stack_scratch)
7848        && flat_frontier.replace_state_with_uniform_stack_keys(
7849            state,
7850            &tokenizer_scratch.states,
7851            stack_scratch,
7852            &acc,
7853        )
7854    {
7855        return true;
7856    }
7857    false
7858}
7859
7860#[inline]
7861fn commit_bytes_impl_inner(
7862    constraint: &Constraint,
7863    state: &mut ParserStateMap,
7864    bytes: &[u8],
7865    bufs: &mut CommitBuffers,
7866) -> Result<(), String> {
7867    commit_bytes_impl_inner_observed(constraint, state, bytes, bufs, &mut NoMarkers)
7868}
7869
7870fn commit_bytes_impl_inner_observed<O: CommitObserver>(
7871    constraint: &Constraint,
7872    state: &mut ParserStateMap,
7873    bytes: &[u8],
7874    bufs: &mut CommitBuffers,
7875    observer: &mut O,
7876) -> Result<(), String> {
7877    if bytes.is_empty() {
7878        return Ok(());
7879    }
7880
7881    let debug_path = crate::env::var_os("GLRMASK_DEBUG_COMMIT_PATH").is_some();
7882    if debug_path {
7883        eprintln!(
7884            "[glrmask/debug][commit_input] entries={} keys_paths={:?}",
7885            state.len(),
7886            state
7887                .iter()
7888                .map(|(&key, gss)| (key, gss.path_count_at_most(17)))
7889                .collect::<Vec<_>>(),
7890        );
7891    }
7892    let ignore_terminal = constraint.ignore_terminal;
7893    // Linker control terminals are zero-width parser transitions.  The
7894    // allocation-free commit fast paths assume that every parser transition is
7895    // driven by a completed lexer terminal and therefore cannot yet preserve
7896    // control closure between lexemes.  Keep explicit-control tables on the
7897    // authoritative queue path until each fast path has its own equivalence
7898    // proof/implementation.
7899    let has_linker_controls = constraint.parser_has_controls()
7900        || constraint.uses_compact_segmented_parser_runtime();
7901    let direct_dynamic = constraint.uses_dynamic_runtime()
7902        && constraint.direct_regular_automaton.is_some();
7903    if state.len() <= 1 && !bufs.admission_cache.is_empty() {
7904        bufs.admission_cache.clear();
7905    }
7906
7907    // A wide direct-regular frontier already carries its exact actionable
7908    // terminal support. Scan only that support instead of materializing every
7909    // tokenizer finalizer, which can be proportional to the remaining source
7910    // file in project-scale diff grammars.
7911    if !has_linker_controls
7912        && state.len() == 1
7913        && !constraint.tokenizer_has_epsilon_transitions
7914    {
7915        let (&start_tokenizer_state, gss) = state.iter().next().unwrap();
7916        if let Some(summary) = constraint.direct_regular_wide_frontier_for_gss(gss)
7917            && let Some(accumulator) = gss.uniform_accumulator()
7918            && let Some(end_state) = scan_wide_frontier_lexer_only(
7919                constraint,
7920                bytes,
7921                start_tokenizer_state,
7922                summary,
7923            )
7924        {
7925            let Some(updated_accumulator) = advance_uniform_disallowed_interest_only(
7926                constraint,
7927                &accumulator,
7928                bytes,
7929            ) else {
7930                state.clear();
7931                return Err("commit rejected: no valid parser states remain".to_string());
7932            };
7933            if !wide_frontier_end_state_may_advance(constraint, summary, end_state) {
7934                state.clear();
7935                return Err("commit rejected: no valid parser states remain".to_string());
7936            }
7937            if let Some(updated) = gss.with_uniform_accumulator(updated_accumulator) {
7938                state.clear();
7939                state.insert(end_state, updated);
7940                return Ok(());
7941            }
7942        }
7943    }
7944
7945    if !has_linker_controls
7946        && !direct_dynamic
7947        && state.len() == 1
7948        && let Some(result) = try_commit_direct_linear_in_place_observed(
7949            constraint,
7950            state,
7951            bytes,
7952            &mut bufs.linear_stack_original,
7953            &mut bufs.linear_stack_work,
7954            &mut bufs.reusable_tokenizer_exec,
7955            bufs.flat_frontier.get_or_insert_with(FlatFrontierScratch::boxed_for_mask_only_shadow),
7956         observer)
7957    {
7958        if debug_path {
7959            eprintln!("[glrmask/debug][commit_path] direct_linear states={}", state.len());
7960        }
7961        return result;
7962    }
7963
7964    if !has_linker_controls && !direct_dynamic {
7965        let lexer_only_result = try_commit_multi_state_lexer_only(
7966            constraint,
7967            state,
7968            bytes,
7969            &mut bufs.reusable_tokenizer_exec,
7970            bufs.flat_frontier.get_or_insert_with(FlatFrontierScratch::boxed_for_mask_only_shadow),
7971            &mut bufs.linear_stack_original,
7972            &mut bufs.admission_cache,
7973        );
7974        if let Some(result) = lexer_only_result {
7975            if debug_path {
7976                eprintln!("[glrmask/debug][commit_path] multi_state_lexer_only states={}", state.len());
7977            }
7978            return result;
7979        }
7980    }
7981    // Exact-simulation tables make continuation admission the dominant cost
7982    // for tiny composed frontiers.  The small queue batches that exact set query,
7983    // so try it before the flat accelerator (whose bounded proof may decline and
7984    // duplicate the work) when its ordinary profitability bounds already hold.
7985    if !has_linker_controls
7986        && !direct_dynamic
7987        && constraint.parser_admission_policy() == AdmissionPolicy::ExactSimulation
7988        && bytes.len() <= 16
7989        && state.len() <= 8
7990    {
7991        let early_small_queue = commit_bytes_small_queue_fast_path_observed(
7992            constraint,
7993            state,
7994            bytes,
7995            &mut bufs.reusable_tokenizer_exec,
7996            bufs.small_queue.get_or_insert_with(SmallCommitQueueScratch::boxed).as_mut(),
7997            &mut bufs.admission_cache,
7998            &mut bufs.prune_tokenizer_exec,
7999         observer);
8000        if let Some(result) = early_small_queue {
8001            if debug_path {
8002                eprintln!("[glrmask/debug][commit_path] early_small_queue states={}", state.len());
8003            }
8004            return result;
8005        }
8006    }
8007
8008    if !has_linker_controls
8009        && !direct_dynamic
8010        && state.len() <= FLAT_FRONTIER_MAX_BRANCHES
8011        && let Some(result) = try_commit_flat_frontier_in_place_observed(
8012            constraint,
8013            state,
8014            bytes,
8015            &mut bufs.linear_stack_original,
8016            &mut bufs.linear_stack_work,
8017            &mut bufs.reusable_tokenizer_exec,
8018            bufs.flat_frontier.get_or_insert_with(FlatFrontierScratch::boxed_for_mask_only_shadow),
8019         observer)
8020    {
8021        if debug_path {
8022            eprintln!("[glrmask/debug][commit_path] flat_frontier states={}", state.len());
8023        }
8024        return result;
8025    }
8026
8027    // All remaining paths use map/GSS semantics. Materialize any bounded flat
8028    // alternatives only after the allocation-free path has declined.
8029    state.normalize_duplicate_keys();
8030
8031    // Exact no-match self-loops are the simplest lexer-only case: neither the
8032    // tokenizer key nor the parser GSS changes.
8033    if !has_linker_controls
8034        && !constraint.tokenizer_has_epsilon_transitions
8035        && state.len() == 1
8036    {
8037        let (&start_tokenizer_state, _) = state.iter().next().unwrap();
8038        let mut tokenizer_state = start_tokenizer_state;
8039        let mut no_matches = true;
8040        for &byte in bytes {
8041            tokenizer_state = constraint.tokenizer_fast_transitions.transition(
8042                &constraint.tokenizer,
8043                tokenizer_state,
8044                byte,
8045            );
8046            if tokenizer_state == u32::MAX
8047                || constraint
8048                    .tokenizer
8049                    .matched_terminals_iter(tokenizer_state)
8050                    .next()
8051                    .is_some()
8052            {
8053                no_matches = false;
8054                break;
8055            }
8056        }
8057        if no_matches && tokenizer_state == start_tokenizer_state {
8058            return Ok(());
8059        }
8060    }
8061
8062    // A large fraction of model tokens only advance the lexer. This proof is
8063    // valid in both monolithic and recursive leaf-scoped coordinates.
8064    if try_commit_single_state_lexer_only(
8065        constraint,
8066        state,
8067        bytes,
8068        ignore_terminal,
8069        &mut bufs.reusable_tokenizer_exec,
8070        bufs.flat_frontier.get_or_insert_with(FlatFrontierScratch::boxed_for_mask_only_shadow),
8071        &mut bufs.linear_stack_original,
8072    ) {
8073        if debug_path && constraint.uses_compact_segmented_parser_runtime() {
8074            eprintln!(
8075                "[glrmask/debug][commit_path] recursive_lexer_only states={}",
8076                state.len(),
8077            );
8078        }
8079        return Ok(());
8080    }
8081
8082    // Common deterministic case: consume one complete model token and mutate
8083    // the uniquely-owned linear parser stack directly. All eligibility checks
8084    // happen before mutation, so declining this path leaves the old fallback
8085    // semantics untouched. A plain shift is exact regardless of whether the
8086    // equivalent template-DFA advance is enabled.
8087    if !has_linker_controls && state.len() == 1 {
8088        let initial_tokenizer_state = constraint.runtime_commit_initial_state();
8089        let (&tokenizer_state, gss) = state.iter().next().unwrap();
8090        if tokenizer_state == initial_tokenizer_state
8091            && gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
8092            && let Some(top_state) = gss.single_exclusive_top_value()
8093            && let Some(step) = choose_direct_linear_step(
8094                constraint,
8095                gss,
8096                bytes,
8097                tokenizer_state,
8098                Some(top_state),
8099            )
8100            && step.width == bytes.len()
8101            && !step.ignored
8102        {
8103            let continuation_is_inert = step.end_state.is_none_or(|end_state| {
8104                let future = constraint.tokenizer.possible_future_terminals(end_state);
8105                !end_state_may_advance(constraint, gss, end_state)
8106                    && !future.contains(step.terminal as usize)
8107            });
8108            if continuation_is_inert
8109                && !constraint.has_template_parser()
8110                && let Some(Action::Shift(target, replace)) =
8111                    constraint.table.action(top_state, step.terminal)
8112                && let Some(gss) = state.values_mut().next()
8113            {
8114                let pushes = [*target];
8115                if gss.try_apply_single_segment_stack_effect_in_place(
8116                    usize::from(*replace),
8117                    &pushes,
8118                ) {
8119                    return Ok(());
8120                }
8121            }
8122        }
8123    }
8124
8125    if !has_linker_controls && state.len() == 1 {
8126        let (&tokenizer_state, _) = state.iter().next().unwrap();
8127        let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
8128        if let Some(result) = commit_bytes_fast_path_observed(
8129            constraint,
8130            state,
8131            bytes,
8132            tokenizer_state,
8133            &exec_result,
8134         observer) {
8135            return result;
8136        }
8137    }
8138
8139    // Single tokenizer state: execute tokenizer ONCE, try fast path, reuse result
8140    if !has_linker_controls && state.len() == 1 {
8141        let (&tokenizer_state, parser_gss) = state.iter().next().unwrap();
8142        if parser_gss.single_exclusive_top_value().is_some()
8143            && let Some(result) = commit_bytes_direct_linear_fast_path_observed(
8144                constraint,
8145                parser_gss.clone(),
8146                bytes,
8147                tokenizer_state,
8148                None,
8149             observer) {
8150                match result {
8151                    LinearFastPathResult::Complete(result) => {
8152                        let final_gss = result?;
8153                        state.clear();
8154                        state.insert(constraint.runtime_commit_initial_state(), final_gss);
8155                        return Ok(());
8156                    }
8157                    LinearFastPathResult::Continue { gss, offset } => {
8158                        state.clear();
8159                        state.insert(constraint.runtime_commit_initial_state(), gss);
8160                        return observer.shifted(offset, |observer| commit_bytes_impl_observed(constraint, state, &bytes[offset..], bufs, observer));
8161                    }
8162                    LinearFastPathResult::Restart => {}
8163                }
8164            }
8165    }
8166
8167    if !has_linker_controls {
8168        let language_small_queue_result = commit_bytes_language_small_queue_fast_path_observed(
8169            constraint,
8170            state,
8171            bytes,
8172            &mut bufs.reusable_tokenizer_exec,
8173            bufs.small_queue.get_or_insert_with(SmallCommitQueueScratch::boxed).as_mut(),
8174            &mut bufs.template_advance_runtime,
8175            false,
8176         observer);
8177        if let Some(result) = language_small_queue_result {
8178            return result;
8179        }
8180    }
8181
8182    let small_queue_result = if constraint.uses_compact_segmented_parser_runtime() {
8183        None
8184    } else {
8185        commit_bytes_small_queue_fast_path_observed(
8186            constraint,
8187            state,
8188            bytes,
8189            &mut bufs.reusable_tokenizer_exec,
8190            bufs.small_queue.get_or_insert_with(SmallCommitQueueScratch::boxed).as_mut(),
8191            &mut bufs.admission_cache,
8192            &mut bufs.prune_tokenizer_exec,
8193         observer)
8194    };
8195    if let Some(result) = small_queue_result {
8196        if debug_path {
8197            eprintln!("[glrmask/debug][commit_path] small_queue states={}", state.len());
8198        }
8199        return result;
8200    }
8201
8202    if !constraint.uses_compact_segmented_parser_runtime()
8203        && let Some(result) = commit_bytes_full_width_fast_path_observed(constraint, state, bytes, observer)
8204    {
8205        if debug_path {
8206            eprintln!("[glrmask/debug][commit_path] full_width states={}", state.len());
8207        }
8208        return result;
8209    }
8210
8211    if !has_linker_controls
8212        && !constraint.tokenizer_has_epsilon_transitions
8213        && state.len() == 1
8214    {
8215        let (&tokenizer_state, _) = state.iter().next().unwrap();
8216        let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
8217
8218        // Try fast path with pre-computed exec_result
8219        if let Some(result) = commit_bytes_fast_path_observed(
8220            constraint, state, bytes, tokenizer_state, &exec_result,
8221         observer) {
8222            return result;
8223        }
8224
8225        if !exec_result
8226            .end_state
8227            .iter()
8228            .copied()
8229            .any(|end_state| {
8230                state
8231                    .values()
8232                    .next()
8233                    .is_some_and(|gss| end_state_may_advance(constraint, gss, end_state))
8234            })
8235        {
8236            let current_gss = state.values().next().unwrap();
8237            let start_gss = if current_gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()) {
8238                current_gss.clone()
8239            } else {
8240                prune_single_initial_state_for_exec(
8241                    constraint,
8242                    current_gss.clone(),
8243                    tokenizer_state,
8244                    &exec_result,
8245                    bytes,
8246                )
8247            };
8248            if start_gss.is_empty() {
8249                return Err("commit rejected: no valid parser states remain".to_string());
8250            }
8251            match commit_bytes_linear_fast_path_observed(
8252                constraint,
8253                start_gss,
8254                bytes,
8255                exec_result.clone(),
8256             observer) {
8257                LinearFastPathResult::Complete(result) => {
8258                    let final_gss = result?;
8259                    state.clear();
8260                    state.insert(constraint.runtime_commit_initial_state(), final_gss);
8261                    return Ok(());
8262                }
8263                LinearFastPathResult::Continue { gss, offset } => {
8264                    bufs.clear_all();
8265                    state.clear();
8266                    state.insert(constraint.runtime_commit_initial_state(), gss);
8267
8268                    if bytes.len() - offset == 1 {
8269                        return observer.shifted(offset, |observer| commit_bytes_impl_observed(constraint, state, &bytes[offset..], bufs, observer));
8270                    }
8271
8272                    let needed_queue_len = bytes.len() + 1;
8273                    let mut processing_queue = std::mem::take(&mut bufs.processing_queue);
8274                    if processing_queue.len() < needed_queue_len {
8275                        processing_queue.resize_with(needed_queue_len, ParserStatesByTokenizer::default);
8276                    }
8277                    for bucket in processing_queue.iter_mut().take(needed_queue_len) {
8278                        bucket.clear();
8279                    }
8280                    processing_queue[offset] = std::mem::take(state).into_iter().collect();
8281
8282                    let mut offset = offset;
8283                    while offset < needed_queue_len {
8284                        if processing_queue[offset].is_empty() {
8285                            offset += 1;
8286                            continue;
8287                        }
8288
8289                        let states_to_process = std::mem::take(&mut processing_queue[offset]);
8290                        for (tokenizer_state, gss_at_offset) in states_to_process {
8291                            let actionable_terminals = ActionableTerminals::from_gss(constraint, &gss_at_offset);
8292                            let exec_result = execute_tokenizer_from_state_small(
8293                                constraint,
8294                                &bytes[offset..],
8295                                tokenizer_state,
8296                            );
8297
8298                            bufs.terminal_result_cache.clear();
8299
8300                            let normalized_matches = collect_unique_actionable_matches(
8301                                constraint,
8302                                actionable_terminals.as_ref(),
8303                                ignore_terminal,
8304                                &exec_result.matches,
8305                                Some(&mut bufs.seen_matches),
8306                            );
8307
8308                            for matched in normalized_matches {
8309                                let new_offset = offset + matched.width;
8310
8311                                if matched.ignored {
8312                                    observer.stack(constraint, &gss_at_offset, new_offset);
8313                                    queue_parser_state(
8314                                        &mut processing_queue,
8315                                        &mut bufs.pending_state,
8316                                        new_offset,
8317                                        bytes.len(),
8318                                        constraint.runtime_commit_initial_state(),
8319                                        gss_at_offset.clone(),
8320                                    );
8321                                    continue;
8322                                }
8323
8324                                let Some(gss) = advance_terminal_match(
8325                                    constraint,
8326                                    &gss_at_offset,
8327                                    matched.terminal_id,
8328                                    &exec_result,
8329                                    &mut bufs.advance_result_cache,
8330                                    &mut bufs.terminal_result_cache,
8331                                ) else {
8332                                    continue;
8333                                };
8334
8335                                observer.stack(constraint, &gss, new_offset);
8336                                queue_parser_state(
8337                                    &mut processing_queue,
8338                                    &mut bufs.pending_state,
8339                                    new_offset,
8340                                    bytes.len(),
8341                                    constraint.runtime_commit_initial_state(),
8342                                    gss,
8343                                );
8344                            }
8345
8346                            let admission_cache_index = cached_batched_end_state_admission(
8347                                constraint,
8348                                &gss_at_offset,
8349                                &exec_result.end_state,
8350                                &mut bufs.admission_cache,
8351                            );
8352                            for &end_state in &exec_result.end_state {
8353                                let may_advance = if let Some(index) = admission_cache_index {
8354                                    end_state_may_advance_from_cache_entry(
8355                                        constraint,
8356                                        end_state,
8357                                        &bufs.admission_cache[index],
8358                                    )
8359                                } else {
8360                                    cached_single_end_state_may_advance(
8361                                        constraint,
8362                                        &gss_at_offset,
8363                                        end_state,
8364                                        &mut bufs.admission_cache,
8365                                    )
8366                                };
8367                                if !may_advance {
8368                                    continue;
8369                                }
8370
8371                                queue_parser_state(
8372                                    &mut processing_queue,
8373                                    &mut bufs.pending_state,
8374                                    bytes.len(),
8375                                    bytes.len(),
8376                                    end_state,
8377                                    gss_at_offset.clone(),
8378                                );
8379                            }
8380                        }
8381                    }
8382
8383                    let new_state = finalize_pending_state(&mut bufs.pending_state);
8384
8385                    *state = new_state;
8386                    bufs.processing_queue = processing_queue;
8387                    if state.is_empty() {
8388                        return Err("commit rejected: no valid parser states remain".to_string());
8389                    }
8390                    return Ok(());
8391                }
8392                LinearFastPathResult::Restart => {}
8393            }
8394        }
8395
8396        // Fast path failed — build scan data from already-computed exec_result
8397        bufs.clear_all();
8398        bufs.exec_results.insert(tokenizer_state, exec_result);
8399    } else {
8400        bufs.clear_all();
8401
8402        for &tokenizer_state in state.keys() {
8403            let exec_result = execute_tokenizer_from_state_small(constraint, bytes, tokenizer_state);
8404            bufs.exec_results.insert(tokenizer_state, exec_result);
8405        }
8406    }
8407
8408    let needed_queue_len = bytes.len() + 1;
8409    let mut processing_queue = std::mem::take(&mut bufs.processing_queue);
8410    if processing_queue.len() < needed_queue_len {
8411        processing_queue.resize_with(needed_queue_len, ParserStatesByTokenizer::default);
8412    }
8413    for bucket in processing_queue.iter_mut().take(needed_queue_len) {
8414        bucket.clear();
8415    }
8416    processing_queue[0] = std::mem::take(state).into_iter().collect();
8417
8418    let mut offset = 0usize;
8419    while offset < needed_queue_len {
8420        if processing_queue[offset].is_empty() {
8421            offset += 1;
8422            continue;
8423        }
8424
8425        let states_to_process = std::mem::take(&mut processing_queue[offset]);
8426        for (tokenizer_state, mut gss_at_offset) in states_to_process {
8427            let exec_result = if offset == 0 {
8428                bufs.exec_results.remove(&tokenizer_state).unwrap_or_else(|| {
8429                    execute_tokenizer_from_state_small(constraint, &bytes[offset..], tokenizer_state)
8430                })
8431            } else {
8432                execute_tokenizer_from_state_small(constraint, &bytes[offset..], tokenizer_state)
8433            };
8434
8435            if offset == 0
8436                && !gss_at_offset
8437                    .all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
8438            {
8439                gss_at_offset = prune_single_initial_state_for_exec(
8440                    constraint,
8441                    gss_at_offset,
8442                    tokenizer_state,
8443                    &exec_result,
8444                    bytes,
8445                );
8446                if gss_at_offset.is_empty() {
8447                    continue;
8448                }
8449            }
8450
8451            let actionable_terminals = ActionableTerminals::from_gss(constraint, &gss_at_offset);
8452
8453            bufs.terminal_result_cache.clear();
8454
8455            let normalized_matches = collect_unique_actionable_matches(
8456                constraint,
8457                actionable_terminals.as_ref(),
8458                ignore_terminal,
8459                &exec_result.matches,
8460                Some(&mut bufs.seen_matches),
8461            );
8462
8463            for matched in normalized_matches {
8464                let new_offset = offset + matched.width;
8465
8466                if matched.ignored {
8467                    observer.stack(constraint, &gss_at_offset, new_offset);
8468                    if !queue_parser_ignored_reset_state(
8469                        constraint,
8470                        &mut processing_queue,
8471                        &mut bufs.pending_state,
8472                        new_offset,
8473                        bytes.len(),
8474                        gss_at_offset.clone(),
8475                    ) {
8476                        panic!("recursive tokenizer reset routing failed");
8477                    }
8478                    continue;
8479                }
8480
8481                let Some(gss) = advance_terminal_match(
8482                    constraint,
8483                    &gss_at_offset,
8484                    matched.terminal_id,
8485                    &exec_result,
8486                    &mut bufs.advance_result_cache,
8487                    &mut bufs.terminal_result_cache,
8488                ) else {
8489                    continue;
8490                };
8491
8492                observer.stack(constraint, &gss, new_offset);
8493                if !queue_parser_reset_state(
8494                    constraint,
8495                    &mut processing_queue,
8496                    &mut bufs.pending_state,
8497                    new_offset,
8498                    bytes.len(),
8499                    gss,
8500                ) {
8501                    panic!("recursive tokenizer reset routing failed");
8502                }
8503            }
8504
8505            let admission_cache_index = cached_batched_end_state_admission(
8506                constraint,
8507                &gss_at_offset,
8508                &exec_result.end_state,
8509                &mut bufs.admission_cache,
8510            );
8511            for &end_state in &exec_result.end_state {
8512                let may_advance = if let Some(index) = admission_cache_index {
8513                    end_state_may_advance_from_cache_entry(
8514                        constraint,
8515                        end_state,
8516                        &bufs.admission_cache[index],
8517                    )
8518                } else {
8519                    cached_single_end_state_may_advance(
8520                        constraint,
8521                        &gss_at_offset,
8522                        end_state,
8523                        &mut bufs.admission_cache,
8524                    )
8525                };
8526                if !may_advance {
8527                    continue;
8528                }
8529
8530                queue_parser_state(
8531                    &mut processing_queue,
8532                    &mut bufs.pending_state,
8533                    bytes.len(),
8534                    bytes.len(),
8535                    end_state,
8536                    gss_at_offset.clone(),
8537                );
8538            }
8539        }
8540
8541        offset += 1;
8542    }
8543
8544    let new_state = finalize_pending_state(&mut bufs.pending_state);
8545
8546    *state = new_state;
8547    bufs.processing_queue = processing_queue;
8548    if state.is_empty() {
8549        return Err("commit rejected: no valid parser states remain".to_string());
8550    }
8551
8552    Ok(())
8553}
8554
8555impl ConstraintState {
8556    /// Run one commit. A failed commit rejects the state: the frontier becomes
8557    /// empty, the mask is empty, and every later commit errors.
8558    fn commit_transaction<T>(
8559        &mut self,
8560        commit: impl FnOnce(&mut Self, &mut CommitBuffers) -> Result<T, String>,
8561    ) -> Result<T, String> {
8562        let mut buffers = commit_scratch(&self.constraint);
8563        match commit(self, &mut buffers) {
8564            Ok(value) => Ok(value),
8565            Err(error) => {
8566                buffers.reset_all();
8567                self.reject_after_failed_commit();
8568                Err(error)
8569            }
8570        }
8571    }
8572
8573    pub(crate) fn reject_after_failed_commit(&mut self) {
8574        self.state.clear();
8575        if let Some(markers) = self.markers.as_mut() { std::sync::Arc::make_mut(markers).begin(); }
8576        self.advance_generation(false);
8577        self.mask_cache.clear();
8578    }
8579
8580    #[inline]
8581    fn commit_token_actual(&mut self, token_id: u32) -> Result<(), String> {
8582        self.commit_transaction(|this, buffers| this.commit_token_actual_inner(token_id, buffers))
8583    }
8584
8585    fn commit_token_actual_inner(&mut self, token_id: u32, buffers: &mut CommitBuffers) -> Result<(), String> {
8586        let constraint = &self.constraint;
8587        let Some(markers) = self.markers.as_mut() else {
8588            return commit_token_impl(constraint, &mut self.state, buffers, token_id);
8589        };
8590        let markers = std::sync::Arc::make_mut(markers);
8591        markers.begin();
8592        let queries = constraint.marker_queries.as_deref().expect("marker-enabled state has immutable queries");
8593        let base = markers.byte_offset;
8594        let width = token_bytes_for_id(constraint, token_id).map_or(0, |bytes| bytes.len());
8595        let next = base.checked_add(width as u64).expect("marker byte position overflow");
8596        let result = markers.observe(queries, base, |observer|
8597            commit_token_impl_observed(constraint, &mut self.state, buffers, token_id, observer));
8598        markers.finish(queries, next, result.is_ok());
8599        result
8600    }
8601
8602    #[inline]
8603    fn commit_bytes_actual(&mut self, bytes: &[u8]) -> Result<(), String> {
8604        self.commit_transaction(|this, buffers| this.commit_bytes_actual_inner(bytes, buffers))
8605    }
8606
8607    fn commit_bytes_actual_inner(&mut self, bytes: &[u8], buffers: &mut CommitBuffers) -> Result<(), String> {
8608        let constraint = &self.constraint;
8609        let Some(markers) = self.markers.as_mut() else {
8610            return commit_bytes_impl(constraint, &mut self.state, bytes, buffers);
8611        };
8612        let markers = std::sync::Arc::make_mut(markers);
8613        markers.begin();
8614        let queries = constraint.marker_queries.as_deref().expect("marker-enabled state has immutable queries");
8615        let base = markers.byte_offset;
8616        let next = base.checked_add(bytes.len() as u64).expect("marker byte position overflow");
8617        let result = markers.observe(queries, base, |observer|
8618            commit_bytes_impl_observed(constraint, &mut self.state, bytes, buffers, observer));
8619        markers.finish(queries, next, result.is_ok());
8620        result
8621    }
8622
8623    pub(crate) fn knows_token_id(&self, token_id: u32) -> bool {
8624        token_bytes_for_id(&self.constraint, token_id).is_some()
8625            || self.constraint.has_special_token_id(token_id)
8626    }
8627
8628    /// Snapshot the exact runtime state only when a reusable mask is currently
8629    /// cached. `ParserGSS` is Arc-backed, so cloning this small map keeps the
8630    /// old GSS identities alive without copying parser stacks.
8631    #[inline]
8632    fn snapshot_current_mask_state(&mut self) -> Option<ParserStateMap> {
8633        let generation = self.generation();
8634        let cache = self.mask_cache.get_mut().unwrap();
8635        cache
8636            .as_ref()
8637            .is_some_and(|cache_data| cache_data.generation == generation)
8638            .then(|| self.state.clone())
8639    }
8640
8641    /// Advance the commit generation while retaining a cached mask when commit
8642    /// left the complete semantic runtime state unchanged. `ParserStateMap`
8643    /// equality compares tokenizer keys and exact immutable GSS structure;
8644    /// `LeveledGSS` itself checks Arc identity first, so the usual unchanged
8645    /// object case remains a pointer comparison. `fill_mask` is a pure
8646    /// function of this state and the immutable constraint.
8647    #[inline]
8648    fn finish_commit_generation(
8649        &mut self,
8650        previous_state: Option<ParserStateMap>,
8651        commit_succeeded: bool,
8652    ) {
8653        // The rejection path has already cleared the frontier and mask cache,
8654        // and advanced the generation. Do not update them a second time.
8655        if !commit_succeeded {
8656            return;
8657        }
8658        let previous_generation = self.generation();
8659        self.advance_generation(false);
8660        let Some(previous_state) = previous_state else {
8661            return;
8662        };
8663        let mask_state_unchanged = previous_state == self.state
8664            || (self.constraint.uses_dynamic_runtime()
8665                // Ordinary tokenizer quotients cannot interpret scoped
8666                // recursive composition IDs. Only exact state equality above
8667                // is currently proved for retaining a composed result.
8668                && !self.constraint.uses_compact_segmented_parser_runtime()
8669                && (self.dynamic_mask_projection_state_eq(&previous_state, &self.state)
8670                    || (crate::env::var_os(
8671                        "GLRMASK_DISABLE_DYNAMIC_MASK_PARSER_RELATIVE_COMMIT_REUSE",
8672                    )
8673                    .is_none()
8674                        && self.dynamic_parser_relative_vocab_mask_eq(&previous_state))));
8675        if !mask_state_unchanged {
8676            return;
8677        }
8678
8679        let generation = self.generation();
8680        let cache = self.mask_cache.get_mut().unwrap();
8681        if let Some(cache_data) = cache
8682            && cache_data.generation == previous_generation
8683        {
8684            cache_data.generation = generation;
8685        }
8686    }
8687
8688    /// Exact equality in the lexer coordinate actually consumed by dynamic
8689    /// mask generation. A commit may advance the source/runtime lexer through
8690    /// states that are distinct only outside the model-vocabulary horizon; if
8691    /// every correlated parser GSS is unchanged and those source states map to
8692    /// the same mask-execution state, the next-token mask is identical and the
8693    /// already-cached mask can survive the generation bump.
8694    ///
8695    /// This is deliberately stricter than general semantic cache lookup: it
8696    /// does not merge parser alternatives or rely on observation classes. It
8697    /// only replaces the exact tokenizer-state coordinate with the exact
8698    /// finite mask coordinate selected by the constraint.
8699    fn dynamic_mask_projection_state_eq(
8700        &self,
8701        previous: &ParserStateMap,
8702        current: &ParserStateMap,
8703    ) -> bool {
8704        if previous.len() != current.len() {
8705            return false;
8706        }
8707        let vocab = self.constraint.dynamic_mask_vocab_for_runtime();
8708        let exact_initial = self.constraint.tokenizer.initial_state();
8709
8710        // The common case is one correlated lexer/parser branch. Keep that
8711        // path allocation-free and constant-time.
8712        if let ([(previous_state, previous_gss)], [(current_state, current_gss)]) =
8713            (previous.entries.as_slice(), current.entries.as_slice())
8714        {
8715            return previous_gss == current_gss
8716                && (*previous_state == exact_initial) == (*current_state == exact_initial)
8717                && vocab.mask_runtime_state(*previous_state)
8718                    == vocab.mask_runtime_state(*current_state);
8719        }
8720
8721        // Flat GLR frontiers can contain duplicate exact tokenizer keys. Match
8722        // correlated branches as a multiset in mask-coordinate space rather
8723        // than assuming source-state ordering survives quotienting.
8724        let mut matched = vec![false; current.len()];
8725        'previous: for (previous_state, previous_gss) in &previous.entries {
8726            let projected = vocab.mask_runtime_state(*previous_state);
8727            let initial = *previous_state == exact_initial;
8728            for (index, (current_state, current_gss)) in current.entries.iter().enumerate() {
8729                if !matched[index]
8730                    && initial == (*current_state == exact_initial)
8731                    && projected == vocab.mask_runtime_state(*current_state)
8732                    && previous_gss == current_gss
8733                {
8734                    matched[index] = true;
8735                    continue 'previous;
8736                }
8737            }
8738            return false;
8739        }
8740        true
8741    }
8742
8743    /// Prove equality of the next-token mask for the common singleton parser
8744    /// frontier even when the exact lexer residual changed.
8745    ///
8746    /// This proof is deliberately vocabulary- and parser-relative. Two lexer
8747    /// states may differ because one still carries futures for terminals the
8748    /// unchanged parser frontier cannot consume. Those differences do not
8749    /// affect the next model-token mask. We walk the model vocabulary trie in
8750    /// lockstep and compare only matched/future observations for terminals
8751    /// admitted by this parser GSS. Once the lexer states converge, or both
8752    /// no-finalization branches become parser-dead, the complete suffix
8753    /// subtree is equal and no further work is needed.
8754    ///
8755    /// Equal admitted finalizers also need no recursive parser simulation:
8756    /// both sides advance the same GSS on the same terminal and reset to the
8757    /// same lexer initial state, so every post-finalization suffix branch is
8758    /// identical by construction.
8759    fn dynamic_parser_relative_vocab_mask_eq(
8760        &mut self,
8761        previous: &ParserStateMap,
8762    ) -> bool {
8763        let current = &self.state;
8764        if self.constraint.static_dynamic_overlay.is_some()
8765            || self.constraint.uses_compact_segmented_parser_runtime()
8766            || self.constraint.tokenizer.has_any_virtual_runtime()
8767        {
8768            return false;
8769        }
8770        let (left_source, left_gss, right_source, right_gss) =
8771            if let ([(left_source, left_gss)], [(right_source, right_gss)]) =
8772                (previous.entries.as_slice(), current.entries.as_slice())
8773            {
8774                (left_source, left_gss, right_source, right_gss)
8775            } else {
8776                // Conservative multi-branch extension: first pair off every
8777                // branch whose exact correlated lexer/GSS state is unchanged.
8778                // Only if exactly one branch remains on each side do we apply
8779                // the parser-relative lexer proof below.  This covers the
8780                // common GLR shape where one guarded/reset branch is stable
8781                // and one ordinary lexer residual advances, without needing a
8782                // general assignment search over unrelated alternatives.
8783                if previous.len() != current.len() {
8784                    return false;
8785                }
8786                let mut matched = vec![false; current.len()];
8787                let mut unmatched_previous = None::<(&u32, &ParserGSS)>;
8788                for (previous_state, previous_gss) in &previous.entries {
8789                    let exact = current
8790                        .entries
8791                        .iter()
8792                        .enumerate()
8793                        .find(|(index, (current_state, current_gss))| {
8794                            !matched[*index]
8795                                && previous_state == current_state
8796                                && previous_gss == current_gss
8797                        })
8798                        .map(|(index, _)| index);
8799                    if let Some(index) = exact {
8800                        matched[index] = true;
8801                        continue;
8802                    }
8803                    if unmatched_previous
8804                        .replace((previous_state, previous_gss))
8805                        .is_some()
8806                    {
8807                        return false;
8808                    }
8809                }
8810                let Some((left_source, left_gss)) = unmatched_previous else {
8811                    return false;
8812                };
8813                let mut unmatched_current = current
8814                    .entries
8815                    .iter()
8816                    .enumerate()
8817                    .filter(|(index, _)| !matched[*index])
8818                    .map(|(_, pair)| pair);
8819                let Some((right_source, right_gss)) = unmatched_current.next() else {
8820                    return false;
8821                };
8822                if unmatched_current.next().is_some() {
8823                    return false;
8824                }
8825                (left_source, left_gss, right_source, right_gss)
8826            };
8827        if left_gss != right_gss
8828            || !left_gss.all_accs_satisfy(|acc: &TerminalsDisallowed| acc.is_empty())
8829        {
8830            return false;
8831        }
8832
8833        let tokenizer = &self.constraint.tokenizer;
8834        let initial = tokenizer.initial_state();
8835        if (*left_source == initial) != (*right_source == initial)
8836            || tokenizer.state_has_epsilon_transitions(*left_source)
8837            || tokenizer.state_has_epsilon_transitions(*right_source)
8838        {
8839            return false;
8840        }
8841
8842        let (cache_left, cache_right) = if left_source <= right_source {
8843            (*left_source, *right_source)
8844        } else {
8845            (*right_source, *left_source)
8846        };
8847        let candidates = crate::ds::bitset::BitSet::all(
8848            self.constraint.parser_terminal_count() as usize,
8849        );
8850        let mut admitted = exact_admitted_terminals_for_candidates(
8851            &self.constraint,
8852            left_gss,
8853            &candidates,
8854        );
8855        // IGNORE is parser-transparent but still lexer-observable: a live
8856        // ignore future permits a token boundary, and an ignore match resets
8857        // the lexer while leaving the current GSS unchanged.  Treat it as an
8858        // always-observed terminal in this equivalence proof. Equal ignore
8859        // events therefore converge exactly just like equal parser-admitted
8860        // finalizers, except without a parser advance.
8861        if let Some(ignore) = self.constraint.ignore_terminal {
8862            admitted.set(ignore as usize);
8863        }
8864        if admitted.count_ones() == 0 {
8865            return true;
8866        }
8867
8868        let mut buffers = commit_scratch(&self.constraint);
8869        if buffers
8870            .parser_relative_mask_eq_cache
8871            .iter()
8872            .any(|entry| {
8873                entry.left == cache_left
8874                    && entry.right == cache_right
8875                    && entry.admitted == admitted
8876            })
8877        {
8878            if crate::env::var_os("GLRMASK_PROFILE_DYNAMIC_MASK_COMMIT_REUSE").is_some() {
8879                eprintln!(
8880                    "[glrmask/profile][parser_relative_commit_reuse] generation={} result=cache_hit left={} right={} admitted={}",
8881                    self.generation(),
8882                    left_source,
8883                    right_source,
8884                    admitted.count_ones(),
8885                );
8886            }
8887            return true;
8888        }
8889        // A new relation certificate can cost tens of microseconds. If the
8890        // destination state already has a materialized global dynamic-mask
8891        // cache entry, proving equality with the previous state cannot beat
8892        // simply letting the next fill copy that existing result. Keep this
8893        // lookup below all cheap structural/relation-cache gates so ordinary
8894        // commits never pay dynamic-mask key construction merely to decline.
8895        if super::dynamic_mask::dynamic_mask_state_has_cached_result(self) {
8896            return false;
8897        }
8898
8899        #[inline(always)]
8900        fn equal_under_mask(
8901            left: &crate::ds::bitset::BitSet,
8902            right: &crate::ds::bitset::BitSet,
8903            mask: &crate::ds::bitset::BitSet,
8904        ) -> bool {
8905            left.words()
8906                .iter()
8907                .zip(right.words())
8908                .zip(mask.words())
8909                .all(|((&left, &right), &mask)| ((left ^ right) & mask) == 0)
8910        }
8911
8912        #[inline(always)]
8913        fn any_under_mask(
8914            value: &crate::ds::bitset::BitSet,
8915            mask: &crate::ds::bitset::BitSet,
8916        ) -> bool {
8917            value
8918                .words()
8919                .iter()
8920                .zip(mask.words())
8921                .any(|(&value, &mask)| value & mask != 0)
8922        }
8923
8924        let compare = |left: u32, right: u32| -> Option<(bool, bool)> {
8925            const DEAD: u32 = u32::MAX;
8926            if left == DEAD || right == DEAD {
8927                let live = |state: u32| {
8928                    state != DEAD
8929                        && (state == initial
8930                            || any_under_mask(
8931                                tokenizer.matched_terminal_bitset(state),
8932                                &admitted,
8933                            )
8934                            || any_under_mask(
8935                                tokenizer.possible_future_terminals(state),
8936                                &admitted,
8937                            ))
8938                };
8939                let left_live = live(left);
8940                let right_live = live(right);
8941                return Some((left_live == right_live, left_live && right_live));
8942            }
8943            if tokenizer.state_has_epsilon_transitions(left)
8944                || tokenizer.state_has_epsilon_transitions(right)
8945                || (left == initial) != (right == initial)
8946            {
8947                return None;
8948            }
8949            let matched_equal = equal_under_mask(
8950                tokenizer.matched_terminal_bitset(left),
8951                tokenizer.matched_terminal_bitset(right),
8952                &admitted,
8953            );
8954            let futures_equal = equal_under_mask(
8955                tokenizer.possible_future_terminals(left),
8956                tokenizer.possible_future_terminals(right),
8957                &admitted,
8958            );
8959            if !matched_equal || !futures_equal {
8960                return Some((false, true));
8961            }
8962            let live = left == initial
8963                || any_under_mask(tokenizer.matched_terminal_bitset(left), &admitted)
8964                || any_under_mask(tokenizer.possible_future_terminals(left), &admitted);
8965            Some((true, live))
8966        };
8967
8968        let Some((root_equal, root_live)) = compare(*left_source, *right_source) else {
8969            return false;
8970        };
8971        if !root_equal {
8972            return false;
8973        }
8974        if !root_live || left_source == right_source {
8975            return true;
8976        }
8977
8978        let vocab = self.constraint.dynamic_mask_vocab_for_runtime();
8979        let trie = vocab.trie.as_ref();
8980        let max_byte_steps = crate::env::var(
8981            "GLRMASK_DYNAMIC_MASK_PARSER_RELATIVE_COMMIT_REUSE_MAX_STEPS",
8982        )
8983        .ok()
8984        .and_then(|value| value.trim().parse::<usize>().ok())
8985        // Speculative commit-time proof work must stay well below the cost of
8986        // an ordinary full vocabulary mask. Successful broad-interior
8987        // equivalences converge rapidly because most first-byte branches either
8988        // die under the parser observation or enter the same lexer state. A
8989        // fixed transition-work budget keeps adversarial/non-equivalent pairs
8990        // from degenerating into a second full vocabulary traversal.
8991        .unwrap_or(2_048);
8992        let started = crate::env::var_os("GLRMASK_PROFILE_DYNAMIC_MASK_COMMIT_REUSE")
8993            .is_some()
8994            .then(std::time::Instant::now);
8995        let mut stack = vec![(0u32, *left_source, *right_source)];
8996        let mut visited_nodes = 0usize;
8997        let mut byte_steps = 0usize;
8998        let mut converged_subtrees = 0usize;
8999        let mut dead_subtrees = 0usize;
9000        // Reuse the existing byte-budget branch as the one-shot checkpoint for
9001        // the stronger terminal-observation quotient. Grammars without a
9002        // prepared quotient retain the historical 2,048-step budget exactly.
9003        // With a prepared quotient, pause once at 256 steps; if the quotient
9004        // cannot certify equality, restore the historical budget and continue.
9005        const TERMINAL_OBSERVATION_QUOTIENT_CHECKPOINT: usize = 256;
9006        let mut byte_step_budget = if max_byte_steps > TERMINAL_OBSERVATION_QUOTIENT_CHECKPOINT
9007            && vocab.shares_terminal_observation_class(*left_source, *right_source)
9008        {
9009            TERMINAL_OBSERVATION_QUOTIENT_CHECKPOINT
9010        } else {
9011            max_byte_steps
9012        };
9013
9014        while let Some((node, left_state, right_state)) = stack.pop() {
9015            visited_nodes += 1;
9016            for edge in trie.children(node) {
9017                let mut left = left_state;
9018                let mut right = right_state;
9019                let mut subtree_done = false;
9020                for &byte in trie.edge_bytes(edge) {
9021                    if left == right {
9022                        converged_subtrees += 1;
9023                        subtree_done = true;
9024                        break;
9025                    }
9026                    byte_steps += 1;
9027                    if byte_steps > byte_step_budget
9028                        || tokenizer.state_has_epsilon_transitions(left)
9029                        || tokenizer.state_has_epsilon_transitions(right)
9030                    {
9031                        if byte_steps > byte_step_budget && byte_step_budget < max_byte_steps {
9032                            byte_step_budget = max_byte_steps;
9033                            if try_terminal_observation_quotient_commit_reuse(
9034                                &mut buffers,
9035                                self.generation(),
9036                                vocab,
9037                                tokenizer,
9038                                *left_source,
9039                                *right_source,
9040                                &admitted,
9041                                cache_left,
9042                                cache_right,
9043                                visited_nodes,
9044                                byte_steps,
9045                                started,
9046                            ) {
9047                                return true;
9048                            }
9049                        }
9050                        if byte_steps > byte_step_budget
9051                            || tokenizer.state_has_epsilon_transitions(left)
9052                            || tokenizer.state_has_epsilon_transitions(right)
9053                        {
9054                            if let Some(started) = started {
9055                                eprintln!(
9056                                    "[glrmask/profile][parser_relative_commit_reuse] generation={} result=decline reason={} nodes={} bytes={} converged={} dead={} elapsed_us={:.1}",
9057                                    self.generation(),
9058                                    if byte_steps > byte_step_budget { "budget" } else { "epsilon" },
9059                                    visited_nodes,
9060                                    byte_steps,
9061                                    converged_subtrees,
9062                                    dead_subtrees,
9063                                    started.elapsed().as_secs_f64() * 1e6,
9064                                );
9065                            }
9066                            return false;
9067                        }
9068                    }
9069                    let left_next = tokenizer.get_transition(left, byte);
9070                    let right_next = tokenizer.get_transition(right, byte);
9071                    let Some((equal, live)) = compare(left_next, right_next) else {
9072                        if let Some(started) = started {
9073                            eprintln!(
9074                                "[glrmask/profile][parser_relative_commit_reuse] generation={} result=decline reason=epsilon_target nodes={} bytes={} converged={} dead={} elapsed_us={:.1}",
9075                                self.generation(),
9076                                visited_nodes,
9077                                byte_steps,
9078                                converged_subtrees,
9079                                dead_subtrees,
9080                                started.elapsed().as_secs_f64() * 1e6,
9081                            );
9082                        }
9083                        return false;
9084                    };
9085                    if !equal {
9086                        if let Some(started) = started {
9087                            eprintln!(
9088                                "[glrmask/profile][parser_relative_commit_reuse] generation={} result=different nodes={} bytes={} converged={} dead={} elapsed_us={:.1}",
9089                                self.generation(),
9090                                visited_nodes,
9091                                byte_steps,
9092                                converged_subtrees,
9093                                dead_subtrees,
9094                                started.elapsed().as_secs_f64() * 1e6,
9095                            );
9096                        }
9097                        return false;
9098                    }
9099                    if !live {
9100                        dead_subtrees += 1;
9101                        subtree_done = true;
9102                        break;
9103                    }
9104                    left = left_next;
9105                    right = right_next;
9106                }
9107                if subtree_done {
9108                    continue;
9109                }
9110                if left == right {
9111                    converged_subtrees += 1;
9112                    continue;
9113                }
9114                stack.push((edge.child, left, right));
9115            }
9116        }
9117
9118        if let Some(started) = started {
9119            eprintln!(
9120                "[glrmask/profile][parser_relative_commit_reuse] generation={} result=equal left={} right={} admitted={} nodes={} bytes={} converged={} dead={} elapsed_us={:.1}",
9121                self.generation(),
9122                left_source,
9123                right_source,
9124                admitted.count_ones(),
9125                visited_nodes,
9126                byte_steps,
9127                converged_subtrees,
9128                dead_subtrees,
9129                started.elapsed().as_secs_f64() * 1e6,
9130            );
9131        }
9132        const CACHE_CAPACITY: usize = 8;
9133        if buffers.parser_relative_mask_eq_cache.len() == CACHE_CAPACITY {
9134            buffers.parser_relative_mask_eq_cache.remove(0);
9135        }
9136        buffers
9137            .parser_relative_mask_eq_cache
9138            .push(ParserRelativeMaskEqCacheEntry {
9139                left: cache_left,
9140                right: cache_right,
9141                admitted,
9142            });
9143        true
9144    }
9145
9146    /// Advances the state by the token. If it isn't allowed, returns `false` and terminates the state.
9147    #[must_use]
9148    pub fn commit_token(
9149        &mut self,
9150        token_id: u32,
9151    ) -> bool {
9152        self.commit_token_raw(token_id).is_ok()
9153    }
9154
9155
9156    /// Return Some when root termination policy handles this commitment.
9157    fn commit_end_token(&mut self, token_id: u32) -> Option<Result<(), String>> {
9158        if self.terminated() {
9159            self.reject_after_failed_commit();
9160            return Some(Err("sequence has already terminated".to_owned()));
9161        }
9162        if self.constraint.end_tokens.binary_search(&token_id).is_err() {
9163            return None;
9164        }
9165        if !self.frontier_complete() {
9166            // An end token before a complete match is a disallowed commit. The
9167            // state is rejected, mirroring every other failed commit.
9168            self.reject_after_failed_commit();
9169            return Some(Err(format!(
9170                "commit_token: end token {token_id} is not allowed for this prefix"
9171            )));
9172        }
9173        if let Some(markers) = self.markers.as_mut() { std::sync::Arc::make_mut(markers).begin(); }
9174        self.advance_generation(true);
9175        self.mask_cache.clear();
9176        Some(Ok(()))
9177    }
9178
9179    pub(crate) fn commit_token_raw(&mut self, token_id: u32) -> Result<(), String> {
9180        if !self.constraint.parser_has_controls() { return self.commit_token_raw_inner(token_id); }
9181        match glrmask_invariant::__private::catch_compilation_resource_limit(|| self.commit_token_raw_inner(token_id)) {
9182            Ok(result) => result,
9183            Err(message) => {
9184                self.reject_after_control_resource_limit();
9185                panic!("parser resource limit: {message}")
9186            }
9187        }
9188    }
9189
9190    fn reject_after_control_resource_limit(&mut self) {
9191        self.reject_after_failed_commit();
9192        // An unwind may have crossed a diagnostic mask guard. Do not retain
9193        // a poisoned mutex or a cached mask that was computed mid-unwind.
9194        self.mask_cache.clear();
9195        // Unwinding scratch leases discard their temporary storage.
9196    }
9197
9198    fn commit_token_raw_inner(&mut self, token_id: u32) -> Result<(), String> {
9199        if let Some(result) = self.commit_end_token(token_id) { return result; }
9200        let constraint = self.constraint.clone();
9201        let bytes = token_bytes_for_id(&constraint, token_id);
9202        if !self.knows_token_id(token_id) {
9203            self.reject_after_failed_commit();
9204            return Err(format!(
9205                "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
9206            ));
9207        }
9208        let assertion_flags = commit_assertion_flags();
9209        let was_in_mask = snapshot_mask_membership(self, token_id, assertion_flags);
9210        let equivalence_reference = (assertion_flags & COMMIT_ASSERT_FAST_PATH_EQUIVALENCE != 0)
9211            .then(|| self.state.clone());
9212        let mask_state_before_commit = self.snapshot_current_mask_state();
9213        let result = self.commit_token_actual(token_id);
9214        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9215        assert_commit_oracles(
9216            &constraint,
9217            token_id,
9218            bytes,
9219            was_in_mask,
9220            equivalence_reference,
9221            &self.state,
9222            result.is_ok(),
9223        );
9224        result
9225    }
9226
9227    pub(crate) fn commit_token_dynamic(&mut self, token_id: u32) -> Result<(), String> {
9228        if let Some(result) = self.commit_end_token(token_id) { return result; }
9229        let constraint = self.constraint.clone();
9230        let bytes = token_bytes_for_id(&constraint, token_id);
9231        if !self.knows_token_id(token_id) {
9232            self.reject_after_failed_commit();
9233            return Err(format!(
9234                "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
9235            ));
9236        }
9237        let assertion_flags = commit_assertion_flags();
9238        let was_in_mask = if assertion_flags & COMMIT_ASSERT_MASK_EQUIVALENCE != 0 {
9239            let mut mask = vec![0u32; constraint.mask_bit_len().div_ceil(32)];
9240            self.fill_mask_dynamic(&mut mask);
9241            Some(token_in_mask(&mask, token_id))
9242        } else {
9243            None
9244        };
9245        let mask_state_before_commit = self.snapshot_current_mask_state();
9246        let result = self.commit_token_actual(token_id);
9247        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9248        assert_commit_oracles(
9249            &constraint,
9250            token_id,
9251            bytes,
9252            was_in_mask,
9253            None,
9254            &self.state,
9255            result.is_ok(),
9256        );
9257        result
9258    }
9259
9260    pub(crate) fn commit_token_timed_ns(&mut self, token_id: u32) -> Result<u64, String> {
9261        if self.terminated() || !self.constraint.end_tokens.is_empty() {
9262            let policy_started = std::time::Instant::now();
9263            if let Some(result) = self.commit_end_token(token_id) {
9264                return result.map(|()| policy_started.elapsed().as_nanos() as u64);
9265            }
9266        }
9267        use std::time::Instant;
9268
9269        let constraint = self.constraint.clone();
9270        let bytes = token_bytes_for_id(&constraint, token_id);
9271        let assertion_flags = commit_assertion_flags();
9272        let was_in_mask = snapshot_mask_membership(self, token_id, assertion_flags);
9273        let equivalence_reference = (assertion_flags & COMMIT_ASSERT_FAST_PATH_EQUIVALENCE != 0)
9274            .then(|| self.state.clone());
9275        let mask_state_before_commit = self.snapshot_current_mask_state();
9276        let start = Instant::now();
9277        let result = self.commit_token_actual(token_id);
9278        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9279        // Cache-preservation proofs are part of commit's runtime cost. Keep
9280        // them inside the timed interval so TBM/commit reporting cannot make a
9281        // mask optimization look free merely by shifting work after the timer.
9282        let total_ns = start.elapsed().as_nanos() as u64;
9283        assert_commit_oracles(
9284            &constraint,
9285            token_id,
9286            bytes,
9287            was_in_mask,
9288            equivalence_reference,
9289            &self.state,
9290            result.is_ok(),
9291        );
9292        result.map(|()| total_ns)
9293    }
9294
9295    pub(crate) fn commit_token_profiled(&mut self, token_id: u32) -> Result<CommitProfile, String> {
9296        if let Some(result) = self.commit_end_token(token_id) {
9297            return result.map(|()| CommitProfile::default());
9298        }
9299        let constraint = self.constraint.clone();
9300        let bytes = token_bytes_for_id(&constraint, token_id);
9301        let has_special = constraint.has_special_token_id(token_id);
9302        if bytes.is_none() && !has_special {
9303            self.reject_after_failed_commit();
9304            return Err(format!(
9305                "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
9306            ));
9307        }
9308        let assertion_flags = commit_assertion_flags();
9309        let was_in_mask = snapshot_mask_membership(self, token_id, assertion_flags);
9310        let equivalence_reference = (assertion_flags & COMMIT_ASSERT_FAST_PATH_EQUIVALENCE != 0)
9311            .then(|| self.state.clone());
9312        let mask_state_before_commit = self.snapshot_current_mask_state();
9313        let total_started_at = std::time::Instant::now();
9314        let result = self.commit_transaction(|this, buffers| {
9315            expand_runtime_product_states(&constraint, &mut this.state);
9316            let special = if has_special {
9317                advance_special_token_paths_profiled(&constraint, &this.state, token_id, None)
9318            } else {
9319                SpecialTokenAdvanceProfile::default()
9320            };
9321            let mut profile = if let Some(bytes) = bytes {
9322                match commit_bytes_impl_profiled(
9323                    &constraint,
9324                    &mut this.state,
9325                    bytes,
9326                    buffers,
9327                    None,
9328                    true,
9329                ) {
9330                    Ok(profile) => profile,
9331                    Err(_) => {
9332                        this.state.clear();
9333                        buffers.reset_all();
9334                        CommitProfile::default()
9335                    }
9336                }
9337            } else {
9338                this.state.clear();
9339                CommitProfile::default()
9340            };
9341            apply_special_token_advance_profile(&mut profile, &special);
9342            let special_merge_result =
9343                merge_special_token_paths(&constraint, &mut this.state, special.paths);
9344            coalesce_uniform_runtime_source_states(&constraint, &mut this.state);
9345            profile.total_ns = total_started_at.elapsed().as_nanos() as u64;
9346            special_merge_result
9347                .and_then(|()| finish_token_commit(&this.state))
9348                .map(|()| profile)
9349        });
9350        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9351        assert_commit_oracles(
9352            &constraint,
9353            token_id,
9354            bytes,
9355            was_in_mask,
9356            equivalence_reference,
9357            &self.state,
9358            result.is_ok(),
9359        );
9360        result
9361    }
9362
9363    pub(crate) fn commit_token_per_advance(
9364        &mut self,
9365        token_id: u32,
9366    ) -> Result<(Vec<PerAdvanceEntry>, Vec<(u32, Vec<Vec<u32>>)>, CommitProfile), String> {
9367        if let Some(result) = self.commit_end_token(token_id) {
9368            return result.map(|()| (Vec::new(), final_stacks(&self.state), CommitProfile::default()));
9369        }
9370        let constraint = self.constraint.clone();
9371        let bytes = token_bytes_for_id(&constraint, token_id);
9372        let has_special = constraint.has_special_token_id(token_id);
9373        if bytes.is_none() && !has_special {
9374            self.reject_after_failed_commit();
9375            return Err(format!(
9376                "commit_token: token_id {token_id} not in vocabulary or special-token terminals"
9377            ));
9378        }
9379        let assertion_flags = commit_assertion_flags();
9380        let was_in_mask = snapshot_mask_membership(self, token_id, assertion_flags);
9381        let equivalence_reference = (assertion_flags & COMMIT_ASSERT_FAST_PATH_EQUIVALENCE != 0)
9382            .then(|| self.state.clone());
9383        let mask_state_before_commit = self.snapshot_current_mask_state();
9384        let total_started_at = std::time::Instant::now();
9385        let mut advances = Vec::new();
9386        let result = self.commit_transaction(|this, buffers| {
9387            expand_runtime_product_states(&constraint, &mut this.state);
9388            let special = if has_special {
9389                advance_special_token_paths_profiled(
9390                    &constraint,
9391                    &this.state,
9392                    token_id,
9393                    Some(&mut advances),
9394                )
9395            } else {
9396                SpecialTokenAdvanceProfile::default()
9397            };
9398            let mut profile = if let Some(bytes) = bytes {
9399                match commit_bytes_impl_profiled(
9400                    &constraint,
9401                    &mut this.state,
9402                    bytes,
9403                    buffers,
9404                    Some(&mut advances),
9405                    profile_allow_fast_paths(),
9406                ) {
9407                    Ok(profile) => profile,
9408                    Err(_) => {
9409                        this.state.clear();
9410                        buffers.clear_all();
9411                        advances.clear();
9412                        CommitProfile::default()
9413                    }
9414                }
9415            } else {
9416                this.state.clear();
9417                CommitProfile::default()
9418            };
9419            apply_special_token_advance_profile(&mut profile, &special);
9420            let special_merge_result =
9421                merge_special_token_paths(&constraint, &mut this.state, special.paths);
9422            coalesce_uniform_runtime_source_states(&constraint, &mut this.state);
9423            profile.total_ns = total_started_at.elapsed().as_nanos() as u64;
9424            special_merge_result
9425                .and_then(|()| finish_token_commit(&this.state))
9426                .map(|()| (advances, final_stacks(&this.state), profile))
9427        });
9428        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9429        assert_commit_oracles(
9430            &constraint,
9431            token_id,
9432            bytes,
9433            was_in_mask,
9434            equivalence_reference,
9435            &self.state,
9436            result.is_ok(),
9437        );
9438        result
9439    }
9440
9441    /// Advances the state by the bytes. If they aren't allowed, returns `false` and terminates the state.
9442    #[must_use]
9443    pub fn commit_bytes(&mut self, bytes: &[u8]) -> bool {
9444        if bytes.is_empty() {
9445            return !self.is_terminated() || self.is_accepting();
9446        }
9447        self.commit_bytes_raw(bytes).is_ok()
9448    }
9449
9450    pub(crate) fn commit_bytes_raw(&mut self, bytes: &[u8]) -> Result<(), String> {
9451        if !self.constraint.parser_has_controls() { return self.commit_bytes_raw_inner(bytes); }
9452        match glrmask_invariant::__private::catch_compilation_resource_limit(|| self.commit_bytes_raw_inner(bytes)) {
9453            Ok(result) => result,
9454            Err(message) => {
9455                self.reject_after_control_resource_limit();
9456                panic!("parser resource limit: {message}")
9457            }
9458        }
9459    }
9460
9461    fn commit_bytes_raw_inner(&mut self, bytes: &[u8]) -> Result<(), String> {
9462        if self.terminated() {
9463            self.reject_after_failed_commit();
9464            return Err("sequence has already terminated".to_owned());
9465        }
9466        if let Some(markers) = self.markers.as_mut() { std::sync::Arc::make_mut(markers).begin(); }
9467        let mask_state_before_commit = self.snapshot_current_mask_state();
9468        let result = self.commit_bytes_actual(bytes);
9469        self.finish_commit_generation(mask_state_before_commit, result.is_ok());
9470        result
9471    }
9472
9473}
9474
9475#[cfg(test)]
9476mod tests {
9477    use glrmask_vocab::__private::VocabExt as _;
9478    use super::*;
9479    use crate::{runtime::Constraint as Constraint, DynamicConstraint, Grammar, Vocab};
9480    use std::collections::BTreeSet;
9481
9482    type CanonicalCommitState =
9483        Vec<(u32, Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)>)>;
9484
9485    #[test]
9486    fn unique_actionable_top_matches_isolation_reference_including_empty_paths() {
9487        fn reference(constraint: &Constraint, gss: &ParserGSS, terminal: u32) -> Option<ParserGSS> {
9488            if constraint.parser_has_controls() || template_advance_selected(constraint) {
9489                return None;
9490            }
9491            let mut selected = None;
9492            for top in gss.peek_values() {
9493                let Some(action) = constraint.table.action(top, terminal) else { continue; };
9494                if selected.is_some() { return None; }
9495                selected = Some((top, action));
9496            }
9497            let (top, action) = selected?;
9498            let isolated = gss.isolate(Some(top));
9499            (!isolated.is_empty())
9500                .then(|| apply_single_top_action_fast(constraint, &isolated, top, terminal, action))
9501                .flatten()
9502        }
9503        let vocab = Vocab::from_entries_unchecked(["a", "b", "ab", "ba", ",", " ", "(", ")"]
9504            .into_iter().enumerate().map(|(i, token)| (i as u32, token.as_bytes().to_vec())).collect());
9505        let grammars = [
9506            r#"start start; t A = "a" | "ab"; t B = "a" | "ba";
9507                nt start = A B? | B A?;"#,
9508            r#"start start; ignore WS; t WS = " "+; t A = "a"+; t B = "a"+ "b"?;
9509                nt item = A | B; nt start = item ("," item)*;"#,
9510            r#"start start; t A = "a"; nt start = A? | "(" `start` ")";"#,
9511        ];
9512        let empty = ParserGSS::from_single_stack(Vec::new(), TerminalsDisallowed::new());
9513        let mut exclusive = 0usize;
9514        let mut with_empty = 0usize;
9515        let mut comparisons = 0usize;
9516        for source in grammars {
9517            let built = Constraint::compile(Grammar::glrm(source), &vocab).unwrap();
9518            let loaded = Constraint::load(built.save(), &vocab).unwrap();
9519            for constraint in [&built, &loaded] {
9520                let mut frontier = vec![constraint.start()];
9521                let mut seen = BTreeSet::new();
9522                for depth in 0..=3 {
9523                    let mut next = Vec::new();
9524                    for state in frontier {
9525                        if !seen.insert(canonical_commit_state(&state.state)) { continue; }
9526                        for gss in state.state.values() {
9527                            for input in [gss.clone(), gss.merge(&empty)] {
9528                                if let Some(top) = input.single_exclusive_top_value() {
9529                                    exclusive += 1;
9530                                    assert!(input.ptr_eq(&input.isolate(Some(top))));
9531                                } else {
9532                                    with_empty += 1;
9533                                }
9534                                for terminal in 0..constraint.parser_terminal_count() {
9535                                    let expected = reference(constraint, &input, terminal);
9536                                    let actual = try_advance_unique_actionable_top_fast(constraint, &input, terminal);
9537                                    assert_eq!(actual.as_ref().map(canonical_gss), expected.as_ref().map(canonical_gss),
9538                                        "terminal={terminal} depth={depth} source={source}");
9539                                    comparisons += 1;
9540                                }
9541                            }
9542                        }
9543                        if depth < 3 {
9544                            let mask = state.mask();
9545                            for (token, _) in constraint.token_bytes_iter() {
9546                                if !token_in_mask(&mask, token) { continue; }
9547                                let mut advanced = state.clone();
9548                                assert!(advanced.commit_token(token));
9549                                next.push(advanced);
9550                            }
9551                        }
9552                    }
9553                    frontier = next;
9554                }
9555            }
9556        }
9557        assert!(exclusive > 0 && with_empty > 0 && comparisons > 20);
9558    }
9559
9560    #[test]
9561    fn reduce_chain_output_factoring_preserves_stacks_and_exclusions() {
9562        let plain = TerminalsDisallowed::new();
9563        let guarded = plain.clone().with_insert(7, 3);
9564        for depth in [1usize, 2, 14, 64, 256] {
9565            let prefix: Vec<u32> = (0..depth as u32).collect();
9566            let extend = |suffix: &[u32]| {
9567                let mut stack = prefix.clone();
9568                stack.extend_from_slice(suffix);
9569                stack
9570            };
9571            let cases = vec![
9572                vec![],
9573                vec![(prefix.clone(), plain.clone())],
9574                vec![(prefix.clone(), plain.clone()), (prefix.clone(), plain.clone())],
9575                vec![(extend(&[500]), plain.clone()), (extend(&[501]), plain.clone())],
9576                vec![(extend(&[500, 502]), plain.clone()), (extend(&[501, 502]), plain.clone())],
9577                vec![(prefix.clone(), plain.clone()), (extend(&[501]), plain.clone())],
9578                vec![(vec![], plain.clone()), (prefix.clone(), plain.clone())],
9579                vec![(prefix.clone(), plain.clone()), (prefix.clone(), guarded.clone())],
9580                vec![(extend(&[500]), guarded.clone()), (extend(&[501]), plain.clone())],
9581            ];
9582            for outputs in cases {
9583                let reference = ParserGSS::from_stacks(&outputs);
9584                let actual = materialize_reduce_chain_outputs(outputs);
9585                assert!(actual.semantically_eq(&reference, 32).unwrap(), "depth={depth}");
9586            }
9587        }
9588    }
9589
9590    #[test]
9591    fn lexer_only_actionable_cache_keeps_distinct_lexer_lanes() {
9592        let vocab = Vocab::from_entries_unchecked(vec![
9593            (0, b"ab".to_vec()), (1, b"cd".to_vec()),
9594            (2, b"abcd".to_vec()), (3, b"abx".to_vec()),
9595            (4, b"zabc".to_vec()),
9596        ]);
9597        let compiled = Constraint::compile(Grammar::glrm(r#"
9598            start document;
9599            pragma glrmask {
9600                lexer group first = A, C;
9601                lexer group second = B;
9602            }
9603            t A = "abx";
9604            t C = "abc";
9605            t B = "abcd";
9606            nt document = A | B | "z" C;
9607        "#), &vocab).unwrap();
9608        for constraint in [&compiled, &Constraint::load(compiled.save(), &vocab).unwrap()] {
9609            let mut state = constraint.start();
9610            assert!(state.commit_bytes(b"ab"));
9611            let mut reference = state.state.clone();
9612            assert!(commit_token_no_fast_path_reference(constraint, &mut reference, 1).is_ok());
9613            let mut actual = state.state.clone();
9614            let mut scratch = CommitBuffers::default();
9615            assert!(commit_token_impl(constraint, &mut actual, &mut scratch, 1).is_ok(),
9616                "lexer lanes sharing parser stacks must not share actionable-match answers");
9617            assert_commit_fast_path_equivalence(constraint, state.state.clone(), 1, &actual, true);
9618        }
9619    }
9620
9621    #[test]
9622    fn unfinished_ignore_prefixes_survive_all_commit_paths() {
9623        let fragments: &[&[u8]] = &[
9624            b"a", b"+", b"b", b"//", b"/////", b"line", b"\n",
9625            b"/*", b"/***", b"body", b"*/", b" /*unfinished", b"//line\n+b",
9626        ];
9627        let vocab = Vocab::from_entries_unchecked(fragments.iter().enumerate()
9628            .map(|(id, bytes)| (id as u32, bytes.to_vec())).collect());
9629        for partitions in [
9630            "",
9631            "pragma glrmask { lexer group words = WORD; lexer group trivia = WS; }",
9632        ] {
9633            let source = format!(r#"
9634                start document;
9635                {partitions}
9636                ignore WS;
9637                t WS = " "+ | "//" b/[^\n]/* "\n" | "/*" (b/[^*]/ | "*" b/[^\/]/)* "*/";
9638                t WORD = /[a-z]+/;
9639                nt document = WORD ("+" WORD)*;
9640            "#);
9641            let built = Constraint::compile(Grammar::glrm(&source), &vocab).unwrap();
9642            let loaded = Constraint::load(built.save(), &vocab).unwrap();
9643            for constraint in [&built, &loaded] {
9644                for ids in [
9645                    vec![0,4,5,6,1,2],
9646                    vec![0,7,9,10,1,2],
9647                    vec![0,8,9,10,1,2],
9648                    vec![0,11,10,1,2],
9649                    vec![0,12],
9650                ] {
9651                    let mut actual = constraint.start();
9652                    let mut bytewise = constraint.start();
9653                    for token in ids {
9654                        let before = actual.state.clone();
9655                        assert!(token_in_mask(&actual.mask(), token),
9656                            "ignore prefix absent from mask partitions={partitions} token={token}");
9657                        let mut reference = before.clone();
9658                        assert!(commit_token_no_fast_path_reference(constraint, &mut reference, token).is_ok(),
9659                            "general queue must retain unfinished ignore token={token}");
9660                        assert!(actual.commit_token(token));
9661                        assert_commit_fast_path_equivalence(constraint, before, token, &actual.state, true);
9662                        for byte in fragments[token as usize] { assert!(bytewise.commit_bytes(&[*byte])); }
9663                        assert_eq!(actual.mask(), bytewise.mask(), "token-vs-byte prefix token={token}");
9664                    }
9665                    assert!(actual.is_accepting());
9666                    assert!(bytewise.is_accepting());
9667                }
9668            }
9669        }
9670    }
9671
9672    #[test]
9673    fn recursive_batched_admission_matches_scalar_provider_reference() {
9674        use crate::ds::bitset::BitSet;
9675        let vocab = Vocab::from_entries_unchecked(b"[ab]! ".iter().enumerate()
9676            .map(|(id,byte)|(id as u32,vec![*byte])).collect());
9677        for source in [
9678            r#"start child; t WORD = /[ab]+/; nt child = WORD;"#,
9679            r#"start child; ignore WS; t WS = " "+; t WORD = /[ab]+/; nt child = WORD?;"#,
9680            r#"start child; t A = "a"; t AB = "ab"; nt child = (A | AB)*;"#,
9681        ] {
9682            let child = Constraint::compile(Grammar::glrm(source), &vocab).unwrap();
9683            let middle = Constraint::compile(Grammar::glrm(
9684                r#"start middle; extern grammar child; nt middle = "[" child "]";"#,
9685            ), &vocab).unwrap().bind_grammar_dynamic_boundary("child", child).unwrap();
9686            let outer = Constraint::compile(Grammar::glrm(
9687                r#"start outer; extern grammar middle; nt outer = middle "!";"#,
9688            ), &vocab).unwrap().bind_grammar_dynamic_boundary("middle", middle).unwrap();
9689            let loaded = Constraint::load(outer.save(), &vocab).unwrap();
9690            for constraint in [&outer, &loaded] {
9691                for prefix in ["", "[", "[a", "[ab", "[ab]", "[ab]!", "[ ", "[]"] {
9692                    let mut state = constraint.start();
9693                    if !state.commit_bytes(prefix.as_bytes()) {continue;}
9694                    let runtime = &state.constraint;
9695                    let count = runtime_terminal_count(runtime);
9696                    for (_, gss) in state.state.iter() {
9697                        for stride in [1,2,3] {
9698                            let mut candidates=BitSet::new(count);
9699                            for terminal in (0..count).step_by(stride) {candidates.set(terminal);}
9700                            let actual=runtime.compact_segmented_parser_admitted_terminals(gss,&candidates).unwrap();
9701                            let mut expected=BitSet::new(count);
9702                            for terminal in candidates.iter_ones() {
9703                                if runtime.compact_segmented_parser_may_advance_on(gss,terminal as u32).unwrap() {
9704                                    expected.set(terminal);
9705                                }
9706                            }
9707                            assert_eq!(actual,expected,"prefix={prefix} stride={stride} source={source}");
9708                            assert_eq!(runtime.compact_segmented_parser_may_advance_on_any(gss,&candidates),Some(!expected.is_empty()));
9709                        }
9710                    }
9711                }
9712            }
9713        }
9714    }
9715
9716    #[test]
9717    fn unchanged_runtime_state_preserves_fill_mask_cache() {
9718        let vocab = Vocab::from_entries_unchecked(vec![
9719            (0, b"a".to_vec()),
9720            (1, b"aa".to_vec()),
9721            (2, b"b".to_vec()),
9722        ]);
9723        let constraint = Constraint::compile(
9724            Grammar::glrm(
9725                r#"glrm 1;
9726                start start;
9727                t A = /a+/;
9728                t B = "b";
9729                nt start = A B;
9730                "#,
9731            ),
9732            &vocab,
9733        )
9734        .unwrap();
9735
9736        let mut state = constraint.start();
9737        assert!(state.commit_token(0));
9738
9739        // Populate the ordinary per-sequence mask cache while inside A. A
9740        // further `a` is an exact lexer self-loop: no parser terminal is
9741        // consumed and the complete runtime state remains identical.
9742        let cached_mask = state.mask();
9743        let before_generation = state.generation();
9744        let before_state = state.state.clone();
9745        {
9746            let cache = state.mask_cache.lock().unwrap();
9747            assert_eq!(cache.as_ref().unwrap().generation, before_generation);
9748        }
9749
9750        assert!(state.commit_token(0));
9751        assert_eq!(state.generation(), before_generation + 1);
9752        assert_eq!(before_state, state.state);
9753        {
9754            let cache = state.mask_cache.lock().unwrap();
9755            assert_eq!(cache.as_ref().unwrap().generation, state.generation());
9756            assert_eq!(cache.as_ref().unwrap().mask, cached_mask);
9757        }
9758        assert_eq!(state.mask(), cached_mask);
9759
9760        // Completing A and advancing the parser must invalidate the cached
9761        // generation. The following mask is therefore recomputed for B.
9762        assert!(state.commit_token(2));
9763        {
9764            let cache = state.mask_cache.lock().unwrap();
9765            assert_ne!(cache.as_ref().unwrap().generation, state.generation());
9766        }
9767    }
9768
9769    #[test]
9770    fn unchanged_dynamic_mask_projection_preserves_fill_mask_cache() {
9771        let vocab = Vocab::from_entries_unchecked(vec![
9772            (0, b"\"".to_vec()),
9773            (1, b"a".to_vec()),
9774            (2, b"aa".to_vec()),
9775            (3, b"b".to_vec()),
9776        ]);
9777        let dynamic = DynamicConstraint::from_json_schema(
9778            r#"{"type":"string","maxLength":1000000000}"#,
9779            &vocab,
9780        )
9781        .unwrap();
9782        let mut state = dynamic.inner.start();
9783
9784        // Enter the quoted lazy bounded-string residual, consume one interior
9785        // byte, then cache its mask. Far from the upper bound, another interior
9786        // byte changes the exact symbolic residual coordinate while the parser
9787        // has not seen a terminal boundary and the finite vocabulary-horizon
9788        // mask coordinate remains unchanged.
9789        assert!(state.commit_token(0)); // opening quote
9790        assert!(state.commit_token(1)); // first interior 'a'
9791        let cached_mask = state.mask();
9792        let before_generation = state.generation();
9793        let before_state = state.state.clone();
9794
9795        assert!(state.commit_token(1)); // second interior 'a'
9796        assert_ne!(before_state, state.state, "test must exercise a changed exact lexer state");
9797        assert!(
9798            state.dynamic_mask_projection_state_eq(&before_state, &state.state),
9799            "changed exact state should remain equal in the mask-only coordinate",
9800        );
9801        {
9802            let cache = state.mask_cache.lock().unwrap();
9803            assert_eq!(cache.as_ref().unwrap().generation, before_generation + 1);
9804            assert_eq!(cache.as_ref().unwrap().mask, cached_mask);
9805        }
9806        assert_eq!(state.mask(), cached_mask);
9807    }
9808
9809    #[test]
9810    fn recursive_radix_candidate_admission_matches_pointwise_exact_commit() {
9811        let vocab = Vocab::from_entries_unchecked(vec![
9812            (0, b"X".to_vec()),
9813            (1, b"X[".to_vec()),
9814            (2, b"X[a".to_vec()),
9815            (3, b"X[a]".to_vec()),
9816            (4, b"X[a]!".to_vec()),
9817            (5, b"X[a]!".to_vec()),
9818            (6, b"[".to_vec()),
9819            (7, b"[a".to_vec()),
9820            (8, b"[a]".to_vec()),
9821            (9, b"[a]!".to_vec()),
9822            (10, b"a".to_vec()),
9823            (11, b"a]".to_vec()),
9824            (12, b"a]!".to_vec()),
9825            (13, b"]".to_vec()),
9826            (14, b"]!".to_vec()),
9827            (15, b"!".to_vec()),
9828        ]);
9829        let child = Constraint::compile(
9830            Grammar::glrm("glrm 1; start child; nt child = \"[\" \"a\" \"]\";"),
9831            &vocab,
9832        )
9833        .unwrap();
9834        let parent = Constraint::compile(
9835            Grammar::glrm(
9836                "glrm 1; start document; extern grammar child; nt document = \"X\" child \"!\";",
9837            ),
9838            &vocab,
9839        )
9840        .unwrap();
9841        let bound = parent
9842            .bind_grammar_dynamic_boundary("child", child)
9843            .unwrap();
9844        assert!(bound.uses_compact_segmented_parser_runtime());
9845
9846        for path in [
9847            &[][..],
9848            &[0][..],
9849            &[0, 6][..],
9850            &[0, 6, 10][..],
9851            &[0, 6, 10, 13][..],
9852        ] {
9853            let mut state = bound.start();
9854            for &token in path {
9855                assert!(state.commit_token(token));
9856            }
9857
9858            let mut batch_candidates = bound.token_bytes_iter().collect::<Vec<_>>();
9859            let mut batch_buffers = CommitBuffers::default();
9860            let mut batched = Vec::new();
9861            admissible_byte_token_candidates_from_state_exact(
9862                &bound,
9863                &state.state,
9864                &mut batch_buffers,
9865                &mut batch_candidates,
9866                &mut batched,
9867            );
9868            batched.sort_unstable();
9869
9870            let mut pointwise_buffers = CommitBuffers::default();
9871            let mut pointwise = bound
9872                .token_bytes_iter()
9873                .filter_map(|(token_id, _)| {
9874                    token_admissible_from_state_exact(
9875                        &bound,
9876                        &state.state,
9877                        &mut pointwise_buffers,
9878                        token_id,
9879                    )
9880                    .then_some(token_id)
9881                })
9882                .collect::<Vec<_>>();
9883            pointwise.sort_unstable();
9884            assert_eq!(batched, pointwise, "candidate mismatch after path {path:?}");
9885        }
9886    }
9887
9888    #[test]
9889    fn recursive_scoped_tokenizer_exec_uses_only_the_active_leaf() {
9890        let vocab = Vocab::from_entries_unchecked(vec![
9891            (0, b"X".to_vec()),
9892            (1, b"a".to_vec()),
9893            (2, b"!".to_vec()),
9894            (3, b"Xa!".to_vec()),
9895        ]);
9896        let child = Constraint::compile(
9897            Grammar::glrm("glrm 1; start child; t A = \"a\"; nt child = A;"),
9898            &vocab,
9899        )
9900        .unwrap();
9901        let parent = Constraint::compile(
9902            Grammar::glrm(
9903                "glrm 1; start document; extern grammar child; t X = \"X\"; t BANG = \"!\"; nt document = X child BANG;",
9904            ),
9905            &vocab,
9906        )
9907        .unwrap();
9908        let local_x = parent
9909            .terminal_display_names
9910            .iter()
9911            .position(|name| name == "X")
9912            .unwrap() as u32;
9913        let local_a = child
9914            .terminal_display_names
9915            .iter()
9916            .position(|name| name == "A")
9917            .unwrap() as u32;
9918        let bound = parent.bind_grammar("child", child).unwrap();
9919        let loaded = Constraint::load(bound.save(), &vocab).unwrap();
9920        for constraint in [&bound, &loaded] {
9921            let layout = constraint.recursive_parser_layout().unwrap().unwrap();
9922            assert_eq!(layout.leaves.len(), 2);
9923            let scoped_x = constraint.recursive_terminal_scoped_id(0, local_x).unwrap();
9924            let scoped_a = constraint.recursive_terminal_scoped_id(1, local_a).unwrap();
9925            assert!(scoped_x >= constraint.parser_terminal_count());
9926            assert!(scoped_a >= constraint.parser_terminal_count());
9927
9928            let root_reset = constraint.recursive_tokenizer_reset_state(0).unwrap();
9929            let root_x = tokenizer_scan::execute_recursive_tokenizer_from_state_small(
9930                constraint,
9931                b"X",
9932                root_reset,
9933            )
9934            .unwrap();
9935            assert!(root_x.matches.iter().any(|matched| matched.id == scoped_x));
9936            assert!(root_x.end_state.iter().all(|&state| {
9937                constraint.recursive_tokenizer_leaf_state(state).unwrap().0 == 0
9938            }));
9939            let root_a = tokenizer_scan::execute_recursive_tokenizer_from_state_small(
9940                constraint,
9941                b"a",
9942                root_reset,
9943            )
9944            .unwrap();
9945            assert!(
9946                root_a.matches.iter().all(|matched| matched.id != scoped_a),
9947                "child terminal leaked from inactive leaf: {:?}",
9948                root_a.matches,
9949            );
9950
9951            let child_reset = constraint.recursive_tokenizer_reset_state(1).unwrap();
9952            let child_a = tokenizer_scan::execute_recursive_tokenizer_from_state_small(
9953                constraint,
9954                b"a",
9955                child_reset,
9956            )
9957            .unwrap();
9958            assert!(child_a.matches.iter().any(|matched| matched.id == scoped_a));
9959            assert!(child_a.end_state.iter().all(|&state| {
9960                constraint.recursive_tokenizer_leaf_state(state).unwrap().0 == 1
9961            }));
9962        }
9963    }
9964
9965    fn canonical_commit_state(
9966        state: &ParserStateMap,
9967    ) -> CanonicalCommitState {
9968        canonical_commit_state_for_equivalence_assert(state)
9969    }
9970
9971    #[test]
9972    fn exact_prefilter_rejects_multiple_conditional_candidates_independent_of_row_order() {
9973        let mut terminals = crate::ds::bitset::BitSet::new(8);
9974        terminals.set(1);
9975        terminals.set(2);
9976        let unconditional = crate::ds::bitset::BitSet::new(8);
9977
9978        let row_a = ActionRow::from_iter([
9979            (1, Action::Reduce(0, 1)),
9980            (2, Action::Reduce(0, 1)),
9981        ]);
9982        let row_b = ActionRow::from_iter([
9983            (2, Action::Reduce(0, 1)),
9984            (1, Action::Reduce(0, 1)),
9985        ]);
9986
9987        assert_eq!(
9988            single_conditional_candidate(&row_a, &unconditional, &terminals),
9989            Err(()),
9990        );
9991        assert_eq!(
9992            single_conditional_candidate(&row_b, &unconditional, &terminals),
9993            Err(()),
9994        );
9995
9996        let mut one_terminal = crate::ds::bitset::BitSet::new(8);
9997        one_terminal.set(2);
9998        assert_eq!(
9999            single_conditional_candidate(&row_a, &unconditional, &one_terminal),
10000            Ok(Some(2)),
10001        );
10002    }
10003
10004    #[test]
10005    fn batched_and_cached_end_state_admission_match_pointwise_simulation() {
10006        let constraint = Constraint::from_glrm_grammar(
10007            r#"
10008                start start;
10009                t A = "a";
10010                t AB = "ab";
10011                t B = "b";
10012                t C = "c";
10013                nt item = A | AB | B;
10014                nt start = item C;
10015            "#,
10016            &Vocab::from_entries_unchecked(vec![
10017                (0, b"a".to_vec()),
10018                (1, b"ab".to_vec()),
10019                (2, b"b".to_vec()),
10020                (3, b"c".to_vec()),
10021                (4, b"ac".to_vec()),
10022                (5, b"abc".to_vec()),
10023            ]),
10024        )
10025        .unwrap();
10026        let state = constraint.start();
10027        let gss = state.state.values().next().unwrap();
10028        let initial = constraint.runtime_commit_initial_state();
10029        let non_initial = (0..constraint.tokenizer.num_states())
10030            .find(|&end_state| {
10031                end_state != initial
10032                    && !constraint
10033                        .tokenizer
10034                        .possible_future_terminals(end_state)
10035                        .is_empty()
10036            })
10037            .expect("test tokenizer should have a live non-initial state");
10038        // Repeating one exact continuation is enough to exercise batching and
10039        // cache reuse; production callers usually provide many distinct states,
10040        // but the theorem does not depend on their distinctness.
10041        let end_states = vec![initial, non_initial, non_initial];
10042
10043        let admitted = batched_end_state_admitted_terminals(&constraint, gss, &end_states);
10044        assert!(admitted.is_none(), "native relations decline the LR batching shortcut");
10045        for &end_state in &end_states {
10046            assert_eq!(end_state_may_advance_with_batch(&constraint, gss, end_state, admitted.as_ref()),
10047                end_state_may_advance(&constraint, gss, end_state));
10048        }
10049        let mut cache = SmallVec::<[ParserAdmissionCacheEntry; 8]>::new();
10050        for _ in 0..2 {
10051            assert!(cached_batched_end_state_admission(&constraint,gss,&end_states,&mut cache).is_none());
10052            assert!(cache.is_empty(), "declined batching must leave the cache unchanged");
10053        }
10054        for (token, _) in constraint.token_bytes_iter() {
10055            let admitted = state.mask()[token as usize / 32] & (1 << (token % 32)) != 0;
10056            assert_eq!(state.clone().commit_token(token), admitted, "token={token}");
10057        }
10058    }
10059
10060    #[test]
10061    fn admission_cache_reset_drops_persistent_gss_references() {
10062        let gss = ParserGSS::from_single_stack(
10063            vec![0_u32, 1],
10064            TerminalsDisallowed::new(),
10065        );
10066        let mut buffers = CommitBuffers::default();
10067        buffers.admission_cache.push(ParserAdmissionCacheEntry {
10068            gss,
10069            tested: crate::ds::bitset::BitSet::new(2),
10070            admitted: crate::ds::bitset::BitSet::new(2),
10071            boolean_queries: SmallVec::new(),
10072        });
10073        buffers.clear_all();
10074        assert_eq!(
10075            buffers.admission_cache.len(),
10076            1,
10077            "ordinary scratch reuse should preserve admission facts",
10078        );
10079        buffers.reset_all();
10080        assert!(buffers.admission_cache.is_empty());
10081    }
10082
10083
10084    #[test]
10085    #[ignore]
10086    fn debug_selected10_completed_child_lookahead_actions() {
10087        use crate::compiler::glr::analysis::EOF;
10088        use crate::compiler::glr::parser::stack_admissible_terminals;
10089        use crate::compiler::glr::table::Action;
10090        use crate::ds::bitset::BitSet;
10091        use std::collections::BTreeMap;
10092
10093        let path = crate::env::var("GLRMASK_DEBUG_ARTIFACT").expect("GLRMASK_DEBUG_ARTIFACT");
10094        let bytes = std::fs::read(path).unwrap();
10095        let vocab = crate::compiler::constraint_compose::load_vocab(
10096            &crate::env::var("GLRMASK_DEBUG_VOCAB").expect("GLRMASK_DEBUG_VOCAB"));
10097        let constraint = Constraint::load(&bytes, &vocab).unwrap();
10098        let mut state = constraint.start();
10099        assert!(state.commit_bytes(b"const x = tools.tool_0({})"));
10100        eprintln!("STACKS {:?}", state.debug_parser_stacks());
10101        for (_, gss) in state.state.iter() {
10102            let all = BitSet::all(constraint.parser_terminal_count() as usize + 1);
10103            let admitted = stack_admissible_terminals(&constraint.table, gss, &all);
10104            let mut factor = gss.clone();
10105            let mut blockers = Vec::<u32>::new();
10106            for depth in 0..16 {
10107                let top = factor.single_exclusive_top_value();
10108                let admitted_now =
10109                    stack_admissible_terminals(&constraint.table, &factor, &all);
10110                eprintln!(
10111                    "FACTOR_DEPTH {depth} top={top:?} stack={:?} admitted={:?} blockers={:?}",
10112                    factor.to_stacks(64),
10113                    admitted_now.iter_ones().collect::<Vec<_>>(),
10114                    blockers,
10115                );
10116                let Some((next, blocked)) =
10117                    crate::compiler::glr::parser::lookahead_reduction_factor(
10118                        &constraint.table,
10119                        &factor,
10120                    )
10121                else {
10122                    break;
10123                };
10124                for terminal in blocked {
10125                    if !blockers.contains(&terminal) {
10126                        blockers.push(terminal);
10127                    }
10128                }
10129                factor = next;
10130            }
10131            for top in gss.peek_values() {
10132                let mut kinds = BTreeMap::<String, Vec<u32>>::new();
10133                for bit in admitted.iter_ones() {
10134                    let terminal = if bit == constraint.parser_terminal_count() as usize {
10135                        EOF
10136                    } else {
10137                        bit as u32
10138                    };
10139                    let desc = match constraint.table.action(top, terminal) {
10140                        Some(Action::Reduce(nt, len)) => format!("reduce:{nt}:{len}"),
10141                        Some(Action::Shift(target, replace)) => format!("shift:{target}:{replace}"),
10142                        Some(Action::StackShifts(shifts)) => format!("stackshifts:{}", shifts.len()),
10143                        Some(Action::GuardedStackShifts(shifts)) => format!("guarded:{}", shifts.len()),
10144                        Some(Action::ReplaceShifts(targets)) => format!("replace:{}", targets.len()),
10145                        Some(Action::Split { shift, reduces, accept }) => format!("split:{shift:?}:{reduces:?}:{accept}"),
10146                        Some(Action::Accept) => "accept".into(),
10147                        Some(Action::Skip) => "skip".into(),
10148                        None => "none".into(),
10149                    };
10150                    kinds.entry(desc).or_default().push(terminal);
10151                }
10152                eprintln!("TOP {top} ADMITTED {} KINDS {}", admitted.count_ones(), kinds.len());
10153                for (kind, terminals) in kinds {
10154                    eprintln!("  {kind} count={} sample={:?}", terminals.len(), &terminals[..terminals.len().min(24)]);
10155                }
10156            }
10157        }
10158    }
10159
10160
10161    #[test]
10162    #[ignore]
10163    fn debug_selected10_core_fast_weight_transport() {
10164        use crate::compiler::glr::labels::DEFAULT_LABEL;
10165        use crate::ds::weight::Weight;
10166
10167        fn accepted_weight(constraint: &Constraint, labels: &[u32]) -> Weight {
10168            let mut state = constraint.parser_dwa.start_state();
10169            let mut weight = Weight::all();
10170            for &label in labels {
10171                let row = &constraint.parser_dwa.states()[state as usize];
10172                let Some((target, edge_weight)) = row
10173                    .transitions
10174                    .get(&(label as i32))
10175                    .or_else(|| row.transitions.get(&DEFAULT_LABEL))
10176                else {
10177                    return Weight::empty();
10178                };
10179                weight = weight.intersection(edge_weight);
10180                state = *target;
10181            }
10182            let Some(final_weight) = constraint.parser_dwa.states()[state as usize]
10183                .final_weight
10184                .as_ref()
10185            else {
10186                return Weight::empty();
10187            };
10188            weight.intersection(final_weight)
10189        }
10190
10191        fn dump(name: &str, constraint: &Constraint, tokenizer_state: u32, token: u32) {
10192            let internal_token = constraint
10193                .original_token_to_internal
10194                .get(token as usize)
10195                .copied()
10196                .unwrap_or(u32::MAX);
10197            let tsids = constraint.internal_tsids_for_state(tokenizer_state).to_vec();
10198            eprintln!("WEIGHT_TRANSPORT {name} tokenizer_state={tokenizer_state} tsids={tsids:?} token={token} internal_token={internal_token}");
10199            for labels in [&[22_u32][..], &[22_u32, 0][..]] {
10200                let weight = accepted_weight(constraint, labels);
10201                let memberships = tsids
10202                    .iter()
10203                    .map(|&tsid| (tsid, internal_token != u32::MAX && weight.tokens_for_tsid(tsid).contains(internal_token), weight.tokens_for_tsid(tsid).len()))
10204                    .collect::<Vec<_>>();
10205                eprintln!("WEIGHT_TRANSPORT {name} labels={labels:?} empty={} memberships={memberships:?}", weight.is_empty());
10206            }
10207            for key in [22_i32, DEFAULT_LABEL] {
10208                if let Some(weight) = constraint.parser_top_accept.get(&key) {
10209                    let memberships = tsids.iter().map(|&tsid| (tsid, weight.tokens_for_tsid(tsid).contains(internal_token), weight.tokens_for_tsid(tsid).len())).collect::<Vec<_>>();
10210                    eprintln!("WEIGHT_TRANSPORT {name} top_accept key={key} memberships={memberships:?}");
10211                }
10212                if let Some(parts) = constraint.parser_top_accept_parts.get(&key) {
10213                    for (part, weight) in parts.iter().enumerate() {
10214                        let memberships = tsids.iter().map(|&tsid| (tsid, weight.tokens_for_tsid(tsid).contains(internal_token), weight.tokens_for_tsid(tsid).len())).collect::<Vec<_>>();
10215                        eprintln!("WEIGHT_TRANSPORT {name} top_part key={key} part={part} memberships={memberships:?}");
10216                    }
10217                }
10218            }
10219            let mut l1 = Vec::new();
10220            constraint.for_each_direct_regular_l1_acceptance(22, |weight| {
10221                l1.push(tsids.iter().map(|&tsid| { let tokens = weight.token_set_for_tsid(tsid).map(|tokens| tokens.to_range_set()).unwrap_or_default(); (tsid, tokens.contains(internal_token), tokens.len()) }).collect::<Vec<_>>());
10222            });
10223            eprintln!("WEIGHT_TRANSPORT {name} l1={l1:?}");
10224        }
10225
10226        let core_path = crate::env::var("GLRMASK_DEBUG_CORE_ARTIFACT").unwrap();
10227        let fast_path = crate::env::var("GLRMASK_DEBUG_ARTIFACT").unwrap();
10228        let vocab = crate::compiler::constraint_compose::load_vocab(
10229            &crate::env::var("GLRMASK_DEBUG_VOCAB").expect("GLRMASK_DEBUG_VOCAB"));
10230        let core = Constraint::load(std::fs::read(core_path).unwrap(), &vocab).unwrap();
10231        let fast = Constraint::load(std::fs::read(fast_path).unwrap(), &vocab).unwrap();
10232        dump("core", &core, 38, 443);
10233        dump("fast", &fast, 39, 443);
10234    }
10235
10236    #[test]
10237    #[ignore]
10238    fn debug_selected10_boundary_shallow_acceptance() {
10239        use crate::compiler::glr::labels::DEFAULT_LABEL;
10240        use crate::ds::weight::Weight;
10241
10242        fn accepted_weight(constraint: &Constraint, labels: &[u32]) -> Weight {
10243            let mut state = constraint.parser_dwa.start_state();
10244            let mut weight = Weight::all();
10245            for &label in labels {
10246                let row = &constraint.parser_dwa.states()[state as usize];
10247                let Some((target, edge_weight)) = row
10248                    .transitions
10249                    .get(&(label as i32))
10250                    .or_else(|| row.transitions.get(&DEFAULT_LABEL))
10251                else { return Weight::empty(); };
10252                weight = weight.intersection(edge_weight);
10253                state = *target;
10254            }
10255            let Some(final_weight) = constraint.parser_dwa.states()[state as usize].final_weight.as_ref()
10256            else { return Weight::empty(); };
10257            weight.intersection(final_weight)
10258        }
10259
10260        fn contains(constraint: &Constraint, tokenizer_state: u32, token: u32, weight: &Weight) -> bool {
10261            let internal = constraint.original_token_to_internal[token as usize];
10262            constraint.internal_tsids_for_state(tokenizer_state)
10263                .iter()
10264                .any(|&tsid| weight.tokens_for_tsid(tsid).contains(internal))
10265        }
10266
10267        fn dump_case(constraint: &Constraint, name: &str, tokenizer_state: u32, stack: &[u32], tokens: &[u32]) {
10268            let reversed = stack.iter().rev().copied().collect::<Vec<_>>();
10269            eprintln!("SHALLOW {name} tokenizer_state={tokenizer_state} stack={stack:?} tsids={:?}", constraint.internal_tsids_for_state(tokenizer_state));
10270            let start_final = constraint.parser_dwa.states()[constraint.parser_dwa.start_state() as usize]
10271                .final_weight.clone().unwrap_or_else(Weight::empty);
10272            for &token in tokens {
10273                let mut first = contains(constraint, tokenizer_state, token, &start_final).then_some(0usize);
10274                for depth in 1..=reversed.len() {
10275                    let w = accepted_weight(constraint, &reversed[..depth]);
10276                    if contains(constraint, tokenizer_state, token, &w) {
10277                        first = Some(depth);
10278                        break;
10279                    }
10280                }
10281                eprintln!("SHALLOW {name} token={token} first_depth={first:?}");
10282            }
10283        }
10284
10285        let full_path = crate::env::var("GLRMASK_DEBUG_FULL_ARTIFACT").unwrap();
10286        let vocab = crate::compiler::constraint_compose::load_vocab(
10287            &crate::env::var("GLRMASK_DEBUG_VOCAB").expect("GLRMASK_DEBUG_VOCAB"));
10288        let full = Constraint::load(std::fs::read(full_path).unwrap(), &vocab).unwrap();
10289        dump_case(&full, "tools_reset_a", 0, &[0,22,198,18], &[739,2446,7255,21966]);
10290        dump_case(&full, "tools_reset_b", 0, &[0,22,198,167], &[739,2446,7255,21966]);
10291        dump_case(&full, "tools_residual", 444, &[0,22,198], &[739,2446,7255,21966]);
10292        dump_case(&full, "tool0", 0, &[0,22,198,193,862], &[49209,69906]);
10293        dump_case(&full, "inside", 0, &[0,22,198,193,873,903], &[3033,3602,4649,9000,14419,16638,17041,29448,31893,32988,35183,36199,39942,44160,53511,71741,79237,82274,95445]);
10294        dump_case(&full, "await_tools", 0, &[0,22,198,109,193], &[3324,32809]);
10295    }
10296
10297    #[test]
10298    #[ignore]
10299    fn debug_selected10_iterated_mask_factor() {
10300        use std::time::Instant;
10301
10302        let fast_path = crate::env::var("GLRMASK_DEBUG_ARTIFACT").unwrap();
10303        let full_path = crate::env::var("GLRMASK_DEBUG_FULL_ARTIFACT").unwrap();
10304        let vocab = crate::compiler::constraint_compose::load_vocab(
10305            &crate::env::var("GLRMASK_DEBUG_VOCAB").expect("GLRMASK_DEBUG_VOCAB"));
10306        let fast = Constraint::load(std::fs::read(fast_path).unwrap(), &vocab).unwrap();
10307        let full = Constraint::load(std::fs::read(full_path).unwrap(), &vocab).unwrap();
10308        unsafe {
10309            crate::__private::set_env_var("GLRMASK_EXPERIMENT_MASK_LOOKAHEAD_FACTOR", Some("1"));
10310            crate::__private::set_env_var("GLRMASK_EXPERIMENT_MASK_LOOKAHEAD_FACTOR_MAX_DEPTH", Some("2"));
10311            crate::__private::set_env_var("GLRMASK_EXPERIMENT_SCOPED_IGNORE_EXACT_OVERLAY", Some("1"));
10312            crate::__private::set_env_var("GLRMASK_EXPERIMENT_STATIC_DYNAMIC_OVERLAY", None);
10313        }
10314        let prefixes: &[&[u8]] = &[
10315            b"",
10316            b"const x",
10317            b"const x =",
10318            b"const x = tools",
10319            b"const x = tools.tool_0",
10320            b"const x = tools.tool_0({",
10321            b"const x = tools.tool_0({})",
10322            b"const x = tools.tool_0({});",
10323            b"const r = await tools.",
10324        ];
10325        for &prefix in prefixes {
10326            let mut fs = full.start();
10327            let mut hs = fast.start();
10328            if !prefix.is_empty() {
10329                assert!(fs.commit_bytes(prefix));
10330                assert!(hs.commit_bytes(prefix));
10331            }
10332            let fm = fs.mask();
10333            let started = Instant::now();
10334            let hm = hs.mask();
10335            let elapsed = started.elapsed().as_micros();
10336            let mut extra = 0usize;
10337            let mut missing = 0usize;
10338            for (&left, &right) in hm.iter().zip(&fm) {
10339                extra += (left & !right).count_ones() as usize;
10340                missing += (right & !left).count_ones() as usize;
10341            }
10342            eprintln!(
10343                "IGNORE_PM prefix={:?} us={} extra={} missing={}",
10344                String::from_utf8_lossy(prefix), elapsed, extra, missing
10345            );
10346        }
10347        std::mem::forget(fast);
10348        std::mem::forget(full);
10349    }
10350
10351    #[test]
10352    fn language_queue_structural_gate_rejects_tiny_and_accepts_wide_complex_gss() {
10353        let mut tiny = ParserStateMap::default();
10354        tiny.insert(
10355            0,
10356            ParserGSS::from_single_stack(
10357                vec![0_u32, 1, 2],
10358                TerminalsDisallowed::new(),
10359            ),
10360        );
10361        assert!(
10362            language_queue_top_value_count_at_most(&tiny, LANGUAGE_QUEUE_MIN_TOP_VALUES)
10363                < LANGUAGE_QUEUE_MIN_TOP_VALUES
10364        );
10365
10366        let stacks = (0_u32..64)
10367            .map(|index| {
10368                (
10369                    vec![0, 1_000 + index, 2_000 + index, 10 + index % 4],
10370                    TerminalsDisallowed::new(),
10371                )
10372            })
10373            .collect::<Vec<_>>();
10374        let mut complex = ParserStateMap::default();
10375        complex.insert(0, ParserGSS::from_stacks(&stacks));
10376        assert_eq!(
10377            language_queue_top_value_count_at_most(
10378                &complex,
10379                LANGUAGE_QUEUE_MIN_TOP_VALUES,
10380            ),
10381            LANGUAGE_QUEUE_MIN_TOP_VALUES,
10382        );
10383        assert_eq!(
10384            language_queue_path_count_at_most(&complex, LANGUAGE_QUEUE_MIN_PATHS),
10385            LANGUAGE_QUEUE_MIN_PATHS,
10386        );
10387        assert_eq!(
10388            language_queue_node_count_at_most(&complex, LANGUAGE_QUEUE_MIN_NODES),
10389            LANGUAGE_QUEUE_MIN_NODES,
10390        );
10391    }
10392
10393    #[test]
10394    fn actionable_terminal_boundary_trigger_requires_distinct_offsets() {
10395        let constraint = Constraint::from_glrm_grammar(
10396            r#"
10397                start start;
10398                t A = "a";
10399                t AB = "ab";
10400                nt start = A | AB;
10401            "#,
10402            &Vocab::from_entries_unchecked(vec![
10403                (0, b"a".to_vec()),
10404                (1, b"ab".to_vec()),
10405                (2, b"b".to_vec()),
10406            ]),
10407        )
10408        .expect("boundary-trigger grammar should compile");
10409        let state = constraint.start();
10410        let mut scratch = tokenizer_scan::ReusableTokenizerExecScratch::default();
10411
10412        assert!(
10413            !has_multiple_actionable_terminal_boundaries(
10414                &constraint,
10415                &state.state,
10416                b"a",
10417                &mut scratch,
10418            ),
10419            "one actionable completion boundary must not select the language queue",
10420        );
10421        assert!(
10422            has_multiple_actionable_terminal_boundaries(
10423                &constraint,
10424                &state.state,
10425                b"ab",
10426                &mut scratch,
10427            ),
10428            "actionable terminal completions at byte offsets one and two must select",
10429        );
10430    }
10431
10432    #[test]
10433    fn actionable_terminal_boundary_trigger_ignores_same_offset_ambiguity() {
10434        let constraint = Constraint::from_glrm_grammar(
10435            r#"
10436                start start;
10437                t A = "a";
10438                t ALSO_A = "a";
10439                nt start = A | ALSO_A;
10440            "#,
10441            &Vocab::from_entries_unchecked(vec![(0, b"a".to_vec())]),
10442        )
10443        .expect("same-offset trigger grammar should compile");
10444        let state = constraint.start();
10445        let mut scratch = tokenizer_scan::ReusableTokenizerExecScratch::default();
10446
10447        assert!(
10448            !has_multiple_actionable_terminal_boundaries(
10449                &constraint,
10450                &state.state,
10451                b"a",
10452                &mut scratch,
10453            ),
10454            "multiple actionable terminals ending at one offset must remain on the ordinary queue",
10455        );
10456    }
10457
10458    #[test]
10459    fn flat_stack_effect_can_replace_the_only_state() {
10460        let mut stack = FlatInlineStack::new();
10461        stack.push(36);
10462
10463        assert_eq!(apply_flat_stack_effect(&mut stack, 1, &[37]), Some(true));
10464        assert_eq!(stack.as_slice(), &[37]);
10465    }
10466
10467    #[test]
10468    fn compile_time_initial_commit_priming_preserves_runtime_semantics() {
10469        let constraint = Constraint::from_glrm_grammar(
10470            r#"
10471                start start;
10472                t A = "a";
10473                t B = "b";
10474                nt start = A B;
10475            "#,
10476            &Vocab::from_entries_unchecked(vec![
10477                (0, b"a".to_vec()),
10478                (1, b"ab".to_vec()),
10479                (2, b"b".to_vec()),
10480                (3, b"x".to_vec()),
10481            ]),
10482        )
10483        .unwrap();
10484
10485        let mut state = constraint.start();
10486        assert_eq!(
10487            state
10488                .mask()
10489                .iter()
10490                .enumerate()
10491                .flat_map(|(word, &bits)| {
10492                    (0..32).filter_map(move |bit| {
10493                        ((bits >> bit) & 1 == 1).then_some((word * 32 + bit) as u32)
10494                    })
10495                })
10496                .collect::<BTreeSet<_>>(),
10497            BTreeSet::from([0, 1]),
10498        );
10499        assert!(state.commit_token(0));
10500        assert!(state.commit_token(2));
10501        assert!(state.is_accepting());
10502
10503        let loaded = Constraint::load(constraint.save(), &crate::public_api::constraint_vocab(&constraint)).unwrap();
10504        let mut loaded_state = loaded.start();
10505        assert!(loaded_state.commit_token(1));
10506        assert!(loaded_state.is_accepting());
10507    }
10508
10509    #[test]
10510    fn duplicate_key_flat_state_reports_completion_without_normalization() {
10511        let constraint = Constraint::from_glrm_grammar(
10512            r#"
10513                start start;
10514                t A = "a";
10515                t B = "a" | "ab";
10516                nt item = A | B;
10517                nt start = item;
10518            "#,
10519            &Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]),
10520        )
10521        .unwrap();
10522
10523        let mut state = constraint.start();
10524        assert!(state.commit_token(0));
10525        assert!(
10526            state.state.has_duplicate_keys(),
10527            "the bounded runtime should retain the completed alternatives separately"
10528        );
10529        assert!(state.is_accepting());
10530
10531        let mut normalized = state.clone();
10532        normalized.state.normalize_duplicate_keys();
10533        assert!(normalized.is_accepting());
10534        assert_eq!(
10535            canonical_commit_state(&state.state),
10536            canonical_commit_state(&normalized.state),
10537        );
10538    }
10539
10540    #[test]
10541    fn special_token_advance_matches_normalized_duplicate_key_state() {
10542        let constraint = Constraint::from_glrm_with_token_ids(
10543            r#"
10544                start start;
10545                t A = "a";
10546                t B = "a" | "ab";
10547                nt item = A | B;
10548                extern token EXACT_100;
10549                nt start = item EXACT_100;
10550            "#,
10551            &Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]),
10552            &[("EXACT_100", 100)],
10553            &[],
10554        )
10555        .unwrap();
10556
10557        let mut flat = constraint.start();
10558        assert!(flat.commit_token(0));
10559        assert!(flat.state.has_duplicate_keys());
10560
10561        let mut normalized = flat.clone();
10562        normalized.state.normalize_duplicate_keys();
10563        assert_eq!(flat.mask(), normalized.mask());
10564
10565        assert!(flat.commit_token(100));
10566        assert!(normalized.commit_token(100));
10567        assert!(flat.is_accepting());
10568        assert!(normalized.is_accepting());
10569        assert_eq!(
10570            canonical_commit_state(&flat.state),
10571            canonical_commit_state(&normalized.state),
10572        );
10573    }
10574
10575    #[test]
10576    fn carried_virtual_stack_stops_when_stack_effect_exposes_branched_floor() {
10577        let acc = TerminalsDisallowed::new();
10578        let left = ParserGSS::from_single_stack(vec![0, 1, 10], acc.clone());
10579        let right = ParserGSS::from_single_stack(vec![0, 2, 10], acc);
10580        let merged = left.merge(&right);
10581
10582        let mut exhausted = merged
10583            .try_virtual_stack()
10584            .expect("merged common top should form a virtual stack");
10585        assert!(!try_apply_action_to_carried_virtual_stack(
10586            &mut exhausted,
10587            &Action::StackShifts(vec![crate::compiler::glr::table::StackShift {
10588                pop: 1,
10589                pushes: Vec::new(),
10590            }]),
10591        ));
10592        assert_eq!(exhausted.top(), Some(&10));
10593
10594        let mut restored_common_top = merged
10595            .try_virtual_stack()
10596            .expect("merged common top should form a virtual stack");
10597        assert!(try_apply_action_to_carried_virtual_stack(
10598            &mut restored_common_top,
10599            &Action::StackShifts(vec![crate::compiler::glr::table::StackShift {
10600                pop: 1,
10601                pushes: vec![40],
10602            }]),
10603        ));
10604        assert_eq!(restored_common_top.top(), Some(&40));
10605        let mut stacks = restored_common_top.into_gss().to_stacks(4_096).expect("stack enumeration exceeded explicit limit");
10606        stacks.sort_by(|left, right| left.0.cmp(&right.0));
10607        assert_eq!(
10608            stacks.into_iter().map(|(stack, _)| stack).collect::<Vec<_>>(),
10609            vec![vec![0, 1, 40], vec![0, 2, 40]],
10610        );
10611
10612        let mut emptied = ParserGSS::from_single_stack(
10613            vec![10],
10614            TerminalsDisallowed::new(),
10615        )
10616        .try_virtual_stack()
10617        .expect("single stack should form a virtual stack");
10618        assert!(!try_apply_action_to_carried_virtual_stack(
10619            &mut emptied,
10620            &Action::StackShifts(vec![crate::compiler::glr::table::StackShift {
10621                pop: 1,
10622                pushes: Vec::new(),
10623            }]),
10624        ));
10625        assert_eq!(emptied.top(), Some(&10));
10626    }
10627
10628    fn canonical_gss(gss: &ParserGSS) -> Vec<(Vec<u32>, Vec<(u32, Vec<u32>)>)> {
10629        canonical_commit_state(&ParserStateMap::singleton(0, gss.clone()))
10630            .pop()
10631            .unwrap()
10632            .1
10633    }
10634
10635    #[test]
10636    fn fused_exact_admission_matches_legacy_two_pass_reference() {
10637        let vocab = Vocab::from_entries_unchecked(vec![
10638            (0, b"a".to_vec()),
10639            (1, b"b".to_vec()),
10640            (2, b"ab".to_vec()),
10641        ]);
10642        let constraint = Constraint::from_glrm_grammar(
10643            r#"
10644                start start;
10645                t A = "a";
10646                t AB = "ab";
10647                t B = "b";
10648                nt item = A | AB | A B;
10649                nt start = item item?;
10650            "#,
10651            &vocab,
10652        )
10653        .unwrap();
10654        assert_eq!(
10655            constraint.parser_admission_policy(),
10656            AdmissionPolicy::ExactSimulation,
10657        );
10658
10659        // Own compiler reference data directly; never restore a table in the
10660        // native Constraint whose commits and admission are under test.
10661        let grammar = constraint.template_parser.as_ref().unwrap().link_grammar.as_ref().unwrap();
10662        let table = crate::compiler::glr::table::GLRTable::build_with_default_construction(
10663            &grammar.analyze(constraint.terminal_display_names.clone()),
10664            crate::compiler::glr::table::GlrTableConstruction::ExperimentalCoreMerged,
10665        );
10666
10667        let mut states = vec![constraint.start()];
10668        let mut after_a = constraint.start();
10669        assert!(after_a.commit_token(0));
10670        states.push(after_a);
10671
10672        for state in states {
10673            for gss in state.state.values() {
10674                for terminal in 0..constraint.parser_terminal_count() {
10675                    let legacy = if stack_may_advance_on(&table, gss, terminal) {
10676                        let advanced = advance_parser_stacks(&constraint, gss, terminal);
10677                        (!advanced.is_empty()).then_some(advanced)
10678                    } else {
10679                        None
10680                    };
10681                    let fused = advance_parser_stacks_if_possible(&constraint, gss, terminal);
10682                    assert_eq!(
10683                        fused.as_ref().map(canonical_gss),
10684                        legacy.as_ref().map(canonical_gss),
10685                        "terminal={terminal} source={:#?}",
10686                        canonical_gss(gss),
10687                    );
10688
10689                    let profiled =
10690                        advance_parser_stacks_profiled_if_possible(&constraint, gss, terminal);
10691                    assert_eq!(
10692                        (!profiled.advanced.is_empty())
10693                            .then(|| canonical_gss(&profiled.advanced)),
10694                        legacy.as_ref().map(canonical_gss),
10695                        "profiled terminal={terminal} source={:#?}",
10696                        canonical_gss(gss),
10697                    );
10698                    assert_eq!(profiled.may_ns, 0);
10699                }
10700            }
10701        }
10702    }
10703
10704    fn top_local_prune_reference(
10705        constraint: &Constraint,
10706        gss: &ParserGSS,
10707        bytes: &[u8],
10708    ) -> ParserGSS {
10709        let prune_partition = |partition: ParserGSS| {
10710            partition.apply_and_prune_no_promote(
10711                |terminals_disallowed: &TerminalsDisallowed| {
10712                    if terminals_disallowed.is_empty() {
10713                        return Some(TerminalsDisallowed::new());
10714                    }
10715
10716                    let mut remapped = BTreeMap::new();
10717                    for (&continuation_tokenizer_state, disallowed) in
10718                        terminals_disallowed.iter()
10719                    {
10720                        let execution = execute_tokenizer_from_state_small(
10721                            constraint,
10722                            bytes,
10723                            continuation_tokenizer_state,
10724                        );
10725                        if execution
10726                            .matches
10727                            .iter()
10728                            .any(|matched| disallowed.contains(&matched.id))
10729                        {
10730                            return None;
10731                        }
10732                        for end_state in execution.end_state {
10733                            let future = constraint
10734                                .tokenizer
10735                                .possible_future_terminals(end_state);
10736                            for &terminal in disallowed.iter() {
10737                                if future.contains(terminal as usize) {
10738                                    remapped
10739                                        .entry(end_state)
10740                                        .or_insert_with(BTreeSet::new)
10741                                        .insert(terminal);
10742                                }
10743                            }
10744                        }
10745                    }
10746                    Some(TerminalsDisallowed::from_map(remapped))
10747                },
10748            )
10749        };
10750
10751        let mut partitions = Vec::new();
10752        let root = gss.isolate(None);
10753        if !root.is_empty() {
10754            let root = prune_partition(root);
10755            if !root.is_empty() {
10756                partitions.push(root);
10757            }
10758        }
10759        for parser_state in gss.peek_values() {
10760            let partition = prune_partition(gss.isolate(Some(parser_state)));
10761            if !partition.is_empty() {
10762                partitions.push(partition);
10763            }
10764        }
10765
10766        let mut iter = partitions.into_iter();
10767        let Some(mut merged) = iter.next() else {
10768            return ParserGSS::empty();
10769        };
10770        for partition in iter {
10771            merged = merged.merge(&partition);
10772        }
10773        merged
10774    }
10775
10776    #[test]
10777    fn initial_prune_advances_each_continuation_tokenizer_state() {
10778        let vocab = Vocab::from_entries_unchecked(
10779            vec![
10780                (0, b"a".to_vec()),
10781                (1, b"b".to_vec()),
10782                (2, b"ab".to_vec()),
10783            ]);
10784        let grammar = r#"
10785start start;
10786t A = "a";
10787t B = "a" | "ab";
10788nt item = A | B;
10789nt start = item item? item?;
10790"#;
10791        let constraint = Constraint::from_glrm_grammar(grammar, &vocab).unwrap();
10792        let mut state = constraint.start();
10793        assert!(state.commit_token(0));
10794
10795        let tokenizer_state = constraint.runtime_commit_initial_state();
10796        // This test exercises the GSS pruning primitive itself, so cross the
10797        // bounded flat-state boundary explicitly before inspecting one map value.
10798        state.state.normalize_duplicate_keys();
10799        let gss = state
10800            .state
10801            .get(&tokenizer_state)
10802            .expect("ambiguous a must retain a reset lexer branch");
10803        assert!(
10804            !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()),
10805            "MRE requires a stale residual exclusion on the reset branch"
10806        );
10807
10808        let exec_result =
10809            execute_tokenizer_from_state_small(&constraint, b"b", tokenizer_state);
10810        assert!(exec_result.matches.is_empty());
10811        assert!(exec_result.end_state.is_empty());
10812
10813        let pruned = prune_single_initial_state_for_exec(
10814            &constraint,
10815            gss.clone(),
10816            tokenizer_state,
10817            &exec_result,
10818            b"b",
10819        );
10820        assert!(
10821            !pruned.is_empty()
10822                && pruned.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty()),
10823            "the valid A=a branch must survive while the provisional B=a branch is invalidated by B=ab"
10824        );
10825    }
10826
10827    #[test]
10828    fn delayed_exclusion_survives_across_model_token_boundaries() {
10829        let vocab = Vocab::from_entries_unchecked(vec![
10830            (0, b"@".to_vec()),
10831            (1, b" double".to_vec()),
10832            (2, b"Quote".to_vec()),
10833            (3, b"x".to_vec()),
10834            (4, b"=".to_vec()),
10835            (5, b"%".to_vec()),
10836            (6, b"0".to_vec()),
10837        ]);
10838        let constraint = Constraint::from_glrm_grammar(
10839            r#"
10840                start start;
10841                ignore WS;
10842                nt start = declaration expression;
10843                nt declaration = "@" ID;
10844                nt expression = ID OP "0";
10845                t WS = b/[ \t\r\n]/+;
10846                t OP = "=" | "%=";
10847                t ID = b/[A-Za-z_$]/ b/[A-Za-z0-9_$]/*;
10848            "#,
10849            &vocab,
10850        )
10851        .unwrap();
10852
10853        let mut state = constraint.start();
10854        assert!(state.commit_token(0));
10855        assert!(state.commit_token(1));
10856        assert!(state.commit_token(2));
10857
10858        let mask = state.mask();
10859        let allowed = |token: u32| {
10860            ((mask[token as usize / 32] >> (token % 32)) & 1) != 0
10861        };
10862        assert!(allowed(3), "continuing the current ID remains viable");
10863        assert!(!allowed(4), "the consumed ID cannot also satisfy the next ID");
10864        assert!(!allowed(5), "a prefix of %= cannot follow until a new ID is consumed");
10865        let mut probe = state.clone();
10866        assert!(!probe.commit_token(4));
10867        let mut probe = state.clone();
10868        assert!(!probe.commit_token(5));
10869    }
10870
10871    #[test]
10872    fn recursive_delayed_exclusion_stays_in_leaf_tokenizer_terminal_coordinate() {
10873        let vocab = Vocab::from_entries_unchecked(vec![
10874            (0, b"@".to_vec()),
10875            (1, b" double".to_vec()),
10876            (2, b"Quote".to_vec()),
10877            (3, b"x".to_vec()),
10878            (4, b"=".to_vec()),
10879            (5, b"%".to_vec()),
10880            (6, b"0".to_vec()),
10881        ]);
10882        let body = Constraint::from_glrm_grammar(
10883            r#"
10884                start start;
10885                ignore WS;
10886                nt start = declaration expression;
10887                nt declaration = "@" ID;
10888                nt expression = ID OP "0";
10889                t WS = b/[ \t\r\n]/+;
10890                t OP = "=" | "%=";
10891                t ID = b/[A-Za-z_$]/ b/[A-Za-z0-9_$]/*;
10892            "#,
10893            &vocab,
10894        )
10895        .unwrap();
10896        let parent = Constraint::compile(
10897            Grammar::glrm("glrm 1; start document; extern grammar body; nt document = body;"),
10898            &vocab,
10899        )
10900        .unwrap();
10901        let bound = parent
10902            .bind_grammar_dynamic_boundary("body", body.clone())
10903            .unwrap();
10904        assert!(bound.uses_compact_segmented_parser_runtime());
10905        let loaded = Constraint::load(bound.save(), &vocab).unwrap();
10906
10907        let mut expected = body.start();
10908        for token in [0, 1, 2] {
10909            assert!(expected.commit_token(token));
10910        }
10911        let expected_mask = expected.mask();
10912        for constraint in [&bound, &loaded] {
10913            let mut state = constraint.start();
10914            for token in [0, 1, 2] {
10915                assert!(state.commit_token(token));
10916            }
10917            assert_eq!(state.mask(), expected_mask);
10918            assert!(state.state.iter().any(|(_, gss)| {
10919                !gss.all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
10920            }));
10921            let mut probe = state.clone();
10922            assert!(!probe.commit_token(4));
10923            let mut probe = state.clone();
10924            assert!(!probe.commit_token(5));
10925        }
10926    }
10927
10928    #[test]
10929    #[cfg_attr(
10930        not(feature = "slow-tests"),
10931        ignore = "slow (~28s); run with --features slow-tests"
10932    )]
10933    fn initial_prune_matches_top_local_reference_on_generated_small_languages() {
10934        const WORDS: [&str; 4] = ["a", "b", "ab", "ba"];
10935        let vocab = Vocab::from_entries_unchecked(
10936            [
10937                "a", "b", "ab", "ba", " ", " a", "a ", " b", "b ", " a ", " b ",
10938            ]
10939            .into_iter()
10940            .enumerate()
10941            .map(|(id, word)| (id as u32, word.as_bytes().to_vec()))
10942            .collect());
10943        let languages = (1u32..1u32 << WORDS.len())
10944            .filter(|mask| mask.count_ones() <= 2)
10945            .collect::<Vec<_>>();
10946        let rule = |name: &str, mask: u32| {
10947            let rhs = WORDS
10948                .iter()
10949                .enumerate()
10950                .filter(|&(index, word)| mask & (1 << index) != 0).map(|(index, word)| format!("\"{word}\""))
10951                .collect::<Vec<_>>()
10952                .join(" | ");
10953            format!("t {name} = {rhs};\n")
10954        };
10955
10956        for &a in &languages {
10957            for &b in &languages {
10958                for start_rule in [
10959                    "nt item = A | B;\nnt start = item item? item?;",
10960                    "nt start = A A | B B;",
10961                    "nt start = A B | B A;",
10962                ] {
10963                    let grammar = format!(
10964                        "start start;\nignore WS;\nt WS = \" \"+;\n{}{}{start_rule}\n",
10965                        rule("A", a),
10966                        rule("B", b),
10967                    );
10968                    let constraint = Constraint::from_glrm_grammar(&grammar, &vocab).unwrap();
10969                    let mut frontier = vec![(constraint.start(), Vec::<u32>::new())];
10970                    let mut seen = BTreeSet::new();
10971
10972                    for depth in 0..=4 {
10973                        let mut next = Vec::new();
10974                        for (state, path) in frontier {
10975                            let state_key = canonical_commit_state(&state.state);
10976                            if !seen.insert(state_key) {
10977                                continue;
10978                            }
10979                            for (token_id, bytes) in constraint.token_bytes_iter() {
10980                                for (&tokenizer_state, gss) in &state.state {
10981                                    if gss
10982                                        .all_accs_satisfy(|td: &TerminalsDisallowed| td.is_empty())
10983                                    {
10984                                        continue;
10985                                    }
10986                                    let exec_result = execute_tokenizer_from_state_small(
10987                                        &constraint,
10988                                        bytes,
10989                                        tokenizer_state,
10990                                    );
10991                                    let actual = prune_single_initial_state_for_exec(
10992                                        &constraint,
10993                                        gss.clone(),
10994                                        tokenizer_state,
10995                                        &exec_result,
10996                                        bytes,
10997                                    );
10998                                    let expected = top_local_prune_reference(
10999                                        &constraint,
11000                                        gss,
11001                                        bytes,
11002                                    );
11003                                    assert_eq!(
11004                                        canonical_gss(&actual),
11005                                        canonical_gss(&expected),
11006                                        "initial prune crossed parser-top correlations: A={a:#06b} B={b:#06b} depth={depth} path={path:?} token={token_id} bytes={bytes:?} tokenizer_state={tokenizer_state}\ngrammar:\n{grammar}\nsource={:#?}\nactual={:#?}\nexpected={:#?}",
11007                                        canonical_gss(gss),
11008                                        canonical_gss(&actual),
11009                                        canonical_gss(&expected),
11010                                    );
11011                                }
11012
11013                                if depth < 4 {
11014                                    let mut advanced = state.clone();
11015                                    if advanced.commit_bytes(bytes) {
11016                                        let mut next_path = path.clone();
11017                                        next_path.push(token_id);
11018                                        next.push((advanced, next_path));
11019                                    }
11020                                }
11021                            }
11022                        }
11023                        frontier = next;
11024                    }
11025                }
11026            }
11027        }
11028    }
11029
11030    #[test]
11031    fn rejected_public_commits_enter_fail_state() {
11032        let vocab = Vocab::from_entries_unchecked(
11033            vec![(0, b"a".to_vec()), (1, b"b".to_vec())]);
11034        let constraint = Constraint::from_glrm_grammar(
11035            r#"
11036                start start;
11037                t A = "a";
11038                nt start = A;
11039            "#,
11040            &vocab,
11041        )
11042        .unwrap();
11043
11044        let assert_failed = |state: &ConstraintState| {
11045            assert!(state.state.is_empty());
11046            assert!(state.mask().iter().all(|&word| word == 0));
11047        };
11048
11049        let mut state = constraint.start();
11050        assert!(!state.commit_token(1));
11051        assert_failed(&state);
11052
11053        let mut state = constraint.start();
11054        assert!(state.commit_token_timed_ns(1).is_err());
11055        assert_failed(&state);
11056
11057        let mut state = constraint.start();
11058        assert!(state.commit_token_profiled(1).is_err());
11059        assert_failed(&state);
11060
11061        let mut state = constraint.start();
11062        assert!(state.commit_token_per_advance(1).is_err());
11063        assert_failed(&state);
11064
11065        let mut state = constraint.start();
11066        assert!(!state.commit_bytes(b"b"));
11067        assert_failed(&state);
11068    }
11069
11070    fn assert_fast_and_general_queue_match(
11071        constraint: &Constraint,
11072        fast_state: &ConstraintState,
11073        token_id: u32,
11074        bytes: &[u8],
11075        context: &str,
11076    ) -> Option<ConstraintState> {
11077        let mut fast = fast_state.clone();
11078        let mut profiled = fast_state.clone();
11079        let mut general = fast_state.clone();
11080
11081        let fast_result = commit_bytes_impl(
11082            constraint,
11083            &mut fast.state,
11084            bytes,
11085            &mut CommitBuffers::for_constraint(constraint),
11086        );
11087        let profiled_result = commit_bytes_impl_profiled(
11088            constraint,
11089            &mut profiled.state,
11090            bytes,
11091            &mut CommitBuffers::for_constraint(constraint),
11092            None,
11093            true,
11094        );
11095        let general_result = commit_bytes_impl_profiled(
11096            constraint,
11097            &mut general.state,
11098            bytes,
11099            &mut CommitBuffers::for_constraint(constraint),
11100            None,
11101            false,
11102        );
11103
11104        assert_eq!(
11105            fast_result.is_ok(),
11106            general_result.is_ok(),
11107            "commit result mismatch: {context} token_id={token_id} bytes={bytes:?}\nfast={:?}\ngeneral={:?}",
11108            fast.state,
11109            general.state,
11110        );
11111        assert_eq!(
11112            profiled_result.is_ok(),
11113            general_result.is_ok(),
11114            "profiled commit result mismatch: {context} token_id={token_id} bytes={bytes:?}\nprofiled={:?}\ngeneral={:?}",
11115            profiled.state,
11116            general.state,
11117        );
11118        if fast_result.is_err() {
11119            return None;
11120        }
11121        assert_eq!(
11122            canonical_commit_state(&fast.state),
11123            canonical_commit_state(&general.state),
11124            "successful commit state mismatch: {context} token_id={token_id} bytes={bytes:?}\nfast_stacks={:#?}\ngeneral_stacks={:#?}",
11125            fast.state
11126                .iter()
11127                .map(|(&ts, gss)| (ts, gss.to_stacks(4_096).expect("stack enumeration exceeded explicit limit")))
11128                .collect::<Vec<_>>(),
11129            general
11130                .state
11131                .iter()
11132                .map(|(&ts, gss)| (ts, gss.to_stacks(4_096).expect("stack enumeration exceeded explicit limit")))
11133                .collect::<Vec<_>>(),
11134        );
11135        assert_eq!(
11136            canonical_commit_state(&profiled.state),
11137            canonical_commit_state(&general.state),
11138            "successful profiled commit state mismatch: {context} token_id={token_id} bytes={bytes:?}\nprofiled_stacks={:#?}\ngeneral_stacks={:#?}",
11139            profiled
11140                .state
11141                .iter()
11142                .map(|(&ts, gss)| (ts, gss.to_stacks(4_096).expect("stack enumeration exceeded explicit limit")))
11143                .collect::<Vec<_>>(),
11144            general
11145                .state
11146                .iter()
11147                .map(|(&ts, gss)| (ts, gss.to_stacks(4_096).expect("stack enumeration exceeded explicit limit")))
11148                .collect::<Vec<_>>(),
11149        );
11150
11151        Some(fast)
11152    }
11153
11154    #[test]
11155    fn flat_frontier_accepts_input_past_the_inline_state_capacity() {
11156        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec())]);
11157        let constraint = Constraint::from_glrm_grammar(
11158            r#"
11159                start start;
11160                t A = "a";
11161                nt start = A;
11162            "#,
11163            &vocab,
11164        )
11165        .expect("single-terminal grammar should compile");
11166        let start = constraint.start();
11167        let (tokenizer_state, parser_gss) = start.state.entries[0].clone();
11168        let mut state = ParserStateMap::default();
11169        for _ in 0..=INLINE_PARSER_STATE_CAPACITY {
11170            state.insert_flat_alternative(tokenizer_state, parser_gss.clone());
11171        }
11172        assert_eq!(state.len(), INLINE_PARSER_STATE_CAPACITY + 1);
11173
11174        let mut actual = start.clone();
11175        actual.state = state;
11176        assert!(actual.commit_bytes(b"a"));
11177        let mut expected = start;
11178        assert!(expected.commit_bytes(b"a"));
11179        assert_eq!(canonical_commit_state(&actual.state), canonical_commit_state(&expected.state));
11180        assert_eq!(actual.mask(), expected.mask());
11181        assert_eq!(actual.is_accepting(), expected.is_accepting());
11182        assert!(actual.is_accepting());
11183    }
11184
11185    #[test]
11186    fn flat_frontier_preserves_all_stacks_in_a_live_lexer_continuation_group() {
11187        let vocab = Vocab::from_entries_unchecked(vec![
11188            (0, b"a".to_vec()),
11189            (1, b"b".to_vec()),
11190            (2, b"ab".to_vec()),
11191            (3, b"ba".to_vec()),
11192        ]);
11193        let grammar = r#"
11194            start start;
11195            t A = "a";
11196            t B = "b" | "ab";
11197            nt item = A | B;
11198            nt start = item item? item?;
11199        "#;
11200        let constraint = Constraint::from_glrm_grammar(grammar, &vocab).unwrap();
11201        let start = constraint.start();
11202        let after_ab = assert_fast_and_general_queue_match(
11203            &constraint,
11204            &start,
11205            2,
11206            b"ab",
11207            "grouped lexer continuation regression after ab",
11208        )
11209        .unwrap();
11210        let after_ba = assert_fast_and_general_queue_match(
11211            &constraint,
11212            &after_ab,
11213            3,
11214            b"ba",
11215            "grouped lexer continuation regression after ab, ba",
11216        )
11217        .unwrap();
11218
11219        let stacks = canonical_commit_state(&after_ba.state);
11220        let tokenizer_one = stacks
11221            .iter()
11222            .find(|(tokenizer_state, _)| *tokenizer_state == 1)
11223            .expect("lexer continuation state must remain live");
11224        assert_eq!(
11225            tokenizer_one.1,
11226            vec![
11227                (vec![0, 3, 2], Vec::new()),
11228                (vec![0, 3, 5, 2], Vec::new()),
11229            ],
11230        );
11231    }
11232
11233    #[test]
11234    #[cfg_attr(
11235        not(feature = "slow-tests"),
11236        ignore = "slow (~11s); run with --features slow-tests"
11237    )]
11238    fn monolithic_commit_fast_paths_match_general_queue_on_small_language_space() {
11239        const WORDS: [&str; 4] = ["a", "b", "ab", "ba"];
11240        let vocab = Vocab::from_entries_unchecked(
11241            WORDS
11242                .iter()
11243                .enumerate()
11244                .map(|(id, word)| (id as u32, word.as_bytes().to_vec()))
11245                .collect());
11246        let languages = (1u32..1u32 << WORDS.len())
11247            .filter(|mask| mask.count_ones() <= 2)
11248            .collect::<Vec<_>>();
11249
11250        let rule = |name: &str, mask: u32| {
11251            let rhs = WORDS
11252                .iter()
11253                .enumerate()
11254                .filter(|&(index, word)| mask & (1 << index) != 0).map(|(index, word)| format!("\"{word}\""))
11255                .collect::<Vec<_>>()
11256                .join(" | ");
11257            format!("t {name} = {rhs};\n")
11258        };
11259
11260        for &a in &languages {
11261            for &b in &languages {
11262                let grammar = format!(
11263                    "start start;\n{}{}nt item = A | B;\nnt start = item item? item?;\n",
11264                    rule("A", a),
11265                    rule("B", b),
11266                );
11267                let constraint = Constraint::from_glrm_grammar(&grammar, &vocab).unwrap();
11268                let mut frontier = vec![(constraint.start(), Vec::<u32>::new())];
11269
11270                for depth in 0..3 {
11271                    let mut next = Vec::new();
11272                    for (state, path) in frontier {
11273                        let mask = state.mask();
11274                        for (&token_id, bytes) in vocab.entries_map().iter() {
11275                            let context = format!(
11276                                "A_mask={a:#06b} B_mask={b:#06b} depth={depth} path={path:?}\ngrammar:\n{grammar}"
11277                            );
11278                            let next_state = assert_fast_and_general_queue_match(
11279                                &constraint,
11280                                &state,
11281                                token_id,
11282                                bytes,
11283                                &context,
11284                            );
11285                            let token_in_mask = mask
11286                                .get(token_id as usize / 32)
11287                                .is_some_and(|word| {
11288                                    word & (1u32 << (token_id % 32)) != 0
11289                                });
11290                            assert_eq!(
11291                                token_in_mask,
11292                                next_state.is_some(),
11293                                "mask/commit mismatch: {context} token_id={token_id} bytes={bytes:?}"
11294                            );
11295                            if let Some(next_state) = next_state {
11296                                let mut next_path = path.clone();
11297                                next_path.push(token_id);
11298                                next.push((next_state, next_path));
11299                            }
11300                        }
11301                    }
11302                    frontier = next;
11303                }
11304            }
11305        }
11306    }
11307
11308    #[test]
11309    fn residual_bc_fast_path_matches_general_queue() {
11310        let vocab = Vocab::from_entries_unchecked(
11311            vec![
11312                (0, b"a".to_vec()),
11313                (1, b"b".to_vec()),
11314                (2, b"c".to_vec()),
11315                (3, b"ab".to_vec()),
11316                (4, b"ba".to_vec()),
11317                (5, b"bc".to_vec()),
11318                (6, b"abc".to_vec()),
11319            ]);
11320        let constraint = Constraint::from_glrm_grammar(
11321            r#"
11322                start start;
11323                t A = "a" | "ab";
11324                t B = "bc";
11325                nt item = A | B;
11326                nt start = item item? item?;
11327            "#,
11328            &vocab,
11329        )
11330        .unwrap();
11331
11332        let mut fast = constraint.start();
11333        let mut slow = constraint.start();
11334        let fast_result = commit_bytes_impl(
11335            &constraint,
11336            &mut fast.state,
11337            vocab.entries_map().get(&0).unwrap(),
11338            &mut CommitBuffers::for_constraint(&constraint),
11339        );
11340        fast.advance_generation(false);
11341        assert!(fast_result.is_ok());
11342        let slow_result = commit_bytes_impl_profiled(
11343            &constraint,
11344            &mut slow.state,
11345            vocab.entries_map().get(&0).unwrap(),
11346            &mut CommitBuffers::for_constraint(&constraint),
11347            None,
11348            false,
11349        );
11350        slow.advance_generation(false);
11351        assert!(slow_result.is_ok());
11352        assert_eq!(fast.state, slow.state, "state mismatch after token a");
11353
11354        let mut next_fast = fast.clone();
11355        let mut next_slow = slow.clone();
11356        let fast_result = commit_bytes_impl(
11357            &constraint,
11358            &mut next_fast.state,
11359            vocab.entries_map().get(&5).unwrap(),
11360            &mut CommitBuffers::for_constraint(&constraint),
11361        );
11362        let slow_result = commit_bytes_impl_profiled(
11363            &constraint,
11364            &mut next_slow.state,
11365            vocab.entries_map().get(&5).unwrap(),
11366            &mut CommitBuffers::for_constraint(&constraint),
11367            None,
11368            false,
11369        );
11370        assert_eq!(
11371            fast_result.is_ok(),
11372            slow_result.is_ok(),
11373            "fast={:?}\nslow={:?}",
11374            next_fast.state,
11375            next_slow.state,
11376        );
11377        if fast_result.is_ok() {
11378            assert_eq!(next_fast.state, next_slow.state);
11379        }
11380    }
11381
11382    #[test]
11383    #[cfg_attr(
11384        not(feature = "slow-tests"),
11385        ignore = "slow (~15s); run with --features slow-tests"
11386    )]
11387    fn epsilon_commit_fast_paths_match_no_fast_path_reference() {
11388        let vocab = Vocab::from_entries_unchecked(
11389            vec![
11390                (0, b"a".to_vec()),
11391                (1, b"b".to_vec()),
11392                (2, b"c".to_vec()),
11393                (3, b"aa".to_vec()),
11394                (4, b"ab".to_vec()),
11395                (5, b" ".to_vec()),
11396                (6, b" a".to_vec()),
11397                (7, b"a ".to_vec()),
11398                (8, b" a ".to_vec()),
11399                (9, b"abc".to_vec()),
11400                (10, b"aab".to_vec()),
11401            ]);
11402        let grammar = crate::grammar::glrm::from_glrm(
11403            r#"
11404                start start;
11405                ignore WS;
11406                pragma glrmask {
11407                pragma glrmask {
11408                    lexer group ws = WS;
11409                    lexer group a = A;
11410                    lexer group b = B;
11411                    lexer group c = C;
11412                }
11413                }
11414                t WS = " "+;
11415                t A = "a"+;
11416                t B = "b";
11417                t C = "c";
11418                nt item = A | B | C;
11419                nt start = item item? item?;
11420            "#,
11421        )
11422        .unwrap();
11423        let grammar = crate::grammar::ast::lower(&grammar).unwrap();
11424        let constraint = crate::compiler::pipeline::compile_owned_with_lexer_adaptive(
11425            grammar,
11426            &vocab,
11427            false,
11428        );
11429        assert!(constraint.tokenizer_has_epsilon_transitions);
11430
11431        let mut frontier = vec![(
11432            constraint.start(),
11433            constraint.start(),
11434            constraint.start(),
11435            Vec::<u32>::new(),
11436        )];
11437        for depth in 0..=4 {
11438            let mut next = Vec::new();
11439            for (fast, profiled, general, path) in frontier {
11440                assert_eq!(
11441                    fast.mask(),
11442                    general.mask(),
11443                    "epsilon mask mismatch after path {path:?}\nfast={:#?}\ngeneral={:#?}",
11444                    canonical_commit_state(&fast.state),
11445                    canonical_commit_state(&general.state),
11446                );
11447                assert_eq!(
11448                    profiled.mask(),
11449                    general.mask(),
11450                    "epsilon profiled-mask mismatch after path {path:?}\nprofiled={:#?}\ngeneral={:#?}",
11451                    canonical_commit_state(&profiled.state),
11452                    canonical_commit_state(&general.state),
11453                );
11454                assert_eq!(
11455                    fast.is_accepting(),
11456                    general.is_accepting(),
11457                    "epsilon completion mismatch after path {path:?}",
11458                );
11459                assert_eq!(
11460                    profiled.is_accepting(),
11461                    general.is_accepting(),
11462                    "epsilon profiled completion mismatch after path {path:?}",
11463                );
11464                if depth == 4 {
11465                    continue;
11466                }
11467
11468                for (&token_id, bytes) in vocab.entries_map().iter() {
11469                    let mut next_fast = fast.clone();
11470                    let mut next_profiled = profiled.clone();
11471                    let mut next_general = general.clone();
11472                    let fast_result = commit_bytes_impl(
11473                        &constraint,
11474                        &mut next_fast.state,
11475                        bytes,
11476                        &mut CommitBuffers::for_constraint(&constraint),
11477                    );
11478                    let profiled_result = commit_bytes_impl_profiled(
11479                        &constraint,
11480                        &mut next_profiled.state,
11481                        bytes,
11482                        &mut CommitBuffers::for_constraint(&constraint),
11483                        None,
11484                        true,
11485                    );
11486                    let general_result = commit_bytes_impl_profiled(
11487                        &constraint,
11488                        &mut next_general.state,
11489                        bytes,
11490                        &mut CommitBuffers::for_constraint(&constraint),
11491                        None,
11492                        false,
11493                    );
11494                    assert_eq!(
11495                        fast_result.is_ok(),
11496                        general_result.is_ok(),
11497                        "epsilon commit result mismatch after path {path:?} token_id={token_id} bytes={bytes:?}\nfast={:#?}\ngeneral={:#?}",
11498                        canonical_commit_state(&next_fast.state),
11499                        canonical_commit_state(&next_general.state),
11500                    );
11501                    assert_eq!(
11502                        profiled_result.is_ok(),
11503                        general_result.is_ok(),
11504                        "epsilon profiled commit result mismatch after path {path:?} token_id={token_id} bytes={bytes:?}\nprofiled={:#?}\ngeneral={:#?}",
11505                        canonical_commit_state(&next_profiled.state),
11506                        canonical_commit_state(&next_general.state),
11507                    );
11508                    if fast_result.is_ok() {
11509                        let mut next_path = path.clone();
11510                        next_path.push(token_id);
11511                        next.push((next_fast, next_profiled, next_general, next_path));
11512                    }
11513                }
11514            }
11515            frontier = next;
11516        }
11517    }
11518
11519    #[test]
11520    fn epsilon_full_width_terminal_with_empty_accumulators_uses_fast_path() {
11521        let vocab = Vocab::from_entries_unchecked(vec![(0, b"a".to_vec()), (1, b"b".to_vec())]);
11522        let grammar = crate::grammar::glrm::from_glrm(
11523            r#"
11524                start start;
11525                pragma glrmask {
11526                    lexer group left = A;
11527                    lexer group right = B;
11528                }
11529                t A = "a";
11530                t B = "b";
11531                nt start = A | B;
11532            "#,
11533        )
11534        .unwrap();
11535        let grammar = crate::grammar::ast::lower(&grammar).unwrap();
11536        let constraint = crate::compiler::pipeline::compile_owned_with_lexer_adaptive(
11537            grammar,
11538            &vocab,
11539            false,
11540        );
11541
11542        let mut state = constraint.start();
11543        let profile = state.commit_token_profiled(0).unwrap();
11544        assert!(profile.fast_path_total_ns > 0, "profile={profile:?}");
11545        assert_eq!(profile.n_queue_entries, 0, "profile={profile:?}");
11546        assert_eq!(profile.n_advances, 1, "profile={profile:?}");
11547    }
11548}
11549
11550#[cfg(test)]
11551mod boxed_small_queue_tests {
11552    use super::SmallCommitQueueScratch;
11553    use crate::runtime::state::CommitBuffers;
11554
11555    #[test]
11556    fn read_only_mask_buffers_leave_commit_queue_uninitialized() {
11557        let mut buffers = CommitBuffers::for_mask_only_shadow();
11558        assert!(buffers.small_queue.is_none());
11559        assert!(buffers.flat_frontier.is_none());
11560        buffers.clear_all();
11561        buffers.reset_all();
11562        assert!(buffers.small_queue.is_none());
11563        assert!(buffers.flat_frontier.is_none());
11564        // An internal caller that subsequently commits still gets an ordinary
11565        // empty queue; this does not change the eager policy of real states.
11566        let queue = buffers.small_queue.get_or_insert_with(SmallCommitQueueScratch::boxed);
11567        assert!(queue.processing.iter().all(|bucket| bucket.is_empty()));
11568        assert!(queue.language_processing.iter().all(|bucket| bucket.is_empty()));
11569        assert!(queue.pending.is_empty() && queue.language_pending.is_empty());
11570    }
11571
11572    #[test]
11573    fn ordinary_commit_buffers_prepare_and_reuse_their_queue() {
11574        for mut buffers in [CommitBuffers::default(), CommitBuffers::for_finite_recursive_mask()] {
11575            let initial = buffers.small_queue.as_deref().unwrap() as *const SmallCommitQueueScratch;
11576            buffers.clear_all();
11577            buffers.reset_all();
11578            let retained = buffers.small_queue.as_deref().unwrap() as *const SmallCommitQueueScratch;
11579            assert_eq!(initial, retained);
11580        }
11581        // The queue's fixed arrays must not be embedded in every state copy.
11582        assert_eq!(std::mem::size_of::<Option<Box<SmallCommitQueueScratch>>>(),
11583            std::mem::size_of::<*mut SmallCommitQueueScratch>());
11584    }
11585
11586    #[test]
11587    fn state_buffers_keep_large_frontier_storage_indirect_and_reusable() {
11588        // Guard the nested construction/copy frames, not a platform-specific
11589        // total stack size. Native pthread tests cover the actual call chain.
11590        assert!(std::mem::size_of::<CommitBuffers>() < 8 * 1024);
11591        let mut buffers = CommitBuffers::default();
11592        let initial = buffers.flat_frontier.as_deref().unwrap() as *const super::FlatFrontierScratch;
11593        buffers.clear_all();
11594        buffers.reset_all();
11595        assert_eq!(initial, buffers.flat_frontier.as_deref().unwrap() as *const super::FlatFrontierScratch);
11596    }
11597}
11598
11599#[cfg(test)]
11600mod flat_pool_order_tests;