Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(logs): honor toMillis(@timestamp) filters and GetQueryResults maxItems (#1292)

ovsteenb940f48cef8f6
diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.py
index 11835a8f..fe8c9094 100644
--- a/ministack/services/cloudwatch_logs.py
+++ b/ministack/services/cloudwatch_logs.py
@@ -1579,6 +1579,7 @@ def _compile_insights_filter(stage: str):
Supported forms:
- ``filter @logStream = 'exact'``
- ``filter @message like /pattern/`` or ``/pattern/i``
+ - ``filter toMillis(@timestamp) <=|>=|<|>|=|!= <epoch_ms>``
"""
text = stage.strip()
if not re.match(r"(?i)^filter\b", text):
@@ -1610,6 +1611,30 @@ def _compile_insights_filter(stage: str):
return _like_pred
+ # CWLT surround queries bound neighbors with toMillis(@timestamp).
+ # Silently ignoring this form made ``after`` return the earliest events
+ # in the stream (sort asc + limit) instead of events at/after the pivot.
+ tomillis = re.match(
+ r"^toMillis\(@timestamp\)\s*(<=|>=|<|>|!=|=)\s*(-?\d+)\s*$",
+ body,
+ )
+ if tomillis:
+ op, bound = tomillis.group(1), int(tomillis.group(2))
+ comparators = {
+ "<=": lambda ts, b: ts <= b,
+ ">=": lambda ts, b: ts >= b,
+ "<": lambda ts, b: ts < b,
+ ">": lambda ts, b: ts > b,
+ "=": lambda ts, b: ts == b,
+ "!=": lambda ts, b: ts != b,
+ }
+ compare = comparators[op]
+
+ def _tomillis_pred(record, _compare=compare, _bound=bound):
+ return _compare(int(record.get("_timestamp_ms", 0)), _bound)
+
+ return _tomillis_pred
+
# Unsupported filter form — ignore (subset emulator).
return None
@@ -1720,7 +1745,8 @@ def _start_query(data):
"""Run a CloudWatch Logs Insights query (CWLI subset).
Supported: ``fields``, chained ``filter`` (``@field = '…'``,
- ``@field like /regex/[i]``), ``sort @timestamp asc|desc``, and ``limit``.
+ ``@field like /regex/[i]``, ``toMillis(@timestamp)`` comparisons),
+ ``sort @timestamp asc|desc``, and ``limit``.
Filters are AND-ed; ``limit`` applies after filter+sort as
``min(query limit, StartQuery limit)``.
"""
@@ -1784,14 +1810,35 @@ def _get_query_results(data):
"ResourceNotFoundException",
f"The specified query does not exist: {query_id}", 400,
)
- return json_response({
+ all_results = query.get("results", [])
+ statistics = query.get(
+ "statistics",
+ {"recordsMatched": 0.0, "recordsScanned": 0.0, "bytesScanned": 0.0},
+ )
+ start = _decode_token(data.get("nextToken"))
+ max_items = data.get("maxItems")
+ if max_items is None:
+ page = all_results[start:]
+ return json_response({
+ "status": query["status"],
+ "results": page,
+ "statistics": statistics,
+ })
+ try:
+ limit = max(1, int(max_items))
+ except (TypeError, ValueError):
+ limit = len(all_results) - start if start < len(all_results) else 0
+ limit = max(1, limit) if limit else 1
+ end = start + limit
+ page = all_results[start:end]
+ resp = {
"status": query["status"],
- "results": query.get("results", []),
- "statistics": query.get(
- "statistics",
- {"recordsMatched": 0.0, "recordsScanned": 0.0, "bytesScanned": 0.0},
- ),
- })
+ "results": page,
+ "statistics": statistics,
+ }
+ if end < len(all_results):
+ resp["nextToken"] = _encode_token(end)
+ return json_response(resp)
def _stop_query(data):
diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.py
index 4e9c2404..a5fea064 100644
--- a/tests/test_cloudwatch_logs.py
+++ b/tests/test_cloudwatch_logs.py
@@ -462,6 +462,77 @@ def test_logs_insights_filter_sort_limit(logs):
assert r3["statistics"]["recordsScanned"] == 6.0
+def test_logs_insights_tomillis_bounds_and_max_items(logs):
+ """toMillis(@timestamp) must bound results; GetQueryResults respects maxItems."""
+ import uuid as _uuid
+
+ group = f"/intg/insights-tomillis/{_uuid.uuid4().hex[:8]}"
+ stream = "pod-a"
+ # Fixed epoch ms so query strings stay readable.
+ base_ms = 1_775_000_000_000
+ logs.create_log_group(logGroupName=group)
+ logs.create_log_stream(logGroupName=group, logStreamName=stream)
+ logs.put_log_events(
+ logGroupName=group,
+ logStreamName=stream,
+ logEvents=[
+ {"timestamp": base_ms + 0, "message": "t0"},
+ {"timestamp": base_ms + 1000, "message": "t1"},
+ {"timestamp": base_ms + 2000, "message": "t2"},
+ {"timestamp": base_ms + 3000, "message": "t3"},
+ {"timestamp": base_ms + 4000, "message": "t4"},
+ ],
+ )
+
+ def fields_map(row):
+ return {cell["field"]: cell["value"] for cell in row}
+
+ pivot = base_ms + 2000
+ start_s = (base_ms // 1000) - 60
+ end_s = (base_ms // 1000) + 60
+
+ # After-direction shape used by CWLT surround expand.
+ q_after = logs.start_query(
+ logGroupName=group,
+ startTime=start_s,
+ endTime=end_s,
+ queryString=(
+ f"fields @timestamp, @message, @logStream "
+ f"| filter @logStream = '{stream}' "
+ f"| filter toMillis(@timestamp) >= {pivot} "
+ f"| sort @timestamp asc | limit 10000"
+ ),
+ limit=10000,
+ )
+ page1 = logs.get_query_results(queryId=q_after["queryId"], maxItems=2)
+ rows1 = [fields_map(row) for row in page1["results"]]
+ assert [row["@message"] for row in rows1] == ["t2", "t3"]
+ assert "nextToken" in page1
+ page2 = logs.get_query_results(
+ queryId=q_after["queryId"], maxItems=2, nextToken=page1["nextToken"]
+ )
+ rows2 = [fields_map(row) for row in page2["results"]]
+ assert [row["@message"] for row in rows2] == ["t4"]
+ assert "nextToken" not in page2
+
+ # Before-direction shape: nearest earlier events, not the stream head.
+ q_before = logs.start_query(
+ logGroupName=group,
+ startTime=start_s,
+ endTime=end_s,
+ queryString=(
+ f"fields @timestamp, @message, @logStream "
+ f"| filter @logStream = '{stream}' "
+ f"| filter toMillis(@timestamp) <= {pivot} "
+ f"| sort @timestamp desc | limit 10000"
+ ),
+ limit=10000,
+ )
+ before = logs.get_query_results(queryId=q_before["queryId"], maxItems=2)
+ before_rows = [fields_map(row) for row in before["results"]]
+ assert [row["@message"] for row in before_rows] == ["t2", "t1"]
+
+
def test_logs_get_log_record_invalid_pointer(logs):
with pytest.raises(ClientError) as exc:
logs.get_log_record(logRecordPointer="does-not-exist", unmask=False)