Skip to main content

writerslogic_warm/core/
admin.rs

1// Copyright 2024-2026 WritersLogic Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use anyhow::{anyhow, bail, ensure, Context, Result};
5use crc32fast::Hasher;
6use memmap2::Mmap;
7use serde::Serialize;
8use serde_json::Value;
9use std::collections::{BTreeMap, BTreeSet};
10use std::fs::File;
11use std::path::{Path, PathBuf};
12use std::time::{SystemTime, UNIX_EPOCH};
13
14use super::storage::{
15    is_log_end, list_segments, FormatManifest, FORMAT_MAGIC, FORMAT_MANIFEST, GROWTH_STEP,
16    HEADER_SIZE, LEGACY_SEGMENT_SIZE, MAX_RAW_FRAME_SIZE, SEGMENT_SIZE, STORAGE_FORMAT_VERSION,
17};
18use super::store_lock::{StoreLock, LOCK_FILE};
19use super::{WarmConfig, WarmCore};
20
21const ARENA_DIRECTORY: &str = "vectors_data.bin";
22
23#[derive(Debug, Clone, Serialize)]
24#[serde(rename_all = "camelCase")]
25pub struct StoreInspection {
26    pub store_path: String,
27    pub format_version: u32,
28    pub segment_count: usize,
29    pub frame_count: usize,
30    pub logical_bytes: u64,
31    pub allocated_bytes: u64,
32    pub checksums_verified: bool,
33    /// Manifests whose checksum sidecar was verified (`verify` only).
34    #[serde(default, skip_serializing_if = "Vec::is_empty")]
35    pub manifests_verified: Vec<String>,
36    /// Document cross-check against the opened store (`verify` only).
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub documents: Option<DocumentCheck>,
39}
40
41#[derive(Debug, Clone, Serialize)]
42#[serde(rename_all = "camelCase")]
43pub struct DocumentCheck {
44    /// False when the store was not opened; `reason` says why.
45    pub checked: bool,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub reason: Option<String>,
48    /// Documents the transaction log says are live; absent when the frames are encrypted.
49    #[serde(skip_serializing_if = "Option::is_none")]
50    pub expected: Option<usize>,
51    pub present: usize,
52    pub missing: Vec<String>,
53}
54
55/// Inspect storage framing without opening or changing the WARM engine.
56pub fn inspect_store(path: impl AsRef<Path>, verify_checksums: bool) -> Result<StoreInspection> {
57    let store_path = path.as_ref();
58    let (manifest, arena_path, ids) = store_layout(store_path)?;
59    let segment_count = ids.len();
60    let mut frame_count = 0usize;
61    let mut logical_bytes = 0u64;
62    let mut allocated_bytes = 0u64;
63    for id in ids {
64        let segment_path = arena_path.join(format!("seg_{id}.bin"));
65        let mmap = map_segment(&segment_path, &manifest, id + 1 == segment_count)?;
66        allocated_bytes = allocated_bytes
67            .checked_add(mmap.len() as u64)
68            .context("arena allocated byte count overflow")?;
69        let (frames, bytes) = inspect_segment(&mmap, &segment_path, verify_checksums)?;
70        frame_count += frames;
71        logical_bytes += bytes as u64;
72    }
73    Ok(StoreInspection {
74        store_path: store_path.display().to_string(),
75        format_version: manifest.version,
76        segment_count,
77        frame_count,
78        logical_bytes,
79        allocated_bytes,
80        checksums_verified: verify_checksums,
81        manifests_verified: Vec::new(),
82        documents: None,
83    })
84}
85
86/// Archive size overrides for an immutable snapshot, keyed by source file path.
87/// Only zero padding beyond format 4's aligned active journal capacity is omitted.
88/// The source files are never changed; older formats keep their fixed segment sizes.
89pub fn snapshot_archive_sizes(path: impl AsRef<Path>) -> Result<BTreeMap<PathBuf, u64>> {
90    let (manifest, arena_path, ids) = store_layout(path.as_ref())?;
91    let mut sizes = BTreeMap::new();
92    if manifest.version >= 4 {
93        let id = ids
94            .last()
95            .context("store contains no active arena segment")?;
96        let path = arena_path.join(format!("seg_{id}.bin"));
97        let map = map_segment(&path, &manifest, true)?;
98        let (_, used) = inspect_segment(&map, &path, false)?;
99        let end = used
100            .checked_add(HEADER_SIZE)
101            .context("journal end overflow")?;
102        let size = end.max(SEGMENT_SIZE).div_ceil(SEGMENT_SIZE) * SEGMENT_SIZE;
103        if size < map.len() && map[size..].iter().all(|&byte| byte == 0) {
104            sizes.insert(path, size as u64);
105        }
106    }
107    Ok(sizes)
108}
109
110fn store_layout(store_path: &Path) -> Result<(FormatManifest, PathBuf, Vec<usize>)> {
111    let arena_path = store_path.join(ARENA_DIRECTORY);
112    let manifest_path = arena_path.join(FORMAT_MANIFEST);
113    let manifest: FormatManifest = serde_json::from_slice(
114        &std::fs::read(&manifest_path)
115            .with_context(|| format!("missing storage manifest {}", manifest_path.display()))?,
116    )
117    .with_context(|| format!("invalid storage manifest {}", manifest_path.display()))?;
118
119    if manifest.magic != FORMAT_MAGIC {
120        bail!("unknown storage magic {}", manifest.magic);
121    }
122    if manifest.version > STORAGE_FORMAT_VERSION {
123        bail!(
124            "storage format {} is newer than supported format {}",
125            manifest.version,
126            STORAGE_FORMAT_VERSION
127        );
128    }
129    let expected = if manifest.version == 3 {
130        SEGMENT_SIZE
131    } else {
132        LEGACY_SEGMENT_SIZE
133    };
134    if manifest.segment_size != expected {
135        bail!(
136            "storage segment size mismatch: manifest={}, runtime={}",
137            manifest.segment_size,
138            expected
139        );
140    }
141
142    let arena_path = super::durable_file::arena_generation(&arena_path)?;
143    let ids = list_segments(&arena_path)?;
144    ensure!(!ids.is_empty(), "store contains no arena segments");
145    ensure!(
146        ids.iter().enumerate().all(|(expected, &id)| expected == id),
147        "arena segments are not contiguous from 0: {ids:?}"
148    );
149    Ok((manifest, arena_path, ids))
150}
151
152fn map_segment(path: &Path, manifest: &FormatManifest, active: bool) -> Result<Mmap> {
153    let file = super::durable_file::open_regular(path, false)?;
154    let length = file.metadata()?.len();
155    let valid_size = if manifest.version >= 4 && active {
156        (GROWTH_STEP as u64..=manifest.segment_size as u64).contains(&length)
157            && length % GROWTH_STEP as u64 == 0
158    } else {
159        length == manifest.segment_size as u64
160    };
161    ensure!(
162        valid_size,
163        "segment {} has size {}, expected {}",
164        path.display(),
165        length,
166        manifest.segment_size
167    );
168    Ok(unsafe { Mmap::map(&file)? })
169}
170
171/// `inspect_store(path, true)` plus the manifest checksums and a document cross-check: the
172/// store is opened through the engine, which authenticates and replays every frame, and
173/// every document the log says is live must resolve there. Corruption fails the verify
174/// instead of being served as a shorter store.
175pub fn verify_store(
176    path: impl AsRef<Path>,
177    encryption_passphrase_env: Option<String>,
178) -> Result<StoreInspection> {
179    let store = path.as_ref();
180    let mut inspection = inspect_store(store, true)?;
181    let arena_path = store.join(ARENA_DIRECTORY);
182    inspection.manifests_verified = super::durable_file::verify_manifests(store, &arena_path)?;
183    let schema_path = store.join("store.json");
184    let schema: Value = serde_json::from_slice(
185        &std::fs::read(&schema_path)
186            .with_context(|| format!("missing store schema {}", schema_path.display()))?,
187    )
188    .with_context(|| format!("invalid store schema {}", schema_path.display()))?;
189    let dimensions = u32::try_from(
190        schema["dimensions"]
191            .as_u64()
192            .context("store.json lacks dimensions")?,
193    )?;
194    let mut config = WarmConfig::default();
195    if let Some(name) = schema["text_encoder"].as_str() {
196        config.text_encoder = name
197            .parse()
198            .map_err(|e| anyhow!("store.json text encoder {name}: {e}"))?;
199    }
200    config.meaning.enabled = schema["meaning_enabled"].as_bool().unwrap_or(false);
201    config.embedding_space = serde_json::from_value(schema["embedding_space"].clone())
202        .context("store.json embedding_space")?;
203    let master_key = schema["key_scheme"].as_str() == Some(super::schema::MASTER_KEY_SCHEME);
204    let expected = if master_key && schema["encrypted"].as_bool().unwrap_or(false) {
205        None
206    } else if schema["encrypted"].as_bool().unwrap_or(false) {
207        let Some(env) = encryption_passphrase_env else {
208            inspection.documents = Some(DocumentCheck {
209                checked: false,
210                reason: Some(
211                    "encrypted store: pass --encryption-passphrase-env to open it and \
212                     authenticate every frame"
213                        .into(),
214                ),
215                expected: None,
216                present: 0,
217                missing: Vec::new(),
218            });
219            return Ok(inspection);
220        };
221        config.security.encryption_enabled = true;
222        config.security.encryption_passphrase_env = Some(env);
223        None
224    } else {
225        Some(live_document_ids(&arena_path)?)
226    };
227    let core = WarmCore::new(dimensions, Some(store.display().to_string()), Some(config))
228        .context("opening the store for the document cross-check")?;
229    core.verified_document_count()
230        .context("validating checkpoint documents for the document cross-check")?;
231    inspection.documents = Some(match expected {
232        Some(ids) => {
233            let missing = missing_documents(&ids, &core);
234            DocumentCheck {
235                checked: true,
236                reason: None,
237                expected: Some(ids.len()),
238                present: ids.len() - missing.len(),
239                missing,
240            }
241        }
242        None => DocumentCheck {
243            checked: true,
244            reason: Some(
245                "every frame authenticated on open; the presence cross-check needs plaintext \
246                 frames"
247                    .into(),
248            ),
249            expected: None,
250            present: 0,
251            missing: Vec::new(),
252        },
253    });
254    Ok(inspection)
255}
256
257/// Document ids the plaintext transaction log leaves live: every `Document` id minus later
258/// `DeleteDocument`s. Frame bounds and checksums were validated by `inspect_store` first.
259fn live_document_ids(arena_path: &Path) -> Result<BTreeSet<String>> {
260    let generation = super::durable_file::arena_generation(arena_path)?;
261    let mut live = BTreeSet::new();
262    for segment in 0usize.. {
263        let segment_path = generation.join(format!("seg_{segment}.bin"));
264        if !segment_path.exists() {
265            break;
266        }
267        let mmap = unsafe { Mmap::map(&File::open(&segment_path)?)? };
268        let mut offset = 0usize;
269        while offset + HEADER_SIZE <= mmap.len() {
270            let header = &mmap[offset..offset + HEADER_SIZE];
271            if is_log_end(header) {
272                break;
273            }
274            let raw_len = u32::from_le_bytes(header[4..8].try_into()?) as usize;
275            let comp_len = u32::from_le_bytes(header[8..12].try_into()?) as usize;
276            let frame_end = offset + HEADER_SIZE + comp_len;
277            ensure!(
278                frame_end <= mmap.len(),
279                "truncated frame in {} at byte {offset}",
280                segment_path.display()
281            );
282            let payload = &mmap[offset + HEADER_SIZE..frame_end];
283            let decoded = if comp_len < raw_len {
284                lz4_flex::decompress(payload, raw_len)?
285            } else {
286                payload.to_vec()
287            };
288            let json = super::engine::journal::payload_json(&decoded)
289                .with_context(|| {
290                    format!(
291                        "frame at byte {offset} of {} is not a transaction frame",
292                        segment_path.display()
293                    )
294                })?
295                .with_context(|| {
296                    format!(
297                        "frame at byte {offset} of {} is not a transaction",
298                        segment_path.display()
299                    )
300                })?;
301            let mutations: Vec<Value> = serde_json::from_slice(&json).with_context(|| {
302                format!(
303                    "frame at byte {offset} of {} is not a transaction",
304                    segment_path.display()
305                )
306            })?;
307            for mutation in &mutations {
308                let id_of = |variant: &str| {
309                    mutation
310                        .get(variant)
311                        .and_then(|m| m.get("id"))
312                        .and_then(Value::as_str)
313                };
314                if let Some(id) = id_of("Document") {
315                    live.insert(id.to_string());
316                } else if let Some(id) = id_of("DeleteDocument") {
317                    live.remove(id);
318                }
319            }
320            offset = frame_end;
321        }
322    }
323    Ok(live)
324}
325
326fn missing_documents(expected: &BTreeSet<String>, core: &WarmCore) -> Vec<String> {
327    expected
328        .iter()
329        .filter(|id| !core.has_document(id))
330        .cloned()
331        .collect()
332}
333
334pub(crate) fn inspect_segment(
335    data: &[u8],
336    path: &Path,
337    verify_checksums: bool,
338) -> Result<(usize, usize)> {
339    let mut offset = 0usize;
340    let mut frames = 0usize;
341    while offset + HEADER_SIZE <= data.len() {
342        let expected_crc = u32::from_le_bytes(data[offset..offset + 4].try_into()?);
343        let raw_len = u32::from_le_bytes(data[offset + 4..offset + 8].try_into()?) as usize;
344        let comp_len = u32::from_le_bytes(data[offset + 8..offset + 12].try_into()?) as usize;
345        if raw_len == 0 && comp_len == 0 {
346            if is_log_end(&data[offset..offset + HEADER_SIZE]) {
347                return Ok((frames, offset));
348            }
349            bail!(
350                "invalid end-of-log header in {} at byte {}",
351                path.display(),
352                offset
353            );
354        }
355        if raw_len == 0 || raw_len > MAX_RAW_FRAME_SIZE || comp_len == 0 || comp_len > data.len() {
356            bail!(
357                "invalid frame header in {} at byte {}",
358                path.display(),
359                offset
360            );
361        }
362        let frame_end = offset
363            .checked_add(HEADER_SIZE + comp_len)
364            .ok_or_else(|| anyhow!("frame length overflow in {}", path.display()))?;
365        if frame_end > data.len() {
366            bail!("truncated frame in {} at byte {}", path.display(), offset);
367        }
368        if verify_checksums {
369            let payload = &data[offset + HEADER_SIZE..frame_end];
370            let decoded = if comp_len < raw_len {
371                lz4_flex::decompress(payload, raw_len).with_context(|| {
372                    format!("invalid LZ4 frame in {} at byte {}", path.display(), offset)
373                })?
374            } else {
375                payload.to_vec()
376            };
377            let mut hasher = Hasher::new();
378            hasher.update(&decoded);
379            if hasher.finalize() != expected_crc {
380                bail!("checksum mismatch in {} at byte {}", path.display(), offset);
381            }
382        }
383        frames += 1;
384        offset = frame_end;
385    }
386    Ok((frames, offset))
387}
388
389/// Create a verified, point-in-time copy of a current-format store.
390/// The source is exclusively locked for the full copy and verification. The
391/// destination appears only after verification succeeds.
392pub fn migrate_store(
393    source: impl AsRef<Path>,
394    destination: impl AsRef<Path>,
395) -> Result<StoreInspection> {
396    let source = source.as_ref();
397    let destination = destination.as_ref();
398    if destination.exists() {
399        bail!(
400            "migration destination already exists: {}",
401            destination.display()
402        );
403    }
404    let source_canonical = source.canonicalize()?;
405    let parent = destination.parent().unwrap_or_else(|| Path::new("."));
406    std::fs::create_dir_all(parent)?;
407    let parent_canonical = parent.canonicalize()?;
408    if parent_canonical.starts_with(&source_canonical) {
409        bail!("migration destination cannot be inside the source store");
410    }
411
412    let _source_lock = StoreLock::acquire(source)?;
413    // Verify after acquiring the lock so the exact snapshot being copied is
414    // the snapshot that passed integrity validation.
415    inspect_store(source, true)?;
416    let nonce = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos();
417    let temp = parent.join(format!(".warm-migrate-{}-{nonce}", std::process::id()));
418    let result = (|| -> Result<StoreInspection> {
419        copy_tree(source, &temp)?;
420        let inspection = inspect_store(&temp, true)?;
421        // Copied files are flushed; supported platforms also sync directory entries.
422        std::fs::rename(&temp, destination).with_context(|| {
423            format!(
424                "failed to atomically publish migration {} -> {}",
425                temp.display(),
426                destination.display()
427            )
428        })?;
429        super::durable_file::sync_directory(parent)?;
430        Ok(StoreInspection {
431            store_path: destination.display().to_string(),
432            ..inspection
433        })
434    })();
435    if result.is_err() && temp.exists() {
436        // Best effort: the migration error is what the caller needs, not a cleanup failure.
437        let _ = std::fs::remove_dir_all(&temp);
438    }
439    result
440}
441
442pub(crate) fn copy_tree(source: &Path, destination: &Path) -> Result<()> {
443    std::fs::create_dir(destination)?;
444    for entry in std::fs::read_dir(source)? {
445        let entry = entry?;
446        let file_type = entry.file_type()?;
447        if file_type.is_symlink() {
448            bail!("migration refuses symbolic link {}", entry.path().display());
449        }
450        if entry.file_name() == LOCK_FILE {
451            continue;
452        }
453        let target = destination.join(entry.file_name());
454        if file_type.is_dir() {
455            copy_tree(&entry.path(), &target)?;
456        } else if file_type.is_file() {
457            super::durable_file::copy_file_synced(&entry.path(), &target)?;
458        } else {
459            bail!("migration refuses special file {}", entry.path().display());
460        }
461    }
462    super::durable_file::sync_directory(destination)
463}
464
465/// Re-encode original JSONL source documents into a new, atomically published store.
466pub fn reencode_documents(
467    input: impl AsRef<Path>,
468    destination: impl AsRef<Path>,
469    dimensions: u32,
470    config: super::WarmConfig,
471) -> Result<StoreInspection> {
472    use std::io::{BufRead, BufReader, Read};
473    let destination = destination.as_ref();
474    if destination.exists() {
475        bail!("re-encoding destination already exists");
476    }
477    let parent = destination
478        .parent()
479        .filter(|p| !p.as_os_str().is_empty())
480        .unwrap_or_else(|| Path::new("."));
481    std::fs::create_dir_all(parent)?;
482    let temporary = tempfile::Builder::new()
483        .prefix(".warm-reencode-")
484        .tempdir_in(parent)?;
485    let mut source = BufReader::new(File::open(input.as_ref())?);
486    {
487        let warm = super::WarmCore::new(
488            dimensions,
489            Some(temporary.path().display().to_string()),
490            Some(config),
491        )?;
492        let mut line_number = 0;
493        loop {
494            let mut line = String::new();
495            let bytes = source
496                .by_ref()
497                .take(16 * 1024 * 1024 + 1)
498                .read_line(&mut line)?;
499            if bytes == 0 {
500                break;
501            }
502            line_number += 1;
503            if bytes > 16 * 1024 * 1024 {
504                bail!("JSONL line {line_number} exceeds 16 MiB");
505            }
506            if line.trim().is_empty() {
507                continue;
508            }
509            let document: super::documents::DocumentInput = serde_json::from_str(&line)
510                .with_context(|| format!("invalid source document on line {line_number}"))?;
511            warm.memorize_document(document)
512                .with_context(|| format!("cannot re-encode line {line_number}"))?;
513        }
514        warm.flush()?;
515    }
516    let inspection = inspect_store(temporary.path(), true)?;
517    super::durable_file::sync_directory(temporary.path())?;
518    std::fs::rename(temporary.path(), destination)?;
519    super::durable_file::sync_directory(parent)?;
520    Ok(StoreInspection {
521        store_path: destination.display().to_string(),
522        ..inspection
523    })
524}
525
526#[cfg(test)]
527mod tests {
528    use super::*;
529    use crate::core::documents::DocumentInput;
530    use crate::core::entangled::EntangledHVec;
531    use crate::core::WarmCore;
532
533    #[test]
534    fn archive_sizes_preserve_end_markers_at_allocation_boundaries() -> Result<()> {
535        use std::io::{Seek, SeekFrom, Write};
536
537        for delta in [-1isize, 0, 1] {
538            let root = tempfile::tempdir()?;
539            drop(WarmCore::new(
540                256,
541                Some(root.path().display().to_string()),
542                None,
543            )?);
544            let path = root.path().join(ARENA_DIRECTORY).join("seg_0.bin");
545            let capacity = 2 * SEGMENT_SIZE;
546            let used = (SEGMENT_SIZE - HEADER_SIZE)
547                .checked_add_signed(delta)
548                .unwrap();
549            let mut file = std::fs::OpenOptions::new().write(true).open(&path)?;
550            file.set_len(capacity as u64)?;
551            let first = SEGMENT_SIZE / 2;
552            for (length, version) in [(first, 1u32), (used - first - 2 * HEADER_SIZE, 2)] {
553                let mut crc = Hasher::new();
554                let zeroes = [0; 8192];
555                let mut left = length;
556                while left > 0 {
557                    let count = left.min(zeroes.len());
558                    crc.update(&zeroes[..count]);
559                    left -= count;
560                }
561                for word in [crc.finalize(), length as u32, length as u32, version] {
562                    file.write_all(&word.to_le_bytes())?;
563                }
564                file.seek(SeekFrom::Current(length as i64))?;
565            }
566            for word in [0u32, 0, 0, super::super::storage::END_MARK] {
567                file.write_all(&word.to_le_bytes())?;
568            }
569            file.sync_all()?;
570            assert_eq!(inspect_store(root.path(), true)?.frame_count, 2);
571            let sizes = snapshot_archive_sizes(root.path())?;
572            let actual = sizes.get(&path).copied().unwrap_or(capacity as u64);
573            let expected = if delta <= 0 { SEGMENT_SIZE } else { capacity };
574            assert_eq!(actual, expected as u64, "end marker boundary {delta}");
575            assert_eq!(file.metadata()?.len(), capacity as u64);
576            file.seek(SeekFrom::End(-1))?;
577            file.write_all(&[0x7f])?;
578            file.sync_all()?;
579            assert!(snapshot_archive_sizes(root.path())?.is_empty());
580        }
581        Ok(())
582    }
583
584    /// `verify` cross-checks the opened store against the log: a healthy store reports every
585    /// live document present, and a logged document the store cannot resolve is named.
586    #[test]
587    fn verify_cross_checks_logged_documents() -> Result<()> {
588        let root = tempfile::tempdir()?;
589        let store = root.path().join("store");
590        {
591            let warm = WarmCore::new(256, Some(store.display().to_string()), None)?;
592            for n in 0..3 {
593                warm.memorize_document(DocumentInput {
594                    id: format!("doc{n}"),
595                    text: format!("document {n} about harbors and ledgers"),
596                    source_uri: None,
597                    version: None,
598                    metadata: None,
599                    chunk_words: None,
600                    overlap_words: None,
601                    store_text: None,
602                    embeddings: None,
603                    title_weight: None,
604                })?;
605            }
606            assert!(warm.delete_document("doc1")?);
607            warm.flush()?;
608        }
609        let verified = verify_store(&store, None)?;
610        assert!(verified
611            .manifests_verified
612            .iter()
613            .any(|m| m == "store.json"));
614        assert!(verified
615            .manifests_verified
616            .iter()
617            .any(|m| m == "format.json"));
618        let documents = verified
619            .documents
620            .expect("plaintext stores are cross-checked");
621        assert_eq!(
622            (documents.checked, documents.expected, documents.present),
623            (true, Some(2), 2)
624        );
625        assert!(documents.missing.is_empty());
626
627        let core = WarmCore::new(256, Some(store.display().to_string()), None)?;
628        let expected: BTreeSet<String> = ["doc0", "doc2", "doc9"]
629            .into_iter()
630            .map(String::from)
631            .collect();
632        assert_eq!(
633            missing_documents(&expected, &core),
634            vec!["doc9".to_string()]
635        );
636        Ok(())
637    }
638
639    #[test]
640    fn migration_copy_preserves_read_only_files_and_excludes_the_lock() -> Result<()> {
641        let root = tempfile::tempdir()?;
642        let source = root.path().join("source");
643        let target = root.path().join("target");
644        std::fs::create_dir_all(source.join("nested"))?;
645        let original = source.join("nested/data");
646        std::fs::write(&original, b"migration data")?;
647        #[cfg(windows)]
648        std::fs::write(source.join("nested/data:metadata"), b"alternate stream")?;
649        std::fs::write(source.join(LOCK_FILE), b"process lock")?;
650        let writable = std::fs::metadata(&original)?.permissions();
651        let mut read_only = writable.clone();
652        read_only.set_readonly(true);
653        std::fs::set_permissions(&original, read_only)?;
654
655        let result = copy_tree(&source, &target);
656        let copied = target.join("nested/data");
657        let source_read_only = std::fs::metadata(&original)?.permissions().readonly();
658        let copied_read_only = std::fs::metadata(&copied).map(|m| m.permissions().readonly());
659        std::fs::set_permissions(&original, writable.clone())?;
660        if copied.exists() {
661            std::fs::set_permissions(&copied, writable)?;
662        }
663
664        result?;
665        assert_eq!(std::fs::read(copied)?, b"migration data");
666        #[cfg(windows)]
667        assert_eq!(
668            std::fs::read(target.join("nested/data:metadata"))?,
669            b"alternate stream"
670        );
671        assert!(source_read_only && copied_read_only?);
672        assert!(!target.join(LOCK_FILE).exists());
673        Ok(())
674    }
675
676    #[test]
677    fn inspect_verify_and_migrate_roundtrip() -> Result<()> {
678        let root = tempfile::tempdir()?;
679        let source = root.path().join("source");
680        {
681            let warm = WarmCore::new(256, Some(source.display().to_string()), None)?;
682            warm.memorize("one".into(), EntangledHVec::new_deterministic(256, 1))?;
683        }
684
685        let inspected = inspect_store(&source, false)?;
686        assert_eq!(inspected.frame_count, 1);
687        assert!(!inspected.checksums_verified);
688        let verified = inspect_store(&source, true)?;
689        assert!(verified.checksums_verified);
690        let destination = root.path().join("destination");
691        let migrated = migrate_store(&source, &destination)?;
692        assert_eq!(migrated.frame_count, 1);
693        let reopened = WarmCore::new(256, Some(destination.display().to_string()), None)?;
694        assert_eq!(reopened.index_status().vector_count, 1);
695        Ok(())
696    }
697
698    #[test]
699    fn verification_rejects_corruption() -> Result<()> {
700        use std::fs::OpenOptions;
701        use std::io::{Seek, SeekFrom, Write};
702        let root = tempfile::tempdir()?;
703        let source = root.path().join("source");
704        {
705            let warm = WarmCore::new(256, Some(source.display().to_string()), None)?;
706            warm.memorize("one".into(), EntangledHVec::new_deterministic(256, 1))?;
707        }
708        let segment = source.join(ARENA_DIRECTORY).join("seg_0.bin");
709        let mut file = OpenOptions::new().write(true).open(segment)?;
710        file.seek(SeekFrom::Start(HEADER_SIZE as u64))?;
711        file.write_all(&[0xff])?;
712        file.sync_all()?;
713        assert!(inspect_store(&source, true).is_err());
714        Ok(())
715    }
716}