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
use std::path::{Path, PathBuf};
use std::time::Instant;

use anyhow::{Context, Result, bail};
use chrono::{DateTime, Duration as ChronoDuration, TimeZone, Utc};
use clap::Parser;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use uuid::Uuid;

use second_brain_core::index::{EMBEDDING_DIM, Indexes};
use second_brain_core::schema::{Memory, MemoryType};
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::Store;

const MEMORY_TYPES: [MemoryType; 8] = [
    MemoryType::Episodic,
    MemoryType::Semantic,
    MemoryType::Procedural,
    MemoryType::Decision,
    MemoryType::Architecture,
    MemoryType::Debugging,
    MemoryType::Task,
    MemoryType::Question,
];

const MIN_BODY_CHARS: usize = 200;
const MAX_BODY_CHARS: usize = 4000;

const WORD_POOL: &[&str] = &[
    "the",
    "a",
    "of",
    "and",
    "with",
    "for",
    "to",
    "in",
    "that",
    "this",
    "on",
    "as",
    "by",
    "from",
    "is",
    "are",
    "was",
    "were",
    "will",
    "can",
    "should",
    "must",
    "when",
    "where",
    "which",
    "because",
    "however",
    "therefore",
    "then",
    "also",
    "more",
    "most",
    "some",
    "many",
    "few",
    "several",
    "each",
    "every",
    "both",
    "either",
    "neither",
    "not",
    "only",
    "just",
    "still",
    "yet",
    "already",
    "now",
    "soon",
    "later",
    "before",
    "after",
    "during",
    "while",
    "since",
    "until",
    "though",
    "although",
    "so",
    "thus",
    "hence",
    "memory",
    "retrieval",
    "embedding",
    "vector",
    "index",
    "cache",
    "database",
    "latency",
    "throughput",
    "concurrency",
    "daemon",
    "snapshot",
    "tenant",
    "cosine",
    "similarity",
    "ranking",
    "tokenizer",
    "query",
    "corpus",
    "workspace",
    "sqlite",
    "tantivy",
    "usearch",
    "outbox",
    "watermark",
    "schema",
    "migration",
    "cluster",
    "replica",
    "shard",
    "partition",
    "checkpoint",
    "transaction",
    "mutex",
    "thread",
    "runtime",
    "serialize",
    "deserialize",
    "protocol",
    "endpoint",
    "gateway",
    "eviction",
    "compaction",
    "benchmark",
    "percentile",
    "jitter",
    "backoff",
    "retry",
    "timeout",
    "heartbeat",
    "consensus",
    "quorum",
    "leader",
    "follower",
    "journal",
    "commit",
    "rollback",
    "isolation",
    "durability",
    "consistency",
    "availability",
    "tolerance",
    "balancer",
    "proxy",
    "router",
    "session",
    "token",
    "credential",
    "encryption",
    "checksum",
    "signature",
    "certificate",
    "socket",
    "packet",
    "header",
    "payload",
    "compress",
    "decompress",
    "model",
    "encoder",
    "decoder",
    "reranker",
    "gate",
    "threshold",
    "blend",
    "recall",
    "precision",
    "score",
    "rank",
    "candidate",
    "fusion",
    "lexical",
    "dense",
    "hybrid",
    "warmup",
    "iteration",
    "worker",
    "pool",
    "scope",
    "lock",
    "writer",
    "reader",
    "segment",
    "tier",
    "archive",
    "supersede",
    "distill",
    "ingest",
    "sync",
    "conflict",
    "resolve",
    "apply",
    "batch",
    "record",
    "sequence",
    "log",
    "event",
    "machine",
    "identity",
    "config",
    "directory",
    "path",
    "file",
    "disk",
    "usage",
    "byte",
    "size",
    "capacity",
    "growth",
    "reserve",
    "save",
    "load",
    "open",
    "close",
    "drain",
    "rebuild",
    "consistent",
    "drift",
];

#[derive(Parser)]
#[command(
    name = "sb-synth-store",
    about = "Generates reproducible synthetic second-brain stores for capacity testing"
)]
struct Cli {
    #[arg(
        long,
        help = "Output directory; one tenant-<i>/ subdirectory per store"
    )]
    out: PathBuf,
    #[arg(long, help = "Number of stores to generate")]
    stores: usize,
    #[arg(long, help = "Number of memories per store")]
    memories: usize,
    #[arg(
        long,
        help = "Seed controlling every random choice; the same seed always produces byte-identical stores"
    )]
    seed: u64,
}

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

    if cli.stores == 0 {
        bail!("--stores must be at least 1, got 0");
    }
    if cli.memories == 0 {
        bail!("--memories must be at least 1, got 0");
    }
    if cli.out.exists() {
        let mut entries = std::fs::read_dir(&cli.out)
            .with_context(|| format!("reading --out directory {}", cli.out.display()))?;
        if entries.next().is_some() {
            bail!(
                "--out {} already exists and is not empty; choose an empty or new directory",
                cli.out.display()
            );
        }
    }
    std::fs::create_dir_all(&cli.out)
        .with_context(|| format!("creating --out directory {}", cli.out.display()))?;

    let started = Instant::now();
    for i in 0..cli.stores {
        generate_store(&cli.out, i, cli.memories, cli.seed)
            .with_context(|| format!("generating store tenant-{i}"))?;
        println!("tenant-{i}: wrote {} memories", cli.memories);
    }
    let elapsed = started.elapsed();

    let total_bytes =
        dir_size(&cli.out).with_context(|| format!("measuring size of {}", cli.out.display()))?;

    println!(
        "synth_store: {} stores x {} memories, {:.2} MiB on disk, {:.2}s wall clock",
        cli.stores,
        cli.memories,
        total_bytes as f64 / (1024.0 * 1024.0),
        elapsed.as_secs_f64()
    );

    Ok(())
}

fn generate_store(out: &Path, store_idx: usize, memory_count: usize, seed: u64) -> Result<()> {
    let store_dir = out.join(format!("tenant-{store_idx}"));
    std::fs::create_dir_all(&store_dir)?;
    let db_path = store_dir.join("brain.db");

    let store = SqliteStore::open(&db_path, format!("synth-{store_idx}"))
        .with_context(|| format!("opening {}", db_path.display()))?;

    // Mixing the store index into the seed keeps every store in a batch
    // independent while remaining a pure function of (seed, store_idx), so
    // regenerating the same --seed reproduces every store byte-for-byte.
    let mut rng =
        StdRng::seed_from_u64(seed.wrapping_add(store_idx as u64 * 0x9E37_79B9_7F4A_7C15));

    for mem_idx in 0..memory_count {
        let memory = synth_memory(&mut rng, store_idx, mem_idx);
        store.store_memory(&memory)?;
    }

    let indexes_dir = db_path.with_extension("indexes");
    let mut indexes = Indexes::open(&indexes_dir)
        .with_context(|| format!("opening indexes at {}", indexes_dir.display()))?;
    let applied = indexes.drain(&store)?;
    if applied != memory_count {
        bail!(
            "index drain applied {applied} rows but {memory_count} memories were written to {}",
            db_path.display()
        );
    }
    if !indexes.consistent_with(&store)? {
        bail!(
            "indexes at {} are inconsistent with {} after drain",
            indexes_dir.display(),
            db_path.display()
        );
    }

    Ok(())
}

fn synth_memory(rng: &mut StdRng, store_idx: usize, mem_idx: usize) -> Memory {
    let content = generate_body(rng, MIN_BODY_CHARS, MAX_BODY_CHARS);
    let memory_type = MEMORY_TYPES[rng.random_range(0..MEMORY_TYPES.len())];
    let mut memory = Memory::new(
        content,
        memory_type,
        "synth".to_string(),
        format!("tenant-{store_idx}-mem-{mem_idx}"),
    );

    // Memory::new draws a v4 uuid and Utc::now() internally, neither of which
    // is reproducible; every field that determinism depends on is overwritten
    // here from the seeded rng instead.
    memory.id = deterministic_uuid(rng);
    memory.embedding = random_unit_embedding(rng);
    memory.machine_id = format!("synth-{store_idx}");

    let created = synth_epoch()
        + ChronoDuration::days(rng.random_range(0..400))
        + ChronoDuration::seconds(rng.random_range(0..86_400));
    memory.created_at = created;
    memory.updated_at = created;
    memory.last_accessed = created;
    memory.access_count = rng.random_range(0..50);
    memory.confidence = rng.random_range(0.5..1.0);

    memory
}

fn synth_epoch() -> DateTime<Utc> {
    Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap()
}

fn deterministic_uuid(rng: &mut StdRng) -> Uuid {
    let mut bytes = [0u8; 16];
    for b in bytes.iter_mut() {
        *b = rng.random();
    }
    Uuid::from_bytes(bytes)
}

fn random_unit_embedding(rng: &mut StdRng) -> Vec<f32> {
    let mut v: Vec<f32> = (0..EMBEDDING_DIM)
        .map(|_| rng.random::<f32>() * 2.0 - 1.0)
        .collect();
    let norm: f32 = v.iter().map(|x| x * x).sum::<f32>().sqrt();
    if norm > f32::EPSILON {
        for x in v.iter_mut() {
            *x /= norm;
        }
    }
    v
}

fn generate_body(rng: &mut StdRng, min_len: usize, max_len: usize) -> String {
    let target = rng.random_range(min_len..=max_len);
    let mut body = String::with_capacity(target + 32);
    let mut sentence_words = 0usize;
    let mut sentence_limit = rng.random_range(8..16);

    while body.len() < target {
        let word = WORD_POOL[rng.random_range(0..WORD_POOL.len())];
        if !body.is_empty() {
            body.push(' ');
        }
        if sentence_words == 0 {
            let mut chars = word.chars();
            if let Some(first) = chars.next() {
                body.push(first.to_ascii_uppercase());
                body.push_str(chars.as_str());
            }
        } else {
            body.push_str(word);
        }
        sentence_words += 1;
        if sentence_words >= sentence_limit {
            body.push('.');
            sentence_words = 0;
            sentence_limit = rng.random_range(8..16);
        }
    }
    if !body.ends_with('.') {
        body.push('.');
    }

    if body.len() > max_len {
        let mut end = max_len;
        while end > 0 && !body.is_char_boundary(end) {
            end -= 1;
        }
        body.truncate(end);
        if !body.ends_with('.') {
            body.push('.');
        }
    }

    body
}

fn dir_size(path: &Path) -> Result<u64> {
    let mut total = 0u64;
    for entry in std::fs::read_dir(path)? {
        let entry = entry?;
        let meta = entry.metadata()?;
        if meta.is_dir() {
            total += dir_size(&entry.path())?;
        } else {
            total += meta.len();
        }
    }
    Ok(total)
}