holix-rs 1.4.0

Local-first context-folding index runtime with SQLite WAL/FTS5 persistence, Orion HNSW semantic routing, BlobSource hydration, and AST/CSV/XLSX/EML slicers.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};

use holix_core_verified::coords::{validate_coordinate, Coordinate};
use holix_core_verified::retrieval::allow_raw_hydration;

use crate::persist::StreamingHash64;
use crate::store::{AssetRecord, IndexStore};

/// Hard upper bound on a single lazy disk hydration read (`4 MiB`).
pub const DEFAULT_MAX_HYDRATE_BYTES: u64 = 4 * 1024 * 1024;

/// Errors emitted during lazy disk hydration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HydrateError {
    DiscoveryModeBlocked,
    UnknownProjection,
    UnknownAsset,
    InvalidCoordinate,
    UnsupportedCoordinate,
    SpanExceedsMaxBytes,
    StaleFileLength,
    StaleContentHash,
    Io(String),
}

/// Validates discovery gate, coordinate bounds, and `max_hydrate_bytes`, returning `(offset, len)`.
pub fn hydrate_span_bounds(
    coord: Coordinate,
    payload_len: u64,
    discovery_mode: bool,
    max_hydrate_bytes: u64,
) -> Result<(u64, u64), HydrateError> {
    if !allow_raw_hydration(discovery_mode) {
        return Err(HydrateError::DiscoveryModeBlocked);
    }
    if !validate_coordinate(coord, payload_len) {
        return Err(HydrateError::InvalidCoordinate);
    }
    let (offset, len) = match coord {
        Coordinate::TextRange {
            start_char,
            end_char,
        } => (start_char, end_char - start_char),
        Coordinate::BinarySpan {
            byte_offset,
            length,
        } => (byte_offset, length),
        Coordinate::PdfRegion { .. } | Coordinate::MediaTimestamp { .. } => {
            return Err(HydrateError::UnsupportedCoordinate);
        }
    };
    let end = offset
        .checked_add(len)
        .ok_or(HydrateError::InvalidCoordinate)?;
    if end > payload_len {
        return Err(HydrateError::InvalidCoordinate);
    }
    if len > max_hydrate_bytes {
        return Err(HydrateError::SpanExceedsMaxBytes);
    }
    Ok((offset, len))
}

/// Storage backend abstraction for lazy, bounded projection hydration.
pub trait BlobSource {
    /// Returns the total byte length of `asset` in the backing store.
    fn content_len(&self, asset: &AssetRecord) -> Result<u64, HydrateError>;

    /// Reads `len` bytes starting at `offset` from `asset`.
    fn read_range(
        &self,
        asset: &AssetRecord,
        offset: u64,
        len: u64,
    ) -> Result<Vec<u8>, HydrateError>;

    /// Reads the entire payload of `asset` from the backing store.
    fn read_all(&self, asset: &AssetRecord) -> Result<Vec<u8>, HydrateError>;

    /// Computes the 64-bit FNV-1a hash of `asset` for optional freshness checks.
    fn hash_all(&self, asset: &AssetRecord) -> Result<u64, HydrateError> {
        let bytes = self.read_all(asset)?;
        let mut hasher = StreamingHash64::default();
        hasher.update(&bytes);
        Ok(hasher.finish())
    }
}

/// Filesystem-backed `BlobSource` resolving relative URIs against an optional workspace root.
#[derive(Debug, Clone, Default)]
pub struct FsBlobSource {
    pub root: Option<PathBuf>,
}

impl FsBlobSource {
    /// Creates an `FsBlobSource` resolving paths directly (relative to CWD when not absolute).
    pub fn new() -> Self {
        Self { root: None }
    }

    /// Creates an `FsBlobSource` anchored at `root` for mounted repository lookups.
    pub fn with_root(root: impl Into<PathBuf>) -> Self {
        Self {
            root: Some(root.into()),
        }
    }

    fn resolve_path(&self, asset: &AssetRecord) -> PathBuf {
        let raw = asset.locator.as_deref().unwrap_or(&asset.uri);
        let p = Path::new(raw);
        if p.is_absolute() {
            return p.to_path_buf();
        }
        match &self.root {
            Some(root) => root.join(p),
            None => p.to_path_buf(),
        }
    }
}

impl BlobSource for FsBlobSource {
    fn content_len(&self, asset: &AssetRecord) -> Result<u64, HydrateError> {
        let path = self.resolve_path(asset);
        let meta = std::fs::metadata(path).map_err(|e| HydrateError::Io(e.to_string()))?;
        Ok(meta.len())
    }

    fn read_range(
        &self,
        asset: &AssetRecord,
        offset: u64,
        len: u64,
    ) -> Result<Vec<u8>, HydrateError> {
        let path = self.resolve_path(asset);
        let mut file = File::open(path).map_err(|e| HydrateError::Io(e.to_string()))?;
        file.seek(SeekFrom::Start(offset))
            .map_err(|e| HydrateError::Io(e.to_string()))?;
        let cap = usize::try_from(len).map_err(|_| HydrateError::SpanExceedsMaxBytes)?;
        let mut out = Vec::with_capacity(cap);
        file.take(len)
            .read_to_end(&mut out)
            .map_err(|e| HydrateError::Io(e.to_string()))?;
        if out.len() as u64 != len {
            return Err(HydrateError::StaleFileLength);
        }
        Ok(out)
    }

    fn read_all(&self, asset: &AssetRecord) -> Result<Vec<u8>, HydrateError> {
        let path = self.resolve_path(asset);
        std::fs::read(path).map_err(|e| HydrateError::Io(e.to_string()))
    }

    fn hash_all(&self, asset: &AssetRecord) -> Result<u64, HydrateError> {
        let path = self.resolve_path(asset);
        let mut file = File::open(path).map_err(|e| HydrateError::Io(e.to_string()))?;
        let mut hasher = StreamingHash64::default();
        let mut chunk = [0u8; 8192];
        loop {
            let n = file
                .read(&mut chunk)
                .map_err(|e| HydrateError::Io(e.to_string()))?;
            if n == 0 {
                break;
            }
            hasher.update(&chunk[..n]);
        }
        Ok(hasher.finish())
    }
}

/// Lazily reads only the exact byte span for `proj_id` from `source`, failing closed on discovery
/// mode, stale payload lengths, content-hash mismatches, or spans exceeding `max_hydrate_bytes`.
pub fn hydrate_projection_with_source(
    store: &IndexStore,
    proj_id: u32,
    discovery_mode: bool,
    max_hydrate_bytes: u64,
    expected_hash: Option<u64>,
    source: &dyn BlobSource,
) -> Result<Vec<u8>, HydrateError> {
    let proj = store
        .projection(proj_id)
        .ok_or(HydrateError::UnknownProjection)?;
    let asset = store
        .asset(proj.asset_id)
        .ok_or(HydrateError::UnknownAsset)?;

    let (offset, len) = hydrate_span_bounds(
        proj.coord,
        asset.payload_len,
        discovery_mode,
        max_hydrate_bytes,
    )?;

    let actual_len = source.content_len(asset)?;
    if actual_len != asset.payload_len {
        return Err(HydrateError::StaleFileLength);
    }

    if !asset.immutable {
        if let Some(expected) = expected_hash {
            if source.hash_all(asset)? != expected {
                return Err(HydrateError::StaleContentHash);
            }
        }
    }

    source.read_range(asset, offset, len)
}

/// Lazily reads only the exact byte span for `proj_id` from disk using `FsBlobSource`.
pub fn hydrate_projection(
    store: &IndexStore,
    proj_id: u32,
    discovery_mode: bool,
    max_hydrate_bytes: u64,
    expected_hash: Option<u64>,
) -> Result<Vec<u8>, HydrateError> {
    hydrate_projection_with_source(
        store,
        proj_id,
        discovery_mode,
        max_hydrate_bytes,
        expected_hash,
        &FsBlobSource::new(),
    )
}

#[cfg(kani)]
#[kani::proof]
#[kani::unwind(2)]
fn verify_hydrate_gate_no_panic() {
    let payload_len: u64 = kani::any();
    let offset: u64 = kani::any();
    let len: u64 = kani::any();
    let discovery_mode: bool = kani::any();
    let max_bytes: u64 = kani::any();

    let coord = Coordinate::BinarySpan {
        byte_offset: offset,
        length: len,
    };
    let res = hydrate_span_bounds(coord, payload_len, discovery_mode, max_bytes);
    if discovery_mode {
        assert!(res == Err(HydrateError::DiscoveryModeBlocked));
    }
    if let Ok((out_off, out_len)) = res {
        assert!(out_off == offset);
        assert!(out_len == len);
        assert!(out_len <= max_bytes);
    }
}

#[cfg(test)]
mod tests {
    use super::{hydrate_projection, HydrateError, DEFAULT_MAX_HYDRATE_BYTES};
    use crate::persist::content_hash_64;
    use crate::store::{AssetRecord, FoldedProjection, IndexStore};
    use holix_core_verified::coords::{Coordinate, Modality};
    use holix_core_verified::tokens::TokenKind;

    #[test]
    fn rejects_discovery_mode_stale_file_and_oversized_span() {
        let tmp = std::env::temp_dir().join("holix_m7_hydrate_test.txt");
        let payload = b"hello holix world";
        std::fs::write(&tmp, payload).unwrap();
        let hash = content_hash_64(payload);

        let mut store = IndexStore::new();
        store
            .register_asset(AssetRecord {
                asset_id: 1,
                modality: Modality::Text,
                payload_len: payload.len() as u64,
                uri: tmp.to_string_lossy().into_owned(),
                mtime_ms: 0,
                locator: None,
                immutable: false,
                tags: std::collections::BTreeMap::new(),
            })
            .unwrap();
        store
            .insert_projection(FoldedProjection {
                id: 1,
                asset_id: 1,
                modality: Modality::Text,
                extractor_id: 1,
                coord: Coordinate::TextRange {
                    start_char: 6,
                    end_char: 11,
                },
                layer_tokens: vec![2],
                kinds: vec![TokenKind::Semantic],
                label: String::new(),
            })
            .unwrap();

        assert_eq!(
            hydrate_projection(&store, 1, true, DEFAULT_MAX_HYDRATE_BYTES, Some(hash)),
            Err(HydrateError::DiscoveryModeBlocked)
        );
        assert_eq!(
            hydrate_projection(&store, 1, false, 4, Some(hash)),
            Err(HydrateError::SpanExceedsMaxBytes)
        );
        assert_eq!(
            hydrate_projection(&store, 1, false, DEFAULT_MAX_HYDRATE_BYTES, Some(hash)),
            Ok(b"holix".to_vec())
        );

        // Same-length in-place edit caught by content hash.
        std::fs::write(&tmp, b"hello XXXXX world").unwrap();
        assert_eq!(
            hydrate_projection(&store, 1, false, DEFAULT_MAX_HYDRATE_BYTES, Some(hash)),
            Err(HydrateError::StaleContentHash)
        );

        // Truncated file caught by length check.
        std::fs::write(&tmp, b"short").unwrap();
        assert_eq!(
            hydrate_projection(&store, 1, false, DEFAULT_MAX_HYDRATE_BYTES, None),
            Err(HydrateError::StaleFileLength)
        );

        let _ = std::fs::remove_file(&tmp);
    }

    #[test]
    fn hydrates_from_custom_blob_source_with_cap_and_hash_check() {
        use std::collections::HashMap;

        struct MemSource(HashMap<String, Vec<u8>>);

        impl super::BlobSource for MemSource {
            fn content_len(&self, asset: &AssetRecord) -> Result<u64, HydrateError> {
                self.0
                    .get(&asset.uri)
                    .map(|b| b.len() as u64)
                    .ok_or_else(|| HydrateError::Io("missing blob".to_string()))
            }

            fn read_range(
                &self,
                asset: &AssetRecord,
                offset: u64,
                len: u64,
            ) -> Result<Vec<u8>, HydrateError> {
                let bytes = self
                    .0
                    .get(&asset.uri)
                    .ok_or_else(|| HydrateError::Io("missing blob".to_string()))?;
                let start = usize::try_from(offset).map_err(|_| HydrateError::InvalidCoordinate)?;
                let span = usize::try_from(len).map_err(|_| HydrateError::SpanExceedsMaxBytes)?;
                Ok(bytes[start..start + span].to_vec())
            }

            fn read_all(&self, asset: &AssetRecord) -> Result<Vec<u8>, HydrateError> {
                self.0
                    .get(&asset.uri)
                    .cloned()
                    .ok_or_else(|| HydrateError::Io("missing blob".to_string()))
            }
        }

        let payload = b"object store payload";
        let hash = content_hash_64(payload);
        let mut blobs = HashMap::new();
        blobs.insert("obj://bucket/doc.txt".to_string(), payload.to_vec());
        let source = MemSource(blobs);

        let mut store = IndexStore::new();
        store
            .register_asset(AssetRecord {
                asset_id: 7,
                modality: Modality::Text,
                payload_len: payload.len() as u64,
                uri: "obj://bucket/doc.txt".to_string(),
                mtime_ms: 0,
                locator: None,
                immutable: false,
                tags: std::collections::BTreeMap::new(),
            })
            .unwrap();
        store
            .insert_projection(FoldedProjection {
                id: 9,
                asset_id: 7,
                modality: Modality::Text,
                extractor_id: 1,
                coord: Coordinate::TextRange {
                    start_char: 7,
                    end_char: 12,
                },
                layer_tokens: vec![2],
                kinds: vec![TokenKind::Semantic],
                label: "store".to_string(),
            })
            .unwrap();

        assert_eq!(
            super::hydrate_projection_with_source(
                &store,
                9,
                false,
                DEFAULT_MAX_HYDRATE_BYTES,
                Some(hash),
                &source
            ),
            Ok(b"store".to_vec())
        );
        assert_eq!(
            super::hydrate_projection_with_source(&store, 9, false, 3, Some(hash), &source),
            Err(HydrateError::SpanExceedsMaxBytes)
        );
        assert_eq!(
            super::hydrate_projection_with_source(
                &store,
                9,
                false,
                DEFAULT_MAX_HYDRATE_BYTES,
                Some(hash ^ 1),
                &source
            ),
            Err(HydrateError::StaleContentHash)
        );
    }
}