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): serialize single-document publication by id
buger16350ac69d43
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rsindex f8e2de221..64c3f1291 100644--- a/engine/crates/xerj-engine/src/index.rs+++ b/engine/crates/xerj-engine/src/index.rs@@ -404,6 +404,19 @@ fn l2_normalize_vec(v: &mut [f32]) {// ── Index ────────────────────────────────────────────────────────────────────+#[cfg(test)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum PublicationTestPoint {+ Acquired,+ AfterWalVersionMap,+ AfterFts,+ AfterHnsw,+ BeforeRelease,+}++#[cfg(test)]+type PublicationTestHook = Arc<dyn Fn(&str, PublicationTestPoint) + Send + Sync + 'static>;+/// Per-index coordinator.////// Owns the storage layer (`IndexStore`), the FTS memtable, and the schema.@@ -421,6 +434,11 @@ pub struct Index {/// clients on N different shards run truly in parallel on the/// write side. Query paths iterate all shards.memtable: Arc<crate::memtable::ShardedFtsMemtable>,+ /// Exact per-document ordering shared by all publication stages wired to+ /// this coordinator. Idle keys are removed immediately.+ write_publication: Arc<crate::write_publication::WritePublicationCoordinator>,+ #[cfg(test)]+ publication_test_hook: Arc<parking_lot::RwLock<Option<PublicationTestHook>>>,doc_count: Arc<AtomicU64>,/// Counter for `update` operations that detected no change to the/// existing source — surfaced via `indices.stats` as@@ -795,6 +813,21 @@ pub struct Index {}impl Index {+ #[cfg(test)]+ fn publication_test_point(&self, id: &str, point: PublicationTestPoint) {+ // Clone the callback while holding the hook registry lock, then invoke+ // it after releasing that lock. Test barriers may intentionally block.+ let hook = self.publication_test_hook.read().clone();+ if let Some(hook) = hook {+ hook(id, point);+ }+ }++ #[cfg(test)]+ fn set_publication_test_hook(&self, hook: Option<PublicationTestHook>) {+ *self.publication_test_hook.write() = hook;+ }+/// Create a new index at `data_dir/<name>`.pub fn create(name: IndexName,@@ -906,6 +939,9 @@ impl Index {config.engine.ingest_shards,),),+ write_publication: crate::write_publication::WritePublicationCoordinator::new(),+ #[cfg(test)]+ publication_test_hook: Arc::new(parking_lot::RwLock::new(None)),doc_count: Arc::new(AtomicU64::new(0)),noop_update_count: Arc::new(AtomicU64::new(0)),request_cache_seen: Arc::new(RwLock::new(RequestCacheSeen::with_capacity(65_536))),@@ -1155,6 +1191,9 @@ impl Index {enrichments: Arc::new(RwLock::new(HashMap::new())),store,memtable: Arc::new(memtable),+ write_publication: crate::write_publication::WritePublicationCoordinator::new(),+ #[cfg(test)]+ publication_test_hook: Arc::new(parking_lot::RwLock::new(None)),doc_count: Arc::new(AtomicU64::new(total_doc_count)),noop_update_count: Arc::new(AtomicU64::new(0)),request_cache_seen: Arc::new(RwLock::new(RequestCacheSeen::with_capacity(65_536))),@@ -1253,26 +1292,17 @@ impl Index {) -> Result<IndexResponse> {let doc_id = id.unwrap_or_else(|| Uuid::new_v4().to_string());let strict = version_type != "external_gte";- // CAS against the caller's prior external version.- if let Some(existing) = self.external_versions.get(&doc_id) {- let cur = *existing;- let ok = if strict {- version > cur- } else {- version >= cur- };- if !ok {- return Err(EngineError::Common(- xerj_common::XerjError::version_conflict(&doc_id, version, cur),- ));- }- }- self.external_versions.insert(doc_id.clone(), version);- let mut resp = self- .index_document_with_version(Some(doc_id), source, None, None)- .await?;- resp.version = version;- Ok(resp)+ self.index_document_with_version_inner_guarded(+ Some(doc_id),+ source,+ None,+ None,+ false,+ None,+ false,+ Some((version, strict)),+ )+ .await}/// Index a document with optional optimistic concurrency control.@@ -1303,6 +1333,31 @@ impl Index {if_seq_no: Option<u64>,if_primary_term: Option<u64>,semantic_embeddings_prepared: bool,+ ) -> Result<IndexResponse> {+ self.index_document_with_version_inner_guarded(+ id,+ source,+ if_seq_no,+ if_primary_term,+ semantic_embeddings_prepared,+ None,+ false,+ None,+ )+ .await+ }++ #[allow(clippy::too_many_arguments)]+ async fn index_document_with_version_inner_guarded(+ &self,+ id: Option<String>,+ source: Value,+ if_seq_no: Option<u64>,+ if_primary_term: Option<u64>,+ semantic_embeddings_prepared: bool,+ publication_guard: Option<crate::write_publication::WritePublicationGuard>,+ create_only: bool,+ external_version: Option<(u64, bool)>,) -> Result<IndexResponse> {// Check write block.if self.is_write_blocked().await {@@ -1314,15 +1369,39 @@ impl Index {// Process-wide admission: disk flood-stage block (item 3) + parent// memory circuit breaker (item 1). Fires before any per-index work.self.governor_write_gate()?;- // Invalidate the response cache: every doc write bumps the- // dataset version, which is part of the cache key, so old- // entries become invisible to lookups. No clear() needed —- // they age out on the next 1k-entry truncation.- self.dataset_version.fetch_add(1, Ordering::Release);-let index_start = std::time::Instant::now();let doc_id = id.unwrap_or_else(|| Uuid::new_v4().to_string());+ // `index.default_pipeline` is resolved and executed at the API layer+ // (xerj-api es_compat::resolve_effective_pipeline) before the document+ // reaches the engine, so no pipeline handling is needed here.++ // Auto-embed `semantic_text` fields: vectorise the field's text into+ // its companion vector field (`<field>_vector`) so it becomes+ // kNN-searchable. Runs before copy_to / storage so the derived vector+ // is part of `_source` and gets picked up by HNSW indexing below.+ let source = if semantic_embeddings_prepared {+ source+ } else {+ self.apply_semantic_embeddings(source).await?+ };++ // Apply copy_to: expand the source by copying field values to their target fields.+ let source = {+ let schema_guard = self.schema.read().await;+ apply_copy_to(&source, &schema_guard.schema)+ };++ // Preprocessing above is independent and can run concurrently.+ // Everything from CAS/liveness through WAL, VM, FTS, HNSW, and the+ // response is one exact per-document publication interval.+ let _publication_guard = match publication_guard {+ Some(guard) => guard,+ None => self.write_publication.lock(doc_id.clone()).await,+ };+ #[cfg(test)]+ self.publication_test_point(&doc_id, PublicationTestPoint::Acquired);+// Optimistic concurrency check: honour `if_seq_no` whenever it// is supplied. ES requires `if_primary_term` alongside it, but// xerj is single-shard with primary_term=1, so we treat a@@ -1350,25 +1429,39 @@ impl Index {}}- // `index.default_pipeline` is resolved and executed at the API layer- // (xerj-api es_compat::resolve_effective_pipeline) before the document- // reaches the engine, so no pipeline handling is needed here.+ if create_only {+ let exists = self+ .store+ .version_map+ .get(&doc_id)+ .map(|entry| !entry.deleted)+ .unwrap_or(false)+ || self.memtable.contains(&doc_id);+ if exists {+ return Err(EngineError::Common(+ xerj_common::XerjError::version_conflict(&doc_id, 0, 1),+ ));+ }+ }- // Auto-embed `semantic_text` fields: vectorise the field's text into- // its companion vector field (`<field>_vector`) so it becomes- // kNN-searchable. Runs before copy_to / storage so the derived vector- // is part of `_source` and gets picked up by HNSW indexing below.- let source = if semantic_embeddings_prepared {- source- } else {- self.apply_semantic_embeddings(source).await?- };+ if let Some((version, strict)) = external_version {+ if let Some(existing) = self.external_versions.get(&doc_id) {+ let current = *existing;+ let valid = if strict {+ version > current+ } else {+ version >= current+ };+ if !valid {+ return Err(EngineError::Common(+ xerj_common::XerjError::version_conflict(&doc_id, version, current),+ ));+ }+ }+ }- // Apply copy_to: expand the source by copying field values to their target fields.- let source = {- let schema_guard = self.schema.read().await;- apply_copy_to(&source, &schema_guard.schema)- };+ // Invalidate the response cache only after admission and CAS succeed.+ self.dataset_version.fetch_add(1, Ordering::Release);// Detect whether this is an overwrite (existing doc) vs a new// insert BEFORE writing to storage. Used to set the response@@ -1386,6 +1479,15 @@ impl Index {// Write to storage WAL.let seq_no = self.store.index(&doc_id, source.clone())?;+ // External-version admission becomes durable only after the WAL write+ // succeeds. Publishing it before `store.index` would poison an exact+ // retry when WAL append fails.+ if let Some((external_version, _)) = external_version {+ self.external_versions+ .insert(doc_id.clone(), external_version);+ }+ #[cfg(test)]+ self.publication_test_point(&doc_id, PublicationTestPoint::AfterWalVersionMap);// Write to FTS memtable.{@@ -1394,6 +1496,8 @@ impl Index {mem.remove(&doc_id);mem.insert(doc_id.clone(), &source, &schema_guard.schema, seq_no);}+ #[cfg(test)]+ self.publication_test_point(&doc_id, PublicationTestPoint::AfterFts);// Bump counter (flush thresholds / stats bookkeeping only — NOT the// response `_version`, which is per-doc).@@ -1460,6 +1564,8 @@ impl Index {// Index any vector fields into the HNSW index.self.index_vectors(&doc_id, &source).await;+ #[cfg(test)]+ self.publication_test_point(&doc_id, PublicationTestPoint::AfterHnsw);// Trigger a background flush if memtable exceeds size or doc-count threshold.self.maybe_spawn_flush().await;@@ -1476,10 +1582,14 @@ impl Index {debug!(doc_id = doc_id.as_str(), seq_no, "document indexed");+ #[cfg(test)]+ self.publication_test_point(&doc_id, PublicationTestPoint::BeforeRelease);Ok(IndexResponse {id: doc_id,seq_no,- version,+ version: external_version+ .map(|(version, _)| version)+ .unwrap_or(version),result: if existed_before {"updated".to_string()} else {@@ -2495,39 +2605,17 @@ impl Index {////// Returns `Err(VersionConflict)` if a live document with the same ID exists.pub async fn create_document(&self, id: String, source: Value) -> Result<IndexResponse> {- // Check write block first.- if self.is_write_blocked().await {- return Err(EngineError::Common(xerj_common::XerjError::index_blocked(- self.name.as_str(),- "write",- )));- }- // Process-wide admission: disk flood-stage block (item 3) + parent- // memory circuit breaker (item 1). Fires before any per-index work.- self.governor_write_gate()?;-- // Fail with 409 if a live document already exists with this id.- let already_exists = {- let in_version_map = self- .store- .version_map- .get(&id)- .map(|e| !e.deleted)- .unwrap_or(false);- let in_memtable = {- let mem = &*self.memtable;- mem.contains(&id)- };- in_version_map || in_memtable- };-- if already_exists {- return Err(EngineError::Common(- xerj_common::XerjError::version_conflict(&id, 0, 1),- ));- }-- self.index_document(Some(id), source).await+ self.index_document_with_version_inner_guarded(+ Some(id),+ source,+ None,+ None,+ false,+ None,+ true,+ None,+ )+ .await}/// Refresh: flush the current active memtable to a disk segment.@@ -3845,6 +3933,7 @@ impl Index {upsert_doc: Option<Value>,doc_as_upsert: bool,) -> Result<Option<IndexResponse>> {+ let publication_guard = self.write_publication.lock(id.to_string()).await;match self.get_document(id).await? {Some(existing) => {// Document exists — merge partial_doc on top.@@ -3875,14 +3964,26 @@ impl Index {// object against the existing source.if merged == existing {self.noop_update_count.fetch_add(1, Ordering::Relaxed);+ let current = self.store.version_map.get(id);return Ok(Some(IndexResponse {id: id.to_string(),- seq_no: 0,- version: 1,+ seq_no: current.as_ref().map(|entry| entry.seq_no).unwrap_or(0),+ version: current.map(|entry| entry.version).unwrap_or(1),result: "noop".to_string(),}));}- let resp = self.index_document(Some(id.to_string()), merged).await?;+ let resp = self+ .index_document_with_version_inner_guarded(+ Some(id.to_string()),+ merged,+ None,+ None,+ false,+ Some(publication_guard),+ false,+ None,+ )+ .await?;Ok(Some(resp))}None => {@@ -3890,7 +3991,18 @@ impl Index {if doc_as_upsert {// Use partial_doc as the creation body.let body = partial_doc.unwrap_or(Value::Object(serde_json::Map::new()));- let resp = self.index_document(Some(id.to_string()), body).await?;+ let resp = self+ .index_document_with_version_inner_guarded(+ Some(id.to_string()),+ body,+ None,+ None,+ false,+ Some(publication_guard),+ false,+ None,+ )+ .await?;Ok(Some(resp))} else if let Some(upsert_body) = upsert_doc {// Create with upsert body, then merge partial_doc on top.@@ -3909,7 +4021,18 @@ impl Index {} else {upsert_body};- let resp = self.index_document(Some(id.to_string()), body).await?;+ let resp = self+ .index_document_with_version_inner_guarded(+ Some(id.to_string()),+ body,+ None,+ None,+ false,+ Some(publication_guard),+ false,+ None,+ )+ .await?;Ok(Some(resp))} else {Ok(None)@@ -6061,6 +6184,9 @@ impl Index {// Process-wide admission: disk flood-stage block (item 3) + parent// memory circuit breaker (item 1). Fires before any per-index work.self.governor_write_gate()?;+ let _publication_guard = self.write_publication.lock(id.to_string()).await;+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::Acquired);self.dataset_version.fetch_add(1, Ordering::Release);// Optimistic concurrency check (see index_document_with_version for@@ -6120,6 +6246,8 @@ impl Index {let seq_no = existing.map(|e| e.seq_no).unwrap_or_else(|| self.store.current_seq_no().saturating_sub(1));+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::BeforeRelease);return Ok(DeleteDocOutcome {found: false,seq_no,@@ -6128,6 +6256,8 @@ impl Index {}let deleted_seq = self.store.delete(id)?;+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::AfterWalVersionMap);let existed = deleted_seq.is_some();// Remove from memtable.@@ -6135,6 +6265,8 @@ impl Index {let mem = &*self.memtable;mem.remove(id);}+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::AfterFts);// v0.6.2 — propagate the delete into the HNSW graph. Pre-fix// a deleted doc was unfindable via _get / _search but the@@ -6163,6 +6295,8 @@ impl Index {}).ok();}+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::AfterHnsw);if existed {self.doc_count.fetch_sub(1, Ordering::Relaxed);@@ -6177,6 +6311,8 @@ impl Index {.version_map.bump_tombstone_version(id).unwrap_or(1);+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::BeforeRelease);return Ok(DeleteDocOutcome {found: false,seq_no: self.store.current_seq_no().saturating_sub(1),@@ -6192,6 +6328,8 @@ impl Index {.map(|e| e.version).unwrap_or(1);let seq_no = deleted_seq.unwrap_or_else(|| self.store.current_seq_no().saturating_sub(1));+ #[cfg(test)]+ self.publication_test_point(id, PublicationTestPoint::BeforeRelease);Ok(DeleteDocOutcome {found: true,seq_no,@@ -6209,6 +6347,7 @@ impl Index {id: &str,partial_doc: Value,) -> Result<Option<IndexResponse>> {+ let publication_guard = self.write_publication.lock(id.to_string()).await;// Fetch existing document source.let existing = match self.get_document(id).await? {Some(src) => src,@@ -6236,7 +6375,18 @@ impl Index {};// Re-index with the same ID (upsert-style).- let resp = self.index_document(Some(id.to_string()), merged).await?;+ let resp = self+ .index_document_with_version_inner_guarded(+ Some(id.to_string()),+ merged,+ None,+ None,+ false,+ Some(publication_guard),+ false,+ None,+ )+ .await?;Ok(Some(resp))}@@ -26282,3 +26432,103 @@ mod chunk_embed_tests {);}}++#[cfg(test)]+mod write_publication_integration_tests {+ use super::*;+ use serde_json::json;+ use std::sync::atomic::{AtomicBool, AtomicUsize};++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn put_holds_publication_key_through_response_before_delete() {+ let dir = tempfile::tempdir().unwrap();+ let mut config = Config::default();+ config.server.data_dir = dir.path().to_string_lossy().into_owned();+ let engine = crate::Engine::new(config).unwrap();+ engine+ .create_index("publication-hook", Schema::empty())+ .unwrap();+ let idx = engine.get_index("publication-hook").unwrap();++ let initial = idx+ .index_document(Some("same".into()), json!({"state": "initial"}))+ .await+ .unwrap();++ let acquired = Arc::new(AtomicUsize::new(0));+ let pause_once = Arc::new(AtomicBool::new(false));+ let (paused_tx, paused_rx) = std::sync::mpsc::sync_channel(1);+ let (resume_tx, resume_rx) = std::sync::mpsc::sync_channel(1);+ let paused_tx = parking_lot::Mutex::new(Some(paused_tx));+ let resume_rx = parking_lot::Mutex::new(Some(resume_rx));+ let hook: PublicationTestHook = {+ let acquired = Arc::clone(&acquired);+ let pause_once = Arc::clone(&pause_once);+ Arc::new(move |id, point| {+ assert_eq!(id, "same");+ if point == PublicationTestPoint::Acquired {+ acquired.fetch_add(1, Ordering::SeqCst);+ }+ if point == PublicationTestPoint::AfterWalVersionMap+ && !pause_once.swap(true, Ordering::SeqCst)+ {+ paused_tx.lock().take().unwrap().send(()).unwrap();+ resume_rx.lock().take().unwrap().recv().unwrap();+ }+ })+ };+ idx.set_publication_test_hook(Some(hook));++ let put = {+ let idx = Arc::clone(&idx);+ tokio::spawn(async move {+ idx.index_document_with_version(+ Some("same".into()),+ json!({"state": "put"}),+ Some(initial.seq_no),+ Some(1),+ )+ .await+ })+ };+ tokio::task::spawn_blocking(move || paused_rx.recv().unwrap())+ .await+ .unwrap();+ assert_eq!(acquired.load(Ordering::SeqCst), 1);++ let (queued_tx, queued_rx) = std::sync::mpsc::sync_channel(1);+ let queued_tx = Arc::new(parking_lot::Mutex::new(Some(queued_tx)));+ idx.write_publication.set_before_mutex_await_hook({+ let queued_tx = Arc::clone(&queued_tx);+ Some(Arc::new(move |id| {+ assert_eq!(id, "same");+ queued_tx.lock().take().unwrap().send(()).unwrap();+ }))+ });+ let delete = {+ let idx = Arc::clone(&idx);+ tokio::spawn(async move { idx.delete_document_versioned("same", None, None).await })+ };+ tokio::task::spawn_blocking(move || queued_rx.recv().unwrap())+ .await+ .unwrap();+ idx.write_publication.set_before_mutex_await_hook(None);+ assert_eq!(+ acquired.load(Ordering::SeqCst),+ 1,+ "delete acquired the same key while PUT was paused after WAL/VM"+ );++ resume_tx.send(()).unwrap();+ let put = put.await.unwrap().unwrap();+ let delete = delete.await.unwrap().unwrap();+ idx.set_publication_test_hook(None);++ assert_eq!(put.version, 2);+ assert!(delete.found);+ assert_eq!(delete.version, 3);+ assert!(delete.seq_no > put.seq_no);+ assert!(idx.get_document("same").await.unwrap().is_none());+ assert_eq!(acquired.load(Ordering::SeqCst), 2);+ }+}diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex 2499e5601..1bb665b5e 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -28,6 +28,7 @@ pub mod rbac;pub mod slow_query;pub mod sql;pub mod turbo_ingest;+mod write_publication;// ── Re-exports ────────────────────────────────────────────────────────────────diff --git a/engine/crates/xerj-engine/src/write_publication.rs b/engine/crates/xerj-engine/src/write_publication.rsnew file mode 100644index 000000000..6e668b6ea--- /dev/null+++ b/engine/crates/xerj-engine/src/write_publication.rs@@ -0,0 +1,290 @@+//! Exact keyed ordering for document publication.+//!+//! A key exists in the registry only while a holder or waiter owns a strong+//! reference to its mutex. The registry keeps a `Weak`, so idle document IDs+//! do not accumulate forever.++use std::sync::{Arc, Weak};++use dashmap::mapref::entry::Entry;+use dashmap::DashMap;+use tokio::sync::{Mutex, OwnedMutexGuard};++#[derive(Default)]+pub(crate) struct WritePublicationCoordinator {+ locks: DashMap<String, Weak<Mutex<()>>>,+ #[cfg(test)]+ before_mutex_await: parking_lot::RwLock<Option<Arc<dyn Fn(&str) + Send + Sync + 'static>>>,+}++pub(crate) struct WritePublicationGuard {+ coordinator: Arc<WritePublicationCoordinator>,+ key: String,+ lock: Arc<Mutex<()>>,+ guard: Option<OwnedMutexGuard<()>>,+}++impl WritePublicationCoordinator {+ pub(crate) fn new() -> Arc<Self> {+ Arc::new(Self::default())+ }++ pub(crate) async fn lock(self: &Arc<Self>, key: impl Into<String>) -> WritePublicationGuard {+ self.lock_inner(key.into(), None).await+ }++ async fn lock_inner(+ self: &Arc<Self>,+ key: String,+ before_await: Option<Box<dyn FnOnce() + Send>>,+ ) -> WritePublicationGuard {+ let lock = match self.locks.entry(key.clone()) {+ Entry::Occupied(mut occupied) => match occupied.get().upgrade() {+ Some(lock) => lock,+ None => {+ let lock = Arc::new(Mutex::new(()));+ occupied.insert(Arc::downgrade(&lock));+ lock+ }+ },+ Entry::Vacant(vacant) => {+ let lock = Arc::new(Mutex::new(()));+ vacant.insert(Arc::downgrade(&lock));+ lock+ }+ };+ // Runs after the registry entry guard is gone and immediately before+ // queueing. Tests use this handshake to cancel a known waiter without+ // sleeps or scheduler guesses.+ if let Some(before_await) = before_await {+ before_await();+ }+ #[cfg(test)]+ {+ let hook = self.before_mutex_await.read().clone();+ if let Some(hook) = hook {+ hook(&key);+ }+ }+ let guard = Arc::clone(&lock).lock_owned().await;+ WritePublicationGuard {+ coordinator: Arc::clone(self),+ key,+ lock,+ guard: Some(guard),+ }+ }++ #[cfg(test)]+ async fn lock_with_before_await(+ self: &Arc<Self>,+ key: impl Into<String>,+ before_await: impl FnOnce() + Send + 'static,+ ) -> WritePublicationGuard {+ self.lock_inner(key.into(), Some(Box::new(before_await)))+ .await+ }++ /// Acquire a deadlock-free set of exact document keys.+ ///+ /// Sorting gives every caller one global acquisition order; deduplication+ /// prevents a request from waiting on its own non-reentrant key.+ #[allow(dead_code)]+ pub(crate) async fn lock_many<I, S>(self: &Arc<Self>, keys: I) -> Vec<WritePublicationGuard>+ where+ I: IntoIterator<Item = S>,+ S: Into<String>,+ {+ let mut keys: Vec<String> = keys.into_iter().map(Into::into).collect();+ keys.sort_unstable();+ keys.dedup();++ let mut guards = Vec::with_capacity(keys.len());+ for key in keys {+ guards.push(self.lock(key).await);+ }+ guards+ }++ #[cfg(test)]+ fn registry_len(&self) -> usize {+ self.locks.len()+ }++ #[cfg(test)]+ pub(crate) fn set_before_mutex_await_hook(+ &self,+ hook: Option<Arc<dyn Fn(&str) + Send + Sync + 'static>>,+ ) {+ *self.before_mutex_await.write() = hook;+ }+}++impl Drop for WritePublicationGuard {+ fn drop(&mut self) {+ // Release the mutex before attempting registry cleanup. Any queued+ // waiter already owns another strong Arc and therefore prevents+ // removal below.+ self.guard.take();++ if let Entry::Occupied(occupied) = self.coordinator.locks.entry(self.key.clone()) {+ let is_same = occupied+ .get()+ .upgrade()+ .map(|registered| Arc::ptr_eq(®istered, &self.lock))+ .unwrap_or(false);+ if is_same && Arc::strong_count(&self.lock) == 1 {+ occupied.remove();+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::time::Duration;++ #[tokio::test]+ async fn same_key_is_strictly_ordered_and_cleans_up() {+ let coordinator = WritePublicationCoordinator::new();+ let first = coordinator.lock("same").await;+ let (attempt_tx, attempt_rx) = tokio::sync::oneshot::channel();+ let (acquired_tx, mut acquired_rx) = tokio::sync::oneshot::channel();++ let task = {+ let coordinator = Arc::clone(&coordinator);+ tokio::spawn(async move {+ attempt_tx.send(()).unwrap();+ let _second = coordinator.lock("same").await;+ acquired_tx.send(()).unwrap();+ })+ };+ attempt_rx.await.unwrap();+ assert!(+ acquired_rx.try_recv().is_err(),+ "same key entered before the first guard was released"+ );+ assert_eq!(coordinator.registry_len(), 1);++ drop(first);+ acquired_rx.await.unwrap();+ task.await.unwrap();+ assert_eq!(coordinator.registry_len(), 0);+ }++ #[tokio::test]+ async fn disjoint_keys_do_not_block_each_other() {+ let coordinator = WritePublicationCoordinator::new();+ let _a = coordinator.lock("a").await;+ tokio::time::timeout(Duration::from_millis(100), coordinator.lock("b"))+ .await+ .expect("unrelated key must not wait");+ }++ #[tokio::test]+ async fn lock_many_sorts_deduplicates_and_cleans_up() {+ let coordinator = WritePublicationCoordinator::new();+ let guards = coordinator.lock_many(["c", "a", "b", "a"]).await;+ assert_eq!(guards.len(), 3);+ assert_eq!(coordinator.registry_len(), 3);+ drop(guards);+ assert_eq!(coordinator.registry_len(), 0);+ }++ #[tokio::test]+ async fn registry_is_bounded_by_live_keys_not_historical_keys() {+ let coordinator = WritePublicationCoordinator::new();+ for i in 0..10_000 {+ let guard = coordinator.lock(format!("historical-{i}")).await;+ drop(guard);+ }+ assert_eq!(+ coordinator.registry_len(),+ 0,+ "idle document IDs must not remain in the registry"+ );+ }++ #[tokio::test]+ async fn cancellation_and_failure_style_early_return_release_key() {+ async fn fail_after_lock(+ coordinator: Arc<WritePublicationCoordinator>,+ ) -> Result<(), &'static str> {+ let _guard = coordinator.lock("wal-failure").await;+ Err("injected WAL failure")+ }++ let coordinator = WritePublicationCoordinator::new();+ assert_eq!(+ fail_after_lock(Arc::clone(&coordinator)).await,+ Err("injected WAL failure")+ );+ assert_eq!(coordinator.registry_len(), 0);+ tokio::time::timeout(Duration::from_millis(100), coordinator.lock("wal-failure"))+ .await+ .expect("key leaked after early error");+ }++ #[tokio::test]+ async fn cancelling_a_queued_waiter_does_not_leak_or_wedge_the_key() {+ let coordinator = WritePublicationCoordinator::new();+ let first = coordinator.lock("cancelled").await;+ let (attempt_tx, attempt_rx) = tokio::sync::oneshot::channel();+ let waiter = {+ let coordinator = Arc::clone(&coordinator);+ tokio::spawn(async move {+ let _guard = coordinator+ .lock_with_before_await("cancelled", move || {+ attempt_tx.send(()).unwrap();+ })+ .await;+ })+ };+ attempt_rx.await.unwrap();+ waiter.abort();+ assert!(waiter.await.unwrap_err().is_cancelled());+ drop(first);++ let guard = coordinator.lock("cancelled").await;+ drop(guard);+ assert_eq!(coordinator.registry_len(), 0);+ }++ #[tokio::test]+ async fn reversed_multi_key_requests_complete_without_deadlock() {+ let coordinator = WritePublicationCoordinator::new();+ let start = Arc::new(tokio::sync::Barrier::new(3));+ let left = {+ let coordinator = Arc::clone(&coordinator);+ let start = Arc::clone(&start);+ tokio::spawn(async move {+ start.wait().await;+ let guards = coordinator.lock_many(["b", "a"]).await;+ tokio::task::yield_now().await;+ drop(guards);+ })+ };+ let right = {+ let coordinator = Arc::clone(&coordinator);+ let start = Arc::clone(&start);+ tokio::spawn(async move {+ start.wait().await;+ let guards = coordinator.lock_many(["a", "b"]).await;+ tokio::task::yield_now().await;+ drop(guards);+ })+ };+ start.wait().await;++ tokio::time::timeout(Duration::from_secs(1), left)+ .await+ .expect("sorted acquisition deadlocked")+ .unwrap();+ tokio::time::timeout(Duration::from_secs(1), right)+ .await+ .expect("second sorted acquisition stayed wedged")+ .unwrap();+ assert_eq!(coordinator.registry_len(), 0);+ }+}diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rsindex cc3b2f81a..7b2252fe9 100644--- a/engine/crates/xerj-engine/tests/integration.rs+++ b/engine/crates/xerj-engine/tests/integration.rs@@ -5044,6 +5044,259 @@ async fn test_semantic_text_bulk_preserves_item_order_status_and_vectors() {assert_eq!(b["content_vector"].as_array().unwrap().len(), 16);}+#[tokio::test]+async fn test_put_delete_recreate_publication_versions_and_visibility() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine+ .create_index("publication-order", Schema::empty())+ .unwrap();+ let idx = engine.get_index("publication-order").unwrap();++ let first = idx+ .index_document(Some("same".into()), json!({"state": "first"}))+ .await+ .unwrap();+ assert_eq!(first.result, "created");+ assert_eq!(first.version, 1);++ let deleted = idx+ .delete_document_versioned("same", None, None)+ .await+ .unwrap();+ assert!(deleted.found);+ assert_eq!(deleted.version, 2);+ assert!(deleted.seq_no > first.seq_no);+ assert!(idx.get_document("same").await.unwrap().is_none());++ let recreated = idx+ .index_document(Some("same".into()), json!({"state": "recreated"}))+ .await+ .unwrap();+ assert_eq!(recreated.result, "created");+ assert_eq!(recreated.version, 3);+ assert!(recreated.seq_no > deleted.seq_no);+ assert_eq!(+ idx.get_document("same").await.unwrap().unwrap()["state"],+ "recreated"+ );++ idx.flush().await.unwrap();+ assert_eq!(+ idx.get_document("same").await.unwrap().unwrap()["state"],+ "recreated",+ "latest publication must survive flush"+ );+}++#[tokio::test]+async fn test_conditional_put_and_delete_same_id_linearize_at_cas() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine+ .create_index("publication-race", Schema::empty())+ .unwrap();+ let idx = engine.get_index("publication-race").unwrap();++ for round in 0..32 {+ let id = format!("same-{round}");+ let initial = idx+ .index_document(Some(id.clone()), json!({"winner": "initial"}))+ .await+ .unwrap();+ let expected_seq = initial.seq_no;+ let start = std::sync::Arc::new(tokio::sync::Barrier::new(3));++ let put = {+ let idx = std::sync::Arc::clone(&idx);+ let id = id.clone();+ let start = std::sync::Arc::clone(&start);+ tokio::spawn(async move {+ start.wait().await;+ idx.index_document_with_version(+ Some(id),+ json!({"winner": "put"}),+ Some(expected_seq),+ Some(1),+ )+ .await+ })+ };+ let delete = {+ let idx = std::sync::Arc::clone(&idx);+ let id = id.clone();+ let start = std::sync::Arc::clone(&start);+ tokio::spawn(async move {+ start.wait().await;+ idx.delete_document_versioned(&id, Some(expected_seq), Some(1))+ .await+ })+ };+ start.wait().await;++ let put = put.await.unwrap();+ let delete = delete.await.unwrap();+ assert_eq!(+ put.is_ok() as u8 + delete.is_ok() as u8,+ 1,+ "exactly one operation may consume the same CAS precondition"+ );++ if let Ok(response) = put {+ assert_eq!(response.version, 2);+ assert_eq!(+ idx.get_document(&id).await.unwrap().unwrap()["winner"],+ "put"+ );+ } else {+ let outcome = delete.unwrap();+ assert!(outcome.found);+ assert_eq!(outcome.version, 2);+ assert!(idx.get_document(&id).await.unwrap().is_none());+ }+ }+}++#[tokio::test]+async fn test_concurrent_create_and_updates_share_exact_publication_key() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine+ .create_index("publication-create-update", Schema::empty())+ .unwrap();+ let idx = engine.get_index("publication-create-update").unwrap();++ let start = std::sync::Arc::new(tokio::sync::Barrier::new(17));+ let mut creates = Vec::new();+ for writer in 0..16 {+ let idx = std::sync::Arc::clone(&idx);+ let start = std::sync::Arc::clone(&start);+ creates.push(tokio::spawn(async move {+ start.wait().await;+ idx.create_document("same".into(), json!({"created_by": writer, "base": true}))+ .await+ }));+ }+ start.wait().await;+ let mut successes = 0;+ for task in creates {+ successes += task.await.unwrap().is_ok() as usize;+ }+ assert_eq!(successes, 1, "create-only admission must be linearized");++ let start = std::sync::Arc::new(tokio::sync::Barrier::new(17));+ let mut updates = Vec::new();+ for writer in 0..16 {+ let idx = std::sync::Arc::clone(&idx);+ let start = std::sync::Arc::clone(&start);+ updates.push(tokio::spawn(async move {+ start.wait().await;+ idx.update_document_with_upsert(+ "same",+ Some(json!({(format!("field_{writer}")): writer})),+ None,+ false,+ )+ .await+ }));+ }+ start.wait().await;+ for task in updates {+ task.await.unwrap().unwrap().unwrap();+ }++ let source = idx.get_document("same").await.unwrap().unwrap();+ for writer in 0..16 {+ assert_eq!(source[format!("field_{writer}")], writer);+ }++ let changed = idx+ .update_document("same", json!({"stable": "value"}))+ .await+ .unwrap()+ .unwrap();+ let noop = idx+ .update_document_with_upsert("same", Some(json!({"stable": "value"})), None, false)+ .await+ .unwrap()+ .unwrap();+ assert_eq!(noop.result, "noop");+ assert_eq!(noop.seq_no, changed.seq_no);+ assert_eq!(noop.version, changed.version);++ let upsert_start = std::sync::Arc::new(tokio::sync::Barrier::new(3));+ let mut upserts = Vec::new();+ for field in ["left", "right"] {+ let idx = std::sync::Arc::clone(&idx);+ let start = std::sync::Arc::clone(&upsert_start);+ upserts.push(tokio::spawn(async move {+ start.wait().await;+ idx.update_document_with_upsert("missing", Some(json!({(field): true})), None, true)+ .await+ }));+ }+ upsert_start.wait().await;+ for task in upserts {+ task.await.unwrap().unwrap().unwrap();+ }+ let upserted = idx.get_document("missing").await.unwrap().unwrap();+ assert_eq!(upserted["left"], true);+ assert_eq!(upserted["right"], true);+}++#[tokio::test]+async fn test_concurrent_external_versions_publish_highest_source() {+ let dir = TempDir::new().unwrap();+ let engine = make_engine(&dir);+ engine+ .create_index("publication-external", Schema::empty())+ .unwrap();+ let idx = engine.get_index("publication-external").unwrap();+ idx.index_document_external(Some("same".into()), json!({"external": 1}), 1, "external")+ .await+ .unwrap();++ let start = std::sync::Arc::new(tokio::sync::Barrier::new(3));+ let mut tasks = Vec::new();+ for version in [2_u64, 3] {+ let idx = std::sync::Arc::clone(&idx);+ let start = std::sync::Arc::clone(&start);+ tasks.push(tokio::spawn(async move {+ start.wait().await;+ (+ version,+ idx.index_document_external(+ Some("same".into()),+ json!({"external": version}),+ version,+ "external",+ )+ .await,+ )+ }));+ }+ start.wait().await;+ let mut version_three_succeeded = false;+ for task in tasks {+ let (requested, result) = task.await.unwrap();+ if requested == 3 {+ assert_eq!(result.unwrap().version, 3);+ version_three_succeeded = true;+ }+ }+ assert!(version_three_succeeded);+ assert_eq!(+ idx.get_document("same").await.unwrap().unwrap()["external"],+ 3+ );+ assert!(+ idx.index_document_external(Some("same".into()), json!({"external": 2}), 2, "external",)+ .await+ .is_err(),+ "lower external version must remain rejected"+ );+}+#[cfg(feature = "onnx-experimental")]#[tokio::test]async fn test_semantic_bulk_preserves_onnx_admission_429() {