Skip to main content

writerslogic_warm/core/
schema.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4#[cfg(not(target_arch = "wasm32"))]
5use anyhow::{bail, Result};
6use serde::{Deserialize, Serialize};
7#[cfg(not(target_arch = "wasm32"))]
8use std::path::Path;
9
10#[cfg(not(target_arch = "wasm32"))]
11use super::config::WarmConfig;
12#[cfg(not(target_arch = "wasm32"))]
13use super::documents::Analyzer;
14
15#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
16pub struct EmbeddingSpace {
17    pub model: String,
18    pub revision: String,
19    pub dimensions: usize,
20    pub normalization: String,
21    pub metric: String,
22}
23
24#[cfg(any(feature = "local-embed", feature = "local-models"))]
25impl EmbeddingSpace {
26    pub(crate) fn effective(
27        model: String,
28        dimensions: usize,
29        normalization: &str,
30        descriptor: &impl Serialize,
31    ) -> Result<Self> {
32        use sha2::{Digest, Sha256};
33        let digest = Sha256::digest(serde_json::to_vec(descriptor)?);
34        Ok(Self {
35            model,
36            revision: format!("hms-embedding-v1:{}", crate::core::hash::hex(&digest)),
37            dimensions,
38            normalization: normalization.into(),
39            metric: "cosine".into(),
40        })
41    }
42}
43
44#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
45#[cfg(not(target_arch = "wasm32"))]
46struct StoreSchema {
47    version: u32,
48    dimensions: usize,
49    text_encoder: String,
50    vector_encoder: String,
51    metric: String,
52    encrypted: bool,
53    meaning_enabled: bool,
54    embedding_space: Option<EmbeddingSpace>,
55    /// Absent for the legacy analyzer, so default stores keep their bytes and older releases
56    /// open them; any other analyzer also marks each chunk it wrote (binary flag bit 7).
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    lexical_analyzer: Option<String>,
59    /// `"master-key"` for a store sealed under a random master key; absent for plaintext
60    /// stores and for passphrase stores (key derived with Argon2 from `encryption.salt`).
61    #[serde(default, skip_serializing_if = "Option::is_none")]
62    key_scheme: Option<String>,
63}
64
65/// How a store's frames and checkpoints are protected.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67#[cfg(not(target_arch = "wasm32"))]
68pub(crate) enum Protection {
69    Plaintext,
70    Passphrase,
71    MasterKey,
72}
73
74/// The protection chosen for a store and whether the store is being created.
75#[derive(Clone, Copy, Debug)]
76#[cfg(not(target_arch = "wasm32"))]
77pub(crate) struct Resolved {
78    pub(crate) protection: Protection,
79    #[cfg_attr(not(feature = "security"), allow(dead_code))]
80    pub(crate) new_store: bool,
81}
82
83pub(crate) const MASTER_KEY_SCHEME: &str = "master-key";
84
85/// Decides the protection of the store at `path`. An existing store keeps the protection its
86/// `store.json` records, so a plaintext store written by an earlier release opens unchanged
87/// under the default configuration; asking for the other protection is an error. A new store
88/// is sealed under a master key unless `security.plaintext` (or `WARM_ENCRYPTION=off`) opts
89/// out, or `security.encryption_enabled` selects a passphrase.
90#[cfg(not(target_arch = "wasm32"))]
91pub(crate) fn resolve_protection(path: &Path, config: &WarmConfig) -> Result<Resolved> {
92    let security = &config.security;
93    let schema_path = path.join("store.json");
94    if !schema_path.exists() {
95        let passphrase = security.encryption_passphrase.is_some()
96            || security.encryption_passphrase_env.is_some();
97        // An explicit encryption request outranks the plaintext opt-out, which only declines
98        // the default.
99        let protection = if security.plaintext && !security.encryption_enabled {
100            Protection::Plaintext
101        } else if security.encryption_enabled && passphrase {
102            Protection::Passphrase
103        } else if security.encryption_enabled
104            || super::sealed::default_mode()? == super::sealed::Mode::Aes256Gcm
105        {
106            Protection::MasterKey
107        } else {
108            Protection::Plaintext
109        };
110        return Ok(Resolved {
111            protection,
112            new_store: true,
113        });
114    }
115    let value: serde_json::Value = serde_json::from_slice(&std::fs::read(schema_path)?)?;
116    let recorded = if !value["encrypted"].as_bool().unwrap_or(false) {
117        Protection::Plaintext
118    } else if value["key_scheme"].as_str() == Some(MASTER_KEY_SCHEME) {
119        Protection::MasterKey
120    } else {
121        Protection::Passphrase
122    };
123    let incompatible =
124        (security.plaintext && !security.encryption_enabled && recorded != Protection::Plaintext)
125            || (security.encryption_enabled && recorded == Protection::Plaintext);
126    if incompatible {
127        bail!("incompatible store schema: dimensions, encoder, embedding model, encryption, or meaning configuration changed; reopen with the original configuration or re-encode source documents into a new store");
128    }
129    Ok(Resolved {
130        protection: recorded,
131        new_store: false,
132    })
133}
134
135/// Checks the store's `store.json` against `config` (writing it for a new store) and returns
136/// its schema version, which fixes the journal format the store is written in, and its lexical
137/// analyzer: the one recorded, else `config.analyzer` for a new store, else the legacy one.
138#[cfg(all(test, not(target_arch = "wasm32")))]
139pub(crate) fn validate_store(
140    path: &Path,
141    dimensions: usize,
142    config: &WarmConfig,
143) -> Result<(u32, Analyzer)> {
144    let resolved = resolve_protection(path, config)?;
145    validate_store_resolved(path, dimensions, config, resolved)
146}
147
148/// [`validate_store`] with the protection already resolved by [`resolve_protection`].
149#[cfg(not(target_arch = "wasm32"))]
150pub(crate) fn validate_store_resolved(
151    path: &Path,
152    dimensions: usize,
153    config: &WarmConfig,
154    resolved: Resolved,
155) -> Result<(u32, Analyzer)> {
156    let mut expected = StoreSchema {
157        version: if config.vector_records {
158            super::format::VECTOR_RECORDS_SCHEMA_VERSION
159        } else {
160            super::format::STORE_SCHEMA_DEFAULT_VERSION
161        },
162        dimensions,
163        text_encoder: config.text_encoder.name().into(),
164        vector_encoder: "signed-projection-v2".into(),
165        metric: "jaccard".into(),
166        encrypted: resolved.protection != Protection::Plaintext,
167        meaning_enabled: config.meaning.enabled,
168        embedding_space: config.embedding_space.clone(),
169        lexical_analyzer: None,
170        key_scheme: (resolved.protection == Protection::MasterKey)
171            .then(|| MASTER_KEY_SCHEME.to_owned()),
172    };
173    let schema_path = path.join("store.json");
174    if schema_path.exists() {
175        let bytes = std::fs::read(schema_path)?;
176        if let Some(version) = serde_json::from_slice::<serde_json::Value>(&bytes)
177            .ok()
178            .and_then(|v| v["version"].as_u64())
179            .filter(|&v| v > u64::from(super::format::STORE_SCHEMA_VERSION))
180        {
181            bail!(
182                "store schema version {version} is newer than the supported version {}; open it with a release that supports it",
183                super::format::STORE_SCHEMA_VERSION
184            );
185        }
186        let actual: StoreSchema = serde_json::from_slice(&bytes)?;
187        let recorded = match &actual.lexical_analyzer {
188            Some(name) => name.parse::<Analyzer>()?,
189            None => Analyzer::Legacy,
190        };
191        if let Some(wanted) = config.analyzer.filter(|&wanted| wanted != recorded) {
192            bail!("store was created with the {recorded} lexical analyzer, not {wanted}; reopen without an analyzer or with {recorded}");
193        }
194        expected.lexical_analyzer = actual.lexical_analyzer.clone();
195        if config.vector_records && actual.version < super::format::VECTOR_RECORDS_SCHEMA_VERSION {
196            bail!("vector records require store schema 7; use warm-format upgrade to create an upgraded copy before opening with vectorRecords");
197        }
198        // Every schema from the oldest supported one opens; only the version differs between
199        // them (it selects the journal format).
200        if (super::format::STORE_SCHEMA_OLDEST..=super::format::STORE_SCHEMA_VERSION)
201            .contains(&actual.version)
202        {
203            expected.version = actual.version;
204        }
205        if actual != expected {
206            bail!("incompatible store schema: dimensions, encoder, embedding model, encryption, or meaning configuration changed; reopen with the original configuration or re-encode source documents into a new store");
207        }
208        Ok((expected.version, recorded))
209    } else {
210        if path.join("vectors_data.bin").exists() {
211            bail!("legacy store has no embedding schema; preserve it and use warm-admin reencode with original source documents to create a new store");
212        }
213        super::audit_effects::AuditEffectStream::open(path)?;
214        super::audit_effects::crash_point("initialized");
215        let analyzer = config.analyzer.unwrap_or_default();
216        expected.lexical_analyzer = (!analyzer.is_legacy()).then(|| analyzer.name().to_owned());
217        super::durable_file::atomic_write(&schema_path, &serde_json::to_vec_pretty(&expected)?)?;
218        Ok((expected.version, analyzer))
219    }
220}