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(storage): merge can never silently drop docs + equal-seq dedup + aged WAL-tail durability

xerj-org689096cf96ef
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 327c0190f..4e3beac98 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -913,9 +913,32 @@ impl Index {
for replay_entry in xerj_storage::wal::replay_all_sorted(&wal_dir) {
match replay_entry.entry {
WalEntry::Index { doc_id, source } => {
- mem.remove(&doc_id);
- mem.insert(doc_id, &source, &schema.schema, replay_entry.seq_no);
- replayed += 1;
+ // Replay idempotence (2026-07, S2): mirror of the
+ // storage-memtable rule in `IndexStore::replay_wal`.
+ // If the version map (segments rebuilt + storage
+ // replay, which ran inside `IndexStore::open`) shows
+ // this doc live and SEGMENT-resident at seq >= this
+ // op, the exact same (or a newer) version is already
+ // in a segment — the pre-restart shutdown flush
+ // persisted it while batch-6 delete-pinning kept its
+ // WAL shard. Inserting it here created an equal-seq
+ // FTS-memtable duplicate that inflated term/count
+ // paths (counts saw both copies; hit lists dedup by
+ // _id which masked it in search results).
+ let already_persisted = match store.version_map.get(&doc_id) {
+ Some(e) => {
+ !e.deleted
+ && e.seq_no >= replay_entry.seq_no
+ && &*e.segment_id
+ != xerj_storage::version_map::IN_MEMORY_SEGMENT_ID
+ }
+ None => false,
+ };
+ if !already_persisted {
+ mem.remove(&doc_id);
+ mem.insert(doc_id, &source, &schema.schema, replay_entry.seq_no);
+ replayed += 1;
+ }
}
WalEntry::Delete { doc_id } => {
mem.remove(&doc_id);
@@ -2660,6 +2683,20 @@ impl Index {
let mut queue_iter = launch_queue.into_iter();
let mut pending = queue_iter.next();
+ // LOSS FIREWALL (2026-07, S1): count batches that ABORTED because an
+ // input segment could not be fully read (open / decode-stored / parse
+ // failure) or the output could not be written. Pre-fix, a decode
+ // failure was `warn!(...); continue;` — the merge output was still
+ // committed by `apply_merge`, which REMOVED the unread input segment
+ // from the snapshot and deleted its files: every doc in it was
+ // silently and permanently lost (live-verified: 752 → 254 docs on a
+ // 48-segment forcemerge whose intermediate carried a CrossDep cycle,
+ // see stored_codec.rs). A merge must never commit unless every input
+ // doc was read — aborted batches keep their inputs untouched and the
+ // pass returns an ERROR so callers (forcemerge HTTP → 500, background
+ // task → error log) hear about it loudly instead of losing data.
+ let failed_batches = Arc::new(std::sync::atomic::AtomicUsize::new(0));
+
let spawn_one = |batch: Vec<xerj_storage::segment::SegmentId>,
metas: Vec<xerj_storage::segment::SegmentMeta>|
-> JoinHandle<Option<MergeOutput>> {
@@ -2669,6 +2706,7 @@ impl Index {
let segments_dir_for_task = segments_dir.clone();
let batch_for_task = batch;
let metas_for_task = metas;
+ let failed_for_task = Arc::clone(&failed_batches);
tokio::task::spawn_blocking(move || -> Option<MergeOutput> {
// Entire merge encode runs on the dedicated SMALL merge
@@ -2754,23 +2792,64 @@ impl Index {
min_seq = min_seq.min(meta.min_seq_no);
max_seq = max_seq.max(meta.max_seq_no);
let seg_path = segments_dir_for_task.join(&meta.seg_path);
+ // LOSS FIREWALL (S1): every failure to fully read an
+ // input segment ABORTS the whole batch (`return None`
+ // — inputs stay live in the snapshot, nothing is
+ // committed or deleted). The old `continue` dropped
+ // the segment's docs from the merge output while
+ // `apply_merge` still removed the input: silent,
+ // permanent data loss.
let reader = match SegmentReader::open(&seg_path) {
Ok(r) => r,
Err(e) => {
- tracing::warn!(?seg_path, "merge: failed to open segment: {e}");
- continue;
+ tracing::error!(
+ ?seg_path,
+ "merge ABORTED: failed to open input segment \
+ (inputs preserved, no docs dropped): {e}"
+ );
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
}
};
let stored_bytes_raw = match reader.section(SectionType::Stored) {
Ok(Some(b)) => b,
- _ => continue,
+ Ok(None) => {
+ // A doc-less segment legitimately has no
+ // stored section; a doc-CARRYING one missing
+ // it would lose docs — abort.
+ if meta.doc_count == 0 {
+ continue;
+ }
+ tracing::error!(
+ ?seg_path,
+ doc_count = meta.doc_count,
+ "merge ABORTED: input segment has docs but no \
+ stored section (inputs preserved)"
+ );
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
+ }
+ Err(e) => {
+ tracing::error!(
+ ?seg_path,
+ "merge ABORTED: failed to read stored section \
+ (inputs preserved, no docs dropped): {e}"
+ );
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
+ }
};
let stored_bytes =
match xerj_storage::stored_codec::decode_stored(stored_bytes_raw) {
Ok(b) => b,
Err(e) => {
- tracing::warn!("merge: failed to decode stored section: {e}");
- continue;
+ tracing::error!(
+ ?seg_path,
+ "merge ABORTED: failed to decode stored section \
+ (inputs preserved, no docs dropped): {e}"
+ );
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
}
};
// `Box<RawValue>` uses a serde-private newtype tag that
@@ -2789,10 +2868,13 @@ impl Index {
match serde_json::from_slice(&stored_bytes) {
Ok(d) => d,
Err(e) => {
- tracing::warn!(
- "merge: failed to parse stored as RawValue: {e}"
+ tracing::error!(
+ ?seg_path,
+ "merge ABORTED: failed to parse stored as RawValue \
+ (inputs preserved, no docs dropped): {e}"
);
- continue;
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
}
};
@@ -2800,7 +2882,17 @@ impl Index {
let raw_str = raw.get();
let id_seq: IdSeq = match serde_json::from_str(raw_str) {
Ok(v) => v,
- Err(_) => continue,
+ Err(e) => {
+ // A doc we cannot even extract (_id, _seq_no)
+ // from must not be silently dropped either.
+ tracing::error!(
+ ?seg_path,
+ "merge ABORTED: stored doc failed _id/_seq_no \
+ parse (inputs preserved): {e}"
+ );
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
+ return None;
+ }
};
if id_seq.id.is_empty() {
continue;
@@ -2853,21 +2945,24 @@ impl Index {
let mut writer = match SegmentWriter::new(&segments_dir_for_task, 1, 0, 0) {
Ok(w) => w,
Err(e) => {
- tracing::warn!("merge: failed to create writer: {e}");
+ tracing::error!("merge ABORTED: failed to create writer: {e}");
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
return None;
}
};
let encoded = xerj_storage::stored_codec::encode_stored_v2(&merged_json_buf);
drop(merged_json_buf);
if let Err(e) = writer.add_section(SectionType::Stored, &encoded) {
- tracing::warn!("merge: failed to add section: {e}");
+ tracing::error!("merge ABORTED: failed to add section: {e}");
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
return None;
}
let merged_meta = match writer.finish(live_doc_count, min_seq, max_seq) {
Ok(m) => m,
Err(e) => {
- tracing::warn!("merge: failed to finish segment: {e}");
+ tracing::error!("merge ABORTED: failed to finish segment: {e}");
+ failed_for_task.fetch_add(1, Ordering::Relaxed);
return None;
}
};
@@ -3080,7 +3175,10 @@ impl Index {
}
}
Ok(None) => {}
- Err(e) => tracing::warn!("merge: spawn_blocking panicked: {e}"),
+ Err(e) => {
+ tracing::error!("merge: spawn_blocking panicked: {e}");
+ failed_batches.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ }
}
// Top up in_flight.
if let Some((batch, metas)) = pending.take() {
@@ -3130,6 +3228,25 @@ impl Index {
}
}
+ // LOSS FIREWALL (S1): surface aborted batches as a hard error AFTER
+ // the successful batches' cache eviction above (their apply_merge
+ // already committed and must stay coherent). Aborted batches kept
+ // their input segments — no document was dropped — but the caller
+ // must hear about it: `_forcemerge` returns HTTP 500 instead of
+ // pretending the index converged, and the background merge task
+ // logs an error every pass until the offending segment is repaired.
+ let failed = failed_batches.load(std::sync::atomic::Ordering::Relaxed);
+ if failed > 0 {
+ return Err(EngineError::Common(xerj_common::XerjError::internal(
+ format!(
+ "merge pass aborted {failed} batch(es): an input segment could not \
+ be fully read or the output could not be written; input segments \
+ were preserved (no documents dropped, {merged_batches} other \
+ batch(es) merged)"
+ ),
+ )));
+ }
+
Ok(merged_batches)
}
diff --git a/engine/crates/xerj-storage/src/index_store.rs b/engine/crates/xerj-storage/src/index_store.rs
index bac418966..08b0200d1 100644
--- a/engine/crates/xerj-storage/src/index_store.rs
+++ b/engine/crates/xerj-storage/src/index_store.rs
@@ -479,6 +479,36 @@ impl IndexStore {
tracing::warn!("segment-dir GC failed: {e}");
}
+ // SEQ-COUNTER SEEDING (2026-07, S3 root cause): the counter starts at
+ // 1 and, pre-fix, was only ever raised from seqs found in surviving
+ // WAL files (`WalWriter::open`) and replayed entries. After a flush
+ // + WAL maintenance (checkpoint + rotate + prune) every WAL shard is
+ // an empty active generation, so a restart RESET the counter to ~1
+ // while segments held seqs up to X — and the stale checkpoint on the
+ // active generation (max_seq_no = X) then made the NEXT replay
+ // discard every post-restart acked op (seqs 1..K <= X): 100% loss of
+ // the post-restart tail. Seed the counter from the durable segment
+ // metadata (snapshot.max_seq_no plus every registered/recovered
+ // segment's max_seq_no) so global seq monotonicity holds across
+ // restarts — the invariant every checkpoint and version-map
+ // comparison silently assumes.
+ {
+ let snap = store.snapshot.load();
+ let durable_max = snap
+ .segments
+ .iter()
+ .map(|s| s.max_seq_no)
+ .max()
+ .unwrap_or(0)
+ .max(snap.max_seq_no);
+ drop(snap);
+ if durable_max > 0 {
+ store
+ .seq_counter
+ .fetch_max(durable_max + 1, Ordering::AcqRel);
+ }
+ }
+
// Replay WAL to rebuild in-memory state (these override segment entries).
store.replay_wal(&wal_dir)?;
@@ -1983,16 +2013,49 @@ impl IndexStore {
match replay_entry.entry {
WalEntry::Index { doc_id, source } => {
let seq_no = replay_entry.seq_no;
- self.version_map
- .set(&doc_id, seq_no, IN_MEMORY_SEGMENT_ID, false);
- let shard = self.shard_for(&doc_id);
- let mut mem = self.memtable_shards[shard].lock().unwrap();
- mem.push(MemEntry {
- seq_no,
- doc_id,
- source: Some(std::sync::Arc::new(source)),
- source_bytes: std::sync::Arc::from(&[][..]),
- });
+ // Replay idempotence (2026-07, S2): if the version map —
+ // rebuilt from segments BEFORE replay — already shows this
+ // doc live in a real segment at seq_no >= this op, the
+ // exact same op (equal seq: the shutdown flush persisted
+ // it) or a newer version is already segment-durable.
+ // Re-materialising it in the memtable created a SECOND
+ // copy of the same (id, seq_no): the strict `doc_seq <
+ // ver.seq_no` stale-copy predicates on the count paths
+ // don't skip an equal-seq segment copy, so counts were
+ // inflated after a SIGTERM restart whose WAL shard was
+ // pinned by an unpersisted delete (batch-6 pinning
+ // correctly preserved the shard, preserving the already-
+ // flushed overwrite entries with it). Skip the memtable
+ // push and version_map set; the seq counter is still
+ // fetch_max'd below.
+ //
+ // Caveat: legacy segments without a `.ids` sidecar
+ // rebuild version-map seqs by approximation
+ // (`rebuild_version_map_from_segments`); with the seq
+ // counter now seeded from segment metadata on open, any
+ // post-flush update carries a seq strictly greater than
+ // its segment's max_seq_no, so the approximation cannot
+ // shadow a genuinely newer WAL-only version.
+ let already_persisted = match self.version_map.get(&doc_id) {
+ Some(e) => {
+ !e.deleted
+ && e.seq_no >= seq_no
+ && &*e.segment_id != IN_MEMORY_SEGMENT_ID
+ }
+ None => false,
+ };
+ if !already_persisted {
+ self.version_map
+ .set(&doc_id, seq_no, IN_MEMORY_SEGMENT_ID, false);
+ let shard = self.shard_for(&doc_id);
+ let mut mem = self.memtable_shards[shard].lock().unwrap();
+ mem.push(MemEntry {
+ seq_no,
+ doc_id,
+ source: Some(std::sync::Arc::new(source)),
+ source_bytes: std::sync::Arc::from(&[][..]),
+ });
+ }
}
WalEntry::Delete { doc_id } => {
let seq_no = replay_entry.seq_no;
diff --git a/engine/crates/xerj-storage/src/stored_codec.rs b/engine/crates/xerj-storage/src/stored_codec.rs
index 49f8340db..745e9e889 100644
--- a/engine/crates/xerj-storage/src/stored_codec.rs
+++ b/engine/crates/xerj-storage/src/stored_codec.rs
@@ -406,6 +406,37 @@ fn encode_v2_columns(
best_cross_dep_source(&dict_encoded, cix, col)
})
.collect();
+
+ // CYCLE BREAKER (2026-07, S1 root cause): `best_cross_dep_source`
+ // admits ANY dict-encodable column as a source — including integer
+ // columns that are themselves about to be CrossDep-encoded. Two
+ // mutually-deterministic low-cardinality integer columns (e.g.
+ // `a = i%5`, `b = (i%5)*7`) each picked the other as source, writing
+ // a dependency CYCLE to disk that `decode_stored_v2` can never
+ // resolve ("cross_dep src not resolved") — the whole stored section
+ // became undecodable and the merge loss-amplifier destroyed every
+ // doc in the segment. Fix: any column chosen as a CrossDep SOURCE
+ // must materialise in decode pass 1, so clear its OWN cross_dep_src
+ // (it falls back to DictBitpack — it is dict-encodable and
+ // ≤ CROSS_DEP_MAX_SRC_CARDINALITY ≤ DICT_MAX_CARDINALITY by
+ // admission, so the compression give-up is negligible). This
+ // structurally rules out cycles AND multi-hop forward chains: every
+ // surviving CrossDep target's source is a pass-1 codec.
+ let cross_dep_src: Vec<Option<usize>> = {
+ let chosen_sources: rustc_hash::FxHashSet<usize> =
+ cross_dep_src.iter().flatten().copied().collect();
+ cross_dep_src
+ .iter()
+ .enumerate()
+ .map(|(cix, src)| {
+ if chosen_sources.contains(&cix) {
+ None
+ } else {
+ *src
+ }
+ })
+ .collect()
+ };
let cross_us = t_cross.elapsed().as_micros();
let t_cols = std::time::Instant::now();
@@ -586,28 +617,66 @@ fn decode_stored_v2(body: &[u8]) -> Result<Vec<u8>> {
col_data.push(values);
}
- // Second pass: resolve deferred CROSS_DEP columns now that all
+ // Second pass: resolve deferred CROSS_DEP columns now that the pass-1
// source columns are materialised.
+ //
+ // FIXPOINT (2026-07, S1 decode hardening): the old resolver was a
+ // SINGLE sweep in column-index order — a CrossDep column whose source
+ // was a LATER CrossDep column (forward reference) failed with
+ // "cross_dep src not resolved" and the entire stored section became
+ // undecodable, which the merge path then amplified into wholesale doc
+ // loss. Now we sweep repeatedly, resolving every column whose source
+ // has materialised, until either all are resolved or a sweep makes no
+ // progress. No-progress means a true dependency CYCLE on disk
+ // (mathematically unrecoverable — the mode tables of both columns
+ // reference each other's values); we return a hard error so callers
+ // (e.g. the merge loss-firewall) PRESERVE the segment instead of
+ // dropping its docs. The encode-side cycle breaker stops new cycles
+ // from being written; this loop recovers forward-chain segments
+ // already on disk.
let col_name_to_ix: HashMap<String, usize> = col_names
.iter()
.enumerate()
.map(|(i, n)| (n.clone(), i))
.collect();
- for cix in 0..col_data.len() {
- if col_data[cix].len() == 1 {
- if let serde_json::Value::Object(ref m) = col_data[cix][0] {
+ let is_deferred = |col: &Vec<serde_json::Value>| -> Option<Vec<u8>> {
+ if col.len() == 1 {
+ if let serde_json::Value::Object(ref m) = col[0] {
if let Some(serde_json::Value::Array(bytes_arr)) = m.get("__deferred_cross_dep__") {
- let payload: Vec<u8> = bytes_arr
- .iter()
- .filter_map(|v| v.as_u64().map(|u| u as u8))
- .collect();
- let resolved =
- decode_cross_dep(&payload, num_docs, &col_data, &col_name_to_ix)?;
+ return Some(
+ bytes_arr
+ .iter()
+ .filter_map(|v| v.as_u64().map(|u| u as u8))
+ .collect(),
+ );
+ }
+ }
+ }
+ None
+ };
+ loop {
+ let mut progressed = false;
+ let mut still_deferred = 0usize;
+ for cix in 0..col_data.len() {
+ let Some(payload) = is_deferred(&col_data[cix]) else {
+ continue;
+ };
+ match decode_cross_dep(&payload, num_docs, &col_data, &col_name_to_ix)? {
+ Some(resolved) => {
col_data[cix] = resolved;
- continue;
+ progressed = true;
}
+ None => still_deferred += 1,
}
}
+ if still_deferred == 0 {
+ break;
+ }
+ if !progressed {
+ return Err(StorageError::Other(anyhow::anyhow!(
+ "cross_dep dependency cycle: {still_deferred} column(s) unresolvable"
+ )));
+ }
}
// Re-assemble the JSON-array payload. col_data[0] = __id, col_data[1] = __seq_no.
@@ -1073,12 +1142,19 @@ fn encode_cross_dep<B: std::borrow::Borrow<serde_json::Value>>(
(final_out, true)
}
+/// Decode one deferred CROSS_DEP column.
+///
+/// Returns `Ok(None)` when the SOURCE column is itself a still-deferred
+/// CROSS_DEP placeholder — the fixpoint loop in `decode_stored_v2` retries
+/// it on the next round once the source has materialised. (Pre-2026-07
+/// this case was a hard error inside a single-pass resolver: any forward
+/// reference or cycle made the whole stored section undecodable.)
fn decode_cross_dep(
payload: &[u8],
num_docs: usize,
col_data: &[Vec<serde_json::Value>],
col_name_to_ix: &HashMap<String, usize>,
-) -> Result<Vec<serde_json::Value>> {
+) -> Result<Option<Vec<serde_json::Value>>> {
if payload.is_empty() {
return Err(StorageError::Other(anyhow::anyhow!("cross_dep empty")));
}
@@ -1117,11 +1193,9 @@ fn decode_cross_dep(
.get(src_ix)
.ok_or_else(|| StorageError::Other(anyhow::anyhow!("cross_dep src missing")))?;
if src_col.len() != num_docs {
- // Source column was itself a CROSS_DEP and not yet resolved. Caller
- // should have resolved RHS first. Bail with a clear error.
- return Err(StorageError::Other(anyhow::anyhow!(
- "cross_dep src not resolved"
- )));
+ // Source column is itself a CROSS_DEP that has not been resolved
+ // yet — tell the fixpoint loop to retry this column next round.
+ return Ok(None);
}
let (_src_entries, src_ids) = dict_encode_column(src_col)
.ok_or_else(|| StorageError::Other(anyhow::anyhow!("cross_dep re-dict src failed")))?;
@@ -1164,7 +1238,7 @@ fn decode_cross_dep(
result.push(serde_json::Value::Number(v.into()));
}
}
- Ok(result)
+ Ok(Some(result))
}
fn decode_raw_json(payload: &[u8]) -> Result<Vec<serde_json::Value>> {
diff --git a/engine/crates/xerj-storage/src/wal.rs b/engine/crates/xerj-storage/src/wal.rs
index c4e375b81..bc12ffd6f 100644
--- a/engine/crates/xerj-storage/src/wal.rs
+++ b/engine/crates/xerj-storage/src/wal.rs
@@ -534,6 +534,19 @@ impl WalWriter {
/// Write a checkpoint file for the current generation.
pub fn checkpoint(&mut self, max_seq_no: SeqNo) -> Result<()> {
+ // STALE-CHECKPOINT FIX (2026-07, S3): never checkpoint an EMPTY
+ // active generation. There is nothing to cover (the previous
+ // generation's checkpoint, if any, still exists), and because
+ // `force_rotate` deliberately no-ops on empty generations, the
+ // .wchk written here would sit on the very generation that
+ // receives FUTURE appends. Combined with a restart-regressed seq
+ // counter that state made `WalReader::replay` discard every
+ // post-restart acked op (seq_no <= checkpoint.max_seq_no) — byte-
+ // verified as wchk=(offset=16, max_seq_no=X) next to tail entries
+ // seq 1..K in the same shard file, 100% tail loss.
+ if self.current_offset <= WAL_HEADER_LEN {
+ return Ok(());
+ }
self.sync()?;
let chkpt = WalCheckpoint {
generation: self.generation,
@@ -741,21 +754,23 @@ impl WalReader {
let (latest_gen, _) = find_latest_generation(&self.dir)?;
// Determine the starting generation and offset from the checkpoint
- let (start_gen, skip_up_to_seq) = match read_checkpoint(&self.dir, latest_gen) {
+ let checkpoint = match read_checkpoint(&self.dir, latest_gen) {
Ok(c) => {
// debug: fires per WAL (16 shards × every index) at startup.
debug!(
generation = c.generation,
max_seq_no = c.max_seq_no,
+ offset = c.offset,
"replaying from checkpoint"
);
- (c.generation, c.max_seq_no)
+ Some(c)
}
Err(_) => {
debug!("no checkpoint found, replaying from generation 0");
- (0u64, 0u64)
+ None
}
};
+ let start_gen = checkpoint.as_ref().map(|c| c.generation).unwrap_or(0);
// Collect all generations >= start_gen
let mut gens: Vec<u64> = fs::read_dir(&self.dir)
@@ -770,7 +785,7 @@ impl WalReader {
let dir = self.dir.clone();
let iter = gens.into_iter().flat_map(move |gen| {
let path = wal_path(&dir, gen);
- read_wal_file(path, skip_up_to_seq)
+ read_wal_file(path, checkpoint.clone())
});
Ok(iter)
@@ -839,9 +854,22 @@ pub fn replay_all_sorted(wal_root: &Path) -> Vec<ReplayEntry> {
all_entries
}
-/// Read all entries from a single WAL file, skipping those with seq_no <=
-/// `skip_up_to_seq`.
-fn read_wal_file(path: PathBuf, skip_up_to_seq: SeqNo) -> Vec<Result<ReplayEntry>> {
+/// Read all entries from a single WAL file, skipping those already covered
+/// by `checkpoint`.
+///
+/// OFFSET-BOUNDED SKIP (2026-07, S3 hardening): an entry is "covered" only
+/// when it sits BEFORE the checkpointed byte offset of the checkpointed
+/// generation (or in an older generation). A checkpoint by construction
+/// covers exactly the bytes `[0, checkpoint.offset)` of its generation —
+/// anything appended past that offset was written AFTER the checkpoint and
+/// must replay regardless of its seq_no. The old rule (`seq_no <=
+/// checkpoint.max_seq_no`, applied file-wide) silently discarded every
+/// post-restart acked op whenever the seq counter had regressed across a
+/// restart (stale .wchk with max_seq_no=X on the active generation, tail
+/// entries seq 1..K <= X) — 100% loss of the acked tail. It also protects
+/// against the flush-checkpoint race where a reserved-but-unflushed seq
+/// range is covered by a concurrent checkpoint's max_seq.
+fn read_wal_file(path: PathBuf, checkpoint: Option<WalCheckpoint>) -> Vec<Result<ReplayEntry>> {
let file = match File::open(&path) {
Ok(f) => f,
Err(e) => return vec![Err(e.into())],
@@ -929,9 +957,14 @@ fn read_wal_file(path: PathBuf, skip_up_to_seq: SeqNo) -> Vec<Result<ReplayEntry
let this_offset = file_offset;
file_offset += entry_total;
- // Skip entries already covered by checkpoint
- if seq_no <= skip_up_to_seq {
- continue;
+ // Skip entries already covered by the checkpoint — see the
+ // offset-bounded rule in the function docs.
+ if let Some(c) = &checkpoint {
+ let positionally_covered = generation < c.generation
+ || (generation == c.generation && this_offset < c.offset);
+ if positionally_covered && seq_no <= c.max_seq_no {
+ continue;
+ }
}
// Check and strip the compression flag from op_code.