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
15 changes: 14 additions & 1 deletion src/agents/memory/openai_responses_compaction_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
OpenAIResponsesCompactionArgs,
OpenAIResponsesCompactionAwareSession,
SessionABC,
_await_mutation,
_CompactionSnapshot,
)

Expand Down Expand Up @@ -455,8 +456,20 @@ async def _run_compaction_locked(
)

if snapshot is not None:
try:

async def replace_snapshot(snapshot: _CompactionSnapshot) -> bool:
replaced = await snapshot.replace_suffix(suffix_start, output_items)
if replaced:
# Publish the backend's successful outcome before caller cancellation
# is propagated. Runner can settle its checkpoint without inferring
# success from history that merely differs from the original append.
self._deferred_response_id = None
if wrapper is not None:
wrapper._session_compaction_completed = True # type: ignore[attr-defined]
return replaced

try:
replaced = await _await_mutation(replace_snapshot(snapshot))
if not replaced:
logger.warning(
"Skipped compaction replacement because the stored suffix changed."
Expand Down
67 changes: 48 additions & 19 deletions src/agents/run_internal/session_persistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,12 @@ async def save_result_to_session(
"store": store,
"has_local_tool_outputs": has_local_tool_outputs,
}
model_exchange = getattr(compaction_wrapper, "_session_compaction_model_exchange", None)
if model_exchange is not None:
resumed_write_state._pending_session_write["compaction_model_exchange"] = {
"item_digests": list(model_exchange[0]),
"reasoning_item_id_policy": model_exchange[1],
}
# resume_pending_session_write() applies post-write compaction itself once the
# checkpoint settles, whether that happens inline below or on a later, separate
# resume -- so it is not repeated after this call returns.
Expand Down Expand Up @@ -912,16 +918,18 @@ def digests(items: Sequence[TResponseInputItem]) -> list[str]:

run_state._session_write_in_progress = True
try:
acknowledged = pending.get("append_acknowledged", False)
before = pending["before"]
if before is None:
committed = False
if before is None and not acknowledged:
# No append has started. Retain the batch even if this first read fails.
tail = await _session_get_items(
session, limit=len(pending["items"]) + 1, wrapper=wrapper
)
pending["before"] = digests(tail)
append = True
else:
expected = before + digests(pending["items"])
expected = (before or []) + digests(pending["items"])
observed_generation: int | None = None
get_with_generation = getattr(session, "_get_items_with_generation", None)
if wrapper is not None and callable(get_with_generation):
Expand All @@ -934,32 +942,53 @@ def digests(items: Sequence[TResponseInputItem]) -> list[str]:
observed = digests(tail)
committed = observed == expected
unchanged = observed[-len(before) :] == before if before else not observed
if committed == unchanged:
if (acknowledged and not committed) or (not acknowledged and committed == unchanged):
raise UserError(
"Cannot reconcile the pending Session write: history changed or is ambiguous. "
"Repair the original Session before resuming; do not rerun the completed tool."
"Cannot reconcile the pending Session write: history changed or is "
"ambiguous. Repair the original Session before resuming; do not rerun "
"the completed tool."
)
append = unchanged
append = not acknowledged and unchanged
# The original append can advance the wrapper generation even when it fails
# atomically. Reconciled unchanged history is also safe to append against;
# subsequent mutations still revoke ownership through the normal generation check.
if observed_generation is not None and wrapper is not None:
# An acknowledged append can regain compaction ownership only when its exact
# history remains, as after replacement rollback. Never re-append that batch.
if (
observed_generation is not None
and wrapper is not None
and (not acknowledged or committed)
):
wrapper._session_compaction_generation = observed_generation # type: ignore[attr-defined]
Comment thread
jbeckwith-oai marked this conversation as resolved.
Resolved
if append:
# Backends may retain or transform their input; the durable checkpoint stays detached.
# Keep the checkpoint detached from backend input retention or transformation.
await _session_add_items(session, copy.deepcopy(pending["items"]), wrapper=wrapper)
# Restore evidence from the successful exchange, never from all stored history.
# A changed history after replacement must not regain compaction ownership.
model_exchange = pending.get("compaction_model_exchange")
if wrapper is not None and model_exchange is not None and (not acknowledged or committed):
wrapper._session_compaction_model_exchange = ( # type: ignore[attr-defined]
tuple(model_exchange["item_digests"]),
model_exchange["reasoning_item_id_policy"],
)
pending["append_acknowledged"] = True
run_state._current_turn_persisted_item_count = pending["persisted_count"]
# Keep the checkpoint until compaction also settles: if _apply_post_write_compaction
# raises below, a later retry must still be able to redo just the compaction step
# instead of silently losing it. The append itself is retry-safe (the reconciliation
# above detects an already-committed batch and skips re-appending it).
await _apply_post_write_compaction(
session,
response_id=pending.get("response_id"),
store=pending.get("store"),
has_local_tool_outputs=pending.get("has_local_tool_outputs", False),
wrapper=wrapper,
)
# A confirmed atomic replacement settles this write even when the caller is
# cancelled before receiving its acknowledgement. All other failed replacements
# retain the checkpoint and must reconcile against the original appended history.
if wrapper is not None:
wrapper._session_compaction_completed = False # type: ignore[attr-defined]
try:
await _apply_post_write_compaction(
session,
response_id=pending.get("response_id"),
store=pending.get("store"),
has_local_tool_outputs=pending.get("has_local_tool_outputs", False),
wrapper=wrapper,
)
finally:
if wrapper is not None and getattr(wrapper, "_session_compaction_completed", False):
run_state._pending_session_write = None
run_state._pending_session_write = None
finally:
run_state._session_write_in_progress = False
Expand Down
46 changes: 44 additions & 2 deletions src/agents/run_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,13 +168,23 @@
]


class _SessionCompactionModelExchange(TypedDict):
"""Digests of one successful model exchange and its resolved replay policy."""

item_digests: list[str]
reasoning_item_id_policy: Literal["preserve", "omit"] | None


class _PendingSessionWrite(TypedDict):
"""One canonical resumed-output append awaiting acknowledgement."""

session_id: str
items: list[TResponseInputItem]
before: list[str] | None
persisted_count: int
# Once acknowledged, only compaction remains; its replacement can change the history.
append_acknowledged: NotRequired[bool]
compaction_model_exchange: NotRequired[_SessionCompactionModelExchange]
# Compaction inputs for the batch this checkpoint is settling, so a later, separate
# resume_pending_session_write() call (not the original save_result_to_session() call)
# can still apply the same post-write Responses compaction decision. Optional so a
Expand Down Expand Up @@ -242,7 +252,8 @@ def _default_run_state_validation_error(
"Binds restored local MCP calls to their configured server and original tool name, "
"preserves independent apply_patch approval scopes, and binds function-tool approval "
"decisions to their owning agent, and retains compaction metadata for pending "
"Session writes."
"Session writes, including acknowledgement and model-exchange evidence for "
"compaction retry."
),
}
SUPPORTED_SCHEMA_VERSIONS = frozenset(SCHEMA_VERSION_SUMMARIES)
Expand Down Expand Up @@ -4512,10 +4523,21 @@ async def _build_run_state_from_json(
# Released schema 1.17 wrote exactly four keys. Compaction metadata belongs to 1.18;
# older checkpoints remain readable without claiming the newer recovery behavior.
optional_pending_write_keys = (
{"response_id", "store", "has_local_tool_outputs"}
{
"response_id",
"store",
"has_local_tool_outputs",
"append_acknowledged",
"compaction_model_exchange",
}
if (schema_major, schema_minor) >= (1, 18)
else set()
)
compaction_exchange = (
pending_write.get("compaction_model_exchange")
if isinstance(pending_write, dict)
else None
)
if (
(schema_major, schema_minor) < (1, 17)
or not isinstance(state._current_step, NextStepRunAgain | NextStepInterruption)
Expand Down Expand Up @@ -4545,6 +4567,26 @@ async def _build_run_state_from_json(
and pending_write["store"] is not None
and not isinstance(pending_write["store"], bool)
)
or (
"append_acknowledged" in pending_write
and not isinstance(pending_write["append_acknowledged"], bool)
)
Comment thread
jbeckwith-oai marked this conversation as resolved.
Resolved
or (
pending_write.get("append_acknowledged") is True and pending_write["before"] is None
)
or (
"compaction_model_exchange" in pending_write
and (
not isinstance(compaction_exchange, dict)
or set(compaction_exchange) != {"item_digests", "reasoning_item_id_policy"}
or not isinstance(compaction_exchange["item_digests"], list)
or not all(
isinstance(digest, str) for digest in compaction_exchange["item_digests"]
)
or compaction_exchange["reasoning_item_id_policy"]
not in (None, "preserve", "omit")
)
)
or (
"has_local_tool_outputs" in pending_write
and not isinstance(pending_write["has_local_tool_outputs"], bool)
Expand Down
Loading
Loading