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(autoindex): replay durable sync floats exactly

bugereb25c0040762
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 23cc2c8fc..2043cfaff 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,6 +25,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
time with the action named** (400), instead of being stored with the action
silently dropped — the accepted-and-ignored class (#204). Executable ILM
actions are `rollover`, `delete`, `readonly`.
+- **`autoindex` no longer rejects a resumed generation after journal replay
+ when inferred floating-point schema statistics need exact decimal
+ round-tripping.** Unchanged reruns and junk-bearing corpus shrink now replay
+ correctly; existing affected journals resume without a rebuild, while the
+ manifest format and integrity checks remain unchanged.
### Added
diff --git a/engine/Cargo.lock b/engine/Cargo.lock
index eb9c46db3..a4910f9fb 100644
--- a/engine/Cargo.lock
+++ b/engine/Cargo.lock
@@ -6488,6 +6488,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
+ "simd-json",
"streaming-iterator",
"tempfile",
"tree-sitter",
diff --git a/engine/crates/xerj-autoindex/Cargo.toml b/engine/crates/xerj-autoindex/Cargo.toml
index a5c0d9849..5f4714caf 100644
--- a/engine/crates/xerj-autoindex/Cargo.toml
+++ b/engine/crates/xerj-autoindex/Cargo.toml
@@ -13,6 +13,9 @@ xerj-common = { path = "../xerj-common" }
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
+# Durable sync_begin replay needs exact decimal-to-f64 recovery without
+# selecting serde_json's slower float parser for the whole server binary.
+simd-json.workspace = true
chrono.workspace = true
regex = "1"
walkdir = "2"
diff --git a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
index ae70c788d..a1ab85d6a 100644
--- a/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
+++ b/engine/crates/xerj-autoindex/src/incremental_reconcile_http_tests.rs
@@ -1138,6 +1138,73 @@ fn a_junk_file_is_recorded_and_never_fatal() {
assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);
}
+#[test]
+fn issue_283_inferred_float_manifest_digest_replays_on_unchanged_rerun() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap();
+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ // 2,209 bytes / 9 records produces the exact inferred f64 which used to
+ // change from 245.44444444444446 to 245.44444444444449 on journal replay.
+ let mut csv = String::from("body\n");
+ for len in [245, 245, 245, 245, 245, 245, 245, 245, 249] {
+ csv.push_str(&"x".repeat(len));
+ csv.push('\n');
+ }
+ fs::write(corpus.path().join("data.csv"), csv).unwrap();
+ let endpoint = HttpEndpoint::start();
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+
+ let (first_code, first_summary) = run_index_report(config.clone()).unwrap();
+ assert_eq!(first_code, 0);
+ assert_eq!(first_summary.unwrap()["generation"], 1);
+
+ let (second_code, second_summary) = run_index_report(config).unwrap();
+ assert_eq!(second_code, 0);
+ assert_eq!(second_summary.unwrap()["generation"], 1);
+}
+
+#[test]
+fn issue_283_junk_bearing_generation_reconciles_a_shrinking_file_set() {
+ let _guard = HTTP_E2E_LOCK.lock().unwrap();
+ let _replay_guard = sync_executor::REPLAY_FAILPOINT_TEST_LOCK.lock().unwrap();
+ let corpus = tempfile::tempdir().unwrap();
+ let state_dir = tempfile::tempdir().unwrap();
+ // Preserve the inferred f64 from the original failure while exercising the
+ // user's actual second-run shape: generation one contains junk, then a
+ // tracked file disappears without any ignore-policy change.
+ let mut csv = String::from("body\n");
+ for len in [245, 245, 245, 245, 245, 245, 245, 245, 249] {
+ csv.push_str(&"x".repeat(len));
+ csv.push('\n');
+ }
+ fs::write(corpus.path().join("data.csv"), csv).unwrap();
+ fs::write(
+ corpus.path().join("remove.md"),
+ "# Temporary report\n\nThis file is removed before generation two.\n",
+ )
+ .unwrap();
+ fs::write(corpus.path().join("empty.csv"), "").unwrap();
+ let endpoint = HttpEndpoint::start();
+ let config = cfg(corpus.path(), state_dir.path(), &endpoint.url, false);
+
+ let (first_code, first_summary) = run_index_report(config.clone()).unwrap();
+ assert_eq!(first_code, 3, "generation one completes with recorded junk");
+ let first_summary = first_summary.unwrap();
+ assert_eq!(first_summary["generation"], 1);
+ assert_eq!(first_summary["files_junk"], 1);
+ assert_eq!(paths(&endpoint.data_docs()), ["data.csv", "remove.md"]);
+
+ fs::remove_file(corpus.path().join("remove.md")).unwrap();
+ let (second_code, second_summary) = run_index_report(config).unwrap();
+ assert_eq!(second_code, 3, "the smaller tree still records empty.csv");
+ let second_summary = second_summary.unwrap();
+ assert_eq!(second_summary["generation"], 2);
+ assert_eq!(second_summary["files_junk"], 1);
+ assert_eq!(paths(&endpoint.data_docs()), ["data.csv"]);
+ assert_eq!(journal_events(state_dir.path(), "sync_commit"), 2);
+}
+
/// Junk *records* were fatal on the generated path
/// (`durable preparation of X produced N junk records`) while the legacy path
/// merely accumulated them — directly contradicting the documented contract
diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rs
index 5bd21e261..511a74001 100644
--- a/engine/crates/xerj-autoindex/src/state.rs
+++ b/engine/crates/xerj-autoindex/src/state.rs
@@ -512,11 +512,10 @@ fn read_plan_for_preflight(
// preflight accepts. It cannot be treated as durable here.
break;
}
- let value: Value =
- serde_json::from_slice(bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice()))
- .with_context(|| {
- format!(
- "journal corruption at byte {record_start} in {}: malformed \
+ let record_bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice());
+ let value = crate::sync::decode_unique_durable_json(record_bytes).with_context(|| {
+ format!(
+ "journal corruption at byte {record_start} in {}: malformed \
newline-terminated record. Refusing to discard later records. Restore \
the journal from a backup, or truncate it to exactly {record_start} \
bytes to keep every completion recorded before the corruption. Deleting \
@@ -527,9 +526,9 @@ fn read_plan_for_preflight(
new --state-dir, new --prefix, and new --brain when graph detection \
is enabled (or --no-graph); explicitly validate and clean the shared \
catalog and old target",
- path.display()
- )
- })?;
+ path.display()
+ )
+ })?;
match value.get("kind").and_then(Value::as_str) {
Some("run") => {
let recorded_root = value.get("root").and_then(Value::as_str).unwrap_or("");
@@ -565,7 +564,12 @@ fn read_plan_for_preflight(
}
}
Some(kind) if crate::sync::is_sync_record_kind(kind) => {
- crate::sync::replay_record(&value, &mut committed_manifest, &mut pending_sync)?;
+ crate::sync::replay_durable_record(
+ &value,
+ record_bytes,
+ &mut committed_manifest,
+ &mut pending_sync,
+ )?;
if matches!(kind, "sync_bootstrap" | "sync_commit") {
plan = committed_manifest
.as_ref()
@@ -735,9 +739,8 @@ impl Journal {
break;
}
let newline_terminated = bytes.last() == Some(&b'\n');
- match serde_json::from_slice::<Value>(
- bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice()),
- ) {
+ let record_bytes = bytes.strip_suffix(b"\n").unwrap_or(bytes.as_slice());
+ match crate::sync::decode_unique_durable_json(record_bytes) {
Ok(v) if newline_terminated => {
valid_end += read as u64;
match v.get("kind").and_then(|k| k.as_str()) {
@@ -838,8 +841,9 @@ impl Journal {
embedding_identity_resumable = resumable;
}
Some(kind) if crate::sync::is_sync_record_kind(kind) => {
- crate::sync::replay_record(
+ crate::sync::replay_durable_record(
&v,
+ record_bytes,
&mut committed_manifest,
&mut pending_sync,
)?;
@@ -902,7 +906,7 @@ impl Journal {
Err(error) => {
anyhow::bail!(
"journal corruption at byte {record_start} in {}: malformed \
- newline-terminated record ({error}). Refusing to discard records \
+ newline-terminated record ({error:#}). Refusing to discard records \
after corruption. Restore the journal from a backup, or truncate it \
to exactly {record_start} bytes to keep every completion recorded \
before the corruption (files journaled after that point are \
@@ -1395,6 +1399,144 @@ mod sync_journal_tests {
.unwrap()
}
+ fn historical_issue_283_journal(sync_begin: &str) -> Vec<u8> {
+ let run = serde_json::json!({
+ "v": 1,
+ "kind": "run",
+ "root": "root",
+ "url": "url",
+ "prefix": "prefix",
+ "bulk_timeout_secs": 300,
+ "run_id": "run-issue-283-fixture",
+ "started": "2026-08-10T00:00:00Z"
+ });
+ let bootstrap = serde_json::json!({
+ "kind": "sync_bootstrap",
+ "manifest": crate::sync::CommittedManifest::genesis().unwrap(),
+ });
+ format!("{run}\n{bootstrap}\n{sync_begin}\n").into_bytes()
+ }
+
+ fn historical_issue_283_begin() -> String {
+ // Mechanical whitespace removal preserves the checked-in decimal
+ // token; parsing it here would erase the historical boundary.
+ include_str!("../tests/fixtures/issue_283_sync_begin.json")
+ .lines()
+ .collect()
+ }
+
+ fn assert_preflight_and_authoritative_open_reject(
+ valid_journal: &[u8],
+ invalid_journal: &[u8],
+ marker: &str,
+ ) {
+ let preflight_dir = tempfile::tempdir().unwrap();
+ std::fs::write(preflight_dir.path().join("journal.ndjson"), invalid_journal).unwrap();
+ let error = Journal::preflight(preflight_dir.path(), "root", "url", "prefix", false)
+ .err()
+ .expect("preflight must reject the raw durable mutation");
+ assert!(format!("{error:#}").contains(marker), "{error:#}");
+
+ // Pass preflight over valid bytes, then mutate the journal while its
+ // lock remains held. This directly exercises the authoritative replay
+ // in open_after_preflight rather than failing in preflight twice.
+ let open_dir = tempfile::tempdir().unwrap();
+ let path = open_dir.path().join("journal.ndjson");
+ std::fs::write(&path, valid_journal).unwrap();
+ let preflight =
+ Journal::preflight(open_dir.path(), "root", "url", "prefix", false).unwrap();
+ std::fs::write(&path, invalid_journal).unwrap();
+ let error = Journal::open_after_preflight(preflight, "root", "url", "prefix", 300, false)
+ .err()
+ .expect("authoritative open must reject the raw durable mutation");
+ assert!(format!("{error:#}").contains(marker), "{error:#}");
+ }
+
+ #[test]
+ fn raw_sync_begin_mutations_fail_at_preflight_and_authoritative_open() {
+ let begin = historical_issue_283_begin();
+ let valid = historical_issue_283_journal(&begin);
+ let cases = [
+ (
+ "desired payload",
+ begin.replacen("245.44444444444446", "245.44444444444449", 1),
+ "desired manifest digest does not match sync_begin payload",
+ ),
+ (
+ "operation list",
+ begin.replacen(
+ "\"operations\": []",
+ "\"operations\": [{\"operation_id\":\"delete:ghost\",\"kind\":\"delete\",\"group_id\":\"ghost\"}]",
+ 1,
+ ),
+ "sync operation list was not derived exactly",
+ ),
+ (
+ "desired digest",
+ begin.replacen(
+ "axm1-5e314eb29c9617433af240313b94e544",
+ "axm1-5e314eb29c9617433af240313b94e545",
+ 1,
+ ),
+ "desired manifest digest does not match sync_begin payload",
+ ),
+ (
+ "execution identity",
+ begin.replacen("\"chunker_identity\": \"chunker-v1\"", "\"chunker_identity\": \"chunker-v2\"", 1),
+ "desired manifest digest does not match sync_begin payload",
+ ),
+ ];
+ for (label, mutated, marker) in cases {
+ assert_ne!(mutated, begin, "mutation did not apply: {label}");
+ assert_preflight_and_authoritative_open_reject(
+ &valid,
+ &historical_issue_283_journal(&mutated),
+ marker,
+ );
+ }
+ }
+
+ #[test]
+ fn raw_content_identity_mutation_fails_at_preflight_and_authoritative_open() {
+ let source = tempfile::tempdir().unwrap();
+ let mut journal = journal_with_plan(source.path());
+ journal.sync_begin(&pending(&journal)).unwrap();
+ drop(journal);
+ let valid = std::fs::read(source.path().join("journal.ndjson")).unwrap();
+ let valid_text = String::from_utf8(valid.clone()).unwrap();
+ // Target only the ManifestGroup field. The plan's FileAssignment has
+ // the same digest text but a different following field.
+ let mutated_text = valid_text.replacen(
+ "\"content_digest\":\"digest-a\",\"content_size\":10,\"canonical\"",
+ "\"content_digest\":\"digest-b\",\"content_size\":10,\"canonical\"",
+ 1,
+ );
+ assert_ne!(mutated_text, valid_text, "content mutation did not apply");
+ assert_preflight_and_authoritative_open_reject(
+ &valid,
+ mutated_text.as_bytes(),
+ "plan canonical projection disagrees with manifest group",
+ );
+ }
+
+ #[test]
+ fn duplicate_kind_is_rejected_before_last_key_can_bypass_sync_routing() {
+ let valid = concat!(
+ "{\"v\":1,\"kind\":\"run\",\"root\":\"root\",\"url\":\"url\",",
+ "\"prefix\":\"prefix\",\"run_id\":\"valid\"}\n"
+ );
+ let duplicate = concat!(
+ "{\"v\":1,\"kind\":\"sync_begin\",\"kind\":\"run\",",
+ "\"root\":\"root\",\"url\":\"url\",\"prefix\":\"prefix\",",
+ "\"run_id\":\"ambiguous\"}\n"
+ );
+ assert_preflight_and_authoritative_open_reject(
+ valid.as_bytes(),
+ duplicate.as_bytes(),
+ "duplicate JSON object key \"kind\"",
+ );
+ }
+
#[test]
fn sync_begin_is_pending_and_never_promotes_the_committed_manifest() {
let _guard = SYNC_IO_FAILPOINT_TEST_LOCK.lock().unwrap();
diff --git a/engine/crates/xerj-autoindex/src/sync.rs b/engine/crates/xerj-autoindex/src/sync.rs
index 5be46c375..ef96ac3a0 100644
--- a/engine/crates/xerj-autoindex/src/sync.rs
+++ b/engine/crates/xerj-autoindex/src/sync.rs
@@ -6,9 +6,11 @@
use crate::state::{DuplicateFile, Plan};
use anyhow::{Context, Result};
+use serde::de::{DeserializeSeed, Error as _, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
+use std::fmt;
pub const EXECUTION_IDENTITY_VERSION: u32 = 2;
@@ -995,6 +997,155 @@ pub fn apply_begin(
Ok(())
}
+#[derive(Clone, Copy)]
+struct UniqueValue;
+
+impl<'de> DeserializeSeed<'de> for UniqueValue {
+ type Value = Value;
+
+ fn deserialize<D>(self, deserializer: D) -> std::result::Result<Value, D::Error>
+ where
+ D: serde::Deserializer<'de>,
+ {
+ deserializer.deserialize_any(self)
+ }
+}
+
+impl<'de> Visitor<'de> for UniqueValue {
+ type Value = Value;
+
+ fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ formatter.write_str("JSON without duplicate object keys")
+ }
+
+ fn visit_bool<E>(self, value: bool) -> std::result::Result<Value, E> {
+ Ok(Value::Bool(value))
+ }
+
+ fn visit_i64<E>(self, value: i64) -> std::result::Result<Value, E> {
+ Ok(Value::Number(value.into()))
+ }
+
+ fn visit_u64<E>(self, value: u64) -> std::result::Result<Value, E> {
+ Ok(Value::Number(value.into()))
+ }
+
+ fn visit_f64<E>(self, value: f64) -> std::result::Result<Value, E>
+ where
+ E: serde::de::Error,
+ {
+ serde_json::Number::from_f64(value)
+ .map(Value::Number)
+ .ok_or_else(|| E::custom("non-finite JSON number"))
+ }
+
+ fn visit_str<E>(self, value: &str) -> std::result::Result<Value, E>
+ where
+ E: serde::de::Error,
+ {
+ Ok(Value::String(value.to_owned()))
+ }
+
+ fn visit_string<E>(self, value: String) -> std::result::Result<Value, E> {
+ Ok(Value::String(value))
+ }
+
+ fn visit_none<E>(self) -> std::result::Result<Value, E> {
+ Ok(Value::Null)
+ }
+
+ fn visit_unit<E>(self) -> std::result::Result<Value, E> {
+ Ok(Value::Null)
+ }
+
+ fn visit_seq<A>(self, mut sequence: A) -> std::result::Result<Value, A::Error>
+ where
+ A: SeqAccess<'de>,
+ {
+ let mut values = Vec::new();
+ while let Some(value) = sequence.next_element_seed(self)? {
+ values.push(value);
+ }
+ Ok(Value::Array(values))
+ }
+
+ fn visit_map<A>(self, mut object: A) -> std::result::Result<Value, A::Error>
+ where
+ A: MapAccess<'de>,
+ {
+ let mut values = serde_json::Map::new();
+ while let Some(key) = object.next_key::<String>()? {
+ if values.contains_key(&key) {
+ return Err(A::Error::custom(format!(
+ "duplicate JSON object key {key:?}"
+ )));
+ }
+ values.insert(key, object.next_value_seed(self)?);
+ }
+ Ok(Value::Object(values))
+ }
+}
+
+pub(crate) fn decode_unique_durable_json(bytes: &[u8]) -> Result<Value> {
+ // Generic JSON maps accept duplicate keys with last-key semantics. A
+ // duplicate `kind` could otherwise make the ordinary routing decoder and
+ // an exact payload decoder disagree about which durable invariant applies;
+ // nested duplicates are equally ambiguous. Journal replay therefore
+ // rejects duplicates for every durable record before routing it.
+ let mut uniqueness = serde_json::Deserializer::from_slice(bytes);
+ let value = UniqueValue
+ .deserialize(&mut uniqueness)
+ .context("validate durable journal record structure")?;
+ uniqueness
+ .end()
+ .context("validate durable journal record trailing bytes")?;
+ Ok(value)
+}
+
+fn decode_durable_sync_begin_validated(bytes: &[u8]) -> Result<PendingSync> {
+ // simd-json 0.14.3 `src/serde.rs:56-62` deserializes directly from the
+ // supplied bytes. Restrict it to this persistence boundary: request and
+ // bulk JSON keep serde_json's default parser. The exact Value retains the
+ // original IEEE-754 bits when the ordinary parser lands on an adjacent
+ // value; conversion from Value into PendingSync performs no decimal parse.
+ let mut exact_bytes = bytes.to_vec();
+ let exact: Value = simd_json::serde::from_slice(&mut exact_bytes)
+ .context("decode durable sync_begin with exact floats")?;
+ anyhow::ensure!(
+ record_str(&exact, "kind")? == "sync_begin",
+ "exact durable decoder disagrees with sync_begin routing"
+ );
+ serde_json::from_value(exact).context("decode durable sync_begin payload")
+}
+
+#[cfg(test)]
+fn decode_durable_sync_begin(bytes: &[u8]) -> Result<PendingSync> {
+ decode_unique_durable_json(bytes)?;
+ decode_durable_sync_begin_validated(bytes)
+}
+
+pub(crate) fn replay_durable_record(
+ record: &Value,
+ bytes: &[u8],
+ committed: &mut Option<CommittedManifest>,
+ pending: &mut Option<PendingSync>,
+) -> Result<()> {
+ if record_str(record, "kind")? != "sync_begin" {
+ return replay_record(record, committed, pending);
+ }
+ // Journal callers validate uniqueness before routing every record. Keep
+ // the exact decoder single-pass here rather than parsing sync_begin a
+ // redundant fourth time.
+ let begin = decode_durable_sync_begin_validated(bytes)?;
+ apply_begin(
+ committed
+ .as_ref()
+ .context("sync_begin has no committed base manifest")?,
+ pending,
+ begin,
+ )
+}
+
pub fn is_sync_record_kind(kind: &str) -> bool {
matches!(
kind,
@@ -1100,6 +1251,7 @@ fn record_str<'a>(record: &'a Value, field: &str) -> Result<&'a str> {
mod tests {
use super::*;
use crate::state::{FileAssignment, PlanDataset};
+ use serde_json::json;
fn path(id_hex: &str, symlink: bool) -> ManifestPath {
ManifestPath {
@@ -1139,6 +1291,175 @@ mod tests {
}
}
+ #[test]
+ fn durable_sync_begin_decoder_preserves_inferred_float_bits() {
+ let original = 245.44444444444446_f64;
+ let replayed = decode_durable_sync_begin(include_bytes!(
+ "../tests/fixtures/issue_283_sync_begin.json"
+ ))
+ .unwrap()
+ .desired
+ .plan
+ .datasets[0]
+ .specs[0]
+ .avg_len;
+ assert_eq!(
+ replayed.to_bits(),
+ original.to_bits(),
+ "the durable decimal must recover the exact inferred f64"
+ );
+ }
+
+ #[test]
+ fn pre_fix_sync_begin_recovers_digest_and_still_rejects_changes() {
+ // Captured before `serde_json/float_roundtrip` was enabled. Its digest
+ // was computed from the original in-memory `avg_len` bits, while the
+ // JSON contains the shortest round-tripping decimal for those bits.
+ let pending = decode_durable_sync_begin(include_bytes!(
+ "../tests/fixtures/issue_283_sync_begin.json"
+ ))
+ .unwrap();
+ let base = CommittedManifest::genesis().unwrap();
+ assert_eq!(
+ base.manifest_digest,
+ "axm1-225526cc79184af5df2509f2e6908557"
+ );
+ assert_eq!(
+ pending.desired.plan.datasets[0].specs[0].avg_len.to_bits(),
+ 245.44444444444446_f64.to_bits()
+ );
+ pending.validate_against(&base).unwrap();
+
+ let mut changed = pending;
+ changed.desired.plan.datasets[0].specs[0].avg_len += 1.0;
+ assert!(
+ changed.validate_against(&base).is_err(),
+ "a genuinely changed manifest must not inherit the persisted digest"
+ );
+ }
+
+ #[test]
+ fn pre_fix_sync_begin_reopens_from_durable_journal_without_digest_drift() {
+ let dir = tempfile::tempdir().unwrap();
+ let base = CommittedManifest::genesis().unwrap();
+ // NDJSON requires one physical line. Remove formatting whitespace
+ // mechanically; never parse through the ordinary float decoder while
+ // constructing the historical record under test.
+ let historical_begin = include_str!("../tests/fixtures/issue_283_sync_begin.json")
+ .lines()
+ .collect::<String>();
+ assert!(historical_begin.contains("\"avg_len\": 245.44444444444446"));
+ let records = [
+ serde_json::to_string(&json!({
+ "v": 1,
+ "kind": "run",
+ "root": "root",
+ "url": "url",
+ "prefix": "prefix",
+ "bulk_timeout_secs": 300,
+ "run_id": "run-issue-283-fixture",
+ "started": "2026-08-10T00:00:00Z"
+ }))
+ .unwrap(),
+ serde_json::to_string(&json!({"kind": "sync_bootstrap", "manifest": base})).unwrap(),
+ historical_begin,
+ ];
+ let mut journal_bytes = records.join("\n").into_bytes();
+ journal_bytes.push(b'\n');
+ std::fs::write(dir.path().join("journal.ndjson"), journal_bytes).unwrap();
+
+ // This is the durable resume boundary only: Journal::open reads the
+ // checked-in pre-fix sync_begin from disk, validates it against the
+ // committed generation, and appends the ordinary resume marker. It
+ // deliberately does not claim to replay network operations.
+ let reopened =
+ crate::state::Journal::open(dir.path(), "root", "url", "prefix", 300, false).unwrap();
+ assert!(reopened.resumed);
+ assert_eq!(
+ reopened
+ .committed_manifest
+ .as_ref()
+ .unwrap()
+ .manifest_digest,
+ "axm1-225526cc79184af5df2509f2e6908557"
+ );
+ let pending = reopened.pending_sync.as_ref().unwrap();
+ assert_eq!(
+ pending.desired_manifest_digest,
+ "axm1-5e314eb29c9617433af240313b94e544"
+ );
+ assert_eq!(
+ manifest_digest(&pending.desired).unwrap(),
+ pending.desired_manifest_digest
+ );
+ assert_eq!(
+ pending.desired.plan.datasets[0].specs[0].avg_len.to_bits(),
+ 245.44444444444446_f64.to_bits()
+ );
+ }
+
+ #[test]
+ fn durable_sync_begin_rejects_duplicate_keys_at_any_depth() {
+ let fixture = include_str!("../tests/fixtures/issue_283_sync_begin.json");
+ let duplicate = fixture.replacen(
+ "\"avg_len\": 245.44444444444446,",
+ "\"avg_len\": 1.0, \"avg_len\": 245.44444444444446,",
+ 1,
+ );
+ let error = decode_durable_sync_begin(duplicate.as_bytes()).unwrap_err();
+ assert!(
+ format!("{error:#}").contains("duplicate JSON object key \"avg_len\""),
+ "{error:#}"
+ );
+ }
+
+ #[test]
+ fn durable_sync_begin_rejects_malformed_trailing_and_deep_input() {
+ let fixture = include_str!("../tests/fixtures/issue_283_sync_begin.json");
+ assert!(decode_durable_sync_begin(b"{\"kind\":\"sync_begin\"").is_err());
+
+ let trailing = format!("{fixture}\n{{}}");
+ let trailing_error = decode_durable_sync_begin(trailing.as_bytes()).unwrap_err();
+ assert!(
+ format!("{trailing_error:#}").contains("trailing"),
+ "{trailing_error:#}"
+ );
+
+ let mut deep = String::from("{\"kind\":\"sync_begin\",\"ignored\":");
+ deep.push_str(&"[".repeat(140));
+ deep.push_str("null");
+ deep.push_str(&"]".repeat(140));
+ deep.push('}');
+ assert!(decode_durable_sync_begin(deep.as_bytes()).is_err());
+ }
+
+ #[test]
+ fn durable_sync_begin_requires_both_parsers_to_route_sync_begin() {
+ let routed = json!({"kind": "sync_begin"});
+ let raw = br#"{"kind":"sync_commit","tx_id":"tx","desired_manifest_digest":"digest"}"#;
+ let mut committed = Some(CommittedManifest::genesis().unwrap());
+ let error = replay_durable_record(&routed, raw, &mut committed, &mut None).unwrap_err();
+ assert!(
+ format!("{error:#}").contains("disagrees with sync_begin routing"),
+ "{error:#}"
+ );
+ }
+
+ #[test]
+ fn alternate_decoder_is_not_used_for_other_durable_records() {
+ let genesis = CommittedManifest::genesis().unwrap();
+ let record = json!({"kind": "sync_bootstrap", "manifest": genesis});
+ let mut committed = None;
+ replay_durable_record(
+ &record,
+ b"not parsed for a non-sync_begin record",
+ &mut committed,
+ &mut None,
+ )
+ .unwrap();
+ assert_eq!(committed.unwrap().generation, 0);
+ }
+
#[test]
fn bootstrap_replay_accepts_only_exact_empty_genesis() {
let genesis = CommittedManifest::genesis().unwrap();
diff --git a/engine/crates/xerj-autoindex/tests/fixtures/issue_283_sync_begin.json b/engine/crates/xerj-autoindex/tests/fixtures/issue_283_sync_begin.json
new file mode 100644
index 000000000..343925e4c
--- /dev/null
+++ b/engine/crates/xerj-autoindex/tests/fixtures/issue_283_sync_begin.json
@@ -0,0 +1,64 @@
+{
+ "kind": "sync_begin",
+ "tx_id": "tx",
+ "base_generation": 0,
+ "base_manifest_digest": "axm1-225526cc79184af5df2509f2e6908557",
+ "desired_manifest_digest": "axm1-5e314eb29c9617433af240313b94e544",
+ "operation_hash": "axo1-39347ff402b6c53d831154110e30ac6a",
+ "desired": {
+ "generation": 1,
+ "execution": {
+ "version": 2,
+ "root_identity": "unix:root",
+ "url": "url",
+ "prefix": "prefix",
+ "follow_symlinks": false,
+ "chunker_identity": "chunker-v1",
+ "embedding_identity_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "embedding_backend": "lexical",
+ "embedding_dimension": 384,
+ "embedding_semantic_contract": "semantic_text-derived-vector.v1",
+ "embedding_resumable": true,
+ "graph_enabled": false,
+ "brain": "disabled",
+ "detector_identity": "disabled",
+ "schema_identity": "schema-v1",
+ "index_identity": "index-v1",
+ "source_policy": {
+ "policy": "abort_on_source_change",
+ "inventory_digest": "inventory-a"
+ }
+ },
+ "plan": {
+ "datasets": [
+ {
+ "slug": "docs",
+ "index": "incremental-http-docs",
+ "family": "code",
+ "specs": [
+ {
+ "name": "body",
+ "es_type": "text",
+ "cardinality_est": 9,
+ "cardinality_overflow": false,
+ "null_ratio": 0.1,
+ "avg_len": 245.44444444444446,
+ "coverage": 0.9,
+ "examples": []
+ }
+ ],
+ "sampled_records": 10,
+ "file_count": 0
+ }
+ ],
+ "files": {},
+ "junk_files": [],
+ "duplicate_files": [],
+ "alias_paths_indexed": false
+ },
+ "groups": []
+ },
+ "operations": [],
+ "operation_states": {},
+ "validated": false
+}