Skip to main content

writerslogic_warm/core/
config.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Debug, Default)]
7pub struct WarmConfig {
8    /// Create a schema-7 store supporting native vector records. Older stores need an offline upgrade.
9    pub vector_records: bool,
10    pub text_encoder: super::encoding::TextEncoder,
11    pub ivf: IVFConfig,
12    pub nsg: NSGConfig,
13    pub shard: ShardConfig,
14    pub query: QueryConfig,
15    pub concepts: ConceptsConfig,
16    pub diffusion: DiffusionConfig,
17    pub security: SecurityConfig,
18    pub provenance: ProvenanceConfig,
19    pub privacy: PrivacyConfig,
20    pub meaning: MeaningConfig,
21    pub cognition: CognitionConfig,
22    pub hopfield: super::hopfield::HopfieldConfig,
23    pub embedding_space: Option<super::schema::EmbeddingSpace>,
24    /// Optional normalized-prefix graph candidates; stored embeddings remain full width.
25    pub vector_candidates: Option<VectorCandidateConfig>,
26    /// Opt-in degree-64/build-500 graph with single-hop traversal; quality remains approximate.
27    pub vector_high_recall: bool,
28    pub document_checkpoint: DocumentCheckpointConfig,
29    /// Lexical analyzer of a new store, recorded in its `store.json`; `None` takes the store's
30    /// recorded one (the legacy analyzer for a new store). Reopening with another one fails.
31    pub analyzer: Option<super::documents::Analyzer>,
32    /// Options of the local embedder `TextEncoder::LocalEmbedV1` loads (default options when
33    /// absent). Ignored by the other encoders.
34    #[cfg(feature = "local-embed")]
35    pub local_embed: Option<super::embed::EmbedOptions>,
36    /// Bounds of one observation in the experience core, and whether form state is parsed
37    /// from the accessibility-tree text observations carry.
38    pub experience: super::experience::ExperienceConfig,
39}
40
41/// Opt-in graph candidate projection and the number of candidates fully reranked.
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct VectorCandidateConfig {
44    pub dimensions: usize,
45    pub rerank_candidates: usize,
46}
47
48impl VectorCandidateConfig {
49    pub(crate) fn validate(&self, space: &super::schema::EmbeddingSpace) -> anyhow::Result<()> {
50        anyhow::ensure!(
51            (1..=space.dimensions).contains(&self.dimensions),
52            "vector candidate dimensions must be 1..=embedding space dimensions"
53        );
54        anyhow::ensure!(
55            (1..=4096).contains(&self.rerank_candidates),
56            "vector rerank candidates must be 1..=4096"
57        );
58        Ok(())
59    }
60}
61
62/// Journal checkpoints (`documents.ckpt`, see `docs/file-format/index.md`): a compaction
63/// that writes the document store as one mapped file in place of the journal frames before it,
64/// so a store opens by mapping it and serves unfiltered lexical queries from the mapping.
65#[derive(Clone, Debug)]
66pub struct DocumentCheckpointConfig {
67    /// Write checkpoints. A store that has one opens from it either way: it is the store's data.
68    pub enabled: bool,
69    /// Journal bytes after the last checkpoint at or above which `flush` or closing the engine
70    /// writes a new one: below it, replaying the frames is about as fast.
71    pub min_journal_bytes: usize,
72    /// Store chunk text in the checkpoint compressed (see `docs/file-format/index.md`), and
73    /// cut the text cache file at close: the checkpoint is much smaller and a served hit decodes
74    /// its block unless `text_cache_bytes` holds it. Off by default.
75    pub compress_text: bool,
76    /// Most bytes of decoded chunk text a store served from a checkpoint keeps for later hits (never
77    /// more than the compression saves on that store). The
78    /// checkpoint holds chunk text compressed, so a hit decodes a block; blocks decoded once stay
79    /// here, first come first kept, until the budget is used. `0` decodes on every hit.
80    pub text_cache_bytes: usize,
81    /// Estimated resident bytes of the live lexical index at which ingest folds it into the
82    /// store's checkpoint and drops it from memory (see `docs/file-format/index.md`,
83    /// "Streaming folds"). The estimate counts postings and per-chunk records, so the process
84    /// holds roughly this much more than its base footprint, not exactly this much. 0 never
85    /// folds: the index then grows with the corpus until the engine closes. Folding applies
86    /// to unencrypted lexical-only stores that take checkpoints.
87    pub index_memory_budget: usize,
88    /// A fold rewrites the whole checkpoint, so folding at a fixed budget does work quadratic
89    /// in the corpus. Ingest therefore folds once the estimate reaches the larger of
90    /// `index_memory_budget` and this fraction of the current checkpoint's size in bytes:
91    /// the checkpoint then at most grows by a constant factor per fold and the number of
92    /// rewrites is logarithmic in the corpus. 0 keeps the fixed budget.
93    pub index_fold_fraction: f64,
94    /// Let [`crate::core::WarmCore::compact`] renumber the document slots of a store that takes a
95    /// checkpoint so that documents sharing terms sit together (recursive graph bisection), which
96    /// shortens posting lists and speeds up conjunctions, phrases and pruned ranking. Results are
97    /// unchanged. Only that explicit call reorders: folds, `flush`, closing, background jobs,
98    /// warm-server's scheduled pass and snapshots never do. The compaction that reorders holds
99    /// writers 3 to 5 times as long as one that does not (see `WarmCore::compact`). On by
100    /// default; see `docs/file-format/index.md`, "Document order".
101    pub reorder: bool,
102    /// Most bytes the reorder of [`crate::core::WarmCore::compact`] may hold beyond a plain
103    /// compaction, by the estimate it computes before it builds anything (its forward index is
104    /// also capped at 2^28 pairs, 1 GiB). Over it, `compact` compacts without reordering and
105    /// `WarmCore::last_reorder` reports `OverBudget`; `WarmCore::reorder_documents` reorders
106    /// regardless. 2 GiB by default.
107    pub reorder_memory_budget: usize,
108}
109
110impl Default for DocumentCheckpointConfig {
111    fn default() -> Self {
112        Self {
113            enabled: true,
114            min_journal_bytes: 256 << 10,
115            compress_text: false,
116            text_cache_bytes: 64 << 20,
117            index_memory_budget: 64 << 20,
118            index_fold_fraction: 20.0,
119            reorder: true,
120            reorder_memory_budget: 2 << 30,
121        }
122    }
123}
124
125#[derive(Clone, Debug)]
126pub struct MeaningConfig {
127    pub enabled: bool,
128    pub beta: f64,
129    pub algebraic_max_fanout: usize,
130    pub auto_decompose: bool,
131    pub max_hop_depth: usize,
132    pub max_rule_depth: usize,
133    pub idf_clip_factor: f64,
134}
135
136impl Default for MeaningConfig {
137    fn default() -> Self {
138        Self {
139            enabled: false,
140            beta: 24.0,
141            algebraic_max_fanout: 40,
142            auto_decompose: false,
143            max_hop_depth: 10,
144            max_rule_depth: 10,
145            idf_clip_factor: 3.0,
146        }
147    }
148}
149
150#[derive(Clone, Debug)]
151#[cfg_attr(not(test), derive(Default))]
152pub struct SecurityConfig {
153    pub signing_enabled: bool,
154    pub key_path: Option<String>,
155    /// Encrypt with a key derived from a passphrase (`encryption_passphrase` or
156    /// `encryption_passphrase_env`). New stores are sealed under a random master key
157    /// without setting this, whenever the `security` feature is compiled in.
158    pub encryption_enabled: bool,
159    /// Explicit opt-out of the default: a new store is written unencrypted. An existing store keeps the
160    /// protection it was created with, so a plaintext store opens without this.
161    pub plaintext: bool,
162    /// Master key file of a default-encrypted store; `<store>/master.key` when unset.
163    /// Keeping it outside the store directory keeps a copy of the directory unreadable.
164    pub master_key_file: Option<String>,
165    pub encryption_passphrase: Option<String>,
166    /// Name of an environment variable containing the encryption passphrase.
167    /// Prefer this over embedding a secret in application configuration.
168    pub encryption_passphrase_env: Option<String>,
169    pub audit_enabled: bool,
170}
171
172#[cfg(test)]
173impl Default for SecurityConfig {
174    fn default() -> Self {
175        Self {
176            signing_enabled: false,
177            key_path: None,
178            encryption_enabled: false,
179            // The crate's own unit tests exercise engine mechanics (checkpoint layout, file
180            // recovery) on plaintext stores; the encrypted default is covered by the
181            // integration tests, which link the library without `cfg(test)`.
182            plaintext: true,
183            master_key_file: None,
184            encryption_passphrase: None,
185            encryption_passphrase_env: None,
186            audit_enabled: false,
187        }
188    }
189}
190
191#[derive(Clone, Debug, Default)]
192pub struct ProvenanceConfig {
193    pub enabled: bool,
194    pub key_path: Option<String>,
195    pub auto_sign: bool,
196    pub status_list_url: Option<String>,
197    #[cfg(feature = "provenance-scitt")]
198    pub scitt_endpoint: Option<String>,
199}
200
201#[derive(Clone, Debug)]
202pub struct PrivacyConfig {
203    /// Enable epsilon-differential privacy in bundle operations.
204    pub dp_enabled: bool,
205    /// Privacy budget epsilon. Smaller = more private, noisier.
206    /// Typical range: 0.1 (strong) to 10.0 (weak).
207    pub epsilon: f64,
208}
209
210impl Default for PrivacyConfig {
211    fn default() -> Self {
212        Self {
213            dp_enabled: false,
214            epsilon: 1.0,
215        }
216    }
217}
218
219#[derive(Clone, Debug)]
220pub struct QueryConfig {
221    pub component_similarity_threshold: f64,
222    pub component_max_neighbors: u32,
223}
224
225impl Default for QueryConfig {
226    fn default() -> Self {
227        Self {
228            component_similarity_threshold: 0.05,
229            component_max_neighbors: 20,
230        }
231    }
232}
233
234#[derive(Clone, Debug)]
235pub struct ConceptsConfig {
236    pub similarity_threshold: f64,
237    pub min_cluster_size: usize,
238}
239
240impl Default for ConceptsConfig {
241    fn default() -> Self {
242        Self {
243            similarity_threshold: 0.3,
244            min_cluster_size: 3,
245        }
246    }
247}
248
249#[derive(Clone, Debug)]
250pub struct DiffusionConfig {
251    pub steps: usize,
252    pub sigma_max: f64,
253    pub sigma_min: f64,
254    pub step_size: f64,
255    pub n_langevin: usize,
256}
257
258impl Default for DiffusionConfig {
259    fn default() -> Self {
260        Self {
261            steps: 10,
262            sigma_max: 0.5,
263            sigma_min: 0.01,
264            step_size: 0.1,
265            n_langevin: 5,
266        }
267    }
268}
269
270#[derive(Clone, Debug)]
271pub struct ShardConfig {
272    pub enabled: bool,
273    pub shard_count: usize,
274    pub auto_threshold: usize,
275    pub target_shard_size: usize,
276}
277
278impl Default for ShardConfig {
279    fn default() -> Self {
280        Self {
281            enabled: false,
282            shard_count: 0,
283            auto_threshold: 1_000_000,
284            target_shard_size: 250_000,
285        }
286    }
287}
288
289#[derive(Clone, Debug, Serialize, Deserialize)]
290pub struct NSGConfig {
291    pub max_degree: usize,
292    pub ef_construction: usize,
293    pub auto_threshold: usize,
294    pub seed: u64,
295}
296
297impl Default for NSGConfig {
298    fn default() -> Self {
299        Self {
300            max_degree: 32,
301            ef_construction: 128,
302            auto_threshold: 10_000,
303            seed: 42,
304        }
305    }
306}
307
308#[derive(Clone, Debug)]
309pub struct IVFConfig {
310    /// Controls auto-training only. Manual `train_ivf()` works regardless.
311    pub enabled: bool,
312    pub n_clusters: usize,
313    pub n_landmarks: usize,
314    pub d_reduced: usize,
315    pub n_probe: usize,
316    pub auto_threshold: usize,
317}
318
319impl Default for IVFConfig {
320    fn default() -> Self {
321        Self {
322            enabled: false,
323            n_clusters: 256,
324            n_landmarks: 1024,
325            d_reduced: 128,
326            n_probe: 8,
327            auto_threshold: 10_000,
328        }
329    }
330}
331
332#[derive(Clone, Debug)]
333pub struct CognitionConfig {
334    pub enabled: bool,
335    pub interval_secs: u64,
336    pub min_pattern_freq: usize,
337    pub min_abstraction_members: usize,
338    pub min_shared_relations: usize,
339    pub min_peer_coverage: f64,
340    pub hypothesis_beta: f64,
341    pub min_hypothesis_confidence: f64,
342    pub min_analogy_relations: usize,
343    pub governor_duplicate_threshold: f64,
344    pub governor_max_scan_size: usize,
345    pub governor_forget_unreferenced: bool,
346    pub refine_atoms: bool,
347}
348
349impl Default for CognitionConfig {
350    fn default() -> Self {
351        Self {
352            enabled: false,
353            interval_secs: 60,
354            min_pattern_freq: 3,
355            min_abstraction_members: 3,
356            min_shared_relations: 2,
357            min_peer_coverage: 0.5,
358            hypothesis_beta: 24.0,
359            min_hypothesis_confidence: 0.3,
360            min_analogy_relations: 2,
361            governor_duplicate_threshold: 0.95,
362            governor_max_scan_size: 1000,
363            governor_forget_unreferenced: false,
364            refine_atoms: false,
365        }
366    }
367}
368
369impl WarmConfig {
370    /// The default configuration with the plaintext opt-out set: a new store is written
371    /// unencrypted. An existing store keeps the protection it was created with.
372    pub fn unencrypted() -> Self {
373        let mut config = Self::default();
374        config.security.plaintext = true;
375        config
376    }
377
378    pub(crate) fn validate(&self) -> anyhow::Result<()> {
379        anyhow::ensure!(
380            self.text_encoder != super::encoding::TextEncoder::MultiscaleCappedUnionV1
381                || cfg!(feature = "experimental"),
382            "capped-union text encoding requires a build with the experimental feature"
383        );
384        anyhow::ensure!(
385            self.text_encoder != super::encoding::TextEncoder::LocalEmbedV1
386                || cfg!(feature = "local-embed"),
387            "the local-embed-v1 text encoder requires a build with the local-embed feature"
388        );
389        anyhow::ensure!(
390            cfg!(feature = "security")
391                || !(self.security.signing_enabled || self.security.encryption_enabled),
392            "signing/encryption requires a build with the security feature"
393        );
394        anyhow::ensure!(
395            cfg!(feature = "provenance") || !self.provenance.enabled,
396            "provenance requires a build with the provenance feature"
397        );
398        anyhow::ensure!(
399            self.privacy.epsilon.is_finite() && self.privacy.epsilon > 0.0,
400            "privacy epsilon must be finite and positive"
401        );
402        anyhow::ensure!(
403            self.shard.target_shard_size > 0 && self.shard.shard_count <= 1024,
404            "invalid shard configuration"
405        );
406        anyhow::ensure!(
407            self.meaning.beta.is_finite() && self.meaning.beta > 0.0,
408            "meaning beta must be finite and positive"
409        );
410        if let Some(candidates) = &self.vector_candidates {
411            let space = self.embedding_space.as_ref().ok_or_else(|| {
412                anyhow::anyhow!("vector candidates require a full embedding space")
413            })?;
414            candidates.validate(space)?;
415        }
416        anyhow::ensure!(
417            !self.vector_high_recall || self.embedding_space.is_some(),
418            "high-recall vector graphs require an embedding space"
419        );
420        if let Some(space) = &self.embedding_space {
421            anyhow::ensure!(!space.model.is_empty() && !space.revision.is_empty() && (1..=65536).contains(&space.dimensions)
422                && space.metric == "cosine" && matches!(space.normalization.as_str(), "l2" | "none"),
423                "embedding space requires model, revision, dimensions 1..=65536, normalization l2/none and metric cosine");
424        }
425        Ok(())
426    }
427}