Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

fix(api): prevalidate multi-index semantic mappings

bugerd6c75f730bc2
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 2e090d1cc..13634e00b 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -1583,6 +1583,11 @@ pub async fn put_mapping(
}
}
+ // Build and validate every target's complete candidate state before
+ // publishing any schema or raw mapping. This prevents deterministic
+ // wildcard/comma-list failures (for example, a later target's field
+ // collision) from leaving earlier targets changed.
+ let mut plans = Vec::with_capacity(targets.len());
for idx_name in &targets {
let idx = match state.engine.get_index(idx_name) {
Ok(i) => i,
@@ -1635,9 +1640,10 @@ pub async fn put_mapping(
}
}
+ let mut additions = Vec::new();
if let Some(properties) = body.get("properties") {
let current = idx.schema().await;
- let mut additions = Vec::new();
+ let mut candidate = current.clone();
for field in es_properties_to_fields(properties) {
if let Some(existing_field) = current.field(&field.name) {
if existing_field.field_type != field.field_type {
@@ -1649,15 +1655,31 @@ pub async fn put_mapping(
}
continue;
}
+ if let Err(error) = candidate.add_field(field.clone()) {
+ return ApiError::new(error).into_response();
+ }
additions.push(field);
}
- if let Err(error) = idx.add_fields(additions).await {
+ }
+ plans.push((idx_name.clone(), idx, existing, additions));
+ }
+
+ // Publication begins only after every deterministic candidate has passed.
+ // `add_fields` repeats engine-side validation defensively. Concurrent
+ // schema evolution and filesystem failures still require a broader
+ // engine-level multi-index transaction primitive; see the engineering
+ // report for that explicitly tracked limitation.
+ for (_, idx, _, additions) in &plans {
+ if !additions.is_empty() {
+ if let Err(error) = idx.add_fields(additions.clone()).await {
return ApiError::new(xerj_common::XerjError::from(error)).into_response();
}
}
+ }
+ for (idx_name, _, existing, _) in plans {
// Persists es_mapping.json into the index dir (atomic) so the
// merged mapping survives a restart.
- state.engine.put_index_mapping(idx_name, existing);
+ state.engine.put_index_mapping(&idx_name, existing);
}
Json(json!({ "acknowledged": true })).into_response()
@@ -13435,6 +13457,112 @@ mod semantic_companion_hnsw_api_tests {
state.engine.flush_all_force().await;
}
+ #[tokio::test]
+ async fn multi_index_put_mapping_validates_every_schema_before_publication() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = data_dir.path().to_string_lossy().into_owned();
+ let state = state(&config);
+ for name in ["a-first-clean", "z-late-collision"] {
+ let (status, response) = request_json(
+ state.clone(),
+ "PUT",
+ &format!("/{name}"),
+ Some("application/json"),
+ json!({"mappings": {"properties": {}}}).to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{response}");
+ }
+
+ // Model an engine-side field that is absent from the raw mapping.
+ // Before two-phase planning, the first target published `body` and
+ // `body_vector` before this later target's add_fields collision
+ // returned an error.
+ state
+ .engine
+ .get_index("z-late-collision")
+ .unwrap()
+ .add_field(FieldConfig::new("body_vector", FieldType::Double))
+ .await
+ .unwrap();
+
+ let first_schema_before = state
+ .engine
+ .get_index("a-first-clean")
+ .unwrap()
+ .schema()
+ .await;
+ let late_schema_before = state
+ .engine
+ .get_index("z-late-collision")
+ .unwrap()
+ .schema()
+ .await;
+ let (_, mappings_before) = request_json(
+ state.clone(),
+ "GET",
+ "/a-first-clean,z-late-collision/_mapping",
+ None,
+ "",
+ )
+ .await;
+
+ let (status, error) = request_json(
+ state.clone(),
+ "PUT",
+ "/a-first-clean,z-late-collision/_mapping",
+ Some("application/json"),
+ json!({
+ "properties": {
+ "body": { "type": "semantic_text", "dimensions": 32 }
+ }
+ })
+ .to_string(),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{error}");
+ assert!(
+ error["error"]["reason"]
+ .as_str()
+ .unwrap()
+ .contains("body_vector"),
+ "{error}"
+ );
+ assert_eq!(
+ state
+ .engine
+ .get_index("a-first-clean")
+ .unwrap()
+ .schema()
+ .await,
+ first_schema_before,
+ "an earlier target schema changed before a later validation failure"
+ );
+ assert_eq!(
+ state
+ .engine
+ .get_index("z-late-collision")
+ .unwrap()
+ .schema()
+ .await,
+ late_schema_before
+ );
+ let (_, mappings_after) = request_json(
+ state.clone(),
+ "GET",
+ "/a-first-clean,z-late-collision/_mapping",
+ None,
+ "",
+ )
+ .await;
+ assert_eq!(
+ mappings_after, mappings_before,
+ "raw mappings changed despite a rejected multi-index update"
+ );
+ state.engine.flush_all_force().await;
+ }
+
#[tokio::test]
async fn shared_semantic_target_is_rejected_before_index_creation() {
let data_dir = tempfile::tempdir().unwrap();
diff --git a/engine/reports/2026-07-28_semantic-companion-hnsw.md b/engine/reports/2026-07-28_semantic-companion-hnsw.md
index bc1c350da..717499925 100644
--- a/engine/reports/2026-07-28_semantic-companion-hnsw.md
+++ b/engine/reports/2026-07-28_semantic-companion-hnsw.md
@@ -39,6 +39,10 @@ Even a correctly populated graph could not serve a `semantic` query.
publishes partial ANN candidates or caches a timed-out result.
- Add atomic multi-field schema publication so a semantic source and companion
cannot become partially visible.
+- Plan the merged raw mapping and schema additions for every index selected by
+ a wildcard/comma-list `PUT _mapping` before publishing the first target.
+ Deterministic candidate failures, such as a collision on a later target,
+ therefore leave all earlier schemas and raw mapping round-trips unchanged.
## Mapping policy and pre-existing inconsistencies now rejected
@@ -86,7 +90,34 @@ Existing phase-attribution coverage also proves successful semantic bulk
publication emits ordered Embed/WAL/Memtable/HNSW records with HNSW
`outcome=ok` and `vectors=1`.
-## Verification
+## Current-main integration
+
+The production changes were replayed onto current-main commit
+`afcb3a76359945c4f1dfe2fd920f8307bc12f261` in the dedicated worktree
+`/workspace/xerj-current-main-semantic-companion-hnsw`.
+
+Both source commits applied without textual conflicts:
+
+- `9d677073a46fb62059a9b518e524c7ddb95efa3b` supplied companion registration,
+ semantic ANN routing, engine/API tests, and this report.
+- `cf32c955fb2f9418b870f5a6f986afae50604bfe` supplied deterministic
+ all-target prevalidation for multi-index mapping updates.
+
+Applying without a textual conflict is not treated as proof of behavioral
+composition. Static inspection specifically confirmed that the replay retains:
+
+- passage-winner metadata and response projection from merged PR 63;
+- the four-element scored tuple carrying an optional passage ordinal;
+- multi-chunk semantic documents falling back to the passage-aware exact path;
+- the static HNSW storage view and reused-external-ID persistence repairs from
+ merged PRs 65 and 64.
+
+At this pre-audit stage only `cargo fmt --all -- --check` and
+`git diff --check afcb3a7..HEAD` were run. Both passed. No current-main test,
+build, conformance, or benchmark result is claimed until an independent source
+audit approves compilation.
+
+## Historical source-branch verification
All commands ran in
`/workspace/xerj-fix-semantic-companion-hnsw/engine`.
@@ -98,17 +129,22 @@ All commands ran in
- `cargo test --release -p xerj-engine fully_covered_semantic_companion_uses_ann_with_exact_rescore --lib -- --nocapture`
passed `1/1`.
- `cargo test --release -p xerj-api semantic_companion --lib -- --nocapture`
- passed `9/9`.
+ passed `10/10` after the follow-up deterministic multi-index validation
+ regression.
+- `cargo test -p xerj-api multi_index_put_mapping_validates_every_schema_before_publication --lib -- --nocapture`
+ passed `1/1`; it places a clean target first and an engine-schema collision
+ second in an explicit comma-list, then proves both schemas and both public
+ mappings are unchanged.
- `cargo fmt --all -- --check` and `git diff --check` passed.
- A fresh branch-local
`cargo build --release -j 32 -p xerj-server -p es-yaml-runner` passed.
Server SHA-256:
- `ea94d57d59064e9846030178ad0913199c19fe04d4ae321eeb66f2913b7dc7e6`.
+ `3ffccd5e2df47b15375523a74811b89e714d6189be567db8742ccbc89363bcb5`.
Runner SHA-256:
`7adb54815499b793b5bdbe7f4340427e81c9e101b34e04a76bc2fd5965d1987b`.
- The built server used fresh data directory
- `/tmp/xerj-semantic-conformance.wh7jtb`.
- `./target/release/es-yaml-runner --dir tests/es-compat-yaml/yaml --verbose`
+ `/tmp/xerj-semantic-followup.ovrpYc`.
+ `./target/release/es-yaml-runner --dir tests/es-compat-yaml/yaml`
passed `1360`, failed `0`, skipped `3` (`1363` total).
## Excluded attempt
@@ -119,3 +155,28 @@ remaining branch-local compiler process was terminated, no artifact was used,
and no result from that attempt is included above. The recorded hashes and
conformance result come only from the later clean branch-local build after all
competing Cargo/Rust compiler activity had cleared.
+
+## Open engine issue: strict cross-index transactionality
+
+The multi-index follow-up deliberately guarantees validation-before-mutation
+for deterministic mapping failures. It does not claim a strict transaction in
+the presence of concurrent schema evolution or filesystem failure.
+
+The exact pre-existing source chain is:
+
+1. `xerj-api/src/es_compat.rs::put_mapping` plans several target indices.
+2. `Index::add_fields` owns only one index's schema write lock; there is no
+ engine-wide schema transaction lock, and dynamic ingest can evolve another
+ target between planning and publication.
+3. `Engine::put_index_mapping` persists one `es_mapping.json` at a time,
+ logs serialization/write failures instead of returning them, and then
+ updates `index_mappings` in memory. A later disk failure therefore cannot
+ roll back already-published schemas or earlier mapping files.
+
+A separate engine change should introduce a global prepare/persist/publish
+primitive: acquire one transaction authority shared by explicit and dynamic
+schema evolution, validate all candidate schemas, serialize and stage every
+schema/raw-mapping file, atomically publish all in-memory states only after
+staging succeeds, and restore staged files/in-memory snapshots on any commit
+failure. Until that exists, the supported guarantee is the narrower,
+tested deterministic validation boundary above.