AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(engine): content-address the neural embedder so a corpus can be re-indexed (#487) (#910)
xerj-org5b9ee64e0308
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ac74e1f5a..cc3a6cfb2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -234,6 +234,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0separate work: it has to prove the #825 union/sum contract with tombstonespresent, and is not attempted here.+- **`--embed-mode neural`: re-indexing an unchanged corpus no longer fails,+ and the identity can now tell one model from another**+ ([#487](https://github.com/xerj-org/xerj/issues/487),+ [#367](https://github.com/xerj-org/xerj/issues/367)). The neural arm of the+ embedding execution identity hashed the configured model *name*+ (`neural-unpinned.v1;configured-model=…`) and reported `resumable: false`+ unconditionally. Two consequences, both reproduced on the released rc.71+ binary before the change:++ - every neural node on earth emitted the same `identity_sha256`+ (`6e51e5ce3e46…`), so the check that exists to catch a swapped model could+ not see one; and+ - the five `resumable` gates in `xerj-autoindex` all fired. `xerj autoindex`+ against a neural node was **one-shot**: the graph path completed+ generation 1 (`exit=0`) and then refused the *identical* command over an+ *unchanged* corpus (`exit=1`, "server embedding backend cannot safely+ resume semantic indexing"), and the `--no-graph` path refused even the+ first run at the generation cutover. That is the whole reference-coding+ loop — index a peer repo, pick up its commits later — so it mattered more+ than a bookkeeping error looks.++ The identity is now the streamed sha256 of `model.safetensors`,+ `tokenizer.json` and `config.json` plus the model's own `hidden_size`,+ pooling and truncation limit, resolved by exactly the path+ `NeuralEmbedder::load` takes (`xerj-ai/src/neural.rs`) — the same thing the+ ONNX arm already did. `resumable` is then honestly `true`, `dimensions` is+ reported instead of omitted, and a genuinely swapped model is refused where+ before nothing was. Assets that cannot be resolved still fail closed, but the+ reason names the file rather than blaming a configuration change that never+ happened.++ Measured on this box, 20-file corpus, `--embed-mode neural` (MiniLM from the+ local HuggingFace cache):++ | run | rc.71 | this change |+ |---|---|---|+ | graph path, run 1 | `exit=0` | `exit=0` |+ | graph path, run 2 — identical command, unchanged corpus | `exit=1` | `exit=0` |+ | graph path, run 3 — one file edited | not reachable | `exit=0` |+ | `--no-graph`, run 1 | `exit=1` | `exit=0` |+ | `--no-graph`, run 2 — unchanged corpus | `exit=1` | `exit=0` |++ The pre-fix identity was already *deterministic* — the same digest on every+ call and every host — so this was never a hashing-stability bug; the flag was+ simply hardcoded. Batch shape (`MAX_BATCH_ROWS`, `PADDED_TOKEN_BUDGET`),+ thread count, device and the resolved file paths are deliberately **not** in+ the digest: they change how rows are grouped, not what any row computes, so+ folding them in would have reintroduced the false "identity changed" one+ layer down.++ On-disk migration: `embedding_execution.json` moves to version 3, so the+ first reopen of a populated neural index after upgrading is grandfathered and+ re-baselined instead of refused — the same handling #533 gave the proxy+ endpoint change. `proxy` is unchanged and still reports `resumable: false`:+ a remote provider attests nothing about its model's bytes, and probing it+ with fixed inputs would hash floats that no provider guarantees to be+ reproducible — which is the bug in this issue, one layer down.+- **A frontmatter block's body is judged as YAML by whether it parses, not onlyby how its lines look**([#587](https://github.com/xerj-org/xerj/issues/587)). The `---` lookaheaddiff --git a/engine/crates/xerj-ai/Cargo.toml b/engine/crates/xerj-ai/Cargo.tomlindex 541d0ae08..40304ad65 100644--- a/engine/crates/xerj-ai/Cargo.toml+++ b/engine/crates/xerj-ai/Cargo.toml@@ -38,7 +38,7 @@ sha2 = { version = "0.10", optional = true }[features]default = []# Bundles the neural BERT embedder. Adds ~candle + tokenizers to the build.-neural = ["dep:candle-core", "dep:candle-nn", "dep:candle-transformers", "dep:tokenizers", "dep:hf-hub"]+neural = ["dep:candle-core", "dep:candle-nn", "dep:candle-transformers", "dep:tokenizers", "dep:hf-hub", "dep:sha2"]# Experimental local ONNX backend; xerj-server exposes it only when the# feature is propagated and explicitly selected at runtime.onnx-experimental = ["dep:ort", "dep:tokenizers", "dep:sha2"]diff --git a/engine/crates/xerj-ai/src/neural.rs b/engine/crates/xerj-ai/src/neural.rsindex 21c6ea9ba..c2dd5a31d 100644--- a/engine/crates/xerj-ai/src/neural.rs+++ b/engine/crates/xerj-ai/src/neural.rs@@ -21,6 +21,7 @@ use anyhow::{anyhow, Context, Result};use candle_core::{DType, Device, Tensor};use candle_nn::VarBuilder;use candle_transformers::models::bert::{BertModel, Config, DTYPE};+use sha2::{Digest, Sha256};use std::path::{Path, PathBuf};use tokenizers::{Encoding, Tokenizer, TruncationParams};@@ -31,7 +32,11 @@ pub const DEFAULT_MODEL_ID: &str = "sentence-transformers/all-MiniLM-L6-v2";/// Cap on tokens per passage. MiniLM's positional table is 512; passages are/// already chunked upstream, so this is a safety clamp, not the usual path.-const MAX_TOKENS: usize = 512;+///+/// Public because it is part of this backend's *output* contract: truncating+/// at a different length gives a different vector for a long passage, so it+/// travels in the execution identity ([`asset_identity`]'s callers).+pub const MAX_TOKENS: usize = 512;/// Rows in one forward pass. Measured on CPU with MiniLM/// (`examples/neural_throughput.rs`): throughput climbs steeply to 64 rows and@@ -295,16 +300,221 @@ impl NeuralEmbedder {}}+/// How [`NeuralEmbedder::embed_blocking`] turns per-token hidden states into+/// one vector. Part of the identity: the same weights pooled differently are a+/// different embedder.+pub const POOLING: &str = "attention-mask-mean+l2-normalize";++/// Content address of the three files a [`NeuralEmbedder`] is built from.+///+/// A *configured model id* cannot identify an embedder: `all-MiniLM-L6-v2`+/// names a mutable hub pointer, and [`NeuralConfig::local_dir`] names a+/// directory whose contents can be swapped underneath a running server. The+/// bytes can, which is how Lucene decides whether a replicated file may be+/// reused — `ReplicaNode.fileIsIdentical` compares length + header id ++/// checksum rather than trusting the name+/// (`lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java:855`),+/// on top of `CodecUtil.checkIndexHeaderID` / `retrieveChecksum`+/// (`lucene/core/src/java/org/apache/lucene/codecs/CodecUtil.java:364`, `:526`).+/// APPROACH ONLY — nothing is copied; the digest below is our own.+///+/// # What is deliberately NOT in here+///+/// Only inputs that can move a vector belong in an execution identity; an+/// identity that moves without the vectors moving is exactly the false+/// "identity changed" this replaces (#487). So these are excluded on purpose:+///+/// * **the model id and the resolved file paths** — two hosts holding the+/// same bytes under different names or directories must be able to resume+/// each other's generation, and a path would also leak into the wire+/// identity, which is documented as privacy-safe;+/// * **`MAX_BATCH_ROWS` / `PADDED_TOKEN_BUDGET`** ([`crate::microbatch`]) —+/// they decide how rows are grouped into forward passes, not what any row+/// computes. Padded positions carry attention-mask 0 and are dropped by+/// the masked mean, so regrouping the same passages returns the same+/// vectors. #366 retuned this batching with no vector change, and an+/// identity that folded it in would have failed every resume across that+/// release for nothing;+/// * **thread count, device, host CPU features** — same reason, and they are+/// not stable across the machines that must agree on one corpus.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AssetIdentity {+ /// sha256 of `model.safetensors` — the weights.+ pub model_sha256: String,+ /// sha256 of `tokenizer.json` — the vocabulary and pre-tokenizer.+ pub tokenizer_sha256: String,+ /// sha256 of `config.json`. Hashed whole rather than field-by-field: it+ /// parameterises the architecture candle instantiates, and enumerating the+ /// fields that matter would silently miss any new one. The cost is that a+ /// whitespace-only edit to a hand-managed `local_model_dir` copy moves the+ /// identity even though the vectors do not — over-strict (fail-closed) on+ /// a file that is byte-stable when it comes from the hub cache.+ pub config_sha256: String,+ /// `hidden_size` from the resolved `config.json` — the width of every+ /// vector this embedder produces, and the same value+ /// [`NeuralEmbedder::dims`] reports, read here without loading the model.+ pub dimensions: usize,+}++/// Why a neural model could not be content-addressed, split in two on purpose.+///+/// `EmbeddingExecutionIdentity` is documented as never carrying model paths or+/// model names across the API boundary, and a resolution failure is precisely+/// where a filesystem path would otherwise escape into+/// `non_resumable_reason` — the failure text is the one part of the identity+/// that is not a digest. So the caller reports [`Self::asset`] on the wire and+/// logs [`Self::detail`] locally.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct AssetIdentityError {+ /// What could not be read, as a bare asset name. Contains no path, no+ /// directory and no model id, so it is safe to return to a remote client.+ pub asset: &'static str,+ /// The same failure with everything useful for an operator in it —+ /// resolved paths, the configured model id, the underlying io error. For+ /// this server's own log, never for a response body.+ pub detail: String,+}++impl AssetIdentityError {+ fn new(asset: &'static str, detail: impl std::fmt::Display) -> Self {+ Self {+ asset,+ detail: detail.to_string(),+ }+ }+}++impl std::fmt::Display for AssetIdentityError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(&self.detail)+ }+}++impl std::error::Error for AssetIdentityError {}++/// Content-address the assets `cfg` resolves to.+///+/// Resolution takes exactly the path [`NeuralEmbedder::load`] takes (local+/// directory when set, hub cache otherwise), so a server that is able to embed+/// is always able to state what it embeds with, and one that cannot resolve its+/// assets reports *which asset* failed instead of a fabricated identity.+///+/// `ApiRepo::get` consults the local cache before the network (hf-hub 0.4+/// `api/sync.rs:709`), so a warm cache resolves offline; a cold one downloads+/// the same ~90 MB the first embed would have downloaded anyway.+///+/// Memoised per [`NeuralConfig`] for the process lifetime — the digest reads+/// ~90 MB and the caller is a request path (measured on this box: 71–77 ms on+/// the first call for MiniLM, 0 ms after). That memo is also what makes the+/// identity *stable within a process*: assets swapped under a running server+/// are not noticed until restart, which is the same bargain the ONNX arm makes+/// with its `runtime_onnx_assets` cell.+pub fn asset_identity(+ cfg: &NeuralConfig,+) -> std::result::Result<AssetIdentity, AssetIdentityError> {+ use std::collections::HashMap;+ use std::sync::{Mutex, OnceLock};++ type Memo = HashMap<NeuralConfig, std::result::Result<AssetIdentity, AssetIdentityError>>;+ static IDENTITIES: OnceLock<Mutex<Memo>> = OnceLock::new();++ let identities = IDENTITIES.get_or_init(|| Mutex::new(HashMap::new()));+ if let Some(cached) = identities+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .get(cfg)+ {+ return cached.clone();+ }+ // Computed outside the lock: hashing is seconds of I/O on a cold cache and+ // must not serialise every other configuration behind it. Two threads+ // racing the same config compute the same answer, so the double insert is+ // harmless.+ let computed = compute_asset_identity(cfg);+ identities+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner())+ .insert(cfg.clone(), computed.clone());+ computed+}++fn compute_asset_identity(+ cfg: &NeuralConfig,+) -> std::result::Result<AssetIdentity, AssetIdentityError> {+ let (config_path, tokenizer_path, weights_path) = match &cfg.local_dir {+ Some(dir) => resolve_local_assets(dir)?,+ None => resolve_from_hub(&cfg.model_id, cfg.cache_dir.as_deref())+ // The hub error names the model id and the cache path; neither may+ // reach a client, so only the generic label travels.+ .map_err(|e| AssetIdentityError::new("the model download", format!("{e:#}")))?,+ };+ let config_json = std::fs::read(&config_path).map_err(|e| {+ AssetIdentityError::new(+ "config.json",+ format!("read model config {}: {e}", config_path.display()),+ )+ })?;+ let config: Config = serde_json::from_slice(&config_json).map_err(|e| {+ AssetIdentityError::new(+ "config.json",+ format!("parse model config {}: {e}", config_path.display()),+ )+ })?;+ Ok(AssetIdentity {+ model_sha256: file_sha256(&weights_path, "model.safetensors")?,+ tokenizer_sha256: file_sha256(&tokenizer_path, "tokenizer.json")?,+ config_sha256: format!("{:x}", Sha256::digest(&config_json)),+ dimensions: config.hidden_size,+ })+}++/// Streamed sha256 — the weights are ~90 MB and must not be held in memory+/// just to be digested.+fn file_sha256(+ path: &Path,+ asset: &'static str,+) -> std::result::Result<String, AssetIdentityError> {+ use std::io::Read;++ let fail = |e: std::io::Error| {+ AssetIdentityError::new(+ asset,+ format!("read embedding asset {}: {e}", path.display()),+ )+ };+ let mut file = std::fs::File::open(path).map_err(fail)?;+ let mut hasher = Sha256::new();+ let mut buf = vec![0u8; 1 << 20];+ loop {+ let read = file.read(&mut buf).map_err(fail)?;+ if read == 0 {+ break;+ }+ hasher.update(&buf[..read]);+ }+ Ok(format!("{:x}", hasher.finalize()))+}+/// Resolve the three model files from a local directory (air-gapped).fn resolve_local(dir: &Path) -> Result<(PathBuf, PathBuf, PathBuf)> {+ // `load` wants the operator-facing text, paths and all; only the identity+ // endpoint has to keep the path off the wire.+ resolve_local_assets(dir).map_err(|e| anyhow!("{}", e.detail))+}++/// [`resolve_local`], keeping the failing asset separable from the path it was+/// looked for at — see [`AssetIdentityError`].+fn resolve_local_assets(+ dir: &Path,+) -> std::result::Result<(PathBuf, PathBuf, PathBuf), AssetIdentityError> {let config = dir.join("config.json");let tokenizer = dir.join("tokenizer.json");let weights = find_local_weights(dir)?;- for (label, p) in [("config.json", &config), ("tokenizer.json", &tokenizer)] {+ for (asset, p) in [("config.json", &config), ("tokenizer.json", &tokenizer)] {if !p.exists() {- return Err(anyhow!(- "local model dir {} is missing {label}",- dir.display()+ return Err(AssetIdentityError::new(+ asset,+ format!("local model dir {} is missing {asset}", dir.display()),));}}@@ -312,15 +522,18 @@ fn resolve_local(dir: &Path) -> Result<(PathBuf, PathBuf, PathBuf)> {}/// Prefer `model.safetensors`; candle cannot read PyTorch `.bin` weights.-fn find_local_weights(dir: &Path) -> Result<PathBuf> {+fn find_local_weights(dir: &Path) -> std::result::Result<PathBuf, AssetIdentityError> {let st = dir.join("model.safetensors");if st.exists() {return Ok(st);}- Err(anyhow!(- "local model dir {} has no model.safetensors (candle requires safetensors, \- not pytorch_model.bin)",- dir.display()+ Err(AssetIdentityError::new(+ "model.safetensors",+ format!(+ "local model dir {} has no model.safetensors (candle requires safetensors, \+ not pytorch_model.bin)",+ dir.display()+ ),))}diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rsindex 8b87b459c..070de6bbf 100644--- a/engine/crates/xerj-autoindex/src/esclient.rs+++ b/engine/crates/xerj-autoindex/src/esclient.rs@@ -319,7 +319,9 @@ pub struct EmbeddingExecutionIdentity {pub backend: String,pub identity_sha256: String,/// Absent for backends whose vector width the server does not pin- /// (`neural`, `proxy`). An absent width must not be read as 384.+ /// (`proxy`, and a `neural` node that could not resolve its model assets;+ /// a resolved `neural` node reports its `config.json` `hidden_size` since+ /// #487). An absent width must not be read as 384.#[serde(default, skip_serializing_if = "Option::is_none")]pub dimensions: Option<usize>,pub semantic_contract: String,diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rsindex 83aeac88b..21b043d9f 100644--- a/engine/crates/xerj-autoindex/src/sync.rs+++ b/engine/crates/xerj-autoindex/src/sync.rs@@ -121,9 +121,10 @@ pub struct ExecutionIdentity {pub embedding_identity_sha256: String,pub embedding_backend: String,/// Vector width, exactly as the server reported it. `None` is the honest- /// record for a backend whose width the server does not pin (`neural`,- /// `proxy` — see `esclient::EmbeddingExecutionIdentity::dimensions`) and- /// for the synthetic `disabled` identity a no-semantic plan pins. It must+ /// record for a backend whose width the server does not pin (`proxy`, and+ /// a `neural` node whose assets it could not resolve — see+ /// `esclient::EmbeddingExecutionIdentity::dimensions`) and for the+ /// synthetic `disabled` identity a no-semantic plan pins. It must/// never be coerced to a number: a generation that recorded "unknown" and/// one that recorded 384 are different execution spaces.#[serde(default)]diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 4999e78c9..15a4cf11f 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -28,12 +28,14 @@ pub struct EmbeddingExecutionIdentity {pub backend: String,pub identity_sha256: String,/// Vector width, but only for the backends where the server actually- /// pins it: `lexical` always emits [`xerj_ai::local::DEFAULT_DIMS`], and- /// `onnx-experimental` is constrained to 384 by `validate_onnx_dimensions`.- /// `neural` takes its width from the loaded model's `hidden_size` and- /// `proxy` from whatever the remote returns, so neither is known here and- /// the field is omitted rather than guessed — a reader must not treat an- /// absent width as 384.+ /// pins it: `lexical` always emits [`xerj_ai::local::DEFAULT_DIMS`],+ /// `onnx-experimental` is constrained to 384 by `validate_onnx_dimensions`,+ /// and `neural` reads `hidden_size` out of the model's own `config.json`+ /// while content-addressing it (#487) — the same number+ /// `NeuralEmbedder::dims` reports, so it is known without loading the+ /// model. It stays `None` for a `neural` node whose assets cannot be+ /// resolved at all, and for `proxy`, whose width is whatever the remote+ /// returns. A reader must not treat an absent width as 384.#[serde(default, skip_serializing_if = "Option::is_none")]pub dimensions: Option<usize>,pub semantic_contract: String,diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex 805f3603e..422bbb5d1 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -31875,7 +31875,15 @@ const EMBEDDING_EXECUTION_FILE: &str = "embedding_execution.json";/// algorithm — `validate_embedding_execution` treats a version delta as/// "unknown" (grandfather + re-record), never a mismatch, so upgrading does not/// brick a populated proxy index; a later change under v2 is still detected.-const PERSISTED_EMBEDDING_EXECUTION_VERSION: u32 = 2;+///+/// Bumped to 3 by #487 for the same reason on the other backend: the neural+/// identity_sha256 is now the digest of the model assets rather than of the+/// configured model NAME, so every v2 record written by a neural node holds a+/// hash from the superseded algorithm. Without the bump, the first restart+/// after upgrading would read `persisted.identity_sha256 != current` over a+/// populated index and refuse to open it — bricking exactly the indices this+/// change exists to make re-indexable.+const PERSISTED_EMBEDDING_EXECUTION_VERSION: u32 = 3;#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]struct PersistedEmbeddingExecution {@@ -31989,6 +31997,110 @@ fn configured_onnx_identity(}}+/// The `NeuralConfig` this server's embedding configuration resolves to.+///+/// Deliberately shared with `make_neural_embedder`: an identity describing a+/// different model than the one that actually loads would be worse than no+/// identity at all.+#[cfg(feature = "neural")]+fn configured_neural_config(+ cfg: &xerj_common::config::EmbeddingConfig,+) -> xerj_ai::neural::NeuralConfig {+ let model_id = if cfg.neural_model.trim().is_empty() {+ xerj_ai::neural::DEFAULT_MODEL_ID.to_string()+ } else {+ cfg.neural_model.clone()+ };+ xerj_ai::neural::NeuralConfig {+ model_id,+ cache_dir: (!cfg.model_cache_dir.is_empty()).then(|| cfg.model_cache_dir.clone().into()),+ local_dir: (!cfg.local_model_dir.is_empty()).then(|| cfg.local_model_dir.clone().into()),+ }+}++/// Execution identity for the built-in Candle backend.+///+/// #487/#367: this arm used to hash the configured model NAME and report+/// `resumable: false` unconditionally. Two consequences, both measured on+/// rc.71 before this change:+///+/// * a brand-new node and a long-running one emit the *identical*+/// `identity_sha256` (`6e51e5ce3e46…` on any host), so the identity could+/// not detect a real model swap — which is why it was correct not to trust+/// it; and+/// * every one of the five `resumable` gates in `xerj-autoindex` fired on a+/// neural node, so `xerj autoindex` was one-shot: the graph path completed+/// generation 1 and then refused the identical re-run over an *unchanged*+/// corpus, and the `--no-graph` path refused even the first run.+///+/// Lucene does not refuse to reuse an artifact it cannot name; it names it from+/// its own bytes and fails only on a proven mismatch —+/// `ReplicaNode.fileIsIdentical`+/// (`lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java:855`)+/// compares length + header id + checksum precisely to catch a reused *name*+/// whose content changed. APPROACH ONLY; the digest here is our own, and the+/// ONNX arm 25 lines above already did the same thing. Candle's assets were+/// already resolved to concrete paths in `xerj-ai/src/neural.rs`; nothing was+/// missing but the digest.+///+/// Still fails closed — assets that cannot be hashed stay non-resumable — but+/// the reason then names the file instead of blaming a configuration change+/// that never happened.+#[cfg(feature = "neural")]+fn configured_neural_identity(+ cfg: &xerj_common::config::EmbeddingConfig,+) -> (String, bool, Option<String>, Option<usize>) {+ let neural = configured_neural_config(cfg);+ match xerj_ai::neural::asset_identity(&neural) {+ Ok(identity) => (+ format!(+ "neural.v1;model={};tokenizer={};config={};dimensions={};pooling={};max_tokens={}",+ identity.model_sha256,+ identity.tokenizer_sha256,+ identity.config_sha256,+ identity.dimensions,+ xerj_ai::neural::POOLING,+ xerj_ai::neural::MAX_TOKENS+ ),+ true,+ None,+ Some(identity.dimensions),+ ),+ Err(e) => {+ // `e.detail` names resolved paths and the configured model id.+ // `EmbeddingExecutionIdentity` is documented as carrying neither+ // across the API boundary, and `non_resumable_reason` is the one+ // field of it that is not a digest — so the detail goes to this+ // server's log and only the bare asset name goes on the wire.+ warn!(+ asset = e.asset,+ detail = %e.detail,+ "neural embedding assets could not be content-addressed; semantic resume is \+ disabled for this node"+ );+ (+ format!("neural-unresolved.v1;configured-model={}", neural.model_id),+ false,+ Some(format!(+ "the neural model assets could not be content-addressed: cannot read {}",+ e.asset+ )),+ None,+ )+ }+ }+}++#[cfg(not(feature = "neural"))]+fn configured_neural_identity(+ _cfg: &xerj_common::config::EmbeddingConfig,+) -> (String, bool, Option<String>, Option<usize>) {+ // `backend` below resolves a requested "neural" to "lexical" in slim+ // builds, so this arm is unreachable there; it exists so the match needs+ // no `cfg` of its own.+ unreachable!("the neural backend is not compiled into this build")+}+pub(crate) fn embedding_execution_identity(cfg: &xerj_common::config::EmbeddingConfig,) -> Result<crate::engine::EmbeddingExecutionIdentity> {@@ -32018,9 +32130,10 @@ pub(crate) fn embedding_execution_identity(backend = "lexical";}// Only report a width for the backends whose width this server actually- // pins. `neural` reads it from the loaded model's `hidden_size` and- // `proxy` gets whatever the remote returns, so both are omitted rather- // than reported as 384.+ // pins. `neural` reads it from the resolved model's `config.json`+ // (`hidden_size`, the same number `NeuralEmbedder::dims` reports) and+ // `proxy` gets whatever the remote returns, so only the latter is omitted+ // rather than reported as 384.let (material, resumable, reason, dimensions) = match backend {"lexical" => (format!(@@ -32053,15 +32166,7 @@ pub(crate) fn embedding_execution_identity(Some(onnx_dimensions),)}- "neural" => (- format!("neural-unpinned.v1;configured-model={}", cfg.neural_model),- false,- Some(- "the neural model is not content-addressed; use a fresh autoindex state after changing it"- .to_string(),- ),- None,- ),+ "neural" => configured_neural_identity(cfg),"proxy" => (// #533: the endpoint is part of the embedder identity — the same// model name behind a different `default_endpoint` is a DIFFERENT@@ -32400,14 +32505,42 @@ mod embedding_identity_tests {mode: "neural".into(),..Default::default()};+ // Resolve against an EMPTY directory rather than the hub: this asserts+ // the fail-closed arm, and a unit test must never reach the network.+ #[cfg(feature = "neural")]+ let empty_model_dir = tempfile::tempdir().unwrap();+ #[cfg(feature = "neural")]+ let neural = xerj_common::config::EmbeddingConfig {+ local_model_dir: empty_model_dir.path().to_string_lossy().into_owned(),+ ..neural+ };let neural_identity = embedding_execution_identity(&neural).unwrap();#[cfg(feature = "neural")]{assert_eq!(neural_identity.backend, "neural");+ // Assets that cannot be resolved stay non-resumable — but the+ // reason names the asset instead of blaming a configuration change+ // (#487: the old text sent operators to reset autoindex state,+ // which no gate here ever reads).assert!(!neural_identity.resumable);- // The neural width is the loaded model's `hidden_size`, which is- // not known until the model loads — reporting 384 here would be a- // false statement for any encoder that is not 384-wide.+ let reason = neural_identity.non_resumable_reason.clone().unwrap();+ assert!(+ reason.contains("content-addressed") && reason.contains("model.safetensors"),+ "the failure must name the missing asset: {reason}"+ );+ // ...and NOTHING else. `non_resumable_reason` is the only field of+ // this struct that is not a digest, so it is the only place a model+ // path or model id could cross the API boundary the struct's own+ // doc comment says they never cross. The operator-facing detail+ // (paths included) goes to the server log instead.+ assert!(+ !reason.contains(&empty_model_dir.path().to_string_lossy().into_owned()),+ "the model directory must not reach a remote client: {reason}"+ );+ assert!(!reason.contains("MiniLM"), "{reason}");+ // The neural width is the resolved model's `hidden_size`, so it is+ // unknown when the model cannot be resolved at all — reporting 384+ // here would be a false statement for any non-384-wide encoder.assert_eq!(neural_identity.dimensions, None);let encoded = serde_json::to_string(&neural_identity).unwrap();assert!(!encoded.contains("dimensions"), "{encoded}");@@ -32569,8 +32702,8 @@ mod embedding_identity_tests {let rewritten: PersistedEmbeddingExecution =serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();assert_eq!(- rewritten.version, 2,- "#533: the record must be re-recorded at v2"+ rewritten.version, PERSISTED_EMBEDDING_EXECUTION_VERSION,+ "#533: the record must be re-recorded at the CURRENT version (asserted against the constant so a later migration bump — #487 took it to 3 — does not silently turn this into a no-op)");assert_eq!(rewritten.identity_sha256,@@ -32588,6 +32721,66 @@ mod embedding_identity_tests {.expect_err("#533: after re-baselining, a v2 endpoint change must be refused");}+ /// #487 migration, the same shape as #533 one backend over: content-+ /// addressing the neural identity MOVES `identity_sha256` for every neural+ /// node, so a v2 record over a POPULATED neural index would compare a hash+ /// from the superseded algorithm against the new one and refuse to open the+ /// index. It must be grandfathered and re-baselined instead — otherwise the+ /// change that makes neural corpora re-indexable bricks the ones that exist.+ ///+ /// Fails on the unfixed code because `PERSISTED_EMBEDDING_EXECUTION_VERSION`+ /// was still 2: the record was current, the hash comparison ran, and the+ /// open was refused.+ #[cfg(feature = "neural")]+ #[test]+ fn a_version_2_neural_record_is_grandfathered_then_rebaselined() {+ let dir = tempfile::tempdir().unwrap();+ let index_dir = dir.path();+ let path = index_dir.join(EMBEDDING_EXECUTION_FILE);+ std::fs::write(+ &path,+ serde_json::to_vec_pretty(&PersistedEmbeddingExecution {+ version: 2,+ backend: "neural".into(),+ // What rc.71 wrote for EVERY neural node: sha256 of+ // "…;backend=neural;neural-unpinned.v1;configured-model=…".+ identity_sha256: "6e51e5ce3e463db6d6d853516c358e4a529308f213e85d2ed005f731d00ce8f3"+ .into(),+ })+ .unwrap(),+ )+ .unwrap();++ let model_dir = neural_model_dir(384, "weights-migration");+ let neural = xerj_common::config::EmbeddingConfig {+ mode: "neural".into(),+ local_model_dir: model_dir.path().to_string_lossy().into_owned(),+ ..Default::default()+ };+ // Populated index, v2 record, v3 current → grandfathered, not refused.+ validate_embedding_execution(index_dir, &neural, false, true)+ .expect("#487: a v2 neural record must be grandfathered, not refused, on upgrade");++ let rewritten: PersistedEmbeddingExecution =+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();+ assert_eq!(rewritten.version, PERSISTED_EMBEDDING_EXECUTION_VERSION);+ assert_eq!(+ rewritten.identity_sha256,+ embedding_execution_identity(&neural)+ .unwrap()+ .identity_sha256+ );++ // Re-baselined, so a GENUINE later model swap is still refused.+ let swapped_dir = neural_model_dir(384, "weights-migration-swapped");+ let swapped = xerj_common::config::EmbeddingConfig {+ local_model_dir: swapped_dir.path().to_string_lossy().into_owned(),+ ..neural.clone()+ };+ validate_embedding_execution(index_dir, &swapped, false, true)+ .expect_err("#487: after re-baselining, a swapped model must be refused");+ }+/// #533: the version-delta grandfather must NOT mask a genuine BACKEND change/// — a lexical->proxy swap is a different embedder regardless of hash, so a/// populated index whose v1 record names a different backend is still refused@@ -32621,6 +32814,155 @@ mod embedding_identity_tests {);}+ /// A local model directory holding the three assets `NeuralEmbedder::load`+ /// resolves. Only the digests and `config.json`'s `hidden_size` are read by+ /// the identity, so the weights can be arbitrary bytes.+ #[cfg(feature = "neural")]+ fn neural_model_dir(hidden_size: usize, weights: &str) -> tempfile::TempDir {+ let dir = tempfile::tempdir().unwrap();+ std::fs::write(+ dir.path().join("config.json"),+ serde_json::to_vec(&serde_json::json!({+ "vocab_size": 30522,+ "hidden_size": hidden_size,+ "num_hidden_layers": 6,+ "num_attention_heads": 12,+ "intermediate_size": 1536,+ "hidden_act": "gelu",+ "hidden_dropout_prob": 0.1,+ "max_position_embeddings": 512,+ "type_vocab_size": 2,+ "initializer_range": 0.02,+ "layer_norm_eps": 1e-12,+ "pad_token_id": 0,+ "classifier_dropout": serde_json::Value::Null,+ "model_type": "bert",+ }))+ .unwrap(),+ )+ .unwrap();+ std::fs::write(dir.path().join("tokenizer.json"), b"{}").unwrap();+ std::fs::write(dir.path().join("model.safetensors"), weights.as_bytes()).unwrap();+ dir+ }++ /// #487: `/v1/embedding/identity` reported `resumable: false` on every+ /// neural node, from an identity derived from the configured model NAME —+ /// so a fresh node and a long-running one were indistinguishable, and every+ /// `resumable` gate in `xerj-autoindex` fired on an UNCHANGED corpus+ /// (measured on rc.71: graph path run 1 `exit=0`, run 2 `exit=1`). The+ /// identity now comes from the assets' bytes, the way Lucene decides+ /// whether a replicated file may be reused (`ReplicaNode.fileIsIdentical`,+ /// lucene/replicator/src/java/org/apache/lucene/replicator/nrt/ReplicaNode.java:855).+ ///+ /// Fails on the unfixed code at the very first assertion: `resumable` was+ /// hardcoded `false` for this backend.+ #[cfg(feature = "neural")]+ #[test]+ fn neural_execution_identity_is_content_addressed_and_resumable() {+ let neural = |dir: &tempfile::TempDir| xerj_common::config::EmbeddingConfig {+ mode: "neural".into(),+ local_model_dir: dir.path().to_string_lossy().into_owned(),+ ..Default::default()+ };++ let first_dir = neural_model_dir(384, "weights-a");+ let identity = embedding_execution_identity(&neural(&first_dir)).unwrap();+ assert_eq!(identity.backend, "neural");+ assert!(+ identity.resumable,+ "content-addressed assets are resumable: {:?}",+ identity.non_resumable_reason+ );+ assert_eq!(identity.non_resumable_reason, None);+ // Width now comes from the resolved `config.json`, not from a guess.+ assert_eq!(identity.dimensions, Some(384));+ // No path, and no bare model name, may leak into the reported identity:+ // the wire contract is documented as privacy-safe.+ let encoded = serde_json::to_string(&identity).unwrap();+ assert!(!encoded.contains(&first_dir.path().to_string_lossy().into_owned()));+ assert!(!encoded.contains("MiniLM"), "{encoded}");++ // Same bytes in a DIFFERENT directory → same identity. This is the+ // property the fix exists for: it is a different `NeuralConfig`, so it+ // misses the memo and is recomputed from scratch, and it stands in for+ // "the same model on another host / after a restart" — anything the+ // digest picked up from a path or a hub pointer would break it.+ let same_content = neural_model_dir(384, "weights-a");+ assert_eq!(+ embedding_execution_identity(&neural(&same_content))+ .unwrap()+ .identity_sha256,+ identity.identity_sha256+ );++ // Different weights → different identity. This is the mismatch the+ // resume gates exist to catch, and the old name-hash could not see it.+ let other_weights = neural_model_dir(384, "weights-b");+ assert_ne!(+ embedding_execution_identity(&neural(&other_weights))+ .unwrap()+ .identity_sha256,+ identity.identity_sha256+ );++ // A different width is a different embedder even with equal weights.+ let other_width = neural_model_dir(768, "weights-a");+ let wider = embedding_execution_identity(&neural(&other_width)).unwrap();+ assert_eq!(wider.dimensions, Some(768));+ assert_ne!(wider.identity_sha256, identity.identity_sha256);+ }++ /// The identity must be a function of the model bytes and NOTHING else.+ /// Recomputing it from many threads at once — the "different worker counts"+ /// half of #487's acceptance — must return one answer, so nothing+ /// order-dependent (map iteration, a race on the memo) can reach the+ /// digest. Combined with the different-directory assertion above, this is+ /// what "stable across restarts" reduces to for a pure function of bytes.+ ///+ /// Honest scope: this one PASSES on the unfixed code too. The pre-fix+ /// identity was already deterministic — the live rc.71 node in #487 emitted+ /// `6e51e5ce3e46…` on every call — so instability was never the defect;+ /// `resumable` being hardcoded `false` was. This is a forward regression+ /// guard on the new digest, not evidence for the fix.+ #[cfg(feature = "neural")]+ #[test]+ fn neural_execution_identity_is_stable_across_threads_and_repeats() {+ let dir = neural_model_dir(384, "weights-stable");+ let cfg = xerj_common::config::EmbeddingConfig {+ mode: "neural".into(),+ local_model_dir: dir.path().to_string_lossy().into_owned(),+ ..Default::default()+ };+ let expected = embedding_execution_identity(&cfg).unwrap().identity_sha256;++ // A second, never-memoised config over byte-identical assets, hammered+ // from 16 threads: every one must agree with the first computation.+ let fresh = neural_model_dir(384, "weights-stable");+ let fresh_cfg = xerj_common::config::EmbeddingConfig {+ mode: "neural".into(),+ local_model_dir: fresh.path().to_string_lossy().into_owned(),+ ..Default::default()+ };+ let digests: std::collections::BTreeSet<String> = std::thread::scope(|scope| {+ let handles: Vec<_> = (0..16)+ .map(|_| {+ scope.spawn(|| {+ embedding_execution_identity(&fresh_cfg)+ .unwrap()+ .identity_sha256+ })+ })+ .collect();+ handles.into_iter().map(|h| h.join().unwrap()).collect()+ });+ assert_eq!(+ digests,+ std::collections::BTreeSet::from([expected]),+ "the execution identity must not depend on which thread computed it"+ );+ }+#[cfg(feature = "onnx-experimental")]#[test]fn onnx_execution_identity_changes_with_asset_content() {@@ -33107,16 +33449,10 @@ fn make_onnx_embedder(_cfg: &xerj_common::config::EmbeddingConfig) -> Result<xer/// and fall back to lexical so a `mode=neural` config never bricks startup.#[cfg(feature = "neural")]fn make_neural_embedder(cfg: &xerj_common::config::EmbeddingConfig) -> xerj_ai::Embedder {- let model_id = if cfg.neural_model.trim().is_empty() {- xerj_ai::neural::DEFAULT_MODEL_ID.to_string()- } else {- cfg.neural_model.clone()- };- let neural_cfg = xerj_ai::neural::NeuralConfig {- model_id,- cache_dir: (!cfg.model_cache_dir.is_empty()).then(|| cfg.model_cache_dir.clone().into()),- local_dir: (!cfg.local_model_dir.is_empty()).then(|| cfg.local_model_dir.clone().into()),- };+ // Exactly the resolution the execution identity content-addresses — see+ // `configured_neural_config`. Duplicating it here once let the reported+ // identity describe a different model than the one that loads.+ let neural_cfg = configured_neural_config(cfg);info!(model = %neural_cfg.model_id, "embedding backend: built-in neural BERT (loads on first use)");xerj_ai::Embedder::neural(neural_cfg)}