@@ -821,6 +821,12 @@ async def save_result_to_session(
821821 "store" : store ,
822822 "has_local_tool_outputs" : has_local_tool_outputs ,
823823 }
824+ model_exchange = getattr (compaction_wrapper , "_session_compaction_model_exchange" , None )
825+ if model_exchange is not None :
826+ resumed_write_state ._pending_session_write ["compaction_model_exchange" ] = {
827+ "item_digests" : list (model_exchange [0 ]),
828+ "reasoning_item_id_policy" : model_exchange [1 ],
829+ }
824830 # resume_pending_session_write() applies post-write compaction itself once the
825831 # checkpoint settles, whether that happens inline below or on a later, separate
826832 # resume -- so it is not repeated after this call returns.
@@ -912,16 +918,18 @@ def digests(items: Sequence[TResponseInputItem]) -> list[str]:
912918
913919 run_state ._session_write_in_progress = True
914920 try :
921+ acknowledged = pending .get ("append_acknowledged" , False )
915922 before = pending ["before" ]
916- if before is None :
923+ committed = False
924+ if before is None and not acknowledged :
917925 # No append has started. Retain the batch even if this first read fails.
918926 tail = await _session_get_items (
919927 session , limit = len (pending ["items" ]) + 1 , wrapper = wrapper
920928 )
921929 pending ["before" ] = digests (tail )
922930 append = True
923931 else :
924- expected = before + digests (pending ["items" ])
932+ expected = ( before or []) + digests (pending ["items" ])
925933 observed_generation : int | None = None
926934 get_with_generation = getattr (session , "_get_items_with_generation" , None )
927935 if wrapper is not None and callable (get_with_generation ):
@@ -934,32 +942,53 @@ def digests(items: Sequence[TResponseInputItem]) -> list[str]:
934942 observed = digests (tail )
935943 committed = observed == expected
936944 unchanged = observed [- len (before ) :] == before if before else not observed
937- if committed == unchanged :
945+ if ( acknowledged and not committed ) or ( not acknowledged and committed == unchanged ) :
938946 raise UserError (
939- "Cannot reconcile the pending Session write: history changed or is ambiguous. "
940- "Repair the original Session before resuming; do not rerun the completed tool."
947+ "Cannot reconcile the pending Session write: history changed or is "
948+ "ambiguous. Repair the original Session before resuming; do not rerun "
949+ "the completed tool."
941950 )
942- append = unchanged
951+ append = not acknowledged and unchanged
943952 # The original append can advance the wrapper generation even when it fails
944953 # atomically. Reconciled unchanged history is also safe to append against;
945954 # subsequent mutations still revoke ownership through the normal generation check.
946- if observed_generation is not None and wrapper is not None :
955+ # An acknowledged append can regain compaction ownership only when its exact
956+ # history remains, as after replacement rollback. Never re-append that batch.
957+ if (
958+ observed_generation is not None
959+ and wrapper is not None
960+ and (not acknowledged or committed )
961+ ):
947962 wrapper ._session_compaction_generation = observed_generation # type: ignore[attr-defined]
948963 if append :
949- # Backends may retain or transform their input; the durable checkpoint stays detached .
964+ # Keep the checkpoint detached from backend input retention or transformation .
950965 await _session_add_items (session , copy .deepcopy (pending ["items" ]), wrapper = wrapper )
966+ # Restore evidence from the successful exchange, never from all stored history.
967+ # A changed history after replacement must not regain compaction ownership.
968+ model_exchange = pending .get ("compaction_model_exchange" )
969+ if wrapper is not None and model_exchange is not None and (not acknowledged or committed ):
970+ wrapper ._session_compaction_model_exchange = ( # type: ignore[attr-defined]
971+ tuple (model_exchange ["item_digests" ]),
972+ model_exchange ["reasoning_item_id_policy" ],
973+ )
974+ pending ["append_acknowledged" ] = True
951975 run_state ._current_turn_persisted_item_count = pending ["persisted_count" ]
952- # Keep the checkpoint until compaction also settles: if _apply_post_write_compaction
953- # raises below, a later retry must still be able to redo just the compaction step
954- # instead of silently losing it. The append itself is retry-safe (the reconciliation
955- # above detects an already-committed batch and skips re-appending it).
956- await _apply_post_write_compaction (
957- session ,
958- response_id = pending .get ("response_id" ),
959- store = pending .get ("store" ),
960- has_local_tool_outputs = pending .get ("has_local_tool_outputs" , False ),
961- wrapper = wrapper ,
962- )
976+ # A confirmed atomic replacement settles this write even when the caller is
977+ # cancelled before receiving its acknowledgement. All other failed replacements
978+ # retain the checkpoint and must reconcile against the original appended history.
979+ if wrapper is not None :
980+ wrapper ._session_compaction_completed = False # type: ignore[attr-defined]
981+ try :
982+ await _apply_post_write_compaction (
983+ session ,
984+ response_id = pending .get ("response_id" ),
985+ store = pending .get ("store" ),
986+ has_local_tool_outputs = pending .get ("has_local_tool_outputs" , False ),
987+ wrapper = wrapper ,
988+ )
989+ finally :
990+ if wrapper is not None and getattr (wrapper , "_session_compaction_completed" , False ):
991+ run_state ._pending_session_write = None
963992 run_state ._pending_session_write = None
964993 finally :
965994 run_state ._session_write_in_progress = False
0 commit comments