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(wal-tap): close the four round-2 review blockers on #320

xerj-org6486e58b7a65
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f492f8283..baca8a68b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -43,18 +43,34 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
since the last one, not the size of the file — the tail reader is a sliding
window over a `File`, shaped after Lucene's `BufferedIndexInput.refill`
(`lucene/core/src/java/org/apache/lucene/store/BufferedIndexInput.java:289-317`,
- Apache-2.0). A caught-up poll reads the 16-byte WAL header and stops.
+ Apache-2.0). A caught-up poll reads the 16-byte WAL header and stops —
+ measured at exactly 16 bytes over a 4,176,200-byte generation, asserted
+ through `tail_shard` itself by
+ `wal::tests::a_caught_up_poll_does_not_read_the_whole_generation`. (The
+ window's 64 KiB read-ahead is deliberately not applied to that header read:
+ it was, and it made the figure 65,536 bytes per shard per poll rather
+ than 16.)
- Delivery is at-least-once, with `version_type: external` carrying the WAL
`seq_no` on every action so a redelivery converges on the same document the
- source holds. Note that XERJ's own `_bulk` ignores per-action `version` /
- `version_type` (only the single-doc path honours them), so a XERJ target
- degrades to last-write-wins by arrival; against Elasticsearch or OpenSearch
- the mechanism is live.
+ source holds. Covered against a stub that implements the actual ES external
+ versioning rule — absent `_id` is created at any version, present `_id` is
+ overwritten only by a strictly greater one, everything else comes back
+ `409 version_conflict_engine_exception` — and asserted on both halves: four
+ documents accepted on the first delivery, four conflicts and zero extra
+ `docs_shipped` on the redelivery, watermark unchanged. Note that XERJ's own
+ `_bulk` ignores per-action `version` / `version_type` (only the single-doc
+ path honours them), so a XERJ target degrades to last-write-wins by
+ arrival; against Elasticsearch or OpenSearch the mechanism is live.
- `_stats` counts what the **target accepted**, per item, not what was
rendered into the request. `lag_seq` is derived from the highest accepted
`seq_no`, and each index carries a `healthy` boolean that is false both when
- sends are failing and when the target answers `200` while rejecting every
- action inside it as a version conflict.
+ sends are failing and when the target answers `200` while applying none of
+ the actions inside it — for **any** reason, not only a version conflict.
+ A target rejecting every document with `mapper_parsing_exception` is a `200`
+ with `errors: true`, so no send fails and the cursor advances past every
+ dropped document; `last_item_rejection` in `_stats` carries the target's own
+ word for it, because "fix the mapping" and "look for a second writer" are
+ opposite responses.
- Cursor state is flushed once per poll cycle rather than once per index per
poll; a deferred flush can only cause a redelivery, which the external
versioning above absorbs.
diff --git a/engine/crates/xerj-api/src/wal_tap_api.rs b/engine/crates/xerj-api/src/wal_tap_api.rs
index bcf61698e..0eb38643b 100644
--- a/engine/crates/xerj-api/src/wal_tap_api.rs
+++ b/engine/crates/xerj-api/src/wal_tap_api.rs
@@ -256,7 +256,11 @@ pub async fn delete_wal_tap(State(state): State<AppState>) -> Response {
/// the index's own sequence counter the tap is; `last_error` is why it stopped
/// advancing; `healthy` is false when either of the two states that used to
/// be indistinguishable from working is in effect — sends failing, or a
-/// target answering 200 while rejecting every action inside it.
+/// target answering 200 while applying none of the actions inside it, for any
+/// reason (`version_conflict_engine_exception`, `mapper_parsing_exception`,
+/// anything else). `last_item_rejection` carries the target's own word for
+/// the last non-conflict rejection, because "fix the mapping" and "look for a
+/// second writer" are opposite responses.
///
/// Superuser-only ([`crate::authz`]): this enumerates every index on the node
/// that the allowlist matches, and it echoes `target_url`. It applies no
diff --git a/engine/crates/xerj-engine/src/wal_tap.rs b/engine/crates/xerj-engine/src/wal_tap.rs
index d2d0d5d7b..c82bcbb25 100644
--- a/engine/crates/xerj-engine/src/wal_tap.rs
+++ b/engine/crates/xerj-engine/src/wal_tap.rs
@@ -61,10 +61,13 @@
//! and that is what the counters mean: `docs_shipped` and `last_shipped_seq`
//! move only for items the target **accepted**. A `_bulk` that returns `200`
//! while rejecting every action inside it — a target holding a higher external
-//! version for every `_id`, i.e. a second writer got there first — is a real
+//! version for every `_id` because a second writer got there first, or one
+//! rejecting every document with a `mapper_parsing_exception` — is a real
//! state and used to be indistinguishable from a healthy tap.
-//! `consecutive_conflict_only_batches` and
-//! [`IndexTapStats::healthy`] exist so it is not.
+//! `consecutive_unapplied_batches`, `last_item_rejection` and
+//! [`IndexTapStats::healthy`] exist so it is not. The counter is deliberately
+//! blind to *why* nothing applied: conflict and rejection are opposite
+//! diagnoses but the same fact, and it is the fact that `healthy` reports.
//!
//! **3. Backpressure.** Bounded by construction: one in-flight request per
//! index, batches capped by `max_batch_docs` and `max_batch_bytes`, and
@@ -265,34 +268,49 @@ pub struct IndexTapStats {
/// instead is what let a target that rejected every single action report
/// `lag_seq: 0` while `docs_shipped` climbed.
pub last_shipped_seq: u64,
- /// Consecutive `_bulk` responses in which the target rejected **every**
- /// action as a version conflict.
+ /// Consecutive `_bulk` responses in which the target accepted **nothing**
+ /// — every action inside came back with an error.
///
- /// One conflict is expected and benign: it is how external versioning
- /// absorbs an at-least-once redelivery. A *sustained run* of batches that
- /// are entirely conflicts is not — it means the target holds a higher
- /// version for every `_id` this tap sends, so the tap is a no-op and the
- /// two sides are diverging. See [`IndexTapStats::healthy`].
- pub consecutive_conflict_only_batches: u32,
+ /// Deliberately blind to *why*. A version conflict and a
+ /// `mapper_parsing_exception` are opposite diagnoses but the same
+ /// operational fact: the documents are not at the target. An earlier shape
+ /// of this counter only counted the conflict case, which meant a target
+ /// answering `200` while rejecting every single item with a mapping error
+ /// read `healthy: true` with `docs_shipped: 0` — the exact class of lie
+ /// the per-item accounting exists to remove.
+ ///
+ /// One such batch is expected and benign: it is how external versioning
+ /// absorbs an at-least-once redelivery. A *sustained run* is not — it means
+ /// the tap is a no-op and the two sides are diverging. See
+ /// [`IndexTapStats::healthy`].
+ pub consecutive_unapplied_batches: u32,
+ /// Error `type` of the most recent item the target rejected for a reason
+ /// other than a version conflict, e.g. `mapper_parsing_exception`.
+ ///
+ /// `item_failures` says how many documents were dropped; this says what
+ /// the target called them, which is the difference between "fix the
+ /// mapping" and "look for a second writer".
+ pub last_item_rejection: Option<String>,
}
-/// How many all-conflict batches in a row stop counting as "a redelivery
-/// landed" and start counting as "this target is not taking our writes".
+/// How many batches in a row that applied nothing stop counting as "a
+/// redelivery landed" and start counting as "this target is not taking our
+/// writes".
///
/// A redelivery after a failed send re-ships exactly the chunks that did not
/// land, so it clears on the next batch that contains anything new. Three in a
/// row cannot be that.
-const CONFLICT_ONLY_UNHEALTHY_AFTER: u32 = 3;
+const UNAPPLIED_UNHEALTHY_AFTER: u32 = 3;
impl IndexTapStats {
/// Is this index's replication actually working?
///
/// `false` for the two states that used to look identical to a healthy
/// tap in `_stats`: a send that keeps failing, and a target that accepts
- /// every request while rejecting every action inside it.
+ /// every request while rejecting every action inside it — for any reason,
+ /// conflict or otherwise.
pub fn healthy(&self) -> bool {
- self.last_error.is_none()
- && self.consecutive_conflict_only_batches < CONFLICT_ONLY_UNHEALTHY_AFTER
+ self.last_error.is_none() && self.consecutive_unapplied_batches < UNAPPLIED_UNHEALTHY_AFTER
}
}
@@ -741,7 +759,13 @@ enum SendOutcome {
/// occurred; the cursor advances either way.
///
/// `outcomes` is positionally aligned with the chunk's actions.
- Accepted { outcomes: Vec<ItemOutcome> },
+ Accepted {
+ outcomes: Vec<ItemOutcome>,
+ /// Error `type` of the first non-conflict rejection in this response,
+ /// so `_stats` can say what the target called the documents it threw
+ /// away rather than only how many there were.
+ rejection: Option<String>,
+ },
/// The request did not land. The cursor must not advance.
Failed(String),
}
@@ -793,6 +817,7 @@ impl WalTap {
debug!(error = %e, "WAL tap: unparseable _bulk response body");
return SendOutcome::Accepted {
outcomes: vec![ItemOutcome::Accepted; actions],
+ rejection: None,
};
}
};
@@ -802,6 +827,7 @@ impl WalTap {
if parsed.get("errors").and_then(Value::as_bool) != Some(true) {
return SendOutcome::Accepted {
outcomes: vec![ItemOutcome::Accepted; actions],
+ rejection: None,
};
}
@@ -824,6 +850,7 @@ impl WalTap {
}
let mut outcomes = Vec::with_capacity(items.len());
+ let mut rejection: Option<String> = None;
let mut warned = false;
for item in items {
let action = item.as_object().and_then(|o| o.values().next());
@@ -841,10 +868,20 @@ impl WalTap {
warn!(error = %error, "WAL tap: target rejected a document — \
skipped (see item_failures in _stats)");
}
+ if rejection.is_none() {
+ rejection = Some(if kind.is_empty() {
+ "unknown".to_string()
+ } else {
+ kind.to_string()
+ });
+ }
outcomes.push(ItemOutcome::Rejected);
}
}
- SendOutcome::Accepted { outcomes }
+ SendOutcome::Accepted {
+ outcomes,
+ rejection,
+ }
}
/// Poll one index once: read its WAL tail, ship it, advance its cursors.
@@ -1000,14 +1037,17 @@ impl WalTap {
let mut item_failures = 0u64;
let mut version_conflicts = 0u64;
let mut batches = 0u64;
- let mut conflict_only_batches = 0u32;
+ let mut unapplied_batches = 0u32;
+ let mut rejection_kind: Option<String> = None;
for chunk in chunks {
let actions = chunk.actions.clone();
match self.send_bulk(config, chunk.body, actions.len()).await {
- SendOutcome::Accepted { outcomes } => {
+ SendOutcome::Accepted {
+ outcomes,
+ rejection,
+ } => {
let mut accepted_here = 0u64;
- let mut conflicts_here = 0u64;
for (action, outcome) in actions.iter().zip(outcomes.iter()) {
match outcome {
ItemOutcome::Accepted => {
@@ -1019,15 +1059,22 @@ impl WalTap {
docs += 1;
}
}
- ItemOutcome::Conflict => {
- conflicts_here += 1;
- version_conflicts += 1;
- }
+ ItemOutcome::Conflict => version_conflicts += 1,
ItemOutcome::Rejected => item_failures += 1,
}
}
- if accepted_here == 0 && conflicts_here == actions.len() as u64 {
- conflict_only_batches += 1;
+ // Nothing in this batch was applied. WHY is a separate
+ // question — a conflict says "a second writer beat us", a
+ // rejection says "the target will not take this document"
+ // — but the operational fact is identical and it is the
+ // one `healthy` answers. Counting only the conflict case
+ // let an all-`mapper_parsing_exception` response read as a
+ // healthy zero-lag tap with `docs_shipped: 0`.
+ if accepted_here == 0 && !actions.is_empty() {
+ unapplied_batches += 1;
+ }
+ if rejection.is_some() {
+ rejection_kind = rejection;
}
batches += 1;
}
@@ -1067,23 +1114,42 @@ impl WalTap {
s.version_conflicts += version_conflicts;
s.last_shipped_seq = s.last_shipped_seq.max(max_accepted_seq);
s.consecutive_failures = 0;
- // A run of batches in which the target rejected every action as a
- // conflict is not "replication working". Only a batch that landed
- // something clears it.
- if conflict_only_batches > 0 && docs == 0 && deletes == 0 {
- s.consecutive_conflict_only_batches = s
- .consecutive_conflict_only_batches
- .saturating_add(conflict_only_batches);
+ if let Some(kind) = &rejection_kind {
+ s.last_item_rejection = Some(kind.clone());
+ }
+ // A run of batches that applied nothing is not "replication
+ // working". Only a batch that landed something clears it.
+ if unapplied_batches > 0 && docs == 0 && deletes == 0 {
+ s.consecutive_unapplied_batches = s
+ .consecutive_unapplied_batches
+ .saturating_add(unapplied_batches);
} else {
- s.consecutive_conflict_only_batches = 0;
+ s.consecutive_unapplied_batches = 0;
}
- if s.consecutive_conflict_only_batches >= CONFLICT_ONLY_UNHEALTHY_AFTER {
- s.last_error = Some(format!(
- "target rejected every action of the last {} batches with \
- version_conflict_engine_exception — it holds a higher version for \
- every document this tap sends, so nothing is being replicated",
- s.consecutive_conflict_only_batches
- ));
+ if s.consecutive_unapplied_batches >= UNAPPLIED_UNHEALTHY_AFTER {
+ let run = s.consecutive_unapplied_batches;
+ // Name the cause the target gave *this poll*, not whatever it
+ // last gave: a conflict and a mapping error need opposite
+ // responses from the operator, and a stale reason would send
+ // them the wrong way. `item_failures` is this poll's count.
+ let reason = if item_failures > 0 {
+ let kind = rejection_kind
+ .as_deref()
+ .or(s.last_item_rejection.as_deref())
+ .unwrap_or("an unnamed error");
+ format!(
+ "target accepted nothing in the last {run} batches — it rejected \
+ every action, most recently with {kind}. Nothing is being \
+ replicated; these documents are being dropped, not retried."
+ )
+ } else {
+ format!(
+ "target rejected every action of the last {run} batches with \
+ version_conflict_engine_exception — it holds a higher version for \
+ every document this tap sends, so nothing is being replicated"
+ )
+ };
+ s.last_error = Some(reason);
true
} else {
s.last_error = None;
@@ -1092,10 +1158,11 @@ impl WalTap {
});
if unhealthy {
warn!(
- index = %name, version_conflicts,
- "WAL tap: every action is being rejected as a version conflict — the \
- target holds higher versions than this node. _stats reports the index \
- unhealthy; check that the target is not also fed by another writer."
+ index = %name, version_conflicts, item_failures,
+ rejection = ?rejection_kind,
+ "WAL tap: the target is accepting the request and applying none of it. \
+ _stats reports the index unhealthy; check last_item_rejection, and \
+ whether the target is also fed by another writer."
);
}
self.clear_backoff();
diff --git a/engine/crates/xerj-engine/tests/wal_tap_push.rs b/engine/crates/xerj-engine/tests/wal_tap_push.rs
index 87eb8fe7e..5a3b783f0 100644
--- a/engine/crates/xerj-engine/tests/wal_tap_push.rs
+++ b/engine/crates/xerj-engine/tests/wal_tap_push.rs
@@ -66,6 +66,48 @@ enum TargetSemantics {
/// is a rejected no-op, and the tap must say so rather than report a
/// healthy zero-lag stream.
ExternalVersioningAheadBy(u64),
+ /// `200` with `errors: true` and a **non-conflict** rejection on every
+ /// item — the shape a target with an incompatible mapping produces.
+ ///
+ /// Operationally identical to `ExternalVersioningAheadBy`: not one
+ /// document is at the target. It exists separately because the health
+ /// signal used to count only the conflict case, so this — every document
+ /// dropped, permanently, with the cursor advancing past them — read as
+ /// `healthy: true`, `last_error: null`.
+ RejectsEveryItem,
+}
+
+/// Answer a `_bulk` the way a target with an incompatible mapping does:
+/// `200 OK`, `errors: true`, and a `mapper_parsing_exception` per item.
+///
+/// Note the status: the request succeeded. `send_bulk`'s whole-request failure
+/// path is not involved, the cursor advances past every one of these documents
+/// (deliberately — see `WalTap::send_bulk`), and they are gone.
+fn reject_every_item(body: &str) -> String {
+ let mut items = Vec::new();
+ let mut lines = body.lines();
+ while let Some(meta_line) = lines.next() {
+ if meta_line.trim().is_empty() {
+ continue;
+ }
+ let meta: Value = serde_json::from_str(meta_line).expect("action line");
+ let (action, spec) = meta
+ .as_object()
+ .and_then(|o| o.iter().next())
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .expect("action object");
+ if action != "delete" {
+ let _ = lines.next().expect("source line");
+ }
+ items.push(json!({action: {
+ "_index": spec["_index"], "_id": spec["_id"], "status": 400,
+ "error": {
+ "type": "mapper_parsing_exception",
+ "reason": "failed to parse field [v] of type [long]",
+ },
+ }}));
+ }
+ json!({"took": 1, "errors": true, "items": items}).to_string()
}
struct StubTarget {
@@ -150,11 +192,23 @@ impl StubTarget {
/// Apply one `_bulk` NDJSON body under [`TargetSemantics::ExternalVersioning`]
/// and return the ES-shaped response body.
///
-/// Deliberately implements the ES rule and not a friendlier one: an `index`
-/// action with `version_type: external` applies iff `version > stored`, a
-/// `delete` the same, and a rejection is
-/// `{"status":409,"error":{"type":"version_conflict_engine_exception", …}}`
-/// with the stored document left alone.
+/// Deliberately implements the ES rule and not a friendlier one:
+///
+/// * an `_id` the target does **not** hold is CREATED, at whatever external
+/// version was supplied — external versioning exists to let an outside
+/// system own the version line, so there is no floor to clear;
+/// * an `_id` it does hold is overwritten iff `version > stored`;
+/// * otherwise the item comes back
+/// `{"status":409,"error":{"type":"version_conflict_engine_exception", …}}`
+/// with the stored document left alone.
+///
+/// The create case is load-bearing. Seeding `stored = incoming` on first
+/// sight — which `held.entry(id).or_insert(incoming + ahead_by)` did whenever
+/// `ahead_by == 0` — made `incoming > stored` false for the FIRST delivery of
+/// every document, so the tap's first send was answered `409` and the
+/// convergence test never observed a single accepted item. It passed anyway,
+/// because "the redelivery changed nothing" is trivially true when the first
+/// delivery changed nothing either.
fn apply_external_versioning(body: &str, held: &mut HashMap<String, u64>, ahead_by: u64) -> String {
let mut items = Vec::new();
let mut errors = false;
@@ -181,22 +235,47 @@ fn apply_external_versioning(body: &str, held: &mut HashMap<String, u64>, ahead_
"the tap must send external versioning or none of this applies"
);
- // `ahead_by > 0` models a second writer that got to this target
- // first: seed a version the tap can never beat.
- let stored = *held.entry(id.clone()).or_insert(incoming + ahead_by);
- if incoming > stored {
- held.insert(id.clone(), incoming);
- let result = if action == "delete" {
- "deleted"
- } else {
- "created"
+ // What the target holds for this `_id`, if anything. `ahead_by > 0`
+ // models a second writer that got to this target first, so the very
+ // first sight of an `_id` is already occupied by a version the tap can
+ // never beat; `ahead_by == 0` means the tap is the only writer and an
+ // unseen `_id` is genuinely absent.
+ let stored = match held.get(&id).copied() {
+ Some(v) => Some(v),
+ None if ahead_by > 0 => {
+ let seeded = incoming + ahead_by;
+ held.insert(id.clone(), seeded);
+ Some(seeded)
+ }
+ None => None,
+ };
+ // Absent → create. Present → strictly-greater wins. This is the ES
+ // rule; anything stricter makes the first delivery a conflict and the
+ // whole at-least-once story untestable.
+ let applies = match stored {
+ None => true,
+ Some(s) => incoming > s,
+ };
+ if applies {
+ let result = match (action.as_str(), stored) {
+ ("delete", None) => "not_found",
+ ("delete", Some(_)) => "deleted",
+ (_, None) => "created",
+ (_, Some(_)) => "updated",
};
+ // A delete leaves a tombstone AT the external version, exactly as
+ // ES does — dropping the entry instead would let a redelivered
+ // `index` at a lower version resurrect the document, which is the
+ // failure this whole mechanism exists to prevent.
+ held.insert(id.clone(), incoming);
items.push(json!({action: {
"_index": index, "_id": id, "_version": incoming,
"result": result,
- "status": 201,
+ "status": if result == "created" { 201 } else { 200 },
}}));
} else {
+ let stored =
+ stored.expect("the conflict branch is only reachable with a stored version");
errors = true;
items.push(json!({action: {
"_index": index, "_id": id, "_version": stored, "status": 409,
@@ -268,6 +347,7 @@ async fn serve_one(
guard.versions = held;
out
}
+ TargetSemantics::RejectsEveryItem => reject_every_item(&body),
};
guard.bodies.push(body);
response
@@ -767,6 +847,28 @@ async fn redelivery_converges_at_a_target_that_honours_external_versioning() {
"all four documents must reach the target: {after_first:?}"
);
+ // The first delivery must have been ACCEPTED, not merely attempted. Take
+ // this away and the rest of the test is vacuous: "the redelivery changed
+ // nothing" is trivially true if nothing ever landed, and the assertions
+ // below would hold even if the tap sent `version: 0` on every action.
+ let first = engine.wal_tap.stats();
+ let first = first.get("edge-logs").expect("stats");
+ assert_eq!(
+ first.docs_shipped, 4,
+ "the FIRST delivery of a document must be created at a target that honours \
+ external versioning — it is absent, so there is no version to conflict with \
+ (conflicts so far: {}, failures: {})",
+ first.version_conflicts, first.item_failures
+ );
+ assert_eq!(
+ first.version_conflicts, 0,
+ "and nothing may be reported as a conflict before anything has been redelivered"
+ );
+ assert!(
+ first.last_shipped_seq > 0,
+ "the accepted watermark must have moved off zero"
+ );
+
// Force the redelivery the at-least-once contract permits: rewind the
// cursor to the start of the stream and poll again. Every action is
// re-sent with the same seq_no as its external version.
@@ -778,14 +880,27 @@ async fn redelivery_converges_at_a_target_that_honours_external_versioning() {
after_redelivery, after_first,
"a redelivery must be a no-op at the target, not a resurrection: {after_redelivery:?}"
);
+ assert!(
+ target.request_count() > 1,
+ "the redelivery must actually have been sent"
+ );
let stats = engine.wal_tap.stats();
let edge = stats.get("edge-logs").expect("stats");
- assert!(
- edge.version_conflicts >= 4,
- "the redelivered actions must be REPORTED as conflicts, not silently counted as \
- shipped (got {})",
- edge.version_conflicts
+ assert_eq!(
+ edge.version_conflicts, 4,
+ "each of the four redelivered actions must be REPORTED as a conflict, not \
+ silently counted as shipped"
+ );
+ assert_eq!(
+ edge.docs_shipped, 4,
+ "and a redelivery must not inflate the shipped count — the same four documents \
+ are at the target, they were not shipped eight times"
+ );
+ assert_eq!(
+ edge.last_shipped_seq, first.last_shipped_seq,
+ "the watermark is the highest ACCEPTED seq_no; a rejected redelivery cannot \
+ move it and must not move it backwards either"
);
assert_eq!(
edge.item_failures, 0,
@@ -856,6 +971,129 @@ async fn a_target_that_rejects_every_action_is_reported_unhealthy_with_real_lag(
);
}
+/// The same lie, told the other way round: a target that rejects every item
+/// for a reason that is **not** a version conflict.
+///
+/// `mapper_parsing_exception` on every action is `200 OK` with `errors: true`,
+/// so no send fails, `last_error` stays `None`, and the cursor advances past
+/// every dropped document — permanently, because per-item failures are passed
+/// over by design. The first version of the health signal counted only the
+/// conflict case, and this state therefore read `healthy: true`,
+/// `last_error: null`, `docs_shipped: 0`, `item_failures: 5` — measured — while
+/// every single document was being thrown away. `healthy` is the one boolean
+/// operators are told to alert on; it does not get to be right only for the
+/// failure mode we thought of first.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn a_target_that_drops_every_item_is_reported_unhealthy() {
+ let target = StubTarget::start_with(TargetSemantics::RejectsEveryItem).await;
+ let dir = TempDir::new().unwrap();
+ let engine = engine_with_tap(&dir, tap_config(&target.url, &["edge-logs"]));
+
+ for round in 0..5 {
+ write_docs(&engine, "edge-logs", &[&format!("d{round}")]).await;
+ engine.wal_tap.tick(&engine).await;
+ }
+
+ let stats = engine.wal_tap.stats();
+ let edge = stats.get("edge-logs").expect("stats for edge-logs");
+ assert!(
+ target.request_count() >= 5,
+ "the tap must actually have tried: {}",
+ target.request_count()
+ );
+ assert_eq!(
+ edge.docs_shipped, 0,
+ "nothing was accepted, so nothing may be counted as shipped"
+ );
+ assert_eq!(
+ edge.item_failures, 5,
+ "every dropped document must be counted"
+ );
+ assert_eq!(
+ edge.version_conflicts, 0,
+ "these are not conflicts — that distinction is the point"
+ );
+ assert_eq!(
+ edge.last_shipped_seq, 0,
+ "the watermark must come from ACCEPTED items"
+ );
+ assert!(
+ !edge.healthy(),
+ "a target dropping every document must not read as healthy \
+ (docs_shipped {}, item_failures {}, last_error {:?})",
+ edge.docs_shipped,
+ edge.item_failures,
+ edge.last_error
+ );
+ assert_eq!(
+ edge.last_item_rejection.as_deref(),
+ Some("mapper_parsing_exception"),
+ "and the operator must be told what the target called them"
+ );
+ assert!(
+ edge.last_error
+ .as_deref()
+ .unwrap_or_default()
+ .contains("mapper_parsing_exception"),
+ "the reason belongs in last_error too, not only in a side counter: {:?}",
+ edge.last_error
+ );
+
+ // Lag must be real, for the same reason as in the conflict case.
+ let head = engine
+ .get_index("edge-logs")
+ .unwrap()
+ .current_seq_no()
+ .saturating_sub(1);
+ assert!(
+ head > edge.last_shipped_seq,
+ "lag must be non-zero (head {head}, watermark {})",
+ edge.last_shipped_seq
+ );
+}
+
+/// A rejection is not a permanent verdict on the index: once the target starts
+/// taking documents again, `healthy` must come back. A latch would be as
+/// useless as the missing signal was — an operator who cannot see a fix land
+/// stops trusting the boolean.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn health_recovers_once_the_target_accepts_again() {
+ let bad = StubTarget::start_with(TargetSemantics::RejectsEveryItem).await;
+ let good = StubTarget::start().await;
+ let dir = TempDir::new().unwrap();
+ let engine = engine_with_tap(&dir, tap_config(&bad.url, &["edge-logs"]));
+
+ for round in 0..5 {
+ write_docs(&engine, "edge-logs", &[&format!("d{round}")]).await;
+ engine.wal_tap.tick(&engine).await;
+ }
+ assert!(!engine.wal_tap.stats()["edge-logs"].healthy());
+
+ // Point at a target that takes writes and ship one more document.
+ engine
+ .wal_tap
+ .set_config(tap_config(&good.url, &["edge-logs"]));
+ write_docs(&engine, "edge-logs", &["recovered"]).await;
+ engine.wal_tap.tick(&engine).await;
+
+ let stats = engine.wal_tap.stats();
+ let edge = stats.get("edge-logs").expect("stats");
+ assert!(
+ edge.healthy(),
+ "one applied batch must clear the run: {:?}",
+ edge.last_error
+ );
+ assert_eq!(
+ edge.consecutive_unapplied_batches, 0,
+ "the run counter must reset, not decay"
+ );
+ assert!(
+ edge.docs_shipped >= 1,
+ "and the document must actually have landed: {}",
+ edge.docs_shipped
+ );
+}
+
/// `PUT /_xerj/wal_tap` advertises "runtime config, no restart". That implied
/// a durability that did not exist: the value lived only in an in-memory
/// `RwLock`, so a restart reverted the tap to the file config — normally
diff --git a/engine/crates/xerj-storage/src/wal.rs b/engine/crates/xerj-storage/src/wal.rs
index a5e40513e..1df629504 100644
--- a/engine/crates/xerj-storage/src/wal.rs
+++ b/engine/crates/xerj-storage/src/wal.rs
@@ -1734,6 +1734,16 @@ pub struct WalShardTail {
pub truncated: bool,
/// Frames skipped because their payload did not decode.
pub corrupt_skipped: usize,
+ /// Bytes this poll actually read off disk, summed over every generation
+ /// file it touched.
+ ///
+ /// The windowed reader exists to keep this proportional to the bytes
+ /// *appended since the last poll* rather than to the size of the stream —
+ /// a caught-up poll costs one 16-byte header read per generation file it
+ /// opens. Exposed so that property is testable through this entry point
+ /// instead of by inspecting the reader's internals, which is what let the
+ /// pre-window `fs::read(path)` shape go uncaught.
+ pub bytes_read: u64,
}
/// Every WAL shard stream under `wal_root`, as `(shard_name, dir)`.
@@ -1801,6 +1811,7 @@ pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize)
gap: false,
truncated: false,
corrupt_skipped: 0,
+ bytes_read: 0,
};
};
let first = gens[0];
@@ -1832,6 +1843,7 @@ pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize)
gap: false,
truncated: false,
corrupt_skipped: 0,
+ bytes_read: scan.bytes_read,
};
}
};
@@ -1888,6 +1900,7 @@ pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize)
let mut entries: Vec<ReplayEntry> = Vec::new();
let mut corrupt_skipped = 0usize;
+ let mut bytes_read = 0u64;
let mut truncated = false;
let mut out_cursor = WalTailCursor {
generation: start_gen,
@@ -1920,6 +1933,7 @@ pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize)
let scan = tail_wal_file(&wal_path(dir, gen), from, allow_resync, budget, true);
corrupt_skipped += scan.corrupt;
+ bytes_read += scan.bytes_read;
entries.extend(scan.entries);
out_cursor = WalTailCursor {
generation: gen,
@@ -1938,6 +1952,7 @@ pub fn tail_shard(dir: &Path, cursor: Option<WalTailCursor>, max_entries: usize)
gap,
truncated,
corrupt_skipped,
+ bytes_read,
}
}
@@ -1951,14 +1966,19 @@ struct FileTail {
/// Stopped because the entry budget ran out.
truncated: bool,
corrupt: usize,
+ /// Bytes actually read off this file by this poll.
+ bytes_read: u64,
}
-/// How much one buffer refill pulls in.
+/// How much one buffer refill reads ahead.
+///
+/// Sized like [`WAL_BUF_CAP`] on the writer side: big enough that a reader
+/// catching up on a burst of small frames pays one `read` for the lot.
///
-/// Sized like [`WAL_BUF_CAP`] on the writer side: big enough that a caught-up
-/// reader picks up a burst of small frames in one `read`, small enough that a
-/// poll over an idle 1 GiB generation costs one 16-byte header read and
-/// nothing else.
+/// It is deliberately **not** applied to the file-header read — see
+/// [`WalWindow::fill_exact`]. That read is the only one a caught-up poll
+/// performs, so charging it 64 KiB of read-ahead that is discarded unread put
+/// the steady-state cost back to 64 KiB per shard per poll.
const WAL_TAIL_READ_CHUNK: usize = 64 * 1024;
/// Bytes of frame header needed before the payload length is known:
@@ -1994,6 +2014,13 @@ struct WalWindow {
buf: Vec<u8>,
/// Read position inside `buf`.
cur: usize,
+ /// Bytes this window has actually pulled off the file.
+ ///
+ /// Not diagnostics: it is the property the windowed reader exists to
+ /// bound, and the only way a test can fail if this path regresses to
+ /// `fs::read`. Surfaced all the way out through
+ /// [`WalShardTail::bytes_read`].
+ bytes_read: u64,
}
impl WalWindow {
@@ -2006,6 +2033,7 @@ impl WalWindow {
base: 0,
buf: Vec::new(),
cur: 0,
+ bytes_read: 0,
})
}
@@ -2027,7 +2055,40 @@ impl WalWindow {
/// Make at least `need` bytes readable at the cursor, pulling more of the
/// file in if necessary. `false` means the file ends first.
+ ///
+ /// Reads ahead by [`WAL_TAIL_READ_CHUNK`] so a burst of small frames costs
+ /// one syscall. Use [`WalWindow::fill_exact`] where the read-ahead would
+ /// be pure waste.
fn fill(&mut self, need: usize) -> bool {
+ self.fill_chunked(need, WAL_TAIL_READ_CHUNK)
+ }
+
+ /// [`WalWindow::fill`] with no read-ahead at all: pull `need` bytes and
+ /// not one more.
+ ///
+ /// Same escape hatch Lucene gives its own buffered reader:
+ /// `BufferedIndexInput.readBytes(byte[], int, int, boolean useBuffer)`
+ /// (`lucene/core/src/java/org/apache/lucene/store/BufferedIndexInput.java:91-134`,
+ /// Apache-2.0) routes a read around the read-ahead buffer whenever
+ /// buffering would not pay — "there's no performance reason not to read it
+ /// all at once … no need to reread what we had in the buffer". Adapted,
+ /// not copied: the case here is the mirror image, a read too *small* to
+ /// justify a chunk that is then discarded.
+ ///
+ /// The header read is the caller that needs this. It is followed
+ /// immediately by `seek_to(start)`, which throws the buffer away, so any
+ /// read-ahead there is discarded unread — and on a *caught-up* poll it is
+ /// the only read that happens, which made "a caught-up poll costs one
+ /// 16-byte header read" false by 4096x: `fill(16)` took the
+ /// `.max(WAL_TAIL_READ_CHUNK)` branch and pulled 64 KiB, per shard, per
+ /// poll. Measured by
+ /// [`a_caught_up_poll_does_not_read_the_whole_generation`] over a
+ /// 4,176,200-byte generation: 65,536 bytes before this split, 16 after.
+ fn fill_exact(&mut self, need: usize) -> bool {
+ self.fill_chunked(need, need)
+ }
+
+ fn fill_chunked(&mut self, need: usize, chunk: usize) -> bool {
if self.available() >= need {
return true;
}
@@ -2042,7 +2103,7 @@ impl WalWindow {
if read_from >= self.len {
return false;
}
- let want = (need - self.buf.len()).max(WAL_TAIL_READ_CHUNK);
+ let want = (need - self.buf.len()).max(chunk);
let want = want.min((self.len - read_from) as usize);
let start = self.buf.len();
self.buf.resize(start + want, 0);
@@ -2055,7 +2116,10 @@ impl WalWindow {
self.buf.truncate(start);
return false;
}
- Ok(n) => self.buf.truncate(start + n),
+ Ok(n) => {
+ self.bytes_read += n as u64;
+ self.buf.truncate(start + n);
+ }
Err(e) if e.kind() == io::ErrorKind::Interrupted => self.buf.truncate(start),
Err(_) => {
self.buf.truncate(start);
@@ -2105,6 +2169,7 @@ fn tail_wal_file(
drained: true,
truncated: false,
corrupt: 0,
+ bytes_read: 0,
};
}
Err(e) => {
@@ -2115,18 +2180,24 @@ fn tail_wal_file(
drained: false,
truncated: false,
corrupt: 0,
+ bytes_read: 0,
};
}
};
win.seek_to(0);
- if !win.fill(WAL_HEADER_LEN as usize) || &win.buf[..4] != WAL_MAGIC {
+ // `fill_exact`, not `fill`: the very next statement is `seek_to(start)`,
+ // which discards the buffer, so read-ahead here is read-and-throw-away —
+ // and on a caught-up poll this is the ONLY read, so the read-ahead was the
+ // whole per-poll cost.
+ if !win.fill_exact(WAL_HEADER_LEN as usize) || &win.buf[..4] != WAL_MAGIC {
return FileTail {
entries: Vec::new(),
end_offset: from_offset.max(WAL_HEADER_LEN),
drained: false,
truncated: false,
corrupt: 0,
+ bytes_read: win.bytes_read,
};
}
let generation = u64::from_le_bytes(win.buf[4..12].try_into().unwrap());
@@ -2142,6 +2213,7 @@ fn tail_wal_file(
drained: false,
truncated: false,
corrupt: 0,
+ bytes_read: win.bytes_read,
};
}
win.seek_to(start);
@@ -2158,6 +2230,7 @@ fn tail_wal_file(
drained: false,
truncated: true,
corrupt,
+ bytes_read: win.bytes_read,
};
}
if win.pos() >= win.len {
@@ -2167,6 +2240,7 @@ fn tail_wal_file(
drained: true,
truncated: false,
corrupt,
+ bytes_read: win.bytes_read,
};
}
@@ -2213,6 +2287,7 @@ fn tail_wal_file(
drained: true,
truncated: false,
corrupt,
+ bytes_read: win.bytes_read,
};
}
None => {
@@ -2225,6 +2300,7 @@ fn tail_wal_file(
drained: false,
truncated: false,
corrupt,
+ bytes_read: win.bytes_read,
};
}
}
@@ -3316,8 +3392,12 @@ mod tests {
/// interval that is ~60x read amplification of the node's live ingest
/// volume per flush window, per shard.
///
- /// Asserted structurally — a caught-up poll never materialises a buffer
- /// the size of the file — by making the file large and the poll a no-op.
+ /// Asserted **through `tail_shard`**, on the bytes it reports reading.
+ /// An earlier version of this test hand-built a `WalWindow`, seeked it
+ /// past the header read and asserted on `win.buf.len()`; it never called
+ /// the entry point, so it could not fail if this path regressed to
+ /// `fs::read(path)` — and it did not fail on the 64 KiB header read-ahead
+ /// that made a caught-up poll cost 65,536 bytes rather than 16.
#[test]
fn a_caught_up_poll_does_not_read_the_whole_generation() {
let dir = tempfile::tempdir().unwrap();
@@ -3347,24 +3427,82 @@ mod tests {
let len = std::fs::metadata(wal_path(dir.path(), 0)).unwrap().len();
assert!(len > 512 * 1024, "the file must be big enough to matter");
- // The window the caught-up poll opens: cursor is at EOF, so it reads
- // the 16-byte header and stops. `WalWindow` is what proves it — it
- // never buffers more than one frame plus a chunk.
- let mut win = WalWindow::open(&wal_path(dir.path(), 0)).unwrap();
- win.seek_to(caught_up.cursor.offset);
- assert!(!win.fill(1), "there is nothing left to read at EOF");
- assert!(
- win.buf.len() < WAL_TAIL_READ_CHUNK,
- "a caught-up poll buffered {} bytes of a {len}-byte file",
- win.buf.len()
+ // The poll that matters: the cursor is at EOF, nothing was appended.
+ // It must read the 16-byte file header to identify the generation and
+ // then stop — not the file (`fs::read`, the original shape), and not a
+ // 64 KiB read-ahead chunk it immediately throws away.
+ let idle = tail_shard(dir.path(), Some(caught_up.cursor), 10_000);
+ assert!(idle.entries.is_empty(), "nothing was appended");
+ assert_eq!(
+ idle.bytes_read, WAL_HEADER_LEN,
+ "a caught-up poll read {} bytes of a {len}-byte generation; it must read \
+ the {WAL_HEADER_LEN}-byte header and stop",
+ idle.bytes_read
);
- // And it is still correct: a poll after new appends reads only those.
+ // And it is still correct: a poll after new appends reads only those,
+ // plus the header — never the history in front of them.
let mut w = make_writer(dir.path());
w.append(&doc("late")).unwrap();
drop(w);
- let after = tail_shard(dir.path(), Some(caught_up.cursor), 10_000);
+ let appended = std::fs::metadata(wal_path(dir.path(), 0)).unwrap().len() - len;
+ let after = tail_shard(dir.path(), Some(idle.cursor), 10_000);
assert_eq!(doc_ids(&after), vec!["+late"]);
+ assert!(
+ after.bytes_read <= WAL_HEADER_LEN + appended,
+ "a poll that is one frame behind read {} bytes for {appended} bytes of new \
+ data in a {len}-byte generation",
+ after.bytes_read
+ );
+ }
+
+ /// The same property one level up: `tail_shard` must not read the history
+ /// in front of a cursor that is far into an established stream.
+ ///
+ /// `fs::read(path)` — the shape this replaced — passes
+ /// [`a_caught_up_poll_does_not_read_the_whole_generation`]'s *correctness*
+ /// assertions perfectly. Only the byte count separates them.
+ #[test]
+ fn a_poll_from_the_middle_of_a_generation_reads_forward_only() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut w = make_writer(dir.path());
+ let mut lcg: u64 = 0x9E37_79B9_7F4A_7C15;
+ let mut noise = || {
+ let mut s = String::with_capacity(8192);
+ for _ in 0..1024 {
+ lcg = lcg.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
+ s.push_str(&format!("{:016x}", lcg));
+ }
+ s
+ };
+ for i in 0..256 {
+ w.append(&WalEntry::Index {
+ doc_id: format!("d{i}"),
+ source: serde_json::json!({ "v": noise() }),
+ })
+ .unwrap();
+ }
+ // Read the whole thing once so the cursor sits at the end…
+ let full = tail_shard(dir.path(), None, 10_000);
+ assert_eq!(full.entries.len(), 256);
+ let history = std::fs::metadata(wal_path(dir.path(), 0)).unwrap().len();
+ assert!(history > 512 * 1024);
+
+ // …then append one small frame and poll for exactly it.
+ w.append(&doc("tail")).unwrap();
+ drop(w);
+ let grown = std::fs::metadata(wal_path(dir.path(), 0)).unwrap().len();
+ let appended = grown - history;
+ assert!(appended < 4096, "the new frame must be small: {appended}");
+
+ let incremental = tail_shard(dir.path(), Some(full.cursor), 10_000);
+ assert_eq!(doc_ids(&incremental), vec!["+tail"]);
+ assert!(
+ incremental.bytes_read < history / 4,
+ "reading {appended} new bytes cost {} of a {grown}-byte file — the poll is \
+ re-reading history",
+ incremental.bytes_read
+ );
}
/// A rotated generation still resyncs past a corrupt region, exactly as
diff --git a/scripts/verify-wal-tap.sh b/scripts/verify-wal-tap.sh
index 63f4514d8..c5daa1a10 100755
--- a/scripts/verify-wal-tap.sh
+++ b/scripts/verify-wal-tap.sh
@@ -16,9 +16,11 @@
# es_compat.rs:2990), so a xerj target is precisely the target that does not
# implement the mechanism, and running two xerj nodes cannot exercise it.
# That claim is covered instead by
-# `redelivery_converges_at_a_target_that_honours_external_versioning` and
-# `a_target_that_rejects_every_action_is_reported_unhealthy_with_real_lag` in
-# wal_tap_push.rs, against a stub that implements the ES rule. Against an
+# `redelivery_converges_at_a_target_that_honours_external_versioning`,
+# `a_target_that_rejects_every_action_is_reported_unhealthy_with_real_lag` and
+# `a_target_that_drops_every_item_is_reported_unhealthy` in
+# wal_tap_push.rs, against stubs that implement the ES rule and the
+# reject-everything shape. Against an
# Elasticsearch or OpenSearch target the mechanism is live; against a xerj
# target the tap degrades to last-write-wins by arrival, as
# `xerj-engine/src/wal_tap.rs` documents.