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(engine): serialize scripted read-modify-write publication

bugerdc24130cc961
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 4aad9f178..85d44a595 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -12683,56 +12683,48 @@ pub async fn update_doc(
if src.is_empty() {
return update_script_bad_request("script source is required".to_string());
}
- match idx.get_document(&id).await {
- Ok(Some(mut current)) => {
- if let Err(e) = apply_painless_update(&mut current, &src, &params) {
- return update_script_bad_request(e);
- }
- return match idx.index_document(Some(id.clone()), current).await {
- Ok(resp) => {
- state.metrics.record_doc_indexed(&index);
- let er = crate::responses::EsDocResponse::updated(
- &index,
- &resp.id,
- resp.version,
- resp.seq_no.saturating_sub(1),
- );
- Json(er).into_response()
- }
- Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
+ let upsert_body = body.upsert.clone().or_else(|| {
+ if body.doc_as_upsert {
+ body.doc.clone()
+ } else {
+ None
+ }
+ });
+ match idx
+ .transform_document_serialized(&id, upsert_body, move |mut current| {
+ apply_painless_update(&mut current, &src, &params)?;
+ Ok::<_, String>(current)
+ })
+ .await
+ {
+ Ok(Ok(Some(outcome))) => {
+ state.metrics.record_doc_indexed(&index);
+ let resp = outcome.response;
+ let er = if outcome.created {
+ crate::responses::EsDocResponse::created(
+ &index,
+ &resp.id,
+ resp.version,
+ resp.seq_no.saturating_sub(1),
+ )
+ } else {
+ crate::responses::EsDocResponse::updated(
+ &index,
+ &resp.id,
+ resp.version,
+ resp.seq_no.saturating_sub(1),
+ )
};
+ return Json(er).into_response();
}
- Ok(None) => {
- // Document missing: honour `upsert` / `doc_as_upsert` by
- // indexing the upsert body as a new document. The script is
- // not run against the upsert body (matches ES default,
- // scripted_upsert=false).
- let upsert_body = body.upsert.clone().or_else(|| {
- if body.doc_as_upsert {
- body.doc.clone()
- } else {
- None
- }
- });
- if let Some(up) = upsert_body {
- return match idx.index_document(Some(id.clone()), up).await {
- Ok(resp) => {
- state.metrics.record_doc_indexed(&index);
- let er = crate::responses::EsDocResponse::created(
- &index,
- &resp.id,
- resp.version,
- resp.seq_no.saturating_sub(1),
- );
- Json(er).into_response()
- }
- Err(e) => ApiError::new(xerj_common::XerjError::from(e)).into_response(),
- };
- }
+ Ok(Ok(None)) => {
let e = xerj_common::XerjError::document_not_found(&id, &index);
return ApiError::new(e).into_response();
}
- Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),
+ Ok(Err(error)) => return update_script_bad_request(error),
+ Err(error) => {
+ return ApiError::new(xerj_common::XerjError::from(error)).into_response();
+ }
}
}
@@ -17354,29 +17346,44 @@ async fn run_update_by_query(
if hit.source.is_null() {
continue;
}
- let mut source = hit.source;
if let Some((src, params)) = script.as_ref() {
- if !src.is_empty() {
- if let Err(e) = apply_painless_update(&mut source, src, params) {
+ if src.is_empty() {
+ failures.push(json!({
+ "id": hit.id,
+ "cause": { "reason": "script source is required" },
+ }));
+ continue;
+ }
+ let result = idx
+ .transform_document_serialized(&hit.id, None, |mut current| {
+ apply_painless_update(&mut current, src, params)?;
+ Ok::<_, String>(current)
+ })
+ .await;
+ match result {
+ Ok(Ok(Some(_))) => updated += 1,
+ Ok(Ok(None)) => {}
+ Ok(Err(error)) => failures.push(json!({
+ "id": hit.id,
+ "cause": { "reason": error },
+ })),
+ Err(error) => failures.push(json!({
+ "id": hit.id,
+ "cause": { "reason": error.to_string() },
+ })),
+ }
+ } else {
+ // No script: preserve the historical re-index-in-place behavior.
+ match idx.index_document(Some(hit.id.clone()), hit.source).await {
+ Ok(_) => updated += 1,
+ Err(e) => {
failures.push(json!({
"id": hit.id,
- "cause": { "reason": e },
+ "cause": { "reason": e.to_string() },
}));
- continue;
}
}
}
- // Re-index in place: same `_id`, mutated source → an update, not an
- // append (verified: `index_document(Some(existing_id), source)`).
- match idx.index_document(Some(hit.id.clone()), source).await {
- Ok(_) => updated += 1,
- Err(e) => {
- failures.push(json!({
- "id": hit.id,
- "cause": { "reason": e.to_string() },
- }));
- }
- }
}
let took = started.elapsed().as_millis() as u64;
@@ -17396,6 +17403,102 @@ async fn run_update_by_query(
})
}
+#[cfg(test)]
+mod scripted_update_publication_tests {
+ use super::*;
+ use std::sync::Arc;
+ use xerj_common::{
+ config::{Config, WalSync},
+ metrics::Metrics,
+ };
+ use xerj_engine::Engine;
+
+ fn test_state() -> AppState {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.keep();
+ let mut config = Config::default();
+ config.server.data_dir = path.to_string_lossy().into_owned();
+ config.storage.wal_sync = WalSync::Async;
+ let metrics = Metrics::new().expect("metrics");
+ let engine = Engine::new(config.clone()).expect("engine");
+ AppState::new(config, engine, metrics)
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn concurrent_scripted_update_requests_preserve_every_increment() {
+ let state = test_state();
+ let idx = state.engine.get_or_create_index("script-counter").unwrap();
+ idx.index_document(Some("counter".into()), json!({"n": 0}))
+ .await
+ .unwrap();
+
+ let start = Arc::new(tokio::sync::Barrier::new(33));
+ let mut tasks = Vec::new();
+ for _ in 0..32 {
+ let state = state.clone();
+ let start = Arc::clone(&start);
+ tasks.push(tokio::spawn(async move {
+ start.wait().await;
+ update_doc(
+ State(state),
+ Path(("script-counter".to_string(), "counter".to_string())),
+ Query(UpdateDocParams::default()),
+ Json(EsUpdateBody {
+ doc: None,
+ doc_as_upsert: false,
+ upsert: None,
+ script: Some(json!("ctx._source.n += 1")),
+ detect_noop: None,
+ }),
+ )
+ .await
+ .into_response()
+ .status()
+ }));
+ }
+ start.wait().await;
+ for task in tasks {
+ assert!(task.await.unwrap().is_success());
+ }
+
+ assert_eq!(idx.get_document("counter").await.unwrap().unwrap()["n"], 32);
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn concurrent_scripted_update_by_query_preserves_every_increment() {
+ let state = test_state();
+ let idx = state
+ .engine
+ .get_or_create_index("script-query-counter")
+ .unwrap();
+ idx.index_document(Some("counter".into()), json!({"n": 0}))
+ .await
+ .unwrap();
+
+ let start = Arc::new(tokio::sync::Barrier::new(17));
+ let mut tasks = Vec::new();
+ for _ in 0..16 {
+ let idx = Arc::clone(&idx);
+ let start = Arc::clone(&start);
+ tasks.push(tokio::spawn(async move {
+ start.wait().await;
+ run_update_by_query(
+ &idx,
+ &xerj_query::SearchRequest::default(),
+ Some(("ctx._source.n += 1".into(), json!({}))),
+ )
+ .await
+ }));
+ }
+ start.wait().await;
+ for task in tasks {
+ assert_eq!(task.await.unwrap()["failures"], json!([]));
+ }
+
+ assert_eq!(idx.get_document("counter").await.unwrap().unwrap()["n"], 16);
+ }
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// GET /_cat/aliases
// ─────────────────────────────────────────────────────────────────────────────
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 64c3f1291..a75932afe 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -172,6 +172,14 @@ pub struct IndexResponse {
pub result: String,
}
+/// Result of a same-ID serialized read-transform-write operation.
+#[derive(Debug, Clone)]
+pub struct SerializedDocumentUpdate {
+ pub response: IndexResponse,
+ /// `true` when the supplied upsert body created a previously missing ID.
+ pub created: bool,
+}
+
/// Outcome of a single-document delete (ES `DELETE /{index}/_doc/{id}`).
///
/// `found == true` → the doc was live and is now tombstoned; `seq_no` is
@@ -4041,6 +4049,54 @@ impl Index {
}
}
+ /// Serialize the load, transform, and publication of one document ID.
+ ///
+ /// The exact-ID publication guard spans the authoritative read, caller
+ /// transform, WAL/version-map update, FTS/HNSW publication, and response.
+ /// This is the engine boundary used by API-layer scripted updates: keeping
+ /// script evaluation outside this method turns `ctx._source.n += 1` into
+ /// an unguarded read-modify-write and loses concurrent increments.
+ ///
+ /// `transform` is called only for an existing source. If the ID is missing,
+ /// `upsert` is created without applying the transform (ES's default
+ /// `scripted_upsert=false` behavior); without an upsert this returns
+ /// `Ok(Ok(None))`. Transform errors are returned in the inner `Result`
+ /// without publishing a write.
+ pub async fn transform_document_serialized<E, F>(
+ &self,
+ id: &str,
+ upsert: Option<Value>,
+ transform: F,
+ ) -> Result<std::result::Result<Option<SerializedDocumentUpdate>, E>>
+ where
+ F: FnOnce(Value) -> std::result::Result<Value, E>,
+ {
+ let publication_guard = self.write_publication.lock(id.to_string()).await;
+ let (source, created) = match self.get_document(id).await? {
+ Some(existing) => match transform(existing) {
+ Ok(transformed) => (transformed, false),
+ Err(error) => return Ok(Err(error)),
+ },
+ None => match upsert {
+ Some(source) => (source, true),
+ None => return Ok(Ok(None)),
+ },
+ };
+ let response = self
+ .index_document_with_version_inner_guarded(
+ Some(id.to_string()),
+ source,
+ None,
+ None,
+ false,
+ Some(publication_guard),
+ false,
+ None,
+ )
+ .await?;
+ Ok(Ok(Some(SerializedDocumentUpdate { response, created })))
+ }
+
/// Scan a document for vector fields and insert them into the HNSW graph.
///
/// FIELD IDENTITY (see `hnsw_field`): one graph indexes exactly ONE
@@ -6187,8 +6243,6 @@ impl Index {
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
// the if_primary_term rationale).
let _ = if_primary_term;
@@ -6255,6 +6309,10 @@ impl Index {
});
}
+ // Invalidate response caches only once the OCC check has succeeded and
+ // the delete will mutate publication state. A rejected conditional
+ // delete must not make unrelated cached responses look stale.
+ self.dataset_version.fetch_add(1, Ordering::Release);
let deleted_seq = self.store.delete(id)?;
#[cfg(test)]
self.publication_test_point(id, PublicationTestPoint::AfterWalVersionMap);
@@ -26531,4 +26589,82 @@ mod write_publication_integration_tests {
assert!(idx.get_document("same").await.unwrap().is_none());
assert_eq!(acquired.load(Ordering::SeqCst), 2);
}
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
+ async fn concurrent_serialized_transforms_do_not_lose_read_modify_write_updates() {
+ 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("atomic-transform", Schema::empty())
+ .unwrap();
+ let idx = engine.get_index("atomic-transform").unwrap();
+ idx.index_document(Some("counter".into()), json!({"n": 0}))
+ .await
+ .unwrap();
+
+ let start = Arc::new(tokio::sync::Barrier::new(33));
+ let mut tasks = Vec::new();
+ for _ in 0..32 {
+ let idx = Arc::clone(&idx);
+ let start = Arc::clone(&start);
+ tasks.push(tokio::spawn(async move {
+ start.wait().await;
+ idx.transform_document_serialized("counter", None, |mut source| {
+ let n = source["n"].as_u64().unwrap();
+ source["n"] = json!(n + 1);
+ Ok::<_, ()>(source)
+ })
+ .await
+ .unwrap()
+ .unwrap()
+ .unwrap()
+ .response
+ }));
+ }
+ start.wait().await;
+ for task in tasks {
+ task.await.unwrap();
+ }
+
+ assert_eq!(idx.get_document("counter").await.unwrap().unwrap()["n"], 32);
+ }
+
+ #[tokio::test]
+ async fn rejected_conditional_delete_does_not_invalidate_query_cache_epoch() {
+ 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("delete-epoch", Schema::empty())
+ .unwrap();
+ let idx = engine.get_index("delete-epoch").unwrap();
+ let indexed = idx
+ .index_document(Some("doc".into()), json!({"live": true}))
+ .await
+ .unwrap();
+ let before = idx.dataset_version.load(Ordering::Acquire);
+
+ let error = idx
+ .delete_document_versioned("doc", Some(indexed.seq_no + 1), Some(1))
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("version conflict"));
+ assert_eq!(
+ idx.dataset_version.load(Ordering::Acquire),
+ before,
+ "rejected OCC delete must not invalidate cached responses"
+ );
+
+ idx.delete_document_versioned("doc", Some(indexed.seq_no), Some(1))
+ .await
+ .unwrap();
+ assert_eq!(
+ idx.dataset_version.load(Ordering::Acquire),
+ before + 1,
+ "successful delete invalidates cached responses exactly once"
+ );
+ }
}
diff --git a/engine/crates/xerj-engine/src/write_publication.rs b/engine/crates/xerj-engine/src/write_publication.rs
index 6e668b6ea..ea6770cb2 100644
--- a/engine/crates/xerj-engine/src/write_publication.rs
+++ b/engine/crates/xerj-engine/src/write_publication.rs
@@ -24,6 +24,17 @@ pub(crate) struct WritePublicationGuard {
guard: Option<OwnedMutexGuard<()>>,
}
+/// Owns the registry's strong reference while `lock_owned()` is pending.
+///
+/// This is deliberately separate from [`WritePublicationGuard`]: cancelling
+/// the acquire future never constructs a guard, so cleanup must live in a
+/// value that already exists before the `.await`.
+struct PendingLock {
+ coordinator: Arc<WritePublicationCoordinator>,
+ key: String,
+ lock: Option<Arc<Mutex<()>>>,
+}
+
impl WritePublicationCoordinator {
pub(crate) fn new() -> Arc<Self> {
Arc::new(Self::default())
@@ -66,7 +77,15 @@ impl WritePublicationCoordinator {
hook(&key);
}
}
- let guard = Arc::clone(&lock).lock_owned().await;
+ let mut pending = PendingLock {
+ coordinator: Arc::clone(self),
+ key: key.clone(),
+ lock: Some(lock),
+ };
+ let guard = Arc::clone(pending.lock.as_ref().expect("pending lock present"))
+ .lock_owned()
+ .await;
+ let lock = pending.lock.take().expect("pending lock present");
WritePublicationGuard {
coordinator: Arc::clone(self),
key,
@@ -120,6 +139,27 @@ impl WritePublicationCoordinator {
}
}
+fn remove_if_idle(coordinator: &WritePublicationCoordinator, key: &str, lock: &Arc<Mutex<()>>) {
+ if let Entry::Occupied(occupied) = coordinator.locks.entry(key.to_string()) {
+ let is_same = occupied
+ .get()
+ .upgrade()
+ .map(|registered| Arc::ptr_eq(&registered, lock))
+ .unwrap_or(false);
+ if is_same && Arc::strong_count(lock) == 1 {
+ occupied.remove();
+ }
+ }
+}
+
+impl Drop for PendingLock {
+ fn drop(&mut self) {
+ if let Some(lock) = self.lock.as_ref() {
+ remove_if_idle(&self.coordinator, &self.key, lock);
+ }
+ }
+}
+
impl Drop for WritePublicationGuard {
fn drop(&mut self) {
// Release the mutex before attempting registry cleanup. Any queued
@@ -127,16 +167,7 @@ impl Drop for WritePublicationGuard {
// 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(&registered, &self.lock))
- .unwrap_or(false);
- if is_same && Arc::strong_count(&self.lock) == 1 {
- occupied.remove();
- }
- }
+ remove_if_idle(&self.coordinator, &self.key, &self.lock);
}
}
@@ -246,9 +277,9 @@ mod tests {
assert!(waiter.await.unwrap_err().is_cancelled());
drop(first);
+ assert_eq!(coordinator.registry_len(), 0);
let guard = coordinator.lock("cancelled").await;
drop(guard);
- assert_eq!(coordinator.registry_len(), 0);
}
#[tokio::test]