second-brain-core 0.13.1

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
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use fastembed::{RerankInitOptions, RerankerModel, TextRerank};

use super::onnx_rerank::{self, OnnxReranker, OnnxSessionConfig};
use crate::model_cache::model_cache_dir;
use crate::session_pool::SessionPool;

const DEFAULT_CHECKOUT_TIMEOUT: Duration = Duration::from_secs(30);

/// evals/rerank-cost-curve.md: at every fuse_top, 1024-char documents track
/// untruncated cross-encoder scores within 1-2 points of MRR while being
/// 15-60% faster, so this is the default budget rather than "no truncation".
const DEFAULT_DOC_CHARS: usize = 1024;

/// Cross-encoder reranker backed by a fixed pool of independent sessions.
/// Both backends' underlying session types take `&mut self` to run
/// inference, so serving concurrent queries means N loaded sessions rather
/// than one behind a shared lock. Each slot keeps the original lazy-load/
/// idle-unload lifecycle independently, so one query going cold does not
/// force every other slot to reload.
pub struct Reranker {
    pool: Arc<SessionPool<RerankSession>>,
    checkout_timeout: Duration,
    model_name: RerankerModel,
    ep: RerankEp,
    max_length: Option<usize>,
    doc_chars: Option<usize>,
    backend: RerankBackend,
    intra_threads: usize,
    inter_threads: usize,
}

/// One loaded rerank session. `fastembed::TextRerank::rerank` and
/// `ort::session::Session::run` both require exclusive (`&mut`) access, so a
/// pool slot holds exactly one of these at a time regardless of backend.
enum RerankSession {
    FastEmbed(TextRerank),
    Onnx(OnnxReranker),
}

/// `fastembed::TextRerank` hardcodes its session's intra-op thread count to
/// `available_parallelism()` with no override in its public API (see
/// `fastembed-5.13.4/src/reranking/impl.rs`), so a pool of N fastembed
/// sessions asks the OS for N times the machine's core count and the
/// sessions fight each other instead of scaling. The `onnx` backend owns its
/// `ort::session::Session` directly and caps `intra_threads` per the pool
/// size instead. `fastembed` stays available as an escape hatch via
/// `SECOND_BRAIN_RERANK_BACKEND=fastembed`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RerankBackend {
    Onnx,
    FastEmbed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RerankEp {
    Cpu,
    Cuda,
}

/// Returned when every session in the pool is still busy past the checkout
/// timeout. Backpressure that surfaces as an error beats a request that
/// hangs forever. A `RerankScorer` that is not a local pool (a remote
/// service shedding load or timing out) returns it too, with `pool_size` 0,
/// because it is the one error `Retriever::rank` degrades on rather than
/// propagating.
#[derive(Debug)]
pub struct RerankTimeoutError {
    pub waited: Duration,
    pub pool_size: usize,
}

impl std::fmt::Display for RerankTimeoutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "timed out after {:?} waiting for an idle rerank session (pool size {})",
            self.waited, self.pool_size
        )
    }
}

impl std::error::Error for RerankTimeoutError {}

/// What `Retriever::rank` needs from a cross-encoder: one score per document,
/// in document order, on the 0..1 scale `RetrievalTunables::rerank_gate` is
/// calibrated against (the sigmoid of the raw logit, which is what `Reranker`
/// returns). A scorer that cannot answer right now must return
/// `RerankTimeoutError`, directly or under anyhow context, so the query falls
/// back to the cosine-gated path instead of failing.
pub trait RerankScorer: Send + Sync {
    fn rerank(&self, query: &str, documents: &[&str]) -> Result<Vec<f32>>;
}

/// Snapshot of pool utilization for capacity planning.
#[derive(Debug, Clone, Copy, Default)]
pub struct RerankMetricsSnapshot {
    pub loaded_sessions: usize,
    pub in_flight: usize,
    pub total_checkouts: u64,
    pub wait_p50: Duration,
    pub wait_max: Duration,
}

pub fn parse_model(name: &str) -> Result<RerankerModel> {
    match name {
        "bge-reranker-v2-m3" => Ok(RerankerModel::BGERerankerV2M3),
        "jina-reranker-v1-turbo" => Ok(RerankerModel::JINARerankerV1TurboEn),
        other => {
            bail!("unknown rerank model '{other}' (bge-reranker-v2-m3, jina-reranker-v1-turbo)")
        }
    }
}

fn parse_ep(raw: &str) -> Result<RerankEp> {
    match raw {
        "cpu" => Ok(RerankEp::Cpu),
        "cuda" => Ok(RerankEp::Cuda),
        other => bail!("unknown SECOND_BRAIN_RERANK_EP '{other}' (valid values: cpu, cuda)"),
    }
}

pub(crate) fn ep_from_env() -> Result<RerankEp> {
    match std::env::var("SECOND_BRAIN_RERANK_EP") {
        Ok(v) => parse_ep(&v),
        Err(_) => Ok(RerankEp::Cpu),
    }
}

fn backend_from_env() -> RerankBackend {
    match std::env::var("SECOND_BRAIN_RERANK_BACKEND") {
        Ok(v) if v == "fastembed" => RerankBackend::FastEmbed,
        _ => RerankBackend::Onnx,
    }
}

/// Defaults to `cores / pool_size` (floor, minimum 1) so a full pool asks
/// the OS for roughly one core's worth of intra-op threads per in-flight
/// session instead of oversubscribing by `pool_size`x, which is the exact
/// bottleneck this backend exists to avoid.
fn intra_threads_from_env(pool_size: usize) -> Result<usize> {
    match std::env::var("SECOND_BRAIN_RERANK_INTRA_THREADS") {
        Ok(v) => {
            let n: usize = v
                .parse()
                .with_context(|| format!("parsing SECOND_BRAIN_RERANK_INTRA_THREADS '{v}'"))?;
            if n == 0 {
                bail!("SECOND_BRAIN_RERANK_INTRA_THREADS must be at least 1");
            }
            Ok(n)
        }
        Err(_) => {
            let cores = std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(1);
            Ok((cores / pool_size.max(1)).max(1))
        }
    }
}

fn max_length_from_env() -> Result<Option<usize>> {
    match std::env::var("SECOND_BRAIN_RERANK_MAX_LEN") {
        Ok(v) => Ok(Some(v.parse::<usize>().with_context(|| {
            format!("parsing SECOND_BRAIN_RERANK_MAX_LEN '{v}'")
        })?)),
        Err(_) => Ok(None),
    }
}

/// `0` is the escape hatch back to unlimited document length: a document
/// budget of zero characters would score nothing, so that value is free to
/// repurpose as "truncation off" rather than needing a second env var.
fn doc_chars_from_env() -> Result<Option<usize>> {
    match std::env::var("SECOND_BRAIN_RERANK_DOC_CHARS") {
        Ok(v) => {
            let n: usize = v
                .parse()
                .with_context(|| format!("parsing SECOND_BRAIN_RERANK_DOC_CHARS '{v}'"))?;
            Ok(if n == 0 { None } else { Some(n) })
        }
        Err(_) => Ok(Some(DEFAULT_DOC_CHARS)),
    }
}

fn checkout_timeout_from_env() -> Result<Duration> {
    match std::env::var("SECOND_BRAIN_RERANK_CHECKOUT_SECS") {
        Ok(v) => {
            let secs: u64 = v
                .parse()
                .with_context(|| format!("parsing SECOND_BRAIN_RERANK_CHECKOUT_SECS '{v}'"))?;
            Ok(Duration::from_secs(secs))
        }
        Err(_) => Ok(DEFAULT_CHECKOUT_TIMEOUT),
    }
}

/// Builds one session on the selected backend.
///
/// The `fastembed` backend cannot select a concrete execution provider: it
/// is not a direct dependency of second-brain-core, and fastembed 5.13.4
/// re-exports only the opaque `ExecutionProviderDispatch`, not a concrete
/// provider type such as `CUDAExecutionProvider` — so there is no way from
/// this crate to construct a value for
/// `RerankInitOptions::with_execution_providers`. Requesting cuda on that
/// path therefore always falls back to cpu, loudly. The `onnx` backend (the
/// default) owns its `ort::Session` directly and can select CUDA for real;
/// see `onnx_rerank::execution_providers`.
#[allow(clippy::too_many_arguments)]
fn load_session(
    backend: RerankBackend,
    model_name: RerankerModel,
    ep: RerankEp,
    max_length: Option<usize>,
    intra_threads: usize,
    inter_threads: usize,
    show_progress: bool,
) -> Result<RerankSession> {
    match backend {
        RerankBackend::FastEmbed => {
            if ep == RerankEp::Cuda {
                tracing::warn!(
                    "SECOND_BRAIN_RERANK_EP=cuda requested but unavailable on the fastembed \
                     rerank backend (ort is not a direct dependency along that path); falling \
                     back to cpu. Use the onnx backend (the default) for real GPU selection."
                );
            }
            let mut opts = RerankInitOptions::new(model_name)
                .with_cache_dir(model_cache_dir()?)
                .with_show_download_progress(show_progress);
            if let Some(len) = max_length {
                opts = opts.with_max_length(len);
            }
            TextRerank::try_new(opts)
                .map(RerankSession::FastEmbed)
                .context("loading rerank model (fastembed backend)")
        }
        RerankBackend::Onnx => {
            let config = OnnxSessionConfig {
                intra_threads,
                inter_threads,
                opt_level: onnx_rerank::default_opt_level(),
                ep,
                max_length,
            };
            OnnxReranker::load(model_name, &config)
                .map(RerankSession::Onnx)
                .context("loading rerank model (onnx backend)")
        }
    }
}

/// Truncation happens exactly once, here, so a document scores identically
/// no matter how long its untruncated form is. Character-based, not
/// byte-based, so it can never split a multi-byte UTF-8 sequence.
fn truncate_chars(s: &str, max_chars: Option<usize>) -> String {
    max_chars.map_or(s, |max| first_chars(s, max)).to_string()
}

/// At most the first `n` characters of `text`, cut on a character boundary.
pub fn first_chars(text: &str, n: usize) -> &str {
    text.char_indices()
        .nth(n)
        .map_or(text, |(end, _)| &text[..end])
}

/// Cross-encoder raw scores are unbounded logits; the blend and the 0.30 gate
/// both assume a 0..1 primary term, so scores pass through a sigmoid.
pub fn sigmoid(score: f32) -> f32 {
    1.0 / (1.0 + (-score).exp())
}

impl Reranker {
    pub fn new(model_name: &str) -> Result<Self> {
        Self::with_sessions(model_name, 1)
    }

    /// Builds a pool of `n` independent sessions, eager-loaded up front so
    /// construction fails fast exactly like the single-session constructor
    /// always has.
    pub fn with_sessions(model_name: &str, n: usize) -> Result<Self> {
        if n == 0 {
            bail!("rerank pool size must be at least 1");
        }
        let parsed_model = parse_model(model_name)?;
        let ep = ep_from_env()?;
        let max_length = max_length_from_env()?;
        let doc_chars = doc_chars_from_env()?;
        let backend = backend_from_env();
        let intra_threads = intra_threads_from_env(n)?;
        let inter_threads = 1;

        let checkout_timeout = checkout_timeout_from_env()?;
        let pool = SessionPool::new("rerank", n, |waited, pool_size| {
            RerankTimeoutError { waited, pool_size }.into()
        });
        for i in 0..n {
            pool.install(i, || {
                load_session(
                    backend,
                    parsed_model.clone(),
                    ep,
                    max_length,
                    intra_threads,
                    inter_threads,
                    true,
                )
            })
            .with_context(|| format!("initializing rerank session {i} of {n}"))?;
        }

        Ok(Self {
            pool: Arc::new(pool),
            checkout_timeout,
            model_name: parsed_model,
            ep,
            max_length,
            doc_chars,
            backend,
            intra_threads,
            inter_threads,
        })
    }

    /// Overrides the default checkout wait bound. Mainly useful for tests
    /// that need to observe the timeout path without a long-running test.
    pub fn with_checkout_timeout(mut self, timeout: Duration) -> Self {
        self.checkout_timeout = timeout;
        self
    }

    pub fn pool_size(&self) -> usize {
        self.pool.len()
    }

    pub fn metrics(&self) -> RerankMetricsSnapshot {
        let stats = self.pool.stats();
        RerankMetricsSnapshot {
            loaded_sessions: stats.loaded_sessions,
            in_flight: stats.in_flight,
            total_checkouts: stats.total_checkouts,
            wait_p50: stats.wait_p50,
            wait_max: stats.wait_max,
        }
    }

    /// Sigmoid-squashed relevance scores in the same order as `documents`.
    pub fn rerank(&self, query: &str, documents: &[&str]) -> Result<Vec<f32>> {
        self.score(query, documents, None)
    }

    /// `rerank` for a caller with a deadline: it takes only a session that
    /// is loaded, waiting at most `wait` (and never past the pool's checkout
    /// timeout), so it fails fast with `RerankTimeoutError` instead of
    /// queueing behind other reranks or paying a model reload; a session
    /// dropped while idle is reloaded in the background for later calls.
    /// A rerank that gets a session runs to completion.
    pub fn rerank_within(
        &self,
        query: &str,
        documents: &[&str],
        wait: Duration,
    ) -> Result<Vec<f32>> {
        self.score(query, documents, Some(wait.min(self.checkout_timeout)))
    }

    /// Starts, on a background thread, the reload a `rerank_within` would
    /// start now (none while a loaded session is free), for a caller with a
    /// deadline that will rerank soon but cannot wait for a load.
    pub fn warm_in_background(&self) {
        self.pool.warm_if_cold(self.loader());
    }

    fn score(
        &self,
        query: &str,
        documents: &[&str],
        warm_within: Option<Duration>,
    ) -> Result<Vec<f32>> {
        if documents.is_empty() {
            return Ok(Vec::new());
        }
        let truncated: Vec<String> = documents
            .iter()
            .map(|d| truncate_chars(d, self.doc_chars))
            .collect();
        let doc_refs: Vec<&str> = truncated.iter().map(String::as_str).collect();
        let doc_count = doc_refs.len();

        let run = move |session: &mut RerankSession| match session {
            RerankSession::FastEmbed(session) => {
                let results = session
                    .rerank(query, doc_refs, false, None)
                    .context("reranking (fastembed backend)")?;
                let mut out = vec![0.0_f32; doc_count];
                for r in results {
                    if let Some(slot) = out.get_mut(r.index) {
                        *slot = r.score;
                    }
                }
                Ok(out)
            }
            RerankSession::Onnx(session) => session
                .rerank_batch(query, &doc_refs)
                .context("reranking (onnx backend)"),
        };
        let raw_scores = match warm_within {
            None => self
                .pool
                .checkout(self.checkout_timeout, self.loader(), run)?,
            Some(wait) => self.pool.checkout_warm(wait, self.loader(), run)?,
        };
        Ok(raw_scores.into_iter().map(sigmoid).collect())
    }

    fn loader(&self) -> impl FnOnce() -> Result<RerankSession> + Send + 'static {
        let model_name = self.model_name.clone();
        let (ep, max_length, backend) = (self.ep, self.max_length, self.backend);
        let (intra_threads, inter_threads) = (self.intra_threads, self.inter_threads);
        move || {
            load_session(
                backend,
                model_name,
                ep,
                max_length,
                intra_threads,
                inter_threads,
                false,
            )
        }
    }

    pub fn drop_if_idle(&self, idle_secs: u64) {
        self.pool.drop_if_idle(idle_secs);
    }

    /// Allocator growth across every slot's load and first use; a dropped slot adds 0.
    pub fn resident_bytes(&self) -> u64 {
        self.pool.slot_resident_bytes().iter().sum()
    }

    /// Allocator growth across each slot's load and first use, 0 for a dropped slot.
    pub fn slot_resident_bytes(&self) -> Vec<u64> {
        self.pool.slot_resident_bytes()
    }
}

impl RerankScorer for Reranker {
    fn rerank(&self, query: &str, documents: &[&str]) -> Result<Vec<f32>> {
        Reranker::rerank(self, query, documents)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn model_names_parse_and_unknown_rejects() {
        assert!(parse_model("bge-reranker-v2-m3").is_ok());
        assert!(parse_model("jina-reranker-v1-turbo").is_ok());
        assert!(parse_model("gpt-reranker").is_err());
    }

    #[test]
    fn sigmoid_maps_logits_into_unit_interval() {
        assert!((sigmoid(0.0) - 0.5).abs() < 1e-6);
        assert!(sigmoid(8.0) > 0.99);
        assert!(sigmoid(-8.0) < 0.01);
    }

    #[test]
    fn ep_parsing_rejects_unknown_values_and_names_valid_ones() {
        assert!(parse_ep("cpu").is_ok());
        assert!(parse_ep("cuda").is_ok());
        let err = parse_ep("tpu").unwrap_err();
        assert!(err.to_string().contains("cpu"));
        assert!(err.to_string().contains("cuda"));
    }

    #[test]
    fn truncate_chars_never_splits_multibyte_utf8() {
        let s = "a".repeat(9) + "\u{1F600}\u{1F600}\u{1F600}";
        for max in 0..(s.chars().count() + 2) {
            let t = truncate_chars(&s, Some(max));
            assert!(std::str::from_utf8(t.as_bytes()).is_ok());
        }
    }

    #[test]
    fn intra_threads_defaults_to_cores_divided_by_pool_size() {
        let cores = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);
        assert_eq!(intra_threads_from_env(1).unwrap(), cores.max(1));
        assert_eq!(intra_threads_from_env(cores.max(2)).unwrap(), 1);
    }

    #[test]
    fn doc_chars_from_env_defaults_to_1024_and_zero_opts_out_of_truncation() {
        // SAFETY: this test owns SECOND_BRAIN_RERANK_DOC_CHARS exclusively;
        // no other test in this binary reads or writes it.
        unsafe { std::env::remove_var("SECOND_BRAIN_RERANK_DOC_CHARS") };
        assert_eq!(doc_chars_from_env().unwrap(), Some(DEFAULT_DOC_CHARS));

        unsafe { std::env::set_var("SECOND_BRAIN_RERANK_DOC_CHARS", "0") };
        assert_eq!(doc_chars_from_env().unwrap(), None);

        unsafe { std::env::set_var("SECOND_BRAIN_RERANK_DOC_CHARS", "512") };
        assert_eq!(doc_chars_from_env().unwrap(), Some(512));

        unsafe { std::env::remove_var("SECOND_BRAIN_RERANK_DOC_CHARS") };
    }

    #[test]
    fn checkout_timeout_from_env_defaults_to_30s_and_parses_override() {
        // SAFETY: this test owns SECOND_BRAIN_RERANK_CHECKOUT_SECS
        // exclusively; no other test in this binary reads or writes it.
        unsafe { std::env::remove_var("SECOND_BRAIN_RERANK_CHECKOUT_SECS") };
        assert_eq!(
            checkout_timeout_from_env().unwrap(),
            DEFAULT_CHECKOUT_TIMEOUT
        );

        unsafe { std::env::set_var("SECOND_BRAIN_RERANK_CHECKOUT_SECS", "5") };
        assert_eq!(checkout_timeout_from_env().unwrap(), Duration::from_secs(5));

        unsafe { std::env::remove_var("SECOND_BRAIN_RERANK_CHECKOUT_SECS") };
    }
}