diff --git a/docs/architecture/task-lifecycle-model.md b/docs/architecture/task-lifecycle-model.md index a6fc40494da..37d7cf0735d 100644 --- a/docs/architecture/task-lifecycle-model.md +++ b/docs/architecture/task-lifecycle-model.md @@ -166,9 +166,11 @@ The production-backed lifecycle checker already models the current serial owners - delegated parent reopen success or failure after durable child history; and - emitting completion. +The model cancel event also represents a failed stream that cancels only its current persistence generation. The task can recover with a new turn. + The model abstracts restart visibility as the `durable` history phase. It allows an already-started write to finish after cancellation because the filesystem operation itself is not cancellable, but it forbids starting a retry write or emitting completion after cancellation. The retry bound is two write starts (the initial attempt plus one retry), which is sufficient to cover the ordering and cancellation state classes without mirroring the production retry count. -Seven semantic landmarks keep the intended positive and negative paths reachable: delayed completion remains pending, failed completion remains pending, exhausted retries settle without completion, cancellation can win after retry delay but before persistence, delegated reopen failure emits no delegated completion, and both standalone and delegated tasks can complete after durable history. The checker explores all reachable states through depth 10 and fails rather than reporting a truncated pass if an unseen successor remains. +Eight semantic landmarks keep the intended positive and negative paths reachable: a failed delegated turn cancels its persistence wait without completing or reopening its parent, delayed completion remains pending, failed completion remains pending, exhausted retries settle without completion, cancellation can win after retry delay but before persistence, delegated reopen failure emits no delegated completion, and both standalone and delegated tasks can complete after durable history. The checker explores all reachable states through depth 10 and fails rather than reporting a truncated pass if an unseen successor remains. ## Invariants diff --git a/docs/architecture/tla/StreamReadCancellation.Dropped.cfg b/docs/architecture/tla/StreamReadCancellation.Dropped.cfg new file mode 100644 index 00000000000..ccd5984f801 --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellation.Dropped.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + DropReason <- DroppedReason +INVARIANTS TypeOK AbortReasonPreserved diff --git a/docs/architecture/tla/StreamReadCancellation.Leak.cfg b/docs/architecture/tla/StreamReadCancellation.Leak.cfg new file mode 100644 index 00000000000..2727b5ead82 --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellation.Leak.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CleanOnSettle <- LeakySettle +INVARIANTS TypeOK NoSettledReadListener diff --git a/docs/architecture/tla/StreamReadCancellation.Reason.cfg b/docs/architecture/tla/StreamReadCancellation.Reason.cfg new file mode 100644 index 00000000000..bcf4ecf4aed --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellation.Reason.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveReason <- GenericReason +INVARIANTS TypeOK AbortReasonPreserved diff --git a/docs/architecture/tla/StreamReadCancellation.cfg b/docs/architecture/tla/StreamReadCancellation.cfg new file mode 100644 index 00000000000..1a52a408646 --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellation.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK NoSettledReadListener AbortReasonPreserved diff --git a/docs/architecture/tla/StreamReadCancellation.tla b/docs/architecture/tla/StreamReadCancellation.tla new file mode 100644 index 00000000000..f5b38326cb2 --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellation.tla @@ -0,0 +1,52 @@ +---- MODULE StreamReadCancellation ---- +\* Source: Task.nextChunkWithAbort awaits iterator.next. Sink: read settlement and the request error handler. +\* Failure: completed or failed reads leave abort listeners attached. Invariant: NoSettledReadListener. +\* Failure: cancellation replaces the request's abort reason. Invariant: AbortReasonPreserved. +\* Expect the old listener race to fail after one settled read and to replace user and deadline reasons. +\* Replay success, failure, pre-aborted reads, and cancellation during a pending read through Task's real request lease. +\* The shared raceAbort helper removes its listener on either settlement path and propagates the signal reason. +\* Reference: https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal#removing_the_abort_event_listener +\* Result: the old model fails after Read and Settle (5 states). All four Task regression cases fail before reuse. +\* Fixed holds (15 states). Leak and Reason fail separately. Four Task cases and 326 focused tests pass after reuse. +\* Task now reuses detachOnAbort. One drain catch owns consumption errors; detached reporting stays independent. +\* Existing ThoughtSignaturePersistence and ThoughtSignatureRecovery gates retain all positive and negative results. +\* Null result: no extra failure in the fixed bounded model. An abort race does not stop an uncooperative iterator. +\* Review counts remain 2 covered, 14 added, 0 gap. This refactor follows the user's simplification request. +\* listeners counts only the Task read's listeners. Transport listeners are outside this model. +\* Validation: all 14 full-test tasks pass, including 15,551 extension tests. Lifecycle, types, lint, formatting, and Knip pass. +\* Suppression counts stay equal. Cost: about 6 agent minutes. The two simplifications remove 24 runtime lines. +\* Review: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4674161290 +\* Expect dropped delivery to pass the old invariant. Track the delivery obligation independently of the delivered value. +\* Result: Dropped passes the old invariant (11 states), which confirms the missing delivery obligation. +\* deliveryRequired now records pending-read cancellation and reads made after abort, independently of delivered. +\* Fixed holds (15 states). Dropped, Reason and Leak fail separately. Abort with no read stays valid. +\* This spec adds the cancellation finding. ThoughtSignatureRecovery records the review round totals. +\* Validation: all 14 full-test tasks pass, including 15,554 extension tests. Types, lint, formatting, and both Knip checks pass. +\* Lifecycle checks and all three relevant TLA+ gates pass. Suppression counts stay equal. Cost: about 15 agent minutes. +EXTENDS Naturals +VARIABLES reads, pending, listeners, reason, delivered, deliveryRequired +vars == <> +CleanOnSettle == TRUE +PreserveReason == TRUE +DropReason == FALSE +Init == /\ reads = 0 /\ pending = FALSE /\ listeners = 0 /\ reason = "none" /\ delivered = "none" /\ deliveryRequired = FALSE +Read == /\ reads < 2 /\ ~pending /\ reads' = reads + 1 + /\ pending' = (reason = "none") /\ deliveryRequired' = (reason # "none") + /\ listeners' = IF reason = "none" THEN listeners + 1 ELSE listeners + /\ delivered' = IF reason = "none" THEN "none" ELSE IF DropReason THEN "none" ELSE IF PreserveReason THEN reason ELSE "generic" + /\ UNCHANGED reason +Settle == /\ pending /\ pending' = FALSE + /\ listeners' = IF CleanOnSettle THEN listeners - 1 ELSE listeners + /\ UNCHANGED <> +Abort(value) == /\ deliveryRequired' = (deliveryRequired \/ pending) /\ reason = "none" /\ reason' = value /\ pending' = FALSE /\ listeners' = 0 + /\ delivered' = IF pending THEN IF DropReason THEN "none" ELSE IF PreserveReason THEN value ELSE "generic" ELSE delivered + /\ UNCHANGED reads +Next == Read \/ Settle \/ (\E value \in {"user", "deadline"} : Abort(value)) +Spec == Init /\ [][Next]_vars +TypeOK == /\ reads \in 0..2 /\ pending \in BOOLEAN /\ listeners \in 0..2 + /\ deliveryRequired \in BOOLEAN + /\ reason \in {"none", "user", "deadline"} /\ delivered \in {"none", "user", "deadline", "generic"} +NoSettledReadListener == ~pending => listeners = 0 +AbortReasonPreserved == /\ (deliveryRequired => delivered = reason /\ delivered # "none") + /\ (delivered # "none" => delivered = reason) +==== diff --git a/docs/architecture/tla/StreamReadCancellationMC.tla b/docs/architecture/tla/StreamReadCancellationMC.tla new file mode 100644 index 00000000000..a7c989a353b --- /dev/null +++ b/docs/architecture/tla/StreamReadCancellationMC.tla @@ -0,0 +1,6 @@ +---- MODULE StreamReadCancellationMC ---- +EXTENDS StreamReadCancellation +LeakySettle == FALSE +GenericReason == FALSE +DroppedReason == TRUE +==== diff --git a/docs/architecture/tla/ThoughtSignature.EchoReasoning.cfg b/docs/architecture/tla/ThoughtSignature.EchoReasoning.cfg new file mode 100644 index 00000000000..6b334c86533 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.EchoReasoning.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + EchoSignedReasoning <- EchoUnsigned +CONSTRAINT Bounded +INVARIANTS NoUnsignedThought TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.EncodedFirst.cfg b/docs/architecture/tla/ThoughtSignature.EncodedFirst.cfg new file mode 100644 index 00000000000..de2ffa2f2e7 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.EncodedFirst.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + PreferExplicit <- EncodedFirst +CONSTRAINT Bounded +INVARIANTS SignatureSourcePriority NoUnsignedThought TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.ForeignEncoded.cfg b/docs/architecture/tla/ThoughtSignature.ForeignEncoded.cfg new file mode 100644 index 00000000000..ac175a16f9b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.ForeignEncoded.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + KeepForeignEncodedIds <- KeepEncodedIds +CONSTRAINT Bounded +INVARIANTS NoForeignEncodedSignature diff --git a/docs/architecture/tla/ThoughtSignature.FrozenCursor.cfg b/docs/architecture/tla/ThoughtSignature.FrozenCursor.cfg new file mode 100644 index 00000000000..7c9b26d825c --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.FrozenCursor.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + AdvanceReplayCursor <- FrozenCursor +CONSTRAINT Bounded +INVARIANTS OccurrenceReplayAfterTurn diff --git a/docs/architecture/tla/ThoughtSignature.IdOnly.cfg b/docs/architecture/tla/ThoughtSignature.IdOnly.cfg new file mode 100644 index 00000000000..0316810467a --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.IdOnly.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + CaptureFromId <- IgnoreId +CONSTRAINT Bounded +INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.NextResult.cfg b/docs/architecture/tla/ThoughtSignature.NextResult.cfg new file mode 100644 index 00000000000..262651f1289 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.NextResult.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + ResultAtNext <- NextResult +CONSTRAINT Bounded +INVARIANTS OccurrenceReplayAfterTurn diff --git a/docs/architecture/tla/ThoughtSignature.NoMarker.cfg b/docs/architecture/tla/ThoughtSignature.NoMarker.cfg deleted file mode 100644 index f831695f73f..00000000000 --- a/docs/architecture/tla/ThoughtSignature.NoMarker.cfg +++ /dev/null @@ -1,7 +0,0 @@ -SPECIFICATION Spec -CHECK_DEADLOCK FALSE -CONSTANTS - MaxTurns = 2 - MarkerFallback <- NoMarkerFallback -CONSTRAINT Bounded -INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode diff --git a/docs/architecture/tla/ThoughtSignature.ReusedId.cfg b/docs/architecture/tla/ThoughtSignature.ReusedId.cfg new file mode 100644 index 00000000000..1be2078a397 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.ReusedId.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + ReplayByOccurrence <- IdOnlyReplay +CONSTRAINT Bounded +INVARIANTS OccurrenceReplayAfterTurn diff --git a/docs/architecture/tla/ThoughtSignature.StreamFirstWins.cfg b/docs/architecture/tla/ThoughtSignature.StreamFirstWins.cfg new file mode 100644 index 00000000000..b3353174392 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.StreamFirstWins.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + CaptureStream <- KeepFirstCaptured +CONSTRAINT Bounded +INVARIANTS StreamPriorityAfterTurn diff --git a/docs/architecture/tla/ThoughtSignature.UnpairedIds.cfg b/docs/architecture/tla/ThoughtSignature.UnpairedIds.cfg new file mode 100644 index 00000000000..605a41bef69 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.UnpairedIds.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + RewriteToolResultIds <- KeepResultIds +CONSTRAINT Bounded +INVARIANTS ToolResultIdsMatch diff --git a/docs/architecture/tla/ThoughtSignature.UnsignedResult.cfg b/docs/architecture/tla/ThoughtSignature.UnsignedResult.cfg new file mode 100644 index 00000000000..defee7de868 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignature.UnsignedResult.cfg @@ -0,0 +1,7 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + MaxTurns = 2 + RetainUnsignedResult <- KeepSignedResult +CONSTRAINT Bounded +INVARIANTS OccurrenceReplayAfterTurn diff --git a/docs/architecture/tla/ThoughtSignature.cfg b/docs/architecture/tla/ThoughtSignature.cfg index 3d0f1ce2935..0975e5d2fbf 100644 --- a/docs/architecture/tla/ThoughtSignature.cfg +++ b/docs/architecture/tla/ThoughtSignature.cfg @@ -3,4 +3,4 @@ CHECK_DEADLOCK FALSE CONSTANTS MaxTurns = 2 CONSTRAINT Bounded -INVARIANTS TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered +INVARIANTS OccurrenceReplayAfterTurn ToolResultIdsMatch NoForeignEncodedSignature StreamPriorityAfterTurn SignatureSourcePriority NoUnsignedThought TypeOK NoRejectedCall NoCorruptIdDecode SignatureDelivered diff --git a/docs/architecture/tla/ThoughtSignature.tla b/docs/architecture/tla/ThoughtSignature.tla index 2c82171d0a8..de14b9e390c 100644 --- a/docs/architecture/tla/ThoughtSignature.tla +++ b/docs/architecture/tla/ThoughtSignature.tla @@ -35,7 +35,7 @@ \* | ThoughtSignature.ModelOnly.cfg | origin ignores litellmBaseUrl | fails after 1 turn | \* | ThoughtSignature.NoOrigin.cfg | no origin check | fails after 1 turn | \* | ThoughtSignature.AllCalls.cfg | signature on every parallel call | fails after 1 turn | -\* | ThoughtSignature.NoMarker.cfg | bypass on the model name only | fails after 1 turn | +\* | ThoughtSignature.NoMarker.cfg | bypass on the model name only | retired: IDs stripped | \* | ThoughtSignature.NoReset.cfg | lastThoughtSignature kept across requests | fails after 2 turns | \* | ThoughtSignature.NativeLeak.cfg | native Gemini reads a LiteLLM signature | fails after 1 turn | \* | ThoughtSignature.DropStored.cfg | stored signature never sent (bypass only) | fails after 1 turn | @@ -55,7 +55,93 @@ \* Review: 2 covered, 1 added, 5 gap, 2 on the spec files (PR 2119). See the list below Rejected. \* The first version came after the code and the reviews. It is not an independent first pass. -EXTENDS Naturals, Sequences +\* Issue 2304 first pass: expect an ID-only response to lose its signature. +\* SignatureDelivered must cover minted signatures absent from provider fields. +\* Replay: readThoughtSignature and OpenAiHandler.createMessage. Sink: applyThoughtSignatures. +\* Expected: IdOnly fails SignatureDelivered. Replay: three ID-only reader cases fail on the old code. +\* Result: fixed passes (507 states). All 14 variants fail. IdOnly fails with 24 states. +\* Live replay: Gemini 3.8 Flash accepts the preserved signature (200) and rejects corrupt bytes (400). +\* Live replay also accepts the bypass (200). The issue claim that Vertex always rejects it did not hold. +\* Live scope: the native Vertex endpoint received a 420-character signature from gemini-3.8-flash. +\* Replay mapped the converted provider field back to a Vertex function-call part. No LiteLLM gateway was tested. +\* Handler tests check the OpenAI and LiteLLM request contracts. gemini-2.5-flash returned 404 on this endpoint. +\* Saved signatures already corrupted by ID sanitization cannot be recovered. Preserve original bytes before storage. +\* Keep OpenAI Responses ID limits and unsigned provider reasoning. Do not replace valid signatures with a bypass. +\* Google contract: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/thinking/thought-signatures +\* Cache tuning is separate. Normal turns append environment details. Resume can refresh the latest user message. +\* Keep global time and cost defaults. This change does not assess cache performance. +\* Validation before refactor: 590 tests in five suites passed, including history storage and ID validation. +\* Validation after refactor: 552 tests in three provider suites passed. Types and lint passed. Suppression counts stayed equal. +\* Property: thought-signature.spec.ts, proxy signature round trip property (40 source/sink cases). +\* Cost: about 8 agent minutes through live replay. Each TLC config takes under 2 seconds. +\* Code sabotage: retaining reasoning_content fails all 40 property cases. The guard was then restored. +\* Null result: the fixed model found no further failure within this domain. +\* Scope: the proxy backends share the signature contract. Existing bypass rules model LiteLLM only. +\* Scope: ID bytes and fragmented ID streams remain outside the model. The property checks complete IDs. +\* Review: 0 covered, 0 added, 0 gap. No external review was read for this change. + +\* Reader simplification: expect no new failure. A later explicit field must beat an earlier encoded ID. +\* Invariant: SignatureSourcePriority. Sabotage: prefer the encoded candidate over an explicit field. +\* Source: readThoughtSignature receives tool_calls. Sink: its returned signature enters history. +\* Refactor result: fixed holds (507 states). All 15 variants fail, including EncodedFirst. +\* Replay: encoded-first code sabotage fails the later-explicit-field test. The fixed reader passes. +\* Null result: the reader refactor found no new behavior failure. No speed gain was measured. +\* Refactor cost: about 3 agent minutes. Each TLC config takes under 2 seconds. + +\* Main rebase expectation: retain request signature reset before Responses API dispatch. +\* Failure: a new request exposes a signature from the prior request. NoReset covers this failure. +\* Keep getReasoningDetails and both thought-signature accessors after the merge. +\* Model limit: Responses API dispatch is outside this model. Handler tests check that path. +\* Rebase result: fixed holds (507 states). All 15 sabotage variants fail as expected. +\* Property and handler checks: 863 tests pass in three suites. Types and lint pass. Suppression counts stay equal. +\* Null result: the existing model found no new failure. No external review was read. +\* Rebase cost: about 3 agent minutes. TLC needs a local socket outside the sandbox. + +\* PR 2643 review ratchet: 1 covered, 0 added, 0 gap. Origin isolation was already modeled. +\* Thread: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4655457066 +\* Finding: the handler replay test accepted a constant origin. Expect mismatch tests to reject it. +\* Replay: four handler cases vary only endpoint or model, with streaming on and off. +\* Code sabotage: a constant origin fails all four cases. Restoring origin derivation passes. +\* Result: fixed holds (507 states), all 15 variants fail as expected, and 254 focused tests pass. +\* Types and lint pass; suppression counts are unchanged. No new model failure. Cost: about 3 agent minutes. + +\* Final rebase result: both header records remain. Model logic is unchanged. +\* Fixed holds (507 states); all 15 variants fail. All 867 tests, types and lint pass. +\* Suppression counts stay equal. No new model failure. Cost: about 1 agent minute. + +\* PR 2643 review ratchet: add streamed source priority. The prior invariant covered one batch only. +\* Thread: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660532072 +\* Failure: the first ID fallback prevents a later explicit field from entering history. +\* Expect StreamFirstWins to fail. Replay both handlers with encoded then explicit chunks. +\* Extend this subsystem through ThoughtSignatureStream to keep the source rules separate. +\* Result: the old rule fails the invariant. Both handler replays keep encoded-0 instead of explicit-1. +\* Fixed holds (507 states). All 16 variants fail, including StreamFirstWins after one turn. +\* Property: ThoughtSignatureReader stream priority property checks 125 streams and each prefix. +\* Code sabotage: keep the first value. The property fails 18 cases. Restore the reader and all 1,000 tests pass. +\* Types, lint and both Knip checks pass. Suppression counts stay equal. +\* Review totals for PR 2643: 1 covered, 1 added, 0 gap. Null result: no further failure in this input domain. +\* Cost: about 5 agent minutes. The model does not check fragmented signature bytes or gateway behavior. + +\* PR 2643 review ratchet: encoded-ID isolation and request ownership need new invariants. +\* Threads: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660769100 +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660769109 +\* Failure: a foreign backend receives signature bytes in an ID. Invariant: NoForeignEncodedSignature. +\* Failure: an old drain changes the current request's signature. Invariant: RequestSignatureOwned. +\* Expect KeepForeignEncodedIds and SharedLast to fail. Replay endpoint changes and two overlapping streams. +\* Request ownership is checked in ThoughtSignatureRequests. It reuses the stream source rules. +\* NoMarker now passes: stripped foreign IDs cannot trigger corrupt-ID decoding. Retire that obsolete variant. +\* This does not prove every unlisted alias accepts unsigned calls. The existing Unlisted limit remains. +\* Result: both old models fail. Handler replays reproduce 11 stale-drain failures and 4 foreign-ID failures. +\* Fixed models hold: 507 history states and 51 request states. All active sabotage variants fail as expected. +\* Properties: 48 origin-isolation cases and 16 handler ownership cases. History signatures are checked through preparation. +\* Encoded-ID code sabotage fails 24 property cases. The restored code passes all 1,074 tests in four suites. +\* Types, lint, formatting and both Knip checks pass. Suppression counts stay equal. +\* Review totals for PR 2643: 1 covered, 3 added, 0 gap. No further failure in the checked domains. +\* Cost: about 8 agent minutes. Hash collisions and history saves after a newer request starts are outside the models. + +\* Latest review ratchet and checks: ThoughtSignatureOccurrences and ThoughtSignaturePersistence. + +EXTENDS Naturals, Sequences, ThoughtSignatureStream, ThoughtSignatureOccurrences VARIABLE history \* One assistant message per turn. Each message has the fields of Message. @@ -92,7 +178,7 @@ Real(s) == s.by \in Backends \* getThoughtSignatureOrigin of the handler that streamed the message. Native Gemini stores none. StoredOrigin(m) == IF LiteLlm(m.by) /\ Real(m.sig) THEN Origin(m.by) ELSE "none" Sigs == {None, Bypass} \cup [by : Backends, step : Nat \ {0}] -Message == [by : Backends, n : 1..2, marker : BOOLEAN, sig : Sigs] +Message == [by : Backends, n : 1..2, marker : BOOLEAN, minted : BOOLEAN, sig : Sigs] TypeOK == history \in Seq(Message) @@ -103,13 +189,17 @@ Captured(t, k, minted) == IF minted THEN [by |-> t, step |-> k] ELSE None \* A turn on backend t returns n tool calls. A Gemini backend can sign the first call. \* LiteLLM then also writes the signature into the id of that call, after __thought__. -Turn(t, n, minted) == +CaptureFromId == TRUE + +Turn(t, n, minted, idOnly) == LET k == Len(history) + 1 IN /\ minted => RunsGemini(t) /\ history' = Append(history, [by |-> t, n |-> n, marker |-> minted /\ LiteLlm(t), - sig |-> Captured(t, k, minted)]) + minted |-> minted, + sig |-> IF idOnly /\ LiteLlm(t) /\ ~CaptureFromId THEN None + ELSE Captured(t, k, minted)]) -Next == \E t \in Backends, n \in 1..2, minted \in BOOLEAN : Turn(t, n, minted) +Next == \E t \in Backends, n \in 1..2, minted \in BOOLEAN, idOnly \in BOOLEAN : Turn(t, n, minted, idOnly) Spec == Init /\ [][Next]_history \* applyThoughtSignatures sends a stored signature only to the backend that minted it. @@ -130,9 +220,24 @@ Sent(t, listed, k, i) == ELSE None ELSE IF Real(m.sig) /\ NativeUses(m) THEN m.sig ELSE Bypass +\* applyThoughtSignatures must remove foreign signature bytes from IDs as well as explicit fields. +KeepForeignEncodedIds == FALSE +EncodedIdSent(t, k) == + LiteLlm(t) /\ history[k].marker /\ (OriginMatches(history[k], t) \/ KeepForeignEncodedIds) +NoForeignEncodedSignature == + \A t \in Backends, k \in 1..Len(history) : + ~OriginMatches(history[k], t) => ~EncodedIdSent(t, k) + +\* Both sides of a tool exchange use the same ID mapping. ID normalization stays an oracle. +RewriteToolResultIds == TRUE +ToolResultIdsMatch == + \A t \in Backends, k \in 1..Len(history) : + LiteLlm(t) => (EncodedIdSent(t, k) = + (IF RewriteToolResultIds THEN EncodedIdSent(t, k) ELSE history[k].marker)) + \* LiteLLM decodes the sanitized __thought__ id of a call that has no field. DecodesCorruptId(t, listed, k, i) == - RunsGemini(t) /\ LiteLlm(t) /\ Sent(t, listed, k, i) = None /\ history[k].marker /\ i = 1 + RunsGemini(t) /\ LiteLlm(t) /\ Sent(t, listed, k, i) = None /\ EncodedIdSent(t, k) /\ i = 1 \* The sink oracle. A backend that does not run Gemini rejects every call with the field. Rejected(t, listed, k, i) == @@ -153,6 +258,24 @@ Rejected(t, listed, k, i) == \* Round 3 comes from a web search for best practice (BerriAI/litellm#19739, vercel/ai#15550). \* Round 4 comes from the simplify pass. A property must constrain the result, not only reject a crash. +\* applyThoughtSignatures omits unsigned reasoning text when it attaches a signature. +EchoSignedReasoning == FALSE +ReasoningSent(t, listed, k) == EchoSignedReasoning /\ Sent(t, listed, k, 1) # None +NoUnsignedThought == + \A t \in Backends, listed \in Listed, k \in 1..Len(history) : ~ReasoningSent(t, listed, k) + +\* Candidate values are oracles for fields and ID suffixes, including no signature. +PreferExplicit == TRUE +SelectedSignature(field, encoded) == + IF field # None /\ PreferExplicit THEN field ELSE IF encoded # None THEN encoded ELSE field +SignatureSourcePriority == Len(history) > 0 => + \A field, encoded \in {None, [by |-> "g1", step |-> 1], [by |-> "g2", step |-> 1]} : + SelectedSignature(field, encoded) = (IF field # None THEN field ELSE encoded) + +OccurrenceReplayAfterTurn == Len(history) > 0 => OccurrenceSignaturesPreserved /\ ResultUsesLatestOccurrence /\ NoResultBeforeConsumption + +StreamPriorityAfterTurn == Len(history) > 0 => StreamSignaturePriority + \* Safety: no backend rejects a tool call in the history. NoRejectedCall == \A t \in Backends, listed \in Listed, k \in 1..Len(history) : @@ -166,6 +289,7 @@ NoCorruptIdDecode == \* Safety: a LiteLLM backend gets back the signature it minted, on the first call of that message. SignatureDelivered == \A t \in Backends, listed \in BOOLEAN, k \in 1..Len(history) : - LiteLlm(t) /\ history[k].by = t /\ Real(history[k].sig) => Sent(t, listed, k, 1) = history[k].sig + LiteLlm(t) /\ history[k].by = t /\ history[k].minted => + Sent(t, listed, k, 1) = [by |-> t, step |-> k] ==== diff --git a/docs/architecture/tla/ThoughtSignatureMC.tla b/docs/architecture/tla/ThoughtSignatureMC.tla index 9b430409185..423537f4689 100644 --- a/docs/architecture/tla/ThoughtSignatureMC.tla +++ b/docs/architecture/tla/ThoughtSignatureMC.tla @@ -2,6 +2,32 @@ \* Model-checking settings and variants for ThoughtSignature. Each config replaces operators with these. EXTENDS ThoughtSignature +\* Issue 2304: the old reader ignores a signature present only in the ID. +IgnoreId == FALSE +\* Reader sabotage: an encoded ID wins over a later explicit field. +EncodedFirst == FALSE +\* Issue 2304: remove the guard that omits unsigned reasoning. +EchoUnsigned == TRUE + +\* Streaming sabotage: keep the first signature, including an ID fallback. +KeepFirstCaptured(previous, chunk) == IF previous # StreamNone THEN previous ELSE chunk + +\* Sabotage: origin checks omit the explicit field but keep the encoded signature in the ID. +KeepEncodedIds == TRUE + +\* Sabotage: rewrite assistant call IDs but keep encoded tool-result IDs. +KeepResultIds == FALSE + +\* Sabotage: look up reused call IDs without their history occurrence. +IdOnlyReplay == FALSE + +\* Sabotage: a result reads the next occurrence instead of the last consumed occurrence. +NextResult == TRUE + +\* Spec review sabotages: keep the cursor at zero, or keep the prior signed result for an unsigned call. +FrozenCursor == FALSE +KeepSignedResult == TRUE + CONSTANT MaxTurns Bounded == Len(history) <= MaxTurns @@ -17,7 +43,7 @@ ModelOrigin(b) == ModelOf(b) AnyOrigin(m, t) == TRUE \* AllCalls: a signature on every parallel call. EveryCall(i) == TRUE -\* NoMarker and Legacy: no __thought__ fallback. +\* Legacy: no __thought__ fallback. The separate NoMarker variant is retired after ID stripping. NoMarkerFallback(m, listed, i) == FALSE \* MarkerAlways: the round 2 code. The __thought__ fallback also applies to a listed model. MarkerAlways(m, listed, i) == m.marker /\ i = 1 diff --git a/docs/architecture/tla/ThoughtSignatureOccurrences.tla b/docs/architecture/tla/ThoughtSignatureOccurrences.tla new file mode 100644 index 00000000000..fc4feebef9f --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureOccurrences.tla @@ -0,0 +1,74 @@ +---- MODULE ThoughtSignatureOccurrences ---- +\* Source: assistant turns can reuse one tool-call ID. Sink: collectToolCallReplay and applyThoughtSignatures. +\* Failure: a later occurrence replaces an earlier signature. Invariant: OccurrenceSignaturesPreserved. +\* PR 2643: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660933927 +\* Expect ID-only lookup to fail when the first occurrence is signed and the second is unsigned. +\* ID normalization is an oracle. Each turn has one call; equal IDs denote reuse across turns. +\* Replay: the old code fails 12 of 16 reused-ID cases across both message converters. +\* Fixed lookup consumes each ID occurrence in order. Results use the latest preceding call occurrence. +\* Result: the history model holds (507 states). ReusedId fails after one turn. +\* Review ratchet: added one invariant for this finding. Normalizer behavior remains outside this model. +\* The canary test finding is covered by NoForeignEncodedSignature, not by this occurrence model. +\* Canary thread: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660933918 +\* An alphanumeric suffix now checks both outgoing IDs. Marker-only code sabotage fails 24 property cases. +\* Review totals for PR 2643: 2 covered, 5 added, 0 gap. Cost and final checks are in ThoughtSignaturePersistence. +\* Simplification expectation: keep occurrences and their cursor in one map entry. +\* The active result mapping is the last consumed occurrence. Do not store a second copy. +\* Invariant: ResultUsesLatestOccurrence. Expect no behavior change; an off-by-one sabotage must fail. +\* Grounding: https://refactoring.com/catalog/replaceDerivedVariableWithQuery.html +\* Grounding: https://react.dev/learn/choosing-the-state-structure (applied here as a design analogy). +\* Simplification result: one map holds each occurrence list and cursor. Result ownership is derived. +\* Fixed models hold (507 history, 51 request, 6 persistence states). All active sabotage variants fail as expected. +\* Next-occurrence code sabotage fails six reused-ID property cases. The restored utility passes all 262 tests. +\* All 1,323 focused tests, types, lint, formatting and both Knip checks pass. Suppression counts stay equal. +\* Null result: no new behavior failure. No speed gain was measured. Cost: about 2 agent minutes. +\* Review ratchet: two spec findings added. The prior checks omitted the second output and unsigned results. +\* Threads: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661110427 +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661110431 +\* Expect a frozen cursor to repeat the first signature. Expect a retained result to hide an unsigned occurrence. +\* Source and sink: replay consumes calls in order and derives each result from the updated per-ID cursor. +\* Review result: the fold checks both outputs, advances each ID cursor, and derives results from the same cursor. +\* The domain includes none, empty sequences and zero consumption. FrozenCursor and UnsignedResult fail as expected. +\* Runtime sabotage: a frozen cursor fails 14 reused-ID property cases. Restore advancement before other checks. +\* This round adds two findings on spec files. Earlier model checks did not cover these failures. +EXTENDS Naturals, Sequences + +ReplayByOccurrence == TRUE +AdvanceReplayCursor == TRUE +ResultAtNext == FALSE +RetainUnsignedResult == FALSE +ReplayIds == {"call_1", "call_2"} +ReplayValues == {"none", "a", "b"} +ReplayInputs == UNION {[1..n -> [id : ReplayIds, signature : ReplayValues]] : n \in 0..2} +InitialReplay == [next |-> [id \in ReplayIds |-> 0], calls |-> <<>>, results |-> <<>>] + +\* History supplies ordered occurrences. Parsing and normalization stay outside this fold. +Occurrences(history, id) == SelectSeq(history, LAMBDA call : call.id = id) +ResultSignature(values, consumed) == + LET position == IF ResultAtNext THEN consumed + 1 ELSE consumed + IN IF consumed = 0 \/ position > Len(values) THEN "none" ELSE values[position].signature + +Consume(history, state, call) == + LET values == Occurrences(history, call.id) + position == IF ReplayByOccurrence THEN state.next[call.id] + 1 ELSE Len(values) + captured == values[position].signature + next == IF AdvanceReplayCursor THEN state.next[call.id] + 1 ELSE state.next[call.id] + current == ResultSignature(values, next) + result == IF RetainUnsignedResult /\ current = "none" /\ Len(state.results) > 0 + THEN state.results[Len(state.results)] ELSE current + IN [next |-> [state.next EXCEPT ![call.id] = next], + calls |-> Append(state.calls, captured), results |-> Append(state.results, result)] + +RECURSIVE ReplayFold(_, _) +ReplayFold(history, count) == + IF count = 0 THEN InitialReplay + ELSE Consume(history, ReplayFold(history, count - 1), history[count]) +ExpectedSignatures(history) == [i \in 1..Len(history) |-> history[i].signature] +OccurrenceSignaturesPreserved == + \A history \in ReplayInputs : ReplayFold(history, Len(history)).calls = ExpectedSignatures(history) +ResultUsesLatestOccurrence == + \A history \in ReplayInputs : ReplayFold(history, Len(history)).results = ExpectedSignatures(history) +\* Before any call is consumed, no result owns a future occurrence, including an unsigned occurrence. +NoResultBeforeConsumption == + \A history \in ReplayInputs, id \in ReplayIds : ResultSignature(Occurrences(history, id), 0) = "none" +==== diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.Replacement.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.Replacement.cfg new file mode 100644 index 00000000000..3d111159c15 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.Replacement.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + UseProducingHandler <- CurrentHandler +INVARIANTS TypeOK SavedFromProducingHandler diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.ReportAttempts.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.ReportAttempts.cfg new file mode 100644 index 00000000000..8ec8e8530c4 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.ReportAttempts.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReportLimit <- ExtraReportAttempt +INVARIANTS TypeOK ReportingBounded diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.Reporting.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.Reporting.cfg new file mode 100644 index 00000000000..c783395ae59 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.Reporting.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + RetryOnReportingFailure <- CoupledReporting +INVARIANTS TypeOK CompletedTurnNotRetried diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.ReportingWait.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.ReportingWait.cfg new file mode 100644 index 00000000000..3472a8e39ec --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.ReportingWait.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + WaitForUsageReporting <- CoupledUsageWait +INVARIANTS TypeOK CompletedTurnNotRetried diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.SaveBeforeDrain.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.SaveBeforeDrain.cfg new file mode 100644 index 00000000000..54740370810 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.SaveBeforeDrain.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + WaitForDrain <- SaveBeforeDrain +INVARIANTS TypeOK SavedSignatureFinal diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.ToolRetry.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.ToolRetry.cfg new file mode 100644 index 00000000000..59bf5174636 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.ToolRetry.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + RetryAfterTool <- UnsafeToolRetry +INVARIANTS TypeOK ToolTurnNotRetried diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.Unbounded.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.Unbounded.cfg new file mode 100644 index 00000000000..bdd822b6cee --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.Unbounded.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + BoundSignatureWait <- UnboundedWait +INVARIANTS TypeOK NoExpiredSignatureWait diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.UsageBudget.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.UsageBudget.cfg new file mode 100644 index 00000000000..9ad1f2da5c2 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.UsageBudget.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + UseUsageTimeout <- UsageBudgetOnly +INVARIANTS TypeOK SavedSignatureFinal diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.cfg b/docs/architecture/tla/ThoughtSignaturePersistence.cfg new file mode 100644 index 00000000000..c04e3e15828 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS ReportingBounded ToolTurnNotRetried CompletedTurnNotRetried TypeOK SavedSignatureFinal SavedFromProducingHandler NoExpiredSignatureWait diff --git a/docs/architecture/tla/ThoughtSignaturePersistence.tla b/docs/architecture/tla/ThoughtSignaturePersistence.tla new file mode 100644 index 00000000000..e016a05c25f --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistence.tla @@ -0,0 +1,130 @@ +---- MODULE ThoughtSignaturePersistence ---- +\* Source: an interrupted proxy stream can deliver an explicit signature during its drain. +\* Sink: Task prepares and saves the assistant history block before replay. +\* Failure: save snapshots an ID fallback before the explicit field arrives. Invariant: SavedSignatureFinal. +\* PR 2643: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4660933915 +\* Expect SaveBeforeDrain to fail. Replay a delayed explicit delta through the real Task request loop. +\* Oracle: the drained stream either supplies an explicit signature or ends without one. +\* Error and cancellation end the consumed stream. Transport liveness is outside this safety model. +\* Replay: two Task cases delay the drain and verify history stays pending until it settles. +\* Both fail on the old code. After release, replay gets the explicit field or the ID fallback if no field arrives. +\* Result: fixed holds (6 states). SaveBeforeDrain fails with 8 states. No additional failure was found. +\* Task waits for opted-in handlers only. Cancellation races the drain read through nextChunkWithAbort. +\* This changes stream/history ordering, not persisted task status or shared lifecycle reducers. +\* Scope: the model checks safety for consumed chunks, not provider completion or transport liveness. +\* Validation: 1,323 focused tests pass. Types, lint, formatting and both Knip checks pass. Suppression counts stay equal. +\* All three signature model gates and lifecycle:model-check pass. Each active sabotage variant fails as expected. +\* Full pnpm test hit an unrelated custom-tool timeout. That suite passes alone; pnpm test --concurrency=2 passes all 14 tasks. +\* The extension suite passes 15,527 tests. No further modeled failure was found. Cost: about 11 agent minutes. +\* Review ratchet: add usage expiry, stalled reads, late ID-only values, and replacement of the producing handler. +\* Follow-up: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661053797 +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661110432 +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661110439 +\* Expect usage expiry to allow an incomplete save, an unbounded read to outlive its deadline, and replacement metadata to leak. +\* Deadline expiry is a terminal failure. No assistant turn may commit from an incomplete drain. +\* Result: four Task cases fail on the old code. All six drain scenarios pass after the fix. +\* Fixed holds (42 states). UsageBudget, Unbounded, Replacement and SaveBeforeDrain fail as expected. +\* Signature completion uses the configured request timeout, independently of usage collection. Timeout rejects the turn. +\* History preparation uses the producing handler and its captured configuration, even after a profile change. +\* Model correction: pending and committed metadata now use the same record type. Mixed values caused a TLC type error. +\* This round: 0 covered, 5 added, 0 gap; two findings concern spec files. PR totals: 2 covered, 10 added, 0 gap. +\* Validation: 1,333 focused tests, types, lint, formatting, both Knip checks, lifecycle checks and all signature gates pass. +\* pnpm test --concurrency=2 passes all 14 tasks. The extension suite passes 15,537 tests. +\* Null result: no further failure in the fixed bounded models. Timers delivering their deadline event remain an assumption. +\* Cost: about 12 agent minutes. The new timeout tests use a controlled budget rather than waiting for the full provider timeout. +\* Review ratchet: usage reporting is an auxiliary sink, separate from stream consumption. +\* Thread: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661256805 +\* Failure: a reporting failure retries a completed turn. Invariant: CompletedTurnNotRetried. +\* Expect the coupled drain to fail after consumption succeeds and reporting rejects or stalls. +\* Preserve failures and deadlines during consumption. A completed turn must not depend on reporting settlement. +\* Result: all three reporting replays fail before the fix and pass after reporting is detached from consumption. +\* Completed reporting may reject once, reject repeatedly or stall. History still saves the completed signature. +\* A separate Task case keeps genuine consumption errors fatal. Existing drain deadlines still reject incomplete turns. +\* Fixed holds (88 states). Reporting and ReportingWait fail independently, alongside all existing sabotage variants. +\* This round: 0 covered, 1 added, 0 gap. PR totals: 2 covered, 11 added, 0 gap; two earlier findings concern spec files. +\* Types, lint, formatting, both Knip checks and lifecycle checks pass. Suppression counts stay equal. +\* pnpm test --concurrency=2 passes all 14 tasks. The extension suite passes 15,541 tests. +\* Null result: no further failure in the fixed bounded model. Reporting delivery remains best effort. +\* Cost: about 7 agent minutes. Consumption and reporting failures use separate paths and separate regression cases. +\* User review of d4d3324636 on PR 2643: an executed tool must not repeat after a consumption failure or deadline. +\* Expect the old retry rule to violate ToolTurnNotRetried. Source: streamed tool calls. Sink: the retry stack. +\* Code: recursivelyMakeClineRequests consumes calls and starts presentAssistantMessageSafe before the signature drain. +\* Runtime guard uses any complete tool call because execution can overlap stream consumption. +\* toolObserved abstracts complete calls. Execution can start after this source event, before stream completion. +\* CodeRabbit reporting checks: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4661514386 +\* Add ReportingBounded and attempt-count and telemetry assertions. Reporting delivery remains best effort. +\* Result: the old retry rule fails after Stop and Deadline with toolObserved true and retries 1. +\* Both real-presenter regressions fail without the guard. Each observes one write-handler call and an unsafe retry. +\* With the guard, both cases retain the result and stop without another request. Partial calls remain retryable. +\* Fixed holds (248 states). ToolRetry and ReportAttempts fail, as do all six existing negative configurations. +\* One-attempt and three-attempt runtime changes fail the reporting tests. The successful case checks an exact telemetry payload. +\* This round: 0 covered, 2 added, 0 gap. PR totals: 2 covered, 13 added, 0 gap. +\* Null result: no additional failure in the fixed bounded model. This change does not add durable tool recovery. +\* Validation: full pnpm test --concurrency=2 passes all 14 tasks, including 15,543 extension tests. +\* The first full run hit an extension-activation timeout. That suite passes alone and on the full rerun. +\* Types, lint, formatting, both Knip checks and lifecycle checks pass. Suppression counts stay equal. +\* Cost: about 12 agent minutes. The runtime change adds one conservative stop before the retry branch. +\* Review: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4673468489 +\* Added ThoughtSignatureRecovery for the ask-to-request boundary. Signature values do not change recovery decisions. +\* The separate bounded model avoids multiplying independent signature and recovery states. +EXTENDS Naturals + +VARIABLES phase, candidate, expected, saved, complete, current, expired, reporting, retries, toolObserved, reportAttempts +vars == <> +RetryAfterTool == FALSE +ReportLimit == 2 +WaitForDrain == TRUE +UseUsageTimeout == FALSE +BoundSignatureWait == TRUE +UseProducingHandler == TRUE +RetryOnReportingFailure == FALSE +WaitForUsageReporting == FALSE +Pending == [signature |-> "pending", origin |-> "pending"] +Init == /\ phase = "reading" /\ candidate \in {"none", "encoded"} + /\ expected \in (IF candidate = "encoded" THEN {"encoded", "explicit"} ELSE {"none", "encoded", "explicit"}) + /\ saved = Pending /\ complete = FALSE /\ current = "producer" /\ expired = FALSE + /\ reporting = "pending" /\ retries = 0 /\ toolObserved \in BOOLEAN /\ reportAttempts = 0 +Stop == /\ phase = "reading" /\ phase' = "stopped" + /\ UNCHANGED <> +Replace == /\ current = "producer" /\ current' = "replacement" + /\ UNCHANGED <> +Drain == /\ phase = "stopped" /\ phase' = "settled" /\ candidate' = expected /\ complete' = TRUE + /\ UNCHANGED <> +UsageExpiry == /\ phase = "stopped" /\ UseUsageTimeout /\ phase' = "settled" + /\ UNCHANGED <> +Deadline == /\ phase = "stopped" /\ ~expired /\ expired' = TRUE + /\ phase' = IF BoundSignatureWait THEN "failed" ELSE "stopped" + /\ retries' = IF BoundSignatureWait /\ (~toolObserved \/ RetryAfterTool) THEN 1 ELSE retries + /\ UNCHANGED <> +StreamFailure == /\ phase = "stopped" /\ phase' = "failed" /\ retries' = IF ~toolObserved \/ RetryAfterTool THEN 1 ELSE 0 + /\ UNCHANGED <> +Report(result) == /\ complete /\ reporting \in {"pending", "failed"} /\ reportAttempts < ReportLimit + /\ reporting' = result /\ reportAttempts' = reportAttempts + 1 + /\ phase' = IF result = "failed" /\ RetryOnReportingFailure THEN "failed" ELSE phase + /\ retries' = IF result = "failed" /\ RetryOnReportingFailure THEN 1 ELSE retries + /\ UNCHANGED <> +ReportDeadline == /\ complete /\ reporting = "stalled" /\ WaitForUsageReporting + /\ phase' = "failed" /\ retries' = 1 + /\ UNCHANGED <> +Save == /\ (phase = "settled" \/ (~WaitForDrain /\ phase = "stopped")) /\ saved = Pending + /\ (~WaitForUsageReporting \/ reporting \in {"ok", "failed"}) + /\ saved' = IF UseProducingHandler \/ current = "producer" + THEN [signature |-> candidate, origin |-> "producer"] + ELSE [signature |-> "replacement", origin |-> "replacement"] + /\ UNCHANGED <> +Next == Stop \/ Replace \/ Drain \/ UsageExpiry \/ Deadline \/ StreamFailure + \/ (\E result \in {"ok", "failed", "stalled"} : Report(result)) \/ ReportDeadline \/ Save +Spec == Init /\ [][Next]_vars +TypeOK == /\ phase \in {"reading", "stopped", "settled", "failed"} + /\ candidate \in {"none", "encoded", "explicit"} /\ expected \in {"none", "encoded", "explicit"} + /\ saved \in {Pending} \cup [signature : {"none", "encoded", "explicit", "replacement"}, origin : {"producer", "replacement"}] + /\ complete \in BOOLEAN /\ expired \in BOOLEAN /\ current \in {"producer", "replacement"} + /\ toolObserved \in BOOLEAN /\ reportAttempts \in 0..3 + /\ reporting \in {"pending", "ok", "failed", "stalled"} /\ retries \in 0..1 +SavedSignatureFinal == saved # Pending => complete /\ saved.signature = expected +SavedFromProducingHandler == saved # Pending => saved.origin = "producer" +NoExpiredSignatureWait == expired => phase # "stopped" +ReportingBounded == reportAttempts <= 2 +ToolTurnNotRetried == toolObserved => retries = 0 +CompletedTurnNotRetried == complete => retries = 0 /\ phase # "failed" +==== diff --git a/docs/architecture/tla/ThoughtSignaturePersistenceMC.tla b/docs/architecture/tla/ThoughtSignaturePersistenceMC.tla new file mode 100644 index 00000000000..b88f6d58e7e --- /dev/null +++ b/docs/architecture/tla/ThoughtSignaturePersistenceMC.tla @@ -0,0 +1,12 @@ +---- MODULE ThoughtSignaturePersistenceMC ---- +\* Sabotage: history can save an ID fallback while the stream still drains. +EXTENDS ThoughtSignaturePersistence +SaveBeforeDrain == FALSE +UsageBudgetOnly == TRUE +UnboundedWait == FALSE +CurrentHandler == FALSE +UnsafeToolRetry == TRUE +ExtraReportAttempt == 3 +CoupledReporting == TRUE +CoupledUsageWait == TRUE +==== diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.Automatic.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.Automatic.cfg new file mode 100644 index 00000000000..f765e3c673d --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.Automatic.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + RequireReply <- NoReply +INVARIANTS TypeOK ExplicitRecovery diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.LateMessage.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.LateMessage.cfg new file mode 100644 index 00000000000..ec7421b51da --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.LateMessage.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + WaitBeforeAsk <- OverlappingAsk +INVARIANTS TypeOK PromptAfterPresenter diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.NoAsk.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.NoAsk.cfg new file mode 100644 index 00000000000..30ff370e4bd --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.NoAsk.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + OfferRecovery <- NoAsk +INVARIANTS TypeOK RecoverableStop diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.Persistence.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.Persistence.cfg new file mode 100644 index 00000000000..ff1f12d8920 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.Persistence.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CancelPersistence <- UnsettledPersistence +INVARIANTS TypeOK CanSettleFailedTurn diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.Presenter.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.Presenter.cfg new file mode 100644 index 00000000000..111deb1a32b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.Presenter.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + WaitBeforeAsk <- NoPresenterWait +INVARIANTS TypeOK NoResumeUnderPresenter diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.Receipt.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.Receipt.cfg new file mode 100644 index 00000000000..ca9be3b4667 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.Receipt.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + PreserveReceipt <- NoReceipt +INVARIANTS TypeOK RecoveryHasReceipt diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.Replay.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.Replay.cfg new file mode 100644 index 00000000000..7a6f734fa0b --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.Replay.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + ReplayTool <- ResendTool +INVARIANTS TypeOK NoToolReplay diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.cfg b/docs/architecture/tla/ThoughtSignatureRecovery.cfg new file mode 100644 index 00000000000..40f632691c0 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS CanSettleFailedTurn PromptAfterPresenter TypeOK RecoverableStop ExplicitRecovery NoToolReplay RecoveryHasReceipt NoResumeUnderPresenter diff --git a/docs/architecture/tla/ThoughtSignatureRecovery.tla b/docs/architecture/tla/ThoughtSignatureRecovery.tla new file mode 100644 index 00000000000..342873a739e --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecovery.tla @@ -0,0 +1,75 @@ +---- MODULE ThoughtSignatureRecovery ---- +\* Source: recursivelyMakeClineRequests catches a failed tool stream. Sink: ask, user reply, and the next request. +\* Thread: https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4673468489 +\* Failure: stopping the loop leaves no recovery action. Invariant: RecoverableStop. +\* Failure: recovery resends the failed tool turn, loses its results, or overlaps its presenter. +\* Invariants: ExplicitRecovery, NoToolReplay, RecoveryHasReceipt, NoResumeUnderPresenter. +\* Expect the old return path to violate RecoverableStop. Replay failures and deadlines through the real presenter. +\* Oracle: a tool has started and may still be running when the stream fails. User input is an explicit event. +\* Scope: in-memory recovery, not restart persistence or a provider's later choice of tools. +\* Result: the old model fails RecoverableStop after Fail (3 states). Both old runtime cases stay Running. +\* Six real-presenter replays cover failure, deadline, late tool settlement, both reply paths, queued input, and decline. +\* Fixed holds (11 states). NoAsk, Automatic, Presenter, Receipt, and Replay each violate their named invariant. +\* Recovery waits for the presenter, then sends tool inputs and recorded results as text. Protocol calls are not resent. +\* This round: 0 covered, 1 added, 0 gap. PR totals: 2 covered, 14 added, 0 gap. +\* Null result: no new failure in the fixed bounded model. New provider tool choices and restart recovery remain outside scope. +\* Validation: 253 focused tests and all 14 full-test tasks pass. The extension suite passes 15,547 tests. +\* Types, lint, formatting, both Knip checks, lifecycle checks, and both signature model gates pass. +\* Suppression counts stay equal. Cost: about 10 agent minutes. +\* Review: cancel failed-turn persistence before joining the presenter, then open the recovery ask. +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4674061742 +\* https://github.com/Zoo-Code-Org/Zoo-Code/pull/2643#discussion_r4674161300 +\* Expect a persistence-dependent presenter to block settlement and late tool messages to invalidate an overlapping ask. +\* Invariants: CanSettleFailedTurn and PromptAfterPresenter. Keep completion and pending-action safeguards. +\* Grounding: https://devblogs.microsoft.com/dotnet/are-deadlocks-still-possible-with-await/ +\* Grounding: https://docs.python.org/3.12/library/asyncio-task.html#task-groups +\* Result: child completion fails both old runtime cases with a held presenter lock. Late error leaves the old ask superseded. +\* Fixed: cancel the failed persistence generation, join its presenter, then open the protected recovery ask. +\* No second presenter wait is needed after the reply. Completion stays uncommitted and pending actions stay intact. +\* Fixed holds (11 states). All seven negative variants fail, including Persistence and LateMessage. +\* Nine recovery cases and 439 focused tests pass, including the real child attempt_completion handler. +\* Review round: 0 covered, 3 added, 0 gap; one finding concerns a spec. PR totals: 2 covered, 17 added, 0 gap. +\* Null result: no further failure in the fixed bounded model. Uncooperative tools can still require task cancellation. +\* Validation: all 14 full-test tasks pass, including 15,554 extension tests. Types, lint, formatting, and both Knip checks pass. +\* Lifecycle checks and all three relevant TLA+ gates pass. Suppression counts stay equal. Cost: about 15 agent minutes. +EXTENDS Naturals +VARIABLES stage, busy, blocked, authorized, receipt, executions +vars == <> +OfferRecovery == TRUE +RequireReply == TRUE +PreserveReceipt == TRUE +ReplayTool == FALSE +CancelPersistence == TRUE +WaitBeforeAsk == TRUE +Init == /\ stage = "streaming" /\ busy \in BOOLEAN + /\ blocked \in (IF busy THEN BOOLEAN ELSE {FALSE}) + /\ authorized = FALSE /\ receipt = FALSE /\ executions = 1 +Fail == /\ stage = "streaming" + /\ stage' = IF ~OfferRecovery THEN "stopped" ELSE IF WaitBeforeAsk THEN "settling" ELSE "waiting" + /\ blocked' = IF CancelPersistence THEN FALSE ELSE blocked + /\ UNCHANGED <> +FinishTool == /\ busy /\ ~blocked /\ busy' = FALSE + /\ UNCHANGED <> +OpenAsk == /\ stage = "settling" /\ ~busy /\ stage' = "waiting" + /\ UNCHANGED <> +Reply == /\ stage = "waiting" /\ stage' = "ready" /\ authorized' = TRUE + /\ UNCHANGED <> +Resume == /\ (stage = "ready" \/ (~RequireReply /\ stage = "waiting")) + /\ stage' = "resumed" + /\ receipt' = PreserveReceipt /\ executions' = IF ReplayTool THEN 2 ELSE executions + /\ UNCHANGED <> +Cancel == /\ stage \in {"settling", "waiting", "ready"} /\ stage' = "cancelled" + /\ UNCHANGED <> +Next == Fail \/ FinishTool \/ OpenAsk \/ Reply \/ Resume \/ Cancel +Spec == Init /\ [][Next]_vars +TypeOK == /\ stage \in {"streaming", "settling", "waiting", "ready", "resumed", "stopped", "cancelled"} + /\ busy \in BOOLEAN /\ blocked \in BOOLEAN /\ authorized \in BOOLEAN + /\ receipt \in BOOLEAN /\ executions \in 1..2 +RecoverableStop == stage # "stopped" +ExplicitRecovery == stage = "resumed" => authorized +NoToolReplay == executions = 1 +RecoveryHasReceipt == stage = "resumed" => receipt +NoResumeUnderPresenter == stage = "resumed" => ~busy +CanSettleFailedTurn == stage \in {"settling", "waiting", "ready"} => ~blocked +PromptAfterPresenter == stage = "waiting" => ~busy +==== diff --git a/docs/architecture/tla/ThoughtSignatureRecoveryMC.tla b/docs/architecture/tla/ThoughtSignatureRecoveryMC.tla new file mode 100644 index 00000000000..4b349794b29 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRecoveryMC.tla @@ -0,0 +1,10 @@ +---- MODULE ThoughtSignatureRecoveryMC ---- +EXTENDS ThoughtSignatureRecovery +NoAsk == FALSE +UnsettledPersistence == FALSE +OverlappingAsk == FALSE +NoReply == FALSE +NoPresenterWait == FALSE +NoReceipt == FALSE +ResendTool == TRUE +==== diff --git a/docs/architecture/tla/ThoughtSignatureRequests.SharedLast.cfg b/docs/architecture/tla/ThoughtSignatureRequests.SharedLast.cfg new file mode 100644 index 00000000000..841952d8010 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRequests.SharedLast.cfg @@ -0,0 +1,5 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + CurrentSignature <- SharedLast +INVARIANTS TypeOK RequestSignatureOwned diff --git a/docs/architecture/tla/ThoughtSignatureRequests.cfg b/docs/architecture/tla/ThoughtSignatureRequests.cfg new file mode 100644 index 00000000000..0c2099ec28d --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRequests.cfg @@ -0,0 +1,3 @@ +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +INVARIANTS TypeOK RequestSignatureOwned diff --git a/docs/architecture/tla/ThoughtSignatureRequests.tla b/docs/architecture/tla/ThoughtSignatureRequests.tla new file mode 100644 index 00000000000..49520f7f106 --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRequests.tla @@ -0,0 +1,38 @@ +---- MODULE ThoughtSignatureRequests ---- +\* Source: createMessage starts a reader; old usage drains keep reading earlier generators. +\* Sink: getThoughtSignature feeds prepareApiConversationMessage for the current request. +\* Failure: an older drain replaces or clears the current signature. Invariant: RequestSignatureOwned. +\* Expect SharedLast to fail when request 1 reads after request 2 starts. +\* Scope: history for a request is prepared before another request starts. Drains can overlap. +\* Two requests and five candidate values cover empty, encoded and explicit signatures. +\* Reader parsing and usage accounting are oracles. No task lifecycle transitions are modeled. +\* Cost and replay results are recorded in ThoughtSignature.tla. +EXTENDS ThoughtSignatureStream + +\* shared records the old publication for the SharedLast sabotage. The fixed view derives from readers. +VARIABLES active, readers, shared +vars == <> +Init == /\ active = 0 + /\ readers = [r \in 1..2 |-> StreamNone] + /\ shared = StreamNone + +Start == /\ active < 2 + /\ active' = active + 1 + /\ shared' = StreamNone + /\ UNCHANGED readers + +Read(r, candidate) == + LET value == CaptureStream(readers[r], candidate) + IN /\ r <= active + /\ readers' = [readers EXCEPT ![r] = value] + /\ shared' = value + /\ UNCHANGED active + +Next == Start \/ (\E r \in 1..2, candidate \in StreamCandidates : Read(r, candidate)) +Spec == Init /\ [][Next]_vars + +\* The handler points to the current request reader. Older drains can update only their own reader. +CurrentSignature == IF active = 0 THEN StreamNone ELSE readers[active] +TypeOK == active \in 0..2 /\ readers \in [1..2 -> StreamCandidates] /\ shared \in StreamCandidates +RequestSignatureOwned == active > 0 => CurrentSignature = readers[active] +==== diff --git a/docs/architecture/tla/ThoughtSignatureRequestsMC.tla b/docs/architecture/tla/ThoughtSignatureRequestsMC.tla new file mode 100644 index 00000000000..70f8d5a227d --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureRequestsMC.tla @@ -0,0 +1,5 @@ +---- MODULE ThoughtSignatureRequestsMC ---- +\* Sabotage: publish the last value read from any stream. +EXTENDS ThoughtSignatureRequests +SharedLast == shared +==== diff --git a/docs/architecture/tla/ThoughtSignatureStream.tla b/docs/architecture/tla/ThoughtSignatureStream.tla new file mode 100644 index 00000000000..c4cb30139cf --- /dev/null +++ b/docs/architecture/tla/ThoughtSignatureStream.tla @@ -0,0 +1,39 @@ +---- MODULE ThoughtSignatureStream ---- +\* Source: OpenAiHandler and LiteLLMHandler consume tool-call chunks in createMessage. +\* Sink: getThoughtSignature returns the value that enters assistant history. +\* Failure: an early ID fallback hides a later explicit field. Invariant: StreamSignaturePriority. +\* Expect the old first-value rule to fail for an encoded chunk followed by an explicit chunk. +\* Candidate values are oracles. ID parsing and transport chunk boundaries are outside this model. +\* Cost and results are recorded in ThoughtSignature.tla. +\* API simplification expectation: update changes reader state; signature reads it without mutation. +\* Keep source priority, request ownership and ID isolation unchanged. Expect no new model failure. +\* The property tests now observe signature after each update. Keep every sabotage configuration. +\* Result: both models pass (507 history states, 51 request states); all active sabotage variants fail as expected. +\* All 1,074 tests, types, lint, formatting and both Knip checks pass. Suppression counts stay equal. +\* Null result: no new failure or state change. Cost: about 1 agent minute. +EXTENDS Naturals, Sequences + +StreamNone == [source |-> "none", value |-> ""] +StreamCandidates == {StreamNone} \cup [source : {"encoded", "explicit"}, value : {"a", "b"}] + +\* Keep the first explicit field. A later explicit field can replace an ID fallback. +CaptureStream(previous, chunk) == + IF previous.source = "explicit" THEN previous + ELSE IF chunk.source = "explicit" \/ previous = StreamNone THEN chunk ELSE previous + +RECURSIVE StreamCaptured(_) +StreamCaptured(chunks) == + IF Len(chunks) = 0 THEN StreamNone + ELSE CaptureStream(StreamCaptured(SubSeq(chunks, 1, Len(chunks) - 1)), chunks[Len(chunks)]) + +\* The contract chooses the first explicit field, or the first ID fallback if no field exists. +StreamExpected(chunks) == + LET explicit == SelectSeq(chunks, LAMBDA c : c.source = "explicit") + encoded == SelectSeq(chunks, LAMBDA c : c.source = "encoded") + IN IF Len(explicit) > 0 THEN Head(explicit) + ELSE IF Len(encoded) > 0 THEN Head(encoded) ELSE StreamNone + +StreamSignaturePriority == + \A chunks \in UNION {[1..n -> StreamCandidates] : n \in 0..3} : + StreamCaptured(chunks) = StreamExpected(chunks) +==== diff --git a/scripts/check-completion-persistence.ts b/scripts/check-completion-persistence.ts index 10c9d967696..d2ce8bf4996 100644 --- a/scripts/check-completion-persistence.ts +++ b/scripts/check-completion-persistence.ts @@ -11,7 +11,7 @@ interface ModelState { writeStarts: WriteStarts completionAccepted: boolean completionEmitted: boolean - cancelled: boolean + cancelled: boolean // Current persistence generation, including a failed stream on an active task. waitSettled: boolean cancelledAtRetryBoundary: boolean delegation: DelegationPhase @@ -82,6 +82,14 @@ const transitionInvariants = { }, } satisfies Record string | undefined> const semanticLandmarks = { + "failed-delegated-turn-settles-without-completion": (state: ModelState) => + state.kind === "delegated" && + state.completionAccepted && + state.history === "idle" && + state.cancelled && + state.waitSettled && + !state.completionEmitted && + state.delegation === "awaiting-reopen", "delayed-completion-pending": (state: ModelState) => state.completionAccepted && state.history === "writing" && !state.completionEmitted, "failed-completion-pending": (state: ModelState) => diff --git a/src/api/index.ts b/src/api/index.ts index 3d4138cbce9..c1cb058360d 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -141,6 +141,9 @@ export interface ModelCacheScope { } export interface ApiHandler { + /** Drain interrupted streams before history captures signatures that can arrive in later chunks. */ + readonly requiresThoughtSignatureDrain?: boolean + createMessage( systemPrompt: string, messages: Anthropic.Messages.MessageParam[], diff --git a/src/api/providers/__tests__/lite-llm.spec.ts b/src/api/providers/__tests__/lite-llm.spec.ts index 7dece92c67e..b4fb408c968 100644 --- a/src/api/providers/__tests__/lite-llm.spec.ts +++ b/src/api/providers/__tests__/lite-llm.spec.ts @@ -688,6 +688,146 @@ describe("LiteLLMHandler", () => { expect(handler.getThoughtSignatureOrigin()).toBe(thoughtSignatureOrigin(endpoint, "gemini-3-pro")) }) + it.each([ + { sources: ["encoded", "explicit"], expected: "explicit-1" }, + { sources: ["explicit", "encoded"], expected: "explicit-0" }, + { sources: ["explicit", "explicit"], expected: "explicit-0" }, + { sources: ["encoded", "encoded"], expected: "encoded-0" }, + ])("keeps signature source priority across $sources chunks", async ({ sources, expected }) => { + useModel("gemini-3-pro") + const chunks = sources.map((source, index) => ({ + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + ...(index === 0 + ? { id: "call_1", function: { name: "read_file", arguments: "{}" } } + : {}), + ...(source === "explicit" + ? { + provider_specific_fields: { + thought_signature: `explicit-${index}`, + }, + } + : { id: `call_1__thought__encoded-${index}` }), + }, + ], + }, + }, + ], + })) + mockStream([...chunks, { choices: [{ delta: { tool_calls: [{ index: 0 }] } }] }]) + await collectStream(handler.createMessage("system", [], metadata)) + expect(handler.requiresThoughtSignatureDrain).toBe(true) + expect(handler.getThoughtSignature()).toBe(expected) + }) + + // RequestSignatureOwned: an older drain cannot change the current request's history signature. + it.each( + [undefined, "old"].flatMap((oldSignature) => + [undefined, "new"].flatMap((newSignature) => + [false, true].map((lateExplicit) => ({ oldSignature, newSignature, lateExplicit })), + ), + ), + )( + "keeps request signature ownership for $oldSignature/$newSignature (lateExplicit=$lateExplicit)", + async ({ oldSignature, newSignature, lateExplicit }) => { + useModel("gemini-3-pro") + const firstChunk = (signature: string | undefined) => ({ + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_1", + function: { name: "read_file", arguments: "{}" }, + ...(signature + ? { provider_specific_fields: { thought_signature: signature } } + : {}), + }, + ], + }, + }, + ], + }) + let chunks = [ + firstChunk(oldSignature), + lateExplicit + ? { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + provider_specific_fields: { thought_signature: "late-old" }, + }, + ], + }, + }, + ], + } + : { choices: [{ delta: {} }] }, + ] + mockStream(chunks) + const older = handler.createMessage("system", [], metadata) + await older.next() + chunks = [firstChunk(newSignature)] + mockStream(chunks) + await collectStream(handler.createMessage("system", [], metadata)) + await collectStream(older) + expect(handler.getThoughtSignature()).toBe(newSignature) + const saved = prepareApiConversationMessage({ + message: { + role: "assistant", + content: [{ type: "tool_use", id: "call_1", name: "read_file", input: {} }], + }, + api: handler, + apiConfiguration: { + apiProvider: providerIdentifiers.litellm, + litellmModelId: "gemini-3-pro", + }, + apiConversationHistory: [], + }) + expect(saved.content).toEqual( + newSignature + ? expect.arrayContaining([ + expect.objectContaining({ + type: "thoughtSignature", + thoughtSignature: newSignature, + }), + ]) + : [expect.objectContaining({ type: "tool_use" })], + ) + }, + ) + + it("captures a signature sent only in the tool call ID", async () => { + useModel("gemini-3-pro") + mockStream([ + { + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: `call_1__thought__${TEST_THOUGHT_SIGNATURE}`, + function: { name: "read_file", arguments: "{}" }, + }, + ], + }, + }, + ], + }, + ]) + await collectStream(handler.createMessage("system", [], metadata)) + expect(handler.getThoughtSignature()).toBe(TEST_THOUGHT_SIGNATURE) + }) + it("captures the signature from a streamed tool call and resets it per request", async () => { useModel("gemini-3-pro") mockStream(signedToolCallStream) diff --git a/src/api/providers/__tests__/openai.spec.ts b/src/api/providers/__tests__/openai.spec.ts index 8006e5dab84..0943afef6c1 100644 --- a/src/api/providers/__tests__/openai.spec.ts +++ b/src/api/providers/__tests__/openai.spec.ts @@ -22,6 +22,12 @@ import { makeApiHandlerOptions, makeCreateMessageMetadata } from "../../../test- import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { expectNoLoneSurrogates } from "../../../test-utils/surrogates" import axios from "axios" +import { + signedAssistantMessage, + toolResultsMessage, + TEST_THOUGHT_SIGNATURE, +} from "../../../test-utils/thought-signature" +import { sanitizeToolUseId } from "../../../utils/tool-id" vitest.mock("../utils/timeout-config", () => ({ getApiRequestTimeout: vitest.fn().mockReturnValue(300_000), @@ -117,6 +123,200 @@ vitest.mock("axios", () => ({ }, })) +describe("OpenAI Compatible proxy signatures", () => { + it.each([ + { sources: ["encoded", "explicit"], expected: "explicit-1" }, + { sources: ["explicit", "encoded"], expected: "explicit-0" }, + { sources: ["explicit", "explicit"], expected: "explicit-0" }, + { sources: ["encoded", "encoded"], expected: "encoded-0" }, + ])("keeps signature source priority across $sources chunks", async ({ sources, expected }) => { + const handler = new OpenAiHandler( + makeApiHandlerOptions({ openAiApiKey: "test", openAiModelId: "gemini-3-flash" }), + ) + const chunks = sources.map((source, index) => ({ + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + ...(index === 0 + ? { id: "call_1", function: { name: "read_file", arguments: "{}" } } + : {}), + ...(source === "explicit" + ? { provider_specific_fields: { thought_signature: `explicit-${index}` } } + : { id: `call_1__thought__encoded-${index}` }), + }, + ], + }, + }, + ], + })) + mockCreate.mockResolvedValueOnce( + asyncStreamFrom([...chunks, { choices: [{ delta: { tool_calls: [{ index: 0 }] } }] }]), + ) + await collectStream(handler.createMessage("system", [])) + expect(handler.requiresThoughtSignatureDrain).toBe(true) + expect(handler.getThoughtSignature()).toBe(expected) + }) + + // RequestSignatureOwned: an older drain cannot change the current request's history signature. + it.each( + [undefined, "old"].flatMap((oldSignature) => + [undefined, "new"].flatMap((newSignature) => + [false, true].map((lateExplicit) => ({ oldSignature, newSignature, lateExplicit })), + ), + ), + )( + "keeps request signature ownership for $oldSignature/$newSignature (lateExplicit=$lateExplicit)", + async ({ oldSignature, newSignature, lateExplicit }) => { + const handler = new OpenAiHandler( + makeApiHandlerOptions({ openAiApiKey: "test", openAiModelId: "gemini-3-flash" }), + ) + const firstChunk = (signature: string | undefined) => ({ + choices: [ + { + delta: { + tool_calls: [ + { + index: 0, + id: "call_1", + function: { name: "read_file", arguments: "{}" }, + ...(signature + ? { provider_specific_fields: { thought_signature: signature } } + : {}), + }, + ], + }, + }, + ], + }) + let chunks = [ + firstChunk(oldSignature), + lateExplicit + ? { + choices: [ + { + delta: { + tool_calls: [ + { index: 0, provider_specific_fields: { thought_signature: "late-old" } }, + ], + }, + }, + ], + } + : { choices: [{ delta: {} }] }, + ] + mockCreate.mockResolvedValueOnce(asyncStreamFrom(chunks)) + const older = handler.createMessage("system", []) + await older.next() + chunks = [firstChunk(newSignature)] + mockCreate.mockResolvedValueOnce(asyncStreamFrom(chunks)) + await collectStream(handler.createMessage("system", [])) + await collectStream(older) + expect(handler.getThoughtSignature()).toBe(newSignature) + const saved = prepareApiConversationMessage({ + message: { + role: "assistant", + content: [{ type: "tool_use", id: "call_1", name: "read_file", input: {} }], + }, + api: handler, + apiConfiguration: { apiProvider: providerIdentifiers.openai, openAiModelId: "gemini-3-flash" }, + apiConversationHistory: [], + }) + expect(saved.content).toEqual( + newSignature + ? expect.arrayContaining([ + expect.objectContaining({ type: "thoughtSignature", thoughtSignature: newSignature }), + ]) + : [expect.objectContaining({ type: "tool_use" })], + ) + }, + ) + + it.each([true, false])("returns an ID-only signature with streaming=%s", async (streaming) => { + const handler = new OpenAiHandler( + makeApiHandlerOptions({ + openAiApiKey: "test", + openAiModelId: "gemini-3-flash", + openAiBaseUrl: "http://proxy:4000/v1", + openAiStreamingEnabled: streaming, + }), + ) + const id = `call_1__thought__${TEST_THOUGHT_SIGNATURE}` + const call = { id, type: "function" as const, function: { name: "read_file", arguments: "{}" } } + mockCreate.mockResolvedValueOnce( + streaming + ? asyncStreamFrom([{ choices: [{ delta: { tool_calls: [{ ...call, index: 0 }] } }] }]) + : { choices: [{ message: { content: "", tool_calls: [call] } }] }, + ) + await collectStream(handler.createMessage("system", [])) + expect(handler.getThoughtSignature()).toBe(TEST_THOUGHT_SIGNATURE) + const origin = handler.getThoughtSignatureOrigin() + expect(origin).toBeDefined() + const storedId = sanitizeToolUseId(id) + const history = [signedAssistantMessage([storedId], { origin }), toolResultsMessage([storedId])] + mockCreate.mockResolvedValueOnce( + streaming ? asyncStreamFrom([]) : { choices: [{ message: { content: "ok" } }] }, + ) + await collectStream(handler.createMessage("system", history)) + const request: OpenAI.Chat.ChatCompletionCreateParams = mockCreate.mock.calls.at(-1)![0] + const assistant = request.messages.find((message) => message.role === "assistant") + expect(assistant).toMatchObject({ + tool_calls: [{ id: storedId, provider_specific_fields: { thought_signature: TEST_THOUGHT_SIGNATURE } }], + }) + expect(request.messages.find((message) => message.role === "tool")).toMatchObject({ tool_call_id: storedId }) + expect(handler.getThoughtSignature()).toBeUndefined() + }) + + it.each([ + { streaming: true, changed: "endpoint", openAiBaseUrl: "http://other-proxy:4000/v1" }, + { streaming: false, changed: "endpoint", openAiBaseUrl: "http://other-proxy:4000/v1" }, + { streaming: true, changed: "model", openAiModelId: "gemini-3-pro" }, + { streaming: false, changed: "model", openAiModelId: "gemini-3-pro" }, + ])( + "withholds a signature after a $changed change with streaming=$streaming", + async ({ streaming, changed: _changed, ...overrides }) => { + const options = makeApiHandlerOptions({ + openAiApiKey: "test", + openAiModelId: "gemini-3-flash", + openAiBaseUrl: "http://proxy:4000/v1", + openAiStreamingEnabled: streaming, + }) + const source = new OpenAiHandler(options) + const id = `call_1__thought__${TEST_THOUGHT_SIGNATURE}` + const call = { id, type: "function" as const, function: { name: "read_file", arguments: "{}" } } + mockCreate.mockResolvedValueOnce( + streaming + ? asyncStreamFrom([{ choices: [{ delta: { tool_calls: [{ ...call, index: 0 }] } }] }]) + : { choices: [{ message: { content: "", tool_calls: [call] } }] }, + ) + await collectStream(source.createMessage("system", [])) + expect(source.getThoughtSignature()).toBe(TEST_THOUGHT_SIGNATURE) + const storedId = sanitizeToolUseId(id) + const history = [ + signedAssistantMessage([storedId], { origin: source.getThoughtSignatureOrigin() }), + toolResultsMessage([storedId]), + ] + const target = new OpenAiHandler({ ...options, ...overrides }) + mockCreate.mockResolvedValueOnce( + streaming ? asyncStreamFrom([]) : { choices: [{ message: { content: "ok" } }] }, + ) + await collectStream(target.createMessage("system", history)) + expect(target.getThoughtSignatureOrigin()).not.toBe(source.getThoughtSignatureOrigin()) + const request: OpenAI.Chat.ChatCompletionCreateParams = mockCreate.mock.calls.at(-1)![0] + const assistant = request.messages.find((message) => message.role === "assistant") + expect(assistant).toMatchObject({ tool_calls: [{ id: expect.stringMatching(/^call_1_[a-f0-9]{16}$/) }] }) + expect(assistant).not.toHaveProperty("tool_calls.0.provider_specific_fields.thought_signature") + expect(JSON.stringify(request.messages)).not.toContain(TEST_THOUGHT_SIGNATURE) + expect(JSON.stringify(request.messages)).not.toContain("__thought__") + expect(request.messages.find((message) => message.role === "tool")).toMatchObject({ + tool_call_id: assistant?.role === "assistant" ? assistant.tool_calls?.[0].id : undefined, + }) + }, + ) +}) + describe("OpenAiHandler", () => { let handler: OpenAiHandler let mockOptions: ApiHandlerOptions diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index babd74f16e3..8e6c9727b41 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -23,7 +23,7 @@ import { sanitizeOpenAiCallId } from "../../utils/tool-id" import { LITELLM_THOUGHT_SIGNATURE_ID_MARKER, applyThoughtSignatures, - readThoughtSignature, + ThoughtSignatureReader, thoughtSignatureOrigin, } from "./utils/thought-signature" @@ -57,7 +57,8 @@ const LITELLM_DEFAULT_BASE_URL = "http://localhost:4000" * It follows the OpenAI API format for compatibility. */ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHandler { - private lastThoughtSignature: string | undefined + readonly requiresThoughtSignatureDrain = true + private thoughtSignatureReader: ThoughtSignatureReader | undefined private thoughtSignatureOrigin: string | undefined constructor(options: ApiHandlerOptions) { @@ -120,7 +121,9 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // already-aborted request fails with AbortError before provider model // discovery (getModels/refreshModels) begins. throwIfAborted(metadata?.abortSignal) - this.lastThoughtSignature = undefined + // Each generator owns its reader. An older usage drain cannot change the current signature. + const signatureReader = new ThoughtSignatureReader() + this.thoughtSignatureReader = signatureReader // Model discovery is shared single-flight (RouterProvider.fetchModel): // concurrent callers join one in-flight fetch, so the fetch itself @@ -326,7 +329,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa // Handle tool calls in stream - emit partial chunks for NativeToolCallParser if (delta?.tool_calls) { - this.lastThoughtSignature ??= readThoughtSignature(delta.tool_calls) + signatureReader.update(delta.tool_calls) for (const toolCall of delta.tool_calls) { throwIfAborted(requestSignal) yield { @@ -396,7 +399,7 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa } getThoughtSignature(): string | undefined { - return this.lastThoughtSignature + return this.thoughtSignatureReader?.signature } getThoughtSignatureOrigin(): string | undefined { diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index 63b8e2ae390..76080b773ee 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -39,6 +39,7 @@ import { DEFAULT_HEADERS, NOT_PROVIDED } from "./constants" import { BaseProvider } from "./base-provider" import type { SingleCompletionHandler, ApiHandlerCreateMessageMetadata, CompletePromptOptions } from "../index" import { handleOpenAIError } from "./utils/error-handler" +import { applyThoughtSignatures, thoughtSignatureOrigin, ThoughtSignatureReader } from "./utils/thought-signature" import { extractReasoningFromDelta } from "./utils/extract-reasoning" import { bridgeExternalAbortSignal, @@ -73,7 +74,10 @@ type OpenAiUsage = export class OpenAiHandler extends BaseProvider implements SingleCompletionHandler { protected options: ApiHandlerOptions protected client: OpenAI + readonly requiresThoughtSignatureDrain = true private readonly providerName = "OpenAI" + private thoughtSignatureReader: ThoughtSignatureReader | undefined + private signatureOrigin: string | undefined private readonly extraBody: Record private responsesReasoning: OpenAI.Responses.ResponseReasoningItem[] = [] @@ -144,6 +148,13 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { + // Each generator owns its reader. An older usage drain cannot change the current signature. + const signatureReader = new ThoughtSignatureReader() + this.thoughtSignatureReader = signatureReader + this.signatureOrigin = thoughtSignatureOrigin( + this.options.openAiBaseUrl || "https://api.openai.com/v1", + this.options.openAiModelId ?? "", + ) const modelId = this.options.openAiModelId ?? "" // Opt-in Responses API path: some OpenAI-compatible endpoints (e.g. Azure // OpenAI deployments of reasoning models behind corporate gateways) reject @@ -237,7 +248,7 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl (this.options.modelTemperature != null || deepseekReasoner) && { temperature: this.options.modelTemperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE, }), - messages: convertedMessages, + messages: applyThoughtSignatures(messages, convertedMessages, { origin: this.signatureOrigin }), stream: true as const, ...(isGrokXAI ? {} : { stream_options: { include_usage: true } }), ...(reasoning && reasoning), @@ -275,6 +286,7 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl for await (const chunk of stream) { const delta = chunk.choices?.[0]?.delta ?? {} const finishReason = chunk.choices?.[0]?.finish_reason + signatureReader.update(delta.tool_calls) const reasoningText = extractReasoningFromDelta(delta) if (reasoningText) { @@ -314,6 +326,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl parallel_tool_calls: metadata?.parallelToolCalls ?? true, } + requestOptions.messages = applyThoughtSignatures(messages, requestOptions.messages, { + origin: this.signatureOrigin, + }) // Add max_tokens if needed this.addMaxTokensIfNeeded(requestOptions, modelInfo) requestOptions = this.withExtraBody(requestOptions) @@ -329,6 +344,7 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } const message = response.choices?.[0]?.message + signatureReader.update(message?.tool_calls) if (message?.tool_calls) { for (const toolCall of message.tool_calls) { @@ -444,6 +460,14 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl })) } + getThoughtSignature(): string | undefined { + return this.thoughtSignatureReader?.signature + } + + getThoughtSignatureOrigin(): string | undefined { + return this.signatureOrigin + } + protected processUsageMetrics(usage: OpenAiUsage, _modelInfo?: ModelInfo): ApiStreamUsageChunk { const inputTokens = usage?.prompt_tokens || 0 const reportedCacheReadTokens = usage?.cache_read_input_tokens ?? usage?.prompt_tokens_details?.cached_tokens diff --git a/src/api/providers/utils/__tests__/thought-signature.spec.ts b/src/api/providers/utils/__tests__/thought-signature.spec.ts index d05319a3a73..8acf39ee448 100644 --- a/src/api/providers/utils/__tests__/thought-signature.spec.ts +++ b/src/api/providers/utils/__tests__/thought-signature.spec.ts @@ -1,8 +1,12 @@ import OpenAI from "openai" +import { convertToR1Format } from "../../../transform/r1-format" +import { convertToOpenAiMessages } from "../../../transform/openai-format" +import { sanitizeToolUseId } from "../../../../utils/tool-id" +import { toolResultsMessage } from "../../../../test-utils/thought-signature" import { sanitizeOpenAiCallId } from "../../../../utils/tool-id" import { signedAssistantMessage, TEST_THOUGHT_SIGNATURE as signature } from "../../../../test-utils/thought-signature" -import { applyThoughtSignatures, readThoughtSignature, thoughtSignatureOrigin } from "../thought-signature" +import { applyThoughtSignatures, thoughtSignatureOrigin, ThoughtSignatureReader } from "../thought-signature" const origin = "litellm|http://localhost:4000|gemini-3-pro" const bypass = "bypass" @@ -19,6 +23,12 @@ function assistantWith(...ids: string[]): OpenAI.Chat.ChatCompletionMessageParam return { role: "assistant", content: null, tool_calls: ids.map(toolCall) } } +function readThoughtSignature(toolCalls: readonly unknown[] | null | undefined): string | undefined { + const reader = new ThoughtSignatureReader() + reader.update(toolCalls) + return reader.signature +} + describe("readThoughtSignature", () => { it("returns the first signature in provider_specific_fields", () => { const toolCalls = [ @@ -30,8 +40,39 @@ describe("readThoughtSignature", () => { expect(readThoughtSignature(toolCalls)).toBe(signature) }) + it.each([64, 200, 2000])("preserves an ID-only signature of length %i", (length) => { + const signature = "+/Aa".repeat(length / 4) + "==" + expect(readThoughtSignature([{ id: `call_1__thought__${signature}` }])).toBe(signature) + }) + + it("prefers explicit fields over the encoded ID", () => { + expect( + readThoughtSignature([ + { id: "call_1__thought__old", provider_specific_fields: { thought_signature: "real" } }, + ]), + ).toBe("real") + }) + + it.each([ + { + calls: [ + { id: "call_1__thought__encoded" }, + { provider_specific_fields: { thought_signature: "explicit" } }, + ], + expected: "explicit", + }, + { calls: [{ id: "call_1__thought__first" }, { id: "call_2__thought__second" }], expected: "first" }, + { calls: [{ id: "call_1__thought__" }, { id: "call_2__thought__second" }], expected: "second" }, + ])("selects $expected from ordered signature sources", ({ calls, expected }) => { + expect(readThoughtSignature(calls)).toBe(expected) + }) + it.each([ ["no tool calls", undefined], + ["a null call", [null]], + ["a non-string ID", [{ id: 42 }]], + ["an unsigned ID", [{ id: "call_1" }]], + ["an empty encoded signature", [{ id: "call_1__thought__" }]], ["null tool calls", null], ["no provider_specific_fields", [{ index: 0 }]], ["an empty signature", [{ index: 0, provider_specific_fields: { thought_signature: "" } }]], @@ -41,6 +82,36 @@ describe("readThoughtSignature", () => { }) }) +describe("ThoughtSignatureReader stream priority property", () => { + // Mirrors StreamSignaturePriority: the first explicit field wins, or the first ID if no field exists. + const candidates = [ + { source: "none", value: undefined, call: {} }, + ...["a", "b"].flatMap((value) => [ + { source: "encoded", value, call: { id: `call_1__thought__${value}` } }, + { source: "explicit", value, call: { provider_specific_fields: { thought_signature: value } } }, + ]), + ] + const streams = candidates.flatMap((a) => + candidates.flatMap((b) => candidates.map((c) => ({ sources: [a, b, c] }))), + ) + + it.each(streams)("selects by source priority for $sources", ({ sources }) => { + const reader = new ThoughtSignatureReader() + reader.update(undefined) + expect(reader.signature).toBeUndefined() + for (let count = 1; count <= sources.length; count++) { + const prefix = sources.slice(0, count) + const expected = + prefix.find((candidate) => candidate.source === "explicit")?.value ?? + prefix.find((candidate) => candidate.source === "encoded")?.value + reader.update([sources[count - 1].call]) + expect(reader.signature).toBe(expected) + reader.update(null) + expect(reader.signature).toBe(expected) + } + }) +}) + describe("thoughtSignatureOrigin", () => { const origin = thoughtSignatureOrigin("http://localhost:4000", "gemini-3-pro") @@ -154,3 +225,150 @@ describe("applyThoughtSignatures", () => { expect(applyThoughtSignatures([], messages, { origin, fallback: () => bypass })).toEqual(messages) }) }) + +describe("proxy signature round trip property", () => { + const cases = [1, 16, 64, 200, 2000].flatMap((length) => + [false, true].flatMap((explicit) => + [false, true].flatMap((truncate) => [false, true].map((r1) => ({ length, explicit, truncate, r1 }))), + ), + ) + it.each(cases)( + "delivers signature length=$length explicit=$explicit truncate=$truncate r1=$r1", + ({ length, explicit, truncate, r1 }) => { + const normalizeToolCallId = truncate ? sanitizeOpenAiCallId : (id: string) => id + const signature = "+/Aa".repeat(length) + "==" + const id = `call_1__thought__${signature}` + const received = readThoughtSignature([ + { id, ...(explicit ? { provider_specific_fields: { thought_signature: signature } } : {}) }, + ]) + expect(received).toBe(signature) + const storedId = sanitizeToolUseId(id) + const history = [ + signedAssistantMessage([storedId], { + signature: received, + origin, + leadingBlocks: [{ type: "reasoning", text: "unsigned" }], + }), + toolResultsMessage([storedId]), + ] + const request = applyThoughtSignatures( + history, + (r1 ? convertToR1Format : convertToOpenAiMessages)(history, { normalizeToolCallId }), + { + origin, + normalizeToolCallId, + }, + ) + expect(request[0]).toMatchObject({ tool_calls: [signed(normalizeToolCallId(storedId), signature)] }) + expect(request[0]).not.toHaveProperty("reasoning_content") + expect(request[1]).toMatchObject({ tool_call_id: normalizeToolCallId(storedId) }) + }, + ) + + it("keeps unsigned provider reasoning", () => { + const message = { + role: "assistant" as const, + content: "", + tool_calls: [toolCall("call_1")], + reasoning_content: "DeepSeek reasoning", + } + expect(applyThoughtSignatures([], [message], { origin })).toEqual([message]) + }) +}) + +// NoForeignEncodedSignature: foreign signature bytes must leave neither through fields nor through IDs. +describe("origin isolation property", () => { + const encodedCanary = "EncodedSuffixCanaryA91Z" + const cases = [undefined, origin, "foreign"].flatMap((storedOrigin) => + [1, 100].flatMap((prefixLength) => + [false, true].flatMap((truncate) => + [false, true].flatMap((r1) => + [false, true].map((useFallback) => ({ storedOrigin, prefixLength, truncate, r1, useFallback })), + ), + ), + ), + ) + it.each(cases)( + "isolates $storedOrigin with prefix=$prefixLength truncate=$truncate r1=$r1 fallback=$useFallback", + ({ storedOrigin, prefixLength, truncate, r1, useFallback }) => { + const prefix = "call_" + "x".repeat(prefixLength) + const ids = [encodedCanary, encodedCanary + "second"].map((value) => + sanitizeToolUseId(`${prefix}__thought__${value}`), + ) + const history = [signedAssistantMessage(ids, { origin: storedOrigin }), toolResultsMessage(ids)] + const normalizeToolCallId = truncate ? sanitizeOpenAiCallId : (id: string) => id + const converted = r1 + ? convertToR1Format(history, { normalizeToolCallId }) + : convertToOpenAiMessages(history, { normalizeToolCallId }) + const before = structuredClone(converted) + const result = applyThoughtSignatures(history, converted, { + origin, + normalizeToolCallId, + fallback: useFallback ? () => bypass : undefined, + }) + const assistant = result.find((message) => message.role === "assistant") + const calls = assistant?.role === "assistant" ? (assistant.tool_calls ?? []) : [] + expect(calls).toHaveLength(2) + expect(new Set(calls.map((call) => call.id)).size).toBe(2) + expect(result.filter((message) => message.role === "tool").map((message) => message.tool_call_id)).toEqual( + calls.map((call) => call.id), + ) + if (storedOrigin === origin) { + expect(calls.map((call) => call.id)).toEqual(ids.map((id) => normalizeToolCallId(id))) + expect(calls[0]).toMatchObject({ provider_specific_fields: { thought_signature: signature } }) + } else { + expect(JSON.stringify(result)).not.toContain("__thought__") + expect(JSON.stringify(result)).not.toContain(signature) + const outgoingIds = [ + ...calls.map((call) => call.id), + ...result.filter((message) => message.role === "tool").map((message) => message.tool_call_id), + ] + expect(outgoingIds).not.toContainEqual(expect.stringContaining(encodedCanary)) + for (const call of calls) { + if (useFallback) + expect(call).toMatchObject({ provider_specific_fields: { thought_signature: bypass } }) + else expect(call).not.toHaveProperty("provider_specific_fields") + } + } + expect(converted).toEqual(before) + }, + ) +}) + +// OccurrenceSignaturesPreserved: reused IDs must keep each turn's own signature and result mapping. +describe("reused call ID property", () => { + const cases = [false, true].flatMap((r1) => + [false, true].flatMap((encoded) => + [undefined, "first"].flatMap((first) => + [undefined, "second"].map((second) => ({ r1, encoded, first, second })), + ), + ), + ) + it.each(cases)( + "keeps occurrences for r1=$r1 encoded=$encoded signatures=$first/$second", + ({ r1, encoded, first, second }) => { + const id = encoded ? "call_1__thought__EncodedCanary" : "call_1" + const assistant = (value: string | undefined) => + value + ? signedAssistantMessage([id], { origin, signature: value }) + : { + role: "assistant" as const, + content: [{ type: "tool_use" as const, id, name: "read_file", input: {} }], + } + const history = [assistant(first), toolResultsMessage([id]), assistant(second), toolResultsMessage([id])] + const converted = r1 ? convertToR1Format(history) : convertToOpenAiMessages(history) + const result = applyThoughtSignatures(history, converted, { origin }) + const calls = result.flatMap((message) => (message.role === "assistant" ? (message.tool_calls ?? []) : [])) + expect(calls).toHaveLength(2) + for (const [index, expected] of [first, second].entries()) { + if (expected) + expect(calls[index]).toMatchObject({ provider_specific_fields: { thought_signature: expected } }) + else expect(calls[index]).not.toHaveProperty("provider_specific_fields") + if (encoded && !expected) expect(calls[index].id).not.toContain("EncodedCanary") + } + expect(result.filter((message) => message.role === "tool").map((message) => message.tool_call_id)).toEqual( + calls.map((call) => call.id), + ) + }, + ) +}) diff --git a/src/api/providers/utils/thought-signature.ts b/src/api/providers/utils/thought-signature.ts index 3b84ab0a840..8ff27e331ed 100644 --- a/src/api/providers/utils/thought-signature.ts +++ b/src/api/providers/utils/thought-signature.ts @@ -25,40 +25,77 @@ function signatureOf(toolCall: unknown): string | undefined { : undefined } -/** - * Read the thought signature from `provider_specific_fields` of tool calls, the slot that - * LiteLLM fills for Gemini. LiteLLM also embeds it in the tool call id, but the history - * sanitizes ids, so the id copy does not survive. - */ -export function readThoughtSignature(toolCalls: readonly unknown[] | null | undefined): string | undefined { - return toolCalls?.map(signatureOf).find((signature) => signature !== undefined) +/** Keep the first explicit signature, or the first ID fallback, across response chunks. */ +export class ThoughtSignatureReader { + private explicit: string | undefined + private encoded: string | undefined + + get signature(): string | undefined { + return this.explicit ?? this.encoded + } + + update(toolCalls: readonly unknown[] | null | undefined): void { + if (this.explicit !== undefined) return + for (const call of toolCalls ?? []) { + this.explicit = signatureOf(call) + if (this.explicit !== undefined) return + // Keep looking for an explicit field after an ID fallback, including in later chunks. + if (this.encoded !== undefined) continue + if (typeof call !== "object" || call === null || !("id" in call) || typeof call.id !== "string") continue + const marker = call.id.indexOf(LITELLM_THOUGHT_SIGNATURE_ID_MARKER) + if (marker < 0) continue + const signature = call.id.slice(marker + LITELLM_THOUGHT_SIGNATURE_ID_MARKER.length) + if (signature) this.encoded = signature + } + } } -function collectThoughtSignatures( +interface ToolCallReplay { + id: string + signature?: string +} + +interface ToolCallReplayCursor { + occurrences: ToolCallReplay[] + next: number +} + +function collectToolCallReplay( history: Anthropic.Messages.MessageParam[], origin: string, normalizeToolCallId: (id: string) => string, -): Map { - const signatureByToolCallId = new Map() +): Map { + const calls = new Map() for (const message of history) { - if (message.role !== "assistant" || !Array.isArray(message.content)) { - continue - } + if (message.role !== "assistant" || !Array.isArray(message.content)) continue let signature: string | undefined - let firstToolUseId: string | undefined + const toolUseIds: string[] = [] const blocks: readonly ExtendedContentBlockParam[] = message.content for (const block of blocks) { if (isThoughtSignatureContentBlock(block)) { signature = block.origin === origin ? block.thoughtSignature : undefined } else if (block.type === "tool_use") { - firstToolUseId ??= block.id + toolUseIds.push(block.id) } } - if (signature && firstToolUseId) { - signatureByToolCallId.set(normalizeToolCallId(firstToolUseId), signature) + for (const [index, id] of toolUseIds.entries()) { + const marker = id.indexOf(LITELLM_THOUGHT_SIGNATURE_ID_MARKER) + // Remove foreign signature bytes before normalization can truncate or hash the ID. + // Keep calls with the same prefix distinct after removing their signature suffixes. + const outgoingId = + !signature && marker >= 0 + ? `${id.slice(0, marker) || "call"}_${createHash("sha256").update(id).digest("hex").slice(0, 16)}` + : id + const key = normalizeToolCallId(id) + const replay = calls.get(key) ?? { occurrences: [], next: 0 } + replay.occurrences.push({ + id: normalizeToolCallId(outgoingId), + ...(index === 0 && signature ? { signature } : {}), + }) + calls.set(key, replay) } } - return signatureByToolCallId + return calls } interface ApplyThoughtSignaturesOptions { @@ -80,20 +117,36 @@ export function applyThoughtSignatures( openAiMessages: OpenAI.Chat.ChatCompletionMessageParam[], { origin, normalizeToolCallId = (id) => id, fallback }: ApplyThoughtSignaturesOptions, ): OpenAI.Chat.ChatCompletionMessageParam[] { - const storedSignatures = collectThoughtSignatures(history, origin, normalizeToolCallId) + const replayByToolCallId = collectToolCallReplay(history, origin, normalizeToolCallId) return openAiMessages.map((message) => { + if (message.role === "tool") { + const replay = replayByToolCallId.get(message.tool_call_id) + const id = replay?.occurrences[replay.next - 1]?.id ?? message.tool_call_id + return id === message.tool_call_id ? message : { ...message, tool_call_id: id } + } if (message.role !== "assistant" || !message.tool_calls?.length) { return message } - return { + let signed = false + const toolCalls = message.tool_calls.map((toolCall) => { + const replay = replayByToolCallId.get(toolCall.id) + const stored = replay?.occurrences[replay.next] + if (replay && stored) replay.next++ + const signature = stored?.signature ?? fallback?.(toolCall.id) + const id = stored?.id ?? toolCall.id + signed ||= Boolean(signature) + if (signature) { + return { ...toolCall, id, provider_specific_fields: { thought_signature: signature } } + } + return id === toolCall.id ? toolCall : { ...toolCall, id } + }) + const result: OpenAI.Chat.ChatCompletionAssistantMessageParam & { reasoning_content?: string } = { ...message, - tool_calls: message.tool_calls.map((toolCall) => { - const signature = storedSignatures.get(toolCall.id) ?? fallback?.(toolCall.id) - return signature - ? { ...toolCall, provider_specific_fields: { thought_signature: signature } } - : toolCall - }), + tool_calls: toolCalls, } + // LiteLLM can turn this text into an unsigned Gemini thought part. + if (signed) delete result.reasoning_content + return result }) } diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 98b1e177376..0dc093d8fc6 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -145,6 +145,9 @@ import { MessageManager } from "../message-manager" import { validateAndFixToolResultIds } from "./validateToolResultIds" import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages" import { prepareApiConversationMessage } from "./apiConversationHistory" +import { waitForThoughtSignatureDrain } from "./thoughtSignatureDrain" +import { detachOnAbort } from "../../api/providers/utils/abort-signal" +import { getApiRequestTimeout } from "../../api/providers/utils/timeout-config" import { shouldAddUserMessageToHistory } from "./messageCounting" import { type TaskExecutionContext } from "./providerHandoff" import { abort, abortReason, initialRunState, type Ask, type RunEvent, type RunState } from "./run-state/runState" @@ -1442,7 +1445,11 @@ export class Task extends EventEmitter implements TaskLike { * Appends an API turn and records whether an assistant turn reached persistent storage. * If the message resolves a pending action, retries the save on initial failure before clearing the action. */ - private async addToApiConversationHistory(message: Anthropic.MessageParam, reasoning?: string): Promise { + private async addToApiConversationHistory( + message: Anthropic.MessageParam, + reasoning?: string, + source = { api: this.api, apiConfiguration: this.apiConfiguration }, + ): Promise { const resolvesPendingAction = this.pendingAction && message.role === "user" && @@ -1454,8 +1461,8 @@ export class Task extends EventEmitter implements TaskLike { prepareApiConversationMessage({ message, reasoning, - api: this.api, - apiConfiguration: this.apiConfiguration, + api: source.api, + apiConfiguration: source.apiConfiguration, apiConversationHistory: this.apiConversationHistory, }), ) @@ -4291,6 +4298,8 @@ export class Task extends EventEmitter implements TaskLike { // Yields only if the first chunk is successful, otherwise will // allow the user to retry the request (most likely due to rate // limit error, which gets thrown on the first chunk). + const requestApi = this.api + const requestApiConfiguration = { ...this.apiConfiguration } const stream = this.attemptApiRequest(currentItem.retryAttempt ?? 0, { skipProviderRateLimit: true, requestModelInfo: streamModelInfo, @@ -4303,31 +4312,10 @@ export class Task extends EventEmitter implements TaskLike { try { const iterator = stream[Symbol.asyncIterator]() - // Helper to race iterator.next() with abort signal - const nextChunkWithAbort = async () => { - const nextPromise = iterator.next() - - // If we have an abort controller, race it with the next chunk - if (this.currentRequestAbortController) { - const abortPromise = new Promise((_, reject) => { - const signal = this.currentRequestAbortController!.signal - if (signal.aborted) { - reject(new Error("Request cancelled by user")) - } else { - signal.addEventListener( - "abort", - () => { - reject(new Error("Request cancelled by user")) - }, - { once: true }, - ) - } - }) - return await Promise.race([nextPromise, abortPromise]) - } - - // No abort controller, just return the next chunk normally - return await nextPromise + const nextChunkWithAbort = () => { + const pending = iterator.next() + const signal = this.currentRequestAbortController?.signal + return signal ? detachOnAbort(pending, signal) : pending } let item = await nextChunkWithAbort() @@ -4709,15 +4697,16 @@ export class Task extends EventEmitter implements TaskLike { } } + let usageFound = false + let chunkCount = 0 try { - // Continue processing the original stream from where the main loop left off - let usageFound = false - let chunkCount = 0 - // Use the same iterator that the main loop was using while (!item.done) { // Check for timeout - if (performance.now() - startTime > timeoutMs) { + if ( + !requestApi.requiresThoughtSignatureDrain && + performance.now() - startTime > timeoutMs + ) { console.warn( `[Background Usage Collection] Timed out after ${timeoutMs}ms for model: ${modelId}, processed ${chunkCount} chunks`, ) @@ -4729,7 +4718,9 @@ export class Task extends EventEmitter implements TaskLike { } const chunk = item.value - item = await iterator.next() + item = await (requestApi.requiresThoughtSignatureDrain + ? nextChunkWithAbort() + : iterator.next()) chunkCount++ if (chunk && chunk.type === "usage") { @@ -4743,67 +4734,63 @@ export class Task extends EventEmitter implements TaskLike { bgTotalCost = chunk.totalCost } } - - if ( - usageFound || - bgInputTokens > 0 || - bgOutputTokens > 0 || - bgCacheWriteTokens > 0 || - bgCacheReadTokens > 0 - ) { - // We have usage data either from a usage chunk or accumulated tokens - await captureUsageData( - { - input: bgInputTokens, - output: bgOutputTokens, - cacheWrite: bgCacheWriteTokens, - cacheWrite1h: bgCacheWrite1hTokens, - cacheWrite12h: bgCacheWrite12hTokens, - cacheRead: bgCacheReadTokens, - total: bgTotalCost, - }, - lastApiReqIndex, - status, - ) - } else { - console.warn( - `[Background Usage Collection] Suspicious: request ${apiReqIndex} is complete, but no usage info was found. Model: ${modelId}`, - ) - } - } catch (error) { - console.error("Error draining stream for usage data:", error) - // Still try to capture whatever usage data we have collected so far - if ( - bgInputTokens > 0 || - bgOutputTokens > 0 || - bgCacheWriteTokens > 0 || - bgCacheReadTokens > 0 - ) { - await captureUsageData( - { - input: bgInputTokens, - output: bgOutputTokens, - cacheWrite: bgCacheWriteTokens, - cacheWrite1h: bgCacheWrite1hTokens, - cacheWrite12h: bgCacheWrite12hTokens, - cacheRead: bgCacheReadTokens, - total: bgTotalCost, - }, - lastApiReqIndex, - status, - ) + } finally { + // Only stream consumption controls history readiness. Usage reporting stays independent. + const reportUsage = async () => { + if ( + !usageFound && + bgInputTokens <= 0 && + bgOutputTokens <= 0 && + bgCacheWriteTokens <= 0 && + bgCacheReadTokens <= 0 + ) { + console.warn( + `[Background Usage Collection] Suspicious: request ${apiReqIndex} is complete, but no usage info was found. Model: ${modelId}`, + ) + return + } + const tokens = { + input: bgInputTokens, + output: bgOutputTokens, + cacheWrite: bgCacheWriteTokens, + cacheWrite1h: bgCacheWrite1hTokens, + cacheWrite12h: bgCacheWrite12hTokens, + cacheRead: bgCacheReadTokens, + total: bgTotalCost, + } + for (let attempt = 0; attempt < 2; attempt++) { + try { + await captureUsageData(tokens, lastApiReqIndex, status) + return + } catch (error) { + console.error("Error reporting stream usage:", error) + } + } } + void reportUsage().catch((error) => + console.error("Background usage reporting failed:", error), + ) } } - // Start the background task and handle any errors + // One boundary handles drain failures. Usage reporting has its own detached boundary. // Pass "cancelled" status if the task was aborted by the user - drainStreamInBackgroundToFindAllUsage( + const requestAbortController = this.currentRequestAbortController + const streamDrain = drainStreamInBackgroundToFindAllUsage( lastApiReqIndex, this.abort ? "cancelled" : "completed", ).catch((error) => { console.error("Background usage collection failed:", error) + if (requestApi.requiresThoughtSignatureDrain) throw error }) + // Proxy signatures can arrive after a tool stops the main loop. Save only after the drain settles. + if (requestApi.requiresThoughtSignatureDrain) { + await waitForThoughtSignatureDrain(streamDrain, { + timeoutMs: getApiRequestTimeout(), + signal: requestAbortController?.signal, + onTimeout: (error) => requestAbortController?.abort(error), + }) + } } catch (error) { // Close the request generator so its `finally` releases the API // work it holds (a replaced handler is disposed once nothing uses @@ -4830,6 +4817,71 @@ export class Task extends EventEmitter implements TaskLike { // A cancel can land during abortStream after cancelReason was computed; setAbortReason keeps the first reason. this.setAbortReason("user_cancelled") await this.abortTask() + } else if ( + this.assistantMessageContent.some( + (block) => + (block.type === "tool_use" || block.type === "mcp_tool_use") && !block.partial, + ) + ) { + // Release completion and delegation waits before joining the presenter for this failed turn. + this.cancelAssistantMessagePersistence() + this.isStreaming = false + await pWaitFor( + () => this.dispatchState === DispatchState.IDLE || this.abort || this.abandoned, + { interval: 100 }, + ) + if (this.abort || this.abandoned) return true + + // All tool messages have settled. A protected ask requires a fresh reply. + await this.say( + "error", + "Automatic retry stopped because a tool may have already run. Check the tool results before you continue.", + ) + const recovery = await this.ask("resume_task", undefined, false, undefined, true) + if (recovery.response !== "yesButtonClicked" && recovery.response !== "messageResponse") { + await this.abortTask() + return true + } + const interruptedTools = this.assistantMessageContent.flatMap((block) => { + if ((block.type !== "tool_use" && block.type !== "mcp_tool_use") || block.partial) + return [] + const result = this.userMessageContent.find( + (result): result is Anthropic.ToolResultBlockParam => + result.type === "tool_result" && + block.id !== undefined && + result.tool_use_id === sanitizeToolUseId(block.id), + ) + return [ + { + tool: block.name, + parameters: + block.type === "mcp_tool_use" + ? block.arguments + : (block.nativeArgs ?? block.params), + result: + result?.content ?? + "No result was recorded. Check the current state before further actions.", + }, + ] + }) + if (recovery.text || recovery.images?.length) { + await this.say("user_feedback", recovery.text, recovery.images) + } + // Use a fresh text context. The incomplete assistant turn and its protocol tool calls cannot be replayed. + stack.push({ + userContent: [ + { + type: "text", + text: `The previous response failed after these tool calls may have run. Do not repeat them. Check their results before further actions.\n${JSON.stringify(interruptedTools)}`, + }, + ...this.userMessageContent.filter((block) => block.type !== "tool_result"), + { type: "text", text: recovery.text || "Continue from the verified tool results." }, + ...formatResponse.imageBlocks(recovery.images), + ], + includeFileDetails: false, + retryAttempt: 0, + }) + continue } else if (error instanceof OutputTokenLimitError) { // Truncation repeats on an identical request, so never auto-retry it // (even with auto-approval); let the user decide once. @@ -5176,6 +5228,7 @@ export class Task extends EventEmitter implements TaskLike { await this.addToApiConversationHistory( { role: "assistant", content: assistantContent }, reasoningMessage || undefined, + { api: requestApi, apiConfiguration: requestApiConfiguration }, ) this.messageCounts.assistant++ diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 8a7bffa7dc7..05264e7b778 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -1,6 +1,8 @@ import { WebviewFocusTracker } from "../../webview/WebviewFocusTracker" // npx vitest core/task/__tests__/Task.spec.ts +import { getEventListeners } from "node:events" + import { DispatchState } from "../dispatchState" import * as fsReal from "fs" import * as os from "os" @@ -13,6 +15,7 @@ import type { Mock } from "vitest" import { providerIdentifiers, RooCodeEventName, + TaskStatus, type ClineMessage, type GlobalState, type HistoryItem, @@ -30,6 +33,10 @@ import { summarizeConversation } from "../../condense" import { getEnvironmentDetails } from "../../environment/getEnvironmentDetails" import { ClineProvider } from "../../webview/ClineProvider" import { ApiStreamChunk } from "../../../api/transform/stream" +import { ThoughtSignatureReader, applyThoughtSignatures } from "../../../api/providers/utils/thought-signature" +import { convertToOpenAiMessages } from "../../../api/transform/openai-format" +import { toolResultsMessage } from "../../../test-utils/thought-signature" +import * as timeoutConfig from "../../../api/providers/utils/timeout-config" import { OutputTokenLimitError } from "../../../api/providers/utils/output-token-limit-error" import { ContextProxy } from "../../config/ContextProxy" import { parseMentions } from "../../mentions" @@ -40,6 +47,7 @@ import { asyncStreamFrom } from "../../../test-utils/stream" import { McpHub } from "../../../services/mcp/McpHub" import { McpServerManager } from "../../../services/mcp/McpServerManager" import { readFileTool } from "../../tools/ReadFileTool" +import { attemptCompletionTool } from "../../tools/AttemptCompletionTool" import { writeToFileTool } from "../../tools/WriteToFileTool" import { manageContext } from "../../context-management" @@ -467,8 +475,9 @@ describe("Cline", () => { })() } - async function createTaskWithManualRetries() { + async function createTaskWithManualRetries(parentTask?: Task) { const task = new Task({ + parentTask, provider: mockProvider, apiConfiguration: mockApiConfig, task: "test task", @@ -2060,6 +2069,56 @@ describe("Cline", () => { }) } + it.each(["success", "failure", "cancel-before", "cancel-during"] as const)( + "cleans up stream-read listeners and preserves cancellation on %s", + async (outcome) => { + const task = await createTaskWithManualRetries() + const state = await mockProvider.getState() + vi.mocked(mockProvider.getState).mockResolvedValue({ ...state, autoApprovalEnabled: true }) + Object.assign(task.api, { requiresThoughtSignatureDrain: true }) + const controller = new AbortController() + const reason = new Error("Request-specific cancellation reason") + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let notifyPending!: () => void + const pending = new Promise((resolve) => { + notifyPending = resolve + }) + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + task.currentRequestAbortController = controller + if (outcome === "cancel-before") controller.abort(reason) + yield { type: "text", text: "first" } + if (outcome === "success" || outcome === "failure") task.didRejectTool = true + yield { type: "text", text: "buffered" } + if (outcome === "cancel-during") { + notifyPending() + await gate + } + if (outcome === "failure") throw new Error("Read failed") + }, + ) + realRequestsThenStop(task) + const backoff = vi.spyOn(getTaskTestAccess(task), "backoffAndAnnounce").mockResolvedValue(undefined) + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = task.recursivelyMakeClineRequests([{ type: "text", text: "go" }]) + try { + if (outcome === "cancel-during") { + await pending + controller.abort(reason) + } + await loop + expect(getEventListeners(controller.signal, "abort")).toHaveLength(0) + if (outcome.startsWith("cancel")) expect(backoff.mock.calls[0]?.[1]).toBe(reason) + } finally { + release() + await loop + } + }, + ) + it("closes a stream whose read failed, releasing the replaced handler (stream.return())", async () => { const task = await createTaskWithManualRetries() const oldDispose = disposableApi(task) @@ -2136,6 +2195,494 @@ describe("Cline", () => { expect(oldDispose).toHaveBeenCalledOnce() }) + it.each([ + { lateExplicit: true, pastUsageLimit: false, replaceHandler: false }, + { lateExplicit: false, pastUsageLimit: false, replaceHandler: false }, + { lateExplicit: true, pastUsageLimit: true, replaceHandler: false }, + { lateExplicit: false, pastUsageLimit: true, replaceHandler: false }, + { lateExplicit: true, pastUsageLimit: false, replaceHandler: true }, + ])( + "settles signatures before save (explicit=$lateExplicit pastUsageLimit=$pastUsageLimit replaceHandler=$replaceHandler)", + async ({ lateExplicit, pastUsageLimit, replaceHandler }) => { + const task = await createTaskWithManualRetries() + task.apiConfiguration = { apiProvider: providerIdentifiers.openai, openAiModelId: "gemini-3-flash" } + const reader = new ThoughtSignatureReader() + Object.assign(task.api, { + requiresThoughtSignatureDrain: true, + getThoughtSignature: () => reader.signature, + getThoughtSignatureOrigin: () => "proxy", + }) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let notifyDraining!: () => void + const draining = new Promise((resolve) => { + notifyDraining = resolve + }) + vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {}) + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + if (lateExplicit) reader.update([{ id: "call_1__thought__encoded" }]) + yield { type: "text", text: "Read the file." } + task.assistantMessageContent.push({ + type: "tool_use", + id: "call_1", + name: "read_file", + params: { path: "a.ts" }, + nativeArgs: { path: "a.ts" }, + partial: false, + }) + task.didRejectTool = true + yield { type: "text", text: "buffered" } + notifyDraining() + await gate + yield { type: "text", text: "late buffered chunk" } + if (!lateExplicit) reader.update([{ id: "call_1__thought__encoded" }]) + if (lateExplicit) + reader.update([{ provider_specific_fields: { thought_signature: "explicit" } }]) + yield { type: "usage", inputTokens: 1, outputTokens: 1 } + }, + ) + realRequestsThenStop(task) + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = task.recursivelyMakeClineRequests([{ type: "text", text: "go" }]) + await draining + if (replaceHandler) { + task.updateApiConfiguration({ ...mockApiConfig }) + Object.assign(task.api, { + getThoughtSignature: () => "replacement", + getThoughtSignatureOrigin: () => "replacement", + }) + } + const clock = pastUsageLimit + ? vi.spyOn(performance, "now").mockReturnValue(performance.now() + 6_001) + : undefined + try { + await new Promise((resolve) => setTimeout(resolve, 250)) + expect( + task.apiConversationHistory.filter((message) => message.role === "assistant"), + ).toHaveLength(0) + } finally { + release() + await loop + clock?.mockRestore() + } + const saved = task.apiConversationHistory.find((message) => message.role === "assistant") + expect(saved).toBeDefined() + if (!saved) throw new Error("Expected the saved assistant turn") + expect(saved.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "thoughtSignature", origin: "proxy" }), + ]), + ) + const history = [saved, toolResultsMessage(["call_1"])] + const replay = applyThoughtSignatures(history, convertToOpenAiMessages(history), { + origin: "proxy", + }) + expect(replay[0]).toMatchObject({ + tool_calls: [ + { provider_specific_fields: { thought_signature: lateExplicit ? "explicit" : "encoded" } }, + ], + }) + }, + ) + + it.each(["once", "always", "stalled"] as const)( + "preserves a completed turn when usage reporting is %s", + async (reporting) => { + const task = await createTaskWithManualRetries() + task.apiConfiguration = { apiProvider: providerIdentifiers.openai, openAiModelId: "gemini-3-flash" } + Object.assign(task.api, { + requiresThoughtSignatureDrain: true, + getThoughtSignature: () => "completed-signature", + getThoughtSignatureOrigin: () => "proxy", + }) + let consumed = false + vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {}) + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + yield { type: "text", text: "The request completed." } + yield { type: "usage", inputTokens: 1, outputTokens: 1, totalCost: 0.125 } + consumed = true + }, + ) + const requests = realRequestsThenStop(task) + const telemetry = vi.spyOn(TelemetryService.instance, "captureLlmCompletion") + const error = new Error("Usage reporting failed") + let releaseReporting!: () => void + const reportingGate = new Promise((resolve) => { + releaseReporting = resolve + }) + let notifyReporting!: () => void + const reportingStarted = new Promise((resolve) => { + notifyReporting = resolve + }) + let attempts = 0 + const update = task["updateClineMessage"].bind(task) + vi.spyOn(getTaskTestAccess(task), "updateClineMessage").mockImplementation(async (message) => { + if (consumed && message.say === "api_req_started") { + attempts++ + notifyReporting() + if (reporting === "stalled") await reportingGate + if (reporting === "always" || (reporting === "once" && attempts === 1)) throw error + } + await update(message) + }) + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = task.recursivelyMakeClineRequests([{ type: "text", text: "go" }]) + await reportingStarted + try { + await vi.waitFor(() => + expect( + task.apiConversationHistory.filter((message) => message.role === "assistant"), + ).toHaveLength(1), + ) + await loop + expect(requests.mock.calls[1]?.[0]).toBe(0) + if (reporting !== "stalled") { + await vi.waitFor(() => expect(attempts).toBe(2)) + if (reporting === "once") { + await vi.waitFor(() => + expect(telemetry).toHaveBeenCalledWith(task.taskId, { + inputTokens: 1, + outputTokens: 1, + cacheWriteTokens: 0, + cacheReadTokens: 0, + cost: 0.125, + }), + ) + } + } + const saved = task.apiConversationHistory.find((message) => message.role === "assistant") + expect(saved?.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "thoughtSignature", + thoughtSignature: "completed-signature", + origin: "proxy", + }), + ]), + ) + } finally { + releaseReporting() + await loop + } + }, + ) + + it.each([ + { failure: "failure", pending: false, reply: "message" }, + { failure: "deadline", pending: false, reply: "message" }, + { failure: "failure", pending: true, reply: "message" }, + { failure: "deadline", pending: true, reply: "message" }, + { failure: "failure", pending: false, reply: "button" }, + { failure: "failure", pending: false, reply: "decline" }, + { failure: "late-error", pending: true, reply: "message" }, + ])( + "offers recovery after $failure, pending tool: $pending, reply: $reply", + async ({ failure, pending, reply }) => { + const task = await createTaskWithManualRetries() + const state = await mockProvider.getState() + vi.mocked(mockProvider.getState).mockResolvedValue({ ...state, autoApprovalEnabled: true }) + Object.assign(task.api, { requiresThoughtSignatureDrain: true }) + vi.spyOn(timeoutConfig, "getApiRequestTimeout").mockReturnValue(25) + vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo) + let finishTool!: () => void + const toolGate = new Promise((resolve) => { + finishTool = resolve + }) + const executeTool = vi + .spyOn(writeToFileTool, "handle") + .mockClear() + .mockImplementation(async (_task, _block, callbacks) => { + if (pending) await toolGate + if (failure === "late-error") { + await callbacks.handleError( + "writing file", + new Error("Write completed but its final step failed"), + ) + return + } + callbacks.pushToolResult("Written") + }) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let turns = 0 + const { default: realPWaitFor } = await vi.importActual("p-wait-for") + vi.mocked(pWaitFor).mockImplementation(realPWaitFor) + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + if (turns++ > 0) { + yield { type: "text", text: "Recovery continued." } + return + } + getTaskTestAccess(task).requestPolicySnapshot = { + disabledTools: [], + customModes: [], + modelInfo: stubModelInfo, + } + yield { + type: "tool_call", + id: "call_write", + name: "write_to_file", + arguments: '{"path":"result.md","content":"done"}', + } + yield { type: "text", text: "buffered" } + await vi.waitFor(() => expect(executeTool).toHaveBeenCalledOnce()) + // User feedback can interrupt the stream while the tool is still running. + task.didRejectTool = true + if (reply === "button") + task.messageQueueService.addMessage("A request queued before recovery.") + yield { type: "text", text: "interrupted" } + if (failure === "deadline") await gate + throw new Error("Stream consumption failed") + }, + ) + const requests = realRequestsThenStop(task, 2) + vi.spyOn(getTaskTestAccess(task), "backoffAndAnnounce").mockResolvedValue(undefined) + const say = vi.spyOn(task, "say") + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = getTaskTestAccess(task).initiateTaskLoop([{ type: "text", text: "write the file" }]) + try { + if (pending) { + await vi.waitFor(() => expect(executeTool).toHaveBeenCalledOnce()) + await vi.waitFor(() => expect(task.isStreaming).toBe(false)) + await new Promise((resolve) => setTimeout(resolve, 0)) + finishTool() + } + await vi.waitFor(() => expect(task.taskStatus).toBe(TaskStatus.Resumable), { timeout: 4_000 }) + expect(task.taskAsk?.ask).toBe("resume_task") + expect(task.taskAsk?.isProtected).toBe(true) + expect(task.isStreaming).toBe(false) + expect(executeTool).toHaveBeenCalledOnce() + expect(requests).toHaveBeenCalledOnce() + if (!pending) + expect(task.userMessageContent).toEqual( + expect.arrayContaining([ + expect.objectContaining({ type: "tool_result", tool_use_id: "call_write" }), + ]), + ) + expect(say).toHaveBeenCalledWith("error", expect.stringContaining("Automatic retry stopped")) + if (reply === "decline") { + task.handleWebviewAskResponse("noButtonClicked") + await loop + expect(task.abort).toBe(true) + expect(turns).toBe(1) + expect(requests).toHaveBeenCalledOnce() + return + } + if (reply === "button") { + expect(task.queuedMessages).toHaveLength(1) + task.handleWebviewAskResponse("yesButtonClicked") + } else { + await task.submitUserMessage("The write is verified. Continue with a read-only check.") + } + + await loop + expect(turns).toBe(2) + expect(executeTool).toHaveBeenCalledOnce() + expect(requests.mock.calls[1]?.[0]).toBe(0) + const recovery = task.apiConversationHistory.find( + (message) => + message.role === "user" && + JSON.stringify(message.content).includes( + failure === "late-error" ? "Write completed but its final step failed" : "Written", + ), + ) + expect(recovery?.content).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + type: "text", + text: expect.stringContaining("write_to_file"), + }), + expect.objectContaining({ + type: "text", + text: + reply === "button" + ? "Continue from the verified tool results." + : "The write is verified. Continue with a read-only check.", + }), + ]), + ) + expect( + task.apiConversationHistory + .flatMap((message) => (Array.isArray(message.content) ? message.content : [])) + .some((block) => block.type === "tool_use" || block.type === "tool_result"), + ).toBe(false) + expect( + task.apiConversationHistory.some( + (message) => + message.role === "assistant" && + JSON.stringify(message.content).includes("Recovery continued."), + ), + ).toBe(true) + } finally { + finishTool() + release() + task.requestAbort(false) + await loop + executeTool.mockRestore() + vi.mocked(pWaitFor).mockImplementation(async () => {}) + } + }, + ) + + it.each(["failure", "deadline"] as const)( + "settles child completion before recovery on %s", + async (failure) => { + const parent = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "parent", + startTask: false, + }) + const task = await createTaskWithManualRetries(parent) + Object.assign(task.api, { requiresThoughtSignatureDrain: true }) + vi.spyOn(timeoutConfig, "getApiRequestTimeout").mockReturnValue(25) + const record = await mockProvider.getTaskWithId(task.taskId) + vi.spyOn(mockProvider, "getTaskWithId").mockImplementation(async (id) => { + return { + ...record, + historyItem: { + ...record.historyItem, + status: id === task.taskId ? "active" : "delegated", + awaitingChildId: id === parent.taskId ? task.taskId : undefined, + }, + } + }) + vi.spyOn(mockProvider, "setPendingTaskAction").mockResolvedValue(undefined) + const clear = vi.spyOn(mockProvider, "clearPendingTaskAction").mockResolvedValue(false) + const reopen = vi.spyOn(mockProvider, "reopenParentFromDelegation").mockResolvedValue(false) + const completed = vi.spyOn(mockProvider, "emitDelegatedTaskCompleted").mockImplementation(() => {}) + const execute = vi.spyOn(attemptCompletionTool, "execute").mockClear() + const persistence = vi.spyOn(task, "waitForCurrentAssistantMessagePersistence") + vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo) + const { default: realPWaitFor } = await vi.importActual("p-wait-for") + vi.mocked(pWaitFor).mockImplementation(realPWaitFor) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let turns = 0 + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + if (turns++ > 0) { + yield { type: "text", text: "Recovery continued." } + return + } + getTaskTestAccess(task).requestPolicySnapshot = { + disabledTools: [], + customModes: [], + modelInfo: stubModelInfo, + } + yield { + type: "tool_call", + id: "call_complete", + name: "attempt_completion", + arguments: '{"result":"Child result"}', + } + yield { type: "text", text: "buffered" } + await vi.waitFor(() => expect(persistence).toHaveBeenCalledOnce()) + task.didRejectTool = true + yield { type: "text", text: "interrupted" } + if (failure === "deadline") await gate + throw new Error("Stream failed after completion started") + }, + ) + const requests = realRequestsThenStop(task, 2) + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = getTaskTestAccess(task).initiateTaskLoop([{ type: "text", text: "finish the child" }]) + try { + await vi.waitFor(() => expect(task.taskStatus).toBe(TaskStatus.Resumable), { timeout: 4_000 }) + expect(task.dispatchState).toBe(DispatchState.IDLE) + expect(await persistence.mock.results[0]?.value).toBe(false) + expect(task["pendingAction"]?.kind).toBe("finish_subtask") + expect(task["assistantMessageSavedToHistory"]).toBe(false) + expect(clear).not.toHaveBeenCalled() + expect(reopen).not.toHaveBeenCalled() + expect(completed).not.toHaveBeenCalled() + expect(requests).toHaveBeenCalledOnce() + await task.submitUserMessage( + "Review the interrupted completion without completing the child again.", + ) + await loop + expect(turns).toBe(2) + expect(execute).toHaveBeenCalledOnce() + expect(clear).not.toHaveBeenCalled() + expect(reopen).not.toHaveBeenCalled() + expect(completed).not.toHaveBeenCalled() + expect(task["pendingAction"]?.kind).toBe("finish_subtask") + } finally { + release() + task.requestAbort(false) + task["cancelAssistantMessagePersistence"]() + await loop + execute.mockRestore() + vi.mocked(pWaitFor).mockImplementation(async () => {}) + } + }, + ) + + it("keeps a signature stream-consumption failure fatal", async () => { + const task = await createTaskWithManualRetries() + Object.assign(task.api, { requiresThoughtSignatureDrain: true }) + const error = new Error("Stream consumption failed") + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + yield { type: "text", text: "partial" } + task.didRejectTool = true + yield { type: "text", text: "buffered" } + throw error + }, + ) + const requests = realRequestsThenStop(task) + vi.spyOn(console, "error").mockImplementation(() => {}) + await task.recursivelyMakeClineRequests([{ type: "text", text: "go" }]) + expect(task.apiConversationHistory.filter((message) => message.role === "assistant")).toHaveLength(0) + expect(requests.mock.calls[1]?.[0]).toBe(1) + }) + + it("rejects a stalled signature drain without saving an incomplete assistant turn", async () => { + const task = await createTaskWithManualRetries() + Object.assign(task.api, { requiresThoughtSignatureDrain: true }) + vi.spyOn(timeoutConfig, "getApiRequestTimeout").mockReturnValue(25) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let notifyDraining!: () => void + const draining = new Promise((resolve) => { + notifyDraining = resolve + }) + vi.spyOn(getTaskTestAccess(task), "attemptApiRequestWithActiveApi").mockImplementation( + async function* () { + yield { type: "text", text: "partial" } + task.didRejectTool = true + yield { type: "text", text: "buffered" } + notifyDraining() + await gate + yield { type: "usage", inputTokens: 1, outputTokens: 1 } + }, + ) + const requests = realRequestsThenStop(task) + vi.spyOn(console, "error").mockImplementation(() => {}) + const loop = task.recursivelyMakeClineRequests([{ type: "text", text: "go" }]) + await draining + try { + await vi.waitFor(() => expect(requests).toHaveBeenCalledTimes(2), { timeout: 1_000 }) + await loop + expect(task.apiConversationHistory.filter((message) => message.role === "assistant")).toHaveLength( + 0, + ) + } finally { + release() + await loop + } + }) + it("keeps a replaced handler alive until the background usage drain finishes", async () => { const task = await createTaskWithManualRetries() const oldDispose = disposableApi(task) diff --git a/src/core/task/__tests__/thoughtSignatureDrain.spec.ts b/src/core/task/__tests__/thoughtSignatureDrain.spec.ts new file mode 100644 index 00000000000..cd68bd1ced6 --- /dev/null +++ b/src/core/task/__tests__/thoughtSignatureDrain.spec.ts @@ -0,0 +1,66 @@ +import { waitForThoughtSignatureDrain } from "../thoughtSignatureDrain" + +describe("waitForThoughtSignatureDrain", () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + it("clears the deadline after a completed drain", async () => { + const onTimeout = vi.fn() + await waitForThoughtSignatureDrain(Promise.resolve(), { timeoutMs: 20_000, onTimeout }) + expect(vi.getTimerCount()).toBe(0) + expect(onTimeout).not.toHaveBeenCalled() + }) + + it("propagates a drain failure and clears its deadline", async () => { + const error = new Error("stream failed") + const onTimeout = vi.fn() + await expect( + waitForThoughtSignatureDrain(Promise.reject(error), { timeoutMs: 20_000, onTimeout }), + ).rejects.toBe(error) + expect(vi.getTimerCount()).toBe(0) + expect(onTimeout).not.toHaveBeenCalled() + }) + + it("allows a late signature beyond the usage collection window", async () => { + let finish!: () => void + const drain = new Promise((resolve) => { + finish = resolve + }) + const onTimeout = vi.fn() + const waiting = waitForThoughtSignatureDrain(drain, { timeoutMs: 20_000, onTimeout }) + await vi.advanceTimersByTimeAsync(6_001) + expect(onTimeout).not.toHaveBeenCalled() + finish() + await waiting + expect(vi.getTimerCount()).toBe(0) + }) + + it("rejects a stalled drain at the independent deadline", async () => { + const onTimeout = vi.fn() + const waiting = waitForThoughtSignatureDrain(new Promise(() => {}), { timeoutMs: 20_000, onTimeout }) + const rejected = expect(waiting).rejects.toMatchObject({ name: "TimeoutError" }) + await vi.advanceTimersByTimeAsync(19_999) + expect(onTimeout).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + await rejected + expect(onTimeout).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ name: "TimeoutError" })) + expect(vi.getTimerCount()).toBe(0) + }) + + it.each(["before", "during"])("propagates cancellation %s the wait", async (when) => { + const controller = new AbortController() + const reason = new Error("cancelled") + if (when === "before") controller.abort(reason) + const onTimeout = vi.fn() + const waiting = waitForThoughtSignatureDrain(new Promise(() => {}), { + timeoutMs: 20_000, + signal: controller.signal, + onTimeout, + }) + const rejected = expect(waiting).rejects.toBe(reason) + if (when === "during") controller.abort(reason) + await rejected + expect(onTimeout).not.toHaveBeenCalled() + expect(vi.getTimerCount()).toBe(0) + }) +}) diff --git a/src/core/task/thoughtSignatureDrain.ts b/src/core/task/thoughtSignatureDrain.ts new file mode 100644 index 00000000000..b1bb6871766 --- /dev/null +++ b/src/core/task/thoughtSignatureDrain.ts @@ -0,0 +1,19 @@ +import { createTimeoutError, detachOnAbort } from "../../api/providers/utils/abort-signal" + +/** A signature drain must complete or fail before the turn can enter history. */ +export async function waitForThoughtSignatureDrain( + drain: Promise, + { timeoutMs, signal, onTimeout }: { timeoutMs: number; signal?: AbortSignal; onTimeout: (error: Error) => void }, +): Promise { + const deadline = new AbortController() + const timer = setTimeout(() => { + const error = createTimeoutError("Thought signature drain") + deadline.abort(error) + onTimeout(error) + }, timeoutMs) + try { + await detachOnAbort(drain, signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal) + } finally { + clearTimeout(timer) + } +}