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(dates): pin a declared date_nanos to nanoseconds, add numeric_type, back-fill legacy indices (#889) (#913)

xerj-org5a6c09872e88
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0209c6664..fa5bc1ced 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -234,6 +234,113 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
separate work: it has to prove the #825 union/sum contract with tombstones
present, and is not attempted here.
+- **A `date_nanos` field no longer guesses its epoch scale value by value, and
+ an index written before that flag existed recovers its scale instead of
+ guessing** ([#889](https://github.com/xerj-org/xerj/issues/889), follow-up to
+ [#790](https://github.com/xerj-org/xerj/issues/790)). #790 made a date
+ field's epoch scale a property of the MAPPING and pinned a declared `date` to
+ milliseconds, but deliberately left `date_nanos` on the old per-VALUE guess
+ (">= 4 fractional-second digits means nanoseconds"). The defect #790
+ describes therefore survived inside `date_nanos`: a column holding both
+ `2020-06-06T06:06:06.123456Z` and `2025-01-01T00:00:00Z` gave the first a
+ nanosecond key (~1.59e18) and the second a millisecond one (~1.74e12), six
+ orders of magnitude apart, so 2025 sorted before 2020 and a range bound could
+ not reach both.
+
+ Pinning `date_nanos` to nanoseconds is not safe on its own — it moves a
+ `date_nanos` field six orders of magnitude away from a `date` field in a
+ cross-index sort — so the prerequisite landed with it:
+
+ - **ES `numeric_type` on a field sort** (`numeric_type: date` /
+ `date_nanos`). It forces the epoch scale every participating index produces
+ sort values on, which is the only way a sort over a field mapped `date`
+ here and `date_nanos` there compares chronologically. The `search_after`
+ cursor is normalised on the same forced scale, so paging works in that one
+ space. `long`/`double` are parsed and ignored (xerj already compares
+ numeric sort keys as `f64`), and unlike ES, xerj does not reject
+ `numeric_type` on a non-numeric field. Without `numeric_type` the raw longs
+ are compared, exactly as ES does and as
+ `tests/es-compat-yaml/yaml/search/240_date_nanos.yml` asserts — that
+ default is unchanged and is pinned by a test.
+ - **`date_nanos` is now uniformly nanosecond-scaled**, including day-first
+ slash dates (`dd/MM/yyyy HH:mm:ss.SSS`), which previously had no nanosecond
+ branch at all and would have re-introduced the mixed-scale split by a
+ different route.
+ - **A NUMERIC date bound is epoch-MILLISECONDS and is converted at the
+ bound, not at the value.** That is ES's own rule — a `date_nanos` field's
+ default format is `strict_date_optional_time_nanos||epoch_millis`, so a
+ bare number is parsed as milliseconds and only then moved to the field's
+ resolution. Moving a `date_nanos` column to nanosecond keys therefore had
+ to move every numeric bound with it: the segment sort-shadow's bounds
+ (`shadow_range_bounds`, which serves both the range doc-values pre-filter
+ and the `_count` shortcut) took a numeric bound verbatim, six orders of
+ magnitude below the keys it bisects. Two shapes reach it — the #788
+ `term`-on-a-date rewrite, which lowers a `term` to the degenerate
+ `range [epoch_ms, epoch_ms]`, and a user-written numeric bound — so on a
+ flushed `date_nanos` index a `term` and a numeric range both matched
+ nothing while the same query answered correctly from the memtable. Bound
+ and key are now on one scale in both directions, and the flush-invariance
+ of both shapes is pinned by a test that asserts pre- AND post-flush.
+ - **One format ladder for both scales.** `date_string_to_epoch` had a
+ separate nanosecond branch that stopped after RFC3339 and
+ `%Y-%m-%dT%H:%M:%S%.f`; the `%Y-%m-%d` date-only fallback existed only in
+ the millisecond branch. A DATE-ONLY value ("2021-01-01") in a `date_nanos`
+ field therefore normalised to nothing at all and was emitted as a raw
+ JSON STRING among i64 epoch keys, where the sort comparator's string arm
+ puts `"` below every digit and the document sorted FIRST ascending
+ whatever its instant — and the segment's sort/range shadow refused to
+ build on that term. Because `numeric_type` forces the nanosecond scale on
+ every participating index, an ordinary `date` field holding a date-only
+ value hit the same hole under a cross-index sort. The ladder is now walked
+ once and the accepted instant rendered on the requested scale at the end,
+ so a format either parses on both scales or on neither. The `search_after`
+ cursor normaliser, which carried a hand-copied second copy of the same
+ ladder whose fallbacks returned milliseconds even on a nanosecond field,
+ now calls the one function.
+ - **Legacy indices are back-filled at open.** `date_precision` is recorded
+ when a field is mapped, so an index created by an older build comes back
+ with no precision at all and every date field falls back to the per-value
+ guess. `schema.json` cannot tell `date` from `date_nanos` — but the raw ES
+ mapping blob beside it (`es_mapping.json`) still carries the original type
+ string, and `Index::open` now recovers the flag from there. Both directions
+ are covered: a legacy `date_nanos` comes back nanosecond-scaled (a blanket
+ default would have silently downgraded it to millisecond resolution) and a
+ legacy `date` comes back millisecond-scaled, i.e. it inherits the #790 fix
+ without a reindex. Nothing on disk is rewritten and no data is reindexed:
+ the epoch keys were always derived at read time from the stored value, so
+ correcting the scale is enough.
+ - **`GET _mapping` reports a `date_nanos` field as `date_nanos`** where the
+ mapping is derived from the schema (it already round-tripped correctly when
+ the raw blob was present). The GET → PUT round trip every reindex helper
+ performs no longer silently downgrades the field.
+
+ **Not fixed, stated plainly:**
+
+ - An index whose `schema.json` predates the flag AND which has no
+ `es_mapping.json` (an index that never went through the ES-compat mapping
+ path) still has no record of `date` vs `date_nanos`, so its date fields
+ keep the legacy per-value guess. Inventing a default there is the silent
+ downgrade this change exists to avoid.
+ - The back-fill reads `{"properties": …}` and `{"mappings": {"properties":
+ …}}`, which is what the mapping API persists. An ES-6-style type wrapper
+ (`{"_doc": {"properties": …}}`) is skipped, and that field then keeps the
+ legacy per-value guess — the same safe fallback, not a new failure mode.
+ - Only STRING-shaped date values move onto the field's scale. A numeric
+ source value (`{"ts": 1591423566123}`) in a `date_nanos` field stays a raw
+ millisecond number in its doc-values column; ES would convert it. A
+ segment holding both shapes ships no column at all and falls to the
+ correct full scan, but two segments that each hold one shape still mix
+ scales in a sort.
+ - `numeric_type` values other than `date`/`date_nanos`/`long`/`double` are
+ lower-cased and then ignored where ES answers 400, and `numeric_type` on a
+ non-numeric field is accepted where ES rejects it.
+ - Sort-value FORMATTING still infers milliseconds vs nanoseconds from the
+ magnitude of the epoch number rather than from the resolved scale
+ (`format_sort_value`, threshold `2 * 10^15`). Unchanged by this work: it
+ reads correctly for every nanosecond instant from 1970-01-24 on
+ (2e15 ns = 2e6 s = 23.1 days) and every millisecond instant below 2e15 ms
+ (~63,000 years past the epoch).
+
- **`autoindex`: a run no longer deletes a sibling corpus's duplicate-alias
catalog documents** ([#905](https://github.com/xerj-org/xerj/issues/905)).
Data loss, and the second of the two holes the #890 review found.
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index e9a7288f6..ceca53ad8 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -4036,8 +4036,12 @@ fn format_sort_value(raw: &Value, format: Option<&str>) -> Value {
return raw.clone();
};
// Numeric sort value → treat as epoch; need to decide ms vs ns by
- // magnitude. Values above ~2 * 10^13 are nanoseconds (more than 600
- // years past epoch in ms); everything else is milliseconds.
+ // magnitude. The split is 2 * 10^15: above it the number is read as
+ // nanoseconds, below it as milliseconds. That is right for every
+ // NANOSECOND instant from 1970-01-24 on (2e15 ns = 2e6 s = 23.1 days) and
+ // every MILLISECOND instant below 2e15 ms (~63,000 years past the epoch),
+ // so only a pre-1970-01-24 nanosecond instant reads as milliseconds.
+ // (The comment used to say ~2 * 10^13, which is not the constant below.)
let n = match raw {
Value::Number(n) => n.as_i64(),
_ => return raw.clone(),
@@ -6561,19 +6565,21 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
},
};
fields.push(sf);
}
Value::Object(obj) => {
for (field_name, spec) in obj {
- let (order, mode, missing, format, unmapped_type) = match spec {
+ let (order, mode, missing, format, unmapped_type, numeric_type) = match spec {
Value::String(ord) => (
parse_sort_order(ord),
SortMode::default(),
SortMissing::default(),
None,
None,
+ None,
),
Value::Object(opts) => {
let order = opts
@@ -6600,7 +6606,16 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
.get("unmapped_type")
.and_then(Value::as_str)
.map(String::from);
- (order, mode, missing, format, unmapped_type)
+ // #889: `numeric_type` forces the scale the sort
+ // values are produced on, so a `date` field in one
+ // index and a `date_nanos` field in another are
+ // compared on ONE epoch scale instead of as raw
+ // longs six orders of magnitude apart.
+ let numeric_type = opts
+ .get("numeric_type")
+ .and_then(Value::as_str)
+ .map(|s| s.to_ascii_lowercase());
+ (order, mode, missing, format, unmapped_type, numeric_type)
}
_ => (
SortOrder::Asc,
@@ -6608,6 +6623,7 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
SortMissing::default(),
None,
None,
+ None,
),
};
let sf = match field_name.as_str() {
@@ -6618,6 +6634,7 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
missing,
format,
unmapped_type,
+ numeric_type,
},
"_doc" => SortField {
field: "_doc".to_string(),
@@ -6626,6 +6643,7 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
missing,
format,
unmapped_type,
+ numeric_type,
},
other => SortField {
field: other.to_string(),
@@ -6634,6 +6652,7 @@ fn parse_sort(sort_val: &Value) -> Vec<xerj_query::sort::SortField> {
missing,
format,
unmapped_type,
+ numeric_type,
},
};
fields.push(sf);
@@ -16919,6 +16938,256 @@ mod date_precision_mapping_tests {
}
}
+#[cfg(test)]
+mod date_nanos_cross_index_sort_tests {
+ use super::*;
+ use axum::{
+ body::{to_bytes, Body},
+ http::Request,
+ };
+ use tower::ServiceExt;
+ use xerj_common::{
+ config::{Config, WalSync},
+ metrics::Metrics,
+ };
+ use xerj_engine::Engine;
+
+ fn test_state() -> AppState {
+ let dir = tempfile::tempdir().expect("tempdir").keep();
+ let mut config = Config::default();
+ config.server.data_dir = dir.to_string_lossy().into_owned();
+ config.storage.wal_sync = WalSync::Async;
+ let metrics = Metrics::new().expect("metrics");
+ let engine = Engine::new(config.clone()).expect("engine");
+ AppState::new(config, engine, metrics)
+ }
+
+ async fn request_json(
+ state: &AppState,
+ method: &str,
+ path: &str,
+ body: Value,
+ ) -> (StatusCode, Value) {
+ let response = crate::router::build_es_compat_router(state.clone())
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(path)
+ .header("content-type", "application/json")
+ .body(Body::from(body.to_string()))
+ .expect("request"),
+ )
+ .await
+ .expect("route response");
+ let status = response.status();
+ let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
+ let json = serde_json::from_slice(&bytes).unwrap_or_else(|error| {
+ panic!(
+ "{method} {path} returned non-JSON ({error}): {}",
+ String::from_utf8_lossy(&bytes)
+ )
+ });
+ (status, json)
+ }
+
+ /// `index`, mapped with a single `timestamp` field of `es_type`, holding
+ /// `docs` as `(id, value)`.
+ async fn build(state: &AppState, index: &str, es_type: &str, docs: &[(&str, &str)]) {
+ let (status, body) = request_json(
+ state,
+ "PUT",
+ &format!("/{index}"),
+ json!({"mappings": {"properties": {"timestamp": {"type": es_type}}}}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ for (id, value) in docs {
+ let (status, body) = request_json(
+ state,
+ "PUT",
+ &format!("/{index}/_doc/{id}"),
+ json!({"timestamp": value}),
+ )
+ .await;
+ assert!(status.is_success(), "{body}");
+ }
+ state
+ .engine
+ .get_index(index)
+ .expect("index")
+ .refresh()
+ .await
+ .expect("refresh");
+ }
+
+ fn ids(json: &Value) -> Vec<String> {
+ json["hits"]["hits"]
+ .as_array()
+ .expect("hits")
+ .iter()
+ .map(|h| h["_id"].as_str().unwrap().to_string())
+ .collect()
+ }
+
+ /// Two indices whose `timestamp` is mapped `date` in one and `date_nanos`
+ /// in the other, with instants that INTERLEAVE chronologically.
+ async fn two_scaled_indices(state: &AppState) {
+ build(
+ state,
+ "nt-ms",
+ "date",
+ &[
+ ("ms-feb", "2021-02-11T08:30:04.828Z"),
+ ("ms-jun", "2021-06-11T04:30:04.828Z"),
+ ],
+ )
+ .await;
+ build(
+ state,
+ "nt-ns",
+ "date_nanos",
+ &[
+ ("ns-apr", "2021-04-15T06:30:04.821123456Z"),
+ ("ns-aug", "2021-08-21T03:30:04.732123456Z"),
+ ],
+ )
+ .await;
+ }
+
+ /// #889: `numeric_type` is what makes a cross-index sort over a `date` and
+ /// a `date_nanos` field comparable at all. Without it both sides emit keys
+ /// on their own scale — epoch-ms ~1.6e12 against epoch-ns ~1.6e18 — and no
+ /// comparison of the raw longs is chronological. `numeric_type` names one
+ /// scale and every participating index produces keys on it.
+ #[tokio::test]
+ async fn numeric_type_date_nanos_interleaves_a_date_and_a_date_nanos_index() {
+ let state = test_state();
+ two_scaled_indices(&state).await;
+ let (status, body) = request_json(
+ &state,
+ "POST",
+ "/nt-*/_search",
+ json!({
+ "size": 4,
+ "sort": [{"timestamp": {"order": "asc", "numeric_type": "date_nanos"}}]
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ ids(&body),
+ vec!["ms-feb", "ns-apr", "ms-jun", "ns-aug"],
+ "#889: numeric_type date_nanos must order both indices by instant: {body}"
+ );
+ // Every sort value is on the requested scale, so the caller can page
+ // with `search_after` in that one space.
+ let sorts: Vec<i64> = body["hits"]["hits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|h| h["sort"][0].as_i64().unwrap())
+ .collect();
+ assert!(
+ sorts.iter().all(|v| *v > 1_000_000_000_000_000),
+ "#889: numeric_type date_nanos must emit epoch-NANOSECOND sort values, got {sorts:?}"
+ );
+ assert!(sorts.windows(2).all(|w| w[0] < w[1]), "{sorts:?}");
+ }
+
+ #[tokio::test]
+ async fn numeric_type_date_interleaves_on_the_millisecond_scale() {
+ let state = test_state();
+ two_scaled_indices(&state).await;
+ let (status, body) = request_json(
+ &state,
+ "POST",
+ "/nt-*/_search",
+ json!({
+ "size": 4,
+ "sort": [{"timestamp": {"order": "asc", "numeric_type": "date"}}]
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ ids(&body),
+ vec!["ms-feb", "ns-apr", "ms-jun", "ns-aug"],
+ "#889: numeric_type date must order both indices by instant: {body}"
+ );
+ let sorts: Vec<i64> = body["hits"]["hits"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|h| h["sort"][0].as_i64().unwrap())
+ .collect();
+ assert!(
+ sorts.iter().all(|v| *v < 1_000_000_000_000_000),
+ "#889: numeric_type date must emit epoch-MILLISECOND sort values, got {sorts:?}"
+ );
+ assert!(sorts.windows(2).all(|w| w[0] < w[1]), "{sorts:?}");
+ // …and paging through that space works, because the cursor is
+ // normalised on the same forced scale.
+ let (status, page2) = request_json(
+ &state,
+ "POST",
+ "/nt-*/_search",
+ json!({
+ "size": 2,
+ "sort": [{"timestamp": {"order": "asc", "numeric_type": "date"}}],
+ "search_after": [sorts[1]]
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{page2}");
+ assert_eq!(ids(&page2), vec!["ms-jun", "ns-aug"], "{page2}");
+ }
+
+ /// The documented DEFAULT, kept honest: with no `numeric_type` ES compares
+ /// the raw longs, so every epoch-nanosecond key outranks every
+ /// epoch-millisecond one regardless of instant. `search/240_date_nanos.yml`
+ /// ("doc value fields are working as expected across date and date_nanos
+ /// fields") asserts exactly that — a `date_nanos` doc at …12.123456789
+ /// sorts above a `date` doc at …12.987 on `desc`. This test pins that the
+ /// #889 change did not quietly turn the default into a conversion.
+ #[tokio::test]
+ async fn without_numeric_type_the_two_scales_do_not_interleave() {
+ let state = test_state();
+ two_scaled_indices(&state).await;
+ let (status, body) = request_json(
+ &state,
+ "POST",
+ "/nt-*/_search",
+ json!({"size": 4, "sort": [{"timestamp": "asc"}]}),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{body}");
+ assert_eq!(
+ ids(&body),
+ vec!["ms-feb", "ms-jun", "ns-apr", "ns-aug"],
+ "#889: without numeric_type the raw longs are compared, ms block first: {body}"
+ );
+ }
+
+ /// #889 "related, also unfixed": `date` and `date_nanos` share one native
+ /// type, so a schema-derived mapping reported every `date_nanos` field as
+ /// `date`. A client that reads a mapping and writes it back — the GET → PUT
+ /// round trip every reindex helper performs — silently downgraded the field
+ /// to millisecond resolution.
+ #[test]
+ fn schema_derived_mapping_reports_date_nanos_as_date_nanos() {
+ let mut ns = FieldConfig::new("when_ns", FieldType::Date);
+ ns.options.date_precision = Some(xerj_common::types::DatePrecision::Nanos);
+ let schema = Schema {
+ fields: vec![FieldConfig::new("when", FieldType::Date), ns],
+ version: 0,
+ updated_at: Utc::now(),
+ };
+ let props = schema_to_es_properties(&schema);
+ assert_eq!(props["when"]["type"], json!("date"));
+ assert_eq!(props["when_ns"]["type"], json!("date_nanos"));
+ }
+}
+
#[cfg(test)]
mod semantic_companion_schema_tests {
use super::*;
@@ -17738,7 +18007,16 @@ mod semantic_companion_hnsw_api_tests {
pub fn schema_to_es_properties(schema: &Schema) -> serde_json::Map<String, Value> {
let mut props = serde_json::Map::new();
for field in &schema.fields {
- let es_type = native_type_to_es(&field.field_type);
+ // #889 — `date` and `date_nanos` both live as `FieldType::Date`, so
+ // rendering the native type alone reported every `date_nanos` field as
+ // a plain `date`. A client that reads a mapping and writes it back
+ // (the GET → PUT round trip Kibana and every reindex helper performs)
+ // then silently downgraded the field to millisecond resolution. Now
+ // that the declared precision is recorded, report it.
+ let es_type = match (&field.field_type, field.options.date_precision) {
+ (FieldType::Date, Some(xerj_common::types::DatePrecision::Nanos)) => "date_nanos",
+ (ft, _) => native_type_to_es(ft),
+ };
let mut field_obj = serde_json::Map::new();
field_obj.insert("type".to_string(), Value::String(es_type.to_string()));
if let Some(n) = field.options.ignore_above {
diff --git a/engine/crates/xerj-common/src/types.rs b/engine/crates/xerj-common/src/types.rs
index 14f150028..8f731aaf0 100644
--- a/engine/crates/xerj-common/src/types.rs
+++ b/engine/crates/xerj-common/src/types.rs
@@ -336,14 +336,18 @@ pub struct FieldOptions {
/// exact default shape ES emits (`ignore_above: 256`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ignore_above: Option<u32>,
- /// Declared resolution of a `Date` field (#790).
+ /// Declared resolution of a `Date` field (#790, #889).
///
- /// `Some(Millis)` for an ES `date`, `Some(Nanos)` for an ES `date_nanos`.
- /// `None` means "the mapping predates this flag" — a schema.json written
- /// by an older build. Query-time date normalisation treats `None` (and,
- /// for now, `Nanos`) as the legacy per-value guess so that upgrading a
- /// data dir cannot silently change how its dates sort; see
- /// `xerj-engine`'s `DateScale`.
+ /// `Some(Millis)` for an ES `date`, `Some(Nanos)` for an ES `date_nanos`;
+ /// query-time date normalisation pins the whole column to that scale (see
+ /// `xerj-engine`'s `DateScale`).
+ ///
+ /// `None` means "the mapping predates this flag" — a schema.json written by
+ /// an older build. `Index::open` back-fills it from the index's persisted
+ /// `es_mapping.json`, which still carries the original type string (#889);
+ /// what survives as `None` is a field no mapping blob describes, and that
+ /// keeps the legacy per-value guess rather than being defaulted to a scale
+ /// nobody declared.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub date_precision: Option<DatePrecision>,
/// Allow the field to appear more than once in a document (always `true` for arrays).
diff --git a/engine/crates/xerj-engine/src/index.rs b/engine/crates/xerj-engine/src/index.rs
index 422bbb5d1..55a4ead28 100644
--- a/engine/crates/xerj-engine/src/index.rs
+++ b/engine/crates/xerj-engine/src/index.rs
@@ -1668,6 +1668,273 @@ mod flush_publication_recovery_tests {
}
}
+ /// Strip `date_precision` from an index's persisted `schema.json`, which
+ /// is byte-for-byte the shape a build older than #790 wrote: the field is
+ /// `skip_serializing_if = "Option::is_none"`, so an old schema simply has
+ /// no such key. This is the legacy fixture — everything about the index is
+ /// current except the one record #790 added.
+ fn strip_date_precision(index_dir: &std::path::Path) {
+ let path = index_dir.join("schema.json");
+ let mut v: serde_json::Value =
+ serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
+ fn walk(fields: &mut serde_json::Value) {
+ let Some(arr) = fields.as_array_mut() else {
+ return;
+ };
+ for f in arr {
+ if let Some(o) = f.get_mut("options").and_then(|o| o.as_object_mut()) {
+ o.remove("date_precision");
+ }
+ if let Some(sub) = f.get_mut("fields") {
+ walk(sub);
+ }
+ }
+ }
+ walk(&mut v["schema"]["fields"]);
+ assert!(
+ !String::from_utf8(serde_json::to_vec(&v).unwrap())
+ .unwrap()
+ .contains("date_precision"),
+ "the legacy fixture must carry no precision record at all"
+ );
+ std::fs::write(&path, serde_json::to_vec_pretty(&v).unwrap()).unwrap();
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn date_nanos_column_is_one_scale_whatever_the_value() {
+ // #889 part 1. #790 pinned a declared `date` to milliseconds but left
+ // `date_nanos` on the per-VALUE guess (">= 4 fractional-second digits
+ // means nanoseconds"), so the very defect #790 describes survived
+ // inside `date_nanos`: doc `sub` (2020, sub-millisecond) got a
+ // NANOSECOND key ~1.59e18 while doc `late` (2025, whole-second) got a
+ // MILLISECOND key ~1.74e12 — six orders of magnitude apart in one
+ // column — and 2025 therefore sorted BEFORE 2020. A `date_nanos` field
+ // is now uniformly nanosecond-scaled, so one column is one scale.
+ let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config).unwrap();
+ let idx = date_index(
+ &engine,
+ "date-ns-mixed",
+ Some(xerj_common::types::DatePrecision::Nanos),
+ &[
+ ("sub", "2020-06-06T06:06:06.123456Z"),
+ ("late", "2025-01-01T00:00:00Z"),
+ ],
+ )
+ .await;
+ let range_count = |idx: std::sync::Arc<crate::Index>, body: serde_json::Value| async move {
+ let req = xerj_query::parse_request(
+ &json!({"query": body, "size": 10, "track_total_hits": true}),
+ )
+ .unwrap();
+ let r = idx.search(&req).await.unwrap();
+ let mut ids: Vec<_> = r.hits.iter().map(|h| h.id.clone()).collect();
+ ids.sort();
+ (r.total.value, ids)
+ };
+ let sort_values = |idx: std::sync::Arc<crate::Index>| async move {
+ let req = xerj_query::parse_request(
+ &json!({"query": {"match_all": {}}, "size": 10, "sort": [{"ts": "asc"}]}),
+ )
+ .unwrap();
+ idx.search(&req)
+ .await
+ .unwrap()
+ .hits
+ .iter()
+ .map(|h| (h.id.clone(), h.sort.clone()))
+ .collect::<Vec<_>>()
+ };
+ for phase in ["pre-flush", "post-flush"] {
+ assert_eq!(
+ sort_values(idx.clone()).await,
+ vec![
+ ("sub".to_string(), vec![json!(1591423566123456000i64)]),
+ ("late".to_string(), vec![json!(1735689600000000000i64)]),
+ ],
+ "#889 {phase}: every value of a date_nanos field is epoch-nanoseconds, \
+ including the whole-second one the old guess called milliseconds"
+ );
+ assert_eq!(
+ sort_ids(&idx, "desc").await,
+ vec!["late".to_string(), "sub".to_string()],
+ "#889 {phase}: desc must be the exact reverse"
+ );
+ // A range bound is normalised on the same field scale, so a
+ // whole-second bound reaches the whole-second doc and nothing else.
+ assert_eq!(
+ range_count(idx.clone(), json!({"range": {"ts": {"gte": "2021-01-01"}}})).await,
+ (1u64, vec!["late".to_string()]),
+ "#889 {phase}: gte 2021 keeps only late"
+ );
+ if phase == "pre-flush" {
+ idx.flush().await.unwrap();
+ assert_eq!(idx.memtable.doc_count(), 0);
+ }
+ }
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn legacy_index_backfills_date_precision_from_es_mapping() {
+ // #889 part 2. `date_precision` is written when a field is MAPPED, so
+ // an index created by a build older than #790 comes back with no
+ // precision at all and every date field falls back to the per-value
+ // guess — the #790 defect, still live, on exactly the data dirs that
+ // already exist. The raw ES mapping blob beside `schema.json` still
+ // says `date` or `date_nanos`, so the flag is recoverable at open.
+ //
+ // Both directions are checked: a legacy `date_nanos` must come back
+ // nanosecond-scaled (a blanket default would silently downgrade it to
+ // milliseconds), and a legacy `date` must come back millisecond-scaled
+ // (i.e. it inherits the #790 fix instead of waiting for a reindex).
+ let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config.clone()).unwrap();
+
+ // Same two documents in both indices: `sub` is the EARLIER instant, so
+ // the per-value guess (which scales them differently) reverses them.
+ let docs = [
+ ("sub", "2020-06-06T06:06:06.123456Z"),
+ ("late", "2025-01-01T00:00:00Z"),
+ ];
+ let mut index_dirs = Vec::new();
+ for (name, es_type, precision) in [
+ (
+ "legacy-ns",
+ "date_nanos",
+ xerj_common::types::DatePrecision::Nanos,
+ ),
+ (
+ "legacy-ms",
+ "date",
+ xerj_common::types::DatePrecision::Millis,
+ ),
+ ] {
+ let idx = date_index(&engine, name, Some(precision), &docs).await;
+ engine
+ .put_index_mapping(name, json!({"properties": {"ts": {"type": es_type}}}))
+ .unwrap();
+ idx.flush().await.unwrap();
+ assert!(idx.data_dir.join("es_mapping.json").is_file());
+ index_dirs.push(idx.data_dir.clone());
+ drop(idx);
+ }
+ drop(engine);
+ // Age the schemas only once the engine that owns them is gone, so
+ // nothing rewrites `schema.json` behind the fixture on shutdown.
+ for dir in &index_dirs {
+ strip_date_precision(dir);
+ }
+
+ let restarted = crate::Engine::new(config).unwrap();
+ for (name, expected) in [
+ (
+ "legacy-ns",
+ vec![json!(1591423566123456000i64), json!(1735689600000000000i64)],
+ ),
+ (
+ "legacy-ms",
+ vec![json!(1591423566123i64), json!(1735689600000i64)],
+ ),
+ ] {
+ let idx = restarted.get_index(name).unwrap();
+ idx.abort_background_tasks();
+ let req = xerj_query::parse_request(
+ &json!({"query": {"match_all": {}}, "size": 10, "sort": [{"ts": "asc"}]}),
+ )
+ .unwrap();
+ let hits = idx.search(&req).await.unwrap().hits;
+ let got: Vec<(String, Vec<serde_json::Value>)> = hits
+ .iter()
+ .map(|h| (h.id.clone(), h.sort.clone()))
+ .collect();
+ assert_eq!(
+ got,
+ vec![
+ ("sub".to_string(), vec![expected[0].clone()]),
+ ("late".to_string(), vec![expected[1].clone()]),
+ ],
+ "#889 {name}: an index whose schema.json predates date_precision must \
+ recover its scale from es_mapping.json, not guess it per value"
+ );
+ }
+ }
+
+ #[test]
+ fn backfill_only_fills_what_the_mapping_actually_says() {
+ // The back-fill is a pure widening: it never overwrites a precision the
+ // current build already recorded, and it never invents one for a field
+ // the ES mapping does not describe as a date — leaving those on the
+ // legacy guess is the whole reason a blanket default was rejected.
+ use xerj_common::types::DatePrecision;
+ let mut fields = vec![
+ FieldConfig::new("declared_ms", FieldType::Date),
+ {
+ let mut f = FieldConfig::new("legacy_ns", FieldType::Date);
+ f.options.date_precision = None;
+ f
+ },
+ {
+ let mut f = FieldConfig::new("legacy_ms", FieldType::Date);
+ f.options.date_precision = None;
+ f
+ },
+ {
+ let mut f = FieldConfig::new("unmentioned", FieldType::Date);
+ f.options.date_precision = None;
+ f
+ },
+ {
+ let mut f = FieldConfig::new("not_a_date_in_mapping", FieldType::Date);
+ f.options.date_precision = None;
+ f
+ },
+ {
+ let mut parent = FieldConfig::new("obj", FieldType::Object);
+ let mut child = FieldConfig::new("when", FieldType::Date);
+ child.options.date_precision = None;
+ parent.fields = vec![child];
+ parent
+ },
+ ];
+ // `declared_ms` is mapped `date_nanos` here on purpose: the current
+ // build already classified it, so the back-fill must not touch it.
+ let props = json!({
+ "declared_ms": {"type": "date_nanos"},
+ "legacy_ns": {"type": "date_nanos"},
+ "legacy_ms": {"type": "date"},
+ "not_a_date_in_mapping": {"type": "keyword"},
+ "obj": {"properties": {"when": {"type": "date_nanos"}}}
+ });
+ assert_eq!(backfill_date_precision(&mut fields, &props), 3);
+ let by_name = |n: &str| {
+ fields
+ .iter()
+ .find(|f| f.name == n)
+ .unwrap()
+ .options
+ .date_precision
+ };
+ assert_eq!(by_name("declared_ms"), Some(DatePrecision::Millis));
+ assert_eq!(by_name("legacy_ns"), Some(DatePrecision::Nanos));
+ assert_eq!(by_name("legacy_ms"), Some(DatePrecision::Millis));
+ assert_eq!(by_name("unmentioned"), None);
+ assert_eq!(by_name("not_a_date_in_mapping"), None);
+ assert_eq!(
+ fields.iter().find(|f| f.name == "obj").unwrap().fields[0]
+ .options
+ .date_precision,
+ Some(DatePrecision::Nanos)
+ );
+ // Idempotent: a second pass classifies nothing new.
+ assert_eq!(backfill_date_precision(&mut fields, &props), 0);
+ }
+
#[test]
fn date_scale_follows_the_declared_mapping() {
// The whole point of #790: the scale is a property of the FIELD.
@@ -1693,13 +1960,20 @@ mod flush_publication_recovery_tests {
.unwrap_or(DateScale::PerValue)
};
assert_eq!(scale("plain"), DateScale::Millis);
- assert_eq!(scale("ns"), DateScale::PerValue);
+ // #889: a DECLARED `date_nanos` is uniformly nanosecond-scaled — it no
+ // longer re-derives its scale from each value.
+ assert_eq!(scale("ns"), DateScale::Nanos);
assert_eq!(scale("legacy"), DateScale::PerValue);
assert_eq!(scale("word"), DateScale::PerValue);
assert_eq!(scale("undeclared"), DateScale::PerValue);
assert_eq!(
- millis_date_fields(&schema),
- ["plain".to_string()].into_iter().collect()
+ date_field_scales(&schema),
+ [
+ ("plain".to_string(), DateScale::Millis),
+ ("ns".to_string(), DateScale::Nanos),
+ ]
+ .into_iter()
+ .collect()
);
// A millisecond field truncates sub-millisecond digits; the per-value
// scale keeps them, which is the whole ms-vs-ns split.
@@ -1712,6 +1986,32 @@ mod flush_publication_recovery_tests {
date_string_to_epoch(sub, DateScale::PerValue),
Some(json!(1591423566123456000i64))
);
+ assert_eq!(
+ date_string_to_epoch(sub, DateScale::Nanos),
+ Some(json!(1591423566123456000i64))
+ );
+ // #889, the defect itself: a WHOLE-SECOND value in a `date_nanos`
+ // column. The per-value guess called it milliseconds — six orders of
+ // magnitude below the same column's sub-millisecond keys, so it sorted
+ // as if it were 1970. `Nanos` puts it on the column's one scale.
+ let whole = "2020-06-06T06:06:06Z";
+ assert_eq!(
+ date_string_to_epoch(whole, DateScale::PerValue),
+ Some(json!(1591423566000i64))
+ );
+ assert_eq!(
+ date_string_to_epoch(whole, DateScale::Nanos),
+ Some(json!(1591423566000000000i64))
+ );
+ // Same for the slash-date shape, which had no nanosecond branch at all.
+ assert_eq!(
+ sort_date_normalize("06/06/2020 06:06:06.123", DateScale::PerValue),
+ Some(json!(1591423566123i64))
+ );
+ assert_eq!(
+ sort_date_normalize("06/06/2020 06:06:06.123", DateScale::Nanos),
+ Some(json!(1591423566123000000i64))
+ );
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
@@ -1798,6 +2098,242 @@ mod flush_publication_recovery_tests {
}
}
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn date_nanos_term_and_epoch_millis_bound_survive_flush() {
+ // #889 regression. Pinning `date_nanos` to `DateScale::Nanos` moved the
+ // segment sort-shadow's keys to epoch-NANOSECONDS, but the bound
+ // derivation that feeds the shadow (`shadow_range_bounds`, used by the
+ // range dv pre-filter and by the `try_shortcut_count` Range arm) still
+ // took a NUMERIC bound verbatim as epoch-milliseconds. Six orders of
+ // magnitude apart, the bisect matched nothing, so the pre-filter came
+ // back `Some(empty)` — which the scan loop treats as PROOF that no doc
+ // in the segment can contribute a hit or a count — and the segment was
+ // skipped whole.
+ //
+ // Two shapes reach that code with a numeric bound:
+ // * the #788 `term`-on-a-date rewrite, which turns a `term` into the
+ // degenerate `range [epoch_ms, epoch_ms]` from `parse_date_ms`, and
+ // * a user-supplied numeric bound, which ES reads as epoch-MILLIS on
+ // a `date_nanos` field too (its default format is
+ // `strict_date_optional_time_nanos||epoch_millis`) — so the
+ // conversion belongs at the BOUND, not at the value.
+ //
+ // Both answered correctly PRE-flush (the memtable compares ms-to-ms via
+ // `parse_date_ms` on both sides) and returned 0 hits POST-flush, which
+ // is the flush-invariance break this pins shut.
+ let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config).unwrap();
+ let idx = date_index(
+ &engine,
+ "date-ns-term",
+ Some(xerj_common::types::DatePrecision::Nanos),
+ &[
+ ("sub", "2020-06-06T06:06:06.123456Z"),
+ ("late", "2025-01-01T00:00:00Z"),
+ ],
+ )
+ .await;
+ let run = |idx: std::sync::Arc<crate::Index>, body: serde_json::Value| async move {
+ let req = xerj_query::parse_request(&json!({
+ "query": body, "size": 10, "track_total_hits": true
+ }))
+ .unwrap();
+ let r = idx.search(&req).await.unwrap();
+ let mut ids: Vec<_> = r.hits.iter().map(|h| h.id.clone()).collect();
+ ids.sort();
+ (r.total.value, ids)
+ };
+ let count0 = |idx: std::sync::Arc<crate::Index>, body: serde_json::Value| async move {
+ let req = xerj_query::parse_request(&json!({
+ "query": body, "size": 0, "track_total_hits": true
+ }))
+ .unwrap();
+ idx.search(&req).await.unwrap().total.value
+ };
+ // `late` is 1735689600000 ms = 1735689600000000000 ns;
+ // `sub` is 1591423566123 ms = 1591423566123456000 ns.
+ let cases: Vec<(serde_json::Value, u64, Vec<&str>)> = vec![
+ // The #788 term rewrite, on the whole-second value the old
+ // per-value guess used to key in milliseconds.
+ (
+ json!({"term": {"ts": "2025-01-01T00:00:00Z"}}),
+ 1,
+ vec!["late"],
+ ),
+ // The same instant spelled as a bare date and as epoch-millis.
+ (json!({"term": {"ts": "2025-01-01"}}), 1, vec!["late"]),
+ (json!({"term": {"ts": 1735689600000i64}}), 1, vec!["late"]),
+ // A user-supplied numeric bound is epoch-MILLIS on `date_nanos`.
+ (
+ json!({"range": {"ts": {"gte": 1735689600000i64}}}),
+ 1,
+ vec!["late"],
+ ),
+ // …and it must still DISCRIMINATE, not merely match everything:
+ // this window opens 456µs before `sub` and closes on `late`.
+ (
+ json!({"range": {"ts": {"gte": 1591423566123i64, "lte": 1735689600000i64}}}),
+ 2,
+ vec!["late", "sub"],
+ ),
+ // A window that closes before `late` excludes it.
+ (
+ json!({"range": {"ts": {"lt": 1735689600000i64}}}),
+ 1,
+ vec!["sub"],
+ ),
+ // The equivalent STRING bound already agreed with the shadow;
+ // pinned here so the numeric fix cannot drift away from it.
+ (
+ json!({"range": {"ts": {"gte": "2025-01-01T00:00:00Z"}}}),
+ 1,
+ vec!["late"],
+ ),
+ ];
+ for phase in ["pre-flush", "post-flush"] {
+ for (body, total, ids) in &cases {
+ let want = (
+ *total,
+ ids.iter().map(|s| (*s).to_string()).collect::<Vec<_>>(),
+ );
+ assert_eq!(
+ run(idx.clone(), body.clone()).await,
+ want,
+ "#889 {phase}: {body} on a date_nanos field"
+ );
+ assert_eq!(
+ count0(idx.clone(), body.clone()).await,
+ *total,
+ "#889 {phase}: {body} size:0 count must agree with the hit scan"
+ );
+ }
+ if phase == "pre-flush" {
+ idx.flush().await.unwrap();
+ assert_eq!(idx.memtable.doc_count(), 0);
+ assert!(!idx.store.snapshot().segments.is_empty());
+ }
+ }
+ }
+
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn date_only_value_on_the_nanosecond_scale_is_still_an_epoch() {
+ // #889 regression. `date_string_to_epoch`'s nanosecond branch tried
+ // only RFC3339 and `%Y-%m-%dT%H:%M:%S%.f`; the `%Y-%m-%d` NaiveDate
+ // fallback existed solely in the millisecond branch. `looks_like_date`
+ // accepts "2021-01-01", so a date-only value in a `date_nanos` field
+ // routed into the nanosecond branch and came back `None` — and
+ // `compute_sort_values` does `.unwrap_or(raw)`, so the hit's `sort`
+ // value became the JSON STRING "2021-01-01" sitting among i64 epochs.
+ // `compare_values` then falls to its string arm, where '"' (0x22) sorts
+ // below every digit, so the doc came FIRST ascending whatever its
+ // instant. `build_sort_shadow` also `?`s out on that term, silently
+ // disabling the segment prefilter for the whole field.
+ //
+ // Both scales now share ONE ladder of accepted formats, so a format
+ // either parses on both or on neither.
+ let _fault_test = FLUSH_FAULT_TEST_LOCK.lock().await;
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.server.data_dir = dir.path().to_string_lossy().into_owned();
+ let engine = crate::Engine::new(config).unwrap();
+ let idx = date_index(
+ &engine,
+ "date-ns-dateonly",
+ Some(xerj_common::types::DatePrecision::Nanos),
+ &[
+ ("day", "2021-01-01"),
+ ("sub", "2020-06-06T06:06:06.123456Z"),
+ ],
+ )
+ .await;
+ let sort_values = |idx: std::sync::Arc<crate::Index>, nt: Option<&'static str>| async move {
+ let sort = match nt {
+ Some(t) => json!([{"ts": {"order": "asc", "numeric_type": t}}]),
+ None => json!([{"ts": "asc"}]),
+ };
+ let req = xerj_query::parse_request(
+ &json!({"query": {"match_all": {}}, "size": 10, "sort": sort}),
+ )
+ .unwrap();
+ idx.search(&req)
+ .await
+ .unwrap()
+ .hits
+ .iter()
+ .map(|h| (h.id.clone(), h.sort.clone()))
+ .collect::<Vec<_>>()
+ };
+ let range_ids = |idx: std::sync::Arc<crate::Index>, body: serde_json::Value| async move {
+ let req = xerj_query::parse_request(
+ &json!({"query": body, "size": 10, "track_total_hits": true}),
+ )
+ .unwrap();
+ let r = idx.search(&req).await.unwrap();
+ let mut ids: Vec<_> = r.hits.iter().map(|h| h.id.clone()).collect();
+ ids.sort();
+ (r.total.value, ids)
+ };
+ for phase in ["pre-flush", "post-flush"] {
+ assert_eq!(
+ sort_values(idx.clone(), None).await,
+ vec![
+ ("sub".to_string(), vec![json!(1591423566123456000i64)]),
+ ("day".to_string(), vec![json!(1609459200000000000i64)]),
+ ],
+ "#889 {phase}: a date-only value in a date_nanos field is an \
+ epoch-nanosecond number, not the raw string"
+ );
+ // The instant, not the lexicographic accident: 2021 is LATER.
+ assert_eq!(
+ sort_ids(&idx, "asc").await,
+ vec!["sub".to_string(), "day".to_string()],
+ "#889 {phase}: asc must order by instant"
+ );
+ assert_eq!(
+ range_ids(idx.clone(), json!({"range": {"ts": {"gte": "2021-01-01"}}})).await,
+ (1u64, vec!["day".to_string()]),
+ "#889 {phase}: gte 2021-01-01 keeps only day"
+ );
+ if phase == "pre-flush" {
+ idx.flush().await.unwrap();
+ assert_eq!(idx.memtable.doc_count(), 0);
+ }
+ }
+
+ // The same hole on this change's own headline feature: `numeric_type`
+ // forces `DateScale::Nanos` on EVERY participating index, so an
+ // ordinary `date` field holding a date-only value went down the very
+ // same branch and returned a raw string under a cross-index sort.
+ let ms = date_index(
+ &engine,
+ "date-ms-dateonly",
+ Some(xerj_common::types::DatePrecision::Millis),
+ &[
+ ("day", "2021-01-01"),
+ ("sub", "2020-06-06T06:06:06.123456Z"),
+ ],
+ )
+ .await;
+ for phase in ["pre-flush", "post-flush"] {
+ assert_eq!(
+ sort_values(ms.clone(), Some("date_nanos")).await,
+ vec![
+ ("sub".to_string(), vec![json!(1591423566123456000i64)]),
+ ("day".to_string(), vec![json!(1609459200000000000i64)]),
+ ],
+ "#889 {phase}: numeric_type date_nanos re-scales a date-only \
+ value on a `date` field instead of emitting the raw string"
+ );
+ if phase == "pre-flush" {
+ ms.flush().await.unwrap();
+ assert_eq!(ms.memtable.doc_count(), 0);
+ }
+ }
+ }
+
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn flush_increments_the_bytes_written_metric() {
// #804: `xerj_bytes_written_total` was registered but nothing ever
@@ -7480,8 +8016,9 @@ pub struct Index {
/// query after a flush/merge doesn't pay the O(n log n) build inside
/// its own latency.
sort_shadow_fields: Arc<dashmap::DashMap<String, DateScale>>,
- /// Sync-readable mirror of every `date`-mapped field that normalises on
- /// the MILLISECOND scale (#790).
+ /// Sync-readable mirror of every date-mapped field whose epoch scale the
+ /// mapping DECLARES — `Millis` for an ES `date`, `Nanos` for an ES
+ /// `date_nanos` (#790, #889).
///
/// The mapping lives in `self.schema`, behind an async `RwLock`; the
/// paths that must agree on a date's epoch scale — `compute_sort_values`
@@ -7489,7 +8026,7 @@ pub struct Index {
/// `sort_epoch_memo` (per buffered memtable doc) — are all sync and on the
/// scan path. The snapshot is swapped wholesale on every schema write
/// (`save_schema`) so a reader always sees one consistent set.
- millis_date_fields: Arc<parking_lot::RwLock<Arc<std::collections::HashSet<String>>>>,
+ date_field_scales: Arc<parking_lot::RwLock<Arc<std::collections::HashMap<String, DateScale>>>>,
/// Per-segment single-flight guard for the `stored_slices_for` miss
/// arm: without it, every in-flight query racing the same cold
/// segment (up to the 64-permit cap) ran its own full stored-section
@@ -7959,7 +8496,7 @@ impl Index {
.any(|f| matches!(f.field_type, FieldType::Date));
let segment_hydration_budget = index_segment_hydration_budget(config);
let passage_chunk_fields_init = passage_chunk_fields_from_schema(&managed.schema);
- let millis_date_fields_snapshot = millis_date_fields(&managed.schema);
+ let date_field_scales_snapshot = date_field_scales(&managed.schema);
let index = Arc::new(Self {
name,
schema: Arc::new(RwLock::new(managed)),
@@ -8071,8 +8608,8 @@ impl Index {
dv_cache: Arc::new(per_index_map()),
sort_shadow_cache: Arc::new(per_index_map()),
sort_shadow_fields: Arc::new(per_index_map()),
- millis_date_fields: Arc::new(parking_lot::RwLock::new(Arc::new(
- millis_date_fields_snapshot,
+ date_field_scales: Arc::new(parking_lot::RwLock::new(Arc::new(
+ date_field_scales_snapshot,
))),
stored_slices_build_locks: Arc::new(per_index_map()),
range_prefilter_cache: Arc::new(per_index_map()),
@@ -8151,7 +8688,15 @@ impl Index {
// pre-persistence index legitimately has no schema.json). Present but
// unparseable → refuse: the explicit mapping is gone and every field
// type would be silently re-inferred from the next writes (#202).
- let schema = load_schema(&index_dir)?.unwrap_or_else(ManagedSchema::dynamic);
+ let mut schema = load_schema(&index_dir)?.unwrap_or_else(ManagedSchema::dynamic);
+ // #889 — an index written before the `date_precision` flag existed has
+ // no record of `date` vs `date_nanos` in `schema.json`, so every date
+ // field would come back on the per-VALUE epoch guess #790 removed for
+ // new indices. The raw ES mapping blob beside it still says which is
+ // which; recover the flag from there before anything can read the
+ // schema, so an upgraded data dir sorts and ranges the same way a
+ // freshly created one does.
+ backfill_date_precision_from_disk(&index_dir, &mut schema, name.as_str());
validate_embedding_identity(
&index_dir,
&schema.schema,
@@ -8352,7 +8897,7 @@ impl Index {
.iter()
.any(|f| matches!(f.field_type, FieldType::Date));
let segment_hydration_budget = index_segment_hydration_budget(config);
- let millis_date_fields_snapshot = millis_date_fields(&schema.schema);
+ let date_field_scales_snapshot = date_field_scales(&schema.schema);
let index = Arc::new(Self {
name,
schema: Arc::new(RwLock::new(schema)),
@@ -8459,8 +9004,8 @@ impl Index {
dv_cache: Arc::new(per_index_map()),
sort_shadow_cache: Arc::new(per_index_map()),
sort_shadow_fields: Arc::new(per_index_map()),
- millis_date_fields: Arc::new(parking_lot::RwLock::new(Arc::new(
- millis_date_fields_snapshot,
+ date_field_scales: Arc::new(parking_lot::RwLock::new(Arc::new(
+ date_field_scales_snapshot,
))),
stored_slices_build_locks: Arc::new(per_index_map()),
range_prefilter_cache: Arc::new(per_index_map()),
@@ -16566,6 +17111,7 @@ impl Index {
missing: xerj_query::sort::SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
r.leaf_ts_field = None;
Some(r)
@@ -17098,7 +17644,7 @@ impl Index {
// output, so it must be normalised on the SAME field
// scale those keys use (#790).
let scale = sf
- .map(|s| self.date_scale(&s.field))
+ .map(|s| self.date_scale_for_sort(s))
.unwrap_or(DateScale::PerValue);
normalize_search_after_value(v, fmt, scale)
})
@@ -17791,8 +18337,10 @@ impl Index {
}
// The memo is per-FIELD-scale (#790): this cut has to
// rank on the same epoch numbers `compute_sort_values`
- // emits for this field, not on a per-value guess.
- let scale = self.date_scale(&sf.field);
+ // emits for this field, not on a per-value guess — and
+ // on the scale THIS SORT asked for, which `numeric_type`
+ // can override (#889).
+ let scale = self.date_scale_for_sort(sf);
mem.sort_candidates_numeric(
&sf.field,
sf.order == SortOrder::Desc,
@@ -22625,9 +23173,9 @@ impl Index {
// evolution), so this is the one place the sync-readable date-scale
// mirror has to be refreshed (#790). Swapped as a whole `Arc` so a
// concurrent reader never observes a half-rebuilt set.
- let next = Arc::new(millis_date_fields(&schema.schema));
+ let next = Arc::new(date_field_scales(&schema.schema));
let changed = {
- let mut cur = self.millis_date_fields.write();
+ let mut cur = self.date_field_scales.write();
let changed = **cur != *next;
*cur = next;
changed
@@ -22647,13 +23195,29 @@ impl Index {
/// The epoch scale `field`'s dates normalise on (#790).
///
/// Read off the sync mirror of the mapping; an undeclared field, or one
- /// whose mapping predates the `date_precision` flag, keeps the legacy
- /// per-value guess.
+ /// whose mapping predates the `date_precision` flag and whose index has no
+ /// `es_mapping.json` to back-fill it from, keeps the legacy per-value
+ /// guess.
fn date_scale(&self, field: &str) -> DateScale {
- if self.millis_date_fields.read().contains(field) {
- DateScale::Millis
- } else {
- DateScale::PerValue
+ self.date_field_scales
+ .read()
+ .get(field)
+ .copied()
+ .unwrap_or(DateScale::PerValue)
+ }
+
+ /// The epoch scale ONE SORT wants `sf.field`'s dates on (#889).
+ ///
+ /// Normally the field's own mapped scale. ES `numeric_type` overrides it,
+ /// which is the only way a cross-index sort over a field mapped `date`
+ /// here and `date_nanos` there can compare at all: every participating
+ /// index is asked for keys on the same scale. `long`/`double` are not date
+ /// conversions and leave the field's scale alone.
+ fn date_scale_for_sort(&self, sf: &xerj_query::sort::SortField) -> DateScale {
+ match sf.numeric_type.as_deref() {
+ Some("date") => DateScale::Millis,
+ Some("date_nanos") => DateScale::Nanos,
+ _ => self.date_scale(&sf.field),
}
}
@@ -26984,6 +27548,17 @@ impl Index {
))
}
+ /// Is the segment sort shadow — built once per (segment, field) on the
+ /// field's MAPPED scale and cached under that key — usable for this sort?
+ ///
+ /// It is not when `numeric_type` re-scales the field (#889): the heap would
+ /// rank on epoch numbers the shadow was not built from, so the candidate
+ /// cut and the ranking would disagree. Rare enough to simply decline —
+ /// the sort still runs, unaccelerated and correct.
+ fn shadow_scale_matches_sort(&self, sf: &xerj_query::sort::SortField) -> bool {
+ self.date_scale_for_sort(sf) == self.date_scale(&sf.field)
+ }
+
fn build_sort_candidates_prefilter(
&self,
segments_dir: &std::path::Path,
@@ -26995,7 +27570,7 @@ impl Index {
use xerj_query::sort::SortOrder;
let sf = topk.fields.first()?;
- if sf.is_score() || sf.is_doc_order() {
+ if sf.is_score() || sf.is_doc_order() || !self.shadow_scale_matches_sort(sf) {
return None;
}
let shadow = self.sorted_shadow_for(segments_dir, segment_id, &sf.field, seg_doc_count)?;
@@ -27209,7 +27784,7 @@ impl Index {
) -> Option<SortCandidates> {
use xerj_query::sort::SortOrder;
let sf = topk.fields.first()?;
- if sf.is_score() || sf.is_doc_order() {
+ if sf.is_score() || sf.is_doc_order() || !self.shadow_scale_matches_sort(sf) {
return None;
}
let shadow = self.sorted_shadow_for(segments_dir, segment_id, &sf.field, seg_doc_count)?;
@@ -33863,6 +34438,96 @@ fn load_schema(index_dir: &Path) -> Result<Option<ManagedSchema>> {
load_sidecar(index_dir, "schema.json")
}
+/// Back-fill `options.date_precision` on a schema written before that flag
+/// existed, reading the index's OWN persisted `es_mapping.json` (#889).
+///
+/// `schema.json` collapses ES `date` and `date_nanos` onto one
+/// `FieldType::Date` and, before #790, recorded nothing that tells them apart —
+/// so an index created by an older build comes back with `date_precision:
+/// None` on every date field and every date-ordered path falls back to the
+/// per-VALUE epoch guess #790 was filed to remove. `es_mapping.json` is the
+/// raw user mapping and still carries the original `"type": "date_nanos"`
+/// string, which is exactly the missing bit.
+///
+/// Only `None` is ever overwritten: a field the current build already
+/// classified keeps its classification, so this is a pure widening and is
+/// idempotent across restarts. A field the ES mapping does not mention (a
+/// dynamically-added date, an index that never had a mapping blob) is left on
+/// `None` — a blanket default here would silently downgrade a real
+/// `date_nanos` column to millisecond resolution, which is the outcome the
+/// legacy guess exists to avoid.
+///
+/// Returns the number of fields it classified.
+fn backfill_date_precision(fields: &mut [FieldConfig], props: &Value) -> usize {
+ use xerj_common::types::DatePrecision;
+ let Some(obj) = props.as_object() else {
+ return 0;
+ };
+ let mut filled = 0;
+ for fc in fields.iter_mut() {
+ let Some(def) = obj.get(&fc.name) else {
+ continue;
+ };
+ if fc.field_type == FieldType::Date && fc.options.date_precision.is_none() {
+ match def.get("type").and_then(Value::as_str) {
+ Some("date_nanos") => {
+ fc.options.date_precision = Some(DatePrecision::Nanos);
+ filled += 1;
+ }
+ Some("date") => {
+ fc.options.date_precision = Some(DatePrecision::Millis);
+ filled += 1;
+ }
+ // A type the mapping renders as something else entirely means
+ // the two are out of step; do not guess from a disagreement.
+ _ => {}
+ }
+ }
+ // Object/nested children live under `properties`; ES multi-fields
+ // under `fields`. `FieldConfig::fields` holds both, keyed off the
+ // parent's own type, so follow whichever the mapping supplies.
+ if !fc.fields.is_empty() {
+ if let Some(sub) = def.get("properties").or_else(|| def.get("fields")) {
+ filled += backfill_date_precision(&mut fc.fields, sub);
+ }
+ }
+ }
+ filled
+}
+
+/// Read `es_mapping.json` out of `index_dir` and back-fill `schema` from it.
+///
+/// Deliberately best-effort: an unreadable or unparseable mapping blob is
+/// already a hard failure in `Engine::load_persisted_es_mapping` (#202), which
+/// runs on the same file moments later and quarantines the index. Failing here
+/// too would only turn one clear error into two, and the fallback — every date
+/// field stays on the legacy guess — is precisely the pre-#889 behaviour.
+fn backfill_date_precision_from_disk(index_dir: &Path, schema: &mut ManagedSchema, name: &str) {
+ let path = index_dir.join("es_mapping.json");
+ let Ok(bytes) = std::fs::read(&path) else {
+ return;
+ };
+ let Ok(mapping) = serde_json::from_slice::<Value>(&bytes) else {
+ return;
+ };
+ let Some(props) = mapping
+ .get("properties")
+ .or_else(|| mapping.get("mappings").and_then(|m| m.get("properties")))
+ else {
+ return;
+ };
+ let filled = backfill_date_precision(&mut schema.schema.fields, props);
+ if filled > 0 {
+ info!(
+ index = name,
+ fields = filled,
+ "back-filled date precision from es_mapping.json (index predates the \
+ date_precision flag); its date fields no longer guess their epoch \
+ scale per value"
+ );
+ }
+}
+
fn load_settings(index_dir: &Path) -> Result<Option<Value>> {
load_sidecar(index_dir, "settings.json")
}
@@ -42956,16 +43621,52 @@ fn build_sort_shadow(
}
}
+/// A NUMERIC range bound on a date field is epoch-MILLISECONDS — on a
+/// `date_nanos` field too — put onto the shadow's own scale (#889).
+///
+/// This is the ES rule, not a xerj convention: a `date_nanos` field's default
+/// format is `strict_date_optional_time_nanos||epoch_millis`, so a bare number
+/// is parsed by `epoch_millis` and only THEN converted to the field's
+/// resolution. Every numeric bound that reaches this code is already in
+/// milliseconds — `parse_date_ms` produced it for the #788 `term`-on-a-date
+/// rewrite, or the user wrote it — while a `Nanos` shadow's keys are
+/// nanoseconds, six orders of magnitude away. Left verbatim, the bisect matched
+/// nothing, the prefilter came back `Some(∅)`, and the scan loop took that as
+/// proof the segment holds no match and skipped it whole: a `term` on a
+/// `date_nanos` field matched pre-flush and vanished post-flush.
+///
+/// `Millis` and `PerValue` keep the bound exactly as it was — a raw epoch-ms
+/// against an epoch-ms column — so nothing outside `date_nanos` moves.
+///
+/// The multiply is done in `i64` when the bound is a whole millisecond count so
+/// it is EXACT: `f64` cannot represent every nanosecond epoch, and the shadow's
+/// own key for that instant is `i64 as f64`. Both sides then round the same
+/// real number the same way, and the bisect stays exact.
+#[inline]
+fn epoch_ms_bound_on_scale(ms: f64, scale: DateScale) -> f64 {
+ if scale != DateScale::Nanos {
+ return ms;
+ }
+ if ms.fract() == 0.0 && ms.abs() < 9.0e15 {
+ if let Some(ns) = (ms as i64).checked_mul(1_000_000) {
+ return ns as f64;
+ }
+ }
+ ms * 1e6
+}
+
/// Re-derive a `Range` query's `[lo,hi]` bounds on the sort-shadow's epoch
-/// scale for the date-shaped-Keyword fallback in `build_range_prefilter_cached`.
+/// scale for the date-shaped-Keyword fallback in `build_range_prefilter_cached`
+/// and the `try_shortcut_count` Range arm.
///
/// The shadow's per-doc key is `sort_date_normalize(value).as_f64()`, so a
/// string bound is normalised with the SAME `sort_date_normalize` function —
/// bound and key are then byte-identical functions of their date string, and
-/// the bisect is exact for any consistent-precision date field. A numeric bound
-/// is taken verbatim (a raw epoch against an epoch column). Returns `None` for a
-/// bound shape neither date-parseable nor numeric → caller bails to the full
-/// scan (still correct).
+/// the bisect is exact for any consistent-precision date field. A NUMERIC bound
+/// (or a numeric-looking string) is epoch-milliseconds by ES's rules and is
+/// converted onto the shadow's scale by `epoch_ms_bound_on_scale`, which is a
+/// no-op off `Nanos`. Returns `None` for a bound shape neither date-parseable
+/// nor numeric → caller bails to the full scan (still correct).
fn shadow_range_bounds(
gte: Option<&Value>,
gt: Option<&Value>,
@@ -42976,12 +43677,13 @@ fn shadow_range_bounds(
let key = |v: Option<&Value>| -> Option<Option<f64>> {
match v {
None => Some(None),
- Some(Value::Number(n)) => Some(n.as_f64()),
+ Some(Value::Number(n)) => Some(n.as_f64().map(|ms| epoch_ms_bound_on_scale(ms, scale))),
Some(Value::String(s)) => {
if let Some(f) = sort_date_normalize(s, scale).and_then(|x| x.as_f64()) {
+ // Already produced ON the shadow's scale — never rescale.
Some(Some(f))
} else if let Ok(f) = s.parse::<f64>() {
- Some(Some(f))
+ Some(Some(epoch_ms_bound_on_scale(f, scale)))
} else {
None // unparseable bound → bail to brute
}
@@ -43401,51 +44103,36 @@ const SHORTCUT_COUNT_CACHE_MAX: usize = 65_536;
fn normalize_search_after_value(v: &Value, fmt_hint: Option<&str>, scale: DateScale) -> Value {
if let Some(s) = v.as_str() {
if let Some(fmt) = fmt_hint {
- if let Some(epoch) = es_format_to_epoch_ms(s, fmt) {
+ if let Some(epoch_ms) = es_format_to_epoch_ms(s, fmt) {
+ // `es_format_to_epoch_ms` is millisecond-resolution by
+ // construction. On a nanosecond-scaled field the hits' keys are
+ // epoch-NANOSECONDS, so a cursor left in milliseconds sits ~9
+ // orders of magnitude below every key and the page boundary is
+ // meaningless (#889). Widen it onto the field's own scale.
+ // Sub-millisecond digits in the cursor string are still lost —
+ // the format parser has no nanosecond path — so the boundary
+ // can be up to 1 ms early, which re-emits at most the docs
+ // inside that millisecond rather than losing any.
+ let epoch = if scale == DateScale::Nanos {
+ match epoch_ms.checked_mul(1_000_000) {
+ Some(ns) => ns,
+ None => return v.clone(),
+ }
+ } else {
+ epoch_ms
+ };
return Value::Number(serde_json::Number::from(epoch));
}
}
- let bytes = s.as_bytes();
- let looks_date = bytes.len() >= 5
- && bytes[0].is_ascii_digit()
- && bytes[1].is_ascii_digit()
- && bytes[2].is_ascii_digit()
- && bytes[3].is_ascii_digit()
- && bytes[4] == b'-';
- if looks_date {
- let is_nanos = scale.is_nanos(s);
- let s_utc = s.replace(' ', "T");
- let s_utc = if s_utc.ends_with('Z') || s_utc.contains('+') {
- s_utc
- } else {
- format!("{}Z", s_utc)
- };
- if is_nanos {
- if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s_utc) {
- let secs = dt.timestamp();
- let nanos = dt.timestamp_subsec_nanos() as i64;
- if let Some(ns) = secs
- .checked_mul(1_000_000_000)
- .and_then(|x| x.checked_add(nanos))
- {
- return Value::Number(serde_json::Number::from(ns));
- }
- }
- }
- if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s_utc) {
- return Value::Number(serde_json::Number::from(dt.timestamp_millis()));
- }
- if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(
- s_utc.trim_end_matches('Z'),
- "%Y-%m-%dT%H:%M:%S%.f",
- ) {
- return Value::Number(serde_json::Number::from(dt.and_utc().timestamp_millis()));
- }
- if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(
- s_utc.trim_end_matches('Z'),
- "%Y-%m-%dT%H:%M:%S",
- ) {
- return Value::Number(serde_json::Number::from(dt.and_utc().timestamp_millis()));
+ // A date-shaped cursor resolves through the SAME ladder
+ // `compute_sort_values` used to produce the keys it is compared
+ // against — `date_string_to_epoch`, on the sort's scale. It used to be
+ // a hand-copied second ladder here whose two `NaiveDateTime` fallbacks
+ // returned `timestamp_millis()` even at `Nanos` (#889); one function
+ // means the cursor and the keys cannot drift apart again.
+ if looks_like_date(s) {
+ if let Some(epoch) = date_string_to_epoch(s, scale) {
+ return epoch;
}
}
}
@@ -43477,22 +44164,30 @@ enum DateScale {
/// declares `type: date`, and for a `FieldType::Date` created through the
/// native API.
Millis,
+ /// ES `date_nanos`: epoch NANOSECONDS for every value, whatever its
+ /// fractional-second width (#889). Set for any field the mapping declares
+ /// `type: date_nanos`, either at create time or back-filled at open from
+ /// the index's persisted `es_mapping.json`.
+ ///
+ /// Uniform nanoseconds is what stops a `date_nanos` column mixing scales:
+ /// under the old per-value guess `2020-06-06T06:06:06.123456Z` became a
+ /// nanosecond key and `2020-06-06T06:06:06Z` a millisecond one, six orders
+ /// of magnitude apart in the same column.
+ ///
+ /// Pinning it is only safe because a sort can now name the scale it wants
+ /// across indices (`numeric_type`, `Index::date_scale_for_sort`) — without
+ /// that, a cross-index sort over a `date` and a `date_nanos` field had no
+ /// way to compare them.
+ Nanos,
/// The pre-#790 per-VALUE guess: >= 4 fractional-second digits means
/// epoch-nanoseconds, anything coarser means epoch-milliseconds.
///
- /// Kept for two kinds of field:
- /// * a `date_nanos` mapping — the guess is the only thing that gives it
- /// nanosecond sort values today, and pinning it to nanos for EVERY
- /// value would change how it compares against a plain `date` field in
- /// a cross-index sort, which the conformance suite pins
- /// (`search/90_search_after.yml`, "Format sort values": a `date_nanos`
- /// field whose values are `dd/MM/yyyy` slash-dates interleaves
- /// chronologically with a `date` field's, i.e. on the millisecond
- /// scale). Making `date_nanos` uniformly nanosecond-scaled is the
- /// remaining half of the mixed-scale problem, tracked separately.
- /// * a field whose mapping predates the `date_precision` flag (a
- /// schema.json written by an older build) — upgrading an existing
- /// index must not silently change how its dates sort.
+ /// Reached only by a field whose scale is genuinely unknown: an
+ /// undeclared/dynamic field, a non-date type, or a `Date` field whose
+ /// mapping predates the `date_precision` flag AND whose index has no
+ /// persisted `es_mapping.json` to back-fill it from (#889). Upgrading such
+ /// an index must not silently change how its dates sort, so the guess
+ /// stays — it is the only description of that column anyone has.
PerValue,
}
@@ -43502,6 +44197,7 @@ impl DateScale {
fn is_nanos(self, s: &str) -> bool {
match self {
DateScale::Millis => false,
+ DateScale::Nanos => true,
DateScale::PerValue => {
s.rsplit_once('.')
.map(|(_, rest)| rest.chars().take_while(|c| c.is_ascii_digit()).count())
@@ -43512,28 +44208,39 @@ impl DateScale {
}
}
-/// Every `Millis` field in `schema`, as the sync-readable mirror the scan
-/// path consults (`Index::millis_date_fields`). The schema itself lives
-/// behind an ASYNC `RwLock`, while `compute_sort_values`,
-/// `build_sort_shadow` and `shadow_range_bounds` are sync and run per hit
-/// and per segment.
-fn millis_date_fields(schema: &Schema) -> std::collections::HashSet<String> {
- fn walk(fields: &[FieldConfig], prefix: &str, out: &mut std::collections::HashSet<String>) {
+/// Every field in `schema` whose date scale is DECLARED (`Millis` or
+/// `Nanos`), as the sync-readable mirror the scan path consults
+/// (`Index::date_field_scales`). The schema itself lives behind an ASYNC
+/// `RwLock`, while `compute_sort_values`, `build_sort_shadow` and
+/// `shadow_range_bounds` are sync and run per hit and per segment.
+///
+/// A field absent from the map has no declared scale and falls back to
+/// `PerValue`, so a path that never consults the map behaves exactly as it did
+/// before #790.
+fn date_field_scales(schema: &Schema) -> std::collections::HashMap<String, DateScale> {
+ fn walk(
+ fields: &[FieldConfig],
+ prefix: &str,
+ out: &mut std::collections::HashMap<String, DateScale>,
+ ) {
for fc in fields {
let path = if prefix.is_empty() {
fc.name.clone()
} else {
format!("{prefix}.{}", fc.name)
};
- if date_scale_of_config(fc) == DateScale::Millis {
- out.insert(path.clone());
+ match date_scale_of_config(fc) {
+ DateScale::PerValue => {}
+ declared => {
+ out.insert(path.clone(), declared);
+ }
}
if !fc.fields.is_empty() {
walk(&fc.fields, &path, out);
}
}
}
- let mut out = std::collections::HashSet::new();
+ let mut out = std::collections::HashMap::new();
walk(&schema.fields, "", &mut out);
out
}
@@ -43541,18 +44248,19 @@ fn millis_date_fields(schema: &Schema) -> std::collections::HashSet<String> {
/// The `DateScale` one declared field asks for — the single rule, so nothing
/// can drift from it.
///
-/// Anything that is not a `Date` carrying `DatePrecision::Millis` — a
-/// `date_nanos`, a mapping written before the flag existed, a non-date type,
-/// an undeclared/dynamic field — stays on `PerValue`, i.e. exactly the
-/// pre-#790 behaviour. The flag only ever *narrows* a field to `Millis`, so a
-/// path that forgets to consult the mapping cannot land on a new scale.
+/// A `Date` carrying an explicit precision gets that precision's scale:
+/// `Millis` for an ES `date`, `Nanos` for an ES `date_nanos` (#889). Anything
+/// else — a non-date type, an undeclared/dynamic field, or a `Date` whose
+/// mapping predates the flag and could not be back-filled at open — stays on
+/// `PerValue`, i.e. exactly the pre-#790 behaviour.
fn date_scale_of_config(fc: &FieldConfig) -> DateScale {
- if fc.field_type == FieldType::Date
- && fc.options.date_precision == Some(xerj_common::types::DatePrecision::Millis)
- {
- DateScale::Millis
- } else {
- DateScale::PerValue
+ if fc.field_type != FieldType::Date {
+ return DateScale::PerValue;
+ }
+ match fc.options.date_precision {
+ Some(xerj_common::types::DatePrecision::Millis) => DateScale::Millis,
+ Some(xerj_common::types::DatePrecision::Nanos) => DateScale::Nanos,
+ None => DateScale::PerValue,
}
}
@@ -43582,7 +44290,25 @@ fn looks_like_slash_date(s: &str) -> bool {
&& parts[2].len() == 4
&& parts[2].bytes().all(|b| b.is_ascii_digit())
}
-fn slash_date_to_epoch(s: &str) -> Option<Value> {
+/// A day-first / month-first slash date on the FIELD's epoch scale (#889).
+///
+/// `scale` matters here for the same reason it matters in
+/// `date_string_to_epoch`: a `date_nanos` field whose values happen to be
+/// slash-dates must produce keys on the SAME scale as its RFC3339 values, or
+/// the column mixes scales again by a different route. `Millis`/`PerValue`
+/// keep the legacy behaviour exactly — the old function had no nanosecond
+/// branch at all, so every slash date was milliseconds.
+fn slash_date_to_epoch(s: &str, scale: DateScale) -> Option<Value> {
+ let out = |dt: chrono::DateTime<chrono::Utc>| -> Option<Value> {
+ if scale == DateScale::Nanos {
+ dt.timestamp_nanos_opt()
+ .map(|ns| Value::Number(serde_json::Number::from(ns)))
+ } else {
+ Some(Value::Number(serde_json::Number::from(
+ dt.timestamp_millis(),
+ )))
+ }
+ };
for pat in [
"%d/%m/%Y %H:%M:%S%.f",
"%d/%m/%Y %H:%M:%S",
@@ -43590,20 +44316,48 @@ fn slash_date_to_epoch(s: &str) -> Option<Value> {
"%m/%d/%Y %H:%M:%S",
] {
if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(s, pat) {
- return Some(Value::Number(serde_json::Number::from(
- dt.and_utc().timestamp_millis(),
- )));
+ return out(dt.and_utc());
}
}
for pat in ["%d/%m/%Y", "%m/%d/%Y"] {
if let Ok(d) = chrono::NaiveDate::parse_from_str(s, pat) {
- return d.and_hms_opt(0, 0, 0).map(|dt| {
- Value::Number(serde_json::Number::from(dt.and_utc().timestamp_millis()))
- });
+ return d.and_hms_opt(0, 0, 0).and_then(|dt| out(dt.and_utc()));
}
}
None
}
+/// One already-parsed instant, rendered on `scale`'s units.
+///
+/// `secs` + `subsec_nanos` is chrono's own decomposition (`timestamp()` is the
+/// FLOOR second and `timestamp_subsec_nanos()` is always non-negative), so
+/// `secs * 1_000 + subsec_nanos / 1_000_000` reproduces `timestamp_millis()`
+/// exactly, negatives included, and `secs * 1_000_000_000 + subsec_nanos`
+/// reproduces `timestamp_nanos_opt()` — but over chrono's full range rather
+/// than only 1677..2262, which is why the multiplication is spelled out here.
+#[inline]
+fn epoch_value_on_scale(secs: i64, subsec_nanos: u32, is_nanos: bool) -> Option<Value> {
+ let n = if is_nanos {
+ secs.checked_mul(1_000_000_000)?
+ .checked_add(subsec_nanos as i64)?
+ } else {
+ secs.checked_mul(1_000)?
+ .checked_add((subsec_nanos / 1_000_000) as i64)?
+ };
+ Some(Value::Number(serde_json::Number::from(n)))
+}
+
+/// A date-shaped string as an epoch number on the FIELD's scale (#790/#889).
+///
+/// The format ladder is walked ONCE and the accepted instant is rendered on
+/// the requested scale at the end — the two scales cannot accept different
+/// sets of strings. They used to: the nanosecond branch was a separate ladder
+/// that stopped after RFC3339 and `%Y-%m-%dT%H:%M:%S%.f`, so a DATE-ONLY value
+/// ("2021-01-01") in a `date_nanos` field — or in any field a `numeric_type`
+/// sort re-scales to nanoseconds — fell out as `None`. `compute_sort_values`
+/// then kept the raw string, which `compare_values` orders lexicographically
+/// (`'"'` below every digit, so the doc sorted FIRST ascending whatever its
+/// instant), and `build_sort_shadow` refused the whole segment's prefilter on
+/// the same term (#889).
fn date_string_to_epoch(s: &str, scale: DateScale) -> Option<Value> {
let is_nanos = scale.is_nanos(s);
let s_utc = s.replace(' ', "T");
@@ -43612,47 +44366,21 @@ fn date_string_to_epoch(s: &str, scale: DateScale) -> Option<Value> {
} else {
format!("{}Z", s_utc)
};
- if is_nanos {
- if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s_utc) {
- let secs = dt.timestamp();
- let nanos = dt.timestamp_subsec_nanos() as i64;
- let epoch_ns = secs.checked_mul(1_000_000_000)?.checked_add(nanos)?;
- return Some(Value::Number(serde_json::Number::from(epoch_ns)));
- }
- if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(
- s_utc.trim_end_matches('Z'),
- "%Y-%m-%dT%H:%M:%S%.f",
- ) {
- let subsec_nanos = dt.and_utc().timestamp_subsec_nanos() as i64;
- let secs = dt.and_utc().timestamp();
- let epoch_ns = secs.checked_mul(1_000_000_000)?.checked_add(subsec_nanos)?;
- return Some(Value::Number(serde_json::Number::from(epoch_ns)));
- }
- return None;
- }
if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&s_utc) {
- return Some(Value::Number(serde_json::Number::from(
- dt.timestamp_millis(),
- )));
- }
- if let Ok(dt) =
- chrono::NaiveDateTime::parse_from_str(s_utc.trim_end_matches('Z'), "%Y-%m-%dT%H:%M:%S%.f")
- {
- return Some(Value::Number(serde_json::Number::from(
- dt.and_utc().timestamp_millis(),
- )));
+ return epoch_value_on_scale(dt.timestamp(), dt.timestamp_subsec_nanos(), is_nanos);
}
- if let Ok(dt) =
- chrono::NaiveDateTime::parse_from_str(s_utc.trim_end_matches('Z'), "%Y-%m-%dT%H:%M:%S")
- {
- return Some(Value::Number(serde_json::Number::from(
- dt.and_utc().timestamp_millis(),
- )));
+ let naive = s_utc.trim_end_matches('Z');
+ for pat in ["%Y-%m-%dT%H:%M:%S%.f", "%Y-%m-%dT%H:%M:%S"] {
+ if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(naive, pat) {
+ let dt = dt.and_utc();
+ return epoch_value_on_scale(dt.timestamp(), dt.timestamp_subsec_nanos(), is_nanos);
+ }
}
- if let Ok(dt) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
- return Some(Value::Number(serde_json::Number::from(
- dt.and_hms_opt(0, 0, 0)?.and_utc().timestamp_millis(),
- )));
+ // Date-only. Parsed off the ORIGINAL `s`: `s_utc` has a `Z` appended that
+ // `%Y-%m-%d` would reject as trailing input.
+ if let Ok(d) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
+ let dt = d.and_hms_opt(0, 0, 0)?.and_utc();
+ return epoch_value_on_scale(dt.timestamp(), dt.timestamp_subsec_nanos(), is_nanos);
}
None
}
@@ -43668,7 +44396,7 @@ fn sort_date_normalize(s: &str, scale: DateScale) -> Option<Value> {
if looks_like_date(s) {
date_string_to_epoch(s, scale)
} else if looks_like_slash_date(s) {
- slash_date_to_epoch(s)
+ slash_date_to_epoch(s, scale)
} else {
None
}
@@ -43734,7 +44462,7 @@ fn memtable_primary_key_rejects(topk: &SortTopK, source: &Value, id: &str, idx:
};
let v = match raw {
Value::Number(n) => n.as_f64(),
- Value::String(s) => sort_epoch_memo(s, idx.date_scale(&sf.field)),
+ Value::String(s) => sort_epoch_memo(s, idx.date_scale_for_sort(sf)),
_ => None,
};
match v {
@@ -43758,10 +44486,13 @@ fn sort_epoch_memo(s: &str, scale: DateScale) -> Option<f64> {
// a borrowed `&str` lookup with no key allocation.
static MEMO_MILLIS: std::sync::LazyLock<dashmap::DashMap<String, Option<f64>>> =
std::sync::LazyLock::new(dashmap::DashMap::new);
+ static MEMO_NANOS: std::sync::LazyLock<dashmap::DashMap<String, Option<f64>>> =
+ std::sync::LazyLock::new(dashmap::DashMap::new);
static MEMO_PER_VALUE: std::sync::LazyLock<dashmap::DashMap<String, Option<f64>>> =
std::sync::LazyLock::new(dashmap::DashMap::new);
let memo = match scale {
DateScale::Millis => &*MEMO_MILLIS,
+ DateScale::Nanos => &*MEMO_NANOS,
DateScale::PerValue => &*MEMO_PER_VALUE,
};
if let Some(e) = memo.get(s) {
@@ -43844,10 +44575,10 @@ fn compute_sort_values(
let raw = xerj_query::sort::reduce_sort_value(&raw, sf.order, sf.mode);
match raw {
Value::String(ref s) if looks_like_date(s) => {
- date_string_to_epoch(s, idx.date_scale(&sf.field)).unwrap_or(raw)
+ date_string_to_epoch(s, idx.date_scale_for_sort(sf)).unwrap_or(raw)
}
Value::String(ref s) if looks_like_slash_date(s) => {
- slash_date_to_epoch(s).unwrap_or(raw)
+ slash_date_to_epoch(s, idx.date_scale_for_sort(sf)).unwrap_or(raw)
}
other => other,
}
diff --git a/engine/crates/xerj-engine/src/sql.rs b/engine/crates/xerj-engine/src/sql.rs
index 6c293f489..54aac6327 100644
--- a/engine/crates/xerj-engine/src/sql.rs
+++ b/engine/crates/xerj-engine/src/sql.rs
@@ -377,6 +377,7 @@ pub fn parse_sql(sql: &str) -> Result<SqlQuery, String> {
missing: xerj_query::sort::SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
});
if let Some(Token::Comma) = peek(pos) {
pos += 1;
diff --git a/engine/crates/xerj-query/src/executor.rs b/engine/crates/xerj-query/src/executor.rs
index 7d641750d..46982a529 100644
--- a/engine/crates/xerj-query/src/executor.rs
+++ b/engine/crates/xerj-query/src/executor.rs
@@ -633,6 +633,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
let merged = merge_hits(vec![vec![h1, h2, h3]], 0, 10, &sort_fields);
diff --git a/engine/crates/xerj-query/src/parser.rs b/engine/crates/xerj-query/src/parser.rs
index 85eeb0e3b..6a4d6773e 100644
--- a/engine/crates/xerj-query/src/parser.rs
+++ b/engine/crates/xerj-query/src/parser.rs
@@ -3242,6 +3242,7 @@ fn parse_sort_field_str(s: &str) -> SortField {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
},
"_doc" => SortField {
field: "_doc".to_string(),
@@ -3250,6 +3251,7 @@ fn parse_sort_field_str(s: &str) -> SortField {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
},
other => SortField {
field: other.to_string(),
@@ -3258,6 +3260,7 @@ fn parse_sort_field_str(s: &str) -> SortField {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
},
}
}
@@ -3272,6 +3275,7 @@ fn parse_sort_field_spec(field: &str, spec: &Value) -> Result<SortField> {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
});
}
@@ -3305,6 +3309,13 @@ fn parse_sort_field_spec(field: &str, spec: &Value) -> Result<SortField> {
.get("unmapped_type")
.and_then(|v| v.as_str())
.map(String::from);
+ // ES `numeric_type` (#889): force the epoch scale this sort's values are
+ // produced on, so a field mapped `date` in one index and `date_nanos` in
+ // another compares on one scale instead of as raw longs.
+ let numeric_type = obj
+ .get("numeric_type")
+ .and_then(|v| v.as_str())
+ .map(|s| s.to_ascii_lowercase());
Ok(SortField {
field: field.to_string(),
@@ -3313,6 +3324,7 @@ fn parse_sort_field_spec(field: &str, spec: &Value) -> Result<SortField> {
missing,
format,
unmapped_type,
+ numeric_type,
})
}
diff --git a/engine/crates/xerj-query/src/sort.rs b/engine/crates/xerj-query/src/sort.rs
index 5e9728fa4..7713df8b5 100644
--- a/engine/crates/xerj-query/src/sort.rs
+++ b/engine/crates/xerj-query/src/sort.rs
@@ -41,6 +41,22 @@ pub struct SortField {
/// survive a schema that predates the field) is not rejected.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub unmapped_type: Option<String>,
+ /// ES `numeric_type`: force the numeric type the sort VALUES are produced
+ /// in, independently of how the field is mapped in each index.
+ ///
+ /// This is what makes a cross-index sort over a field mapped `date` in one
+ /// index and `date_nanos` in another comparable at all: without it ES (and
+ /// xerj) compares the raw longs, so an epoch-nanosecond key always sorts
+ /// above every epoch-millisecond key rather than interleaving with it
+ /// (`search/240_date_nanos.yml` pins exactly that default). xerj implements
+ /// the two date values — `date` pins the sort to epoch-MILLISECONDS,
+ /// `date_nanos` to epoch-NANOSECONDS, for every participating index (#889).
+ ///
+ /// `long` / `double` are parsed and then ignored: xerj already compares
+ /// numeric sort keys as `f64`, so there is nothing to convert. Unlike ES,
+ /// xerj does not reject `numeric_type` on a non-numeric field.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub numeric_type: Option<String>,
}
impl SortField {
@@ -53,6 +69,7 @@ impl SortField {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
}
}
@@ -65,6 +82,7 @@ impl SortField {
missing: SortMissing::default(),
format: None,
unmapped_type: None,
+ numeric_type: None,
}
}
@@ -373,6 +391,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
let a = vec![json!(1)];
let b = vec![json!(2)];
@@ -388,6 +407,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
let a = vec![json!(2)];
let b = vec![json!(1)];
@@ -403,6 +423,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
// null sorts after non-null
assert_eq!(
@@ -420,6 +441,7 @@ mod tests {
missing: SortMissing::First,
format: None,
unmapped_type: None,
+ numeric_type: None,
}];
assert_eq!(
compare_sort_keys(&[json!(null)], &[json!(1)], &fields),
@@ -437,6 +459,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
},
SortField {
field: "name".to_string(),
@@ -445,6 +468,7 @@ mod tests {
missing: SortMissing::Last,
format: None,
unmapped_type: None,
+ numeric_type: None,
},
];
// Same date, "alice" < "bob"
diff --git a/engine/tests/es-compat-yaml/yaml/search/241_date_nanos_term_and_bounds.yml b/engine/tests/es-compat-yaml/yaml/search/241_date_nanos_term_and_bounds.yml
new file mode 100644
index 000000000..fdfef6cc0
--- /dev/null
+++ b/engine/tests/es-compat-yaml/yaml/search/241_date_nanos_term_and_bounds.yml
@@ -0,0 +1,174 @@
+setup:
+
+ - do:
+ indices.create:
+ index: date_ns_bounds
+ body:
+ settings:
+ number_of_shards: 1
+ mappings:
+ properties:
+ ts:
+ type: date_nanos
+ name:
+ type: keyword
+
+ - do:
+ bulk:
+ refresh: true
+ index: date_ns_bounds
+ body:
+ - '{ "index" : { "_id" : "sub" } }'
+ # 1591423566123 ms -> 1591423566123456000 ns
+ - '{ "ts" : "2020-06-06T06:06:06.123456Z", "name" : "sub" }'
+ - '{ "index" : { "_id" : "late" } }'
+ # whole-second: 1735689600000 ms -> 1735689600000000000 ns
+ - '{ "ts" : "2025-01-01T00:00:00Z", "name" : "late" }'
+ - '{ "index" : { "_id" : "day" } }'
+ # date-only: 1609459200000 ms -> 1609459200000000000 ns
+ - '{ "ts" : "2021-01-01", "name" : "day" }'
+
+ # The regressions these cases pin are invisible until the values live in a
+ # SEGMENT: the pre-flush memtable answers a date comparison in milliseconds
+ # on both sides and gets the right answer, while the segment's doc-values
+ # pre-filter works on the field's own epoch scale. Flush explicitly so every
+ # assertion below is answered by the segment path.
+ - do:
+ indices.flush:
+ index: date_ns_bounds
+
+---
+"a term on a date_nanos field matches by instant in every spelling":
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ term:
+ ts: "2025-01-01T00:00:00Z"
+
+ - match: { hits.total: 1 }
+ - match: { hits.hits.0._id: "late" }
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ term:
+ ts: "2025-01-01"
+
+ - match: { hits.total: 1 }
+ - match: { hits.hits.0._id: "late" }
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ term:
+ ts: 1735689600000
+
+ - match: { hits.total: 1 }
+ - match: { hits.hits.0._id: "late" }
+
+ - do:
+ count:
+ index: date_ns_bounds
+ body:
+ query:
+ term:
+ ts: "2025-01-01T00:00:00Z"
+
+ - match: { count: 1 }
+
+---
+"a numeric range bound on a date_nanos field is epoch millis":
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ range:
+ ts:
+ gte: 1735689600000
+
+ - match: { hits.total: 1 }
+ - match: { hits.hits.0._id: "late" }
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ sort: [ { "ts": "asc" } ]
+ query:
+ range:
+ ts:
+ gte: 1591423566123
+ lte: 1735689600000
+
+ - match: { hits.total: 3 }
+ - match: { hits.hits.0._id: "sub" }
+ - match: { hits.hits.1._id: "day" }
+ - match: { hits.hits.2._id: "late" }
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ range:
+ ts:
+ lt: 1609459200000
+
+ - match: { hits.total: 1 }
+ - match: { hits.hits.0._id: "sub" }
+
+ - do:
+ count:
+ index: date_ns_bounds
+ body:
+ query:
+ range:
+ ts:
+ gte: 1735689600000
+
+ - match: { count: 1 }
+
+---
+"a date-only value in a date_nanos field sorts as a nanosecond epoch":
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ sort: [ { "ts": "asc" } ]
+
+ - match: { hits.total: 3 }
+ - match: { hits.hits.0._id: "sub" }
+ - match: { hits.hits.0.sort: [1591423566123456000] }
+ - match: { hits.hits.1._id: "day" }
+ - match: { hits.hits.1.sort: [1609459200000000000] }
+ - match: { hits.hits.2._id: "late" }
+ - match: { hits.hits.2.sort: [1735689600000000000] }
+
+ - do:
+ search:
+ rest_total_hits_as_int: true
+ index: date_ns_bounds
+ body:
+ query:
+ range:
+ ts:
+ gte: "2021-01-01"
+
+ - match: { hits.total: 2 }