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,fts,wasm): close the #204 sweep's own blind spots

xerj-org934c026ec859
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a7c40cba7..bfde84eea 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,7 +21,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
build. `PUT /{index}/_settings` with an `analysis` block is likewise refused
(it only ever changed what `GET /_settings` echoed; the registry is built
once, at create/open, and there is no rebuild path — Elasticsearch also
- refuses analysis updates on an open index).
+ refuses analysis updates on an open index). That refusal covers every
+ spelling this handler *accepts*, not just the nested one: the flat dotted
+ `{"index.analysis.analyzer.x.type": "custom"}` and half-dotted
+ `{"index": {"analysis.analyzer.x.type": "custom"}}` forms that ES clients
+ routinely send used to walk straight past it into the display copy, and
+ `GET /_settings` then echoed back an analyzer that analysed nothing.
**This rejects settings blocks that XERJ used to accept with a `200`, and the
ES-YAML conformance suite does not cover them — CI being green is not
@@ -78,6 +83,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
it, and option-level divergence inside a supported type (`synonyms_path`,
`length.min`, `asciifolding.preserve_original`) is not checked at all.**
+- **BREAKING — `PUT /_ingest/pipeline/{id}` refuses processor configuration
+ XERJ cannot honour, so a pipeline that used to be acknowledged can now be a
+ `400`, and a stored one can start refusing writes**
+ ([#204](https://github.com/xerj-org/xerj/issues/204)). This is the same
+ change as the "`200 acknowledged` … means we will run this" entry under
+ *Fixed* below, stated from the upgrader's side, because it converts `201`
+ 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.
+
+ The same rule applies one level up. Teaching the analysis resolver the
+ canonical `settings.index.analysis` nesting (see the analysis entry above) is
+ a fix at index *create* and a data bug at index *open*: `settings.json` keeps
+ the caller's nesting verbatim, so an index created before this release with
+ the canonical shape has postings that were written with `standard`, and
+ honouring the declaration on reopen would tokenise every new write
+ differently from everything already on disk. An index now records the
+ analysis binding it was created with (`<index>/analysis-binding.json`) and
+ keeps it for life. An index with no marker and analyzers declared *only*
+ under `index.analysis` keeps the legacy binding if it holds documents — with
+ an ERROR naming the index and saying a reindex is the repair — and adopts the
+ canonical binding if it is empty, recording that so a later restart cannot
+ disagree.
+
### Fixed
- **`200 acknowledged` on an ingest pipeline now means "we will run this", and
@@ -96,9 +138,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
handler emitted `{from, to}`, the plugin requires `{mappings: {…}}`) and
renamed nothing; ES `append` was executed as `set`, replacing the field
instead of extending it, and disagreeing with `_simulate`, which implemented
- a real append; `set.override` defaulted to `false` where Elasticsearch
- defaults it to `true`; an unknown `pii_redaction` type built an empty pattern
- set and redacted nothing; an unknown `grok` pattern name silently became the
+ a real append; an ES `set` processor did not override an existing value where
+ Elasticsearch does (the ES→XERJ translation now writes `"override": true`
+ explicitly when the processor omits it — the **native** `type: "set"` stage
+ keeps its long-standing `override: false` default, because native definitions
+ are recompiled from `cluster_state.json` at every boot and flipping the stage
+ default would have changed what an already-running cluster's pipelines do to
+ documents on a binary upgrade alone); an unknown `pii_redaction` type built an
+ empty pattern set and redacted nothing; an unknown `grok` pattern name
+ silently became the
catch-all; an unknown `convert` target left the field unconverted per
document; array-typed keys given as a bare string were dropped and the stage
behaved as if unconfigured; and `DELETE /_ingest/pipeline/{id}` removed the
@@ -114,6 +162,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
at `PUT`, refused at the write) rather than as `mapper_parsing_exception:
missing value`, which told the caller their valid ES pipeline was malformed.
+ **The refusal reads the value, not the key.** A processor-level option is
+ refused only when what the caller *wrote* asks for behaviour this build does
+ not have; writing the value XERJ already implements is the same as omitting
+ it. `ignore_failure: false` is Elasticsearch's own default and ES clients emit
+ it verbatim — a presence check made that pipeline register and then `400`
+ every write through it, while the byte-identical processor without the key
+ indexed fine. Accepted: `ignore_failure: false`, an empty `on_failure: []`,
+ `ignore_missing: true` (which is exactly what `remove`/`rename`/`convert`/
+ `date` already do — they pass the document through unchanged when the field
+ is absent), `ignore_empty_value: false`, `allow_duplicates: true`. Refused:
+ the opposite value in each case, and any `if` at all. (Modelled on Lucene's
+ consume-then-complain: `AbstractAnalysisFactory.getBoolean(args, name,
+ default)` at `lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java:213-217`
+ removes the key and returns the default only when it was absent, and
+ `ArabicStemFilterFactory` at
+ `lucene/analysis/common/src/java/org/apache/lucene/analysis/ar/ArabicStemFilterFactory.java:44-51`
+ then throws on whatever is left. Lucene is Apache-2.0, the same licence as
+ XERJ; no code is reproduced.)
+
+ **`remove` and `rename` no longer walk around the gate.** Their ES→XERJ
+ translation built a fresh config object holding only the translated keys, so
+ a processor-level `if` / `on_failure` / `ignore_failure` / `ignore_missing` on
+ them was dropped *before* the gate ran: `{"remove": {"field": "secret", "if":
+ "ctx.tenant == 'a'"}}` compiled, was acknowledged, and dropped the field on
+ every document — while the identical `if` on `set` was refused. Every branch
+ of the translation now edits the caller's config instead of rebuilding it.
+
+ **`_simulate` speaks Elasticsearch's vocabulary again.** It walks the
+ *stored* pipeline, and once ES `rename` started compiling the stored form
+ became XERJ's internal `stages` shape — whose stage names leaked straight into
+ the response, so `processor_type` read `field_rename` where ES reports
+ `rename`. The stages→processors conversion now inverts both halves of the
+ translation, name and config.
+
**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=`
@@ -138,9 +220,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
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
- backing index's `default_pipeline`; and `_update_by_query` reports a `drop`
+ 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.
+ 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.
## [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 4a8c5bd81..6515b8880 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -24198,6 +24198,31 @@ async fn sync_display_blocks(state: &AppState, name: &str) {
.insert(name.to_string(), display);
}
+/// Does this settings object reach into the `analysis` namespace, in ANY of the
+/// spellings Elasticsearch clients send?
+///
+/// Nested (`{"analysis": {..}}`, `{"index": {"analysis": {..}}}`), fully dotted
+/// (`{"index.analysis.analyzer.x.type": "custom"}`) and half-dotted
+/// (`{"index": {"analysis.analyzer.x.type": "custom"}}`) are the same request;
+/// this handler already accepts all three for other settings, so a gate that
+/// tests only the nested one is not a gate (issue #204).
+fn declares_analysis(settings: &Value) -> bool {
+ let Some(obj) = settings.as_object() else {
+ return false;
+ };
+ obj.keys().any(|k| {
+ let k = k.strip_prefix("index.").unwrap_or(k);
+ k == "analysis" || k.starts_with("analysis.")
+ }) || settings.pointer("/index/analysis").is_some()
+ || settings
+ .get("index")
+ .and_then(Value::as_object)
+ .is_some_and(|ix| {
+ ix.keys()
+ .any(|k| k == "analysis" || k.starts_with("analysis."))
+ })
+}
+
pub async fn put_settings(
State(state): State<AppState>,
Path(index): Path<String>,
@@ -24222,7 +24247,14 @@ pub async fn put_settings(
// Refuse it. Elasticsearch also refuses analysis updates on an open index
// (they are non-dynamic settings), so this narrows behaviour towards ES
// rather than away from it (issue #204).
- if inner.pointer("/analysis").is_some() || body.pointer("/analysis").is_some() {
+ //
+ // The gate has to cover every spelling this handler ACCEPTS, not just the
+ // nested one. ES clients routinely send flat dotted keys
+ // (`{"index.analysis.analyzer.x.type": "custom"}`), this handler merges
+ // them into `index_settings` verbatim, and `GET /{index}/_settings` then
+ // echoes an analyzer that analyses nothing — the same silent lie the
+ // nested spelling was closed against, one string away.
+ if declares_analysis(&body) || declares_analysis(&inner) {
let e = xerj_common::XerjError::config(format!(
"index [{index}]: `analysis` settings cannot be updated after the index is \
created — the analyzer registry is built at index creation and this request \
@@ -24384,6 +24416,127 @@ fn pipeline_empty_result_error(pipeline: &str) -> ApiError {
)))
}
+/// ES processor name → xerj stage type, for the processors whose names differ.
+///
+/// Paired with [`es_proc_name`], which MUST stay its inverse: `_simulate` walks
+/// a STORED pipeline, and after this sweep made ES `rename` compile, stored
+/// pipelines are in xerj's `stages` shape rather than the raw ES body. Renaming
+/// them back is what keeps `processor_type` reading `rename` and not
+/// `field_rename` in the simulate response (the ES-compat YAML conformance case
+/// "Test verbose simulate with error in pipeline").
+fn map_proc_name(es_name: &str) -> String {
+ match es_name {
+ "remove" => "drop_field".to_string(),
+ "rename" => "field_rename".to_string(),
+ "date" => "timestamp_parse".to_string(),
+ "json" => "json_parse".to_string(),
+ "convert" => "convert".to_string(),
+ // `append` used to be folded into `set` here, which REPLACES the
+ // field instead of extending it — a different document, under a
+ // 200, and in disagreement with the `_simulate` interpreter below,
+ // which has always implemented a real append (issue #204). There is
+ // now an `append` stage; the two agree.
+ "set" => "set".to_string(),
+ "copy" => "copy_field".to_string(),
+ other => other.to_string(),
+ }
+}
+
+/// Inverse of [`map_proc_name`]: xerj stage type → ES processor name.
+fn es_proc_name(xerj_type: &str) -> &str {
+ match xerj_type {
+ "drop_field" => "remove",
+ "field_rename" => "rename",
+ "timestamp_parse" => "date",
+ "json_parse" => "json",
+ "copy_field" => "copy",
+ other => other,
+ }
+}
+
+/// Render one stored xerj stage back into the Elasticsearch processor shape
+/// `_simulate` interprets.
+///
+/// The inverse of the name mapping AND of the config adaptation in
+/// [`put_ingest_pipeline`]: `drop_field`'s `{"fields": [..]}` becomes
+/// `remove`'s `{"field": ..}`, and `field_rename`'s `{"mappings": {a: b}}`
+/// becomes one `rename` per entry (ES's `rename` is 1:1). Everything else on
+/// the stage config — `tag`, `description`, `if`, `on_failure` — is carried
+/// through untouched, because `_simulate`'s interpreter reads those to build
+/// its per-processor result entries.
+///
+/// Returns a list because one `field_rename` stage can hold several mappings.
+fn stage_to_es_processors(stage: &Value) -> Vec<Value> {
+ let Some(obj) = stage.as_object() else {
+ return Vec::new();
+ };
+ let Some(ty) = obj.get("type").and_then(Value::as_str) else {
+ return Vec::new();
+ };
+ let cfg = obj
+ .get("config")
+ .cloned()
+ .unwrap_or(Value::Object(serde_json::Map::new()));
+ let es_name = es_proc_name(ty);
+
+ let wrap = |c: Value| {
+ let mut m = serde_json::Map::new();
+ m.insert(es_name.to_string(), c);
+ Value::Object(m)
+ };
+
+ match ty {
+ "drop_field" => {
+ let mut c = cfg.clone();
+ let fields = cfg.get("fields").and_then(Value::as_array).cloned();
+ if let Some(map) = c.as_object_mut() {
+ map.remove("fields");
+ match fields {
+ // ES's `remove` accepts a single name or an array; emit the
+ // single-name form for the common one-field case so the
+ // response reads the way the caller wrote it.
+ Some(f) if f.len() == 1 => {
+ map.insert("field".to_string(), f[0].clone());
+ }
+ Some(f) => {
+ map.insert("field".to_string(), Value::Array(f));
+ }
+ None => {}
+ }
+ }
+ vec![wrap(c)]
+ }
+ "field_rename" => {
+ let mappings = cfg
+ .get("mappings")
+ .and_then(Value::as_object)
+ .cloned()
+ .unwrap_or_default();
+ if mappings.is_empty() {
+ return vec![wrap(cfg)];
+ }
+ mappings
+ .into_iter()
+ .map(|(from, to)| {
+ let mut c = cfg.clone();
+ if let Some(map) = c.as_object_mut() {
+ map.remove("mappings");
+ map.insert("field".to_string(), Value::String(from));
+ map.insert("target_field".to_string(), to);
+ }
+ wrap(c)
+ })
+ .collect()
+ }
+ _ => vec![wrap(cfg)],
+ }
+}
+
+/// Every stage of a stored pipeline, in ES processor shape.
+fn stages_to_es_processors(stages: &[Value]) -> Vec<Value> {
+ stages.iter().flat_map(stage_to_es_processors).collect()
+}
+
pub async fn put_ingest_pipeline(
State(state): State<AppState>,
Path(id): Path<String>,
@@ -24400,24 +24553,9 @@ pub async fn put_ingest_pipeline(
// parsing the caller asked for silently did not happen. Compile first,
// store only on success, and answer 400 like ES does.
//
- // ES → xerj name mapping for processors whose names differ:
- fn map_proc_name(es_name: &str) -> String {
- match es_name {
- "remove" => "drop_field".to_string(),
- "rename" => "field_rename".to_string(),
- "date" => "timestamp_parse".to_string(),
- "json" => "json_parse".to_string(),
- "convert" => "convert".to_string(),
- // `append` used to be folded into `set` here, which REPLACES the
- // field instead of extending it — a different document, under a
- // 200, and in disagreement with the `_simulate` interpreter below,
- // which has always implemented a real append (issue #204). There is
- // now an `append` stage; the two agree.
- "set" => "set".to_string(),
- "copy" => "copy_field".to_string(),
- other => other.to_string(),
- }
- }
+ // ES → xerj name mapping lives at module scope (`map_proc_name`), paired
+ // with its inverse `es_proc_name`, so `_simulate` can render a stored
+ // pipeline back in ES vocabulary.
/// Elasticsearch `convert` target types that name exactly the same
/// conversion as one of xerj's, under a different word.
@@ -24451,17 +24589,40 @@ pub async fn put_ingest_pipeline(
};
let xerj_type = map_proc_name(proc_type.as_str());
// Adapt ES config shapes to xerj config shapes where they differ.
- let adapted_config = match proc_type.as_str() {
- "remove" => {
+ //
+ // EVERY branch here starts from `proc_config.clone()` and edits it.
+ // `remove` and `rename` used to build a fresh `json!({..})` holding
+ // only the translated keys, which threw away the processor-level
+ // `if` / `on_failure` / `ignore_failure` / `ignore_missing` BEFORE
+ // `build_plugin` — the exact keys the compile-time gate exists to
+ // refuse. `{"remove": {"field": "secret", "if": "ctx.tenant ==
+ // 'a'"}}` then compiled, was acknowledged, and dropped the field on
+ // EVERY document: "compiled implies honoured" made false inside the
+ // gate meant to guarantee it, and self-inconsistent too — the same
+ // `if` on `set` was refused. Translate by editing, never by
+ // rebuilding.
+ let mut adapted_config = proc_config.clone();
+ let adapted_obj = adapted_config.as_object_mut();
+ match (proc_type.as_str(), adapted_obj) {
+ ("remove", Some(cfg)) => {
// ES: {"field": "x"} or {"field": ["x","y"]}
// xerj drop_field: {"fields": ["x","y"]}
- match proc_config.get("field") {
- Some(Value::String(s)) => json!({"fields": [s]}),
- Some(Value::Array(a)) => json!({"fields": a}),
- _ => proc_config.clone(),
+ match cfg.remove("field") {
+ Some(Value::String(s)) => {
+ cfg.insert("fields".to_string(), json!([s]));
+ }
+ Some(Value::Array(a)) => {
+ cfg.insert("fields".to_string(), Value::Array(a));
+ }
+ // Put back whatever it was; the plugin's own
+ // validation produces the error message.
+ Some(other) => {
+ cfg.insert("field".to_string(), other);
+ }
+ None => {}
}
}
- "rename" => {
+ ("rename", Some(cfg)) => {
// ES: {"field": "old", "target_field": "new"}
// xerj field_rename: {"mappings": {"old": "new"}}
//
@@ -24473,31 +24634,46 @@ pub async fn put_ingest_pipeline(
// GET, and renamed nothing at ingest. Issue #204 is what
// surfaced it; the translation is fixed here rather than
// left as a permanently-unrunnable processor.
- match (
- proc_config.get("field").and_then(Value::as_str),
- proc_config.get("target_field").and_then(Value::as_str),
- ) {
- (Some(from), Some(to)) => json!({ "mappings": { from: to } }),
- // Leave malformed input alone; the plugin's own
- // validation produces the error message.
- _ => proc_config.clone(),
+ let from = cfg.get("field").and_then(Value::as_str).map(str::to_string);
+ let to = cfg
+ .get("target_field")
+ .and_then(Value::as_str)
+ .map(str::to_string);
+ if let (Some(from), Some(to)) = (from, to) {
+ cfg.remove("field");
+ cfg.remove("target_field");
+ cfg.insert("mappings".to_string(), json!({ from: to }));
}
}
- "convert" => {
+ ("convert", Some(cfg)) => {
// ES vocabulary → xerj vocabulary for the two targets that
// are the same conversion under a different name.
- let mut cfg = proc_config.clone();
- if let Some(mapped) = proc_config
+ if let Some(mapped) = cfg
.get("type")
.and_then(Value::as_str)
.and_then(map_convert_type)
{
- cfg["type"] = json!(mapped);
+ cfg.insert("type".to_string(), json!(mapped));
}
- cfg
}
- _ => proc_config.clone(),
- };
+ ("set", Some(cfg)) => {
+ // Elasticsearch's `set` processor defaults `override` to
+ // TRUE (`SetProcessor.java:135` — read for semantics only,
+ // no code reproduced). xerj's NATIVE `set` stage defaults it
+ // to false and must keep doing so: native definitions are
+ // recompiled from `cluster_state.json` at every boot, so
+ // flipping the stage default would change what an
+ // already-running cluster's pipelines do to documents on a
+ // binary upgrade alone. ES parity belongs here, in the
+ // translation, where it applies to ES processors only and
+ // is written down explicitly instead of being a default
+ // two layers away.
+ if !cfg.contains_key("override") {
+ cfg.insert("override".to_string(), json!(true));
+ }
+ }
+ _ => {}
+ }
stages.push(json!({"type": xerj_type, "config": adapted_config}));
}
json!({
@@ -24816,20 +24992,10 @@ fn expand_pipeline_processors(state: &AppState, processors: &[Value]) -> Vec<Val
let inner = if let Some(p) = pipe.get("processors").and_then(Value::as_array) {
p.clone()
} else if let Some(stages) = pipe.get("stages").and_then(Value::as_array) {
- stages
- .iter()
- .filter_map(|st| {
- let obj = st.as_object()?;
- let ty = obj.get("type").and_then(Value::as_str)?;
- let cfg = obj
- .get("config")
- .cloned()
- .unwrap_or(Value::Object(serde_json::Map::new()));
- let mut m = serde_json::Map::new();
- m.insert(ty.to_string(), cfg);
- Some(Value::Object(m))
- })
- .collect()
+ // Back into ES vocabulary — `field_rename` is `rename`
+ // to every caller of `_simulate`. See
+ // `stages_to_es_processors`.
+ stages_to_es_processors(stages)
} else {
Vec::new()
};
@@ -25704,24 +25870,18 @@ pub async fn simulate_ingest_pipeline(
// when it was round-tripped verbatim, OR in xerj internal shape
// (`stages: [{type: "set", config: {...}}]`) after compilation.
// Accept either — convert stages back into the ES-processor shape.
+ //
+ // The conversion has to invert BOTH halves of the translation
+ // `put_ingest_pipeline` applied, name and config. Emitting the internal
+ // name here reported `processor_type: "field_rename"` where ES reports
+ // `"rename"` — invisible while every ES `rename` failed to compile (the
+ // raw ES body was stored, so this branch was never taken), and a
+ // conformance failure the moment `rename` started compiling.
let processors: Vec<Value> = if let Some(p) = stored.get("processors").and_then(Value::as_array)
{
p.clone()
} else if let Some(stages) = stored.get("stages").and_then(Value::as_array) {
- stages
- .iter()
- .filter_map(|st| {
- let obj = st.as_object()?;
- let ty = obj.get("type").and_then(Value::as_str)?;
- let cfg = obj
- .get("config")
- .cloned()
- .unwrap_or(Value::Object(serde_json::Map::new()));
- let mut m = serde_json::Map::new();
- m.insert(ty.to_string(), cfg);
- Some(Value::Object(m))
- })
- .collect()
+ stages_to_es_processors(stages)
} else {
Vec::new()
};
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 0ab8ea5b9..73cfcbe89 100644
--- a/engine/crates/xerj-api/tests/fail_closed_config_http.rs
+++ b/engine/crates/xerj-api/tests/fail_closed_config_http.rs
@@ -728,3 +728,301 @@ async fn a_synonym_filter_given_a_bare_string_is_refused_not_silently_emptied()
.await;
assert_eq!(status, StatusCode::OK, "{body}");
}
+
+// ── Round 2 of the sweep: the gate's own blind spots ─────────────────────────
+
+/// `_simulate` walks the STORED pipeline. Once ES `rename` started compiling,
+/// the stored form became xerj's `stages` shape — and the stages→processors
+/// conversion emitted the INTERNAL stage name, so `processor_type` read
+/// `field_rename` where Elasticsearch reports `rename`. This is the ES-compat
+/// YAML conformance case "Test verbose simulate with error in pipeline"
+/// (`40_simulate.yml`) as a Rust test.
+#[tokio::test]
+async fn simulate_reports_elasticsearch_processor_names_for_a_compiled_pipeline() {
+ let (app, _dir) = app();
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/my_pipeline",
+ json!({
+ "description": "_description",
+ "processors": [
+ { "rename": { "field": "does_not_exist", "target_field": "_value" } }
+ ]
+ }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(body["acknowledged"], true, "{body}");
+
+ let (status, body) = send(
+ &app,
+ post(
+ "/_ingest/pipeline/my_pipeline/_simulate?verbose=true",
+ json!({ "docs": [{ "_index": "index", "_id": "id",
+ "_source": { "foo": "bar" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let results = body
+ .pointer("/docs/0/processor_results")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_else(|| panic!("processor_results missing: {body}"));
+ assert_eq!(results.len(), 1, "{body}");
+ assert_eq!(
+ results[0]["processor_type"], "rename",
+ "the internal stage name must not leak into the simulate response: {body}"
+ );
+ assert_eq!(results[0]["status"], "error", "{body}");
+ assert_eq!(
+ results[0]["error"]["reason"], "field [does_not_exist] doesn't exist",
+ "{body}"
+ );
+
+ // The `remove` translation round-trips too: `drop_field`'s `fields` array
+ // must come back as ES's single `field`.
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/rm",
+ json!({ "processors": [{ "remove": { "field": "secret" } }] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ let (_, body) = send(
+ &app,
+ post(
+ "/_ingest/pipeline/rm/_simulate?verbose=true",
+ json!({ "docs": [{ "_source": { "secret": "s", "keep": 1 } }] }),
+ ),
+ )
+ .await;
+ let results = body
+ .pointer("/docs/0/processor_results")
+ .and_then(Value::as_array)
+ .cloned()
+ .unwrap_or_else(|| panic!("processor_results missing: {body}"));
+ assert_eq!(results[0]["processor_type"], "remove", "{body}");
+ assert_eq!(
+ results[0].pointer("/doc/_source/secret"),
+ None,
+ "the simulated `remove` must actually remove: {body}"
+ );
+}
+
+/// `ignore_failure: false` is Elasticsearch's OWN default and ES clients write
+/// it out. Testing key presence refused it, so this pipeline registered and
+/// then 400'd every write through it — while the byte-identical processor
+/// without the key indexed fine.
+#[tokio::test]
+async fn spelling_out_the_elasticsearch_default_does_not_break_the_pipeline() {
+ let (app, _dir) = app();
+ let (status, body) = write_through(
+ &app,
+ "defaults_spelled_out",
+ json!([{ "set": { "field": "env", "value": "prod",
+ "ignore_failure": false, "on_failure": [] } }]),
+ json!({ "msg": "hello" }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "ignore_failure:false is the ES default and must not make a pipeline \
+ unrunnable: {body}"
+ );
+ let (_, doc) = send(&app, get("/docs/_doc/1")).await;
+ assert_eq!(doc["_source"]["env"], "prod", "{doc}");
+
+ // `ignore_failure: true` still asks for something this build cannot do.
+ let (status, _) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/ignoring",
+ json!({ "processors": [
+ { "set": { "field": "e", "value": "p", "ignore_failure": true } }
+ ] }),
+ ),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "ES accepts it, so xerj stores it");
+ let (status, body) = send(
+ &app,
+ put("/docs/_doc/9?pipeline=ignoring", json!({ "a": 1 })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
+}
+
+/// `remove` and `rename` built their xerj config from scratch, so a
+/// processor-level `if` on them was DROPPED before the gate ever saw it: the
+/// pipeline compiled, was acknowledged, and dropped the field on EVERY
+/// document — the exact defect this sweep exists to eliminate, surviving
+/// inside its own gate, and self-inconsistent with `set`, which refused the
+/// identical key.
+#[tokio::test]
+async fn a_guard_on_remove_or_rename_is_not_dropped_by_the_translation() {
+ for (name, processor) in [
+ (
+ "guarded_remove",
+ json!({ "remove": { "field": "secret", "if": "ctx.tenant == 'a'" } }),
+ ),
+ (
+ "guarded_rename",
+ json!({ "rename": { "field": "a", "target_field": "b",
+ "if": "ctx.tenant == 'a'" } }),
+ ),
+ (
+ "failing_remove",
+ json!({ "remove": { "field": "secret", "ignore_failure": true } }),
+ ),
+ (
+ "recovering_rename",
+ json!({ "rename": { "field": "a", "target_field": "b",
+ "on_failure": [{ "set": { "field": "x", "value": 1 } }] } }),
+ ),
+ ] {
+ let (app, _dir) = app();
+ let (status, body) = write_through(
+ &app,
+ name,
+ json!([processor]),
+ json!({ "tenant": "b", "secret": "s", "a": 1 }),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "{name}: a processor-level key the gate refuses on `set` must not be \
+ silently dropped on `remove`/`rename`: {body}"
+ );
+
+ // And the untransformed document was not indexed behind a 2xx.
+ let (status, _) = send(&app, get("/docs/_doc/1")).await;
+ assert_ne!(
+ status,
+ StatusCode::OK,
+ "{name}: the write must not have happened"
+ );
+ }
+}
+
+/// The bare `remove`/`rename` still work — the translation was fixed by
+/// editing the config rather than rebuilding it, so nothing was lost.
+#[tokio::test]
+async fn remove_and_rename_still_do_their_job() {
+ let (app, _dir) = app();
+ let (status, body) = write_through(
+ &app,
+ "cleanup",
+ json!([
+ { "remove": { "field": "secret" } },
+ { "rename": { "field": "a", "target_field": "b" } }
+ ]),
+ json!({ "secret": "s", "a": 1 }),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ let (_, doc) = send(&app, get("/docs/_doc/1")).await;
+ assert_eq!(doc.pointer("/_source/secret"), None, "{doc}");
+ assert_eq!(doc["_source"]["b"], 1, "{doc}");
+}
+
+/// `ignore_missing: true` is exactly what every field-reading stage already
+/// does, so it is honoured. `false` asks for the document to be FAILED on a
+/// missing field, which no stage can do — `ProcessAction` has no error
+/// variant — so it is refused rather than silently accepted.
+#[tokio::test]
+async fn ignore_missing_is_honoured_or_refused_never_silently_accepted() {
+ let (app, _dir) = app();
+ let (status, body) = write_through(
+ &app,
+ "lenient",
+ json!([{ "rename": { "field": "nope", "target_field": "b",
+ "ignore_missing": true } }]),
+ json!({ "a": 1 }),
+ )
+ .await;
+ assert!(
+ status.is_success(),
+ "ignore_missing:true is honoured: {body}"
+ );
+
+ let (status, body) = send(
+ &app,
+ put(
+ "/_ingest/pipeline/strict_missing",
+ json!({ "processors": [
+ { "rename": { "field": "nope", "target_field": "b",
+ "ignore_missing": false } }
+ ] }),
+ ),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::OK,
+ "ES accepts it, so xerj stores it: {body}"
+ );
+ let (status, body) = send(
+ &app,
+ put("/docs/_doc/7?pipeline=strict_missing", json!({ "a": 1 })),
+ )
+ .await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "ignore_missing:false must not be silently accepted: {body}"
+ );
+ assert!(
+ body["error"]["reason"]
+ .as_str()
+ .is_some_and(|r| r.contains("ignore_missing")),
+ "{body}"
+ );
+}
+
+/// The `analysis` refusal in `PUT /{index}/_settings` tested two nested
+/// pointers only. ES clients routinely send flat dotted keys, this handler
+/// accepts them for every other setting, and `GET /_settings` then echoed back
+/// an analyzer that analyses nothing.
+#[tokio::test]
+async fn the_dotted_analysis_spelling_does_not_walk_past_the_settings_gate() {
+ for body in [
+ json!({ "index.analysis.analyzer.x.type": "custom" }),
+ json!({ "index": { "analysis.analyzer.x.type": "custom" } }),
+ json!({ "analysis.analyzer.x.type": "custom" }),
+ json!({ "index": { "analysis": { "analyzer": { "x": { "type": "custom" } } } } }),
+ ] {
+ let (app, _dir) = app();
+ let (status, _) = send(&app, put("/blog", json!({}))).await;
+ assert_eq!(status, StatusCode::OK);
+
+ let (status, resp) = send(&app, put("/blog/_settings", body.clone())).await;
+ assert_eq!(
+ status,
+ StatusCode::BAD_REQUEST,
+ "{body} must be refused like the nested spelling: {resp}"
+ );
+
+ // …and nothing was echoed back into the display copy.
+ let (_, settings) = send(&app, get("/blog/_settings")).await;
+ assert!(
+ !settings.to_string().contains("analysis"),
+ "a refused settings PUT must leave no analysis trace: {settings}"
+ );
+ }
+
+ // A dotted setting that is NOT analysis is unaffected.
+ let (app, _dir) = app();
+ send(&app, put("/blog", json!({}))).await;
+ let (status, body) = send(
+ &app,
+ put("/blog/_settings", json!({ "index.number_of_replicas": 0 })),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+}
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 9cd78e921..4d6db905a 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -450,6 +450,17 @@ 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 → configuration the running build cannot honour but that
+ /// was already persisted by an older one.
+ ///
+ /// Issue #204. The pipeline RUNS — exactly as the build that stored it ran
+ /// it — because failing it at boot would turn a working cluster's writes
+ /// from 201 into 400 on a binary upgrade alone. This map is what stops that
+ /// compatibility door from being silent: it is populated only by the boot
+ /// replay ([`Engine::compile_pipeline_with_mode`] with
+ /// [`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode)), and
+ /// a re-`PUT` of the same definition answers 400 with the same reason.
+ pub degraded_pipelines: Arc<DashMap<String, String>>,
/// index_name → open/closed state (true = closed)
pub closed_indices: Arc<DashMap<String, bool>>,
/// data stream name → DataStream. Persisted in
@@ -726,6 +737,7 @@ impl Engine {
scrolls: Arc::new(DashMap::new()),
pipelines: Arc::new(DashMap::new()),
unrunnable_pipelines: Arc::new(DashMap::new()),
+ degraded_pipelines: Arc::new(DashMap::new()),
closed_indices: Arc::new(DashMap::new()),
data_streams: Arc::new(DashMap::new()),
ilm_policies: Arc::new(DashMap::new()),
@@ -2154,7 +2166,14 @@ impl Engine {
let mut pipelines_restored = 0usize;
for (name, config) in state.pipelines {
self.pipelines.insert(name.clone(), config.clone());
- match self.compile_pipeline(&name, config) {
+ // 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,
Err(e) => {
// Issue #204: record WHY there is no executable form, so
@@ -2395,6 +2414,9 @@ 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 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());
// `compile_pipeline` mutates nothing when it fails, so an abort only
// has to undo the two lines above.
@@ -2409,6 +2431,9 @@ impl Engine {
}
Some(doc) => {
self.pipelines.insert(id.to_string(), doc);
+ // A definition that does not compile has nothing running,
+ // so it cannot be running *degraded* either.
+ self.degraded_pipelines.remove(id);
// 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.
@@ -2437,6 +2462,10 @@ impl Engine {
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);
}
@@ -2460,6 +2489,7 @@ impl Engine {
// "stored but not runnable" reason behind either — the next
// definition under this id starts from a clean slate.
self.unrunnable_pipelines.remove(name);
+ self.degraded_pipelines.remove(name);
}
Ok(removed)
}
@@ -3350,10 +3380,49 @@ impl Engine {
&self,
name: &str,
config_json: Value,
+ ) -> std::result::Result<(), xerj_wasm::WasmError> {
+ self.compile_pipeline_with_mode(name, config_json, xerj_wasm::pipeline::CompileMode::Strict)
+ }
+
+ /// [`Self::compile_pipeline`], with the strictness chosen by the caller.
+ ///
+ /// Issue #204. The boot replay passes
+ /// [`CompileMode::ReplayPersisted`](xerj_wasm::pipeline::CompileMode) — a
+ /// definition already in `cluster_state.json` was accepted by whichever
+ /// build wrote it, and there is no caller left to answer 400. Refusing it
+ /// at boot would flip a working cluster's writes from 201 to 400 on a
+ /// binary upgrade alone, with no PUT and no operator action. Whatever the
+ /// replay had to wave through is recorded in `degraded_pipelines` and
+ /// logged at ERROR, so it is loud instead of silent.
+ fn compile_pipeline_with_mode(
+ &self,
+ name: &str,
+ config_json: Value,
+ mode: xerj_wasm::pipeline::CompileMode,
) -> std::result::Result<(), xerj_wasm::WasmError> {
let cfg: xerj_wasm::pipeline::PipelineConfig =
serde_json::from_value(config_json.clone()).map_err(xerj_wasm::WasmError::Json)?;
- let pipeline = xerj_wasm::pipeline::Pipeline::from_config(name, &cfg)?;
+ let pipeline = match mode {
+ xerj_wasm::pipeline::CompileMode::Strict => {
+ xerj_wasm::pipeline::Pipeline::from_config(name, &cfg)?
+ }
+ xerj_wasm::pipeline::CompileMode::ReplayPersisted => {
+ xerj_wasm::pipeline::Pipeline::from_config_replaying_persisted(name, &cfg)?
+ }
+ };
+ if pipeline.degradations.is_empty() {
+ self.degraded_pipelines.remove(name);
+ } else {
+ let summary = pipeline.degradations.join("; ");
+ error!(
+ pipeline = name,
+ degradations = summary.as_str(),
+ "persisted ingest pipeline uses configuration this build cannot honour — it \
+ is still running exactly as the build that stored it ran it, but it is NOT \
+ doing what the definition says; re-PUT the definition to see the error"
+ );
+ self.degraded_pipelines.insert(name.to_string(), summary);
+ }
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
@@ -3398,6 +3467,9 @@ impl Engine {
self.pipelines.insert(name.to_string(), definition);
self.unrunnable_pipelines
.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);
if let Err(e) = self.flush_cluster_state() {
match previous_doc {
Some(d) => self.pipelines.insert(name.to_string(), d),
@@ -3410,6 +3482,9 @@ impl Engine {
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);
+ }
return Err(e);
}
warn!(
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index c7b5462e1..c728f52fe 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -14,7 +14,7 @@ use uuid::Uuid;
use xerj_common::config::Config;
use xerj_common::schema::ManagedSchema;
use xerj_common::types::{FieldConfig, FieldType, IndexName, Schema};
-use xerj_fts::analyzer::AnalyzerRegistry;
+use xerj_fts::analyzer::{AnalysisBinding, AnalyzerRegistry};
use xerj_fts::index::FtsIndexReader;
use xerj_fts::search::{
BoolQuery as FtsBool, DisMaxQuery as FtsDisMax, FtsSearcher, Query as FtsQuery,
@@ -5946,6 +5946,9 @@ impl Index {
}
// Build analyzer registry, applying any custom analysis settings.
+ // A NEW index always gets the canonical binding, and records that it
+ // did — see `analysis_binding_for_open` (issue #204).
+ record_canonical_analysis_binding(&index_dir);
let registry = Arc::new(build_registry_from_settings(&settings));
info!(name = name.as_str(), "index created");
@@ -6141,8 +6144,19 @@ impl Index {
// Build analyzer registry from persisted settings so WAL replay uses
// the same custom analyzers (synonyms, ngrams, etc.) that were active
- // when the documents were originally indexed.
- let registry = Arc::new(build_registry_from_settings(&settings));
+ // when the documents were originally indexed — INCLUDING which
+ // `analysis` spelling was in force when they were written, which is
+ // not necessarily the one this build resolves at create time
+ // (issue #204; see `analysis_binding_for_open`).
+ let analysis_binding = analysis_binding_for_open(
+ &index_dir,
+ &settings,
+ segment_doc_count > 0 || store.version_map.live_count() > 0,
+ );
+ let registry = Arc::new(build_registry_from_settings_with_binding(
+ &settings,
+ analysis_binding,
+ ));
let passage_scored_fields_at_open = passage_scored_vector_fields(&schema.schema);
let mut wal_passage_chunk_fields = HashSet::new();
@@ -39115,6 +39129,13 @@ fn combine_scores(query_score: f32, fn_score: f32, boost_mode: BoostMode) -> f32
/// }
/// ```
fn build_registry_from_settings(settings: &Value) -> AnalyzerRegistry {
+ build_registry_from_settings_with_binding(settings, AnalysisBinding::Canonical)
+}
+
+fn build_registry_from_settings_with_binding(
+ settings: &Value,
+ binding: AnalysisBinding,
+) -> AnalyzerRegistry {
let mut registry = AnalyzerRegistry::default();
// Settings may be stored as the full settings envelope or as the inner
@@ -39122,10 +39143,89 @@ fn build_registry_from_settings(settings: &Value) -> AnalyzerRegistry {
// as-is so that both shapes work.
let analysis_root = settings.pointer("/settings").unwrap_or(settings);
- registry.apply_settings(analysis_root);
+ registry.apply_settings_with_binding(analysis_root, binding);
registry
}
+/// Marker written into an index directory when its analyzer registry was built
+/// with [`AnalysisBinding::Canonical`].
+///
+/// Its ABSENCE is the load-bearing signal: an index directory laid down before
+/// the #204 sweep has no such file, and its postings were produced by a build
+/// that read `settings.analysis` only.
+const ANALYSIS_BINDING_MARKER: &str = "analysis-binding.json";
+
+/// Which `analysis` spellings to honour when REOPENING an existing index.
+///
+/// Issue #204. `analysis_block` learning to resolve the canonical
+/// `settings.index.analysis` is a fix at index-create time and a silent data
+/// bug at index-open time: `settings.json` persists the caller's nesting
+/// verbatim, so an index created before the sweep with the canonical ES shape
+/// was written with `standard` and would, after a binary upgrade alone, reopen
+/// with the declared analyzers live. Query-time analysis then stops matching
+/// the on-disk postings — no error, no log, results that quietly disappear.
+///
+/// The decision is stable for the life of the index:
+///
+/// * marker present → the index was created by a build that honoured the
+/// canonical form; honour it.
+/// * no canonical-only block → the two bindings resolve identically; nothing to
+/// decide, and the marker is written so this stays true.
+/// * canonical-only block, index EMPTY → no postings to disagree with. Adopt
+/// the canonical binding and record it, so adding documents now cannot flip
+/// the answer at the next boot.
+/// * canonical-only block, index has documents → keep the legacy binding, and
+/// say so at ERROR. Reindex is the only correct repair and only the operator
+/// can order it.
+fn analysis_binding_for_open(
+ index_dir: &Path,
+ settings: &Value,
+ has_documents: bool,
+) -> AnalysisBinding {
+ if index_dir.join(ANALYSIS_BINDING_MARKER).exists() {
+ return AnalysisBinding::Canonical;
+ }
+ if !AnalyzerRegistry::declares_namespaced_analysis_only(settings) {
+ record_canonical_analysis_binding(index_dir);
+ return AnalysisBinding::Canonical;
+ }
+ if !has_documents {
+ record_canonical_analysis_binding(index_dir);
+ return AnalysisBinding::Canonical;
+ }
+ tracing::error!(
+ index_dir = %index_dir.display(),
+ "index declares its analyzers under `index.analysis` and was created by a build \
+ that did not read that block — its postings on disk were produced by the \
+ `standard` analyzer. Honouring the declaration now would silently stop queries \
+ matching them, so it is NOT being honoured: this index still analyses as \
+ `standard`. Reindex into a newly-created index to activate the declared analyzers."
+ );
+ AnalysisBinding::LegacyShorthandOnly
+}
+
+/// Record that this index's analyzer registry is built with the canonical
+/// binding, so the decision cannot change under it later.
+///
+/// Best effort: a failure here means the next boot re-derives the same answer
+/// from the same inputs, EXCEPT for the empty-index case, where documents
+/// written in between would flip it. That is worth an ERROR and is not worth
+/// refusing to open the index over.
+fn record_canonical_analysis_binding(index_dir: &Path) {
+ let path = index_dir.join(ANALYSIS_BINDING_MARKER);
+ if path.exists() {
+ return;
+ }
+ if let Err(e) = write_file_atomic(&path, br#"{"binding":"canonical"}"#) {
+ tracing::error!(
+ path = %path.display(), error = %e,
+ "could not record this index's analysis binding — if the index is empty now \
+ and analyzers are declared under `index.analysis`, a later restart may \
+ disagree with how documents written in the meantime were analysed"
+ );
+ }
+}
+
#[cfg(test)]
mod date_detection_tests {
use super::*;
diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rs
index 7ce8673e5..ac445f711 100644
--- a/engine/crates/xerj-engine/tests/integration.rs
+++ b/engine/crates/xerj-engine/tests/integration.rs
@@ -6599,3 +6599,266 @@ async fn create_index_still_accepts_every_analysis_construct_we_support() {
.create_index_with_settings("plain_idx", Schema::empty(), json!({}))
.expect("empty settings must still create");
}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Issue #204 — teaching the analysis resolver the canonical
+// `settings.index.analysis` nesting is a fix at index CREATE and a silent data
+// bug at index OPEN. `settings.json` keeps the caller's nesting verbatim, so an
+// index created before the sweep with the canonical shape has postings on disk
+// that were produced by `standard` — reopening it with the declared analyzers
+// live makes query-time analysis stop matching them, with no error and no log.
+// ─────────────────────────────────────────────────────────────────────────────
+
+/// A 3-gram `default` analyzer under the CANONICAL `index.analysis` nesting.
+/// Chosen because the mismatch is unmistakable in one direction: a document
+/// indexed with `standard` holds the whole term, and a query analysed with this
+/// holds only 3-grams, so an exact-term search silently returns nothing.
+fn namespaced_ngram_settings() -> Value {
+ json!({
+ "index": {
+ "analysis": {
+ "tokenizer": { "ngram_tok": { "type": "ngram",
+ "min_gram": 3, "max_gram": 3 } },
+ "analyzer": { "default": { "type": "custom",
+ "tokenizer": "ngram_tok",
+ "filter": ["lowercase"] } }
+ }
+ }
+ })
+}
+
+/// Rewrite an index directory into the state a pre-sweep build would have left:
+/// `settings.json` holding the canonical nesting verbatim, and no record that
+/// the canonical binding was ever honoured.
+fn make_index_dir_look_pre_sweep(dir: &std::path::Path, index: &str) {
+ let index_dir = dir.join(index);
+ std::fs::write(
+ index_dir.join("settings.json"),
+ serde_json::to_vec_pretty(&namespaced_ngram_settings()).unwrap(),
+ )
+ .expect("rewrite settings.json");
+ let marker = index_dir.join("analysis-binding.json");
+ if marker.exists() {
+ std::fs::remove_file(&marker).expect("remove binding marker");
+ }
+}
+
+#[tokio::test]
+async fn reopening_a_pre_sweep_index_does_not_silently_change_how_it_analyses() {
+ let dir = TempDir::new().unwrap();
+ {
+ let engine = make_engine(&dir);
+ // Created with no analysis at all: every token on disk is `standard`.
+ engine
+ .create_index_with_settings("legacy_idx", Schema::empty(), json!({}))
+ .unwrap();
+ let idx = engine.get_index("legacy_idx").unwrap();
+ idx.index_document(Some("1".into()), json!({ "name": "basketball" }))
+ .await
+ .unwrap();
+ idx.flush().await.unwrap();
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "basketball"}})))
+ .await
+ .unwrap();
+ assert_eq!(result.total.value, 1, "sanity: the term is findable");
+ }
+
+ // Now make it look exactly like an index a pre-sweep build created with
+ // the canonical nesting — settings declared, never honoured.
+ make_index_dir_look_pre_sweep(dir.path(), "legacy_idx");
+
+ let engine = make_engine(&dir);
+ let idx = engine.get_index("legacy_idx").unwrap();
+ // The document already on disk is still findable…
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "basketball"}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ result.total.value, 1,
+ "the existing document is still findable"
+ );
+
+ // …and a document written AFTER the reopen goes into the SAME term space.
+ //
+ // This is the half that actually breaks. A declared `default` analyzer is
+ // what the memtable indexes and searches with (`memtable.rs` —
+ // `get_analyzer("default").or_else(standard)`), while the on-disk segments
+ // hold `standard` postings. Honouring `index.analysis` on the open path
+ // therefore makes the reopened index tokenise every new write differently
+ // from everything already on disk: the same query answers differently
+ // depending on whether a document has been flushed yet, with no error and
+ // no log. `ket` is a 3-gram of `basketball` and matches under the declared
+ // analyzer only.
+ idx.index_document(Some("2".into()), json!({ "name": "basketball" }))
+ .await
+ .unwrap();
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "ket"}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ result.total.value, 0,
+ "reopening a pre-sweep index must keep analysing the way its postings \
+ were written — switching to the declared analyzers silently splits the \
+ index into two incompatible term spaces"
+ );
+
+ // And the plain term still finds both, before and after a flush.
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "basketball"}})))
+ .await
+ .unwrap();
+ assert_eq!(result.total.value, 2, "both documents share one term space");
+}
+
+#[tokio::test]
+async fn an_empty_pre_sweep_index_adopts_the_canonical_binding_and_records_it() {
+ let dir = TempDir::new().unwrap();
+ {
+ let engine = make_engine(&dir);
+ engine
+ .create_index_with_settings("empty_idx", Schema::empty(), json!({}))
+ .unwrap();
+ }
+ // Same doctoring, but nothing was ever indexed: there are no postings for
+ // the declared analyzers to disagree with, so honouring them is free.
+ make_index_dir_look_pre_sweep(dir.path(), "empty_idx");
+
+ let marker = dir.path().join("empty_idx").join("analysis-binding.json");
+ assert!(!marker.exists(), "precondition: the marker was removed");
+
+ {
+ let engine = make_engine(&dir);
+ let idx = engine.get_index("empty_idx").unwrap();
+ idx.index_document(Some("1".into()), json!({ "name": "basketball" }))
+ .await
+ .unwrap();
+ // The 3-gram analyzer really is in force now.
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "ket"}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ result.total.value, 1,
+ "an empty index may adopt the canonical binding"
+ );
+ }
+
+ // …and the decision was written down, so adding documents cannot make the
+ // next boot answer differently.
+ assert!(
+ marker.exists(),
+ "the adopted binding must be recorded, or a later restart would fall \
+ back to the legacy binding and stop matching what was just written"
+ );
+ let engine = make_engine(&dir);
+ let idx = engine.get_index("empty_idx").unwrap();
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "ket"}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ result.total.value, 1,
+ "the recorded binding must survive the restart"
+ );
+}
+
+#[tokio::test]
+async fn a_freshly_created_index_honours_the_canonical_analysis_nesting() {
+ let dir = TempDir::new().unwrap();
+ let engine = make_engine(&dir);
+ engine
+ .create_index_with_settings("new_idx", Schema::empty(), namespaced_ngram_settings())
+ .expect("the canonical nesting is a supported analysis block");
+ let idx = engine.get_index("new_idx").unwrap();
+ idx.index_document(Some("1".into()), json!({ "name": "basketball" }))
+ .await
+ .unwrap();
+ let result = idx
+ .search(&make_search(json!({"match": {"name": "ket"}})))
+ .await
+ .unwrap();
+ assert_eq!(
+ result.total.value, 1,
+ "a NEW index must honour `index.analysis` — that half of the fix stands"
+ );
+ assert!(
+ dir.path()
+ .join("new_idx")
+ .join("analysis-binding.json")
+ .exists(),
+ "a new index records the binding it was created with"
+ );
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Issue #204 — boot replay of an ALREADY-PERSISTED pipeline is not definition
+// time. Refusing it at startup turns a working cluster's writes from 201 into
+// 400 on a binary upgrade alone, with no PUT and no operator action.
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn a_persisted_pipeline_the_new_checks_refuse_still_runs_after_a_restart() {
+ let dir = TempDir::new().unwrap();
+ let cluster_state = dir.path().join("cluster_state.json");
+
+ // Write a cluster_state.json holding a pipeline in exactly the shape a
+ // pre-sweep build would have persisted and happily run: an unknown grok
+ // pattern name, which used to fall through to the catch-all.
+ {
+ 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 mut state: Value =
+ serde_json::from_slice(&std::fs::read(&cluster_state).expect("cluster_state.json"))
+ .expect("parse cluster_state.json");
+ state["pipelines"]["legacy_pipe"]["stages"][0]["config"]["pattern"] = json!("NGINX_COMBINE");
+ std::fs::write(&cluster_state, serde_json::to_vec_pretty(&state).unwrap()).unwrap();
+
+ // Boot again. The definition is on disk and must keep working.
+ let engine = make_engine(&dir);
+ assert!(
+ engine.transform_pipelines.contains_key("legacy_pipe"),
+ "a persisted pipeline must not be dropped by a check added after it was stored"
+ );
+ assert!(
+ !engine.unrunnable_pipelines.contains_key("legacy_pipe"),
+ "…and writes through it must not start 400ing on a binary upgrade alone"
+ );
+ // But the compatibility door is loud, not silent.
+ let degraded = engine
+ .degraded_pipelines
+ .get("legacy_pipe")
+ .map(|r| r.value().clone())
+ .expect("the replay must record what it had to wave through");
+ assert!(
+ degraded.contains("NGINX_COMBINE"),
+ "the degradation must name the offending config: {degraded}"
+ );
+
+ // A live re-PUT of the same definition is still refused — the operator's
+ // repair path answers with the real error.
+ let err = engine
+ .put_pipeline(
+ "legacy_pipe",
+ json!({ "stages": [
+ { "type": "grok", "config": { "field": "msg", "pattern": "NGINX_COMBINE" } }
+ ] }),
+ None,
+ )
+ .expect("put_pipeline returns the compile error, not an Err");
+ assert!(
+ err.is_some_and(|e| e.to_string().contains("NGINX_COMBINE")),
+ "a definition-time PUT must still refuse the same config"
+ );
+}
diff --git a/engine/crates/xerj-fts/src/analyzer.rs b/engine/crates/xerj-fts/src/analyzer.rs
index 53716ff64..710fbea43 100644
--- a/engine/crates/xerj-fts/src/analyzer.rs
+++ b/engine/crates/xerj-fts/src/analyzer.rs
@@ -903,6 +903,33 @@ pub const SUPPORTED_FILTER_TYPES: &[&str] = &["synonym", "length", "shingle", "a
/// actually build. Must stay in step with the `match tok_type` arms there.
pub const SUPPORTED_TOKENIZER_TYPES: &[&str] = &["ngram", "edge_ngram", "pattern"];
+/// Which spellings of the index `analysis` block a registry build honours.
+///
+/// Elasticsearch accepts both the shorthand (`settings.analysis.*`) and the
+/// canonical namespaced form (`settings.index.analysis.*`). Only the shorthand
+/// used to be read here, so an index created with the canonical shape was
+/// written with `standard` for every field that named a custom analyzer
+/// (issue #204).
+///
+/// Fixing that at index CREATE is a fix. Applying it on the index OPEN path
+/// would be a silent data bug: an index created before the fix, with the
+/// canonical shape, has postings on disk that were produced by `standard`.
+/// Reopening it with the declared analyzers live makes query-time analysis stop
+/// matching them — no error, no log, just results that quietly disappear. So
+/// the binding is a property of the index, decided when it is created, exactly
+/// as Lucene keys back-compat off the version an index was created with rather
+/// than the running one (`LiveIndexWriterConfig.getIndexCreatedVersionMajor`,
+/// lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java:290-298).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AnalysisBinding {
+ /// `settings.analysis` and `settings.index.analysis`. What a NEW index
+ /// gets, and what the create-time gate validates against.
+ Canonical,
+ /// `settings.analysis` only — what every build before the #204 sweep did,
+ /// and therefore what an index created by one of them was written with.
+ LegacyShorthandOnly,
+}
+
/// Central registry that maps analyzer names to their pipelines.
///
/// Built-in analyzers are registered by default; custom analyzers can be
@@ -1091,7 +1118,17 @@ impl AnalyzerRegistry {
/// }
/// ```
pub fn apply_settings(&mut self, settings: &serde_json::Value) {
- let analysis = match Self::analysis_block(settings) {
+ self.apply_settings_with_binding(settings, AnalysisBinding::Canonical);
+ }
+
+ /// [`Self::apply_settings`], with the set of accepted `analysis` spellings
+ /// chosen by the caller. See [`AnalysisBinding`].
+ pub fn apply_settings_with_binding(
+ &mut self,
+ settings: &serde_json::Value,
+ binding: AnalysisBinding,
+ ) {
+ let analysis = match Self::analysis_block_with_binding(settings, binding) {
Some(a) => a,
None => return,
};
@@ -1669,9 +1706,28 @@ impl AnalyzerRegistry {
/// [`AnalyzerRegistry::unsupported_analysis`] can never disagree about
/// which block is in force.
fn analysis_block(settings: &serde_json::Value) -> Option<&serde_json::Value> {
- settings
- .pointer("/analysis")
- .or_else(|| settings.pointer("/index/analysis"))
+ Self::analysis_block_with_binding(settings, AnalysisBinding::Canonical)
+ }
+
+ fn analysis_block_with_binding(
+ settings: &serde_json::Value,
+ binding: AnalysisBinding,
+ ) -> Option<&serde_json::Value> {
+ let shorthand = settings.pointer("/analysis");
+ match binding {
+ AnalysisBinding::Canonical => shorthand.or_else(|| settings.pointer("/index/analysis")),
+ AnalysisBinding::LegacyShorthandOnly => shorthand,
+ }
+ }
+
+ /// True when the only `analysis` block in `settings` is the canonical
+ /// namespaced one — i.e. this is exactly the settings shape whose meaning
+ /// [`AnalysisBinding`] changes.
+ ///
+ /// Accepts the same two envelopes as [`Self::unsupported_analysis`].
+ pub fn declares_namespaced_analysis_only(settings: &serde_json::Value) -> bool {
+ let root = settings.pointer("/settings").unwrap_or(settings);
+ root.pointer("/analysis").is_none() && root.pointer("/index/analysis").is_some()
}
/// Resolve a tokenizer by its built-in name.
@@ -2482,6 +2538,71 @@ mod unsupported_analysis_tests {
assert_eq!(AnalyzerRegistry::unsupported_analysis(&bad).len(), 1);
}
+ /// Honouring `index.analysis` is a fix when an index is CREATED and a data
+ /// bug when one is REOPENED — an index written before this build resolved
+ /// that block has postings the declared analyzers do not match. The
+ /// binding is therefore selectable, and `declares_namespaced_analysis_only`
+ /// is what tells the open path whether the choice even matters.
+ #[test]
+ fn the_legacy_binding_reads_the_shorthand_only() {
+ let namespaced = json!({ "index": { "analysis": { "analyzer": {
+ "ac": { "type": "custom", "tokenizer": "whitespace" } } } } });
+ let shorthand = json!({ "analysis": { "analyzer": {
+ "ac": { "type": "custom", "tokenizer": "whitespace" } } } });
+
+ // Canonical resolves both spellings…
+ for settings in [&namespaced, &shorthand] {
+ let mut registry = AnalyzerRegistry::with_defaults();
+ registry.apply_settings_with_binding(settings, AnalysisBinding::Canonical);
+ assert!(
+ registry.get_analyzer("ac").is_some(),
+ "canonical binding must resolve {settings}"
+ );
+ }
+
+ // …the legacy binding resolves only the shorthand, which is exactly
+ // what every build before the #204 sweep did.
+ let mut registry = AnalyzerRegistry::with_defaults();
+ registry.apply_settings_with_binding(&namespaced, AnalysisBinding::LegacyShorthandOnly);
+ assert!(
+ registry.get_analyzer("ac").is_none(),
+ "the legacy binding must NOT resolve `index.analysis`"
+ );
+ let mut registry = AnalyzerRegistry::with_defaults();
+ registry.apply_settings_with_binding(&shorthand, AnalysisBinding::LegacyShorthandOnly);
+ assert!(
+ registry.get_analyzer("ac").is_some(),
+ "the legacy binding still resolves the shorthand"
+ );
+ }
+
+ #[test]
+ fn declares_namespaced_analysis_only_identifies_the_shape_that_diverges() {
+ // Only the canonical nesting → the binding decides the outcome.
+ assert!(AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({ "index": { "analysis": { "analyzer": {} } } })
+ ));
+ // …including through the outer `settings` envelope.
+ assert!(AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({ "settings": { "index": { "analysis": { "analyzer": {} } } } })
+ ));
+ // Shorthand present → both bindings resolve identically.
+ assert!(!AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({ "analysis": { "analyzer": {} } })
+ ));
+ assert!(!AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({ "analysis": { "analyzer": {} },
+ "index": { "analysis": { "analyzer": {} } } })
+ ));
+ // No analysis at all → nothing to decide.
+ assert!(!AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({})
+ ));
+ assert!(!AnalyzerRegistry::declares_namespaced_analysis_only(
+ &json!({ "index": { "number_of_replicas": 0 } })
+ ));
+ }
+
#[test]
fn unresolvable_tokenizer_is_reported() {
// Pre-fix: this analyzer was registered with a StandardTokenizer and
diff --git a/engine/crates/xerj-wasm/src/pipeline.rs b/engine/crates/xerj-wasm/src/pipeline.rs
index a7b17d8b4..63ef9a5b6 100644
--- a/engine/crates/xerj-wasm/src/pipeline.rs
+++ b/engine/crates/xerj-wasm/src/pipeline.rs
@@ -94,10 +94,57 @@ pub struct Pipeline {
pub on_error: ErrorPolicy,
/// Per-document timeout (informational — enforced by the caller).
pub timeout: Duration,
+ /// Config this build could not honour but accepted anyway because the
+ /// definition was **already persisted** by an older, laxer build.
+ ///
+ /// Always empty for [`Pipeline::from_config`]. Non-empty only via
+ /// [`Pipeline::from_config_replaying_persisted`] — see [`CompileMode`].
+ /// One human-readable line per degraded stage; the caller logs them and
+ /// exposes them so the operator can re-`PUT` the definition.
+ pub degradations: Vec<String>,
+}
+
+/// How strictly [`Pipeline::from_config`] enforces the issue-#204 contract.
+///
+/// The two call sites are not the same situation and must not get the same
+/// answer:
+///
+/// * `Strict` — a caller is on the other end of a `PUT /_ingest/pipeline` and
+/// can still act on a 400. Anything this build cannot honour is refused.
+/// * `ReplayPersisted` — boot replay of a definition that is *already* in
+/// `cluster_state.json`, accepted by whichever build wrote it. There is no
+/// caller to fail: refusing it turns a working cluster's writes from `201`
+/// into `400` on a binary upgrade alone, with no `PUT` and no operator
+/// action. Lucene keys back-compat off the version an index was *created*
+/// with rather than the running one for exactly this reason
+/// (`LiveIndexWriterConfig.getIndexCreatedVersionMajor`,
+/// lucene/core/src/java/org/apache/lucene/index/LiveIndexWriterConfig.java:290-298;
+/// set by `IndexWriterConfig.setIndexCreatedVersionMajor`,
+/// .../IndexWriterConfig.java:188-220). So replay reproduces the
+/// *previously shipped* behaviour for the checks this sweep newly added, and
+/// records every one of them in [`Pipeline::degradations`] so it is loud
+/// rather than silent.
+///
+/// Checks that predate the sweep (a missing required field, an unknown stage
+/// type) fail in BOTH modes: those definitions did not work before the upgrade
+/// either.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum CompileMode {
+ /// Definition time. Refuse anything this build cannot honour.
+ Strict,
+ /// Boot replay of an already-persisted definition. Reproduce the
+ /// pre-sweep behaviour for newly-added checks, and report it.
+ ReplayPersisted,
+}
+
+impl CompileMode {
+ fn is_replay(self) -> bool {
+ matches!(self, Self::ReplayPersisted)
+ }
}
impl Pipeline {
- /// Build a [`Pipeline`] from a [`PipelineConfig`].
+ /// Build a [`Pipeline`] from a [`PipelineConfig`] at **definition time**.
///
/// Three outcomes, deliberately distinct (issue #204):
///
@@ -111,31 +158,64 @@ impl Pipeline {
/// a `grok` `patterns` array). Silently dropping these is what makes a
/// compiled pipeline write the wrong document under a `201`.
pub fn from_config(name: impl Into<String>, config: &PipelineConfig) -> Result<Self> {
+ Self::compile(name, config, CompileMode::Strict)
+ }
+
+ /// Build a [`Pipeline`] from a definition that is **already on disk**.
+ ///
+ /// See [`CompileMode::ReplayPersisted`]. Callers MUST surface
+ /// [`Pipeline::degradations`]; a silent success here would be the same
+ /// defect this sweep exists to remove, only at boot instead of at `PUT`.
+ pub fn from_config_replaying_persisted(
+ name: impl Into<String>,
+ config: &PipelineConfig,
+ ) -> Result<Self> {
+ Self::compile(name, config, CompileMode::ReplayPersisted)
+ }
+
+ fn compile(
+ name: impl Into<String>,
+ config: &PipelineConfig,
+ mode: CompileMode,
+ ) -> Result<Self> {
let name = name.into();
let mut stages: Vec<Arc<dyn TransformPlugin>> = Vec::new();
+ let mut degradations: Vec<String> = Vec::new();
for stage_cfg in &config.stages {
- let plugin =
- build_plugin(&stage_cfg.stage_type, &stage_cfg.config).map_err(|e| match e {
- StageBuildError::Unsupported(stage) => WasmError::UnsupportedStage { stage },
- StageBuildError::UnsupportedOption { option, reason } => {
- WasmError::UnsupportedOption {
- stage: stage_cfg.stage_type.clone(),
- option,
- reason,
- }
- }
- StageBuildError::Config(reason) => WasmError::InvalidConfig {
- plugin: stage_cfg.stage_type.clone(),
+ let mut stage_degradations: Vec<String> = Vec::new();
+ let plugin = build_plugin(
+ &stage_cfg.stage_type,
+ &stage_cfg.config,
+ mode,
+ &mut stage_degradations,
+ )
+ .map_err(|e| match e {
+ StageBuildError::Unsupported(stage) => WasmError::UnsupportedStage { stage },
+ StageBuildError::UnsupportedOption { option, reason } => {
+ WasmError::UnsupportedOption {
+ stage: stage_cfg.stage_type.clone(),
+ option,
reason,
- },
- })?;
+ }
+ }
+ StageBuildError::Config(reason) => WasmError::InvalidConfig {
+ plugin: stage_cfg.stage_type.clone(),
+ reason,
+ },
+ })?;
+ degradations.extend(
+ stage_degradations
+ .into_iter()
+ .map(|d| format!("stage [{}]: {d}", stage_cfg.stage_type)),
+ );
stages.push(plugin);
}
Ok(Self {
name,
stages,
+ degradations,
on_error: config.on_error.clone(),
timeout: if config.timeout_ms == 0 {
Duration::from_secs(30)
@@ -221,11 +301,60 @@ impl From<String> for StageBuildError {
}
}
-/// Elasticsearch processor-level keys that decide **whether** a processor runs
-/// or **what happens when it fails**, none of which the compiled pipeline can
-/// act on.
+impl StageBuildError {
+ /// One human-readable line, for [`Pipeline::degradations`].
+ pub(crate) fn to_reason(&self) -> String {
+ match self {
+ Self::Unsupported(stage) => format!("stage type [{stage}] is not implemented"),
+ Self::UnsupportedOption { option, reason } => format!("`{option}` — {reason}"),
+ Self::Config(reason) => reason.clone(),
+ }
+ }
+}
+
+/// Read a processor-level boolean whose *written* value decides whether this
+/// build can honour the processor.
///
-/// Issue #204, applied to this PR's own new surface. `PUT /_ingest/pipeline`
+/// `honoured` is the one value this build actually implements. Absence returns
+/// `Ok(())` — an omitted key is not configuration, and it is what every
+/// pre-existing definition looks like. A written value that equals `honoured`
+/// also returns `Ok(())`: **spelling the honoured value out is exactly
+/// equivalent to omitting it**, and refusing it is what made
+/// `{"set": {…, "ignore_failure": false}}` — Elasticsearch's own default,
+/// which ES clients emit verbatim — register a pipeline that 400s every write
+/// through it. Anything else is a request this build cannot serve.
+///
+/// This is Lucene's consume-then-complain shape rather than a presence check:
+/// `AbstractAnalysisFactory.getBoolean(args, name, defaultVal)`
+/// (lucene/core/src/java/org/apache/lucene/analysis/AbstractAnalysisFactory.java:213-217)
+/// does `args.remove(name)` and falls back to the default only when the key was
+/// ABSENT; `ArabicStemFilterFactory`
+/// (lucene/analysis/common/src/java/org/apache/lucene/analysis/ar/ArabicStemFilterFactory.java:44-51)
+/// then throws `Unknown parameters` on whatever is LEFT. Presence alone never
+/// decides anything.
+fn honoured_bool(
+ config: &Value,
+ key: &'static str,
+ honoured: bool,
+ reason: &str,
+) -> std::result::Result<(), StageBuildError> {
+ match config.get(key) {
+ None => Ok(()),
+ Some(Value::Bool(b)) if *b == honoured => Ok(()),
+ Some(Value::Bool(_)) => Err(StageBuildError::UnsupportedOption {
+ option: key.to_string(),
+ reason: reason.to_string(),
+ }),
+ Some(other) => Err(StageBuildError::Config(format!(
+ "'{key}' must be a boolean, got {other}"
+ ))),
+ }
+}
+
+/// Processor-level keys that decide **whether** a processor runs or **what
+/// happens when it fails**, none of which the compiled pipeline can act on.
+///
+/// Issue #204, applied to this sweep's own new surface. `PUT /_ingest/pipeline`
/// now means "compiled ⇒ xerj honours this"; a `{"set": {…, "if": "ctx.foo ==
/// 'never'"}}` that compiles and then sets the field on every document makes
/// that promise false, and writes the wrong document under a `201`. The
@@ -234,33 +363,106 @@ impl From<String> for StageBuildError {
///
/// `tag` and `description` are deliberately NOT here: they are identification
/// metadata that changes no document and no decision on this path.
-const UNHONOURED_PROCESSOR_KEYS: &[(&str, &str)] = &[
- (
- "if",
- "the guard is not evaluated, so the processor would run on documents it excludes",
- ),
- (
- "on_failure",
- "the recovery processors are not run; the pipeline's `on_error` policy applies instead",
- ),
- (
+///
+/// The rule this applies, uniformly: **accept the value this build actually
+/// implements (and absence, which is not configuration); refuse any other
+/// written value.** It is the same rule `append`'s `allow_duplicates` already
+/// used — ES's default there is `true`, which is what `AppendPlugin` does, so
+/// `true`/absent are accepted and `false` is refused.
+fn check_unhonourable_processor_keys(config: &Value) -> std::result::Result<(), StageBuildError> {
+ // `if`: EVERY value changes which documents the processor runs on, and
+ // none of them is evaluated here. Unlike the booleans below there is no
+ // spelling of `if` that means "no guard" — that spelling is omitting it.
+ if config.get("if").is_some() {
+ return Err(StageBuildError::UnsupportedOption {
+ option: "if".to_string(),
+ reason: "the guard is not evaluated, so the processor would run on documents \
+ it excludes"
+ .to_string(),
+ });
+ }
+ // `on_failure`: an EMPTY recovery chain asks for nothing, which is what
+ // happens. A non-empty one is a chain that would not run.
+ match config.get("on_failure") {
+ None => {}
+ Some(Value::Array(a)) if a.is_empty() => {}
+ Some(_) => {
+ return Err(StageBuildError::UnsupportedOption {
+ option: "on_failure".to_string(),
+ reason: "the recovery processors are not run; the pipeline's `on_error` \
+ policy applies instead"
+ .to_string(),
+ })
+ }
+ }
+ // `ignore_failure`: ES's default is `false` and `false` is what this build
+ // does — `ProcessAction` has no error variant, so a stage cannot report a
+ // runtime failure for anything to ignore in the first place. `true` asks
+ // for a decision this build cannot make.
+ honoured_bool(
+ config,
"ignore_failure",
+ false,
"a failing processor is not ignored; the pipeline's `on_error` policy applies instead",
- ),
-];
+ )
+}
+
+/// `ignore_missing`, for the four stages that read one named field
+/// (`drop_field`, `field_rename`, `convert`, `timestamp_parse`).
+///
+/// Every one of those plugins returns `ProcessAction::Pass` when the field is
+/// absent — `DropFieldPlugin::process` (`builtins.rs`) calls `obj.remove` and
+/// moves on; `ConvertTypePlugin::process` returns early on `None`. That is
+/// exactly `ignore_missing: true`, so `true` is honoured to the letter.
+/// `false` asks for the document to be FAILED when the field is absent, and
+/// this build cannot fail a document from inside a stage at all:
+/// [`ProcessAction`] has no error variant.
+///
+/// **Known, documented divergence** (`CHANGELOG.md`, "Known gaps"): when
+/// `ignore_missing` is OMITTED, ES's default is `false` and xerj still does
+/// not fail the document. Absence is not configuration — nothing was written
+/// for this build to break its word on — and refusing it would 400 every ES
+/// `remove`/`rename`/`convert`/`date` processor ever written. Writing `false`
+/// explicitly IS configuration, and is refused.
+fn check_ignore_missing(config: &Value, stage: &str) -> std::result::Result<(), StageBuildError> {
+ honoured_bool(
+ config,
+ "ignore_missing",
+ true,
+ &format!(
+ "xerj's `{stage}` stage passes the document through unchanged when the field is \
+ absent; failing the document on a missing field is not implemented"
+ ),
+ )
+}
/// Instantiate a built-in plugin by name.
+///
+/// `mode` decides what happens to config this build cannot honour; see
+/// [`CompileMode`]. Every check that `ReplayPersisted` waves through pushes one
+/// line onto `degradations` — the pipeline runs exactly as the previous build
+/// ran it, and the caller reports that it is doing so.
fn build_plugin(
stage_type: &str,
config: &Value,
+ mode: CompileMode,
+ degradations: &mut Vec<String>,
) -> std::result::Result<Arc<dyn TransformPlugin>, StageBuildError> {
- for (key, reason) in UNHONOURED_PROCESSOR_KEYS {
- if config.get(key).is_some() {
- return Err(StageBuildError::UnsupportedOption {
- option: (*key).to_string(),
- reason: (*reason).to_string(),
- });
- }
+ // `soften` turns a refusal into a recorded degradation under
+ // `ReplayPersisted`, and leaves it a refusal under `Strict`.
+ macro_rules! soften {
+ ($err:expr, $legacy:expr) => {{
+ let e: StageBuildError = $err;
+ if mode.is_replay() {
+ degradations.push(e.to_reason());
+ $legacy
+ } else {
+ return Err(e);
+ }
+ }};
+ }
+ if let Err(e) = check_unhonourable_processor_keys(config) {
+ soften!(e, ());
}
match stage_type {
"json_parse" => {
@@ -275,7 +477,14 @@ fn build_plugin(
"timestamp_parse" => {
let field = str_field(config, "field")?;
- let formats = optional_string_array(config, "formats")?.unwrap_or_default();
+ if let Err(e) = check_ignore_missing(config, "timestamp_parse") {
+ soften!(e, ());
+ }
+ let formats = match optional_string_array(config, "formats") {
+ Ok(v) => v,
+ Err(e) => soften!(e.into(), None),
+ }
+ .unwrap_or_default();
let target = config
.get("target")
.and_then(Value::as_str)
@@ -284,6 +493,9 @@ fn build_plugin(
}
"field_rename" => {
+ if let Err(e) = check_ignore_missing(config, "field_rename") {
+ soften!(e, ());
+ }
let mappings = config
.get("mappings")
.and_then(Value::as_object)
@@ -296,6 +508,9 @@ fn build_plugin(
}
"drop_field" => {
+ if let Err(e) = check_ignore_missing(config, "drop_field") {
+ soften!(e, ());
+ }
let fields = string_array(config, "fields")?;
Ok(Arc::new(DropFieldPlugin::new(fields)))
}
@@ -339,14 +554,17 @@ fn build_plugin(
// `{"message": "10.0.0.1 GET"}` came back with no `client` field).
for key in ["patterns", "pattern_definitions"] {
if config.get(key).is_some() {
- return Err(StageBuildError::UnsupportedOption {
- option: key.to_string(),
- reason: format!(
- "xerj's grok stage takes a named `pattern` from [{}], not \
- arbitrary grok expressions",
- GROK_PATTERN_NAMES.join(", ")
- ),
- });
+ soften!(
+ StageBuildError::UnsupportedOption {
+ option: key.to_string(),
+ reason: format!(
+ "xerj's grok stage takes a named `pattern` from [{}], not \
+ arbitrary grok expressions",
+ GROK_PATTERN_NAMES.join(", ")
+ ),
+ },
+ ()
+ );
}
}
let pattern_name = match config.get("pattern") {
@@ -356,17 +574,21 @@ fn build_plugin(
// through to the generic catch-all, which extracts a
// single `message` field and nothing else (issue #204).
if !GROK_PATTERN_NAMES.contains(&s.as_str()) {
- return Err(format!(
- "unknown grok pattern '{s}' (known patterns: {})",
- GROK_PATTERN_NAMES.join(", ")
- )
- .into());
+ soften!(
+ format!(
+ "unknown grok pattern '{s}' (known patterns: {})",
+ GROK_PATTERN_NAMES.join(", ")
+ )
+ .into(),
+ ()
+ );
}
s.clone()
}
- Some(other) => {
- return Err(format!("'pattern' must be a string, got {other}").into());
- }
+ Some(other) => soften!(
+ format!("'pattern' must be a string, got {other}").into(),
+ "SYSLOG".to_string()
+ ),
};
Ok(Arc::new(GrokPlugin::new(field, pattern_name)))
}
@@ -375,16 +597,23 @@ fn build_plugin(
// Fail closed on an unknown PII type: it used to contribute no
// regex, so a typo'd `types` list produced a stage that redacted
// nothing while reporting success (issue #204).
- let types = match optional_string_array(config, "types")? {
+ let declared = match optional_string_array(config, "types") {
+ Ok(v) => v,
+ Err(e) => soften!(e.into(), None),
+ };
+ let types = match declared {
None => vec!["email".into(), "ip".into(), "credit_card".into()],
Some(requested) => {
for t in &requested {
if !PII_TYPE_NAMES.contains(&t.as_str()) {
- return Err(format!(
- "unknown pii type '{t}' (known types: {})",
- PII_TYPE_NAMES.join(", ")
- )
- .into());
+ soften!(
+ format!(
+ "unknown pii type '{t}' (known types: {})",
+ PII_TYPE_NAMES.join(", ")
+ )
+ .into(),
+ ()
+ );
}
}
requested
@@ -401,15 +630,21 @@ fn build_plugin(
"convert" => {
let field = str_field(config, "field")?;
+ if let Err(e) = check_ignore_missing(config, "convert") {
+ soften!(e, ());
+ }
let target_type = str_field(config, "type")?;
// Fail closed: an unknown target type used to no-op per document
// rather than fail the pipeline definition (issue #204).
if !CONVERT_TARGET_TYPES.contains(&target_type.as_str()) {
- return Err(format!(
- "unknown convert target type '{target_type}' (known types: {})",
- CONVERT_TARGET_TYPES.join(", ")
- )
- .into());
+ soften!(
+ format!(
+ "unknown convert target type '{target_type}' (known types: {})",
+ CONVERT_TARGET_TYPES.join(", ")
+ )
+ .into(),
+ ()
+ );
}
Ok(Arc::new(ConvertTypePlugin::new(field, target_type)))
}
@@ -445,30 +680,55 @@ fn build_plugin(
// write) rather than falling through to `missing 'value'`, which
// told the caller their correct ES pipeline was malformed.
if config.get("copy_from").is_some() {
- return Err(StageBuildError::UnsupportedOption {
- option: "copy_from".to_string(),
- reason: "xerj's set stage assigns a literal `value`; copying the value \
- from another field at ingest time is not implemented"
- .to_string(),
- });
+ soften!(
+ StageBuildError::UnsupportedOption {
+ option: "copy_from".to_string(),
+ reason: "xerj's set stage assigns a literal `value`; copying the value \
+ from another field at ingest time is not implemented"
+ .to_string(),
+ },
+ ()
+ );
+ }
+ // `ignore_empty_value: true` asks the stage to skip when the value
+ // is null or empty. `SetPlugin` always assigns, which is ES's
+ // default (`false`) — so `false`/absent are honoured exactly and
+ // `true` is a request this build cannot serve.
+ if let Err(e) = honoured_bool(
+ config,
+ "ignore_empty_value",
+ false,
+ "the value is assigned even when it is null or empty; skipping on an empty \
+ value is not implemented",
+ ) {
+ soften!(e, ());
}
let value = config
.get("value")
.cloned()
.ok_or_else(|| "missing 'value'".to_string())?;
- // Elasticsearch's `set` processor defaults `override` to TRUE
- // (`SetProcessor.java:135` — `readBooleanProperty(…, "override",
- // true)`; ES is read for semantics only, no code reproduced). This
- // was `unwrap_or(false)`, so `{"set": {"field": "env", "value":
- // "prod"}}` left an existing `{"env": "dev"}` untouched: a weaker
- // fallback on user configuration, in the file the #204 sweep
- // rewrote. A present-but-non-boolean `override` is a caller error
- // rather than a silent fall-through to the default.
+ // `override` defaults to FALSE for a native `type: "set"` stage and
+ // always has. Elasticsearch's `set` defaults it to TRUE
+ // (`SetProcessor.java:135` — read for semantics only, no code
+ // reproduced), and that parity is applied where it belongs: the
+ // ES→xerj translation in `es_compat::put_ingest_pipeline` writes
+ // `"override": true` explicitly when an ES `set` processor omits
+ // it. Flipping the default HERE would have changed the meaning of
+ // every already-persisted NATIVE pipeline as well — native
+ // definitions are recompiled from `cluster_state.json` at every
+ // boot, so a `set` stage that had been preserving an existing field
+ // value for the life of a cluster would start overwriting it on a
+ // binary upgrade alone, with no PUT and no operator action.
+ //
+ // A present-but-non-boolean `override` is a caller error rather
+ // than a silent fall-through to the default.
let override_existing = match config.get("override") {
- None => true,
- Some(v) => v
- .as_bool()
- .ok_or_else(|| format!("'override' must be a boolean, got {v}"))?,
+ None => false,
+ Some(Value::Bool(b)) => *b,
+ Some(v) => soften!(
+ format!("'override' must be a boolean, got {v}").into(),
+ false
+ ),
};
Ok(Arc::new(SetPlugin::new(field, value, override_existing)))
}
@@ -483,16 +743,13 @@ fn build_plugin(
// .java:121`) and that is what `AppendPlugin` does; the
// de-duplicating variant is not implemented, so asking for it must
// not be silently ignored.
- match config.get("allow_duplicates") {
- None | Some(Value::Bool(true)) => {}
- Some(_) => {
- return Err(StageBuildError::UnsupportedOption {
- option: "allow_duplicates".to_string(),
- reason: "values are always appended; de-duplicating append is not \
- implemented"
- .to_string(),
- })
- }
+ if let Err(e) = honoured_bool(
+ config,
+ "allow_duplicates",
+ true,
+ "values are always appended; de-duplicating append is not implemented",
+ ) {
+ soften!(e, ());
}
Ok(Arc::new(AppendPlugin::new(field, value)))
}
@@ -860,11 +1117,16 @@ mod fallback_regression_tests {
);
}
- /// Elasticsearch's `set` defaults `override` to true (SetProcessor.java:135
- /// — read for semantics only). `unwrap_or(false)` made `{"set": {"field":
- /// "env", "value": "prod"}}` a no-op against an existing `{"env": "dev"}`.
+ /// The NATIVE `set` stage keeps `override: false` as its default, and must
+ /// keep it: native definitions live in `cluster_state.json` and are
+ /// recompiled at every boot, so flipping the default here would silently
+ /// change what an already-running cluster's pipelines do to documents on a
+ /// binary upgrade alone — no PUT, no operator action. ES parity for the
+ /// `set` PROCESSOR is applied in the translation layer instead, which
+ /// writes `"override": true` explicitly (see
+ /// `es_compat::put_ingest_pipeline`).
#[test]
- fn set_overrides_by_default_like_elasticsearch() {
+ fn native_set_stage_keeps_its_non_overriding_default() {
let pl = build(
"set",
serde_json::json!({ "field": "env", "value": "prod" }),
@@ -872,17 +1134,26 @@ mod fallback_regression_tests {
.expect("set builds");
let mut doc = serde_json::json!({ "env": "dev" });
pl.process(&mut doc);
+ assert_eq!(
+ doc["env"], "dev",
+ "a native `set` stage with no `override` must NOT overwrite an existing value"
+ );
+
+ // An absent field is still filled in.
+ let mut doc = serde_json::json!({});
+ pl.process(&mut doc);
assert_eq!(doc["env"], "prod");
- // …and the opt-out still works.
+ // …and the explicit opt-in overwrites, which is what the ES
+ // translation writes for every ES `set` processor.
let pl = build(
"set",
- serde_json::json!({ "field": "env", "value": "prod", "override": false }),
+ serde_json::json!({ "field": "env", "value": "prod", "override": true }),
)
.expect("set builds");
let mut doc = serde_json::json!({ "env": "dev" });
pl.process(&mut doc);
- assert_eq!(doc["env"], "dev");
+ assert_eq!(doc["env"], "prod");
// A non-boolean `override` is refused rather than defaulted.
assert!(build(
@@ -892,6 +1163,169 @@ mod fallback_regression_tests {
.is_err());
}
+ /// `ignore_failure: false` is Elasticsearch's OWN default, and ES clients
+ /// write it out verbatim. Testing `config.get(key).is_some()` refused it,
+ /// so `{"set": {"field": "env", "value": "prod", "ignore_failure": false}}`
+ /// registered a pipeline that 400'd every write through it — while the
+ /// byte-identical processor without the key compiled fine.
+ #[test]
+ fn writing_the_honoured_default_is_the_same_as_omitting_it() {
+ for cfg in [
+ serde_json::json!({ "field": "env", "value": "prod", "ignore_failure": false }),
+ serde_json::json!({ "field": "env", "value": "prod", "on_failure": [] }),
+ serde_json::json!({ "field": "env", "value": "prod", "ignore_empty_value": false }),
+ ] {
+ let pl = build("set", cfg.clone())
+ .unwrap_or_else(|e| panic!("{cfg} must compile like the bare processor: {e}"));
+ let mut doc = serde_json::json!({});
+ pl.process(&mut doc);
+ assert_eq!(doc["env"], "prod");
+ }
+
+ // `ignore_missing: true` is what every field-reading stage already
+ // does, so it is honoured to the letter rather than refused.
+ for (stage, cfg) in [
+ (
+ "drop_field",
+ serde_json::json!({ "fields": ["a"], "ignore_missing": true }),
+ ),
+ (
+ "field_rename",
+ serde_json::json!({ "mappings": { "a": "b" }, "ignore_missing": true }),
+ ),
+ (
+ "convert",
+ serde_json::json!({ "field": "a", "type": "integer", "ignore_missing": true }),
+ ),
+ (
+ "timestamp_parse",
+ serde_json::json!({ "field": "a", "ignore_missing": true }),
+ ),
+ ] {
+ assert!(
+ build(stage, cfg.clone()).is_ok(),
+ "{stage} must accept the ignore_missing value it implements: {cfg}"
+ );
+ }
+ }
+
+ /// The other half of the same rule: a written value this build does NOT
+ /// implement is refused, whether or not it happens to be ES's default.
+ #[test]
+ fn writing_an_unhonoured_value_is_refused_even_when_it_is_the_es_default() {
+ // `ignore_missing: false` asks for the document to be failed on a
+ // missing field. `ProcessAction` has no error variant.
+ let err = build(
+ "drop_field",
+ serde_json::json!({ "fields": ["a"], "ignore_missing": false }),
+ )
+ .expect_err("ignore_missing:false must not compile");
+ assert!(
+ matches!(&err, WasmError::UnsupportedOption { option, .. } if option == "ignore_missing"),
+ "expected UnsupportedOption(ignore_missing), got: {err:?}"
+ );
+
+ // `ignore_empty_value: true` asks `set` to skip on an empty value.
+ let err = build(
+ "set",
+ serde_json::json!({ "field": "env", "value": "", "ignore_empty_value": true }),
+ )
+ .expect_err("ignore_empty_value:true must not compile");
+ assert!(
+ matches!(&err, WasmError::UnsupportedOption { option, .. }
+ if option == "ignore_empty_value"),
+ "expected UnsupportedOption(ignore_empty_value), got: {err:?}"
+ );
+
+ // A non-boolean is the caller's mistake, not a capability gap.
+ assert!(matches!(
+ build(
+ "set",
+ serde_json::json!({ "field": "e", "value": 1, "ignore_failure": "no" })
+ )
+ .expect_err("non-boolean ignore_failure must not compile"),
+ WasmError::InvalidConfig { .. }
+ ));
+ }
+
+ /// Boot replay is not definition time. A definition that is ALREADY in
+ /// `cluster_state.json` was accepted by whichever build wrote it; refusing
+ /// it now turns a working cluster's writes from 201 into 400 on a binary
+ /// upgrade alone. Replay reproduces the previously-shipped behaviour and
+ /// reports every instance in `degradations`.
+ #[test]
+ fn replaying_a_persisted_definition_does_not_break_on_a_newly_added_check() {
+ fn replay(stage_type: &str, config: Value) -> Result<Pipeline> {
+ Pipeline::from_config_replaying_persisted(
+ "t",
+ &PipelineConfig {
+ description: String::new(),
+ stages: vec![PipelineStageConfig {
+ stage_type: stage_type.into(),
+ config,
+ }],
+ on_error: ErrorPolicy::Drop,
+ timeout_ms: 0,
+ },
+ )
+ }
+
+ // Every check this sweep added, in the shape a pre-upgrade
+ // cluster_state.json can legitimately hold.
+ let cases: Vec<(&str, Value)> = vec![
+ (
+ "grok",
+ serde_json::json!({ "field": "m", "pattern": "NGINX_COMBINE" }),
+ ),
+ (
+ "convert",
+ serde_json::json!({ "field": "status", "type": "int" }),
+ ),
+ (
+ "timestamp_parse",
+ serde_json::json!({ "field": "ts", "formats": "%Y-%m-%d" }),
+ ),
+ ("pii_redaction", serde_json::json!({ "types": "ssn" })),
+ (
+ "set",
+ serde_json::json!({ "field": "e", "value": "p", "copy_from": "other" }),
+ ),
+ (
+ "set",
+ serde_json::json!({ "field": "e", "value": "p", "if": "ctx.x == 'y'" }),
+ ),
+ ];
+ for (stage, cfg) in cases {
+ // Strict (a live PUT) refuses…
+ assert!(
+ build(stage, cfg.clone()).is_err(),
+ "{stage} {cfg} must be refused at definition time"
+ );
+ // …replay of the same persisted definition keeps running, loudly.
+ let pl = replay(stage, cfg.clone())
+ .unwrap_or_else(|e| panic!("replay of {stage} {cfg} must not fail the boot: {e}"));
+ assert!(
+ !pl.degradations.is_empty(),
+ "replay of {stage} {cfg} must record why it is degraded"
+ );
+ assert!(
+ pl.degradations[0].starts_with(&format!("stage [{stage}]:")),
+ "degradation must name the stage: {:?}",
+ pl.degradations
+ );
+ }
+
+ // A definition that did NOT work before the upgrade either still
+ // fails in both modes — replay is a compatibility door, not a mute.
+ assert!(replay("no_such_stage", serde_json::json!({})).is_err());
+ assert!(replay("drop_field", serde_json::json!({})).is_err());
+
+ // And a clean definition replays with nothing to report.
+ let pl = replay("set", serde_json::json!({ "field": "e", "value": "p" }))
+ .expect("a clean definition replays");
+ assert!(pl.degradations.is_empty());
+ }
+
/// `append` used to be mapped onto `set` in the ES translation, so it
/// REPLACED the field. It is now a real append and agrees with the
/// `_simulate` interpreter.