lean-ctx-engine 3.12.12

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0

//! The unit read of a [`RootedUnitSource`]: the raw bytes of its descriptor
//! are grouped into UNITS of complete records (lines), and every unit — and
//! the SEAM between two units first — is admitted before any of its text
//! leaves this module. A caller receives only admitted, storable text; the
//! raw reads and the single admissions stay inside the crate.

use super::RootedUnitSource;
use crate::core::context_admission::cross_line::BOUNDED_REACH_BYTES;

/// Size of one raw read from the descriptor.
const READ_CHUNK_BYTES: usize = 64 * 1024;

/// Bounds of [`RootedUnitSource::admit_records`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnitBounds {
    /// Largest unit, and so the largest record: a record is never cut.
    pub unit_bytes: usize,
    /// How much of each unit next to a boundary is admitted once more as a
    /// seam. Raised to at least the bounded cross-line reach
    /// (`cross_line::BOUNDED_REACH_BYTES`) and capped at a quarter of
    /// `unit_bytes`: a half is at most twice its side, so a whole seam is at
    /// most one unit. A unit under four times the reach is refused
    /// ([`UnitRefusal::UnitAdmissionUnsupported`]).
    pub seam_side: usize,
    /// Most bytes read from the descriptor before the source is refused.
    pub max_total_bytes: u64,
}

/// Why [`RootedUnitSource::admit_records`] refused the source. Content-free.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnitRefusal {
    /// More than `max_total_bytes` were read.
    TooLarge,
    /// One record alone is above `unit_bytes`.
    RecordTooLarge,
    /// Admission withheld a unit or a seam, or delivered it for a reader only.
    Withheld,
    /// The active rules cannot be applied unit by unit.
    UnitAdmissionUnsupported,
    /// A read failed, a unit is not UTF-8 text, or the caller's sink failed.
    Unreadable,
}

impl RootedUnitSource {
    /// Read this source to its end in units of complete records and hand the
    /// admitted text of each unit, in file order, to `sink`.
    ///
    /// Each unit is admitted on its ORIGINAL bytes (`Self::admit_unit`),
    /// after the seam with the unit before it (`Self::admit_seam`). Only
    /// what may feed a derived store is handed out; any other outcome, of a
    /// seam as of a unit, refuses the whole source. On `Err` the caller must
    /// take over nothing `sink` has seen.
    pub fn admit_records(
        &mut self,
        bounds: UnitBounds,
        mut sink: impl FnMut(&str) -> Result<(), UnitRefusal>,
    ) -> Result<(), UnitRefusal> {
        let seam_side = seam_side(bounds)?;
        let mut units = Units {
            unit: Vec::new(),
            tail: Vec::new(),
            cap: bounds.unit_bytes,
            seam_side,
        };
        // `units.unit`: complete records not yet admitted. `record`: the
        // record being assembled. Both stay at or below the cap.
        let mut record = Vec::new();
        let mut chunk = vec![0_u8; READ_CHUNK_BYTES];
        let mut total = 0_u64;
        loop {
            let read = self
                .read_raw(&mut chunk)
                .map_err(|_| UnitRefusal::Unreadable)?;
            if read == 0 {
                break;
            }
            total += read as u64;
            if total > bounds.max_total_bytes {
                return Err(UnitRefusal::TooLarge);
            }
            let mut rest = &chunk[..read];
            // A record ends at a line feed. That byte never occurs inside a
            // multi-byte UTF-8 character, so a unit never divides a character.
            while let Some(newline) = rest.iter().position(|byte| *byte == b'\n') {
                let (head, tail) = rest.split_at(newline + 1);
                extend_record(&mut record, head, units.cap)?;
                close_record(self, &mut units, &mut record, &mut sink)?;
                rest = tail;
            }
            extend_record(&mut record, rest, units.cap)?;
        }
        // The last record may end without a line feed.
        close_record(self, &mut units, &mut record, &mut sink)?;
        admit_pending(self, &mut units, &mut sink)
    }
}

/// The seam side actually used: at least what the built-in rules can match
/// across a line end with a bound ([`BOUNDED_REACH_BYTES`]), at most a
/// quarter of a unit. The caller cannot turn the seam off: when a unit is
/// too small for a seam of that reach, unit admission does not apply.
fn seam_side(bounds: UnitBounds) -> Result<usize, UnitRefusal> {
    let most = bounds.unit_bytes / 4;
    if most < BOUNDED_REACH_BYTES {
        return Err(UnitRefusal::UnitAdmissionUnsupported);
    }
    Ok(bounds.seam_side.clamp(BOUNDED_REACH_BYTES, most))
}

/// The units being assembled.
struct Units {
    unit: Vec<u8>,
    /// The end of the last admitted unit: the earlier half of the next seam.
    tail: Vec<u8>,
    cap: usize,
    seam_side: usize,
}

fn extend_record(record: &mut Vec<u8>, bytes: &[u8], cap: usize) -> Result<(), UnitRefusal> {
    if record.len() + bytes.len() > cap {
        return Err(UnitRefusal::RecordTooLarge);
    }
    record.extend_from_slice(bytes);
    Ok(())
}

/// Move the finished `record` into the unit, admitting the unit first when
/// the record no longer fits into it.
fn close_record(
    reader: &RootedUnitSource,
    units: &mut Units,
    record: &mut Vec<u8>,
    sink: &mut impl FnMut(&str) -> Result<(), UnitRefusal>,
) -> Result<(), UnitRefusal> {
    if units.unit.len() + record.len() > units.cap {
        admit_pending(reader, units, sink)?;
    }
    units.unit.append(record);
    Ok(())
}

/// Admit the pending unit — first the seam with the unit before it, then the
/// unit — and hand the unit's admitted text to `sink`.
fn admit_pending(
    reader: &RootedUnitSource,
    units: &mut Units,
    sink: &mut impl FnMut(&str) -> Result<(), UnitRefusal>,
) -> Result<(), UnitRefusal> {
    if units.unit.is_empty() {
        return Ok(());
    }
    let bytes = std::mem::take(&mut units.unit);
    if !units.tail.is_empty() {
        let mut seam = std::mem::take(&mut units.tail);
        seam.extend_from_slice(seam_head(&bytes, units.seam_side));
        let seam = reader.admit_seam(seam).map_err(|error| refusal(&error))?;
        if !seam.storable {
            return Err(UnitRefusal::Withheld);
        }
    }
    units.tail = seam_tail(&bytes, units.seam_side).to_vec();
    let unit = reader.admit_unit(bytes).map_err(|error| refusal(&error))?;
    if !unit.storable {
        return Err(UnitRefusal::Withheld);
    }
    sink(&unit.content)
}

/// The end of a unit for a seam: at least its last `side` bytes, extended
/// back to the start of the record they begin in — complete records, so a
/// line anchor sees what it sees in the file. When that would be more than
/// twice `side` (one long record), the last `side` bytes instead, moved
/// forward to a character boundary (at most three bytes less).
fn seam_tail(unit: &[u8], side: usize) -> &[u8] {
    if unit.len() <= side {
        return unit;
    }
    let start = unit.len() - side;
    let record = unit[..start]
        .iter()
        .rposition(|byte| *byte == b'\n')
        .map_or(0, |newline| newline + 1);
    if unit.len() - record <= 2 * side {
        return &unit[record..];
    }
    let mut start = start;
    while start < unit.len() && unit[start] & 0xC0 == 0x80 {
        start += 1;
    }
    &unit[start..]
}

/// The start of a unit for a seam: at least its first `side` bytes, extended
/// to the end of the record they end in. When that would be more than twice
/// `side`, the first `side` bytes instead, moved back to a character boundary.
fn seam_head(unit: &[u8], side: usize) -> &[u8] {
    if unit.len() <= side {
        return unit;
    }
    let record = unit[side - 1..]
        .iter()
        .position(|byte| *byte == b'\n')
        .map_or(unit.len(), |newline| side + newline);
    if record <= 2 * side {
        return &unit[..record];
    }
    let mut end = side;
    while end > 0 && unit[end] & 0xC0 == 0x80 {
        end -= 1;
    }
    &unit[..end]
}

/// The typed refusal of an admission error: unit admission not applicable,
/// withheld by a rule, or not readable.
fn refusal(error: &std::io::Error) -> UnitRefusal {
    match error.kind() {
        std::io::ErrorKind::Unsupported => UnitRefusal::UnitAdmissionUnsupported,
        std::io::ErrorKind::PermissionDenied => UnitRefusal::Withheld,
        _ => UnitRefusal::Unreadable,
    }
}

#[cfg(test)]
mod tests {
    use super::{BOUNDED_REACH_BYTES, UnitBounds, UnitRefusal, seam_head, seam_side, seam_tail};

    fn bounds(unit_bytes: usize, seam_side: usize) -> UnitBounds {
        UnitBounds {
            unit_bytes,
            seam_side,
            max_total_bytes: u64::MAX,
        }
    }

    #[test]
    fn the_caller_cannot_shrink_or_disable_the_seam() {
        let unit = 64 * BOUNDED_REACH_BYTES;
        // Zero, or anything under the reach, is raised to the reach.
        assert_eq!(seam_side(bounds(unit, 0)), Ok(BOUNDED_REACH_BYTES));
        assert_eq!(seam_side(bounds(unit, 1)), Ok(BOUNDED_REACH_BYTES));
        // Above a quarter of the unit it is capped there.
        assert_eq!(seam_side(bounds(unit, usize::MAX)), Ok(unit / 4));
        assert_eq!(
            seam_side(bounds(unit, 2 * BOUNDED_REACH_BYTES)),
            Ok(2 * BOUNDED_REACH_BYTES)
        );
        // Smallest read cap: a side is exactly the reach.
        assert_eq!(
            seam_side(bounds(4 * BOUNDED_REACH_BYTES, 0)),
            Ok(BOUNDED_REACH_BYTES)
        );
    }

    #[test]
    fn a_unit_too_small_for_a_seam_is_refused() {
        for unit in [0, 3, 4 * BOUNDED_REACH_BYTES - 1] {
            assert_eq!(
                seam_side(bounds(unit, BOUNDED_REACH_BYTES)),
                Err(UnitRefusal::UnitAdmissionUnsupported),
                "unit {unit}"
            );
        }
    }

    #[test]
    fn seams_take_whole_records_up_to_twice_the_side() {
        let unit = b"aaaa\nbbbb\ncccc\n";
        assert_eq!(seam_tail(unit, 5), b"cccc\n");
        assert_eq!(seam_head(unit, 5), b"aaaa\n");
        assert_eq!(seam_tail(unit, 64), unit);
        assert_eq!(seam_head(unit, 64), unit);
    }

    #[test]
    fn a_long_record_is_cut_at_a_character_boundary() {
        let unit = "x".repeat(10) + &"é".repeat(10);
        let tail = seam_tail(unit.as_bytes(), 3);
        assert!(std::str::from_utf8(tail).is_ok() && tail.len() <= 3);
        let unit = "é".repeat(10) + "\n";
        let head = seam_head(unit.as_bytes(), 3);
        assert!(std::str::from_utf8(head).is_ok() && head.len() <= 3);
    }
}