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(api): order _eql/search events by @timestamp instant across alias members before truncating (#567)

xerj-org31c3f294edb6
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 34d2ed321..fe9c9ff13 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -33188,6 +33188,42 @@ fn glob_match(pattern: &str, name: &str) -> bool {
// POST /{index}/_eql/search — EQL search stub
// ─────────────────────────────────────────────────────────────────────────────
+/// Compare two EQL timestamp-field values (pulled from each event's `_source`)
+/// for the ascending merge sort (#567). Epoch numbers compare numerically (one
+/// unit per corpus). Strings are parsed as RFC3339 / ISO-8601 and compared as
+/// real instants — NOT byte-wise: a raw string compare misorders mixed
+/// fractional-second precision (`…:01.500Z` vs `…:01Z`, since `.` < `Z`) and
+/// non-UTC offsets (`…+05:00` is an earlier instant than the lexically-smaller
+/// `…Z`), which are the norm in SIEM/log corpora. `chrono::DateTime` orders by
+/// the UTC instant, so both are handled. An unparseable value falls back to a
+/// deterministic byte order; a missing field sorts last so a malformed doc never
+/// displaces a real earliest hit.
+fn eql_timestamp_cmp(a: Option<&Value>, b: Option<&Value>) -> std::cmp::Ordering {
+ use std::cmp::Ordering::{Equal, Greater, Less};
+ match (a, b) {
+ (Some(x), Some(y)) => {
+ if let (Some(nx), Some(ny)) = (x.as_f64(), y.as_f64()) {
+ nx.partial_cmp(&ny).unwrap_or(Equal)
+ } else if let (Some(sx), Some(sy)) = (x.as_str(), y.as_str()) {
+ match (
+ chrono::DateTime::parse_from_rfc3339(sx),
+ chrono::DateTime::parse_from_rfc3339(sy),
+ ) {
+ (Ok(dx), Ok(dy)) => dx.cmp(&dy),
+ // Non-RFC3339 formats the engine may still accept: fall back
+ // to a deterministic byte order rather than misrank silently.
+ _ => sx.cmp(sy),
+ }
+ } else {
+ Equal
+ }
+ }
+ (Some(_), None) => Less,
+ (None, Some(_)) => Greater,
+ (None, None) => Equal,
+ }
+}
+
pub async fn eql_search(
State(state): State<AppState>,
Path(index): Path<String>,
@@ -33251,6 +33287,16 @@ pub async fn eql_search(
// Translate EQL -> xerj DSL, then run it through the normal search path.
let inner_query = eql_to_query(&eql);
let size = body.get("size").and_then(Value::as_u64).unwrap_or(10);
+ // #567: EQL orders single-event results by the timestamp field ascending
+ // (default `@timestamp`, overridable via `timestamp_field`). The alias
+ // fan-out below must sort the MERGED events by it before truncating to
+ // `size`, otherwise the surviving page is biased toward the earlier-iterated
+ // members rather than the globally-earliest events.
+ let ts_field = body
+ .get("timestamp_field")
+ .and_then(Value::as_str)
+ .unwrap_or("@timestamp")
+ .to_string();
// Fan out to every member of a multi-index alias (#451 `_eql` arm):
// eql_search used Engine::get_index -> aliased.first(), silently returning
@@ -33269,7 +33315,24 @@ pub async fn eql_search(
} else {
json!({ "bool": { "must": [inner_query], "filter": filters } })
};
- let search_body = json!({ "query": effective_query, "size": size, "from": 0 });
+ // Sort each member ascending by the timestamp field: a member with more than
+ // `size` matches must contribute its EARLIEST events to the merge, not its
+ // top-scored ones, or the global-earliest page can miss them. `unmapped_type`
+ // is ES's escape hatch so a member index without the timestamp field is not a
+ // 400 ("No mapping found for [@timestamp] in order to sort on") — XERJ's EQL,
+ // unlike ES, does not require a timestamp field, so this must degrade to
+ // unsorted for such a corpus rather than fail.
+ let mut ts_sort = serde_json::Map::new();
+ ts_sort.insert(
+ ts_field.clone(),
+ json!({ "order": "asc", "unmapped_type": "date" }),
+ );
+ let search_body = json!({
+ "query": effective_query,
+ "size": size,
+ "from": 0,
+ "sort": [Value::Object(ts_sort)],
+ });
let req = match xerj_query::parse_request(&search_body)
.map_err(|e| xerj_common::XerjError::invalid_query(e.to_string()))
@@ -33299,6 +33362,16 @@ pub async fn eql_search(
Err(e) => return ApiError::new(xerj_common::XerjError::from(e)).into_response(),
}
}
+ // #567: order the merged events by the timestamp field ascending BEFORE
+ // truncating, so the returned page is the globally-earliest `size` events
+ // (ES EQL semantics), not whichever alias members were iterated first. Stable
+ // so events with equal timestamps keep member/order determinism.
+ events.sort_by(|a, b| {
+ eql_timestamp_cmp(
+ a.get("_source").and_then(|s| s.get(&ts_field)),
+ b.get("_source").and_then(|s| s.get(&ts_field)),
+ )
+ });
// Apply the EQL `size` limit across the merged member results.
events.truncate(size as usize);
let took_ms = started.elapsed().as_millis() as u64;
diff --git a/engine/crates/xerj-api/tests/eql_through_alias_sees_every_member.rs b/engine/crates/xerj-api/tests/eql_through_alias_sees_every_member.rs
index 0eaa705e0..95ecb8a6f 100644
--- a/engine/crates/xerj-api/tests/eql_through_alias_sees_every_member.rs
+++ b/engine/crates/xerj-api/tests/eql_through_alias_sees_every_member.rs
@@ -181,3 +181,182 @@ async fn eql_search_through_a_filtered_alias_honours_the_filter_on_every_member(
member name: {body}"
);
}
+
+/// #567: when the summed match count across alias members exceeds `size`, the
+/// returned page must be the globally-earliest by `@timestamp` (ES EQL ascending
+/// order), not biased toward the earlier-iterated member. Two members with
+/// interleaving timestamps and a `size` below the combined count.
+#[tokio::test]
+async fn eql_events_are_timestamp_ordered_across_members_before_truncation() {
+ let (app, _dir) = app().await;
+
+ // ts-a at odd seconds, ts-b at even — the global @timestamp order interleaves
+ // the two members, so a member-order concat + truncate would return the wrong
+ // page.
+ let members: [(&str, &[u32]); 2] = [("ts-a", &[1, 3, 5]), ("ts-b", &[2, 4, 6])];
+ for (member, secs) in members {
+ let (st, _) = call(
+ &app,
+ "PUT",
+ &format!("/{member}"),
+ json!({"mappings": {"properties": {
+ "status": {"type": "keyword"},
+ "@timestamp": {"type": "date"}
+ }}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create {member}");
+ for s in secs {
+ let (st, _) = call(
+ &app,
+ "POST",
+ &format!("/{member}/_doc/{member}-{s}"),
+ json!({ "status": "active", "@timestamp": format!("2026-01-01T00:00:0{s}Z") }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::CREATED, "index {member}-{s}");
+ }
+ let (st, _) = call(&app, "POST", &format!("/{member}/_refresh"), Value::Null).await;
+ assert_eq!(st, StatusCode::OK, "refresh {member}");
+ }
+ let (st, _) = call(
+ &app,
+ "POST",
+ "/_aliases",
+ json!({"actions": [
+ {"add": {"index": "ts-a", "alias": "ts-all"}},
+ {"add": {"index": "ts-b", "alias": "ts-all"}}
+ ]}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create alias ts-all");
+
+ // 3 of 6 total: must be the three earliest by @timestamp (01, 02, 03), which
+ // spans BOTH members — not ts-a's first three (01, 03, 05).
+ let (status, body) = call(
+ &app,
+ "POST",
+ "/ts-all/_eql/search",
+ json!({ "query": "any where status == \"active\"", "size": 3 }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "_eql/search status: {body}");
+
+ let stamps: Vec<String> = body
+ .pointer("/hits/events")
+ .and_then(Value::as_array)
+ .expect("events array")
+ .iter()
+ .map(|e| {
+ e.pointer("/_source/@timestamp")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string()
+ })
+ .collect();
+ assert_eq!(
+ stamps,
+ vec![
+ "2026-01-01T00:00:01Z".to_string(),
+ "2026-01-01T00:00:02Z".to_string(),
+ "2026-01-01T00:00:03Z".to_string(),
+ ],
+ "the returned page must be the globally-earliest by @timestamp across members, not the \
+ first member's earliest three (#567): {body}"
+ );
+ assert_eq!(
+ body.pointer("/hits/total/value").and_then(Value::as_u64),
+ Some(6),
+ "total must be the true summed match count: {body}"
+ );
+}
+
+/// #567 (correctness): the cross-member merge must order by the true INSTANT, not
+/// the raw timestamp string. Mixed fractional-second precision and non-UTC
+/// offsets are the norm in log/SIEM corpora, and a lexical byte compare misorders
+/// both: `…:01.500Z` sorts before `…:01Z` (`.` < `Z`), and `…+05:00` — an earlier
+/// instant — sorts after the lexically-smaller `…Z`.
+#[tokio::test]
+async fn eql_events_order_by_instant_not_lexical_string() {
+ let (app, _dir) = app().await;
+ // True chronological order of the four events:
+ // 2026-01-01T05:00:00+05:00 == 00:00:00.000Z
+ // 2026-01-01T00:00:01Z == 00:00:01.000Z
+ // 2026-01-01T00:00:01.500Z == 00:00:01.500Z
+ // 2026-01-01T01:00:00Z == 01:00:00.000Z
+ let members: [(&str, &[&str]); 2] = [
+ (
+ "iz-a",
+ &["2026-01-01T05:00:00+05:00", "2026-01-01T00:00:01.500Z"],
+ ),
+ ("iz-b", &["2026-01-01T00:00:01Z", "2026-01-01T01:00:00Z"]),
+ ];
+ for (member, stamps) in members {
+ let (st, _) = call(
+ &app,
+ "PUT",
+ &format!("/{member}"),
+ json!({"mappings": {"properties": {
+ "status": {"type": "keyword"},
+ "@timestamp": {"type": "date"}
+ }}}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create {member}");
+ for (i, ts) in stamps.iter().enumerate() {
+ let (st, _) = call(
+ &app,
+ "POST",
+ &format!("/{member}/_doc/{member}-{i}"),
+ json!({ "status": "active", "@timestamp": ts }),
+ )
+ .await;
+ assert_eq!(st, StatusCode::CREATED, "index {member}-{i} ({ts})");
+ }
+ let (st, _) = call(&app, "POST", &format!("/{member}/_refresh"), Value::Null).await;
+ assert_eq!(st, StatusCode::OK, "refresh {member}");
+ }
+ let (st, _) = call(
+ &app,
+ "POST",
+ "/_aliases",
+ json!({"actions": [
+ {"add": {"index": "iz-a", "alias": "iz"}},
+ {"add": {"index": "iz-b", "alias": "iz"}}
+ ]}),
+ )
+ .await;
+ assert_eq!(st, StatusCode::OK, "create alias iz");
+
+ let (status, body) = call(
+ &app,
+ "POST",
+ "/iz/_eql/search",
+ json!({ "query": "any where status == \"active\"", "size": 4 }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "_eql/search status: {body}");
+
+ let stamps: Vec<String> = body
+ .pointer("/hits/events")
+ .and_then(Value::as_array)
+ .expect("events array")
+ .iter()
+ .map(|e| {
+ e.pointer("/_source/@timestamp")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string()
+ })
+ .collect();
+ assert_eq!(
+ stamps,
+ vec![
+ "2026-01-01T05:00:00+05:00".to_string(),
+ "2026-01-01T00:00:01Z".to_string(),
+ "2026-01-01T00:00:01.500Z".to_string(),
+ "2026-01-01T01:00:00Z".to_string(),
+ ],
+ "EQL events must be ordered by the true instant, not the lexical string (#567): {body}"
+ );
+}