aft-store 0.68.1

On-disk index formats for Agent Foundational Toolkit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! The text plane's sections in a segment.
//!
//! | Section | Holds |
//! |---|---|
//! | text units | a unit table: each content key in ascending order; a content's ordinal is its position |
//! | text unit data | per content: byte length (u64), distinct trigram count (u32), status (u8) |
//! | trigram lookup | a lookup table: each trigram to its posting list |
//! | trigram postings | posting lists of content ordinals, each entry with its next-character mask (u8) |
//!
//! A content that is not indexed (binary, or too large) has a unit and no
//! postings, so readers know to verify it directly.

use std::collections::BTreeMap;

use crate::ids::{ContentKey, Digest128};
use crate::postings::{PostingCursor, PostingLayout, PostingsBuilder, Width};
use crate::segment::{
    Alignment, ErrorKind, KeySpace, KnownSection, Requirement, SectionHandle, SectionId,
    SectionKind, SectionSpec, Segment, SegmentError, SegmentWriter,
};
use crate::table::{
    LookupTable, LookupTableBuilder, UnitLocation, UnitTable, UnitTableBuilder, UnitTableParts,
};

use super::trigrams::ContentTrigrams;

const UNITS: SectionKind = SectionKind::new(0x0100);
const UNIT_DATA: SectionKind = SectionKind::new(0x0101);
const TRIGRAM_LOOKUP: SectionKind = SectionKind::new(0x0102);
const TRIGRAM_POSTINGS: SectionKind = SectionKind::new(0x0103);
const VERSION: u16 = 1;
const KEY_SPACE: KeySpace = KeySpace::new(0);
const UNIT_DATA_LEN: usize = 13;
const UNIT_DATA_LEN_U32: u32 = 13;

/// The text sections this build reads.
pub const KNOWN: [KnownSection; 4] = [
    KnownSection {
        kind: UNITS,
        version: VERSION,
    },
    KnownSection {
        kind: UNIT_DATA,
        version: VERSION,
    },
    KnownSection {
        kind: TRIGRAM_LOOKUP,
        version: VERSION,
    },
    KnownSection {
        kind: TRIGRAM_POSTINGS,
        version: VERSION,
    },
];

fn posting_layout() -> PostingLayout {
    PostingLayout::new(&[Width::U8])
}

/// Whether a content's trigrams are indexed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TextStatus {
    Indexed,
    /// Holds binary data. Grep reads it only if asked to.
    Binary,
    /// Larger than the indexing limit; verified by reading it.
    Oversize,
}

impl TextStatus {
    const fn code(self) -> u8 {
        match self {
            Self::Indexed => 0,
            Self::Binary => 1,
            Self::Oversize => 2,
        }
    }

    const fn from_code(code: u8) -> Option<Self> {
        match code {
            0 => Some(Self::Indexed),
            1 => Some(Self::Binary),
            2 => Some(Self::Oversize),
            _ => None,
        }
    }
}

/// What the text plane records about one content.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct TextUnit {
    pub len: u64,
    /// Distinct trigrams; the lexical score of `aft_search` divides by it.
    pub distinct: u32,
    pub status: TextStatus,
}

/// Collects contents for the text sections of one segment.
#[derive(Debug, Default)]
pub struct TextSectionsBuilder {
    units: BTreeMap<ContentKey, (TextUnit, Vec<(u32, u8)>)>,
}

impl crate::heap::HeapBytes for TextSectionsBuilder {
    fn heap_bytes(&self, _seen: &mut crate::heap::Seen) -> usize {
        let entry =
            std::mem::size_of::<ContentKey>() + std::mem::size_of::<(TextUnit, Vec<(u32, u8)>)>();
        crate::heap::btree_bytes(self.units.len(), entry)
            + self
                .units
                .values()
                .map(|(_, trigrams)| trigrams.capacity() * std::mem::size_of::<(u32, u8)>())
                .sum::<usize>()
    }
}

impl TextSectionsBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an indexed content. Adding a content twice keeps the first.
    pub fn add_indexed(&mut self, key: ContentKey, len: u64, trigrams: &ContentTrigrams) {
        let unit = TextUnit {
            len,
            distinct: u32::try_from(trigrams.distinct()).unwrap_or(u32::MAX),
            status: TextStatus::Indexed,
        };
        self.units
            .entry(key)
            .or_insert_with(|| (unit, trigrams.entries().to_vec()));
    }

    /// Adds a content whose trigrams are not indexed.
    pub fn add_unindexed(&mut self, key: ContentKey, len: u64, status: TextStatus) {
        debug_assert_ne!(status, TextStatus::Indexed);
        let unit = TextUnit {
            len,
            distinct: 0,
            status,
        };
        self.units.entry(key).or_insert((unit, Vec::new()));
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.units.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.units.is_empty()
    }

    /// Keeps only the contents `keep` accepts: a build leaves out those
    /// another segment of the family already holds.
    pub fn retain(&mut self, mut keep: impl FnMut(ContentKey) -> bool) {
        self.units.retain(|key, _| keep(*key));
    }

    /// Writes the four sections into `writer`.
    ///
    /// # Errors
    ///
    /// When a write fails.
    pub fn write(self, writer: &mut SegmentWriter) -> Result<(), SegmentError> {
        let mut table = UnitTableBuilder::new(Digest128::LEN);
        let mut data = Vec::with_capacity(self.units.len() * UNIT_DATA_LEN);
        let mut lists = BTreeMap::<u32, (Vec<u32>, Vec<u32>)>::new();
        for (key, (unit, trigrams)) in self.units {
            let ordinal = table.push(
                key.digest().as_bytes(),
                UnitLocation {
                    offset: data.len() as u64,
                    len: UNIT_DATA_LEN_U32,
                },
            );
            push_unit_data(&mut data, unit);
            for (trigram, mask) in trigrams {
                let (ordinals, masks) = lists.entry(trigram).or_default();
                ordinals.push(ordinal);
                masks.push(u32::from(mask));
            }
        }
        let mut postings = PostingsBuilder::new(posting_layout());
        let mut lookup = LookupTableBuilder::new();
        for (trigram, (ordinals, masks)) in lists {
            let list = postings.add_list(&ordinals, &[&masks]);
            lookup.push(u64::from(trigram), list);
        }
        let (table, units) = table.finish();
        writer.write_section(spec(UNITS), &table, units)?;
        writer.write_section(spec(UNIT_DATA), &data, units)?;
        let (lookup, keys) = lookup.finish();
        writer.write_section(spec(TRIGRAM_LOOKUP), &lookup, keys)?;
        let (postings, entries) = postings.finish();
        writer.write_section(spec(TRIGRAM_POSTINGS), &postings, entries)
    }
}

fn push_unit_data(data: &mut Vec<u8>, unit: TextUnit) {
    data.extend_from_slice(&unit.len.to_le_bytes());
    data.extend_from_slice(&unit.distinct.to_le_bytes());
    data.push(unit.status.code());
}

/// Where a folded segment's text unit comes from.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TextCopy {
    /// The unit at `ordinal` of the source segment at `source`, with its
    /// postings.
    Stored { source: usize, ordinal: u32 },
    /// A content whose trigrams are not indexed: its unit alone, with the
    /// length and status a segment holding it records.
    Unindexed { len: u64, status: TextStatus },
}

/// Writes into `writer` the text sections of a segment holding `units`,
/// copied from `sources` without reading any content again: the same
/// sections a [`TextSectionsBuilder`] holding the same units writes (see
/// `crate::fold`). `units` must be in strictly ascending key order.
///
/// # Errors
///
/// When a read or a write fails, or a source's sections are malformed.
///
/// # Panics
///
/// When `units` is not in strictly ascending key order, names a source
/// that is not in `sources`, or an ordinal past its source's units.
pub fn write_folded(
    writer: &mut SegmentWriter,
    sources: &[TextSegment<'_>],
    units: &[(ContentKey, TextCopy)],
) -> Result<(), SegmentError> {
    let mut renumbered = sources
        .iter()
        .map(|source| vec![crate::fold::NOT_COPIED; source.len() as usize])
        .collect::<Vec<_>>();
    let count = u32::try_from(units.len()).expect("a text table holds fewer than 2^32 units");
    writer.begin_section(spec(UNITS))?;
    writer.write(&(Digest128::LEN as u16).to_le_bytes())?;
    writer.write(&[0, 0])?;
    writer.write(&count.to_le_bytes())?;
    let mut previous = None;
    for (ordinal, (key, copy)) in units.iter().enumerate() {
        assert!(
            previous.is_none_or(|old| old < *key),
            "unit keys must be strictly ascending"
        );
        previous = Some(*key);
        writer.write(key.digest().as_bytes())?;
        writer.write(&((ordinal * UNIT_DATA_LEN) as u64).to_le_bytes())?;
        writer.write(&UNIT_DATA_LEN_U32.to_le_bytes())?;
        if let TextCopy::Stored {
            source,
            ordinal: old,
        } = *copy
        {
            renumbered[source][old as usize] = ordinal as u32;
        }
    }
    writer.end_section(u64::from(count))?;
    writer.begin_section(spec(UNIT_DATA))?;
    for (_, copy) in units {
        let unit = match *copy {
            TextCopy::Stored { source, ordinal } => sources[source].unit(ordinal)?,
            TextCopy::Unindexed { len, status } => {
                debug_assert_ne!(status, TextStatus::Indexed);
                TextUnit {
                    len,
                    distinct: 0,
                    status,
                }
            }
        };
        let mut data = Vec::with_capacity(UNIT_DATA_LEN);
        push_unit_data(&mut data, unit);
        writer.write(&data)?;
    }
    writer.end_section(u64::from(count))?;
    let postings = sources
        .iter()
        .zip(&renumbered)
        .map(|(source, renumbered)| crate::fold::PostingSource {
            segment: source.segment,
            lookup: LookupTable::reopen(source.segment, source.lookup.section()),
            postings: source.postings,
            renumbered,
        })
        .collect::<Vec<_>>();
    crate::fold::write_postings(
        writer,
        spec(TRIGRAM_POSTINGS),
        spec(TRIGRAM_LOOKUP),
        &posting_layout(),
        &postings,
    )
}

fn spec(kind: SectionKind) -> SectionSpec {
    SectionSpec {
        id: SectionId::new(kind, KEY_SPACE),
        version: VERSION,
        alignment: Alignment::Word,
        requirement: Requirement::Required,
    }
}

/// The text sections of one open segment.
#[derive(Debug)]
pub struct TextSegment<'s> {
    segment: &'s Segment,
    units: UnitTable<'s>,
    data: SectionHandle,
    lookup: LookupTable<'s>,
    postings: SectionHandle,
}

/// A segment's text sections as [`TextSegment::open`] found and checked
/// them, kept without the segment so a reader that holds the segment can
/// rebuild the [`TextSegment`] for each query without reading it again
/// (see [`TextSegment::with_sections`]).
#[derive(Clone, Copy, Debug)]
pub struct TextSections {
    units: UnitTableParts,
    data: SectionHandle,
    lookup: SectionHandle,
    postings: SectionHandle,
}

impl<'s> TextSegment<'s> {
    /// The segment's text sections, or `None` when it has none.
    ///
    /// # Errors
    ///
    /// When the segment has only some of them, or they are malformed.
    pub fn open(segment: &'s Segment) -> Result<Option<Self>, SegmentError> {
        let handles = [UNITS, UNIT_DATA, TRIGRAM_LOOKUP, TRIGRAM_POSTINGS]
            .map(|kind| segment.section(SectionId::new(kind, KEY_SPACE)));
        let [Some(units), Some(data), Some(lookup), Some(postings)] = handles else {
            if handles.iter().any(Option::is_some) {
                return Err(SegmentError::new(
                    segment.path(),
                    ErrorKind::Malformed("a segment has only some text sections"),
                ));
            }
            return Ok(None);
        };
        let units = UnitTable::open(segment, units)?;
        if segment.info(data).len != u64::from(units.len()) * UNIT_DATA_LEN as u64 {
            return Err(SegmentError::new(
                segment.path(),
                ErrorKind::Malformed("text unit data does not match the unit table"),
            ));
        }
        Ok(Some(Self {
            segment,
            units,
            data,
            lookup: LookupTable::open(segment, lookup)?,
            postings,
        }))
    }

    /// What [`Self::open`] found and checked.
    #[must_use]
    pub fn sections(&self) -> TextSections {
        TextSections {
            units: self.units.parts(),
            data: self.data,
            lookup: self.lookup.section(),
            postings: self.postings,
        }
    }

    /// The text sections of `segment`, from what [`Self::sections`] took
    /// from the same segment, without reading or checking them again.
    ///
    /// `sections` must come from `segment` itself: a section handle panics
    /// on any other segment.
    #[must_use]
    pub fn with_sections(segment: &'s Segment, sections: TextSections) -> Self {
        Self {
            segment,
            units: UnitTable::attach(segment, sections.units),
            data: sections.data,
            lookup: LookupTable::reopen(segment, sections.lookup),
            postings: sections.postings,
        }
    }

    /// How many contents the segment holds.
    #[must_use]
    pub fn len(&self) -> u32 {
        self.units.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.units.is_empty()
    }

    /// The content key of every unit, in ordinal order.
    ///
    /// # Errors
    ///
    /// When a read fails.
    pub fn keys(&self) -> Result<Vec<ContentKey>, SegmentError> {
        (0..self.units.len())
            .map(|ordinal| {
                let (key, _) = self.units.entry(ordinal)?;
                let bytes = <[u8; Digest128::LEN]>::try_from(key.as_slice())
                    .map_err(|_| self.malformed("a text unit key is not a content key"))?;
                Ok(ContentKey::from_digest(Digest128::from_bytes(bytes)))
            })
            .collect()
    }

    /// What the segment records about the content at `ordinal`.
    ///
    /// # Errors
    ///
    /// When a read fails or the record is malformed.
    pub fn unit(&self, ordinal: u32) -> Result<TextUnit, SegmentError> {
        let mut bytes = [0; UNIT_DATA_LEN];
        self.segment.read(
            self.data,
            u64::from(ordinal) * UNIT_DATA_LEN as u64,
            &mut bytes,
        )?;
        let status = TextStatus::from_code(bytes[12])
            .ok_or_else(|| self.malformed("unknown text status"))?;
        Ok(TextUnit {
            len: crate::le::u64_at(&bytes, 0),
            distinct: crate::le::u32_at(&bytes, 8),
            status,
        })
    }

    /// How many contents hold `trigram`.
    ///
    /// # Errors
    ///
    /// When a read fails.
    pub fn count(&self, trigram: u32) -> Result<u32, SegmentError> {
        Ok(self
            .lookup
            .get(u64::from(trigram))?
            .map_or(0, |list| list.count))
    }

    /// The ordinals in `within` (ascending) whose content holds `trigram`
    /// followed by a byte in `next` (zero: by anything), ascending.
    ///
    /// # Errors
    ///
    /// When a read fails or a posting block is malformed.
    pub fn ordinals(
        &self,
        trigram: u32,
        next: u8,
        within: &[u32],
    ) -> Result<Vec<u32>, SegmentError> {
        let Some(list) = self.lookup.get(u64::from(trigram))? else {
            return Ok(Vec::new());
        };
        let mut cursor = PostingCursor::new(self.segment, self.postings, posting_layout(), list);
        let mut found = Vec::new();
        let mut wanted = within.iter().copied().peekable();
        while let Some(&target) = wanted.peek() {
            cursor.skip_below(target)?;
            let Some(block) = cursor.next_block()? else {
                break;
            };
            let masks = &block.columns[0];
            for (ordinal, mask) in block.ordinals.iter().zip(masks) {
                while wanted.peek().is_some_and(|target| target < ordinal) {
                    wanted.next();
                }
                if wanted.peek() == Some(ordinal) {
                    if next == 0 || u32::from(next) & mask != 0 {
                        found.push(*ordinal);
                    }
                    wanted.next();
                }
            }
        }
        Ok(found)
    }

    /// Every ordinal whose content holds `trigram`, ascending: the whole
    /// posting list, for a caller that holds most of the segment's contents.
    ///
    /// # Errors
    ///
    /// When a read fails or a posting block is malformed.
    pub fn all_ordinals(&self, trigram: u32) -> Result<Vec<u32>, SegmentError> {
        let Some(list) = self.lookup.get(u64::from(trigram))? else {
            return Ok(Vec::new());
        };
        let mut found = Vec::with_capacity(list.count as usize);
        let mut cursor = PostingCursor::new(self.segment, self.postings, posting_layout(), list);
        while let Some(block) = cursor.next_block()? {
            found.extend_from_slice(&block.ordinals);
        }
        Ok(found)
    }

    fn malformed(&self, reason: &'static str) -> SegmentError {
        SegmentError::new(self.segment.path(), ErrorKind::Malformed(reason))
    }
}

crate::heap_bytes_none!(TextSections);