second-brain-api 0.13.5

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
use clap::Parser;
use fs4::fs_std::FileExt;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use serde::Serialize;

use second_brain_core::embedding::{Embedder, query_prompt};
use second_brain_core::index::{CLAIM_FILE, EMBEDDING_DIM, Indexes};
use second_brain_core::query::{QueryFilters, QueryRequest};
use second_brain_core::retrieval::{RerankScorer, Reranker, RetrievalTunables, Retriever};
use second_brain_core::sqlite_store::SqliteStore;

const DEFAULT_LIMIT: usize = 10;

#[derive(Parser)]
#[command(
    name = "sb-recall-bench",
    about = "In-process throughput/latency harness for second-brain hybrid recall (Retriever::rank, not the HTTP layer)"
)]
struct Cli {
    #[arg(long, help = "Path to the SqliteStore brain.db to bench against")]
    store: PathBuf,
    #[arg(
        long,
        help = "Path to the Indexes directory (vectors.usearch + tantivy/) beside the store"
    )]
    indexes: PathBuf,
    #[arg(
        long,
        help = "A positive integer (synthesize that many queries from the store's own memories, no model download needed) or a path to a recall_eval-style JSONL query file (requires the bge-small embedding model)"
    )]
    queries: String,
    #[arg(
        long,
        default_value_t = 1,
        help = "Number of concurrent worker threads issuing recall calls"
    )]
    concurrency: usize,
    #[arg(
        long,
        help = "Run the measured phase for this many seconds (mutually exclusive with --iterations)"
    )]
    duration: Option<u64>,
    #[arg(
        long,
        help = "Run the measured phase for exactly this many total recall calls (mutually exclusive with --duration)"
    )]
    iterations: Option<u64>,
    #[arg(long, help = "Where to write the JSON report")]
    out: PathBuf,
    #[arg(
        long,
        default_value = "off",
        help = "Cross-encoder rerank model to load (bge-reranker-v2-m3, jina-reranker-v1-turbo), or 'off' to skip reranking"
    )]
    rerank: String,
    #[arg(
        long,
        default_value_t = DEFAULT_LIMIT,
        help = "recall limit passed to Retriever::rank"
    )]
    limit: usize,
    #[arg(
        long,
        help = "RRF fuse_top override; defaults to the engine's own default"
    )]
    fuse_top: Option<usize>,
    #[arg(
        long,
        help = "Discarded warmup calls before measurement begins; defaults to concurrency*5 (min 20)"
    )]
    warmup: Option<usize>,
    #[arg(
        long,
        default_value_t = 42,
        help = "Seed for deterministic sampling when --queries is a synthetic count"
    )]
    seed: u64,
}

#[derive(Clone, Copy)]
enum Workload {
    Duration(Duration),
    Iterations(u64),
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum QuerySourceConfig {
    File { path: String },
    Synthetic { count: usize, seed: u64 },
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum WorkloadConfig {
    Duration { seconds: u64 },
    Iterations { count: u64 },
}

#[derive(Serialize)]
struct BenchConfig {
    store: String,
    indexes: String,
    queries: QuerySourceConfig,
    query_count: usize,
    concurrency: usize,
    workload: WorkloadConfig,
    limit: usize,
    rerank: String,
    fuse_top: usize,
    warmup_discarded: usize,
}

#[derive(Serialize, Default)]
struct LatencyStats {
    p50_ms: f64,
    p95_ms: f64,
    p99_ms: f64,
    max_ms: f64,
    mean_ms: f64,
}

#[derive(Serialize)]
struct ErrorsReport {
    count: u64,
    kinds: BTreeMap<String, u64>,
}

#[derive(Serialize)]
struct BenchReport {
    config: BenchConfig,
    total_queries: u64,
    elapsed_secs: f64,
    achieved_qps: f64,
    latency_ms: LatencyStats,
    errors: ErrorsReport,
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    if cli.concurrency == 0 {
        bail!("--concurrency must be at least 1, got 0");
    }
    if cli.limit == 0 {
        bail!("--limit must be at least 1, got 0");
    }
    match (cli.duration, cli.iterations) {
        (None, None) => bail!("exactly one of --duration or --iterations is required"),
        (Some(_), Some(_)) => {
            bail!("--duration and --iterations are mutually exclusive; pass exactly one")
        }
        _ => {}
    }
    let workload = match (cli.duration, cli.iterations) {
        (Some(secs), None) => {
            if secs == 0 {
                bail!("--duration must be at least 1 second, got 0");
            }
            Workload::Duration(Duration::from_secs(secs))
        }
        (None, Some(n)) => {
            if n == 0 {
                bail!("--iterations must be at least 1, got 0");
            }
            Workload::Iterations(n)
        }
        _ => unreachable!("validated above"),
    };

    check_no_live_writer(&cli.indexes)?;

    let store = SqliteStore::open(&cli.store, "sb-recall-bench".to_string())
        .with_context(|| format!("opening store at {}", cli.store.display()))?;

    // Read-only, same as the daemon's serving handle: recall_bench measures
    // the shipped recall path, which never takes a lock to search indexes,
    // and never rebuilds or drains them, so a writable handle here would
    // measure a path the service does not take.
    let indexes = Indexes::open_readonly(&cli.indexes)
        .with_context(|| format!("opening indexes at {}", cli.indexes.display()))?;
    match indexes.consistent_with(&store) {
        Ok(true) => eprintln!(
            "indexes at {} are consistent with the store",
            cli.indexes.display()
        ),
        Ok(false) => eprintln!(
            "warning: indexes at {} look stale relative to the store; recall_bench never \
             rebuilds indexes, so results reflect them as-is",
            cli.indexes.display()
        ),
        Err(e) => eprintln!("warning: could not verify index consistency: {e}"),
    }

    let reranker = match cli.rerank.as_str() {
        "off" => None,
        model => {
            eprintln!("loading rerank model {model}");
            Some(Reranker::new(model).context("loading rerank model")?)
        }
    };

    let fuse_top = cli
        .fuse_top
        .unwrap_or(RetrievalTunables::default().fuse_top);
    let tunables = RetrievalTunables {
        fuse_top,
        ..Default::default()
    };
    let retriever = Retriever { tunables };

    let (queries, query_source) = prepare_queries(&store, &cli)?;
    if queries.is_empty() {
        bail!("no queries to run; check --queries");
    }
    println!(
        "prepared {} queries ({})",
        queries.len(),
        match &query_source {
            QuerySourceConfig::File { path } => format!("from file {path}, bge-small embeddings"),
            QuerySourceConfig::Synthetic { count, seed } => format!(
                "synthetic, {count} sampled from the store at seed {seed}, no embedding model"
            ),
        }
    );

    let warmup_n = cli.warmup.unwrap_or_else(|| (cli.concurrency * 5).max(20));
    let warmup_start = Instant::now();
    let warmup_outcome = run_workload(
        &store,
        &indexes,
        &retriever,
        reranker.as_ref(),
        &queries,
        cli.concurrency,
        Workload::Iterations(warmup_n as u64),
    );
    println!(
        "discarded {} warmup queries in {:.2}s",
        warmup_outcome.len(),
        warmup_start.elapsed().as_secs_f64()
    );

    let measure_start = Instant::now();
    let outcome = run_workload(
        &store,
        &indexes,
        &retriever,
        reranker.as_ref(),
        &queries,
        cli.concurrency,
        workload,
    );
    let elapsed = measure_start.elapsed();

    let report = build_report(
        BenchConfig {
            store: cli.store.display().to_string(),
            indexes: cli.indexes.display().to_string(),
            queries: query_source,
            query_count: queries.len(),
            concurrency: cli.concurrency,
            workload: match workload {
                Workload::Duration(d) => WorkloadConfig::Duration {
                    seconds: d.as_secs(),
                },
                Workload::Iterations(n) => WorkloadConfig::Iterations { count: n },
            },
            limit: cli.limit,
            rerank: cli.rerank.clone(),
            fuse_top,
            warmup_discarded: warmup_outcome.len() as usize,
        },
        &outcome,
        elapsed,
    );

    let json = serde_json::to_string_pretty(&report)?;
    std::fs::write(&cli.out, &json)
        .with_context(|| format!("writing report to {}", cli.out.display()))?;

    print_summary(&report);
    println!("report written to {}", cli.out.display());

    Ok(())
}

/// Refuses to start rather than risk hanging on tantivy's meta lock or racing
/// a live daemon. A daemon holds `CLAIM_FILE` for its whole life, even while
/// its writer is released, and tantivy's lock catches any other writer.
/// Neither file exists until some process first takes it, so a missing file
/// means no such process has run here.
fn check_no_live_writer(indexes_dir: &Path) -> Result<()> {
    check_lock(&indexes_dir.join(CLAIM_FILE))?;
    check_lock(&indexes_dir.join("tantivy").join(".tantivy-writer.lock"))
}

fn check_lock(lock_path: &Path) -> Result<()> {
    if !lock_path.exists() {
        return Ok(());
    }

    let file = std::fs::OpenOptions::new()
        .write(true)
        .open(lock_path)
        .with_context(|| format!("opening {} to probe for a live writer", lock_path.display()))?;

    let acquired = file
        .try_lock_exclusive()
        .with_context(|| format!("probing lock state of {}", lock_path.display()))?;

    if acquired {
        let _ = file.unlock();
        return Ok(());
    }

    match find_lock_holder_pid(lock_path) {
        Some(pid) => bail!(
            "refusing to start: {} is held by another process (pid {pid}), most likely a live \
             daemon. Point --indexes at a private copy, never at a directory an active daemon owns.",
            lock_path.display()
        ),
        None => bail!(
            "refusing to start: {} is held by another process (pid undetermined), most likely a \
             live daemon. Point --indexes at a private copy, never at a directory an active \
             daemon owns.",
            lock_path.display()
        ),
    }
}

/// Best-effort holder lookup via /proc/locks (Linux only): flock entries list
/// a pid but not which file, so each FLOCK pid's open fds are checked for one
/// that resolves to our lock path.
fn find_lock_holder_pid(lock_path: &Path) -> Option<u32> {
    let canonical = lock_path.canonicalize().ok()?;
    let locks = std::fs::read_to_string("/proc/locks").ok()?;
    for line in locks.lines() {
        let fields: Vec<&str> = line.split_whitespace().collect();
        if fields.len() < 5 || fields[1] != "FLOCK" {
            continue;
        }
        let Ok(pid) = fields[4].parse::<u32>() else {
            continue;
        };
        let Ok(entries) = std::fs::read_dir(format!("/proc/{pid}/fd")) else {
            continue;
        };
        for entry in entries.flatten() {
            if let Ok(target) = std::fs::read_link(entry.path())
                && target == canonical
            {
                return Some(pid);
            }
        }
    }
    None
}

fn prepare_queries(
    store: &SqliteStore,
    cli: &Cli,
) -> Result<(Vec<QueryRequest>, QuerySourceConfig)> {
    match cli.queries.parse::<usize>() {
        Ok(count) => {
            if count == 0 {
                bail!("--queries count must be at least 1, got 0");
            }
            let synthetic = synthesize_queries(store, count, cli.seed, cli.limit)?;
            Ok((
                synthetic,
                QuerySourceConfig::Synthetic {
                    count,
                    seed: cli.seed,
                },
            ))
        }
        Err(_) => {
            let path = PathBuf::from(&cli.queries);
            let loaded = load_file_queries(&path, cli.limit)?;
            Ok((
                loaded,
                QuerySourceConfig::File {
                    path: cli.queries.clone(),
                },
            ))
        }
    }
}

fn synthesize_queries(
    store: &SqliteStore,
    count: usize,
    seed: u64,
    limit: usize,
) -> Result<Vec<QueryRequest>> {
    let indexable = store.all_indexable()?;
    let usable: Vec<(uuid::Uuid, Vec<f32>, String)> = indexable
        .into_iter()
        .filter(|(_, embedding, _)| embedding.len() == EMBEDDING_DIM)
        .collect();
    if usable.is_empty() {
        bail!(
            "the store has no indexable memories with {EMBEDDING_DIM}-dim embeddings; cannot \
             synthesize queries from it"
        );
    }

    let mut rng = StdRng::seed_from_u64(seed);
    let mut queries = Vec::with_capacity(count);
    for _ in 0..count {
        let idx = rng.random_range(0..usable.len());
        let (_, embedding, body) = &usable[idx];
        let text = query_text_from_body(body);
        queries.push(build_request(text, embedding.clone(), limit));
    }
    Ok(queries)
}

fn query_text_from_body(body: &str) -> String {
    let words: Vec<&str> = body.split_whitespace().take(10).collect();
    if words.is_empty() {
        body.chars().take(40).collect()
    } else {
        words.join(" ")
    }
}

fn load_file_queries(path: &Path, limit: usize) -> Result<Vec<QueryRequest>> {
    let eval_queries = second_brain_api::eval::load_eval_set(path)
        .with_context(|| format!("loading queries from {}", path.display()))?;
    if eval_queries.is_empty() {
        bail!("query file {} contains no queries", path.display());
    }

    eprintln!(
        "loading embedding model to embed {} file queries",
        eval_queries.len()
    );
    let embedder = Embedder::new().context("loading embedding model")?;
    let prefixed: Vec<String> = eval_queries
        .iter()
        .map(|q| query_prompt(&q.query))
        .collect();
    let refs: Vec<&str> = prefixed.iter().map(|s| s.as_str()).collect();
    let embeddings = embedder
        .embed_batch(&refs)
        .context("embedding file queries")?;

    Ok(eval_queries
        .into_iter()
        .zip(embeddings)
        .map(|(q, embedding)| build_request(q.query, embedding, limit))
        .collect())
}

fn build_request(text: String, embedding: Vec<f32>, limit: usize) -> QueryRequest {
    let entity_names = second_brain_api::link_query_entities(&text);
    QueryRequest {
        text,
        embedding,
        limit,
        filters: QueryFilters {
            entity_names,
            ..QueryFilters::default()
        },
    }
}

struct WorkloadOutcome {
    latencies_us_ok: Vec<u64>,
    error_kinds: BTreeMap<String, u64>,
}

impl WorkloadOutcome {
    fn len(&self) -> u64 {
        self.latencies_us_ok.len() as u64 + self.error_kinds.values().sum::<u64>()
    }
}

#[allow(clippy::too_many_arguments)]
fn run_workload(
    store: &SqliteStore,
    indexes: &Indexes,
    retriever: &Retriever,
    reranker: Option<&Reranker>,
    queries: &[QueryRequest],
    concurrency: usize,
    workload: Workload,
) -> WorkloadOutcome {
    let issued = AtomicU64::new(0);
    let stop = AtomicBool::new(false);
    let deadline = match workload {
        Workload::Duration(d) => Some(Instant::now() + d),
        Workload::Iterations(_) => None,
    };
    let target = match workload {
        Workload::Iterations(n) => Some(n),
        Workload::Duration(_) => None,
    };

    let collected: Mutex<Vec<(u64, Option<String>)>> = Mutex::new(Vec::new());

    thread::scope(|scope| {
        for _ in 0..concurrency {
            scope.spawn(|| {
                let mut local: Vec<(u64, Option<String>)> = Vec::new();
                loop {
                    if stop.load(Ordering::Relaxed) {
                        break;
                    }
                    let i = issued.fetch_add(1, Ordering::Relaxed);
                    if let Some(t) = target
                        && i >= t
                    {
                        stop.store(true, Ordering::Relaxed);
                        break;
                    }
                    let request = &queries[(i as usize) % queries.len()];

                    let started = Instant::now();
                    let outcome: Result<usize> = (|| {
                        let pool = retriever.candidates(indexes, store, request)?;
                        let ranked = retriever.rank(
                            store,
                            request,
                            &pool,
                            reranker.map(|r| r as &dyn RerankScorer),
                        )?;
                        Ok(ranked.len())
                    })();
                    let elapsed_us = started.elapsed().as_micros() as u64;

                    match outcome {
                        Ok(_) => local.push((elapsed_us, None)),
                        Err(e) => local.push((elapsed_us, Some(short_kind(&e)))),
                    }

                    if let Some(dl) = deadline
                        && Instant::now() >= dl
                    {
                        stop.store(true, Ordering::Relaxed);
                        break;
                    }
                }
                collected.lock().unwrap().extend(local);
            });
        }
    });

    let all = collected.into_inner().unwrap();
    let mut latencies_us_ok = Vec::with_capacity(all.len());
    let mut error_kinds: BTreeMap<String, u64> = BTreeMap::new();
    for (us, kind) in all {
        match kind {
            None => latencies_us_ok.push(us),
            Some(k) => *error_kinds.entry(k).or_insert(0) += 1,
        }
    }
    WorkloadOutcome {
        latencies_us_ok,
        error_kinds,
    }
}

fn short_kind(e: &anyhow::Error) -> String {
    let s = e.to_string();
    let line = s.lines().next().unwrap_or("unknown error");
    if line.len() <= 140 {
        line.to_string()
    } else {
        let mut end = 140;
        while end > 0 && !line.is_char_boundary(end) {
            end -= 1;
        }
        format!("{}...", &line[..end])
    }
}

fn percentile(sorted_asc: &[f64], p: f64) -> f64 {
    if sorted_asc.is_empty() {
        return 0.0;
    }
    if sorted_asc.len() == 1 {
        return sorted_asc[0];
    }
    let rank = (p / 100.0) * (sorted_asc.len() as f64 - 1.0);
    let lower = rank.floor() as usize;
    let upper = rank.ceil() as usize;
    if lower == upper {
        sorted_asc[lower]
    } else {
        let frac = rank - lower as f64;
        sorted_asc[lower] + (sorted_asc[upper] - sorted_asc[lower]) * frac
    }
}

fn build_report(config: BenchConfig, outcome: &WorkloadOutcome, elapsed: Duration) -> BenchReport {
    let mut latencies_ms: Vec<f64> = outcome
        .latencies_us_ok
        .iter()
        .map(|us| *us as f64 / 1000.0)
        .collect();
    latencies_ms.sort_by(|a, b| a.partial_cmp(b).unwrap());

    let latency_ms = if latencies_ms.is_empty() {
        LatencyStats::default()
    } else {
        LatencyStats {
            p50_ms: percentile(&latencies_ms, 50.0),
            p95_ms: percentile(&latencies_ms, 95.0),
            p99_ms: percentile(&latencies_ms, 99.0),
            max_ms: *latencies_ms.last().unwrap(),
            mean_ms: latencies_ms.iter().sum::<f64>() / latencies_ms.len() as f64,
        }
    };

    let total_queries = outcome.len();
    let elapsed_secs = elapsed.as_secs_f64();
    let achieved_qps = if elapsed_secs > 0.0 {
        total_queries as f64 / elapsed_secs
    } else {
        0.0
    };
    let error_count: u64 = outcome.error_kinds.values().sum();

    BenchReport {
        config,
        total_queries,
        elapsed_secs,
        achieved_qps,
        latency_ms,
        errors: ErrorsReport {
            count: error_count,
            kinds: outcome.error_kinds.clone(),
        },
    }
}

fn print_summary(report: &BenchReport) {
    println!(
        "{} queries in {:.2}s ({:.1} qps, concurrency {})",
        report.total_queries, report.elapsed_secs, report.achieved_qps, report.config.concurrency
    );
    println!(
        "latency ms: p50={:.2} p95={:.2} p99={:.2} max={:.2} mean={:.2}",
        report.latency_ms.p50_ms,
        report.latency_ms.p95_ms,
        report.latency_ms.p99_ms,
        report.latency_ms.max_ms,
        report.latency_ms.mean_ms,
    );
    if report.errors.count > 0 {
        println!("errors: {} total", report.errors.count);
        for (kind, count) in &report.errors.kinds {
            println!("  {count}x {kind}");
        }
    } else {
        println!("errors: none");
    }
}

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

    #[test]
    fn a_daemon_claim_refuses_the_bench_while_held() {
        let dir = tempfile::tempdir().unwrap();
        let claim = IndexClaim::acquire(dir.path()).unwrap();
        let err = check_no_live_writer(dir.path()).err().unwrap();
        assert!(format!("{err:#}").contains("refusing to start"), "{err:#}");
        drop(claim);
        check_no_live_writer(dir.path()).unwrap();
    }
}