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(autoindex): make bulk request timeout configurable

buger5f62d44ea6d0
diff --git a/engine/crates/xerj-autoindex/src/cli.rs b/engine/crates/xerj-autoindex/src/cli.rs
index c046d6fe6..b3c915f88 100644
--- a/engine/crates/xerj-autoindex/src/cli.rs
+++ b/engine/crates/xerj-autoindex/src/cli.rs
@@ -9,6 +9,7 @@ pub struct IndexCfg {
pub api_key: Option<String>,
pub workers: usize,
pub bulk_mb: usize,
+ pub bulk_timeout_secs: u64,
pub prefix: String,
pub state_dir: Option<PathBuf>,
pub fresh: bool,
@@ -60,6 +61,9 @@ pub fn print_help() {
--api-key <K> Authorization header (or env XERJ_API_KEY)\n\
--workers <N> extract workers (default min(cores,8))\n\
--bulk-mb <N> bulk cut size in MB (default 8)\n\
+ --bulk-timeout-secs <N>\n\
+ bulk HTTP request timeout in seconds (default 300;\n\
+ valid range 1..=3600)\n\
--prefix <P> index prefix (default ax)\n\
--state-dir <PATH> resume journal location (default ~/.xerj/autoindex/<hash>/)\n\
--fresh ignore existing journal, restart (ids stay idempotent)\n\
@@ -99,6 +103,8 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.unwrap_or(8)
.min(8);
let mut bulk_mb = 8usize;
+ let mut bulk_timeout_secs = 300u64;
+ let mut bulk_timeout_explicit = false;
let mut prefix = "ax".to_string();
let mut state_dir: Option<PathBuf> = None;
let mut fresh = false;
@@ -127,6 +133,17 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
.and_then(|s| s.parse().ok())
.ok_or("--bulk-mb needs a number")?
}
+ "--bulk-timeout-secs" => {
+ bulk_timeout_explicit = true;
+ bulk_timeout_secs = it
+ .next()
+ .ok_or("--bulk-timeout-secs needs a value in seconds")?
+ .parse()
+ .map_err(|_| "--bulk-timeout-secs needs an integer in the range 1..=3600")?;
+ if !(1..=3_600).contains(&bulk_timeout_secs) {
+ return Err("--bulk-timeout-secs must be in the range 1..=3600 seconds".into());
+ }
+ }
"--in-flight" => {
let _ = it.next(); // reserved (bulks are worker-synchronous in v1)
}
@@ -168,6 +185,9 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
}
match (sub.as_deref(), folder) {
+ (Some("map"), _) if bulk_timeout_explicit => {
+ Err("--bulk-timeout-secs applies only to indexing, not `autoindex map`".into())
+ }
(Some("map"), _) => Ok(Cmd::Map(MapCfg {
url,
api_key,
@@ -175,6 +195,9 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
json,
dataset,
})),
+ (Some("status"), _) if bulk_timeout_explicit => {
+ Err("--bulk-timeout-secs applies only to indexing, not `autoindex status`".into())
+ }
(Some("status"), _) => Ok(Cmd::Status(StatusCfg {
url,
api_key,
@@ -187,6 +210,7 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
api_key,
workers: workers.max(1),
bulk_mb: bulk_mb.clamp(1, 24),
+ bulk_timeout_secs,
prefix,
state_dir,
fresh,
@@ -201,3 +225,54 @@ pub fn parse(args: Vec<String>) -> Result<Cmd, String> {
_ => Ok(Cmd::Help),
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::{parse, Cmd};
+
+ fn index(args: &[&str]) -> super::IndexCfg {
+ match parse(args.iter().map(|s| s.to_string()).collect()).unwrap() {
+ Cmd::Index(cfg) => cfg,
+ other => panic!("expected index config, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn bulk_timeout_defaults_to_300_seconds() {
+ assert_eq!(index(&["data"]).bulk_timeout_secs, 300);
+ }
+
+ #[test]
+ fn bulk_timeout_accepts_custom_bounded_value() {
+ assert_eq!(
+ index(&["data", "--bulk-timeout-secs", "3600"]).bulk_timeout_secs,
+ 3600
+ );
+ }
+
+ #[test]
+ fn bulk_timeout_rejects_missing_non_numeric_zero_and_too_large() {
+ for args in [
+ vec!["data", "--bulk-timeout-secs"],
+ vec!["data", "--bulk-timeout-secs", "slow"],
+ vec!["data", "--bulk-timeout-secs", "0"],
+ vec!["data", "--bulk-timeout-secs", "3601"],
+ ] {
+ let err = parse(args.into_iter().map(str::to_string).collect()).unwrap_err();
+ assert!(err.contains("--bulk-timeout-secs"), "{err}");
+ }
+ }
+
+ #[test]
+ fn bulk_timeout_is_rejected_for_non_index_subcommands_in_any_position() {
+ for args in [
+ vec!["map", "--bulk-timeout-secs", "900"],
+ vec!["--bulk-timeout-secs", "900", "map"],
+ vec!["status", "--bulk-timeout-secs", "900"],
+ vec!["--bulk-timeout-secs", "900", "status"],
+ ] {
+ let err = parse(args.into_iter().map(str::to_string).collect()).unwrap_err();
+ assert!(err.contains("applies only to indexing"), "{err}");
+ }
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/esclient.rs b/engine/crates/xerj-autoindex/src/esclient.rs
index 3b4273345..e5bc2348b 100644
--- a/engine/crates/xerj-autoindex/src/esclient.rs
+++ b/engine/crates/xerj-autoindex/src/esclient.rs
@@ -10,6 +10,9 @@ pub struct Es {
base: String,
http: reqwest::blocking::Client,
api_key: Option<String>,
+ bulk_timeout: Duration,
+ retry_initial_delay: Duration,
+ retry_max_delay: Duration,
}
pub struct BulkOutcome {
@@ -23,6 +26,30 @@ pub struct BulkOutcome {
impl Es {
pub fn new(url: &str, api_key: Option<String>) -> Result<Self> {
+ Self::with_bulk_timeout(url, api_key, 300)
+ }
+
+ pub fn with_bulk_timeout(
+ url: &str,
+ api_key: Option<String>,
+ bulk_timeout_secs: u64,
+ ) -> Result<Self> {
+ Self::with_bulk_policy(
+ url,
+ api_key,
+ Duration::from_secs(bulk_timeout_secs),
+ Duration::from_millis(250),
+ Duration::from_secs(8),
+ )
+ }
+
+ fn with_bulk_policy(
+ url: &str,
+ api_key: Option<String>,
+ bulk_timeout: Duration,
+ retry_initial_delay: Duration,
+ retry_max_delay: Duration,
+ ) -> Result<Self> {
let http = reqwest::blocking::Client::builder()
.timeout(Duration::from_secs(300))
.danger_accept_invalid_certs(true)
@@ -32,6 +59,9 @@ impl Es {
base: url.trim_end_matches('/').to_string(),
http,
api_key,
+ bulk_timeout,
+ retry_initial_delay,
+ retry_max_delay,
})
}
@@ -58,9 +88,10 @@ impl Es {
mut f: impl FnMut() -> Result<reqwest::blocking::Response>,
parse: impl Fn(reqwest::blocking::Response) -> Result<T>,
) -> Result<T> {
- let mut delay = Duration::from_millis(250);
+ const MAX_ATTEMPTS: usize = 6;
+ let mut delay = self.retry_initial_delay;
let mut last_err = None;
- for _ in 0..6 {
+ for attempt in 0..MAX_ATTEMPTS {
match f() {
Ok(resp) => {
let status = resp.status();
@@ -72,8 +103,10 @@ impl Es {
}
Err(e) => last_err = Some(e),
}
- std::thread::sleep(delay);
- delay = (delay * 2).min(Duration::from_secs(8));
+ if attempt + 1 < MAX_ATTEMPTS {
+ std::thread::sleep(delay);
+ delay = (delay * 2).min(self.retry_max_delay);
+ }
}
Err(last_err.unwrap_or_else(|| anyhow!("{what}: retries exhausted")))
}
@@ -101,14 +134,7 @@ impl Es {
pub fn bulk(&self, body: Vec<u8>) -> Result<BulkOutcome> {
self.with_retry(
"_bulk",
- || {
- self.req(reqwest::Method::POST, "/_bulk")
- .header("Content-Type", "application/x-ndjson")
- .header("X-Turbo", "1")
- .body(body.clone())
- .send()
- .map_err(|e| anyhow!("bulk send: {e}"))
- },
+ || self.send_bulk(body.clone()),
|resp| {
let status = resp.status();
if !status.is_success() {
@@ -159,6 +185,16 @@ impl Es {
)
}
+ fn send_bulk(&self, body: Vec<u8>) -> Result<reqwest::blocking::Response> {
+ self.req(reqwest::Method::POST, "/_bulk")
+ .timeout(self.bulk_timeout)
+ .header("Content-Type", "application/x-ndjson")
+ .header("X-Turbo", "1")
+ .body(body)
+ .send()
+ .with_context(|| format!("bulk send (request timeout {:?})", self.bulk_timeout))
+ }
+
pub fn refresh(&self, pattern: &str) -> Result<()> {
self.with_retry(
"refresh",
@@ -257,3 +293,196 @@ impl Es {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::Es;
+ use std::io::Read;
+ use std::io::Write;
+ use std::net::TcpListener;
+ use std::sync::{mpsc, Arc, Mutex};
+ use std::time::{Duration, Instant};
+
+ #[test]
+ fn bulk_request_uses_custom_timeout_and_drops_timed_out_connection() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let (closed_tx, closed_rx) = mpsc::channel();
+ let server = std::thread::spawn(move || {
+ let (mut stream, _) = listener.accept().unwrap();
+ stream
+ .set_read_timeout(Some(Duration::from_secs(4)))
+ .unwrap();
+ let mut request = [0u8; 4096];
+ let read = stream.read(&mut request).unwrap();
+ assert!(String::from_utf8_lossy(&request[..read]).contains("POST /_bulk"));
+ std::thread::sleep(Duration::from_millis(1300));
+ let closed = stream.read(&mut request).map(|n| n == 0).unwrap_or(true);
+ closed_tx.send(closed).unwrap();
+ });
+ let es = Es::with_bulk_policy(
+ &format!("http://{address}"),
+ None,
+ Duration::from_secs(1),
+ Duration::from_millis(10),
+ Duration::from_millis(20),
+ )
+ .unwrap();
+ let started = Instant::now();
+ let err = es.send_bulk(b"{}\n".to_vec()).unwrap_err();
+ let elapsed = started.elapsed();
+ assert!(format!("{err:#}").contains("timed out"), "{err:#}");
+ assert!(elapsed >= Duration::from_millis(800), "{elapsed:?}");
+ assert!(elapsed < Duration::from_secs(3), "{elapsed:?}");
+ assert!(closed_rx.recv_timeout(Duration::from_secs(4)).unwrap());
+ server.join().unwrap();
+ }
+
+ fn read_request(stream: &mut std::net::TcpStream) -> Vec<u8> {
+ stream
+ .set_read_timeout(Some(Duration::from_secs(2)))
+ .unwrap();
+ let mut request = Vec::new();
+ let mut buffer = [0u8; 4096];
+ loop {
+ let count = stream.read(&mut buffer).unwrap();
+ request.extend_from_slice(&buffer[..count]);
+ if let Some(header_end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
+ let headers = String::from_utf8_lossy(&request[..header_end]);
+ let length = headers
+ .lines()
+ .find_map(|line| {
+ line.to_ascii_lowercase()
+ .strip_prefix("content-length:")
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ })
+ .unwrap_or(0);
+ if request.len() >= header_end + 4 + length {
+ break;
+ }
+ }
+ }
+ request
+ }
+
+ fn success(stream: &mut std::net::TcpStream) {
+ let body = br#"{"errors":false,"items":[]}"#;
+ write!(
+ stream,
+ "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
+ body.len()
+ )
+ .unwrap();
+ stream.write_all(body).unwrap();
+ }
+
+ #[test]
+ fn retry_path_recovers_after_one_bulk_timeout() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let server = std::thread::spawn(move || {
+ let (mut first, _) = listener.accept().unwrap();
+ read_request(&mut first);
+ let first = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_millis(120));
+ drop(first);
+ });
+ let (mut second, _) = listener.accept().unwrap();
+ read_request(&mut second);
+ success(&mut second);
+ first.join().unwrap();
+ });
+ let es = Es::with_bulk_policy(
+ &format!("http://{address}"),
+ None,
+ Duration::from_millis(50),
+ Duration::from_millis(10),
+ Duration::from_millis(20),
+ )
+ .unwrap();
+ let outcome = es.bulk(b"{\"index\":{}}\n{}\n".to_vec()).unwrap();
+ assert_eq!(outcome.item_errors, 0);
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn all_timeout_retry_path_is_bounded_to_six_attempts_without_final_sleep() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let accepted = Arc::new(Mutex::new(0usize));
+ let accepted_server = accepted.clone();
+ let server = std::thread::spawn(move || {
+ let mut handlers = Vec::new();
+ for _ in 0..6 {
+ let (mut stream, _) = listener.accept().unwrap();
+ *accepted_server.lock().unwrap() += 1;
+ handlers.push(std::thread::spawn(move || {
+ read_request(&mut stream);
+ std::thread::sleep(Duration::from_millis(100));
+ }));
+ }
+ for handler in handlers {
+ handler.join().unwrap();
+ }
+ });
+ let es = Es::with_bulk_policy(
+ &format!("http://{address}"),
+ None,
+ Duration::from_millis(25),
+ Duration::from_millis(10),
+ Duration::from_millis(20),
+ )
+ .unwrap();
+ let started = Instant::now();
+ let error = match es.bulk(b"{}\n".to_vec()) {
+ Ok(_) => panic!("all six delayed responses unexpectedly succeeded"),
+ Err(error) => error,
+ };
+ let elapsed = started.elapsed();
+ assert!(format!("{error:#}").contains("timed out"), "{error:#}");
+ assert_eq!(*accepted.lock().unwrap(), 6);
+ // Six 25ms attempts plus 10+20+20+20+20ms backoffs. A sixth
+ // post-failure sleep would push this past the deliberately tight cap.
+ assert!(elapsed < Duration::from_millis(260), "{elapsed:?}");
+ server.join().unwrap();
+ }
+
+ #[test]
+ fn ambiguous_dropped_response_retries_byte_identical_bulk_body() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let address = listener.local_addr().unwrap();
+ let requests = Arc::new(Mutex::new(Vec::new()));
+ let requests_server = requests.clone();
+ let server = std::thread::spawn(move || {
+ let (mut first, _) = listener.accept().unwrap();
+ requests_server
+ .lock()
+ .unwrap()
+ .push(read_request(&mut first));
+ drop(first); // backend may have committed, but response is ambiguous
+ let (mut second, _) = listener.accept().unwrap();
+ requests_server
+ .lock()
+ .unwrap()
+ .push(read_request(&mut second));
+ success(&mut second);
+ });
+ let body = b"{\"index\":{\"_index\":\"i\",\"_id\":\"stable-id\"}}\n{\"v\":1}\n".to_vec();
+ let es = Es::with_bulk_policy(
+ &format!("http://{address}"),
+ None,
+ Duration::from_millis(100),
+ Duration::from_millis(10),
+ Duration::from_millis(20),
+ )
+ .unwrap();
+ es.bulk(body.clone()).unwrap();
+ server.join().unwrap();
+ let requests = requests.lock().unwrap();
+ assert_eq!(requests.len(), 2);
+ for request in requests.iter() {
+ let offset = request.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
+ assert_eq!(&request[offset..], body.as_slice());
+ }
+ }
+}
diff --git a/engine/crates/xerj-autoindex/src/lib.rs b/engine/crates/xerj-autoindex/src/lib.rs
index 643c6f6d7..39e487a16 100644
--- a/engine/crates/xerj-autoindex/src/lib.rs
+++ b/engine/crates/xerj-autoindex/src/lib.rs
@@ -190,7 +190,13 @@ fn build_mapping(specs: &[infer::FieldSpec]) -> Value {
fn run_index(cfg: IndexCfg) -> Result<i32> {
let t0 = Instant::now();
- let es = Es::new(&cfg.url, cfg.api_key.clone())?;
+ if !cfg.quiet {
+ eprintln!(
+ "autoindex: bulk HTTP request timeout: {}s",
+ cfg.bulk_timeout_secs
+ );
+ }
+ let es = Es::with_bulk_timeout(&cfg.url, cfg.api_key.clone(), cfg.bulk_timeout_secs)?;
es.ping()?;
let files = walk::walk(&cfg.root, cfg.follow_symlinks)?;
@@ -224,8 +230,14 @@ fn run_index(cfg: IndexCfg) -> Result<i32> {
.state_dir
.clone()
.unwrap_or_else(|| state::default_state_dir(&root_str, &cfg.url, &cfg.prefix));
- let mut journal =
- state::Journal::open(&state_dir, &root_str, &cfg.url, &cfg.prefix, cfg.fresh)?;
+ let mut journal = state::Journal::open(
+ &state_dir,
+ &root_str,
+ &cfg.url,
+ &cfg.prefix,
+ cfg.bulk_timeout_secs,
+ cfg.fresh,
+ )?;
let run_id = journal.run_id.clone();
if journal.resumed && !cfg.quiet {
eprintln!(
diff --git a/engine/crates/xerj-autoindex/src/state.rs b/engine/crates/xerj-autoindex/src/state.rs
index ed15e57b7..a69118fd4 100644
--- a/engine/crates/xerj-autoindex/src/state.rs
+++ b/engine/crates/xerj-autoindex/src/state.rs
@@ -26,6 +26,49 @@ pub struct PlanDataset {
pub file_count: usize,
}
+#[cfg(test)]
+mod tests {
+ use super::Journal;
+
+ #[test]
+ fn legacy_journal_can_resume_with_a_custom_operational_timeout() {
+ let dir = tempfile::tempdir().unwrap();
+ std::fs::write(
+ dir.path().join("journal.ndjson"),
+ concat!(
+ "{\"v\":1,\"kind\":\"run\",\"root\":\"root\",\"url\":\"url\",",
+ "\"prefix\":\"prefix\",\"run_id\":\"legacy\"}\n"
+ ),
+ )
+ .unwrap();
+ let journal = Journal::open(dir.path(), "root", "url", "prefix", 3600, false).unwrap();
+ assert!(journal.resumed);
+ drop(journal);
+ let text = std::fs::read_to_string(dir.path().join("journal.ndjson")).unwrap();
+ assert!(text.contains("\"kind\":\"resume\""));
+ assert!(text.contains("\"bulk_timeout_secs\":3600"));
+ }
+
+ #[test]
+ fn fresh_journal_records_each_runs_effective_operational_timeout() {
+ let dir = tempfile::tempdir().unwrap();
+ let journal = Journal::open(dir.path(), "root", "url", "prefix", 3600, true).unwrap();
+ drop(journal);
+ let text = std::fs::read_to_string(dir.path().join("journal.ndjson")).unwrap();
+ assert!(text.contains("\"bulk_timeout_secs\":3600"));
+ assert!(
+ Journal::open(dir.path(), "root", "url", "prefix", 900, false)
+ .unwrap()
+ .resumed
+ );
+ let text = std::fs::read_to_string(dir.path().join("journal.ndjson")).unwrap();
+ assert!(text.contains("\"kind\":\"run\""));
+ assert!(text.contains("\"bulk_timeout_secs\":3600"));
+ assert!(text.contains("\"kind\":\"resume\""));
+ assert!(text.contains("\"bulk_timeout_secs\":900"));
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileAssignment {
pub rel: String,
@@ -87,6 +130,7 @@ impl Journal {
root: &str,
url: &str,
prefix: &str,
+ bulk_timeout_secs: u64,
fresh: bool,
) -> Result<Journal> {
std::fs::create_dir_all(state_dir)
@@ -168,11 +212,13 @@ impl Journal {
if is_new {
j.append(&serde_json::json!({
"v": 1, "kind": "run", "root": root, "url": url, "prefix": prefix,
+ "bulk_timeout_secs": bulk_timeout_secs,
"run_id": run_id, "started": chrono::Utc::now().to_rfc3339(),
}))?;
} else {
j.append(&serde_json::json!({
- "kind": "resume", "at": chrono::Utc::now().to_rfc3339(),
+ "kind": "resume", "bulk_timeout_secs": bulk_timeout_secs,
+ "at": chrono::Utc::now().to_rfc3339(),
}))?;
}
Ok(j)