diff --git a/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md b/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md index ebd9d5b06..83a9b8a3c 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md @@ -327,6 +327,27 @@ real Lambda ARNs) and an error `name` of normal length (a type name such as message of 8,192 control characters, each escaped as `\u00XX`) fits any limit of 128 KB (131,072 bytes) or more. +Truncation finds how many results and how many operations to drop with a +binary search. So it renders the record about `2 * log2(n)` times for `n` +operations, with any `render`. The emitted record is always measured. So the +output never goes over the limit, as long as dropping everything droppable makes +it fit. If even that does not fit, the output is over the limit, as before. + +The search assumes that each drop makes the rendered record smaller. Some +records break this assumption, and then truncation can drop more results and +operations than the one-at-a-time truncation of earlier versions. For example, +one old result of 2,000 bytes followed by 1,999 results of `true` is 1 byte over +the limit. The earlier versions clear the old result only. This version clears +every result and drops 41 operations. Three cases break the assumption: + +- In the `array` format, the `"truncated":true` marker is longer than a short + result such as `1`, `true` or `"ok"`. So clearing a short result makes the + record bigger. +- In the `operationsByName` map, the result and error of a repeated name appear + when the other operation with that name is dropped. +- A render that escapes the record, such as the single string body of + `OTelExporter`, changes size by a different amount for each drop. + Names are each language's own and differ across SDKs. For example, a step that throws `PaymentError` can be reported as `StepError` in JS, `aws_durable_execution_sdk_python.exceptions.StepError` or `PaymentError` in diff --git a/packages/aws-durable-execution-sdk-python-telemetry-exporter/src/aws_durable_execution_sdk_python_telemetry_exporter/truncation.py b/packages/aws-durable-execution-sdk-python-telemetry-exporter/src/aws_durable_execution_sdk_python_telemetry_exporter/truncation.py index b1ed91c65..f5a7514ba 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/src/aws_durable_execution_sdk_python_telemetry_exporter/truncation.py +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/src/aws_durable_execution_sdk_python_telemetry_exporter/truncation.py @@ -13,6 +13,9 @@ 3. last resort — execution ``input`` then ``output`` (``droppedInput`` / ``droppedOutput``). +Steps 1 and 2 find their drop count with a binary search, so a record is +rendered about ``2 * log2(n)`` times for ``n`` operations. + Identity/timeline fields are never dropped. The input record is never mutated. ``render`` maps the record to the exact value the exporter serializes, so the size check measures what is actually emitted. By default the byte size is that @@ -72,7 +75,6 @@ def truncate_record( return record ops: list[dict[str, Any]] = [dict(op) for op in record.get("operations", [])] - kept = [True] * len(ops) # Oldest-first by the startTime string. Every record timestamp has the same # fixed-width UTC format, so text order equals time order. Operations # without a startTime sort last. @@ -85,15 +87,29 @@ def truncate_record( dropped_causes = _has_cause(record) or any(_has_cause(op) for op in ops) for op in ops: _drop_cause(op) + # rank[i] is the position of operation i in ``order``. A candidate clears + # the results of the operations with rank below ``cleared_results`` and + # removes the operations with rank below ``dropped_ops``. + rank = [0] * len(ops) + for position, idx in enumerate(order): + rank[idx] = position + cleared = [ + {**{k: v for k, v in op.items() if k != "result"}, "truncated": True} + if op.get("result") is not None + else op + for op in ops + ] - any_result = False - dropped_ops = 0 dropped_input = False dropped_output = False - def candidate() -> dict[str, Any]: + def candidate(cleared_results: int, dropped_ops: int) -> dict[str, Any]: out = dict(record) - out["operations"] = [op for i, op in enumerate(ops) if kept[i]] + out["operations"] = [ + cleared[i] if rank[i] < cleared_results else op + for i, op in enumerate(ops) + if rank[i] >= dropped_ops + ] out["truncated"] = True if dropped_causes: _drop_cause(out) @@ -108,33 +124,45 @@ def candidate() -> dict[str, Any]: out["droppedOutput"] = True return out - def fits() -> bool: - size = measure(render(candidate())) + def fits(cleared_results: int, dropped_ops: int) -> bool: + size = measure(render(candidate(cleared_results, dropped_ops))) return size is not None and size <= max_bytes + def first_fit(low: int, high: int, fits_at: Callable[[int], bool]) -> int | None: + # Binary search for the smallest count in ``low..high`` that fits. The + # search assumes that a larger count never makes the record larger. + # Some records break this assumption, for example a by-name map with + # repeated names, a short result replaced by the truncated marker, or + # an escaped string body. Then the search can return a larger count + # than the smallest one that fits. So truncation can drop more results + # or operations than the one-at-a-time check. The returned count was + # always measured. So the output never goes over the limit, as long as + # dropping everything droppable makes it fit. + found = None + while low <= high: + middle = (low + high) // 2 + if fits_at(middle): + found, high = middle, middle - 1 + else: + low = middle + 1 + return found + # Phase 1: drop operation results oldest-first. - for idx in order: - if fits(): - break - if kept[idx] and ops[idx].get("result") is not None: - trimmed = dict(ops[idx]) - trimmed.pop("result", None) - trimmed["truncated"] = True - ops[idx] = trimmed - any_result = True + count = len(ops) + found = first_fit(0, count, lambda j: fits(j, 0)) + cleared_results = count if found is None else found + dropped_ops = 0 + any_result = any(ops[i].get("result") is not None for i in order[:cleared_results]) # Phase 2: drop whole operations oldest-first. - for idx in order: - if fits(): - break - if kept[idx]: - kept[idx] = False - dropped_ops += 1 + if found is None: + found = first_fit(1, count, lambda k: fits(count, k)) + dropped_ops = count if found is None else found # Phase 3 (last resort): drop input then output. - if not fits() and record.get("input") is not None: + if not fits(cleared_results, dropped_ops) and record.get("input") is not None: dropped_input = True - if not fits() and record.get("output") is not None: + if not fits(cleared_results, dropped_ops) and record.get("output") is not None: dropped_output = True if ( @@ -146,4 +174,4 @@ def fits() -> bool: ): return record - return candidate() + return candidate(cleared_results, dropped_ops) diff --git a/packages/aws-durable-execution-sdk-python-telemetry-exporter/tests/test_shaping.py b/packages/aws-durable-execution-sdk-python-telemetry-exporter/tests/test_shaping.py index 77f678aa8..6c47d03be 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/tests/test_shaping.py +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/tests/test_shaping.py @@ -5,6 +5,7 @@ from __future__ import annotations +import random from typing import Any from aws_durable_execution_sdk_python_telemetry_exporter.operations_index import ( @@ -14,6 +15,7 @@ with_operations_by_name, ) from aws_durable_execution_sdk_python_telemetry_exporter.truncation import ( + json_byte_size, truncate_record, ) @@ -224,3 +226,245 @@ def measure(value: Any) -> int: assert sizes and out["truncated"] is True # The default measure would keep this small record unchanged. assert truncate_record(record, 1000, render=lambda r: r) is record + + +def _named_ops_record(count: int) -> dict[str, Any]: + ops = [ + { + "id": f"{i:016x}", + "name": f"step-{i:05d}", + "type": "STEP", + "subType": "Step", + "status": "SUCCEEDED", + "startTime": ( + f"2026-01-01T{i // 3600:02d}:{i // 60 % 60:02d}:{i % 60:02d}.000Z" + ), + "durationMs": 12, + "attempt": 1, + } + for i in range(count) + ] + return { + "recordType": "DurableExecutionTelemetry", + "schemaVersion": "1.0", + "executionArn": "arn:aws:lambda:us-west-2:123456789012:function:fn:$LATEST/durable-execution/exec/inv", + "status": "SUCCEEDED", + "startTime": "2026-01-01T00:00:00.000Z", + "operations": ops, + } + + +def test_truncation_renders_a_logarithmic_number_of_times(): + from aws_durable_execution_sdk_python_telemetry_exporter.exporters.lambda_log_exporter import ( + LambdaLogExporter, + ) + + exporter = LambdaLogExporter() + renders = 0 + + def render(record: dict[str, Any]) -> Any: + nonlocal renders + renders += 1 + return exporter.render(record) + + record = _named_ops_record(2000) + out = truncate_record(record, 256_000, render, exporter.measure) + size = exporter.measure(exporter.render(out)) + assert size is not None and size <= 256_000 + assert out["droppedOperations"] > 0 + # Two binary searches over 2,001 drop counts need about 2 * 11 renders. + assert renders < 40 + + +def test_truncation_renders_a_logarithmic_number_of_times_for_a_custom_render(): + renders = 0 + + def render(record: dict[str, Any]) -> Any: + nonlocal renders + renders += 1 + return {"wrapped": [dict(op, extra="e") for op in record["operations"]]} + + out = truncate_record(_named_ops_record(2000), 100_000, render) + size = json_byte_size(render(out)) + assert size is not None and size <= 100_000 + assert out["droppedOperations"] > 0 + assert renders < 40 + + +_NAMES = ["a", "a", "b", "", 'q"uote', "back\\slash", "ünï", "😀", "\u2028", None] + + +def _random_record(rng: random.Random) -> dict[str, Any]: + ops = [] + for i in range(rng.randint(0, 30)): + op: dict[str, Any] = { + "id": f"{i:016x}", + "type": "STEP", + "status": rng.choice(["SUCCEEDED", "FAILED"]), + "durationMs": rng.randint(0, 100), + "attempt": rng.randint(1, 3), + } + name = rng.choice(_NAMES) + if name is not None: + op["name"] = name + if rng.random() < 0.9: + op["startTime"] = f"2026-01-01T00:00:{rng.randint(0, 59):02d}.000Z" + if rng.random() < 0.5: + op["result"] = rng.choice(['"x"', "ü" * rng.randint(0, 80), "\\" * 9]) + if rng.random() < 0.3: + op["error"] = {"name": "E", "message": "m" * rng.randint(0, 60)} + ops.append(op) + record: dict[str, Any] = {"executionArn": "arn", "operations": ops} + if rng.random() < 0.7: + record["input"] = "i" * rng.randint(0, 200) + if rng.random() < 0.7: + record["output"] = '"o"' * rng.randint(0, 50) + return record + + +def _oldest_first(record: dict[str, Any]) -> list[str]: + ops = record["operations"] + order = sorted( + range(len(ops)), key=lambda i: (ops[i].get("startTime") or "\uffff", i) + ) + return [ops[i]["id"] for i in order] + + +def test_truncation_never_exceeds_the_limit_and_drops_oldest_first(): + rng = random.Random(908) + for _ in range(300): + record = _random_record(rng) + fmt = rng.choice(list(OperationsFormat)) + + def render(r: dict[str, Any], fmt: OperationsFormat = fmt) -> Any: + return apply_operations_format(r, fmt) + + full = json_byte_size(render(record)) + assert full is not None + limit = rng.randint(1, full + 10) + out = truncate_record(record, limit, render) + size = json_byte_size(render(out)) + assert size is not None + # Over the limit only when nothing is left to drop. + assert size <= limit or ( + not out["operations"] and "input" not in out and "output" not in out + ) + # The kept operations are the newest ones. + ids = _oldest_first(record) + kept = {op["id"]: op for op in out["operations"]} + assert [i for i in ids if i in kept] == ids[len(ids) - len(kept) :] + # Results are cleared oldest first. + had_result = {op["id"] for op in record["operations"] if "result" in op} + cleared = [ + "result" not in kept[i] for i in ids if i in kept and i in had_result + ] + assert cleared == sorted(cleared, reverse=True) + + +def _one_at_a_time(record: dict[str, Any], limit: int) -> dict[str, Any]: + # The truncation before the binary search, for the identity render. + ids = _oldest_first(record) + ops = {op["id"]: dict(op) for op in record["operations"]} + out: dict[str, Any] = {} + dropped = 0 + + def fits() -> bool: + out.clear() + out.update(record, truncated=True) + out["operations"] = [ + ops[op["id"]] for op in record["operations"] if op["id"] in ops + ] + if dropped: + out["droppedOperations"] = dropped + size = json_byte_size(out) + return size is not None and size <= limit + + for i in ids: + if fits(): + return out + if ops[i].pop("result", None) is not None: + ops[i]["truncated"] = True + for i in ids: + if fits(): + return out + del ops[i] + dropped += 1 + fits() + return out + + +def test_truncation_matches_one_at_a_time_drops_for_the_array_format(): + rng = random.Random(1174) + for _ in range(300): + record = _random_record(rng) + record.pop("input", None) + record.pop("output", None) + # Every result is longer than 20 bytes. So each cleared result and each + # dropped operation makes the record smaller, and the fewest drops are + # well defined. + for op in record["operations"]: + if "result" in op: + op["result"] = "r" * rng.randint(21, 80) + full = json_byte_size(record) + assert full is not None + limit = rng.randint(1, full - 1) if full > 1 else 1 + expected = _one_at_a_time(record, limit) + out = truncate_record(record, limit) + if out is record: + continue + assert out == expected + + +def test_by_name_truncation_can_drop_more_than_the_fewest_but_fits(): + # Dropping the older "x" makes the error of the newer "x" appear in the + # by-name map. So the size does not shrink with every drop. Dropping one + # operation fits, but the binary search measures 5 drops first, which do + # not fit, and then settles on 6. + ops = [_op(f"p{i}", id=f"{i:02d}", startTime=f"t{i:02d}") for i in range(4)] + ops.append(_op("x", id="04", startTime="t04")) + error = {"name": "E", "message": "m" * 2000} + ops.append(_op("x", id="05", startTime="t05", status="FAILED", error=error)) + ops += [ + _op(f"q{i}", id=f"{6 + i:02d}", startTime=f"t{6 + i:02d}") for i in range(4) + ] + record = {"executionArn": "arn", "operations": ops} + full = json_byte_size(with_operations_by_name(record)) + assert full is not None + out = truncate_record(record, full - 10, with_operations_by_name) + assert out["droppedOperations"] == 6 + size = json_byte_size(with_operations_by_name(out)) + assert size is not None and size <= full - 10 + + +def test_truncation_clears_every_result_before_it_drops_an_operation(): + ops = [ + _op(f"o{i}", id=f"{i}", startTime=f"t{i}", result="r" * 100) for i in range(4) + ] + record = {"executionArn": "arn", "operations": ops} + cleared = { + **record, + "truncated": True, + "operations": [ + {**{k: v for k, v in op.items() if k != "result"}, "truncated": True} + for op in ops + ], + } + limit = json_byte_size(cleared) + assert limit is not None + out = truncate_record(record, limit) + assert out == cleared + + +def test_truncation_drops_every_operation_before_it_drops_the_input(): + ops = [_op(f"o{i}", id=f"{i}", startTime=f"t{i}") for i in range(4)] + record = {"executionArn": "arn", "input": "i" * 50, "operations": ops} + dropped = { + **record, + "truncated": True, + "operations": [], + "droppedOperations": 4, + } + limit = json_byte_size(dropped) + assert limit is not None + out = truncate_record(record, limit) + assert out == dropped