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.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(engine,api): serialise the refusal flush, and close the spellings and round trips the gate missed
xerj-org4854af02f199
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4eae01ea9..e2dc2404f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -220,6 +220,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- a `synonym` filter whose `synonyms` is a bare string rather than an array(it built a filter with zero rules).+ **The gate covers every spelling, at create as well as at update.** An+ `analysis` declaration written with flat dotted keys+ (`{"index.analysis.filter.my_lower.type": "lowercase"}`) or half-dotted ones+ (`{"index": {"analysis.analyzer.a.type": "custom"}}`) is the same request as+ the nested form to an Elasticsearch client, and this handler already parses+ dotted keys for other settings (`index.sort.field`). The analyzer registry+ resolves the nested spellings only, so a dotted declaration was accepted,+ echoed back by `GET /{index}/_settings`, and applied to nothing. It is now a+ `400` naming the offending key, on both `PUT /{index}` and+ `PUT /{index}/_settings`. Measured on this release, the same+ `my_lower`/`lowercase` declaration in four spellings — nested, `index.`-+ namespaced, fully dotted, half-dotted — answers `400`, `400`, `400`, `400`;+ a settings body with no analysis in it (`index.number_of_shards`,+ `index.sort.field`) still answers `200`. Nothing already on disk changes+ meaning: the dotted form is refused, not newly honoured, so no existing+ index's analysis is re-derived on reopen.+**Upgrading:** there is no opt-out flag. Either remove the analysis block andname a built-in analyzer on the field (`"analyzer": "english"`), or keep onlythe constructs in the table. The `400` names every offending construct in one@@ -275,11 +292,32 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0cannot be read or parsed, no pipeline's provenance is known, so **every**persisted pipeline is replayed at definition strictness and any that fails isrecorded unrunnable with the file named in the reason — fail closed and- loudly, rather than silently reopening the hole. An older binary reading a+ loudly, rather than silently reopening the hole. **In that state a refusal is+ also not acknowledged:** the file is written whole from the in-memory map,+ which a failed load leaves empty, so the next refused `PUT` would have+ replaced it with a one-entry map and erased every refusal it still held —+ after which it parses cleanly, every earlier refusal reads as "no provenance",+ and the fail-closed behaviour converts itself into the hole it exists to+ close after exactly one process lifetime. `PUT /_ingest/pipeline/{id}` now+ answers `500` naming the file instead, and the file is left byte-for-byte as+ found; move it aside and restart to clear the state. An older binary reading adata dir written by this one simply ignores the file; it is a sidecarprecisely because `cluster_state.json`'s format-1 envelope is`deny_unknown_fields` and widening it would break downgrades.+ **The marker survives concurrent refusals, not just sequential ones.** The+ sidecar is rewritten whole, so two refused `PUT`s in flight at once were a+ lost update rather than a merge: each snapshotted the map, and whichever+ wrote second with the older snapshot erased the other's marker — while both+ callers were told `{"acknowledged": true}`. Measured at a live node against+ the first cut of this work: 40 concurrent refused `PUT`s, 40 acknowledged, 37+ markers on disk, and after a plain restart the three that were lost answered+ `201` and dropped `secret` from a document their `if` guard excludes. The+ snapshot and the write now happen under the same `cluster_state_write` mutex+ that `flush_cluster_state` has always taken. Measured on this release: 40+ concurrent refused `PUT`s, 40 acknowledged, 40 markers on disk, plain restart,+ 40 of 40 still `400`.+The same rule applies one level up. Teaching the analysis resolver thecanonical `settings.index.analysis` nesting (see the analysis entry above) isa fix at index *create* and a data bug at index *open*: `settings.json` keeps@@ -397,17 +435,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0now applies Elasticsearch's rule (default `true`; `false` leaves an existingnon-null value alone).-- **Three wire-visible refusals that were fixed in this sweep but not written- down** ([#204](https://github.com/xerj-org/xerj/issues/204)). All three+ **This is also the only read endpoint for a pipeline created through+ `PUT /v1/pipelines/{name}`** — the native surface registers no `GET` — so the+ round trip has to be lossless in xerj's own vocabulary too, and it was not.+ `PUT /_ingest/pipeline/{id}` rebuilt the stored definition as+ `{description, stages}` and dropped every other top-level key, so PUTting+ `GET`'s own output back silently discarded a natively-defined pipeline's+ `on_error` and `timeout_ms`: the error policy reverted from `pass` (keep the+ document) to the `Drop` default (discard it) under a+ `200 {"acknowledged": true}`. The translation now edits the body instead of+ rebuilding it — the same rule already applied to `remove`/`rename` one level+ down. Measured on this release, `{"description":"n3","on_error":"pass",+ "timeout_ms":250,"stages":[…]}` reads back with both keys intact, and PUTting+ that body back leaves them intact, before and after a restart. Elasticsearch's+ own pipeline metadata (`version`, `_meta`, `deprecated`) rides along the same+ way and is now echoed back rather than dropped. `PUT /v1/pipelines/{name}`+ given that ES-shaped body used to answer `500` with `internal error: missing+ field stages`; it now answers `400` naming `/_ingest/pipeline/{name}` as the+ endpoint that accepts it.++- **Four wire-visible refusals that were fixed in this sweep but not written+ down** ([#204](https://github.com/xerj-org/xerj/issues/204)). All fourreplace a silent fallback with an error, which is the point of the issue, buteach changes a status code:`POST /v1/admin/backup` answers `400` on a request body that is present butunparseable, where it previously ran a *default* backup under a successresponse; `GET /{index}/_stats` and `GET /_all/_stats` carry an addednon-Elasticsearch key `primaries.mappings.schema_persist_failures` inside an- otherwise ES-shaped response; and the authorization layer's response pruning+ otherwise ES-shaped response; the authorization layer's response pruninganswers `500` when it cannot parse the body it was asked to filter, instead- of falling back to the unfiltered bytes.+ of falling back to the unfiltered bytes; and the bundled console's+ `DELETE /_xerj-console/api/v1/auth/passkeys/{id}` propagates a failed delete+ instead of discarding it — it answered `204 No Content` unconditionally, so a+ revoke refused by the engine (index write block, disk flood stage, storage+ error) reported success while the passkey stayed on disk and kept+ authenticating. An already-absent credential is still a `204`; only a genuine+ failure now surfaces.**The refusal now covers every ingest path, not only `PUT /{index}/_doc`.**`POST /_bulk?pipeline=`, `index.default_pipeline` under `_bulk`,@@ -453,10 +516,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0at write time; a write addressed to an **alias** does not pick up thebacking 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; and `Engine::degraded_pipelines` is in-memory only and has no+ delete path; `Engine::degraded_pipelines` is in-memory only and has noHTTP surface yet, so a boot-replay degradation is visible in the startup logand nowhere else — unlike a definition-time refusal, which is now durable- (see *Changed*).+ (see *Changed*); and a refusal marker is only read back at boot, so a data+ dir opened by two processes at once is outside what the sidecar can promise+ (the node lock already prevents that).## [1.0.0-rc.16] - 2026-08-13diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rsindex 4d8a80e04..9513a0a11 100644--- a/engine/crates/xerj-api/src/es_compat.rs+++ b/engine/crates/xerj-api/src/es_compat.rs@@ -24206,21 +24206,14 @@ async fn sync_display_blocks(state: &AppState, name: &str) {/// (`{"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).+///+/// The spelling set lives in `xerj-fts` next to the resolver that decides which+/// of them the registry actually reads, so this gate and the create-time one+/// (`AnalyzerRegistry::unsupported_analysis`) cannot drift apart — they did:+/// this handler refused all four spellings while index creation refused two and+/// handed a `200` to the byte-equivalent dotted one.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."))- })+ xerj_engine::AnalyzerRegistry::declares_analysis(settings)}pub async fn put_settings(@@ -24826,10 +24819,32 @@ pub async fn put_ingest_pipeline(}stages.push(json!({"type": xerj_type, "config": adapted_config}));}- json!({- "description": body.get("description").and_then(Value::as_str).unwrap_or(""),- "stages": stages- })+ // Start from the body and REPLACE `processors` with `stages`, rather+ // than building a two-key object from scratch. `GET /_ingest/pipeline`+ // is the only read endpoint for a pipeline created through+ // `PUT /v1/pipelines/{name}` (the native surface registers no GET), and+ // it renders the stored definition in ES vocabulary — so GET's own+ // output, PUT back here, is an ordinary request. Rebuilding dropped+ // every key that is not `description`: a natively-defined pipeline's+ // `on_error` and `timeout_ms` vanished, silently reverting the error+ // policy from `pass` (keep the document) to the `Drop` default+ // (discard it), under a `200 {"acknowledged": true}`. That is a write+ // doing something smaller than asked — the defect class this sweep+ // exists to remove — so carry the whole body through. `PipelineConfig`+ // is not `deny_unknown_fields`, so ES-only keys (`version`, `_meta`,+ // `deprecated`) ride along harmlessly and `GET` echoes them back, which+ // is what Elasticsearch does too. Same rule as the processor-level+ // translation directly above: edit the caller's object, never rebuild+ // it (issue #204).+ let mut translated = body.clone();+ let obj = translated+ .as_object_mut()+ .expect("`body.get(\"processors\")` matched, so the body is an object");+ obj.remove("processors");+ obj.insert("stages".to_string(), Value::Array(stages));+ obj.entry("description")+ .or_insert_with(|| Value::String(String::new()));+ translated} else {body.clone()};@@ -24873,12 +24888,12 @@ pub async fn put_ingest_pipeline(// mis-ingested.//// Whichever way it goes, nothing is acknowledged before it reaches- // `cluster_state.json` (issue #203): `put_pipeline` (with `None`, so a- // refused definition stores nothing) and `register_unrunnable_pipeline`+ // `cluster_state.json` (issue #203): `put_pipeline` (which stores nothing+ // for a definition it cannot compile) and `register_unrunnable_pipeline`// both flush before returning, and an `Err` from either means the write// did not reach disk — answering `acknowledged` there would promise a// pipeline that is gone at the next boot.- match state.engine.put_pipeline(&id, xerj_config, None) {+ match state.engine.put_pipeline(&id, xerj_config) {Ok(None) if unhonoured_top_level.is_some() => {// Every stage compiled, but a top-level key we cannot act on came// with it. `register_unrunnable_pipeline` drops the compiled formdiff --git a/engine/crates/xerj-api/src/native.rs b/engine/crates/xerj-api/src/native.rsindex a6d57d7ce..a387e8944 100644--- a/engine/crates/xerj-api/src/native.rs+++ b/engine/crates/xerj-api/src/native.rs@@ -2511,12 +2511,30 @@ pub async fn put_pipeline(let started = Instant::now();let request_id = Uuid::new_v4().to_string();- // `None` — this surface rejects a definition it cannot compile, so- // nothing is stored on a compile error. On success the pipeline is- // written to `<data_dir>/cluster_state.json` before we acknowledge it- // (issue #203): it used to live only in memory and vanish on restart,- // exactly like the ES-compat one.- match state.engine.put_pipeline(&name, body, None) {+ // `GET /_ingest/pipeline/{name}` is the only read endpoint for a pipeline+ // created here (this surface registers no native GET), and it answers in+ // Elasticsearch's `processors` vocabulary. PUTting that output back here+ // used to hit `serde`'s "missing field `stages`" and surface as a bare+ // `500 internal error` — a client-shaped mistake reported as an engine+ // fault, with no hint of where the body belongs. Name the endpoint that+ // accepts it instead (issue #204).+ if body.get("stages").is_none() && body.get("processors").is_some() {+ let e = xerj_common::XerjError::config(format!(+ "pipeline [{name}]: this body is Elasticsearch-shaped (`processors`), which \+ this endpoint does not accept — it takes xerj's `stages` form. `GET \+ /_ingest/pipeline/{name}` renders every stored pipeline in Elasticsearch \+ vocabulary, so PUT that body to `/_ingest/pipeline/{name}` instead."+ ));+ return native_error(e, Some(&request_id), started.elapsed().as_millis() as u64)+ .into_response();+ }++ // This surface rejects a definition it cannot compile, so nothing is+ // stored on a compile error. On success the pipeline is written to+ // `<data_dir>/cluster_state.json` before we acknowledge it (issue #203):+ // it used to live only in memory and vanish on restart, exactly like the+ // ES-compat one.+ match state.engine.put_pipeline(&name, body) {Ok(None) => {let took_ms = started.elapsed().as_millis() as u64;let resp = NativeResponse::new(diff --git a/engine/crates/xerj-api/tests/fail_closed_config_http.rs b/engine/crates/xerj-api/tests/fail_closed_config_http.rsindex 5f8763527..74a677a6b 100644--- a/engine/crates/xerj-api/tests/fail_closed_config_http.rs+++ b/engine/crates/xerj-api/tests/fail_closed_config_http.rs@@ -1424,3 +1424,318 @@ async fn get_states_the_override_the_stage_actually_applies() {"a re-PUT of GET's own output must not start overwriting: {doc}");}++// ── The create-time analysis gate must cover every spelling it accepts ───────++/// `PUT /{index}/_settings` refuses an `analysis` declaration in all four+/// spellings; index CREATION refused two of them and handed a `200` to the+/// byte-equivalent dotted one.+///+/// The create gate resolves the JSON pointers `/analysis` and `/index/analysis`+/// only, so `{"index.analysis.filter.my_lower.type": "lowercase"}` — a flat+/// dotted key, which this same handler already parses for `index.sort.field` —+/// found nothing to check, built no filter, and was echoed straight back by+/// `GET /{index}/_settings`. By this release's own words that declaration+/// "never lowercased anything": accepted and not honoured, which is the silent+/// lie the nested spelling was closed against.+#[tokio::test]+async fn every_spelling_of_an_unhonourable_analysis_block_is_refused_at_create() {+ let (app, _dir) = app();++ // The same declaration, written four ways. `my_lower` is a custom NAME+ // that resolves to no built-in, so none of them can be honoured.+ let nested = json!({+ "filter": { "my_lower": { "type": "lowercase" } },+ "analyzer": { "a": { "type": "custom", "tokenizer": "standard", "filter": ["my_lower"] } }+ });+ let bodies = [+ ("nested", json!({ "settings": { "analysis": nested } })),+ (+ "namespaced",+ json!({ "settings": { "index": { "analysis": nested } } }),+ ),+ (+ "dotted",+ json!({ "settings": {+ "index.analysis.filter.my_lower.type": "lowercase",+ "index.analysis.analyzer.a.type": "custom",+ "index.analysis.analyzer.a.tokenizer": "standard"+ } }),+ ),+ (+ "half-dotted",+ json!({ "settings": { "index": {+ "analysis.filter.my_lower.type": "lowercase",+ "analysis.analyzer.a.type": "custom"+ } } }),+ ),+ ];++ for (i, (spelling, body)) in bodies.iter().enumerate() {+ let (status, resp) = send(&app, put(&format!("/spelling_{i}"), body.clone())).await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "the {spelling} spelling must be refused like the others: {resp}"+ );+ assert_eq!(+ resp["error"]["type"], "action_request_validation_exception",+ "{spelling}: {resp}"+ );+ assert!(+ resp["error"]["reason"]+ .as_str()+ .is_some_and(|r| r.contains("my_lower")),+ "{spelling}: the refusal must name the construct it cannot honour: {resp}"+ );+ }++ // And the gate stays narrow: a settings body that declares no analysis at+ // all still creates, and an unrelated dotted key does not trip it.+ let (status, resp) = send(+ &app,+ put(+ "/plain_idx",+ json!({ "settings": { "index.number_of_shards": 1, "index.sort.field": "ts" } }),+ ),+ )+ .await;+ assert!(+ status.is_success(),+ "an unrelated dotted setting is not an analysis declaration: {resp}"+ );+}++// ── A native definition read back in ES vocabulary must round-trip ───────────++/// `GET /_ingest/pipeline` is the only read endpoint for a pipeline created in+/// xerj's own `stages` vocabulary — the native surface registers no GET — and+/// this release taught it to answer in Elasticsearch's `processors` vocabulary.+/// PUTting that output back then went through the ES translation, which built a+/// fresh `{description, stages}` object and dropped everything else: a+/// pipeline's `on_error: "pass"` (keep the document) silently reverted to the+/// `Drop` default (discard it), and its `timeout_ms` vanished — under a+/// `200 {"acknowledged": true}`.+#[tokio::test]+async fn a_pipelines_error_policy_survives_a_round_trip_through_the_es_endpoint() {+ let dir = tempfile::tempdir().expect("tempdir");+ let app = app_in(dir.path());++ // A `stages`-shaped body takes the handler's pass-through branch, which is+ // exactly what `PUT /v1/pipelines/{name}` stores.+ let native = json!({+ "description": "n3",+ "on_error": "pass",+ "timeout_ms": 250,+ "stages": [{ "type": "set", "config": { "field": "e", "value": "prod" } }]+ });+ let (status, body) = send(&app, put("/_ingest/pipeline/n3", native)).await;+ assert_eq!(status, StatusCode::OK, "{body}");++ let (_, stored) = send(&app, get("/_ingest/pipeline/n3")).await;+ assert_eq!(stored["n3"]["on_error"], "pass", "{stored}");+ assert_eq!(stored["n3"]["timeout_ms"], 250, "{stored}");++ // The operator PUTs back what GET handed them, unedited.+ let (status, body) = send(&app, put("/_ingest/pipeline/n3", stored["n3"].clone())).await;+ assert_eq!(status, StatusCode::OK, "{body}");++ let (_, after) = send(&app, get("/_ingest/pipeline/n3")).await;+ assert_eq!(+ after["n3"]["on_error"], "pass",+ "measured before this fix: the key was gone and the policy reverted from `pass` \+ (keep the document) to the `Drop` default (discard it): {after}"+ );+ assert_eq!(after["n3"]["timeout_ms"], 250, "{after}");++ // The same must hold across a restart, since it is the stored definition+ // that the boot recompiles.+ drop(app);+ let app = app_in(dir.path());+ let (_, rebooted) = send(&app, get("/_ingest/pipeline/n3")).await;+ assert_eq!(rebooted["n3"]["on_error"], "pass", "{rebooted}");+ assert_eq!(rebooted["n3"]["timeout_ms"], 250, "{rebooted}");+}++/// Elasticsearch metadata on a pipeline that compiles is echoed back rather+/// than dropped — the same edit-do-not-rebuild rule, one level up.+#[tokio::test]+async fn es_pipeline_metadata_is_not_dropped_by_the_translation() {+ let (app, _dir) = app();+ let (status, body) = send(+ &app,+ put(+ "/_ingest/pipeline/meta",+ json!({+ "description": "d",+ "version": 3,+ "_meta": { "owner": "platform" },+ "processors": [{ "set": { "field": "e", "value": "prod" } }]+ }),+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{body}");+ let (_, got) = send(&app, get("/_ingest/pipeline/meta")).await;+ assert_eq!(got["meta"]["version"], 3, "{got}");+ assert_eq!(got["meta"]["_meta"]["owner"], "platform", "{got}");+ assert_eq!(got["meta"]["description"], "d", "{got}");+ assert!(got["meta"].get("stages").is_none(), "{got}");+}++// ── Concurrency: the refusal marker under parallel writes ───────────────────++/// The HTTP statement of the engine-level race: refusals issued CONCURRENTLY+/// must all survive a restart. Every other restart test on this endpoint is+/// sequential, which is why a green suite sat on top of a mechanism that did+/// not hold.+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]+async fn concurrently_refused_pipelines_are_all_still_refused_after_a_restart() {+ const N: usize = 24;++ let dir = tempfile::tempdir().expect("tempdir");+ let app = app_in(dir.path());++ let mut tasks = Vec::with_capacity(N);+ for i in 0..N {+ let app = app.clone();+ tasks.push(tokio::spawn(async move {+ let (status, body) = send(+ &app,+ put(+ &format!("/_ingest/pipeline/sc{i}"),+ json!({ "stages": [{+ "type": "drop_field",+ "config": { "fields": ["secret"], "if": "ctx.tenant == 'a'" }+ }] }),+ ),+ )+ .await;+ (i, status, body)+ }));+ }+ for t in tasks {+ let (i, status, body) = t.await.expect("no panic");+ assert_eq!(status, StatusCode::OK, "sc{i}: {body}");+ assert_eq!(body["acknowledged"], true, "sc{i}: {body}");+ }++ // Restart. Nothing else — no PUT, no operator action.+ drop(app);+ let app = app_in(dir.path());++ for i in 0..N {+ let (status, body) = send(+ &app,+ put(+ &format!("/docs/_doc/{i}?pipeline=sc{i}"),+ json!({ "tenant": "b", "secret": "ssn-111" }),+ ),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "sc{i} was refused before the restart and must still be refused after it — \+ measured before the flush was serialised: 3 of 40 markers never reached \+ disk, and the identical write answered 201 with `secret` dropped from a \+ document the guard excludes: {body}"+ );+ let (status, doc) = send(&app, get(&format!("/docs/_doc/{i}"))).await;+ assert_ne!(status, StatusCode::OK, "sc{i}: {doc}");+ }+}++/// A corrupt sidecar must not be silently repaired into a smaller one. Seen+/// from HTTP: the refusal that would have overwritten it is not acknowledged.+#[tokio::test]+async fn a_refused_put_is_not_acknowledged_while_the_sidecar_is_unreadable() {+ let dir = tempfile::tempdir().expect("tempdir");+ let path = dir.path().join("ingest-pipeline-refusals.json");+ let corrupt = b"{\"older_refusal\": \"processor-level [if] is not supported\", ";+ std::fs::write(&path, corrupt).unwrap();++ let app = app_in(dir.path());+ let (status, body) = send(+ &app,+ put(+ "/_ingest/pipeline/newly_refused",+ json!({ "processors": [+ { "set": { "field": "e", "value": "prod", "ignore_failure": true } }+ ] }),+ ),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::INTERNAL_SERVER_ERROR,+ "a refusal that cannot be recorded must not be acknowledged: {body}"+ );+ assert!(+ body["error"]["reason"]+ .as_str()+ .is_some_and(|r| r.contains("ingest-pipeline-refusals.json")),+ "and it must name the file to move aside: {body}"+ );+ assert_eq!(+ std::fs::read(&path).unwrap(),+ corrupt,+ "the sidecar must be left exactly as found"+ );+}++// ── The native pipeline endpoint and the ES body it now hands out ───────────++fn native_app_in(data_dir: &std::path::Path) -> axum::Router {+ let mut config = xerj_common::config::Config::default();+ config.server.data_dir = data_dir.to_string_lossy().into_owned();+ config.storage.wal_sync = xerj_common::config::WalSync::Async;+ let metrics = xerj_common::metrics::Metrics::new().expect("metrics");+ let engine = xerj_engine::Engine::new(config.clone()).expect("engine");+ let state = xerj_api::state::AppState::new(config, engine, metrics);+ xerj_api::router::build_native_router(state)+}++/// `GET /_ingest/pipeline/{name}` is the only way to read a pipeline created+/// through `PUT /v1/pipelines/{name}`, and it now answers in Elasticsearch's+/// vocabulary. PUTting that body back to the native endpoint hit serde's+/// "missing field stages" and surfaced as a bare `500 internal error` — a+/// client-shaped mistake reported as an engine fault, with no hint of where the+/// body belongs.+#[tokio::test]+async fn the_native_endpoint_answers_400_and_names_the_endpoint_for_an_es_body() {+ let dir = tempfile::tempdir().expect("tempdir");+ let app = native_app_in(dir.path());++ let (status, body) = send(+ &app,+ put(+ "/v1/pipelines/n1",+ json!({ "description": "n1",+ "processors": [{ "set": { "field": "e", "value": "prod" } }] }),+ ),+ )+ .await;+ assert_eq!(+ status,+ StatusCode::BAD_REQUEST,+ "measured before this fix: 500 internal error, missing field `stages`: {body}"+ );+ assert!(+ body["reason"]+ .as_str()+ .is_some_and(|r| r.contains("/_ingest/pipeline/n1")),+ "the error must name the endpoint that accepts the body: {body}"+ );++ // The native shape still works.+ let (status, body) = send(+ &app,+ put(+ "/v1/pipelines/n1",+ json!({ "stages": [{ "type": "set", "config": { "field": "e", "value": "prod" } }] }),+ ),+ )+ .await;+ assert!(status.is_success(), "{body}");+}diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rsindex 8686a0b12..c527162de 100644--- a/engine/crates/xerj-engine/src/engine.rs+++ b/engine/crates/xerj-engine/src/engine.rs@@ -983,6 +983,14 @@ impl Engine {// the operator designed. Must run after the index scan above, so a// restored data stream can report which of its backing indices are// actually present, and before the server accepts requests.+ // Issue #204: the refusal markers are read BEFORE the pipelines+ // they classify, and unconditionally — not from inside+ // `apply_cluster_state`, which returns early when there is no+ // `cluster_state.json`. On that path an unreadable sidecar left+ // `pipeline_refusals_unreadable` false, so the first refused `PUT`+ // would have overwritten the file with a one-entry map and erased+ // every marker still in it.+ engine.load_persisted_pipeline_refusals();engine.apply_cluster_state(prepared_cluster_state);// Then say plainly which `.ds-*` indices no restored stream claims.@@ -1753,7 +1761,50 @@ impl Engine {/// one an older, gate-less build wrote, and would soften the refusal back/// into a `201` (issue #204). Same rule `flush_cluster_state` already/// enforces for the definition itself (issue #203).+ ///+ /// # Why the snapshot is taken inside the lock+ ///+ /// This writes the WHOLE map, so two concurrent refused `PUT`s are a+ /// lost-update race, not a merge: each inserts its own marker, each+ /// snapshots, and the one that writes SECOND with the OLDER snapshot+ /// erases the other's marker from disk — while both callers are told+ /// `{"acknowledged": true}`, which is exactly the promise this function's+ /// `Err` contract exists to keep. Measured on the unlocked version at a+ /// live node: 40 concurrent refused `PUT`s, 40 acknowledged, 37 markers on+ /// disk; after a plain restart the three lost ones replayed at+ /// `ReplayPersisted`, answered `201`, and dropped a field from a document+ /// their `if` guard excluded. Sequential tests never see it.+ ///+ /// `cluster_state_write` is the mutex, not a second one, because the two+ /// files are written back to back by the same callers and one order for+ /// both is easier to reason about than two. It is taken and released here,+ /// never held across `flush_cluster_state` — `parking_lot::Mutex` is not+ /// reentrant.fn flush_pipeline_refusals(&self) -> Result<()> {+ // A boot that could not READ this file has an empty in-memory map, so+ // writing it would erase every marker still on disk: the next boot+ // would parse the truncated file cleanly, conclude those definitions+ // have no provenance, and replay them at `ReplayPersisted` — the very+ // hole the marker closes, reopened by the fail-closed path itself.+ // Refuse instead, and name the file, so the operator's repair is to+ // move it aside rather than to discover the loss at the next restart+ // (issue #204).+ if self+ .pipeline_refusals_unreadable+ .load(std::sync::atomic::Ordering::SeqCst)+ {+ return Err(EngineError::Common(xerj_common::XerjError::internal(+ format!(+ "{} could not be read at boot, so its markers are not in memory and \+ rewriting it here would erase every refusal it still holds; every \+ persisted pipeline is being replayed at definition strictness until \+ the file is moved aside and this node restarted",+ self.pipeline_refusals_path().display()+ ),+ )));+ }+ // One writer at a time, snapshot included — see the doc comment.+ let _writing = self.cluster_state_write.lock();let snapshot: std::collections::BTreeMap<String, String> = self.definition_time_refusals.iter()@@ -2351,8 +2402,11 @@ impl Engine {// exactly as it did before the restart.//// Which strictness a definition is replayed at is decided by- // PROVENANCE, never by the calendar (issue #204). Load the markers- // first — see `definition_time_refusals`.+ // PROVENANCE, never by the calendar (issue #204). The markers are+ // already loaded — `Engine::new` does it before this runs, so the+ // no-`cluster_state.json` path sees them too — and loading is+ // idempotent, so this call keeps every other caller of+ // `apply_cluster_state` correct on its own.self.load_persisted_pipeline_refusals();let provenance_unknown = self.pipeline_refusals_unreadable@@ -2607,32 +2661,33 @@ impl Engine {/// gets stored (and handed back by `GET /_ingest/pipeline/{id}`) when it/// compiles — the shape this endpoint has always returned.///- /// `keep_if_uncompilable` says what to do when it does *not* compile, and- /// differs by surface:+ /// A definition that does not compile is NOT stored: `Ok(Some(err))` is+ /// returned, nothing is flushed, and any pipeline already registered under+ /// this id is left untouched. A caller that must keep an uncompilable+ /// definition readable — the ES-compat surface does, because Elasticsearch+ /// accepts processors this build does not implement — calls+ /// [`Self::register_unrunnable_pipeline`] instead, which stores the+ /// definition *and* the reason it cannot run, and persists the refusal+ /// marker that makes that reason survive a restart.///- /// * `Some(doc)` — the ES-compat surface. It has always answered- /// `acknowledged` and left the definition readable, so `doc` (the- /// ES-shaped body as received) is stored and the compile error is- /// returned as `Ok(Some(err))` for the caller to log.- /// * `None` — the xerj-native surface, which rejects a definition it- /// cannot compile. Nothing is stored, nothing is flushed, and any- /// pipeline already registered under this id is left untouched.+ /// (This used to take a third `keep_if_uncompilable: Option<Value>`+ /// argument whose `Some` arm stored the definition here. Every caller in+ /// the workspace passed `None` — the ES surface routes through+ /// `register_unrunnable_pipeline` — so the arm was unreachable, untested,+ /// and held its own copy of the refusal-marker bookkeeping that the live+ /// path already does. Issue #204: a security-relevant branch with no+ /// caller is a liability, not a spare part.)///- /// Either way a compile failure drops the *executable* form under this- /// id. Leaving the old one behind would mean `?pipeline={id}` kept- /// running a definition `GET` no longer shows — and stopped running it at- /// the next restart. A definition must behave the same before and after a- /// reboot; that is the whole point of persisting it.+ /// A compile failure drops the *executable* form under this id. Leaving+ /// the old one behind would mean `?pipeline={id}` kept running a+ /// definition `GET` no longer shows — and stopped running it at the next+ /// restart. A definition must behave the same before and after a reboot;+ /// that is the whole point of persisting it.////// `Err` means the definition did not reach disk. The in-memory change is/// rolled back first, so the caller can report the write as failed/// without leaving behind a pipeline only this process can see.- pub fn put_pipeline(- &self,- id: &str,- config: Value,- keep_if_uncompilable: Option<Value>,- ) -> Result<Option<xerj_wasm::WasmError>> {+ pub fn put_pipeline(&self, id: &str, config: Value) -> Result<Option<xerj_wasm::WasmError>> {// Up front, so a refused write never disturbs the compiled form of a// pipeline that is still running.self.ensure_cluster_state_writable()?;@@ -2658,38 +2713,12 @@ impl Engine {// `compile_pipeline` mutates nothing when it fails, so an abort only// has to undo the two lines above.- let compile_err = match self.compile_pipeline(id, config) {- Ok(()) => None,- Err(e) => match keep_if_uncompilable {- None => {- if let Some(p) = previous_compiled {- self.transform_pipelines.insert(id.to_string(), p);- }- return Ok(Some(e));- }- 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.- let reason = format!(- "the stored definition does not compile ({e}); no \- document can be ingested through pipeline [{id}]"- );- self.unrunnable_pipelines- .insert(id.to_string(), reason.clone());- // …and the refusal must survive a restart, or the boot- // replay softens it and the definition starts running- // with the refused option ignored (issue #204). Flushed- // below, after the definition itself reaches disk.- self.definition_time_refusals.insert(id.to_string(), reason);- Some(e)- }- },- };+ if let Err(e) = self.compile_pipeline(id, config) {+ if let Some(p) = previous_compiled {+ self.transform_pipelines.insert(id.to_string(), p);+ }+ return Ok(Some(e));+ }// Every abort path restores exactly the state this call found, so a// write that did not reach disk leaves nothing only this process can@@ -2753,12 +2782,10 @@ impl Engine {return Err(e);}- if let Some(e) = &compile_err {- warn!(pipeline = id, error = %e, "pipeline stored but failed to compile");- } else {- info!(name = id, "transform pipeline created");- }- Ok(compile_err)+ info!(name = id, "transform pipeline created");+ // `Ok(None)` is now the only success: a definition that does not+ // compile returned `Ok(Some(err))` above without storing anything.+ Ok(None)}/// Delete an ingest pipeline — both the stored definition and the@@ -3803,9 +3830,22 @@ impl Engine {/// Like [`Engine::put_pipeline`], the stored definition is flushed to/// `cluster_state.json` before the caller may acknowledge it (issue/// #203). `Err` means it did not reach disk; the in-memory change is- /// rolled back first. The *reason* itself is in-memory only: after a- /// restart the boot replay fails to recompile the stored definition and- /// re-records why, so the pipeline stays unrunnable — loudly — either way.+ /// rolled back first.+ ///+ /// The *reason* is persisted too, in+ /// `<data_dir>/ingest-pipeline-refusals.json`, and that is not+ /// belt-and-braces. This docstring used to claim the reason could stay in+ /// memory "because the boot replay fails to recompile the stored+ /// definition and re-records why" — which is false for the shape that+ /// matters. A `stages`-shaped definition (the one `GET` hands an operator+ /// to edit and re-`PUT`) recompiles at boot in the compatibility mode that+ /// exists for definitions written by a gate-less build, so the refusal was+ /// SOFTENED by a restart: measured, a refused `{"remove": {"field":+ /// "secret", "if": …}}` went from `400` to `201` across a plain restart,+ /// with `secret` dropped from a document the guard excludes. The marker is+ /// what tells the replay "this build already answered 400 for this exact+ /// definition", so the flush below is on the acknowledge path exactly like+ /// the definition's own.pub fn register_unrunnable_pipeline(&self,name: &str,diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rsindex 61a80b1ad..8b12b5b2b 100644--- a/engine/crates/xerj-engine/src/lib.rs+++ b/engine/crates/xerj-engine/src/lib.rs@@ -235,9 +235,15 @@ pub(crate) fn flush_finalize_gate() -> &'static tokio::sync::Semaphore {// ── Analyzer helpers ──────────────────────────────────────────────────────────use std::sync::Arc;+// `AnalyzerRegistry` is `pub use`d, not merely imported, so the API layer can+// gate `PUT /{index}/_settings` on exactly the `analysis` spellings the+// registry resolves without xerj-api taking a direct dependency on xerj-fts.+// The create-time and settings-time gates drifted apart once already — one+// refused four spellings, the other two — and one shared symbol is what stops+// that (issue #204).+pub use xerj_fts::analyzer::AnalyzerRegistry;use xerj_fts::analyzer::{- AnalyzerRegistry, LowercaseFilter, StandardTokenizer, StemmerFilter, StopwordsFilter,- TokenFilter, Tokenizer,+ LowercaseFilter, StandardTokenizer, StemmerFilter, StopwordsFilter, TokenFilter, Tokenizer,};/// Return a default [`AnalyzerRegistry`] pre-populated with all built-in analyzers.diff --git a/engine/crates/xerj-engine/tests/es_compat_tests.rs b/engine/crates/xerj-engine/tests/es_compat_tests.rsindex 2c8f617a7..606d39baa 100644--- a/engine/crates/xerj-engine/tests/es_compat_tests.rs+++ b/engine/crates/xerj-engine/tests/es_compat_tests.rs@@ -874,7 +874,6 @@ async fn test_es_bulk_per_item_pipeline() {{ "type": "set", "config": { "field": "ingested", "value": "yes", "override": true } }]}),- None,).expect("put_pipeline");assert!(diff --git a/engine/crates/xerj-engine/tests/integration.rs b/engine/crates/xerj-engine/tests/integration.rsindex 7fcce1a7d..f61e5402c 100644--- a/engine/crates/xerj-engine/tests/integration.rs+++ b/engine/crates/xerj-engine/tests/integration.rs@@ -6815,7 +6815,6 @@ async fn a_persisted_pipeline_the_new_checks_refuse_still_runs_after_a_restart()json!({ "stages": [{ "type": "grok", "config": { "field": "msg", "pattern": "GENERIC" } }] }),- None,).expect("a clean definition stores");}@@ -6854,7 +6853,6 @@ async fn a_persisted_pipeline_the_new_checks_refuse_still_runs_after_a_restart()json!({ "stages": [{ "type": "grok", "config": { "field": "msg", "pattern": "NGINX_COMBINE" } }] }),- None,).expect("put_pipeline returns the compile error, not an Err");assert!(@@ -6932,7 +6930,6 @@ async fn a_definition_that_compiles_clears_its_refusal_marker() {.put_pipeline("p",json!({ "stages": [{ "type": "set", "config": { "field": "a", "value": 1 } }] }),- None,).expect("no IO failure").is_none());@@ -6972,7 +6969,6 @@ async fn a_refusal_marker_deleted_with_its_pipeline_cannot_haunt_the_next_defini.put_pipeline("p",json!({ "stages": [{ "type": "set", "config": { "field": "a", "value": 1 } }] }),- None,).expect("no IO failure").is_none());@@ -6998,7 +6994,6 @@ async fn an_unparseable_refusal_marker_makes_the_replay_strict() {json!({ "stages": [{ "type": "grok", "config": { "field": "msg", "pattern": "GENERIC" } }] }),- None,).expect("a clean definition stores");}@@ -7033,3 +7028,146 @@ async fn an_unparseable_refusal_marker_makes_the_replay_strict() {"the reason must name the file to repair: {reason}");}++// ─────────────────────────────────────────────────────────────────────────────+// Issue #204 — a refusal marker must survive CONCURRENT definition-time+// refusals, not just sequential ones.+// ─────────────────────────────────────────────────────────────────────────────++/// `flush_pipeline_refusals` writes the WHOLE map, so two refusals racing is a+/// lost update, not a merge: both callers are told the write succeeded, and the+/// one that writes second with the older snapshot erases the other's marker.+/// The next boot then finds no provenance for that definition, replays it in+/// the compatibility mode meant for gate-less builds, and answers `201` to the+/// write an operator was already told was a `400` — with the field dropped from+/// a document the `if` guard excludes.+///+/// Fail-before, measured on this test with only the `cluster_state_write.lock()`+/// line removed from `flush_pipeline_refusals` and nothing else: 6 runs, 5+/// failed — 3, 2, 8, 5 and 1 marker(s) of 64 acknowledged and never written,+/// one run clean. Three bursts per run is what makes the detector reliable+/// rather than 5-in-6; a false pass needs all three to come out clean.+#[tokio::test(flavor = "multi_thread", worker_threads = 8)]+async fn concurrent_definition_time_refusals_all_reach_disk() {+ const THREADS: usize = 64;+ const BURSTS: usize = 3;++ let dir = TempDir::new().unwrap();+ let engine = std::sync::Arc::new(make_engine(&dir));+ let path = dir.path().join("ingest-pipeline-refusals.json");+ let mut expected: Vec<String> = Vec::with_capacity(THREADS * BURSTS);++ for burst in 0..BURSTS {+ // Deliberately NOT barriered. A barrier makes every insert land before+ // the first snapshot is taken, which closes the very window this is+ // about; the losses come from threads that snapshot while others are+ // still inserting. `spawn_blocking` rather than `std::thread` because+ // the engine's writes are synchronous but its constructor wants a+ // runtime handle in scope.+ let mut handles = Vec::with_capacity(THREADS);+ for i in 0..THREADS {+ let engine = std::sync::Arc::clone(&engine);+ let id = format!("refused_{burst}_{i}");+ expected.push(id.clone());+ handles.push(tokio::task::spawn_blocking(move || {+ engine.register_unrunnable_pipeline(+ &id,+ json!({ "stages": [+ { "type": "drop_field",+ "config": { "fields": ["secret"], "if": "ctx.tenant == 'a'" } }+ ] }),+ format!("processor-level [if] is not supported ({id})"),+ )+ }));+ }+ for (i, h) in handles.into_iter().enumerate() {+ h.await+ .expect("no panic")+ .unwrap_or_else(|e| panic!("refused_{burst}_{i} was not acknowledgeable: {e}"));+ }++ // Every call returned `Ok`, which is the promise that the marker+ // reached disk. Read the file back and hold it to that — including+ // every marker from an earlier burst, which a stale snapshot erases+ // just as easily.+ let on_disk: std::collections::BTreeMap<String, String> =+ serde_json::from_slice(&std::fs::read(&path).expect("the sidecar must exist"))+ .expect("and it must parse");+ let missing: Vec<&String> = expected+ .iter()+ .filter(|id| !on_disk.contains_key(*id))+ .collect();+ assert!(+ missing.is_empty(),+ "burst {burst}: {} of {} markers were acknowledged and never reached disk: \+ {missing:?}",+ missing.len(),+ expected.len()+ );+ }++ // …and the point of the marker: every one of them is still refused after a+ // restart, with no PUT and no operator action in between.+ drop(engine);+ let rebooted = make_engine(&dir);+ for id in &expected {+ assert!(+ !rebooted.transform_pipelines.contains_key(id),+ "{id} was refused at definition time; a restart must not start running it"+ );+ assert!(+ rebooted.unrunnable_pipelines.contains_key(id),+ "{id} must still say why it cannot run"+ );+ }+}++/// A sidecar this build could not READ must not be overwritten by the next+/// refusal.+///+/// The file is written whole from the in-memory map, and a boot that could not+/// parse it starts with that map EMPTY. Flushing it then leaves exactly one+/// marker on disk and erases every other refusal the file still held — after+/// which the file parses cleanly, so the next boot concludes those definitions+/// have no provenance and replays them softly. The fail-closed behaviour would+/// last exactly one process lifetime and then convert itself into the hole it+/// exists to close, with no signal.+#[tokio::test]+async fn a_refusal_is_not_acknowledged_while_the_sidecar_is_unreadable() {+ let dir = TempDir::new().unwrap();+ let path = dir.path().join("ingest-pipeline-refusals.json");+ let corrupt = b"{\"still_refused\": \"processor-level [if] is not supported\", ";+ std::fs::write(&path, corrupt).unwrap();++ let engine = make_engine(&dir);+ assert!(+ engine+ .pipeline_refusals_unreadable+ .load(std::sync::atomic::Ordering::SeqCst),+ "boot must record that the markers could not be classified"+ );++ let err = engine+ .register_unrunnable_pipeline(+ "newly_refused",+ json!({ "stages": [{ "type": "drop_field", "config": { "fields": ["s"] } }] }),+ "processor-level [if] is not supported".to_string(),+ )+ .expect_err("this must NOT be acknowledgeable while the sidecar is unreadable");+ let err = err.to_string();+ assert!(+ err.contains("ingest-pipeline-refusals.json"),+ "the error must name the file the operator has to move aside: {err}"+ );++ assert_eq!(+ std::fs::read(&path).unwrap(),+ corrupt,+ "the unreadable sidecar must be left exactly as found — rewriting it from an \+ empty in-memory map is what erases every refusal it still holds"+ );+ assert!(+ !engine.pipelines.contains_key("newly_refused"),+ "and nothing may be left behind that only this process can see"+ );+}diff --git a/engine/crates/xerj-fts/src/analyzer.rs b/engine/crates/xerj-fts/src/analyzer.rsindex 710fbea43..c13a6d3be 100644--- a/engine/crates/xerj-fts/src/analyzer.rs+++ b/engine/crates/xerj-fts/src/analyzer.rs@@ -1395,11 +1395,38 @@ impl AnalyzerRegistry {/// `build_registry_from_settings` accepts.pub fn unsupported_analysis(settings: &serde_json::Value) -> Vec<String> {let root = settings.pointer("/settings").unwrap_or(settings);+ let mut problems = Vec::new();++ // The DOTTED spelling first, because it is not a variant of the block+ // below — it is a block this build never reads at all.+ // `analysis_block` resolves two JSON pointers, so+ // `{"index.analysis.filter.my_lower.type": "lowercase"}` finds nothing:+ // the gate passes it, `apply_settings` builds no filter from it, and+ // `GET /{index}/_settings` echoes back an analyzer that analyses+ // nothing. Byte-for-byte the same request as the nested form this gate+ // 400s, one spelling apart — and `PUT /{index}/_settings` already+ // refuses all four spellings, so accepting it here made the two gates+ // disagree about the same string (issue #204).+ //+ // Reported rather than honoured: teaching the registry to expand+ // dotted keys would change what an EXISTING index analyses the moment+ // it reopens, which is the upgrade break `analysis-binding.json`+ // exists to prevent. Refusing at create time changes nothing already+ // on disk.+ for key in Self::dotted_analysis_keys(root) {+ problems.push(format!(+ "setting [{key}]: the flat dotted spelling of an `analysis` declaration is \+ not read by this build — the analyzer registry resolves `analysis.*` and \+ `index.analysis.*` as nested objects only, so this declaration would be \+ stored, echoed back by `GET /_settings`, and applied to nothing. Write it \+ as a nested object instead"+ ));+ }+let Some(analysis) = Self::analysis_block(root) else {- return Vec::new();+ return problems;};let probe = Self::with_defaults();- let mut problems = Vec::new();// Declared names are collected even when their `type` is unsupported,// so a bad type is reported once (as a type problem) rather than twice@@ -1720,6 +1747,69 @@ impl AnalyzerRegistry {}}+ /// Every key in `settings` that declares something under `analysis` using+ /// a DOTTED path rather than a nested object, in the order they appear.+ ///+ /// The three spellings below are one request as far as an Elasticsearch+ /// client is concerned, and xerj's settings handlers accept all of them for+ /// other namespaces (`index.sort.field` is parsed dotted today):+ ///+ /// ```json+ /// {"index.analysis.analyzer.x.type": "custom"} // fully dotted+ /// {"analysis.analyzer.x.type": "custom"} // dotted, unnamespaced+ /// {"index": {"analysis.analyzer.x.type": "custom"}} // half-dotted+ /// ```+ ///+ /// [`Self::analysis_block`] resolves none of them, so on their own they are+ /// accepted-and-ignored. Callers that gate on+ /// [`Self::unsupported_analysis`] get them reported; the registry builder+ /// deliberately still ignores them, so nothing already on disk changes+ /// meaning (issue #204).+ ///+ /// `settings` may be the full envelope or the inner settings object, the+ /// same two shapes [`Self::unsupported_analysis`] accepts.+ pub fn dotted_analysis_keys(settings: &serde_json::Value) -> Vec<String> {+ let root = settings.pointer("/settings").unwrap_or(settings);+ let mut keys = Vec::new();+ if let Some(obj) = root.as_object() {+ for k in obj.keys() {+ // A bare `analysis` key IS the nested form `analysis_block`+ // reads; it is not a dotted spelling and is gated elsewhere.+ // `index.analysis` is dotted even though its value is nested,+ // because the pointer this build resolves is `/index/analysis`+ // — an `index` OBJECT with an `analysis` member, which a key+ // literally named `index.analysis` is not.+ if k == "analysis" {+ continue;+ }+ let bare = k.strip_prefix("index.").unwrap_or(k);+ if bare == "analysis" || bare.starts_with("analysis.") {+ keys.push(k.clone());+ }+ }+ }+ if let Some(ix) = root.get("index").and_then(serde_json::Value::as_object) {+ keys.extend(+ ix.keys()+ .filter(|k| k.starts_with("analysis."))+ .map(|k| format!("index.{k}")),+ );+ }+ keys+ }++ /// True when `settings` reaches into the `analysis` namespace in ANY+ /// spelling — nested, namespaced, dotted or half-dotted.+ ///+ /// One helper so a caller cannot gate on a subset of the spellings it+ /// accepts. A gate that tests only the nested one is not a gate (#204).+ pub fn declares_analysis(settings: &serde_json::Value) -> bool {+ let root = settings.pointer("/settings").unwrap_or(settings);+ root.pointer("/analysis").is_some()+ || root.pointer("/index/analysis").is_some()+ || !Self::dotted_analysis_keys(root).is_empty()+ }+/// 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.@@ -2603,6 +2693,76 @@ mod unsupported_analysis_tests {));}+ /// The flat dotted spelling of an analysis declaration is one `apply_settings`+ /// never reads, so accepting it is accepting a block that analyses nothing.+ ///+ /// `PUT /{index}/_settings` refused all four spellings while `PUT /{index}`+ /// refused two: `unsupported_analysis` resolved the pointers `/analysis` and+ /// `/index/analysis` and nothing else, so the byte-equivalent dotted request+ /// got a `200` and `GET /_settings` echoed the analyzer straight back+ /// (issue #204).+ #[test]+ fn the_dotted_spellings_of_an_analysis_declaration_are_reported() {+ for dotted in [+ json!({ "index.analysis.filter.my_lower.type": "lowercase" }),+ json!({ "analysis.filter.my_lower.type": "lowercase" }),+ json!({ "index": { "analysis.filter.my_lower.type": "lowercase" } }),+ // Dotted namespace, nested value — `pointer("/index/analysis")`+ // wants an `index` OBJECT, which this key is not.+ json!({ "index.analysis": { "filter": { "my_lower": { "type": "lowercase" } } } }),+ // …and through the outer `settings` envelope, the shape index+ // creation actually hands over.+ json!({ "settings": { "index.analysis.analyzer.a.type": "custom" } }),+ ] {+ assert!(+ AnalyzerRegistry::declares_analysis(&dotted),+ "must be recognised as an analysis declaration: {dotted}"+ );+ let problems = AnalyzerRegistry::unsupported_analysis(&dotted);+ assert_eq!(+ problems.len(),+ 1,+ "exactly one problem, naming the offending key: {dotted} -> {problems:?}"+ );+ assert!(+ problems[0].contains("dotted"),+ "the message must say what is wrong with it: {problems:?}"+ );+ }+ }++ /// …and the check stays narrow: a nested block is judged on its merits, and+ /// a dotted key outside the `analysis` namespace is not an analysis+ /// declaration at all. `index.sort.field` is parsed dotted by the same+ /// create handler, so a prefix-only test would have 400'd it.+ #[test]+ fn a_dotted_key_outside_the_analysis_namespace_is_not_a_declaration() {+ for innocent in [+ json!({ "index.number_of_shards": 1 }),+ json!({ "index.sort.field": "ts", "index.sort.order": "desc" }),+ json!({ "index": { "number_of_replicas": 0 } }),+ json!({}),+ // The nested spellings are NOT dotted — they are read, and judged+ // by the checks below rather than reported here.+ json!({ "analysis": { "filter": { "lowercase": { "type": "lowercase" } } } }),+ json!({ "index": { "analysis": { "filter": {} } } }),+ ] {+ assert!(+ AnalyzerRegistry::dotted_analysis_keys(&innocent).is_empty(),+ "not a dotted analysis declaration: {innocent}"+ );+ }+ // A nested, honourable block is still accepted — the dotted check must+ // not have turned the gate into a blanket refusal.+ assert!(+ AnalyzerRegistry::unsupported_analysis(&json!({+ "analysis": { "filter": { "lowercase": { "type": "lowercase" } } }+ }))+ .is_empty(),+ "a declaration whose NAME resolves to a built-in is honoured"+ );+ }+#[test]fn unresolvable_tokenizer_is_reported() {// Pre-fix: this analyzer was registered with a StandardTokenizer and