logit-loom-core 0.2.0

Backend-neutral contracts for mechanistic token-stream manipulation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Backend-neutral generation and native-sampler plans.

use std::collections::HashSet;

use serde::{Deserialize, Serialize};

use crate::{CoreError, Digest, TokenId};

/// Maximum exact sequence breakers accepted by one DRY sampler.
pub const MAX_DRY_SEQUENCE_BREAKERS: usize = 64;
/// Maximum UTF-8 bytes accepted in one DRY sequence breaker.
pub const MAX_DRY_SEQUENCE_BREAKER_BYTES: usize = 40;
/// Maximum additive token biases accepted by one generation plan.
pub const MAX_LOGIT_BIASES: usize = 65_536;
/// Maximum UTF-8 bytes accepted in an eager grammar source.
pub const MAX_GRAMMAR_SOURCE_BYTES: usize = 1024 * 1024;
/// Maximum UTF-8 bytes accepted in an eager grammar root name.
pub const MAX_GRAMMAR_ROOT_BYTES: usize = 256;
/// Maximum trigger patterns accepted by one lazy grammar.
pub const MAX_LAZY_GRAMMAR_TRIGGER_PATTERNS: usize = 64;
/// Maximum UTF-8 bytes accepted in one lazy-grammar trigger pattern.
pub const MAX_LAZY_GRAMMAR_TRIGGER_PATTERN_BYTES: usize = 4_096;
/// Maximum aggregate UTF-8 bytes accepted across lazy-grammar trigger patterns.
pub const MAX_LAZY_GRAMMAR_TRIGGER_BYTES: usize = 64 * 1_024;
/// Maximum trigger tokens accepted by one lazy grammar.
pub const MAX_LAZY_GRAMMAR_TRIGGER_TOKENS: usize = 4_096;
/// Maximum exact byte stop sequences accepted by one generation plan.
pub const MAX_STOP_SEQUENCES: usize = 64;
/// Maximum bytes accepted in one exact stop sequence.
pub const MAX_STOP_SEQUENCE_BYTES: usize = 4_096;

/// Stateful repetition, frequency, and presence penalties.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RepetitionSampler {
    /// Number of preceding tokens to retain; `-1` selects the context bound.
    pub last_n: i32,
    /// Multiplicative repeat penalty; `1.0` is neutral.
    pub repeat_penalty: f32,
    /// Additive frequency penalty per occurrence.
    pub frequency_penalty: f32,
    /// Additive penalty when a token is present.
    pub presence_penalty: f32,
}

/// Don't Repeat Yourself sampler configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DrySampler {
    /// Positive penalty multiplier.
    pub multiplier: f32,
    /// Exponential penalty base, at least `1.0`.
    pub base: f32,
    /// Prefix length allowed before penalties begin.
    pub allowed_length: i32,
    /// Number of preceding tokens to scan; `-1` selects the context bound.
    pub penalty_last_n: i32,
    /// Exact sequence breakers.
    pub sequence_breakers: Vec<String>,
}

/// Native Mirostat algorithm version.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MirostatVersion {
    /// Original Mirostat algorithm.
    V1,
    /// Mirostat 2.0.
    V2,
}

/// Stateful Mirostat terminal sampler configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MirostatSampler {
    /// Selected algorithm.
    pub version: MirostatVersion,
    /// Target surprisal.
    pub tau: f32,
    /// Adaptive learning rate.
    pub eta: f32,
    /// Positive candidate-estimation window for version one; zero for version
    /// two.
    pub m: i32,
}

/// Native sampler configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SamplingPlan {
    /// Deterministic sampler seed.
    pub seed: u32,
    /// Temperature; zero selects greedy decoding.
    pub temperature: f32,
    /// Top-k candidate count; zero disables the filter.
    pub top_k: i32,
    /// Nucleus probability.
    pub top_p: f32,
    /// Minimum probability relative to the most likely token.
    pub min_p: f32,
    /// Locally typical probability mass; `1.0` disables the filter.
    pub typical_p: f32,
    /// Optional repetition/frequency/presence penalties.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repetition: Option<RepetitionSampler>,
    /// Optional DRY sampler.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dry: Option<DrySampler>,
    /// Optional Mirostat terminal sampler.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mirostat: Option<MirostatSampler>,
}

impl Default for SamplingPlan {
    fn default() -> Self {
        Self {
            seed: 0,
            temperature: 0.0,
            top_k: 40,
            top_p: 0.95,
            min_p: 0.05,
            typical_p: 1.0,
            repetition: None,
            dry: None,
            mirostat: None,
        }
    }
}

impl SamplingPlan {
    /// Validates finite values and native sampler bounds.
    ///
    /// # Errors
    ///
    /// Returns an error for unsupported numeric values.
    pub fn validate(&self) -> Result<(), CoreError> {
        for (field, value) in [
            ("temperature", self.temperature),
            ("top p", self.top_p),
            ("min p", self.min_p),
            ("typical p", self.typical_p),
        ] {
            if !value.is_finite() {
                return Err(CoreError::NonFinite { field });
            }
        }
        if self.temperature < 0.0
            || self.top_k < 0
            || !(0.0..=1.0).contains(&self.top_p)
            || !(0.0..=1.0).contains(&self.min_p)
            || !(0.0..=1.0).contains(&self.typical_p)
        {
            return Err(CoreError::invalid(
                "sampling plan",
                "temperature/top-k must be non-negative and probabilities must be in 0..=1",
            ));
        }
        if let Some(repetition) = &self.repetition {
            for (field, value) in [
                ("repeat penalty", repetition.repeat_penalty),
                ("frequency penalty", repetition.frequency_penalty),
                ("presence penalty", repetition.presence_penalty),
            ] {
                if !value.is_finite() {
                    return Err(CoreError::NonFinite { field });
                }
            }
            if repetition.last_n < -1 || repetition.repeat_penalty <= 0.0 {
                return Err(CoreError::invalid(
                    "repetition sampler",
                    "last_n must be at least -1 and repeat_penalty must be positive",
                ));
            }
        }
        if let Some(dry) = &self.dry {
            for (field, value) in [("DRY multiplier", dry.multiplier), ("DRY base", dry.base)] {
                if !value.is_finite() {
                    return Err(CoreError::NonFinite { field });
                }
            }
            if dry.multiplier <= 0.0
                || dry.base < 1.0
                || dry.allowed_length < 0
                || dry.penalty_last_n < -1
                || dry.penalty_last_n == 0
            {
                return Err(CoreError::invalid(
                    "dry sampler",
                    "multiplier must be positive, base at least one, allowed length non-negative, and lookback -1 or positive",
                ));
            }
            if dry.sequence_breakers.len() > MAX_DRY_SEQUENCE_BREAKERS
                || dry.sequence_breakers.iter().any(|value| {
                    value.is_empty()
                        || value.len() > MAX_DRY_SEQUENCE_BREAKER_BYTES
                        || value.contains('\0')
                })
            {
                return Err(CoreError::invalid(
                    "dry sequence breakers",
                    format!(
                        "requires at most {MAX_DRY_SEQUENCE_BREAKERS} non-empty, NUL-free values of at most {MAX_DRY_SEQUENCE_BREAKER_BYTES} bytes"
                    ),
                ));
            }
        }
        if let Some(mirostat) = &self.mirostat {
            for (field, value) in [
                ("Mirostat tau", mirostat.tau),
                ("Mirostat eta", mirostat.eta),
            ] {
                if !value.is_finite() {
                    return Err(CoreError::NonFinite { field });
                }
            }
            let invalid_window = match mirostat.version {
                MirostatVersion::V1 => mirostat.m <= 0,
                MirostatVersion::V2 => mirostat.m != 0,
            };
            if self.temperature <= 0.0
                || mirostat.tau <= 0.0
                || mirostat.eta <= 0.0
                || invalid_window
            {
                return Err(CoreError::invalid(
                    "mirostat sampler",
                    "temperature, tau, and eta must be positive; m must be positive for v1 and zero for v2",
                ));
            }
        }
        Ok(())
    }
}

/// One additive token-logit bias.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct LogitBias {
    /// Target token.
    pub token: TokenId,
    /// Finite additive bias.
    pub bias: f32,
}

/// An eager llama.cpp GBNF grammar.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Grammar {
    /// Complete GBNF source.
    pub source: String,
    /// Root rule name.
    pub root: String,
}

impl Grammar {
    /// Validates bounded strings before they cross a native C-string boundary.
    ///
    /// # Errors
    ///
    /// Returns an error for empty, oversized, or NUL-containing values.
    pub fn validate(&self) -> Result<(), CoreError> {
        if self.source.is_empty() || self.root.is_empty() {
            return Err(CoreError::Empty {
                field: "grammar source/root",
            });
        }
        if self.source.len() > MAX_GRAMMAR_SOURCE_BYTES || self.root.len() > MAX_GRAMMAR_ROOT_BYTES
        {
            return Err(CoreError::invalid(
                "grammar",
                format!(
                    "source must be at most {MAX_GRAMMAR_SOURCE_BYTES} bytes and root at most {MAX_GRAMMAR_ROOT_BYTES} bytes"
                ),
            ));
        }
        if self.source.contains('\0') || self.root.contains('\0') {
            return Err(CoreError::invalid(
                "grammar",
                "source and root must not contain NUL bytes",
            ));
        }
        Ok(())
    }
}

/// Activation policy for a version-two native grammar.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum GrammarActivationV2 {
    /// Constrain the first generated token and every subsequent token.
    Eager,
    /// Begin unconstrained and activate when an exact pattern or token
    /// trigger is observed by the native sampler.
    Lazy {
        /// Ordered native regular-expression trigger patterns.
        trigger_patterns: Vec<String>,
        /// Ordered exact tokenizer IDs that activate the grammar.
        trigger_tokens: Vec<TokenId>,
    },
}

/// Version-two eager or lazy llama.cpp GBNF grammar.
///
/// This is a separate serialized contract from [`Grammar`]. Existing
/// generation-plan-v1 identities therefore remain unchanged.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GrammarPlanV2 {
    /// Complete bounded GBNF grammar and root rule.
    pub grammar: Grammar,
    /// Eager or trigger-driven activation.
    pub activation: GrammarActivationV2,
}

impl GrammarPlanV2 {
    /// Validates grammar and lazy-trigger bounds.
    ///
    /// # Errors
    ///
    /// Returns an error for malformed grammar text, empty lazy activation,
    /// duplicate triggers, excessive trigger counts, or excessive pattern
    /// bytes.
    pub fn validate(&self) -> Result<(), CoreError> {
        self.grammar.validate()?;
        let GrammarActivationV2::Lazy {
            trigger_patterns,
            trigger_tokens,
        } = &self.activation
        else {
            return Ok(());
        };
        if trigger_patterns.is_empty() && trigger_tokens.is_empty() {
            return Err(CoreError::invalid(
                "lazy grammar",
                "at least one trigger pattern or token is required",
            ));
        }
        let trigger_bytes = trigger_patterns
            .iter()
            .try_fold(0_usize, |total, pattern| {
                total
                    .checked_add(pattern.len())
                    .ok_or_else(|| CoreError::invalid("lazy grammar", "trigger bytes overflowed"))
            })?;
        if trigger_patterns.len() > MAX_LAZY_GRAMMAR_TRIGGER_PATTERNS
            || trigger_patterns.iter().any(|pattern| {
                pattern.is_empty()
                    || pattern.len() > MAX_LAZY_GRAMMAR_TRIGGER_PATTERN_BYTES
                    || pattern.contains('\0')
            })
            || trigger_bytes > MAX_LAZY_GRAMMAR_TRIGGER_BYTES
            || trigger_tokens.len() > MAX_LAZY_GRAMMAR_TRIGGER_TOKENS
        {
            return Err(CoreError::invalid(
                "lazy grammar",
                format!(
                    "requires at most {MAX_LAZY_GRAMMAR_TRIGGER_PATTERNS} non-empty NUL-free patterns of at most {MAX_LAZY_GRAMMAR_TRIGGER_PATTERN_BYTES} bytes, {MAX_LAZY_GRAMMAR_TRIGGER_BYTES} aggregate pattern bytes, and {MAX_LAZY_GRAMMAR_TRIGGER_TOKENS} trigger tokens"
                ),
            ));
        }
        if trigger_patterns.iter().collect::<HashSet<_>>().len() != trigger_patterns.len()
            || trigger_tokens.iter().collect::<HashSet<_>>().len() != trigger_tokens.len()
        {
            return Err(CoreError::invalid(
                "lazy grammar",
                "trigger patterns and token identifiers must each be unique",
            ));
        }
        Ok(())
    }

    /// Returns the exact grammar identity.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("grammar-plan-v2", self)
    }
}

/// Complete bounded generation mechanics independent of prompt semantics.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct GenerationPlan {
    /// Native sampler configuration.
    pub sampling: SamplingPlan,
    /// Maximum causally admitted output tokens.
    pub max_tokens: u32,
    /// Additive biases with unique token IDs, applied after Rust transforms and
    /// before filters.
    #[serde(default)]
    pub biases: Vec<LogitBias>,
    /// Optional eager grammar.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grammar: Option<Grammar>,
    /// Exact byte suffixes that stop after causal admission.
    ///
    /// Matching bytes remain in output and causal state. When several suffixes
    /// match the same output, the lowest declared index wins.
    #[serde(default)]
    pub stops: Vec<Vec<u8>>,
}

impl GenerationPlan {
    /// Validates all bounded generation mechanics.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid samplers, bounds, biases, grammar, or stops.
    pub fn validate(&self) -> Result<(), CoreError> {
        self.sampling.validate()?;
        if self.max_tokens == 0 {
            return Err(CoreError::invalid(
                "maximum tokens",
                "must be greater than zero",
            ));
        }
        if self.biases.len() > MAX_LOGIT_BIASES
            || self.biases.iter().any(|bias| !bias.bias.is_finite())
        {
            return Err(CoreError::invalid(
                "logit biases",
                "too many biases or a non-finite value",
            ));
        }
        if self
            .biases
            .iter()
            .map(|bias| bias.token)
            .collect::<HashSet<_>>()
            .len()
            != self.biases.len()
        {
            return Err(CoreError::invalid(
                "logit biases",
                "token identifiers must be unique",
            ));
        }
        if let Some(grammar) = &self.grammar {
            grammar.validate()?;
        }
        if self.stops.len() > MAX_STOP_SEQUENCES
            || self
                .stops
                .iter()
                .any(|stop| stop.is_empty() || stop.len() > MAX_STOP_SEQUENCE_BYTES)
        {
            return Err(CoreError::invalid(
                "stop sequences",
                format!(
                    "requires at most {MAX_STOP_SEQUENCES} non-empty sequences of at most {MAX_STOP_SEQUENCE_BYTES} bytes"
                ),
            ));
        }
        Ok(())
    }

    /// Returns a content identity for exact generation mechanics.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("generation-plan-v1", self)
    }
}

/// Version-two generation mechanics with explicit eager or lazy grammar.
///
/// The embedded v1 generation plan must not select its eager grammar. This
/// prevents the new contract from reinterpreting `generation-plan-v1` while
/// reusing all unchanged sampler, bias, stop, and bound mechanics.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GenerationPlanV2 {
    /// Complete unchanged v1 sampler, bias, stop, and token-bound mechanics.
    pub generation: GenerationPlan,
    /// Optional version-two eager or lazy grammar.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grammar: Option<GrammarPlanV2>,
}

impl GenerationPlanV2 {
    /// Validates the complete version-two generation plan.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid v1 mechanics, simultaneous v1 and v2
    /// grammar selection, or invalid version-two grammar triggers.
    pub fn validate(&self) -> Result<(), CoreError> {
        self.generation.validate()?;
        if self.generation.grammar.is_some() {
            return Err(CoreError::invalid(
                "generation plan v2",
                "the embedded generation-plan-v1 grammar must be absent",
            ));
        }
        if let Some(grammar) = &self.grammar {
            grammar.validate()?;
        }
        Ok(())
    }

    /// Returns a content identity for exact version-two mechanics.
    ///
    /// # Errors
    ///
    /// Returns a validation or serialization error.
    pub fn digest(&self) -> Result<Digest, CoreError> {
        self.validate()?;
        Digest::of_serializable("generation-plan-v2", self)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn plan() -> GenerationPlan {
        GenerationPlan {
            sampling: SamplingPlan::default(),
            max_tokens: 8,
            biases: Vec::new(),
            grammar: None,
            stops: vec![b"stop".to_vec()],
        }
    }

    #[test]
    fn generation_plan_roundtrip_preserves_identity() {
        let original = plan();
        let encoded = serde_json::to_vec(&original).unwrap();
        let decoded: GenerationPlan = serde_json::from_slice(&encoded).unwrap();
        assert_eq!(original.digest().unwrap(), decoded.digest().unwrap());
    }

    #[test]
    fn generation_plan_rejects_unbounded_or_nonfinite_mechanics() {
        let mut invalid = plan();
        invalid.max_tokens = 0;
        assert!(invalid.validate().is_err());
        invalid.max_tokens = 1;
        invalid.sampling.temperature = f32::NAN;
        assert!(invalid.validate().is_err());
        invalid.sampling.temperature = 0.0;
        invalid.stops = vec![Vec::new()];
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn stateful_sampler_bounds_are_explicit() {
        let mut sampling = SamplingPlan {
            temperature: 0.8,
            dry: Some(DrySampler {
                multiplier: 0.8,
                base: 1.75,
                allowed_length: 2,
                penalty_last_n: -1,
                sequence_breakers: vec!["\n".to_owned()],
            }),
            mirostat: Some(MirostatSampler {
                version: MirostatVersion::V2,
                tau: 5.0,
                eta: 0.1,
                m: 0,
            }),
            ..SamplingPlan::default()
        };
        assert!(sampling.validate().is_ok());

        sampling.dry.as_mut().unwrap().sequence_breakers = vec![String::new()];
        assert!(sampling.validate().is_err());
        sampling.dry.as_mut().unwrap().sequence_breakers = vec!["\n".to_owned()];
        sampling.dry.as_mut().unwrap().base = f32::NAN;
        assert!(matches!(
            sampling.validate(),
            Err(CoreError::NonFinite { field: "DRY base" })
        ));

        sampling.dry = None;
        sampling.temperature = 0.0;
        assert!(sampling.validate().is_err());

        sampling.temperature = 0.8;
        sampling.mirostat.as_mut().unwrap().m = 1;
        assert!(sampling.validate().is_err());
        sampling.mirostat = Some(MirostatSampler {
            version: MirostatVersion::V1,
            tau: 5.0,
            eta: 0.1,
            m: 0,
        });
        assert!(sampling.validate().is_err());
    }

    #[test]
    fn grammar_and_stop_inputs_have_explicit_byte_bounds() {
        let oversized_source = Grammar {
            source: "x".repeat(MAX_GRAMMAR_SOURCE_BYTES + 1),
            root: "root".to_owned(),
        };
        assert!(oversized_source.validate().is_err());

        let oversized_root = Grammar {
            source: "root ::= \"x\"".to_owned(),
            root: "x".repeat(MAX_GRAMMAR_ROOT_BYTES + 1),
        };
        assert!(oversized_root.validate().is_err());

        let mut invalid = plan();
        invalid.stops = vec![vec![b'x'; MAX_STOP_SEQUENCE_BYTES + 1]];
        assert!(invalid.validate().is_err());
        invalid.stops = vec![vec![b'x']; MAX_STOP_SEQUENCES + 1];
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn every_logit_bias_must_be_finite() {
        let mut invalid = plan();
        invalid.biases.push(LogitBias {
            token: TokenId::new(7).unwrap(),
            bias: f32::INFINITY,
        });
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn generation_logit_bias_tokens_must_be_unique() {
        let mut invalid = plan();
        invalid.biases = vec![
            LogitBias {
                token: TokenId::new(7).unwrap(),
                bias: 1.0,
            },
            LogitBias {
                token: TokenId::new(7).unwrap(),
                bias: 2.0,
            },
        ];
        assert!(invalid.validate().is_err());
    }

    #[test]
    fn version_two_generation_preserves_v1_and_binds_lazy_triggers() {
        let grammar = GrammarPlanV2 {
            grammar: Grammar {
                source: "root ::= \"{}\"".to_owned(),
                root: "root".to_owned(),
            },
            activation: GrammarActivationV2::Lazy {
                trigger_patterns: vec!["<tool>.*".to_owned()],
                trigger_tokens: vec![TokenId::new(7).unwrap()],
            },
        };
        let version_two = GenerationPlanV2 {
            generation: plan(),
            grammar: Some(grammar.clone()),
        };
        assert!(version_two.validate().is_ok());
        assert_ne!(
            version_two.digest().unwrap(),
            version_two.generation.digest().unwrap()
        );

        let mut duplicate = version_two.clone();
        duplicate.grammar.as_mut().unwrap().activation = GrammarActivationV2::Lazy {
            trigger_patterns: vec!["x".to_owned(), "x".to_owned()],
            trigger_tokens: Vec::new(),
        };
        assert!(duplicate.validate().is_err());

        let mut ambiguous = version_two;
        ambiguous.generation.grammar = Some(grammar.grammar);
        assert!(ambiguous.validate().is_err());
    }
}