Skip to content

Commit 2244e9f

Browse files
fix: preserve caller-owned exceptions during sandbox redaction (#5367)
* fix: preserve caller-owned exceptions during sandbox redaction * fix: detach only root tracebacks during redaction
1 parent 67d4f8a commit 2244e9f

13 files changed

Lines changed: 318 additions & 223 deletions

‎src/agents/exceptions.py‎

Lines changed: 16 additions & 117 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def _prepare_data_redacted_error(
183183
*,
184184
trusted_error_message: str | None = None,
185185
) -> BaseException:
186-
"""Detach payload-owned state and return a safe error for a public boundary."""
186+
"""Build a safe replacement and detach only the source's retry traceback."""
187187
error_type = type(error)
188188
process_control_error = _replace_data_redacted_process_control_error(error)
189189
if process_control_error is not None:
@@ -199,7 +199,7 @@ def _prepare_data_redacted_error(
199199
except BaseException:
200200
pass
201201

202-
_discard_exception_graph(error)
202+
_detach_source_exception_traceback(error)
203203

204204
safe_error: BaseException = RuntimeError(_DATA_REDACTED_ERROR_MESSAGE)
205205
if error_type is ModelBehaviorError:
@@ -281,133 +281,32 @@ def _copy_data_redacted_process_control_error(
281281
def _replace_data_redacted_process_control_error(
282282
error: BaseException,
283283
) -> BaseException | None:
284-
"""Discard a process-control source and return a fresh value-free replacement."""
284+
"""Detach the source traceback and return a fresh process-control replacement."""
285285
safe_error = _copy_data_redacted_process_control_error(error)
286286
if safe_error is None:
287287
return None
288-
_discard_exception_graph(error)
288+
_detach_source_exception_traceback(error)
289289
return safe_error
290290

291291

292-
def _collect_nested_exceptions(value: object, linked: list[BaseException]) -> None:
293-
"""Collect exceptions reachable through exact built-in containers without callbacks."""
294-
pending = [value]
295-
seen: set[int] = set()
296-
while pending:
297-
current = pending.pop()
298-
if id(current) in seen:
299-
continue
300-
seen.add(id(current))
301-
if issubclass(type(current), BaseException):
302-
linked.append(cast(BaseException, current))
303-
elif type(current) is dict:
304-
for key, item in dict.items(current):
305-
pending.extend((key, item))
306-
elif (
307-
type(current) is list
308-
or type(current) is tuple
309-
or type(current) is set
310-
or type(current) is frozenset
311-
):
312-
pending.extend(current)
313-
292+
def _detach_source_exception_traceback(error: BaseException) -> None:
293+
"""Bound retry tracebacks without clearing caller frames or linked exceptions.
314294
315-
def _discard_exception_graph(error: BaseException) -> None:
316-
"""Best-effort clear discoverable state from an exception and its linked graph.
317-
318-
Exact built-in descriptors avoid provider-controlled attribute, descriptor, and
319-
metaclass callbacks. Read-only storage such as an exception group's message
320-
cannot be changed in place, so public boundaries must return a fresh error that
321-
does not retain the source exception.
295+
Re-raising a cached failure prepends new traceback nodes. Drop only the caught
296+
root's traceback; its fields and linked exception state remain caller-owned.
297+
Clearing frames can close suspended caller coroutines on Python before 3.13.
322298
"""
323-
pending = [error]
324-
seen: set[int] = set()
325-
while pending:
326-
current = pending.pop()
327-
if id(current) in seen:
328-
continue
329-
seen.add(id(current))
330-
331-
linked: list[BaseException] = []
332-
group_exceptions: tuple[BaseException, ...] | None = None
333-
current_type = type(current)
334-
if issubclass(current_type, BaseExceptionGroup):
335-
group_exceptions = _base_exception_group_exceptions(current)
336-
if group_exceptions is not None:
337-
linked.extend(group_exceptions)
338-
for descriptor in (
339-
cast(Any, BaseException.__cause__),
340-
cast(Any, BaseException.__context__),
341-
):
342-
try:
343-
candidate = descriptor.__get__(current, current_type)
344-
except BaseException:
345-
continue
346-
if issubclass(type(candidate), BaseException):
347-
linked.append(cast(BaseException, candidate))
348-
349-
try:
350-
args = cast(Any, BaseException.args).__get__(current, current_type)
351-
_collect_nested_exceptions(args, linked)
352-
except BaseException:
353-
pass
354-
355-
try:
356-
source_traceback = cast(Any, BaseException.__traceback__).__get__(current, current_type)
357-
except BaseException:
358-
source_traceback = None
359-
if source_traceback is not None:
360-
try:
361-
traceback.clear_frames(source_traceback)
362-
except BaseException:
363-
pass
364-
365-
state = _base_exception_instance_dict(current)
366-
if state is not None:
367-
_collect_nested_exceptions(state, linked)
368-
state.clear()
369-
370-
current_metadata = _static_type_metadata(current_type)
371-
if current_metadata is not None:
372-
_, current_mro = current_metadata
373-
for base in current_mro:
374-
base_metadata = _static_type_metadata(base)
375-
if base_metadata is None:
376-
continue
377-
namespace, _ = base_metadata
378-
for descriptor in namespace.values():
379-
if type(descriptor) is not types.MemberDescriptorType:
380-
continue
381-
try:
382-
value = descriptor.__get__(current, current_type)
383-
_collect_nested_exceptions(value, linked)
384-
except BaseException:
385-
pass
386-
try:
387-
descriptor.__delete__(current)
388-
except BaseException:
389-
pass
390-
391-
if group_exceptions is None:
392-
safe_args: tuple[object, ...] = ()
393-
else:
394-
safe_args = (_DATA_REDACTED_ERROR_MESSAGE, group_exceptions)
395-
for descriptor, value in (
396-
(cast(Any, BaseException.args), safe_args),
397-
(cast(Any, BaseException.__traceback__), None),
398-
(cast(Any, BaseException.__cause__), None),
399-
(cast(Any, BaseException.__context__), None),
400-
):
401-
try:
402-
descriptor.__set__(current, value)
403-
except BaseException:
404-
pass
405-
pending.extend(linked)
299+
cast(Any, BaseException.__traceback__).__set__(error, None)
406300

407301

408302
def _raise_data_redacted_error(error: BaseException) -> NoReturn:
409303
"""Raise a detached redacted error from a frame that owns no payload data."""
410-
raise error from None
304+
try:
305+
raise error from None
306+
finally:
307+
# Python attaches the caller's active exception even with ``from None``.
308+
# Detach that link on our replacement, never on the caller's exception.
309+
cast(Any, BaseException.__context__).__set__(error, None)
411310

412311

413312
@dataclass

‎src/agents/result.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
_await_data_redacted_error_boundary,
2323
_detach_data_redacted_error_traceback,
2424
_is_error_data_redacted,
25+
_raise_data_redacted_error,
2526
_should_drain_stream_events_before_raising,
2627
)
2728
from .guardrail import InputGuardrailResult, OutputGuardrailResult
@@ -1137,6 +1138,7 @@ def register_current_consumer() -> None:
11371138
self = cast(Any, None)
11381139
registered_consumer_task = None
11391140
item = cast(Any, None)
1141+
_raise_data_redacted_error(stored_exception)
11401142
raise stored_exception
11411143

11421144
def _create_error_details(self) -> RunErrorDetails | None:

‎src/agents/run.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -374,7 +374,7 @@ async def run(
374374
session = cast(Any, None)
375375
runner = cast(Any, None)
376376
assert redacted_error is not None
377-
raise redacted_error from None
377+
_raise_data_redacted_error(redacted_error)
378378

379379
@classmethod
380380
def run_sync(
@@ -477,7 +477,7 @@ def run_sync(
477477
session = cast(Any, None)
478478
runner = cast(Any, None)
479479
assert redacted_error is not None
480-
raise redacted_error from None
480+
_raise_data_redacted_error(redacted_error)
481481

482482
@classmethod
483483
def run_streamed(
@@ -618,7 +618,7 @@ async def run(
618618
cast(dict[str, Any], kwargs).clear()
619619
assert redacted_error is not None
620620
_detach_data_redacted_error_traceback(redacted_error)
621-
raise redacted_error from None
621+
_raise_data_redacted_error(redacted_error)
622622

623623
async def _run_impl(
624624
self,
@@ -2424,6 +2424,7 @@ def run_sync(
24242424
_detach_data_redacted_error_traceback(redacted_source)
24252425
redacted_error = redacted_source
24262426

2427+
redacted_source = None
24272428
self = cast(Any, None)
24282429
starting_agent = cast(Any, None)
24292430
input = cast(Any, None)

‎src/agents/run_internal/run_loop.py‎

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@
4141
_clear_data_redacted_error_traceback,
4242
_copy_data_redacted_process_control_error,
4343
_detach_data_redacted_error_traceback,
44+
_detach_source_exception_traceback,
4445
_is_error_data_redacted,
4546
_mark_error_data_redacted,
4647
_mark_error_to_drain_stream_events,
47-
_prepare_data_redacted_error,
4848
)
4949
from ..guardrail import OutputGuardrailResult
5050
from ..handoffs import Handoff
@@ -760,7 +760,7 @@ def _safe_redacted_persistence_error(error: BaseException) -> BaseException:
760760
"""Return a payload-free persistence failure without swallowing control flow."""
761761
if _base_exception_group_exceptions(error) is None:
762762
safe_error = _safe_redacted_persistence_leaf_error(error)
763-
_prepare_data_redacted_error(error)
763+
_detach_source_exception_traceback(error)
764764
return safe_error
765765

766766
group_children: dict[int, tuple[BaseException, ...]] = {}
@@ -787,15 +787,14 @@ def _safe_redacted_persistence_error(error: BaseException) -> BaseException:
787787
pending.append((current, True))
788788
pending.extend((child, False) for child in reversed(children))
789789

790-
# Snapshot the full group topology before clearing any source exception. On Python 3.10,
791-
# the exceptiongroup backport stores children in the instance dictionary, so sanitizing a
792-
# linked leaf can otherwise erase a group that has not been converted yet.
790+
# Snapshot leaf replacements before rebuilding the group topology. Source exceptions
791+
# and the exceptiongroup backport's instance state remain caller-owned.
793792
for current_id, current in leaf_errors.items():
794793
safe_errors[current_id] = _safe_redacted_persistence_leaf_error(current)
795794

796-
# Clear the complete provider-owned graph before constructing replacement groups. Group
797-
# messages are read-only, so the source objects must never cross the public boundary.
798-
_prepare_data_redacted_error(error)
795+
# Detach the source root's retry traceback before constructing replacement groups.
796+
# Its fields and linked exceptions remain intact and never cross the public boundary.
797+
_detach_source_exception_traceback(error)
799798

800799
for group in group_postorder:
801800
children = group_children[id(group)]
@@ -816,11 +815,11 @@ def _safe_redacted_persistence_error(error: BaseException) -> BaseException:
816815
safe_errors[id(group)] = safe_group
817816
return safe_errors[id(error)]
818817
except BaseException as conversion_error:
819-
# Fail closed if traversal or reconstruction itself fails. Preparing the conversion error
820-
# also clears its implicit context, including any source group still referenced there.
821-
_prepare_data_redacted_error(error)
818+
# Fail closed if traversal or reconstruction itself fails. Detach the caught roots'
819+
# tracebacks without clearing caller frames or mutating linked exceptions.
820+
_detach_source_exception_traceback(error)
822821
safe_error = _safe_redacted_persistence_leaf_error(conversion_error)
823-
_prepare_data_redacted_error(conversion_error)
822+
_detach_source_exception_traceback(conversion_error)
824823
return safe_error
825824

826825

‎src/agents/run_state.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
from .exceptions import (
6969
ModelBehaviorError,
7070
UserError,
71+
_detach_source_exception_traceback,
7172
_mark_error_data_redacted,
7273
_prepare_data_redacted_error,
7374
_raise_data_redacted_error,
@@ -1126,7 +1127,7 @@ def get_interruptions(self) -> list[ToolApprovalItem]:
11261127
)
11271128
)
11281129
except Exception as error:
1129-
_prepare_data_redacted_error(error)
1130+
_detach_source_exception_traceback(error)
11301131
copy_error = UserError(
11311132
"Cannot safely copy pending tool approvals. Ensure each interruption uses a "
11321133
"supported tool call or contains only JSON-compatible mapping data."
@@ -2377,7 +2378,7 @@ async def from_string(
23772378
state_json = json.loads(state_string)
23782379
except json.JSONDecodeError as error:
23792380
state_string = "<redacted>"
2380-
_prepare_data_redacted_error(error)
2381+
_detach_source_exception_traceback(error)
23812382
parse_error = UserError("Failed to parse run state JSON")
23822383
except BaseException as error:
23832384
state_string = "<redacted>"

‎src/agents/sandbox/_mount_security.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
from ..exceptions import (
1616
_base_exception_instance_dict,
17-
_discard_exception_graph,
17+
_detach_source_exception_traceback,
1818
_exact_string_state_entry,
1919
_exact_string_state_value,
2020
_is_error_data_redacted,
@@ -487,7 +487,7 @@ class _InvalidRawMountManifestError(ValueError):
487487
def redact_mount_error_data(
488488
function: Callable[_P, Coroutine[Any, Any, _T]],
489489
) -> Callable[_P, Coroutine[Any, Any, _T]]:
490-
"""Replace failures after clearing async frames that handled mount authority."""
490+
"""Replace protected failures without retaining their source exception graph."""
491491

492492
@wraps(function)
493493
async def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
@@ -518,7 +518,7 @@ def _redact_mount_error_data_sync(
518518
*,
519519
preserve_value_error_type: bool,
520520
) -> Callable[_P, _T]:
521-
"""Replace failures after clearing sync frames that handled mount authority."""
521+
"""Replace protected failures without retaining their source exception graph."""
522522

523523
@wraps(function)
524524
def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
@@ -549,7 +549,7 @@ def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _T:
549549

550550

551551
def redact_mount_error_data_sync(function: Callable[_P, _T]) -> Callable[_P, _T]:
552-
"""Replace failures after clearing sync frames that handled mount authority."""
552+
"""Replace protected failures without retaining their source exception graph."""
553553

554554
return _redact_mount_error_data_sync(function, preserve_value_error_type=False)
555555

@@ -660,8 +660,8 @@ def _replace_mount_operation_error(error: BaseException) -> RuntimeError:
660660

661661

662662
def discard_mount_source_exception(error: BaseException) -> None:
663-
"""Clear source frames without consulting provider-defined exception attributes."""
664-
_discard_exception_graph(error)
663+
"""Detach only the source traceback, without clearing frames or linked errors."""
664+
_detach_source_exception_traceback(error)
665665

666666

667667
def _url_contains_inline_authority(value: object) -> bool:

‎tests/extensions/sandbox/test_modal.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5090,6 +5090,7 @@ async def test_modal_direct_persist_redacts_protected_mount_provider_error(
50905090
modal_module, _create_calls, _registry_tags = _load_modal_module(monkeypatch)
50915091
sentinel = "direct-modal-persist-secret"
50925092
source_error = RuntimeError(f"provider echoed {sentinel}")
5093+
source_args = cast(Any, BaseException.args).__get__(source_error, type(source_error))
50935094
state = modal_module.ModalSandboxSessionState(
50945095
manifest=Manifest(
50955096
root="/workspace",
@@ -5117,7 +5118,7 @@ async def fail_persist() -> io.IOBase:
51175118
assert sentinel not in str(exc_info.value)
51185119
assert exc_info.value.__cause__ is None
51195120
assert exc_info.value.__context__ is None
5120-
assert source_error.args == ()
5121+
assert source_error.args == source_args
51215122
assert source_error.__traceback__ is None
51225123

51235124

0 commit comments

Comments
 (0)