Skip to main content

reddb_server/runtime/
config_matrix.rs

1//! Performance / operational config matrix.
2//!
3//! Two tiers:
4//!
5//! - **Tier A (`Critical`)** — self-healing on boot. If the key is
6//!   missing from `red.config`, the loader writes the default in.
7//!   Operators always see these via `SHOW CONFIG` so they know what
8//!   guarantees and tuning they have.
9//! - **Tier B (`Optional`)** — in-memory default. Never self-populated.
10//!   Appears in `SHOW CONFIG` only after an explicit `SET CONFIG`.
11//!
12//! The matrix is the single source of truth for perf / durability /
13//! concurrency / storage keys introduced by the perf-parity push.
14//! It intentionally does **not** cover the pre-existing `red.*`
15//! trees (ai, server, storage, search, etc.) — those have their own
16//! lifecycle in `impl_core`. Keys here live under the new
17//! `cache.*`, `durability.*`, `concurrency.*`, `storage.*` namespaces.
18
19use crate::serde_json::Value as JsonValue;
20use crate::storage::UnifiedStore;
21
22#[inline]
23fn num(v: f64) -> JsonValue {
24    JsonValue::Number(v)
25}
26
27#[inline]
28fn text(s: &str) -> JsonValue {
29    JsonValue::String(s.to_string())
30}
31
32/// Default value encoded as JSON so the loader can delegate to
33/// `set_config_tree` which already handles every `Value` variant.
34#[derive(Debug, Clone)]
35pub struct ConfigDefault {
36    pub key: &'static str,
37    pub tier: Tier,
38    /// Lazily produced JSON default. A closure because `bgwriter.delay_ms`
39    /// etc. are unsigned and `serde_json::Value::from(u64)` is fine, but
40    /// we want the option of composing richer defaults later.
41    pub default: fn() -> JsonValue,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub enum Tier {
46    /// Self-healing on boot. Always visible in `SHOW CONFIG`.
47    Critical,
48    /// In-memory default. Only visible in `SHOW CONFIG` after user writes.
49    Optional,
50}
51
52/// The full matrix. Keep sorted by namespace for readability.
53pub const MATRIX: &[ConfigDefault] = &[
54    // ask.*
55    ConfigDefault {
56        key: "ask.max_prompt_tokens",
57        tier: Tier::Optional,
58        default: || num(8192.0),
59    },
60    ConfigDefault {
61        key: "ask.max_completion_tokens",
62        tier: Tier::Optional,
63        default: || num(1024.0),
64    },
65    ConfigDefault {
66        key: "ask.max_sources_bytes",
67        tier: Tier::Optional,
68        default: || num(262_144.0),
69    },
70    ConfigDefault {
71        key: "ask.timeout_ms",
72        tier: Tier::Optional,
73        default: || num(30_000.0),
74    },
75    ConfigDefault {
76        key: "ask.daily_cost_cap_usd",
77        tier: Tier::Optional,
78        default: || text(""),
79    },
80    ConfigDefault {
81        key: "ask.audit.include_answer",
82        tier: Tier::Optional,
83        default: || JsonValue::Bool(false),
84    },
85    ConfigDefault {
86        key: "ask.audit.retention_days",
87        tier: Tier::Optional,
88        default: || num(90.0),
89    },
90    ConfigDefault {
91        key: "ask.cache.enabled",
92        tier: Tier::Optional,
93        default: || JsonValue::Bool(false),
94    },
95    ConfigDefault {
96        key: "ask.cache.default_ttl",
97        tier: Tier::Optional,
98        default: || text(""),
99    },
100    ConfigDefault {
101        key: "ask.cache.max_entries",
102        tier: Tier::Optional,
103        default: || num(1024.0),
104    },
105    // control_events.* — issue #2900. Duration (`48h`, `7d`) or `off`.
106    ConfigDefault {
107        key: "control_events.retention",
108        tier: Tier::Optional,
109        default: || text(crate::runtime::control_events_retention::DEFAULT_RETENTION),
110    },
111    // cache.blob.*
112    ConfigDefault {
113        key: "cache.blob.l1_bytes_max",
114        tier: Tier::Critical,
115        default: || num(crate::storage::cache::DEFAULT_BLOB_L1_BYTES_MAX as f64),
116    },
117    ConfigDefault {
118        key: "cache.blob.l2_bytes_max",
119        tier: Tier::Critical,
120        default: || num(crate::storage::cache::DEFAULT_BLOB_L2_BYTES_MAX as f64),
121    },
122    ConfigDefault {
123        key: "cache.blob.namespace_bytes_max",
124        tier: Tier::Critical,
125        default: || num(crate::storage::cache::DEFAULT_BLOB_NAMESPACE_BYTES_MAX as f64),
126    },
127    ConfigDefault {
128        key: "cache.blob.max_namespaces",
129        tier: Tier::Critical,
130        default: || num(crate::storage::cache::DEFAULT_BLOB_MAX_NAMESPACES as f64),
131    },
132    // Protocol-specific public addresses. Environment overlays keep each
133    // node's listeners separate from replicated application configuration.
134    ConfigDefault {
135        key: "routing.red.advertise_addr",
136        tier: Tier::Optional,
137        default: || text(""),
138    },
139    ConfigDefault {
140        key: "routing.reds.advertise_addr",
141        tier: Tier::Optional,
142        default: || text(""),
143    },
144    ConfigDefault {
145        key: "routing.grpc.advertise_addr",
146        tier: Tier::Optional,
147        default: || text(""),
148    },
149    ConfigDefault {
150        key: "routing.grpcs.advertise_addr",
151        tier: Tier::Optional,
152        default: || text(""),
153    },
154    ConfigDefault {
155        key: "routing.http.advertise_addr",
156        tier: Tier::Optional,
157        default: || text(""),
158    },
159    ConfigDefault {
160        key: "routing.https.advertise_addr",
161        tier: Tier::Optional,
162        default: || text(""),
163    },
164    ConfigDefault {
165        key: "routing.ws.advertise_addr",
166        tier: Tier::Optional,
167        default: || text(""),
168    },
169    ConfigDefault {
170        key: "routing.wss.advertise_addr",
171        tier: Tier::Optional,
172        default: || text(""),
173    },
174    // storage.binary_document_body — DOCUMENT native binary body container
175    // (PRD-1398, ADR-0063). Production cutover default: document writes store
176    // the body as the native binary container; reads decode it back to JSON
177    // transparently. (Keyed off `storage.*`, not `document.*`, because
178    // `document` is a reserved RQL keyword and would break SET CONFIG.)
179    ConfigDefault {
180        key: "storage.binary_document_body",
181        tier: Tier::Optional,
182        default: || JsonValue::Bool(true),
183    },
184    // durability.*
185    ConfigDefault {
186        key: "durability.mode",
187        tier: Tier::Critical,
188        default: || text("sync"),
189    },
190    // runtime.result_cache.*
191    // Kill-switch (issue #802). Critical so it self-heals to `true` on
192    // boot and is always visible in SHOW CONFIG — operators flip it to
193    // `false` to disable result caching wholesale for debugging.
194    ConfigDefault {
195        key: "runtime.result_cache.enabled",
196        tier: Tier::Critical,
197        default: || JsonValue::Bool(true),
198    },
199    // Per-entry freshness window in seconds (issue #802). Mirrors the
200    // former `RESULT_CACHE_TTL_SECS` constant.
201    ConfigDefault {
202        key: "runtime.result_cache.ttl_seconds",
203        tier: Tier::Optional,
204        default: || num(30.0),
205    },
206    // LRU capacity in entries (issue #802). Mirrors the former
207    // `RESULT_CACHE_MAX_ENTRIES` constant.
208    ConfigDefault {
209        key: "runtime.result_cache.capacity_entries",
210        tier: Tier::Optional,
211        default: || num(1000.0),
212    },
213    // concurrency.*
214    ConfigDefault {
215        key: "concurrency.locking.enabled",
216        tier: Tier::Critical,
217        default: || JsonValue::Bool(true),
218    },
219    ConfigDefault {
220        key: "concurrency.locking.deadlock_timeout_ms",
221        tier: Tier::Optional,
222        default: || num(5000.0),
223    },
224    // storage.wal.*
225    ConfigDefault {
226        key: "storage.wal.max_interval_ms",
227        tier: Tier::Critical,
228        default: || num(10.0),
229    },
230    ConfigDefault {
231        key: "storage.wal.min_batch_size",
232        tier: Tier::Optional,
233        default: || num(4.0),
234    },
235    // storage.deploy.* — official deploy/storage profile selection.
236    ConfigDefault {
237        key: "storage.deploy.profile",
238        tier: Tier::Critical,
239        default: || text("embedded"),
240    },
241    ConfigDefault {
242        key: "storage.deploy.packaging",
243        tier: Tier::Critical,
244        default: || text("single-file"),
245    },
246    ConfigDefault {
247        key: "storage.deploy.preset",
248        tier: Tier::Critical,
249        default: || text("embedded"),
250    },
251    ConfigDefault {
252        key: "storage.deploy.replica_count",
253        tier: Tier::Critical,
254        default: || num(0.0),
255    },
256    ConfigDefault {
257        key: "storage.deploy.managed_backup",
258        tier: Tier::Critical,
259        default: || JsonValue::Bool(false),
260    },
261    ConfigDefault {
262        key: "storage.deploy.wal_retention",
263        tier: Tier::Critical,
264        default: || JsonValue::Bool(false),
265    },
266    // storage.bgwriter.*
267    ConfigDefault {
268        key: "storage.bgwriter.delay_ms",
269        tier: Tier::Critical,
270        default: || num(200.0),
271    },
272    ConfigDefault {
273        key: "storage.bgwriter.max_pages_per_round",
274        tier: Tier::Optional,
275        default: || num(100.0),
276    },
277    ConfigDefault {
278        key: "storage.bgwriter.lru_multiplier",
279        tier: Tier::Optional,
280        default: || num(2.0),
281    },
282    // storage.bulk_insert.*
283    ConfigDefault {
284        key: "storage.bulk_insert.max_buffered_rows",
285        tier: Tier::Optional,
286        default: || num(1000.0),
287    },
288    ConfigDefault {
289        key: "storage.bulk_insert.max_buffered_bytes",
290        tier: Tier::Optional,
291        default: || num(65536.0),
292    },
293    // storage.hot_update.*
294    ConfigDefault {
295        key: "storage.hot_update.max_chain_hops",
296        tier: Tier::Optional,
297        default: || num(32.0),
298    },
299    // storage.time_series.*
300    ConfigDefault {
301        key: "storage.time_series.max_series_per_collection",
302        tier: Tier::Optional,
303        default: || num(1_000_000.0),
304    },
305    // storage.btree.*
306    ConfigDefault {
307        key: "storage.btree.lehman_yao",
308        tier: Tier::Critical,
309        default: || JsonValue::Bool(true),
310    },
311    // ai.ner.* — opt-in LLM backend for AskPipeline Stage 1 (issue #189).
312    ConfigDefault {
313        key: "ai.collection_descriptions.auto_enrich",
314        tier: Tier::Optional,
315        default: || JsonValue::Bool(false),
316    },
317    // Default backend stays heuristic so existing deployments keep
318    // their current behaviour without operator action.
319    ConfigDefault {
320        key: "ai.ner.backend",
321        tier: Tier::Optional,
322        default: || text("heuristic"),
323    },
324    ConfigDefault {
325        key: "ai.ner.endpoint",
326        tier: Tier::Optional,
327        default: || text(""),
328    },
329    ConfigDefault {
330        key: "ai.ner.model",
331        tier: Tier::Optional,
332        default: || text(""),
333    },
334    ConfigDefault {
335        key: "ai.ner.timeout_ms",
336        tier: Tier::Optional,
337        default: || num(5000.0),
338    },
339    ConfigDefault {
340        key: "ai.ner.fallback",
341        tier: Tier::Optional,
342        default: || text("use_heuristic"),
343    },
344    // runtime.ai.transport.* — shared outbound AI HTTP client foundation
345    // (issue #274). Provider rewiring can opt into these defaults
346    // incrementally.
347    ConfigDefault {
348        key: "runtime.ai.transport_pool_size",
349        tier: Tier::Optional,
350        default: || num(16.0),
351    },
352    ConfigDefault {
353        key: "runtime.ai.transport_timeout_ms",
354        tier: Tier::Optional,
355        default: || num(30000.0),
356    },
357    ConfigDefault {
358        key: "runtime.ai.transport_retry_max_attempts",
359        tier: Tier::Optional,
360        default: || num(3.0),
361    },
362    ConfigDefault {
363        key: "runtime.ai.transport_retry_base_ms",
364        tier: Tier::Optional,
365        default: || num(500.0),
366    },
367    // cache.blob.policy.* — extended TTL hot-path opt-in (issue #189).
368    ConfigDefault {
369        key: "cache.blob.policy.extended",
370        tier: Tier::Optional,
371        default: || text("off"),
372    },
373    // cache.blob.async_promotion — async L2->L1 promotion pool opt-in
374    // (issue #193). When "on", L2 hits return bytes to the caller
375    // immediately and the L1 install runs on a background worker.
376    // Default "off" for safe rollout — legacy synchronous promotion path.
377    ConfigDefault {
378        key: "cache.blob.async_promotion",
379        tier: Tier::Optional,
380        default: || text("off"),
381    },
382];
383
384/// Fetch the JSON default for a matrix key. Returns `None` when the
385/// key is not in the matrix (callers should treat that as a
386/// programming error — unknown key, unknown tier, unknown semantics).
387pub fn default_for(key: &str) -> Option<JsonValue> {
388    MATRIX
389        .iter()
390        .find(|entry| entry.key == key)
391        .map(|entry| (entry.default)())
392}
393
394/// Tier lookup — useful for tests and for introspection commands
395/// that want to report whether a key is expected to self-heal.
396pub fn tier_for(key: &str) -> Option<Tier> {
397    MATRIX
398        .iter()
399        .find(|entry| entry.key == key)
400        .map(|entry| entry.tier)
401}
402
403/// Boot-time self-healing pass: for every `Tier::Critical` key, if
404/// `red.config` does not already contain the key, write the default
405/// in. Idempotent — re-running produces no writes.
406///
407/// `Tier::Optional` keys are never touched here; they stay
408/// transparent-default until a user `SET CONFIG` elevates them.
409pub fn heal_critical_keys(store: &UnifiedStore) {
410    // `set_config_tree` dot-splits the key and stores one row per
411    // leaf, so we handle each matrix entry individually.
412    for entry in MATRIX {
413        if entry.tier != Tier::Critical {
414            continue;
415        }
416        if is_key_present(store, entry.key) {
417            continue;
418        }
419        store.set_config_tree(entry.key, &(entry.default)());
420    }
421}
422
423/// Lightweight presence probe. Avoids loading the whole red.config
424/// collection; scans until the first hit.
425fn is_key_present(store: &UnifiedStore, key: &str) -> bool {
426    match store.try_get_config(key) {
427        Ok(value) => value.is_some(),
428        Err(error) => {
429            // A failed physical read is not a missing operator setting. Never
430            // overwrite it with a default or a mounted-file value.
431            tracing::warn!(key, %error, "cannot read persisted configuration; skipping seed");
432            true
433        }
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn every_matrix_entry_has_a_default_that_resolves() {
443        for entry in MATRIX {
444            let value = (entry.default)();
445            assert!(
446                !matches!(value, JsonValue::Null),
447                "matrix key {} has a null default, defeats self-heal",
448                entry.key
449            );
450        }
451    }
452
453    #[test]
454    fn critical_keys_cover_the_core_guarantees() {
455        // This list is a tripwire — if someone drops one of these
456        // from Tier A without updating callers, the test catches it.
457        let required_critical = [
458            "cache.blob.l1_bytes_max",
459            "cache.blob.l2_bytes_max",
460            "cache.blob.namespace_bytes_max",
461            "cache.blob.max_namespaces",
462            "durability.mode",
463            "concurrency.locking.enabled",
464            "storage.wal.max_interval_ms",
465            "storage.deploy.profile",
466            "storage.deploy.packaging",
467            "storage.deploy.preset",
468            "storage.deploy.replica_count",
469            "storage.deploy.managed_backup",
470            "storage.deploy.wal_retention",
471            "storage.bgwriter.delay_ms",
472            "storage.btree.lehman_yao",
473        ];
474        for key in required_critical {
475            assert_eq!(
476                tier_for(key),
477                Some(Tier::Critical),
478                "{key} must be a Tier A (Critical) key",
479            );
480        }
481    }
482
483    #[test]
484    fn optional_keys_are_not_self_healed() {
485        let must_be_optional = [
486            "concurrency.locking.deadlock_timeout_ms",
487            "storage.wal.min_batch_size",
488            "storage.bgwriter.max_pages_per_round",
489            "storage.bgwriter.lru_multiplier",
490            "storage.bulk_insert.max_buffered_rows",
491            "storage.bulk_insert.max_buffered_bytes",
492            "storage.hot_update.max_chain_hops",
493            "storage.time_series.max_series_per_collection",
494        ];
495        for key in must_be_optional {
496            assert_eq!(tier_for(key), Some(Tier::Optional), "{key} tier mismatch");
497        }
498    }
499
500    #[test]
501    fn unknown_key_returns_none() {
502        assert!(default_for("nonexistent.key").is_none());
503        assert!(tier_for("nonexistent.key").is_none());
504    }
505}