second-brain-core 0.9.0

Core library for second-brain: KuzuDB graph storage, BGE embeddings, and weighted query engine
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
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

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

use super::onnx_rerank::{self, OnnxReranker, OnnxSessionConfig};

const DEFAULT_CHECKOUT_TIMEOUT: Duration = Duration::from_secs(30);
const WAIT_SAMPLE_CAP: usize = 512;

/// 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: SessionPool,
    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 in_flight: usize,
    pub total_checkouts: u64,
    pub wait_p50: Duration,
    pub wait_max: Duration,
}

fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs()
}

fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(|e| e.into_inner())
}

#[derive(Default)]
struct PoolMetrics {
    in_flight: AtomicUsize,
    total_checkouts: AtomicU64,
    wait_max_ns: AtomicU64,
    // Bounded ring buffer rather than a full histogram crate: cheap enough
    // to sample on every checkout, and a sorted snapshot gives an exact
    // median over the recent window, which is all capacity planning needs.
    wait_samples: Mutex<VecDeque<u64>>,
}

impl PoolMetrics {
    fn record_wait(&self, ns: u64) {
        self.wait_max_ns.fetch_max(ns, Ordering::Relaxed);
        let mut samples = lock_or_recover(&self.wait_samples);
        if samples.len() >= WAIT_SAMPLE_CAP {
            samples.pop_front();
        }
        samples.push_back(ns);
    }

    fn p50_ns(&self) -> u64 {
        let mut samples: Vec<u64> = lock_or_recover(&self.wait_samples)
            .iter()
            .copied()
            .collect();
        if samples.is_empty() {
            return 0;
        }
        samples.sort_unstable();
        samples[samples.len() / 2]
    }
}

/// Fixed-size pool of lazily-loaded, independently idle-unloadable sessions.
/// Checkout pulls an index off a free list guarded by a condvar, so waiters
/// are woken in order instead of spin-polling N mutexes with `try_lock`.
struct SessionPool {
    sessions: Vec<Mutex<Option<RerankSession>>>,
    last_used_secs: Vec<AtomicU64>,
    free: Mutex<VecDeque<usize>>,
    free_cv: Condvar,
    checkout_timeout: Duration,
    metrics: PoolMetrics,
}

/// Returns the checked-out slot to the free list on drop, including on a
/// panic unwind, so a failure inside one rerank call cannot permanently
/// shrink the pool.
struct Checkout<'a> {
    pool: &'a SessionPool,
    idx: usize,
}

impl Drop for Checkout<'_> {
    fn drop(&mut self) {
        self.pool.metrics.in_flight.fetch_sub(1, Ordering::Relaxed);
        lock_or_recover(&self.pool.free).push_back(self.idx);
        self.pool.free_cv.notify_one();
    }
}

impl SessionPool {
    fn new(n: usize, checkout_timeout: Duration) -> Self {
        let mut sessions = Vec::with_capacity(n);
        let mut last_used_secs = Vec::with_capacity(n);
        let mut free = VecDeque::with_capacity(n);
        for i in 0..n {
            sessions.push(Mutex::new(None));
            last_used_secs.push(AtomicU64::new(0));
            free.push_back(i);
        }
        Self {
            sessions,
            last_used_secs,
            free: Mutex::new(free),
            free_cv: Condvar::new(),
            checkout_timeout,
            metrics: PoolMetrics::default(),
        }
    }

    fn len(&self) -> usize {
        self.sessions.len()
    }

    fn checkout<R>(
        &self,
        load: impl FnOnce() -> Result<RerankSession>,
        with_session: impl FnOnce(&mut RerankSession) -> Result<R>,
    ) -> Result<R> {
        let start = Instant::now();
        let guard = lock_or_recover(&self.free);
        let (mut guard, wait_result) = self
            .free_cv
            .wait_timeout_while(guard, self.checkout_timeout, |q| q.is_empty())
            .unwrap_or_else(|e| e.into_inner());
        if wait_result.timed_out() && guard.is_empty() {
            return Err(RerankTimeoutError {
                waited: start.elapsed(),
                pool_size: self.len(),
            }
            .into());
        }
        let idx = guard.pop_front().expect("free slot present after wait");
        drop(guard);

        self.metrics.record_wait(start.elapsed().as_nanos() as u64);
        self.metrics.total_checkouts.fetch_add(1, Ordering::Relaxed);
        self.metrics.in_flight.fetch_add(1, Ordering::Relaxed);
        let _checkout = Checkout { pool: self, idx };

        let mut slot = lock_or_recover(&self.sessions[idx]);
        if slot.is_none() {
            tracing::info!("reloading rerank model after idle drop (slot {idx})");
            *slot = Some(load()?);
        }
        self.last_used_secs[idx].store(now_secs(), Ordering::Relaxed);
        with_session(slot.as_mut().expect("session loaded above"))
    }

    fn drop_if_idle(&self, idle_secs: u64) {
        let now = now_secs();
        for (idx, last) in self.last_used_secs.iter().enumerate() {
            if now.saturating_sub(last.load(Ordering::Relaxed)) < idle_secs {
                continue;
            }
            // try_lock, not lock: a busy slot is by definition not idle, and
            // this must never block behind an in-flight rerank.
            if let Ok(mut slot) = self.sessions[idx].try_lock()
                && slot.is_some()
            {
                *slot = None;
                tracing::info!("rerank session {idx} dropped after {idle_secs}s idle");
            }
        }
    }
}

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_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 {
    match max_chars {
        Some(max) => s.chars().take(max).collect(),
        None => s.to_string(),
    }
}

/// 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 pool = SessionPool::new(n, checkout_timeout_from_env()?);
        for i in 0..n {
            let mut slot = lock_or_recover(&pool.sessions[i]);
            *slot = Some(
                load_session(
                    backend,
                    parsed_model.clone(),
                    ep,
                    max_length,
                    intra_threads,
                    inter_threads,
                    true,
                )
                .with_context(|| format!("initializing rerank session {i} of {n}"))?,
            );
            pool.last_used_secs[i].store(now_secs(), Ordering::Relaxed);
        }

        Ok(Self {
            pool,
            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.pool.checkout_timeout = timeout;
        self
    }

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

    pub fn metrics(&self) -> RerankMetricsSnapshot {
        RerankMetricsSnapshot {
            in_flight: self.pool.metrics.in_flight.load(Ordering::Relaxed),
            total_checkouts: self.pool.metrics.total_checkouts.load(Ordering::Relaxed),
            wait_p50: Duration::from_nanos(self.pool.metrics.p50_ns()),
            wait_max: Duration::from_nanos(self.pool.metrics.wait_max_ns.load(Ordering::Relaxed)),
        }
    }

    /// Sigmoid-squashed relevance scores in the same order as `documents`.
    pub fn rerank(&self, query: &str, documents: &[&str]) -> 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 model_name = self.model_name.clone();
        let ep = self.ep;
        let max_length = self.max_length;
        let backend = self.backend;
        let intra_threads = self.intra_threads;
        let inter_threads = self.inter_threads;

        let raw_scores: Vec<f32> = self.pool.checkout(
            move || {
                load_session(
                    backend,
                    model_name,
                    ep,
                    max_length,
                    intra_threads,
                    inter_threads,
                    false,
                )
            },
            move |session| 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)"),
            },
        )?;

        Ok(raw_scores.into_iter().map(sigmoid).collect())
    }

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

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") };
    }
}