From 4af2d1b4af26aa024cb58279088210ee5f207f9b Mon Sep 17 00:00:00 2001 From: Serhiy Bzhezytskyy Date: Sat, 21 Nov 2026 15:14:22 +0200 Subject: [PATCH 1/4] Start date_histogram facets at the range the query asks for A converted date_histogram began at NOW/YEAR-10YEAR, so data older than ten years fell outside every bucket. Take start and end from the query's range on the same field, align a fixed_interval to the epoch as the engine does, and leave a loud placeholder when the query has no such range. --- solrorbit/conversion/query.py | 123 ++++++++++++++++----- tests/unit/solr/test_workload_converter.py | 48 ++++++++ 2 files changed, 142 insertions(+), 29 deletions(-) diff --git a/solrorbit/conversion/query.py b/solrorbit/conversion/query.py index cf6b16ba..9b798cbc 100644 --- a/solrorbit/conversion/query.py +++ b/solrorbit/conversion/query.py @@ -182,27 +182,7 @@ def _translate_query_node(node: dict, fq_list: list = None) -> str: if "range" in node: for field, bounds in node["range"].items(): field = normalize_field_name(field) - # gt/lt are exclusive; Solr spells that with a curly bracket. - if "gte" in bounds: - lo, lo_bracket, lo_key = bounds["gte"], "[", "gte" - elif "gt" in bounds: - lo, lo_bracket, lo_key = bounds["gt"], "{", "gt" - else: - lo, lo_bracket, lo_key = "*", "[", None - if "lte" in bounds: - hi, hi_bracket, hi_key = bounds["lte"], "]", "lte" - elif "lt" in bounds: - hi, hi_bracket, hi_key = bounds["lt"], "}", "lt" - else: - hi, hi_bracket, hi_key = "*", "]", None - # Convert dates if format is specified (common for date fields) - os_format = bounds.get("format") - lo, lo_is_date_only = _convert_date_to_solr_format(lo, os_format) - hi, hi_is_date_only = _convert_date_to_solr_format(hi, os_format) - if hi_is_date_only and hi_key == "lte": - hi, hi_bracket = _round_date_only_bound(hi), "}" - if lo_is_date_only and lo_key == "gt": - lo, lo_bracket = _round_date_only_bound(lo), "[" + lo, lo_bracket, hi, hi_bracket = _range_bounds(bounds) return f"{field}:{lo_bracket}{lo} TO {hi}{hi_bracket}" if "exists" in node: @@ -382,14 +362,84 @@ def translate_to_solr_json_dsl(body: dict) -> dict: aggs = body.get("aggs") or body.get("aggregations") if aggs and isinstance(aggs, dict): - facets = _convert_aggregations_to_facets(aggs) + facets = _convert_aggregations_to_facets(aggs, body.get("query")) if facets: result["facet"] = facets return result -def _convert_aggregations_to_facets(aggs: dict) -> dict: +def _range_bounds(bounds: dict) -> tuple: + """The (low, low bracket, high, high bracket) Solr spells for an OpenSearch range clause.""" + # gt/lt are exclusive; Solr spells that with a curly bracket. + if "gte" in bounds: + lo, lo_bracket, lo_key = bounds["gte"], "[", "gte" + elif "gt" in bounds: + lo, lo_bracket, lo_key = bounds["gt"], "{", "gt" + else: + lo, lo_bracket, lo_key = "*", "[", None + if "lte" in bounds: + hi, hi_bracket, hi_key = bounds["lte"], "]", "lte" + elif "lt" in bounds: + hi, hi_bracket, hi_key = bounds["lt"], "}", "lt" + else: + hi, hi_bracket, hi_key = "*", "]", None + # Convert dates if format is specified (common for date fields) + os_format = bounds.get("format") + lo, lo_is_date_only = _convert_date_to_solr_format(lo, os_format) + hi, hi_is_date_only = _convert_date_to_solr_format(hi, os_format) + if hi_is_date_only and hi_key == "lte": + hi, hi_bracket = _round_date_only_bound(hi), "}" + if lo_is_date_only and lo_key == "gt": + lo, lo_bracket = _round_date_only_bound(lo), "[" + return lo, lo_bracket, hi, hi_bracket + + +def _date_bounds_for_field(query, field: str): + """ + The (start, end) of the range the query puts on ``field``, or None. + + OpenSearch derives a date_histogram's span from the data; a Solr range facet needs it + spelled out. The query's own range on the aggregated field is the span the buckets cover. + """ + if not isinstance(query, dict): + return None + if "range" in query and isinstance(query["range"], dict): + for name, bounds in query["range"].items(): + if normalize_field_name(name) == field and isinstance(bounds, dict): + lo, _, hi, _ = _range_bounds(bounds) + if _SOLR_INSTANT.fullmatch(str(lo)) and _SOLR_INSTANT.fullmatch(str(hi)): + return lo, hi + return None + bool_q = query.get("bool") + if isinstance(bool_q, dict): + for key in ("must", "filter"): + clauses = bool_q.get(key) or [] + for clause in [clauses] if isinstance(clauses, dict) else clauses: + found = _date_bounds_for_field(clause, field) + if found: + return found + return None + + +def _align_to_epoch(start: str, interval: str): + """ + ``start`` moved down to a multiple of a fixed interval counted from the epoch. + + A fixed_interval's buckets are aligned to 1970-01-01, not to the start of the range, so + ``60d`` over 2015 begins at 2014-11-06. A Solr range facet starts where it is told to. + """ + match = re.fullmatch(r"(\d*)(ms|[smhd])", str(interval).strip()) + if not match: + return None + seconds = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400}[match.group(2)] + step = int(match.group(1) or 1) * seconds + epoch = datetime(1970, 1, 1) + elapsed = (datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ") - epoch).total_seconds() + return (epoch + timedelta(seconds=(elapsed // step) * step)).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: """ Convert OpenSearch aggregations to Solr JSON Facet API format. @@ -408,6 +458,7 @@ def _convert_aggregations_to_facets(aggs: dict) -> dict: Args: aggs: OpenSearch aggregations dict (the value of "aggs" or "aggregations") + query: the operation's OpenSearch query, which gives a date_histogram its start and end Returns: Solr JSON Facet API dict suitable for the ``"facet"`` key in JSON Query DSL @@ -419,14 +470,14 @@ def _convert_aggregations_to_facets(aggs: dict) -> dict: for agg_name, agg_def in aggs.items(): if not isinstance(agg_def, dict): continue - entry = _convert_single_agg(agg_name, agg_def) + entry = _convert_single_agg(agg_name, agg_def, query) if entry is not None: result[agg_name] = entry return result -def _convert_single_agg(agg_name: str, agg_def: dict): +def _convert_single_agg(agg_name: str, agg_def: dict, query=None): """Convert a single named OpenSearch aggregation to a Solr facet entry.""" # --- bucket aggregations --- if "terms" in agg_def: @@ -442,7 +493,7 @@ def _convert_single_agg(agg_name: str, agg_def: dict): } nested = agg_def.get("aggs") or agg_def.get("aggregations") if nested: - sub = _convert_aggregations_to_facets(nested) + sub = _convert_aggregations_to_facets(nested, query) if sub: facet_def["facet"] = sub return facet_def @@ -454,17 +505,28 @@ def _convert_single_agg(agg_name: str, agg_def: dict): logger.warning("date_histogram agg '%s' has no field — skipping", agg_name) return None gap = _date_histogram_gap(dh_conf, agg_name) + bounds = _date_bounds_for_field(query, field) + if bounds: + start, end = bounds + if "fixed_interval" in dh_conf: + start = _align_to_epoch(start, dh_conf["fixed_interval"]) or start + else: + logger.warning( + "date_histogram agg '%s' has no date range on '%s' in its query: start and end " + "are placeholders that must be set to the data's range before the operation runs.", + agg_name, field) + start, end = "REPLACE_WITH_START", "REPLACE_WITH_END" facet_def = { "type": "range", "field": field, "gap": gap, "mincount": 1, - "start": "NOW/YEAR-10YEAR", - "end": "NOW/YEAR+1YEAR", + "start": start, + "end": end, } nested = agg_def.get("aggs") or agg_def.get("aggregations") if nested: - sub = _convert_aggregations_to_facets(nested) + sub = _convert_aggregations_to_facets(nested, query) if sub: facet_def["facet"] = sub return facet_def @@ -647,6 +709,9 @@ def _convert_date_to_solr_format(date_str, os_format=None) -> tuple: return date_str, False +_SOLR_INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z") + + def _round_date_only_bound(value: str) -> str: """ Advance a whole-day bound to the start of the following day. diff --git a/tests/unit/solr/test_workload_converter.py b/tests/unit/solr/test_workload_converter.py index 29640f7e..5d115707 100644 --- a/tests/unit/solr/test_workload_converter.py +++ b/tests/unit/solr/test_workload_converter.py @@ -469,6 +469,54 @@ def test_calendar_month_abbreviation_is_not_a_minute(self): self.assertEqual("+1MONTH", gap) +class TestDateHistogramFacetBounds(unittest.TestCase): + def _facet(self, date_histogram, range_clause): + body = { + "query": range_clause, + "aggs": {"dropoffs_over_time": {"date_histogram": date_histogram}}, + } + return translate_to_solr_json_dsl(body)["facet"]["dropoffs_over_time"] + + def _range(self, **bounds): + return {"range": {"dropoff_datetime": bounds}} + + def test_bounds_come_from_the_query_range_on_the_same_field(self): + facet = self._facet( + {"field": "dropoff_datetime", "calendar_interval": "month"}, + self._range(gte="2015-01-01 00:00:00", lt="2016-01-01 00:00:00", format="yyyy-MM-dd HH:mm:ss")) + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertEqual("2016-01-01T00:00:00Z", facet["end"]) + + def test_bounds_are_found_inside_bool_filter(self): + clause = {"bool": {"filter": [self._range(gte="2015-01-01", lte="2015-01-21", format="yyyy-MM-dd")]}} + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "day"}, clause) + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertEqual("2015-01-22T00:00:00Z", facet["end"]) + + def test_fixed_interval_starts_where_the_engine_aligns_it(self): + facet = self._facet( + {"field": "dropoff_datetime", "fixed_interval": "60d"}, + self._range(gte="2015-01-01 00:00:00", lt="2016-01-01 00:00:00", format="yyyy-MM-dd HH:mm:ss")) + self.assertEqual("2014-11-06T00:00:00Z", facet["start"]) + + def test_range_on_another_field_is_not_used(self): + clause = {"range": {"fare_amount": {"gte": 1, "lt": 5}}} + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, clause) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + + def test_no_range_leaves_a_placeholder_and_says_so(self): + with self.assertLogs("solrorbit.conversion.query", level="WARNING") as log: + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, {"match_all": {}}) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + self.assertEqual("REPLACE_WITH_END", facet["end"]) + self.assertTrue(any("dropoffs_over_time" in msg for msg in log.output)) + + def test_date_math_bounds_are_not_taken_as_dates(self): + facet = self._facet({"field": "dropoff_datetime", "calendar_interval": "month"}, + self._range(gte="now-30d", lt="now")) + self.assertEqual("REPLACE_WITH_START", facet["start"]) + + class TestMergeWaitConversion(unittest.TestCase): """Tests for OpenSearch's index-stats merge wait becoming Solr's wait-for-merges.""" From 533fc8209b0d34812e230282b3767586de98e02b Mon Sep 17 00:00:00 2001 From: Serhiy Bzhezytskyy Date: Sat, 21 Nov 2026 15:14:22 +0200 Subject: [PATCH 2/4] Convert date_histogram time_zone and stats sub-aggregations Dropping time_zone moves every bucket edge without failing, and stats was skipped, so the metrics of a bucket were missing. Pass the zone as TZ, enumerate day-based fixed intervals across the offset change, and turn stats into min, max, sum and avg. --- solrorbit/conversion/query.py | 94 +++++++++++++++++++--- tests/unit/solr/test_workload_converter.py | 36 +++++++++ 2 files changed, 121 insertions(+), 9 deletions(-) diff --git a/solrorbit/conversion/query.py b/solrorbit/conversion/query.py index 9b798cbc..791ac69f 100644 --- a/solrorbit/conversion/query.py +++ b/solrorbit/conversion/query.py @@ -27,7 +27,8 @@ import logging import re -from datetime import datetime, timedelta +from datetime import date, datetime, time, timedelta, timezone +from zoneinfo import ZoneInfo from .field import normalize_field_name @@ -365,6 +366,9 @@ def translate_to_solr_json_dsl(body: dict) -> dict: facets = _convert_aggregations_to_facets(aggs, body.get("query")) if facets: result["facet"] = facets + zone = _time_zone_of(aggs) + if zone and facets: + result["params"] = {"TZ": zone} return result @@ -439,6 +443,54 @@ def _align_to_epoch(start: str, interval: str): return (epoch + timedelta(seconds=(elapsed // step) * step)).strftime("%Y-%m-%dT%H:%M:%SZ") +_CALENDAR_ROUNDING = {"+1YEAR": "YEAR", "+1MONTH": "MONTH", "+1DAY": "DAY", "+1HOUR": "HOUR", "+1MINUTE": "MINUTE"} + + +def _fixed_ranges_in_zone(start: str, end: str, interval: str, zone: str): + """ + Explicit ranges for a day-based fixed_interval in a named zone, or None. + + The UTC offset changes inside the range, so the buckets are N days of local calendar time + (counted from 1970-01-01 local) and no single Solr gap describes them. + """ + match = re.fullmatch(r"(\d*)d", str(interval).strip()) + if not match or not int(match.group(1) or 1): + return None + step = int(match.group(1) or 1) + try: + tz = ZoneInfo(zone) + except Exception: # pylint: disable=broad-except + return None + local_start = datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).astimezone(tz) + last = datetime.strptime(end, "%Y-%m-%dT%H:%M:%SZ") + epoch = date(1970, 1, 1) + edge = epoch + timedelta(days=((local_start.date() - epoch).days // step) * step) + + def utc(day): + return datetime.combine(day, time()).replace(tzinfo=tz).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + ranges = [] + while datetime.strptime(utc(edge), "%Y-%m-%dT%H:%M:%SZ") < last: + ranges.append({"from": utc(edge), "to": utc(edge + timedelta(days=step)), + "inclusive_from": True, "inclusive_to": False}) + edge += timedelta(days=step) + return ranges or None + + +def _time_zone_of(aggs): + """The first time_zone a date_histogram anywhere in ``aggs`` declares, or None.""" + for agg in (aggs or {}).values(): + if not isinstance(agg, dict): + continue + zone = (agg.get("date_histogram") or {}).get("time_zone") + if zone: + return zone + zone = _time_zone_of(agg.get("aggs") or agg.get("aggregations")) + if zone: + return zone + return None + + def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: """ Convert OpenSearch aggregations to Solr JSON Facet API format. @@ -470,6 +522,13 @@ def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: for agg_name, agg_def in aggs.items(): if not isinstance(agg_def, dict): continue + if "stats" in agg_def: + # `stats` is four numbers in OpenSearch and four function facets in Solr: _min ... _avg. + field = normalize_field_name(agg_def["stats"].get("field", "")) + if field: + for stat in ("min", "max", "sum", "avg"): + result[f"{agg_name}_{stat}"] = f"{stat}({field})" + continue entry = _convert_single_agg(agg_name, agg_def, query) if entry is not None: result[agg_name] = entry @@ -516,14 +575,31 @@ def _convert_single_agg(agg_name: str, agg_def: dict, query=None): "are placeholders that must be set to the data's range before the operation runs.", agg_name, field) start, end = "REPLACE_WITH_START", "REPLACE_WITH_END" - facet_def = { - "type": "range", - "field": field, - "gap": gap, - "mincount": 1, - "start": start, - "end": end, - } + zone = dh_conf.get("time_zone") + ranges, in_zone = None, False + if zone and bounds: + if "fixed_interval" in dh_conf: + ranges = _fixed_ranges_in_zone(bounds[0], bounds[1], dh_conf["fixed_interval"], zone) + in_zone = bool(ranges) + elif gap in _CALENDAR_ROUNDING: + # Solr rounds date math in the request's TZ; the end is rounded first, then one gap added. + unit = _CALENDAR_ROUNDING[gap] + start, end = f"{start}/{unit}", f"{end}/{unit}{gap}" + in_zone = True + if zone and not in_zone: + logger.warning("date_histogram agg '%s': time_zone '%s' could not be applied; buckets are in UTC", + agg_name, zone) + if ranges: + facet_def = {"type": "range", "field": field, "mincount": 1, "ranges": ranges} + else: + facet_def = { + "type": "range", + "field": field, + "gap": gap, + "mincount": 1, + "start": start, + "end": end, + } nested = agg_def.get("aggs") or agg_def.get("aggregations") if nested: sub = _convert_aggregations_to_facets(nested, query) diff --git a/tests/unit/solr/test_workload_converter.py b/tests/unit/solr/test_workload_converter.py index 5d115707..6d878699 100644 --- a/tests/unit/solr/test_workload_converter.py +++ b/tests/unit/solr/test_workload_converter.py @@ -517,6 +517,42 @@ def test_date_math_bounds_are_not_taken_as_dates(self): self.assertEqual("REPLACE_WITH_START", facet["start"]) +class TestDateHistogramTimeZoneAndStats(unittest.TestCase): + QUERY = {"range": {"dropoff_datetime": {"gte": "2015-01-01 00:00:00", "lt": "2016-01-01 00:00:00", + "format": "yyyy-MM-dd HH:mm:ss"}}} + + def _convert(self, date_histogram, sub_aggs=None): + agg = {"date_histogram": dict({"field": "dropoff_datetime"}, **date_histogram)} + if sub_aggs: + agg["aggs"] = sub_aggs + return translate_to_solr_json_dsl({"query": self.QUERY, "aggs": {"over_time": agg}}) + + def test_calendar_interval_in_a_zone_rounds_in_that_zone(self): + result = self._convert({"calendar_interval": "month", "time_zone": "America/New_York"}) + facet = result["facet"]["over_time"] + self.assertEqual({"TZ": "America/New_York"}, result["params"]) + self.assertEqual("2015-01-01T00:00:00Z/MONTH", facet["start"]) + self.assertEqual("2016-01-01T00:00:00Z/MONTH+1MONTH", facet["end"]) + + def test_fixed_interval_in_a_zone_follows_the_offset_change(self): + facet = self._convert({"fixed_interval": "60d", "time_zone": "America/New_York"})["facet"]["over_time"] + edges = [(r["from"], r["to"]) for r in facet["ranges"]] + self.assertEqual(8, len(edges)) + self.assertEqual(("2014-11-06T05:00:00Z", "2015-01-05T05:00:00Z"), edges[0]) + # 2015-05-05 is after the clocks change: local midnight is 04:00Z, not 05:00Z + self.assertEqual("2015-05-05T04:00:00Z", edges[2][1]) + self.assertEqual("2015-12-31T05:00:00Z", edges[7][0]) + + def test_no_time_zone_adds_no_params(self): + self.assertNotIn("params", self._convert({"calendar_interval": "month"})) + + def test_stats_becomes_four_function_facets(self): + facet = self._convert({"fixed_interval": "60d"}, {"total_amount": {"stats": {"field": "total_amount"}}} + )["facet"]["over_time"]["facet"] + self.assertEqual({"total_amount_min": "min(total_amount)", "total_amount_max": "max(total_amount)", + "total_amount_sum": "sum(total_amount)", "total_amount_avg": "avg(total_amount)"}, facet) + + class TestMergeWaitConversion(unittest.TestCase): """Tests for OpenSearch's index-stats merge wait becoming Solr's wait-for-merges.""" From c3a90feccbdd6e8f656b18f246af0c97220e395a Mon Sep 17 00:00:00 2001 From: Serhiy Bzhezytskyy Date: Sat, 21 Nov 2026 15:14:22 +0200 Subject: [PATCH 3/4] Document how the converter bounds date_histogram and converts stats The converter page said only that date_histogram becomes a range facet, which hid that its bounds come from the query and that a missing range leaves placeholders. --- docs/converter/what-converts.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/converter/what-converts.md b/docs/converter/what-converts.md index fdaeeed2..0a7978b6 100644 --- a/docs/converter/what-converts.md +++ b/docs/converter/what-converts.md @@ -21,8 +21,9 @@ The table below summarizes which OpenSearch Benchmark constructs are automatical | `bool` queries (`must` / `filter` / `should` / `must_not`) | Converted to Solr `bool` query parser | | Date ranges with `format` parameter | Dates parsed per format and written as ISO 8601 | | `terms` aggregations | Converted to Solr `terms` facet | -| `date_histogram` aggregations | Converted to Solr `range` facet with calendar gap | +| `date_histogram` aggregations | Converted to Solr `range` facet with calendar gap. `start` and `end` come from the query's range on the same field, a `fixed_interval` starts on the epoch-aligned boundary, and `time_zone` is passed as `TZ` | | `avg` / `sum` / `min` / `max` aggregations | Converted to Solr function query stats | +| `stats` aggregations | Converted to four function facets, `_min`, `_max`, `_sum` and `_avg` | | `index-stats` retried until `merges.current` reaches zero | → `wait-for-merges`, with the polling expressed as `retry-wait-period` and `max-wait-seconds` | ## Requires manual review @@ -35,6 +36,7 @@ These constructs are flagged in `CONVERTED.md` but not automatically converted: | Complex nested aggregations (3+ levels) | Auto-translation may be incomplete; verify output | | Custom analyzers in mapping | Configset `schema.xml` must be created manually | | `multi_match` queries | Partially converted; review field list for Solr equivalents | +| `date_histogram` without a date range on its field in the query | `start` and `end` are the placeholders `REPLACE_WITH_START` and `REPLACE_WITH_END`; set them to the data's range | ## Skipped (with TODO comment) From 4db7c4b52de05b0b4c11eb6a2529b1cc993d7b70 Mon Sep 17 00:00:00 2001 From: Serhiy Bzhezytskyy Date: Sun, 22 Nov 2026 11:25:25 +0200 Subject: [PATCH 4/4] Close the edges of the date_histogram conversion A review of the bounds, time_zone and stats conversion found inputs that gave wrong buckets without an error: one TZ taken for several differently zoned histograms, an inclusive upper bound on a bucket edge dropping the documents on it, float arithmetic in the epoch alignment, a stats name overwriting a sibling, calendar intervals starting in the middle of their unit, and bounds with fractional seconds read as missing. Refuse what one Solr request cannot express and fix the rest. --- solrorbit/conversion/query.py | 127 ++++++++++++++++----- tests/unit/solr/test_workload_converter.py | 70 ++++++++++++ 2 files changed, 166 insertions(+), 31 deletions(-) diff --git a/solrorbit/conversion/query.py b/solrorbit/conversion/query.py index 791ac69f..f832fa34 100644 --- a/solrorbit/conversion/query.py +++ b/solrorbit/conversion/query.py @@ -363,10 +363,15 @@ def translate_to_solr_json_dsl(body: dict) -> dict: aggs = body.get("aggs") or body.get("aggregations") if aggs and isinstance(aggs, dict): + zones = _date_histogram_zones(aggs) + if len(zones) > 1: + raise ValueError( + "date_histogram aggregations in one request use different time zones (%s), and Solr applies one TZ " + "to a whole request" % ", ".join(sorted(z or "none" for z in zones))) facets = _convert_aggregations_to_facets(aggs, body.get("query")) if facets: result["facet"] = facets - zone = _time_zone_of(aggs) + zone = next(iter(zones), None) if zone and facets: result["params"] = {"TZ": zone} @@ -401,7 +406,7 @@ def _range_bounds(bounds: dict) -> tuple: def _date_bounds_for_field(query, field: str): """ - The (start, end) of the range the query puts on ``field``, or None. + The (start, end, end is inclusive) of the range the query puts on ``field``, or None. OpenSearch derives a date_histogram's span from the data; a Solr range facet needs it spelled out. The query's own range on the aggregated field is the span the buckets cover. @@ -411,9 +416,9 @@ def _date_bounds_for_field(query, field: str): if "range" in query and isinstance(query["range"], dict): for name, bounds in query["range"].items(): if normalize_field_name(name) == field and isinstance(bounds, dict): - lo, _, hi, _ = _range_bounds(bounds) + lo, _, hi, hi_bracket = _range_bounds(bounds) if _SOLR_INSTANT.fullmatch(str(lo)) and _SOLR_INSTANT.fullmatch(str(hi)): - return lo, hi + return lo, hi, hi_bracket == "]" return None bool_q = query.get("bool") if isinstance(bool_q, dict): @@ -426,32 +431,73 @@ def _date_bounds_for_field(query, field: str): return None +def _parse_instant(value: str) -> datetime: + """A naive UTC datetime from a Solr instant, with or without fractional seconds.""" + text = value[:-1] + return datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%f" if "." in text else "%Y-%m-%dT%H:%M:%S") + + +def _format_instant(moment: datetime) -> str: + """A Solr instant; milliseconds are written only when there are some.""" + base = moment.strftime("%Y-%m-%dT%H:%M:%S") + millis = moment.microsecond // 1000 + return "%s.%03dZ" % (base, millis) if millis else base + "Z" + + +_FIXED_UNIT_MS = {"ms": 1, "s": 1000, "m": 60000, "h": 3600000, "d": 86400000} + + def _align_to_epoch(start: str, interval: str): """ ``start`` moved down to a multiple of a fixed interval counted from the epoch. A fixed_interval's buckets are aligned to 1970-01-01, not to the start of the range, so ``60d`` over 2015 begins at 2014-11-06. A Solr range facet starts where it is told to. + Integer milliseconds throughout: a float step moves exact boundaries. """ match = re.fullmatch(r"(\d*)(ms|[smhd])", str(interval).strip()) if not match: return None - seconds = {"ms": 0.001, "s": 1, "m": 60, "h": 3600, "d": 86400}[match.group(2)] - step = int(match.group(1) or 1) * seconds + step = int(match.group(1) or 1) * _FIXED_UNIT_MS[match.group(2)] + if step <= 0: + return None epoch = datetime(1970, 1, 1) - elapsed = (datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ") - epoch).total_seconds() - return (epoch + timedelta(seconds=(elapsed // step) * step)).strftime("%Y-%m-%dT%H:%M:%SZ") + elapsed = (_parse_instant(start) - epoch) // timedelta(milliseconds=1) + return _format_instant(epoch + timedelta(milliseconds=(elapsed // step) * step)) + + +def _floor_calendar(start: str, gap: str): + """``start`` rounded down to the calendar unit of ``gap`` in UTC (weeks begin on Monday), or None.""" + moment = _parse_instant(start) + if gap == "+1MINUTE": + moment = moment.replace(second=0, microsecond=0) + elif gap == "+1HOUR": + moment = moment.replace(minute=0, second=0, microsecond=0) + elif gap == "+1DAY": + moment = moment.replace(hour=0, minute=0, second=0, microsecond=0) + elif gap == "+7DAYS": + moment = (moment - timedelta(days=moment.weekday())).replace(hour=0, minute=0, second=0, microsecond=0) + elif gap == "+1MONTH": + moment = moment.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + elif gap == "+3MONTHS": + moment = moment.replace(month=3 * ((moment.month - 1) // 3) + 1, day=1, hour=0, minute=0, second=0, microsecond=0) + elif gap == "+1YEAR": + moment = moment.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0) + else: + return None + return _format_instant(moment) _CALENDAR_ROUNDING = {"+1YEAR": "YEAR", "+1MONTH": "MONTH", "+1DAY": "DAY", "+1HOUR": "HOUR", "+1MINUTE": "MINUTE"} -def _fixed_ranges_in_zone(start: str, end: str, interval: str, zone: str): +def _fixed_ranges_in_zone(start: str, end: str, interval: str, zone: str, inclusive: bool = False): """ Explicit ranges for a day-based fixed_interval in a named zone, or None. The UTC offset changes inside the range, so the buckets are N days of local calendar time - (counted from 1970-01-01 local) and no single Solr gap describes them. + (counted from 1970-01-01 local) and no single Solr gap describes them. A range is opened for an + inclusive end that falls exactly on a bucket edge. """ match = re.fullmatch(r"(\d*)d", str(interval).strip()) if not match or not int(match.group(1) or 1): @@ -461,34 +507,35 @@ def _fixed_ranges_in_zone(start: str, end: str, interval: str, zone: str): tz = ZoneInfo(zone) except Exception: # pylint: disable=broad-except return None - local_start = datetime.strptime(start, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).astimezone(tz) - last = datetime.strptime(end, "%Y-%m-%dT%H:%M:%SZ") + local_start = _parse_instant(start).replace(tzinfo=timezone.utc).astimezone(tz) + last = _parse_instant(end) epoch = date(1970, 1, 1) edge = epoch + timedelta(days=((local_start.date() - epoch).days // step) * step) def utc(day): - return datetime.combine(day, time()).replace(tzinfo=tz).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + return datetime.combine(day, time()).replace(tzinfo=tz).astimezone(timezone.utc).replace(tzinfo=None) ranges = [] - while datetime.strptime(utc(edge), "%Y-%m-%dT%H:%M:%SZ") < last: - ranges.append({"from": utc(edge), "to": utc(edge + timedelta(days=step)), + while True: + opens = utc(edge) + if opens > last or (opens == last and not inclusive): + break + ranges.append({"from": _format_instant(opens), "to": _format_instant(utc(edge + timedelta(days=step))), "inclusive_from": True, "inclusive_to": False}) edge += timedelta(days=step) return ranges or None -def _time_zone_of(aggs): - """The first time_zone a date_histogram anywhere in ``aggs`` declares, or None.""" +def _date_histogram_zones(aggs): + """The set of time_zone values (None for a histogram without one) of every date_histogram in ``aggs``.""" + zones = set() for agg in (aggs or {}).values(): if not isinstance(agg, dict): continue - zone = (agg.get("date_histogram") or {}).get("time_zone") - if zone: - return zone - zone = _time_zone_of(agg.get("aggs") or agg.get("aggregations")) - if zone: - return zone - return None + if "date_histogram" in agg: + zones.add((agg["date_histogram"] or {}).get("time_zone")) + zones |= _date_histogram_zones(agg.get("aggs") or agg.get("aggregations")) + return zones def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: @@ -519,6 +566,13 @@ def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: return {} result = {} + + def put(key, value): + if key in result: + raise ValueError("aggregation name '%s' is used twice in the converted facets (a stats aggregation " + "also produces _min, _max, _sum and _avg)" % key) + result[key] = value + for agg_name, agg_def in aggs.items(): if not isinstance(agg_def, dict): continue @@ -527,11 +581,14 @@ def _convert_aggregations_to_facets(aggs: dict, query=None) -> dict: field = normalize_field_name(agg_def["stats"].get("field", "")) if field: for stat in ("min", "max", "sum", "avg"): - result[f"{agg_name}_{stat}"] = f"{stat}({field})" + if f"{agg_name}_{stat}" in aggs: + raise ValueError("stats aggregation '%s' would overwrite the aggregation '%s_%s'" + % (agg_name, agg_name, stat)) + put(f"{agg_name}_{stat}", f"{stat}({field})") continue entry = _convert_single_agg(agg_name, agg_def, query) if entry is not None: - result[agg_name] = entry + put(agg_name, entry) return result @@ -565,30 +622,38 @@ def _convert_single_agg(agg_name: str, agg_def: dict, query=None): return None gap = _date_histogram_gap(dh_conf, agg_name) bounds = _date_bounds_for_field(query, field) + zone = dh_conf.get("time_zone") + inclusive = False if bounds: - start, end = bounds + start, end, inclusive = bounds if "fixed_interval" in dh_conf: start = _align_to_epoch(start, dh_conf["fixed_interval"]) or start + elif not zone: + start = _floor_calendar(start, gap) or start else: logger.warning( "date_histogram agg '%s' has no date range on '%s' in its query: start and end " "are placeholders that must be set to the data's range before the operation runs.", agg_name, field) start, end = "REPLACE_WITH_START", "REPLACE_WITH_END" - zone = dh_conf.get("time_zone") ranges, in_zone = None, False if zone and bounds: if "fixed_interval" in dh_conf: - ranges = _fixed_ranges_in_zone(bounds[0], bounds[1], dh_conf["fixed_interval"], zone) + ranges = _fixed_ranges_in_zone(bounds[0], bounds[1], dh_conf["fixed_interval"], zone, inclusive) in_zone = bool(ranges) elif gap in _CALENDAR_ROUNDING: - # Solr rounds date math in the request's TZ; the end is rounded first, then one gap added. + # Solr rounds date math in the request's TZ; the end is rounded first, then one gap added + # (which also covers an inclusive end that falls on a bucket edge). unit = _CALENDAR_ROUNDING[gap] start, end = f"{start}/{unit}", f"{end}/{unit}{gap}" in_zone = True + inclusive = False if zone and not in_zone: logger.warning("date_histogram agg '%s': time_zone '%s' could not be applied; buckets are in UTC", agg_name, zone) + if inclusive and bounds and not ranges: + # An inclusive upper bound that falls on a bucket edge belongs to the bucket that starts there. + end = f"{end}{gap}" if ranges: facet_def = {"type": "range", "field": field, "mincount": 1, "ranges": ranges} else: @@ -785,7 +850,7 @@ def _convert_date_to_solr_format(date_str, os_format=None) -> tuple: return date_str, False -_SOLR_INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z") +_SOLR_INSTANT = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z") def _round_date_only_bound(value: str) -> str: diff --git a/tests/unit/solr/test_workload_converter.py b/tests/unit/solr/test_workload_converter.py index 6d878699..0407d1d6 100644 --- a/tests/unit/solr/test_workload_converter.py +++ b/tests/unit/solr/test_workload_converter.py @@ -553,6 +553,76 @@ def test_stats_becomes_four_function_facets(self): "total_amount_sum": "sum(total_amount)", "total_amount_avg": "avg(total_amount)"}, facet) +class TestDateHistogramReviewCases(unittest.TestCase): + """Edges of the bounds / time_zone / stats conversion that a review reproduced.""" + + def _range(self, lo, hi, op="lt"): + return {"range": {"dropoff_datetime": {"gte": lo, op: hi}}} + + def _convert(self, query, aggs): + return translate_to_solr_json_dsl({"query": query, "aggs": aggs}) + + def _hist(self, **conf): + return {"date_histogram": dict({"field": "dropoff_datetime"}, **conf)} + + def test_two_time_zones_in_one_request_are_refused(self): + aggs = {"ny": self._hist(calendar_interval="month", time_zone="America/New_York"), + "paris": self._hist(calendar_interval="month", time_zone="Europe/Paris")} + with self.assertRaises(ValueError): + self._convert(self._range("2015-01-01T00:00:00Z", "2016-01-01T00:00:00Z"), aggs) + + def test_a_zoned_and_an_unzoned_histogram_in_one_request_are_refused(self): + aggs = {"utc": self._hist(calendar_interval="month"), + "ny": self._hist(calendar_interval="month", time_zone="America/New_York")} + with self.assertRaises(ValueError): + self._convert(self._range("2015-01-01T00:00:00Z", "2016-01-01T00:00:00Z"), aggs) + + def test_inclusive_upper_bound_on_a_bucket_edge_gets_the_bucket_that_starts_there(self): + facet = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z", "lte"), + {"d": self._hist(fixed_interval="1d")})["facet"]["d"] + self.assertEqual("2015-01-02T00:00:00Z+1DAY", facet["end"]) + + def test_exclusive_upper_bound_keeps_its_end(self): + facet = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z"), + {"d": self._hist(fixed_interval="1d")})["facet"]["d"] + self.assertEqual("2015-01-02T00:00:00Z", facet["end"]) + + def test_inclusive_end_on_an_edge_opens_one_more_zoned_range(self): + ranges = self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-05T05:00:00Z", "lte"), + {"d": self._hist(fixed_interval="60d", time_zone="America/New_York")})["facet"]["d"]["ranges"] + self.assertEqual("2015-01-05T05:00:00Z", ranges[-1]["from"]) + + def test_millisecond_fixed_intervals_align_in_integer_milliseconds(self): + facet = lambda interval: self._convert(self._range("2015-01-01T00:00:00Z", "2015-01-02T00:00:00Z"), + {"d": self._hist(fixed_interval=interval)})["facet"]["d"]["start"] + self.assertEqual("2015-01-01T00:00:00Z", facet("1ms")) + self.assertEqual("2014-12-31T23:51:14.048Z", facet("2699999ms")) + + def test_stats_does_not_overwrite_a_sibling_aggregation(self): + for aggs in ({"fare": {"stats": {"field": "fare_amount"}}, "fare_avg": {"avg": {"field": "tip_amount"}}}, + {"fare_avg": {"avg": {"field": "tip_amount"}}, "fare": {"stats": {"field": "fare_amount"}}}): + with self.assertRaises(ValueError): + self._convert({"match_all": {}}, aggs) + + def test_calendar_intervals_start_on_their_unit_in_utc(self): + start = lambda lo, interval: self._convert(self._range(lo, "2016-06-01T00:00:00Z"), + {"d": self._hist(calendar_interval=interval)})["facet"]["d"]["start"] + self.assertEqual("2015-01-01T00:00:00Z", start("2015-01-15T12:00:00Z", "month")) + self.assertEqual("2015-01-12T00:00:00Z", start("2015-01-15T12:00:00Z", "week")) # a Monday + self.assertEqual("2015-01-01T00:00:00Z", start("2015-02-10T00:00:00Z", "quarter")) + self.assertEqual("2015-01-01T00:00:00Z", start("2015-05-17T08:30:00Z", "year")) + self.assertEqual("2015-01-01T00:00:00Z", start("2015-01-01T00:00:00Z", "month")) # already on the edge + + def test_fractional_second_bounds_are_accepted(self): + facet = self._convert(self._range("2015-01-01T00:00:00.000Z", "2016-01-01T00:00:00.000Z"), + {"d": self._hist(calendar_interval="month")})["facet"]["d"] + self.assertEqual("2015-01-01T00:00:00Z", facet["start"]) + self.assertNotIn("REPLACE", facet["end"]) + ranges = self._convert(self._range("2015-01-01T00:00:00.500Z", "2016-01-01T00:00:00.000Z"), + {"d": self._hist(fixed_interval="60d", time_zone="America/New_York")})["facet"]["d"]["ranges"] + self.assertEqual("2014-11-06T05:00:00Z", ranges[0]["from"]) + + class TestMergeWaitConversion(unittest.TestCase): """Tests for OpenSearch's index-stats merge wait becoming Solr's wait-for-merges."""