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): bind every listener before claiming to have started
xerj-orgdb61716887d9
diff --git a/engine/crates/xerj-server/Cargo.toml b/engine/crates/xerj-server/Cargo.tomlindex 3f8f0d786..32ba663a5 100644--- a/engine/crates/xerj-server/Cargo.toml+++ b/engine/crates/xerj-server/Cargo.toml@@ -52,6 +52,10 @@ rayon = { workspace = true }# gRPC server: the real XerjSearch service on :8081 (proto: ../../proto/xerj.proto).tonic.workspace = true+# `TcpListenerStream`, so the gRPC listener can be bound up front alongside+# the REST ones and a taken port fails startup rather than being logged+# under a banner that already claimed it (issue #465).+tokio-stream = { version = "0.1", features = ["net"] }prost.workspace = true# Use jemalloc as the global allocator. The default glibc malloc causes@@ -98,4 +102,3 @@ protox = { workspace = true }reqwest = { workspace = true }tempfile = { workspace = true }flate2 = "1"-tokio-stream = "0.1"diff --git a/engine/crates/xerj-server/src/grpc.rs b/engine/crates/xerj-server/src/grpc.rsindex 703b15736..5f7f08b3d 100644--- a/engine/crates/xerj-server/src/grpc.rs+++ b/engine/crates/xerj-server/src/grpc.rs@@ -19,6 +19,9 @@//! tonic's own `tls` feature (a second crypto backend beside axum-server's//! ring) is the open follow-up; documented in `docs/SECURITY_MODEL.md`.+// Only the test-only `serve_grpc` takes an address now; the server hands in+// a listener it already bound (issue #465).+#[cfg(test)]use std::net::SocketAddr;use anyhow::Context;@@ -400,10 +403,41 @@ impl tonic::service::Interceptor for GrpcAuth {/// acceptable for `addr` is decided before this is called (`main.rs` step 5b);/// this function does not re-check, so do not call it on a new code path/// without carrying that decision with you.+/// Bind `addr` and serve. Kept for tests, which want the convenience of `:0`+/// and do not care about startup ordering; the server binds up front via+/// [`serve_grpc_on`] instead (issue #465).+#[cfg(test)]pub async fn serve_grpc<F>(addr: SocketAddr, state: AppState, shutdown: F) -> anyhow::Result<()>whereF: std::future::Future<Output = ()> + Send + 'static,{+ let listener =+ std::net::TcpListener::bind(addr).with_context(|| format!("gRPC: bind {addr}"))?;+ listener+ .set_nonblocking(true)+ .with_context(|| format!("gRPC: set the listener on {addr} non-blocking"))?;+ serve_grpc_on(listener, state, shutdown).await+}++/// Serve gRPC on a listener the caller already bound.+///+/// The server binds every listener before it prints its banner, so that a+/// taken port fails startup instead of being logged under a banner that+/// already claimed the port (issue #465). That requires handing the bound+/// listener in rather than letting tonic bind it here.+pub async fn serve_grpc_on<F>(+ listener: std::net::TcpListener,+ state: AppState,+ shutdown: F,+) -> anyhow::Result<()>+where+ F: std::future::Future<Output = ()> + Send + 'static,+{+ let addr = listener+ .local_addr()+ .context("gRPC: read the bound address")?;+ let listener =+ tokio::net::TcpListener::from_std(listener).context("gRPC: adopt the bound listener")?;let interceptor = GrpcAuth {state: state.clone(),};@@ -411,7 +445,10 @@ whereinfo!("gRPC XerjSearch listening on {addr}");tonic::transport::Server::builder().add_service(svc)- .serve_with_shutdown(addr, shutdown)+ .serve_with_incoming_shutdown(+ tokio_stream::wrappers::TcpListenerStream::new(listener),+ shutdown,+ ).await.context("gRPC transport error")?;Ok(())diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rsindex 0144fa54b..aa83b3a44 100644--- a/engine/crates/xerj-server/src/main.rs+++ b/engine/crates/xerj-server/src/main.rs@@ -356,7 +356,18 @@ fn url_host(bind: &str) -> String {}}-fn print_banner(cfg: &Config, startup_ms: u128) {+/// The three addresses the node actually holds, as reported by the kernel.+///+/// The banner is printed from *these*, never from `cfg.server.*_port`, because+/// a port in the config is a request and a port in here is a fact. See+/// `bind_listeners` for why that distinction is load-bearing (issue #465).+struct BoundAddrs {+ rest: SocketAddr,+ es: SocketAddr,+ grpc: SocketAddr,+}++fn print_banner(cfg: &Config, bound: &BoundAddrs, startup_ms: u128) {let tls = if cfg.tls.enabled { "TLS " } else { "plain" };println!();println!(" ██╗ ██╗███████╗██████╗ ██╗");@@ -378,24 +389,22 @@ fn print_banner(cfg: &Config, startup_ms: u128) {// Bracketed for IPv6 so `host:port` stays unambiguous.let bind_hostport = url_host(&cfg.server.bind_address);let bind = bind_hostport.as_str();- println!(" Native REST {}:{} [{}]", bind, cfg.server.rest_port, tls);- println!(- " ES-compat {}:{} [{}]",- bind, cfg.server.es_compat_port, tls- );+ println!(" Native REST {}:{} [{}]", bind, bound.rest.port(), tls);+ println!(" ES-compat {}:{} [{}]", bind, bound.es.port(), tls);// Never interpolated with `tls`: the gRPC listener is h2c whatever// `[tls]` says (issue #229), and a line that read "TLS" here would be the// exact false promise the startup check exists to prevent.println!(" gRPC {}:{} [h2c — plaintext, no TLS]",- bind, cfg.server.grpc_port+ bind,+ bound.grpc.port());println!(" Data dir {}", cfg.server.data_dir);println!(" Started in {}ms", startup_ms);println!();println!(" Xerj Console UI http://localhost:{}/_xerj-console/ ({} files bundled)",- cfg.server.es_compat_port,+ bound.es.port(),xerj_console_api::spa::asset_count(),);println!();@@ -434,14 +443,14 @@ fn print_banner(cfg: &Config, startup_ms: u128) {if !cfg.bind_address_is_loopback() {println!(" │ ⚠ gRPC: :{} is NOT covered by TLS — cleartext h2c on a non-loopback",- cfg.server.grpc_port+ bound.grpc.port());println!(" │ bind, allowed by tls.allow_insecure_grpc_h2c (issue #229).");println!(" │ Terminate TLS for it at your proxy/mesh, or bind loopback.");} else {println!(" │ ⚠ gRPC: :{} is NOT covered by TLS — cleartext h2c, loopback-only",- cfg.server.grpc_port+ bound.grpc.port());}}@@ -1005,12 +1014,50 @@ fn spawn_periodic_flusher(/// bought an unlimited quota (#76 S5-4). Forwarding headers are believed only/// when the peer is listed in `server.trusted_proxies`; without connect-info on/// *both* listeners the limiter would fall back to a single shared bucket.+/// Take an address and bind it, then serve. Kept for tests, which want the+/// convenience of `:0` and do not care about startup ordering.+///+/// The server itself must NOT use this: it binds every listener up front, in+/// `bind_listeners`, so that a taken port is a startup failure rather than a+/// line in the log under a banner that already claimed success (issue #465).+#[cfg(test)]async fn serve(router: Router,addr: SocketAddr,name: &'static str,tls: Option<RustlsConfig>,) -> Result<()> {+ serve_on(router, bind_listener(addr, name)?, name, tls).await+}++/// Bind one listener, or fail.+///+/// Binding is synchronous and eager on purpose. The three listeners are bound+/// before the banner prints and before anything reports readiness, so the node+/// can never advertise a port another process owns — the failure mode that+/// sent one user's contracts, invoices and bank export into a stranger's data+/// directory under `ok=true exit=0` (issue #465).+fn bind_listener(addr: SocketAddr, name: &str) -> Result<std::net::TcpListener> {+ let listener =+ std::net::TcpListener::bind(addr).with_context(|| format!("{name}: bind {addr}"))?;+ // Both axum's accept loop and axum-server's rustls acceptor drive this+ // listener from the reactor; a blocking fd would stall the runtime thread+ // on the first accept.+ listener+ .set_nonblocking(true)+ .with_context(|| format!("{name}: set the listener on {addr} non-blocking"))?;+ Ok(listener)+}++async fn serve_on(+ router: Router,+ listener: std::net::TcpListener,+ name: &'static str,+ tls: Option<RustlsConfig>,+) -> Result<()> {+ let addr = listener+ .local_addr()+ .with_context(|| format!("{name}: read the bound address"))?;// ── TLS path: in-process rustls termination via axum-server ──────────//// When TLS is enabled the plain `axum::serve` (hyper) accept loop can't@@ -1033,7 +1080,7 @@ async fn serve(info!("{name} listening on {addr} (TLS)");- axum_server::bind_rustls(addr, tls)+ axum_server::from_tcp_rustls(listener, tls).handle(handle).serve(router.into_make_service_with_connect_info::<SocketAddr>()).await@@ -1044,9 +1091,8 @@ async fn serve(}// ── Plain path: unchanged cleartext HTTP ─────────────────────────────- let listener = TcpListener::bind(addr)- .await- .with_context(|| format!("{name}: bind {addr}"))?;+ let listener = TcpListener::from_std(listener)+ .with_context(|| format!("{name}: adopt the bound listener on {addr}"))?;info!("{name} listening on {addr}");@@ -2271,12 +2317,7 @@ async fn async_main() -> Result<()> {es_router = es_router.merge(xerj_console_router);}- // 10. Banner (includes total startup time)- let startup_ms = startup_start.elapsed().as_millis();- info!("startup complete in {}ms", startup_ms);- print_banner(&cfg, startup_ms);-- // 11. Bind addresses. Composed from the parsed IP, never by formatting+ // 10. Bind addresses. Composed from the parsed IP, never by formatting// `"{bind}:{port}"` — that string is unparseable for every IPv6// literal (`"::1:9200"`), which made `bind_address = "::1"` a node// that could not start at all.@@ -2296,6 +2337,46 @@ async fn async_main() -> Result<()> {.socket_addr(cfg.server.grpc_port).with_context(|| bad_bind_address(&cfg))?;+ // 10a. Bind all three listeners NOW — before the banner, before anything+ // reports readiness, and fatally.+ //+ // This used to happen inside the three `tokio::spawn`s below, where a+ // bind error was `error!`-logged and explicitly non-fatal. Because+ // `tokio::join!` returns only when all three tasks end, a node that+ // lost just one port stayed up — and the banner, printed earlier,+ // had already announced that port and this data directory as its own.+ //+ // That is not a cosmetic lie. The node that *does* own :9200 answers+ // `GET /_cluster/health` with `green`, which is the readiness probe+ // the docs prescribe, so `xerj autoindex` proceeds and streams the+ // user's corpus into a datastore they have never heard of. It was+ // reported by three independent agents; one of them put 905 files —+ // contracts, invoices, a bank export — into another node's data+ // directory and got `ok=true exit=0` for it (issue #465).+ //+ // Binding first collapses the whole class: the kernel decides who+ // owns the port before we make any claim about owning it.+ let rest_listener = bind_listener(rest_addr, "native REST")?;+ let es_listener = bind_listener(es_addr, "ES-compat")?;+ let grpc_listener = bind_listener(grpc_addr, "gRPC")?;++ // 11. Banner (includes total startup time). Printed from the addresses the+ // kernel gave us, so every port on it is one this process holds.+ let bound = BoundAddrs {+ rest: rest_listener+ .local_addr()+ .context("native REST: read the bound address")?,+ es: es_listener+ .local_addr()+ .context("ES-compat: read the bound address")?,+ grpc: grpc_listener+ .local_addr()+ .context("gRPC: read the bound address")?,+ };+ let startup_ms = startup_start.elapsed().as_millis();+ info!("startup complete in {}ms", startup_ms);+ print_banner(&cfg, &bound, startup_ms);+// 12. Background flush timerlet flusher = storage_available.then(|| {spawn_periodic_flusher(@@ -2324,24 +2405,26 @@ async fn async_main() -> Result<()> {// 13. Start servers concurrentlylet rest_tls = tls_config.clone();let rest = tokio::spawn(async move {- if let Err(e) = serve(native_router, rest_addr, "native REST", rest_tls).await {+ if let Err(e) = serve_on(native_router, rest_listener, "native REST", rest_tls).await {error!("native REST: {e:#}");}});let es_tls = tls_config.clone();let es = tokio::spawn(async move {- if let Err(e) = serve(es_router, es_addr, "ES-compat", es_tls).await {+ if let Err(e) = serve_on(es_router, es_listener, "ES-compat", es_tls).await {error!("ES-compat: {e:#}");}});// Real tonic XerjSearch service. Exits on the same SIGTERM/SIGINT as the// REST listeners so `tokio::join!` below returns and the shutdown flush- // hook runs. A bind/transport failure is logged, not fatal.+ // hook runs. The bind already succeeded above — a *later* transport+ // failure is logged rather than fatal, because by then the process has+ // made no false claim: it did hold the port.let grpc_state = state.clone();let grpc = tokio::spawn(async move {- if let Err(e) = grpc::serve_grpc(grpc_addr, grpc_state, shutdown_signal()).await {+ if let Err(e) = grpc::serve_grpc_on(grpc_listener, grpc_state, shutdown_signal()).await {error!("gRPC server: {e:#}");}});diff --git a/engine/crates/xerj-server/tests/taken_port_fails_startup.rs b/engine/crates/xerj-server/tests/taken_port_fails_startup.rsnew file mode 100644index 000000000..f4eebf3e0--- /dev/null+++ b/engine/crates/xerj-server/tests/taken_port_fails_startup.rs@@ -0,0 +1,288 @@+//! Issue #465: a node that could not bind a listener must not claim it did.+//!+//! Before the fix the three listeners were bound inside `tokio::spawn`s that+//! ran *after* the banner, and a bind error there was `error!`-logged and+//! explicitly non-fatal. A node whose ES-compat port was already held by+//! another process therefore printed the full success banner — that port, this+//! data directory, `Started in {ms}` — and then stayed up serving nothing on+//! it, because `tokio::join!` returns only once all three tasks end.+//!+//! The consequence is not cosmetic. The process that *does* own the port+//! answers `GET /_cluster/health` with `green`, which is the readiness probe+//! the docs prescribe, so `xerj autoindex` proceeds and streams the user's+//! corpus into a datastore they have never heard of and cannot name. Three+//! agents hit this independently in a field study; one wrote 905 files —+//! contracts, invoices, a bank export — into a stranger's data directory and+//! got `ok=true exit=0` for it.+//!+//! These are process-level tests because the defect is invisible from inside+//! the config crate: every value was valid, the machine simply said no. The+//! first two hold a port for real and assert the binary dies; the third holds+//! nothing and asserts it still lives, so a binary that refused to start for+//! any unrelated reason cannot pass this file.++use std::io::Read;+use std::net::TcpListener;+use std::process::{Command, Stdio};+use std::time::{Duration, Instant};++/// The foreign process that already owns the ES-compat port, plus two more+/// free ports for the listeners the node must still get.+///+/// The squatter is bound on `:0` and **never released** — the port number is+/// read off a listener this test still holds. Deriving it the other way round+/// (pick a free port, drop it, re-bind it) is what the first version did, and+/// it lost the race constantly: the two `#[test]`s in this file run on+/// separate threads, both drew from the same just-released ephemeral pool, and+/// whichever re-bound second got `AddrInUse` from the *other test* rather than+/// from the node under test.+///+/// `rest` and `grpc` still go through hold-then-release, which is unavoidable+/// — the child has to be the one to bind them. `Config::validate` requires all+/// three to differ, which holding them simultaneously guarantees.+fn squatter_and_two_free_ports() -> (TcpListener, u16, u16) {+ let squatter = TcpListener::bind("127.0.0.1:0").expect("hold a port for the foreign process");+ let held: Vec<TcpListener> = (0..2)+ .map(|_| TcpListener::bind("127.0.0.1:0").unwrap())+ .collect();+ let p: Vec<u16> = held+ .iter()+ .map(|l| l.local_addr().unwrap().port())+ .collect();+ (squatter, p[0], p[1])+}++/// Three distinct free ports for the control, which needs every one of them to+/// still be free when the child starts.+fn three_free_ports() -> (u16, u16, u16) {+ let held: Vec<TcpListener> = (0..3)+ .map(|_| TcpListener::bind("127.0.0.1:0").unwrap())+ .collect();+ let p: Vec<u16> = held+ .iter()+ .map(|l| l.local_addr().unwrap().port())+ .collect();+ (p[0], p[1], p[2])+}++/// TOML-safe rendering of a temp path.+fn toml_path(p: &std::path::Path) -> String {+ p.to_string_lossy().replace('\\', "/")+}++fn config_for(dir: &std::path::Path, rest: u16, grpc: u16, es: u16) -> String {+ format!(+ r#"+[server]+bind_address = "127.0.0.1"+rest_port = {rest}+grpc_port = {grpc}+es_compat_port = {es}+data_dir = "{data}"++[limits]+disk_flood_stage_percent = 0+"#,+ data = toml_path(&dir.join("data")),+ )+}++struct Outcome {+ exited: bool,+ success: bool,+ stdout: String,+ stderr: String,+}++/// Spawn the real binary and watch it for `wait` seconds.+///+/// Returns as soon as it exits. A binary that is still running when the window+/// closes is reported as `exited: false` with whatever it has written so far —+/// the pre-fix behaviour every test here is written against.+fn run(config_body: &str, dir: &std::path::Path, wait: Duration) -> Outcome {+ let config_path = dir.join("xerj.toml");+ std::fs::write(&config_path, config_body).unwrap();++ let mut child = Command::new(env!("CARGO_BIN_EXE_xerj"))+ .arg("--config")+ .arg(&config_path)+ .arg("--insecure")+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .expect("spawn xerj");++ let deadline = Instant::now() + wait;+ let mut exited = false;+ let mut success = false;+ loop {+ match child.try_wait().expect("poll child") {+ Some(status) => {+ exited = true;+ success = status.success();+ break;+ }+ None if Instant::now() > deadline => {+ // Read the pipes BEFORE killing: the child holds the write+ // ends, and on a kill we still want everything it printed.+ break;+ }+ None => std::thread::sleep(Duration::from_millis(100)),+ }+ }++ let mut stdout = String::new();+ let mut stderr = String::new();+ if exited {+ child+ .stdout+ .take()+ .expect("stdout piped")+ .read_to_string(&mut stdout)+ .expect("read child stdout");+ child+ .stderr+ .take()+ .expect("stderr piped")+ .read_to_string(&mut stderr)+ .expect("read child stderr");+ } else {+ child.kill().ok();+ child.wait().ok();+ // The pipes are drained after the kill so `read_to_string` sees EOF.+ child+ .stdout+ .take()+ .map(|mut s| s.read_to_string(&mut stdout));+ child+ .stderr+ .take()+ .map(|mut s| s.read_to_string(&mut stderr));+ }++ Outcome {+ exited,+ success,+ stdout,+ stderr,+ }+}++/// The whole defect in one assertion: someone else owns the ES-compat port, so+/// this process must not run.+#[test]+fn a_taken_es_compat_port_ends_the_process() {+ let dir = tempfile::tempdir().unwrap();+ // A foreign process — in the field, another XERJ node, a Docker publish,+ // or a real Elasticsearch — already holds it, for the whole test.+ let (squatter, rest, grpc) = squatter_and_two_free_ports();+ let es = squatter.local_addr().unwrap().port();++ let out = run(+ &config_for(dir.path(), rest, grpc, es),+ dir.path(),+ Duration::from_secs(60),+ );++ assert!(+ out.exited,+ "xerj kept running without the ES-compat port it was configured for. \+ Whoever holds :{es} now answers the readiness probe the docs \+ prescribe, so `xerj autoindex` will write this user's corpus into \+ that node's data directory instead of theirs.\n--- stdout ---\n{}\n--- stderr ---\n{}",+ out.stdout, out.stderr+ );+ assert!(+ !out.success,+ "xerj exited 0 after failing to bind :{es}; a supervisor or a script \+ reading the exit code learns nothing.\n--- stderr ---\n{}",+ out.stderr+ );+ assert!(+ out.stderr.contains(&es.to_string()),+ "the failure must name the port that was taken, so the operator can \+ act on it without reading the log\n--- stderr ---\n{}",+ out.stderr+ );++ drop(squatter);+}++/// The banner is the lie the user acts on, so it gets its own assertion:+/// nothing that reads as success may reach stdout when a listener was lost.+#[test]+fn no_success_banner_is_printed_when_a_port_is_taken() {+ let dir = tempfile::tempdir().unwrap();+ let (squatter, rest, grpc) = squatter_and_two_free_ports();+ let es = squatter.local_addr().unwrap().port();++ let out = run(+ &config_for(dir.path(), rest, grpc, es),+ dir.path(),+ Duration::from_secs(60),+ );++ for claim in ["Started in", "Xerj Console UI", "Data dir"] {+ assert!(+ !out.stdout.contains(claim),+ "the banner printed {claim:?} for a node that never got :{es}. \+ That line is what a user checks before pointing their documents \+ at it.\n--- stdout ---\n{}",+ out.stdout+ );+ }+ assert!(+ !out.stdout.contains(&format!("ES-compat 127.0.0.1:{es}")),+ "the banner advertised an ES-compat port this process does not \+ own\n--- stdout ---\n{}",+ out.stdout+ );++ drop(squatter);+}++/// Control. With every port free the same invocation must start and stay up —+/// otherwise the two assertions above would pass against a binary that simply+/// never starts, which is not the fix.+///+/// Retried, unlike the other two: the three ports have to be released before+/// the child can bind them, so on a busy machine an unrelated process can take+/// one in between and the node would then be *correctly* refusing to start.+/// Three losses in a row is not that race any more.+#[test]+fn with_the_ports_free_it_starts_and_stays_up() {+ let dir = tempfile::tempdir().unwrap();+ let mut out = None;+ let mut es = 0;+ for _ in 0..3 {+ let (rest, grpc, port) = three_free_ports();+ es = port;+ let attempt = run(+ &config_for(dir.path(), rest, grpc, es),+ dir.path(),+ Duration::from_secs(20),+ );+ let lost_a_port = attempt.exited && attempt.stderr.contains("Address already in use");+ out = Some(attempt);+ if !lost_a_port {+ break;+ }+ }+ let out = out.expect("at least one attempt");++ assert!(+ !out.exited,+ "xerj exited on its own with all three ports free\n--- stdout ---\n{}\n--- stderr ---\n{}",+ out.stdout, out.stderr+ );+ assert!(+ out.stdout.contains("Started in"),+ "a node that bound everything must still print its banner\n--- stdout ---\n{}",+ out.stdout+ );+ assert!(+ out.stdout.contains(&format!("ES-compat 127.0.0.1:{es}")),+ "the banner must name the ES-compat port it actually holds\n--- stdout ---\n{}",+ out.stdout+ );+}