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 for a NEWLY created database.
21///
22/// Sized for `qwen/qwen3-embedding-8b`, the model the OpenRouter REST backend
23/// uses today. Matryoshka Representation Learning (MRL, arXiv 2205.13147) lets
24/// a prefix of the native vector stand on its own, so 1024 is a real truncation
25/// point rather than a lossy resize.
26///
27/// This value governs `init` only. An existing database keeps the width
28/// recorded in `schema_meta.dim`, which [`crate::storage::connection`] adopts on
29/// every open — so raising this default can never silently reinterpret vectors
30/// already on disk. Widening a populated database is a deliberate migration
31/// that must re-embed every row; the previous default was 384, generated
32/// against `multilingual-e5-small`.
33///
34/// Precedence for the active dim is documented on [`embedding_dim`].
35pub const DEFAULT_EMBEDDING_DIM: usize = 1024;
36
37/// Default tracing filter level when neither CLI `-v`/`-q` nor XDG `log.level`
38/// is set (GAP-SG-93).
39pub const DEFAULT_LOG_LEVEL: &str = "info";
40
41/// Default OpenRouter chat completions endpoint (override via XDG
42/// `network.openrouter.chat_url` or alias `network.chat_url`).
43pub const DEFAULT_OPENROUTER_CHAT_URL: &str = "https://openrouter.ai/api/v1/chat/completions";
44
45/// Default OpenRouter embeddings endpoint (override via XDG
46/// `network.openrouter.embeddings_url` or alias `network.embed_url`).
47pub const DEFAULT_OPENROUTER_EMBEDDINGS_URL: &str = "https://openrouter.ai/api/v1/embeddings";
48
49/// Fail-fast probe budget for LLM backends before spawning (ms).
50/// Override via XDG `llm.probe_timeout_ms`.
51pub const DEFAULT_LLM_PROBE_TIMEOUT_MS: u64 = 800;
52
53/// Per-call timeout for query embedding (recall/hybrid Auto chain).
54/// Short budget so dead OAuth falls back to FTS quickly (GAP-E2E-06).
55/// Override via XDG `llm.query_embed_timeout_secs`.
56pub const DEFAULT_QUERY_EMBED_TIMEOUT_SECS: u64 = 3;
57
58/// Accepted range for any embedding dimensionality, override or recorded.
59///
60/// Declared once because the bound is checked on the CLI/XDG override, on the
61/// value adopted from `schema_meta`, and in the warning text. Three separate
62/// literals would be three chances to drift.
63pub const EMBEDDING_DIM_RANGE: std::ops::RangeInclusive<usize> = 8..=4096;
64
65/// Active embedding dimensionality for this process. `0` means unresolved.
66static ACTIVE_EMBEDDING_DIM: std::sync::atomic::AtomicUsize =
67 std::sync::atomic::AtomicUsize::new(0);
68
69/// Resolves the active embedding dimensionality (single source of truth).
70///
71/// Precedence (G-T-XDG-04):
72/// 1. CLI `--embedding-dim` / XDG `embedding.dim` via [`crate::runtime_config`];
73/// 2. the value recorded via [`set_active_embedding_dim`] — from `schema_meta`;
74/// 3. [`DEFAULT_EMBEDDING_DIM`].
75pub fn embedding_dim() -> usize {
76 if let Some(dim) = embedding_dim_from_runtime() {
77 return dim;
78 }
79 let active = ACTIVE_EMBEDDING_DIM.load(std::sync::atomic::Ordering::Acquire);
80 if active != 0 {
81 return active;
82 }
83 DEFAULT_EMBEDDING_DIM
84}
85
86/// Reads the CLI `--embedding-dim` flag or the XDG key `embedding.dim`.
87///
88/// Values outside [`EMBEDDING_DIM_RANGE`] are rejected with a warning rather
89/// than clamped: a clamped width would still mismatch the stored vectors, and
90/// `cosine_similarity` reports a dimension mismatch as `0.0` with no error, so
91/// the search would go quiet instead of failing.
92pub fn embedding_dim_from_runtime() -> Option<usize> {
93 let n = crate::runtime_config::embedding_dim_override()? as usize;
94 if EMBEDDING_DIM_RANGE.contains(&n) {
95 Some(n)
96 } else {
97 tracing::warn!(
98 value = n,
99 min = *EMBEDDING_DIM_RANGE.start(),
100 max = *EMBEDDING_DIM_RANGE.end(),
101 "embedding.dim override out of range; ignoring"
102 );
103 None
104 }
105}
106
107/// Records the dimensionality found in the opened database (`schema_meta.dim`).
108///
109/// Out-of-range values are ignored. A CLI flag or XDG override still wins over
110/// this value — see the precedence documented on [`embedding_dim`].
111pub fn set_active_embedding_dim(dim: usize) {
112 if EMBEDDING_DIM_RANGE.contains(&dim) {
113 ACTIVE_EMBEDDING_DIM.store(dim, std::sync::atomic::Ordering::Release);
114 }
115}
116
117// G46: FASTEMBED_MODEL_DEFAULT removed — the fastembed model was deleted in
118// v1.0.76 (LLM-only build); `schema_meta.model` now records the CLI version.
119
120/// Default worker count for the global Rayon pool.
121///
122/// Each worker holds one batch-embedding call in flight, so a wider pool buys
123/// no throughput on the LLM-only path and risks RSS oversubscription on a
124/// 4-8 GiB host. Override via XDG `parallelism.rayon_threads`.
125pub const DEFAULT_RAYON_THREADS: usize = 2;
126
127/// Batch size for `fastembed` encoding calls.
128pub const FASTEMBED_BATCH_SIZE: usize = 32;
129
130/// Maximum byte length for a memory `name` field in kebab-case.
131pub const MAX_MEMORY_NAME_LEN: usize = 80;
132
133/// Maximum byte length for an `ingest`-derived kebab-case name.
134///
135/// Stricter than `MAX_MEMORY_NAME_LEN` (80) to leave headroom for collision
136/// suffixes (`-2`, `-10`, ...) when multiple files derive to the same base.
137/// Used exclusively by `src/commands/ingest.rs`.
138pub const DERIVED_NAME_MAX_LEN: usize = 60;
139
140/// Maximum character length for a memory `description` field.
141pub const MAX_MEMORY_DESCRIPTION_LEN: usize = 500;
142
143/// Hard upper bound on memory `body` length in bytes.
144pub const MAX_MEMORY_BODY_LEN: usize = 512_000;
145
146/// Body character count above which the body is split into chunks.
147pub const MAX_BODY_CHARS_BEFORE_CHUNK: usize = 8_000;
148
149/// Maximum attempts when a statement returns `SQLITE_BUSY`.
150pub const MAX_SQLITE_BUSY_RETRIES: u32 = 5;
151
152/// Base delay in milliseconds for the first SQLITE_BUSY retry.
153///
154/// Each subsequent attempt doubles the delay (exponential backoff):
155/// 300 ms → 600 ms → 1200 ms → 2400 ms → 4800 ms (≈ 9.3 s total).
156pub const SQLITE_BUSY_BASE_DELAY_MS: u64 = 300;
157
158/// Query timeout applied to statements in milliseconds.
159pub const QUERY_TIMEOUT_MILLIS: u64 = 5_000;
160
161/// Jaccard threshold above which two memories are considered fuzzy duplicates.
162pub const DEDUP_FUZZY_THRESHOLD: f64 = 0.8;
163
164/// Cosine distance threshold below which two memories are semantic duplicates.
165pub const DEDUP_SEMANTIC_THRESHOLD: f32 = 0.1;
166
167/// Maximum number of hops allowed in graph traversals.
168pub const MAX_GRAPH_HOPS: u32 = 2;
169
170/// Minimum relationship weight required for traversal inclusion.
171pub const MIN_RELATION_WEIGHT: f64 = 0.3;
172
173/// Default traversal depth for `related` when `--hops` is omitted.
174pub const DEFAULT_MAX_HOPS: u32 = 2;
175
176/// Default minimum weight filter applied during graph traversal.
177pub const DEFAULT_MIN_WEIGHT: f64 = 0.3;
178
179/// Default weight assigned to newly created relationships.
180pub const DEFAULT_RELATION_WEIGHT: f64 = 0.5;
181
182/// Default `k` used by `recall` when the caller omits `--k`.
183pub const DEFAULT_K_RECALL: usize = 10;
184
185/// Default `k` for memory KNN searches when the caller omits `--k`.
186pub const K_MEMORIES_DEFAULT: usize = 10;
187
188/// Default `k` for entity KNN searches during graph expansion.
189pub const K_ENTITIES_SEARCH: usize = 5;
190
191/// Default upper bound on distinct entities persisted per memory.
192///
193/// Bumped from 30 → 50 in v1.0.43 to reduce semantic loss on rich documents.
194/// Configurable at runtime via XDG / runtime_config (not product env).
195pub const MAX_ENTITIES_PER_MEMORY: usize = 50;
196
197/// Resolves the per-memory entity cap (flag/XDG/`runtime_config`).
198///
199/// v1.0.43: makes the cap (default 50) configurable without product env.
200/// Stress tests showed inputs with 33-46 candidates being truncated at the old cap of 30.
201/// Values outside [1, 1000] fall back to the default.
202pub fn max_entities_per_memory() -> usize {
203 let n = crate::runtime_config::max_entities_per_memory(MAX_ENTITIES_PER_MEMORY);
204 if (1..=1_000).contains(&n) {
205 n
206 } else {
207 MAX_ENTITIES_PER_MEMORY
208 }
209}
210
211/// Upper bound on distinct relationships persisted per memory.
212pub const MAX_RELATIONSHIPS_PER_MEMORY: usize = 50;
213
214/// Resolves the per-memory relationship cap (flag/XDG/`runtime_config`).
215///
216/// v1.0.22: makes the cap (default 50) configurable without product env.
217/// Audit found that rich documents silently hit the cap; users with dense technical corpora
218/// can raise it via XDG. Values outside [1, 10000] fall back to the default.
219pub fn max_relationships_per_memory() -> usize {
220 let n = crate::runtime_config::max_relations_per_memory(MAX_RELATIONSHIPS_PER_MEMORY);
221 if (1..=10_000).contains(&n) {
222 n
223 } else {
224 MAX_RELATIONSHIPS_PER_MEMORY
225 }
226}
227
228/// Character length of the description preview shown in `list` output.
229pub const TEXT_DESCRIPTION_PREVIEW_LEN: usize = 100;
230
231/// `PRAGMA busy_timeout` value applied on every connection.
232pub const BUSY_TIMEOUT_MILLIS: i32 = 5_000;
233
234/// `PRAGMA cache_size` value in kibibytes (negative means KiB).
235pub const CACHE_SIZE_KB: i32 = -64_000;
236
237/// `PRAGMA mmap_size` value in bytes applied to each connection.
238pub const MMAP_SIZE_BYTES: i64 = 268_435_456;
239
240/// `PRAGMA wal_autocheckpoint` threshold in pages.
241pub const WAL_AUTOCHECKPOINT_PAGES: i32 = 1_000;
242
243/// Default `k` constant used by Reciprocal Rank Fusion in `hybrid-search`.
244pub const RRF_K_DEFAULT: u32 = 60;
245
246/// Chunk size expressed in tokens for body splitting.
247pub const CHUNK_SIZE_TOKENS: usize = 400;
248
249/// Token overlap between consecutive chunks.
250pub const CHUNK_OVERLAP_TOKENS: usize = 50;
251
252/// Explicit operational guard for multi-chunk documents in `remember`.
253///
254/// The multi-chunk path uses serial embeddings to avoid ONNX memory amplification.
255/// This limit preserves a clear operational ceiling for agents and scripts.
256pub const REMEMBER_MAX_SAFE_MULTI_CHUNKS: usize = 512;
257
258/// Ceiling on chunks per controlled micro-batch in `remember`.
259///
260/// The `fastembed` runtime uses `BatchLongest` padding, so oversized batches amplify
261/// the cost of the longest chunk. This ceiling keeps batches small even when chunks are short.
262pub const REMEMBER_MAX_CONTROLLED_BATCH_CHUNKS: usize = 4;
263
264/// Maximum padded-token budget per controlled micro-batch in `remember`.
265///
266/// The budget uses `max_tokens_no_batch * batch_size`, approximating the real cost of
267/// `BatchLongest` padding. Values exceeding this fall back to smaller batches or serialisation.
268pub const REMEMBER_MAX_CONTROLLED_BATCH_PADDED_TOKENS: usize = 512;
269
270/// Prefix prepended to bodies before embedding as required by E5 models.
271pub const PASSAGE_PREFIX: &str = "passage: ";
272
273/// Prefix prepended to queries before embedding as required by E5 models.
274pub const QUERY_PREFIX: &str = "query: ";
275
276/// Crate version string sourced from `CARGO_PKG_VERSION` at build time.
277pub const SQLITE_GRAPHRAG_VERSION: &str = env!("CARGO_PKG_VERSION");
278
279/// PRD-canonical regex that validates names and namespaces. Allows 1 char `[a-z0-9]`
280/// OR a 2-80 char string starting with a letter and ending with a letter/digit,
281/// containing only `[a-z0-9-]`. Rejects the `__` prefix (internal reserved).
282pub const NAME_SLUG_REGEX: &str = r"^[a-z][a-z0-9-]{0,78}[a-z0-9]$|^[a-z0-9]$";
283
284static NAME_SLUG_RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
285
286/// Returns a reference to the compiled [`NAME_SLUG_REGEX`] pattern.
287/// Compiled once on first call, cached via `OnceLock`.
288// expect_used (audited v1.0.97): NAME_SLUG_REGEX is a const literal; a parse
289// failure would be a compile-reproducible bug, never a runtime condition.
290#[allow(clippy::expect_used)]
291pub fn name_slug_regex() -> &'static regex::Regex {
292 NAME_SLUG_RE.get_or_init(|| {
293 regex::Regex::new(NAME_SLUG_REGEX).expect("NAME_SLUG_REGEX is a valid pattern")
294 })
295}
296
297/// Default retention period (days) used by `purge` when `--retention-days` is omitted.
298pub const PURGE_RETENTION_DAYS_DEFAULT: u32 = 90;
299
300/// Maximum number of simultaneously active namespaces (deleted_at IS NULL). Exit 5 when exceeded.
301pub const MAX_NAMESPACES_ACTIVE: u32 = 100;
302
303/// Maximum tokens accepted by an embedding input before chunking.
304pub const EMBEDDING_MAX_TOKENS: usize = 512;
305
306/// Maximum token count for a SINGLE embedding request input (GAP-SG-02).
307///
308/// The `qwen/qwen3-embedding-8b` model used by the OpenRouter backend accepts
309/// roughly 32K tokens of context. This ceiling rejects an input above a safe
310/// margin BEFORE the HTTP request, using the conservative cl100k_base proxy in
311/// [`crate::tokenizer::count_tokens`] (which emits at least as many tokens as
312/// Qwen for the same text). Distinct from [`EMBEDDING_MAX_TOKENS`] (512), which
313/// is the per-chunk ceiling that drives chunking.
314pub const EMBEDDING_REQUEST_MAX_TOKENS: usize = 30_000;
315
316/// Initial `max_tokens` budget sent on an `enrich` chat-completion request
317/// (GAP-SG-70/71).
318///
319/// Chosen well below [`ENRICH_MAX_TOKENS_CEILING`] so a well-formed response
320/// completes in one attempt for the common case; only bodies that need more
321/// room trigger the growth loop below.
322pub const ENRICH_INITIAL_MAX_TOKENS: u32 = 4_096;
323
324/// Multiplier applied to `max_tokens` each time OpenRouter reports
325/// `finish_reason: "length"` on an `enrich` chat-completion (GAP-SG-70/71).
326pub const ENRICH_MAX_TOKENS_GROWTH_FACTOR: u32 = 2;
327
328/// Upper bound on `max_tokens` growth for an `enrich` chat-completion
329/// (GAP-SG-70/71).
330///
331/// Kept with margin under the ~32K-token context ceiling of
332/// `deepseek/deepseek-v4-flash:nitro` (see [`EMBEDDING_REQUEST_MAX_TOKENS`]
333/// for the equivalent embedding-side ceiling) so growth never requests a
334/// budget the model cannot honour.
335pub const ENRICH_MAX_TOKENS_CEILING: u32 = 16_384;
336
337/// Maximum number of `max_tokens`-growth re-attempts after a truncated
338/// (`finish_reason: "length"`) `enrich` chat-completion, before giving up and
339/// returning the truncation as an error (GAP-SG-70/71).
340pub const ENRICH_MAX_LENGTH_RETRIES: u32 = 2;
341
342/// Byte budget for one auto-split partition (sub-memory) in `ingest`
343/// (GAP-SG-04/07).
344///
345/// Chosen below the 127 KB body margin so each partition also stays under
346/// [`REMEMBER_MAX_SAFE_MULTI_CHUNKS`] chunks and [`EMBEDDING_REQUEST_MAX_TOKENS`]
347/// tokens, even for multibyte/CJK text (~1 cl100k token per UTF-8 char, so
348/// 80 KiB / 3 bytes-per-char yields about 27K tokens, below the 30K ceiling).
349pub const AUTOSPLIT_PARTITION_MAX_BYTES: usize = 80 * 1024;
350
351/// Maximum result count from the recursive graph CTE in `recall`.
352pub const K_GRAPH_MATCHES_LIMIT: usize = 20;
353
354/// Default `--limit` for `list` when omitted.
355pub const K_LIST_DEFAULT_LIMIT: usize = 100;
356
357/// Default `--limit` for `graph entities` when omitted.
358pub const K_GRAPH_ENTITIES_DEFAULT_LIMIT: usize = 50;
359
360/// Default `--limit` for `related` when omitted.
361pub const K_RELATED_DEFAULT_LIMIT: usize = 10;
362
363/// Default `--limit` for `history` when omitted.
364pub const K_HISTORY_DEFAULT_LIMIT: usize = 20;
365
366/// Default weight for the vector contribution in the `hybrid-search` RRF formula.
367pub const WEIGHT_VEC_DEFAULT: f64 = 1.0;
368
369/// Default weight for the BM25 text contribution in the `hybrid-search` RRF formula.
370pub const WEIGHT_FTS_DEFAULT: f64 = 1.0;
371
372/// Character size of the body preview emitted in text/markdown formats.
373pub const TEXT_BODY_PREVIEW_LEN: usize = 200;
374
375/// Default value injected into ORT_NUM_THREADS when not set by the user.
376pub const ORT_NUM_THREADS_DEFAULT: &str = "1";
377
378/// Default value injected into ORT_INTRA_OP_NUM_THREADS when not set.
379pub const ORT_INTRA_OP_NUM_THREADS_DEFAULT: &str = "1";
380
381/// Default value injected into OMP_NUM_THREADS when not set by the user.
382pub const OMP_NUM_THREADS_DEFAULT: &str = "1";
383
384/// Exit code for partial batch failure (PRD line 1822). Conflicts with DbBusy in v1.x;
385/// in v2.0.0 DbBusy migrates to 15 and this code takes 13 per PRD.
386pub const BATCH_PARTIAL_FAILURE_EXIT_CODE: i32 = 13;
387
388/// Exit code for DbBusy in v2.0.0 (migrated from 13 to free 13 for batch failure).
389pub const DB_BUSY_EXIT_CODE: i32 = 15;
390
391/// Polling interval in milliseconds used by `--wait-lock` between `try_lock_exclusive` attempts.
392pub const CLI_LOCK_POLL_INTERVAL_MS: u64 = 500;
393
394/// Process exit code returned when the lock is busy and no wait was requested (EX_TEMPFAIL).
395pub const CLI_LOCK_EXIT_CODE: i32 = 75;
396
397/// Maximum number of CLI instances running simultaneously.
398///
399/// Limits the counting
400/// semaphore in [`crate::lock`] to prevent memory overload when multiple parallel
401/// v1.0.75 (G18 solution): removed the rigid 4-slot ceiling. The adaptive
402/// `calculate_safe_concurrency` function in [`crate::lock`]` now reports
403/// the dynamic limit. This constant is preserved as a *legacy fallback*
404/// when the dynamic calculation cannot be performed (e.g. when `sysinfo`
405/// cannot read `/proc/meminfo`).
406///
407/// Operators should prefer passing `--max-concurrency` explicitly OR
408/// letting the runtime compute the limit. The default ceiling is intentionally
409/// higher (16) so the legacy 4-slot hard cap does not silently reappear.
410pub const MAX_CONCURRENT_CLI_INSTANCES: usize = 16;
411
412/// G28-B (v1.0.68): polling interval in milliseconds used by
413/// `acquire_job_singleton` between retry attempts when another invocation
414/// already holds the singleton for `(job_type, namespace)`.
415pub const JOB_SINGLETON_POLL_INTERVAL_MS: u64 = 1000;
416
417/// Minimum available memory in MiB required before starting model loading.
418///
419/// If `sysinfo::System::available_memory() / 1_048_576` falls below this value,
420/// the invocation is aborted with [`crate::errors::AppError::LowMemory`]
421/// (exit code [`LOW_MEMORY_EXIT_CODE`]).
422pub const MIN_AVAILABLE_MEMORY_MB: u64 = 2_048;
423
424/// Maximum process RSS in MiB before aborting embedding operations.
425/// Users can override via `--max-rss-mb`. Set to 8 GiB by default.
426pub const DEFAULT_MAX_RSS_MB: u64 = 8_192;
427
428/// Maximum time in seconds an instance waits to acquire a concurrency slot.
429///
430/// Passed as the default for `--max-wait-secs` in the CLI. After exhausting this limit,
431/// the invocation returns [`crate::errors::AppError::AllSlotsFull`] with exit code
432/// [`CLI_LOCK_EXIT_CODE`] (75).
433pub const CLI_LOCK_DEFAULT_WAIT_SECS: u64 = 300;
434
435/// v1.0.75 (G18 + G23): expected RSS in MiB for an LLM-only worker that
436/// spawns a `claude -p` or `codex exec` subprocess. Much lower than the
437/// embedding cost because the ONNX model is not loaded per-worker.
438pub const LLM_WORKER_RSS_MB: u64 = 350;
439
440/// Process exit code returned when available memory is below [`MIN_AVAILABLE_MEMORY_MB`].
441///
442/// Value `77` is `EX_NOPERM` in glibc sysexits, reused here to indicate
443/// "insufficient system resource to proceed".
444pub const LOW_MEMORY_EXIT_CODE: i32 = 77;
445
446/// Process exit code returned when a duplicate memory or entity is detected (exit 9).
447///
448/// Moved from `2` to `9` in v1.0.52 to free exit code `2` for future use and align
449/// with the PRD exit code contract. Shell callers and LLM agents must use `9` from
450/// this version onwards.
451pub const DUPLICATE_EXIT_CODE: i32 = 9;
452
453/// Process exit code returned when shutdown is requested via SIGINT/SIGTERM/SIGHUP
454/// (v1.0.82, GAP-002 final).
455///
456/// The shell sees this code INSTEAD of the legacy `128 + signal` (130/143/129) so
457/// that LLM agents and orchestrators can branch on a single deterministic value
458/// when the operation was cancelled by the user. The signal name is preserved in
459/// the JSON envelope emitted before exit (`{"code":19,"signal":"SIGINT",...}`).
460pub const SHUTDOWN_EXIT_CODE: i32 = 19;
461
462/// Canonical value of `PRAGMA user_version` written after migrations.
463///
464/// **Why 50 instead of `CURRENT_SCHEMA_VERSION` (15)?**
465/// `user_version` is a 32-bit integer that SQLite reserves for application use.
466/// We deliberately set it to a project-specific marker (50 = decimal) so external
467/// inspection tools (`sqlite3 db.sqlite "PRAGMA user_version"`, the `file` command,
468/// SQLite browser GUIs) can distinguish a sqlite-graphrag database from a generic
469/// SQLite file at a glance. The application-level schema version (15, matching
470/// `CURRENT_SCHEMA_VERSION`) is stored in the `schema_meta` table and exposed via
471/// `health --json`/`stats --json`. Bumping migrations does NOT change this constant.
472/// Refinery uses its own `refinery_schema_history` table for migration bookkeeping.
473pub const SCHEMA_USER_VERSION: i64 = 50;
474
475/// Current schema version, equal to the highest migration number in `migrations/Vnnn__*.sql`.
476///
477/// Added in v1.0.27 as a runtime and test sanity check.
478/// Must be bumped in sync with new Refinery migrations; the unit test
479/// `schema_version_matches_migrations_count` validates this automatically.
480pub const CURRENT_SCHEMA_VERSION: u32 = 16;
481
482#[cfg(test)]
483mod tests_schema_version {
484 use super::CURRENT_SCHEMA_VERSION;
485
486 #[test]
487 fn schema_version_matches_migrations_count() {
488 let manifest_dir = env!("CARGO_MANIFEST_DIR");
489 let migrations_dir = std::path::Path::new(manifest_dir).join("migrations");
490 let count = std::fs::read_dir(&migrations_dir)
491 .expect("migrations directory must exist")
492 .filter_map(|entry| entry.ok())
493 .filter(|entry| entry.file_name().to_string_lossy().starts_with('V'))
494 .count() as u32;
495 assert_eq!(
496 CURRENT_SCHEMA_VERSION, count,
497 "CURRENT_SCHEMA_VERSION ({CURRENT_SCHEMA_VERSION}) must equal the number of V*.sql migrations ({count})"
498 );
499 }
500}