Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
feat(logs): GetLogRecord, Insights @ptr rows, and StartLiveTail (#1287)
ovsteenba771d8523c25
diff --git a/README.md b/README.mdindex c3461487..d37743dc 100644--- a/README.md+++ b/README.md@@ -408,7 +408,7 @@ subnet = ec2.create_subnet(| **ECS Task Metadata V4** | `GET /v4/<token>`, `GET /v4/<token>/task`, `GET /v4/<token>/stats`, `GET /v4/<token>/task/stats` | Per-container token injected as `ECS_CONTAINER_METADATA_URI_V4` on every container started by `RunTask`. `/task` returns sibling containers in the same task. Containers reach the gateway via `host.docker.internal` (mapped through `extra_hosts: host-gateway`, so it works on user-defined Docker networks); `networkMode: host` containers use loopback. Volatile by design (stripped on persistence, cleared by `/_ministack/reset`) || **ECS Container Credentials** | `GET /v2/credentials/<uuid>` | The path real ECS exposes via `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/<uuid>` (resolved by SDKs against `169.254.170.2`). MiniStack serves the same path on the gateway and returns the AWS-strict 5-field credentials document (`AccessKeyId`, `SecretAccessKey`, `Token`, `Expiration`, `RoleArn`) — distinct from the IMDS shape served at `/latest/meta-data/iam/security-credentials/<role>`. `RunTask` injects `AWS_CONTAINER_CREDENTIALS_FULL_URI`, `AWS_CONTAINER_AUTHORIZATION_TOKEN` (satisfies botocore's allow-list for non-loopback gateway hosts), and `AWS_ENDPOINT_URL` so unmodified SDKs inside the task fetch credentials and route service calls through MiniStack with no client config || **SecretsManager** | CreateSecret, GetSecretValue, ListSecrets, DeleteSecret, UpdateSecret, DescribeSecret, PutSecretValue, UpdateSecretVersionStage, RestoreSecret, RotateSecret, GetRandomPassword, ListSecretVersionIds, ReplicateSecretToRegions, TagResource, UntagResource, PutResourcePolicy, GetResourcePolicy, DeleteResourcePolicy, ValidateResourcePolicy | |-| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion |+| **CloudWatch Logs** | CreateLogGroup, DeleteLogGroup, DescribeLogGroups, CreateLogStream, DeleteLogStream, DescribeLogStreams, PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, StartLiveTail, PutRetentionPolicy, DeleteRetentionPolicy, PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters, PutMetricFilter, DeleteMetricFilter, DescribeMetricFilters, TagLogGroup, UntagLogGroup, ListTagsLogGroup, TagResource, UntagResource, ListTagsForResource, StartQuery, GetQueryResults, StopQuery, PutDestination, DeleteDestination, DescribeDestinations, PutDestinationPolicy | `FilterLogEvents` supports `*`/`?` globs, multi-term AND, `-term` exclusion; `GetLogRecord` resolves Insights `@ptr` values issued at `PutLogEvents`; Insights CWLI subset: `fields`, chained `| filter` (`=` / `like /regex/`), `| sort @timestamp`, post-filter `| limit` as `min(query, API)`; `StartLiveTail` holds an AWS eventstream open until client disconnect and fans matching `PutLogEvents` into `sessionUpdate` frames (1s idle heartbeats; buffer of 10 updates, oldest dropped when full); use `Config(inject_host_prefix=False)` with a custom endpoint so boto3 does not prepend `stream-` to the hostname; `DescribeLogGroups` includes both `arn` (`:*`) and `logGroupArn` (no star) |### Extended Servicesdiff --git a/ministack/app.py b/ministack/app.pyindex 84da6b53..28f21980 100644--- a/ministack/app.py+++ b/ministack/app.py@@ -489,18 +489,14 @@ async def _read_request_body(receive, method: str, headers: dict) -> bytes:return _decode_aws_chunked_body(body, headers)-async def _send_response(send, status, headers, body):- """Send ASGI HTTP response."""+def _encode_header_value(v: str) -> bytes:+ try:+ return v.encode("latin-1")+ except UnicodeEncodeError:+ return v.encode("utf-8")- def _encode_header_value(v: str) -> bytes:- try:- return v.encode("latin-1")- except UnicodeEncodeError:- return v.encode("utf-8")- body_bytes = body if isinstance(body, bytes) else body.encode("utf-8")- if "content-length" not in {k.lower() for k in headers}:- headers["Content-Length"] = str(len(body_bytes))+def _asgi_header_list(headers: dict) -> list:# A list/tuple header value expands to one header line per item. This is# required for Set-Cookie, which RFC 6265 §3 forbids folding into a single# comma-joined header; APIGW Lambda-proxy responses surface multiple@@ -512,11 +508,24 @@ async def _send_response(send, status, headers, body):header_list.append((k.encode("latin-1"), _encode_header_value(str(item))))else:header_list.append((k.encode("latin-1"), _encode_header_value(str(v))))+ return header_list+++async def _send_response(send, status, headers, body):+ """Send ASGI HTTP response."""+ from ministack.core.responses import StreamingResponse++ if isinstance(body, StreamingResponse):+ raise TypeError("StreamingResponse requires _send_streaming_response(send, receive, ...)")++ body_bytes = body if isinstance(body, bytes) else body.encode("utf-8")+ if "content-length" not in {k.lower() for k in headers}:+ headers["Content-Length"] = str(len(body_bytes))await send({"type": "http.response.start","status": status,- "headers": header_list,+ "headers": _asgi_header_list(headers),})await send(@@ -528,11 +537,43 @@ async def _send_response(send, status, headers, body):)-async def _send_if_handled(send, response) -> bool:+async def _send_streaming_response(send, receive, status, headers, streaming):+ """Hold an HTTP response open and stream body chunks until the runner ends.++ Used by CloudWatch Logs ``StartLiveTail`` (and any future long-lived+ eventstream). Omits ``Content-Length`` so the ASGI server can chunk.+ """+ headers = {k: v for k, v in headers.items() if k.lower() != "content-length"}+ await send(+ {+ "type": "http.response.start",+ "status": status,+ "headers": _asgi_header_list(headers),+ }+ )+ try:+ await streaming.runner(send, receive)+ except Exception:+ logger.exception("Streaming response failed")+ try:+ await send({"type": "http.response.body", "body": b"", "more_body": False})+ except Exception:+ pass+++async def _send_if_handled(send, response, receive=None) -> bool:"""Send a response tuple and report whether the request was handled."""if response is None:return False- await _send_response(send, *response)+ from ministack.core.responses import StreamingResponse++ status, headers, body = response+ if isinstance(body, StreamingResponse):+ if receive is None:+ raise TypeError("StreamingResponse requires the ASGI receive channel")+ await _send_streaming_response(send, receive, status, headers, body)+ else:+ await _send_response(send, status, headers, body)return True@@ -1840,20 +1881,34 @@ async def app(scope, receive, send):# requests carry the credential in query params, not the header.set_request_region(extract_region(headers, query_params))- if await _send_if_handled(send, await _handle_pre_body_request(method, path, headers, query_params, request_id)):+ if await _send_if_handled(+ send, await _handle_pre_body_request(method, path, headers, query_params, request_id), receive+ ):returnbody = await _read_request_body(receive, method, headers)- if await _send_if_handled(send, await _handle_post_body_shortcuts(method, path, headers, body, query_params, request_id)):+ if await _send_if_handled(+ send, await _handle_post_body_shortcuts(method, path, headers, body, query_params, request_id), receive+ ):returnif await _send_if_handled(- send, await _handle_special_data_plane_request(method, path, headers, body, query_params, request_id)+ send,+ await _handle_special_data_plane_request(method, path, headers, body, query_params, request_id),+ receive,):return- await _send_response(send, *await _dispatch_service_request(method, path, headers, body, query_params, request_id))+ status, resp_headers, resp_body = await _dispatch_service_request(+ method, path, headers, body, query_params, request_id+ )+ from ministack.core.responses import StreamingResponse++ if isinstance(resp_body, StreamingResponse):+ await _send_streaming_response(send, receive, status, resp_headers, resp_body)+ else:+ await _send_response(send, status, resp_headers, resp_body)# ---------------------------------------------------------------------------diff --git a/ministack/core/responses.py b/ministack/core/responses.pyindex 21d79210..a9ae85a0 100644--- a/ministack/core/responses.py+++ b/ministack/core/responses.py@@ -421,6 +421,21 @@ def error_response_json(code: str, message: str, status: int = 400) -> tuple:}, body+class StreamingResponse:+ """Marker body for long-lived HTTP responses (chunked ASGI ``more_body``).++ Handlers return ``(status, headers, StreamingResponse(runner))``. The ASGI+ app sends ``http.response.start`` without ``Content-Length``, then awaits+ ``runner(send, receive)``. The runner should emit ``http.response.body``+ frames with ``more_body=True`` and finish with ``more_body=False``.+ """++ __slots__ = ("runner",)++ def __init__(self, runner):+ self.runner = runner++def now_iso() -> str:"""Current time in AWS ISO format."""return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"diff --git a/ministack/services/cloudwatch_logs.py b/ministack/services/cloudwatch_logs.pyindex a80498de..7a88275c 100644--- a/ministack/services/cloudwatch_logs.py+++ b/ministack/services/cloudwatch_logs.py@@ -3,7 +3,7 @@ CloudWatch Logs Service Emulator.JSON-based API via X-Amz-Target (Logs_20140328).Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,CreateLogStream, DeleteLogStream, DescribeLogStreams,- PutLogEvents, GetLogEvents, FilterLogEvents,+ PutLogEvents, GetLogEvents, FilterLogEvents, GetLogRecord, StartLiveTail,PutRetentionPolicy, DeleteRetentionPolicy,PutSubscriptionFilter, DeleteSubscriptionFilter, DescribeSubscriptionFilters,TagLogGroup, UntagLogGroup, ListTagsLogGroup,@@ -18,17 +18,22 @@ Supports: CreateLogGroup, DeleteLogGroup, DescribeLogGroups,"""import base64+import contextlibimport copyimport fnmatchimport jsonimport loggingimport os+import reimport time+import zlib+from datetime import datetime, timezonefrom ministack.core.arn import ArnParseError, parse_arnfrom ministack.core.responses import (AccountRegionScopedDict,AccountScopedDict,+ StreamingResponse,error_response_json,get_account_id,get_region,@@ -62,7 +67,16 @@ _metric_filters = AccountRegionScopedDict()# (log_group_name, filter_name) -> {filterName, logGroupName, filterPattern, metricTransformations, creationTime}_queries = AccountRegionScopedDict()-# query_id -> {queryId, logGroupName, startTime, endTime, queryString, status}+# query_id -> {queryId, logGroupName, startTime, endTime, queryString, status,+# results, statistics}++# Opaque Insights/GetLogRecord pointers → full transformed log record fields.+# Keys are UUID strings assigned at PutLogEvents time (AWS-shaped: opaque).+_log_records = AccountRegionScopedDict()+# ptr -> {+# "@ptr", "@timestamp", "@message", "@logStream", "@log",+# "_timestamp_ms" (internal; stripped from GetLogRecord responses)+# }_delivery_sources = AccountRegionScopedDict()# source_name -> {name, arn, resourceArns: [str], logType, service, tags}@@ -76,6 +90,15 @@ _deliveries = AccountRegionScopedDict()# deliveryDestinationType, recordFields, fieldDelimiter,# s3DeliveryConfiguration, tags}+# Active StartLiveTail sessions (not persisted). session_id -> session dict.+# Populated while an ASGI stream is open; PutLogEvents fans matching events in.+_live_tail_sessions: dict[str, dict] = {}++# AWS Live Tail: one sessionUpdate per second (empty when idle), and at most+# 10 buffered sessionUpdate events before the oldest is dropped.+_LIVE_TAIL_IDLE_SECONDS = 1.0+_LIVE_TAIL_QUEUE_MAX = 10+# ── Persistence ────────────────────────────────────────────@@ -85,6 +108,7 @@ def get_state():"destinations": copy.deepcopy(_destinations),"metric_filters": copy.deepcopy(_metric_filters),"queries": copy.deepcopy(_queries),+ "log_records": copy.deepcopy(_log_records),"delivery_sources": copy.deepcopy(_delivery_sources),"delivery_destinations": copy.deepcopy(_delivery_destinations),"deliveries": copy.deepcopy(_deliveries),@@ -170,6 +194,7 @@ def restore_state(data):_destinations.update(data.get("destinations", {}))_restore_metric_filters(data.get("metric_filters", {}))_restore_queries(data.get("queries", {}))+ _log_records.update(data.get("log_records", {}))_delivery_sources.update(data.get("delivery_sources", {}))_delivery_destinations.update(data.get("delivery_destinations", {}))_deliveries.update(data.get("deliveries", {}))@@ -194,6 +219,11 @@ def _make_group_arn(name):return f"arn:aws:logs:{get_region()}:{get_account_id()}:log-group:{name}:*"+def _make_group_arn_no_star(name):+ """ARN form accepted by StartLiveTail (no trailing ``:*``)."""+ return f"arn:aws:logs:{get_region()}:{get_account_id()}:log-group:{name}"++def _resolve_group_by_arn(arn):"""Return the group name whose ARN matches, or None.Accepts both 'arn:...:log-group:name' and 'arn:...:log-group:name:*'@@ -262,6 +292,8 @@ async def handle_request(method, path, headers, body, query_params):"PutLogEvents": _put_log_events,"GetLogEvents": _get_log_events,"FilterLogEvents": _filter_log_events,+ "GetLogRecord": _get_log_record,+ "StartLiveTail": _start_live_tail,"PutRetentionPolicy": _put_retention_policy,"DeleteRetentionPolicy": _delete_retention_policy,"PutSubscriptionFilter": _put_subscription_filter,@@ -334,6 +366,7 @@ def _delete_log_group(data):"ResourceNotFoundException",f"The specified log group does not exist: {name}", 400,)+ _forget_log_records_for_group(name)del _log_groups[name]return json_response({})@@ -366,6 +399,7 @@ def _describe_log_groups(data):entry = {"logGroupName": n,"arn": g["arn"],+ "logGroupArn": _make_group_arn_no_star(n),"creationTime": g["creationTime"],"storedBytes": sum(sum(len(e.get("message", "")) for e in s["events"])@@ -429,6 +463,7 @@ def _delete_log_stream(data):"ResourceNotFoundException",f"The specified log stream does not exist: {stream}", 400,)+ _forget_log_records_for_stream(group, stream)del _log_groups[group]["streams"][stream]return json_response({})@@ -512,7 +547,20 @@ def _put_log_events(data):for e in events:ts = e.get("timestamp", now_ms)msg = e.get("message", "")- s["events"].append({"timestamp": ts, "message": msg, "ingestionTime": now_ms})+ ptr = new_uuid()+ s["events"].append({+ "timestamp": ts,+ "message": msg,+ "ingestionTime": now_ms,+ "eventId": ptr,+ })+ _log_records[ptr] = _build_log_record(+ ptr=ptr,+ timestamp_ms=ts,+ message=msg,+ log_group=group,+ log_stream=stream,+ )if s["firstEventTimestamp"] is None or ts < s["firstEventTimestamp"]:s["firstEventTimestamp"] = ts@@ -524,9 +572,362 @@ def _put_log_events(data):s["uploadSequenceToken"] = token_fanout_to_subscription_filters(group, stream, events)+ # Fan out the stored shape (ingestionTime filled) to any Live Tail sessions.+ stored = s["events"][-len(events) :] if events else []+ _fanout_to_live_tail_sessions(group, stream, stored)return json_response({"nextSequenceToken": token})+def _format_insights_timestamp(timestamp_ms: int) -> str:+ """AWS Logs Insights @timestamp string (UTC, millisecond precision)."""+ dt = datetime.fromtimestamp(timestamp_ms / 1000.0, tz=timezone.utc)+ return dt.strftime("%Y-%m-%d %H:%M:%S.") + f"{dt.microsecond // 1000:03d}"+++def _build_log_record(*, ptr, timestamp_ms, message, log_group, log_stream):+ return {+ "@ptr": ptr,+ "@timestamp": _format_insights_timestamp(timestamp_ms),+ "@message": message,+ "@logStream": log_stream,+ "@log": log_group,+ "_timestamp_ms": timestamp_ms,+ }+++def _public_log_record(record: dict) -> dict:+ """Strip MiniStack-internal fields before returning GetLogRecord payload."""+ return {k: v for k, v in record.items() if not k.startswith("_")}+++def _forget_log_records_for_stream(group_name: str, stream_name: str) -> None:+ to_delete = [+ ptr+ for ptr, record in list(_log_records.items())+ if record.get("@log") == group_name and record.get("@logStream") == stream_name+ ]+ for ptr in to_delete:+ del _log_records[ptr]+++def _forget_log_records_for_group(group_name: str) -> None:+ to_delete = [+ ptr for ptr, record in list(_log_records.items()) if record.get("@log") == group_name+ ]+ for ptr in to_delete:+ del _log_records[ptr]+++def _get_log_record(data):+ """Retrieve the full transformed field map for one Insights ``@ptr``.++ AWS accepts ``unmask``; MiniStack does not implement field masking, so the+ flag is accepted and ignored. Invalid/missing pointers raise+ ``InvalidParameterException`` (AWS behavior).+ """+ ptr = data.get("logRecordPointer")+ if not ptr:+ return error_response_json(+ "InvalidParameterException",+ "1 validation error detected: Value null at 'logRecordPointer' "+ "failed to satisfy constraint: Member must not be null",+ 400,+ )+ # Accepted for SDK/AWS parity; masking is not implemented.+ _ = data.get("unmask", False)++ record = _log_records.get(ptr)+ if not record:+ return error_response_json(+ "InvalidParameterException",+ "Invalid logRecordPointer provided",+ 400,+ )+ return json_response({"logRecord": _public_log_record(record)})+++# ---------------------------------------------------------------------------+# Live Tail (StartLiveTail eventstream)+# ---------------------------------------------------------------------------++def _es_encode_message(headers: dict[str, str], payload: bytes) -> bytes:+ """Encode one ``application/vnd.amazon.eventstream`` message (AWS wire format)."""+ hdr_bytes = bytearray()+ for name, value in headers.items():+ name_b = name.encode("utf-8")+ val_b = value.encode("utf-8")+ hdr_bytes.append(len(name_b))+ hdr_bytes.extend(name_b)+ hdr_bytes.append(7) # string+ hdr_bytes.extend(len(val_b).to_bytes(2, "big"))+ hdr_bytes.extend(val_b)++ headers_length = len(hdr_bytes)+ total_length = 12 + headers_length + len(payload) + 4+ prelude = total_length.to_bytes(4, "big") + headers_length.to_bytes(4, "big")+ prelude_crc = zlib.crc32(prelude).to_bytes(4, "big")+ msg_head = prelude + prelude_crc + bytes(hdr_bytes) + payload+ message_crc = zlib.crc32(msg_head).to_bytes(4, "big")+ return msg_head + message_crc+++def _es_event(event_type: str, payload: dict) -> bytes:+ return _es_encode_message(+ {+ ":message-type": "event",+ ":event-type": event_type,+ ":content-type": "application/json",+ },+ json.dumps(payload, ensure_ascii=False).encode("utf-8"),+ )+++def _resolve_live_tail_group_name(identifier: str) -> str | None:+ """Resolve a StartLiveTail logGroupIdentifier (ARN without ``:*``, or bare name)."""+ if not identifier:+ return None+ if identifier.startswith("arn:"):+ if identifier.endswith(":*"):+ return None # AWS rejects trailing :* for Live Tail identifiers+ return _log_group_name_from_identifier_arn(identifier) or _resolve_group_by_arn(identifier)+ if identifier in _log_groups:+ return identifier+ return None+++def _live_tail_stream_allowed(stream_name: str, stream_names, stream_prefixes) -> bool:+ if stream_names:+ return stream_name in stream_names+ if stream_prefixes:+ return any(stream_name.startswith(prefix) for prefix in stream_prefixes)+ return True+++def _fanout_to_live_tail_sessions(group_name: str, stream_name: str, events: list[dict]) -> None:+ """Push matching PutLogEvents into active Live Tail session queues."""+ import asyncio++ if not events or not _live_tail_sessions:+ return+ account_id = get_account_id()+ region = get_region()+ for session in list(_live_tail_sessions.values()):+ if session.get("account_id") != account_id or session.get("region") != region:+ continue+ if group_name not in session["group_names"]:+ continue+ if not _live_tail_stream_allowed(+ stream_name, session.get("stream_names"), session.get("stream_prefixes")+ ):+ continue+ identifier = session["identifiers_by_name"][group_name]+ filter_pattern = session.get("filter_pattern") or ""+ matched = []+ for event in events:+ message = event.get("message", "")+ if not _subscription_pattern_matches(filter_pattern, message):+ continue+ matched.append(+ {+ "logStreamName": stream_name,+ "logGroupIdentifier": identifier,+ "message": message,+ "timestamp": event.get("timestamp"),+ "ingestionTime": event.get("ingestionTime"),+ }+ )+ if not matched:+ continue+ queue = session["queue"]+ item = (matched, False)+ try:+ queue.put_nowait(item)+ except asyncio.QueueFull:+ # AWS keeps at most 10 LiveTailSessionUpdate events; drop oldest.+ session["sampled"] = True+ with contextlib.suppress(asyncio.QueueEmpty):+ queue.get_nowait()+ with contextlib.suppress(asyncio.QueueFull):+ queue.put_nowait((matched, True))+++async def _await_http_disconnect(receive) -> None:+ while True:+ message = await receive()+ if message.get("type") == "http.disconnect":+ return+++def _start_live_tail(data):+ """Start a Live Tail session.++ Holds the HTTP eventstream open until the client disconnects. Matching+ ``PutLogEvents`` calls fan into ``sessionUpdate`` frames via an asyncio+ queue (same pattern as API Gateway WebSocket outboxes). Idle empty+ ``sessionUpdate`` frames are emitted once per second (AWS cadence). At most+ 10 updates are buffered; overflow drops the oldest and sets ``sampled``.+ """+ import asyncio++ identifiers = data.get("logGroupIdentifiers") or []+ if not identifiers:+ return error_response_json(+ "InvalidParameterException",+ "1 validation error detected: Value null at 'logGroupIdentifiers' "+ "failed to satisfy constraint: Member must not be null",+ 400,+ )+ if len(identifiers) > 10:+ return error_response_json(+ "InvalidParameterException",+ "logGroupIdentifiers may contain at most 10 items",+ 400,+ )++ stream_names = data.get("logStreamNames") or None+ stream_prefixes = data.get("logStreamNamePrefixes") or None+ if stream_names and stream_prefixes:+ return error_response_json(+ "InvalidParameterException",+ "logStreamNames and logStreamNamePrefixes are mutually exclusive",+ 400,+ )+ if (stream_names or stream_prefixes) and len(identifiers) != 1:+ return error_response_json(+ "InvalidParameterException",+ "logStreamNames/logStreamNamePrefixes require exactly one log group",+ 400,+ )++ resolved_names: list[str] = []+ identifiers_by_name: dict[str, str] = {}+ for identifier in identifiers:+ name = _resolve_live_tail_group_name(identifier)+ if not name or name not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {identifier}",+ 400,+ )+ if name not in resolved_names:+ resolved_names.append(name)+ identifiers_by_name[name] = (+ identifier if identifier.startswith("arn:") else _make_group_arn_no_star(name)+ )++ filter_pattern = data.get("logEventFilterPattern") or ""+ request_id = new_uuid()+ session_id = new_uuid()+ start_payload = {+ "requestId": request_id,+ "sessionId": session_id,+ "logGroupIdentifiers": [identifiers_by_name[n] for n in resolved_names],+ }+ if stream_names:+ start_payload["logStreamNames"] = list(stream_names)+ if stream_prefixes:+ start_payload["logStreamNamePrefixes"] = list(stream_prefixes)+ if filter_pattern:+ start_payload["logEventFilterPattern"] = filter_pattern++ account_id = get_account_id()+ region = get_region()++ initial_bytes = _es_encode_message(+ {+ ":message-type": "event",+ ":event-type": "initial-response",+ ":content-type": "application/json",+ },+ b"{}",+ )+ start_bytes = _es_event("sessionStart", start_payload)++ async def _run(send, receive):+ async def _send_chunk(payload: bytes, *, more: bool = True) -> None:+ await send({"type": "http.response.body", "body": payload, "more_body": more})++ # Register before the first await so concurrent PutLogEvents cannot race+ # past sessionStart into a missing session.+ queue: asyncio.Queue = asyncio.Queue(maxsize=_LIVE_TAIL_QUEUE_MAX)+ session = {+ "session_id": session_id,+ "account_id": account_id,+ "region": region,+ "group_names": set(resolved_names),+ "identifiers_by_name": identifiers_by_name,+ "stream_names": list(stream_names) if stream_names else None,+ "stream_prefixes": list(stream_prefixes) if stream_prefixes else None,+ "filter_pattern": filter_pattern,+ "queue": queue,+ "sampled": False,+ }+ _live_tail_sessions[session_id] = session++ await _send_chunk(initial_bytes)+ await _send_chunk(start_bytes)++ disconnect_task = asyncio.create_task(_await_http_disconnect(receive))+ try:+ while not disconnect_task.done():+ get_task = asyncio.create_task(queue.get())+ done, _pending = await asyncio.wait(+ {get_task, disconnect_task},+ timeout=_LIVE_TAIL_IDLE_SECONDS,+ return_when=asyncio.FIRST_COMPLETED,+ )+ if disconnect_task in done:+ get_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await get_task+ break+ if get_task in done:+ item = get_task.result()+ if item is None:+ break+ results, sampled_flag = item+ sampled = bool(sampled_flag or session.get("sampled"))+ session["sampled"] = False+ await _send_chunk(+ _es_event(+ "sessionUpdate",+ {+ "sessionMetadata": {"sampled": sampled},+ "sessionResults": results,+ },+ )+ )+ else:+ get_task.cancel()+ with contextlib.suppress(asyncio.CancelledError):+ await get_task+ await _send_chunk(+ _es_event(+ "sessionUpdate",+ {+ "sessionMetadata": {"sampled": False},+ "sessionResults": [],+ },+ )+ )+ finally:+ _live_tail_sessions.pop(session_id, None)+ disconnect_task.cancel()+ with contextlib.suppress(asyncio.CancelledError, Exception):+ await disconnect_task+ with contextlib.suppress(Exception):+ await _send_chunk(b"", more=False)++ return (+ 200,+ {+ "Content-Type": "application/vnd.amazon.eventstream",+ "x-amzn-RequestId": request_id,+ },+ StreamingResponse(_run),+ )++def _subscription_pattern_matches(pattern, message):"""Minimal CloudWatch Logs filter-pattern match: an empty pattern matchesevery event; otherwise every bare term in the pattern must appear in the@@ -1065,19 +1466,307 @@ def _describe_metric_filters(data):# ----------------------------------------------------------------------------# CloudWatch Logs Insights (stubs)+# CloudWatch Logs Insights# ---------------------------------------------------------------------------+def _split_insights_pipes(query_string: str) -> list[str]:+ """Split a CWLI query on ``|`` outside quotes and ``/regex/`` literals."""+ text = query_string or ""+ parts: list[str] = []+ buf: list[str] = []+ i = 0+ n = len(text)+ while i < n:+ ch = text[i]+ if ch == "|":+ parts.append("".join(buf).strip())+ buf = []+ i += 1+ continue+ if ch in ("'", '"'):+ quote = ch+ buf.append(ch)+ i += 1+ while i < n:+ c = text[i]+ buf.append(c)+ if c == "\\" and i + 1 < n:+ buf.append(text[i + 1])+ i += 2+ continue+ if c == quote:+ i += 1+ break+ i += 1+ continue+ if ch == "/":+ buf.append(ch)+ i += 1+ while i < n:+ c = text[i]+ buf.append(c)+ if c == "\\" and i + 1 < n:+ buf.append(text[i + 1])+ i += 2+ continue+ if c == "/":+ i += 1+ # optional flags (e.g. i)+ while i < n and text[i].isalpha():+ buf.append(text[i])+ i += 1+ break+ i += 1+ continue+ buf.append(ch)+ i += 1+ parts.append("".join(buf).strip())+ return [p for p in parts if p]+++def _parse_insights_fields(query_string: str) -> list[str]:+ """Extract field names from a simple ``fields a, b | ...`` Insights query.++ Falls back to the CWLT/default set when the query has no fields clause.+ Supports a CWLI subset: ``fields``, ``filter``, ``sort @timestamp``, ``limit``.+ """+ for stage in _split_insights_pipes(query_string):+ match = re.match(r"(?i)^fields\s+(.+)$", stage.strip())+ if match:+ fields = [part.strip() for part in match.group(1).split(",") if part.strip()]+ if "@ptr" not in fields:+ fields.append("@ptr")+ return fields+ return ["@timestamp", "@message", "@logStream", "@log", "@ptr"]+++def _clamp_insights_limit(value) -> int | None:+ try:+ return max(1, min(int(value), 10000))+ except (TypeError, ValueError):+ return None+++def _parse_insights_limit(query_string: str, explicit_limit) -> int:+ """Effective Insights limit: ``min(query | limit, StartQuery limit)``.++ Both sides default to 10000 when omitted. The query-string limit must apply+ to the post-filter result set and must not be bypassed by a large API limit.+ """+ pipe_limit = None+ for stage in _split_insights_pipes(query_string):+ match = re.match(r"(?i)^limit\s+(\d+)\s*$", stage.strip())+ if match:+ pipe_limit = _clamp_insights_limit(match.group(1))+ api_limit = _clamp_insights_limit(explicit_limit) if explicit_limit is not None else None+ if pipe_limit is None and api_limit is None:+ return 10000+ if pipe_limit is None:+ return api_limit+ if api_limit is None:+ return pipe_limit+ return min(pipe_limit, api_limit)+++def _compile_insights_filter(stage: str):+ """Compile one ``filter`` stage into a predicate ``record -> bool``.++ Supported forms:+ - ``filter @logStream = 'exact'``+ - ``filter @message like /pattern/`` or ``/pattern/i``+ """+ text = stage.strip()+ if not re.match(r"(?i)^filter\b", text):+ return None+ body = re.sub(r"(?i)^filter\s+", "", text, count=1).strip()++ eq = re.match(r"^(@\w+)\s*=\s*'((?:\\'|[^'])*)'\s*$", body)+ if eq:+ field, raw = eq.group(1), eq.group(2).replace("\\'", "'")++ def _eq_pred(record, _field=field, _raw=raw):+ public = _public_log_record(record)+ return str(public.get(_field, "")) == _raw++ return _eq_pred++ like = re.match(r"^(@\w+)\s+like\s+/((?:\\.|[^/])*)/([i]*)\s*$", body, re.IGNORECASE)+ if like:+ field, pattern, flags_s = like.group(1), like.group(2), like.group(3)+ flags = re.IGNORECASE if "i" in (flags_s or "").lower() else 0+ try:+ compiled = re.compile(pattern, flags)+ except re.error:+ return lambda _record: False++ def _like_pred(record, _field=field, _compiled=compiled):+ public = _public_log_record(record)+ return _compiled.search(str(public.get(_field, ""))) is not None++ return _like_pred++ # Unsupported filter form — ignore (subset emulator).+ return None+++def _parse_insights_sort(query_string: str) -> tuple[str, bool] | None:+ """Return ``(field, ascending)`` for ``sort @timestamp [asc|desc]``, else None."""+ for stage in _split_insights_pipes(query_string):+ match = re.match(+ r"(?i)^sort\s+(@\w+)(?:\s+(asc|desc))?\s*$",+ stage.strip(),+ )+ if match:+ field = match.group(1)+ direction = (match.group(2) or "asc").lower()+ return field, direction != "desc"+ return None+++def _insights_filter_predicates(query_string: str) -> list:+ preds = []+ for stage in _split_insights_pipes(query_string):+ if not re.match(r"(?i)^filter\b", stage.strip()):+ continue+ pred = _compile_insights_filter(stage)+ if pred is not None:+ preds.append(pred)+ return preds+++def _apply_insights_sort(records: list[dict], query_string: str) -> list[dict]:+ sort_spec = _parse_insights_sort(query_string)+ if not sort_spec:+ return records+ field, ascending = sort_spec+ if field == "@timestamp":+ return sorted(+ records,+ key=lambda r: r.get("_timestamp_ms", 0),+ reverse=not ascending,+ )+ return sorted(+ records,+ key=lambda r: str(_public_log_record(r).get(field, "")),+ reverse=not ascending,+ )+++def _resolve_query_log_groups(data) -> list[str]:+ groups: list[str] = []+ if data.get("logGroupName"):+ groups.append(data["logGroupName"])+ for name in data.get("logGroupNames") or []:+ if name and name not in groups:+ groups.append(name)+ for identifier in data.get("logGroupIdentifiers") or []:+ # Accept plain names or ARNs (...:log-group:NAME[:*]).+ name = identifier+ if ":log-group:" in identifier:+ name = identifier.split(":log-group:", 1)[1]+ if name.endswith(":*"):+ name = name[:-2]+ elif ":" in name:+ name = name.split(":", 1)[0]+ if name and name not in groups:+ groups.append(name)+ return groups+++def _collect_query_records(group_names, start_time_s, end_time_s):+ """Collect stored log records in [start, end] (epoch seconds, AWS Insights)."""+ start_ms = int(start_time_s) * 1000+ end_ms = int(end_time_s) * 1000+ collected = []+ for group_name in group_names:+ group = _log_groups.get(group_name)+ if not group:+ continue+ for stream_name, stream in group.get("streams", {}).items():+ for event in stream.get("events", []):+ ts = event.get("timestamp", 0)+ if ts < start_ms or ts > end_ms:+ continue+ ptr = event.get("eventId")+ record = _log_records.get(ptr) if ptr else None+ if not record:+ # Rebuild for events ingested before ptr indexing existed.+ ptr = ptr or new_uuid()+ record = _build_log_record(+ ptr=ptr,+ timestamp_ms=ts,+ message=event.get("message", ""),+ log_group=group_name,+ log_stream=stream_name,+ )+ _log_records[ptr] = record+ event["eventId"] = ptr+ collected.append(record)+ collected.sort(key=lambda r: r.get("_timestamp_ms", 0))+ return collected+++def _row_from_record(record: dict, fields: list[str]) -> list[dict]:+ public = _public_log_record(record)+ return [{"field": field, "value": str(public.get(field, ""))} for field in fields]++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``.+ Filters are AND-ed; ``limit`` applies after filter+sort as+ ``min(query limit, StartQuery limit)``.+ """+ group_names = _resolve_query_log_groups(data)+ if not group_names:+ return error_response_json(+ "InvalidParameterException",+ "logGroupName, logGroupNames, or logGroupIdentifiers is required",+ 400,+ )+ for name in group_names:+ if name not in _log_groups:+ return error_response_json(+ "ResourceNotFoundException",+ f"The specified log group does not exist: {name}",+ 400,+ )++ query_string = data.get("queryString", "")+ fields = _parse_insights_fields(query_string)+ limit = _parse_insights_limit(query_string, data.get("limit"))+ start_time = data.get("startTime", 0)+ end_time = data.get("endTime", int(time.time()))++ scanned = _collect_query_records(group_names, start_time, end_time)+ predicates = _insights_filter_predicates(query_string)+ if predicates:+ filtered = [r for r in scanned if all(pred(r) for pred in predicates)]+ else:+ filtered = list(scanned)+ ordered = _apply_insights_sort(filtered, query_string)+ limited = ordered[:limit]+ results = [_row_from_record(record, fields) for record in limited]+ bytes_scanned = float(sum(len(r.get("@message", "")) for r in scanned))+query_id = new_uuid()_queries[query_id] = {"queryId": query_id,"logGroupName": data.get("logGroupName", ""),"logGroupNames": data.get("logGroupNames", []),- "startTime": data.get("startTime", 0),- "endTime": data.get("endTime", 0),- "queryString": data.get("queryString", ""),+ "logGroupIdentifiers": data.get("logGroupIdentifiers", []),+ "startTime": start_time,+ "endTime": end_time,+ "queryString": query_string,"status": "Complete",+ "results": results,+ "statistics": {+ "recordsMatched": float(len(filtered)),+ "recordsScanned": float(len(scanned)),+ "bytesScanned": bytes_scanned,+ },}return json_response({"queryId": query_id})@@ -1092,8 +1781,11 @@ def _get_query_results(data):)return json_response({"status": query["status"],- "results": [],- "statistics": {"recordsMatched": 0.0, "recordsScanned": 0.0, "bytesScanned": 0.0},+ "results": query.get("results", []),+ "statistics": query.get(+ "statistics",+ {"recordsMatched": 0.0, "recordsScanned": 0.0, "bytesScanned": 0.0},+ ),})@@ -1109,9 +1801,17 @@ def reset():_destinations.clear()_metric_filters.clear()_queries.clear()+ _log_records.clear()_delivery_sources.clear()_delivery_destinations.clear()_deliveries.clear()+ # Wake any held Live Tail streams so they exit on reset.+ for session in list(_live_tail_sessions.values()):+ queue = session.get("queue")+ if queue is not None:+ with contextlib.suppress(Exception):+ queue.put_nowait(None)+ _live_tail_sessions.clear()# ---------------------------------------------------------------------------diff --git a/tests/conftest.py b/tests/conftest.pyindex 4621bc61..a563c6f8 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -253,7 +253,10 @@ def sm():@pytest.fixture(scope="session")def logs():- return make_client("logs")+ # StartLiveTail uses hostPrefix ``stream-``; with a custom endpoint that+ # becomes ``stream-127.0.0.1`` which does not resolve. Disable injection so+ # Live Tail hits the same MiniStack listener as every other Logs API.+ return make_client("logs", additional_config_kwargs={"inject_host_prefix": False})@pytest.fixture(scope="session")diff --git a/tests/test_cloudwatch_logs.py b/tests/test_cloudwatch_logs.pyindex 6ab71392..4e9c2404 100644--- a/tests/test_cloudwatch_logs.py+++ b/tests/test_cloudwatch_logs.py@@ -321,6 +321,245 @@ def test_logs_insights_start_query(logs):results = logs.get_query_results(queryId=resp["queryId"])assert results["status"] in ("Complete", "Running", "Scheduled")++def test_logs_get_log_record_round_trip(logs):+ """PutLogEvents assigns opaque @ptr; Insights returns it; GetLogRecord resolves fields."""+ import uuid as _uuid++ group = f"/intg/get-log-record/{_uuid.uuid4().hex[:8]}"+ stream = "stream-a"+ now_ms = int(time.time() * 1000)+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream,+ logEvents=[+ {"timestamp": now_ms - 1000, "message": "before"},+ {"timestamp": now_ms, "message": '{"log":"anchor-row"}'},+ {"timestamp": now_ms + 1000, "message": "after"},+ ],+ )++ query = logs.start_query(+ logGroupName=group,+ startTime=(now_ms // 1000) - 60,+ endTime=(now_ms // 1000) + 60,+ queryString="fields @timestamp, @message, @logStream, @log | sort @timestamp asc | limit 10",+ limit=10,+ )+ results = logs.get_query_results(queryId=query["queryId"])+ assert results["status"] == "Complete"+ assert len(results["results"]) == 3++ def fields_map(row):+ return {cell["field"]: cell["value"] for cell in row}++ rows = [fields_map(row) for row in results["results"]]+ assert all("@ptr" in row and row["@ptr"] for row in rows)+ assert rows[1]["@message"] == '{"log":"anchor-row"}'+ assert rows[1]["@logStream"] == stream+ assert rows[1]["@log"] == group++ record = logs.get_log_record(logRecordPointer=rows[1]["@ptr"], unmask=False)["logRecord"]+ assert record["@message"] == '{"log":"anchor-row"}'+ assert record["@logStream"] == stream+ assert record["@ptr"] == rows[1]["@ptr"]+ assert "_timestamp_ms" not in record+++def test_logs_insights_filter_sort_limit(logs):+ """CWLI filter/sort/limit: stream equality, like regex, AND, sort, post-filter limit."""+ import uuid as _uuid++ group = f"/intg/insights-filter/{_uuid.uuid4().hex[:8]}"+ stream_a = "nerv-deployment-aaa"+ stream_b = "mbir-deployment-5d66976c69-p8qr6"+ now_ms = int(time.time() * 1000)+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream_a)+ logs.create_log_stream(logGroupName=group, logStreamName=stream_b)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream_a,+ logEvents=[+ {"timestamp": now_ms - 4000, "message": "nerv has a link too"},+ {"timestamp": now_ms - 3000, "message": "nerv other"},+ ],+ )+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream_b,+ logEvents=[+ {"timestamp": now_ms - 2000, "message": "first link event"},+ {"timestamp": now_ms - 1000, "message": "no match here"},+ {"timestamp": now_ms, "message": "second link event"},+ {"timestamp": now_ms + 1000, "message": "third link event"},+ ],+ )++ def fields_map(row):+ return {cell["field"]: cell["value"] for cell in row}++ # @logStream equality+ q1 = logs.start_query(+ logGroupName=group,+ startTime=(now_ms // 1000) - 60,+ endTime=(now_ms // 1000) + 60,+ queryString=(+ f"fields @timestamp, @message, @logStream "+ f"| filter @logStream = '{stream_b}' "+ f"| sort @timestamp asc | limit 20"+ ),+ limit=1000,+ )+ r1 = logs.get_query_results(queryId=q1["queryId"])+ assert r1["status"] == "Complete"+ rows1 = [fields_map(row) for row in r1["results"]]+ assert len(rows1) == 4+ assert all(row["@logStream"] == stream_b for row in rows1)+ assert r1["statistics"]["recordsScanned"] == 6.0+ assert r1["statistics"]["recordsMatched"] == 4.0++ # @message like /link/+ q2 = logs.start_query(+ logGroupName=group,+ startTime=(now_ms // 1000) - 60,+ endTime=(now_ms // 1000) + 60,+ queryString=(+ "fields @timestamp, @message, @logStream "+ "| filter @message like /link/ "+ "| sort @timestamp asc | limit 20"+ ),+ limit=1000,+ )+ r2 = logs.get_query_results(queryId=q2["queryId"])+ rows2 = [fields_map(row) for row in r2["results"]]+ assert len(rows2) == 4 # nerv link + 3 mbir links+ assert all("link" in row["@message"] for row in rows2)++ # AND filters + sort + query limit vs large API limit+ q3 = logs.start_query(+ logGroupName=group,+ startTime=(now_ms // 1000) - 60,+ endTime=(now_ms // 1000) + 60,+ queryString=(+ f"fields @timestamp, @message, @logStream "+ f"| filter @logStream = '{stream_b}' "+ f"| filter @message like /link/ "+ f"| sort @timestamp asc | limit 2"+ ),+ limit=1000,+ )+ r3 = logs.get_query_results(queryId=q3["queryId"])+ rows3 = [fields_map(row) for row in r3["results"]]+ assert len(rows3) == 2+ assert all(row["@logStream"] == stream_b for row in rows3)+ assert all("link" in row["@message"] for row in rows3)+ assert rows3[0]["@message"] == "first link event"+ assert rows3[1]["@message"] == "second link event"+ assert r3["statistics"]["recordsMatched"] == 3.0+ assert r3["statistics"]["recordsScanned"] == 6.0+++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)+ assert exc.value.response["Error"]["Code"] == "InvalidParameterException"+++def test_logs_describe_includes_log_group_arn_without_star(logs):+ import uuid as _uuid++ group = f"/intg/log-group-arn/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ described = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]+ assert described["arn"].endswith(":*")+ assert described["logGroupArn"] == described["arn"].removesuffix(":*")+ assert ":*" not in described["logGroupArn"].split("log-group:")[-1]+++def test_logs_start_live_tail_receives_put_events(logs):+ """StartLiveTail stays open and receives matching PutLogEvents until disconnect."""+ import threading+ import uuid as _uuid++ group = f"/intg/live-tail/{_uuid.uuid4().hex[:8]}"+ stream = "app/stream-1"+ logs.create_log_group(logGroupName=group)+ logs.create_log_stream(logGroupName=group, logStreamName=stream)+ arn = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]["logGroupArn"]++ started = threading.Event()+ got_events = threading.Event()+ errors: list[BaseException] = []+ seen: list[str] = []+ stream_holder: dict = {}++ def _tail():+ try:+ response = logs.start_live_tail(+ logGroupIdentifiers=[arn],+ logEventFilterPattern="ERROR",+ )+ event_stream = response["responseStream"]+ stream_holder["stream"] = event_stream+ started.set()+ for event in event_stream:+ if "sessionStart" in event:+ assert event["sessionStart"]["sessionId"]+ assert arn in event["sessionStart"]["logGroupIdentifiers"]+ continue+ if "sessionUpdate" not in event:+ continue+ for item in event["sessionUpdate"].get("sessionResults") or []:+ seen.append(item["message"])+ assert item["logStreamName"] == stream+ assert item["logGroupIdentifier"] == arn+ if "ERROR boom" in seen and "ERROR again" in seen:+ got_events.set()+ break+ except BaseException as exc: # noqa: BLE001 — surface to main thread+ errors.append(exc)+ started.set()+ got_events.set()++ worker = threading.Thread(target=_tail, daemon=True)+ worker.start()+ assert started.wait(10), f"StartLiveTail did not start: {errors}"+ time.sleep(0.3) # allow session registration on the server++ now_ms = int(time.time() * 1000)+ logs.put_log_events(+ logGroupName=group,+ logStreamName=stream,+ logEvents=[+ {"timestamp": now_ms - 2000, "message": "INFO ok"},+ {"timestamp": now_ms - 1000, "message": "ERROR boom"},+ {"timestamp": now_ms, "message": "ERROR again"},+ ],+ )+ assert got_events.wait(10), f"timed out waiting for Live Tail events; seen={seen} errors={errors}"+ assert not errors, errors+ assert seen == ["ERROR boom", "ERROR again"]++ event_stream = stream_holder.get("stream")+ if event_stream is not None:+ event_stream.close()+ worker.join(timeout=5)+++def test_logs_start_live_tail_rejects_star_arn(logs):+ import uuid as _uuid++ group = f"/intg/live-tail-star/{_uuid.uuid4().hex[:8]}"+ logs.create_log_group(logGroupName=group)+ starred = logs.describe_log_groups(logGroupNamePrefix=group)["logGroups"][0]["arn"]+ with pytest.raises(ClientError) as exc:+ logs.start_live_tail(logGroupIdentifiers=[starred])+ assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"++def test_logs_filter_with_wildcard(logs):"""FilterLogEvents with wildcard pattern matches correctly."""logs.create_log_group(logGroupName="/qa/logs/wildcard")@@ -904,6 +1143,67 @@ def _module():return importlib.import_module("ministack.services.cloudwatch_logs")+def test_get_log_record_inprocess_round_trip():+ """Handler-level coverage without a running gateway (CI-friendly)."""+ import json as _json++ from ministack.core.responses import set_request_account_id, set_request_region++ mod = _module()+ mod.reset()+ set_request_account_id("test")+ set_request_region("us-east-1")++ group = "/aws/lambda/get-log-record-unit"+ stream = "stream-a"+ now_ms = 1_700_000_000_000++ assert mod._create_log_group({"logGroupName": group})[0] == 200+ assert mod._create_log_stream({"logGroupName": group, "logStreamName": stream})[0] == 200+ put = mod._put_log_events({+ "logGroupName": group,+ "logStreamName": stream,+ "logEvents": [+ {"timestamp": now_ms - 1000, "message": "before"},+ {"timestamp": now_ms, "message": "anchor"},+ {"timestamp": now_ms + 1000, "message": "after"},+ ],+ })+ assert put[0] == 200++ start = mod._start_query({+ "logGroupName": group,+ "startTime": (now_ms // 1000) - 10,+ "endTime": (now_ms // 1000) + 10,+ "queryString": "fields @timestamp, @message, @logStream, @log | limit 10",+ "limit": 10,+ })+ assert start[0] == 200+ query_id = _json.loads(start[2])["queryId"]++ results = mod._get_query_results({"queryId": query_id})+ assert results[0] == 200+ body = _json.loads(results[2])+ assert body["status"] == "Complete"+ assert len(body["results"]) == 3+ middle = {cell["field"]: cell["value"] for cell in body["results"][1]}+ assert middle["@message"] == "anchor"+ ptr = middle["@ptr"]++ record_resp = mod._get_log_record({"logRecordPointer": ptr, "unmask": False})+ assert record_resp[0] == 200+ record = _json.loads(record_resp[2])["logRecord"]+ assert record["@message"] == "anchor"+ assert record["@logStream"] == stream+ assert record["@log"] == group+ assert "_timestamp_ms" not in record++ bad = mod._get_log_record({"logRecordPointer": "missing"})+ assert bad[0] == 400+ assert _json.loads(bad[2])["__type"] == "InvalidParameterException"+ mod.reset()++@pytest.fixture(autouse=True)def _enable_persistence(monkeypatch, tmp_path):"""Force PERSIST_STATE on and point STATE_DIR at a tmp dir for the@@ -1065,6 +1365,7 @@ def test_queries_are_region_scoped():try:set_request_region("us-east-1")+ assert mod._create_log_group({"logGroupName": "/aws/lambda/query-east"})[0] == 200east = mod._start_query({"logGroupName": "/aws/lambda/query-east","startTime": 1,@@ -1074,6 +1375,7 @@ def test_queries_are_region_scoped():east_id = json.loads(east[2])["queryId"]set_request_region("us-west-2")+ assert mod._create_log_group({"logGroupName": "/aws/lambda/query-west"})[0] == 200west = mod._start_query({"logGroupName": "/aws/lambda/query-west","startTime": 1,