Skip to content

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

fix(SQS): source mapping, improve putObjectS3 (#1583)

Nahuel Nucera8d9e72860608
diff --git a/ministack/app.py b/ministack/app.py
index 81e582bf..0c13facc 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -503,14 +503,19 @@ def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:
):
return body
- decoded = b""
- remaining = body
+ # Walked by index with the chunks collected for one join. Both the
+ # decoded += chunk append and re-slicing the unparsed tail copy an
+ # amount proportional to the whole body on every chunk, which made this
+ # decode quadratic twice over -- and aws-chunked is what the AWS CLI
+ # sends for a large streaming PutObject.
+ chunks = []
+ pos = 0
trailer = b""
- while remaining:
- crlf = remaining.find(b"\r\n")
+ while pos < len(body):
+ crlf = body.find(b"\r\n", pos)
if crlf == -1:
break
- chunk_header = remaining[:crlf].decode("ascii", errors="replace")
+ chunk_header = body[pos:crlf].decode("ascii", errors="replace")
size_hex = chunk_header.split(";")[0].strip()
try:
chunk_size = int(size_hex, 16)
@@ -519,11 +524,12 @@ def _decode_aws_chunked_body(body: bytes, headers: dict) -> bytes:
if chunk_size == 0:
# Whatever follows the final chunk is the trailing header
# section the request announced in x-amz-trailer.
- trailer = remaining[crlf + 2 :]
+ trailer = body[crlf + 2 :]
break
data_start = crlf + 2
- decoded += remaining[data_start : data_start + chunk_size]
- remaining = remaining[data_start + chunk_size + 2 :] # skip trailing \r\n
+ chunks.append(body[data_start : data_start + chunk_size])
+ pos = data_start + chunk_size + 2 # skip trailing \r\n
+ decoded = b"".join(chunks)
# A checksum computed while the body streamed arrives here rather than
# among the request headers, and the rest of the request has no way to
@@ -553,11 +559,18 @@ async def _read_request_body(receive, method: str, headers: dict) -> bytes:
"""Read and decode the request body only for methods or headers that can carry one."""
body = b""
if headers.get("content-length") or headers.get("transfer-encoding") or method in _BODY_METHODS:
+ # Chunks are collected and joined once. Appending to a bytes object
+ # re-copies everything received so far on every 64 KB chunk, which made
+ # assembling a 95 MB PutObject copy ~76 GB of memory.
+ chunks = []
while True:
message = await receive()
- body += message.get("body", b"")
+ chunk = message.get("body", b"")
+ if chunk:
+ chunks.append(chunk)
if not message.get("more_body", False):
break
+ body = b"".join(chunks)
return _decode_aws_chunked_body(body, headers)
diff --git a/ministack/core/pgproxy.py b/ministack/core/pgproxy.py
index 28184b25..cc218c92 100644
--- a/ministack/core/pgproxy.py
+++ b/ministack/core/pgproxy.py
@@ -1765,10 +1765,12 @@ async def _handle_query(conn, sql, b_writer, c_writer):
await c_writer.drain()
return
if kind == "rows":
- out = _row_description(result["cols"])
- for row in result["rows"]:
- out += _data_row(row)
- out += _command_complete(result["tag"])
+ # One join, not a growing bytes append -- per-row += re-copies the
+ # whole response for every row, quadratic in result-set size.
+ frames = [_row_description(result["cols"])]
+ frames.extend(_data_row(row) for row in result["rows"])
+ frames.append(_command_complete(result["tag"]))
+ out = b"".join(frames)
c_writer.write(out + _ready(_status(conn)))
await c_writer.drain()
return
@@ -1985,9 +1987,7 @@ async def _ext_execute(conn, payload, b_writer, c_writer):
kind, result = entry["synth"]
if kind == "rows":
- out = b""
- for row in result["rows"]:
- out += _data_row(row)
+ out = b"".join(_data_row(row) for row in result["rows"])
c_writer.write(out + _command_complete(result["tag"]))
await c_writer.drain()
return
diff --git a/ministack/services/kms.py b/ministack/services/kms.py
index 6c5d9756..599f4246 100644
--- a/ministack/services/kms.py
+++ b/ministack/services/kms.py
@@ -26,6 +26,7 @@ from ministack.core.responses import (
get_region,
json_response,
new_uuid,
+ request_scope,
)
logger = logging.getLogger("kms")
@@ -238,6 +239,23 @@ def _key_metadata(rec):
# that is, when its KeyState is PendingDeletion."
if "DeletionDate" in rec:
metadata["DeletionDate"] = rec["DeletionDate"]
+ metadata["MultiRegion"] = rec.get("MultiRegion", False)
+ if rec.get("MultiRegion"):
+ account = get_account_id()
+ primary_region = rec.get("_mrk_primary_region", get_region())
+ regions = rec.get("_mrk_regions") or [primary_region]
+ def member_arn(region):
+ return f"arn:aws:kms:{region}:{account}:key/{rec['KeyId']}"
+ metadata["MultiRegionConfiguration"] = {
+ "MultiRegionKeyType": rec.get("_mrk_type", "PRIMARY"),
+ "PrimaryKey": {"Arn": member_arn(primary_region), "Region": primary_region},
+ "ReplicaKeys": [
+ {"Arn": member_arn(region), "Region": region}
+ for region in regions if region != primary_region
+ ],
+ }
+ if rec.get("KeyState") == "PendingReplicaDeletion" and rec.get("_pending_window_days"):
+ metadata["PendingDeletionWindowInDays"] = rec["_pending_window_days"]
return metadata
@@ -331,7 +349,10 @@ def _require_crypto(operation):
def _create_key(data):
- key_id = new_uuid()
+ # A multi-Region key's id carries the mrk- prefix, and the id is what ties
+ # the primary and its replicas together across regions.
+ multi_region = bool(data.get("MultiRegion", False))
+ key_id = f"mrk-{new_uuid().replace('-', '')}" if multi_region else new_uuid()
key_spec = data.get("KeySpec", data.get("CustomerMasterKeySpec", "SYMMETRIC_DEFAULT"))
key_usage = data.get("KeyUsage", "ENCRYPT_DECRYPT")
if key_spec in _HMAC_KEY_SPECS and key_usage != MAC_KEY_USAGE:
@@ -375,7 +396,16 @@ def _create_key(data):
"Origin": "AWS_KMS",
"Tags": tags,
"Policy": policy,
+ "MultiRegion": multi_region,
}
+ if multi_region:
+ # Topology lives on every member and is kept in sync by ReplicateKey
+ # and ScheduleKeyDeletion: the primary region plus every region that
+ # holds a member, from which each member's MultiRegionConfiguration is
+ # rebuilt on read.
+ rec["_mrk_type"] = "PRIMARY"
+ rec["_mrk_primary_region"] = get_region()
+ rec["_mrk_regions"] = [get_region()]
if key_spec == "SYMMETRIC_DEFAULT":
rec["_symmetric_key"] = os.urandom(32)
@@ -1447,17 +1477,142 @@ def _update_key_description(data):
return json_response({})
+_KEY_MATERIAL_FIELDS = (
+ "_symmetric_key", "_hmac_key", "_private_key", "_public_key_der",
+ "EncryptionAlgorithms", "SigningAlgorithms", "MacAlgorithms",
+)
+
+
+def _mrk_members(rec):
+ """Yield (region, member record) for every member of a multi-Region key."""
+ account = get_account_id()
+ for region in rec.get("_mrk_regions") or []:
+ with request_scope(account, region):
+ member = _keys.get(rec["KeyId"])
+ if member is not None:
+ yield region, member
+
+
+def _replicate_key(data):
+ """ReplicateKey — create a replica of a multi-Region primary key in
+ another region, sharing its id and key material, so a ciphertext produced
+ in one region decrypts in the other, as AWS's shared-material model
+ guarantees."""
+ rec = _resolve_key(data.get("KeyId", ""))
+ if not rec:
+ return error_response_json(
+ "NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)
+ if not rec.get("MultiRegion"):
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"{rec['Arn']} is not a multi-Region key.", 400)
+ if rec.get("_mrk_type") != "PRIMARY":
+ return error_response_json(
+ "UnsupportedOperationException",
+ f"{rec['Arn']} is a multi-Region replica key. ReplicateKey must be "
+ "called on the multi-Region primary key.", 400)
+ if rec.get("KeyState") not in ("Enabled", "Disabled"):
+ return error_response_json(
+ "KMSInvalidStateException",
+ f"{rec['Arn']} is in the {rec.get('KeyState')} state; it cannot be "
+ "replicated.", 400)
+ replica_region = data.get("ReplicaRegion")
+ if not replica_region:
+ return error_response_json(
+ "ValidationException", "ReplicaRegion is required", 400)
+ if replica_region in (rec.get("_mrk_regions") or []):
+ return error_response_json(
+ "AlreadyExistsException",
+ f"Key {rec['KeyId']} already exists in region {replica_region}", 400)
+
+ account = get_account_id()
+ tags = data.get("Tags", [])
+ policy = data.get("Policy") or json.dumps({
+ "Version": "2012-10-17",
+ "Id": "key-default-1",
+ "Statement": [{
+ "Sid": "Enable IAM User Permissions",
+ "Effect": "Allow",
+ "Principal": {"AWS": f"arn:aws:iam::{account}:root"},
+ "Action": "kms:*",
+ "Resource": "*",
+ }],
+ })
+ replica = {
+ "KeyId": rec["KeyId"],
+ "Arn": f"arn:aws:kms:{replica_region}:{account}:key/{rec['KeyId']}",
+ "KeyState": "Enabled",
+ "Enabled": True,
+ "KeySpec": rec["KeySpec"],
+ "KeyUsage": rec["KeyUsage"],
+ # The replica has its own description, policy and tags; only the key
+ # material and id are shared. An omitted Description is empty, per the
+ # API reference.
+ "Description": data.get("Description", ""),
+ "CreationDate": int(time.time()),
+ "Origin": rec["Origin"],
+ "Tags": tags,
+ "Policy": policy,
+ "MultiRegion": True,
+ "_mrk_type": "REPLICA",
+ "_mrk_primary_region": rec["_mrk_primary_region"],
+ }
+ for field in _KEY_MATERIAL_FIELDS:
+ if field in rec:
+ replica[field] = rec[field]
+
+ regions = list(rec.get("_mrk_regions") or []) + [replica_region]
+ replica["_mrk_regions"] = regions
+ with request_scope(account, replica_region):
+ _keys[rec["KeyId"]] = replica
+ # Every member reports the full topology.
+ for _region, member in _mrk_members(rec):
+ member["_mrk_regions"] = regions
+
+ return json_response({
+ "ReplicaKeyMetadata": _key_metadata_in_region(replica, replica_region),
+ "ReplicaPolicy": policy,
+ "ReplicaTags": tags,
+ })
+
+
+def _key_metadata_in_region(rec, region):
+ """_key_metadata built as the target region would build it — the ARNs it
+ contains are region-qualified via the request context."""
+ with request_scope(get_account_id(), region):
+ return _key_metadata(rec)
+
+
def _schedule_key_deletion(data):
rec = _resolve_key(data.get("KeyId", ""))
if not rec:
return error_response_json("NotFoundException", f"Key {data.get('KeyId', '')} not found", 400)
days = data.get("PendingWindowInDays", 30)
- rec["KeyState"] = "PendingDeletion"
+ state = "PendingDeletion"
+ if rec.get("MultiRegion"):
+ others = [r for r in (rec.get("_mrk_regions") or []) if r != get_region()]
+ if rec.get("_mrk_type") == "PRIMARY" and others:
+ # A primary with live replicas waits on them, as AWS does.
+ state = "PendingReplicaDeletion"
+ rec["_pending_window_days"] = days
+ elif rec.get("_mrk_type") == "REPLICA":
+ # The departing replica leaves the topology every member reports,
+ # and a primary that was only waiting on it moves on to
+ # PendingDeletion.
+ regions = [r for r in (rec.get("_mrk_regions") or []) if r != get_region()]
+ for _region, member in _mrk_members(rec):
+ member["_mrk_regions"] = regions
+ if (member.get("_mrk_type") == "PRIMARY"
+ and member.get("KeyState") == "PendingReplicaDeletion"
+ and len(regions) == 1):
+ member["KeyState"] = "PendingDeletion"
+ rec["_mrk_regions"] = [get_region()]
+ rec["KeyState"] = state
rec["Enabled"] = False
rec["DeletionDate"] = int(time.time() + (days * 86400))
return json_response({
"KeyId": rec["Arn"],
- "KeyState": "PendingDeletion",
+ "KeyState": state,
"DeletionDate": rec["DeletionDate"],
})
@@ -1565,6 +1720,7 @@ async def handle_request(method, path, headers, body, query_params):
handlers = {
"CreateKey": _create_key,
+ "ReplicateKey": _replicate_key,
"ListKeys": _list_keys,
"DescribeKey": _describe_key,
"GetPublicKey": _get_public_key,
diff --git a/ministack/services/lambda_svc.py b/ministack/services/lambda_svc.py
index 9229d110..62386c24 100644
--- a/ministack/services/lambda_svc.py
+++ b/ministack/services/lambda_svc.py
@@ -6488,16 +6488,31 @@ def _poll_sqs():
records = []
for msg in batch:
first_recv = msg.get("first_receive_at") or now
+ attributes = {
+ "ApproximateReceiveCount": str(msg.get("receive_count", 1)),
+ "SentTimestamp": str(int(msg["sent_at"] * 1000)),
+ "SenderId": get_account_id(),
+ "ApproximateFirstReceiveTimestamp": str(int(first_recv * 1000)),
+ }
+ # AWSTraceHeader carries X-Ray / OpenTelemetry trace context
+ # through SQS into the consumer; AWS delivers it inside the
+ # record's attributes map when the producer set it.
+ trace_header = (msg.get("sys") or {}).get("AWSTraceHeader")
+ if trace_header:
+ attributes["AWSTraceHeader"] = trace_header
+ # FIFO records carry their sequencing attributes, per the
+ # documented FIFO event shape.
+ if msg.get("group_id"):
+ attributes["MessageGroupId"] = msg["group_id"]
+ if msg.get("dedup_id"):
+ attributes["MessageDeduplicationId"] = msg["dedup_id"]
+ if msg.get("seq") is not None:
+ attributes["SequenceNumber"] = str(msg["seq"])
records.append({
"messageId": msg["id"],
"receiptHandle": msg["receipt_handle"],
"body": msg["body"],
- "attributes": {
- "ApproximateReceiveCount": str(msg.get("receive_count", 1)),
- "SentTimestamp": str(int(msg["sent_at"] * 1000)),
- "SenderId": get_account_id(),
- "ApproximateFirstReceiveTimestamp": str(int(first_recv * 1000)),
- },
+ "attributes": attributes,
"messageAttributes": _sqs_message_attributes_to_camel_case(
msg.get("message_attributes", {})
),
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index e9eead85..0ef0a44d 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -5982,7 +5982,10 @@ def _complete_multipart_upload(
ordered_parts.sort(key=lambda x: x[0])
md5_digests = b""
- combined = b""
+ # Part bodies are joined once at the end: appending each 5 MB+ part to a
+ # growing bytes object re-copies the whole object per part, which is
+ # quadratic in object size across up to 10,000 parts.
+ combined_parts = []
part_records = []
checksum_algorithm = upload.get("checksum_algorithm")
part_digests = []
@@ -6016,7 +6019,7 @@ def _complete_multipart_upload(
if checksum_algorithm:
part_digests.append(stored_checksums.get(checksum_algorithm))
md5_digests += hashlib.md5(stored["body"]).digest()
- combined += stored["body"]
+ combined_parts.append(stored["body"])
# Retained so GetObjectAttributes can report ObjectParts (ListParts
# functionality) for the completed multipart object.
part_records.append({"PartNumber": pn, "Size": len(stored["body"])})
@@ -6035,6 +6038,7 @@ def _complete_multipart_upload(
final_md5 = hashlib.md5(md5_digests).hexdigest()
final_etag = f'"{final_md5}-{len(ordered_parts)}"'
+ combined = b"".join(combined_parts)
obj = {
"body": combined,
"content_type": upload["content_type"],
diff --git a/tests/test_kms.py b/tests/test_kms.py
index 3c1023e1..8162fde6 100644
--- a/tests/test_kms.py
+++ b/tests/test_kms.py
@@ -2037,3 +2037,94 @@ def test_kms_generate_random_refuses_a_recipient(kms_client):
},
)
assert e.value.response["Error"]["Code"] == "UnsupportedOperationException"
+
+
+# ---------------------------------------------------------------------------
+# Multi-Region keys and ReplicateKey
+# ---------------------------------------------------------------------------
+
+def test_kms_multi_region_key_metadata(kms_client):
+ """A MultiRegion key carries the mrk- id prefix and reports its
+ MultiRegionConfiguration; a plain key reports MultiRegion false."""
+ plain = kms_client.create_key()["KeyMetadata"]
+ assert plain["MultiRegion"] is False
+ assert "MultiRegionConfiguration" not in plain
+
+ meta = kms_client.create_key(MultiRegion=True)["KeyMetadata"]
+ assert meta["KeyId"].startswith("mrk-")
+ assert meta["MultiRegion"] is True
+ cfg = meta["MultiRegionConfiguration"]
+ assert cfg["MultiRegionKeyType"] == "PRIMARY"
+ assert cfg["PrimaryKey"]["Region"] == "us-east-1"
+ assert cfg["PrimaryKey"]["Arn"].endswith(f":key/{meta['KeyId']}")
+ assert cfg["ReplicaKeys"] == []
+
+
+def test_kms_replicate_key_cross_region_decrypt():
+ """ReplicateKey creates a same-id replica in the target region sharing the
+ key material, so a ciphertext produced against the primary decrypts
+ against the replica — the S3 SSE-KMS cross-region case."""
+ east, west = _regional_kms("us-east-1"), _regional_kms("us-west-2")
+ key_id = east.create_key(MultiRegion=True)["KeyMetadata"]["KeyId"]
+
+ resp = east.replicate_key(KeyId=key_id, ReplicaRegion="us-west-2",
+ Description="the west copy")
+ replica = resp["ReplicaKeyMetadata"]
+ assert replica["KeyId"] == key_id
+ assert replica["Arn"] == f"arn:aws:kms:us-west-2:000000000000:key/{key_id}"
+ assert replica["MultiRegionConfiguration"]["MultiRegionKeyType"] == "REPLICA"
+ assert replica["Description"] == "the west copy"
+ assert resp["ReplicaPolicy"]
+ assert resp["ReplicaTags"] == []
+
+ # Both members report the full topology.
+ for client, kind in ((east, "PRIMARY"), (west, "REPLICA")):
+ cfg = client.describe_key(KeyId=key_id)["KeyMetadata"]["MultiRegionConfiguration"]
+ assert cfg["MultiRegionKeyType"] == kind
+ assert cfg["PrimaryKey"]["Region"] == "us-east-1"
+ assert [r["Region"] for r in cfg["ReplicaKeys"]] == ["us-west-2"]
+
+ # Shared key material: encrypt east, decrypt west.
+ blob = east.encrypt(KeyId=key_id, Plaintext=b"cross-region")["CiphertextBlob"]
+ out = west.decrypt(CiphertextBlob=blob)
+ assert out["Plaintext"] == b"cross-region"
+ assert out["KeyId"].endswith(f":key/{key_id}")
+
+ # The same region twice is a conflict.
+ with pytest.raises(ClientError) as ei:
+ east.replicate_key(KeyId=key_id, ReplicaRegion="us-west-2")
+ assert ei.value.response["Error"]["Code"] == "AlreadyExistsException"
+
+
+def test_kms_replicate_key_refusals(kms_client):
+ """A plain key cannot be replicated, and a replica cannot be the source."""
+ east, west = _regional_kms("us-east-1"), _regional_kms("us-west-2")
+
+ plain = kms_client.create_key()["KeyMetadata"]["KeyId"]
+ with pytest.raises(ClientError) as ei:
+ kms_client.replicate_key(KeyId=plain, ReplicaRegion="us-west-2")
+ assert ei.value.response["Error"]["Code"] == "UnsupportedOperationException"
+
+ key_id = east.create_key(MultiRegion=True)["KeyMetadata"]["KeyId"]
+ east.replicate_key(KeyId=key_id, ReplicaRegion="us-west-2")
+ with pytest.raises(ClientError) as ei:
+ west.replicate_key(KeyId=key_id, ReplicaRegion="eu-west-1")
+ assert ei.value.response["Error"]["Code"] == "UnsupportedOperationException"
+
+
+def test_kms_primary_with_replicas_waits_on_deletion():
+ """Scheduling deletion on a primary with a live replica lands
+ PendingReplicaDeletion; once the replica is scheduled away, the primary
+ moves on to PendingDeletion."""
+ east, west = _regional_kms("us-east-1"), _regional_kms("us-west-2")
+ key_id = east.create_key(MultiRegion=True)["KeyMetadata"]["KeyId"]
+ east.replicate_key(KeyId=key_id, ReplicaRegion="us-west-2")
+
+ resp = east.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)
+ assert resp["KeyState"] == "PendingReplicaDeletion"
+ meta = east.describe_key(KeyId=key_id)["KeyMetadata"]
+ assert meta["KeyState"] == "PendingReplicaDeletion"
+ assert meta["PendingDeletionWindowInDays"] == 7
+
+ west.schedule_key_deletion(KeyId=key_id, PendingWindowInDays=7)
+ assert east.describe_key(KeyId=key_id)["KeyMetadata"]["KeyState"] == "PendingDeletion"
diff --git a/tests/test_lambda.py b/tests/test_lambda.py
index 4948499d..f938a7de 100644
--- a/tests/test_lambda.py
+++ b/tests/test_lambda.py
@@ -5409,6 +5409,76 @@ def test_poll_sqs_backs_off_failing_esm_without_starving_other_esms(esm_poll_sta
assert len(_sqs._queues[broken_queue_url]["messages"]) == 1
+def test_poll_sqs_record_carries_trace_header_and_fifo_attributes(esm_poll_state, monkeypatch):
+ """The record's attributes map carries AWSTraceHeader when the producer set
+ it, and the FIFO sequencing attributes on a FIFO message — the keys AWS
+ documents in the SQS event shape, which X-Ray/OpenTelemetry consumers read.
+ A message without them omits the keys rather than sending empty ones."""
+ _lsvc, _sqs, _kin, _ddb = esm_poll_state
+
+ queue_name = "esm-trace-attrs"
+ queue_url = f"http://localhost:4566/000000000000/{queue_name}"
+ trace = "Root=1-6893a2b4-aaaabbbbccccddddeeeeffff;Parent=0123456789abcdef;Sampled=1"
+ base = {
+ "md5_body": "", "sent_at": time.time(), "visible_at": 0,
+ "receive_count": 0, "first_receive_at": None, "message_attributes": {},
+ }
+ _sqs._queues[queue_url] = {
+ "name": queue_name,
+ "messages": [
+ {**base, "id": "msg-plain", "body": "plain", "receipt_handle": "rh-1"},
+ {**base, "id": "msg-traced", "body": "traced", "receipt_handle": "rh-2",
+ "sys": {"SenderId": "000000000000", "SentTimestamp": "0",
+ "AWSTraceHeader": trace},
+ "group_id": "g1", "dedup_id": "d1", "seq": 18849496460467696128},
+ ],
+ "attributes": {
+ "QueueArn": f"arn:aws:sqs:us-east-1:000000000000:{queue_name}",
+ "VisibilityTimeout": "0",
+ },
+ "is_fifo": False,
+ "dedup_cache": {},
+ "fifo_seq": 0,
+ }
+ _lsvc._functions["esm-trace-attrs-fn"] = {
+ "config": {
+ "FunctionName": "esm-trace-attrs-fn",
+ "FunctionArn": "arn:aws:lambda:us-east-1:000000000000:function:esm-trace-attrs-fn",
+ },
+ "versions": {}, "aliases": {},
+ }
+ _lsvc._esms["esm-trace-attrs"] = {
+ "UUID": "esm-trace-attrs",
+ "EventSourceArn": f"arn:aws:sqs:us-east-1:000000000000:{queue_name}",
+ "FunctionName": "esm-trace-attrs-fn",
+ "State": "Enabled",
+ "Enabled": True,
+ "BatchSize": 10,
+ }
+ events = []
+ monkeypatch.setattr(
+ _lsvc, "_execute_function",
+ lambda _func, event: (events.append(event), {"body": "ok"})[1],
+ )
+
+ _lsvc._poll_sqs()
+
+ records = {r["messageId"]: r for e in events for r in e["Records"]}
+ plain = records["msg-plain"]["attributes"]
+ assert "AWSTraceHeader" not in plain
+ assert "MessageGroupId" not in plain and "SequenceNumber" not in plain
+
+ traced = records["msg-traced"]["attributes"]
+ assert traced["AWSTraceHeader"] == trace
+ assert traced["MessageGroupId"] == "g1"
+ assert traced["MessageDeduplicationId"] == "d1"
+ assert traced["SequenceNumber"] == "18849496460467696128"
+ # The standard four are still present alongside.
+ for key in ("ApproximateReceiveCount", "SentTimestamp", "SenderId",
+ "ApproximateFirstReceiveTimestamp"):
+ assert key in traced, key
+
+
def test_poll_sqs_retries_esm_after_backoff_expires(esm_poll_state, monkeypatch):
"""Once the cooldown elapses, a previously-failing ESM is retried again —
the backoff paces retries, it doesn't disable the ESM."""