use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use tracing::info;
use crate::graph::pdg::ProgramDependenceGraph;
use crate::search::search::{SearchEngine, SearchSnapshot};
use super::fragment;
pub(crate) fn persist_embeddings_to_mmap(
search_engine: &SearchEngine,
project_path: &Path,
) -> Result<()> {
let path = crate::search::vector::mmap_embeddings_path(project_path);
if search_engine.is_mmap_backed() && path.is_file() {
let engine_rows = search_engine.node_count();
let file_rows = crate::search::vector::MmapEmbeddingIndex::open(&path)
.map(|index| index.len())
.unwrap_or(usize::MAX);
if file_rows == engine_rows {
return Ok(());
}
info!(
file_rows,
engine_rows, "Rewriting mmap embeddings after row-count drift"
);
}
let embeddings = search_engine.collect_embeddings();
if embeddings.is_empty() {
return Ok(());
}
crate::search::vector::write_mmap_embeddings(&path, &embeddings)
.map_err(|e| anyhow::anyhow!("Failed to write mmap embeddings: {e}"))?;
info!(
count = embeddings.len(),
path = %path.display(),
"Persisted embeddings to mmap file"
);
Ok(())
}
fn search_snapshot_path(project_path: &Path) -> PathBuf {
project_path.join(".leindex").join("search_snapshot.bin")
}
pub(crate) fn persisted_search_identity_from_graph(
pdg: &crate::graph::pdg::ProgramDependenceGraph,
) -> (usize, usize, String) {
let mut collapsed = crate::storage::generation::graph_codec::collapse_for_layer(pdg);
super::normalize_external_nodes(&mut collapsed);
let fingerprint = pdg_search_fingerprint(&collapsed);
(collapsed.node_count(), collapsed.edge_count(), fingerprint)
}
pub(crate) fn persist_search_snapshot(
search_engine: &SearchEngine,
project_path: &Path,
pdg_nodes: usize,
pdg_edges: usize,
pdg_fingerprint: String,
) -> Result<()> {
let mut snapshot = search_engine.search_snapshot(pdg_nodes, pdg_edges, pdg_fingerprint);
if snapshot.indexed_nodes == 0 {
return Ok(());
}
let fragment_embeddings = search_engine.collect_fragment_embeddings();
persist_fragment_embeddings_to_mmap(project_path, &fragment_embeddings)?;
if !fragment_embeddings.is_empty() {
let fragment_ids: Vec<String> = fragment_embeddings
.iter()
.map(|(id, _)| id.clone())
.collect();
snapshot.fragment_root_hash = Some(fragment::sync::compute_fragment_root_hash_from_ids(
&fragment_ids,
));
let generation =
fragment::sync::load_fragment_sync_manifest(&project_path.join(".leindex"))
.ok()
.flatten()
.map(|manifest| manifest.generation)
.unwrap_or(0);
fragment::sync::persist_fragment_root_from_ids(project_path, &fragment_ids, generation)?;
}
let path = search_snapshot_path(project_path);
let sidecar_path = project_path
.join(".leindex")
.join("search_snapshot.identity");
let bytes = bincode::serialize(&snapshot).context("Failed to serialize search snapshot")?;
let identity = format!("v2:{}\n", blake3::hash(&bytes));
if path.is_file()
&& std::fs::read_to_string(&sidecar_path).ok().as_deref() == Some(identity.as_str())
{
tracing::debug!(
path = %path.display(),
"Search snapshot unchanged; skipping rewrite"
);
return Ok(());
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create search snapshot directory: {}",
parent.display()
)
})?;
}
std::fs::write(&path, &bytes)
.with_context(|| format!("Failed to write search snapshot: {}", path.display()))?;
std::fs::write(&sidecar_path, &identity).with_context(|| {
format!(
"Failed to write search snapshot identity sidecar: {}",
sidecar_path.display()
)
})?;
info!(
count = snapshot.indexed_nodes,
path = %path.display(),
"Persisted search snapshot"
);
Ok(())
}
pub(crate) fn try_load_search_snapshot_from_storage(storage_path: &Path) -> Option<SearchSnapshot> {
let path = storage_path.join("search_snapshot.bin");
if !path.exists() {
return None;
}
match std::fs::read(&path)
.with_context(|| format!("Failed to read search snapshot: {}", path.display()))
.and_then(|bytes| {
bincode::deserialize::<SearchSnapshot>(&bytes)
.context("Failed to deserialize search snapshot")
}) {
Ok(snapshot) => {
info!(
count = snapshot.indexed_nodes,
path = %path.display(),
"Loaded search snapshot"
);
Some(snapshot)
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Failed to load search snapshot"
);
None
}
}
}
struct Blake3FormatWriter<'a>(&'a mut blake3::Hasher);
impl std::fmt::Write for Blake3FormatWriter<'_> {
fn write_str(&mut self, value: &str) -> std::fmt::Result {
self.0.update(value.as_bytes());
Ok(())
}
}
pub(crate) fn pdg_search_fingerprint(pdg: &ProgramDependenceGraph) -> String {
use std::fmt::Write as _;
let mut hasher = blake3::Hasher::new();
hasher.update(b"leindex-pdg-search-v2");
use rayon::prelude::*;
let node_ids: Vec<_> = pdg.node_indices().collect();
let mut nodes: Vec<[u8; 32]> = node_ids
.par_iter()
.filter_map(|&node_idx| {
pdg.get_node(node_idx).map(|node| {
let mut record = blake3::Hasher::new();
write!(
Blake3FormatWriter(&mut record),
"{}\0{:?}\0{}\0{}\0{}\0{}\0{}\0{}",
node.id,
node.node_type,
node.name,
node.file_path,
node.byte_range.0,
node.byte_range.1,
node.complexity,
node.language
)
.expect("hash writer is infallible");
*record.finalize().as_bytes()
})
})
.collect();
nodes.par_sort_unstable();
for node in nodes {
hasher.update(&node);
}
let edge_ids: Vec<_> = pdg.edge_indices().collect();
let mut edges: Vec<[u8; 32]> = edge_ids
.par_iter()
.filter_map(|&edge_idx| {
let edge = pdg.get_edge(edge_idx)?;
let (from, to) = pdg.edge_endpoints(edge_idx)?;
let from = pdg.get_node(from)?;
let to = pdg.get_node(to)?;
let mut record = blake3::Hasher::new();
write!(
Blake3FormatWriter(&mut record),
"{}\0{}\0{:?}\0{:?}\0{:?}\0{:?}",
from.id,
to.id,
edge.edge_type,
edge.metadata.call_count,
edge.metadata.variable_name,
edge.metadata.confidence.map(f32::to_bits)
)
.expect("hash writer is infallible");
Some(*record.finalize().as_bytes())
})
.collect();
edges.par_sort_unstable();
for edge in edges {
hasher.update(&edge);
}
hasher.finalize().to_hex().to_string()
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn persist_neural_embeddings_to_mmap(
search_engine: &SearchEngine,
project_path: &Path,
identity: Option<&str>,
matryoshka: crate::config::MatryoshkaSetting,
) -> Result<()> {
let embeddings = search_engine.collect_neural_embeddings();
let path = neural_mmap_embeddings_path(project_path);
let storage_path = project_path.join(".leindex");
if embeddings.is_empty() {
remove_neural_generation(&path, project_path, &storage_path)?;
return Ok(());
}
let spans = search_engine.collect_node_span_bytes();
let buckets =
crate::search::mrl::partition_rows_by_slice_dimension(&embeddings, &spans, matryoshka);
let native_dim = canonical_native_dim(&embeddings, project_path, identity);
let staged = stage_neural_tiers(project_path, &path, identity, native_dim, &buckets)?;
commit_neural_generation(
project_path,
&path,
&storage_path,
identity,
matryoshka,
native_dim,
staged,
)
}
fn canonical_native_dim(
embeddings: &[(String, Vec<f32>)],
project_path: &Path,
identity: Option<&str>,
) -> usize {
let widest_row = embeddings
.iter()
.map(|(_, row)| row.len())
.max()
.unwrap_or(0);
let persisted = try_load_neural_mmap_embeddings(project_path)
.filter(|mmap| match (identity, mmap.identity()) {
(Some(incoming), Some(on_disk)) => incoming == on_disk,
_ => false,
})
.map(|mmap| {
if mmap.dimension() as usize >= widest_row {
mmap.dimension() as usize
} else {
widest_row
}
})
.unwrap_or(0);
widest_row.max(persisted)
}
fn remove_neural_generation(path: &Path, project_path: &Path, storage_path: &Path) -> Result<()> {
if path.exists() {
std::fs::remove_file(path)
.map_err(|e| anyhow::anyhow!("Failed to remove stale neural mmap embeddings: {e}"))?;
info!(
path = %path.display(),
"Removed stale neural embeddings mmap file"
);
}
remove_neural_tier_mmaps(project_path, &[])?;
remove_neural_generation_manifest(storage_path)?;
Ok(())
}
fn stage_neural_tiers(
project_path: &Path,
canonical_path: &Path,
identity: Option<&str>,
native_dim: usize,
buckets: &[(usize, Vec<(String, Vec<f32>)>)],
) -> Result<Vec<StagedNeuralTier>> {
let mut staged: Vec<StagedNeuralTier> = Vec::with_capacity(buckets.len());
for (dim, rows) in buckets {
let final_path = if *dim == native_dim {
canonical_path.to_path_buf()
} else {
neural_tier_mmap_embeddings_path(project_path, *dim)
};
let stage_path = neural_staging_path(&final_path);
crate::search::vector::write_mmap_embeddings_with_identity(&stage_path, rows, identity)
.map_err(|e| anyhow::anyhow!("Failed to stage neural mmap embeddings: {e}"))?;
match crate::search::vector::MmapEmbeddingIndex::open(&stage_path) {
Ok(written) if written.len() == rows.len() => {}
Ok(written) => {
return Err(anyhow::anyhow!(
"Staged neural mmap {} reopened with {} rows, expected {}",
stage_path.display(),
written.len(),
rows.len()
));
}
Err(e) => {
return Err(anyhow::anyhow!(
"Failed to reopen staged neural mmap {}: {e}",
stage_path.display()
));
}
}
staged.push(StagedNeuralTier {
dim: *dim,
rows: rows.len(),
final_path,
stage_path,
});
}
if !staged.iter().any(|tier| tier.dim == native_dim) {
let stage_path = neural_staging_path(canonical_path);
crate::search::vector::write_empty_mmap_embeddings_with_identity(
&stage_path,
native_dim as u32,
identity,
)
.map_err(|e| {
anyhow::anyhow!("Failed to stage tier-only canonical neural mmap header: {e}")
})?;
info!(
path = %stage_path.display(),
dim = native_dim,
"Staged tier-only canonical neural mmap header (identity + native dimension, zero rows)"
);
staged.push(StagedNeuralTier {
dim: native_dim,
rows: 0,
final_path: canonical_path.to_path_buf(),
stage_path,
});
}
Ok(staged)
}
fn commit_neural_generation(
project_path: &Path,
canonical_path: &Path,
storage_path: &Path,
identity: Option<&str>,
matryoshka: crate::config::MatryoshkaSetting,
native_dim: usize,
staged: Vec<StagedNeuralTier>,
) -> Result<()> {
let empty_header = staged
.iter()
.any(|tier| tier.dim == native_dim && tier.rows == 0);
for tier in &staged {
publish_staged_tier(tier)?;
info!(
count = tier.rows,
dim = tier.dim,
path = %tier.final_path.display(),
"Published neural embeddings mmap tier"
);
}
let header_only = staged
.iter()
.any(|tier| tier.dim == native_dim && tier.rows == 0);
let mut committed: Vec<(usize, usize)> = staged
.iter()
.filter(|tier| tier.rows > 0)
.map(|tier| (tier.dim, tier.rows))
.collect();
if header_only {
committed.push((native_dim, 0));
}
persist_neural_generation_manifest(storage_path, identity, matryoshka, &committed)?;
let keep: Vec<usize> = staged
.iter()
.filter(|tier| tier.final_path != canonical_path)
.map(|tier| tier.dim)
.collect();
remove_neural_tier_mmaps(project_path, &keep)?;
if empty_header {
info!(
path = %canonical_path.display(),
dim = native_dim,
"Canonical neural mmap carries identity only (all rows are sliced)"
);
}
Ok(())
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
struct StagedNeuralTier {
dim: usize,
rows: usize,
final_path: PathBuf,
stage_path: PathBuf,
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn neural_staging_path(final_path: &Path) -> PathBuf {
let name = final_path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("neural");
final_path.with_file_name(format!(".{name}.staged"))
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn publish_staged_tier(tier: &StagedNeuralTier) -> Result<()> {
if let Some(parent) = tier.final_path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!(
"Failed to create neural mmap directory: {}",
parent.display()
)
})?;
}
crate::search::vector::replace_file_atomically(&tier.stage_path, &tier.final_path)
.with_context(|| {
format!(
"Failed to publish staged neural mmap {} -> {}",
tier.stage_path.display(),
tier.final_path.display()
)
})?;
Ok(())
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn neural_tier_mmap_embeddings_path(project_path: &Path, dim: usize) -> PathBuf {
project_path
.join(".leindex")
.join(format!("neural_embeddings_{dim}.bin"))
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct NeuralGenerationManifest {
schema_version: u32,
identity: Option<String>,
matryoshka: String,
tiers: Vec<(usize, usize)>,
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
const NEURAL_GENERATION_MANIFEST_SCHEMA_VERSION: u32 = 1;
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn neural_generation_manifest_path(storage_path: &Path) -> PathBuf {
storage_path.join("neural_generation.bin")
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn persist_neural_generation_manifest(
storage_path: &Path,
identity: Option<&str>,
matryoshka: crate::config::MatryoshkaSetting,
tiers: &[(usize, usize)],
) -> Result<()> {
let mut tiers = tiers.to_vec();
tiers.sort_unstable();
let manifest = NeuralGenerationManifest {
schema_version: NEURAL_GENERATION_MANIFEST_SCHEMA_VERSION,
identity: identity.map(str::to_owned),
matryoshka: format!("{matryoshka:?}"),
tiers,
};
let path = neural_generation_manifest_path(storage_path);
let payload = bincode::serialize(&manifest).context("Failed to serialize neural manifest")?;
fragment::atomic_write(&path, &payload).with_context(|| {
format!(
"Failed to persist neural generation manifest: {}",
path.display()
)
})?;
info!(
tiers = manifest.tiers.len(),
path = %path.display(),
"Committed neural generation manifest"
);
Ok(())
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn remove_neural_generation_manifest(storage_path: &Path) -> Result<()> {
let path = neural_generation_manifest_path(storage_path);
if path.exists() {
std::fs::remove_file(&path).with_context(|| {
format!(
"Failed to remove stale neural generation manifest: {}",
path.display()
)
})?;
}
Ok(())
}
#[cfg(any(test, feature = "onnx", feature = "remote-embeddings"))]
fn try_load_neural_generation_manifest(storage_path: &Path) -> Option<NeuralGenerationManifest> {
let path = neural_generation_manifest_path(storage_path);
let bytes = std::fs::read(&path).ok()?;
match bincode::deserialize::<NeuralGenerationManifest>(&bytes) {
Ok(manifest) => {
if manifest.schema_version != NEURAL_GENERATION_MANIFEST_SCHEMA_VERSION {
tracing::warn!(
path = %path.display(),
found = manifest.schema_version,
expected = NEURAL_GENERATION_MANIFEST_SCHEMA_VERSION,
"Neural generation manifest schema mismatch; ignoring it and \
falling back to per-file identity gating"
);
return None;
}
Some(manifest)
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Failed to deserialize neural generation manifest; ignoring it"
);
None
}
}
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
fn remove_neural_tier_mmaps(project_path: &Path, keep: &[usize]) -> Result<()> {
for dim in crate::search::mrl::MRL_TIERS {
if keep.contains(&dim) {
continue;
}
let path = neural_tier_mmap_embeddings_path(project_path, dim);
if path.exists() {
std::fs::remove_file(&path)
.map_err(|e| anyhow::anyhow!("Failed to remove stale neural tier mmap: {e}"))?;
info!(
path = %path.display(),
"Removed stale neural tier mmap file"
);
}
}
Ok(())
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn load_neural_tier_mmaps_from_storage(
storage_path: &Path,
expected_identity: Option<&str>,
) -> Vec<crate::search::vector::MmapEmbeddingIndex> {
let manifest = try_load_neural_generation_manifest(storage_path);
let policy_matches = manifest.as_ref().is_none_or(|manifest| {
manifest.matryoshka
== format!(
"{:?}",
crate::config::LeIndexConfig::load_cached()
.indexing
.embeddings
.effective_matryoshka()
)
});
if !policy_matches {
tracing::warn!(
recorded = manifest
.as_ref()
.map(|manifest| manifest.matryoshka.as_str())
.unwrap_or_default(),
"Neural generation was partitioned under a different Matryoshka policy; \
tier disabled until re-indexed"
);
return Vec::new();
}
let canonical_dim = try_load_neural_mmap_embeddings_from_storage(storage_path)
.filter(|index| !index.is_empty())
.map(|index| index.dimension() as usize);
let mut loaded: Vec<crate::search::vector::MmapEmbeddingIndex> = crate::search::mrl::MRL_TIERS
.iter()
.filter_map(|dim| {
let path = storage_path.join(format!("neural_embeddings_{dim}.bin"));
if !path.exists() {
return None;
}
if canonical_dim == Some(*dim) {
tracing::warn!(
path = %path.display(),
dim = *dim,
"Stale neural tier mmap duplicates the canonical generation; \
tier disabled"
);
return None;
}
let committed_rows = manifest.as_ref().and_then(|manifest| {
manifest
.tiers
.iter()
.find(|(tier, _)| tier == dim)
.map(|(_, rows)| *rows)
});
if manifest.is_some() && committed_rows.is_none() {
tracing::warn!(
path = %path.display(),
dim = *dim,
"Neural tier mmap is not part of the committed generation; tier disabled"
);
return None;
}
let expected_for_file = manifest
.as_ref()
.and_then(|manifest| manifest.identity.as_deref())
.or(expected_identity);
match crate::search::vector::MmapEmbeddingIndex::open(&path) {
Ok(index) => {
if let Some(expected_rows) = committed_rows {
if index.len() != expected_rows {
tracing::warn!(
path = %path.display(),
dim = *dim,
found = index.len(),
expected = expected_rows,
"Neural tier mmap row count disagrees with the committed \
generation; tier disabled"
);
return None;
}
}
if let (Some(expected), Some(found)) = (expected_for_file, index.identity()) {
if found != expected {
tracing::warn!(
path = %path.display(),
dim = *dim,
found = %found,
expected = %expected,
"Neural tier mmap is from a different generation \
(provider/model/dimension/template); tier disabled"
);
return None;
}
}
Some(index)
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Failed to load neural tier mmap; tier disabled"
);
None
}
}
})
.collect();
loaded.sort_by_key(|index| index.dimension());
loaded
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn neural_mmap_embeddings_path(project_path: &Path) -> PathBuf {
project_path.join(".leindex").join("neural_embeddings.bin")
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn try_load_neural_mmap_embeddings(
project_path: &Path,
) -> Option<crate::search::vector::MmapEmbeddingIndex> {
try_load_neural_mmap_embeddings_from_storage(&project_path.join(".leindex"))
}
#[cfg(any(feature = "onnx", feature = "remote-embeddings"))]
pub(crate) fn try_load_neural_mmap_embeddings_from_storage(
storage_path: &Path,
) -> Option<crate::search::vector::MmapEmbeddingIndex> {
let path = storage_path.join("neural_embeddings.bin");
if !path.exists() {
return None;
}
match crate::search::vector::MmapEmbeddingIndex::open(&path) {
Ok(index) => {
info!(
nodes = index.len(),
dim = index.dimension(),
path = %path.display(),
"Loaded neural mmap embedding index"
);
Some(index)
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Failed to load neural mmap embedding index"
);
None
}
}
}
pub(crate) fn fragment_mmap_embeddings_path(project_path: &Path) -> PathBuf {
project_path
.join(".leindex")
.join("fragments_embeddings.bin")
}
pub(crate) fn persist_fragment_embeddings_to_mmap(
project_path: &Path,
embeddings: &[(String, Vec<f32>)],
) -> Result<()> {
let path = fragment_mmap_embeddings_path(project_path);
if embeddings.is_empty() {
if path.exists() {
std::fs::remove_file(&path).map_err(|e| {
anyhow::anyhow!("Failed to remove stale fragment mmap embeddings: {e}")
})?;
info!(
path = %path.display(),
"Removed stale fragment embeddings mmap file"
);
}
return Ok(());
}
crate::search::vector::write_mmap_embeddings(&path, embeddings)
.map_err(|e| anyhow::anyhow!("Failed to write fragment mmap embeddings: {e}"))?;
info!(
count = embeddings.len(),
path = %path.display(),
"Persisted fragment embeddings to mmap file"
);
Ok(())
}
pub(crate) fn try_load_fragment_mmap_embeddings_from_storage(
storage_path: &Path,
) -> Option<crate::search::vector::MmapEmbeddingIndex> {
let path = storage_path.join("fragments_embeddings.bin");
if !path.exists() {
return None;
}
match crate::search::vector::MmapEmbeddingIndex::open(&path) {
Ok(index) => {
info!(
nodes = index.len(),
dim = index.dimension(),
path = %path.display(),
"Loaded fragment mmap embedding index"
);
Some(index)
}
Err(e) => {
tracing::warn!(
path = %path.display(),
error = %e,
"Failed to load fragment mmap embedding index"
);
None
}
}
}
pub(crate) fn fragment_layer_is_valid(
snapshot_root: Option<&str>,
fragment_mmap: Option<&crate::search::vector::MmapEmbeddingIndex>,
storage_path: &Path,
) -> bool {
let (Some(root), Some(mmap)) = (snapshot_root, fragment_mmap) else {
return false;
};
match fragment::sync::load_fragment_root(storage_path) {
Ok(Some(state)) => {
state.root_hash == root
&& state.fragment_rows == mmap.len() as u64
&& fragment::sync::fragment_layer_generation_is_consistent(storage_path, &state)
}
Ok(None) => false,
Err(e) => {
tracing::warn!(
error = %e,
"Failed to load fragment root for validation; fragment layer disabled"
);
false
}
}
}
#[cfg(all(test, any(feature = "onnx", feature = "remote-embeddings")))]
mod tests {
use super::*;
fn tier_store(identity: Option<&str>) -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
let dim = crate::search::mrl::MRL_TIERS[1]; let rows = vec![("node-1".to_string(), vec![0.25_f32; dim])];
crate::search::vector::write_mmap_embeddings_with_identity(
&dir.path().join(format!("neural_embeddings_{dim}.bin")),
&rows,
identity,
)
.unwrap();
dir
}
#[test]
fn test_tier_mmap_from_a_foreign_generation_is_not_loaded() {
let dir = tier_store(Some("remote|openai|old-model||768"));
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|new-model||768"));
assert!(
loaded.is_empty(),
"a sidecar from another generation must not contribute rows"
);
}
#[test]
fn test_tier_mmap_of_the_current_generation_is_loaded() {
let dir = tier_store(Some("remote|openai|same-model||768"));
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same-model||768"));
assert_eq!(loaded.len(), 1, "the current generation's sidecar loads");
assert_eq!(loaded[0].len(), 1, "and its rows are reachable");
}
#[test]
fn test_tier_mmap_is_loaded_when_no_generation_is_known() {
let dir = tier_store(Some("remote|openai|whatever||768"));
let loaded = load_neural_tier_mmaps_from_storage(dir.path(), None);
assert_eq!(
loaded.len(),
1,
"an unknown generation must not disable tiers"
);
}
#[test]
fn test_tier_mmap_without_an_identity_trailer_is_loaded() {
let dir = tier_store(None);
let loaded = load_neural_tier_mmaps_from_storage(dir.path(), Some("any|identity||768"));
assert_eq!(
loaded.len(),
1,
"a sidecar with no trailer is not provably foreign"
);
}
fn commit_manifest(dir: &tempfile::TempDir, identity: Option<&str>, tiers: &[(usize, usize)]) {
persist_neural_generation_manifest(
dir.path(),
identity,
crate::config::LeIndexConfig::load_cached()
.indexing
.embeddings
.effective_matryoshka(),
tiers,
)
.unwrap();
}
#[test]
fn test_tier_outside_the_committed_generation_is_not_loaded() {
let dir = tier_store(Some("remote|openai|same||768"));
let dim = crate::search::mrl::MRL_TIERS[1];
commit_manifest(&dir, Some("remote|openai|same||768"), &[(128, 1)]);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert!(
loaded.is_empty(),
"a sidecar the committed generation does not name must not contribute rows ({dim})"
);
}
#[test]
fn test_tier_row_count_disagreeing_with_the_committed_generation_is_not_loaded() {
let dir = tier_store(Some("remote|openai|same||768"));
let dim = crate::search::mrl::MRL_TIERS[1];
commit_manifest(&dir, Some("remote|openai|same||768"), &[(dim, 99)]);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert!(
loaded.is_empty(),
"a sidecar whose weight disagrees with the commit marker must not load"
);
}
#[test]
fn test_tier_named_by_the_committed_generation_is_loaded() {
let dir = tier_store(Some("remote|openai|same||768"));
let dim = crate::search::mrl::MRL_TIERS[1];
commit_manifest(&dir, Some("remote|openai|same||768"), &[(dim, 1)]);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert_eq!(loaded.len(), 1, "the committed generation's tier loads");
assert_eq!(loaded[0].len(), 1, "and its rows are reachable");
}
#[test]
fn test_manifest_identity_overrides_the_canonical_one() {
let dir = tier_store(Some("remote|openai|manifest-model||768"));
let dim = crate::search::mrl::MRL_TIERS[1];
commit_manifest(&dir, Some("remote|openai|manifest-model||768"), &[(dim, 1)]);
let loaded = load_neural_tier_mmaps_from_storage(
dir.path(),
Some("remote|openai|canonical-disagrees||768"),
);
assert_eq!(
loaded.len(),
1,
"the committed manifest, not the canonical trailer, identifies the generation"
);
}
#[test]
fn test_absent_manifest_falls_back_to_per_file_identity_gating() {
let dir = tier_store(Some("remote|openai|same||768"));
assert!(
try_load_neural_generation_manifest(dir.path()).is_none(),
"precondition: no manifest was written"
);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert_eq!(loaded.len(), 1, "legacy artifacts stay readable");
}
#[test]
fn test_publish_leaves_no_staging_file_and_commits_the_manifest() {
let dir = tempfile::tempdir().unwrap();
let storage = dir.path().join(".leindex");
std::fs::create_dir_all(&storage).unwrap();
let tier_path = storage.join(format!(
"neural_embeddings_{}.bin",
crate::search::mrl::MRL_TIERS[1]
));
let stage_path = neural_staging_path(&tier_path);
let rows = vec![(
"node-1".to_string(),
vec![0.5_f32; crate::search::mrl::MRL_TIERS[1]],
)];
crate::search::vector::write_mmap_embeddings_with_identity(&stage_path, &rows, Some("id"))
.unwrap();
let tier = StagedNeuralTier {
dim: crate::search::mrl::MRL_TIERS[1],
rows: rows.len(),
final_path: tier_path.clone(),
stage_path: stage_path.clone(),
};
publish_staged_tier(&tier).unwrap();
assert!(tier_path.is_file(), "the tier landed at its canonical path");
assert!(
!stage_path.exists(),
"rename must not leave the staging file behind"
);
persist_neural_generation_manifest(
&storage,
Some("id"),
crate::config::LeIndexConfig::load_cached()
.indexing
.embeddings
.effective_matryoshka(),
&[(tier.dim, tier.rows)],
)
.unwrap();
let manifest = try_load_neural_generation_manifest(&storage).expect("manifest committed");
assert_eq!(manifest.tiers, vec![(tier.dim, tier.rows)]);
let loaded = load_neural_tier_mmaps_from_storage(&storage, Some("id"));
assert_eq!(loaded.len(), 1, "a just-committed generation loads");
}
#[test]
fn test_failed_publish_keeps_the_previous_generation_readable() {
let dir = tempfile::tempdir().unwrap();
let storage = dir.path().join(".leindex");
std::fs::create_dir_all(&storage).unwrap();
let dim = crate::search::mrl::MRL_TIERS[1];
let tier_path = storage.join(format!("neural_embeddings_{dim}.bin"));
let previous = vec![("node-1".to_string(), vec![0.25_f32; dim])];
crate::search::vector::write_mmap_embeddings_with_identity(
&tier_path,
&previous,
Some("id"),
)
.unwrap();
persist_neural_generation_manifest(
&storage,
Some("id"),
crate::config::LeIndexConfig::load_cached()
.indexing
.embeddings
.effective_matryoshka(),
&[(dim, previous.len())],
)
.unwrap();
let newer = vec![
("node-1".to_string(), vec![0.75_f32; dim]),
("node-2".to_string(), vec![0.75_f32; dim]),
];
crate::search::vector::write_mmap_embeddings_with_identity(
&neural_staging_path(&tier_path),
&newer,
Some("id"),
)
.unwrap();
let loaded = load_neural_tier_mmaps_from_storage(&storage, Some("id"));
assert_eq!(loaded.len(), 1, "the previous generation still loads");
assert_eq!(
loaded[0].len(),
previous.len(),
"and it is the previous generation's rows, not the uncommitted ones"
);
}
#[test]
fn test_generation_partitioned_under_another_policy_is_not_loaded() {
let dir = tier_store(Some("remote|openai|same||768"));
let dim = crate::search::mrl::MRL_TIERS[1];
persist_neural_generation_manifest(
dir.path(),
Some("remote|openai|same||768"),
crate::config::MatryoshkaSetting::Dynamic,
&[(dim, 1)],
)
.unwrap();
let effective = crate::config::LeIndexConfig::load_cached()
.indexing
.embeddings
.effective_matryoshka();
if effective == crate::config::MatryoshkaSetting::Dynamic {
return;
}
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert!(
loaded.is_empty(),
"a generation committed under a different policy must not serve"
);
}
#[test]
fn test_canonical_file_is_never_returned_as_a_tier() {
let dir = tier_store(Some("remote|openai|same||768"));
let canonical_rows = vec![("node-1".to_string(), vec![0.5_f32; 768])];
crate::search::vector::write_mmap_embeddings_with_identity(
&dir.path().join("neural_embeddings.bin"),
&canonical_rows,
Some("remote|openai|same||768"),
)
.unwrap();
let dim = crate::search::mrl::MRL_TIERS[1];
commit_manifest(&dir, Some("remote|openai|same||768"), &[(dim, 1)]);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert_eq!(loaded.len(), 1, "one sidecar, one entry");
assert_eq!(
loaded[0].dimension(),
dim as u32,
"the canonical file is never returned as a tier"
);
}
#[test]
fn test_stale_sidecar_duplicating_the_canonical_dimension_is_not_returned_as_a_tier() {
let dir = tier_store(None);
let native = *crate::search::mrl::MRL_TIERS.last().unwrap(); let canonical_rows = vec![("node-1".to_string(), vec![0.5_f32; native])];
crate::search::vector::write_mmap_embeddings_with_identity(
&dir.path().join("neural_embeddings.bin"),
&canonical_rows,
Some("remote|openai|same||768"),
)
.unwrap();
crate::search::vector::write_mmap_embeddings_with_identity(
&dir.path().join(format!("neural_embeddings_{native}.bin")),
&canonical_rows,
Some("remote|openai|same||768"),
)
.unwrap();
commit_manifest(
&dir,
Some("remote|openai|same||768"),
&[(native, canonical_rows.len())],
);
let loaded =
load_neural_tier_mmaps_from_storage(dir.path(), Some("remote|openai|same||768"));
assert!(
loaded.is_empty(),
"a sidecar at the canonical dimension duplicates the generation and must not load"
);
}
#[test]
fn test_staging_path_is_a_sibling_of_the_tier_file() {
let final_path = Path::new("/tmp/proj/.leindex/neural_embeddings_256.bin");
let staged = neural_staging_path(final_path);
assert_eq!(staged.parent(), final_path.parent());
assert_eq!(
staged.file_name().and_then(|name| name.to_str()),
Some(".neural_embeddings_256.bin.staged")
);
}
#[test]
fn test_canonical_native_dim_is_the_provider_width() {
let rows = |dim: usize, count: usize| -> Vec<(String, Vec<f32>)> {
(0..count)
.map(|i| (format!("node-{i}"), vec![0.5_f32; dim]))
.collect()
};
let empty = tempfile::tempdir().unwrap();
assert_eq!(
canonical_native_dim(&rows(1024, 2), empty.path(), None),
1024,
"a width the ladder never produces still owns the canonical file"
);
assert_eq!(
canonical_native_dim(&rows(256, 3), empty.path(), None),
256,
"a sub-768 provider must not be reported as 768"
);
assert_eq!(canonical_native_dim(&rows(768, 1), empty.path(), None), 768);
assert_eq!(
canonical_native_dim(&[], empty.path(), None),
0,
"no rows and nothing persisted means no width to claim"
);
}
#[test]
fn test_canonical_native_dim_keeps_the_persisted_width_over_restored_slices() {
let dir = tempfile::tempdir().unwrap();
let storage = dir.path().join(".leindex");
std::fs::create_dir_all(&storage).unwrap();
crate::search::vector::write_empty_mmap_embeddings_with_identity(
&storage.join("neural_embeddings.bin"),
768,
Some("remote|openai|same||768"),
)
.unwrap();
let sliced: Vec<(String, Vec<f32>)> = (0..3)
.map(|i| (format!("node-{i}"), vec![0.5_f32; 512]))
.collect();
assert_eq!(
canonical_native_dim(&sliced, dir.path(), Some("remote|openai|same||768")),
768,
"the persisted provider width outranks the restored slice width"
);
}
#[test]
fn test_canonical_native_dim_follows_a_narrower_provider_change() {
let dir = tempfile::tempdir().unwrap();
let storage = dir.path().join(".leindex");
std::fs::create_dir_all(&storage).unwrap();
crate::search::vector::write_empty_mmap_embeddings_with_identity(
&storage.join("neural_embeddings.bin"),
768,
Some("remote|openai|old-endpoint||768"),
)
.unwrap();
let fresh: Vec<(String, Vec<f32>)> = (0..3)
.map(|i| (format!("node-{i}"), vec![0.5_f32; 384]))
.collect();
assert_eq!(
canonical_native_dim(&fresh, dir.path(), Some("remote|openai|new-endpoint||384")),
384,
"a different generation's width must not outrank fresh provider rows"
);
assert_eq!(
canonical_native_dim(&fresh, dir.path(), None),
384,
"an unknown incoming identity cannot prove a slice restore"
);
}
}