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//! ## Cálculo dinâmico de permits de concorrência
8//!
9//! O número máximo de instâncias simultâneas pode ser ajustado em runtime
10//! usando a fórmula:
11//!
12//! ```text
13//! permits = min(cpus, available_memory_mb / EMBEDDING_LOAD_EXPECTED_RSS_MB) * 0.5
14//! ```
15//!
16//! onde `available_memory_mb` é obtido via `sysinfo::System::available_memory()`
17//! convertido para MiB. O resultado é limitado superiormente por
18//! `MAX_CONCURRENT_CLI_INSTANCES` e inferiorizado em 1.
19
20/// Embedding vector dimensionality produced by `multilingual-e5-small`.
21pub const EMBEDDING_DIM: usize = 384;
22
23/// Default `fastembed` model identifier used by `remember` and `recall`.
24pub const FASTEMBED_MODEL_DEFAULT: &str = "multilingual-e5-small";
25
26/// Batch size for `fastembed` encoding calls.
27pub const FASTEMBED_BATCH_SIZE: usize = 32;
28
29/// Maximum byte length for a memory `name` field in kebab-case.
30pub const MAX_MEMORY_NAME_LEN: usize = 80;
31
32/// Maximum character length for a memory `description` field.
33pub const MAX_MEMORY_DESCRIPTION_LEN: usize = 500;
34
35/// Hard upper bound on memory `body` length in characters.
36pub const MAX_MEMORY_BODY_LEN: usize = 20_000;
37
38/// Body character count above which the body is split into chunks.
39pub const MAX_BODY_CHARS_BEFORE_CHUNK: usize = 8_000;
40
41/// Maximum attempts when a statement returns `SQLITE_BUSY`.
42pub const MAX_SQLITE_BUSY_RETRIES: u32 = 5;
43
44/// Query timeout applied to statements in milliseconds.
45pub const QUERY_TIMEOUT_MILLIS: u64 = 5_000;
46
47/// Jaccard threshold above which two memories are considered fuzzy duplicates.
48pub const DEDUP_FUZZY_THRESHOLD: f64 = 0.8;
49
50/// Cosine distance threshold below which two memories are semantic duplicates.
51pub const DEDUP_SEMANTIC_THRESHOLD: f32 = 0.1;
52
53/// Maximum number of hops allowed in graph traversals.
54pub const MAX_GRAPH_HOPS: u32 = 2;
55
56/// Minimum relationship weight required for traversal inclusion.
57pub const MIN_RELATION_WEIGHT: f64 = 0.3;
58
59/// Default traversal depth for `related` when `--hops` is omitted.
60pub const DEFAULT_MAX_HOPS: u32 = 2;
61
62/// Default minimum weight filter applied during graph traversal.
63pub const DEFAULT_MIN_WEIGHT: f64 = 0.3;
64
65/// Default weight assigned to newly created relationships.
66pub const DEFAULT_RELATION_WEIGHT: f64 = 0.5;
67
68/// Default `k` used by `recall` when the caller omits `--k`.
69pub const DEFAULT_K_RECALL: usize = 10;
70
71/// Default `k` for memory KNN searches when the caller omits `--k`.
72pub const K_MEMORIES_DEFAULT: usize = 10;
73
74/// Default `k` for entity KNN searches during graph expansion.
75pub const K_ENTITIES_SEARCH: usize = 5;
76
77/// Upper bound on distinct entities persisted per memory.
78pub const MAX_ENTITIES_PER_MEMORY: usize = 30;
79
80/// Upper bound on distinct relationships persisted per memory.
81pub const MAX_RELATIONSHIPS_PER_MEMORY: usize = 50;
82
83/// Character length of the description preview shown in `list` output.
84pub const TEXT_DESCRIPTION_PREVIEW_LEN: usize = 100;
85
86/// `PRAGMA busy_timeout` value applied on every connection.
87pub const BUSY_TIMEOUT_MILLIS: i32 = 5_000;
88
89/// `PRAGMA cache_size` value in kibibytes (negative means KiB).
90pub const CACHE_SIZE_KB: i32 = -64_000;
91
92/// `PRAGMA mmap_size` value in bytes applied to each connection.
93pub const MMAP_SIZE_BYTES: i64 = 268_435_456;
94
95/// `PRAGMA wal_autocheckpoint` threshold in pages.
96pub const WAL_AUTOCHECKPOINT_PAGES: i32 = 1_000;
97
98/// Default `k` constant used by Reciprocal Rank Fusion in `hybrid-search`.
99pub const RRF_K_DEFAULT: u32 = 60;
100
101/// Chunk size expressed in tokens for body splitting.
102pub const CHUNK_SIZE_TOKENS: usize = 400;
103
104/// Token overlap between consecutive chunks.
105pub const CHUNK_OVERLAP_TOKENS: usize = 50;
106
107/// Timeout in milliseconds for a single ping probe against the daemon socket.
108pub const DAEMON_PING_TIMEOUT_MS: u64 = 10;
109
110/// Idle duration in seconds before the daemon shuts itself down.
111pub const DAEMON_IDLE_SHUTDOWN_SECS: u64 = 600;
112
113/// Prefix prepended to bodies before embedding as required by E5 models.
114pub const PASSAGE_PREFIX: &str = "passage: ";
115
116/// Prefix prepended to queries before embedding as required by E5 models.
117pub const QUERY_PREFIX: &str = "query: ";
118
119/// Crate version string sourced from `CARGO_PKG_VERSION` at build time.
120pub const SQLITE_GRAPHRAG_VERSION: &str = env!("CARGO_PKG_VERSION");
121
122/// PRD-canonical regex que valida nomes e namespaces. Permite 1 char `[a-z0-9]`
123/// OU string de 2-80 chars começando com letra e terminando com letra/dígito,
124/// contendo apenas `[a-z0-9-]`. Rejeita prefixo `__` (internal reserved).
125pub const NAME_SLUG_REGEX: &str = r"^[a-z][a-z0-9-]{0,78}[a-z0-9]$|^[a-z0-9]$";
126
127/// Retenção padrão (dias) usada por `purge` quando `--retention-days` é omitido.
128pub const PURGE_RETENTION_DAYS_DEFAULT: u32 = 90;
129
130/// Limite máximo de namespaces ativos (deleted_at IS NULL) simultâneos. Exit 5 ao exceder.
131pub const MAX_NAMESPACES_ACTIVE: u32 = 100;
132
133/// Máximo de tokens aceito por embedding input antes de chunking.
134pub const EMBEDDING_MAX_TOKENS: usize = 512;
135
136/// Limite máximo de resultados da CTE recursiva de grafo em `recall`.
137pub const K_GRAPH_MATCHES_LIMIT: usize = 20;
138
139/// Default `--limit` para `list` quando omitido.
140pub const K_LIST_DEFAULT_LIMIT: usize = 100;
141
142/// Default `--limit` para `graph entities` quando omitido.
143pub const K_GRAPH_ENTITIES_DEFAULT_LIMIT: usize = 50;
144
145/// Default `--limit` para `related` quando omitido.
146pub const K_RELATED_DEFAULT_LIMIT: usize = 10;
147
148/// Default `--limit` para `history` quando omitido.
149pub const K_HISTORY_DEFAULT_LIMIT: usize = 20;
150
151/// Peso padrão da contribuição vetorial na fórmula RRF de `hybrid-search`.
152pub const WEIGHT_VEC_DEFAULT: f64 = 1.0;
153
154/// Peso padrão da contribuição textual BM25 na fórmula RRF de `hybrid-search`.
155pub const WEIGHT_FTS_DEFAULT: f64 = 1.0;
156
157/// Tamanho em caracteres do preview do body emitido em formatos text/markdown.
158pub const TEXT_BODY_PREVIEW_LEN: usize = 200;
159
160/// Valor default injetado em ORT_NUM_THREADS quando não definido pelo usuário.
161pub const ORT_NUM_THREADS_DEFAULT: &str = "1";
162
163/// Valor default injetado em ORT_INTRA_OP_NUM_THREADS quando não definido.
164pub const ORT_INTRA_OP_NUM_THREADS_DEFAULT: &str = "1";
165
166/// Valor default injetado em OMP_NUM_THREADS quando não definido pelo usuário.
167pub const OMP_NUM_THREADS_DEFAULT: &str = "1";
168
169/// Exit code para falha parcial de batch (PRD linha 1822). Conflita com DbBusy em v1.x;
170/// em v2.0.0 DbBusy migra para 15 e este código assume 13 conforme PRD.
171pub const BATCH_PARTIAL_FAILURE_EXIT_CODE: i32 = 13;
172
173/// Exit code para DbBusy em v2.0.0 (migrado de 13 para liberar 13 para batch failure).
174pub const DB_BUSY_EXIT_CODE: i32 = 15;
175
176/// Filename used for the advisory exclusive lock that prevents parallel invocations.
177pub const CLI_LOCK_FILE: &str = "cli.lock";
178
179/// Polling interval em milliseconds usado por `--wait-lock` entre tentativas de `try_lock_exclusive`.
180pub const CLI_LOCK_POLL_INTERVAL_MS: u64 = 500;
181
182/// Process exit code returned when the lock is busy and no wait was requested (EX_TEMPFAIL).
183pub const CLI_LOCK_EXIT_CODE: i32 = 75;
184
185/// Número máximo de instâncias CLI em execução simultânea.
186///
187/// Alinhado com `DAEMON_MAX_CONCURRENT_CLIENTS` do PRD. Limita o semáforo de
188/// contagem em [`crate::lock`] para evitar sobrecarga de memória quando múltiplas
189/// invocações paralelas tentam carregar o modelo ONNX simultaneamente.
190pub const MAX_CONCURRENT_CLI_INSTANCES: usize = 4;
191
192/// Memória disponível mínima em MiB exigida antes de iniciar o carregamento do modelo.
193///
194/// Se `sysinfo::System::available_memory() / 1_048_576` estiver abaixo deste
195/// valor, a invocação é abortada com [`crate::errors::AppError::LowMemory`]
196/// (exit code [`LOW_MEMORY_EXIT_CODE`]).
197pub const MIN_AVAILABLE_MEMORY_MB: u64 = 2_048;
198
199/// Tempo máximo em segundos que uma instância aguarda para adquirir um slot de concorrência.
200///
201/// Passado como default de `--max-wait-secs` na CLI. Após esgotar este limite,
202/// a invocação retorna [`crate::errors::AppError::AllSlotsFull`] com exit code
203/// [`CLI_LOCK_EXIT_CODE`] (75).
204pub const CLI_LOCK_DEFAULT_WAIT_SECS: u64 = 300;
205
206/// RSS esperado em MiB de uma única instância com o modelo ONNX carregado via fastembed.
207///
208/// Usado na fórmula `min(cpus, available_memory_mb / EMBEDDING_LOAD_EXPECTED_RSS_MB) * 0.5`
209/// para calcular o número dinâmico de permits.
210///
211/// Valor calibrado em 2026-04-23 com `/usr/bin/time -v` sobre `sqlite-graphrag v1.0.3`
212/// nos comandos pesados `remember`, `recall` e `hybrid-search`, todos com pico de RSS
213/// próximo de 1.03 GiB por processo. O valor abaixo arredonda para cima com margem defensiva.
214pub const EMBEDDING_LOAD_EXPECTED_RSS_MB: u64 = 1_100;
215
216/// Process exit code retornado quando memória disponível está abaixo de [`MIN_AVAILABLE_MEMORY_MB`].
217///
218/// Valor `77` é `EX_NOPERM` na glibc sysexits, reutilizado aqui para indicar
219/// "recurso de sistema insuficiente para prosseguir".
220pub const LOW_MEMORY_EXIT_CODE: i32 = 77;
221
222/// Valor canônico de `PRAGMA user_version` gravado após migrações.
223///
224/// Deve permanecer em sincronia com o identificador legível-por-humanos
225/// da versão do schema. Refinery usa sua própria tabela de histórico;
226/// `user_version` é um campo auxiliar de diagnóstico para ferramentas
227/// externas (ex: `sqlite3 db.sqlite "PRAGMA user_version"`).
228pub const SCHEMA_USER_VERSION: i64 = 49;