From 6124107ef38ccd9f1c4c44037e5156e4e2e4bf3f Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 25 Nov 2026 21:03:30 +0000 Subject: [PATCH 1/6] test(telemetry): count truncation renders Truncation renders and measures the whole record before every drop. A by-name record with 2,000 operations over a 256,000-byte limit takes 2,680 renders on main. This test asserts fewer than 40 renders. So it fails until the drop count is found by a binary search. --- .../tests/test_shaping.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) 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..76b8491e8 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 @@ -224,3 +224,51 @@ 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 From 413ad01569d092b8b0d0373ab68880bb69bbd09b Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 25 Nov 2026 21:08:30 +0000 Subject: [PATCH 2/6] fix(telemetry): binary search truncation drops Truncation dropped one result or operation at a time. After each drop it rendered and measured the whole record. So a record with n operations took up to about 2n renders of size n, which is O(n^2). Each phase now finds its drop count with a binary search. So a record takes about 2 * log2(n) renders, with any render function. The search assumes that each drop makes the record smaller. The by-name map can break this. Then truncation can drop more old operations than the fewest that fit. The chosen count is always measured, so the output never goes over the limit. Fixes #908 Co-authored-by: pcbeingused333 <82875882+pcbeingused333@users.noreply.github.com> Co-authored-by: jay23606 <4602056+jay23606@users.noreply.github.com> --- .../README.md | 9 + .../truncation.py | 76 ++++++--- .../tests/test_shaping.py | 156 ++++++++++++++++++ 3 files changed, 216 insertions(+), 25 deletions(-) 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..83c25b931 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,15 @@ 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 search assumes that each drop makes the +rendered record smaller. The `operationsByName` map can break this: when one of +two operations with the same name is dropped, the result and error of the other +one appear. In such a record, truncation can drop a few more old operations than +the fewest that fit. The emitted record is always measured, so it never goes +over the limit. + 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..960e77220 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,43 @@ 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. + # The by-name map can break this: when one of two operations with the + # same name is dropped, the result and error of the other one appear. + # Then the search can return a larger count than the smallest one that + # fits. The returned count was always measured. So the output never + # goes over the limit. + 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 +172,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 76b8491e8..c878ce1ce 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, ) @@ -272,3 +274,157 @@ def render(record: dict[str, Any]) -> Any: 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) + 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 From 604305cc225e2aaa3f7ccace423f0ca539d05c92 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 25 Nov 2026 22:40:56 +0000 Subject: [PATCH 3/6] fix(telemetry): keep small results in truncation Clearing a result replaces "result": with "truncated":true. When the result JSON is 7 bytes or shorter, the record grows. So the size after clearing j results was not monotonic, and the binary search could clear every result and drop operations that the one-at-a-time check kept. Only results longer than 7 bytes are now cleared. Shorter results stay in the record, unmarked. The record after dropping causes is measured before the results search, so a record that fits then keeps every result. The array format now drops the fewest. Extra drops can happen only in the by-name format. --- .../README.md | 16 ++- .../truncation.py | 64 +++++++--- .../tests/test_shaping.py | 110 +++++++++++++++++- 3 files changed, 163 insertions(+), 27 deletions(-) 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 83c25b931..01eb46941 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md @@ -327,14 +327,20 @@ 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 keeps a result whose JSON is 7 bytes or shorter (for example `1`, +`true` or `"ok"`). Clearing such a result replaces it with `"truncated":true`, +which is longer, so the record would grow. + 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 search assumes that each drop makes the -rendered record smaller. The `operationsByName` map can break this: when one of -two operations with the same name is dropped, the result and error of the other -one appear. In such a record, truncation can drop a few more old operations than -the fewest that fit. The emitted record is always measured, so it never goes -over the limit. +rendered record smaller. In the `array` format this holds, so truncation drops +the fewest results and operations that fit. The `operationsByName` map can +break it: when one of two operations with the same name is dropped, the result +and error of the other one appear. So in the `by-name` format, and in the +by-name part of `both`, truncation can drop a few more old operations than the +fewest that fit. The emitted record is always measured, so it never goes over +the limit. Names are each language's own and differ across SDKs. For example, a step that throws `PaymentError` can be reported as `StepError` in JS, 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 960e77220..da7772c19 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 @@ -8,7 +8,8 @@ SDK never carry a cause, so this step only changes a record whose errors were given a ``cause`` by other code; 1. operation ``result`` fields, oldest operation first (each dropped op marked - ``truncated: true``); + ``truncated: true``). A result whose JSON is 7 bytes or shorter stays, + because clearing it would make the record bigger; 2. whole operations, oldest first (``droppedOperations`` count); 3. last resort — execution ``input`` then ``output`` (``droppedInput`` / ``droppedOutput``). @@ -46,6 +47,16 @@ def json_byte_size(value: Any) -> int | None: return None +# Size of ``"truncated":true`` minus the size of ``"result":`` (7 bytes). +_MAX_KEPT_RESULT_SIZE = len('"truncated":true') - len('"result":') + + +def _shrinks_when_cleared(result: Any) -> bool: + # A result that cannot be measured is cleared, as before. + size = json_byte_size(result) + return size is None or size > _MAX_KEPT_RESULT_SIZE + + def _has_cause(holder: dict[str, Any]) -> bool: error = holder.get("error") return isinstance(error, dict) and "cause" in error @@ -87,17 +98,30 @@ 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[i] is the position of operation i in ``order``. A candidate removes + # the operations with rank below ``dropped_ops``. rank = [0] * len(ops) for position, idx in enumerate(order): rank[idx] = position + # Clearing replaces ``"result":`` with ``"truncated":true`` (16 + # bytes). When the result JSON is 7 bytes or shorter (for example ``1``, + # ``true`` or ``"ok"``), clearing makes the record bigger, so it cannot help + # the record fit. So only longer results are cleared. result_rank[i] is + # the position of operation i among these results, oldest first. A + # candidate clears the results with result_rank below ``cleared_results``. + result_ops = [ + i + for i in order + if ops[i].get("result") is not None and _shrinks_when_cleared(ops[i]["result"]) + ] + result_rank = [len(ops)] * len(ops) + for position, idx in enumerate(result_ops): + result_rank[idx] = position cleared = [ {**{k: v for k, v in op.items() if k != "result"}, "truncated": True} - if op.get("result") is not None + if result_rank[i] < len(ops) else op - for op in ops + for i, op in enumerate(ops) ] dropped_input = False @@ -106,7 +130,7 @@ def truncate_record( def candidate(cleared_results: int, dropped_ops: int) -> dict[str, Any]: out = dict(record) out["operations"] = [ - cleared[i] if rank[i] < cleared_results else op + cleared[i] if result_rank[i] < cleared_results else op for i, op in enumerate(ops) if rank[i] >= dropped_ops ] @@ -131,11 +155,14 @@ def fits(cleared_results: int, dropped_ops: int) -> bool: 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. - # The by-name map can break this: when one of two operations with the - # same name is dropped, the result and error of the other one appear. - # Then the search can return a larger count than the smallest one that - # fits. The returned count was always measured. So the output never - # goes over the limit. + # In the array form this holds, because only results that shrink the + # record are cleared. So the array form drops the fewest. The by-name + # map can break it: when one of two operations with the same name is + # dropped, the result and error of the other one appear. Then the + # search can return a larger count than the smallest one that fits. + # So extra drops can happen only in the by-name form (and the by-name + # part of "both"). The returned count was always measured. So the + # output never goes over the limit. found = None while low <= high: middle = (low + high) // 2 @@ -145,16 +172,19 @@ def first_fit(low: int, high: int, fits_at: Callable[[int], bool]) -> int | None low = middle + 1 return found - # Phase 1: drop operation results oldest-first. + # Phase 1: drop operation results oldest-first. The record after phase 0 + # is measured first, so a record that fits without clearing a result keeps + # every result. count = len(ops) - found = first_fit(0, count, lambda j: fits(j, 0)) - cleared_results = count if found is None else found + results = len(result_ops) + found = 0 if fits(0, 0) else first_fit(1, results, lambda j: fits(j, 0)) + cleared_results = results 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]) + any_result = cleared_results > 0 # Phase 2: drop whole operations oldest-first. if found is None: - found = first_fit(1, count, lambda k: fits(count, k)) + found = first_fit(1, count, lambda k: fits(results, k)) dropped_ops = count if found is None else found # Phase 3 (last resort): drop input then output. 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 c878ce1ce..35a874f31 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 @@ -292,6 +292,22 @@ def render(record: dict[str, Any]) -> Any: _NAMES = ["a", "a", "b", "", 'q"uote', "back\\slash", "ünï", "😀", "\u2028", None] +# Short results are common: 1, true and "ok" are shorter than the +# "truncated":true marker, so truncation keeps them. +_RESULTS = [ + 1, + 0, + True, + False, + "", + "ok", + '"x"', + "12345", + "123456", + [1], + {"k": [1, 2]}, + "\\" * 9, +] def _random_record(rng: random.Random) -> dict[str, Any]: @@ -310,7 +326,7 @@ def _random_record(rng: random.Random) -> dict[str, Any]: 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]) + op["result"] = rng.choice(_RESULTS + ["ü" * rng.randint(0, 80)]) if rng.random() < 0.3: op["error"] = {"name": "E", "message": "m" * rng.randint(0, 60)} ops.append(op) @@ -353,8 +369,18 @@ def render(r: dict[str, Any], fmt: OperationsFormat = fmt) -> Any: 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} + # Results longer than 7 bytes are cleared oldest first. Shorter ones + # are kept. + had_result = { + op["id"] + for op in record["operations"] + if (json_byte_size(op.get("result")) or 0) > 7 + } + assert all( + "result" in kept[op["id"]] + for op in record["operations"] + if op["id"] in kept and op["id"] not in had_result and "result" in op + ) cleared = [ "result" not in kept[i] for i in ids if i in kept and i in had_result ] @@ -362,7 +388,8 @@ def render(r: dict[str, Any], fmt: OperationsFormat = fmt) -> Any: def _one_at_a_time(record: dict[str, Any], limit: int) -> dict[str, Any]: - # The truncation before the binary search, for the identity render. + # The truncation before the binary search, for the identity render. A + # result whose JSON is 7 bytes or shorter is kept. ids = _oldest_first(record) ops = {op["id"]: dict(op) for op in record["operations"]} out: dict[str, Any] = {} @@ -382,7 +409,9 @@ def fits() -> bool: for i in ids: if fits(): return out - if ops[i].pop("result", None) is not None: + result_size = json_byte_size(ops[i].get("result")) + if ops[i].get("result") is not None and (result_size or 0) > 7: + del ops[i]["result"] ops[i]["truncated"] = True for i in ids: if fits(): @@ -428,3 +457,74 @@ def test_by_name_truncation_can_drop_more_than_the_fewest_but_fits(): 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_keeps_small_results_and_clears_the_large_old_one(): + # Clearing a small result (true, 1, "ok") adds bytes in the array format. + # So only the large oldest result is cleared, and no operation is dropped. + small = [True, 1, "ok", None, 1] + ops = [_op("big", id="0000", startTime="t0000", result="x" * 2000)] + ops += [ + _op(f"s{i}", id=f"{i:04d}", startTime=f"t{i:04d}", result=small[i % 5]) + for i in range(1, 2000) + ] + record = {"executionArn": "arn", "operations": ops} + full = json_byte_size(record) + assert full is not None + out = truncate_record(record, full - 1) + assert out == _one_at_a_time(record, full - 1) + assert "droppedOperations" not in out + assert [op["id"] for op in out["operations"] if op.get("truncated")] == ["0000"] + + +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 + + +def test_truncation_keeps_results_when_dropping_causes_is_enough(): + error = {"name": "E", "message": "m", "cause": {"name": "C", "message": "c" * 400}} + ops = [ + _op(f"o{i}", id=f"{i}", startTime=f"t{i}", result="r" * 100) for i in range(3) + ] + ops.append(_op("f", id="3", startTime="t3", status="FAILED", error=error)) + record = {"executionArn": "arn", "operations": ops} + no_causes = { + **record, + "truncated": True, + "droppedCauses": True, + "operations": ops[:3] + [{**ops[3], "error": {"name": "E", "message": "m"}}], + } + limit = json_byte_size(no_causes) + assert limit is not None + out = truncate_record(record, limit) + assert out == no_causes From 4172d78f1b59e63da465db9c045a4a5edbf09cd4 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Wed, 25 Nov 2026 22:47:54 +0000 Subject: [PATCH 4/6] fix(telemetry): clear small results when hidden The by-name map writes no truncated marker. So in by-name, clearing a result of 7 bytes or less still makes the record smaller. Keeping such results made by-name truncation drop operations that the base kept. Before the results search, one render clears every small result. If it is smaller than the record after dropping causes, small results stay candidates, as in the base. Otherwise only longer results are cleared. The extra render runs only when small results exist. --- .../README.md | 9 ++- .../truncation.py | 63 ++++++++++++------- .../tests/test_shaping.py | 52 +++++++++++---- 3 files changed, 87 insertions(+), 37 deletions(-) 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 01eb46941..695d24a8a 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md @@ -327,9 +327,12 @@ 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 keeps a result whose JSON is 7 bytes or shorter (for example `1`, -`true` or `"ok"`). Clearing such a result replaces it with `"truncated":true`, -which is longer, so the record would grow. +Clearing a result replaces it with `"truncated":true`. When the result JSON is +7 bytes or shorter (for example `1`, `true` or `"ok"`), this makes the `array` +format bigger. So truncation first renders the record once with every such +small result cleared. If that render is smaller, the render hides the marker +(as `operationsByName` does), and small results are cleared like the others. +Otherwise truncation keeps small results. 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` 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 da7772c19..a40a4a4d5 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 @@ -8,8 +8,8 @@ SDK never carry a cause, so this step only changes a record whose errors were given a ``cause`` by other code; 1. operation ``result`` fields, oldest operation first (each dropped op marked - ``truncated: true``). A result whose JSON is 7 bytes or shorter stays, - because clearing it would make the record bigger; + ``truncated: true``). A result whose JSON is 7 bytes or shorter stays + when clearing it makes the rendered record bigger; 2. whole operations, oldest first (``droppedOperations`` count); 3. last resort — execution ``input`` then ``output`` (``droppedInput`` / ``droppedOutput``). @@ -103,25 +103,25 @@ def truncate_record( rank = [0] * len(ops) for position, idx in enumerate(order): rank[idx] = position - # Clearing replaces ``"result":`` with ``"truncated":true`` (16 - # bytes). When the result JSON is 7 bytes or shorter (for example ``1``, - # ``true`` or ``"ok"``), clearing makes the record bigger, so it cannot help - # the record fit. So only longer results are cleared. result_rank[i] is - # the position of operation i among these results, oldest first. A + # result_ops lists the operations whose result truncation may clear, + # oldest first. result_rank[i] is the position of operation i in it. A # candidate clears the results with result_rank below ``cleared_results``. - result_ops = [ - i - for i in order - if ops[i].get("result") is not None and _shrinks_when_cleared(ops[i]["result"]) - ] + with_result = [i for i in order if ops[i].get("result") is not None] + small = [i for i in with_result if not _shrinks_when_cleared(ops[i]["result"])] + result_ops = [i for i in with_result if _shrinks_when_cleared(ops[i]["result"])] result_rank = [len(ops)] * len(ops) - for position, idx in enumerate(result_ops): - result_rank[idx] = position + + def rank_results(selected: list[int]) -> None: + for i in range(len(ops)): + result_rank[i] = len(ops) + for position, idx in enumerate(selected): + result_rank[idx] = position + cleared = [ {**{k: v for k, v in op.items() if k != "result"}, "truncated": True} - if result_rank[i] < len(ops) + if op.get("result") is not None else op - for i, op in enumerate(ops) + for op in ops ] dropped_input = False @@ -148,17 +148,20 @@ def candidate(cleared_results: int, dropped_ops: int) -> dict[str, Any]: out["droppedOutput"] = True return out + def size_at(cleared_results: int, dropped_ops: int) -> int | None: + return measure(render(candidate(cleared_results, dropped_ops))) + def fits(cleared_results: int, dropped_ops: int) -> bool: - size = measure(render(candidate(cleared_results, dropped_ops))) + size = size_at(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. # In the array form this holds, because only results that shrink the - # record are cleared. So the array form drops the fewest. The by-name - # map can break it: when one of two operations with the same name is - # dropped, the result and error of the other one appear. Then the + # rendered record are cleared. So the array form drops the fewest. + # The by-name map can break it: when one of two operations with the + # same name is dropped, the result and error of the other one appear. Then the # search can return a larger count than the smallest one that fits. # So extra drops can happen only in the by-name form (and the by-name # part of "both"). The returned count was always measured. So the @@ -176,8 +179,26 @@ def first_fit(low: int, high: int, fits_at: Callable[[int], bool]) -> int | None # is measured first, so a record that fits without clearing a result keeps # every result. count = len(ops) + base_size = size_at(0, 0) + found = 0 if base_size is not None and base_size <= max_bytes else None + # Clearing replaces ``"result":`` with ``"truncated":true``. When + # the result JSON is 7 bytes or shorter (for example ``1``, ``true`` or + # ``"ok"``), this makes the array form bigger, so it cannot help the + # record fit. A render that hides the marker (for example the by-name map) + # still gets smaller. So one render clears every small result. If it is + # smaller than the record after phase 0, small results stay candidates. + # Otherwise only the longer results are cleared, and small results stay. + if found is None and small: + rank_results(small) + small_cleared = size_at(len(small), 0) + if small_cleared is not None and ( + base_size is None or small_cleared < base_size + ): + result_ops = with_result + rank_results(result_ops) results = len(result_ops) - found = 0 if fits(0, 0) else first_fit(1, results, lambda j: fits(j, 0)) + if found is None: + found = first_fit(1, results, lambda j: fits(j, 0)) cleared_results = results if found is None else found dropped_ops = 0 any_result = cleared_results > 0 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 35a874f31..b71769a05 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 @@ -369,27 +369,33 @@ def render(r: dict[str, Any], fmt: OperationsFormat = fmt) -> Any: 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 longer than 7 bytes are cleared oldest first. Shorter ones - # are kept. - had_result = { + # Results are cleared oldest first. A result of 7 bytes or shorter is + # a candidate only when the render hides the marker. In the array + # format it is never cleared, because clearing it adds bytes. + large = { op["id"] for op in record["operations"] if (json_byte_size(op.get("result")) or 0) > 7 } - assert all( - "result" in kept[op["id"]] - for op in record["operations"] - if op["id"] in kept and op["id"] not in had_result and "result" in op - ) + small = {op["id"] for op in record["operations"] if "result" in op} - large + small_cleared = any("result" not in kept[i] for i in small if i in kept) + assert not (fmt == OperationsFormat.ARRAY and small_cleared) + had_result = large | small if small_cleared else large 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. A - # result whose JSON is 7 bytes or shorter is kept. +def _one_at_a_time( + record: dict[str, Any], + limit: int, + render: Any = None, + max_kept: int = 7, +) -> dict[str, Any]: + # The truncation before the binary search. A result whose JSON is + # ``max_kept`` bytes or shorter is kept. Pass -1 to clear every result. + render = render or (lambda r: r) ids = _oldest_first(record) ops = {op["id"]: dict(op) for op in record["operations"]} out: dict[str, Any] = {} @@ -403,14 +409,14 @@ def fits() -> bool: ] if dropped: out["droppedOperations"] = dropped - size = json_byte_size(out) + size = json_byte_size(render(out)) return size is not None and size <= limit for i in ids: if fits(): return out result_size = json_byte_size(ops[i].get("result")) - if ops[i].get("result") is not None and (result_size or 0) > 7: + if ops[i].get("result") is not None and (result_size or 0) > max_kept: del ops[i]["result"] ops[i]["truncated"] = True for i in ids: @@ -528,3 +534,23 @@ def test_truncation_keeps_results_when_dropping_causes_is_enough(): assert limit is not None out = truncate_record(record, limit) assert out == no_causes + + +def test_by_name_truncation_clears_small_results_like_the_base(): + # The by-name map writes no truncated marker. So clearing a small result + # makes the record smaller, and small results stay candidates. The limit + # needs the large result and about half of the small results cleared. + small = [True, 1, "ok", None, 1] + ops = [_op("big", id="0000", startTime="t0000", result="x" * 2000)] + ops += [ + _op(f"s{i}", id=f"{i:04d}", startTime=f"t{i:04d}", result=small[i % 5]) + for i in range(1, 200) + ] + record = {"executionArn": "arn", "operations": ops} + full = json_byte_size(with_operations_by_name(record)) + assert full is not None + limit = full - 2000 - 800 + expected = _one_at_a_time(record, limit, with_operations_by_name, max_kept=-1) + assert "droppedOperations" not in expected + out = truncate_record(record, limit, with_operations_by_name) + assert out == expected From b59569a747b3824c555086d8424f5d9bd7d20966 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 02:43:12 +0000 Subject: [PATCH 5/6] docs(telemetry): state the truncation guarantee The binary search can drop more results or operations than the one-at-a-time check. This happens with escaped string bodies (OTel) and with repeated names in the by-name map. The output never goes over the limit while dropping everything droppable makes it fit. --- .../README.md | 15 +++++++------- .../truncation.py | 20 +++++++++---------- 2 files changed, 18 insertions(+), 17 deletions(-) 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 695d24a8a..746f386f8 100644 --- a/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md +++ b/packages/aws-durable-execution-sdk-python-telemetry-exporter/README.md @@ -337,13 +337,14 @@ Otherwise truncation keeps small results. 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 search assumes that each drop makes the -rendered record smaller. In the `array` format this holds, so truncation drops -the fewest results and operations that fit. The `operationsByName` map can -break it: when one of two operations with the same name is dropped, the result -and error of the other one appear. So in the `by-name` format, and in the -by-name part of `both`, truncation can drop a few more old operations than the -fewest that fit. The emitted record is always measured, so it never goes over -the limit. +rendered record smaller. Some renders break this assumption. For example, +`OTelExporter` escapes the record into one string body. In the +`operationsByName` map, the result and error of a repeated name appear when the +other operation with that name is dropped. So truncation can drop more results +or operations than the fewest that fit. 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. Names are each language's own and differ across SDKs. For example, a step that throws `PaymentError` can be reported as `StepError` in JS, 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 a40a4a4d5..6a6df3f26 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 @@ -8,8 +8,9 @@ SDK never carry a cause, so this step only changes a record whose errors were given a ``cause`` by other code; 1. operation ``result`` fields, oldest operation first (each dropped op marked - ``truncated: true``). A result whose JSON is 7 bytes or shorter stays - when clearing it makes the rendered record bigger; + ``truncated: true``). A result whose JSON is 7 bytes or shorter is a + small result. One probe render decides for all small results at once: + either all of them can be cleared, or all of them stay; 2. whole operations, oldest first (``droppedOperations`` count); 3. last resort — execution ``input`` then ``output`` (``droppedInput`` / ``droppedOutput``). @@ -158,14 +159,13 @@ def fits(cleared_results: int, dropped_ops: int) -> bool: 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. - # In the array form this holds, because only results that shrink the - # rendered record are cleared. So the array form drops the fewest. - # The by-name map can break it: when one of two operations with the - # same name is dropped, the result and error of the other one appear. Then the - # search can return a larger count than the smallest one that fits. - # So extra drops can happen only in the by-name form (and the by-name - # part of "both"). The returned count was always measured. So the - # output never goes over the limit. + # Some renders break this assumption, for example an escaped string + # body or a by-name map with repeated names. 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 From 202615cd14c4a1115c2e2b50ff1e6a4b2810a3a9 Mon Sep 17 00:00:00 2001 From: Pooya Paridel Date: Thu, 26 Nov 2026 02:53:25 +0000 Subject: [PATCH 6/6] refactor(telemetry): return to plain binary search Remove the small-result probe and the separate check before the results search. Every operation with a result is a candidate again, oldest first, as in the first binary-search commit. The output never goes over the limit, as long as dropping everything droppable makes it fit. Truncation can drop more results and operations than the one-at-a-time code. That trade-off is accepted for simpler code. Tests: remove the small-result and cause-only tests. Keep the one-at-a-time comparison only for results longer than 20 bytes, where each drop makes the record smaller. Keep the upper-bound tests. --- .../README.md | 34 +++--- .../truncation.py | 85 +++---------- .../tests/test_shaping.py | 112 ++---------------- 3 files changed, 49 insertions(+), 182 deletions(-) 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 746f386f8..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,24 +327,26 @@ 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. -Clearing a result replaces it with `"truncated":true`. When the result JSON is -7 bytes or shorter (for example `1`, `true` or `"ok"`), this makes the `array` -format bigger. So truncation first renders the record once with every such -small result cleared. If that render is smaller, the render hides the marker -(as `operationsByName` does), and small results are cleared like the others. -Otherwise truncation keeps small results. - 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 search assumes that each drop makes the -rendered record smaller. Some renders break this assumption. For example, -`OTelExporter` escapes the record into one string body. In the -`operationsByName` map, the result and error of a repeated name appear when the -other operation with that name is dropped. So truncation can drop more results -or operations than the fewest that fit. 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. +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, 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 6a6df3f26..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 @@ -8,9 +8,7 @@ SDK never carry a cause, so this step only changes a record whose errors were given a ``cause`` by other code; 1. operation ``result`` fields, oldest operation first (each dropped op marked - ``truncated: true``). A result whose JSON is 7 bytes or shorter is a - small result. One probe render decides for all small results at once: - either all of them can be cleared, or all of them stay; + ``truncated: true``); 2. whole operations, oldest first (``droppedOperations`` count); 3. last resort — execution ``input`` then ``output`` (``droppedInput`` / ``droppedOutput``). @@ -48,16 +46,6 @@ def json_byte_size(value: Any) -> int | None: return None -# Size of ``"truncated":true`` minus the size of ``"result":`` (7 bytes). -_MAX_KEPT_RESULT_SIZE = len('"truncated":true') - len('"result":') - - -def _shrinks_when_cleared(result: Any) -> bool: - # A result that cannot be measured is cleared, as before. - size = json_byte_size(result) - return size is None or size > _MAX_KEPT_RESULT_SIZE - - def _has_cause(holder: dict[str, Any]) -> bool: error = holder.get("error") return isinstance(error, dict) and "cause" in error @@ -99,25 +87,12 @@ 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 removes - # the operations with rank below ``dropped_ops``. + # 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 - # result_ops lists the operations whose result truncation may clear, - # oldest first. result_rank[i] is the position of operation i in it. A - # candidate clears the results with result_rank below ``cleared_results``. - with_result = [i for i in order if ops[i].get("result") is not None] - small = [i for i in with_result if not _shrinks_when_cleared(ops[i]["result"])] - result_ops = [i for i in with_result if _shrinks_when_cleared(ops[i]["result"])] - result_rank = [len(ops)] * len(ops) - - def rank_results(selected: list[int]) -> None: - for i in range(len(ops)): - result_rank[i] = len(ops) - for position, idx in enumerate(selected): - result_rank[idx] = position - cleared = [ {**{k: v for k, v in op.items() if k != "result"}, "truncated": True} if op.get("result") is not None @@ -131,7 +106,7 @@ def rank_results(selected: list[int]) -> None: def candidate(cleared_results: int, dropped_ops: int) -> dict[str, Any]: out = dict(record) out["operations"] = [ - cleared[i] if result_rank[i] < cleared_results else op + cleared[i] if rank[i] < cleared_results else op for i, op in enumerate(ops) if rank[i] >= dropped_ops ] @@ -149,23 +124,20 @@ def candidate(cleared_results: int, dropped_ops: int) -> dict[str, Any]: out["droppedOutput"] = True return out - def size_at(cleared_results: int, dropped_ops: int) -> int | None: - return measure(render(candidate(cleared_results, dropped_ops))) - def fits(cleared_results: int, dropped_ops: int) -> bool: - size = size_at(cleared_results, dropped_ops) + 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 renders break this assumption, for example an escaped string - # body or a by-name map with repeated names. 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. + # 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 @@ -175,37 +147,16 @@ def first_fit(low: int, high: int, fits_at: Callable[[int], bool]) -> int | None low = middle + 1 return found - # Phase 1: drop operation results oldest-first. The record after phase 0 - # is measured first, so a record that fits without clearing a result keeps - # every result. + # Phase 1: drop operation results oldest-first. count = len(ops) - base_size = size_at(0, 0) - found = 0 if base_size is not None and base_size <= max_bytes else None - # Clearing replaces ``"result":`` with ``"truncated":true``. When - # the result JSON is 7 bytes or shorter (for example ``1``, ``true`` or - # ``"ok"``), this makes the array form bigger, so it cannot help the - # record fit. A render that hides the marker (for example the by-name map) - # still gets smaller. So one render clears every small result. If it is - # smaller than the record after phase 0, small results stay candidates. - # Otherwise only the longer results are cleared, and small results stay. - if found is None and small: - rank_results(small) - small_cleared = size_at(len(small), 0) - if small_cleared is not None and ( - base_size is None or small_cleared < base_size - ): - result_ops = with_result - rank_results(result_ops) - results = len(result_ops) - if found is None: - found = first_fit(1, results, lambda j: fits(j, 0)) - cleared_results = results if found is None else found + found = first_fit(0, count, lambda j: fits(j, 0)) + cleared_results = count if found is None else found dropped_ops = 0 - any_result = cleared_results > 0 + any_result = any(ops[i].get("result") is not None for i in order[:cleared_results]) # Phase 2: drop whole operations oldest-first. if found is None: - found = first_fit(1, count, lambda k: fits(results, k)) + 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. 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 b71769a05..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 @@ -292,22 +292,6 @@ def render(record: dict[str, Any]) -> Any: _NAMES = ["a", "a", "b", "", 'q"uote', "back\\slash", "ünï", "😀", "\u2028", None] -# Short results are common: 1, true and "ok" are shorter than the -# "truncated":true marker, so truncation keeps them. -_RESULTS = [ - 1, - 0, - True, - False, - "", - "ok", - '"x"', - "12345", - "123456", - [1], - {"k": [1, 2]}, - "\\" * 9, -] def _random_record(rng: random.Random) -> dict[str, Any]: @@ -326,7 +310,7 @@ def _random_record(rng: random.Random) -> dict[str, Any]: 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(_RESULTS + ["ü" * rng.randint(0, 80)]) + 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) @@ -369,33 +353,16 @@ def render(r: dict[str, Any], fmt: OperationsFormat = fmt) -> Any: 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. A result of 7 bytes or shorter is - # a candidate only when the render hides the marker. In the array - # format it is never cleared, because clearing it adds bytes. - large = { - op["id"] - for op in record["operations"] - if (json_byte_size(op.get("result")) or 0) > 7 - } - small = {op["id"] for op in record["operations"] if "result" in op} - large - small_cleared = any("result" not in kept[i] for i in small if i in kept) - assert not (fmt == OperationsFormat.ARRAY and small_cleared) - had_result = large | small if small_cleared else large + # 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, - render: Any = None, - max_kept: int = 7, -) -> dict[str, Any]: - # The truncation before the binary search. A result whose JSON is - # ``max_kept`` bytes or shorter is kept. Pass -1 to clear every result. - render = render or (lambda r: r) +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] = {} @@ -409,15 +376,13 @@ def fits() -> bool: ] if dropped: out["droppedOperations"] = dropped - size = json_byte_size(render(out)) + size = json_byte_size(out) return size is not None and size <= limit for i in ids: if fits(): return out - result_size = json_byte_size(ops[i].get("result")) - if ops[i].get("result") is not None and (result_size or 0) > max_kept: - del ops[i]["result"] + if ops[i].pop("result", None) is not None: ops[i]["truncated"] = True for i in ids: if fits(): @@ -434,6 +399,12 @@ def test_truncation_matches_one_at_a_time_drops_for_the_array_format(): 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 @@ -465,24 +436,6 @@ def test_by_name_truncation_can_drop_more_than_the_fewest_but_fits(): assert size is not None and size <= full - 10 -def test_truncation_keeps_small_results_and_clears_the_large_old_one(): - # Clearing a small result (true, 1, "ok") adds bytes in the array format. - # So only the large oldest result is cleared, and no operation is dropped. - small = [True, 1, "ok", None, 1] - ops = [_op("big", id="0000", startTime="t0000", result="x" * 2000)] - ops += [ - _op(f"s{i}", id=f"{i:04d}", startTime=f"t{i:04d}", result=small[i % 5]) - for i in range(1, 2000) - ] - record = {"executionArn": "arn", "operations": ops} - full = json_byte_size(record) - assert full is not None - out = truncate_record(record, full - 1) - assert out == _one_at_a_time(record, full - 1) - assert "droppedOperations" not in out - assert [op["id"] for op in out["operations"] if op.get("truncated")] == ["0000"] - - 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) @@ -515,42 +468,3 @@ def test_truncation_drops_every_operation_before_it_drops_the_input(): assert limit is not None out = truncate_record(record, limit) assert out == dropped - - -def test_truncation_keeps_results_when_dropping_causes_is_enough(): - error = {"name": "E", "message": "m", "cause": {"name": "C", "message": "c" * 400}} - ops = [ - _op(f"o{i}", id=f"{i}", startTime=f"t{i}", result="r" * 100) for i in range(3) - ] - ops.append(_op("f", id="3", startTime="t3", status="FAILED", error=error)) - record = {"executionArn": "arn", "operations": ops} - no_causes = { - **record, - "truncated": True, - "droppedCauses": True, - "operations": ops[:3] + [{**ops[3], "error": {"name": "E", "message": "m"}}], - } - limit = json_byte_size(no_causes) - assert limit is not None - out = truncate_record(record, limit) - assert out == no_causes - - -def test_by_name_truncation_clears_small_results_like_the_base(): - # The by-name map writes no truncated marker. So clearing a small result - # makes the record smaller, and small results stay candidates. The limit - # needs the large result and about half of the small results cleared. - small = [True, 1, "ok", None, 1] - ops = [_op("big", id="0000", startTime="t0000", result="x" * 2000)] - ops += [ - _op(f"s{i}", id=f"{i:04d}", startTime=f"t{i:04d}", result=small[i % 5]) - for i in range(1, 200) - ] - record = {"executionArn": "arn", "operations": ops} - full = json_byte_size(with_operations_by_name(record)) - assert full is not None - limit = full - 2000 - 800 - expected = _one_at_a_time(record, limit, with_operations_by_name, max_kept=-1) - assert "droppedOperations" not in expected - out = truncate_record(record, limit, with_operations_by_name) - assert out == expected