sqlite_graphrag/constants.rs
1//! Compile-time constants shared across the crate.
2//!
3//! Grouped into embedding configuration, length and size limits, SQLite
4//! pragmas and retrieval tuning knobs. Values are taken from the PRD and
5//! must stay in sync with the migrations under `migrations/`.
6//!
7//! ## Dynamic concurrency permit calculation
8//!
9//! The maximum number of simultaneous instances can be adjusted at runtime
10//! using the formula:
11//!
12//! ```text
13//! permits = min(cpus, available_memory_mb / LLM_WORKER_RSS_MB) * 0.5
14//! ```
15//!
16//! where `available_memory_mb` is obtained via `sysinfo::System::available_memory()`
17//! converted to MiB. The result is capped at `MAX_CONCURRENT_CLI_INSTANCES`
18//! and floored at 1.
19
20/// Default embedding vector dimensionality (v1.0.79, G42/S1).
21///
22/// Lowered from 384 to 64: with the LLM-only backend (v1.0.76+) each float
23/// costs ~8 autoregressive output tokens, so 384 dims ≈ 3072 tokens per
24/// vector at 50-100 tokens/s (30-60s per vector). 64 dims retain 90%+
25/// retrieval quality for corpora under 100k memories (Matryoshka
26/// Representation Learning, arXiv 2205.13147) while cutting generation
27/// time ~6x. The historical 384 value matched `multilingual-e5-small`.
28pub const DEFAULT_EMBEDDING_DIM: usize = 64;
29
30/// Active embedding dimensionality for this process. `0` means unresolved.
31static ACTIVE_EMBEDDING_DIM: std::sync::atomic::AtomicUsize =
32 std::sync::atomic::AtomicUsize::new(0);
33
34/// Resolves the active embedding dimensionality (single source of truth).
35///
36/// Precedence:
37/// 1. `SQLITE_GRAPHRAG_EMBEDDING_DIM` env var (also set by the global
38/// `--embedding-dim` flag before dispatch);
39/// 2. the value recorded via [`set_active_embedding_dim`] — populated from
40/// the `dim` key of `schema_meta` when the database is opened, so
41/// existing 384-dim databases keep working unchanged;
42/// 3. [`DEFAULT_EMBEDDING_DIM`].
43pub fn embedding_dim() -> usize {
44 if let Some(env_dim) = embedding_dim_from_env() {
45 return env_dim;
46 }
47 let active = ACTIVE_EMBEDDING_DIM.load(std::sync::atomic::Ordering::Acquire);
48 if active != 0 {
49 return active;
50 }
51 DEFAULT_EMBEDDING_DIM
52}
53
54/// Reads and validates the env-var override. Values outside [8, 4096]
55/// are rejected (returns `None`) so a typo cannot produce degenerate
56/// vectors or multi-MB embedding rows.
57pub fn embedding_dim_from_env() -> Option<usize> {
58 std::env::var("SQLITE_GRAPHRAG_EMBEDDING_DIM")
59 .ok()
60 .and_then(|v| v.parse::<usize>().ok())
61 .filter(|&n| (8..=4096).contains(&n))
62}
63
64/// Records the dimensionality found in the opened database
65/// (`schema_meta.dim`). Out-of-range values are ignored. The env var,
66/// when set, always wins over this value (see [`embedding_dim`]).
67pub fn set_active_embedding_dim(dim: usize) {
68 if (8..=4096).contains(&dim) {
69 ACTIVE_EMBEDDING_DIM.store(dim, std::sync::atomic::Ordering::Release);
70 }
71}
72
73/// Default `fastembed` model identifier used by `remember` and `recall`.
74pub const FASTEMBED_MODEL_DEFAULT: &str = "multilingual-e5-small";
75
76/// Batch size for `fastembed` encoding calls.
77pub const FASTEMBED_BATCH_SIZE: usize = 32;
78
79/// Maximum byte length for a memory `name` field in kebab-case.
80pub const MAX_MEMORY_NAME_LEN: usize = 80;
81
82/// Maximum byte length for an `ingest`-derived kebab-case name.
83///
84/// Stricter than `MAX_MEMORY_NAME_LEN` (80) to leave headroom for collision
85/// suffixes (`-2`, `-10`, ...) when multiple files derive to the same base.
86/// Used exclusively by `src/commands/ingest.rs`.
87pub const DERIVED_NAME_MAX_LEN: usize = 60;
88
89/// Maximum character length for a memory `description` field.
90pub const MAX_MEMORY_DESCRIPTION_LEN: usize = 500;
91
92/// Hard upper bound on memory `body` length in bytes.
93pub const MAX_MEMORY_BODY_LEN: usize = 512_000;
94
95/// Body character count above which the body is split into chunks.
96pub const MAX_BODY_CHARS_BEFORE_CHUNK: usize = 8_000;
97
98/// Maximum attempts when a statement returns `SQLITE_BUSY`.
99pub const MAX_SQLITE_BUSY_RETRIES: u32 = 5;
100
101/// Base delay in milliseconds for the first SQLITE_BUSY retry.
102///
103/// Each subsequent attempt doubles the delay (exponential backoff):
104/// 300 ms → 600 ms → 1200 ms → 2400 ms → 4800 ms (≈ 9.3 s total).
105pub const SQLITE_BUSY_BASE_DELAY_MS: u64 = 300;
106
107/// Query timeout applied to statements in milliseconds.
108pub const QUERY_TIMEOUT_MILLIS: u64 = 5_000;
109
110/// Jaccard threshold above which two memories are considered fuzzy duplicates.
111pub const DEDUP_FUZZY_THRESHOLD: f64 = 0.8;
112
113/// Cosine distance threshold below which two memories are semantic duplicates.
114pub const DEDUP_SEMANTIC_THRESHOLD: f32 = 0.1;
115
116/// Maximum number of hops allowed in graph traversals.
117pub const MAX_GRAPH_HOPS: u32 = 2;
118
119/// Minimum relationship weight required for traversal inclusion.
120pub const MIN_RELATION_WEIGHT: f64 = 0.3;
121
122/// Default traversal depth for `related` when `--hops` is omitted.
123pub const DEFAULT_MAX_HOPS: u32 = 2;
124
125/// Default minimum weight filter applied during graph traversal.
126pub const DEFAULT_MIN_WEIGHT: f64 = 0.3;
127
128/// Default weight assigned to newly created relationships.
129pub const DEFAULT_RELATION_WEIGHT: f64 = 0.5;
130
131/// Default `k` used by `recall` when the caller omits `--k`.
132pub const DEFAULT_K_RECALL: usize = 10;
133
134/// Default `k` for memory KNN searches when the caller omits `--k`.
135pub const K_MEMORIES_DEFAULT: usize = 10;
136
137/// Default `k` for entity KNN searches during graph expansion.
138pub const K_ENTITIES_SEARCH: usize = 5;
139
140/// Default upper bound on distinct entities persisted per memory.
141///
142/// Bumped from 30 → 50 in v1.0.43 to reduce semantic loss on rich documents.
143/// Configurable at runtime via `SQLITE_GRAPHRAG_MAX_ENTITIES_PER_MEMORY`.
144pub const MAX_ENTITIES_PER_MEMORY: usize = 50;
145
146/// Resolves the per-memory entity cap, honouring the env-var override.
147///
148/// v1.0.43: makes the cap (default 50) configurable via `SQLITE_GRAPHRAG_MAX_ENTITIES_PER_MEMORY`.
149/// Stress tests showed inputs with 33-46 candidates being truncated at the old cap of 30.
150/// Values outside [1, 1000] fall back to the default.
151pub fn max_entities_per_memory() -> usize {
152 std::env::var("SQLITE_GRAPHRAG_MAX_ENTITIES_PER_MEMORY")
153 .ok()
154 .and_then(|v| v.parse::<usize>().ok())
155 .filter(|&n| (1..=1_000).contains(&n))
156 .unwrap_or(MAX_ENTITIES_PER_MEMORY)
157}
158
159/// Upper bound on distinct relationships persisted per memory.
160pub const MAX_RELATIONSHIPS_PER_MEMORY: usize = 50;
161
162/// Resolves the per-memory relationship cap, honouring the env-var override.
163///
164/// v1.0.22: makes the cap (default 50) configurable via `SQLITE_GRAPHRAG_MAX_RELATIONS_PER_MEMORY`.
165/// Audit found that rich documents silently hit the cap; users with dense technical corpora
166/// can raise it via env. Values outside [1, 10000] fall back to the default.
167pub fn max_relationships_per_memory() -> usize {
168 std::env::var("SQLITE_GRAPHRAG_MAX_RELATIONS_PER_MEMORY")
169 .ok()
170 .and_then(|v| v.parse::<usize>().ok())
171 .filter(|&n| (1..=10_000).contains(&n))
172 .unwrap_or(MAX_RELATIONSHIPS_PER_MEMORY)
173}
174
175/// Character length of the description preview shown in `list` output.
176pub const TEXT_DESCRIPTION_PREVIEW_LEN: usize = 100;
177
178/// `PRAGMA busy_timeout` value applied on every connection.
179pub const BUSY_TIMEOUT_MILLIS: i32 = 5_000;
180
181/// `PRAGMA cache_size` value in kibibytes (negative means KiB).
182pub const CACHE_SIZE_KB: i32 = -64_000;
183
184/// `PRAGMA mmap_size` value in bytes applied to each connection.
185pub const MMAP_SIZE_BYTES: i64 = 268_435_456;
186
187/// `PRAGMA wal_autocheckpoint` threshold in pages.
188pub const WAL_AUTOCHECKPOINT_PAGES: i32 = 1_000;
189
190/// Default `k` constant used by Reciprocal Rank Fusion in `hybrid-search`.
191pub const RRF_K_DEFAULT: u32 = 60;
192
193/// Chunk size expressed in tokens for body splitting.
194pub const CHUNK_SIZE_TOKENS: usize = 400;
195
196/// Token overlap between consecutive chunks.
197pub const CHUNK_OVERLAP_TOKENS: usize = 50;
198
199/// Explicit operational guard for multi-chunk documents in `remember`.
200///
201/// The multi-chunk path uses serial embeddings to avoid ONNX memory amplification.
202/// This limit preserves a clear operational ceiling for agents and scripts.
203pub const REMEMBER_MAX_SAFE_MULTI_CHUNKS: usize = 512;
204
205/// Ceiling on chunks per controlled micro-batch in `remember`.
206///
207/// The `fastembed` runtime uses `BatchLongest` padding, so oversized batches amplify
208/// the cost of the longest chunk. This ceiling keeps batches small even when chunks are short.
209pub const REMEMBER_MAX_CONTROLLED_BATCH_CHUNKS: usize = 4;
210
211/// Maximum padded-token budget per controlled micro-batch in `remember`.
212///
213/// The budget uses `max_tokens_no_batch * batch_size`, approximating the real cost of
214/// `BatchLongest` padding. Values exceeding this fall back to smaller batches or serialisation.
215pub const REMEMBER_MAX_CONTROLLED_BATCH_PADDED_TOKENS: usize = 512;
216
217/// Prefix prepended to bodies before embedding as required by E5 models.
218pub const PASSAGE_PREFIX: &str = "passage: ";
219
220/// Prefix prepended to queries before embedding as required by E5 models.
221pub const QUERY_PREFIX: &str = "query: ";
222
223/// Crate version string sourced from `CARGO_PKG_VERSION` at build time.
224pub const SQLITE_GRAPHRAG_VERSION: &str = env!("CARGO_PKG_VERSION");
225
226/// Batch size for GLiNER NER forward passes.
227///
228/// Larger values amortise fixed forward-pass overhead but increase peak RAM.
229/// Memory guide (CPU only, max 512-token windows):
230/// N=4 → ~54 MiB peak
231/// N=8 → ~108 MiB peak ← default
232/// N=16 → ~216 MiB peak
233/// N=32 → ~432 MiB peak (not recommended without 16+ GiB RAM)
234///
235/// Override via `GRAPHRAG_NER_BATCH_SIZE` env var. Values outside [1, 32] are
236/// clamped silently.
237pub fn ner_batch_size() -> usize {
238 std::env::var("GRAPHRAG_NER_BATCH_SIZE")
239 .ok()
240 .and_then(|v| v.parse::<usize>().ok())
241 .unwrap_or(8)
242 .clamp(1, 32)
243}
244
245/// Default cap on tokens fed to GLiNER NER per memory body.
246///
247/// v1.0.31: large markdown documents (>50 KB) tokenise into thousands of
248/// 512-token windows, each requiring a CPU forward pass that takes hundreds
249/// of milliseconds. A 68 KB document was observed taking 5+ minutes.
250/// Truncating the input before sliding-window construction caps the worst-case
251/// latency while preserving extraction quality for the leading body region.
252///
253/// Regex prefilter still runs on the full body, so URLs, emails, UUIDs,
254/// all-caps identifiers and CamelCase brand names are extracted regardless.
255pub const EXTRACTION_MAX_TOKENS_DEFAULT: usize = 5_000;
256
257/// Resolves the per-body NER token cap, honouring the env-var override.
258///
259/// Override via `SQLITE_GRAPHRAG_EXTRACTION_MAX_TOKENS` env var. Values outside
260/// [512, 100_000] fall back to [`EXTRACTION_MAX_TOKENS_DEFAULT`].
261pub fn extraction_max_tokens() -> usize {
262 std::env::var("SQLITE_GRAPHRAG_EXTRACTION_MAX_TOKENS")
263 .ok()
264 .and_then(|v| v.parse::<usize>().ok())
265 .filter(|&n| (512..=100_000).contains(&n))
266 .unwrap_or(EXTRACTION_MAX_TOKENS_DEFAULT)
267}
268
269/// GLiNER confidence threshold for span scoring.
270///
271/// Override via `SQLITE_GRAPHRAG_GLINER_THRESHOLD` env var. Values outside
272/// `[0.0, 1.0]` are ignored and the default `0.5` is used.
273pub fn gliner_confidence_threshold() -> f32 {
274 std::env::var("SQLITE_GRAPHRAG_GLINER_THRESHOLD")
275 .ok()
276 .and_then(|v| v.parse::<f32>().ok())
277 .filter(|&v| (0.0..=1.0).contains(&v))
278 .unwrap_or(0.5)
279}
280
281/// HuggingFace repository for the GLiNER ONNX model.
282///
283/// Override via `SQLITE_GRAPHRAG_GLINER_MODEL` env var.
284pub fn gliner_model_repo() -> String {
285 std::env::var("SQLITE_GRAPHRAG_GLINER_MODEL")
286 .unwrap_or_else(|_| "onnx-community/gliner_multi-v2.1".to_string())
287}
288
289/// PRD-canonical regex that validates names and namespaces. Allows 1 char `[a-z0-9]`
290/// OR a 2-80 char string starting with a letter and ending with a letter/digit,
291/// containing only `[a-z0-9-]`. Rejects the `__` prefix (internal reserved).
292pub const NAME_SLUG_REGEX: &str = r"^[a-z][a-z0-9-]{0,78}[a-z0-9]$|^[a-z0-9]$";
293
294static NAME_SLUG_RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
295
296/// Returns a reference to the compiled [`NAME_SLUG_REGEX`] pattern.
297/// Compiled once on first call, cached via `OnceLock`.
298pub fn name_slug_regex() -> &'static regex::Regex {
299 NAME_SLUG_RE.get_or_init(|| {
300 regex::Regex::new(NAME_SLUG_REGEX).expect("NAME_SLUG_REGEX is a valid pattern")
301 })
302}
303
304/// Default retention period (days) used by `purge` when `--retention-days` is omitted.
305pub const PURGE_RETENTION_DAYS_DEFAULT: u32 = 90;
306
307/// Maximum number of simultaneously active namespaces (deleted_at IS NULL). Exit 5 when exceeded.
308pub const MAX_NAMESPACES_ACTIVE: u32 = 100;
309
310/// Maximum tokens accepted by an embedding input before chunking.
311pub const EMBEDDING_MAX_TOKENS: usize = 512;
312
313/// Maximum result count from the recursive graph CTE in `recall`.
314pub const K_GRAPH_MATCHES_LIMIT: usize = 20;
315
316/// Default `--limit` for `list` when omitted.
317pub const K_LIST_DEFAULT_LIMIT: usize = 100;
318
319/// Default `--limit` for `graph entities` when omitted.
320pub const K_GRAPH_ENTITIES_DEFAULT_LIMIT: usize = 50;
321
322/// Default `--limit` for `related` when omitted.
323pub const K_RELATED_DEFAULT_LIMIT: usize = 10;
324
325/// Default `--limit` for `history` when omitted.
326pub const K_HISTORY_DEFAULT_LIMIT: usize = 20;
327
328/// Default weight for the vector contribution in the `hybrid-search` RRF formula.
329pub const WEIGHT_VEC_DEFAULT: f64 = 1.0;
330
331/// Default weight for the BM25 text contribution in the `hybrid-search` RRF formula.
332pub const WEIGHT_FTS_DEFAULT: f64 = 1.0;
333
334/// Character size of the body preview emitted in text/markdown formats.
335pub const TEXT_BODY_PREVIEW_LEN: usize = 200;
336
337/// Default value injected into ORT_NUM_THREADS when not set by the user.
338pub const ORT_NUM_THREADS_DEFAULT: &str = "1";
339
340/// Default value injected into ORT_INTRA_OP_NUM_THREADS when not set.
341pub const ORT_INTRA_OP_NUM_THREADS_DEFAULT: &str = "1";
342
343/// Default value injected into OMP_NUM_THREADS when not set by the user.
344pub const OMP_NUM_THREADS_DEFAULT: &str = "1";
345
346/// Exit code for partial batch failure (PRD line 1822). Conflicts with DbBusy in v1.x;
347/// in v2.0.0 DbBusy migrates to 15 and this code takes 13 per PRD.
348pub const BATCH_PARTIAL_FAILURE_EXIT_CODE: i32 = 13;
349
350/// Exit code for DbBusy in v2.0.0 (migrated from 13 to free 13 for batch failure).
351pub const DB_BUSY_EXIT_CODE: i32 = 15;
352
353/// Filename used for the advisory exclusive lock that prevents parallel invocations.
354pub const CLI_LOCK_FILE: &str = "cli.lock";
355
356/// Polling interval in milliseconds used by `--wait-lock` between `try_lock_exclusive` attempts.
357pub const CLI_LOCK_POLL_INTERVAL_MS: u64 = 500;
358
359/// Process exit code returned when the lock is busy and no wait was requested (EX_TEMPFAIL).
360pub const CLI_LOCK_EXIT_CODE: i32 = 75;
361
362/// Maximum number of CLI instances running simultaneously.
363///
364/// Limits the counting
365/// semaphore in [`crate::lock`] to prevent memory overload when multiple parallel
366/// v1.0.75 (G18 solution): removed the rigid 4-slot ceiling. The adaptive
367/// `calculate_safe_concurrency` function in [`crate::lock`]` now reports
368/// the dynamic limit. This constant is preserved as a *legacy fallback*
369/// when the dynamic calculation cannot be performed (e.g. when `sysinfo`
370/// cannot read `/proc/meminfo`).
371///
372/// Operators should prefer passing `--max-concurrency` explicitly OR
373/// letting the runtime compute the limit. The default ceiling is intentionally
374/// higher (16) so the legacy 4-slot hard cap does not silently reappear.
375pub const MAX_CONCURRENT_CLI_INSTANCES: usize = 16;
376
377/// G28-B (v1.0.68): polling interval in milliseconds used by
378/// `acquire_job_singleton` between retry attempts when another invocation
379/// already holds the singleton for `(job_type, namespace)`.
380pub const JOB_SINGLETON_POLL_INTERVAL_MS: u64 = 1000;
381
382/// Minimum available memory in MiB required before starting model loading.
383///
384/// If `sysinfo::System::available_memory() / 1_048_576` falls below this value,
385/// the invocation is aborted with [`crate::errors::AppError::LowMemory`]
386/// (exit code [`LOW_MEMORY_EXIT_CODE`]).
387pub const MIN_AVAILABLE_MEMORY_MB: u64 = 2_048;
388
389/// Maximum process RSS in MiB before aborting embedding operations.
390/// Users can override via `--max-rss-mb`. Set to 8 GiB by default.
391pub const DEFAULT_MAX_RSS_MB: u64 = 8_192;
392
393/// Maximum time in seconds an instance waits to acquire a concurrency slot.
394///
395/// Passed as the default for `--max-wait-secs` in the CLI. After exhausting this limit,
396/// the invocation returns [`crate::errors::AppError::AllSlotsFull`] with exit code
397/// [`CLI_LOCK_EXIT_CODE`] (75).
398pub const CLI_LOCK_DEFAULT_WAIT_SECS: u64 = 300;
399
400/// v1.0.75 (G18 + G23): expected RSS in MiB for an LLM-only worker that
401/// spawns a `claude -p` or `codex exec` subprocess. Much lower than the
402/// embedding cost because the ONNX model is not loaded per-worker.
403pub const LLM_WORKER_RSS_MB: u64 = 350;
404
405/// Process exit code returned when available memory is below [`MIN_AVAILABLE_MEMORY_MB`].
406///
407/// Value `77` is `EX_NOPERM` in glibc sysexits, reused here to indicate
408/// "insufficient system resource to proceed".
409pub const LOW_MEMORY_EXIT_CODE: i32 = 77;
410
411/// Process exit code returned when a duplicate memory or entity is detected (exit 9).
412///
413/// Moved from `2` to `9` in v1.0.52 to free exit code `2` for future use and align
414/// with the PRD exit code contract. Shell callers and LLM agents must use `9` from
415/// this version onwards.
416pub const DUPLICATE_EXIT_CODE: i32 = 9;
417
418/// Canonical value of `PRAGMA user_version` written after migrations.
419///
420/// **Why 49 instead of `CURRENT_SCHEMA_VERSION` (9)?**
421/// `user_version` is a 32-bit integer that SQLite reserves for application use.
422/// We deliberately set it to a project-specific marker (49 = decimal) so external
423/// inspection tools (`sqlite3 db.sqlite "PRAGMA user_version"`, the `file` command,
424/// SQLite browser GUIs) can distinguish a sqlite-graphrag database from a generic
425/// SQLite file at a glance. The application-level schema version (9, matching
426/// `CURRENT_SCHEMA_VERSION`) is stored in the `schema_meta` table and exposed via
427/// `health --json`/`stats --json`. Bumping migrations does NOT change this constant.
428/// Refinery uses its own `refinery_schema_history` table for migration bookkeeping.
429pub const SCHEMA_USER_VERSION: i64 = 50;
430
431/// Current schema version, equal to the highest migration number in `migrations/Vnnn__*.sql`.
432///
433/// Added in v1.0.27 as a runtime and test sanity check.
434/// Must be bumped in sync with new Refinery migrations; the unit test
435/// `schema_version_matches_migrations_count` validates this automatically.
436pub const CURRENT_SCHEMA_VERSION: u32 = 13;
437
438#[cfg(test)]
439mod tests_schema_version {
440 use super::CURRENT_SCHEMA_VERSION;
441
442 #[test]
443 fn schema_version_matches_migrations_count() {
444 let manifest_dir = env!("CARGO_MANIFEST_DIR");
445 let migrations_dir = std::path::Path::new(manifest_dir).join("migrations");
446 let count = std::fs::read_dir(&migrations_dir)
447 .expect("migrations directory must exist")
448 .filter_map(|entry| entry.ok())
449 .filter(|entry| entry.file_name().to_string_lossy().starts_with('V'))
450 .count() as u32;
451 assert_eq!(
452 CURRENT_SCHEMA_VERSION, count,
453 "CURRENT_SCHEMA_VERSION ({CURRENT_SCHEMA_VERSION}) must equal the number of V*.sql migrations ({count})"
454 );
455 }
456}