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(server): report effective data directory provenance at startup (#2414)
Jarvis4a5de64c6f2e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1bd033cfe..0a01cec3b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -79,6 +79,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Server startup now reports the resolved data directory, its configuration+ source and whether this launch created it. New-directory guidance points+ operators back to their previous `--data-dir` or `--config` when they expected+ existing indices/accounts. Defaults, flag precedence, auto-port relocation+ and existing data are preserved; no other data directories are scanned (#2409).+- `POST /{index}/_search` applies `post_filter` to the hits, asElasticsearch does. It used to be accepted and ignored: every documentthe query matched came back and `hits.total` counted them all.diff --git a/README.md b/README.mdindex 57c710717..b77074071 100644--- a/README.md+++ b/README.md@@ -67,6 +67,12 @@ Keep that data directory outside any folder you will autoindex. `data/` is not ibuilt-in ignore list, so `--data-dir ./data` inside a tree you then index makes the nodeindex its own storage.+At startup, `Data dir` shows the resolved absolute path, `Data source` identifies+the flag, selected config file or default, and `Data status` says whether this+launch created the directory. A new directory can make an older node's indices+or owner account appear missing: restart with the previous `--data-dir` or+`--config`. XERJ does not discover or migrate other data directories automatically.+Windows and a hand-verified install are under [Install by hand](#install-by-hand).That `--insecure` flag is a trust boundary, not a formality. It turns off TLS and API-keydiff --git a/engine/Cargo.lock b/engine/Cargo.lockindex ff36d778d..ee3e68adf 100644--- a/engine/Cargo.lock+++ b/engine/Cargo.lock@@ -7767,6 +7767,7 @@ dependencies = ["tikv-jemallocator","tokio","tokio-stream",+ "toml","tonic","tonic-build","tower 0.4.13",diff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.tomlindex de5ecaa1b..cc2523d6d 100644--- a/engine/crates/xerj-server/Cargo.toml+++ b/engine/crates/xerj-server/Cargo.toml@@ -44,6 +44,7 @@ tracing.workspace = truetracing-subscriber.workspace = trueserde.workspace = trueserde_json.workspace = true+toml.workspace = truercgen.workspace = truerand.workspace = trueanyhow.workspace = truediff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 8d83fec68..1553adabd 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -143,6 +143,7 @@ mod grpc;mod grpc_hub;mod ingest_memory_trace;mod share;+mod startup_data_dir;// ─────────────────────────────────────────────────────────────────────────────// CLI@@ -638,7 +639,12 @@ fn auth_disabled_line(loopback: bool) -> &'static str {}}-fn print_banner(cfg: &Config, bound: &BoundAddrs, startup_ms: u128) {+fn print_banner(+ cfg: &Config,+ bound: &BoundAddrs,+ startup_ms: u128,+ data_dir: &startup_data_dir::Report,+) {let tls = if cfg.tls.enabled { "TLS " } else { "plain" };println!();println!(" ██╗ ██╗███████╗██████╗ ██╗");@@ -670,7 +676,12 @@ fn print_banner(cfg: &Config, bound: &BoundAddrs, startup_ms: u128) {bind,bound.grpc.port());- println!(" Data dir {}", cfg.server.data_dir);+ println!(" Data dir {}", data_dir.path_text());+ println!(" Data source {}", data_dir.source);+ println!(" Data status {}", data_dir.status());+ if data_dir.created {+ println!(" {}", startup_data_dir::NEW_DIRECTORY_HINT);+ }println!(" Started in {}ms", startup_ms);println!();println!(@@ -757,22 +768,50 @@ fn print_banner(cfg: &Config, bound: &BoundAddrs, startup_ms: u128) {// ─────────────────────────────────────────────────────────────────────────────fn load_config(args: &CliArgs) -> Result<Config> {+ load_config_with_data_dir_origin(args).map(|(cfg, _)| cfg)+}++fn load_config_with_data_dir_origin(args: &CliArgs) -> Result<(Config, startup_data_dir::Origin)> {let config_path = args.config.clone()- .or_else(|| std::env::var("XERJ_CONFIG").ok().map(PathBuf::from));-- let mut cfg = if let Some(path) = config_path {- info!("loading config from {}", path.display());- Config::load(&path).with_context(|| format!("load config from {}", path.display()))?+ .map(|path| (path, "--config"))+ .or_else(|| {+ std::env::var("XERJ_CONFIG")+ .ok()+ .map(|path| (PathBuf::from(path), "XERJ_CONFIG"))+ });+ let mut source = format!("default {}", Config::default().server.data_dir);+ let mut cfg = if let Some((path, selected_by)) = config_path {+ // Parse both configuration and key presence from the same read. A+ // selected file may omit data_dir, in which case its default wins.+ let raw = std::fs::read_to_string(&path)+ .with_context(|| format!("load config from {}", path.display()))?;+ let cfg = Config::from_toml_str(&raw)+ .with_context(|| format!("load config from {}", path.display()))?;+ let fields: toml::Value = toml::from_str(&raw)?;+ let file_source = format!("config file ({selected_by}) {:?}", path);+ if fields+ .get("server")+ .and_then(|server| server.get("data_dir"))+ .is_some()+ {+ source = file_source;+ } else {+ source.push_str(&format!("; {file_source} omits server.data_dir"));+ }+ cfg} else {- info!("no config file — using defaults");Config::default()};-if let Some(dir) = &args.data_dir {cfg.server.data_dir = dir.clone();+ source = "--data-dir".into();}+ let origin = startup_data_dir::Origin {+ source,+ requested: cfg.server.data_dir.clone(),+ };// `rerank.endpoint` is where document text gets POSTed. `Config::validate`// checked the file's value; the `TYPESAFE_ENDPOINT` fallback is only@@ -1012,7 +1051,7 @@ fn load_config(args: &CliArgs) -> Result<Config> {cfg.compat.version = version;}- Ok(cfg)+ Ok((cfg, origin))}// ─────────────────────────────────────────────────────────────────────────────@@ -4196,7 +4235,7 @@ async fn async_main() -> Result<()> {// 2. Config — loaded before tracing so the [logging] format (text/json)// governs the very first startup line (RC4-W4 item 6). A config-load// failure still surfaces via the returned Result → stderr.- let mut cfg = load_config(&args)?;+ let (mut cfg, data_dir_origin) = load_config_with_data_dir_origin(&args)?;// 3. Tracinginit_tracing(&cfg.logging);@@ -4338,9 +4377,14 @@ async fn async_main() -> Result<()> {}}- // 4. Data directory- std::fs::create_dir_all(&cfg.server.data_dir)- .with_context(|| format!("create data dir {}", cfg.server.data_dir))?;+ // 4. Data directory — report after resolution/creation, before admin/TLS state.+ let data_dir_report =+ startup_data_dir::prepare(Path::new(&cfg.server.data_dir), data_dir_origin)?;+ info!(data_dir = %data_dir_report.path_text(), data_dir_source = %data_dir_report.source,+ data_dir_state = data_dir_report.status(), "server data directory");+ if data_dir_report.created {+ warn!("{}", startup_data_dir::NEW_DIRECTORY_HINT);+ }open_crash_log(Path::new(&cfg.server.data_dir));// 5. Admin key (first-run)@@ -4869,7 +4913,7 @@ async fn async_main() -> Result<()> {// process holds.let startup_ms = startup_start.elapsed().as_millis();info!("startup complete in {}ms", startup_ms);- print_banner(&cfg, &bound, startup_ms);+ print_banner(&cfg, &bound, startup_ms, &data_dir_report);// 12. Background flush timerlet flusher = storage_available.then(|| {diff --git a/engine/crates/xerj-server/src/startup_data_dir.rs b/engine/crates/xerj-server/src/startup_data_dir.rsnew file mode 100644index 000000000..e3037816f--- /dev/null+++ b/engine/crates/xerj-server/src/startup_data_dir.rs@@ -0,0 +1,128 @@+//! Startup diagnostics only; neither discovers nor chooses a different data directory.+use anyhow::{Context, Result};+use std::path::{Path, PathBuf};++pub(crate) struct Origin {+ pub source: String,+ pub requested: String,+}++pub(crate) struct Report {+ pub path: PathBuf,+ pub source: String,+ pub created: bool,+}++impl Report {+ pub fn path_text(&self) -> String {+ self.path.display().to_string().escape_debug().to_string()+ }++ pub fn status(&self) -> &'static str {+ if self.created {+ "created this launch"+ } else {+ "existing directory (may be empty)"+ }+ }+}++pub(crate) const NEW_DIRECTORY_HINT: &str = "New data directory: if you expected existing indices or an owner account, restart with your previous --data-dir or --config. This node does not search for or migrate another directory.";++pub(crate) fn prepare(path: &Path, origin: Origin) -> Result<Report> {+ let selected = path;+ // create_dir_all("") previously accepted the current directory.+ let path = if path.as_os_str().is_empty() {+ Path::new(".")+ } else {+ path+ };+ // create_dir_all cannot say who created the leaf. A single create_dir+ // distinguishes our creation from an existing/concurrently supplied dir.+ // See std::fs::create_dir; parent creation preserves the prior nested-path workflow.+ if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {+ std::fs::create_dir_all(parent)+ .with_context(|| format!("create data dir parent {}", parent.display()))?;+ }+ let created = match std::fs::create_dir(path) {+ Ok(()) => true,+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && path.is_dir() => false,+ Err(e) => return Err(e).with_context(|| format!("create data dir {}", path.display())),+ };+ // Resolving a display path must not become a new startup dependency.+ let resolved = std::fs::canonicalize(path)+ .or_else(|_| std::path::absolute(path))+ .unwrap_or_else(|_| path.to_path_buf());+ let mut source = origin.source;+ if selected != Path::new(&origin.requested) {+ source.push_str("; auto-port selected an available sibling directory");+ }+ Ok(Report {+ path: resolved,+ source,+ created,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn origin(path: &Path) -> Origin {+ Origin {+ source: "--data-dir".into(),+ requested: path.display().to_string(),+ }+ }++ #[test]+ fn creates_nested_directory_then_preserves_existing_contents() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("nested/data");+ assert!(prepare(&path, origin(&path)).unwrap().created);+ let sentinel = path.join("operator-sentinel");+ std::fs::write(&sentinel, "keep").unwrap();+ let report = prepare(&path, origin(&path)).unwrap();+ assert!(!report.created);+ assert!(report.path.is_absolute());+ assert_eq!(std::fs::read_to_string(sentinel).unwrap(), "keep");+ }++ #[test]+ fn refuses_file_without_replacing_it_and_recovers_at_a_new_path() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("data");+ std::fs::write(&path, "keep").unwrap();+ assert!(prepare(&path, origin(&path)).is_err());+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "keep");+ let recovery = temp.path().join("new-data");+ assert!(prepare(&recovery, origin(&recovery)).unwrap().created);+ }++ #[test]+ fn relocation_is_explicit_and_control_characters_are_escaped() {+ let temp = tempfile::tempdir().unwrap();+ let path = temp.path().join("selected");+ let report = prepare(&path, origin(&temp.path().join("requested"))).unwrap();+ assert!(report.source.contains("auto-port"));+ let display = Report {+ path: PathBuf::from("line\nnext"),+ source: String::new(),+ created: false,+ };+ assert!(!display.path_text().contains('\n'));+ }++ #[cfg(unix)]+ #[test]+ fn existing_symlink_directory_is_reused_and_resolved_for_display() {+ let temp = tempfile::tempdir().unwrap();+ let target = temp.path().join("target");+ std::fs::create_dir(&target).unwrap();+ let link = temp.path().join("link");+ std::os::unix::fs::symlink(&target, &link).unwrap();+ let report = prepare(&link, origin(&link)).unwrap();+ assert!(!report.created);+ assert_eq!(report.path, std::fs::canonicalize(target).unwrap());+ }+}diff --git a/engine/crates/xerj-server/tests/data_directory_startup.rs b/engine/crates/xerj-server/tests/data_directory_startup.rsnew file mode 100644index 000000000..b481d9c6c--- /dev/null+++ b/engine/crates/xerj-server/tests/data_directory_startup.rs@@ -0,0 +1,133 @@+//! Observe the real startup banner without touching any existing node or data.+use std::fs::File;+use std::process::{Child, Command, Stdio};+use std::time::{Duration, Instant};++struct Node(Child);+impl Drop for Node {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+}++fn startup(work: &std::path::Path, extra: &[&str], env_config: Option<&str>) -> String {+ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"));+ child+ .current_dir(work)+ .env_clear()+ .env("XERJ_DISABLE_FEEDBACK", "true")+ .env("XERJ_NUM_CPUS", "2")+ .args(["--insecure"])+ .args(extra)+ .stdout(Stdio::from(File::create(work.join("stdout")).unwrap()))+ .stderr(Stdio::from(File::create(work.join("stderr")).unwrap()));+ if let Some(path) = env_config {+ child.env("XERJ_CONFIG", path);+ }+ let mut node = Node(child.spawn().unwrap());+ let deadline = Instant::now() + Duration::from_secs(60);+ loop {+ let output = std::fs::read_to_string(work.join("stdout")).unwrap();+ if output.contains(" Started in ") {+ return output;+ }+ if let Some(status) = node.0.try_wait().unwrap() {+ panic!(+ "node exited {status}: {}",+ std::fs::read_to_string(work.join("stderr")).unwrap()+ );+ }+ assert!(Instant::now() < deadline, "startup timed out");+ std::thread::sleep(Duration::from_millis(20));+ }+}++fn config(work: &std::path::Path, data: Option<&str>) {+ let first = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let second = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let mut text = format!(+ "[server]\nes_compat_port={}\nrest_port={}\ngrpc_port=0\n",+ first.local_addr().unwrap().port(),+ second.local_addr().unwrap().port()+ );+ if let Some(data) = data {+ text.push_str(&format!(+ "data_dir={}\n",+ serde_json::to_string(data).unwrap()+ ));+ }+ std::fs::write(work.join("node.toml"), text).unwrap();+}++#[test]+fn startup_names_the_actual_data_directory_source_and_creation_state() {+ for (kind, setting, flags, env, expected_dir, source) in [+ (+ "config",+ Some("persistent"),+ vec!["-c", "node.toml"],+ Some("missing.toml"),+ "persistent",+ "config file (--config)",+ ),+ (+ "env",+ Some("persistent"),+ vec![],+ Some("node.toml"),+ "persistent",+ "config file (XERJ_CONFIG)",+ ),+ (+ "flag",+ Some("unused"),+ vec!["-c", "node.toml", "--data-dir", "selected"],+ None,+ "selected",+ "--data-dir",+ ),+ (+ "default",+ None,+ vec!["-c", "node.toml"],+ None,+ "data",+ "default ./data",+ ),+ ] {+ let temp = tempfile::tempdir().unwrap();+ let work = temp.path();+ config(work, setting);+ let output = startup(work, &flags, env);+ assert!(output.contains(" Data source "), "{kind}: {output}");+ assert!(output.contains(source), "{kind}: {output}");+ assert!(output.contains("created this launch"), "{kind}: {output}");+ let actual = std::fs::canonicalize(work.join(expected_dir)).unwrap();+ assert!(+ output.contains(&actual.display().to_string().escape_debug().to_string()),+ "{kind}: {output}"+ );+ assert!(+ output.contains("previous --data-dir or --config"),+ "{kind}: {output}"+ );+ if kind == "flag" {+ assert!(!work.join("unused").exists());+ }+ std::fs::write(work.join(expected_dir).join("operator-sentinel"), "keep").unwrap();+ let repeated = startup(work, &flags, env);+ assert!(+ repeated.contains("existing directory"),+ "{kind}: {repeated}"+ );+ assert!(+ !repeated.contains("created this launch"),+ "{kind}: {repeated}"+ );+ assert_eq!(+ std::fs::read_to_string(work.join(expected_dir).join("operator-sentinel")).unwrap(),+ "keep"+ );+ }+}diff --git a/tools/startup-diagnostics/README.md b/tools/startup-diagnostics/README.mdnew file mode 100644index 000000000..926d51b4e--- /dev/null+++ b/tools/startup-diagnostics/README.md@@ -0,0 +1,62 @@+# Data directory startup diagnostics++The server prints `Data dir` (canonical absolute path when available),+`Data source` and `Data status` in the existing startup banner. Structured+tracing also records `data_dir`, `data_dir_source` and `data_dir_state` before+admin-key/TLS state is created. Logging filters still apply to tracing; the+banner remains the existing human-readable startup output.++Precedence is unchanged: `--data-dir` wins over the selected TOML file;+`--config` wins over `XERJ_CONFIG`; no explicit `server.data_dir` uses `./data`+relative to the process working directory. A selected config that omits the+key is identified as a default, not incorrectly attributed to that file.+There is no new `XERJ_DATA_DIR` variable. Relative config-file values remain+relative to the process working directory, not the config file's directory.++`created this launch` means this process successfully created the final directory+with one `create_dir` call. A directory supplied by another process before that+call is `existing directory (may be empty)`. Missing parents are still created.+Existing symlink directories are reused; display resolves their target when+possible. Display-resolution failure falls back to an absolute/requested path+and does not prevent an otherwise valid startup. Control characters are escaped.+If opt-in auto-port selection relocates a locked data directory to an available+sibling, the final path and that relocation are identified together.++A new directory is not evidence that old data was lost. If existing indices or+the owner account were expected, stop this node and use the previous explicit+`--data-dir` or `--config`. No directory is searched, selected, moved or deleted+by these diagnostics. Existing files remain authoritative. There is no record+of previously used directories or account/index inspection to guess a match.+Console empty-state changes and automatic comparison of other known data+directories remain outside this scoped part of #2409.++## Reproduction and verification++The real CLI regression starts private nodes with temporary directories and+tests config/`XERJ_CONFIG`/flag/default selection, omitted config keys, first+creation and an existing-directory restart. An operator sentinel must survive.+It failed on the unchanged base because `Data source` was absent.++```sh+cd engine+cargo +1.97.1 test --locked --offline -p xerj-server \+ --bin xerj --test data_directory_startup -- --test-threads=1+cargo +1.97.1 clippy --locked --offline --no-deps -p xerj-server \+ --bin xerj --test data_directory_startup -- -D warnings+cargo +1.97.1 build --locked --offline --release -j 32 -p xerj-server -p es-yaml-runner+```++The implementation preserves the prior loader's validation through+`Config::from_toml_str` and derives key presence from the same file bytes.+The added direct TOML dependency already exists in the workspace/lockfile; no+dependency version changes. Existing CLI in-process indexing still uses the+same config loader and never opts into directory relocation.++Reference before implementation: existing `Config::load` at baseline+`9cf3f29c`, `engine/crates/xerj-common/src/config.rs:138`, and startup's+`engine/crates/xerj-server/src/main.rs:4341`. Rust's+[`create_dir`](https://doc.rust-lang.org/std/fs/fn.create_dir.html) documents+leaf creation/failure, while [`path::absolute`](https://doc.rust-lang.org/std/path/fn.absolute.html)+distinguishes absolute display paths from symlink resolution. No external+implementation was copied. This is startup observability, not an engine+storage-format or data-recovery change.diff --git a/tools/startup-diagnostics/VERIFICATION.md b/tools/startup-diagnostics/VERIFICATION.mdnew file mode 100644index 000000000..10d731d1e--- /dev/null+++ b/tools/startup-diagnostics/VERIFICATION.md@@ -0,0 +1,94 @@+# Local startup-diagnostics verification — 2026-10-26++OpenAI Codex, operated by Jarvis636431. macOS arm64, Rust 1.97.1.+Implementation `f1d97951`, independently based on upstream `9cf3f29c`.+No dependency on the catalog-namespace, Codex-import (#2413) or batch-benchmark+(#2384) branches. `git merge-tree --write-tree` composed the two diagnostic+branches without conflicts; their execution is separately verified below.++## Observed checks++From `engine/`:++```sh+cargo +1.97.1 fmt --all+cargo +1.97.1 fmt --all -- --check+TMPDIR=/private/tmp cargo +1.97.1 test --locked --offline -p xerj-server \+ --bin xerj --test data_directory_startup -- --test-threads=1+cargo +1.97.1 clippy --locked --offline --no-deps -p xerj-server \+ --bin xerj --test data_directory_startup -- -D warnings+cargo +1.97.1 build --locked --offline --release -j 32 -p xerj-server -p es-yaml-runner+```++- New startup integration test on the unmodified base: **0 passed, 1 failed**+ because the real banner lacked `Data source`.+- Candidate: **123 main tests passed** (including 4 new helper tests),+ **1 startup integration test passed**. The latter checks four source cases+ and their existing-directory restarts: selected config, `XERJ_CONFIG`, flag+ override and a selected config that omits the key/defaults to `./data`.+- Scoped release build, formatting, whitespace and scoped strict Clippy passed.+ No tests skipped/filtered in these server targets. This is not a full run of+ every server integration target or every workspace crate.+- Workflow timeout guard passed (40 jobs / 12 workflows). Python compilation+ passed. New Markdown is covered by the explicit `!tools/**/*.md` rule.++A private standalone copy of `startup_data_dir.rs` passed all 4 helper tests.+Changing its successful `create_dir` branch to report `created=false` made+exactly the nested-directory and file-refusal/recovery regressions fail+(2 failed, 2 passed). Production source was not mutated. This independently+checks that new-directory reporting is exercised, beyond matching banner text.++From the repository root:++```sh+python3 tools/startup-diagnostics/smoke.py --binary engine/target/release/xerj+```++Release candidate `xerj v1.0.0-rc.99`, SHA-256+`861f50c47d2ce7e0af86c1ce9b3588d16398e0739580c8ae6142c46282ebd9cd`,+was copied to a private executable snapshot used by lifecycle and conformance+runs. No source changed between the release build and those runs.++The private-node smoke passed: first launch reported `created this launch`,+stored one document, then exited gracefully with status 0. Restart reported+`existing directory`, returned the same document/body and exited 0. Both+structured JSON diagnostics and the banner identified the selected config and+resolved path. The test fixes `XERJ_LOG=info`; an initial harness invocation+inherited host `RUST_LOG=warn` and correctly could not observe INFO events.+No logging-policy or production-source change was needed for that correction.++On a separate fresh private node using the same snapshot:++```sh+engine/target/release/es-yaml-runner --url "$PRIVATE_NODE_URL" \+ --dir engine/tests/es-compat-yaml/yaml+```++**230 files: 1,447 passed, 0 failed, 10 skipped, 1,457 total; exit 0.**+The unchanged policy reported 75 catch-lenient cases. Node shutdown exited 0;+no YAML, runner or policy was edited. These are local source-build receipts,+not a verification of published release assets or hosted merge-ref CI.++## Audit and boundaries++Audited against `docs/CONTRIBUTION_REVIEW.md`: effective diff is limited to+server config provenance/startup presentation, directory creation reporting,+one existing workspace dependency, tests and documentation. The two TOML+parses use the same file bytes; typed validation still precedes overrides and+startup mutation. Atomic leaf creation determines status; another writer's+existing directory is not claimed as this launch's creation. Existing-file+refusal preserves bytes, and recovery at a new path succeeds. Symlink reuse,+nested paths and control-character escaping are covered. Display fallback+does not become a new availability requirement.++No index mapping, journal, storage format, auth policy or data-directory+selection/auto-port rule changes. No previous-directory lookup, migration or+deletion occurs. Recovery is the existing explicit `--data-dir` / `--config`+selection; the program does not guess where earlier data lives. Legacy data+migration, distributed writes, optional accelerators and model execution are+not applicable. No performance claim is made.++Not tested: Linux/Windows execution, real owner-account state, production+directories, other-known-directory comparisons or console empty-state changes.+These last two suggestions remain outside this scoped portion of #2409.+Website generation gates were not run because no landing files changed.diff --git a/tools/startup-diagnostics/smoke.py b/tools/startup-diagnostics/smoke.pynew file mode 100644index 000000000..4a9965910--- /dev/null+++ b/tools/startup-diagnostics/smoke.py@@ -0,0 +1,87 @@+#!/usr/bin/env python3+"""Private-node creation, durable write, restart and data-directory diagnostics."""+import argparse+import json+import os+from pathlib import Path+import socket+import subprocess+import tempfile+import time+import urllib.request+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--binary', type=Path, required=True)+ binary = parser.parse_args().binary.resolve(strict=True)+ env = {k: v for k, v in os.environ.items() if not k.startswith('XERJ_')+ and k.lower() not in ('all_proxy', 'http_proxy', 'https_proxy', 'no_proxy')}+ env.update(XERJ_DISABLE_FEEDBACK='true', XERJ_NUM_CPUS='2', XERJ_LOG='info')+ opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))+ with tempfile.TemporaryDirectory(prefix='xerj-data-dir-smoke-') as temp:+ work = Path(temp)+ sockets = [socket.socket(), socket.socket()]+ for sock in sockets:+ sock.bind(('127.0.0.1', 0))+ port, rest = [sock.getsockname()[1] for sock in sockets]+ for sock in sockets:+ sock.close()+ url = f'http://127.0.0.1:{port}'+ cfg = work / 'node.toml'+ cfg.write_text(f'[server]\nes_compat_port={port}\nrest_port={rest}\ngrpc_port=0\ndata_dir="persistent"\n'+ '[logging]\nformat="json"\n')++ def request(path, method='GET', body=None):+ data = None if body is None else json.dumps(body).encode()+ with opener.open(urllib.request.Request(url + path, data=data, method=method,+ headers={'Content-Type': 'application/json'}), timeout=10) as response:+ return json.load(response)++ for generation in range(2):+ log_path = work / f'node-{generation}.log'+ with log_path.open('w') as log:+ node = subprocess.Popen([str(binary), '--insecure', '-c', str(cfg)], cwd=work,+ env=env, stdout=log, stderr=log)+ try:+ deadline = time.monotonic() + 60+ while True:+ if node.poll() is not None:+ raise RuntimeError(log_path.read_text())+ try:+ request('/')+ break+ except OSError:+ if time.monotonic() >= deadline:+ raise RuntimeError('private node readiness timed out')+ time.sleep(.1)+ if generation == 0:+ request('/directory-smoke', 'PUT', {'mappings': {'properties': {'body': {'type': 'text'}}}})+ request('/directory-smoke/_doc/decision?refresh=true', 'PUT', {'body': 'retain this decision'})+ assert request('/directory-smoke/_count')['count'] == 1+ assert request('/directory-smoke/_doc/decision')['_source']['body'] == 'retain this decision'+ finally:+ if node.poll() is None:+ node.terminate()+ try:+ node.wait(timeout=20)+ except subprocess.TimeoutExpired:+ node.kill()+ node.wait(timeout=5)+ raise RuntimeError('graceful stop required SIGKILL')+ assert node.returncode == 0, node.returncode+ text = log_path.read_text()+ assert 'config file (--config)' in text+ assert str((work / 'persistent').resolve()) in text+ expected = 'created this launch' if generation == 0 else 'existing directory'+ assert expected in text+ structured = [json.loads(line) for line in text.splitlines() if line.startswith('{')]+ diagnostic = next(event['fields'] for event in structured if event.get('fields', {}).get('message') == 'server data directory')+ assert diagnostic['data_dir_state'].startswith(expected), diagnostic+ assert diagnostic['data_dir_source'].startswith('config file (--config)'), diagnostic+ print(f'PASS node {generation + 1}: {expected}; one durable document; JSON tracing; graceful exit 0', flush=True)+ return 0+++if __name__ == '__main__':+ raise SystemExit(main())