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/// Guard operacional explícito para documentos multi-chunk no `remember`.
108///
109/// Enquanto o bug crítico de crescimento explosivo de memória não for totalmente eliminado,
110/// documentos que geram mais de 6 chunks são rejeitados antes do embedding.
111///
112/// Limite calibrado a partir da auditoria segura da `v1.0.4` publicada sob `MemoryMax=4G`:
113/// documentos com 6 chunks passaram, enquanto documentos moderados que implicaram 7+ chunks
114/// ainda acionaram OOM no caminho de `remember`.
115pub const REMEMBER_MAX_SAFE_MULTI_CHUNKS: usize = 6;
116
117/// Guard operacional temporário por tamanho do body quando `remember` entra no caminho multi-chunk.
118///
119/// A auditoria segura da `v1.0.4` e da `v1.0.5` mostrou que documentos reais densos já
120/// estouravam OOM entre `4141` bytes (passou) e `4540` bytes (falhou) sob `MemoryMax=4G`.
121/// Até a causa raiz final ser eliminada, corpos multi-chunk acima deste valor são rejeitados
122/// antes de qualquer trabalho ONNX.
123pub const REMEMBER_MAX_SAFE_MULTI_CHUNK_BODY_BYTES: usize = 4_500;
124
125/// Teto de chunks por micro-batch controlado no `remember`.
126///
127/// O runtime do `fastembed` usa padding `BatchLongest`, então batches muito grandes amplificam
128/// o custo do maior chunk. Este teto mantém batches pequenos mesmo quando os chunks são curtos.
129pub const REMEMBER_MAX_CONTROLLED_BATCH_CHUNKS: usize = 4;
130
131/// Orçamento máximo de tokens preenchidos por micro-batch controlado no `remember`.
132///
133/// O orçamento usa `max_tokens_no_batch * tamanho_do_batch`, aproximando o custo real do
134/// padding `BatchLongest`. Valores acima disso voltam para batches menores ou serialização.
135pub const REMEMBER_MAX_CONTROLLED_BATCH_PADDED_TOKENS: usize = 512;
136
137/// Timeout in milliseconds for a single ping probe against the daemon socket.
138pub const DAEMON_PING_TIMEOUT_MS: u64 = 10;
139
140/// Idle duration in seconds before the daemon shuts itself down.
141pub const DAEMON_IDLE_SHUTDOWN_SECS: u64 = 600;
142
143/// Tempo máximo de espera para o daemon ficar saudável após auto-start.
144pub const DAEMON_AUTO_START_MAX_WAIT_MS: u64 = 5_000;
145
146/// Intervalo inicial de polling para verificar se o daemon ficou saudável.
147pub const DAEMON_AUTO_START_INITIAL_BACKOFF_MS: u64 = 50;
148
149/// Teto do backoff entre tentativas automáticas de spawn do daemon.
150pub const DAEMON_AUTO_START_MAX_BACKOFF_MS: u64 = 30_000;
151
152/// Backoff base usado após falhas de spawn/health do daemon.
153pub const DAEMON_SPAWN_BACKOFF_BASE_MS: u64 = 500;
154
155/// Tempo máximo de espera para obter o lock de spawn do daemon.
156pub const DAEMON_SPAWN_LOCK_WAIT_MS: u64 = 2_000;
157
158/// Prefix prepended to bodies before embedding as required by E5 models.
159pub const PASSAGE_PREFIX: &str = "passage: ";
160
161/// Prefix prepended to queries before embedding as required by E5 models.
162pub const QUERY_PREFIX: &str = "query: ";
163
164/// Crate version string sourced from `CARGO_PKG_VERSION` at build time.
165pub const SQLITE_GRAPHRAG_VERSION: &str = env!("CARGO_PKG_VERSION");
166
167/// PRD-canonical regex que valida nomes e namespaces. Permite 1 char `[a-z0-9]`
168/// OU string de 2-80 chars começando com letra e terminando com letra/dígito,
169/// contendo apenas `[a-z0-9-]`. Rejeita prefixo `__` (internal reserved).
170pub const NAME_SLUG_REGEX: &str = r"^[a-z][a-z0-9-]{0,78}[a-z0-9]$|^[a-z0-9]$";
171
172/// Retenção padrão (dias) usada por `purge` quando `--retention-days` é omitido.
173pub const PURGE_RETENTION_DAYS_DEFAULT: u32 = 90;
174
175/// Limite máximo de namespaces ativos (deleted_at IS NULL) simultâneos. Exit 5 ao exceder.
176pub const MAX_NAMESPACES_ACTIVE: u32 = 100;
177
178/// Máximo de tokens aceito por embedding input antes de chunking.
179pub const EMBEDDING_MAX_TOKENS: usize = 512;
180
181/// Limite máximo de resultados da CTE recursiva de grafo em `recall`.
182pub const K_GRAPH_MATCHES_LIMIT: usize = 20;
183
184/// Default `--limit` para `list` quando omitido.
185pub const K_LIST_DEFAULT_LIMIT: usize = 100;
186
187/// Default `--limit` para `graph entities` quando omitido.
188pub const K_GRAPH_ENTITIES_DEFAULT_LIMIT: usize = 50;
189
190/// Default `--limit` para `related` quando omitido.
191pub const K_RELATED_DEFAULT_LIMIT: usize = 10;
192
193/// Default `--limit` para `history` quando omitido.
194pub const K_HISTORY_DEFAULT_LIMIT: usize = 20;
195
196/// Peso padrão da contribuição vetorial na fórmula RRF de `hybrid-search`.
197pub const WEIGHT_VEC_DEFAULT: f64 = 1.0;
198
199/// Peso padrão da contribuição textual BM25 na fórmula RRF de `hybrid-search`.
200pub const WEIGHT_FTS_DEFAULT: f64 = 1.0;
201
202/// Tamanho em caracteres do preview do body emitido em formatos text/markdown.
203pub const TEXT_BODY_PREVIEW_LEN: usize = 200;
204
205/// Valor default injetado em ORT_NUM_THREADS quando não definido pelo usuário.
206pub const ORT_NUM_THREADS_DEFAULT: &str = "1";
207
208/// Valor default injetado em ORT_INTRA_OP_NUM_THREADS quando não definido.
209pub const ORT_INTRA_OP_NUM_THREADS_DEFAULT: &str = "1";
210
211/// Valor default injetado em OMP_NUM_THREADS quando não definido pelo usuário.
212pub const OMP_NUM_THREADS_DEFAULT: &str = "1";
213
214/// Exit code para falha parcial de batch (PRD linha 1822). Conflita com DbBusy em v1.x;
215/// em v2.0.0 DbBusy migra para 15 e este código assume 13 conforme PRD.
216pub const BATCH_PARTIAL_FAILURE_EXIT_CODE: i32 = 13;
217
218/// Exit code para DbBusy em v2.0.0 (migrado de 13 para liberar 13 para batch failure).
219pub const DB_BUSY_EXIT_CODE: i32 = 15;
220
221/// Filename used for the advisory exclusive lock that prevents parallel invocations.
222pub const CLI_LOCK_FILE: &str = "cli.lock";
223
224/// Polling interval em milliseconds usado por `--wait-lock` entre tentativas de `try_lock_exclusive`.
225pub const CLI_LOCK_POLL_INTERVAL_MS: u64 = 500;
226
227/// Process exit code returned when the lock is busy and no wait was requested (EX_TEMPFAIL).
228pub const CLI_LOCK_EXIT_CODE: i32 = 75;
229
230/// Número máximo de instâncias CLI em execução simultânea.
231///
232/// Alinhado com `DAEMON_MAX_CONCURRENT_CLIENTS` do PRD. Limita o semáforo de
233/// contagem em [`crate::lock`] para evitar sobrecarga de memória quando múltiplas
234/// invocações paralelas tentam carregar o modelo ONNX simultaneamente.
235pub const MAX_CONCURRENT_CLI_INSTANCES: usize = 4;
236
237/// Memória disponível mínima em MiB exigida antes de iniciar o carregamento do modelo.
238///
239/// Se `sysinfo::System::available_memory() / 1_048_576` estiver abaixo deste
240/// valor, a invocação é abortada com [`crate::errors::AppError::LowMemory`]
241/// (exit code [`LOW_MEMORY_EXIT_CODE`]).
242pub const MIN_AVAILABLE_MEMORY_MB: u64 = 2_048;
243
244/// Tempo máximo em segundos que uma instância aguarda para adquirir um slot de concorrência.
245///
246/// Passado como default de `--max-wait-secs` na CLI. Após esgotar este limite,
247/// a invocação retorna [`crate::errors::AppError::AllSlotsFull`] com exit code
248/// [`CLI_LOCK_EXIT_CODE`] (75).
249pub const CLI_LOCK_DEFAULT_WAIT_SECS: u64 = 300;
250
251/// RSS esperado em MiB de uma única instância com o modelo ONNX carregado via fastembed.
252///
253/// Usado na fórmula `min(cpus, available_memory_mb / EMBEDDING_LOAD_EXPECTED_RSS_MB) * 0.5`
254/// para calcular o número dinâmico de permits.
255///
256/// Valor calibrado em 2026-04-23 com `/usr/bin/time -v` sobre `sqlite-graphrag v1.0.3`
257/// nos comandos pesados `remember`, `recall` e `hybrid-search`, todos com pico de RSS
258/// próximo de 1.03 GiB por processo. O valor abaixo arredonda para cima com margem defensiva.
259pub const EMBEDDING_LOAD_EXPECTED_RSS_MB: u64 = 1_100;
260
261/// Process exit code retornado quando memória disponível está abaixo de [`MIN_AVAILABLE_MEMORY_MB`].
262///
263/// Valor `77` é `EX_NOPERM` na glibc sysexits, reutilizado aqui para indicar
264/// "recurso de sistema insuficiente para prosseguir".
265pub const LOW_MEMORY_EXIT_CODE: i32 = 77;
266
267/// Valor canônico de `PRAGMA user_version` gravado após migrações.
268///
269/// Deve permanecer em sincronia com o identificador legível-por-humanos
270/// da versão do schema. Refinery usa sua própria tabela de histórico;
271/// `user_version` é um campo auxiliar de diagnóstico para ferramentas
272/// externas (ex: `sqlite3 db.sqlite "PRAGMA user_version"`).
273pub const SCHEMA_USER_VERSION: i64 = 49;