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