Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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)
Expand All @@ -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:
Comment thread
ParidelPooya marked this conversation as resolved.
Resolved
# 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
Comment on lines +131 to +148

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this loop could use the standard library. bisect.bisect_left takes a key= function since Python 3.10, and this package needs 3.11 or newer:

import bisect

def first_fit(low: int, high: int, fits_at: Callable[[int], bool]) -> int | None:
    counts = range(low, high + 1)
    i = bisect.bisect_left(counts, True, key=fits_at)
    return counts[i] if i < len(counts) else None

range is lazy, so this probes the same number of counts as the loop, and the count it returns was always measured to fit. One thing to know: bisect_left uses the upper midpoint, like Go's sort.Search, Java and Rust, while this loop and JS use the lower one. For low..high = 0..3 it probes 2 first, not 1. So this fits if the SDKs settle on the upper midpoint as the shared rule.

🤖 AI-assisted comment


# 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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should-fix: Python searches over every operation, but JS #1293 searches only over the operations that have a result. So the two can drop different things.

Example: 5 operations, oldest first. Only the first 2 have a result: B (a big one) and C (true).

Python tries Results cleared Fits?
1 B yes
2 B and C no. Clearing C makes the record 3 bytes bigger.
3 to 5 B and C no. There is nothing left to clear.
  • JS only tries 0 to 2. It tries 1 first, so it clears B and stops.
  • Python tries 0 to 5. It tries 2, then 4, then 5. None fit, so it drops whole operations.

With no results at all, Python also renders about 11 times where JS renders once.

Could Python search only over the operations that have a result?

🤖 AI-assisted comment

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 (
Expand All @@ -146,4 +174,4 @@ def fits() -> bool:
):
return record

return candidate()
return candidate(cleared_results, dropped_ops)
Loading