Skip to content

armgit / xerj

Public Imported from GitHub
0

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

fix(engine): reclaim a stale node.lock left by a dead process (#2246)

xerj-org40e57ff4a4f4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e887859fb..c536ebd61 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -64,6 +64,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
deduplicate. Plain-string `xerj_search` requests the
provenance fields needed for this distinction by default.
+- SIGTERM and SIGINT keep the HTTP ports bound until the final memtable
+ flush has finished writing the data directory. New HTTP requests during
+ that window get 503, except `/health/live`, which stays 200 so a liveness
+ probe does not restart the process mid-flush. Connection refusal is the
+ signal that the process is done with the data directory; closing the port
+ first let a wipe that keys off that signal delete a segment the flush was
+ still publishing.
+
+- A `node.lock` left by a process that is no longer running no longer blocks
+ the next start
+ ([#2233](https://github.com/xerj-org/xerj/issues/2233)). The data-directory
+ lock is still the OS file lock, so a live node blocks a second start. When
+ that lock is busy and the PID recorded in the file is not running — a
+ Windows crash can leave `LockFileEx` stuck after the process is gone — the
+ file is replaced and the reclaim is logged. A PID that cannot be read or
+ checked is left alone. `--auto-port` does not treat that stale lock as a
+ reason to start on an empty sibling directory.
+
- `xerj corpus index` killed mid-index resumes that build's journal instead of
starting a legacy index under a new prefix. When the journal still has a
generation in progress, indexing continues at the uncommitted operations and
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 13af60469..8b1540f8a 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -841,16 +841,17 @@ pub struct Engine {
/// commits a new shard assignment.
pub shard_router: Arc<parking_lot::RwLock<xerj_cluster::router::ShardRouter>>,
- /// Exclusive advisory lock on `<data_dir>/node.lock`, held for the
- /// engine's whole lifetime (RC4 blocker 13). Acquired in
- /// [`Engine::new`] BEFORE any index is opened (i.e. before any WAL
- /// replay or segment flush can touch the directory), so a second
- /// xerj process pointed at a live data dir fails fast instead of
- /// replaying the WAL and flushing duplicate segments into it — the
- /// classic systemd double-start corruption. The lock is an OS-level
- /// `flock`-style lock (`std::fs::File::try_lock`), so it dies with
- /// the process: a `kill -9` releases it automatically and a stale
- /// `node.lock` file never blocks the next boot.
+ /// Exclusive lock on `<data_dir>/node.lock`, held for the engine's
+ /// whole lifetime (RC4 blocker 13). Acquired in [`Engine::new`] BEFORE
+ /// any index is opened (i.e. before any WAL replay or segment flush can
+ /// touch the directory), so a second xerj process pointed at a live data
+ /// dir fails fast instead of replaying the WAL and flushing duplicate
+ /// segments into it — the classic systemd double-start corruption.
+ ///
+ /// The OS lock dies with the process on Unix. A crash on Windows can
+ /// leave `LockFileEx` stuck on the file; `node_lock` reclaims it when
+ /// the PID it records is not running, and logs that reclaim. A live
+ /// holder still blocks a second start.
_node_lock: Arc<std::fs::File>,
/// Serializes rewrites of `<data_dir>/cluster_state.json` (issue #203).
@@ -930,7 +931,7 @@ impl Engine {
// scanning/opening any index below — Index::open replays the WAL
// and can flush segments, which must never happen while another
// process serves the same directory.
- let node_lock = Arc::new(Self::acquire_node_lock(&data_dir)?);
+ let node_lock = Arc::new(crate::node_lock::acquire(&data_dir)?);
// Classify durable cluster metadata before Index::open can replay a
// WAL or startup reconciliation can rewrite it. The parsed document
@@ -1215,61 +1216,6 @@ impl Engine {
Ok(engine)
}
- /// Acquire the exclusive `<data_dir>/node.lock` advisory lock (RC4
- /// blocker 13 — data-dir exclusivity).
- ///
- /// Uses `std::fs::File::try_lock` (flock-style, non-blocking): if
- /// another process already holds the lock we fail fast with the
- /// holder's pid instead of replaying its WAL and flushing duplicate
- /// segments into a live directory. On success our own pid is written
- /// into the file purely as a diagnostic for the *next* contender —
- /// exclusivity comes from the OS lock, never from the pid content,
- /// so a stale file left by `kill -9` (lock auto-released at process
- /// death) can never wedge a reboot.
- fn acquire_node_lock(data_dir: &std::path::Path) -> Result<std::fs::File> {
- use std::io::Write;
- let lock_path = data_dir.join("node.lock");
- // Never O_TRUNC here: truncation must only happen AFTER the lock
- // is ours, or a losing contender would erase the holder's pid.
- let file = std::fs::OpenOptions::new()
- .read(true)
- .write(true)
- .create(true)
- .truncate(false)
- .open(&lock_path)?;
- match file.try_lock() {
- Ok(()) => {
- let _ = file.set_len(0);
- let _ = writeln!(&file, "{}", std::process::id());
- let _ = file.sync_all();
- Ok(file)
- }
- Err(std::fs::TryLockError::WouldBlock) => {
- let holder = std::fs::read_to_string(&lock_path)
- .ok()
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
- .unwrap_or_else(|| "unknown".to_string());
- Err(EngineError::Common(xerj_common::XerjError::config(
- format!(
- "data dir '{}' is already in use by another running xerj process \
- (pid {holder}, lock file '{}') — refusing to start. Two processes \
- serving one data dir would replay each other's WAL and corrupt \
- segments; stop the other process or point this one at its own \
- server.data_dir.",
- data_dir.display(),
- lock_path.display(),
- ),
- )))
- }
- Err(std::fs::TryLockError::Error(e)) => {
- Err(EngineError::Common(xerj_common::XerjError::config(
- format!("failed to acquire node lock '{}': {e}", lock_path.display()),
- )))
- }
- }
- }
-
/// Drop PIT contexts whose `expires_at` is in the past. Cheap
/// O(N) walk; runs on the background sweeper task and is also
/// invoked opportunistically inside `open_pit` so a tight
diff --git a/engine/crates/xerj-engine/src/lib.rs b/engine/crates/xerj-engine/src/lib.rs
index 14507a36d..ddeaabc43 100644
--- a/engine/crates/xerj-engine/src/lib.rs
+++ b/engine/crates/xerj-engine/src/lib.rs
@@ -30,6 +30,7 @@ pub mod index_guard;
pub mod ingest_memory;
pub mod lifecycle;
pub mod memtable;
+mod node_lock;
pub mod painless;
pub mod pools;
pub mod rbac;
@@ -56,6 +57,7 @@ pub use index::{
storage_mode_from_config, EnrichTable, FieldEncodingInfo, Index, IndexResponse, IndexStats,
LogFormat,
};
+pub use node_lock::data_dir_lock_held;
// Second-brain graph expansion (bounded columnar traversal over an edges
// index). Lives under `index` for private-field access; re-exported at the
// crate root so callers write `xerj_engine::graph::GraphExpandRequest`.
diff --git a/engine/crates/xerj-engine/src/node_lock.rs b/engine/crates/xerj-engine/src/node_lock.rs
new file mode 100644
index 000000000..05e8c7769
--- /dev/null
+++ b/engine/crates/xerj-engine/src/node_lock.rs
@@ -0,0 +1,709 @@
+//! Exclusive lock on `<data_dir>/node.lock` (RC4 blocker 13).
+//!
+//! A second process must not open a data directory that a live node is
+//! serving: `Index::open` replays the WAL and can flush segments. The
+//! exclusion itself is `File::try_lock` — `flock(2)` on Unix and
+//! `LockFileEx` on Windows — the same call the hub starter uses
+//! (`engine/crates/xerj-hub/src/flock.rs` lines 11–25). That comment is
+//! right about `flock`: the kernel drops it when the holder exits, including
+//! `kill -9`, so the file left behind is only a PID note.
+//!
+//! `LockFileEx` is a mandatory byte-range lock, and a Windows process that
+//! dies during ingest can leave it stuck on `node.lock` until the file is
+//! replaced (issue #2233: the next start refused until someone deleted the
+//! file by hand). Recovery therefore also asks whether the PID recorded in
+//! the file is still a process, the question `xerj-hub` already asks in
+//! `proc_state` (`engine/crates/xerj-hub/src/node.rs` lines 1313–1320 and
+//! 1439–1458). The engine uses `kill(pid, 0)` and `OpenProcess` rather than
+//! the hub's `ps` / `tasklist` spawn: startup should not pay for a process
+//! to decide if it may start.
+//!
+//! A live PID, or a PID that cannot be checked, still fails the second
+//! start. The recorded PID is a diagnostic; a running holder is excluded by
+//! the OS lock, not by the bytes in the file.
+
+use std::fs::{self, File, OpenOptions, TryLockError};
+use std::io::{self, Read, Seek, SeekFrom, Write};
+use std::path::{Path, PathBuf};
+use std::time::Duration;
+
+use tracing::warn;
+
+use crate::{EngineError, Result};
+
+const LOCK_NAME: &str = "node.lock";
+
+/// How many times [`acquire`] will replace a stale lock file before giving up.
+const ACQUIRE_ATTEMPTS: u32 = 4;
+
+/// Pause before treating a busy lock whose recorded PID is dead as stale.
+///
+/// A live holder writes its PID immediately after `try_lock` returns. The
+/// file can still contain the previous (dead) PID for that short window.
+/// Replacing the file in the window would drop a running node's lock. A
+/// holder that has not stamped within this long is not the process the file
+/// names.
+const STALE_CONFIRM: Duration = Duration::from_millis(100);
+
+/// Whether a PID names a running process.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum Liveness {
+ /// The operating system still has this process.
+ Alive,
+ /// The operating system reports no such process.
+ Dead,
+ /// The check failed. Treated as alive so a lock is never stolen.
+ Unknown,
+}
+
+/// Take the exclusive `<data_dir>/node.lock`, creating the file if needed.
+///
+/// The returned file holds the lock until it is dropped. On success the file
+/// contains this process's PID.
+pub(crate) fn acquire(data_dir: &Path) -> Result<File> {
+ let lock_path = data_dir.join(LOCK_NAME);
+ let mut reclaimed_from: Option<u32> = None;
+
+ for _ in 0..ACQUIRE_ATTEMPTS {
+ let file = open_lock(&lock_path).map_err(|e| {
+ config_err(format!(
+ "failed to open node lock '{}': {e}",
+ lock_path.display()
+ ))
+ })?;
+ match file.try_lock() {
+ Ok(()) => {
+ if !path_names_this_file(&file, &lock_path) {
+ // Locked an inode that is no longer the directory entry —
+ // a concurrent reclaim renamed it away. Dropping releases
+ // that inode; the next pass opens whatever is there now.
+ drop(file);
+ continue;
+ }
+ let previous = read_pid_from_file(&file);
+ stamp(&file).map_err(|e| {
+ config_err(format!(
+ "failed to record the holder pid in '{}': {e}",
+ lock_path.display()
+ ))
+ })?;
+ if !path_names_this_file(&file, &lock_path) {
+ drop(file);
+ continue;
+ }
+ if let Some(pid) = reclaimed_from.or_else(|| dead_other(previous)) {
+ log_reclaim(&lock_path, pid);
+ }
+ return Ok(file);
+ }
+ Err(TryLockError::WouldBlock) => {
+ drop(file);
+ match read_holder(&lock_path) {
+ Some(pid) if pid_liveness(pid) == Liveness::Dead => {
+ if confirm_still_dead(&lock_path, pid)
+ && still_blocked(&lock_path).map_err(|e| {
+ config_err(format!(
+ "failed to acquire node lock '{}': {e}",
+ lock_path.display()
+ ))
+ })?
+ {
+ reclaimed_from = Some(pid);
+ move_aside(&lock_path, pid).map_err(|e| {
+ config_err(format!(
+ "data dir '{}' has a stale node.lock for pid {pid}, which is not running, but replacing '{}' failed: {e}. Remove the lock file and start again.",
+ data_dir.display(),
+ lock_path.display(),
+ ))
+ })?;
+ }
+ continue;
+ }
+ holder => {
+ return Err(in_use(data_dir, &lock_path, &holder_label(holder)));
+ }
+ }
+ }
+ Err(TryLockError::Error(e)) => {
+ return Err(config_err(format!(
+ "failed to acquire node lock '{}': {e}",
+ lock_path.display()
+ )));
+ }
+ }
+ }
+
+ Err(config_err(format!(
+ "failed to acquire node lock '{}': the lock stayed busy across {ACQUIRE_ATTEMPTS} attempts. If no xerj process is running, remove the lock file and start again.",
+ lock_path.display(),
+ )))
+}
+
+/// Is `dir/node.lock` held by a live process?
+///
+/// Used by `--auto-port` to pick a free sibling directory. A missing file,
+/// a free OS lock, or a busy lock whose recorded PID is not running is not
+/// held — the engine reclaims the last of those when it opens the directory.
+/// A PID that cannot be read or checked counts as held, so a live node is
+/// never treated as free.
+pub fn data_dir_lock_held(dir: &Path) -> bool {
+ let path = dir.join(LOCK_NAME);
+ let file = match OpenOptions::new().read(true).write(true).open(&path) {
+ Ok(file) => file,
+ Err(_) => return false,
+ };
+ match file.try_lock() {
+ Ok(()) => false,
+ Err(TryLockError::WouldBlock) => {
+ let recorded_dead = matches!(
+ read_holder(&path),
+ Some(pid) if pid_liveness(pid) == Liveness::Dead
+ );
+ !recorded_dead
+ }
+ Err(TryLockError::Error(_)) => false,
+ }
+}
+
+fn config_err(reason: String) -> EngineError {
+ EngineError::Common(xerj_common::XerjError::config(reason))
+}
+
+fn in_use(data_dir: &Path, lock_path: &Path, holder: &str) -> EngineError {
+ config_err(format!(
+ "data dir '{}' is already in use by another running xerj process \
+ (pid {holder}, lock file '{}') — refusing to start. Two processes \
+ serving one data dir would replay each other's WAL and corrupt \
+ segments; stop the other process or point this one at its own \
+ server.data_dir.",
+ data_dir.display(),
+ lock_path.display(),
+ ))
+}
+
+fn holder_label(holder: Option<u32>) -> String {
+ holder
+ .map(|pid| pid.to_string())
+ .unwrap_or_else(|| "unknown".to_string())
+}
+
+/// A recorded PID that is not this process and is not running.
+fn dead_other(previous: Option<u32>) -> Option<u32> {
+ let pid = previous?;
+ if pid == std::process::id() {
+ return None;
+ }
+ (pid_liveness(pid) == Liveness::Dead).then_some(pid)
+}
+
+fn log_reclaim(lock_path: &Path, pid: u32) {
+ warn!(
+ "reclaimed stale node.lock left by pid {pid} (process is not running) at {}",
+ lock_path.display()
+ );
+}
+
+fn open_lock(path: &Path) -> io::Result<File> {
+ if let Some(parent) = path.parent() {
+ if !parent.as_os_str().is_empty() {
+ fs::create_dir_all(parent)?;
+ }
+ }
+ OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .truncate(false)
+ .open(path)
+}
+
+/// Record our PID without shrinking the file.
+///
+/// `LockFileEx` locks a byte range. Truncating to zero (the old stamp) drops
+/// every range that ends past the new end of the file, which on Windows is
+/// the whole lock. The record is a fixed 10-digit line, overwritten in
+/// place, so a later stamp does not shorten the file. A longer tail, if a
+/// previous writer left one, sits past the newline and is ignored.
+fn stamp(file: &File) -> io::Result<()> {
+ let mut out = file.try_clone()?;
+ out.seek(SeekFrom::Start(0))?;
+ let pid = std::process::id();
+ let record = format!("{pid:010}\n");
+ out.write_all(record.as_bytes())?;
+ out.flush()?;
+ out.sync_all()?;
+ Ok(())
+}
+
+fn confirm_still_dead(path: &Path, pid: u32) -> bool {
+ if pid_liveness(pid) != Liveness::Dead {
+ return false;
+ }
+ std::thread::sleep(STALE_CONFIRM);
+ read_holder(path) == Some(pid) && pid_liveness(pid) == Liveness::Dead
+}
+
+/// `true` when a fresh open still cannot take the OS lock.
+fn still_blocked(path: &Path) -> io::Result<bool> {
+ let file = match OpenOptions::new().read(true).write(true).open(path) {
+ Ok(file) => file,
+ Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
+ Err(e) => return Err(e),
+ };
+ match file.try_lock() {
+ Ok(()) => Ok(false),
+ Err(TryLockError::WouldBlock) => Ok(true),
+ Err(TryLockError::Error(e)) => Err(e),
+ }
+}
+
+/// Rename `node.lock` aside when it still records `pid` and that PID is dead.
+///
+/// Removing the directory entry is what clears a `LockFileEx` that survived
+/// its holder: the stuck range belongs to the old file object, and the next
+/// `open` creates a different one. The rename is skipped when the contents
+/// changed, so a holder that stamped during [`STALE_CONFIRM`] keeps its file.
+fn move_aside(path: &Path, pid: u32) -> io::Result<()> {
+ if read_holder(path) != Some(pid) || pid_liveness(pid) != Liveness::Dead {
+ return Ok(());
+ }
+ let dest = reclaim_dest(path, pid);
+ match fs::rename(path, &dest) {
+ Ok(()) => {
+ let _ = fs::remove_file(&dest);
+ Ok(())
+ }
+ Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
+ Err(_) => match fs::remove_file(path) {
+ Ok(()) => Ok(()),
+ Err(_) if !path.exists() => Ok(()),
+ Err(e) => Err(e),
+ },
+ }
+}
+
+fn reclaim_dest(path: &Path, pid: u32) -> PathBuf {
+ use std::sync::atomic::{AtomicU64, Ordering};
+ static SEQ: AtomicU64 = AtomicU64::new(1);
+ let seq = SEQ.fetch_add(1, Ordering::Relaxed);
+ path.with_file_name(format!(
+ "node.lock.reclaim-{pid}-{}-{seq}",
+ std::process::id()
+ ))
+}
+
+fn read_holder(path: &Path) -> Option<u32> {
+ let file = File::open(path).ok()?;
+ read_pid_from_file(&file)
+}
+
+fn read_pid_from_file(file: &File) -> Option<u32> {
+ let mut cloned = file.try_clone().ok()?;
+ cloned.seek(SeekFrom::Start(0)).ok()?;
+ let mut buf = [0_u8; 64];
+ let n = cloned.read(&mut buf).ok()?;
+ let text = std::str::from_utf8(&buf[..n]).ok()?;
+ parse_pid(text)
+}
+
+fn parse_pid(text: &str) -> Option<u32> {
+ let line = text.lines().next()?.trim();
+ if line.is_empty() {
+ return None;
+ }
+ let pid: u32 = line.parse().ok()?;
+ (pid != 0).then_some(pid)
+}
+
+fn path_names_this_file(file: &File, path: &Path) -> bool {
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ match (file.metadata(), fs::metadata(path)) {
+ (Ok(ours), Ok(named)) => ours.dev() == named.dev() && ours.ino() == named.ino(),
+ _ => false,
+ }
+ }
+ #[cfg(windows)]
+ {
+ windows_same_file(file, path)
+ }
+ #[cfg(not(any(unix, windows)))]
+ {
+ let _ = (file, path);
+ true
+ }
+}
+
+#[cfg(unix)]
+fn pid_liveness(pid: u32) -> Liveness {
+ // `kill` takes a `pid_t`. A value that does not fit is not a Unix PID;
+ // refusing to signal it also avoids casting it to a negative pid.
+ let Some(pid) = i32::try_from(pid).ok().filter(|pid| *pid > 0) else {
+ return Liveness::Unknown;
+ };
+ // SAFETY: signal 0 does not deliver a signal. `kill` only checks that
+ // `pid` names a process the caller may signal, and writes the result to
+ // the return value and errno. No other state is modified.
+ let rc = unsafe { libc::kill(pid, 0) };
+ if rc == 0 {
+ // Includes zombies: the process entry still exists. A zombie has
+ // already closed its descriptors, so it does not hold `flock`;
+ // treating it as alive only refuses a steal, which is the safe side.
+ return Liveness::Alive;
+ }
+ match io::Error::last_os_error().raw_os_error() {
+ Some(code) if code == libc::ESRCH => Liveness::Dead,
+ // The process exists, but it belongs to another user.
+ Some(code) if code == libc::EPERM => Liveness::Alive,
+ _ => Liveness::Unknown,
+ }
+}
+
+#[cfg(windows)]
+fn pid_liveness(pid: u32) -> Liveness {
+ if pid == 0 {
+ return Liveness::Unknown;
+ }
+ // PROCESS_QUERY_LIMITED_INFORMATION, SYNCHRONIZE, and the wait/error codes.
+ // `WaitForSingleObject` needs SYNCHRONIZE on the handle; query-limited
+ // alone is not enough to observe exit.
+ const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
+ const SYNCHRONIZE: u32 = 0x0010_0000;
+ const ERROR_INVALID_PARAMETER: u32 = 87;
+ const ERROR_ACCESS_DENIED: u32 = 5;
+ const WAIT_OBJECT_0: u32 = 0;
+ const WAIT_TIMEOUT: u32 = 0x102;
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn OpenProcess(
+ desired_access: u32,
+ inherit_handle: i32,
+ process_id: u32,
+ ) -> *mut std::ffi::c_void;
+ fn WaitForSingleObject(handle: *mut std::ffi::c_void, milliseconds: u32) -> u32;
+ fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
+ fn GetLastError() -> u32;
+ }
+
+ // SAFETY: `OpenProcess` / `WaitForSingleObject` / `CloseHandle` /
+ // `GetLastError` are the Win32 process-liveness calls. The handle is
+ // either null or a process handle this function closes before returning.
+ // `GetLastError` is read immediately after a failed `OpenProcess`, before
+ // any other call can overwrite the thread's last-error code.
+ unsafe {
+ let handle = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
+ if handle.is_null() {
+ return match GetLastError() {
+ ERROR_INVALID_PARAMETER => Liveness::Dead,
+ ERROR_ACCESS_DENIED => Liveness::Alive,
+ _ => Liveness::Unknown,
+ };
+ }
+ let waited = WaitForSingleObject(handle, 0);
+ CloseHandle(handle);
+ match waited {
+ WAIT_TIMEOUT => Liveness::Alive,
+ // The process object is signaled once the process has exited,
+ // even if a leftover handle has kept the PID from disappearing.
+ WAIT_OBJECT_0 => Liveness::Dead,
+ _ => Liveness::Unknown,
+ }
+ }
+}
+
+#[cfg(not(any(unix, windows)))]
+fn pid_liveness(_pid: u32) -> Liveness {
+ Liveness::Unknown
+}
+
+#[cfg(windows)]
+fn windows_same_file(file: &File, path: &Path) -> bool {
+ use std::os::windows::io::AsRawHandle;
+
+ #[repr(C)]
+ struct Filetime {
+ low: u32,
+ high: u32,
+ }
+ #[repr(C)]
+ struct ByHandleFileInformation {
+ file_attributes: u32,
+ creation_time: Filetime,
+ last_access_time: Filetime,
+ last_write_time: Filetime,
+ volume_serial_number: u32,
+ file_size_high: u32,
+ file_size_low: u32,
+ number_of_links: u32,
+ file_index_high: u32,
+ file_index_low: u32,
+ }
+
+ #[link(name = "kernel32")]
+ extern "system" {
+ fn GetFileInformationByHandle(
+ file: *mut std::ffi::c_void,
+ info: *mut ByHandleFileInformation,
+ ) -> i32;
+ }
+
+ fn identity(handle: *mut std::ffi::c_void) -> Option<(u32, u64)> {
+ // SAFETY: `handle` is a live file handle. `info` points at a
+ // zeroed `BY_HANDLE_FILE_INFORMATION` the caller owns. The call
+ // writes that struct and returns zero on failure.
+ unsafe {
+ let mut info = std::mem::zeroed();
+ if GetFileInformationByHandle(handle, &mut info) == 0 {
+ return None;
+ }
+ let index = (u64::from(info.file_index_high) << 32) | u64::from(info.file_index_low);
+ Some((info.volume_serial_number, index))
+ }
+ }
+
+ let Ok(named) = File::open(path) else {
+ return false;
+ };
+ match (
+ identity(file.as_raw_handle()),
+ identity(named.as_raw_handle()),
+ ) {
+ (Some(ours), Some(theirs)) => ours == theirs,
+ _ => false,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{Mutex, OnceLock};
+
+ fn serialize_tests() -> std::sync::MutexGuard<'static, ()> {
+ static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
+ LOCK.get_or_init(|| Mutex::new(()))
+ .lock()
+ .unwrap_or_else(|poison| poison.into_inner())
+ }
+
+ #[derive(Clone)]
+ struct LogBuffer(std::sync::Arc<Mutex<Vec<u8>>>);
+
+ struct LogWriter(std::sync::Arc<Mutex<Vec<u8>>>);
+
+ impl Write for LogWriter {
+ fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogBuffer {
+ type Writer = LogWriter;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ LogWriter(self.0.clone())
+ }
+ }
+
+ fn capture_warns(body: impl FnOnce()) -> String {
+ let buffer = LogBuffer(std::sync::Arc::new(Mutex::new(Vec::new())));
+ let subscriber = tracing_subscriber::fmt()
+ .without_time()
+ .with_ansi(false)
+ .with_target(false)
+ .with_max_level(tracing::Level::WARN)
+ .with_writer(buffer.clone())
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+ tracing::callsite::rebuild_interest_cache();
+ body();
+ let bytes = buffer.0.lock().unwrap().clone();
+ String::from_utf8(bytes).unwrap()
+ }
+
+ fn reaped_pid() -> u32 {
+ for _ in 0..20 {
+ let mut cmd = if cfg!(windows) {
+ let mut cmd = std::process::Command::new("cmd");
+ cmd.args(["/C", "exit", "0"]);
+ cmd
+ } else {
+ std::process::Command::new("true")
+ };
+ let mut child = cmd.spawn().expect("spawn a process that exits");
+ let pid = child.id();
+ child.wait().unwrap();
+ if pid_liveness(pid) == Liveness::Dead {
+ return pid;
+ }
+ }
+ panic!("could not observe a reaped pid");
+ }
+
+ fn hold(path: &Path) -> File {
+ let file = OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(path)
+ .unwrap();
+ file.try_lock().expect("the test process locks the file");
+ file
+ }
+
+ #[test]
+ fn this_process_is_alive_and_a_reaped_child_is_dead() {
+ assert_eq!(pid_liveness(std::process::id()), Liveness::Alive);
+ assert_eq!(pid_liveness(0), Liveness::Unknown);
+ let dead = reaped_pid();
+ assert_eq!(pid_liveness(dead), Liveness::Dead);
+ }
+
+ #[test]
+ fn a_second_acquire_fails_while_the_holder_is_alive_and_reopen_does_not_warn() {
+ let _guard = serialize_tests();
+ let dir = tempfile::tempdir().unwrap();
+ let held = acquire(dir.path()).expect("first lock");
+ let err = acquire(dir.path()).expect_err("a live holder must block");
+ let err = err.to_string();
+ assert!(
+ err.contains("already in use"),
+ "unexpected lock error: {err}"
+ );
+ assert!(
+ err.contains(&std::process::id().to_string()),
+ "lock error should name the holding pid: {err}"
+ );
+ drop(held);
+
+ let logs = capture_warns(|| {
+ let again = acquire(dir.path()).expect("reopen after the holder drops");
+ drop(again);
+ });
+ assert!(
+ !logs.contains("reclaimed stale node.lock"),
+ "dropping our own lock is not a dead holder: {logs}"
+ );
+ }
+
+ #[test]
+ fn a_lock_file_left_by_a_dead_pid_is_reclaimed_and_logged() {
+ let _guard = serialize_tests();
+ let dir = tempfile::tempdir().unwrap();
+ let dead = reaped_pid();
+ fs::write(dir.path().join(LOCK_NAME), format!("{dead}\n")).unwrap();
+
+ let logs = capture_warns(|| {
+ let file = acquire(dir.path()).expect("a dead pid with no os holder is stale");
+ let recorded = read_pid_from_file(&file);
+ assert_eq!(recorded, Some(std::process::id()));
+ let err = acquire(dir.path()).expect_err("the reclaimed lock is exclusive");
+ assert!(err.to_string().contains("already in use"));
+ drop(file);
+ });
+ assert!(
+ logs.contains(&format!(
+ "reclaimed stale node.lock left by pid {dead} (process is not running)"
+ )),
+ "reclaim must be logged: {logs}"
+ );
+ }
+
+ #[test]
+ fn a_busy_lock_whose_recorded_pid_is_dead_is_reclaimed_when_that_pid_is_readable() {
+ let _guard = serialize_tests();
+ let dir = tempfile::tempdir().unwrap();
+ let dead = reaped_pid();
+ let path = dir.path().join(LOCK_NAME);
+ fs::write(&path, format!("{dead}\n")).unwrap();
+ // Simulates the Windows failure mode: the OS lock is still busy, but
+ // the PID in the file is not a running process. On Unix the bytes
+ // stay readable under `flock`. A mandatory lock that hides them
+ // cannot be shown to be stale, and must keep blocking.
+ let holder = hold(&path);
+ let readable = read_holder(&path) == Some(dead);
+
+ let logs = capture_warns(|| {
+ let result = acquire(dir.path());
+ if readable {
+ let file =
+ result.expect("a readable dead pid is reclaimed even if try_lock is busy");
+ assert_eq!(read_pid_from_file(&file), Some(std::process::id()));
+ // Reclaim replaces the file. The same inode would mean
+ // `try_lock` succeeded on the busy file and this did not
+ // exercise the stuck-lock path.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::MetadataExt;
+ let held_ino = holder.metadata().unwrap().ino();
+ let now_ino = fs::metadata(&path).unwrap().ino();
+ assert_ne!(
+ held_ino, now_ino,
+ "reclaim must replace the stuck lock file"
+ );
+ }
+ let err = acquire(dir.path()).expect_err("replacement lock is held");
+ assert!(err.to_string().contains(&std::process::id().to_string()));
+ drop(file);
+ } else {
+ let err = result.expect_err("an unreadable busy lock must block");
+ assert!(
+ err.to_string().contains("already in use"),
+ "unexpected lock error: {err}"
+ );
+ }
+ });
+ if readable {
+ assert!(
+ logs.contains(&format!("reclaimed stale node.lock left by pid {dead}")),
+ "stuck-lock reclaim must be logged: {logs}"
+ );
+ }
+ drop(holder);
+ }
+
+ #[test]
+ fn a_busy_lock_with_no_pid_still_blocks() {
+ let _guard = serialize_tests();
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join(LOCK_NAME);
+ fs::write(&path, b"\n").unwrap();
+ let _holder = hold(&path);
+ let err = acquire(dir.path()).expect_err("no pid means the holder is unknown");
+ let err = err.to_string();
+ assert!(err.contains("already in use"), "{err}");
+ assert!(err.contains("unknown"), "{err}");
+ }
+
+ #[test]
+ fn data_dir_lock_held_ignores_a_dead_pid_and_honors_a_live_one() {
+ let _guard = serialize_tests();
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!data_dir_lock_held(dir.path()));
+
+ let dead = reaped_pid();
+ fs::write(dir.path().join(LOCK_NAME), format!("{dead}\n")).unwrap();
+ assert!(
+ !data_dir_lock_held(dir.path()),
+ "a lock file from a dead pid with no os lock is not held"
+ );
+
+ // `acquire` logs the reclaim. A subscriber has to be installed first:
+ // the callsite interest cache is process-global, and a first hit with
+ // no subscriber would drop the warning the other tests assert.
+ capture_warns(|| {
+ let held = acquire(dir.path()).unwrap();
+ assert!(
+ data_dir_lock_held(dir.path()),
+ "a lock held by this live process is held"
+ );
+ drop(held);
+ });
+ assert!(!data_dir_lock_held(dir.path()));
+ }
+}
diff --git a/engine/crates/xerj-engine/tests/node_lock.rs b/engine/crates/xerj-engine/tests/node_lock.rs
index 68741fabf..4a53909de 100644
--- a/engine/crates/xerj-engine/tests/node_lock.rs
+++ b/engine/crates/xerj-engine/tests/node_lock.rs
@@ -48,3 +48,113 @@ async fn second_engine_on_same_data_dir_fails_fast_with_holder_pid() {
reopened.err()
);
}
+
+/// A `node.lock` left by a process that has exited must not block the next
+/// boot, and the reclaim is logged. This is the file `kill -9` leaves once
+/// the kernel has dropped `flock`, and the file a crashed Windows process
+/// leaves behind when `LockFileEx` does not.
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn stale_node_lock_from_a_dead_pid_is_reclaimed_on_start() {
+ let dir = TempDir::new().unwrap();
+ let dead = reaped_pid();
+ std::fs::write(dir.path().join("node.lock"), format!("{dead}\n")).unwrap();
+
+ let logs = capture_warns(|| {
+ let engine = Engine::new(config_for(&dir)).expect("dead pid lock file must be reclaimed");
+ let stamped = std::fs::read_to_string(dir.path().join("node.lock")).unwrap();
+ assert_eq!(
+ stamped.trim().parse::<u32>().ok(),
+ Some(std::process::id()),
+ "the live process stamps node.lock, got {stamped:?}"
+ );
+
+ // The reclaimed lock is the real exclusive lock: a second start blocks.
+ let err = match Engine::new(config_for(&dir)) {
+ Ok(_) => panic!("second engine on the reclaimed data dir must fail fast"),
+ Err(e) => e.to_string(),
+ };
+ assert!(err.contains("already in use"), "{err}");
+ assert!(
+ err.contains(&std::process::id().to_string()),
+ "lock error should name the holding pid: {err}"
+ );
+ drop(engine);
+ });
+ assert!(
+ logs.contains(&format!(
+ "reclaimed stale node.lock left by pid {dead} (process is not running)"
+ )),
+ "reclaim must be logged: {logs}"
+ );
+}
+
+fn reaped_pid() -> u32 {
+ for _ in 0..20 {
+ let mut cmd = if cfg!(windows) {
+ let mut cmd = std::process::Command::new("cmd");
+ cmd.args(["/C", "exit", "0"]);
+ cmd
+ } else {
+ std::process::Command::new("true")
+ };
+ let mut child = cmd.spawn().expect("spawn a process that exits");
+ let pid = child.id();
+ let status = child.wait().unwrap();
+ assert!(status.success());
+ // The child has been waited on, so it is not a zombie. `ps` exiting
+ // non-zero is "no such process". A recycled pid is still running;
+ // try another one. `ps` missing (Windows) skips the probe.
+ if !pid_still_listed(pid) {
+ return pid;
+ }
+ }
+ panic!("could not observe a reaped pid");
+}
+
+fn pid_still_listed(pid: u32) -> bool {
+ std::process::Command::new("ps")
+ .args(["-p", &pid.to_string()])
+ .output()
+ .map(|out| out.status.success())
+ .unwrap_or(false)
+}
+
+#[derive(Clone)]
+struct LogBuffer(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
+
+struct LogWriter(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
+
+impl std::io::Write for LogWriter {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for LogBuffer {
+ type Writer = LogWriter;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ LogWriter(self.0.clone())
+ }
+}
+
+fn capture_warns(body: impl FnOnce()) -> String {
+ let buffer = LogBuffer(std::sync::Arc::new(std::sync::Mutex::new(Vec::new())));
+ let subscriber = tracing_subscriber::fmt()
+ .without_time()
+ .with_ansi(false)
+ .with_target(false)
+ .with_max_level(tracing::Level::WARN)
+ .with_writer(buffer.clone())
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+ tracing::callsite::rebuild_interest_cache();
+ body();
+ let bytes = buffer.0.lock().unwrap().clone();
+ String::from_utf8(bytes).unwrap()
+}
diff --git a/engine/crates/xerj-server/src/main.rs b/engine/crates/xerj-server/src/main.rs
index d639b6e09..e18ea1ff8 100644
--- a/engine/crates/xerj-server/src/main.rs
+++ b/engine/crates/xerj-server/src/main.rs
@@ -116,8 +116,13 @@ pub static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muz
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
+use std::sync::Arc;
use anyhow::{Context, Result};
+use axum::extract::Request;
+use axum::middleware::Next;
+use axum::response::{IntoResponse, Response};
use axum::Router;
use axum_server::tls_rustls::RustlsConfig;
use tokio::net::TcpListener;
@@ -1284,8 +1289,9 @@ async fn shutdown_signal() {
#[cfg(not(unix))]
let sigterm = std::future::pending::<()>();
- // `shutdown_signal()` is awaited once per listener (native REST, ES-compat,
- // gRPC), so all of them wake on the same Ctrl-C. Log the banner only once.
+ // Awaited once, from `async_main`. The listeners wait on `ShutdownPhase`
+ // instead, so they do not close their ports before the final flush. Log
+ // the banner only once.
static SHUTDOWN_LOGGED: std::sync::Once = std::sync::Once::new();
tokio::select! {
_ = ctrl_c => { SHUTDOWN_LOGGED.call_once(|| info!("SIGINT received — shutting down")); }
@@ -1355,7 +1361,108 @@ async fn serve(
name: &'static str,
tls: Option<RustlsConfig>,
) -> Result<()> {
- serve_on(router, bind_listener(addr, name)?, name, tls).await
+ // Unit tests stop the server by dropping the runtime, not by signalling.
+ // Holding the sender keeps the phase at `Serving` for the life of `serve`.
+ let (tx, rx) = tokio::sync::watch::channel(ShutdownPhase::Serving);
+ let _hold = tx;
+ serve_on(router, bind_listener(addr, name)?, name, tls, rx).await
+}
+
+/// How far shutdown has gotten.
+///
+/// Listeners used to stop accepting on the signal itself, and the final flush
+/// ran only after those tasks returned. `/health/ready` then refused
+/// connections while `flush_all_force` was still publishing segments. A caller
+/// that treats connection refusal as "the process is done with the data
+/// directory" — the use-case harness wipes the data dir at that moment —
+/// deleted those segments out from under the flush (`Directory not empty`,
+/// then `Segment … not found` on the next open).
+///
+/// `Draining` rejects new HTTP work and stops gRPC, but the HTTP ports stay
+/// bound so a connect still succeeds. `Released` is after the flush; only
+/// then do the HTTP listeners close.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum ShutdownPhase {
+ Serving,
+ Draining,
+ Released,
+}
+
+/// New HTTP requests are refused once shutdown starts, and counted until they
+/// finish, so the final flush does not race a request that was allowed in.
+/// `/health/live` stays 200: a liveness 5xx restarts the process (see
+/// `native::liveness`).
+#[derive(Clone)]
+struct DrainGate {
+ draining: Arc<AtomicBool>,
+ in_flight: Arc<AtomicUsize>,
+}
+
+impl DrainGate {
+ fn new() -> Self {
+ Self {
+ draining: Arc::new(AtomicBool::new(false)),
+ in_flight: Arc::new(AtomicUsize::new(0)),
+ }
+ }
+
+ fn begin(&self) {
+ self.draining.store(true, Ordering::SeqCst);
+ }
+
+ fn in_flight(&self) -> usize {
+ self.in_flight.load(Ordering::SeqCst)
+ }
+}
+
+struct InFlightGuard(Arc<AtomicUsize>);
+
+impl Drop for InFlightGuard {
+ fn drop(&mut self) {
+ self.0.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+fn hold_port_while_draining(router: Router, gate: DrainGate) -> Router {
+ router.layer(axum::middleware::from_fn(move |req, next| {
+ let gate = gate.clone();
+ async move { reject_when_draining(req, next, gate).await }
+ }))
+}
+
+async fn reject_when_draining(req: Request, next: Next, gate: DrainGate) -> Response {
+ // Liveness must keep answering 200 for the whole process lifetime. A 503
+ // here is what makes kubelet kill the pod, which would cut the flush off.
+ if req.uri().path() == "/health/live" {
+ return next.run(req).await;
+ }
+ if gate.draining.load(Ordering::SeqCst) {
+ return shutting_down_response();
+ }
+ gate.in_flight.fetch_add(1, Ordering::SeqCst);
+ let _guard = InFlightGuard(Arc::clone(&gate.in_flight));
+ if gate.draining.load(Ordering::SeqCst) {
+ return shutting_down_response();
+ }
+ next.run(req).await
+}
+
+fn shutting_down_response() -> Response {
+ (axum::http::StatusCode::SERVICE_UNAVAILABLE, "shutting down").into_response()
+}
+
+async fn wait_for_phase(
+ mut rx: tokio::sync::watch::Receiver<ShutdownPhase>,
+ ready: impl Fn(ShutdownPhase) -> bool,
+) {
+ loop {
+ if ready(*rx.borrow()) {
+ return;
+ }
+ if rx.changed().await.is_err() {
+ return;
+ }
+ }
}
/// Bind one listener, or fail.
@@ -1550,15 +1657,15 @@ fn resolve_available_data_dir(requested: &str) -> String {
/// How many `<dir>-N` siblings [`resolve_available_data_dir`] will try.
const MAX_DATA_DIR_SIBLINGS: usize = 64;
-/// Is `dir/node.lock` currently locked by a live process? A missing or
-/// unopenable lock file is "not held" — the engine's own lock acquisition is
-/// the authority and reports anything stranger.
+/// Is `dir/node.lock` currently locked by a live process?
+///
+/// A missing file, a free OS lock, or a busy lock whose recorded PID is not
+/// running is not held. The engine reclaims the stale case itself; treating
+/// it as held here would make `--auto-port` start on an empty sibling and
+/// leave the real data directory behind. A PID that cannot be read still
+/// counts as held.
fn data_dir_held(dir: &Path) -> bool {
- std::fs::OpenOptions::new()
- .read(true)
- .write(true)
- .open(dir.join("node.lock"))
- .is_ok_and(|f| matches!(f.try_lock(), Err(std::fs::TryLockError::WouldBlock)))
+ xerj_engine::data_dir_lock_held(dir)
}
/// Bind one listener, attempting consecutive ports if `auto_port` is true and
@@ -1617,6 +1724,7 @@ async fn serve_on(
listener: std::net::TcpListener,
name: &'static str,
tls: Option<RustlsConfig>,
+ release: tokio::sync::watch::Receiver<ShutdownPhase>,
) -> Result<()> {
let addr = listener
.local_addr()
@@ -1631,13 +1739,16 @@ async fn serve_on(
// caller from the PEM files that `ensure_tls_cert` generated/validated.
if let Some(tls) = tls {
// axum-server drives shutdown through a `Handle` rather than a
- // graceful-shutdown future, so bridge our SIGINT/SIGTERM signal to
- // it: on signal, stop accepting and drain in-flight connections
- // (10 s grace) so ongoing requests finish cleanly.
+ // graceful-shutdown future, so bridge the post-flush release to it:
+ // stop accepting and drain in-flight connections (10 s grace) only
+ // after the final flush has finished writing the data directory.
let handle = axum_server::Handle::new();
let shutdown_handle = handle.clone();
tokio::spawn(async move {
- shutdown_signal().await;
+ // The port stays bound through the final flush. Closing it on the
+ // signal itself is what let a concurrent wipe remove segments the
+ // flush was still writing.
+ wait_for_phase(release, |phase| phase == ShutdownPhase::Released).await;
shutdown_handle.graceful_shutdown(Some(std::time::Duration::from_secs(10)));
});
@@ -1664,11 +1775,12 @@ async fn serve_on(
// round-trips can stall on the delayed-ACK/Nagle interaction, which
// shows up as a fixed per-request latency tax on trivial reads.
//
- // Bounded drain (#1635): `with_graceful_shutdown` stops accepting on
- // signal but then waits forever for in-flight connections to drain. A
- // request parked on a wedged flush never drains, so SIGTERM would hang
- // the process until SIGKILL. Mirror the TLS path's 10 s grace: once the
- // signal fires, give drainers 10 s, then force the listener down.
+ // Bounded drain (#1635): `with_graceful_shutdown` stops accepting once
+ // the shutdown flush has released the listener, then waits forever for
+ // in-flight connections to drain. A request parked on a wedged flush
+ // never drains, so shutdown would hang the process until SIGKILL.
+ // Mirror the TLS path's 10 s grace: once the flush releases the port,
+ // give drainers 10 s, then force the listener down.
let (drain_tx, drain_rx) = tokio::sync::oneshot::channel::<()>();
let serve = axum::serve(
listener,
@@ -1676,7 +1788,7 @@ async fn serve_on(
)
.tcp_nodelay(true)
.with_graceful_shutdown(async move {
- shutdown_signal().await;
+ wait_for_phase(release, |phase| phase == ShutdownPhase::Released).await;
let _ = drain_tx.send(());
});
// `with_graceful_shutdown` yields an `IntoFuture`, not a `Future`; the
@@ -1689,7 +1801,7 @@ async fn serve_on(
let _ = drain_rx.await;
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
} => {
- warn!("{name}: in-flight connections did not drain within 10s of signal; forcing shutdown");
+ warn!("{name}: in-flight connections did not drain within 10s of the shutdown flush; forcing shutdown");
}
}
@@ -4338,6 +4450,13 @@ async fn async_main() -> Result<()> {
native_router = native_router.merge(xerj_console_router.clone());
es_router = es_router.merge(xerj_console_router);
}
+ // Outermost, so it runs before auth: once shutdown starts, new HTTP work
+ // is refused while the listening socket stays open. `/health/live` is
+ // exempt inside the layer.
+ let drain = DrainGate::new();
+ native_router = hold_port_while_draining(native_router, drain.clone());
+ es_router = hold_port_while_draining(es_router, drain.clone());
+ let (phase_tx, phase_rx) = tokio::sync::watch::channel(ShutdownPhase::Serving);
// 10/10a. Bind addresses + listeners: moved up to step 8c, ahead of the
// console bootstrap at step 9, so the setup link it prints is
@@ -4403,70 +4522,108 @@ async fn async_main() -> Result<()> {
}
let _ingest_memory_trace = storage_available.then(|| ingest_memory_trace::spawn(&state.engine));
- // 13. Start servers concurrently
+ // 13. Start servers concurrently. Their sockets stay open until
+ // `phase_tx` says the final flush has finished; see `ShutdownPhase`.
let rest_tls = tls_config.clone();
- let rest = tokio::spawn(async move {
- if let Err(e) = serve_on(native_router, rest_listener, "native REST", rest_tls).await {
+ let rest_phase = phase_rx.clone();
+ let mut rest = tokio::spawn(async move {
+ if let Err(e) = serve_on(
+ native_router,
+ rest_listener,
+ "native REST",
+ rest_tls,
+ rest_phase,
+ )
+ .await
+ {
error!("native REST: {e:#}");
}
});
let es_tls = tls_config.clone();
- let es = tokio::spawn(async move {
- if let Err(e) = serve_on(es_router, es_listener, "ES-compat", es_tls).await {
+ let es_phase = phase_rx.clone();
+ let mut es = tokio::spawn(async move {
+ if let Err(e) = serve_on(es_router, es_listener, "ES-compat", es_tls, es_phase).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. 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.
+ // gRPC closes when draining starts, before the flush. It is not the port
+ // a readiness probe uses. 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_on(grpc_listener, grpc_state, hub_shared, shutdown_signal()).await
+ let grpc_phase = phase_rx;
+ let mut grpc = tokio::spawn(async move {
+ if let Err(e) = grpc::serve_grpc_on(
+ grpc_listener,
+ grpc_state,
+ hub_shared,
+ wait_for_phase(grpc_phase, |phase| phase != ShutdownPhase::Serving),
+ )
+ .await
{
error!("gRPC server: {e:#}");
}
});
- // 14. Wait for all servers (they exit together on shutdown)
- let _ = tokio::join!(rest, es, grpc);
+ // 14. Park until the signal, or until a listener task returns on its own
+ // (a transport error). Do not join the HTTP listeners here: they are what
+ // keeps the port bound through the flush below.
+ tokio::select! {
+ _ = shutdown_signal() => {}
+ _ = &mut rest => {}
+ _ = &mut es => {}
+ _ = &mut grpc => {}
+ }
- // Servers are down — stop the periodic flusher BEFORE the final
- // synchronous flush below so its next tick can't race
- // `flush_all_force` during shutdown.
+ drain.begin();
+ // gRPC stops accepting now. HTTP keeps the socket and answers 503.
+ let _ = phase_tx.send(ShutdownPhase::Draining);
+ let _ = grpc.await;
+
+ let drain_deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ while drain.in_flight() > 0 && std::time::Instant::now() < drain_deadline {
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ if drain.in_flight() > 0 {
+ warn!("in-flight HTTP requests did not finish within 10s of shutdown; flushing anyway");
+ }
+
+ // Stop the periodic flusher BEFORE the final synchronous flush so its
+ // next tick can't race `flush_all_force`.
//
- // RC4 W2 #20: this abort used to sit ABOVE the `join!`, killing the
- // flusher milliseconds after it was spawned. `flush_interval_secs`
- // was inert for the entire life of the server: an over-threshold
- // memtable that the write-path flush scheduler missed (WAL replay at
- // boot, flush-permit exhaustion on the last write) sat in memory —
- // pinning its WAL generations on disk — until shutdown or the next
- // explicit `_flush`.
+ // RC4 W2 #20: this abort used to sit at startup, above the `join!`,
+ // killing the flusher milliseconds after it was spawned.
+ // `flush_interval_secs` was inert for the entire life of the server: an
+ // over-threshold memtable that the write-path flush scheduler missed
+ // (WAL replay at boot, flush-permit exhaustion on the last write) sat in
+ // memory — pinning its WAL generations on disk — until shutdown or the
+ // next explicit `_flush`. Aborting here is after the server has been
+ // serving; the signal is what reached this line.
if let Some(flusher) = flusher {
flusher.abort();
}
- // 15. Final synchronous flush across every index.
+ // 15. Final synchronous flush across every index, WHILE the HTTP ports
+ // are still bound.
+ //
+ // The flush has to land memtables as segments before the process exits.
+ // Without it, anything bulk-ingested after the last auto-flush threshold
+ // lives only in the WAL until the next startup — and an index whose
+ // memtable never reached that threshold loses its data on restart because
+ // startup index discovery looks for segment-bearing directories first.
+ // See POV report 2026-04-24T23-58-00 (B-2).
//
- // The graceful-shutdown future fires on SIGTERM/SIGINT and stops axum
- // from accepting new connections, but it does NOT drain the engine's
- // in-memory memtables to durable segments. Without this final pass,
- // any docs that were bulk-ingested after the last auto-flush threshold
- // crossing live only in the WAL until the next startup — and an index
- // whose memtable never reached that threshold (small batches, brief
- // sessions) loses 100 % of its data on restart because startup index
- // discovery looks for segment-bearing directories first. See POV
- // report 2026-04-24T23-58-00 (B-2) for the full failure mode.
+ // The port stays open across this flush. Closing it first made connection
+ // refusal mean "still writing", and a wipe that started at that signal
+ // deleted the segment files the flush was creating.
if storage_available {
info!("flushing in-memory state before exit…");
let flush_started = std::time::Instant::now();
- // Bounded (#1635): a wedged memtable flush must not re-hang shutdown
- // after the listeners drained. Docs live in the WAL and replay on the
- // next boot, so a skipped final flush is non-destructive.
+ // Bounded (#1635): a wedged memtable flush must not re-hang shutdown.
+ // Docs live in the WAL and replay on the next boot, so a skipped
+ // final flush is non-destructive.
let flush_budget = std::time::Duration::from_secs(10);
match tokio::time::timeout(flush_budget, state.engine.flush_all_force()).await {
Ok(()) => info!("final flush complete in {:.0?}", flush_started.elapsed()),
@@ -4476,6 +4633,10 @@ async fn async_main() -> Result<()> {
}
}
+ let _ = phase_tx.send(ShutdownPhase::Released);
+ let _ = rest.await;
+ let _ = es.await;
+
info!("xerj v{} stopped. Goodbye.", env!("CARGO_PKG_VERSION"));
Ok(())
}
@@ -4483,6 +4644,113 @@ async fn async_main() -> Result<()> {
// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod shutdown_port_tests {
+ use super::*;
+
+ /// The use-case harness (and anything else that wipes a data directory
+ /// when connect() fails) must still be able to connect while the shutdown
+ /// flush would be running, and must fail only after the flush releases
+ /// the listener.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn http_port_stays_bound_until_the_shutdown_flush_releases_it() {
+ let (tx, rx) = tokio::sync::watch::channel(ShutdownPhase::Serving);
+ let gate = DrainGate::new();
+ let app = hold_port_while_draining(
+ Router::new().route("/health/ready", axum::routing::get(|| async { "ready" })),
+ gate.clone(),
+ );
+ let listener = bind_listener("127.0.0.1:0".parse().unwrap(), "test-shutdown").unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = tokio::spawn(async move {
+ serve_on(app, listener, "test-shutdown", None, rx)
+ .await
+ .unwrap();
+ });
+
+ let client = reqwest::Client::new();
+ let url = format!("http://{addr}/health/ready");
+ let mut saw_ok = false;
+ for _ in 0..50 {
+ if let Ok(resp) = client.get(&url).send().await {
+ assert_eq!(resp.status(), 200);
+ saw_ok = true;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert!(saw_ok, "listener did not answer before shutdown");
+
+ gate.begin();
+ let draining = client.get(&url).send().await.unwrap();
+ assert_eq!(
+ draining.status(),
+ 503,
+ "new HTTP work is refused once draining starts"
+ );
+ // The socket is still ours: connect succeeds. This is the window the
+ // harness used to treat as "process exited".
+ std::net::TcpStream::connect(addr).expect("port stays bound while draining");
+
+ tx.send(ShutdownPhase::Released).unwrap();
+ server.await.unwrap();
+
+ let mut refused = false;
+ for _ in 0..20 {
+ if std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(50))
+ .is_err()
+ {
+ refused = true;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert!(
+ refused,
+ "port must close once the shutdown flush releases it"
+ );
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn liveness_stays_200_while_other_routes_refuse() {
+ let gate = DrainGate::new();
+ let app = hold_port_while_draining(
+ Router::new()
+ .route("/health/live", axum::routing::get(|| async { "live" }))
+ .route("/health/ready", axum::routing::get(|| async { "ready" })),
+ gate.clone(),
+ );
+ let listener = bind_listener("127.0.0.1:0".parse().unwrap(), "test-live").unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (tx, rx) = tokio::sync::watch::channel(ShutdownPhase::Serving);
+ let server = tokio::spawn(async move {
+ serve_on(app, listener, "test-live", None, rx)
+ .await
+ .unwrap();
+ });
+ let client = reqwest::Client::new();
+ let live = format!("http://{addr}/health/live");
+ let ready = format!("http://{addr}/health/ready");
+ for _ in 0..50 {
+ if client.get(&live).send().await.is_ok() {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ gate.begin();
+ assert_eq!(client.get(&live).send().await.unwrap().status(), 200);
+ assert_eq!(client.get(&ready).send().await.unwrap().status(), 503);
+ assert_eq!(
+ gate.in_flight(),
+ 0,
+ "a refused request must not be counted in flight"
+ );
+ tx.send(ShutdownPhase::Released).unwrap();
+ server.await.unwrap();
+ }
+}
+
//
// These live as an in-crate unit test module (not `tests/tls.rs`) because
// `serve` / `build_tls_config` / `ensure_tls_cert` are private items of a
@@ -4984,6 +5252,49 @@ mod auto_port_tests {
assert_eq!(resolve_available_data_dir(d), d);
}
+ #[test]
+ fn a_busy_lock_recorded_against_a_dead_pid_does_not_move_when_readable() {
+ let t = tempfile::tempdir().unwrap();
+ let d = t.path().join("data");
+ std::fs::create_dir_all(&d).unwrap();
+ let dead = reaped_pid();
+ let lock_path = d.join("node.lock");
+ std::fs::write(&lock_path, format!("{dead}\n")).unwrap();
+ let holder = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&lock_path)
+ .unwrap();
+ holder.try_lock().unwrap();
+ let readable = std::fs::read_to_string(&lock_path)
+ .ok()
+ .is_some_and(|text| text.trim().parse::<u32>().ok() == Some(dead));
+ let ds = d.to_str().unwrap();
+ if readable {
+ // Advisory lock: the PID can be shown to be dead, so --auto-port
+ // stays on this directory and the engine reclaims the lock.
+ assert_eq!(resolve_available_data_dir(ds), ds);
+ } else {
+ // Mandatory lock hides the PID. A live handle still counts as held.
+ assert_eq!(resolve_available_data_dir(ds), format!("{ds}-2"));
+ }
+ drop(holder);
+ }
+
+ fn reaped_pid() -> u32 {
+ let mut cmd = if cfg!(windows) {
+ let mut cmd = std::process::Command::new("cmd");
+ cmd.args(["/C", "exit", "0"]);
+ cmd
+ } else {
+ std::process::Command::new("true")
+ };
+ let mut child = cmd.spawn().expect("spawn a process that exits");
+ let pid = child.id();
+ child.wait().unwrap();
+ pid
+ }
+
#[test]
fn held_data_dir_moves_to_a_sibling() {
let t = tempfile::tempdir().unwrap();