Skip to main content

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/// Timeout in milliseconds for a single ping probe against the daemon socket.
126pub const DAEMON_PING_TIMEOUT_MS: u64 = 10;
127
128/// Idle duration in seconds before the daemon shuts itself down.
129pub const DAEMON_IDLE_SHUTDOWN_SECS: u64 = 600;
130
131/// Prefix prepended to bodies before embedding as required by E5 models.
132pub const PASSAGE_PREFIX: &str = "passage: ";
133
134/// Prefix prepended to queries before embedding as required by E5 models.
135pub const QUERY_PREFIX: &str = "query: ";
136
137/// Crate version string sourced from `CARGO_PKG_VERSION` at build time.
138pub const SQLITE_GRAPHRAG_VERSION: &str = env!("CARGO_PKG_VERSION");
139
140/// PRD-canonical regex que valida nomes e namespaces. Permite 1 char `[a-z0-9]`
141/// OU string de 2-80 chars começando com letra e terminando com letra/dígito,
142/// contendo apenas `[a-z0-9-]`. Rejeita prefixo `__` (internal reserved).
143pub const NAME_SLUG_REGEX: &str = r"^[a-z][a-z0-9-]{0,78}[a-z0-9]$|^[a-z0-9]$";
144
145/// Retenção padrão (dias) usada por `purge` quando `--retention-days` é omitido.
146pub const PURGE_RETENTION_DAYS_DEFAULT: u32 = 90;
147
148/// Limite máximo de namespaces ativos (deleted_at IS NULL) simultâneos. Exit 5 ao exceder.
149pub const MAX_NAMESPACES_ACTIVE: u32 = 100;
150
151/// Máximo de tokens aceito por embedding input antes de chunking.
152pub const EMBEDDING_MAX_TOKENS: usize = 512;
153
154/// Limite máximo de resultados da CTE recursiva de grafo em `recall`.
155pub const K_GRAPH_MATCHES_LIMIT: usize = 20;
156
157/// Default `--limit` para `list` quando omitido.
158pub const K_LIST_DEFAULT_LIMIT: usize = 100;
159
160/// Default `--limit` para `graph entities` quando omitido.
161pub const K_GRAPH_ENTITIES_DEFAULT_LIMIT: usize = 50;
162
163/// Default `--limit` para `related` quando omitido.
164pub const K_RELATED_DEFAULT_LIMIT: usize = 10;
165
166/// Default `--limit` para `history` quando omitido.
167pub const K_HISTORY_DEFAULT_LIMIT: usize = 20;
168
169/// Peso padrão da contribuição vetorial na fórmula RRF de `hybrid-search`.
170pub const WEIGHT_VEC_DEFAULT: f64 = 1.0;
171
172/// Peso padrão da contribuição textual BM25 na fórmula RRF de `hybrid-search`.
173pub const WEIGHT_FTS_DEFAULT: f64 = 1.0;
174
175/// Tamanho em caracteres do preview do body emitido em formatos text/markdown.
176pub const TEXT_BODY_PREVIEW_LEN: usize = 200;
177
178/// Valor default injetado em ORT_NUM_THREADS quando não definido pelo usuário.
179pub const ORT_NUM_THREADS_DEFAULT: &str = "1";
180
181/// Valor default injetado em ORT_INTRA_OP_NUM_THREADS quando não definido.
182pub const ORT_INTRA_OP_NUM_THREADS_DEFAULT: &str = "1";
183
184/// Valor default injetado em OMP_NUM_THREADS quando não definido pelo usuário.
185pub const OMP_NUM_THREADS_DEFAULT: &str = "1";
186
187/// Exit code para falha parcial de batch (PRD linha 1822). Conflita com DbBusy em v1.x;
188/// em v2.0.0 DbBusy migra para 15 e este código assume 13 conforme PRD.
189pub const BATCH_PARTIAL_FAILURE_EXIT_CODE: i32 = 13;
190
191/// Exit code para DbBusy em v2.0.0 (migrado de 13 para liberar 13 para batch failure).
192pub const DB_BUSY_EXIT_CODE: i32 = 15;
193
194/// Filename used for the advisory exclusive lock that prevents parallel invocations.
195pub const CLI_LOCK_FILE: &str = "cli.lock";
196
197/// Polling interval em milliseconds usado por `--wait-lock` entre tentativas de `try_lock_exclusive`.
198pub const CLI_LOCK_POLL_INTERVAL_MS: u64 = 500;
199
200/// Process exit code returned when the lock is busy and no wait was requested (EX_TEMPFAIL).
201pub const CLI_LOCK_EXIT_CODE: i32 = 75;
202
203/// Número máximo de instâncias CLI em execução simultânea.
204///
205/// Alinhado com `DAEMON_MAX_CONCURRENT_CLIENTS` do PRD. Limita o semáforo de
206/// contagem em [`crate::lock`] para evitar sobrecarga de memória quando múltiplas
207/// invocações paralelas tentam carregar o modelo ONNX simultaneamente.
208pub const MAX_CONCURRENT_CLI_INSTANCES: usize = 4;
209
210/// Memória disponível mínima em MiB exigida antes de iniciar o carregamento do modelo.
211///
212/// Se `sysinfo::System::available_memory() / 1_048_576` estiver abaixo deste
213/// valor, a invocação é abortada com [`crate::errors::AppError::LowMemory`]
214/// (exit code [`LOW_MEMORY_EXIT_CODE`]).
215pub const MIN_AVAILABLE_MEMORY_MB: u64 = 2_048;
216
217/// Tempo máximo em segundos que uma instância aguarda para adquirir um slot de concorrência.
218///
219/// Passado como default de `--max-wait-secs` na CLI. Após esgotar este limite,
220/// a invocação retorna [`crate::errors::AppError::AllSlotsFull`] com exit code
221/// [`CLI_LOCK_EXIT_CODE`] (75).
222pub const CLI_LOCK_DEFAULT_WAIT_SECS: u64 = 300;
223
224/// RSS esperado em MiB de uma única instância com o modelo ONNX carregado via fastembed.
225///
226/// Usado na fórmula `min(cpus, available_memory_mb / EMBEDDING_LOAD_EXPECTED_RSS_MB) * 0.5`
227/// para calcular o número dinâmico de permits.
228///
229/// Valor calibrado em 2026-04-23 com `/usr/bin/time -v` sobre `sqlite-graphrag v1.0.3`
230/// nos comandos pesados `remember`, `recall` e `hybrid-search`, todos com pico de RSS
231/// próximo de 1.03 GiB por processo. O valor abaixo arredonda para cima com margem defensiva.
232pub const EMBEDDING_LOAD_EXPECTED_RSS_MB: u64 = 1_100;
233
234/// Process exit code retornado quando memória disponível está abaixo de [`MIN_AVAILABLE_MEMORY_MB`].
235///
236/// Valor `77` é `EX_NOPERM` na glibc sysexits, reutilizado aqui para indicar
237/// "recurso de sistema insuficiente para prosseguir".
238pub const LOW_MEMORY_EXIT_CODE: i32 = 77;
239
240/// Valor canônico de `PRAGMA user_version` gravado após migrações.
241///
242/// Deve permanecer em sincronia com o identificador legível-por-humanos
243/// da versão do schema. Refinery usa sua própria tabela de histórico;
244/// `user_version` é um campo auxiliar de diagnóstico para ferramentas
245/// externas (ex: `sqlite3 db.sqlite "PRAGMA user_version"`).
246pub const SCHEMA_USER_VERSION: i64 = 49;