second-brain-core 0.13.3

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

use anyhow::{Context, Result};
use lru::LruCache;
use tantivy::HasLen;
use tantivy::directory::error::{DeleteError, LockError, OpenReadError, OpenWriteError};
use tantivy::directory::{
    AntiCallToken, Directory, DirectoryLock, FileHandle, Lock, MmapDirectory, OwnedBytes,
    TerminatingWrite, WatchCallback, WatchHandle, WritePtr,
};

use super::{
    CHUNK_LEN, SealKeys, SealWriter, SealedReader, is_tmp_name, read_file, reseal_file,
    sealed_key_id, write_file,
};

/// Decrypted chunks kept per directory, shared by every file in it.
const CACHED_CHUNKS: usize = 64;
const META_FILE: &str = "meta.json";

/// A tantivy directory whose files are sealed at rest. Reads decrypt the
/// 64 KiB chunks they touch, through a small LRU shared by the directory's
/// files; files written before sealing are read as plaintext until
/// `reseal_all` seals them. Locks and change watching are those of an
/// `MmapDirectory` over the same path: lock files hold no content.
#[derive(Clone)]
pub struct SealedDirectory {
    root: PathBuf,
    keys: Arc<RwLock<SealKeys>>,
    cache: Arc<Mutex<LruCache<(u128, u64), Arc<[u8]>>>>,
    plain: MmapDirectory,
}

impl fmt::Debug for SealedDirectory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SealedDirectory({})", self.root.display())
    }
}

impl SealedDirectory {
    /// `root` must exist.
    pub fn open(root: &Path, keys: SealKeys) -> Result<Self> {
        let plain = MmapDirectory::open(root)
            .with_context(|| format!("opening tantivy directory {}", root.display()))?;
        let directory = Self {
            root: root.to_path_buf(),
            keys: Arc::new(RwLock::new(keys)),
            cache: Arc::new(Mutex::new(LruCache::new(
                NonZeroUsize::new(CACHED_CHUNKS).expect("nonzero"),
            ))),
            plain,
        };
        Ok(directory)
    }

    /// Opens the index's `meta.json`, when it has one, so keys that can't
    /// open the directory fail here with a `SealError` rather than inside
    /// tantivy, whose errors drop the cause.
    pub fn check_keys_open(&self) -> Result<()> {
        let meta = self.root.join(META_FILE);
        if meta.exists() {
            read_file(&meta, Some(&self.keys()), META_FILE)?;
        }
        Ok(())
    }

    /// Removes temporary files a crash left mid-write. Only the directory's
    /// one writer may call this: a reader beside a live writer would delete
    /// the file that writer is about to rename into place.
    pub fn remove_leftover_tmp_files(&self) -> Result<()> {
        for name in self.file_names()? {
            if is_tmp_name(&name) {
                let path = self.root.join(&name);
                fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
            }
        }
        Ok(())
    }

    pub fn keys(&self) -> SealKeys {
        self.keys
            .read()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Files written from now on are sealed under `keys`' current key.
    pub fn set_keys(&self, keys: SealKeys) {
        *self.keys.write().unwrap_or_else(PoisonError::into_inner) = keys;
    }

    /// Seals every plaintext file, and seals again every file sealed under
    /// another key than the current one; returns how many were rewritten.
    /// No `IndexWriter` may be open on the directory meanwhile: its garbage
    /// collection deleting a file mid-reseal would have the rename bring
    /// the file back.
    pub fn reseal_all(&self) -> Result<usize> {
        let keys = self.keys();
        let mut rewritten = 0;
        for name in self.file_names()? {
            if is_lock_name(&name) || is_tmp_name(&name) {
                continue;
            }
            match reseal_file(&self.root.join(&name), &keys, &name) {
                Ok(true) => rewritten += 1,
                Ok(false) => {}
                Err(e) if not_found(&e) => {}
                Err(e) => return Err(e),
            }
        }
        Ok(rewritten)
    }

    /// Names of files under `keys` other than the current one or not sealed,
    /// lock files left out.
    pub fn unsealed_files(&self) -> Result<Vec<String>> {
        let current = self.keys().current_id();
        let mut out = Vec::new();
        for name in self.file_names()? {
            if is_lock_name(&name) || is_tmp_name(&name) {
                continue;
            }
            if sealed_key_id(&self.root.join(&name))? != Some(current) {
                out.push(name);
            }
        }
        Ok(out)
    }

    fn file_names(&self) -> Result<Vec<String>> {
        let mut names = Vec::new();
        for entry in
            fs::read_dir(&self.root).with_context(|| format!("listing {}", self.root.display()))?
        {
            let entry = entry?;
            if entry.file_type()?.is_file()
                && let Some(name) = entry.file_name().to_str()
            {
                names.push(name.to_string());
            }
        }
        Ok(names)
    }

    fn name_of(path: &Path) -> io::Result<&str> {
        path.to_str()
            .ok_or_else(|| io::Error::new(ErrorKind::InvalidInput, "path is not utf-8"))
    }
}

fn is_lock_name(name: &str) -> bool {
    name.starts_with(".tantivy-") && name.ends_with(".lock")
}

fn not_found(error: &anyhow::Error) -> bool {
    error
        .chain()
        .filter_map(|e| e.downcast_ref::<io::Error>())
        .any(|e| e.kind() == ErrorKind::NotFound)
}

fn open_read_error(path: &Path, error: anyhow::Error) -> OpenReadError {
    if not_found(&error) {
        return OpenReadError::FileDoesNotExist(path.to_path_buf());
    }
    OpenReadError::wrap_io_error(io::Error::other(format!("{error:#}")), path.to_path_buf())
}

struct SealedHandle {
    reader: SealedReader,
    cache: Arc<Mutex<LruCache<(u128, u64), Arc<[u8]>>>>,
}

impl fmt::Debug for SealedHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "SealedHandle({:?})", self.reader)
    }
}

impl HasLen for SealedHandle {
    fn len(&self) -> usize {
        self.reader.len() as usize
    }
}

impl SealedHandle {
    fn chunk(&self, chunk: u64) -> io::Result<Arc<[u8]>> {
        let key = (self.reader.file_id(), chunk);
        if let Some(hit) = self
            .cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .get(&key)
        {
            return Ok(hit.clone());
        }
        let bytes: Arc<[u8]> = self
            .reader
            .read_chunk(chunk)
            .map_err(|e| io::Error::other(format!("{e:#}")))?
            .into();
        self.cache
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .put(key, bytes.clone());
        Ok(bytes)
    }
}

impl FileHandle for SealedHandle {
    fn read_bytes(&self, range: Range<usize>) -> io::Result<OwnedBytes> {
        if range.end > self.len() || range.start > range.end {
            return Err(io::Error::new(
                ErrorKind::InvalidInput,
                format!("range {range:?} is outside a file of {} bytes", self.len()),
            ));
        }
        if range.is_empty() {
            return Ok(OwnedBytes::empty());
        }
        let first = (range.start / CHUNK_LEN) as u64;
        let last = ((range.end - 1) / CHUNK_LEN) as u64;
        if first == last {
            let base = first as usize * CHUNK_LEN;
            let chunk = self.chunk(first)?;
            return Ok(OwnedBytes::new(chunk).slice(range.start - base..range.end - base));
        }
        let mut out = Vec::with_capacity(range.len());
        for chunk in first..=last {
            let base = chunk as usize * CHUNK_LEN;
            let bytes = self
                .reader
                .read_chunk(chunk)
                .map_err(|e| io::Error::other(format!("{e:#}")))?;
            let from = range.start.saturating_sub(base);
            let to = (range.end - base).min(bytes.len());
            out.extend_from_slice(&bytes[from..to]);
        }
        Ok(OwnedBytes::new(out))
    }
}

struct SealedFileWriter {
    writer: Option<SealWriter<BufWriter<File>>>,
}

impl Write for SealedFileWriter {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        self.writer
            .as_mut()
            .ok_or_else(|| io::Error::other("the file was already terminated"))?
            .write(data)
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.writer.as_mut() {
            Some(writer) => writer.flush(),
            None => Ok(()),
        }
    }
}

impl TerminatingWrite for SealedFileWriter {
    fn terminate_ref(&mut self, _: AntiCallToken) -> io::Result<()> {
        let writer = self
            .writer
            .take()
            .ok_or_else(|| io::Error::other("the file was already terminated"))?;
        let mut buffered = writer
            .finish()
            .map_err(|e| io::Error::other(format!("{e:#}")))?;
        buffered.flush()?;
        buffered
            .into_inner()
            .map_err(|e| e.into_error())?
            .sync_data()
    }
}

impl Directory for SealedDirectory {
    fn get_file_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>, OpenReadError> {
        let full = self.root.join(path);
        let name =
            Self::name_of(path).map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))?;
        match sealed_key_id(&full) {
            Ok(Some(_)) => {
                let reader = SealedReader::open(&full, &self.keys(), name)
                    .map_err(|e| open_read_error(path, e))?;
                Ok(Arc::new(SealedHandle {
                    reader,
                    cache: self.cache.clone(),
                }))
            }
            Ok(None) => self.plain.get_file_handle(path),
            Err(e) => Err(open_read_error(path, e)),
        }
    }

    fn delete(&self, path: &Path) -> Result<(), DeleteError> {
        fs::remove_file(self.root.join(path)).map_err(|e| {
            if e.kind() == ErrorKind::NotFound {
                DeleteError::FileDoesNotExist(path.to_path_buf())
            } else {
                DeleteError::IoError {
                    io_error: Arc::new(e),
                    filepath: path.to_path_buf(),
                }
            }
        })
    }

    fn exists(&self, path: &Path) -> Result<bool, OpenReadError> {
        Ok(self.root.join(path).exists())
    }

    fn open_write(&self, path: &Path) -> Result<WritePtr, OpenWriteError> {
        let full = self.root.join(path);
        let wrap = |e: io::Error| OpenWriteError::wrap_io_error(e, path.to_path_buf());
        let name = Self::name_of(path).map_err(wrap)?;
        let file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&full)
            .map_err(|e| {
                if e.kind() == ErrorKind::AlreadyExists {
                    OpenWriteError::FileAlreadyExists(path.to_path_buf())
                } else {
                    wrap(e)
                }
            })?;
        let writer = SealWriter::new(BufWriter::new(file), &self.keys(), name)
            .map_err(|e| wrap(io::Error::other(format!("{e:#}"))))?;
        Ok(BufWriter::new(Box::new(SealedFileWriter {
            writer: Some(writer),
        })))
    }

    fn atomic_read(&self, path: &Path) -> Result<Vec<u8>, OpenReadError> {
        let name =
            Self::name_of(path).map_err(|e| OpenReadError::wrap_io_error(e, path.to_path_buf()))?;
        read_file(&self.root.join(path), Some(&self.keys()), name)
            .map_err(|e| open_read_error(path, e))
    }

    fn atomic_write(&self, path: &Path, data: &[u8]) -> io::Result<()> {
        let name = Self::name_of(path)?;
        write_file(&self.root.join(path), Some(&self.keys()), name, data)
            .map_err(|e| io::Error::other(format!("{e:#}")))
    }

    fn sync_directory(&self) -> io::Result<()> {
        File::open(&self.root)?.sync_all()
    }

    fn acquire_lock(&self, lock: &Lock) -> Result<DirectoryLock, LockError> {
        self.plain.acquire_lock(lock)
    }

    fn watch(&self, watch_callback: WatchCallback) -> tantivy::Result<WatchHandle> {
        self.plain.watch(watch_callback)
    }
}

#[cfg(test)]
mod tests {
    use tantivy::collector::TopDocs;
    use tantivy::query::QueryParser;
    use tantivy::schema::{STORED, Schema, TEXT, Value};
    use tantivy::{Index, TantivyDocument, doc};

    use super::*;
    use crate::keys::KeyGuard;
    use crate::sealed::{SealError, SealKey, seal_error};

    fn keys(byte: u8) -> SealKeys {
        SealKeys::single(SealKey::from_bytes(KeyGuard::new([byte; 32])).unwrap())
    }

    fn schema() -> Schema {
        let mut builder = Schema::builder();
        builder.add_text_field("body", TEXT | STORED);
        builder.build()
    }

    fn write_docs(index: &Index, texts: &[&str]) {
        let body = index.schema().get_field("body").unwrap();
        let mut writer = index.writer::<TantivyDocument>(15_000_000).unwrap();
        for text in texts {
            writer.add_document(doc!(body => *text)).unwrap();
        }
        writer.commit().unwrap();
        writer.wait_merging_threads().unwrap();
    }

    fn search(index: &Index, query: &str) -> Vec<String> {
        let body = index.schema().get_field("body").unwrap();
        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let query = QueryParser::for_index(index, vec![body])
            .parse_query(query)
            .unwrap();
        searcher
            .search(&query, &TopDocs::with_limit(10).order_by_score())
            .unwrap()
            .into_iter()
            .map(|(_, address)| {
                let doc: TantivyDocument = searcher.doc(address).unwrap();
                doc.get_first(body).unwrap().as_str().unwrap().to_string()
            })
            .collect()
    }

    fn all_file_bytes(dir: &Path) -> Vec<u8> {
        let mut out = Vec::new();
        for entry in fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_file() {
                out.extend(fs::read(path).unwrap());
            }
        }
        out
    }

    #[test]
    fn an_index_in_a_sealed_directory_searches_and_keeps_no_plaintext() {
        let dir = tempfile::tempdir().unwrap();
        let sealed = SealedDirectory::open(dir.path(), keys(1)).unwrap();
        let index = Index::create(sealed, schema(), Default::default()).unwrap();
        let long = "harbour ".repeat(20_000);
        write_docs(
            &index,
            &[
                "the ferry timetable moved",
                "lighthouse keeper notes",
                &long,
            ],
        );
        assert_eq!(search(&index, "ferry"), vec!["the ferry timetable moved"]);
        assert_eq!(search(&index, "harbour").len(), 1);

        let bytes = all_file_bytes(dir.path());
        for needle in [&b"ferry"[..], b"lighthouse", b"harbour", b"segments"] {
            assert!(
                !bytes.windows(needle.len()).any(|w| w == needle),
                "{needle:?} on disk"
            );
        }

        let reopened = Index::open(SealedDirectory::open(dir.path(), keys(1)).unwrap()).unwrap();
        assert_eq!(
            search(&reopened, "lighthouse"),
            vec!["lighthouse keeper notes"]
        );
    }

    #[test]
    fn a_sealed_index_does_not_open_without_its_key() {
        let dir = tempfile::tempdir().unwrap();
        let index = Index::create(
            SealedDirectory::open(dir.path(), keys(2)).unwrap(),
            schema(),
            Default::default(),
        )
        .unwrap();
        write_docs(&index, &["ferry"]);
        drop(index);
        assert!(Index::open(MmapDirectory::open(dir.path()).unwrap()).is_err());
        let err = Index::open(SealedDirectory::open(dir.path(), keys(3)).unwrap()).unwrap_err();
        assert!(format!("{err:?}").contains("not held"), "{err:?}");
        let err = SealedDirectory::open(dir.path(), keys(3))
            .unwrap()
            .check_keys_open()
            .unwrap_err();
        assert!(
            matches!(seal_error(&err), Some(SealError::UnknownKey(_))),
            "{err:#}"
        );
        SealedDirectory::open(dir.path(), keys(2))
            .unwrap()
            .check_keys_open()
            .unwrap();
    }

    #[test]
    fn a_plaintext_index_is_read_then_sealed_in_place() {
        let dir = tempfile::tempdir().unwrap();
        let plain = Index::create(
            MmapDirectory::open(dir.path()).unwrap(),
            schema(),
            Default::default(),
        )
        .unwrap();
        write_docs(&plain, &["the ferry timetable moved"]);
        drop(plain);

        let sealed = SealedDirectory::open(dir.path(), keys(4)).unwrap();
        let index = Index::open(sealed.clone()).unwrap();
        assert_eq!(search(&index, "ferry").len(), 1);
        assert!(!sealed.unsealed_files().unwrap().is_empty());
        drop(index);
        assert!(sealed.reseal_all().unwrap() > 0);
        assert!(sealed.unsealed_files().unwrap().is_empty());
        let bytes = all_file_bytes(dir.path());
        assert!(!bytes.windows(5).any(|w| w == b"ferry"));
        let index = Index::open(SealedDirectory::open(dir.path(), keys(4)).unwrap()).unwrap();
        assert_eq!(search(&index, "ferry").len(), 1);
    }

    #[test]
    fn a_rotation_reseals_every_file_under_the_new_key() {
        let dir = tempfile::tempdir().unwrap();
        let old = || SealKey::from_bytes(KeyGuard::new([5; 32])).unwrap();
        let new = || SealKey::from_bytes(KeyGuard::new([6; 32])).unwrap();
        let sealed = SealedDirectory::open(dir.path(), SealKeys::single(old())).unwrap();
        let index = Index::create(sealed.clone(), schema(), Default::default()).unwrap();
        write_docs(&index, &["ferry"]);
        drop(index);

        sealed.set_keys(SealKeys::new(new(), vec![old()]));
        assert!(!sealed.unsealed_files().unwrap().is_empty());
        sealed.reseal_all().unwrap();
        assert!(sealed.unsealed_files().unwrap().is_empty());
        let index =
            Index::open(SealedDirectory::open(dir.path(), SealKeys::single(new())).unwrap())
                .unwrap();
        assert_eq!(search(&index, "ferry").len(), 1);
    }

    #[test]
    fn reads_across_chunk_boundaries_match_the_plaintext() {
        let dir = tempfile::tempdir().unwrap();
        let sealed = SealedDirectory::open(dir.path(), keys(7)).unwrap();
        let data: Vec<u8> = (0..3 * CHUNK_LEN + 11).map(|i| (i % 253) as u8).collect();
        let mut writer = sealed.open_write(Path::new("blob")).unwrap();
        writer.write_all(&data).unwrap();
        writer.terminate().unwrap();
        let handle = sealed.get_file_handle(Path::new("blob")).unwrap();
        assert_eq!(handle.len(), data.len());
        for range in [
            0..0,
            0..1,
            5..CHUNK_LEN + 3,
            CHUNK_LEN - 1..CHUNK_LEN,
            0..data.len(),
            2 * CHUNK_LEN..3 * CHUNK_LEN + 11,
        ] {
            assert_eq!(
                handle.read_bytes(range.clone()).unwrap().as_slice(),
                &data[range.clone()],
                "{range:?}"
            );
        }
        assert!(handle.read_bytes(0..data.len() + 1).is_err());
        assert!(matches!(
            sealed.open_write(Path::new("blob")),
            Err(OpenWriteError::FileAlreadyExists(_))
        ));
    }

    #[test]
    fn a_file_cut_short_fails_to_read() {
        let dir = tempfile::tempdir().unwrap();
        let sealed = SealedDirectory::open(dir.path(), keys(8)).unwrap();
        sealed
            .atomic_write(Path::new("meta.json"), &vec![b'x'; 2 * CHUNK_LEN])
            .unwrap();
        let path = dir.path().join("meta.json");
        let len = fs::metadata(&path).unwrap().len();
        let file = OpenOptions::new().write(true).open(&path).unwrap();
        file.set_len(len - (CHUNK_LEN as u64 + 16)).unwrap();
        let err = read_file(&path, Some(&keys(8)), "meta.json").unwrap_err();
        assert_eq!(seal_error(&err), Some(&SealError::Damaged));
        assert!(sealed.atomic_read(Path::new("meta.json")).is_err());
    }

    #[test]
    fn only_the_writer_removes_temporary_files_a_crash_left() {
        let dir = tempfile::tempdir().unwrap();
        fs::write(dir.path().join("meta.json.seal-tmp.00ff"), b"partial").unwrap();
        let sealed = SealedDirectory::open(dir.path(), keys(9)).unwrap();
        assert!(dir.path().join("meta.json.seal-tmp.00ff").exists());
        sealed.remove_leftover_tmp_files().unwrap();
        assert!(!dir.path().join("meta.json.seal-tmp.00ff").exists());
    }
}