Skip to main content

dynamo_tokens/
lib.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4#![deny(missing_docs)]
5
6//! Types and utilities for handling sequences of tokens, including block creation and hashing.
7
8use bytemuck::cast_slice;
9use derive_getters::Dissolve;
10use std::ops::Range;
11
12pub mod blocks;
13mod radix;
14pub use radix::PositionalRadixTree;
15
16/// Trait for hashes that include position information.
17pub trait PositionalHash {
18    /// Returns the position associated with the hash.
19    fn position(&self) -> u64;
20}
21
22/// A token is represented as a 32-bit unsigned integer.
23pub type Token = u32;
24
25/// A salt used for hashing, represented as a vector of bytes.
26/// This might encode model architecture, weights, PEFT info, etc.
27pub type Salt = Vec<u8>;
28
29/// A 64-bit hash of the salt. Computed once per request and used as the seed for
30/// every block-hash computation in that request.
31///
32/// The canonical construction path is [`compute_salt_hash_from_bytes`] (or
33/// `dynamo_kv_hashing::Request::salt_hash` at the application layer).
34pub type SaltHash = u64;
35
36/// A 64-bit hash computed from the tokens within a single block (with optional MM
37/// frames), seeded by the request's [`SaltHash`].
38///
39/// The canonical construction path is [`compute_block_hash`].
40pub type BlockHash = u64;
41
42/// A 64-bit sequence-aware hash. Equals the [`BlockHash`] at position 0 and
43/// [`compute_next_sequence_hash(prev_seq, block_hash)`](compute_next_sequence_hash)
44/// at every subsequent position. Salt propagates through `seq_hash[0]` since
45/// `block_hash[0]` already encodes it.
46pub type SequenceHash = u64;
47
48/// Computes a hash of the data using the given seed (raw u64).
49///
50/// Prefer [`compute_block_hash`] / [`compute_salt_hash_from_bytes`] for typed
51/// construction; this raw-u64 form is kept for low-level callers.
52pub fn compute_hash_v2(data: &[u8], seed: u64) -> u64 {
53    xxhash_rust::xxh3::xxh3_64_with_seed(data, seed)
54}
55
56/// Canonical XXH3 seed used by every chain-step `(parent_seq, child_block_hash) → next_seq`
57/// in this codebase. Must match `dynamo_kv_router::protocols::XXH3_SEED` — the router's
58/// `compute_seq_hash_for_block` and the `PositionalIndexer`'s chain re-computation both
59/// route through [`compute_next_sequence_hash`] (or equivalently seeded helpers in
60/// `kv-router`), so changing this constant requires all of them to flip in lockstep.
61pub const CHAIN_XXH3_SEED: u64 = 1337;
62
63/// Chain-step for sequence hashing: returns the [`SequenceHash`] at `position + 1`
64/// given the parent's `SequenceHash` and the child block's [`BlockHash`].
65///
66/// This is the single source of truth for the chain recurrence used by:
67/// - [`PositionalLineageHash::extend`]
68/// - `TokenBlock::from_chunk`
69/// - `dynamo_kv_router::protocols::compute_next_seq_hash` (request side)
70/// - `dynamo_kv_router::indexer::PositionalIndexer` (chain re-validation)
71///
72/// Salt is already mixed into `block_hash[0]` and propagates through every parent, so
73/// the per-step seed is a constant: re-feeding salt at each step would be redundant.
74/// Any constant seed preserves PLH composability — the value is set to
75/// [`CHAIN_XXH3_SEED`] to match the router's existing wire format.
76#[inline]
77pub fn compute_next_sequence_hash(
78    parent_sequence_hash: SequenceHash,
79    child_block_hash: BlockHash,
80) -> SequenceHash {
81    let combined = [parent_sequence_hash, child_block_hash];
82    compute_hash_v2(cast_slice(&combined), CHAIN_XXH3_SEED)
83}
84
85/// Custom serde codec that encodes a `u128` as a 16-byte big-endian byte sequence.
86///
87/// MessagePack (`rmp-serde`) has no native 128-bit integer type, so the default
88/// `u128` derive does not roundtrip reliably. Encoding as raw bytes is supported
89/// uniformly across msgpack, JSON, CBOR, etc.
90mod serde_bytes_u128 {
91    use serde::{Deserializer, Serializer};
92
93    pub fn serialize<S>(val: &u128, serializer: S) -> Result<S::Ok, S::Error>
94    where
95        S: Serializer,
96    {
97        serializer.serialize_bytes(&val.to_be_bytes())
98    }
99
100    pub fn deserialize<'de, D>(deserializer: D) -> Result<u128, D::Error>
101    where
102        D: Deserializer<'de>,
103    {
104        use serde::de::{self, SeqAccess, Visitor};
105        use std::fmt;
106
107        struct V;
108        impl<'de> Visitor<'de> for V {
109            type Value = [u8; 16];
110
111            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
112                f.write_str("16 bytes (msgpack bin) or a sequence of 16 u8 values")
113            }
114
115            fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<[u8; 16], E> {
116                v.try_into()
117                    .map_err(|_| E::invalid_length(v.len(), &"16 bytes"))
118            }
119
120            fn visit_borrowed_bytes<E: de::Error>(self, v: &'de [u8]) -> Result<[u8; 16], E> {
121                self.visit_bytes(v)
122            }
123
124            fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<[u8; 16], E> {
125                self.visit_bytes(&v)
126            }
127
128            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<[u8; 16], A::Error> {
129                let mut arr = [0u8; 16];
130                for (i, slot) in arr.iter_mut().enumerate() {
131                    *slot = seq
132                        .next_element()?
133                        .ok_or_else(|| de::Error::invalid_length(i, &"16 u8 elements"))?;
134                }
135                Ok(arr)
136            }
137        }
138
139        let arr = deserializer.deserialize_bytes(V)?;
140        Ok(u128::from_be_bytes(arr))
141    }
142}
143
144/// Canonical [`BlockHash`] construction: XXH3 over the per-block byte buffer
145/// (already encoded by [`compute_block_bytes_with_mm`] or `cast_slice` for the
146/// no-MM path), seeded by [`SaltHash`].
147#[inline]
148pub fn compute_block_hash(block_bytes: &[u8], salt: SaltHash) -> BlockHash {
149    compute_hash_v2(block_bytes, salt)
150}
151
152/// Canonical [`BlockHash`] construction for a token-only block.
153///
154/// Multimodal token sequences must first route through
155/// [`compute_block_bytes_with_mm`] so placeholder slots use their multimodal
156/// identities instead of their token IDs.
157#[inline]
158pub fn compute_block_hash_for_tokens(tokens: &[Token], salt: SaltHash) -> BlockHash {
159    compute_block_hash(cast_slice(tokens), salt)
160}
161
162/// Canonical [`SaltHash`] construction from a pre-canonicalized salt-payload byte
163/// buffer. Application-layer callers should use `dynamo_kv_hashing::Request::salt_hash`
164/// which canonicalizes `(salt, lora_name)` first; this function is the low-level path.
165#[inline]
166pub fn compute_salt_hash_from_bytes(payload: &[u8]) -> SaltHash {
167    compute_hash_v2(payload, 0)
168}
169
170/// Metadata describing a single multimodal placeholder run within a token sequence.
171///
172/// A run occupies `length` consecutive slots starting at `offset`. The token IDs at
173/// those slot positions are opaque for hashing — the `(mm_hash, run_offset)` pair drives
174/// the per-slot bytes during block formation.
175///
176/// See [`compute_block_bytes_with_mm`] for the byte-encoding rule.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
178pub struct TokenBlockMmInfo {
179    /// Hash identifying the multimodal object (image / audio / etc.).
180    pub mm_hash: u64,
181    /// Start position of the placeholder run in the full token sequence (zero-based).
182    pub offset: usize,
183    /// Number of placeholder slots in the run.
184    pub length: usize,
185}
186
187/// Slot-tag byte distinguishing real-token slots from multimodal placeholder slots in
188/// the per-block byte buffer. See [`compute_block_bytes_with_mm`].
189pub const MM_SLOT_TAG_TOKEN: u8 = 0x00;
190/// Slot-tag byte for multimodal placeholder slots. See [`compute_block_bytes_with_mm`].
191pub const MM_SLOT_TAG_PLACEHOLDER: u8 = 0x01;
192
193impl TokenBlockMmInfo {
194    /// Returns the exclusive end position of this run, or `None` on `usize` overflow.
195    #[inline]
196    pub fn checked_end(&self) -> Option<usize> {
197        self.offset.checked_add(self.length)
198    }
199
200    /// Returns the exclusive end position of this run.
201    ///
202    /// # Panics
203    /// Panics if `offset + length` overflows `usize`. Prefer [`Self::checked_end`] in
204    /// validation paths; this helper is for already-validated runs.
205    #[inline]
206    pub fn end(&self) -> usize {
207        self.checked_end()
208            .expect("TokenBlockMmInfo::end overflowed usize; run was not validated")
209    }
210
211    /// Returns `true` if the given absolute position falls inside this run.
212    /// Returns `false` if the run's end overflows `usize` (such a run is invalid; use
213    /// [`validate_and_sort_mm_info`] before relying on this method).
214    #[inline]
215    pub fn covers(&self, position: usize) -> bool {
216        match self.checked_end() {
217            Some(end) => position >= self.offset && position < end,
218            None => false,
219        }
220    }
221}
222
223/// Errors raised while validating [`TokenBlockMmInfo`] inputs.
224#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
225pub enum MmInfoError {
226    /// The run extends past the end of the token sequence.
227    #[error(
228        "mm_info range starting at {offset} (length {length}) exceeds tokens length {tokens_len}"
229    )]
230    OutOfBounds {
231        /// Run start.
232        offset: usize,
233        /// Run length.
234        length: usize,
235        /// Length of the token sequence the run was validated against.
236        tokens_len: usize,
237    },
238    /// `offset + length` overflows `usize`.
239    #[error("mm_info range starting at {offset} (length {length}) overflows usize")]
240    OffsetOverflow {
241        /// Run start.
242        offset: usize,
243        /// Run length.
244        length: usize,
245    },
246    /// Two runs overlap.
247    #[error("mm_info ranges overlap at position {position}")]
248    Overlapping {
249        /// Position where the overlap begins.
250        position: usize,
251    },
252    /// A run has zero length.
253    #[error("mm_info length must be greater than zero")]
254    EmptyRun,
255}
256
257/// Validates `mm_info` against `tokens_len` and returns a copy sorted by `offset`.
258///
259/// Validation rules:
260/// - Every run must have `length > 0`.
261/// - `offset + length` must not overflow `usize`.
262/// - Every run's end (`offset + length`) must be `<= tokens_len`.
263/// - No two runs may overlap.
264pub fn validate_and_sort_mm_info(
265    mm_info: &[TokenBlockMmInfo],
266    tokens_len: usize,
267) -> Result<Vec<TokenBlockMmInfo>, MmInfoError> {
268    let mut sorted: Vec<TokenBlockMmInfo> = mm_info.to_vec();
269    sorted.sort_by_key(|m| m.offset);
270    let mut prev_end = 0usize;
271    for m in &sorted {
272        if m.length == 0 {
273            return Err(MmInfoError::EmptyRun);
274        }
275        let end = m
276            .offset
277            .checked_add(m.length)
278            .ok_or(MmInfoError::OffsetOverflow {
279                offset: m.offset,
280                length: m.length,
281            })?;
282        if end > tokens_len {
283            return Err(MmInfoError::OutOfBounds {
284                offset: m.offset,
285                length: m.length,
286                tokens_len,
287            });
288        }
289        if m.offset < prev_end {
290            return Err(MmInfoError::Overlapping { position: m.offset });
291        }
292        prev_end = end;
293    }
294    Ok(sorted)
295}
296
297/// Returns `true` if any run in `mm_runs` overlaps the block `[block_offset, block_offset + len)`.
298/// `mm_runs` must be validated and sorted.
299fn block_has_mm(block_offset: usize, len: usize, mm_runs: &[TokenBlockMmInfo]) -> bool {
300    let block_end = block_offset.saturating_add(len);
301    mm_runs
302        .iter()
303        .any(|m| m.offset < block_end && m.end() > block_offset)
304}
305
306/// Builds the byte buffer used to compute a block's [`BlockHash`].
307///
308/// **Two encodings, picked per-block:**
309///
310/// 1. **Legacy / zero-MM** — when no run in `mm_runs` overlaps this block, the buffer is
311///    `bytemuck::cast_slice(tokens)` (4 bytes per slot, LE u32). This matches the existing
312///    `compute_hash_v2(cast_slice(&tokens), salt_hash)` path used by every existing
313///    [`TokenBlock`] in `dynamo_tokens` and kvbm — preserving cache identity for any block
314///    that is not itself MM-affected.
315///
316/// 2. **Tagged / MM-affected** — when at least one run overlaps this block, every slot
317///    emits a fixed 13-byte frame:
318///    - Real-token slot: `[MM_SLOT_TAG_TOKEN | token_id u32 LE | 0u64 LE]`
319///      The trailing `0u64` is **frame padding only** — it has no semantic meaning,
320///      it is there so the real-token frame matches the placeholder frame's width.
321///      Token IDs at placeholder positions are *ignored* by this encoder; whether
322///      a slot is a placeholder is determined solely by `mm_runs[run_idx].covers(g)`.
323///    - Placeholder slot: `[MM_SLOT_TAG_PLACEHOLDER | run_offset u32 LE | mm_hash u64 LE]`,
324///      where `run_offset = (block_offset + s) - run.offset`.
325///
326///    The 1-byte tag plus the fixed-width frame make the encoding self-delimiting and
327///    slot-position-preserving: two MM-affected byte buffers compare equal iff they describe
328///    the same `(slot_kind, slot_payload)` sequence at the same slot positions.
329///
330/// The two encodings have different per-slot widths (4 vs 13), so an all-tokens block can
331/// never produce the same byte buffer as an MM-affected block — eliminating cross-encoding
332/// collisions.
333///
334/// `mm_runs` must be validated and sorted (typically the output of
335/// [`validate_and_sort_mm_info`]).
336pub fn compute_block_bytes_with_mm(
337    tokens: &[Token],
338    block_offset: usize,
339    mm_runs: &[TokenBlockMmInfo],
340) -> Vec<u8> {
341    // Defense-in-depth: routing of each slot to the placeholder vs real-token branch
342    // depends on `mm_runs` being sorted by offset and non-overlapping. The public
343    // entry points (`Request::new`, `TokenBlockSequence::new_with_mm`,
344    // `split_tokens_with_mm`) enforce this via `validate_and_sort_mm_info`, but this
345    // function is also pub so we re-check in debug to catch direct misuse.
346    debug_assert!(
347        mm_runs.windows(2).all(|w| w[0].end() <= w[1].offset),
348        "compute_block_bytes_with_mm: mm_runs must be sorted by offset and non-overlapping (use validate_and_sort_mm_info)",
349    );
350    debug_assert!(
351        mm_runs.iter().all(|r| r.length > 0),
352        "compute_block_bytes_with_mm: mm_runs must have non-zero length",
353    );
354
355    if !block_has_mm(block_offset, tokens.len(), mm_runs) {
356        // Zero-MM-affecting-this-block: use the legacy encoding so the resulting block_hash
357        // matches what TokenBlockSequence::new would produce.
358        return cast_slice::<Token, u8>(tokens).to_vec();
359    }
360
361    const FRAME: usize = 13;
362    let mut out: Vec<u8> = Vec::with_capacity(tokens.len() * FRAME);
363    let mut run_idx = 0usize;
364    // Skip runs that ended at or before this block starts.
365    while run_idx < mm_runs.len() && mm_runs[run_idx].end() <= block_offset {
366        run_idx += 1;
367    }
368    for (s, &tok) in tokens.iter().enumerate() {
369        let g = block_offset + s;
370        // Advance past runs that end at or before g (validated non-overlapping => monotonic).
371        while run_idx < mm_runs.len() && mm_runs[run_idx].end() <= g {
372            run_idx += 1;
373        }
374        if run_idx < mm_runs.len() && mm_runs[run_idx].covers(g) {
375            let run = &mm_runs[run_idx];
376            let run_offset = (g - run.offset) as u32;
377            out.push(MM_SLOT_TAG_PLACEHOLDER);
378            out.extend_from_slice(&run_offset.to_le_bytes());
379            out.extend_from_slice(&run.mm_hash.to_le_bytes());
380        } else {
381            out.push(MM_SLOT_TAG_TOKEN);
382            out.extend_from_slice(&tok.to_le_bytes());
383            out.extend_from_slice(&0u64.to_le_bytes());
384        }
385    }
386    out
387}
388
389/// Hashes of one complete block. The tokens that produced them are not stored.
390///
391/// Built by [`hash_complete_blocks`]. The fields match the corresponding
392/// [`TokenBlock`] from [`TokenBlockSequence::split_tokens_with_mm`].
393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub struct BlockLineage {
395    /// XXH3 over this block's byte encoding, seeded by the request salt.
396    pub block_hash: BlockHash,
397    /// Parent-chained sequence hash. Equals [`Self::block_hash`] at position 0.
398    pub sequence_hash: SequenceHash,
399    /// Sequence hash of the previous complete block, if this is not position 0.
400    pub parent_sequence_hash: Option<SequenceHash>,
401    /// Packed positional lineage hash for this block.
402    pub positional_lineage_hash: PositionalLineageHash,
403}
404
405/// Hashes every complete `block_size` window of `tokens` without copying them.
406///
407/// `mm_runs` must already be validated and sorted (non-overlapping, in bounds),
408/// the same contract as [`TokenBlockSequence::split_tokens_with_mm`]. A trailing
409/// partial window is ignored.
410///
411/// A window that does not overlap a run is hashed in place with
412/// [`compute_block_hash_for_tokens`] (legacy 4-byte native-endian token ids).
413/// A window that overlaps a run allocates 13 bytes per slot (13 × `block_size`)
414/// for the tagged frame from [`compute_block_bytes_with_mm`] and hashes that buffer. The chain step uses
415/// [`compute_next_sequence_hash`] and [`PositionalLineageHash::new`], the same
416/// recurrence `TokenBlock` uses.
417///
418/// # Panics
419///
420/// Panics if `block_size` is 0.
421pub fn hash_complete_blocks(
422    tokens: &[Token],
423    mm_runs: &[TokenBlockMmInfo],
424    block_size: u32,
425    salt_hash: SaltHash,
426) -> Vec<BlockLineage> {
427    assert!(block_size > 0, "block_size must be greater than 0");
428    debug_assert!(
429        mm_runs.windows(2).all(|w| w[0].end() <= w[1].offset),
430        "hash_complete_blocks: mm_runs must be sorted by offset and non-overlapping",
431    );
432    debug_assert!(
433        mm_runs.iter().all(|r| r.length > 0),
434        "hash_complete_blocks: mm_runs must have non-zero length",
435    );
436
437    let bs = block_size as usize;
438    let n_complete = tokens.len() / bs;
439    let mut lineages = Vec::with_capacity(n_complete);
440    let mut run_cursor = 0usize;
441    let mut parent_sequence_hash: Option<SequenceHash> = None;
442
443    for position in 0..n_complete {
444        let block_offset = position * bs;
445        let block_end = block_offset + bs;
446        let block_tokens = &tokens[block_offset..block_end];
447
448        // Runs are sorted and non-overlapping, so a cursor can drop runs that
449        // ended at or before this window. The next run is the only one that can
450        // overlap it.
451        while run_cursor < mm_runs.len() && mm_runs[run_cursor].end() <= block_offset {
452            run_cursor += 1;
453        }
454        let overlaps = run_cursor < mm_runs.len() && mm_runs[run_cursor].offset < block_end;
455        let block_hash = if overlaps {
456            let block_bytes = compute_block_bytes_with_mm(block_tokens, block_offset, mm_runs);
457            compute_block_hash(&block_bytes, salt_hash)
458        } else {
459            compute_block_hash_for_tokens(block_tokens, salt_hash)
460        };
461
462        let sequence_hash = match parent_sequence_hash {
463            Some(parent) => compute_next_sequence_hash(parent, block_hash),
464            None => block_hash,
465        };
466        let positional_lineage_hash =
467            PositionalLineageHash::new(sequence_hash, parent_sequence_hash, position as u64);
468        lineages.push(BlockLineage {
469            block_hash,
470            sequence_hash,
471            parent_sequence_hash,
472            positional_lineage_hash,
473        });
474        parent_sequence_hash = Some(sequence_hash);
475    }
476
477    lineages
478}
479
480/// A 128-bit positional sequence hash combining traditional sequence hash with positional information.
481///
482/// Layout:
483/// - Lower 64 bits: Traditional SequenceHash
484/// - Upper 64 bits: 2-bit mode + position + LocalBlockHash (BlockHash)
485///
486/// Modes (automatically selected based on position):
487/// - Mode 00: 8-bit position (max 255) + 54-bit LBH
488/// - Mode 01: 16-bit position (max 65,535) + 46-bit LBH
489/// - Mode 10: 24-bit position (max 16,777,215) + 38-bit LBH
490/// - Mode 11: 31-bit position (max 2,147,483,647) + 31-bit LBH
491#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
492#[serde(transparent)]
493pub struct PositionalSequenceHash(#[serde(with = "serde_bytes_u128")] u128);
494
495impl PositionalSequenceHash {
496    /// Creates a new PositionalSequenceHash from components.
497    ///
498    /// The mode is automatically selected based on the position value to use the minimal
499    /// representation that can fit the position.
500    pub fn new(sequence_hash: SequenceHash, position: u64, local_block_hash: BlockHash) -> Self {
501        let mode = Self::select_mode(position);
502        let upper = Self::encode_upper(mode, position, local_block_hash);
503        let value = ((upper as u128) << 64) | (sequence_hash as u128);
504        PositionalSequenceHash(value)
505    }
506
507    /// Returns the sequence hash component (lower 64 bits).
508    pub fn sequence_hash(&self) -> SequenceHash {
509        (self.0 & 0xFFFF_FFFF_FFFF_FFFF) as u64
510    }
511
512    /// Returns the block position.
513    pub fn position(&self) -> u64 {
514        let (_, position, _) = self.decode_upper();
515        position
516    }
517
518    /// Returns the local block hash (BlockHash) component.
519    pub fn local_block_hash(&self) -> BlockHash {
520        let (_, _, lbh) = self.decode_upper();
521        lbh
522    }
523
524    /// Returns the mode used for encoding (0, 1, 2, or 3).
525    pub fn mode(&self) -> u8 {
526        let (mode, _, _) = self.decode_upper();
527        mode
528    }
529
530    /// Returns the inner 128-bit value.
531    #[inline(always)]
532    pub fn as_u128(&self) -> u128 {
533        self.0
534    }
535
536    /// Selects the minimal mode that can represent the given position.
537    fn select_mode(position: u64) -> u8 {
538        if position < (1u64 << 8) {
539            0 // Mode 00: 8-bit position
540        } else if position < (1u64 << 16) {
541            1 // Mode 01: 16-bit position
542        } else if position < (1u64 << 24) {
543            2 // Mode 10: 24-bit position
544        } else if position < (1u64 << 31) {
545            3 // Mode 11: 31-bit position
546        } else {
547            panic!(
548                "Position {} exceeds maximum supported value (2^31 - 1)",
549                position
550            );
551        }
552    }
553
554    /// Encodes the upper 64 bits from mode, position, and local block hash.
555    fn encode_upper(mode: u8, position: u64, local_block_hash: u64) -> u64 {
556        let (position_bits, lbh_bits) = match mode {
557            0 => (8, 54),  // 2 + 8 + 54 = 64
558            1 => (16, 46), // 2 + 16 + 46 = 64
559            2 => (24, 38), // 2 + 24 + 38 = 64
560            3 => (31, 31), // 2 + 31 + 31 = 64
561            _ => unreachable!(
562                "Invalid mode {} when encoding PositionalSequenceHash; mode must be 0, 1, 2, or 3",
563                mode
564            ),
565        };
566
567        // Create masks for extracting the relevant bits
568        let position_mask = (1u64 << position_bits) - 1;
569        let lbh_mask = (1u64 << lbh_bits) - 1;
570
571        // Extract and position components
572        let position_part = position & position_mask;
573        let lbh_part = local_block_hash & lbh_mask;
574
575        // Combine: [mode (2 bits)][position (X bits)][lbh (R bits)]
576        ((mode as u64) << 62) | (position_part << lbh_bits) | lbh_part
577    }
578
579    /// Decodes the upper 64 bits into (mode, position, local_block_hash).
580    fn decode_upper(&self) -> (u8, u64, u64) {
581        let upper = (self.0 >> 64) as u64;
582
583        // Extract mode from top 2 bits
584        let mode = (upper >> 62) as u8;
585
586        let (position_bits, lbh_bits) = match mode {
587            0 => (8, 54),
588            1 => (16, 46),
589            2 => (24, 38),
590            3 => (31, 31),
591            _ => unreachable!(
592                "Invalid mode {} in PositionalSequenceHash - value may be corrupted",
593                mode
594            ),
595        };
596
597        // Create masks
598        let lbh_mask = (1u64 << lbh_bits) - 1;
599        let position_mask = (1u64 << position_bits) - 1;
600
601        // Extract components
602        let lbh = upper & lbh_mask;
603        let position = (upper >> lbh_bits) & position_mask;
604
605        (mode, position, lbh)
606    }
607}
608
609impl std::fmt::Debug for PositionalSequenceHash {
610    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
611        f.debug_struct("PositionalSequenceHash")
612            .field("sequence_hash", &self.sequence_hash())
613            .field("local_block_hash", &self.local_block_hash())
614            .field("position", &self.position())
615            .finish()
616    }
617}
618
619/// A 128-bit positional lineage hash encoding parental lineage for tree traversal.
620///
621/// Layout (using full 128 bits):
622/// - Mode (2 bits): Determines position field size
623/// - Position (8/16/24 bits): Block position in sequence
624/// - Current Sequence Hash (64 bits): Full u64 sequence hash for this block
625/// - Parent Fragment (variable bits): Truncated lower bits of the parent's sequence hash
626///
627/// Modes (automatically selected based on position):
628/// - Mode 00: 8-bit position (max 255) + 64-bit current + 54-bit parent fragment
629/// - Mode 01: 16-bit position (max 65,535) + 64-bit current + 46-bit parent fragment
630/// - Mode 10: 24-bit position (max 16,777,215) + 64-bit current + 38-bit parent fragment
631///
632/// Carrying the full 64-bit current sequence hash inline makes PLH self-contained for
633/// chain extension: a child PLH can be derived from a parent PLH plus the child's
634/// `BlockHash` alone, with no out-of-band state. The parent fragment shrinks as
635/// position grows, but radix backward-traversal always matches on
636/// `(position, parent_fragment)`, and the probability of a shared parent at high
637/// positions decreases faster than the fragment-collision bound rises.
638#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
639#[serde(transparent)]
640pub struct PositionalLineageHash(#[serde(with = "serde_bytes_u128")] u128);
641
642impl PositionalLineageHash {
643    /// Creates a new PositionalLineageHash from components.
644    ///
645    /// The mode is automatically selected based on the position value to use the minimal
646    /// representation that can fit the position.
647    ///
648    /// # Arguments
649    ///
650    /// * `current_seq_hash` - The full u64 sequence hash of the current block
651    /// * `parent_seq_hash` - The full u64 sequence hash of the parent block (None for root).
652    ///   Will be truncated to this position's parent-fragment width.
653    /// * `position` - The block position in the sequence
654    ///
655    /// # Panics
656    ///
657    /// Panics if position >= 2^24 (16,777,216).
658    pub fn new(
659        current_seq_hash: SequenceHash,
660        parent_seq_hash: Option<SequenceHash>,
661        position: u64,
662    ) -> Self {
663        if position >= (1u64 << 24) {
664            panic!(
665                "Position {} exceeds maximum supported value (2^24 - 1 = 16,777,215)",
666                position
667            );
668        }
669
670        let mode = Self::select_mode(position);
671        let (position_bits, parent_bits) = Self::bit_layout(mode);
672
673        let position_mask = (1u128 << position_bits) - 1;
674        let parent_mask = (1u128 << parent_bits) - 1;
675
676        let position_part = (position as u128) & position_mask;
677        let current_part = current_seq_hash as u128;
678        let parent_part = (parent_seq_hash.unwrap_or(0) as u128) & parent_mask;
679
680        // Pack: [mode (2)][position (P)][current_u64 (64)][parent_fragment (R)]
681        let value = ((mode as u128) << 126)
682            | (position_part << (64 + parent_bits))
683            | (current_part << parent_bits)
684            | parent_part;
685
686        PositionalLineageHash(value)
687    }
688
689    /// Creates a root [`PositionalLineageHash`] (position 0).
690    ///
691    /// At the root, the sequence hash equals the block hash and there is no parent.
692    pub fn root(block_hash: BlockHash) -> Self {
693        Self::new(block_hash, None, 0)
694    }
695
696    /// Extends this lineage by one block, producing the child PLH.
697    ///
698    /// The chain recurrence is [`compute_next_sequence_hash`]. Salt does not seed the
699    /// per-step xxh3: `BlockHash` is already `xxh3(tokens, salt_hash)`, so salt is mixed
700    /// into `seq_hash[0]` and propagates through every parent. Re-feeding it at each step
701    /// would be redundant.
702    ///
703    /// # Panics
704    ///
705    /// Panics if `self.position() + 1 >= 2^24`.
706    pub fn extend(&self, child_block_hash: BlockHash) -> Self {
707        let parent_seq = self.current_sequence_hash();
708        let child_seq = compute_next_sequence_hash(parent_seq, child_block_hash);
709        Self::new(child_seq, Some(parent_seq), self.position() + 1)
710    }
711
712    /// Returns the block position.
713    pub fn position(&self) -> u64 {
714        let mode = self.mode();
715        let (position_bits, parent_bits) = Self::bit_layout(mode);
716        let position_mask = (1u128 << position_bits) - 1;
717        ((self.0 >> (64 + parent_bits)) & position_mask) as u64
718    }
719
720    /// Returns the full 64-bit sequence hash of the current block.
721    ///
722    /// Unlike the legacy `current_hash_fragment` (now removed), this is the complete
723    /// `SequenceHash` and is what [`extend`](Self::extend) feeds into the chain.
724    pub fn current_sequence_hash(&self) -> SequenceHash {
725        let mode = self.mode();
726        let (_, parent_bits) = Self::bit_layout(mode);
727        ((self.0 >> parent_bits) & 0xFFFF_FFFF_FFFF_FFFFu128) as u64
728    }
729
730    /// Returns the parent sequence hash fragment as stored in this PLH.
731    ///
732    /// Width depends on this PLH's mode (54/46/38 bits). Backward radix lookup must
733    /// always combine `(position, parent_fragment)` — the fragment alone is not unique.
734    pub fn parent_hash_fragment(&self) -> u64 {
735        let mode = self.mode();
736        let (_, parent_bits) = Self::bit_layout(mode);
737        let parent_mask = (1u128 << parent_bits) - 1;
738        (self.0 & parent_mask) as u64
739    }
740
741    /// Truncates this PLH's `current_sequence_hash` to the parent-fragment width that
742    /// a child at `child_position` would store.
743    ///
744    /// Useful when an external builder wants to construct a child PLH or verify a
745    /// parent/child edge: `child.parent_hash_fragment() ==
746    /// parent.parent_fragment_for_child_position(child.position())`.
747    pub fn parent_fragment_for_child_position(&self, child_position: u64) -> u64 {
748        let child_mode = Self::select_mode(child_position);
749        let (_, child_parent_bits) = Self::bit_layout(child_mode);
750        let mask = (1u64 << child_parent_bits).wrapping_sub(1);
751        self.current_sequence_hash() & mask
752    }
753
754    /// Returns the mode used for encoding (0, 1, or 2).
755    pub fn mode(&self) -> u8 {
756        (self.0 >> 126) as u8
757    }
758
759    /// Returns the inner 128-bit value.
760    #[inline(always)]
761    pub fn as_u128(&self) -> u128 {
762        self.0
763    }
764
765    /// Selects the minimal mode that can represent the given position.
766    fn select_mode(position: u64) -> u8 {
767        if position < (1u64 << 8) {
768            0 // Mode 00: 8-bit position
769        } else if position < (1u64 << 16) {
770            1 // Mode 01: 16-bit position
771        } else {
772            2 // Mode 10: 24-bit position
773        }
774    }
775
776    /// Returns the bit layout for a given mode: (position_bits, parent_fragment_bits).
777    /// Current is always 64 bits.
778    fn bit_layout(mode: u8) -> (u32, u32) {
779        match mode {
780            0 => (8, 54),  // 2 + 8 + 64 + 54 = 128
781            1 => (16, 46), // 2 + 16 + 64 + 46 = 128
782            2 => (24, 38), // 2 + 24 + 64 + 38 = 128
783            _ => unreachable!(
784                "Invalid mode {} in PositionalLineageHash; mode must be 0, 1, or 2",
785                mode
786            ),
787        }
788    }
789}
790
791impl PositionalLineageHash {
792    fn format_impl(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
793        let position = self.position();
794        let current_hash = self.current_sequence_hash();
795        let current_hash_b58 = bs58::encode(current_hash.to_be_bytes()).into_string();
796
797        if position == 0 {
798            write!(f, "{}:{}", position, current_hash_b58)
799        } else {
800            let parent_hash = self.parent_hash_fragment();
801            let parent_hash_b58 = bs58::encode(parent_hash.to_be_bytes()).into_string();
802            write!(f, "{}:{}:{}", position, current_hash_b58, parent_hash_b58)
803        }
804    }
805}
806
807impl std::fmt::Debug for PositionalLineageHash {
808    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
809        self.format_impl(f)
810    }
811}
812
813impl std::fmt::Display for PositionalLineageHash {
814    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
815        self.format_impl(f)
816    }
817}
818
819impl std::cmp::PartialOrd for PositionalLineageHash {
820    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
821        Some(self.cmp(other))
822    }
823}
824
825impl std::cmp::Ord for PositionalLineageHash {
826    /// Lexicographic order: [`Self::position`], then [`Self::current_sequence_hash`],
827    /// then the full packed [`Self::as_u128`] so the order is total and consistent with [`Eq`].
828    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
829        self.position()
830            .cmp(&other.position())
831            .then_with(|| {
832                self.current_sequence_hash()
833                    .cmp(&other.current_sequence_hash())
834            })
835            .then_with(|| self.0.cmp(&other.0))
836    }
837}
838
839/// A collection of tokens, represented as a `Vec<Token>`.
840///
841/// Provides convenience methods for conversion and manipulation.
842#[derive(Debug, Clone, Dissolve, Default, Eq)]
843pub struct Tokens(Vec<Token>);
844
845impl AsRef<[Token]> for Tokens {
846    fn as_ref(&self) -> &[Token] {
847        &self.0
848    }
849}
850
851impl std::ops::Deref for Tokens {
852    type Target = [Token];
853
854    fn deref(&self) -> &Self::Target {
855        &self.0
856    }
857}
858
859impl std::borrow::Borrow<[Token]> for Tokens {
860    fn borrow(&self) -> &[Token] {
861        &self.0
862    }
863}
864
865impl From<Vec<Token>> for Tokens {
866    fn from(tokens: Vec<Token>) -> Self {
867        Tokens(tokens)
868    }
869}
870
871impl From<&[Token]> for Tokens {
872    fn from(tokens: &[Token]) -> Self {
873        Tokens(tokens.to_vec())
874    }
875}
876
877impl From<Vec<usize>> for Tokens {
878    fn from(tokens: Vec<usize>) -> Self {
879        Tokens(
880            tokens
881                .into_iter()
882                .map(|t| t.try_into().expect("Token ID exceeds u32::MAX"))
883                .collect(),
884        )
885    }
886}
887
888impl From<Vec<i32>> for Tokens {
889    /// Converts `Vec<i32>` to `Tokens`, casting each `i32` to `u32`.
890    fn from(tokens: Vec<i32>) -> Self {
891        Tokens(tokens.into_iter().map(|t| t as u32).collect())
892    }
893}
894
895impl From<&[i32]> for Tokens {
896    /// Converts `&[i32]` to `Tokens`, casting each `i32` to `u32`.
897    fn from(tokens: &[i32]) -> Self {
898        Tokens(tokens.iter().map(|&t| t as u32).collect())
899    }
900}
901
902impl From<Tokens> for Vec<Token> {
903    fn from(tokens: Tokens) -> Self {
904        tokens.0
905    }
906}
907
908// PartialEq implementations for comparing Tokens with Vec<Token> and &[Token]
909// (Generated implementations are usually sufficient, but explicit ones can be clearer)
910impl PartialEq<Vec<Token>> for Tokens {
911    fn eq(&self, other: &Vec<Token>) -> bool {
912        self.0 == *other
913    }
914}
915
916impl PartialEq<Tokens> for Vec<Token> {
917    fn eq(&self, other: &Tokens) -> bool {
918        *self == other.0
919    }
920}
921
922impl PartialEq<[Token]> for Tokens {
923    fn eq(&self, other: &[Token]) -> bool {
924        self.0.as_slice() == other
925    }
926}
927
928impl PartialEq<Tokens> for &[Token] {
929    fn eq(&self, other: &Tokens) -> bool {
930        *self == other.0.as_slice()
931    }
932}
933
934impl PartialEq for Tokens {
935    fn eq(&self, other: &Self) -> bool {
936        self.0 == other.0
937    }
938}
939
940// Add PartialEq<&[T]> where T: Into<Token> + Copy could be more general,
941// but specifically implementing for &[Token] is sufficient for the tests.
942impl PartialEq<&[Token]> for Tokens {
943    fn eq(&self, other: &&[Token]) -> bool {
944        self.0.as_slice() == *other
945    }
946}
947
948impl Tokens {
949    fn with_capacity(capacity: usize) -> Self {
950        Tokens(Vec::with_capacity(capacity))
951    }
952
953    /// Consumes the [`Tokens`] object and creates a [`TokenBlockSequence`].
954    ///
955    /// The sequence is initialized with the provided tokens, splitting them into blocks
956    /// of the specified `block_size` using the given `salt_hash` (or 0 if `None`).
957    ///
958    /// # Arguments
959    ///
960    /// * `block_size` - The fixed size for each [`TokenBlock`].
961    /// * `salt_hash` - An optional [`SaltHash`] used as the base seed for hashing. Defaults to 0.
962    pub fn into_sequence(self, block_size: u32, salt_hash: Option<SaltHash>) -> TokenBlockSequence {
963        TokenBlockSequence::new(self, block_size, salt_hash)
964    }
965}
966
967/// Errors that can occur during [`PartialTokenBlock`] operations.
968#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
969pub enum TokenBlockError {
970    /// The operation could not be completed because the block is full.
971    #[error("TokenBlock is full")]
972    Full,
973
974    /// The operation requires a full block, but the block is incomplete.
975    #[error("TokenBlock is incomplete")]
976    Incomplete,
977
978    /// The operation could not be completed because the block is empty.
979    #[error("TokenBlock is empty")]
980    Empty,
981
982    /// The operation requires more tokens than are currently in the block.
983    #[error("TokenBlock has insufficient tokens")]
984    InsufficientTokens,
985
986    /// Multimodal info validation failed.
987    #[error(transparent)]
988    MmInfo(#[from] MmInfoError),
989
990    /// A mutating operation is not supported on a sequence with multimodal runs.
991    #[error("operation is not supported on a TokenBlockSequence with multimodal runs")]
992    MmRunsPresent,
993}
994
995/// Represents a partially filled block of tokens within a sequence.
996///
997/// This structure accumulates tokens until it reaches the specified `block_size`,
998/// at which point it can be [`commit`](PartialTokenBlock::commit)ted into a full [`TokenBlock`].
999#[derive(Debug, PartialEq)] // No Clone: intended to be unique within a sequence
1000pub struct PartialTokenBlock {
1001    tokens: Tokens,
1002    block_size: u32,
1003    salt_hash: SaltHash,
1004    parent_sequence_hash: Option<SequenceHash>,
1005    position: usize, // The position this block will have when committed
1006}
1007
1008impl PartialTokenBlock {
1009    /// Creates the first partial block (root) for a new sequence.
1010    ///
1011    /// # Arguments
1012    ///
1013    /// * `block_size` - The fixed size for blocks in this sequence.
1014    /// * `salt_hash` - The [`SaltHash`] for the sequence.
1015    pub(crate) fn create_sequence_root(block_size: u32, salt_hash: SaltHash) -> Self {
1016        Self {
1017            tokens: Tokens::with_capacity(block_size as usize),
1018            block_size,
1019            salt_hash,
1020            parent_sequence_hash: None, // Root has no parent
1021            position: 0,                // First block is at position 0
1022        }
1023    }
1024
1025    /// Attempts to push multiple tokens onto the block from a [`Tokens`] object.
1026    ///
1027    /// Tokens are added until the block is full or all input tokens are consumed.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// * `tokens` - The [`Tokens`] to push.
1032    ///
1033    /// # Returns
1034    ///
1035    /// A new [`Tokens`] object containing any tokens that did not fit,
1036    /// if all tokens were added, the returned object will be empty.
1037    pub(crate) fn push_tokens(&mut self, tokens: Tokens) -> Tokens {
1038        let remaining_space = self.remaining();
1039
1040        if remaining_space == 0 {
1041            return tokens; // Block is already full
1042        }
1043
1044        if tokens.0.len() <= remaining_space {
1045            // All tokens fit
1046            self.tokens.0.extend(tokens.0);
1047            Tokens::default() // No remaining tokens
1048        } else {
1049            // Only some tokens fit
1050            let (to_add, remaining) = tokens.0.split_at(remaining_space);
1051            self.tokens.0.extend_from_slice(to_add);
1052            Tokens(remaining.to_vec()) // Return the leftover tokens
1053        }
1054    }
1055
1056    /// Attempts to push a single token onto the block.
1057    ///
1058    /// # Returns
1059    ///
1060    /// * `Ok(())` - If the token was successfully added.
1061    /// * `Err(TokenBlockError::Full)` - If the block already contains `block_size` tokens.
1062    #[cfg(test)]
1063    pub(crate) fn push_token(&mut self, token: Token) -> Result<(), TokenBlockError> {
1064        if self.tokens.0.len() >= self.block_size as usize {
1065            return Err(TokenBlockError::Full);
1066        }
1067        self.tokens.0.push(token);
1068        Ok(())
1069    }
1070
1071    /// Attempts to remove the last `count` tokens from the block.
1072    ///
1073    /// # Arguments
1074    ///
1075    /// * `count` - The number of tokens to remove.
1076    ///
1077    /// # Returns
1078    ///
1079    /// * `Ok(())` - If the specified number of tokens were successfully removed.
1080    /// * `Err(TokenBlockError::InsufficientTokens)` - If `count` is greater than the number of tokens in the block.
1081    pub(crate) fn pop_tokens(&mut self, count: usize) -> Result<(), TokenBlockError> {
1082        if self.tokens.0.len() < count {
1083            return Err(TokenBlockError::InsufficientTokens);
1084        }
1085        self.tokens.0.truncate(self.tokens.0.len() - count);
1086        Ok(())
1087    }
1088
1089    /// Attempts to commit the current partial block into a full [`TokenBlock`].
1090    ///
1091    /// This operation consumes the tokens within the partial block.
1092    /// After a successful commit, this `PartialTokenBlock` instance is reset
1093    /// to represent the *next* partial block in the sequence, inheriting the
1094    /// sequence hash from the block just committed.
1095    ///
1096    /// # Returns
1097    ///
1098    /// * `Ok(TokenBlock)` - The newly created full [`TokenBlock`].
1099    /// * `Err(TokenBlockError::Incomplete)` - If the block does not contain exactly `block_size` tokens.
1100    pub fn commit(&mut self) -> Result<TokenBlock, TokenBlockError> {
1101        if self.tokens.0.len() != self.block_size as usize {
1102            // Check for exact size match for committing
1103            return Err(TokenBlockError::Incomplete);
1104        }
1105
1106        // Take ownership of the tokens, leaving the internal tokens empty
1107        let tokens = std::mem::replace(
1108            &mut self.tokens,
1109            Tokens::with_capacity(self.block_size as usize),
1110        );
1111
1112        let chunk = TokenBlockChunk::new(tokens, self.salt_hash);
1113        let block = TokenBlock::from_chunk(chunk, self.parent_sequence_hash, self.position);
1114
1115        // Reset self to be the next block in the sequence
1116        self.parent_sequence_hash = Some(block.sequence_hash());
1117        self.position += 1; // Increment position for the next block
1118        // self.block_size and self.salt_hash remain the same
1119
1120        Ok(block)
1121    }
1122
1123    /// Returns the number of additional tokens required to fill the block.
1124    pub fn remaining(&self) -> usize {
1125        // Use saturating_sub to prevent underflow if len somehow exceeds block_size
1126        (self.block_size as usize).saturating_sub(self.tokens.0.len())
1127    }
1128
1129    /// Returns the number of tokens currently in the block.
1130    pub fn len(&self) -> usize {
1131        self.tokens.0.len()
1132    }
1133
1134    /// Returns `true` if the block contains no tokens.
1135    pub fn is_empty(&self) -> bool {
1136        self.tokens.0.is_empty()
1137    }
1138
1139    /// Returns a reference to the tokens currently in the block.
1140    pub fn tokens(&self) -> &Tokens {
1141        &self.tokens
1142    }
1143}
1144
1145// Deref allows treating &PartialTokenBlock like &Tokens for read-only access.
1146impl std::ops::Deref for PartialTokenBlock {
1147    type Target = Tokens;
1148
1149    fn deref(&self) -> &Self::Target {
1150        &self.tokens
1151    }
1152}
1153
1154/// An intermediate structure holding a chunk of tokens destined to become a [`TokenBlock`].
1155///
1156/// This calculates the [`BlockHash`] but does not compute the final [`SequenceHash`],
1157/// allowing chunks to be processed independently (e.g., in parallel).
1158#[derive(Debug)] // No Clone: temporary intermediate value
1159struct TokenBlockChunk {
1160    tokens: Tokens,
1161    salt_hash: SaltHash,
1162    block_hash: BlockHash,
1163}
1164
1165impl TokenBlockChunk {
1166    /// Creates a new chunk from [`Tokens`], calculating the [`BlockHash`].
1167    fn new(tokens: Tokens, salt_hash: SaltHash) -> Self {
1168        let block_hash = compute_block_hash_for_tokens(&tokens, salt_hash);
1169        Self {
1170            tokens,
1171            salt_hash,
1172            block_hash,
1173        }
1174    }
1175
1176    /// Creates a new chunk from a slice of `&[Token]`, calculating the [`BlockHash`].
1177    fn from_tokens(tokens: &[Token], salt_hash: SaltHash) -> Self {
1178        let block_hash = compute_block_hash_for_tokens(tokens, salt_hash);
1179        Self {
1180            tokens: tokens.into(), // Converts slice to owned Tokens
1181            salt_hash,
1182            block_hash,
1183        }
1184    }
1185}
1186
1187/// Represents a completed, immutable block of tokens with associated hashes.
1188///
1189/// Contains exactly `block_size` tokens and includes the [`SaltHash`], [`BlockHash`],
1190/// [`SequenceHash`], [`PositionalSequenceHash`], [`PositionalLineageHash`], and optionally the parent's [`SequenceHash`].
1191#[derive(Debug, Clone, Default, PartialEq)] // Add PartialEq for tests
1192pub struct TokenBlock {
1193    tokens: Tokens,
1194    salt_hash: SaltHash,
1195    block_hash: BlockHash,
1196    sequence_hash: SequenceHash,
1197    parent_sequence_hash: Option<SequenceHash>,
1198    positional_sequence_hash: PositionalSequenceHash,
1199    positional_lineage_hash: PositionalLineageHash,
1200}
1201
1202impl TokenBlock {
1203    /// Creates a new [`PartialTokenBlock`] representing the block immediately following this one.
1204    ///
1205    /// The new partial block will have the correct `parent_sequence_hash` and `position` set.
1206    pub fn next_block(&self) -> PartialTokenBlock {
1207        PartialTokenBlock {
1208            tokens: Tokens::with_capacity(self.tokens.len()),
1209            block_size: self.tokens.len() as u32, // Should be == self.block_size
1210            salt_hash: self.salt_hash,
1211            parent_sequence_hash: Some(self.sequence_hash), // Link to this block
1212            position: self.position() as usize + 1,         // Next position
1213        }
1214    }
1215
1216    /// Finalizes a [`TokenBlock`] from a [`TokenBlockChunk`], parent's sequence hash, and position.
1217    ///
1218    /// This computes the final [`SequenceHash`], [`PositionalSequenceHash`], and [`PositionalLineageHash`] for the block.
1219    fn from_chunk(
1220        chunk: TokenBlockChunk,
1221        parent_sequence_hash: Option<SequenceHash>,
1222        position: usize,
1223    ) -> Self {
1224        let sequence_hash = match parent_sequence_hash {
1225            Some(parent) => compute_next_sequence_hash(parent, chunk.block_hash),
1226            None => {
1227                // First block: sequence hash is just the block hash
1228                chunk.block_hash
1229            }
1230        };
1231
1232        let positional_sequence_hash = PositionalSequenceHash::new(
1233            sequence_hash,
1234            position as u64,
1235            chunk.block_hash, // LocalBlockHash is the same as BlockHash
1236        );
1237
1238        let positional_lineage_hash =
1239            PositionalLineageHash::new(sequence_hash, parent_sequence_hash, position as u64);
1240
1241        Self {
1242            tokens: chunk.tokens,
1243            salt_hash: chunk.salt_hash,
1244            block_hash: chunk.block_hash,
1245            sequence_hash,
1246            parent_sequence_hash,
1247            positional_sequence_hash,
1248            positional_lineage_hash,
1249        }
1250    }
1251
1252    /// Returns a reference to the tokens in this block.
1253    pub fn tokens(&self) -> &Tokens {
1254        &self.tokens
1255    }
1256
1257    /// Returns the salt hash used for this block's hashing.
1258    pub fn salt_hash(&self) -> SaltHash {
1259        self.salt_hash
1260    }
1261
1262    /// Returns the hash of only the tokens within this block.
1263    pub fn block_hash(&self) -> BlockHash {
1264        self.block_hash
1265    }
1266
1267    /// Returns the sequence-aware hash for this block.
1268    pub fn sequence_hash(&self) -> SequenceHash {
1269        self.sequence_hash
1270    }
1271
1272    /// Returns the sequence hash of the preceding block, if any.
1273    pub fn parent_sequence_hash(&self) -> Option<SequenceHash> {
1274        self.parent_sequence_hash
1275    }
1276
1277    /// Returns the number of tokens in the block.
1278    pub fn block_size(&self) -> usize {
1279        self.tokens.0.len()
1280    }
1281
1282    /// Returns the positional sequence hash for this block.
1283    pub fn positional_sequence_hash(&self) -> PositionalSequenceHash {
1284        self.positional_sequence_hash
1285    }
1286
1287    /// Returns the positional lineage hash for this block.
1288    pub fn positional_lineage_hash(&self) -> PositionalLineageHash {
1289        self.positional_lineage_hash
1290    }
1291
1292    /// Returns the position of this block in the sequence.
1293    pub fn position(&self) -> u64 {
1294        self.positional_sequence_hash.position()
1295    }
1296}
1297
1298impl PositionalHash for PositionalSequenceHash {
1299    fn position(&self) -> u64 {
1300        self.position()
1301    }
1302}
1303
1304impl PositionalHash for PositionalLineageHash {
1305    fn position(&self) -> u64 {
1306        self.position()
1307    }
1308}
1309
1310/// Represents a sequence of tokens, segmented into fixed-size, hashed blocks.
1311///
1312/// This structure manages a series of completed [`TokenBlock`]s and one
1313/// [`PartialTokenBlock`] for accumulating incoming tokens.
1314/// It provides methods for appending tokens (`append`, `extend`), removing tokens
1315/// (`pop`, `truncate`, `unwind`), and accessing sequence information.
1316///
1317/// Hashing incorporates an initial [`SaltHash`] to ensure uniqueness across different
1318/// contexts (e.g., different models, PEFTs).
1319///
1320/// Key Hashes:
1321/// - [`BlockHash`]: Hash of tokens within a single block (seeded by [`SaltHash`]).
1322/// - [`SequenceHash`]: Hash combining the previous block's [`SequenceHash`] and the current
1323///   block's [`BlockHash`] (also seeded by [`SaltHash`]).
1324#[derive(Debug, PartialEq)]
1325pub struct TokenBlockSequence {
1326    blocks: Vec<TokenBlock>,
1327    current_block: PartialTokenBlock,
1328    salt_hash: SaltHash,
1329    block_size: usize,
1330    /// Validated, sorted multimodal runs covering committed and partial slots.
1331    /// Empty for sequences built via the zero-MM constructors; populated by
1332    /// [`TokenBlockSequence::new_with_mm`] and the streaming MM helpers.
1333    mm_runs: Vec<TokenBlockMmInfo>,
1334}
1335
1336impl TokenBlockSequence {
1337    /// Creates a new [`TokenBlockSequence`] from an initial set of tokens.
1338    ///
1339    /// The tokens are split into blocks of `block_size`. Any remaining tokens
1340    /// form the initial `current_block`.
1341    ///
1342    /// # Arguments
1343    ///
1344    /// * `tokens` - The initial [`Tokens`] for the sequence.
1345    /// * `block_size` - The fixed size for each [`TokenBlock`]. Must be greater than 0.
1346    /// * `salt_hash` - An optional [`SaltHash`]. Defaults to 0 if `None`.
1347    ///
1348    /// # Panics
1349    ///
1350    /// Panics if `block_size` is 0.
1351    pub fn new(tokens: Tokens, block_size: u32, salt_hash: Option<SaltHash>) -> Self {
1352        assert!(block_size > 0, "block_size must be greater than 0");
1353        let salt_hash = salt_hash.unwrap_or_default();
1354        let (blocks, current_block) = Self::split_tokens(&tokens, block_size, salt_hash);
1355
1356        Self {
1357            blocks,
1358            current_block,
1359            salt_hash,
1360            block_size: block_size as usize,
1361            mm_runs: Vec::new(),
1362        }
1363    }
1364
1365    /// Extends the sequence with the given tokens, potentially completing multiple blocks.
1366    ///
1367    /// This method processes all tokens from the input [`Tokens`] object.
1368    /// If adding tokens causes one or more blocks to become full, they are committed
1369    /// and added to the internal list of completed blocks.
1370    ///
1371    /// # Arguments
1372    ///
1373    /// * `tokens` - The [`Tokens`] object containing the tokens to extend the sequence with.
1374    ///
1375    /// # Returns
1376    ///
1377    /// * `Ok(Some(Range<usize>))` - The range of indices in the `blocks` vector corresponding
1378    ///   to the blocks completed during this `extend` operation.
1379    /// * `Ok(None)` - If no blocks were completed.
1380    /// * `Err(TokenBlockError)` - If an internal error occurs during commit.
1381    pub fn extend(&mut self, tokens: Tokens) -> Result<Option<Range<usize>>, TokenBlockError> {
1382        let start_block_index = self.blocks.len();
1383        let mut tokens_to_append = tokens;
1384
1385        while !tokens_to_append.is_empty() {
1386            let remaining_in_current = self.current_block.remaining();
1387
1388            if remaining_in_current == 0 {
1389                // Current block is full, commit it first.
1390                let new_block = self.commit_current()?;
1391                self.blocks.push(new_block);
1392                // Continue loop to add tokens to the *new* current_block.
1393            }
1394
1395            // Push as many tokens as possible into the current (potentially new) block.
1396            let available_tokens = tokens_to_append;
1397            tokens_to_append = self.current_block.push_tokens(available_tokens);
1398
1399            // Check if the current block *became* full after pushing tokens.
1400            if self.current_block.remaining() == 0 {
1401                // If it became full AND there are still more tokens to append,
1402                // commit it now so the next loop iteration starts with a fresh block.
1403                let new_block = self.commit_current()?;
1404                self.blocks.push(new_block);
1405            }
1406        }
1407
1408        let end_block_index = self.blocks.len();
1409        if start_block_index == end_block_index {
1410            Ok(None) // No blocks were completed.
1411        } else {
1412            Ok(Some(start_block_index..end_block_index))
1413        }
1414    }
1415
1416    /// Commits the current partial block.
1417    ///
1418    /// Routes through the MM-aware byte encoding when [`Self::mm_runs`] is non-empty;
1419    /// otherwise behaves identically to [`PartialTokenBlock::commit`].
1420    fn commit_current(&mut self) -> Result<TokenBlock, TokenBlockError> {
1421        if self.mm_runs.is_empty() {
1422            return self.current_block.commit();
1423        }
1424        // MM-aware path: compute block_hash from the substituted byte buffer.
1425        if self.current_block.tokens.0.len() != self.current_block.block_size as usize {
1426            return Err(TokenBlockError::Incomplete);
1427        }
1428        let block_offset = self.blocks.len() * (self.current_block.block_size as usize);
1429        let tokens = std::mem::take(&mut self.current_block.tokens);
1430        // Text windows keep the legacy in-place hash. Only a window that overlaps
1431        // a run pays for 13 bytes per slot (13 × block_size) for the tagged frame.
1432        let block_hash = if block_has_mm(block_offset, tokens.len(), &self.mm_runs) {
1433            let block_bytes = compute_block_bytes_with_mm(&tokens, block_offset, &self.mm_runs);
1434            compute_block_hash(&block_bytes, self.current_block.salt_hash)
1435        } else {
1436            compute_block_hash_for_tokens(&tokens, self.current_block.salt_hash)
1437        };
1438        let chunk = TokenBlockChunk {
1439            tokens,
1440            salt_hash: self.current_block.salt_hash,
1441            block_hash,
1442        };
1443        let block = TokenBlock::from_chunk(
1444            chunk,
1445            self.current_block.parent_sequence_hash,
1446            self.current_block.position,
1447        );
1448        self.current_block.parent_sequence_hash = Some(block.sequence_hash());
1449        self.current_block.position += 1;
1450        Ok(block)
1451    }
1452
1453    /// Appends a single token to the sequence.
1454    ///
1455    /// If adding this token completes the current partial block, the block is committed,
1456    /// and the index of the newly completed block is returned.
1457    ///
1458    /// This method is equivalent to calling `extend` with a single-token [`Tokens`] object.
1459    ///
1460    /// # Arguments
1461    ///
1462    /// * `token` - The [`Token`] to append.
1463    ///
1464    /// # Returns
1465    ///
1466    /// * `Ok(Some(usize))` - The index of the block that was just completed.
1467    /// * `Ok(None)` - No block was completed by adding this token.
1468    /// * `Err(TokenBlockError)` - If an internal error occurs during processing.
1469    pub fn append(&mut self, token: Token) -> Result<Option<usize>, TokenBlockError> {
1470        let before = self.blocks.len();
1471        self.extend(Tokens::from(vec![token]))?;
1472        Ok(if self.blocks.len() > before {
1473            Some(before)
1474        } else {
1475            None
1476        })
1477    }
1478
1479    /// Shortens the sequence, keeping the first `len` tokens and removing the rest.
1480    ///
1481    /// If `len` is greater than the sequence's current length, this has no effect.
1482    ///
1483    /// This operation is analogous to `Vec::truncate`.
1484    /// It may involve removing tokens from the current partial block, removing entire
1485    /// completed blocks, and adjusting the current partial block
1486    /// to reflect the new end of the sequence.
1487    ///
1488    /// # Arguments
1489    ///
1490    /// * `len` - The number of tokens to keep.
1491    ///
1492    /// # Returns
1493    ///
1494    /// * `Ok(())` - If the sequence was successfully truncated.
1495    /// * `Err(TokenBlockError::InsufficientTokens)` - This error should ideally not occur if `len`
1496    ///   is correctly checked against `total_tokens`, but the underlying `pop_tokens` might return it.
1497    pub fn truncate(&mut self, len: usize) -> Result<(), TokenBlockError> {
1498        if !self.mm_runs.is_empty() {
1499            return Err(TokenBlockError::MmRunsPresent);
1500        }
1501        let current_total_len = self.total_tokens();
1502        if len >= current_total_len {
1503            return Ok(()); // Nothing to truncate
1504        }
1505
1506        let n = current_total_len - len; // Number of tokens to remove
1507
1508        // This inner block handles the actual removal logic based on `n` tokens to remove.
1509        {
1510            let current_len = self.current_block.len();
1511            // Avoid division by zero if block_size is somehow 0 (though asserted in new)
1512            let block_size = self.current_block.block_size.max(1);
1513
1514            if n <= current_len {
1515                // Only need to pop from the current partial block
1516                self.current_block.pop_tokens(n)?;
1517            } else {
1518                // Need to pop from full blocks as well
1519                let tokens_to_pop_from_blocks = n - current_len;
1520
1521                // Calculate how many blocks are affected (including the one partially popped)
1522                let num_blocks_to_affect = tokens_to_pop_from_blocks.div_ceil(block_size as usize);
1523
1524                // Check if we need to pop more blocks than available (should be prevented by initial len check)
1525                if num_blocks_to_affect > self.blocks.len() {
1526                    // This indicates an inconsistency between total_tokens() and internal state.
1527                    debug_assert!(
1528                        false,
1529                        "Truncate calculation error: trying to pop too many blocks."
1530                    );
1531                    return Err(TokenBlockError::InsufficientTokens);
1532                }
1533
1534                // Determine the index of the block that will be the source for the new partial block
1535                let source_block_index = self.blocks.len() - num_blocks_to_affect;
1536
1537                // Calculate how many tokens to keep from that source block
1538                let num_full_blocks_completely_popped = num_blocks_to_affect - 1;
1539                let num_tokens_to_pop_from_source_block = tokens_to_pop_from_blocks
1540                    - num_full_blocks_completely_popped * block_size as usize;
1541                let num_tokens_to_keep_in_new_partial =
1542                    (block_size as usize).saturating_sub(num_tokens_to_pop_from_source_block);
1543
1544                // Get the tokens for the new partial block
1545                let new_partial_tokens = if num_tokens_to_keep_in_new_partial > 0 {
1546                    self.blocks[source_block_index].tokens().as_ref()
1547                        [..num_tokens_to_keep_in_new_partial]
1548                        .to_vec()
1549                } else {
1550                    Vec::new()
1551                };
1552
1553                // Truncate the blocks vector to remove popped blocks
1554                self.blocks.truncate(source_block_index);
1555
1556                // Update the current_block state
1557                self.current_block.tokens = Tokens(new_partial_tokens);
1558                // Correctly set the parent hash based on the *new* last block
1559                self.current_block.parent_sequence_hash =
1560                    self.blocks.last().map(|b| b.sequence_hash());
1561                // Update position to match the number of complete blocks
1562                self.current_block.position = self.blocks.len();
1563                // salt_hash and block_size remain the same for current_block
1564            }
1565        }
1566        Ok(())
1567    }
1568
1569    /// Removes the last `count` tokens from the sequence.
1570    ///
1571    /// This is a convenience method that calculates the required length and calls `truncate`.
1572    ///
1573    /// # Arguments
1574    ///
1575    /// * `count` - The number of tokens to remove from the end.
1576    ///
1577    /// # Returns
1578    ///
1579    /// * `Ok(())` - If the tokens were successfully removed.
1580    /// * `Err(TokenBlockError::InsufficientTokens)` - If `count` is greater than or equal to
1581    ///   the total number of tokens in the sequence.
1582    pub fn unwind(&mut self, count: usize) -> Result<(), TokenBlockError> {
1583        let current_total_len = self.total_tokens();
1584        if count > current_total_len {
1585            // Allow count == current_total_len, which truncates to 0.
1586            return Err(TokenBlockError::InsufficientTokens);
1587        }
1588
1589        // number of tokens remaining in the sequence after undoing the given count
1590        let len = current_total_len - count;
1591        self.truncate(len)
1592    }
1593
1594    /// Resets the sequence to the initial state.
1595    ///
1596    /// Clears any accumulated multimodal runs; after `reset` the sequence behaves
1597    /// identically to a freshly-constructed zero-MM sequence with the same `salt_hash`
1598    /// and `block_size`.
1599    pub fn reset(&mut self) {
1600        self.blocks.clear();
1601        self.current_block =
1602            PartialTokenBlock::create_sequence_root(self.block_size as u32, self.salt_hash);
1603        self.mm_runs.clear();
1604    }
1605
1606    /// Removes the last token from the sequence and returns it, or [`None`] if it is empty.
1607    ///
1608    /// This operation is analogous to `Vec::pop`.
1609    ///
1610    /// # Returns
1611    ///
1612    /// * `Some(Token)` - The last token, if the sequence was not empty.
1613    /// * `None` - If the sequence was empty.
1614    ///
1615    /// # Panics
1616    ///
1617    /// Panics if the sequence has accumulated multimodal runs (see [`Self::try_pop`] for a
1618    /// non-panicking variant). `pop` returns `Option<Token>` and cannot signal
1619    /// "operation unsupported on MM sequence" through its return type without breaking the
1620    /// `Vec::pop` analogy and silently lying to callers.
1621    pub fn pop(&mut self) -> Option<Token> {
1622        if !self.mm_runs.is_empty() {
1623            panic!(
1624                "TokenBlockSequence::pop is not supported on a sequence with multimodal runs; \
1625                 use try_pop or reset before pop"
1626            );
1627        }
1628        let current_total_len = self.total_tokens();
1629        if current_total_len == 0 {
1630            return None;
1631        }
1632
1633        // Determine the last token. It must be in the current_block if current_block is not empty.
1634        // If current_block is empty, it must be the last token of the last full block.
1635        let last_token = if !self.current_block.tokens.is_empty() {
1636            // Last token is in the partial block
1637            *self
1638                .current_block
1639                .tokens
1640                .last()
1641                .expect("Current block checked for non-empty")
1642        } else {
1643            // Current block is empty, sequence is not. Must be in the last full block.
1644            let last_block = self
1645                .blocks
1646                .last()
1647                .expect("Sequence is not empty but has no blocks and empty current block?");
1648            *last_block
1649                .tokens()
1650                .last()
1651                .expect("Last block cannot be empty")
1652        };
1653
1654        // Truncate the sequence by one element.
1655        // We expect this to succeed since we know the length > 0.
1656        match self.truncate(current_total_len - 1) {
1657            Ok(_) => Some(last_token),
1658            Err(_) => {
1659                // This should be logically impossible if total_tokens() and truncate() are correct.
1660                // Panic in debug, return None in release as a fallback, though it indicates a bug.
1661                debug_assert!(
1662                    false,
1663                    "truncate failed unexpectedly after checking length in pop"
1664                );
1665                None
1666            }
1667        }
1668    }
1669
1670    /// Non-panicking variant of [`Self::pop`].
1671    ///
1672    /// Returns:
1673    /// - `Ok(Some(token))` when the sequence had at least one token and pop succeeded.
1674    /// - `Ok(None)` when the sequence was empty.
1675    /// - `Err(TokenBlockError::MmRunsPresent)` when the sequence has multimodal runs.
1676    pub fn try_pop(&mut self) -> Result<Option<Token>, TokenBlockError> {
1677        if !self.mm_runs.is_empty() {
1678            return Err(TokenBlockError::MmRunsPresent);
1679        }
1680        Ok(self.pop())
1681    }
1682
1683    /// Returns a slice containing all the completed [`TokenBlock`]s in the sequence.
1684    pub fn blocks(&self) -> &[TokenBlock] {
1685        &self.blocks
1686    }
1687
1688    /// Returns a reference to the last completed [`TokenBlock`] in the sequence, if any.
1689    pub fn last_complete_block(&self) -> Option<&TokenBlock> {
1690        self.blocks.last()
1691    }
1692
1693    /// Returns a reference to the current [`PartialTokenBlock`] where new tokens are added.
1694    pub fn current_block(&self) -> &PartialTokenBlock {
1695        &self.current_block
1696    }
1697
1698    /// Consumes the sequence and returns its parts: a `Vec` of completed blocks and the final partial block.
1699    pub fn into_parts(self) -> (Vec<TokenBlock>, PartialTokenBlock) {
1700        (self.blocks, self.current_block)
1701    }
1702
1703    /// Returns the block size used for this sequence.
1704    pub fn block_size(&self) -> usize {
1705        self.block_size
1706    }
1707
1708    /// Returns the [`SaltHash`] used for this sequence.
1709    pub fn salt_hash(&self) -> SaltHash {
1710        self.salt_hash
1711    }
1712
1713    /// Returns the total number of tokens in the sequence (sum of tokens in all completed blocks
1714    /// plus tokens in the current partial block).
1715    pub fn total_tokens(&self) -> usize {
1716        let block_size = self.current_block.block_size as usize;
1717        (self.blocks.len() * block_size) + self.current_block.len()
1718    }
1719
1720    /// Extract the token with the range
1721    pub fn tokens_at(&self, range: Range<usize>) -> Tokens {
1722        let total = self.total_tokens();
1723
1724        // Validate range - return empty tokens for invalid ranges
1725        if range.start > range.end || range.end > total {
1726            return Tokens::default();
1727        }
1728
1729        // Handle empty range
1730        if range.is_empty() {
1731            return Tokens::default();
1732        }
1733
1734        let mut result = Vec::with_capacity(range.len());
1735
1736        for i in range {
1737            if i < self.blocks.len() * self.block_size {
1738                // Token is in a completed block
1739                let block_index = i / self.block_size;
1740                let token_index = i % self.block_size;
1741                result.push(self.blocks[block_index].tokens()[token_index]);
1742            } else {
1743                // Token is in the current partial block
1744                let current_block_index = i - (self.blocks.len() * self.block_size);
1745                result.push(self.current_block.tokens()[current_block_index]);
1746            }
1747        }
1748
1749        Tokens::from(result)
1750    }
1751
1752    /// Splits a [`Tokens`] object into a vector of completed blocks and a final partial block.
1753    ///
1754    /// This is primarily used internally by [`TokenBlockSequence::new`] but can be used externally.
1755    ///
1756    /// # Arguments
1757    ///
1758    /// * `tokens` - The [`Tokens`] to split.
1759    /// * `block_size` - The size of each block.
1760    /// * `salt_hash` - The [`SaltHash`] to use for hashing.
1761    ///
1762    /// # Returns
1763    ///
1764    /// A tuple containing `(Vec<TokenBlock>, PartialTokenBlock)`.
1765    ///
1766    /// # Panics
1767    ///
1768    /// Panics if `block_size` is 0.
1769    pub fn split_tokens(
1770        tokens: &[Token],
1771        block_size: u32,
1772        salt_hash: SaltHash,
1773    ) -> (Vec<TokenBlock>, PartialTokenBlock) {
1774        assert!(block_size > 0, "block_size must be greater than 0");
1775        let chunks: Vec<TokenBlockChunk> = tokens
1776            .as_ref()
1777            .chunks_exact(block_size as usize)
1778            .map(|chunk| TokenBlockChunk::from_tokens(chunk, salt_hash))
1779            .collect();
1780
1781        let mut result_blocks = Vec::with_capacity(chunks.len());
1782        let mut last_sequence_hash: Option<SequenceHash> = None;
1783
1784        // Sequentially combine chunks to compute sequence hashes
1785        for (position, chunk) in chunks.into_iter().enumerate() {
1786            let new_block = TokenBlock::from_chunk(chunk, last_sequence_hash, position);
1787            last_sequence_hash = Some(new_block.sequence_hash());
1788            result_blocks.push(new_block);
1789        }
1790
1791        // Handle any remaining tokens
1792        let remainder = tokens
1793            .as_ref()
1794            .chunks_exact(block_size as usize)
1795            .remainder();
1796
1797        let next_position = result_blocks.len(); // Position for the next block to be committed
1798
1799        let mut partial_tokens = Tokens::with_capacity(block_size as usize);
1800        partial_tokens.0.extend_from_slice(remainder);
1801
1802        let current_block = PartialTokenBlock {
1803            tokens: partial_tokens,
1804            block_size,
1805            salt_hash,
1806            // Parent hash is the sequence hash of the last *full* block computed
1807            parent_sequence_hash: last_sequence_hash,
1808            position: next_position,
1809        };
1810
1811        (result_blocks, current_block)
1812    }
1813
1814    /// Creates a new [`TokenBlockSequence`] from a slice of tokens.
1815    ///
1816    /// The tokens are split into blocks of `block_size`. Any remaining tokens
1817    /// form the initial `current_block`.
1818    ///
1819    /// # Arguments
1820    ///
1821    /// * `tokens` - The slice of tokens to create the sequence from.
1822    /// * `block_size` - The size of each block.
1823    /// * `salt_hash` - The [`SaltHash`] to use for hashing.
1824    pub fn from_slice(tokens: &[Token], block_size: u32, salt_hash: Option<SaltHash>) -> Self {
1825        assert!(block_size > 0, "block_size must be greater than 0");
1826        let salt_hash = salt_hash.unwrap_or_default();
1827        let (blocks, current_block) = Self::split_tokens(tokens, block_size, salt_hash);
1828
1829        Self {
1830            blocks,
1831            current_block,
1832            salt_hash,
1833            block_size: block_size as usize,
1834            mm_runs: Vec::new(),
1835        }
1836    }
1837
1838    /// Creates a [`TokenBlockSequence`] with multimodal placeholder runs.
1839    ///
1840    /// `mm_info` is validated and sorted via [`validate_and_sort_mm_info`]. Each block's
1841    /// [`BlockHash`] is computed using the per-block byte encoding documented on
1842    /// [`compute_block_bytes_with_mm`], which selects one of two encodings:
1843    ///
1844    /// - **MM-affected block** (at least one run overlaps the block): every slot emits
1845    ///   13 bytes — a 1-byte tag ([`MM_SLOT_TAG_TOKEN`] or [`MM_SLOT_TAG_PLACEHOLDER`])
1846    ///   followed by a 12-byte payload. Real-token slots carry `token_id u32 LE` plus
1847    ///   8 bytes of padding; placeholder slots carry `run_offset u32 LE | mm_hash u64 LE`.
1848    /// - **Non-MM block** (no run overlaps): the legacy `bytemuck::cast_slice(tokens)`
1849    ///   form is used (4 bytes per slot, LE u32), preserving cache identity with blocks
1850    ///   produced by [`Self::from_slice`].
1851    ///
1852    /// Returns an error if `mm_info` is invalid (overlap, out of bounds, zero-length run).
1853    pub fn new_with_mm(
1854        tokens: Tokens,
1855        mm_info: &[TokenBlockMmInfo],
1856        block_size: u32,
1857        salt_hash: Option<SaltHash>,
1858    ) -> Result<Self, TokenBlockError> {
1859        assert!(block_size > 0, "block_size must be greater than 0");
1860        let salt_hash = salt_hash.unwrap_or_default();
1861        let validated =
1862            validate_and_sort_mm_info(mm_info, tokens.len()).map_err(TokenBlockError::MmInfo)?;
1863        let (blocks, current_block) =
1864            Self::split_tokens_with_mm(&tokens, &validated, block_size, salt_hash);
1865        Ok(Self {
1866            blocks,
1867            current_block,
1868            salt_hash,
1869            block_size: block_size as usize,
1870            mm_runs: validated,
1871        })
1872    }
1873
1874    /// MM-aware variant of [`Self::split_tokens`].
1875    ///
1876    /// `mm_runs` must be pre-validated and sorted (e.g., via [`validate_and_sort_mm_info`]).
1877    pub fn split_tokens_with_mm(
1878        tokens: &[Token],
1879        mm_runs: &[TokenBlockMmInfo],
1880        block_size: u32,
1881        salt_hash: SaltHash,
1882    ) -> (Vec<TokenBlock>, PartialTokenBlock) {
1883        assert!(block_size > 0, "block_size must be greater than 0");
1884        let bs = block_size as usize;
1885        let lineages = hash_complete_blocks(tokens, mm_runs, block_size, salt_hash);
1886        let mut result_blocks = Vec::with_capacity(lineages.len());
1887        for (position, lineage) in lineages.into_iter().enumerate() {
1888            let block_offset = position * bs;
1889            let chunk = TokenBlockChunk {
1890                tokens: tokens[block_offset..block_offset + bs].into(),
1891                salt_hash,
1892                block_hash: lineage.block_hash,
1893            };
1894            let new_block = TokenBlock::from_chunk(chunk, lineage.parent_sequence_hash, position);
1895            debug_assert_eq!(new_block.sequence_hash(), lineage.sequence_hash);
1896            debug_assert_eq!(
1897                new_block.positional_lineage_hash(),
1898                lineage.positional_lineage_hash
1899            );
1900            result_blocks.push(new_block);
1901        }
1902        let n_complete = result_blocks.len();
1903        let remainder = &tokens[n_complete * bs..];
1904        let current_block = PartialTokenBlock {
1905            tokens: remainder.into(),
1906            block_size,
1907            salt_hash,
1908            parent_sequence_hash: result_blocks.last().map(|block| block.sequence_hash()),
1909            position: n_complete,
1910        };
1911        (result_blocks, current_block)
1912    }
1913
1914    /// Returns the validated, sorted multimodal runs accumulated by this sequence.
1915    pub fn mm_runs(&self) -> &[TokenBlockMmInfo] {
1916        &self.mm_runs
1917    }
1918
1919    /// Appends a single real token to the sequence.
1920    ///
1921    /// Equivalent to [`Self::append`] but named for symmetry with [`Self::push_mm_run`].
1922    pub fn push_token(&mut self, token: Token) -> Result<Option<usize>, TokenBlockError> {
1923        self.append(token)
1924    }
1925
1926    /// Appends a multimodal placeholder run of `length` slots all tagged with `mm_hash`.
1927    ///
1928    /// The placeholder run starts at the current end of the sequence (`total_tokens()` before
1929    /// the call). The token IDs at placeholder slot positions are filled with zero sentinels;
1930    /// hashing uses the `(mm_hash, run_offset)` pair instead of those token bytes.
1931    ///
1932    /// Returns the range of fully-committed block indices completed during the call (if any).
1933    pub fn push_mm_run(
1934        &mut self,
1935        mm_hash: u64,
1936        length: usize,
1937    ) -> Result<Option<Range<usize>>, TokenBlockError> {
1938        if length == 0 {
1939            return Err(TokenBlockError::MmInfo(MmInfoError::EmptyRun));
1940        }
1941        let offset = self.total_tokens();
1942        self.mm_runs.push(TokenBlockMmInfo {
1943            mm_hash,
1944            offset,
1945            length,
1946        });
1947        // The token values at placeholder slots are opaque for hashing; use 0 sentinels.
1948        let placeholders = Tokens::from(vec![0u32; length]);
1949        self.extend(placeholders)
1950    }
1951
1952    /// Batch-validated extension: appends `tokens` (with embedded multimodal runs in `mm_info`)
1953    /// to the sequence in a single validated step.
1954    ///
1955    /// `mm_info` offsets are **relative to the start of `tokens`** (not the existing sequence).
1956    /// The function validates the chunk, then translates to absolute offsets and applies the
1957    /// updates atomically: it errors before mutating any state if `mm_info` is invalid.
1958    ///
1959    /// Real-token regions and placeholder runs are interleaved per the chunk's layout.
1960    pub fn extend_with_mm(
1961        &mut self,
1962        tokens: &[Token],
1963        mm_info: &[TokenBlockMmInfo],
1964    ) -> Result<Option<Range<usize>>, TokenBlockError> {
1965        let validated =
1966            validate_and_sort_mm_info(mm_info, tokens.len()).map_err(TokenBlockError::MmInfo)?;
1967        let start_block = self.blocks.len();
1968        let mut cursor = 0usize;
1969        for run in &validated {
1970            if run.offset > cursor {
1971                let real = Tokens::from(tokens[cursor..run.offset].to_vec());
1972                self.extend(real)?;
1973            }
1974            self.push_mm_run(run.mm_hash, run.length)?;
1975            cursor = run.offset + run.length;
1976        }
1977        if cursor < tokens.len() {
1978            let real = Tokens::from(tokens[cursor..].to_vec());
1979            self.extend(real)?;
1980        }
1981        let end_block = self.blocks.len();
1982        if start_block == end_block {
1983            Ok(None)
1984        } else {
1985            Ok(Some(start_block..end_block))
1986        }
1987    }
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992    use super::*;
1993    use bytemuck::cast_slice;
1994
1995    // Helper to create a sequence for testing
1996    fn create_test_sequence(
1997        initial_tokens: &[Token],
1998        block_size: u32,
1999        salt_hash: Option<SaltHash>,
2000    ) -> TokenBlockSequence {
2001        TokenBlockSequence::new(Tokens::from(initial_tokens), block_size, salt_hash)
2002    }
2003
2004    // Helper to get expected hashes (replace with actual calculated values if needed)
2005    const TEST_SALT_HASH: SaltHash = 1337;
2006    const HASH_1_4: BlockHash = 14643705804678351452; // hash([1,2,3,4], 1337)
2007    const SEQ_HASH_1_4: SequenceHash = HASH_1_4;
2008    const HASH_5_8: BlockHash = 16777012769546811212; // hash([5,6,7,8], 1337)
2009    const SEQ_HASH_5_8: SequenceHash = 4945711292740353085; // hash([SEQ_HASH_1_4, HASH_5_8], CHAIN_XXH3_SEED)
2010    const HASH_9_12: BlockHash = 483935686894639516; // hash([9,10,11,12], 1337)
2011    const SEQ_HASH_9_12: SequenceHash = 12583592247330656132; // hash([SEQ_HASH_5_8, HASH_9_12], CHAIN_XXH3_SEED)
2012
2013    #[test]
2014    fn token_hash_helper_matches_canonical_byte_encoding() {
2015        let tokens = [1u32, 2, 3, 4];
2016        assert_eq!(
2017            compute_block_hash_for_tokens(&tokens, TEST_SALT_HASH),
2018            compute_block_hash(cast_slice(&tokens), TEST_SALT_HASH)
2019        );
2020        assert_eq!(
2021            compute_block_hash_for_tokens(&tokens, TEST_SALT_HASH),
2022            HASH_1_4
2023        );
2024    }
2025
2026    impl PartialTokenBlock {
2027        /// Attempts to remove the last token from the block.
2028        ///
2029        /// # Returns
2030        ///
2031        /// * `Ok(())` - If a token was successfully removed.
2032        /// * `Err(TokenBlockError::Empty)` - If the block was already empty.
2033        pub fn pop_token(&mut self) -> Result<(), TokenBlockError> {
2034            if self.tokens.0.is_empty() {
2035                return Err(TokenBlockError::Empty);
2036            }
2037            self.tokens.0.pop();
2038            Ok(())
2039        }
2040    }
2041
2042    #[test]
2043    fn test_validate_hash_constants() {
2044        let salt = TEST_SALT_HASH;
2045
2046        // Block 1: [1, 2, 3, 4]
2047        let tokens_1_4 = &[1u32, 2, 3, 4];
2048        let computed_hash_1_4 = compute_block_hash(cast_slice(tokens_1_4), salt);
2049        assert_eq!(computed_hash_1_4, HASH_1_4, "Mismatch for HASH_1_4");
2050        // First block's sequence hash is its block hash
2051        assert_eq!(computed_hash_1_4, SEQ_HASH_1_4, "Mismatch for SEQ_HASH_1_4");
2052
2053        // Block 2: [5, 6, 7, 8]
2054        let tokens_5_8 = &[5u32, 6, 7, 8];
2055        let computed_hash_5_8 = compute_block_hash(cast_slice(tokens_5_8), salt);
2056        assert_eq!(computed_hash_5_8, HASH_5_8, "Mismatch for HASH_5_8");
2057        // Chain step uses the shared CHAIN_XXH3_SEED; salt is already mixed into block_hash.
2058        let computed_seq_hash_5_8 = compute_next_sequence_hash(SEQ_HASH_1_4, HASH_5_8);
2059        assert_eq!(
2060            computed_seq_hash_5_8, SEQ_HASH_5_8,
2061            "Mismatch for SEQ_HASH_5_8"
2062        );
2063
2064        // Block 3: [9, 10, 11, 12]
2065        let tokens_9_12 = &[9u32, 10, 11, 12];
2066        let computed_hash_9_12 = compute_block_hash(cast_slice(tokens_9_12), salt);
2067        assert_eq!(computed_hash_9_12, HASH_9_12, "Mismatch for HASH_9_12");
2068        let computed_seq_hash_9_12 = compute_next_sequence_hash(SEQ_HASH_5_8, HASH_9_12);
2069        assert_eq!(
2070            computed_seq_hash_9_12, SEQ_HASH_9_12,
2071            "Mismatch for SEQ_HASH_9_12"
2072        );
2073    }
2074
2075    #[test]
2076    fn test_positional_sequence_hash_encoding_decoding() {
2077        // Test Mode 0: position fits in 8 bits (< 256)
2078        let seq_hash_0 = 0x1234567890ABCDEF;
2079        let position_0 = 100;
2080        let lbh_0 = 0xFEDCBA9876543210;
2081        let psh_0 = PositionalSequenceHash::new(seq_hash_0, position_0, lbh_0);
2082
2083        assert_eq!(psh_0.mode(), 0, "Position 100 should use mode 0");
2084        assert_eq!(psh_0.sequence_hash(), seq_hash_0);
2085        assert_eq!(psh_0.position(), position_0);
2086        // LBH is truncated to 54 bits in mode 0
2087        assert_eq!(
2088            psh_0.local_block_hash(),
2089            lbh_0 & ((1u64 << 54) - 1),
2090            "LBH should be truncated to 54 bits"
2091        );
2092
2093        // Test Mode 1: position fits in 16 bits (256 <= pos < 65536)
2094        let position_1 = 1000;
2095        let psh_1 = PositionalSequenceHash::new(seq_hash_0, position_1, lbh_0);
2096
2097        assert_eq!(psh_1.mode(), 1, "Position 1000 should use mode 1");
2098        assert_eq!(psh_1.sequence_hash(), seq_hash_0);
2099        assert_eq!(psh_1.position(), position_1);
2100        // LBH is truncated to 46 bits in mode 1
2101        assert_eq!(
2102            psh_1.local_block_hash(),
2103            lbh_0 & ((1u64 << 46) - 1),
2104            "LBH should be truncated to 46 bits"
2105        );
2106
2107        // Test Mode 2: position fits in 24 bits (65536 <= pos < 16777216)
2108        let position_2 = 100_000;
2109        let psh_2 = PositionalSequenceHash::new(seq_hash_0, position_2, lbh_0);
2110
2111        assert_eq!(psh_2.mode(), 2, "Position 100,000 should use mode 2");
2112        assert_eq!(psh_2.sequence_hash(), seq_hash_0);
2113        assert_eq!(psh_2.position(), position_2);
2114        // LBH is truncated to 38 bits in mode 2
2115        assert_eq!(
2116            psh_2.local_block_hash(),
2117            lbh_0 & ((1u64 << 38) - 1),
2118            "LBH should be truncated to 38 bits"
2119        );
2120
2121        // Test Mode 3: position fits in 31 bits (16777216 <= pos < 2^31)
2122        let position_3 = 20_000_000;
2123        let psh_3 = PositionalSequenceHash::new(seq_hash_0, position_3, lbh_0);
2124
2125        assert_eq!(psh_3.mode(), 3, "Position 20,000,000 should use mode 3");
2126        assert_eq!(psh_3.sequence_hash(), seq_hash_0);
2127        assert_eq!(psh_3.position(), position_3);
2128        // LBH is truncated to 31 bits in mode 3
2129        assert_eq!(
2130            psh_3.local_block_hash(),
2131            lbh_0 & ((1u64 << 31) - 1),
2132            "LBH should be truncated to 31 bits"
2133        );
2134
2135        // Test edge case: position at boundary
2136        let position_255 = 255;
2137        let psh_255 = PositionalSequenceHash::new(seq_hash_0, position_255, lbh_0);
2138        assert_eq!(psh_255.mode(), 0, "Position 255 should use mode 0");
2139        assert_eq!(psh_255.position(), position_255);
2140
2141        let position_256 = 256;
2142        let psh_256 = PositionalSequenceHash::new(seq_hash_0, position_256, lbh_0);
2143        assert_eq!(psh_256.mode(), 1, "Position 256 should use mode 1");
2144        assert_eq!(psh_256.position(), position_256);
2145    }
2146
2147    #[test]
2148    fn test_positional_lineage_hash() {
2149        // Test Mode 0: position fits in 8 bits (< 256)
2150        let current_hash_0 = 0x1234567890ABCDEF;
2151        let parent_hash_0 = 0xFEDCBA9876543210;
2152        let position_0 = 100;
2153        let plh_0 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_0);
2154
2155        assert_eq!(plh_0.mode(), 0, "Position 100 should use mode 0");
2156        assert_eq!(plh_0.position(), position_0);
2157        // Current carries the full u64; parent fragment is 54 bits in mode 0
2158        assert_eq!(
2159            plh_0.current_sequence_hash(),
2160            current_hash_0,
2161            "Current sequence hash should be stored in full"
2162        );
2163        assert_eq!(
2164            plh_0.parent_hash_fragment(),
2165            parent_hash_0 & ((1u64 << 54) - 1),
2166            "Parent fragment should be truncated to 54 bits in mode 0"
2167        );
2168
2169        // Test Mode 1: position fits in 16 bits (256 <= pos < 65536)
2170        let position_1 = 1000;
2171        let plh_1 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_1);
2172
2173        assert_eq!(plh_1.mode(), 1, "Position 1000 should use mode 1");
2174        assert_eq!(plh_1.position(), position_1);
2175        assert_eq!(plh_1.current_sequence_hash(), current_hash_0);
2176        assert_eq!(
2177            plh_1.parent_hash_fragment(),
2178            parent_hash_0 & ((1u64 << 46) - 1),
2179            "Parent fragment should be truncated to 46 bits in mode 1"
2180        );
2181
2182        // Test Mode 2: position fits in 24 bits (65536 <= pos < 16777216)
2183        let position_2 = 100_000;
2184        let plh_2 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_2);
2185
2186        assert_eq!(plh_2.mode(), 2, "Position 100,000 should use mode 2");
2187        assert_eq!(plh_2.position(), position_2);
2188        assert_eq!(plh_2.current_sequence_hash(), current_hash_0);
2189        assert_eq!(
2190            plh_2.parent_hash_fragment(),
2191            parent_hash_0 & ((1u64 << 38) - 1),
2192            "Parent fragment should be truncated to 38 bits in mode 2"
2193        );
2194
2195        // Test edge cases: position at boundaries
2196        let position_255 = 255;
2197        let plh_255 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_255);
2198        assert_eq!(plh_255.mode(), 0, "Position 255 should use mode 0");
2199        assert_eq!(plh_255.position(), position_255);
2200
2201        let position_256 = 256;
2202        let plh_256 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_256);
2203        assert_eq!(plh_256.mode(), 1, "Position 256 should use mode 1");
2204        assert_eq!(plh_256.position(), position_256);
2205
2206        let position_65535 = 65535;
2207        let plh_65535 =
2208            PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_65535);
2209        assert_eq!(plh_65535.mode(), 1, "Position 65535 should use mode 1");
2210        assert_eq!(plh_65535.position(), position_65535);
2211
2212        let position_65536 = 65536;
2213        let plh_65536 =
2214            PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_65536);
2215        assert_eq!(plh_65536.mode(), 2, "Position 65536 should use mode 2");
2216        assert_eq!(plh_65536.position(), position_65536);
2217
2218        // Test with None parent (root block)
2219        let plh_root = PositionalLineageHash::new(current_hash_0, None, 0);
2220        assert_eq!(plh_root.mode(), 0);
2221        assert_eq!(plh_root.position(), 0);
2222        assert_eq!(
2223            plh_root.parent_hash_fragment(),
2224            0,
2225            "Root should have zero parent fragment"
2226        );
2227        assert_eq!(plh_root.current_sequence_hash(), current_hash_0);
2228    }
2229
2230    #[test]
2231    #[should_panic(expected = "Position 16777216 exceeds maximum supported value")]
2232    fn test_positional_lineage_hash_panic_on_large_position() {
2233        let current_hash = 0x1234567890ABCDEF;
2234        let parent_hash = 0xFEDCBA9876543210;
2235        let position = 1u64 << 24; // 2^24 = 16,777,216
2236        let _ = PositionalLineageHash::new(current_hash, Some(parent_hash), position);
2237    }
2238
2239    #[test]
2240    fn test_positional_lineage_hash_mode_boundary_alignment() {
2241        // Test that backward radix traversal still works across mode boundaries.
2242        // Under the asymmetric layout, the parent fragment is sized to the *child's*
2243        // mode and pulled from the parent's full u64 via
2244        // `parent_fragment_for_child_position`.
2245
2246        let parent_hash = 0xFEDCBA9876543210;
2247        let current_hash_255 = 0x1234567890ABCDEF;
2248        let current_hash_256 = 0xABCDEF0123456789;
2249
2250        // Position 255: Mode 0 (last position before boundary)
2251        let plh_255 = PositionalLineageHash::new(current_hash_255, Some(parent_hash), 255);
2252        assert_eq!(plh_255.mode(), 0);
2253        assert_eq!(plh_255.current_sequence_hash(), current_hash_255);
2254
2255        // Position 256: Mode 1 (first position after boundary)
2256        let plh_256 = PositionalLineageHash::new(current_hash_256, Some(current_hash_255), 256);
2257        assert_eq!(plh_256.mode(), 1);
2258
2259        // CRITICAL: child's parent_fragment must equal parent's current truncated to
2260        // the child's mode width (46 bits at mode 1).
2261        let mask_46 = (1u64 << 46) - 1;
2262        assert_eq!(
2263            plh_256.parent_hash_fragment(),
2264            current_hash_255 & mask_46,
2265            "Mode boundary: position 256's parent fragment matches position 255's current truncated to 46 bits"
2266        );
2267        assert_eq!(
2268            plh_256.parent_hash_fragment(),
2269            plh_255.parent_fragment_for_child_position(256),
2270            "parent_fragment_for_child_position helper should match"
2271        );
2272
2273        // Test the other boundary: 65535 -> 65536 (Mode 1 -> Mode 2)
2274        let current_hash_65535 = 0x1111222233334444;
2275        let current_hash_65536 = 0x5555666677778888;
2276
2277        let plh_65535 = PositionalLineageHash::new(current_hash_65535, Some(parent_hash), 65535);
2278        assert_eq!(plh_65535.mode(), 1);
2279
2280        let plh_65536 =
2281            PositionalLineageHash::new(current_hash_65536, Some(current_hash_65535), 65536);
2282        assert_eq!(plh_65536.mode(), 2);
2283
2284        // Mode 2 parent fragment is 38 bits.
2285        let mask_38 = (1u64 << 38) - 1;
2286        assert_eq!(
2287            plh_65536.parent_hash_fragment(),
2288            current_hash_65535 & mask_38,
2289            "Mode boundary: position 65536's parent fragment matches position 65535's current truncated to 38 bits"
2290        );
2291        assert_eq!(
2292            plh_65536.parent_hash_fragment(),
2293            plh_65535.parent_fragment_for_child_position(65536),
2294        );
2295    }
2296
2297    #[test]
2298    fn test_positional_lineage_hash_extend() {
2299        // PLH must be self-extending: a chain built from PLH::root + extend should be
2300        // bitwise identical to the chain produced by full TokenBlock construction.
2301        let salt: SaltHash = 1337;
2302        let bh: [BlockHash; 3] = [
2303            compute_block_hash(cast_slice(&[1u32, 2, 3, 4]), salt),
2304            compute_block_hash(cast_slice(&[5u32, 6, 7, 8]), salt),
2305            compute_block_hash(cast_slice(&[9u32, 10, 11, 12]), salt),
2306        ];
2307
2308        // Direct construction via TokenBlock
2309        let blk0 =
2310            TokenBlock::from_chunk(TokenBlockChunk::from_tokens(&[1, 2, 3, 4], salt), None, 0);
2311        let blk1 = TokenBlock::from_chunk(
2312            TokenBlockChunk::from_tokens(&[5, 6, 7, 8], salt),
2313            Some(blk0.sequence_hash()),
2314            1,
2315        );
2316        let blk2 = TokenBlock::from_chunk(
2317            TokenBlockChunk::from_tokens(&[9, 10, 11, 12], salt),
2318            Some(blk1.sequence_hash()),
2319            2,
2320        );
2321
2322        // Self-extending construction via PLH::root + extend
2323        let plh0 = PositionalLineageHash::root(bh[0]);
2324        let plh1 = plh0.extend(bh[1]);
2325        let plh2 = plh1.extend(bh[2]);
2326
2327        assert_eq!(plh0.as_u128(), blk0.positional_lineage_hash().as_u128());
2328        assert_eq!(plh1.as_u128(), blk1.positional_lineage_hash().as_u128());
2329        assert_eq!(plh2.as_u128(), blk2.positional_lineage_hash().as_u128());
2330
2331        // Chain definition: extended.current_sequence_hash == compute_next_sequence_hash(parent, child)
2332        assert_eq!(
2333            plh1.current_sequence_hash(),
2334            compute_next_sequence_hash(plh0.current_sequence_hash(), bh[1]),
2335        );
2336
2337        // Salt propagation: changing salt changes block_hash[0] and therefore every
2338        // subsequent PLH, even though salt no longer seeds the per-step chain.
2339        let alt_salt: SaltHash = 4242;
2340        let alt_bh0 = compute_block_hash(cast_slice(&[1u32, 2, 3, 4]), alt_salt);
2341        assert_ne!(alt_bh0, bh[0]);
2342        let alt_plh0 = PositionalLineageHash::root(alt_bh0);
2343        let alt_plh1 = alt_plh0.extend(compute_block_hash(cast_slice(&[5u32, 6, 7, 8]), alt_salt));
2344        assert_ne!(alt_plh0.as_u128(), plh0.as_u128());
2345        assert_ne!(alt_plh1.as_u128(), plh1.as_u128());
2346    }
2347
2348    #[test]
2349    fn test_tokens_from() {
2350        let vec_u32: Vec<u32> = vec![1, 2, 3];
2351        let tokens_u32: Tokens = vec_u32.clone().into();
2352        assert_eq!(tokens_u32.0, vec_u32);
2353
2354        let slice_u32: &[u32] = &[4, 5];
2355        let tokens_slice_u32: Tokens = slice_u32.into();
2356        assert_eq!(tokens_slice_u32.0, vec![4, 5]);
2357
2358        let vec_i32: Vec<i32> = vec![-1, 0, 1]; // Note: -1 becomes large u32
2359        let tokens_i32: Tokens = vec_i32.into();
2360        assert_eq!(tokens_i32.0, vec![u32::MAX, 0, 1]);
2361
2362        let slice_i32: &[i32] = &[100, 200];
2363        let tokens_slice_i32: Tokens = slice_i32.into();
2364        assert_eq!(tokens_slice_i32.0, vec![100, 200]);
2365
2366        let into_vec: Vec<u32> = tokens_slice_i32.into();
2367        assert_eq!(into_vec, vec![100, 200]);
2368    }
2369
2370    #[test]
2371    fn test_tokens_equality() {
2372        let tokens = Tokens::from(vec![1, 2, 3]);
2373        assert_eq!(tokens, vec![1, 2, 3]);
2374        assert_eq!(vec![1, 2, 3], tokens);
2375        assert_eq!(tokens, &[1, 2, 3][..]);
2376        assert_eq!(&[1, 2, 3][..], tokens);
2377        assert_eq!(tokens, Tokens::from(vec![1, 2, 3]));
2378        assert_ne!(tokens, Tokens::from(vec![1, 2, 4]));
2379    }
2380
2381    #[test]
2382    fn test_tokens_deref_asref() {
2383        let tokens = Tokens::from(vec![10, 20, 30]);
2384
2385        // Deref to &[Token]
2386        assert_eq!(tokens.len(), 3);
2387        assert_eq!(tokens[1], 20);
2388        let slice: &[Token] = &tokens;
2389        assert_eq!(slice, &[10, 20, 30]);
2390
2391        // AsRef<[Token]>
2392        let as_ref_slice: &[Token] = tokens.as_ref();
2393        assert_eq!(as_ref_slice, &[10, 20, 30]);
2394
2395        // Borrow<[Token]>
2396        let borrowed_slice: &[Token] = std::borrow::Borrow::borrow(&tokens);
2397        assert_eq!(borrowed_slice, &[10, 20, 30]);
2398    }
2399
2400    #[test]
2401    fn test_tokens_into_sequence() {
2402        let tokens = Tokens::from(vec![1, 2, 3, 4, 5]);
2403        let seq = tokens.into_sequence(3, Some(TEST_SALT_HASH));
2404        assert_eq!(seq.blocks().len(), 1);
2405        assert_eq!(seq.blocks[0].tokens().as_ref(), &[1, 2, 3]);
2406        assert_eq!(seq.current_block().tokens().as_ref(), &[4, 5]);
2407        assert_eq!(seq.salt_hash(), TEST_SALT_HASH);
2408    }
2409
2410    #[test]
2411    fn test_partial_block_ops() {
2412        let mut partial = PartialTokenBlock::create_sequence_root(3, TEST_SALT_HASH);
2413        assert_eq!(partial.len(), 0);
2414        assert_eq!(partial.remaining(), 3);
2415        assert!(partial.is_empty());
2416
2417        // Push tokens
2418        assert!(partial.push_token(1).is_ok());
2419        assert_eq!(partial.len(), 1);
2420        assert_eq!(partial.remaining(), 2);
2421        let remaining = partial.push_tokens(Tokens::from(vec![2, 3, 4]));
2422        assert_eq!(partial.len(), 3);
2423        assert_eq!(partial.remaining(), 0);
2424        assert_eq!(remaining.as_ref(), &[4]); // Token 4 didn't fit
2425        assert_eq!(partial.tokens().as_ref(), &[1, 2, 3]);
2426
2427        // Push when full
2428        assert_eq!(partial.push_token(5), Err(TokenBlockError::Full));
2429        let remaining_full = partial.push_tokens(Tokens::from(vec![5]));
2430        assert_eq!(remaining_full.as_ref(), &[5]);
2431
2432        // Pop tokens
2433        assert!(partial.pop_token().is_ok());
2434        assert_eq!(partial.len(), 2);
2435        assert_eq!(partial.tokens().as_ref(), &[1, 2]);
2436        assert!(partial.pop_tokens(2).is_ok());
2437        assert!(partial.is_empty());
2438
2439        // Pop when empty
2440        assert_eq!(partial.pop_token(), Err(TokenBlockError::Empty));
2441        assert_eq!(
2442            partial.pop_tokens(1),
2443            Err(TokenBlockError::InsufficientTokens)
2444        );
2445
2446        // Commit incomplete
2447        assert!(partial.push_token(10).is_ok());
2448        assert_eq!(partial.commit(), Err(TokenBlockError::Incomplete));
2449
2450        // Commit complete
2451        assert!(partial.push_token(11).is_ok());
2452        assert!(partial.push_token(12).is_ok());
2453        assert_eq!(partial.len(), 3);
2454        let commit_result = partial.commit();
2455        assert!(commit_result.is_ok());
2456        let committed_block = commit_result.unwrap();
2457        assert_eq!(committed_block.tokens().as_ref(), &[10, 11, 12]);
2458
2459        // Check state after commit (partial block is now the next one)
2460        assert!(partial.is_empty());
2461        assert_eq!(
2462            partial.parent_sequence_hash,
2463            Some(committed_block.sequence_hash())
2464        );
2465        assert_eq!(partial.block_size, 3);
2466    }
2467
2468    #[test]
2469    fn test_token_block_creation_and_hashes() {
2470        let salt = TEST_SALT_HASH;
2471        let tokens1 = Tokens::from(vec![1, 2, 3, 4]);
2472        let chunk1 = TokenBlockChunk::new(tokens1.clone(), salt);
2473        let block1 = TokenBlock::from_chunk(chunk1, None, 0);
2474
2475        assert_eq!(block1.tokens(), &tokens1);
2476        assert_eq!(block1.salt_hash(), salt);
2477        assert_eq!(block1.parent_sequence_hash(), None);
2478        assert_eq!(block1.block_hash(), HASH_1_4);
2479        assert_eq!(block1.sequence_hash(), SEQ_HASH_1_4); // First block seq_hash == block_hash
2480        assert_eq!(block1.position(), 0); // First block is at position 0
2481
2482        // Verify positional lineage hash for block 1
2483        let plh1 = block1.positional_lineage_hash();
2484        assert_eq!(plh1.position(), 0);
2485        assert_eq!(plh1.parent_hash_fragment(), 0); // Root has no parent
2486        assert_eq!(plh1.current_sequence_hash(), SEQ_HASH_1_4);
2487
2488        let tokens2 = Tokens::from(vec![5, 6, 7, 8]);
2489        let chunk2 = TokenBlockChunk::new(tokens2.clone(), salt);
2490        let block2 = TokenBlock::from_chunk(chunk2, block1.parent_sequence_hash(), 1); // Incorrect parent
2491        // Sequence hash should differ if parent is wrong
2492        assert_ne!(block2.sequence_hash(), SEQ_HASH_5_8);
2493
2494        let chunk2_correct = TokenBlockChunk::new(tokens2.clone(), salt);
2495        let block2_correct =
2496            TokenBlock::from_chunk(chunk2_correct, Some(block1.sequence_hash()), 1);
2497
2498        assert_eq!(block2_correct.tokens(), &tokens2);
2499        assert_eq!(block2_correct.salt_hash(), salt);
2500        assert_eq!(
2501            block2_correct.parent_sequence_hash(),
2502            Some(block1.sequence_hash())
2503        );
2504        assert_eq!(block2_correct.block_hash(), HASH_5_8);
2505        assert_eq!(block2_correct.sequence_hash(), SEQ_HASH_5_8);
2506        assert_eq!(block2_correct.position(), 1); // Second block is at position 1
2507
2508        // Verify positional lineage hash for block 2
2509        let plh2 = block2_correct.positional_lineage_hash();
2510        assert_eq!(plh2.position(), 1);
2511        assert_eq!(
2512            plh2.parent_hash_fragment(),
2513            SEQ_HASH_1_4 & ((1u64 << 54) - 1)
2514        ); // Parent fragment is the parent's u64 truncated to 54 bits in mode 0
2515        assert_eq!(plh2.current_sequence_hash(), SEQ_HASH_5_8);
2516    }
2517
2518    #[test]
2519    fn test_new_sequence() {
2520        // Empty initial tokens
2521        let seq_empty = create_test_sequence(&[], 4, Some(TEST_SALT_HASH));
2522        assert!(seq_empty.blocks().is_empty());
2523        assert!(seq_empty.current_block().is_empty());
2524        assert_eq!(seq_empty.total_tokens(), 0);
2525        assert_eq!(seq_empty.salt_hash(), TEST_SALT_HASH);
2526        assert_eq!(seq_empty.current_block().parent_sequence_hash, None);
2527
2528        // Less than one block
2529        let seq_partial = create_test_sequence(&[1, 2], 4, Some(TEST_SALT_HASH));
2530        assert!(seq_partial.blocks().is_empty());
2531        assert_eq!(seq_partial.current_block().tokens().as_ref(), &[1, 2]);
2532        assert_eq!(seq_partial.total_tokens(), 2);
2533        assert_eq!(seq_partial.current_block().parent_sequence_hash, None);
2534
2535        // Exactly one block
2536        let seq_one_block = create_test_sequence(&[1, 2, 3, 4], 4, Some(TEST_SALT_HASH));
2537        assert_eq!(seq_one_block.blocks().len(), 1);
2538        assert!(seq_one_block.current_block().is_empty());
2539        assert_eq!(seq_one_block.total_tokens(), 4);
2540        assert_eq!(seq_one_block.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2541        assert_eq!(seq_one_block.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2542        assert_eq!(
2543            seq_one_block.current_block().parent_sequence_hash,
2544            Some(SEQ_HASH_1_4)
2545        );
2546
2547        // More than one block
2548        let seq_multi = create_test_sequence(&[1, 2, 3, 4, 5, 6, 7, 8, 9], 4, Some(TEST_SALT_HASH));
2549        assert_eq!(seq_multi.blocks().len(), 2);
2550        assert_eq!(seq_multi.current_block().tokens().as_ref(), &[9]);
2551        assert_eq!(seq_multi.total_tokens(), 9);
2552        assert_eq!(seq_multi.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2553        assert_eq!(seq_multi.blocks[1].sequence_hash(), SEQ_HASH_5_8);
2554        assert_eq!(
2555            seq_multi.current_block().parent_sequence_hash,
2556            Some(SEQ_HASH_5_8)
2557        );
2558
2559        // Test tokens_at across blocks and partial block
2560        assert_eq!(seq_multi.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]); // First complete block
2561        assert_eq!(seq_multi.tokens_at(4..8).as_ref(), &[5, 6, 7, 8]); // Second complete block
2562        assert_eq!(seq_multi.tokens_at(8..9).as_ref(), &[9]); // Current partial block
2563        assert_eq!(seq_multi.tokens_at(2..6).as_ref(), &[3, 4, 5, 6]); // Spanning blocks
2564        assert_eq!(seq_multi.tokens_at(6..9).as_ref(), &[7, 8, 9]); // Spanning to partial
2565        assert_eq!(seq_multi.tokens_at(5..5).as_ref(), &[0u32; 0]); // Empty range
2566        assert_eq!(seq_multi.tokens_at(10..15).as_ref(), &[0u32; 0]); // Out of bounds
2567
2568        // No salt hash
2569        let seq_no_salt = create_test_sequence(&[1, 2, 3, 4, 5], 4, None);
2570        assert_eq!(seq_no_salt.salt_hash(), 0);
2571        assert_eq!(seq_no_salt.blocks().len(), 1);
2572        assert_ne!(seq_no_salt.blocks[0].block_hash(), HASH_1_4); // Hash differs with salt 0
2573        assert_eq!(seq_no_salt.current_block().tokens().as_ref(), &[5]);
2574    }
2575
2576    #[test]
2577    #[should_panic]
2578    fn test_new_sequence_zero_block_size() {
2579        let _ = create_test_sequence(&[1], 0, None);
2580    }
2581
2582    #[test]
2583    fn test_append_single_token() {
2584        let mut sequence =
2585            create_test_sequence(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4, Some(TEST_SALT_HASH));
2586        assert_eq!(sequence.blocks().len(), 2);
2587        assert_eq!(sequence.current_block().tokens.len(), 2);
2588        assert_eq!(sequence.current_block().tokens, vec![9, 10]);
2589        assert_eq!(
2590            sequence.current_block().parent_sequence_hash,
2591            Some(SEQ_HASH_5_8)
2592        );
2593
2594        // Append token 11 - should not complete a block
2595        let completed_idx = sequence.append(11).unwrap();
2596        assert_eq!(completed_idx, None);
2597        assert_eq!(sequence.blocks().len(), 2);
2598        assert_eq!(sequence.current_block().tokens.as_ref(), &[9, 10, 11]);
2599
2600        // Append token 12 - should complete block 2 (index 2)
2601        // This will also commit block 2
2602        let completed_idx = sequence.append(12).unwrap();
2603        assert_eq!(completed_idx, Some(2));
2604        assert_eq!(sequence.blocks().len(), 3);
2605        assert_eq!(sequence.current_block.tokens.as_ref(), &[0u32; 0]);
2606        assert_eq!(sequence.current_block.remaining(), 4);
2607        assert_eq!(
2608            sequence.current_block().parent_sequence_hash,
2609            Some(SEQ_HASH_9_12)
2610        ); // Still linked to block 1
2611
2612        // Append token 13 - should not complete a block
2613        let completed_idx_13 = sequence.append(13).unwrap();
2614        assert_eq!(completed_idx_13, None);
2615        assert_eq!(sequence.blocks().len(), 3);
2616        assert_eq!(sequence.blocks[2].tokens().as_ref(), &[9, 10, 11, 12]);
2617        assert_eq!(sequence.blocks[2].sequence_hash(), SEQ_HASH_9_12);
2618        assert_eq!(sequence.current_block.tokens.as_ref(), &[13]); // New current block has 13
2619        assert_eq!(sequence.current_block.remaining(), 3);
2620        assert_eq!(
2621            sequence.current_block.parent_sequence_hash,
2622            Some(SEQ_HASH_9_12)
2623        ); // Linked to new block 2
2624    }
2625
2626    #[test]
2627    fn test_extend() {
2628        let block_size = 4;
2629        let salt_hash = Some(TEST_SALT_HASH);
2630
2631        // Case 1: Extend less than block size
2632        let mut seq1 = create_test_sequence(&[], block_size, salt_hash);
2633        let tokens1 = Tokens::from(vec![1, 2]);
2634        let completed1 = seq1.extend(tokens1).unwrap();
2635        assert_eq!(completed1, None); // No blocks completed
2636        assert_eq!(seq1.blocks.len(), 0);
2637        assert_eq!(seq1.current_block.tokens.as_ref(), &[1, 2]);
2638        assert_eq!(seq1.current_block.remaining(), 2);
2639        assert_eq!(seq1.current_block.parent_sequence_hash, None); // Still the root block
2640
2641        // Case 2: Extend exactly block size
2642        let mut seq2 = create_test_sequence(&[], block_size, salt_hash);
2643        let tokens2 = Tokens::from(vec![1, 2, 3, 4]);
2644        let completed2 = seq2.extend(tokens2).unwrap();
2645        assert_eq!(completed2, Some(0..1));
2646        assert_eq!(seq2.blocks.len(), 1);
2647        assert_eq!(seq2.current_block.tokens.as_ref(), &[0u32; 0]); // Current block is empty
2648        assert_eq!(seq2.current_block.remaining(), 4);
2649        assert_eq!(seq2.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4)); // Still the root block
2650
2651        // Case 3: Extend more than block size, less than two blocks
2652        let mut seq3 = create_test_sequence(&[], block_size, salt_hash);
2653        let tokens3 = Tokens::from(vec![1, 2, 3, 4, 5, 6]);
2654        let completed3 = seq3.extend(tokens3).unwrap();
2655        assert_eq!(completed3, Some(0..1)); // Block at index 0 completed
2656        assert_eq!(seq3.blocks.len(), 1);
2657        assert_eq!(seq3.current_block.tokens.as_ref(), &[5, 6]); // Partial block has remainder
2658        assert_eq!(seq3.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2659        assert_eq!(seq3.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2660        assert_eq!(seq3.current_block.remaining(), 2);
2661
2662        // Case 4: Extend exactly two blocks
2663        let mut seq4 = create_test_sequence(&[], block_size, salt_hash);
2664        let tokens4 = Tokens::from(vec![1, 2, 3, 4, 5, 6, 7, 8]);
2665        let completed4 = seq4.extend(tokens4).unwrap();
2666        assert_eq!(completed4, Some(0..2)); // Only block 0 is committed
2667        assert_eq!(seq4.blocks.len(), 2); // Only 1 block committed
2668        assert_eq!(seq4.current_block.tokens.as_ref(), &[0u32; 0]);
2669        assert_eq!(seq4.current_block.remaining(), 4);
2670        assert_eq!(seq4.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2671        assert_eq!(seq4.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2672        assert_eq!(seq4.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8)); // Parent is the first block
2673
2674        // Case 5: Extend multiple times, completing blocks across calls
2675        let mut seq5 = create_test_sequence(&[], block_size, salt_hash);
2676        let tokens5a = Tokens::from(vec![1, 2]);
2677        let completed5a = seq5.extend(tokens5a).unwrap();
2678        assert_eq!(completed5a, None);
2679        assert_eq!(seq5.blocks.len(), 0);
2680        assert_eq!(seq5.current_block.tokens.as_ref(), &[1, 2]);
2681
2682        let tokens5b = Tokens::from(vec![3, 4, 5]);
2683        let completed5b = seq5.extend(tokens5b).unwrap();
2684        assert_eq!(completed5b, Some(0..1)); // Block at index 0 completed
2685        assert_eq!(seq5.blocks.len(), 1);
2686        assert_eq!(seq5.current_block.tokens.as_ref(), &[5]);
2687        assert_eq!(seq5.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2688        assert_eq!(seq5.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2689        assert_eq!(seq5.current_block.remaining(), 3);
2690
2691        let tokens5c = Tokens::from(vec![6, 7, 8, 9, 10]);
2692        let completed5c = seq5.extend(tokens5c).unwrap();
2693        assert_eq!(completed5c, Some(1..2)); // Block at index 1 completed
2694        assert_eq!(seq5.blocks.len(), 2);
2695        assert_eq!(seq5.current_block.tokens.as_ref(), &[9, 10]);
2696        assert_eq!(seq5.blocks[1].tokens().as_ref(), &[5, 6, 7, 8]);
2697        assert_eq!(seq5.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8));
2698        assert_eq!(seq5.current_block.remaining(), 2);
2699
2700        // Case 6: Extend empty tokens
2701        let mut seq6 = create_test_sequence(&[1], block_size, salt_hash);
2702        let completed6 = seq6.extend(Tokens::default()).unwrap();
2703        assert_eq!(completed6, None);
2704        assert_eq!(seq6.blocks.len(), 0);
2705        assert_eq!(seq6.current_block.tokens.as_ref(), &[1]);
2706        assert_eq!(seq6.total_tokens(), 1);
2707
2708        // Case 7: Extend fills current exactly, no remainder
2709        let mut seq7 = create_test_sequence(&[1, 2], block_size, salt_hash);
2710        let tokens7 = Tokens::from(vec![3, 4]);
2711        let completed7 = seq7.extend(tokens7).unwrap();
2712        assert_eq!(completed7, Some(0..1)); // Block is full but not committed yet
2713        assert_eq!(seq7.blocks.len(), 1);
2714        assert_eq!(seq7.current_block.tokens.as_ref(), &[0u32; 0]); // Current block is full
2715        assert_eq!(seq7.current_block.remaining(), 4);
2716        assert_eq!(seq7.total_tokens(), 4);
2717        assert_eq!(seq7.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4)); // Still the root block
2718
2719        // Test tokens_at extraction
2720        assert_eq!(seq7.tokens_at(0..2).as_ref(), &[1, 2]);
2721        assert_eq!(seq7.tokens_at(1..3).as_ref(), &[2, 3]);
2722        assert_eq!(seq7.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]);
2723        assert_eq!(seq7.tokens_at(2..2).as_ref(), &[0u32; 0]); // Empty range
2724    }
2725
2726    #[test]
2727    fn test_truncate() {
2728        let block_size = 4;
2729        let salt_hash = Some(TEST_SALT_HASH);
2730        let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // 10 tokens
2731
2732        // Case 1: Truncate within current block (len 9)
2733        let mut seq1 = create_test_sequence(initial_tokens, block_size, salt_hash);
2734        assert!(seq1.truncate(9).is_ok());
2735        assert_eq!(seq1.total_tokens(), 9);
2736        assert_eq!(seq1.blocks().len(), 2);
2737        assert_eq!(seq1.current_block().tokens.as_ref(), &[9]);
2738        assert_eq!(
2739            seq1.current_block().parent_sequence_hash,
2740            Some(SEQ_HASH_5_8)
2741        );
2742
2743        // Case 2: Truncate to exact block boundary (len 8)
2744        let mut seq2 = create_test_sequence(initial_tokens, block_size, salt_hash);
2745        assert!(seq2.truncate(8).is_ok());
2746        assert_eq!(seq2.total_tokens(), 8);
2747        assert_eq!(seq2.blocks().len(), 2);
2748        assert!(seq2.current_block().tokens.is_empty());
2749        assert_eq!(
2750            seq2.current_block().parent_sequence_hash,
2751            Some(SEQ_HASH_5_8)
2752        );
2753
2754        // Case 3: Truncate into last full block (len 7)
2755        let mut seq3 = create_test_sequence(initial_tokens, block_size, salt_hash);
2756        assert!(seq3.truncate(7).is_ok());
2757        assert_eq!(seq3.total_tokens(), 7);
2758        assert_eq!(seq3.blocks().len(), 1); // Block [5,6,7,8] removed conceptually
2759        assert_eq!(seq3.current_block().tokens.as_ref(), &[5, 6, 7]); // Kept 3 from [5,6,7,8]
2760        assert_eq!(
2761            seq3.current_block().parent_sequence_hash,
2762            Some(SEQ_HASH_1_4)
2763        ); // Parent is hash of [1,2,3,4]
2764        assert_eq!(seq3.blocks()[0].tokens().as_ref(), &[1, 2, 3, 4]);
2765
2766        // Case 4: Truncate removing full block(s) exactly (len 4)
2767        let mut seq4 = create_test_sequence(initial_tokens, block_size, salt_hash);
2768        assert!(seq4.truncate(4).is_ok());
2769        assert_eq!(seq4.total_tokens(), 4);
2770        assert_eq!(seq4.blocks().len(), 1); // Block [5,6,7,8] removed
2771        assert!(seq4.current_block().tokens.is_empty()); // New partial based on block [1,2,3,4]
2772        assert_eq!(
2773            seq4.current_block().parent_sequence_hash,
2774            Some(SEQ_HASH_1_4)
2775        );
2776        assert_eq!(seq4.blocks()[0].tokens().as_ref(), &[1, 2, 3, 4]);
2777
2778        // Case 5: Truncate into first block (len 3)
2779        let mut seq5 = create_test_sequence(initial_tokens, block_size, salt_hash);
2780        assert!(seq5.truncate(3).is_ok());
2781        assert_eq!(seq5.total_tokens(), 3);
2782        assert!(seq5.blocks().is_empty()); // Both blocks removed conceptually
2783        assert_eq!(seq5.current_block().tokens.as_ref(), &[1, 2, 3]); // Kept 3 from [1,2,3,4]
2784        assert_eq!(seq5.current_block().parent_sequence_hash, None); // No parent
2785
2786        // Case 6: Truncate to zero length (len 0)
2787        let mut seq6 = create_test_sequence(initial_tokens, block_size, salt_hash);
2788        assert!(seq6.truncate(0).is_ok());
2789        assert_eq!(seq6.total_tokens(), 0);
2790        assert!(seq6.blocks().is_empty());
2791        assert!(seq6.current_block().tokens.is_empty());
2792        assert_eq!(seq6.current_block().parent_sequence_hash, None);
2793
2794        // Case 7: Truncate to length greater than current (len 11)
2795        let mut seq7 = create_test_sequence(initial_tokens, block_size, salt_hash);
2796        let original_state = (seq7.blocks.clone(), seq7.current_block.tokens.clone()); // Clone for state check
2797        assert!(seq7.truncate(11).is_ok()); // Should have no effect
2798        assert_eq!(seq7.total_tokens(), 10);
2799        assert_eq!(seq7.blocks, original_state.0);
2800        assert_eq!(seq7.current_block.tokens, original_state.1);
2801
2802        // Case 8: Truncate to current length (len 10)
2803        let mut seq8 = create_test_sequence(initial_tokens, block_size, salt_hash);
2804        let original_state = (seq8.blocks.clone(), seq8.current_block.tokens.clone());
2805        assert!(seq8.truncate(10).is_ok());
2806        assert_eq!(seq8.total_tokens(), 10);
2807        assert_eq!(seq8.blocks, original_state.0);
2808        assert_eq!(seq8.current_block.tokens, original_state.1);
2809
2810        // Case 9: Truncate an empty sequence to 0
2811        let mut seq9 = create_test_sequence(&[], block_size, salt_hash);
2812        assert!(seq9.truncate(0).is_ok());
2813        assert_eq!(seq9.total_tokens(), 0);
2814        assert!(seq9.blocks().is_empty());
2815        assert!(seq9.current_block().tokens.is_empty());
2816
2817        // Case 10: Truncate on exact block boundary when current is empty (len 4)
2818        let tokens10 = &[1, 2, 3, 4, 5, 6, 7, 8]; // 8 tokens
2819        let mut seq10 = create_test_sequence(tokens10, block_size, salt_hash);
2820        assert_eq!(seq10.total_tokens(), 8);
2821        assert!(seq10.current_block().is_empty());
2822        assert!(seq10.truncate(4).is_ok()); // Remove block [5, 6, 7, 8]
2823        assert_eq!(seq10.total_tokens(), 4);
2824        assert_eq!(seq10.blocks().len(), 1);
2825        assert!(seq10.current_block().tokens.is_empty());
2826        assert_eq!(
2827            seq10.current_block().parent_sequence_hash,
2828            Some(SEQ_HASH_1_4)
2829        );
2830
2831        // Case 11: Truncate into first block when current is empty (len 3)
2832        let tokens11 = &[1, 2, 3, 4, 5, 6, 7, 8]; // 8 tokens
2833        let mut seq11 = create_test_sequence(tokens11, block_size, salt_hash);
2834        assert!(seq11.truncate(3).is_ok()); // Pop block [5,6,7,8] + 1 from [1,2,3,4]
2835        assert_eq!(seq11.total_tokens(), 3);
2836        assert!(seq11.blocks().is_empty());
2837        assert_eq!(seq11.current_block().tokens.as_ref(), &[1, 2, 3]); // Kept 3 from [1,2,3,4]
2838        assert_eq!(seq11.current_block().parent_sequence_hash, None);
2839    }
2840
2841    #[test]
2842    fn test_unwind() {
2843        let block_size = 4;
2844        let salt_hash = Some(TEST_SALT_HASH);
2845        let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // 10 tokens
2846
2847        // Unwind 0
2848        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2849        assert!(seq.unwind(0).is_ok());
2850        assert_eq!(seq.total_tokens(), 10);
2851
2852        // Unwind 1
2853        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2854        assert!(seq.unwind(1).is_ok());
2855        assert_eq!(seq.total_tokens(), 9);
2856        assert_eq!(seq.current_block.tokens.as_ref(), &[9]);
2857
2858        // Unwind 3 (crosses boundary)
2859        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2860        assert!(seq.unwind(3).is_ok());
2861        assert_eq!(seq.total_tokens(), 7);
2862        assert_eq!(seq.blocks.len(), 1);
2863        assert_eq!(seq.current_block.tokens.as_ref(), &[5, 6, 7]);
2864
2865        // Unwind all (10)
2866        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2867        assert!(seq.unwind(10).is_ok());
2868        assert_eq!(seq.total_tokens(), 0);
2869        assert!(seq.blocks.is_empty());
2870        assert!(seq.current_block.is_empty());
2871
2872        // Unwind more than available (11)
2873        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2874        assert_eq!(seq.unwind(11), Err(TokenBlockError::InsufficientTokens));
2875        assert_eq!(seq.total_tokens(), 10); // State unchanged
2876
2877        // Unwind from empty
2878        let mut seq_empty = create_test_sequence(&[], block_size, salt_hash);
2879        assert_eq!(
2880            seq_empty.unwind(1),
2881            Err(TokenBlockError::InsufficientTokens)
2882        );
2883    }
2884
2885    #[test]
2886    fn test_pop() {
2887        let block_size = 4;
2888        let salt_hash = Some(TEST_SALT_HASH);
2889        let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // 10 tokens
2890
2891        let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2892
2893        // Pop 10
2894        assert_eq!(seq.pop(), Some(10));
2895        assert_eq!(seq.total_tokens(), 9);
2896        assert_eq!(seq.current_block.tokens.as_ref(), &[9]);
2897        assert_eq!(seq.blocks.len(), 2);
2898
2899        // Pop 9
2900        assert_eq!(seq.pop(), Some(9));
2901        assert_eq!(seq.total_tokens(), 8);
2902        assert!(seq.current_block.is_empty());
2903        assert_eq!(seq.blocks.len(), 2);
2904        assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8));
2905
2906        // Pop 8 (crosses boundary)
2907        assert_eq!(seq.pop(), Some(8));
2908        assert_eq!(seq.total_tokens(), 7);
2909        assert_eq!(seq.current_block.tokens.as_ref(), &[5, 6, 7]);
2910        assert_eq!(seq.blocks.len(), 1);
2911        assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2912
2913        // Pop remaining partial (7, 6, 5)
2914        assert_eq!(seq.pop(), Some(7));
2915        assert_eq!(seq.pop(), Some(6));
2916        assert_eq!(seq.pop(), Some(5));
2917        assert_eq!(seq.total_tokens(), 4);
2918        assert!(seq.current_block.is_empty());
2919        assert_eq!(seq.blocks.len(), 1);
2920        assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2921
2922        // Pop 4 (crosses boundary)
2923        assert_eq!(seq.pop(), Some(4));
2924        assert_eq!(seq.total_tokens(), 3);
2925        assert_eq!(seq.current_block.tokens.as_ref(), &[1, 2, 3]);
2926        assert!(seq.blocks.is_empty());
2927        assert_eq!(seq.current_block.parent_sequence_hash, None);
2928
2929        // Pop 3, 2, 1
2930        assert_eq!(seq.pop(), Some(3));
2931        assert_eq!(seq.pop(), Some(2));
2932        assert_eq!(seq.pop(), Some(1));
2933        assert_eq!(seq.total_tokens(), 0);
2934        assert!(seq.current_block.is_empty());
2935        assert!(seq.blocks.is_empty());
2936
2937        // Pop from empty
2938        assert_eq!(seq.pop(), None);
2939        assert_eq!(seq.total_tokens(), 0);
2940    }
2941
2942    #[test]
2943    fn test_total_tokens() {
2944        let block_size = 3;
2945        let salt_hash = Some(TEST_SALT_HASH);
2946
2947        let mut seq = create_test_sequence(&[], block_size, salt_hash);
2948        assert_eq!(seq.total_tokens(), 0);
2949
2950        seq.extend(Tokens::from(vec![1, 2])).unwrap();
2951        assert_eq!(seq.total_tokens(), 2);
2952
2953        seq.append(3).unwrap(); // Completes block 0
2954        assert_eq!(seq.total_tokens(), 3);
2955
2956        seq.extend(Tokens::from(vec![4, 5, 6, 7])).unwrap(); // Completes block 1, partial [7]
2957        assert_eq!(seq.total_tokens(), 7);
2958
2959        seq.pop().unwrap(); // Removes 7
2960        assert_eq!(seq.total_tokens(), 6);
2961
2962        seq.truncate(4).unwrap(); // Keep [1,2,3,4]
2963        assert_eq!(seq.total_tokens(), 4);
2964
2965        seq.unwind(2).unwrap(); // Keep [1,2]
2966        assert_eq!(seq.total_tokens(), 2);
2967    }
2968
2969    #[test]
2970    fn test_push_tokens_partial_block() {
2971        let mut partial = PartialTokenBlock::create_sequence_root(4, 1337);
2972
2973        let tokens = Tokens(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2974
2975        let remaining = partial.push_tokens(tokens);
2976        assert_eq!(partial.tokens.len(), 4);
2977        assert_eq!(remaining.len(), 6);
2978    }
2979
2980    // ========== Additional tests for coverage improvement ==========
2981
2982    // === PositionalRadixTree Tests ===
2983
2984    #[test]
2985    fn test_positional_radix_tree_basic_operations() {
2986        use crate::PositionalRadixTree;
2987
2988        // Test new() and is_empty()
2989        let tree: PositionalRadixTree<String> = PositionalRadixTree::new();
2990        assert!(tree.is_empty());
2991        assert_eq!(tree.len(), 0);
2992
2993        // Test default()
2994        let tree2: PositionalRadixTree<i32> = PositionalRadixTree::default();
2995        assert!(tree2.is_empty());
2996
2997        // Test prefix() and insertion
2998        let psh1 = PositionalSequenceHash::new(0x1234, 0, 0xABCD);
2999        let psh2 = PositionalSequenceHash::new(0x5678, 0, 0xEF01);
3000        let psh3 = PositionalSequenceHash::new(0x9ABC, 1, 0x2345);
3001
3002        tree.prefix(&psh1).insert(psh1, "value1".to_string());
3003        assert!(!tree.is_empty());
3004        assert_eq!(tree.len(), 1);
3005
3006        tree.prefix(&psh2).insert(psh2, "value2".to_string());
3007        assert_eq!(tree.len(), 2);
3008
3009        tree.prefix(&psh3).insert(psh3, "value3".to_string());
3010        assert_eq!(tree.len(), 3);
3011
3012        // Test retrieval
3013        assert_eq!(
3014            tree.prefix(&psh1).get(&psh1).cloned(),
3015            Some("value1".to_string())
3016        );
3017    }
3018
3019    #[test]
3020    fn test_positional_radix_tree_with_lineage_hash() {
3021        use crate::PositionalRadixTree;
3022
3023        // Test generic usage with PositionalLineageHash
3024        let tree: PositionalRadixTree<u32, PositionalLineageHash> = PositionalRadixTree::new();
3025        assert!(tree.is_empty());
3026
3027        let plh1 = PositionalLineageHash::new(0x1234, None, 0);
3028        let plh2 = PositionalLineageHash::new(0x5678, Some(0x1234), 1);
3029
3030        tree.prefix(&plh1).insert(plh1, 100);
3031        tree.prefix(&plh2).insert(plh2, 200);
3032
3033        assert_eq!(tree.len(), 2);
3034        assert_eq!(tree.prefix(&plh1).get(&plh1).copied(), Some(100));
3035        assert_eq!(tree.prefix(&plh2).get(&plh2).copied(), Some(200));
3036    }
3037
3038    #[test]
3039    fn test_positional_radix_tree_position_lookup() {
3040        use crate::PositionalRadixTree;
3041
3042        let tree: PositionalRadixTree<String> = PositionalRadixTree::new();
3043
3044        // Insert at different positions
3045        let psh0 = PositionalSequenceHash::new(0x1111, 0, 0xAAAA);
3046        let psh1 = PositionalSequenceHash::new(0x2222, 1, 0xBBBB);
3047        let psh2 = PositionalSequenceHash::new(0x3333, 2, 0xCCCC);
3048
3049        tree.prefix(&psh0).insert(psh0, "pos0".to_string());
3050        tree.prefix(&psh1).insert(psh1, "pos1".to_string());
3051        tree.prefix(&psh2).insert(psh2, "pos2".to_string());
3052
3053        // Test position() method
3054        assert!(tree.position(0).is_some());
3055        assert!(tree.position(1).is_some());
3056        assert!(tree.position(2).is_some());
3057        assert!(tree.position(3).is_none()); // No entries at position 3
3058
3059        // Verify position lookup returns correct submap
3060        let pos0_map = tree.position(0).unwrap();
3061        assert_eq!(pos0_map.len(), 1);
3062    }
3063
3064    #[test]
3065    fn test_positional_radix_tree_concurrent_same_position() {
3066        use crate::PositionalRadixTree;
3067        use std::sync::Arc;
3068
3069        let tree = Arc::new(PositionalRadixTree::new());
3070        let threads: Vec<_> = (0..8_u64)
3071            .map(|value| {
3072                let tree = Arc::clone(&tree);
3073                std::thread::spawn(move || {
3074                    let key = PositionalSequenceHash::new(value, 7, value);
3075                    tree.prefix(&key).insert(key, value);
3076                })
3077            })
3078            .collect();
3079
3080        for thread in threads {
3081            thread.join().unwrap();
3082        }
3083
3084        assert_eq!(tree.len(), 8);
3085        assert_eq!(tree.position(7).unwrap().len(), 8);
3086    }
3087
3088    // === PositionalSequenceHash Additional Tests ===
3089
3090    #[test]
3091    fn test_positional_sequence_hash_mode_2_and_3() {
3092        // Mode 2: position fits in 24 bits (65536 <= pos < 16777216)
3093        let position_mode2 = 100_000u64;
3094        let seq_hash = 0x1234567890ABCDEF;
3095        let block_hash = 0xFEDCBA9876543210;
3096
3097        let psh_mode2 = PositionalSequenceHash::new(seq_hash, position_mode2, block_hash);
3098        assert_eq!(psh_mode2.mode(), 2, "Position 100,000 should use mode 2");
3099        assert_eq!(psh_mode2.position(), position_mode2);
3100        assert_eq!(psh_mode2.sequence_hash(), seq_hash);
3101        // Local block hash truncated to 38 bits in mode 2
3102        assert_eq!(
3103            psh_mode2.local_block_hash(),
3104            block_hash & ((1u64 << 38) - 1)
3105        );
3106
3107        // Mode 3: position fits in 31 bits (16777216 <= pos < 2147483648)
3108        let position_mode3 = 100_000_000u64;
3109        let psh_mode3 = PositionalSequenceHash::new(seq_hash, position_mode3, block_hash);
3110        assert_eq!(
3111            psh_mode3.mode(),
3112            3,
3113            "Position 100,000,000 should use mode 3"
3114        );
3115        assert_eq!(psh_mode3.position(), position_mode3);
3116        assert_eq!(psh_mode3.sequence_hash(), seq_hash);
3117        // Local block hash truncated to 31 bits in mode 3
3118        assert_eq!(
3119            psh_mode3.local_block_hash(),
3120            block_hash & ((1u64 << 31) - 1)
3121        );
3122    }
3123
3124    #[test]
3125    fn test_positional_sequence_hash_as_u128() {
3126        let psh = PositionalSequenceHash::new(0x1234, 100, 0xABCD);
3127        let raw = psh.as_u128();
3128
3129        // Verify we can reconstruct from raw value
3130        assert_eq!(raw & 0xFFFF_FFFF_FFFF_FFFF, 0x1234);
3131        assert!(raw > 0); // Non-zero
3132
3133        // Create another and compare
3134        let psh2 = PositionalSequenceHash::new(0x1234, 100, 0xABCD);
3135        assert_eq!(psh.as_u128(), psh2.as_u128());
3136    }
3137
3138    #[test]
3139    fn test_positional_sequence_hash_debug() {
3140        let psh = PositionalSequenceHash::new(0x1234567890ABCDEF, 42, 0xFEDCBA98);
3141        let debug_str = format!("{:?}", psh);
3142
3143        // Debug should contain field names and values
3144        assert!(debug_str.contains("PositionalSequenceHash"));
3145        assert!(debug_str.contains("sequence_hash"));
3146        assert!(debug_str.contains("local_block_hash"));
3147        assert!(debug_str.contains("position"));
3148    }
3149
3150    // === PositionalLineageHash Additional Tests ===
3151
3152    #[test]
3153    fn test_positional_lineage_hash_debug_and_display() {
3154        // Test position 0 (no parent shown)
3155        let plh_root = PositionalLineageHash::new(0x123456789ABCDEF0, None, 0);
3156        let debug_root = format!("{:?}", plh_root);
3157        let display_root = format!("{}", plh_root);
3158
3159        // Debug and Display should show position 0
3160        assert!(debug_root.starts_with("0:"));
3161        assert!(display_root.starts_with("0:"));
3162        // Position 0 should not show parent
3163        assert_eq!(debug_root.matches(':').count(), 1);
3164        assert_eq!(display_root.matches(':').count(), 1);
3165
3166        // Test position > 0 (parent shown)
3167        let plh_child = PositionalLineageHash::new(0xABCDEF0123456789, Some(0x123456789ABCDEF0), 5);
3168        let debug_child = format!("{:?}", plh_child);
3169        let display_child = format!("{}", plh_child);
3170
3171        // Should show position:current:parent
3172        assert!(debug_child.starts_with("5:"));
3173        assert!(display_child.starts_with("5:"));
3174        // Position > 0 should show parent (3 parts)
3175        assert_eq!(debug_child.matches(':').count(), 2);
3176        assert_eq!(display_child.matches(':').count(), 2);
3177    }
3178
3179    #[test]
3180    fn test_positional_lineage_hash_as_u128() {
3181        let plh = PositionalLineageHash::new(0x1234, Some(0x5678), 10);
3182        let raw = plh.as_u128();
3183
3184        assert!(raw > 0);
3185
3186        // Create another with same params and compare
3187        let plh2 = PositionalLineageHash::new(0x1234, Some(0x5678), 10);
3188        assert_eq!(plh.as_u128(), plh2.as_u128());
3189
3190        // Different params should give different hash
3191        let plh3 = PositionalLineageHash::new(0x1234, Some(0x5678), 11);
3192        assert_ne!(plh.as_u128(), plh3.as_u128());
3193    }
3194
3195    #[test]
3196    fn test_positional_lineage_hash_ord_by_position_then_current_fragment() {
3197        let at_5_low = PositionalLineageHash::new(0x10, Some(0x1111), 5);
3198        let at_5_high = PositionalLineageHash::new(0x20, Some(0x1111), 5);
3199        assert!(
3200            at_5_low.current_sequence_hash() < at_5_high.current_sequence_hash(),
3201            "test assumes distinct current sequence hashes at the same position"
3202        );
3203        assert!(at_5_low < at_5_high);
3204        assert!(at_5_high > at_5_low);
3205
3206        let at_3 = PositionalLineageHash::new(0x99, Some(0x2222), 3);
3207        assert!(at_3 < at_5_low);
3208        assert!(at_5_high < PositionalLineageHash::new(0x01, Some(0x3333), 6));
3209    }
3210
3211    #[test]
3212    fn test_positional_lineage_hash_ord_tiebreak_parent_via_packed_u128() {
3213        let same_pos_same_current = PositionalLineageHash::new(0x1234, Some(0x100), 10);
3214        let same_pos_same_current_other_parent =
3215            PositionalLineageHash::new(0x1234, Some(0x200), 10);
3216        assert_eq!(same_pos_same_current.position(), 10);
3217        assert_eq!(
3218            same_pos_same_current.position(),
3219            same_pos_same_current_other_parent.position()
3220        );
3221        assert_eq!(
3222            same_pos_same_current.current_sequence_hash(),
3223            same_pos_same_current_other_parent.current_sequence_hash()
3224        );
3225        assert_ne!(same_pos_same_current, same_pos_same_current_other_parent);
3226        assert_ne!(
3227            same_pos_same_current.cmp(&same_pos_same_current_other_parent),
3228            std::cmp::Ordering::Equal
3229        );
3230    }
3231
3232    #[test]
3233    fn test_positional_lineage_hash_vec_sort_matches_ord() {
3234        let a = PositionalLineageHash::new(0x30, None, 0);
3235        let b = PositionalLineageHash::new(0x10, Some(0x30), 2);
3236        let c = PositionalLineageHash::new(0x20, Some(0x30), 2);
3237        let mut v = vec![b, a, c];
3238        v.sort();
3239        assert_eq!(v, vec![a, b, c]);
3240    }
3241
3242    #[test]
3243    fn test_positional_lineage_hash_itertools_sorted() {
3244        use itertools::Itertools;
3245
3246        let a = PositionalLineageHash::new(0x30, None, 0);
3247        let b = PositionalLineageHash::new(0x10, Some(0x30), 2);
3248        let c = PositionalLineageHash::new(0x20, Some(0x30), 2);
3249        let sorted: Vec<_> = vec![b, a, c].into_iter().sorted().collect();
3250        assert_eq!(sorted, vec![a, b, c]);
3251    }
3252
3253    // === Tokens From Impls ===
3254
3255    #[test]
3256    fn test_tokens_from_vec_usize() {
3257        let usize_vec: Vec<usize> = vec![1, 2, 3, 4, 5];
3258        let tokens = Tokens::from(usize_vec);
3259
3260        assert_eq!(tokens.as_ref(), &[1u32, 2, 3, 4, 5]);
3261        assert_eq!(tokens.len(), 5);
3262    }
3263
3264    #[test]
3265    fn test_tokens_partial_eq_slice_ref() {
3266        let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3267        let slice: &[Token] = &[1, 2, 3, 4];
3268
3269        // Test PartialEq<&[Token]> for Tokens
3270        assert!(tokens == slice);
3271
3272        let different_slice: &[Token] = &[1, 2, 3, 5];
3273        assert!(tokens != different_slice);
3274    }
3275
3276    // === TokenBlock Accessors ===
3277
3278    #[test]
3279    fn test_token_block_accessors() {
3280        let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3281        let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3282
3283        let block = &seq.blocks()[0];
3284
3285        // Test block_size()
3286        assert_eq!(block.block_size(), 4);
3287
3288        // Test positional_sequence_hash()
3289        let psh = block.positional_sequence_hash();
3290        assert_eq!(psh.position(), 0);
3291
3292        // Test positional_lineage_hash()
3293        let plh = block.positional_lineage_hash();
3294        assert_eq!(plh.position(), 0);
3295        assert_eq!(plh.parent_hash_fragment(), 0); // Root has no parent
3296    }
3297
3298    #[test]
3299    fn test_positional_hash_trait_impls() {
3300        use crate::PositionalHash;
3301
3302        // Test PositionalHash for PositionalSequenceHash
3303        let psh = PositionalSequenceHash::new(0x1234, 42, 0xABCD);
3304        assert_eq!(PositionalHash::position(&psh), 42);
3305
3306        // Test PositionalHash for PositionalLineageHash
3307        let plh = PositionalLineageHash::new(0x1234, None, 99);
3308        assert_eq!(PositionalHash::position(&plh), 99);
3309    }
3310
3311    // === TokenBlockSequence Edge Cases ===
3312
3313    #[test]
3314    fn test_sequence_pop_from_full_block() {
3315        // Test pop when current partial block is empty (must pop from full block)
3316        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8]);
3317        let mut seq = TokenBlockSequence::new(tokens, 4, Some(TEST_SALT_HASH));
3318
3319        // Current block should be empty, all tokens in completed blocks
3320        assert!(seq.current_block().is_empty());
3321        assert_eq!(seq.blocks().len(), 2);
3322        assert_eq!(seq.total_tokens(), 8);
3323
3324        // Pop should remove from last full block
3325        let popped = seq.pop();
3326        assert_eq!(popped, Some(8));
3327        assert_eq!(seq.total_tokens(), 7);
3328        assert_eq!(seq.blocks().len(), 1);
3329        assert_eq!(seq.current_block().tokens.as_ref(), &[5, 6, 7]);
3330    }
3331
3332    #[test]
3333    #[allow(clippy::reversed_empty_ranges)] // so we can explicitly test invalid ranges
3334    fn test_sequence_tokens_at_edge_cases() {
3335        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5]);
3336        let seq = TokenBlockSequence::new(tokens, 4, Some(TEST_SALT_HASH));
3337
3338        // Start > end (invalid range
3339        assert!(seq.tokens_at(3..2).is_empty());
3340
3341        // End > total (out of bounds)
3342        assert!(seq.tokens_at(0..10).is_empty());
3343
3344        // Valid edge case: exact boundaries
3345        assert_eq!(seq.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]);
3346        assert_eq!(seq.tokens_at(4..5).as_ref(), &[5]);
3347    }
3348
3349    #[test]
3350    fn test_sequence_next_block() {
3351        let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3352        let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3353
3354        let block = &seq.blocks()[0];
3355        let next_partial = block.next_block();
3356
3357        // next_block should create a partial block linked to this block
3358        assert!(next_partial.is_empty());
3359        assert_eq!(next_partial.remaining(), 4);
3360        assert_eq!(
3361            next_partial.parent_sequence_hash,
3362            Some(block.sequence_hash())
3363        );
3364        assert_eq!(next_partial.position, 1);
3365    }
3366
3367    #[test]
3368    fn test_sequence_reset() {
3369        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9]);
3370        let mut seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3371
3372        assert_eq!(seq.blocks().len(), 2);
3373        assert_eq!(seq.total_tokens(), 9);
3374
3375        seq.reset();
3376
3377        assert!(seq.blocks().is_empty());
3378        assert!(seq.current_block().is_empty());
3379        assert_eq!(seq.total_tokens(), 0);
3380        assert_eq!(seq.current_block().parent_sequence_hash, None);
3381    }
3382
3383    #[test]
3384    fn test_sequence_into_parts() {
3385        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5]);
3386        let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3387
3388        let (blocks, partial) = seq.into_parts();
3389
3390        assert_eq!(blocks.len(), 1);
3391        assert_eq!(partial.tokens.as_ref(), &[5]);
3392    }
3393
3394    #[test]
3395    fn test_sequence_last_complete_block() {
3396        // Empty sequence
3397        let seq_empty = TokenBlockSequence::new(Tokens::default(), 4, None);
3398        assert!(seq_empty.last_complete_block().is_none());
3399
3400        // With blocks
3401        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8]);
3402        let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3403        let last = seq.last_complete_block();
3404        assert!(last.is_some());
3405        assert_eq!(last.unwrap().tokens().as_ref(), &[5, 6, 7, 8]);
3406    }
3407
3408    #[test]
3409    fn test_positional_hashes_msgpack_roundtrip() {
3410        let psh = PositionalSequenceHash::new(0xDEAD_BEEF_CAFE_BABE, 12345, 0x0123_4567_89AB_CDEF);
3411        let bytes = rmp_serde::to_vec(&psh).expect("psh serialize");
3412        let decoded: PositionalSequenceHash =
3413            rmp_serde::from_slice(&bytes).expect("psh deserialize");
3414        assert_eq!(psh, decoded);
3415        assert_eq!(psh.as_u128(), decoded.as_u128());
3416
3417        let plh =
3418            PositionalLineageHash::new(0x1111_2222_3333_4444, Some(0x5555_6666_7777_8888), 256);
3419        let bytes = rmp_serde::to_vec(&plh).expect("plh serialize");
3420        let decoded: PositionalLineageHash =
3421            rmp_serde::from_slice(&bytes).expect("plh deserialize");
3422        assert_eq!(plh, decoded);
3423        assert_eq!(plh.as_u128(), decoded.as_u128());
3424
3425        // Vec roundtrip — exercises the codec inside a container.
3426        let vec = vec![psh, PositionalSequenceHash::default(), psh];
3427        let bytes = rmp_serde::to_vec(&vec).expect("vec serialize");
3428        let decoded: Vec<PositionalSequenceHash> =
3429            rmp_serde::from_slice(&bytes).expect("vec deserialize");
3430        assert_eq!(vec, decoded);
3431    }
3432
3433    #[test]
3434    fn test_positional_hashes_json_roundtrip() {
3435        // Confirm the byte-array codec also roundtrips through JSON (array of u8).
3436        let psh = PositionalSequenceHash::new(0xAAAA_BBBB_CCCC_DDDD, 7, 0xEEEE_FFFF_0000_1111);
3437        let json = serde_json::to_string(&psh).expect("psh json serialize");
3438        let decoded: PositionalSequenceHash =
3439            serde_json::from_str(&json).expect("psh json deserialize");
3440        assert_eq!(psh, decoded);
3441
3442        let plh = PositionalLineageHash::new(0x1234_5678, Some(0xABCD_EF01), 42);
3443        let json = serde_json::to_string(&plh).expect("plh json serialize");
3444        let decoded: PositionalLineageHash =
3445            serde_json::from_str(&json).expect("plh json deserialize");
3446        assert_eq!(plh, decoded);
3447    }
3448
3449    // ----------------------------------------------------------------------------------------
3450    // Multimodal block-formation tests (#10–14 in the kv-hashing plan).
3451    // ----------------------------------------------------------------------------------------
3452
3453    /// #10: a sequence built via `new_with_mm` with empty mm_info must equal one built via `new`.
3454    #[test]
3455    fn tokens_mm_zero_mm_equivalence() {
3456        let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9]);
3457        let baseline = TokenBlockSequence::new(tokens.clone(), 4, Some(TEST_SALT_HASH));
3458        let mm = TokenBlockSequence::new_with_mm(tokens, &[], 4, Some(TEST_SALT_HASH))
3459            .expect("validation should pass for empty mm_info");
3460
3461        assert_eq!(mm.blocks().len(), baseline.blocks().len());
3462        for (a, b) in mm.blocks().iter().zip(baseline.blocks().iter()) {
3463            assert_eq!(a.salt_hash(), b.salt_hash());
3464            assert_eq!(a.block_hash(), b.block_hash());
3465            assert_eq!(a.sequence_hash(), b.sequence_hash());
3466            assert_eq!(a.parent_sequence_hash(), b.parent_sequence_hash());
3467            assert_eq!(a.positional_lineage_hash(), b.positional_lineage_hash());
3468        }
3469        assert!(mm.mm_runs().is_empty());
3470    }
3471
3472    /// #11: byte layout — verify the MM-aware buffer matches the documented
3473    /// 13-bytes-per-slot tagged framing, and that block_hash is XXH3 over that exact buffer.
3474    #[test]
3475    fn tokens_mm_byte_layout() {
3476        // Block 0: tokens [t0..t3], placeholder run [4..6) with mm_hash=0xAA, then t6, t7.
3477        // block_size = 8 ⇒ block_offset = 0, run covers slots 4..6. The block is MM-affected
3478        // ⇒ tagged 13-byte frames apply to *every* slot.
3479        let tokens = Tokens::from(vec![100u32, 101, 102, 103, 0, 0, 106, 107]);
3480        let mm = vec![TokenBlockMmInfo {
3481            mm_hash: 0xAAu64,
3482            offset: 4,
3483            length: 2,
3484        }];
3485        let salt = TEST_SALT_HASH;
3486
3487        // Build expected bytes manually: each slot is 13 bytes.
3488        let mut expected = Vec::new();
3489        for &t in &[100u32, 101, 102, 103] {
3490            expected.push(MM_SLOT_TAG_TOKEN);
3491            expected.extend_from_slice(&t.to_le_bytes());
3492            expected.extend_from_slice(&0u64.to_le_bytes());
3493        }
3494        for run_off in 0u32..2 {
3495            expected.push(MM_SLOT_TAG_PLACEHOLDER);
3496            expected.extend_from_slice(&run_off.to_le_bytes());
3497            expected.extend_from_slice(&0xAAu64.to_le_bytes());
3498        }
3499        for &t in &[106u32, 107] {
3500            expected.push(MM_SLOT_TAG_TOKEN);
3501            expected.extend_from_slice(&t.to_le_bytes());
3502            expected.extend_from_slice(&0u64.to_le_bytes());
3503        }
3504        assert_eq!(expected.len(), 8 * 13);
3505
3506        // Validate helper output matches.
3507        let helper_bytes = compute_block_bytes_with_mm(&tokens, 0, &mm);
3508        assert_eq!(helper_bytes, expected, "MM-aware byte buffer mismatch");
3509
3510        // Validate block_hash equals XXH3 over the expected buffer.
3511        let expected_block_hash = compute_block_hash(&expected, salt);
3512        let seq = TokenBlockSequence::new_with_mm(tokens, &mm, 8, Some(salt)).unwrap();
3513        assert_eq!(seq.blocks().len(), 1);
3514        assert_eq!(seq.blocks()[0].block_hash(), expected_block_hash);
3515    }
3516
3517    /// #11b — collision regression. Reviewer P1: with the original 4/12 mixed encoding,
3518    /// `block_size=2` blocks `[MM(slot 0), token]` and `[token, MM(slot 1)]` could produce
3519    /// identical byte streams under chosen `mm_hash`/token values. With tagged 13-byte
3520    /// framing they MUST differ.
3521    #[test]
3522    fn tokens_mm_no_position_collision() {
3523        let salt = TEST_SALT_HASH;
3524        // Layout A: block_size=2, MM at slot 0, token at slot 1.
3525        let tokens_a = Tokens::from(vec![0u32, 0xAB]);
3526        let mm_a = vec![TokenBlockMmInfo {
3527            mm_hash: 0x1122_3344_5566_7788,
3528            offset: 0,
3529            length: 1,
3530        }];
3531        // Layout B: block_size=2, token at slot 0, MM at slot 1.
3532        let tokens_b = Tokens::from(vec![0xAB, 0u32]);
3533        let mm_b = vec![TokenBlockMmInfo {
3534            mm_hash: 0x1122_3344_5566_7788,
3535            offset: 1,
3536            length: 1,
3537        }];
3538
3539        let bytes_a = compute_block_bytes_with_mm(&tokens_a, 0, &mm_a);
3540        let bytes_b = compute_block_bytes_with_mm(&tokens_b, 0, &mm_b);
3541        assert_ne!(
3542            bytes_a, bytes_b,
3543            "tagged framing must distinguish slot kinds at different positions"
3544        );
3545
3546        let seq_a = TokenBlockSequence::new_with_mm(tokens_a, &mm_a, 2, Some(salt)).unwrap();
3547        let seq_b = TokenBlockSequence::new_with_mm(tokens_b, &mm_b, 2, Some(salt)).unwrap();
3548        assert_ne!(
3549            seq_a.blocks()[0].block_hash(),
3550            seq_b.blocks()[0].block_hash()
3551        );
3552    }
3553
3554    /// #11c — per-block legacy fallback. A block with no overlapping MM run uses the legacy
3555    /// 4-byte-per-slot encoding so its `block_hash` matches the existing zero-MM path. Block 0
3556    /// of an MM-bearing sequence (run starts in block 1) must equal block 0 of a no-MM sequence.
3557    #[test]
3558    fn tokens_mm_legacy_fallback_per_block() {
3559        let block_size: u32 = 4;
3560        let salt = Some(TEST_SALT_HASH);
3561        let raw = vec![1u32, 2, 3, 4, 5, 6, 7, 8];
3562        // MM run covers only block 1 (positions [4..7)).
3563        let mm = vec![TokenBlockMmInfo {
3564            mm_hash: 0xAB,
3565            offset: 4,
3566            length: 3,
3567        }];
3568        let seq_mm =
3569            TokenBlockSequence::new_with_mm(Tokens::from(raw.clone()), &mm, block_size, salt)
3570                .unwrap();
3571        let seq_plain = TokenBlockSequence::new(Tokens::from(raw), block_size, salt);
3572
3573        // Block 0 untouched by MM ⇒ identical hashes.
3574        assert_eq!(
3575            seq_mm.blocks()[0].block_hash(),
3576            seq_plain.blocks()[0].block_hash()
3577        );
3578        assert_eq!(
3579            seq_mm.blocks()[0].sequence_hash(),
3580            seq_plain.blocks()[0].sequence_hash()
3581        );
3582        // Block 1 IS MM-affected ⇒ hashes diverge.
3583        assert_ne!(
3584            seq_mm.blocks()[1].block_hash(),
3585            seq_plain.blocks()[1].block_hash()
3586        );
3587    }
3588
3589    /// Borrowed hashing matches `TokenBlockSequence` and keeps the legacy block hash
3590    /// for text windows on either side of an MM run.
3591    #[test]
3592    fn hash_complete_blocks_matches_sequence_around_mm_run() {
3593        let block_size: u32 = 4;
3594        let salt = TEST_SALT_HASH;
3595        // Three complete blocks. The MM run covers only the middle one.
3596        let raw = vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
3597        let mm = vec![TokenBlockMmInfo {
3598            mm_hash: 0xAB,
3599            offset: 4,
3600            length: 4,
3601        }];
3602
3603        let empty = hash_complete_blocks(&raw, &[], block_size, salt);
3604        let plain = TokenBlockSequence::new(Tokens::from(raw.clone()), block_size, Some(salt));
3605        assert_eq!(empty.len(), plain.blocks().len());
3606        assert_eq!(empty.len(), 3);
3607        for (lineage, block) in empty.iter().zip(plain.blocks().iter()) {
3608            assert_eq!(lineage.block_hash, block.block_hash());
3609            assert_eq!(lineage.sequence_hash, block.sequence_hash());
3610            assert_eq!(lineage.parent_sequence_hash, block.parent_sequence_hash());
3611            assert_eq!(
3612                lineage.positional_lineage_hash,
3613                block.positional_lineage_hash()
3614            );
3615        }
3616
3617        let lineages = hash_complete_blocks(&raw, &mm, block_size, salt);
3618        let seq_mm =
3619            TokenBlockSequence::new_with_mm(Tokens::from(raw.clone()), &mm, block_size, Some(salt))
3620                .unwrap();
3621        for (lineage, block) in lineages.iter().zip(seq_mm.blocks().iter()) {
3622            assert_eq!(lineage.block_hash, block.block_hash());
3623            assert_eq!(lineage.sequence_hash, block.sequence_hash());
3624            assert_eq!(lineage.parent_sequence_hash, block.parent_sequence_hash());
3625            assert_eq!(
3626                lineage.positional_lineage_hash,
3627                block.positional_lineage_hash()
3628            );
3629        }
3630
3631        // Text windows use the in-place token hash, including the window after the run.
3632        assert_eq!(
3633            lineages[0].block_hash,
3634            compute_block_hash_for_tokens(&raw[0..4], salt)
3635        );
3636        assert_eq!(
3637            lineages[2].block_hash,
3638            compute_block_hash_for_tokens(&raw[8..12], salt)
3639        );
3640        let mm_bytes = compute_block_bytes_with_mm(&raw[4..8], 4, &mm);
3641        assert_eq!(lineages[1].block_hash, compute_block_hash(&mm_bytes, salt));
3642        // The chain still carries the middle block, so the following sequence hash differs.
3643        assert_ne!(lineages[2].sequence_hash, plain.blocks()[2].sequence_hash());
3644    }
3645
3646    /// Tests cursor gate boundaries in `hash_complete_blocks` against ground-truth
3647    /// `compute_block_bytes_with_mm` buffer hashing:
3648    /// (a) run ending one slot into a block
3649    /// (b) run starting at a block's last slot
3650    /// (c) run ending exactly on a block boundary
3651    /// (d) adjacent runs.
3652    #[test]
3653    fn hash_complete_blocks_cursor_gate_boundaries() {
3654        let block_size: u32 = 4;
3655        let salt = TEST_SALT_HASH;
3656        let bs = block_size as usize;
3657        // 6 complete blocks (24 tokens)
3658        let tokens: Vec<Token> = (0..24).collect();
3659
3660        let verify_cases = |mm_runs: &[TokenBlockMmInfo]| {
3661            let lineages = hash_complete_blocks(&tokens, mm_runs, block_size, salt);
3662            let n_complete = tokens.len() / bs;
3663            assert_eq!(lineages.len(), n_complete);
3664
3665            for (position, lineage) in lineages.iter().enumerate() {
3666                let block_offset = position * bs;
3667                let block_tokens = &tokens[block_offset..block_offset + bs];
3668                let expected_bytes =
3669                    compute_block_bytes_with_mm(block_tokens, block_offset, mm_runs);
3670                let expected_hash = compute_block_hash(&expected_bytes, salt);
3671                assert_eq!(
3672                    lineage.block_hash,
3673                    expected_hash,
3674                    "Cursor gate block hash mismatch at block position {position} [offset {block_offset}..{}) run layout: {:?}",
3675                    block_offset + bs,
3676                    mm_runs
3677                );
3678            }
3679        };
3680
3681        // Case (a): run ending one slot into a block ([4..8) block, run [1..5))
3682        verify_cases(&[TokenBlockMmInfo {
3683            mm_hash: 0x0A,
3684            offset: 1,
3685            length: 4,
3686        }]);
3687
3688        // Case (b): run starting at a block's last slot ([4..8) block, run [7..10))
3689        verify_cases(&[TokenBlockMmInfo {
3690            mm_hash: 0x0B,
3691            offset: 7,
3692            length: 3,
3693        }]);
3694
3695        // Case (c): run ending exactly on a block boundary ([4..8) block, run [4..8))
3696        verify_cases(&[TokenBlockMmInfo {
3697            mm_hash: 0x0C,
3698            offset: 4,
3699            length: 4,
3700        }]);
3701
3702        // Case (d): adjacent runs ([4..8) and [8..12))
3703        verify_cases(&[
3704            TokenBlockMmInfo {
3705                mm_hash: 0x0D1,
3706                offset: 4,
3707                length: 4,
3708            },
3709            TokenBlockMmInfo {
3710                mm_hash: 0x0D2,
3711                offset: 8,
3712                length: 4,
3713            },
3714        ]);
3715    }
3716
3717    /// #11d — `offset + length` overflow is rejected as a dedicated error variant rather
3718    /// than panicking or silently wrapping.
3719    #[test]
3720    fn tokens_mm_validation_overflow() {
3721        let bad = vec![TokenBlockMmInfo {
3722            mm_hash: 1,
3723            offset: usize::MAX - 2,
3724            length: 10,
3725        }];
3726        let err = validate_and_sort_mm_info(&bad, usize::MAX).expect_err("must reject overflow");
3727        assert!(matches!(err, MmInfoError::OffsetOverflow { .. }));
3728    }
3729
3730    /// #12: building incrementally via push_token / push_mm_run yields the same sequence
3731    /// as the batch `new_with_mm` constructor.
3732    #[test]
3733    fn tokens_mm_streaming_equals_batch() {
3734        // Layout: [t,t,t,(MM=0xAA len=4),t,t] over block_size=4 ⇒ 2 blocks + partial.
3735        let tokens = Tokens::from(vec![1u32, 2, 3, 0, 0, 0, 0, 6, 7]);
3736        let mm = vec![TokenBlockMmInfo {
3737            mm_hash: 0xAAu64,
3738            offset: 3,
3739            length: 4,
3740        }];
3741        let salt = Some(TEST_SALT_HASH);
3742        let batch = TokenBlockSequence::new_with_mm(tokens, &mm, 4, salt).unwrap();
3743
3744        let mut streamed = TokenBlockSequence::new(Tokens::default(), 4, salt);
3745        streamed.push_token(1).unwrap();
3746        streamed.push_token(2).unwrap();
3747        streamed.push_token(3).unwrap();
3748        streamed.push_mm_run(0xAAu64, 4).unwrap();
3749        streamed.push_token(6).unwrap();
3750        streamed.push_token(7).unwrap();
3751
3752        assert_eq!(streamed.blocks().len(), batch.blocks().len());
3753        for (a, b) in streamed.blocks().iter().zip(batch.blocks().iter()) {
3754            assert_eq!(a.block_hash(), b.block_hash(), "block_hash mismatch");
3755            assert_eq!(a.sequence_hash(), b.sequence_hash(), "seq_hash mismatch");
3756            assert_eq!(
3757                a.positional_lineage_hash(),
3758                b.positional_lineage_hash(),
3759                "PLH mismatch"
3760            );
3761        }
3762        assert_eq!(streamed.mm_runs(), batch.mm_runs());
3763    }
3764
3765    /// #13: a multi-block MM run produces distinct block_hashes for blocks fully covered by
3766    /// the run (run_offset increases monotonically), and shares prefix hashes with another
3767    /// request whose run starts at the same global offset.
3768    #[test]
3769    fn tokens_mm_multi_block_run() {
3770        let block_size: u32 = 8;
3771        let bs = block_size as usize;
3772        // Run of length 2*bs + k = 20 starting at the boundary of block 0 ⇒ spans blocks 0,1,2.
3773        // Blocks 0 and 1 are fully placeholders; block 2 starts as 4 placeholders + 4 reals.
3774        let mut tokens_a: Vec<Token> = vec![0u32; 2 * bs]; // blocks 0, 1 (placeholders)
3775        tokens_a.extend_from_slice(&[0u32, 0, 0, 0, 100, 101, 102, 103]); // block 2
3776        let tokens_a = Tokens::from(tokens_a);
3777        let mm = vec![TokenBlockMmInfo {
3778            mm_hash: 0xCAFEBABEu64,
3779            offset: 0,
3780            length: 20,
3781        }];
3782        let seq_a = TokenBlockSequence::new_with_mm(
3783            tokens_a.clone(),
3784            &mm,
3785            block_size,
3786            Some(TEST_SALT_HASH),
3787        )
3788        .unwrap();
3789        assert_eq!(seq_a.blocks().len(), 3);
3790
3791        // Block 0 and block 1 are *both* fully placeholder, but with different run_offsets
3792        // (0..7 vs 8..15) → block_hashes must differ.
3793        let bh0 = seq_a.blocks()[0].block_hash();
3794        let bh1 = seq_a.blocks()[1].block_hash();
3795        assert_ne!(
3796            bh0, bh1,
3797            "fully-placeholder blocks at different run_offsets must hash differently"
3798        );
3799
3800        // Same image at the same global starting position in another request must share blocks.
3801        let seq_b =
3802            TokenBlockSequence::new_with_mm(tokens_a, &mm, block_size, Some(TEST_SALT_HASH))
3803                .unwrap();
3804        assert_eq!(
3805            seq_a.blocks()[0].block_hash(),
3806            seq_b.blocks()[0].block_hash()
3807        );
3808        assert_eq!(
3809            seq_a.blocks()[1].block_hash(),
3810            seq_b.blocks()[1].block_hash()
3811        );
3812        assert_eq!(
3813            seq_a.blocks()[2].block_hash(),
3814            seq_b.blocks()[2].block_hash()
3815        );
3816
3817        // A different mm_hash at the same position must diverge starting at block 0.
3818        let mm_diff = vec![TokenBlockMmInfo {
3819            mm_hash: 0xDEADBEEFu64,
3820            offset: 0,
3821            length: 20,
3822        }];
3823        let mut tokens_c: Vec<Token> = vec![0u32; 2 * bs];
3824        tokens_c.extend_from_slice(&[0u32, 0, 0, 0, 100, 101, 102, 103]);
3825        let seq_c = TokenBlockSequence::new_with_mm(
3826            Tokens::from(tokens_c),
3827            &mm_diff,
3828            block_size,
3829            Some(TEST_SALT_HASH),
3830        )
3831        .unwrap();
3832        assert_ne!(
3833            seq_a.blocks()[0].block_hash(),
3834            seq_c.blocks()[0].block_hash()
3835        );
3836    }
3837
3838    /// #14: mm_info validation rejects overlap, out-of-bounds, and zero-length runs.
3839    #[test]
3840    fn tokens_mm_validation() {
3841        let tokens = Tokens::from(vec![0u32; 32]);
3842        // Overlap.
3843        let overlap = vec![
3844            TokenBlockMmInfo {
3845                mm_hash: 1,
3846                offset: 0,
3847                length: 5,
3848            },
3849            TokenBlockMmInfo {
3850                mm_hash: 2,
3851                offset: 4,
3852                length: 5,
3853            },
3854        ];
3855        let err = TokenBlockSequence::new_with_mm(tokens.clone(), &overlap, 4, None).unwrap_err();
3856        assert!(matches!(
3857            err,
3858            TokenBlockError::MmInfo(MmInfoError::Overlapping { .. })
3859        ));
3860
3861        // Out-of-bounds.
3862        let oob = vec![TokenBlockMmInfo {
3863            mm_hash: 1,
3864            offset: 30,
3865            length: 10,
3866        }];
3867        let err = TokenBlockSequence::new_with_mm(tokens.clone(), &oob, 4, None).unwrap_err();
3868        assert!(matches!(
3869            err,
3870            TokenBlockError::MmInfo(MmInfoError::OutOfBounds { .. })
3871        ));
3872
3873        // Zero-length run.
3874        let empty = vec![TokenBlockMmInfo {
3875            mm_hash: 1,
3876            offset: 0,
3877            length: 0,
3878        }];
3879        let err = TokenBlockSequence::new_with_mm(tokens, &empty, 4, None).unwrap_err();
3880        assert!(matches!(
3881            err,
3882            TokenBlockError::MmInfo(MmInfoError::EmptyRun)
3883        ));
3884
3885        // push_mm_run with length 0.
3886        let mut seq = TokenBlockSequence::new(Tokens::default(), 4, None);
3887        let err = seq.push_mm_run(0xAB, 0).unwrap_err();
3888        assert!(matches!(
3889            err,
3890            TokenBlockError::MmInfo(MmInfoError::EmptyRun)
3891        ));
3892
3893        // truncate / pop / unwind blocked once mm_runs is non-empty.
3894        let mut seq = TokenBlockSequence::new(Tokens::from(vec![1u32, 2, 3]), 4, None);
3895        seq.push_mm_run(0xAB, 2).unwrap();
3896        assert!(matches!(
3897            seq.truncate(0).unwrap_err(),
3898            TokenBlockError::MmRunsPresent
3899        ));
3900        assert!(matches!(
3901            seq.unwind(1).unwrap_err(),
3902            TokenBlockError::MmRunsPresent
3903        ));
3904    }
3905}