picovolt 2.3.0

Embedded SQL database with MVCC history and single-file deployment
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
//! Application-owned full-text indexes over a consistent PicoVolt query result.
//!
//! Unicode alphanumeric tokens are lowercased; there is no stemming, accent
//! folding, phrase search, SQL MATCH syntax or automatic transaction tracking.
//! Queries require all distinct terms and rank with BM25 (k1=1.2, b=0.75).
//! Rebuild from a database snapshot after commits, then replace the old index.
//! Limits bound input and cardinality, not an exact allocator memory budget.

use crate::{QueryResult, Value};
use std::collections::{BTreeMap, BTreeSet};

const MAX_DOCUMENTS: usize = 10_000;
const MAX_DOCUMENT_BYTES: usize = 65_536;
const MAX_TOTAL_BYTES: usize = 8 * 1024 * 1024;
const MAX_TERMS: usize = 65_536;

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SearchError {
    #[error("full-text input exceeds its configured bounds")]
    Limit,
    #[error("expected unique integer document IDs and text columns")]
    InvalidRows,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SearchHit {
    pub id: i64,
    pub score: f64,
}

#[derive(Debug, Clone)]
struct Document {
    terms: BTreeMap<String, u32>,
    length: usize,
    bytes: usize,
}

/// A bounded in-memory inverted index. It never mutates the source database.
#[derive(Debug, Default)]
pub struct SearchIndex {
    documents: BTreeMap<i64, Document>,
    postings: BTreeMap<String, BTreeMap<i64, u32>>,
    total_tokens: usize,
    total_bytes: usize,
}

fn tokens(text: &str) -> Vec<String> {
    text.split(|c: char| !c.is_alphanumeric())
        .filter(|word| !word.is_empty() && word.len() <= 128)
        .map(str::to_lowercase)
        .collect()
}

impl SearchIndex {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn len(&self) -> usize {
        self.documents.len()
    }
    pub fn is_empty(&self) -> bool {
        self.documents.is_empty()
    }

    /// Insert or replace one document. Validation failure preserves the old one.
    pub fn upsert(&mut self, id: i64, text: &str) -> Result<(), SearchError> {
        let previous_bytes = self.documents.get(&id).map_or(0, |d| d.bytes);
        if text.len() > MAX_DOCUMENT_BYTES
            || self.total_bytes - previous_bytes + text.len() > MAX_TOTAL_BYTES
            || (!self.documents.contains_key(&id) && self.len() >= MAX_DOCUMENTS)
        {
            return Err(SearchError::Limit);
        }
        let words = tokens(text);
        let mut terms = BTreeMap::<String, u32>::new();
        for word in &words {
            *terms.entry(word.clone()).or_default() += 1;
        }
        if terms.len() > 4096
            || self.postings.len()
                + terms
                    .keys()
                    .filter(|t| !self.postings.contains_key(*t))
                    .count()
                > MAX_TERMS
        {
            return Err(SearchError::Limit);
        }
        self.remove(id);
        for (term, frequency) in &terms {
            self.postings
                .entry(term.clone())
                .or_default()
                .insert(id, *frequency);
        }
        self.total_tokens += words.len();
        self.total_bytes += text.len();
        self.documents.insert(
            id,
            Document {
                terms,
                length: words.len(),
                bytes: text.len(),
            },
        );
        Ok(())
    }

    pub fn remove(&mut self, id: i64) -> bool {
        let Some(document) = self.documents.remove(&id) else {
            return false;
        };
        self.total_tokens -= document.length;
        self.total_bytes -= document.bytes;
        for term in document.terms.keys() {
            if let Some(posting) = self.postings.get_mut(term) {
                posting.remove(&id);
                if posting.is_empty() {
                    self.postings.remove(term);
                }
            }
        }
        true
    }

    /// All-term matching, deterministic ranking; equal scores use ascending IDs.
    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<SearchHit>, SearchError> {
        if query.len() > 1024 || limit > 100 {
            return Err(SearchError::Limit);
        }
        let terms: BTreeSet<_> = tokens(query).into_iter().collect();
        if terms.len() > 32 {
            return Err(SearchError::Limit);
        }
        if terms.is_empty() || limit == 0 || self.total_tokens == 0 {
            return Ok(vec![]);
        }
        let mut lists = Vec::new();
        for term in terms {
            let Some(posting) = self.postings.get(&term) else {
                return Ok(vec![]);
            };
            lists.push(posting);
        }
        lists.sort_by_key(|posting| posting.len());
        let n = self.len() as f64;
        let average = self.total_tokens as f64 / n;
        let mut hits = Vec::new();
        for id in lists[0].keys() {
            let mut score = 0.0;
            let mut matches = true;
            for posting in &lists {
                let Some(frequency) = posting.get(id) else {
                    matches = false;
                    break;
                };
                let df = posting.len() as f64;
                let idf = (1.0 + (n - df + 0.5) / (df + 0.5)).ln();
                let tf = f64::from(*frequency);
                let length = self.documents[id].length as f64;
                score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / average));
            }
            if matches {
                hits.push(SearchHit { id: *id, score });
            }
        }
        hits.sort_by(|a, b| b.score.total_cmp(&a.score).then_with(|| a.id.cmp(&b.id)));
        hits.truncate(limit);
        Ok(hits)
    }

    /// Build from one SELECT result, using explicit column names.
    pub fn from_rows(
        result: &QueryResult,
        id_column: &str,
        text_columns: &[&str],
    ) -> Result<Self, SearchError> {
        let QueryResult::Rows { columns, rows } = result else {
            return Err(SearchError::InvalidRows);
        };
        if rows.len() > MAX_DOCUMENTS || text_columns.is_empty() || text_columns.len() > 16 {
            return Err(SearchError::Limit);
        }
        let id_index = columns
            .iter()
            .position(|c| c == id_column)
            .ok_or(SearchError::InvalidRows)?;
        let positions: Vec<_> = text_columns
            .iter()
            .map(|name| {
                columns
                    .iter()
                    .position(|c| c == name)
                    .ok_or(SearchError::InvalidRows)
            })
            .collect::<Result<_, _>>()?;
        let mut index = Self::new();
        for row in rows {
            let Some(Value::Int(id)) = row.get(id_index) else {
                return Err(SearchError::InvalidRows);
            };
            if index.documents.contains_key(id) {
                return Err(SearchError::InvalidRows);
            }
            let mut text = String::new();
            for position in &positions {
                let field = match row.get(*position) {
                    Some(Value::Text(value)) => value.as_str(),
                    Some(Value::Null) => "",
                    _ => return Err(SearchError::InvalidRows),
                };
                if text.len() + field.len() + 1 > MAX_DOCUMENT_BYTES {
                    return Err(SearchError::Limit);
                }
                text.push_str(field);
                text.push(' ');
            }
            index.upsert(*id, &text)?;
        }
        Ok(index)
    }
}

// PV23 binary codec and filtered-corpus execution. Legacy public search is unchanged.
impl SearchIndex {
    pub(crate) fn search_filtered(
        &self,
        query: &str,
        limit: usize,
        ids: &BTreeSet<i64>,
    ) -> Result<Vec<SearchHit>, SearchError> {
        if ids.len() > MAX_DOCUMENTS || ids.iter().any(|id| !self.documents.contains_key(id)) {
            return Err(SearchError::InvalidRows);
        }
        if ids.len() == self.len() {
            return self.search(query, limit);
        }
        if query.len() > 1024 || limit > 100 {
            return Err(SearchError::Limit);
        }
        let terms: BTreeSet<_> = tokens(query).into_iter().collect();
        if terms.len() > 32 {
            return Err(SearchError::Limit);
        }
        let total_tokens: usize = ids.iter().map(|id| self.documents[id].length).sum();
        if terms.is_empty() || limit == 0 || total_tokens == 0 {
            return Ok(Vec::new());
        }
        let mut lists = Vec::new();
        for term in terms {
            let Some(posting) = self.postings.get(&term) else {
                return Ok(Vec::new());
            };
            let frequency = posting.keys().filter(|id| ids.contains(id)).count();
            if frequency == 0 {
                return Ok(Vec::new());
            }
            lists.push((posting, frequency));
        }
        // Match the reference's stable frequency ordering, but over the SELECT
        // corpus, not global tenants. This also preserves floating addition order.
        lists.sort_by_key(|(_, frequency)| *frequency);
        let n = ids.len() as f64;
        let average = total_tokens as f64 / n;
        let mut hits = Vec::new();
        for id in lists[0].0.keys().filter(|id| ids.contains(id)) {
            let mut score = 0.0;
            let mut matches = true;
            for (posting, frequency) in &lists {
                let Some(tf) = posting.get(id) else {
                    matches = false;
                    break;
                };
                let df = *frequency as f64;
                let idf = (1.0 + (n - df + 0.5) / (df + 0.5)).ln();
                let tf = f64::from(*tf);
                let length = self.documents[id].length as f64;
                score += idf * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * length / average));
            }
            if matches {
                hits.push(SearchHit { id: *id, score });
            }
        }
        hits.sort_by(|a, b| b.score.total_cmp(&a.score).then_with(|| a.id.cmp(&b.id)));
        hits.truncate(limit);
        Ok(hits)
    }

    pub(crate) fn encode_persistent(&self) -> crate::Result<Vec<u8>> {
        use crate::persistent::Encoder;
        let entries: usize = self
            .documents
            .values()
            .map(|document| document.terms.len())
            .sum();
        if entries > 1_048_576 {
            return Err(crate::PvError::ResourceLimit(
                "persistent text term-entry limit exceeded".into(),
            ));
        }
        let mut out = Encoder::new();
        out.count(self.len())?;
        out.count(self.postings.len())?;
        out.count(self.total_tokens)?;
        out.count(self.total_bytes)?;
        for (id, document) in &self.documents {
            out.put(&id.to_le_bytes())?;
            out.count(document.length)?;
            out.count(document.bytes)?;
            out.count(document.terms.len())?;
            for (term, frequency) in &document.terms {
                out.count(term.len())?;
                out.put(term.as_bytes())?;
                out.put(&frequency.to_le_bytes())?;
            }
        }
        Ok(out.finish())
    }

    pub(crate) fn decode_persistent(bytes: &[u8]) -> crate::Result<Self> {
        use crate::persistent::{corrupt, Decoder};
        let mut input = Decoder::new(bytes)?;
        let count = input.count(MAX_DOCUMENTS)?;
        let expected_terms = input.count(MAX_TERMS)?;
        let expected_tokens = input.count(MAX_TOTAL_BYTES)?;
        let expected_bytes = input.count(MAX_TOTAL_BYTES)?;
        let mut index = Self::new();
        let mut last_id = None;
        let mut entries = 0usize;
        for _ in 0..count {
            let id = input.i64()?;
            if last_id.is_some_and(|previous| previous >= id) {
                return Err(corrupt("text IDs are not strictly ordered"));
            }
            last_id = Some(id);
            let length = input.count(MAX_DOCUMENT_BYTES)?;
            let source_bytes = input.count(MAX_DOCUMENT_BYTES)?;
            let count = input.count(4096)?;
            entries = entries
                .checked_add(count)
                .ok_or_else(|| corrupt("text term count overflow"))?;
            if entries > 1_048_576 || length > source_bytes {
                return Err(corrupt("text document budget or length mismatch"));
            }
            let mut terms = BTreeMap::new();
            let mut last_term = String::new();
            let mut total = 0usize;
            for _ in 0..count {
                let len = input.count(384)?;
                if len == 0 {
                    return Err(corrupt("empty encoded token"));
                }
                let term = std::str::from_utf8(input.take(len)?)
                    .map_err(|_| corrupt("token is not UTF-8"))?;
                if term <= last_term.as_str() {
                    return Err(corrupt("tokens are not strictly ordered"));
                }
                let frequency = input.count(MAX_DOCUMENT_BYTES)?;
                total = total
                    .checked_add(frequency)
                    .ok_or_else(|| corrupt("token frequency overflow"))?;
                if frequency == 0 || total > length {
                    return Err(corrupt("invalid token frequency"));
                }
                if !index.postings.contains_key(term) && index.postings.len() >= MAX_TERMS {
                    return Err(corrupt("corpus term limit"));
                }
                index
                    .postings
                    .entry(term.to_owned())
                    .or_default()
                    .insert(id, frequency as u32);
                terms.insert(term.to_owned(), frequency as u32);
                last_term = term.to_owned();
            }
            if total != length {
                return Err(corrupt("document token total mismatch"));
            }
            index.total_tokens = index
                .total_tokens
                .checked_add(length)
                .ok_or_else(|| corrupt("token total overflow"))?;
            index.total_bytes = index
                .total_bytes
                .checked_add(source_bytes)
                .ok_or_else(|| corrupt("source total overflow"))?;
            if index.total_tokens > expected_tokens || index.total_bytes > expected_bytes {
                return Err(corrupt("text corpus total mismatch"));
            }
            index.documents.insert(
                id,
                Document {
                    terms,
                    length,
                    bytes: source_bytes,
                },
            );
        }
        input.finish()?;
        if index.postings.len() != expected_terms
            || index.total_tokens != expected_tokens
            || index.total_bytes != expected_bytes
        {
            return Err(corrupt("text corpus metadata mismatch"));
        }
        Ok(index)
    }
}