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.

perf(xerj-autoindex): O(1) journal state writes and per-replay lookups

xerj-orgcc5f3a983e40
diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rs
index 8735268a4..5cd35e7db 100644
--- a/engine/crates/xerj-autoindex/src/state.rs
+++ b/engine/crates/xerj-autoindex/src/state.rs
@@ -1447,13 +1447,22 @@ impl Journal {
operation_id: &str,
state: crate::sync::SyncOperationState,
) -> Result<()> {
+ // This runs twice per replayed operation (Started, then Committed).
+ // The copy-on-write this used to do cloned the ENTIRE pending sync —
+ // desired manifest, every group, every operation — per state write,
+ // which on the 402,744-operation cve-records run was ~0.7 s of
+ // client CPU per file and a 5.7 GB client RSS (#1224). The durable
+ // journal line is the transaction boundary: validate the transition
+ // first (pure), append durably, and only then mutate the in-memory
+ // map. A crash between append and mutation loses nothing — the next
+ // open replays the journal, which now carries the event; a failed
+ // append returns before any mutation, same as the clone did.
let pending = self
.pending_sync
.as_ref()
.context("cannot record operation state without sync_begin")?;
let tx_id = pending.tx_id.clone();
- let mut candidate = pending.clone();
- candidate.apply_operation_state(&tx_id, operation_id, state.clone())?;
+ pending.validate_operation_state(&tx_id, operation_id, &state)?;
self.append_transaction(
&serde_json::json!({
"kind": "sync_operation_state",
@@ -1463,7 +1472,9 @@ impl Journal {
}),
"sync_operation_state",
)?;
- self.pending_sync = Some(candidate);
+ if let Some(pending) = self.pending_sync.as_mut() {
+ pending.record_operation_state(operation_id, state);
+ }
Ok(())
}
diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rs
index 97214371f..2d2fe541c 100644
--- a/engine/crates/xerj-autoindex/src/sync.rs
+++ b/engine/crates/xerj-autoindex/src/sync.rs
@@ -308,6 +308,47 @@ pub struct PendingSync {
pub operation_states: BTreeMap<String, SyncOperationState>,
#[serde(default)]
pub validated: bool,
+ /// Lazily-derived membership index over `operations`; never serialized.
+ /// See [`OperationIdIndex`] for why it exists.
+ #[serde(skip)]
+ operation_id_index: std::sync::OnceLock<OperationIdIndex>,
+}
+
+/// Derived, never-serialized membership index over
+/// [`PendingSync::operations`] (#1224).
+///
+/// Every journaled operation state event validates that its operation id
+/// belongs to the sync's plan, and a resumed run replays all of those events
+/// again on load. A linear scan per event makes both quadratic in the
+/// operation count; the index makes them O(1) after one build. `len` is the
+/// `operations` length the set was built from — nothing in production
+/// mutates the list after `PendingSync::new`, but the guard keeps a
+/// restructured struct answering correctly instead of trusting a stale set.
+#[derive(Debug, Clone, Default)]
+struct OperationIdIndex {
+ len: usize,
+ ids: std::collections::HashSet<String>,
+}
+
+impl OperationIdIndex {
+ fn build(operations: &[SyncOperation]) -> Self {
+ Self {
+ len: operations.len(),
+ ids: operations
+ .iter()
+ .map(|operation| operation.operation_id.clone())
+ .collect(),
+ }
+ }
+
+ fn contains(&self, operations: &[SyncOperation], operation_id: &str) -> bool {
+ if self.len != operations.len() {
+ return operations
+ .iter()
+ .any(|operation| operation.operation_id == operation_id);
+ }
+ self.ids.contains(operation_id)
+ }
}
impl PendingSync {
@@ -330,6 +371,7 @@ impl PendingSync {
operations,
operation_states: BTreeMap::new(),
validated: false,
+ operation_id_index: std::sync::OnceLock::new(),
};
pending.validate_against(base)?;
Ok(pending)
@@ -378,23 +420,37 @@ impl PendingSync {
tx_id: &str,
operation_id: &str,
state: SyncOperationState,
+ ) -> Result<()> {
+ self.validate_operation_state(tx_id, operation_id, &state)?;
+ self.record_operation_state(operation_id, state);
+ Ok(())
+ }
+
+ /// The pure half of [`Self::apply_operation_state`]: every rejection, no
+ /// mutation. The journal checks a state write here before making it
+ /// durable, then records in place only after the append succeeded, so a
+ /// failed append leaves memory exactly as it was without cloning the
+ /// whole pending sync per event (#1224).
+ pub fn validate_operation_state(
+ &self,
+ tx_id: &str,
+ operation_id: &str,
+ state: &SyncOperationState,
) -> Result<()> {
anyhow::ensure!(
self.tx_id == tx_id,
"operation state belongs to another sync"
);
anyhow::ensure!(
- self.operations
- .iter()
- .any(|operation| operation.operation_id == operation_id),
+ self.known_operation(operation_id),
"operation state references unknown operation {operation_id}"
);
let legal = match self.operation_states.get(operation_id) {
- None => state == SyncOperationState::Started,
+ None => *state == SyncOperationState::Started,
Some(previous) => {
- previous == &state
+ previous == state
|| previous == &SyncOperationState::Started
- && state == SyncOperationState::Committed
+ && state == &SyncOperationState::Committed
}
};
anyhow::ensure!(
@@ -402,9 +458,26 @@ impl PendingSync {
"illegal operation transition {:?} -> {state:?}",
self.operation_states.get(operation_id)
);
+ Ok(())
+ }
+
+ /// The mutating half of [`Self::apply_operation_state`]. Only meaningful
+ /// after [`Self::validate_operation_state`] accepted the same
+ /// transition.
+ pub fn record_operation_state(&mut self, operation_id: &str, state: SyncOperationState) {
self.operation_states
.insert(operation_id.to_string(), state);
- Ok(())
+ }
+
+ /// Membership of `operation_id` in this sync's plan. A corpus run
+ /// journals two state events per operation and replays every event
+ /// again on resume, so the linear scan this replaces is quadratic in
+ /// the run size — on the 402,744-operation cve-records build that scan
+ /// alone is minutes of client CPU (#1224).
+ fn known_operation(&self, operation_id: &str) -> bool {
+ self.operation_id_index
+ .get_or_init(|| OperationIdIndex::build(&self.operations))
+ .contains(&self.operations, operation_id)
}
pub fn all_operations_committed(&self) -> bool {
@@ -1401,6 +1474,94 @@ mod tests {
}
}
+ #[test]
+ fn operation_state_split_semantics_and_membership_index_hold() {
+ // #1224: the journal records Started/Committed per operation through
+ // validate-then-record, and a resumed run replays every state event
+ // again on load. Pin the split's semantics — validate is pure,
+ // apply is validate+record — and the derived membership index,
+ // including across Clone and across a restructured operations list.
+ let operations: Vec<SyncOperation> = (0..1000)
+ .map(|n| SyncOperation {
+ operation_id: format!("op-{n}"),
+ kind: SyncOperationKind::Upsert,
+ group_id: format!("g{n}"),
+ desired_content_id: Some(format!("content-{n}")),
+ })
+ .collect();
+ let mut pending = PendingSync {
+ tx_id: "tx".into(),
+ base_generation: 0,
+ base_manifest_digest: "base".into(),
+ desired_manifest_digest: "desired".into(),
+ operation_hash: "hash".into(),
+ desired: GenerationManifest {
+ generation: 1,
+ execution: None,
+ plan: Plan::default(),
+ groups: Vec::new(),
+ },
+ operations,
+ operation_states: BTreeMap::new(),
+ validated: false,
+ operation_id_index: std::sync::OnceLock::new(),
+ };
+
+ // Known ids validate, unknown ids stay rejected — through the index
+ // once built, and on a clone that inherited the built index.
+ assert!(pending
+ .validate_operation_state("tx", "op-0", &SyncOperationState::Started)
+ .is_ok());
+ assert!(pending
+ .validate_operation_state("tx", "missing", &SyncOperationState::Started)
+ .is_err());
+ let cloned = pending.clone();
+ assert!(cloned
+ .validate_operation_state("tx", "op-1", &SyncOperationState::Started)
+ .is_ok());
+ assert!(cloned
+ .validate_operation_state("tx", "missing", &SyncOperationState::Started)
+ .is_err());
+
+ // Transitions keep their pre-split rules: Committed without Started
+ // is illegal, Started then Committed is legal, a repeated Committed
+ // is accepted, and a step back to Started is not.
+ assert!(pending
+ .validate_operation_state("tx", "op-0", &SyncOperationState::Committed)
+ .is_err());
+ pending
+ .apply_operation_state("tx", "op-0", SyncOperationState::Started)
+ .unwrap();
+ pending
+ .apply_operation_state("tx", "op-0", SyncOperationState::Committed)
+ .unwrap();
+ pending
+ .apply_operation_state("tx", "op-0", SyncOperationState::Committed)
+ .unwrap();
+ assert!(pending
+ .validate_operation_state("tx", "op-0", &SyncOperationState::Started)
+ .is_err());
+
+ // A wrong tx is rejected and records nothing; validate alone never
+ // mutates.
+ assert!(pending
+ .apply_operation_state("other", "op-1", SyncOperationState::Started)
+ .is_err());
+ assert!(pending.operation_states.get("op-1").is_none());
+ assert!(pending
+ .validate_operation_state("tx", "op-2", &SyncOperationState::Committed)
+ .is_err());
+ assert!(pending.operation_states.get("op-2").is_none());
+
+ // A restructured operations list must not be answered from a stale
+ // index built for the old shape.
+ let mut shrunk = pending.clone();
+ shrunk.operations.clear();
+ assert!(shrunk
+ .validate_operation_state("tx", "op-3", &SyncOperationState::Started)
+ .is_err());
+ }
+
#[test]
fn durable_sync_begin_decoder_preserves_inferred_float_bits() {
let original = 245.44444444444446_f64;
diff --git a/engine/crates/xerj-autoindex/src/sync_executor.rs b/engine/crates/xerj-autoindex/src/sync_executor.rs
index 93c93c031..ab9eda3a1 100644
--- a/engine/crates/xerj-autoindex/src/sync_executor.rs
+++ b/engine/crates/xerj-autoindex/src/sync_executor.rs
@@ -407,6 +407,117 @@ fn panic_message(panic: Box<dyn std::any::Any + Send>) -> String {
}
}
+/// Per-replay id→position caches for the manifests and snapshot a replay
+/// walks (#1224).
+///
+/// `apply_shared` resolves every operation's group in the base and desired
+/// manifests and its content in the snapshot, and the linear `iter().find()`
+/// each resolution used is quadratic over a corpus run — the 402,744-operation
+/// cve-records build paid milliseconds of scanning per file. Built once per
+/// [`EsSyncBackend::replay_operations`] call from that call's arguments, so
+/// inside a replay every hit is exact. A lookup outside a replay (or against
+/// differently-shaped data than the cache was built from — guarded by the
+/// recorded lengths) falls back to the scan the cache replaced, and every hit
+/// is verified against the slice it answers from, so a stale cache can never
+/// return a group the scan would not have.
+#[derive(Debug, Clone, Default)]
+struct ReplayLookup {
+ base_len: usize,
+ base: std::collections::HashMap<String, usize>,
+ desired_len: usize,
+ desired: std::collections::HashMap<String, usize>,
+ files_len: usize,
+ files: std::collections::HashMap<String, usize>,
+}
+
+impl ReplayLookup {
+ fn build(
+ base: &crate::sync::CommittedManifest,
+ desired: &crate::sync::GenerationManifest,
+ snapshot: &SourceSnapshot,
+ ) -> Self {
+ Self {
+ base_len: base.groups.len(),
+ base: base
+ .groups
+ .iter()
+ .enumerate()
+ .map(|(position, group)| (group.group_id.clone(), position))
+ .collect(),
+ desired_len: desired.groups.len(),
+ desired: desired
+ .groups
+ .iter()
+ .enumerate()
+ .map(|(position, group)| (group.group_id.clone(), position))
+ .collect(),
+ files_len: snapshot.files.len(),
+ files: snapshot
+ .files
+ .iter()
+ .enumerate()
+ .map(|(position, file)| (file.content_id.clone(), position))
+ .collect(),
+ }
+ }
+
+ /// `groups` by id through a cache side, falling back to the scan when the
+ /// cache does not describe this exact slice.
+ fn group<'m, G>(
+ side: &std::collections::HashMap<String, usize>,
+ cached_len: usize,
+ groups: &'m [G],
+ group_id: &str,
+ id_of: impl Fn(&G) -> &str,
+ ) -> Option<&'m G> {
+ if cached_len != groups.len() {
+ return groups.iter().find(|group| id_of(group) == group_id);
+ }
+ side.get(group_id)
+ .copied()
+ .and_then(|position| groups.get(position))
+ .filter(|group| id_of(group) == group_id)
+ }
+
+ fn base_group<'m>(
+ &self,
+ base: &'m crate::sync::CommittedManifest,
+ group_id: &str,
+ ) -> Option<&'m crate::sync::ManifestGroup> {
+ Self::group(&self.base, self.base_len, &base.groups, group_id, |group| {
+ &group.group_id
+ })
+ }
+
+ fn desired_group<'m>(
+ &self,
+ desired: &'m crate::sync::GenerationManifest,
+ group_id: &str,
+ ) -> Option<&'m crate::sync::ManifestGroup> {
+ Self::group(
+ &self.desired,
+ self.desired_len,
+ &desired.groups,
+ group_id,
+ |group| &group.group_id,
+ )
+ }
+
+ fn file<'m>(&self, snapshot: &'m SourceSnapshot, content_id: &str) -> Option<&'m SnapshotFile> {
+ if self.files_len != snapshot.files.len() {
+ return snapshot
+ .files
+ .iter()
+ .find(|file| file.content_id == content_id);
+ }
+ self.files
+ .get(content_id)
+ .copied()
+ .and_then(|position| snapshot.files.get(position))
+ .filter(|file| file.content_id == content_id)
+ }
+}
+
/// Production ES-compatible operation backend for graph-disabled generations.
///
/// Upserts stream sealed index actions after removing both replaced and
@@ -418,6 +529,10 @@ pub struct EsSyncBackend<'a> {
es: &'a crate::esclient::Es,
state_dir: &'a Path,
bulk_bytes: usize,
+ /// #1224: per-replay lookup caches; empty outside
+ /// [`Self::replay_operations`], where every lookup falls back to the
+ /// linear scan this field exists to avoid. See [`ReplayLookup`].
+ lookup: ReplayLookup,
/// #755: the run's progress surface, so a legacy-catalog mapping warning
/// reaches the operator through the surface that owns stderr (#241) rather
/// than a bare `eprintln!` that `--progress none` cannot silence and
@@ -451,6 +566,7 @@ impl<'a> EsSyncBackend<'a> {
es,
state_dir,
bulk_bytes: bulk_bytes.max(64 * 1024),
+ lookup: ReplayLookup::default(),
pr,
installed_index_identity: None,
in_flight: None,
@@ -545,14 +661,8 @@ impl<'a> EsSyncBackend<'a> {
.is_some_and(|execution| !execution.graph_enabled),
"production incremental graph reconciliation is not enabled yet"
);
- let old = base
- .groups
- .iter()
- .find(|group| group.group_id == operation.group_id);
- let new = desired
- .groups
- .iter()
- .find(|group| group.group_id == operation.group_id);
+ let old = self.lookup.base_group(base, &operation.group_id);
+ let new = self.lookup.desired_group(desired, &operation.group_id);
match operation.kind {
crate::sync::SyncOperationKind::Delete => self.delete_group(
old.context("delete operation has no committed group")?,
@@ -578,7 +688,15 @@ impl<'a> EsSyncBackend<'a> {
}
fn replay_prepared(&self, snapshot: &SourceSnapshot, content_id: &str) -> Result<()> {
- let prepared = prepared_for(snapshot, content_id)?;
+ // Cache-first resolution of the sealed artifact (#1224): a linear
+ // scan of the snapshot's files per upsert is quadratic over a corpus
+ // run. Falls back to `prepared_for`'s scan when no replay cache
+ // describes this snapshot.
+ let prepared = self
+ .lookup
+ .file(snapshot, content_id)
+ .and_then(|file| file.prepared.as_ref())
+ .with_context(|| format!("content {content_id} has no sealed prepared artifact"))?;
let snapshot_dir = self.state_dir.join("sync-snapshots").join(&snapshot.tx_id);
let file = File::open(snapshot_dir.join(&prepared.relative_ndjson))?;
stream_ndjson_pairs(BufReader::new(file), self.bulk_bytes, |body| {
@@ -592,10 +710,9 @@ impl<'a> EsSyncBackend<'a> {
desired_group: &ManifestGroup,
) -> Result<()> {
let base_snapshot = open_committed_snapshot(self.state_dir, base)?;
- let old_group = base
- .groups
- .iter()
- .find(|group| group.group_id == desired_group.group_id)
+ let old_group = self
+ .lookup
+ .base_group(base, &desired_group.group_id)
.context("metadata operation has no committed group")?;
let prepared = prepared_for(&base_snapshot, &old_group.content_id)?;
let snapshot_dir = self
@@ -1023,6 +1140,9 @@ impl SyncOperationBackend for EsSyncBackend<'_> {
snapshot: &SourceSnapshot,
journal: &mut Journal,
) -> Result<()> {
+ // #1224: resolve per-operation groups and prepared artifacts through
+ // id indexes built once here, not a linear scan per operation.
+ self.lookup = ReplayLookup::build(base, desired, snapshot);
let width = self.replay_workers;
if width <= 1 || items.len() <= 1 {
return replay_serial(self, items, base, desired, snapshot, journal);