Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(engine,api): a refusal must survive a restart, and GET must speak ES

xerj-org88e9068ea921
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bfde84eea..4e9e5110e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -92,19 +92,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
into `400` for any pipeline using an ES processor or option this build does
not implement. Read that entry for the full list.
- **What is NOT broken, deliberately.** A definition already in
- `cluster_state.json` was accepted by whichever build wrote it, and there is
- no caller left to answer `400` at boot. Boot replay therefore compiles in a
- compatibility mode that reproduces the *previously shipped* behaviour for
- every check this sweep added (unknown `grok` pattern name, unknown `convert`
- target, a bare string where an array is required, `set.copy_from`, a
- processor-level `if`/`on_failure`/`ignore_failure`), so **an upgrade alone
- never turns a running cluster's writes from `201` into `400`**. Each one is
- logged at ERROR naming the pipeline and the offending config, and recorded in
- `Engine::degraded_pipelines`; a re-`PUT` of the same definition answers `400`
- with the same reason, which is the repair path. A definition that did not
- compile before the upgrade either (unknown stage type, missing required
- field) still fails at boot and is recorded unrunnable, as before.
+ **What is NOT broken, deliberately.** A definition persisted by a build with
+ **no gate** was accepted by whichever build wrote it, and there is no caller
+ left to answer `400` at boot. Boot replay therefore compiles *those*
+ definitions in a compatibility mode that reproduces the previously shipped
+ behaviour for every check this sweep added (unknown `grok` pattern name,
+ unknown `convert` target, a bare string where an array is required,
+ `set.copy_from`, a processor-level `if`/`on_failure`/`ignore_failure`), so
+ **an upgrade alone never turns a running cluster's writes from `201` into
+ `400`**. Each one is logged at ERROR naming the pipeline and the offending
+ config, and recorded in `Engine::degraded_pipelines`; a re-`PUT` of the same
+ definition answers `400` with the same reason, which is the repair path. A
+ definition that did not compile before the upgrade either (unknown stage
+ type, missing required field) still fails at boot and is recorded unrunnable,
+ as before.
+
+ **Which definitions those are is decided by provenance, not by the calendar.**
+ A definition THIS build refused at `PUT` time is recorded in
+ `<data_dir>/ingest-pipeline-refusals.json` and replayed at *definition*
+ strictness, so the refusal survives a restart. Without that marker the replay
+ could not tell "written by an older, laxer build" from "written by this build
+ and answered `400`", and a plain restart overturned the answer the operator
+ had already been given: measured, `PUT` a `{"remove": {"field": "secret"}}`
+ pipeline, add an `if` guard to it (refused — every write `400`s), restart the
+ node and nothing else, and the identical write answered `201` with `secret`
+ dropped from a document the guard EXCLUDES. It covered every check the sweep
+ added; only an unimplemented *stage* survived a restart, because the raw ES
+ body it stores does not deserialise. This is the same pattern as an index's
+ `<index>/analysis-binding.json`: the marker's ABSENCE is the load-bearing
+ signal.
+
+ The marker is provenance, not a tombstone. A marked definition that compiles
+ cleanly on the new build — because that build implements what the refusing
+ one could not — clears its own marker at boot and runs, with an INFO line; a
+ successful re-`PUT` or a `DELETE` clears it too. If the file exists but
+ cannot be read or parsed, no pipeline's provenance is known, so **every**
+ persisted pipeline is replayed at definition strictness and any that fails is
+ recorded unrunnable with the file named in the reason — fail closed and
+ loudly, rather than silently reopening the hole. An older binary reading a
+ data dir written by this one simply ignores the file; it is a sidecar
+ precisely because `cluster_state.json`'s format-1 envelope is
+ `deny_unknown_fields` and widening it would break downgrades.
The same rule applies one level up. Teaching the analysis resolver the
canonical `settings.index.analysis` nesting (see the analysis entry above) is
@@ -196,6 +224,45 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`rename`. The stages→processors conversion now inverts both halves of the
translation, name and config.
+- **`GET /_ingest/pipeline[/{id}]` answers in Elasticsearch's `processors`
+ vocabulary instead of XERJ's internal `stages` shape**
+ ([#204](https://github.com/xerj-org/xerj/issues/204)). Two shapes reach the
+ store: the translated `stages` body (everything that compiles) and the raw ES
+ body (kept verbatim for a definition XERJ stores but cannot run). Only the
+ second was ever ES-shaped, so `GET` spoke XERJ's vocabulary for every pipeline
+ that *worked* — measured before this release, an ES `rename` pipeline came
+ back as
+ `{"p":{"description":"d","stages":[{"type":"field_rename","config":{"mappings":{"a":"b"}}}]}}`.
+ This is a wire-visible change on both `GET /_ingest/pipeline/{id}` and
+ `GET /_ingest/pipeline`. It also mattered beyond cosmetics: `GET`'s output is
+ what an operator edits and `PUT`s back, and a `stages`-shaped body takes the
+ handler's pass-through branch — which is exactly how the restart hole
+ described under *Changed* was reached in ordinary use.
+
+ `set` is rendered with an explicit `"override"`, always, because it is the one
+ key whose default differs between the two vocabularies (Elasticsearch `true`,
+ XERJ's native `set` stage `false`). Emitting a bare ES `set` for a native
+ stage would claim it overwrites when it preserves. A pipeline created through
+ `PUT /_ingest/pipeline` therefore shows `"override": true` even when the
+ caller omitted it — that is the value XERJ applies, and it round-trips: PUTting
+ `GET`'s own output back cannot silently flip the stage's behaviour. Relatedly,
+ `_simulate`'s `set` interpreter honoured no `override` at all and always
+ overwrote, so it reported a document the ingest path would never produce; it
+ now applies Elasticsearch's rule (default `true`; `false` leaves an existing
+ non-null value alone).
+
+- **Three wire-visible refusals that were fixed in this sweep but not written
+ down** ([#204](https://github.com/xerj-org/xerj/issues/204)). All three
+ replace a silent fallback with an error, which is the point of the issue, but
+ each changes a status code:
+ `POST /v1/admin/backup` answers `400` on a request body that is present but
+ unparseable, where it previously ran a *default* backup under a success
+ response; `GET /{index}/_stats` and `GET /_all/_stats` carry an added
+ non-Elasticsearch key `primaries.mappings.schema_persist_failures` inside an
+ otherwise ES-shaped response; and the authorization layer's response pruning
+ answers `500` when it cannot parse the body it was asked to filter, instead
+ of falling back to the unfiltered bytes.
+
**The refusal now covers every ingest path, not only `PUT /{index}/_doc`.**
`POST /_bulk?pipeline=`, `index.default_pipeline` under `_bulk`,
`_reindex` `dest.pipeline` and `POST /{index}/_update_by_query?pipeline=`
@@ -213,24 +280,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
`_bulk` item no longer reports `"result": "deleted"` alongside its own
`status: 400`, which claimed a deletion that never happened.
+ **`ignore_missing: false` is refused on purpose, and it is not the same call
+ as `ignore_failure: false`.** Both are Elasticsearch defaults that ES clients
+ emit verbatim, so the difference is worth stating plainly: the rule is *accept
+ the value this build actually implements*, and the two land on opposite sides
+ of it. `ignore_failure: false` means "a failing processor is not ignored",
+ which is exactly what XERJ does, so it is accepted. `ignore_missing: false`
+ means "FAIL the document when the field is absent", which XERJ cannot do at
+ all — `ProcessAction` has no error variant, and every field-reading stage
+ passes the document through untouched. Accepting it would be precisely the
+ silent lie this issue exists to remove, so it is refused: a `remove` /
+ `rename` / `convert` / `date` processor that spells out `ignore_missing:
+ false` registers and then `400`s every write through it. **Omitting the key
+ is accepted** and behaves as `true`. That asymmetry — omission accepted,
+ the ES default written out refused — is deliberate but is a hard `400` for
+ ES-generated pipelines; strip the key, or set it to `true`, to state what
+ XERJ will actually do. `ignore_empty_value` is the mirror image: omitting it
+ or writing `false` is honoured exactly, `true` is refused.
+
**Known gaps, stated rather than closed:** `_simulate` interprets the stored
ES body directly and covers processors the compiled path does not, so a
pipeline recorded as unrunnable can still show a transformation under
`_simulate` that ingest refuses to perform; `GET /_ingest/pipeline/{id}`
- returns the stored definition (the ES body for an unrunnable pipeline, the
- compiled shape otherwise) with no runnability signal, so an operator only
- learns at write time; a write addressed to an **alias** does not pick up the
+ carries no runnability signal — it renders the stored definition in ES
+ vocabulary whether or not this build can run it, so an operator only learns
+ at write time; a write addressed to an **alias** does not pick up the
backing index's `default_pipeline`; `_update_by_query` reports a `drop`
processor as a per-document failure, because it updates in place and has no
- delete path; `Engine::degraded_pipelines` is in-memory only and has no HTTP
- surface yet, so a boot-replay degradation is visible in the startup log and
- nowhere else; and **an OMITTED `ignore_missing` still diverges from
- Elasticsearch** — ES defaults it to `false` and fails the document when the
- field is absent, while XERJ passes the document through unchanged, because a
- stage cannot fail a document at all (`ProcessAction` has no error variant).
- Writing `ignore_missing: false` explicitly is refused; omitting it is
- accepted and behaves as `true`. `ignore_empty_value` is the mirror image:
- omitting it or writing `false` is honoured exactly, `true` is refused.
+ delete path; and `Engine::degraded_pipelines` is in-memory only and has no
+ HTTP surface yet, so a boot-replay degradation is visible in the startup log
+ and nowhere else — unlike a definition-time refusal, which is now durable
+ (see *Changed*).
## [1.0.0-rc.16] - 2026-08-13
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index a31c67b6c..4d8a80e04 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -24528,6 +24528,25 @@ fn stage_to_es_processors(stage: &Value) -> Vec<Value> {
})
.collect()
}
+ "set" => {
+ // `override` is the one key whose DEFAULT differs between the two
+ // vocabularies: Elasticsearch's `set` defaults it to `true`, xerj's
+ // native `set` stage to `false` (see `put_ingest_pipeline`, which
+ // is why the translation writes it in). Rendering a stored stage
+ // without it would therefore be a lie in one direction or the
+ // other — for a native stage a bare ES `set` claims it overwrites,
+ // when it preserves. State it instead, always, with the value the
+ // stage actually applies.
+ let mut c = cfg.clone();
+ if let Some(map) = c.as_object_mut() {
+ let effective = map
+ .get("override")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ map.insert("override".to_string(), Value::Bool(effective));
+ }
+ vec![wrap(c)]
+ }
_ => vec![wrap(cfg)],
}
}
@@ -24537,6 +24556,135 @@ fn stages_to_es_processors(stages: &[Value]) -> Vec<Value> {
stages.iter().flat_map(stage_to_es_processors).collect()
}
+/// A stored pipeline definition as `GET /_ingest/pipeline` must answer it.
+///
+/// Two shapes reach `engine.pipelines`: the translated xerj `stages` body
+/// (everything that compiles) and the raw Elasticsearch body (kept verbatim
+/// for a definition this build stores but cannot run). Only the second was
+/// ever ES-shaped, so GET spoke xerj's internal vocabulary for every pipeline
+/// that worked — and that output is what an operator edits and PUTs back, which
+/// is how a `stages`-shaped body reached `put_ingest_pipeline`'s pass-through
+/// branch in the first place. `_simulate` was taught this inverse in this same
+/// sweep ([`stages_to_es_processors`]); GET was not.
+///
+/// A body that is already ES-shaped is returned untouched.
+fn stored_pipeline_as_es(doc: &Value) -> Value {
+ let Some(stages) = doc.get("stages").and_then(Value::as_array) else {
+ return doc.clone();
+ };
+ let mut out = serde_json::Map::new();
+ if let Some(obj) = doc.as_object() {
+ for (k, v) in obj {
+ if k != "stages" {
+ out.insert(k.clone(), v.clone());
+ }
+ }
+ }
+ out.insert(
+ "processors".to_string(),
+ Value::Array(stages_to_es_processors(stages)),
+ );
+ Value::Object(out)
+}
+
+#[cfg(test)]
+mod stored_pipeline_rendering_tests {
+ use super::*;
+
+ /// `GET /_ingest/pipeline/{id}` leaked xerj's internal `stages` vocabulary
+ /// for every pipeline that compiled. Measured before this fix:
+ /// `{"p":{"description":"d","stages":[{"type":"field_rename","config":
+ /// {"mappings":{"a":"b"}}}]}}`.
+ #[test]
+ fn a_stages_body_renders_as_elasticsearch_processors() {
+ let stored = json!({
+ "description": "d",
+ "stages": [{ "type": "field_rename", "config": { "mappings": { "a": "b" } } }]
+ });
+ let es = stored_pipeline_as_es(&stored);
+ assert_eq!(es["description"], "d");
+ assert_eq!(es["processors"][0]["rename"]["field"], "a", "{es}");
+ assert_eq!(es["processors"][0]["rename"]["target_field"], "b", "{es}");
+ assert_eq!(es.get("stages"), None, "{es}");
+ }
+
+ /// The raw Elasticsearch body kept for a definition this build stores but
+ /// cannot run is already ES-shaped and must not be touched.
+ #[test]
+ fn an_elasticsearch_body_is_returned_verbatim() {
+ let stored = json!({
+ "processors": [{ "grok": { "field": "m", "patterns": ["%{IP:c}"] } }]
+ });
+ assert_eq!(stored_pipeline_as_es(&stored), stored);
+ }
+
+ /// A NATIVE `set` stage preserves an existing value; a bare Elasticsearch
+ /// `set` claims the opposite, because ES defaults `override` to `true`.
+ /// Rendering must state the value the stage actually applies, in both
+ /// directions.
+ #[test]
+ fn set_renders_the_override_it_actually_applies() {
+ let native = json!({ "stages": [
+ { "type": "set", "config": { "field": "e", "value": "prod" } }
+ ] });
+ assert_eq!(
+ stored_pipeline_as_es(&native)["processors"][0]["set"]["override"],
+ false,
+ "a native `set` does not override"
+ );
+
+ let translated = json!({ "stages": [
+ { "type": "set", "config": { "field": "e", "value": "prod", "override": true } }
+ ] });
+ assert_eq!(
+ stored_pipeline_as_es(&translated)["processors"][0]["set"]["override"],
+ true,
+ "an Elasticsearch `set` does"
+ );
+
+ let explicit_false = json!({ "stages": [
+ { "type": "set", "config": { "field": "e", "value": "prod", "override": false } }
+ ] });
+ assert_eq!(
+ stored_pipeline_as_es(&explicit_false)["processors"][0]["set"]["override"],
+ false,
+ "an explicit `false` is carried through"
+ );
+ }
+
+ /// `_simulate` interpreted `set` as an unconditional overwrite, so it
+ /// reported a document the ingest path would never produce for a stage
+ /// that preserves. Now that GET states `override`, that disagreement is
+ /// reachable by copy-paste.
+ #[test]
+ fn simulate_honours_the_set_override_flag() {
+ let mut doc = json!({ "e": "dev" });
+ apply_single_processor(
+ "set",
+ &json!({ "field": "e", "value": "prod", "override": false }),
+ &mut doc,
+ )
+ .expect("set applies");
+ assert_eq!(doc["e"], "dev", "override:false preserves: {doc}");
+
+ let mut doc = json!({ "e": "dev" });
+ apply_single_processor("set", &json!({ "field": "e", "value": "prod" }), &mut doc)
+ .expect("set applies");
+ assert_eq!(doc["e"], "prod", "the ES default still overwrites: {doc}");
+
+ // A missing field is set even with `override: false` — ES only
+ // declines to REPLACE an existing non-null value.
+ let mut doc = json!({ "other": 1 });
+ apply_single_processor(
+ "set",
+ &json!({ "field": "e", "value": "prod", "override": false }),
+ &mut doc,
+ )
+ .expect("set applies");
+ assert_eq!(doc["e"], "prod", "{doc}");
+ }
+}
+
pub async fn put_ingest_pipeline(
State(state): State<AppState>,
Path(id): Path<String>,
@@ -24801,13 +24949,13 @@ pub async fn get_ingest_pipeline(
if id == "*" || id == "_all" {
let mut result = serde_json::Map::new();
for entry in state.engine.pipelines.iter() {
- result.insert(entry.key().clone(), entry.value().clone());
+ result.insert(entry.key().clone(), stored_pipeline_as_es(entry.value()));
}
return Json(Value::Object(result)).into_response();
}
match state.engine.pipelines.get(&id) {
Some(pipeline) => {
- let result = json!({ id.clone(): pipeline.clone() });
+ let result = json!({ id.clone(): stored_pipeline_as_es(pipeline.value()) });
Json(result).into_response()
}
None => {
@@ -24857,7 +25005,7 @@ pub struct SimulatePipelineParams {
pub async fn get_all_ingest_pipelines(State(state): State<AppState>) -> impl IntoResponse {
let mut out = serde_json::Map::new();
for entry in state.engine.pipelines.iter() {
- out.insert(entry.key().clone(), entry.value().clone());
+ out.insert(entry.key().clone(), stored_pipeline_as_es(entry.value()));
}
Json(Value::Object(out)).into_response()
}
@@ -25683,6 +25831,19 @@ fn apply_single_processor(name: &str, cfg: &Value, source: &mut Value) -> Result
.ok_or_else(|| "set processor: 'field' required".to_string())?
.to_string();
let value = cfg.get("value").cloned().unwrap_or(Value::Null);
+ // `override` is Elasticsearch's own key on `set`, defaulting to
+ // `true`. The interpreter used to overwrite unconditionally, so a
+ // `_simulate` of a stored pipeline that PRESERVES an existing value
+ // reported a document the ingest path would never produce — the
+ // same class of quiet disagreement issue #204 is about, and now
+ // reachable from GET, which states `override` explicitly.
+ let overrides = cfg.get("override").and_then(Value::as_bool).unwrap_or(true);
+ if !overrides
+ && get_dotted_path_mut(source_obj, &field)
+ .is_some_and(|existing| !existing.is_null())
+ {
+ return Ok(());
+ }
set_dotted_path(source_obj, &field, value);
Ok(())
}
diff --git a/engine/crates/xerj-api/tests/fail_closed_config_http.rs b/engine/crates/xerj-api/tests/fail_closed_config_http.rs
index 73cfcbe89..5f8763527 100644
--- a/engine/crates/xerj-api/tests/fail_closed_config_http.rs
+++ b/engine/crates/xerj-api/tests/fail_closed_config_http.rs
@@ -29,13 +29,22 @@ use tower::ServiceExt;
fn app() -> (axum::Router, tempfile::TempDir) {
let dir = tempfile::tempdir().expect("tempdir");
+ let app = app_in(dir.path());
+ (app, dir)
+}
+
+/// A node on an EXISTING data dir — i.e. a restart. Dropping the previous
+/// router and building another one over the same directory replays
+/// `cluster_state.json` exactly as a process restart does; it is the only way
+/// to reach the boot path from a request-level test.
+fn app_in(data_dir: &std::path::Path) -> axum::Router {
let mut config = xerj_common::config::Config::default();
- config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ config.server.data_dir = data_dir.to_string_lossy().into_owned();
config.storage.wal_sync = xerj_common::config::WalSync::Async;
let metrics = xerj_common::metrics::Metrics::new().expect("metrics");
let engine = xerj_engine::Engine::new(config.clone()).expect("engine");
let state = xerj_api::state::AppState::new(config, engine, metrics);
- (xerj_api::router::build_es_compat_router(state), dir)
+ xerj_api::router::build_es_compat_router(state)
}
async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {
@@ -1026,3 +1035,392 @@ async fn the_dotted_analysis_spelling_does_not_walk_past_the_settings_gate() {
.await;
assert_eq!(status, StatusCode::OK, "{body}");
}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// A refusal must survive a restart.
+//
+// The boot replay softens config this build cannot honour, so that replacing
+// the binary does not flip a working cluster's writes from 201 to 400. That
+// door was opened for definitions written by a build with NO gate — but
+// `CompileMode::ReplayPersisted` could not tell those from definitions THIS
+// build had already refused, so a plain restart resurrected a refused pipeline
+// and ran it with the refused option ignored. Verbatim repro below, using only
+// xerj's own output.
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// The exact sequence measured against the first cut of this branch:
+/// PUT → GET → edit → PUT (refused, 400 on write) → restart → 201, and
+/// `secret` dropped from a document the guard EXCLUDES.
+#[tokio::test]
+async fn a_refusal_recorded_at_put_time_survives_a_restart() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let app = app_in(dir.path());
+
+ // (1) a plain, runnable redaction pipeline.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/redact",
+ json!({ "description": "redact",
+ "processors": [{ "remove": { "field": "secret" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ // (2) the operator reads it back and (3) adds a tenant guard to whatever
+ // GET handed them, then PUTs it back. Both shapes must behave the same,
+ // so drive the loop through the response body rather than a literal.
+ let (_, stored) = send(&app, get("/_ingest/pipeline/redact")).await;
+ let mut edited = stored["redact"].clone();
+ let processors = edited["processors"]
+ .as_array_mut()
+ .expect("GET must answer in the Elasticsearch `processors` vocabulary");
+ processors[0]["remove"]["if"] = json!("ctx.tenant == 'a'");
+ let (status, body) = send(&app, put("/_ingest/pipeline/redact", edited)).await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "ES accepts a guard, so xerj stores it: {body}"
+ );
+
+ // (4) …and every write through it is refused, because the guard is not
+ // evaluated.
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/1?pipeline=redact",
+ json!({ "tenant": "b", "secret": "ssn-111" }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+
+ // (5) restart the node. Nothing else — no PUT, no operator action.
+ drop(app);
+ let app = app_in(dir.path());
+
+ // (6) the identical write must still be refused.
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/2?pipeline=redact",
+ json!({ "tenant": "b", "secret": "ssn-111" }),
+ ),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "a restart must not overturn a refusal the operator was already given: {body}"
+ );
+ assert!(
+ body["error"]["reason"]
+ .as_str()
+ .is_some_and(|r| r.contains("if")),
+ "and it must answer with the same reason: {body}"
+ );
+
+ // (7) …and no document was written with `secret` dropped by a guard that
+ // excludes it.
+ let (status, doc) = send(&app, get("/docs/_doc/2")).await;
+ assert_ne!(
+ status,
+ StatusCode::OK,
+ "the guarded write must not have happened: {doc}"
+ );
+}
+
+/// The same defect reached through the shape the engine itself persists.
+///
+/// `PUT /_ingest/pipeline/{id}` passes a body with no `processors` key straight
+/// through as a xerj `stages` definition, and that body is what
+/// `register_unrunnable_pipeline` stores. A `stages` body — unlike the raw
+/// Elasticsearch one — deserialises perfectly at boot, so the replay recompiled
+/// it softly and the refusal evaporated. This is the case the ES-vocabulary
+/// GET does not incidentally cover, and the one the persisted marker is for.
+#[tokio::test]
+async fn a_refusal_survives_a_restart_for_a_stages_shaped_definition_too() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let app = app_in(dir.path());
+
+ let stages = json!({
+ "description": "redact",
+ "stages": [{
+ "type": "drop_field",
+ "config": { "fields": ["secret"], "if": "ctx.tenant == 'a'" }
+ }]
+ });
+ let (status, body) = send(&app, put("/_ingest/pipeline/redact_native", stages)).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(body["acknowledged"], true, "{body}");
+
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/1?pipeline=redact_native",
+ json!({ "tenant": "b", "secret": "ssn-111" }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+
+ // Restart. Nothing else.
+ drop(app);
+ let app = app_in(dir.path());
+
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/2?pipeline=redact_native",
+ json!({ "tenant": "b", "secret": "ssn-111" }),
+ ),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "measured before the persisted refusal marker: 201, and `secret` dropped from a \
+ document the guard excludes: {body}"
+ );
+ let (status, doc) = send(&app, get("/docs/_doc/2")).await;
+ assert_ne!(status, StatusCode::OK, "{doc}");
+}
+
+/// The marker is provenance, not a tombstone: a definition this build compiles
+/// cleanly must not stay refused because some earlier build could not run it.
+#[tokio::test]
+async fn a_recorded_refusal_is_cleared_by_a_definition_that_compiles() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let app = app_in(dir.path());
+
+ // Refused: `ignore_failure: true` is a decision this build cannot make.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/p",
+ json!({ "processors": [
+ { "set": { "field": "env", "value": "prod", "ignore_failure": true } }
+ ] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, _) = send(&app, put("/docs/_doc/1?pipeline=p", json!({ "a": 1 }))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST);
+
+ // The operator drops the option and re-PUTs.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/p",
+ json!({ "processors": [{ "set": { "field": "env", "value": "prod" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ // It runs now, and still runs after a restart — the marker did not outlive
+ // its cause.
+ drop(app);
+ let app = app_in(dir.path());
+ let (status, body) = send(
+ &app,
+ put("/docs/_doc/2?pipeline=p&refresh=true", json!({ "a": 1 })),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ let (_, doc) = send(&app, get("/docs/_doc/2")).await;
+ assert_eq!(doc["_source"]["env"], "prod", "{doc}");
+}
+
+/// A pipeline persisted by a build with NO gate still runs after the upgrade —
+/// the compatibility door this marker narrows must stay open for the case it
+/// was cut for.
+///
+/// Built the way `cluster_state.json` actually looked before the sweep: a
+/// definition that COMPILED (so the translated `stages` body was stored),
+/// carrying an option no build then checked, and with no marker file — which
+/// is exactly the on-disk state an older binary leaves behind.
+#[tokio::test]
+async fn a_definition_with_no_refusal_marker_still_replays_softly() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let app = app_in(dir.path());
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/legacy",
+ json!({ "processors": [{ "set": { "field": "env", "value": "prod" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ drop(app);
+
+ let state_path = dir.path().join("cluster_state.json");
+ let mut state: Value =
+ serde_json::from_slice(&std::fs::read(&state_path).expect("cluster_state.json"))
+ .expect("parse");
+ state["pipelines"]["legacy"]["stages"][0]["config"]["ignore_failure"] = json!(true);
+ std::fs::write(&state_path, serde_json::to_vec_pretty(&state).unwrap()).unwrap();
+ assert!(
+ !dir.path().join("ingest-pipeline-refusals.json").exists(),
+ "a definition that compiled records no refusal, and older builds wrote no marker at all"
+ );
+
+ let app = app_in(dir.path());
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/1?pipeline=legacy&refresh=true",
+ json!({ "a": 1 }),
+ ),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "an unmarked definition must keep working across a binary upgrade: {body}"
+ );
+ let (_, doc) = send(&app, get("/docs/_doc/1")).await;
+ assert_eq!(doc["_source"]["env"], "prod", "{doc}");
+
+ // …and a live re-PUT of the same thing is still refused, so the door is
+ // narrow and the repair path still answers.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/legacy",
+ json!({ "processors": [
+ { "set": { "field": "env", "value": "prod", "ignore_failure": true } }
+ ] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = send(&app, put("/docs/_doc/2?pipeline=legacy", json!({ "a": 1 }))).await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// `GET /_ingest/pipeline/{id}` speaks Elasticsearch.
+//
+// `_simulate` was taught the ES vocabulary in this branch; GET was not, so it
+// handed back xerj's internal `stages` shape. That is what an operator edits
+// and PUTs back, which is precisely how the restart hole above is reached.
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn get_ingest_pipeline_answers_in_elasticsearch_vocabulary() {
+ let (app, _dir) = app();
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/p_rename",
+ json!({ "description": "d",
+ "processors": [{ "rename": { "field": "a", "target_field": "b" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+
+ let (_, got) = send(&app, get("/_ingest/pipeline/p_rename")).await;
+ assert_eq!(got["p_rename"]["description"], "d", "{got}");
+ assert_eq!(
+ got["p_rename"]["processors"][0]["rename"]["field"], "a",
+ "GET must not leak the internal `stages` shape: {got}"
+ );
+ assert_eq!(
+ got["p_rename"]["processors"][0]["rename"]["target_field"], "b",
+ "{got}"
+ );
+ assert_eq!(
+ got["p_rename"].get("stages"),
+ None,
+ "…and must not carry both shapes: {got}"
+ );
+
+ // `GET /_ingest/pipeline` (all) answers the same way.
+ let (_, all) = send(&app, get("/_ingest/pipeline")).await;
+ assert_eq!(
+ all["p_rename"]["processors"][0]["rename"]["field"], "a",
+ "{all}"
+ );
+
+ // Round trip: what GET hands back must PUT back cleanly and still run.
+ let (status, body) = send(&app, put("/_ingest/pipeline/p2", got["p_rename"].clone())).await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = send(
+ &app,
+ put("/docs/_doc/1?pipeline=p2&refresh=true", json!({ "a": 1 })),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ let (_, doc) = send(&app, get("/docs/_doc/1")).await;
+ assert_eq!(doc["_source"]["b"], 1, "{doc}");
+ assert_eq!(doc.pointer("/_source/a"), None, "{doc}");
+}
+
+/// The ES→xerj `set` translation writes `override` into the stored config
+/// because Elasticsearch's default is `true` and xerj's native default is
+/// `false`. GET must therefore STATE it rather than echo a key the caller never
+/// wrote without explanation — and it must round-trip, so that editing the
+/// response and PUTting it back cannot silently flip the stage's behaviour.
+/// (The native-stage half of this — `override: false` — is unit-tested on
+/// `stage_to_es_processors` in `es_compat.rs`, since the native `PUT
+/// /v1/pipelines/{name}` lives on the other router.)
+#[tokio::test]
+async fn get_states_the_override_the_stage_actually_applies() {
+ let (app, _dir) = app();
+ send(
+ &app,
+ put(
+ "/_ingest/pipeline/es_set",
+ json!({ "processors": [{ "set": { "field": "e", "value": "prod" } }] }),
+ ),
+ )
+ .await;
+ let (_, got) = send(&app, get("/_ingest/pipeline/es_set")).await;
+ assert_eq!(
+ got["es_set"]["processors"][0]["set"]["override"], true,
+ "an ES `set` overrides, and GET says so: {got}"
+ );
+
+ // An explicit `override: false` survives the round trip and still
+ // preserves the existing value.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/keeper",
+ json!({ "processors": [
+ { "set": { "field": "e", "value": "prod", "override": false } }
+ ] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (_, got) = send(&app, get("/_ingest/pipeline/keeper")).await;
+ assert_eq!(
+ got["keeper"]["processors"][0]["set"]["override"], false,
+ "{got}"
+ );
+ let (status, body) = send(
+ &app,
+ put("/_ingest/pipeline/keeper2", got["keeper"].clone()),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (status, body) = send(
+ &app,
+ put(
+ "/docs/_doc/1?pipeline=keeper2&refresh=true",
+ json!({ "e": "dev" }),
+ ),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ let (_, doc) = send(&app, get("/docs/_doc/1")).await;
+ assert_eq!(
+ doc["_source"]["e"], "dev",
+ "a re-PUT of GET's own output must not start overwriting: {doc}"
+ );
+}
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 4d6db905a..f56c22c75 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -450,6 +450,53 @@ pub struct Engine {
/// ingested through it: `process_through_pipeline` refuses with the reason
/// recorded here instead of quietly indexing the untransformed document.
pub unrunnable_pipelines: Arc<DashMap<String, String>>,
+ /// pipeline_id → the reason a **gate-bearing build refused this exact
+ /// definition at PUT time**, persisted so a restart cannot overturn the
+ /// answer the operator already received.
+ ///
+ /// Issue #204. This is PROVENANCE, and it plays the same role for a
+ /// pipeline that `analysis-binding.json` plays for an index: its ABSENCE is
+ /// the load-bearing signal. A definition in `cluster_state.json` with no
+ /// entry here was written by a build that had no gate, so the boot replay
+ /// may soften it ([`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode)).
+ /// A definition WITH an entry here was already answered "no" by this
+ /// contract, and the replay must not resurrect it — without this marker,
+ /// `ReplayPersisted` cannot tell the two apart, and a plain restart turned a
+ /// PUT-time refusal back into a `201` that wrote the wrong document
+ /// (`GET` hands the operator the stored shape, they edit it, PUT it back,
+ /// get the refusal, restart, and the refusal is gone).
+ ///
+ /// Persisted in `<data_dir>/ingest-pipeline-refusals.json`, deliberately
+ /// NOT in `cluster_state.json`: that envelope is a closed format-1 contract
+ /// with `deny_unknown_fields` (see [`crate::cluster_state`]), so adding a
+ /// field to it would make every file this build writes unreadable to an
+ /// older binary. A sidecar an older build simply ignores does not.
+ ///
+ /// Reference: Lucene records the same kind of fact for the same reason.
+ /// `SegmentInfos.indexCreatedVersionMajor`
+ /// (`lucene/core/src/java/org/apache/lucene/index/SegmentInfos.java:172`,
+ /// "The Lucene version major that was used to create the index") is written
+ /// once into the commit
+ /// (`SegmentInfos.java:633`, `out.writeVInt(indexCreatedVersionMajor)`) and
+ /// then *decides how the bytes are read back* rather than being re-derived:
+ /// `readCommit` throws `CorruptIndexException` when a segment predates the
+ /// recorded creation version (`SegmentInfos.java:491-501`), and
+ /// `readLatestCommit(dir, minSupportedMajor)` refuses a commit whose
+ /// recorded creation major is below the caller's floor
+ /// (`SegmentInfos.java:572-578`). The lesson taken here is the shape, not
+ /// the code: what a *later* reader may assume about persisted bytes has to
+ /// be recorded WITH them at write time, because it cannot be recovered
+ /// afterwards. Lucene is Apache-2.0, the same licence as XERJ; no code is
+ /// reproduced.
+ pub definition_time_refusals: Arc<DashMap<String, String>>,
+ /// Set when `ingest-pipeline-refusals.json` exists but could not be read or
+ /// parsed, so no pipeline's provenance is known.
+ ///
+ /// Issue #204. "Unknown provenance" is not "no refusal": replaying softly
+ /// there would resurrect exactly the refusals the marker exists to keep.
+ /// Every persisted pipeline is replayed at DEFINITION strictness instead —
+ /// fail closed, and loudly, with the repair named in the reason.
+ pub pipeline_refusals_unreadable: Arc<std::sync::atomic::AtomicBool>,
/// pipeline_id → configuration the running build cannot honour but that
/// was already persisted by an older one.
///
@@ -737,6 +784,8 @@ impl Engine {
scrolls: Arc::new(DashMap::new()),
pipelines: Arc::new(DashMap::new()),
unrunnable_pipelines: Arc::new(DashMap::new()),
+ definition_time_refusals: Arc::new(DashMap::new()),
+ pipeline_refusals_unreadable: Arc::new(std::sync::atomic::AtomicBool::new(false)),
degraded_pipelines: Arc::new(DashMap::new()),
closed_indices: Arc::new(DashMap::new()),
data_streams: Arc::new(DashMap::new()),
@@ -1648,6 +1697,106 @@ impl Engine {
}
}
+ // ── Ingest-pipeline refusal provenance (issue #204) ─────────────────────
+
+ /// Sidecar holding [`Engine::definition_time_refusals`].
+ ///
+ /// A separate file rather than an eighth field in `cluster_state.json`:
+ /// that envelope is `deny_unknown_fields`, so widening it would make every
+ /// file this build writes unreadable to an older binary — a downgrade
+ /// break traded for an upgrade fix. An older binary ignores this file.
+ fn pipeline_refusals_path(&self) -> PathBuf {
+ self.data_dir.join("ingest-pipeline-refusals.json")
+ }
+
+ /// Write the whole refusal map atomically.
+ ///
+ /// `Err` means the marker did not reach disk, and the caller MUST NOT
+ /// acknowledge: without it the next boot cannot tell this definition from
+ /// one an older, gate-less build wrote, and would soften the refusal back
+ /// into a `201` (issue #204). Same rule `flush_cluster_state` already
+ /// enforces for the definition itself (issue #203).
+ fn flush_pipeline_refusals(&self) -> Result<()> {
+ let snapshot: std::collections::BTreeMap<String, String> = self
+ .definition_time_refusals
+ .iter()
+ .map(|e| (e.key().clone(), e.value().clone()))
+ .collect();
+ let bytes = serde_json::to_vec_pretty(&snapshot).map_err(|e| {
+ xerj_common::XerjError::internal(format!(
+ "could not serialise the ingest-pipeline refusal markers: {e}"
+ ))
+ })?;
+ crate::index::write_file_atomic(&self.pipeline_refusals_path(), &bytes).map_err(|e| {
+ EngineError::Common(xerj_common::XerjError::internal(format!(
+ "could not persist {}: {e}",
+ self.pipeline_refusals_path().display()
+ )))
+ })
+ }
+
+ /// Clearing a refusal marker is not on the acknowledge path — a marker
+ /// that outlives its cause makes a pipeline *more* refused, never less —
+ /// so a write failure is logged rather than propagated.
+ fn flush_pipeline_refusals_best_effort(&self) {
+ if let Err(e) = self.flush_pipeline_refusals() {
+ warn!(
+ error = %e,
+ "could not clear an ingest-pipeline refusal marker; the pipeline will be \
+ refused again after the next restart until a re-PUT succeeds"
+ );
+ }
+ }
+
+ /// Read the refusal markers back at boot, before any pipeline is replayed.
+ ///
+ /// A missing file is the normal case for a data dir written before this
+ /// build — every pipeline in it is then treated as "no provenance", which
+ /// is exactly the compatibility door the replay mode exists for. A corrupt
+ /// file is NOT treated as "no refusals": that would silently reopen the
+ /// hole this marker closes, so the boot refuses to run any pipeline it
+ /// cannot classify.
+ fn load_persisted_pipeline_refusals(&self) {
+ let path = self.pipeline_refusals_path();
+ let bytes = match std::fs::read(&path) {
+ Ok(b) => b,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
+ Err(e) => {
+ error!(
+ path = %path.display(), error = %e,
+ "ingest-pipeline refusal markers are unreadable; every persisted pipeline \
+ will be replayed at DEFINITION strictness so a refusal cannot be lost"
+ );
+ self.pipeline_refusals_unreadable
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ return;
+ }
+ };
+ match serde_json::from_slice::<std::collections::BTreeMap<String, String>>(&bytes) {
+ Ok(map) => {
+ let n = map.len();
+ for (id, reason) in map {
+ self.definition_time_refusals.insert(id, reason);
+ }
+ if n > 0 {
+ info!(
+ count = n,
+ "restored ingest-pipeline refusals recorded at definition time"
+ );
+ }
+ }
+ Err(e) => {
+ error!(
+ path = %path.display(), error = %e,
+ "ingest-pipeline refusal markers are corrupt; every persisted pipeline will \
+ be replayed at DEFINITION strictness so a refusal cannot be lost"
+ );
+ self.pipeline_refusals_unreadable
+ .store(true, std::sync::atomic::Ordering::SeqCst);
+ }
+ }
+ }
+
// ── Lifecycle management (ISM/ILM) persistence ──────────────────────────
fn ism_policies_path(&self) -> PathBuf {
@@ -2163,33 +2312,78 @@ impl Engine {
// `?pipeline=x` would be accepted after a restart and quietly do
// nothing. Keep the stored document either way so GET round-trips
// exactly as it did before the restart.
+ //
+ // Which strictness a definition is replayed at is decided by
+ // PROVENANCE, never by the calendar (issue #204). Load the markers
+ // first — see `definition_time_refusals`.
+ self.load_persisted_pipeline_refusals();
+ let provenance_unknown = self
+ .pipeline_refusals_unreadable
+ .load(std::sync::atomic::Ordering::SeqCst);
let mut pipelines_restored = 0usize;
for (name, config) in state.pipelines {
self.pipelines.insert(name.clone(), config.clone());
- // Replay strictness, NOT definition-time strictness: this
- // definition is already on disk and was accepted by whichever
- // build wrote it. See `compile_pipeline_with_mode` (issue #204).
- match self.compile_pipeline_with_mode(
- &name,
- config,
- xerj_wasm::pipeline::CompileMode::ReplayPersisted,
- ) {
- Ok(()) => pipelines_restored += 1,
+ let refused_at_definition_time = self
+ .definition_time_refusals
+ .get(&name)
+ .map(|r| r.value().clone());
+ // Replay strictness is for definitions written by a build with NO
+ // gate: those were accepted by whichever build wrote them and
+ // failing them at boot would flip a working cluster's writes from
+ // 201 to 400 on a binary upgrade alone. A definition THIS contract
+ // already refused is the opposite case — the operator asked, was
+ // told 400, and a restart must not answer differently. Softening
+ // it here dropped `secret` from documents an `if` guard excluded,
+ // under a 201, with no PUT in between.
+ let mode = if refused_at_definition_time.is_some() || provenance_unknown {
+ xerj_wasm::pipeline::CompileMode::Strict
+ } else {
+ xerj_wasm::pipeline::CompileMode::ReplayPersisted
+ };
+ match self.compile_pipeline_with_mode(&name, config, mode) {
+ Ok(()) => {
+ if refused_at_definition_time.is_some() {
+ // This build honours what the refusing one could not,
+ // so the marker has outlived its cause. Clearing it is
+ // what stops a capability upgrade needing a re-PUT.
+ info!(
+ pipeline = name.as_str(),
+ "a pipeline refused at definition time by an earlier build compiles \
+ cleanly here; the recorded refusal is cleared and it now runs"
+ );
+ self.definition_time_refusals.remove(&name);
+ self.flush_pipeline_refusals_best_effort();
+ }
+ pipelines_restored += 1
+ }
Err(e) => {
// Issue #204: record WHY there is no executable form, so
// every ingest path refuses loudly with the reason
// instead of reporting a pipeline GET plainly shows as
// "not found" — the same contract as a fresh PUT.
- self.unrunnable_pipelines.insert(
- name.clone(),
- format!(
+ let reason = match (&refused_at_definition_time, provenance_unknown) {
+ // Answer the operator with the words they already
+ // read at PUT time, so the restart is visibly a
+ // continuation rather than a new, different failure.
+ (Some(recorded), _) => recorded.clone(),
+ (None, true) => format!(
+ "the persisted definition could not be recompiled at startup ({e}), \
+ and `ingest-pipeline-refusals.json` could not be read, so this \
+ build cannot tell an already-refused definition from one an \
+ older build accepted; no document can be ingested through \
+ pipeline [{name}] — repair or delete that file, or re-PUT the \
+ definition"
+ ),
+ (None, false) => format!(
"the persisted definition could not be recompiled \
at startup ({e}); no document can be ingested \
through pipeline [{name}] — re-PUT the definition"
),
- );
+ };
+ self.unrunnable_pipelines.insert(name.clone(), reason);
error!(
pipeline = name.as_str(), error = %e,
+ refused_at_definition_time = refused_at_definition_time.is_some(),
"persisted ingest pipeline could not be recompiled — it is \
still visible to GET /_ingest/pipeline but will NOT \
transform anything; re-PUT the definition"
@@ -2414,6 +2608,13 @@ impl Engine {
// (issue #204 — a rolled-back write must not turn "stored but not
// runnable, and here is why" into a bare "not found").
let previous_reason = self.unrunnable_pipelines.get(id).map(|r| r.value().clone());
+ // Same for the persisted refusal marker (issue #204): a rolled-back
+ // write must not silently un-refuse a definition that is still the one
+ // on disk.
+ let previous_marker = self
+ .definition_time_refusals
+ .get(id)
+ .map(|r| r.value().clone());
// Same for the boot-replay degradation note: a rolled-back write must
// leave the previous definition described exactly as it was.
let previous_degradation = self.degraded_pipelines.get(id).map(|r| r.value().clone());
@@ -2437,35 +2638,81 @@ impl Engine {
// Issue #204: the kept definition is visible to `GET`, so
// ingest through it must refuse WITH the reason rather
// than claim the pipeline is missing.
- self.unrunnable_pipelines.insert(
- id.to_string(),
- format!(
- "the stored definition does not compile ({e}); no \
- document can be ingested through pipeline [{id}]"
- ),
+ let reason = format!(
+ "the stored definition does not compile ({e}); no \
+ document can be ingested through pipeline [{id}]"
);
+ self.unrunnable_pipelines
+ .insert(id.to_string(), reason.clone());
+ // …and the refusal must survive a restart, or the boot
+ // replay softens it and the definition starts running
+ // with the refused option ignored (issue #204). Flushed
+ // below, after the definition itself reaches disk.
+ self.definition_time_refusals.insert(id.to_string(), reason);
Some(e)
}
},
};
+ // Every abort path restores exactly the state this call found, so a
+ // write that did not reach disk leaves nothing only this process can
+ // see. Each expansion sits in a branch that returns, so the moves out
+ // of the `previous_*` snapshots never overlap.
+ macro_rules! rollback {
+ () => {{
+ match previous_doc {
+ Some(d) => self.pipelines.insert(id.to_string(), d),
+ None => self.pipelines.remove(id).map(|(_, v)| v),
+ };
+ self.transform_pipelines.remove(id);
+ if let Some(p) = previous_compiled {
+ self.transform_pipelines.insert(id.to_string(), p);
+ }
+ match previous_reason {
+ Some(r) => self.unrunnable_pipelines.insert(id.to_string(), r),
+ None => self.unrunnable_pipelines.remove(id).map(|(_, v)| v),
+ };
+ match previous_marker {
+ Some(r) => self.definition_time_refusals.insert(id.to_string(), r),
+ None => self.definition_time_refusals.remove(id).map(|(_, v)| v),
+ };
+ match previous_degradation {
+ Some(r) => self.degraded_pipelines.insert(id.to_string(), r),
+ None => self.degraded_pipelines.remove(id).map(|(_, v)| v),
+ };
+ }};
+ }
+
+ // Issue #204: the persisted refusal marker reaches disk BEFORE the
+ // definition, and that order is load-bearing.
+ //
+ // marker without its definition — the PREVIOUS definition replays at
+ // definition strictness. It compiled once, so it compiles again,
+ // and the boot self-heal clears the marker. Loud at worst.
+ // definition without its marker — the boot replay softens a refusal
+ // the operator has already been given, and the pipeline silently
+ // starts running with the refused option ignored. That is the
+ // defect this marker exists to close.
+ let marker_changed = self
+ .definition_time_refusals
+ .get(id)
+ .map(|r| r.value().clone())
+ != previous_marker;
+ if marker_changed {
+ if let Err(e) = self.flush_pipeline_refusals() {
+ rollback!();
+ return Err(e);
+ }
+ }
+
if let Err(e) = self.flush_cluster_state() {
- match previous_doc {
- Some(d) => self.pipelines.insert(id.to_string(), d),
- None => self.pipelines.remove(id).map(|(_, v)| v),
- };
- self.transform_pipelines.remove(id);
- if let Some(p) = previous_compiled {
- self.transform_pipelines.insert(id.to_string(), p);
+ rollback!();
+ // The marker file is now ahead of the definition; put it back in
+ // step. Best effort: the boot self-heal above already covers the
+ // case where it does not.
+ if marker_changed {
+ self.flush_pipeline_refusals_best_effort();
}
- match previous_reason {
- Some(r) => self.unrunnable_pipelines.insert(id.to_string(), r),
- None => self.unrunnable_pipelines.remove(id).map(|(_, v)| v),
- };
- match previous_degradation {
- Some(r) => self.degraded_pipelines.insert(id.to_string(), r),
- None => self.degraded_pipelines.remove(id).map(|(_, v)| v),
- };
return Err(e);
}
@@ -2490,6 +2737,13 @@ impl Engine {
// definition under this id starts from a clean slate.
self.unrunnable_pipelines.remove(name);
self.degraded_pipelines.remove(name);
+ // …and neither may the persisted refusal marker outlive the
+ // definition it refers to, or a later PUT of a *different*
+ // definition under the same id would inherit its 400 at the next
+ // boot (issue #204).
+ if self.definition_time_refusals.remove(name).is_some() {
+ self.flush_pipeline_refusals_best_effort();
+ }
}
Ok(removed)
}
@@ -3426,8 +3680,14 @@ impl Engine {
self.pipelines.insert(name.to_string(), config_json);
self.transform_pipelines.insert(name.to_string(), pipeline);
// Issue #204: a successful compile clears any recorded "stored but
- // not runnable" reason left by a previous definition under this id.
+ // not runnable" reason left by a previous definition under this id —
+ // including the persisted refusal marker, whose only job is to keep a
+ // refusal alive across a restart. Persisting the removal is the
+ // caller's (`put_pipeline`, and the boot replay's self-heal); an
+ // orphaned marker only ever makes a pipeline more refused, and the
+ // next successful PUT clears it again.
self.unrunnable_pipelines.remove(name);
+ self.definition_time_refusals.remove(name);
Ok(())
}
@@ -3464,27 +3724,53 @@ impl Engine {
.unrunnable_pipelines
.get(name)
.map(|r| r.value().clone());
+ let previous_marker = self
+ .definition_time_refusals
+ .get(name)
+ .map(|r| r.value().clone());
self.pipelines.insert(name.to_string(), definition);
self.unrunnable_pipelines
.insert(name.to_string(), reason.clone());
+ // The marker that makes this refusal survive a restart. Without it the
+ // boot replay softens the refusal and the pipeline silently starts
+ // running, ignoring the very option it was refused for (issue #204).
+ self.definition_time_refusals
+ .insert(name.to_string(), reason.clone());
// Nothing is running under this id any more, so nothing is running
// degraded either.
let previous_degradation = self.degraded_pipelines.remove(name).map(|(_, v)| v);
+ macro_rules! rollback {
+ () => {{
+ match previous_doc {
+ Some(d) => self.pipelines.insert(name.to_string(), d),
+ None => self.pipelines.remove(name).map(|(_, v)| v),
+ };
+ match previous_reason {
+ Some(r) => self.unrunnable_pipelines.insert(name.to_string(), r),
+ None => self.unrunnable_pipelines.remove(name).map(|(_, v)| v),
+ };
+ match previous_marker {
+ Some(r) => self.definition_time_refusals.insert(name.to_string(), r),
+ None => self.definition_time_refusals.remove(name).map(|(_, v)| v),
+ };
+ if let Some(p) = previous_compiled {
+ self.transform_pipelines.insert(name.to_string(), p);
+ }
+ if let Some(d) = previous_degradation {
+ self.degraded_pipelines.insert(name.to_string(), d);
+ }
+ }};
+ }
+ // Marker before definition — see `put_pipeline` for why that order is
+ // load-bearing. An `Err` from either is NOT acknowledgeable: a refusal
+ // the next boot cannot see is the whole defect.
+ if let Err(e) = self.flush_pipeline_refusals() {
+ rollback!();
+ return Err(e);
+ }
if let Err(e) = self.flush_cluster_state() {
- match previous_doc {
- Some(d) => self.pipelines.insert(name.to_string(), d),
- None => self.pipelines.remove(name).map(|(_, v)| v),
- };
- match previous_reason {
- Some(r) => self.unrunnable_pipelines.insert(name.to_string(), r),
- None => self.unrunnable_pipelines.remove(name).map(|(_, v)| v),
- };
- if let Some(p) = previous_compiled {
- self.transform_pipelines.insert(name.to_string(), p);
- }
- if let Some(d) = previous_degradation {
- self.degraded_pipelines.insert(name.to_string(), d);
- }
+ rollback!();
+ self.flush_pipeline_refusals_best_effort();
return Err(e);
}
warn!(
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index ac445f711..7fcce1a7d 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -6862,3 +6862,174 @@ async fn a_persisted_pipeline_the_new_checks_refuse_still_runs_after_a_restart()
"a definition-time PUT must still refuse the same config"
);
}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Issue #204 — …but the door above is for definitions written by a build with
+// NO gate. A definition THIS build already refused must not walk through it.
+// `ingest-pipeline-refusals.json` is the provenance that tells them apart, the
+// same role `analysis-binding.json` plays for an index.
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn a_definition_time_refusal_is_recorded_on_disk_and_replayed_strictly() {
+ let dir = TempDir::new().unwrap();
+ let marker = dir.path().join("ingest-pipeline-refusals.json");
+
+ {
+ let engine = make_engine(&dir);
+ engine
+ .register_unrunnable_pipeline(
+ "guarded",
+ json!({ "stages": [
+ { "type": "drop_field",
+ "config": { "fields": ["secret"], "if": "ctx.tenant == 'a'" } }
+ ] }),
+ "processor [drop_field] option [if] is not supported by this xerj build".into(),
+ )
+ .expect("the refusal reaches disk");
+ assert!(
+ marker.exists(),
+ "the refusal must be durable, not process-local"
+ );
+ }
+
+ let engine = make_engine(&dir);
+ assert!(
+ !engine.transform_pipelines.contains_key("guarded"),
+ "a restart must not resurrect a definition this build refused"
+ );
+ let reason = engine
+ .unrunnable_pipelines
+ .get("guarded")
+ .map(|r| r.value().clone())
+ .expect("the refusal is still recorded after the restart");
+ assert!(
+ reason.contains("if"),
+ "and it answers with the reason the operator already read: {reason}"
+ );
+ assert!(
+ engine.definition_time_refusals.contains_key("guarded"),
+ "the marker itself survives too, or the NEXT restart would soften it"
+ );
+}
+
+#[tokio::test]
+async fn a_definition_that_compiles_clears_its_refusal_marker() {
+ let dir = TempDir::new().unwrap();
+ let marker = dir.path().join("ingest-pipeline-refusals.json");
+ {
+ let engine = make_engine(&dir);
+ engine
+ .register_unrunnable_pipeline(
+ "p",
+ json!({ "stages": [{ "type": "set",
+ "config": { "field": "a", "value": 1, "if": "ctx.x" } }] }),
+ "processor [set] option [if] is not supported by this xerj build".into(),
+ )
+ .expect("refusal stored");
+ // The operator drops the option.
+ assert!(engine
+ .put_pipeline(
+ "p",
+ json!({ "stages": [{ "type": "set", "config": { "field": "a", "value": 1 } }] }),
+ None,
+ )
+ .expect("no IO failure")
+ .is_none());
+ let on_disk: serde_json::Map<String, Value> =
+ serde_json::from_slice(&std::fs::read(&marker).expect("marker")).expect("parse");
+ assert!(
+ !on_disk.contains_key("p"),
+ "a marker that outlives its cause refuses a pipeline that runs: {on_disk:?}"
+ );
+ }
+ let engine = make_engine(&dir);
+ assert!(
+ engine.transform_pipelines.contains_key("p"),
+ "…and the accepted definition runs after the restart"
+ );
+}
+
+#[tokio::test]
+async fn a_refusal_marker_deleted_with_its_pipeline_cannot_haunt_the_next_definition() {
+ let dir = TempDir::new().unwrap();
+ {
+ let engine = make_engine(&dir);
+ engine
+ .register_unrunnable_pipeline(
+ "p",
+ json!({ "stages": [{ "type": "set",
+ "config": { "field": "a", "value": 1, "if": "ctx.x" } }] }),
+ "processor [set] option [if] is not supported by this xerj build".into(),
+ )
+ .expect("refusal stored");
+ assert!(engine.delete_pipeline("p").expect("delete"));
+ assert!(
+ !engine.definition_time_refusals.contains_key("p"),
+ "the marker refers to a definition that no longer exists"
+ );
+ assert!(engine
+ .put_pipeline(
+ "p",
+ json!({ "stages": [{ "type": "set", "config": { "field": "a", "value": 1 } }] }),
+ None,
+ )
+ .expect("no IO failure")
+ .is_none());
+ }
+ let engine = make_engine(&dir);
+ assert!(
+ engine.transform_pipelines.contains_key("p"),
+ "a fresh definition under a reused id must not inherit the old one's 400"
+ );
+}
+
+/// "Provenance unknown" is not "no refusal". A marker file that exists but
+/// cannot be parsed must fail CLOSED — replay everything at definition
+/// strictness — rather than silently reopen the hole it closes.
+#[tokio::test]
+async fn an_unparseable_refusal_marker_makes_the_replay_strict() {
+ let dir = TempDir::new().unwrap();
+ {
+ let engine = make_engine(&dir);
+ engine
+ .put_pipeline(
+ "legacy_pipe",
+ json!({ "stages": [
+ { "type": "grok", "config": { "field": "msg", "pattern": "GENERIC" } }
+ ] }),
+ None,
+ )
+ .expect("a clean definition stores");
+ }
+ let cluster_state = dir.path().join("cluster_state.json");
+ let mut state: Value = serde_json::from_slice(&std::fs::read(&cluster_state).unwrap()).unwrap();
+ state["pipelines"]["legacy_pipe"]["stages"][0]["config"]["pattern"] = json!("NGINX_COMBINE");
+ std::fs::write(&cluster_state, serde_json::to_vec_pretty(&state).unwrap()).unwrap();
+ std::fs::write(
+ dir.path().join("ingest-pipeline-refusals.json"),
+ b"{not json",
+ )
+ .unwrap();
+
+ let engine = make_engine(&dir);
+ assert!(
+ engine
+ .pipeline_refusals_unreadable
+ .load(std::sync::atomic::Ordering::SeqCst),
+ "the boot must record that it could not classify any pipeline"
+ );
+ assert!(
+ !engine.transform_pipelines.contains_key("legacy_pipe"),
+ "with no provenance the replay must not soften anything"
+ );
+ let reason = engine
+ .unrunnable_pipelines
+ .get("legacy_pipe")
+ .map(|r| r.value().clone())
+ .expect("and it must say why, naming the repair");
+ assert!(
+ reason.contains("ingest-pipeline-refusals.json"),
+ "the reason must name the file to repair: {reason}"
+ );
+}