diff --git a/docs/architecture/tla/CondenseTruncate.AllBlocks.cfg b/docs/architecture/tla/CondenseTruncate.AllBlocks.cfg new file mode 100644 index 0000000000..6f7ba8b8b7 --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.AllBlocks.cfg @@ -0,0 +1,9 @@ +\* PR 2696 review round 1: the unfixed block clear wipes every tool_result +\* block of the selected message, so a small parallel result is lost. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "AllBlocks" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK DegradationKeepsOtherBlocks diff --git a/docs/architecture/tla/CondenseTruncate.EmptyOK.cfg b/docs/architecture/tla/CondenseTruncate.EmptyOK.cfg new file mode 100644 index 0000000000..043597cf24 --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.EmptyOK.cfg @@ -0,0 +1,9 @@ +\* PR 2696 review round 1: the unfixed size rule treats an empty-content +\* tool result as oversized; clearing it cannot shrink the token count. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "EmptyOK" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK SuccessIsMonotonic diff --git a/docs/architecture/tla/CondenseTruncate.NoPairDeg.cfg b/docs/architecture/tla/CondenseTruncate.NoPairDeg.cfg new file mode 100644 index 0000000000..e61ecaa5c3 --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.NoPairDeg.cfg @@ -0,0 +1,9 @@ +\* Pair sabotage for issue 1254: the degrade step also tags the paired tool +\* use, so the degraded tool result stays live with an orphaned half. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "NoPairDeg" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK DegradationPreservesPair diff --git a/docs/architecture/tla/CondenseTruncate.NoStop.cfg b/docs/architecture/tla/CondenseTruncate.NoStop.cfg new file mode 100644 index 0000000000..2347073e16 --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.NoStop.cfg @@ -0,0 +1,9 @@ +\* PR 2696 review round 6: the unfixed caller resends the unchanged history +\* after an Error round (both request paths loop on the generic retry branch). +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "NoStop" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK ErrStopsRequests diff --git a/docs/architecture/tla/CondenseTruncate.OnlyBig.cfg b/docs/architecture/tla/CondenseTruncate.OnlyBig.cfg new file mode 100644 index 0000000000..39debb0bf8 --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.OnlyBig.cfg @@ -0,0 +1,10 @@ +\* PR 2696 review round 2: the unfixed scan accepts only the first oversized +\* block, so a message whose first block is cleared leaves the scan and the +\* round reports Error while the second block still contributes weight. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "OnlyBig" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK ErrExhaustsCandidates diff --git a/docs/architecture/tla/CondenseTruncate.PreScan.cfg b/docs/architecture/tla/CondenseTruncate.PreScan.cfg new file mode 100644 index 0000000000..772b3debac --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.PreScan.cfg @@ -0,0 +1,9 @@ +\* PR 2696 review round 1: the unfixed degradation scan ignores the +\* latest-summary boundary and can pick a pre-summary tool result. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "PreScan" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK DegSelectionLive diff --git a/docs/architecture/tla/CondenseTruncate.ZeroOK.cfg b/docs/architecture/tla/CondenseTruncate.ZeroOK.cfg new file mode 100644 index 0000000000..adb24def6d --- /dev/null +++ b/docs/architecture/tla/CondenseTruncate.ZeroOK.cfg @@ -0,0 +1,9 @@ +\* The live code before the fix of issue 1254: a zero-removal round reports +\* success with no change. AddToolPair, Recover: oversized history, fake success. +SPECIFICATION Spec +CHECK_DEADLOCK FALSE +CONSTANTS + Mode = "ZeroOK" + MaxMsgs = 7 +CONSTRAINT Bounded +INVARIANTS TypeOK NoZeroProgressSuccess diff --git a/docs/architecture/tla/CondenseTruncate.cfg b/docs/architecture/tla/CondenseTruncate.cfg index 18f4aaa786..0641167f16 100644 --- a/docs/architecture/tla/CondenseTruncate.cfg +++ b/docs/architecture/tla/CondenseTruncate.cfg @@ -4,4 +4,4 @@ CONSTANTS Mode = "Fixed" MaxMsgs = 7 CONSTRAINT Bounded -INVARIANTS TypeOK RemovedIsLive CountExact SelectionMatchesLive SummaryUntagged +INVARIANTS TypeOK RemovedIsLive CountExact SelectionMatchesLive SummaryUntagged SuccessIsMonotonic DegradationPreservesPair DegSelectionLive DegradationKeepsOtherBlocks NoZeroProgressSuccess BoundedRecovery ErrExhaustsCandidates ErrStopsRequests diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 85c4d69801..ad1cec53fb 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -1,96 +1,146 @@ ---- MODULE CondenseTruncate ---- -\* Models truncateConversation and the count after it in src/core/context-management/index.ts. +\* Models truncateConversation and the recovery round after it in +\* src/core/context-management/index.ts (the manageContext fallback). \* Source: summarizeConversation (src/core/condense/index.ts) tags each old message with -\* condenseParent and adds a summary. truncateConversation picks "visible" messages and -\* tags them with truncationParent. manageContext reports the token count after truncation. -\* Sink: getEffectiveApiHistory (src/core/condense/index.ts). With a summary, it returns -\* only the messages from the latest summary onward (fresh start). Without one, a cond -\* tag hides a message only when its summary still exists. -\* Failure 1 (issue 1823): after a condense, the visible filter ignores condenseParent. -\* Truncation hides only messages that the sink already hides. The live history stays -\* over the context window, so each request fails. -\* Failure 2: the count after truncation ignores condenseParent, so it counts messages -\* that the sink already hides and overstates the live context. -\* Failure 3 (PR 2647 review round 2): a rewind deletes the summary, so its tagged messages -\* are live again at the sink. The coarse rule still hides them, so a truncation cannot -\* remove them and the count omits them. -\* Failure 4 (PR 2647 review round 3): with a summary present, a message before it stays a -\* truncation candidate and the count includes it. The truncation can tag the summary -\* itself, and the sink then drops the tagged summary from the live history. +\* condenseParent and adds a summary. truncateConversation picks "visible" messages, tags +\* them with truncationParent, and on a zero-removal history degrades one tool result. +\* manageContext reports the token count after the round. +\* Sink: getEffectiveApiHistory (src/core/condense/index.ts). With a summary, it returns only +\* the messages from the latest summary onward (fresh start). Without one, a cond tag hides +\* a message only when its summary still exists. +\* Failure 1 (issue 1823): after a condense, the visible filter ignores condenseParent, so a +\* truncation hides messages the sink already hides. Failure 2: the count after truncation +\* ignores condenseParent and overstates the live context. +\* Failure 3 (PR 2647 round 2): a rewind deletes the summary, so its tagged messages are live +\* again at the sink. The coarse rule still hides them. +\* Failure 4 (PR 2647 round 3): with a summary present, a message before it stays a +\* truncation candidate, and the truncation can tag the summary itself. +\* Failure 5 (issue 1254): a short visible history yields messagesToRemove = 0 under the +\* 0.5 even-rounding rule, and the round still reports success with no change, so an +\* oversized history retries forever. The withdrawn PR 1617 findings guided this design; +\* no code of it is reused. Degradation must not orphan either half of a pair, and a +\* stalled round ends in Error. \* Invariant RemovedIsLive: a truncation removes exactly the live messages that it reports. \* Invariant CountExact: right after a truncation, the reported count equals the live count. \* Invariant SelectionMatchesLive: every candidate is live and removable, and every live \* message except the latest summary is a candidate. \* Invariant SummaryUntagged: no summary carries a truncation tag. -\* Modes: Fixed applies the latest-summary boundary (the fix). Matched is the code on the -\* reviewed head f20ae85: tags decide, no positional boundary. Coarse hides every tagged -\* message (the first version of the fix). Buggy ignores condenseParent. -\* LiveMsg correction (PR 2647 review round 3): the first version approximated the sink -\* with tag matching. It agreed with the real sink only on tag-matched layouts. The real -\* rule is position-aware: with a summary, only the latest summary and the messages after -\* it are live. The round-3 review exposed the divergence, so LiveMsg now uses position. -\* Expected before the run: Matched breaks SelectionMatchesLive (a stale orphan before -\* the summary is a candidate but dead) and SummaryUntagged (Truncate tags the summary). -\* Matched breaks CountExact when the stale orphans counted do not balance the tagged -\* summary lost. Fixed holds every invariant. Buggy and Coarse keep the round-2 failures. -\* Not modeled: token sizes (each message is one unit), the removal fraction (0.5 in the -\* code), the threshold that starts truncation, and the cleanup pass cleanupAfterTruncation -\* that clears orphan tags. A rewind that orphans tags is modeled by the Rewind action. -\* Gap: the sink also sends the marker text. The code count and this model exclude the -\* marker. The error is small and constant. Out of scope for this fix. -\* Cost: each run takes under 10 seconds. Agent time is not measured. -\* Result: CondenseTruncate.cfg (Fixed) holds with 400 distinct states. UnfixedRemoved -\* and UnfixedCount fail with 48 states each. CoarseSelection fails with 3 states. -\* CoarseCount fails with 749 states. MatchedSelection fails with 3 states. -\* MatchedSummary fails with 221 states. MatchedCount fails with 222 states. -\* Every variant models a rule that this fix replaces, so each failure is a reproduction. -\* The round-4 review (thread 4657986893) found that excluding the summary from -\* the candidates split tool_use/tool_result pairs, and the Messages API rejects -\* a split pair. Added: the summary is the first candidate and skip-first keeps -\* it untagged (VisMsg Fixed uses i >= LastSumIdx, SelectionMatchesLive simplified -\* to the sink rule). The pair-integrity unit test replays it on the real code. -\* Findings: covered 4, added 4, gap 3. The two failures of issue 1823 are covered -\* findings. The round-2 review had two findings: the oracle duplication is covered, the -\* orphan regression is added (Rewind action, Coarse mode, SelectionMatchesLive). -\* The round-3 review had three findings: the missing boundary is added (boundary VisMsg, -\* SelectionMatchesLive redefinition, SummaryUntagged, Matched mode, three Matched cfgs, -\* PR 2647 review thread comment 4657855243), the LiveMsg approximation is added (stale -\* field, position-aware sink rule), and the pre-merge regression-evidence warning on the -\* count test is covered (PR 2647, review of head f20ae85): CountExact already models the -\* API-visible count, and the count tests now derive their expected values from the sink. -\* Mutation round (PR 2647): the getExistingSummaryIds guard lacked direct tests. This -\* spec cannot express the guard: it abstracts condense IDs away, so SummaryExists checks -\* only summ and cannot tell an untagged summary from a non-summary that carries an ID. -\* That guard is a gap here. The direct unit tests in src/core/condense/__tests__/ -\* index.spec.ts pin it on the real code (PR 2647 review thread, comment 4657908739). -\* The other gap is the marker text below. -\* Mutation round 2 (PR 2647, head a68ba75): four boundary mutants survived (the -\* scan guard and the clamp, in the selection and the count). They are equivalent: -\* the boundary is the sole consumer of the scan, and index >= boundary treats -1 -\* and 0 alike for array indices. The model derives LastSumIdx directly, so the -\* scan and clamp guards are a gap here. The documented Stryker disables in the -\* code pin them (PR 2647 mutation report, comment 7078205049). -\* Replay: UnfixedRemoved and UnfixedCount keep the counterexample AddMsg x4, Condense, -\* Truncate (2 removed reported, 0 live removed). CoarseSelection gives Condense, Rewind: -\* one orphan is live but coarse-invisible. CoarseCount gives Condense, Rewind, AddMsg x5, -\* Truncate: the coarse count reports 3 but the live count is 4. MatchedSelection gives -\* Condense: the summary is a candidate, but the sink keeps it as the first effective -\* message, so it is live but not removable. MatchedSummary gives AddMsg, Condense, Rewind, -\* Condense, AddMsg x2, Truncate: the truncation tags the new summary. MatchedCount gives -\* AddMsg x3, Condense, Rewind, Condense, Truncate: the count reports a stale orphan that -\* the sink drops. The unit tests replay the rules on the real code. +\* Invariant SuccessIsMonotonic: every reported success strictly shrinks the live weight +\* (one unit per live message, one per live oversized tool result). +\* Invariant DegradationPreservesPair: right after a degrade step, the degraded tool +\* result and its paired tool use are both live. +\* Invariant NoZeroProgressSuccess: a round that removes nothing and degrades nothing +\* never reports success. +\* Invariant BoundedRecovery: two stalled rounds in a row end in Error. +\* Failure 6 (PR 2696 review round 1, thread 4692295250): the degradation scan +\* checks every message, so with a summary it can degrade a tool result before +\* the latest summary that the sink never counts, and the round still succeeds. +\* Failure 7 (thread 4692295271): an empty tool_result array passes the size +\* scan, the clear cannot shrink the recounted tokens, and the round succeeds. +\* Failure 8 (thread 4692295281): the degrade step clears every tool_result +\* block of the selected message, so a small parallel result is lost. +\* Invariant DegSelectionLive: a degraded tool result is live at the sink. +\* Invariant DegradationKeepsOtherBlocks: a degrade keeps a second oversized +\* block of the same message. +\* Failure 9 (PR 2696 review round 2, thread 4693277487): the recovery scan +\* accepts only the first oversized block, so a message whose first block is +\* cleared leaves the scan while the second block still weighs, and the round +\* reports Error though the runtime can still recover it. Recovery selects one +\* block per round; the scan must accept either block. +\* Invariant ErrExhaustsCandidates: an Error round means no live paired tool +\* result still carries an oversized block. +\* Failure 10 (PR 2696 review round 5, taltas threads 4695751055/65/75): the +\* no-progress outcome left both Task request paths free to resend the +\* unchanged history (now they throw ContextManagementNoProgressError); a +\* degrade lost the original content (now preserved on a hidden +\* degradedOriginals marker so rewind can restore it); and the success check +\* compared a fresh recount against the API-reported total, so a +\* prompt-dominated or undercounted total rejected real reductions (now both +\* sides use the same estimator over the effective slice). +\* Failure 11 (PR 2696 review round 6, threads on CondenseTruncate.tla:56/59): +\* the caller had no modeled response to an Error round, so nothing checked +\* that either Task request path stops instead of resending the unchanged +\* history; and the degraded-round recount comparison has no model side. +\* Invariant ErrStopsRequests: after an Error round the caller never resends +\* the unchanged history. +\* Modes: Fixed applies the latest-summary boundary (the fix) and the fixed recovery +\* contract (degrade one eligible tool result, or stop with Error). Matched is the reviewed +\* head f20ae85 of PR 2647: tags decide, no positional boundary. Coarse hides every tagged +\* message. Buggy ignores condenseParent. ZeroOK reports success on a zero-removal round +\* with no change (issue 1254). NoPairDeg also tags the paired tool use. PreScan scans +\* without the summary boundary; EmptyOK treats an empty-content result as oversized; +\* AllBlocks also clears the second oversized block. OnlyBig scans only the first +\* oversized block. NoStop lets the caller resend the unchanged history +\* after an Error round. Other modes use the Fixed arms. +\* LiveMsg correction (PR 2647 round 3): the sink rule is position-aware, not tag +\* matching. Round 4 (thread 4657986893): the summary stays the first candidate and +\* skip-first keeps pairs whole. Mutation round: the getExistingSummaryIds guard and four +\* equivalent boundary mutants are pinned by code, not the model. Not modeled: the budget +\* that starts a round, real token sizes, marker text, cleanupAfterTruncation. A rewind +\* that orphans tags is the Rewind action. Eligibility also needs a live paired tool use; +\* a pre-existing sliding-window split of a pair is out of scope for issue 1254. +\* Cost: the full check takes under 3 minutes. Agent time is not measured. +\* Result: CondenseTruncate.cfg (Fixed) holds. Every variant models a rule the fix +\* replaces and fails its target invariant. CHOOSE over several eligible results makes +\* the exact state count vary between runs; polarity does not. +\* Issue 1823 failures are covered; PR 2647 rounds 2-4 added the Rewind action, +\* boundary VisMsg, SummaryUntagged, skip-first (threads 4657855243, 4657986893). Issue 1254 added four invariants (ZeroOK, NoPairDeg). +\* PR 2696 round 1 (threads 4692295250/71/81) added DegSelectionLive, the fake-big +\* EmptyOK case, and DegradationKeepsOtherBlocks (PreScan, EmptyOK, AllBlocks sabotage). +\* Round 2 (thread 4693277487) added ErrExhaustsCandidates and one-block-per-round +\* selection (OnlyBig sabotage); its Persistence Integrity note is a gap. Round 6 +\* (threads on tla:56/59) added the caller transition and ErrStopsRequests +\* (NoStop sabotage); the recount comparison is a recorded gap. Round 7 +\* (threads 4697695475/4697701195) records rewind restoration of the +\* degradedOriginals as a gap (see Gaps) and pins the recount-unchanged +\* degrade with a unit test. +\* Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the recovery +\* budget, the caller persist path for a failed round, residual code eligibility, and +\* the degraded-round recount comparison (the code rejects a degrade whose fresh +\* recount did not shrink; the model weights are binary units, so a +\* recount-unchanged degrade is unrepresentable here — the unit tests pin it). +\* Rewind restoration (round 7) is a gap: modeling the marker-carrying history +\* needs the degraded message's identity to survive across rounds, but this +\* model's degIdx resets every history-mutating action (the fresh-round record +\* DegradationPreservesPair and DegSelectionLive pin), and a persistent identity +\* breaks DegSelectionLive when a later Truncate tags the degraded message; a +\* marker Msg record would add a variable and multiply the state count. The +\* message-manager rewind tests pin the restore behavior on the real code. +\* Round 9 stays inside this gap: the lookup order (recorded index before the +\* timestamp heuristic) and the retry turn-removal window are both below the +\* model's abstraction (message identity and disk persistence are not modeled); +\* the rewind and persistence tests pin them on the real code. +\* Findings: covered 4, added 9, gap 8. +\* Replay: ZeroOK gives Init, Recover: a one-message history reports success with no +\* change, so the live code (issue 1254) retries forever. This is the unfixed-code +\* reproduction. NoPairDeg gives Init, AddToolPair, Recover: the degraded tool result +\* stays live while its paired tool use is tagged. PreScan gives Init, AddMsg, +\* AddToolPair, Condense, Recover: the degraded result sits before the summary, +\* hidden at the sink. EmptyOK gives Init, AddFakePair, Recover: a round succeeds +\* with no weight loss. AllBlocks gives Init, AddToolPair, Recover: a second +\* oversized block vanishes. OnlyBig gives Init, AddToolPair, Recover twice: the +\* second round reports Error while the second block still weighs. NoStop gives +\* Init, AddToolPair, Recover, CallerRespond: the caller resends the unchanged +\* history after the Error round. The unit tests replay every rule. EXTENDS Naturals, FiniteSets CONSTANTS Mode, MaxMsgs -Msg == [cond : BOOLEAN, trunc : BOOLEAN, mark : BOOLEAN, summ : BOOLEAN, stale : BOOLEAN] -FreshMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE] -SummaryMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> TRUE, stale |-> FALSE] -MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, stale |-> FALSE] +\* fake: passes the size scan of the unfixed code but weighs nothing (the +\* empty-array shape). big2: a second oversized tool_result block of the same +\* message (the parallel tool call shape). +Msg == [cond : BOOLEAN, trunc : BOOLEAN, mark : BOOLEAN, summ : BOOLEAN, stale : BOOLEAN, tres : BOOLEAN, big : BOOLEAN, fake : BOOLEAN, big2 : BOOLEAN] +FreshMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE, fake |-> FALSE, big2 |-> FALSE] +SummaryMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> TRUE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE, fake |-> FALSE, big2 |-> FALSE] +MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE, fake |-> FALSE, big2 |-> FALSE] +ToolResMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> TRUE, big |-> TRUE, fake |-> FALSE, big2 |-> TRUE] +FakeToolResMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> TRUE, big |-> FALSE, fake |-> TRUE, big2 |-> FALSE] -VARIABLES n, msgs, last, repValid, repTokens -vars == <> +VARIABLES n, msgs, last, repValid, repTokens, phase, stall, prevWt, degIdx, degClr2, resentErr +vars == <> +\* degClr2: the last degrade round selected the second block (big2) as the +\* block to clear, so the first block was not touched this round. \* The latest summary, when one exists. SumIdxSet == {i \in 1..n : msgs[i].summ} @@ -112,49 +162,41 @@ LiveMsg(i) == LiveCount == Cardinality({i \in 1..n : LiveMsg(i)}) -\* The visible filter of truncateConversation per mode. -\* Fixed: the latest-summary boundary. The summary is the first candidate; -\* the skip-first rule in Truncate keeps it untagged (review round 4). -\* Matched: the code on the reviewed head. Tags decide, position does not. -\* Coarse: hides every tagged message (the first version of the fix). -\* Buggy: ignores condenseParent (the code before the fix). +\* The live weight: one unit per live message plus one per live oversized +\* tool result. The code measures tokens; this is the countable progress. +LiveWeight == LiveCount + + Cardinality({i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big}) + + Cardinality({i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big2}) + +\* The 0.5 even-rounding rule of truncateConversation: half of the visible +\* messages after the first one, rounded down to an even count. A short +\* visible history yields zero (issue 1254). +RemovedCount(vc) == + LET raw == (vc - 1) \div 2 + IN IF raw % 2 = 0 THEN raw ELSE raw - 1 + +\* The visible filter of truncateConversation per mode. The else arm is Fixed: +\* the latest-summary boundary. The summary is the first candidate and the +\* skip-first rule in Truncate keeps it untagged (PR 2647 round 4). VisMsg(mode, i) == - IF mode = "Fixed" THEN - /\ ~msgs[i].trunc - /\ ~msgs[i].mark - /\ \/ ~HasSummary - \/ i >= LastSumIdx - ELSE IF mode = "Matched" THEN - /\ ~msgs[i].trunc - /\ ~msgs[i].mark - /\ ~(msgs[i].cond /\ ~msgs[i].stale /\ HasSummary) - ELSE IF mode = "Coarse" THEN - /\ ~msgs[i].trunc - /\ ~msgs[i].mark - /\ ~msgs[i].cond - ELSE - /\ ~msgs[i].trunc - /\ ~msgs[i].mark + IF mode = "Matched" THEN /\ ~msgs[i].trunc /\ ~msgs[i].mark + /\ ~(msgs[i].cond /\ ~msgs[i].stale /\ HasSummary) + ELSE IF mode = "Coarse" THEN /\ ~msgs[i].trunc /\ ~msgs[i].mark /\ ~msgs[i].cond + ELSE IF mode = "Buggy" THEN /\ ~msgs[i].trunc /\ ~msgs[i].mark + ELSE /\ ~msgs[i].trunc /\ ~msgs[i].mark + /\ \/ ~HasSummary + \/ i >= LastSumIdx -\* The count after truncation per mode. Fixed uses the boundary and keeps the -\* summary in the count. Each other mode counts by its own rule. +\* The count after truncation per mode. The else arm is Fixed: the boundary, +\* and the summary stays in the count. CountMsg(mode, m, i) == - IF mode = "Fixed" THEN - /\ ~m.trunc - /\ ~m.mark - /\ \/ ~HasSummary - \/ i >= LastSumIdx - ELSE IF mode = "Matched" THEN - /\ ~m.trunc - /\ ~m.mark - /\ ~(m.cond /\ ~m.stale /\ HasSummary) - ELSE IF mode = "Coarse" THEN - /\ ~m.trunc - /\ ~m.mark - /\ ~m.cond - ELSE - /\ ~m.trunc - /\ ~m.mark + IF mode = "Matched" THEN /\ ~m.trunc /\ ~m.mark + /\ ~(m.cond /\ ~m.stale /\ HasSummary) + ELSE IF mode = "Coarse" THEN /\ ~m.trunc /\ ~m.mark /\ ~m.cond + ELSE IF mode = "Buggy" THEN /\ ~m.trunc /\ ~m.mark + ELSE /\ ~m.trunc /\ ~m.mark + /\ \/ ~HasSummary + \/ i >= LastSumIdx \* The k smallest elements of S. S has at least k elements when this runs. RECURSIVE MinN(_, _) @@ -169,10 +211,38 @@ AddMsg == /\ n' = n + 1 /\ msgs' = [i \in 1..(n + 1) |-> IF i = n + 1 THEN FreshMsg ELSE msgs[i]] /\ repValid' = FALSE + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED resentErr + +\* A tool turn: an assistant tool use and a user tool result, adjacent. The +\* result starts oversized, the shape of the 4MB case in issue 1254. +AddToolPair == + /\ n + 2 <= MaxMsgs + /\ n' = n + 2 + /\ msgs' = [i \in 1..(n + 2) |-> IF i = n + 1 THEN FreshMsg + ELSE IF i = n + 2 THEN ToolResMsg + ELSE msgs[i]] + /\ repValid' = FALSE + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> + /\ UNCHANGED resentErr -\* The condense source: every untagged message gets condenseParent, then a summary -\* follows. A fresh tag always has a live summary (stale = FALSE). +\* An empty-content tool turn: the serialized empty array passes the size +\* scan of the unfixed code, but clearing it cannot shrink the token count. +AddFakePair == + /\ n + 2 <= MaxMsgs + /\ n' = n + 2 + /\ msgs' = [i \in 1..(n + 2) |-> IF i = n + 1 THEN FreshMsg + ELSE IF i = n + 2 THEN FakeToolResMsg + ELSE msgs[i]] + /\ repValid' = FALSE + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED resentErr + +\* The condense source: every untagged message gets condenseParent, then a +\* summary follows. A fresh tag always has a live summary (stale = FALSE). Condense == /\ n < MaxMsgs /\ n' = n + 1 @@ -180,17 +250,17 @@ Condense == ELSE IF msgs[i].cond THEN msgs[i] ELSE [msgs[i] EXCEPT !.cond = TRUE, !.stale = FALSE]] /\ repValid' = FALSE + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> + /\ UNCHANGED resentErr -\* The code under test. It hides half of the visible messages after the first one, -\* rounded to an even count. Then it reports how many it removed. -\* Truncate keeps every message, so the summary positions keep their value. +\* The code under test. It hides half of the visible messages after the first +\* one, rounded to an even count. Then it reports how many it removed. Truncate == /\ n < MaxMsgs /\ LET Vis == {i \in 1..n : VisMsg(Mode, i)} vc == Cardinality(Vis) - raw == (vc - 1) \div 2 - removed == IF raw % 2 = 0 THEN raw ELSE raw - 1 + removed == RemovedCount(vc) IN /\ vc >= 5 /\ LET first == CHOOSE i \in Vis : \A j \in Vis : i <= j tagged == MinN(Vis \ {first}, removed) @@ -199,10 +269,11 @@ Truncate == ELSE msgs[i]] IN /\ msgs' = newM /\ n' = n + 1 - /\ last' = [rep |-> removed, - lost |-> Cardinality({i \in tagged : LiveMsg(i)})] + /\ last' = [rep |-> removed, lost |-> Cardinality({i \in tagged : LiveMsg(i)})] /\ repValid' = TRUE /\ repTokens' = Cardinality({i \in 1..(n + 1) : CountMsg(Mode, newM[i], i)}) + /\ phase' = "ok" /\ stall' = 0 /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ degClr2' = FALSE + /\ UNCHANGED resentErr \* A rewind to a point before the summary deletes it and the messages after it. \* The tagged messages before it stay, now stale and live again. @@ -214,24 +285,94 @@ Rewind == IN /\ n' = k - 1 /\ msgs' = [i \in 1..(k - 1) |-> IF msgs[i].cond THEN [msgs[i] EXCEPT !.stale = TRUE] ELSE msgs[i]] - /\ repValid' = FALSE - /\ repTokens' = 0 + /\ repValid' = FALSE /\ repTokens' = 0 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED last + /\ UNCHANGED resentErr + +\* The Task-side response to a round outcome (PR 2696 review round 6, thread +\* on CondenseTruncate.tla:56): after an Error round the request paths stop +\* (ContextManagementNoProgressError) instead of resending the unchanged +\* history. Fixed records the stop; the NoStop sabotage arm resends. Normal +\* round iteration is out of scope: only the Error decision is modeled. +CallerRespond == + /\ phase = "err" + /\ IF Mode = "NoStop" + THEN /\ resentErr' = TRUE + /\ UNCHANGED <> + ELSE /\ resentErr' = FALSE + /\ UNCHANGED <> + +\* One recovery round of manageContext (issue 1254) on a zero-removal history. +\* Fixed: degrade one eligible live tool result (its paired tool use stays +\* live), or stop with Error. ZeroOK: the live code reports success with no +\* change and never degrades. NoPairDeg: the degrade step also tags the pair. +\* Sizes are binary, so any eligible choice models the largest one. +Recover == + /\ stall < 2 + \* After an Error round no further Recover is enabled: both request + \* paths stop instead of resending the unchanged history (PR 2696 + \* review round 8). CallerRespond models the caller's decision; a new + \* recovery round starts only from a fresh run phase via AddMsg and + \* friends, which reset phase to "run". + /\ phase # "err" + /\ LET Vis == {i \in 1..n : VisMsg(Mode, i)} + vc == Cardinality(Vis) + IN /\ vc >= 1 + /\ RemovedCount(vc) = 0 + /\ LET Deg == IF Mode = "PreScan" /\ HasSummary + THEN {i \in 2..(LastSumIdx - 1) : ~msgs[i].trunc /\ ~msgs[i].mark /\ msgs[i].tres /\ msgs[i].big} + ELSE IF Mode = "EmptyOK" + THEN {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].fake /\ LiveMsg(i - 1)} + ELSE IF Mode = "OnlyBig" + THEN {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big /\ LiveMsg(i - 1)} + ELSE {i \in 1..n : LiveMsg(i) /\ msgs[i].tres + /\ (msgs[i].big \/ msgs[i].big2) /\ LiveMsg(i - 1)} + IN \/ /\ Deg # {} + /\ Mode # "ZeroOK" + /\ LET d == CHOOSE x \in Deg : TRUE + dm == IF Mode = "NoPairDeg" + THEN [msgs EXCEPT ![d] = IF msgs[d].big + THEN [msgs[d] EXCEPT !.big = FALSE] + ELSE [msgs[d] EXCEPT !.big2 = FALSE], + ![d - 1] = [msgs[d - 1] EXCEPT !.trunc = TRUE]] + ELSE IF Mode = "AllBlocks" + THEN [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE, !.big2 = FALSE]] + ELSE IF msgs[d].big + THEN [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE, !.fake = FALSE]] + ELSE [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big2 = FALSE, !.fake = FALSE]] + IN /\ msgs' = dm + /\ phase' = "ok" /\ stall' = 0 /\ prevWt' = LiveWeight /\ degIdx' = d + /\ degClr2' = ((Mode # "AllBlocks") /\ ~msgs[d].big) + /\ repValid' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED resentErr + \/ /\ (Deg = {} \/ Mode = "ZeroOK") + /\ phase' = IF Mode = "ZeroOK" THEN "ok" ELSE "err" + /\ stall' = stall + 1 + /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ degClr2' = FALSE /\ repValid' = FALSE + /\ UNCHANGED <> + /\ UNCHANGED resentErr Init == /\ n = 1 /\ msgs = [i \in 1..1 |-> FreshMsg] /\ last = [rep |-> 0, lost |-> 0] - /\ repValid = FALSE - /\ repTokens = 0 + /\ repValid = FALSE /\ repTokens = 0 + /\ phase = "run" /\ stall = 0 /\ prevWt = 0 /\ degIdx = 0 /\ degClr2 = FALSE + /\ resentErr = FALSE -Next == \/ AddMsg \/ Condense \/ Truncate \/ Rewind +Next == \/ AddMsg \/ AddToolPair \/ AddFakePair \/ Condense \/ Truncate \/ Rewind \/ Recover + \/ CallerRespond Spec == Init /\ [][Next]_vars TypeOK == /\ n \in 1..MaxMsgs /\ msgs \in [1..n -> Msg] /\ last \in [rep : Nat, lost : Nat] - /\ repTokens \in Nat - /\ repValid \in BOOLEAN + /\ repTokens \in Nat /\ repValid \in BOOLEAN + /\ phase \in {"run", "ok", "err"} /\ stall \in 0..2 + /\ prevWt \in Nat /\ degIdx \in 0..MaxMsgs + /\ degClr2 \in BOOLEAN + /\ resentErr \in BOOLEAN \* The opposite of Failure 1: a truncation that reports k removed messages hides \* exactly k live messages, so the live history shrinks by what the code reports. @@ -252,4 +393,50 @@ SelectionMatchesLive == \* first effective message, so no truncation may ever tag it. SummaryUntagged == \A i \in 1..n : msgs[i].summ => ~msgs[i].trunc +\* The opposite of the fake-success half of Failure 5: a reported success +\* strictly shrinks the live weight, so the history cannot retry at the +\* same size forever. +SuccessIsMonotonic == phase = "ok" => prevWt > LiveWeight + +\* The opposite of the orphan half of Failure 5: right after a degrade step, +\* the degraded tool result is live, its content is degraded, and its paired +\* tool use is live. The Messages API rejects an orphaned half. +DegradationPreservesPair == + degIdx = 0 \/ + /\ degIdx > 1 + /\ LiveMsg(degIdx) + /\ msgs[degIdx].tres + /\ ~msgs[degIdx].big + /\ LiveMsg(degIdx - 1) + +\* The opposite of Failure 6: a degraded tool result is live at the sink, so +\* the cleared content was still model-facing and the round could count it. +DegSelectionLive == degIdx = 0 \/ LiveMsg(degIdx) + +\* The opposite of Failure 8: the degrade keeps a second oversized block of +\* the selected message, so only the selected result loses its content. Each +\* round selects one block; degClr2 marks big2 as the selected one. +DegradationKeepsOtherBlocks == degIdx = 0 \/ degClr2 \/ msgs[degIdx].big2 + +\* The opposite of Failure 9: the stop is honest. A round that reports Error +\* leaves no selectable oversized block on any live paired tool result. +ErrExhaustsCandidates == + phase = "err" => + \A i \in 1..n : + ~(LiveMsg(i) /\ msgs[i].tres + /\ (msgs[i].big \/ msgs[i].big2) /\ LiveMsg(i - 1)) + +\* The opposite of the zero-progress half of Failure 5: a round that removes +\* nothing and degrades nothing never reports success. +NoZeroProgressSuccess == phase = "ok" => stall = 0 + +\* The opposite of the unbounded half of Failure 5: two stalled rounds in a +\* row end in Error, never a repeated success. +BoundedRecovery == stall >= 2 => phase = "err" + +\* The opposite of Failure 11: after an Error round no request resends the +\* unchanged history — the caller stops (the code throws +\* ContextManagementNoProgressError on both request paths). +ErrStopsRequests == ~resentErr + ==== diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index e706133e7e..cd0d2de67f 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -269,6 +269,307 @@ describe("Context Management", () => { * Tests for the manageContext function */ describe("manageContext", () => { + it("reports no progress when a degraded round cannot shrink the caller's total", async () => { + // A degraded success must leave the recounted total LOWER than the + // prevContextTokens value the caller compares against, not only + // lower than the same-estimator slice estimate (issue 1254 review + // round 8, linked-issues check). Otherwise the caller would loop on + // a round that cannot make progress. The prompt-dominated scenario + // below still clears the same-estimator check: the fresh recount + // drops the oversized result, so it is lower than the + // original-slice estimate — but it stays above the caller's + // API-reported total, so the round reports the controlled error. + const history: ApiMessage[] = [ + { role: "user", content: "task" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x" }] }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 60, + contextWindow: 60, + maxTokens: 1, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "S".repeat(4000), + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + // The controlled error hands back the ORIGINAL history: the caller + // keeps it by array identity and stops on noProgress (review + // round 8). No cleared content is ever persisted. + expect(result.messages).toBe(history) + expect(result.messagesRemoved).toBe(0) + expect(result.noProgress).toBe(true) + expect(result.error).toContain("Unable to reduce context") + expect(history.some((m) => m.isTruncationMarker)).toBe(false) + }) + + it("reports no progress when the degraded recount is not lower than prevContextTokens", async () => { + // The demanded round-8 scenario: prevContextTokens sits below the + // estimate of the original slice, and the degraded recount lands + // between the two — lower than the slice estimate (the oversized + // result was cleared) but not lower than the caller's number. The + // round must report no progress so the caller stops instead of + // looping (issue 1254 review round 8, linked-issues check). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }], ts: 1100 }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: "t1", content: "x".repeat(6000) }], + ts: 1200, + }, + { role: "user", content: "tiny last", ts: 1300 }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 60, + contextWindow: 60, + maxTokens: 1, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "S".repeat(4000), + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.noProgress).toBe(true) + expect(result.messages).toBe(history) + }) + + it("reproduces the 4 MB tool-result case from the issue acceptance criteria", async () => { + // Issue 1254 acceptance: "Focused tests reproduce the 4 MB + // tool-result case and verify bounded recovery." A 4 MB result is + // ~1M tokens by the chars/4 estimate, far beyond any realistic + // window, and the degradation must clear it in one round without + // orphaning the pair or looping. + const big4MB = "x".repeat(4 * 1024 * 1024) + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }], ts: 1100 }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: "t1", content: big4MB }], + ts: 1200, + }, + { role: "user", content: "after", ts: 1300 }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 1_100_000, + contextWindow: 1_000_000, + maxTokens: 1, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + // One degradation round recovers: the recount no longer exceeds the + // budget, and the original survives on the hidden marker. + expect(result.error).toBeUndefined() + expect(result.messagesRemoved).toBe(0) + const marker = result.messages[result.messages.length - 1] + expect(marker.degradedOriginals?.[0]?.content).toBe(big4MB) + const degraded = result.messages[2].content as { content?: unknown }[] + expect(degraded[0].content).toBe("") + // Bounded: exactly one hidden marker was appended — no retry loop + // multiplied the history. + expect(result.messages).toHaveLength(5) + }) + + it("does not recount the original history on a plain truncation round", async () => { + // The original-history recount feeds only the degradation + // comparison; a plain sliding-window round must not re-tokenize + // the removed messages (issue 1254 review). + const modelInfo = createModelInfo(100000, 30000) + const countSpy = vi.spyOn(mockApiHandler, "countTokens") + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: "REMOVED-one", ts: 1100 }, + { role: "user", content: "REMOVED-two", ts: 1200 }, + { role: "assistant", content: "KEPT-three", ts: 1300 }, + { role: "user", content: "keep", ts: 1400 }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 70001, + contextWindow: modelInfo.contextWindow, + maxTokens: modelInfo.maxTokens, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.messagesRemoved).toBe(2) + const tokenized = countSpy.mock.calls.map(([content]) => JSON.stringify(content)).join("\n") + // The window removes indexes 1-2; KEPT-three stays, so the + // retained recount may still tokenize it. + const offenders = ["REMOVED-one", "REMOVED-two"].filter((m) => tokenized.includes(m)) + expect(offenders).toStrictEqual([]) + }) + + it("returns the no-progress outcome when nothing is removable or degradable", async () => { + // A short history with no paired oversized tool result removes zero + // messages and offers no degradation candidate: the round reports the + // controlled error with an unchanged token count (Regression Evidence, + // review round 2). + const history: ApiMessage[] = [ + { role: "user", content: "task" }, + { role: "user", content: "more context" }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 60, + contextWindow: 60, + maxTokens: 1, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.error).toBeDefined() + expect(result.messagesRemoved).toBe(0) + expect(result.newContextTokensAfterTruncation).toBe(result.prevContextTokens) + // The caller keeps ITS array: identity, not just equal content + // (Persistence Integrity, review round 3). + expect(result.messages).toBe(history) + }) + + it("returns the degraded content when the round shrinks the recounted tokens", async () => { + // A degraded round is a success only when the recounted total drops: + // the cleared result reaches the caller, so the shrink is real + // (Regression Evidence, review round 2). + const history: ApiMessage[] = [ + { role: "user", content: "task" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x".repeat(3000) }] }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 60, + contextWindow: 60, + maxTokens: 1, + apiHandler: mockApiHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.error).toBeUndefined() + expect(result.messagesRemoved).toBe(0) + expect(result.messages.slice(0, 3)).toStrictEqual([ + history[0], + history[1], + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "" }] }, + ]) + // The degradation marker rides at the end, hidden from the API: it + // preserves the original result so rewind can restore it (issue + // 1254 review, taltas thread 4695751065). + const marker = result.messages[3] + expect(marker.isTruncationMarker).toBe(true) + expect(marker.degradedOriginals?.[0]).toEqual({ + index: 2, + blockIndex: 0, + content: "x".repeat(3000), + }) + expect(result.newContextTokensAfterTruncation).toBeLessThan(result.prevContextTokens) + }) + it("reports the degraded round as no progress when the recount is unchanged", async () => { + // A degrade whose fresh recount does not shrink the original slice + // cannot make progress: the round must report the controlled error, + // flag noProgress for the caller, and hand back the ORIGINAL + // history, not the cleared result (PR 2696 review round 7, thread + // on CondenseTruncate.tla:59). + const countingHandler = new MockApiHandler() + vi.spyOn(countingHandler, "countTokens").mockResolvedValue(5) + const history: ApiMessage[] = [ + { role: "user", content: "task" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x".repeat(3000) }] }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 60, + contextWindow: 60, + maxTokens: 1, + apiHandler: countingHandler, + autoCondenseContext: false, + autoCondenseContextPercent: 100, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.error).toBeDefined() + expect(result.noProgress).toBe(true) + // The caller keeps ITS array: identity, not just equal content. + expect(result.messages).toBe(history) + }) + + it("keeps a failed condensation below the truncation limit out of no-progress", async () => { + // A condense failure with the history still below the fallback + // truncation limit returns the original messages with the error + // set, but the context still fits: the round is NOT no-progress, + // so the caller proceeds with the request instead of stopping + // (PR 2696 review round 7, thread on Task.ts). + const failingHandler = new MockApiHandler() + vi.spyOn(failingHandler, "createMessage").mockImplementation(() => { + throw new Error("condense backend down") + }) + const history: ApiMessage[] = [ + { role: "user", content: "task" }, + { role: "assistant", content: "middle context" }, + { role: "user", content: "latest" }, + ] + + const result = await manageContext({ + messages: history, + totalTokens: 200, + contextWindow: 1000, + maxTokens: 1, + apiHandler: failingHandler, + autoCondenseContext: true, + autoCondenseContextPercent: 10, + systemPrompt: "System prompt", + taskId, + profileThresholds: {}, + currentProfileId: "default", + }) + + expect(result.error).toBeDefined() + expect(result.noProgress).toBeUndefined() + expect(result.messages).toBe(history) + }) + const createModelInfo = (contextWindow: number, maxTokens?: number): ModelInfo => ({ contextWindow, supportsPromptCache: true, diff --git a/src/core/context-management/__tests__/truncation.spec.ts b/src/core/context-management/__tests__/truncation.spec.ts index 3d0ec1bf00..03592662ac 100644 --- a/src/core/context-management/__tests__/truncation.spec.ts +++ b/src/core/context-management/__tests__/truncation.spec.ts @@ -766,3 +766,202 @@ describe("Non-Destructive Sliding Window Truncation", () => { } }) }) + +describe("degradation candidate selection (PR 2696 review round 1)", () => { + const toolUse = (id: string) => [{ type: "tool_use" as const, id, name: "probe", input: {} }] + const toolResult = (id: string, content: string | { type: "text"; text: string }[]) => [ + { type: "tool_result" as const, tool_use_id: id, content }, + ] + const big = (n: number) => "x".repeat(n) + const arrayed = (m: ApiMessage) => + m.content as { tool_use_id?: string; content: unknown; originalContent?: unknown }[] + + it("never selects a pre-summary tool result when nothing post-summary is eligible", () => { + // The sink serves only the summary onward, so clearing a pre-summary + // result cannot shrink model-facing tokens: the round must stall, not + // claim success (thread 4692295250). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: toolUse("t1"), ts: 1100 }, + { role: "user", content: toolResult("t1", big(5000)), ts: 1200 }, + { role: "user", content: "Summary of the conversation", ts: 1300, isSummary: true }, + { role: "user", content: "after", ts: 1400 }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + expect(result.noProgress).toBe(true) + expect(arrayed(result.messages[2])).toStrictEqual(toolResult("t1", big(5000))) + }) + + it("selects the post-summary tool result when both sides are eligible", () => { + // The boundary skips the pre-summary result even though it is larger, + // so the scan and the recount see the same candidate set. + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: toolUse("t1"), ts: 1100 }, + { role: "user", content: toolResult("t1", big(8000)), ts: 1200 }, + { role: "user", content: "Summary of the conversation", ts: 1300, isSummary: true }, + { role: "user", content: "after", ts: 1400 }, + { role: "assistant", content: toolUse("t2"), ts: 1500 }, + { role: "user", content: toolResult("t2", big(3000)), ts: 1600 }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + expect(result.degraded).toBe(true) + const pre = arrayed(result.messages[2]) + const post = arrayed(result.messages[6]) + expect(pre[0].tool_use_id).toBe("t1") + expect(pre[0].content).toBe(big(8000)) + expect(post[0].tool_use_id).toBe("t2") + expect(post[0].content).toBe("") + }) + + it.each([ + ["an empty array stays ineligible", [] as { type: "text"; text: string }[], true], + [ + "a non-empty array stays eligible", + [{ type: "text", text: "hello" }] as { type: "text"; text: string }[], + false, + ], + ])("array size rule: %s", (_label, arrayContent, expectNoProgress) => { + // An empty array serializes to a non-empty string, but clearing it + // cannot shrink the token count, so it must never be a candidate + // (thread 4692295271). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: toolUse("t1"), ts: 1100 }, + { role: "user", content: toolResult("t1", arrayContent), ts: 1200 }, + { role: "user", content: "after", ts: 1300 }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + if (expectNoProgress) { + expect(result.noProgress).toBe(true) + } else { + expect(result.degraded).toBe(true) + } + }) + + it.each([ + [ + "a tool_use_id that matches no preceding tool_use", + [{ role: "assistant", content: toolUse("t1"), ts: 1100 }] as ApiMessage[], + ], + ["no preceding assistant tool_use", [{ role: "user", content: "plain text", ts: 1100 }] as ApiMessage[]], + ])("skips degradation when %s", (_label, middle) => { + // Pairing: a result is a candidate only when the preceding assistant + // message carries a tool_use with the matching id (Regression Evidence, + // review round 2). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + ...middle, + { role: "user", content: toolResult("t9", big(5000)), ts: 1200 }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + expect(result.noProgress).toBe(true) + expect(arrayed(result.messages[2])).toStrictEqual(toolResult("t9", big(5000))) + }) + + it("never selects a truncation marker as a degradation candidate", () => { + // Marker and parent messages are bookkeeping, not live content: the + // scan skips them even when they carry a paired oversized tool result + // (Regression Evidence, review round 2). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: toolUse("t1"), ts: 1100 }, + { + role: "user", + content: toolResult("t1", big(5000)), + ts: 1200, + isTruncationMarker: true, + truncationParent: "m1", + }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + expect(result.noProgress).toBe(true) + expect(arrayed(result.messages[2])).toStrictEqual(toolResult("t1", big(5000))) + }) + + it("clears only the selected tool_result block of the message", () => { + // Parallel tool calls share one message; clearing every block erases + // a small result that was not selected (thread 4692295281). + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: [...toolUse("t1"), ...toolUse("t2")], ts: 1100 }, + { + role: "user", + content: [...toolResult("t1", big(6000)), ...toolResult("t2", "keep me")], + ts: 1200, + }, + { role: "user", content: "after", ts: 1300 }, + ] + + const result = truncateConversation(history, 0.5, "test-task-id") + + expect(result.degraded).toBe(true) + const blocks = arrayed(result.messages[2]) + expect(blocks[0].content).toBe("") + expect(blocks[1].content).toBe("keep me") + // The original survives on the hidden degradation marker appended at + // the end, NOT on the cleared block: native providers serialize + // content blocks as-is, so an extra field there would be sent back to + // the API (issue 1254 review, taltas thread 4695751065). + expect(blocks[0]).not.toHaveProperty("originalContent") + const marker = result.messages[result.messages.length - 1] + expect(marker.isTruncationMarker).toBe(true) + expect(marker.degradedOriginals?.[0]).toEqual({ + index: 2, + blockIndex: 0, + content: big(6000), + }) + }) + + it("degrades one block per round until no eligible block remains", () => { + // ErrExhaustsCandidates (CondenseTruncate.tla) models recovery rounds: + // a premature noProgress on the second round passes every single-call + // test, so the chain must run for real (thread 4693794543). frac 0.25 + // keeps floor((visible-1)*frac) at the degenerate 0 so every round + // takes the degradation path. + const history: ApiMessage[] = [ + { role: "user", content: "task", ts: 1000 }, + { role: "assistant", content: toolUse("t1"), ts: 1100 }, + { role: "user", content: toolResult("t1", big(8000)), ts: 1200 }, + { role: "assistant", content: toolUse("t2"), ts: 1300 }, + { role: "user", content: toolResult("t2", big(5000)), ts: 1400 }, + ] + + const round1 = truncateConversation(history, 0.25, "test-task-id") + expect(round1.degraded).toBe(true) + expect(arrayed(round1.messages[2])[0].content).toBe("") + expect(arrayed(round1.messages[4])[0].content).toBe(big(5000)) + + const round2 = truncateConversation(round1.messages, 0.25, "test-task-id") + // The second round degrades the remaining oversized block... + expect(round2.degraded).toBe(true) + expect(arrayed(round2.messages[4])[0].content).toBe("") + // ...keeps round 1's block cleared, and retains both paired + // tool_use messages and their tool_result messages. Each round + // appends one hidden degradation marker, so the visible 5 messages + // are joined by round 1's and round 2's markers. + expect(arrayed(round2.messages[2])[0].content).toBe("") + expect(round2.messages[1].content).toStrictEqual(toolUse("t1")) + expect(round2.messages[3].content).toStrictEqual(toolUse("t2")) + expect(round2.messages).toHaveLength(7) + expect(round2.messages[5].isTruncationMarker).toBe(true) + expect(round2.messages[6].isTruncationMarker).toBe(true) + + const round3 = truncateConversation(round2.messages, 0.25, "test-task-id") + // noProgress fires only when no eligible block remains: both blocks + // stay cleared and no content returns. + expect(round3.noProgress).toBe(true) + expect(arrayed(round3.messages[2])[0].content).toBe("") + expect(arrayed(round3.messages[4])[0].content).toBe("") + }) +}) diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index 4ab38053ee..f69c0bf08b 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -25,6 +25,19 @@ import { RooIgnoreController } from "../ignore/RooIgnoreController" */ export const TOKEN_BUFFER_PERCENTAGE = 0.1 +/** + * Thrown by the Task call sites when context management reports a + * no-progress outcome (issue 1254 review, taltas thread 4695751055): the + * history cannot be shrunk, so resending it unchanged would fail again. + * The API request catch block re-throws this error without retrying. + */ +export class ContextManagementNoProgressError extends Error { + constructor(message: string) { + super(message) + this.name = "ContextManagementNoProgressError" + } +} + /** * Counts tokens for user content using the provider's token counting implementation. * @@ -73,6 +86,10 @@ export type TruncationResult = { messages: ApiMessage[] truncationId: string messagesRemoved: number + /** True when a zero-removal round degraded an oversized tool result instead of reporting success. */ + degraded?: boolean + /** True when no progress could be made (nothing removed and nothing degraded). */ + noProgress?: boolean } /** @@ -126,11 +143,128 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe const messagesToRemove = rawMessagesToRemove - (rawMessagesToRemove % 2) if (messagesToRemove <= 0) { - // Nothing to truncate + // Nothing to truncate by sliding window. Instead of reporting success + // with no change (issue 1254), degrade the largest eligible oversized + // tool_result content while preserving its tool_use_id pairing. If no + // eligible tool result can shrink, report a no-progress outcome so the + // caller can escalate instead of retrying forever. + const eligible: { index: number; size: number; blockIndex: number }[] = [] + messages.forEach((msg, index) => { + // The sink (getEffectiveApiHistory) never serves messages before the + // latest summary, so clearing one cannot shrink model-facing tokens. + // Candidates start at the same boundary the recount uses. + if (index < boundary) return + if (msg.truncationParent || msg.isTruncationMarker) return + const content = msg.content + if (!Array.isArray(content)) return + content.forEach((block, blockIndex) => { + if (block && typeof block === "object" && (block as { type?: string }).type === "tool_result") { + const b = block as { content?: unknown } + const size = + typeof b.content === "string" + ? b.content.length + : Array.isArray(b.content) && b.content.length > 0 + ? JSON.stringify(b.content).length + : 0 + // Only oversized results are eligible for degradation. An empty + // array serializes to a non-empty string, but clearing it cannot + // shrink the token count, so it must stay ineligible. + if (size > 0) { + // Preserve pairing: require a preceding assistant tool_use with matching id. + const toolUseId = (block as { tool_use_id?: string }).tool_use_id + let paired = false + if (index > 0) { + const prev = messages[index - 1] + const prevContent = prev?.content + if (Array.isArray(prevContent)) { + paired = prevContent.some( + (pb) => + pb && + typeof pb === "object" && + (pb as { type?: string }).type === "tool_use" && + (toolUseId === undefined || (pb as { id?: string }).id === toolUseId), + ) + } + } + if (paired) { + eligible.push({ index, size, blockIndex }) + } + } + } + }) + }) + + if (eligible.length === 0) { + return { + messages, + truncationId, + messagesRemoved: 0, + noProgress: true, + } + } + + // Degrade the largest eligible tool result (one step per round). Only + // the selected block loses its content: a message can carry several + // parallel tool results, and clearing the others is data loss. + eligible.sort((a, b) => b.size - a.size) + const targetIndex = eligible[0].index + const targetBlockIndex = eligible[0].blockIndex + const targetBlock = (() => { + const content = messages[targetIndex]?.content + return Array.isArray(content) ? content[targetBlockIndex] : undefined + })() + const degradedMessages = messages.map((msg, index) => { + if (index !== targetIndex) return msg + const content = Array.isArray(msg.content) ? [...msg.content] : msg.content + if (Array.isArray(content)) { + const newContent = content.map((block, blockIndex) => { + if ( + blockIndex === targetBlockIndex && + block && + typeof block === "object" && + (block as { type?: string }).type === "tool_result" + ) { + return { ...(block as unknown as Record), content: "" } + } + return block + }) + return { ...msg, content: newContent } as ApiMessage + } + return msg + }) + + // Preserve the original result on a hidden marker so a rewind can + // restore the un-degraded history (issue 1254 review, taltas thread + // 4695751065). The marker is hidden from every API-bound slice by its + // isTruncationMarker flag — native providers (Anthropic, Bedrock) + // serialize content blocks as-is, so the original must NOT ride on the + // cleared block itself or it would be sent straight back to the API. + const degradedOriginals = + targetBlock !== undefined + ? [ + { + index: targetIndex, + blockIndex: targetBlockIndex, + content: (targetBlock as { content?: unknown }).content, + }, + ] + : undefined + if (degradedOriginals) { + degradedMessages.push({ + role: "user", + content: `[Tool result degradation: oversized result cleared to reduce context]`, + ts: (messages[targetIndex]?.ts ?? Date.now()) + 1, + isTruncationMarker: true, + truncationId, + degradedOriginals, + }) + } + return { - messages, + messages: degradedMessages, truncationId, messagesRemoved: 0, + degraded: true, } } @@ -294,6 +428,13 @@ export type ContextManagementResult = SummarizeResponse & { truncationId?: string messagesRemoved?: number newContextTokensAfterTruncation?: number + /** + * True only when the round ended unable to reduce the context: nothing + * removable and no degradation candidate, or a degrade whose recount did + * not shrink. A condensation error below the truncation limit is NOT + * no-progress: the original history still fits, so the request proceeds. + */ + noProgress?: boolean } /** @@ -397,8 +538,37 @@ export async function manageContext({ // Fall back to sliding window truncation if needed if (prevContextTokens > allowedTokens) { + // The boundary of the ORIGINAL history: the latest summary anchors the + // same fresh-start slice the sink uses, so the estimate below covers + // exactly what the API still receives before this round (issue 1254). + let originalLastSummaryIndex = -1 + for (let i = messages.length - 1; i >= 0; i--) { + if (messages[i].isSummary) { + originalLastSummaryIndex = i + break + } + } + const originalBoundary = originalLastSummaryIndex === -1 ? 0 : originalLastSummaryIndex + const truncationResult = truncateConversation(messages, 0.5, taskId) + if (truncationResult.noProgress) { + error = + "Unable to reduce context: no messages removable and no oversized tool result eligible for degradation." + return { + messages, + prevContextTokens, + summary: "", + cost, + error, + errorDetails, + truncationId: truncationResult.truncationId, + messagesRemoved: 0, + newContextTokensAfterTruncation: prevContextTokens, + noProgress: true, + } + } + // Calculate new context tokens after truncation by counting the messages the // API still receives. The sink's fresh-start slice (getEffectiveApiHistory) // starts at the latest summary, so the count covers the summary plus the @@ -439,6 +609,59 @@ export async function manageContext({ } } + // A degraded round must shrink the recounted total before it reports + // success (issue 1254); otherwise the caller would retry a round that + // cannot make progress. Both sides of the comparison must use the SAME + // token counter (issue 1254 review, taltas thread 4695751075): + // prevContextTokens carries the API-reported cumulative usage, which + // includes cache reads and provider accounting the local estimator + // never sees, so comparing the fresh estimate against it can reject a + // reduction that really shrank the history. Recount the original + // effective slice with the same estimator instead. + // Only the degradation path consumes the original-history recount: + // the comparison below is gated on truncationResult.degraded, and + // running the loop for ordinary truncation re-tokenized the removed + // oversized results for nothing (issue 1254 review). + if (truncationResult.degraded) { + const originalEffectiveMessages = messages.filter( + (msg, index) => index >= originalBoundary && !msg.truncationParent && !msg.isTruncationMarker, + ) + let prevEstimatedTokens = await estimateTokenCount([{ type: "text", text: systemPrompt }], apiHandler) + for (const msg of originalEffectiveMessages) { + const content = msg.content + if (Array.isArray(content)) { + prevEstimatedTokens += await estimateTokenCount(content, apiHandler) + } else if (typeof content === "string") { + prevEstimatedTokens += await estimateTokenCount([{ type: "text", text: content }], apiHandler) + } + } + // Success must clear BOTH measures (issue 1254 review round 8): the + // same-estimator check rejects a round that did not shrink the + // recounted slice, and the caller-visible check rejects a round whose + // recount is not lower than the prevContextTokens value the caller + // compares against — without it the caller would loop on a round + // that cannot make progress. + if ( + newContextTokensAfterTruncation >= prevEstimatedTokens || + newContextTokensAfterTruncation >= prevContextTokens + ) { + // The round failed: handing back the degraded history would persist + // cleared tool_result content, so the caller keeps the original. + return { + messages, + prevContextTokens, + summary: "", + cost, + error: "Unable to reduce context: tool result degradation did not reduce the recounted tokens.", + errorDetails, + truncationId: truncationResult.truncationId, + messagesRemoved: 0, + newContextTokensAfterTruncation, + noProgress: true, + } + } + } + return { messages: truncationResult.messages, prevContextTokens, diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index 770b8347cf..2ef4f03e71 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -394,6 +394,281 @@ describe("MessageManager", () => { const hasMarker = apiCall.some((m: any) => m.isTruncationMarker) expect(hasMarker).toBe(false) }) + it("restores the degraded tool result when a removal drops its marker", async () => { + const truncationId = "trunc-deg-1" + const originalContent = [{ type: "text", text: "4MB of original output" }] + + mockTask.clineMessages = [ + { ts: 100, say: "user", text: "First" }, + { ts: 150, say: "user", text: "Second" }, + { ts: 300, say: "sliding_window_truncation", contextTruncation: { truncationId, reason: "window" } }, + { ts: 400, say: "user", text: "Third" }, + ] + + mockTask.apiConversationHistory = [ + { ts: 100, role: "user", content: [{ type: "text", text: "First" }] }, + { + ts: 110, + role: "user", + content: [ + { type: "tool_use", id: "t1", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t1", content: "" }, + ], + }, + { + ts: 111, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId, + degradedOriginals: [{ index: 1, blockIndex: 1, content: originalContent }], + }, + { ts: 150, role: "user", content: [{ type: "text", text: "Second" }] }, + ] + + // Rewind to ts=150: the marker and its degraded message stay + // (below the cutoff) but the truncation event is removed, which + // dooms the marker — the original must come back with it gone. + await manager.rewindToTimestamp(150) + + const apiCall = mockTask.overwriteApiConversationHistory.mock.calls[0][0] + expect(apiCall.some((m: { isTruncationMarker?: boolean }) => m.isTruncationMarker)).toBe(false) + const degraded = apiCall.find((m: { ts?: number }) => m.ts === 110) + expect(degraded).toBeDefined() + expect((degraded as unknown as { content: unknown[] }).content[1]).toStrictEqual({ + type: "tool_result", + tool_use_id: "t1", + content: originalContent, + }) + }) + + it("restores the degraded result when the cutoff equals the marker timestamp", async () => { + const truncationId = "trunc-deg-2" + const originalContent = [{ type: "text", text: "original output for equal cutoff" }] + + mockTask.clineMessages = [ + { ts: 100, say: "user", text: "First" }, + { ts: 111, say: "sliding_window_truncation", contextTruncation: { truncationId, reason: "window" } }, + { ts: 150, say: "user", text: "Second" }, + { ts: 400, say: "user", text: "Third" }, + ] + + mockTask.apiConversationHistory = [ + { ts: 100, role: "user", content: [{ type: "text", text: "First" }] }, + { + ts: 110, + role: "user", + content: [ + { type: "tool_use", id: "t2", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t2", content: "" }, + ], + }, + { + ts: 111, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId, + degradedOriginals: [{ index: 1, blockIndex: 1, content: originalContent }], + }, + { ts: 150, role: "user", content: [{ type: "text", text: "Second" }] }, + ] + + // Rewind with cutoff 111: the marker sits at the cutoff and the + // timestamp filter removes it, while the degraded message (ts 110) + // survives — the original must still be restored (PR 2696 review + // round 7). + await manager.rewindToTimestamp(111) + + const apiCall = mockTask.overwriteApiConversationHistory.mock.calls[0][0] + expect(apiCall.some((m: { isTruncationMarker?: boolean }) => m.isTruncationMarker)).toBe(false) + const degraded = apiCall.find((m: { ts?: number }) => m.ts === 110) + expect(degraded).toBeDefined() + expect((degraded as unknown as { content: unknown[] }).content[1]).toStrictEqual({ + type: "tool_result", + tool_use_id: "t2", + content: originalContent, + }) + }) + + it("restores a degraded result whose message carries no timestamp", async () => { + const truncationId = "trunc-deg-3" + const originalContent = [{ type: "text", text: "original output without ts" }] + + mockTask.clineMessages = [ + { ts: 100, say: "user", text: "First" }, + { ts: 150, say: "user", text: "Second" }, + { ts: 300, say: "sliding_window_truncation", contextTruncation: { truncationId, reason: "window" } }, + { ts: 400, say: "user", text: "Third" }, + ] + + mockTask.apiConversationHistory = [ + { ts: 100, role: "user", content: [{ type: "text", text: "First" }] }, + { + role: "user", + content: [ + { type: "tool_use", id: "t3", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t3", content: "" }, + ], + }, + { + ts: 50, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId, + degradedOriginals: [{ index: 1, blockIndex: 1, content: originalContent }], + }, + { ts: 150, role: "user", content: [{ type: "text", text: "Second" }] }, + ] + + // The degraded message has no ts, so the marker fell back to a + // Date.now()-derived timestamp (50 here) and the marker.ts - 1 + // lookup cannot find it. The predecessor identity must restore it + // (PR 2696 review round 7). + await manager.rewindToTimestamp(150) + + const apiCall = mockTask.overwriteApiConversationHistory.mock.calls[0][0] + expect(apiCall.some((m: { isTruncationMarker?: boolean }) => m.isTruncationMarker)).toBe(false) + const degraded = apiCall.find( + (m: { ts?: number; content?: unknown }) => m.ts === undefined && Array.isArray(m.content), + ) + expect(degraded).toBeDefined() + expect((degraded as unknown as { content: unknown[] }).content[1]).toStrictEqual({ + type: "tool_result", + tool_use_id: "t3", + content: originalContent, + }) + }) + + it("restores both results when two markers chain behind timestamp-free messages", async () => { + const truncationIdA = "trunc-deg-4a" + const truncationIdB = "trunc-deg-4b" + const originalA = [{ type: "text", text: "original output A" }] + const originalB = [{ type: "text", text: "original output B" }] + + mockTask.clineMessages = [ + { ts: 100, say: "user", text: "First" }, + { ts: 150, say: "user", text: "Second" }, + { + ts: 300, + say: "sliding_window_truncation", + contextTruncation: { truncationId: truncationIdA, reason: "window" }, + }, + { + ts: 301, + say: "sliding_window_truncation", + contextTruncation: { truncationId: truncationIdB, reason: "window" }, + }, + { ts: 400, say: "user", text: "Third" }, + ] + + mockTask.apiConversationHistory = [ + { ts: 100, role: "user", content: [{ type: "text", text: "First" }] }, + { ts: 150, role: "user", content: [{ type: "text", text: "Second" }] }, + { + role: "user", + content: [ + { type: "tool_use", id: "t4", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t4", content: "" }, + ], + }, + { + role: "user", + content: [ + { type: "tool_use", id: "t5", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t5", content: "" }, + ], + }, + { + ts: 60, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId: truncationIdA, + degradedOriginals: [{ index: 2, blockIndex: 1, content: originalA }], + }, + { + ts: 61, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId: truncationIdB, + degradedOriginals: [{ index: 3, blockIndex: 1, content: originalB }], + }, + ] + + // Both degraded messages carry no ts, so each marker fell back to a + // Date.now()-derived timestamp and the second marker trails the + // first marker, not its degraded message. Result B sits before + // marker A, so without the recorded-index lookup the predecessor + // fallback mislinks marker A to result B's message and leaves + // marker B nothing valid: BOTH blocks must come from their + // recorded original-history indexes (PR 2696 review round 9). + await manager.rewindToTimestamp(150) + + const apiCall = mockTask.overwriteApiConversationHistory.mock.calls[0][0] + expect(apiCall.some((m: { isTruncationMarker?: boolean }) => m.isTruncationMarker)).toBe(false) + const restoredA = apiCall.find( + (m: { content?: unknown }) => + Array.isArray(m.content) && + (m.content as { tool_use_id?: string }[]).some((b) => b?.tool_use_id === "t4"), + ) as { content: unknown[] } | undefined + expect(restoredA?.content[1]).toStrictEqual({ type: "tool_result", tool_use_id: "t4", content: originalA }) + const restoredB = apiCall.find( + (m: { content?: unknown }) => + Array.isArray(m.content) && + (m.content as { tool_use_id?: string }[]).some((b) => b?.tool_use_id === "t5"), + ) as { content: unknown[] } | undefined + expect(restoredB?.content[1]).toStrictEqual({ type: "tool_result", tool_use_id: "t5", content: originalB }) + }) + + it("restores from the recorded link when a retained message shares marker.ts - 1", async () => { + const truncationId = "trunc-deg-ts" + const original = [{ type: "text", text: "original output t9" }] + + mockTask.clineMessages = [ + { ts: 100, say: "user", text: "First" }, + { ts: 150, say: "user", text: "Second" }, + { ts: 300, say: "sliding_window_truncation", contextTruncation: { truncationId, reason: "window" } }, + ] + + mockTask.apiConversationHistory = [ + { ts: 100, role: "user", content: [{ type: "text", text: "First" }] }, + { + role: "user", + content: [ + { type: "tool_use", id: "t9", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t9", content: "" }, + ], + }, + { ts: 200, role: "user", content: "Retained plain note" }, + { + ts: 201, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId, + degradedOriginals: [{ index: 1, blockIndex: 1, content: original }], + }, + ] + + // The degraded message carries no ts, so the marker derived its + // timestamp in the same millisecond window as the retained note: + // marker.ts - 1 equals the note's ts, and the timestamp lookup + // returns a string-content message the restore step must skip. + // The validated recorded link wins instead (PR 2696 review round 9). + await manager.rewindToTimestamp(150) + + const apiCall = mockTask.overwriteApiConversationHistory.mock.calls[0][0] + expect(apiCall.some((m: { isTruncationMarker?: boolean }) => m.isTruncationMarker)).toBe(false) + const degraded = apiCall.find( + (m: { content?: unknown }) => + Array.isArray(m.content) && + (m.content as { tool_use_id?: string }[]).some((b) => b?.tool_use_id === "t9"), + ) as { content: unknown[] } | undefined + expect(degraded?.content[1]).toStrictEqual({ type: "tool_result", tool_use_id: "t9", content: original }) + }) it("should clear orphaned truncationParent tags via cleanup", async () => { const truncationId = "trunc-123" diff --git a/src/core/message-manager/index.ts b/src/core/message-manager/index.ts index 2d4666e9ee..846793778e 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -3,6 +3,7 @@ import { Task } from "../task/Task" import { cleanupAfterTruncation } from "../condense" import { OutputInterceptor } from "../../integrations/terminal/OutputInterceptor" import { getTaskDirectoryPath } from "../../utils/storage" +import type { ApiMessage } from "../task-persistence/apiMessages" export interface RewindOptions { /** Whether to include the target message in deletion (edit=true, delete=false) */ @@ -192,6 +193,105 @@ export class MessageManager { // Step 4: Remove truncation markers whose sliding_window_truncation was removed if (removedIds.truncationIds.size > 0) { + // Restore first: a doomed degradation marker carries the original + // tool_result content its round cleared, and dropping it without + // restoring would lose that content permanently (issue 1254 + // review). The scan runs over the ORIGINAL history: the cutoff + // filter above removes a marker whose timestamp equals the cutoff + // while the degraded message (marker.ts - 1) survives it, so a + // scan after the filter would miss that marker. The degraded + // message is located by ts (the marker is written at degraded.ts + // + 1), or — when it carries no timestamp and the marker fell + // back to Date.now() — as the original-history predecessor of the + // marker. Retained messages keep their object identity, so the + // ops map keys on the message object; restored messages are new + // objects routed through the final history write. + const restoreOps = new Map>() + for (let markerIndex = 0; markerIndex < originalHistory.length; markerIndex++) { + const marker = originalHistory[markerIndex] + if (!( + marker.isTruncationMarker && + marker.truncationId && + removedIds.truncationIds.has(marker.truncationId) + )) { + continue + } + if (!Array.isArray(marker.degradedOriginals)) { + continue + } + let degraded: ApiMessage | undefined + // Stable link first: the marker records the degraded message's + // original-history index, and a validated link is strictly more + // precise than the timestamp heuristic - two API messages can + // share the millisecond marker.ts - 1, and a retained + // string-content match would win the lookup and strand the + // cleared block (issue 1254 review round 9). Degradation rounds + // only append markers, so recorded positions stay valid across + // rounds; the predecessor fallback cannot find the message when + // it carries no timestamp and another marker sits between it + // and this one (issue 1254 review round 8). Validate the + // candidate so a stale index cannot mislink another message: + // it must still hold the cleared block. + const link = marker.degradedOriginals?.[0] + const linked = link && typeof link.index === "number" ? originalHistory[link.index] : undefined + const linkedBlock = + linked && Array.isArray(linked.content) + ? (linked.content[link.blockIndex] as { type?: string; content?: unknown } | undefined) + : undefined + if ( + linked && + !linked.isTruncationMarker && + linkedBlock?.type === "tool_result" && + linkedBlock.content === "" + ) { + degraded = linked + } + if (!degraded && marker.ts !== undefined) { + const degradedTs = marker.ts - 1 + // A marker is never the degraded target: two rounds on + // timestamp-free messages chain markers, and marker.ts - 1 + // then resolves to the earlier marker instead of the message + // this marker cleared (issue 1254 review round 8). + degraded = originalHistory.find((m) => m.ts === degradedTs && !m.isTruncationMarker) + } + if (!degraded && markerIndex > 0) { + const previous = originalHistory[markerIndex - 1] + if (Array.isArray(previous.content)) { + degraded = previous + } + } + if (!degraded) { + continue + } + const ops = restoreOps.get(degraded) ?? [] + for (const original of marker.degradedOriginals) { + ops.push({ blockIndex: original.blockIndex, content: original.content }) + } + restoreOps.set(degraded, ops) + } + if (restoreOps.size > 0) { + apiHistory = apiHistory.map((msg) => { + const ops = restoreOps.get(msg) + if (!ops || !Array.isArray(msg.content)) { + return msg + } + let changed = false + const content = msg.content.map((block, blockIndex) => { + const op = ops.find((candidate) => candidate.blockIndex === blockIndex) + if ( + !op || + !block || + (block as { type?: string }).type !== "tool_result" || + (block as { content?: unknown }).content !== "" + ) { + return block + } + changed = true + return { ...(block as unknown as Record), content: op.content } + }) + return changed ? ({ ...msg, content } as typeof msg) : msg + }) + } apiHistory = apiHistory.filter((msg) => { if (msg.isTruncationMarker && msg.truncationId && removedIds.truncationIds.has(msg.truncationId)) { console.log( diff --git a/src/core/task-persistence/apiMessages.ts b/src/core/task-persistence/apiMessages.ts index 51749e50fe..fd631ed7ff 100644 --- a/src/core/task-persistence/apiMessages.ts +++ b/src/core/task-persistence/apiMessages.ts @@ -36,6 +36,12 @@ export type ApiMessage = Anthropic.MessageParam & { truncationParent?: string // Identifies a message as a truncation boundary marker isTruncationMarker?: boolean + // For non-destructive tool-result degradation (issue 1254): the originals + // this degradation marker cleared, so a rewind can restore the + // un-degraded history. Carried on the marker because native providers + // serialize content blocks as-is — the originals must not ride on the + // cleared blocks or they would be sent back to the API. + degradedOriginals?: Array<{ index: number; blockIndex: number; content: unknown }> } export type ApiMessagesReadErrorKind = "invalid" | "io_error" diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 47a28aaaeb..9505c57989 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -114,7 +114,12 @@ import { type AssistantMessageContent, presentAssistantMessage } from "../assist import { DispatchState, type PendingWork } from "./dispatchState" import { type RequestPolicySnapshot } from "../prompts/tools/effective-tool-policy" import { NativeToolCallParser } from "../assistant-message/NativeToolCallParser" -import { type ContextManagementResult, manageContext, willManageContext } from "../context-management" +import { + type ContextManagementResult, + ContextManagementNoProgressError, + manageContext, + willManageContext, +} from "../context-management" import { ClineProvider } from "../webview/ClineProvider" import { MultiSearchReplaceDiffStrategy } from "../diff/strategies/multi-search-replace" import { @@ -565,6 +570,13 @@ export class Task extends EventEmitter implements TaskLike { * Set to `true` only after the assistant message is durably saved. */ assistantMessageSavedToHistory = false + /** + * A failed authoritative (merge=false) write leaves the disk holding a + * stale copy while memory holds the replacement turn under a new message + * id; a later merge write would then persist both copies. While this flag + * is set every history save stays authoritative until one of them lands. + */ + private historyReplacementPending = false private assistantMessagePersistencePromise!: Promise private resolveAssistantMessagePersistence!: (result: AssistantMessagePersistenceResult) => void private assistantMessagePersistenceCancellation?: AssistantMessagePersistenceCancellation @@ -1458,6 +1470,7 @@ export class Task extends EventEmitter implements TaskLike { private async addToApiConversationHistory( message: Anthropic.MessageParam, reasoning?: string, + persistMerge = true, source = { api: this.api, apiConfiguration: this.apiConfiguration }, ): Promise { const resolvesPendingAction = @@ -1477,7 +1490,7 @@ export class Task extends EventEmitter implements TaskLike { }), ) - let saved = await this.saveApiConversationHistory() + let saved = await this.saveApiConversationHistory(persistMerge) if (!saved && resolvesPendingAction) { saved = await this.retrySaveApiConversationHistory() } @@ -1647,16 +1660,23 @@ export class Task extends EventEmitter implements TaskLike { /** Persists the current API conversation history to disk, returning false on I/O errors. */ private async saveApiConversationHistory(merge = true): Promise { + const effectiveMerge = merge && !this.historyReplacementPending try { await saveApiMessages({ messages: snapshotHistory(this.apiConversationHistory), taskId: this.taskId, globalStoragePath: this.globalStoragePath, - merge, + merge: effectiveMerge, }) + if (!effectiveMerge) { + this.historyReplacementPending = false + } return true } catch (error) { console.error("Failed to save API conversation history:", error) + if (!effectiveMerge) { + this.historyReplacementPending = true + } return false } } @@ -3349,7 +3369,15 @@ export class Task extends EventEmitter implements TaskLike { if (existingApiConversationHistory.length > 0) { const lastMessage = existingApiConversationHistory[existingApiConversationHistory.length - 1] - if (lastMessage.isSummary) { + if (lastMessage.isTruncationMarker) { + // A trailing truncation marker must stay in the saved history: + // it carries the metadata (e.g. degradedOriginals) a later + // rewind restores, and the request never sees it + // (getEffectiveApiHistory filters markers). The resumed turn is + // built from the new user content only. + modifiedApiConversationHistory = [...existingApiConversationHistory] + modifiedOldUserContent = [] + } else if (lastMessage.isSummary) { // IMPORTANT: If the last message is a condensation summary, we must preserve it // intact. The summary message carries critical metadata (isSummary, condenseId) // that getEffectiveApiHistory() uses to filter out condensed messages. @@ -4020,6 +4048,7 @@ export class Task extends EventEmitter implements TaskLike { pendingContent?: Promise // Resolved after the request row shows includeFileDetails: boolean retryAttempt?: number + userMessageWasRemoved?: boolean // Track if user message was removed due to empty response } const stack: StackItem[] = [ @@ -4130,9 +4159,18 @@ export class Task extends EventEmitter implements TaskLike { const shouldAddUserMessage = shouldAddUserMessageToHistory({ retryAttempt: currentItem.retryAttempt, isEmptyUserContent, + userMessageWasRemoved: currentItem.userMessageWasRemoved, }) if (shouldAddUserMessage) { - await this.addToApiConversationHistory({ role: "user", content: finalUserContent }) + // A confirmed retry re-adds the removed turn here: merge=false + // makes this single write replace the stale disk copy, so the + // disk never holds a duplicate and never holds a turn-less + // intermediate state (issue 1254 review rounds 8-9). + await this.addToApiConversationHistory( + { role: "user", content: finalUserContent }, + undefined, + !currentItem.userMessageWasRemoved, + ) this.messageCounts.user++ } @@ -4870,11 +4908,97 @@ export class Task extends EventEmitter implements TaskLike { throw new Error("API request failed") } + // The failed attempt already saved this user turn; remove it so + // the retry does not persist a second copy. The next iteration + // re-adds it exactly once via userMessageWasRemoved. + let removedSavedUserTurn = false + if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { + // Context recovery can append a truncation marker + // (role "user") after the saved turn, so the tail is + // not always this attempt's turn. Walk back over + // markers and remove the saved turn itself: popping + // the marker would drop its degradedOriginals and a + // later rewind could not restore the cleared result + // (issue 1254 review round 8). + let turnIndex = -1 + for (let i = this.apiConversationHistory.length - 1; i >= 0; i--) { + if (this.apiConversationHistory[i].isTruncationMarker) { + continue + } + turnIndex = i + break + } + if (turnIndex !== -1 && this.apiConversationHistory[turnIndex].role === "user") { + this.apiConversationHistory.splice(turnIndex, 1) + this.messageCounts.user-- + removedSavedUserTurn = true + // The removal stays in memory only. The next iteration's + // re-add persists the replacement with merge=false in one + // authoritative write (issue 1254 review round 8, + // persistence integrity - moved from this branch in + // round 9): writing the turn-less state here would strand + // a saved tool_use without its tool_result on disk when + // the task aborts before the re-add runs. + } + } await this.say("api_req_retried") stack.push({ userContent: currentUserContent, includeFileDetails: false, - retryAttempt: 0, + retryAttempt: (currentItem.retryAttempt ?? 0) + 1, + userMessageWasRemoved: removedSavedUserTurn, + }) + continue + } else if (error instanceof ContextManagementNoProgressError) { + // Context management stopped without shrinking the history: resending + // the same request repeats the failure forever, so like + // OutputTokenLimitError the retry is the user's call, never an + // automatic loop (issue 1254 review). + const { response } = await this.ask("api_req_failed", rawErrorMessage) + + if (response !== "yesButtonClicked") { + throw new Error("API request failed") + } + + // The failed attempt already saved this user turn; remove it so + // the retry does not persist a second copy. The next iteration + // re-adds it exactly once via userMessageWasRemoved. + let removedSavedUserTurn = false + if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { + // Context recovery can append a truncation marker + // (role "user") after the saved turn, so the tail is + // not always this attempt's turn. Walk back over + // markers and remove the saved turn itself: popping + // the marker would drop its degradedOriginals and a + // later rewind could not restore the cleared result + // (issue 1254 review round 8). + let turnIndex = -1 + for (let i = this.apiConversationHistory.length - 1; i >= 0; i--) { + if (this.apiConversationHistory[i].isTruncationMarker) { + continue + } + turnIndex = i + break + } + if (turnIndex !== -1 && this.apiConversationHistory[turnIndex].role === "user") { + this.apiConversationHistory.splice(turnIndex, 1) + this.messageCounts.user-- + removedSavedUserTurn = true + // The removal stays in memory only. The next iteration's + // re-add persists the replacement with merge=false in one + // authoritative write (issue 1254 review round 8, + // persistence integrity - moved from this branch in + // round 9): writing the turn-less state here would strand + // a saved tool_use without its tool_result on disk when + // the task aborts before the re-add runs. + } + } + await this.say("api_req_retried") + stack.push({ + userContent: currentUserContent, + includeFileDetails: false, + retryAttempt: (currentItem.retryAttempt ?? 0) + 1, + userMessageWasRemoved: removedSavedUserTurn, }) continue } else { @@ -5207,6 +5331,7 @@ export class Task extends EventEmitter implements TaskLike { await this.addToApiConversationHistory( { role: "assistant", content: assistantContent }, reasoningMessage || undefined, + undefined, { api: requestApi, apiConfiguration: requestApiConfiguration }, ) @@ -5701,6 +5826,15 @@ export class Task extends EventEmitter implements TaskLike { useAvailableInputForContextPercent, }) + // Evaluate no-progress BEFORE the overwrite: a successful fallback + // reduction returns a NEW array, and once it is written back + // ensureMessageIdentifiers makes this.apiConversationHistory the same + // array, so a check after the overwrite would false-flag every + // successful round (issue 1254 review). + const noProgressError = + truncateResult.messages === this.apiConversationHistory && truncateResult.noProgress + ? truncateResult.error + : undefined if (truncateResult.summary) { this.armInstructionRefresh() } @@ -5708,6 +5842,12 @@ export class Task extends EventEmitter implements TaskLike { await this.overwriteApiConversationHistory(truncateResult.messages) } await this.reportContextManagementResult(truncateResult) + // A no-progress outcome leaves the history unchanged: resending it + // would exceed the window again, so both request paths stop here + // instead (issue 1254 review, taltas thread 4695751055). + if (noProgressError) { + throw new ContextManagementNoProgressError(noProgressError) + } } finally { // Notify webview that context management is complete (removes in-progress spinner) // IMPORTANT: Must always be sent to dismiss the spinner, even on error @@ -5967,6 +6107,15 @@ export class Task extends EventEmitter implements TaskLike { rooIgnoreController: this.rooIgnoreController, useAvailableInputForContextPercent, }) + // Evaluate no-progress BEFORE the overwrite: a successful fallback + // reduction returns a NEW array, and once it is written back + // ensureMessageIdentifiers makes this.apiConversationHistory the same + // array, so a check after the overwrite would false-flag every + // successful round (issue 1254 review). + const noProgressError = + truncateResult.messages === this.apiConversationHistory && truncateResult.noProgress + ? truncateResult.error + : undefined if (truncateResult.summary) { this.armInstructionRefresh() } @@ -5974,6 +6123,12 @@ export class Task extends EventEmitter implements TaskLike { await this.overwriteApiConversationHistory(truncateResult.messages) } await this.reportContextManagementResult(truncateResult) + // A no-progress outcome leaves the history unchanged: resending it + // would exceed the window again, so the automatic request path + // stops here instead (issue 1254 review, taltas thread 4695751055). + if (noProgressError) { + throw new ContextManagementNoProgressError(noProgressError) + } if (truncateResult.summary) { // Same request-state snapshot keeps prompt and tools consistent; files are re-read. instructionFailures = [] diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 1b95d41e5a..e7d611ffb6 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -15,6 +15,9 @@ import { import { TelemetryService } from "@roo-code/telemetry" import type { Anthropic } from "@anthropic-ai/sdk" +import { OutputTokenLimitError } from "../../../api/providers/utils/output-token-limit-error" +import { ContextManagementNoProgressError } from "../../context-management/index" +import type { ApiStreamChunk } from "../../../api/transform/stream" import { PendingActionSettlementError, Task } from "../Task" import { parseMentions } from "../../mentions" import { ClineProvider } from "../../webview/ClineProvider" @@ -457,6 +460,242 @@ describe("Task persistence", () => { expect(mockSaveApiMessages).toHaveBeenCalledWith(expect.objectContaining({ merge: true })) }) + it("persists exactly one user turn across a confirmed output-limit retry", async () => { + mockSaveApiMessages.mockResolvedValue([]) + + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + const access = task as unknown as { + diffViewProvider: { reset: () => Promise } + safeEnsureModelFetched: () => Promise + presentAssistantMessageSafe: () => void + } + vi.spyOn(access.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(access, "safeEnsureModelFetched").mockResolvedValue(undefined) + vi.spyOn(access, "presentAssistantMessageSafe").mockImplementation(() => {}) + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } as never) + + async function* truncatedStream(): AsyncGenerator { + yield { type: "text", text: "partial answer" } + throw new OutputTokenLimitError() + } + + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => { + // Context recovery ran before the stream failed: the marker + // (role "user") now trails the saved turn. + task.apiConversationHistory.push({ + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + ts: Date.now() + 1, + isTruncationMarker: true, + truncationId: "trunc-disk", + degradedOriginals: [{ index: 0, blockIndex: 0, content: "original" }], + }) + return truncatedStream() + }) + .mockImplementationOnce(() => + (async function* (): AsyncGenerator { + yield { type: "text", text: "done" } + })(), + ) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + expect(attemptApiRequestSpy).toHaveBeenCalled() + + // The confirmed retry must persist the turn removal with merge=false + // so the disk file drops the removed record; the default merge keeps + // disk-only records and the re-add would duplicate the turn + // (PR 2696 review round 8, persistence integrity). + expect(mockSaveApiMessages.mock.calls.some(([arg]) => arg.merge === false)).toBe(true) + + const lastSave = mockSaveApiMessages.mock.calls.at(-1)?.[0] + const saved = (lastSave?.messages ?? []) as Array<{ + role: string + content: unknown + isTruncationMarker?: boolean + truncationId?: string + }> + const savedTurns = saved.filter( + (m) => + m.role === "user" && + !m.isTruncationMarker && + Array.isArray(m.content) && + (m.content as { text?: string }[]).some((b) => b?.text === "long request"), + ) + expect(savedTurns).toHaveLength(1) + // The recovery marker survives on disk with its metadata. + expect(saved.some((m) => m.isTruncationMarker && m.truncationId === "trunc-disk")).toBe(true) + }) + + it.each([ + ["output-limit retry", new OutputTokenLimitError()], + ["no-progress retry", new ContextManagementNoProgressError("unable to reduce context")], + ] as const)( + "keeps later saves authoritative when the replacement write fails (%s)", + async (_name, streamError) => { + let replacementFailed = false + mockSaveApiMessages.mockImplementation(async (arg: unknown) => { + const merge = (arg as { merge?: boolean }).merge + if (merge === false && !replacementFailed) { + replacementFailed = true + throw new Error("disk full") + } + return [] + }) + + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + const access = task as unknown as { + diffViewProvider: { reset: () => Promise } + safeEnsureModelFetched: () => Promise + presentAssistantMessageSafe: () => void + } + vi.spyOn(access.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(access, "safeEnsureModelFetched").mockResolvedValue(undefined) + vi.spyOn(access, "presentAssistantMessageSafe").mockImplementation(() => {}) + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } as never) + + async function* failingStream(): AsyncGenerator { + yield { type: "text", text: "partial answer" } + throw streamError + } + + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => { + // Context recovery ran before the stream failed: the marker + // (role "user") now trails the saved turn. + task.apiConversationHistory.push({ + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + ts: Date.now() + 1, + isTruncationMarker: true, + truncationId: "trunc-disk", + degradedOriginals: [{ index: 0, blockIndex: 0, content: "original" }], + }) + return failingStream() + }) + .mockImplementationOnce(() => + (async function* (): AsyncGenerator { + yield { type: "text", text: "done" } + })(), + ) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + expect(attemptApiRequestSpy).toHaveBeenCalled() + expect(replacementFailed).toBe(true) + + const calls = mockSaveApiMessages.mock.calls + const failedIndex = calls.findIndex(([arg]) => (arg as { merge?: boolean }).merge === false) + expect(failedIndex).toBeGreaterThan(-1) + // The very next history save stays authoritative: a merge there would + // keep the stale disk copy beside the replacement turn, whose new + // message id defeats the merge dedupe. + expect((calls[failedIndex + 1]?.[0] as { merge?: boolean }).merge).toBe(false) + + const lastSave = calls.at(-1)?.[0] as { + messages?: Array> + merge?: boolean + } + const savedTurns = (lastSave?.messages ?? []).filter( + (m) => + m.role === "user" && + !m.isTruncationMarker && + Array.isArray(m.content) && + (m.content as { text?: string }[]).some((b) => b?.text === "long request"), + ) + expect(savedTurns).toHaveLength(1) + + // The latch clears once an authoritative write lands: later saves may + // merge again. + await task.retrySaveApiConversationHistory() + expect(mockSaveApiMessages.mock.calls.at(-1)?.[0]).toMatchObject({ merge: true }) + }, + ) + + it("keeps the saved user turn on disk when the task aborts before the retry re-add", async () => { + mockSaveApiMessages.mockResolvedValue([]) + + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + const access = task as unknown as { + diffViewProvider: { reset: () => Promise } + safeEnsureModelFetched: () => Promise + presentAssistantMessageSafe: () => void + } + vi.spyOn(access.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(access, "safeEnsureModelFetched").mockResolvedValue(undefined) + vi.spyOn(access, "presentAssistantMessageSafe").mockImplementation(() => {}) + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } as never) + const realSay = task.say.bind(task) + vi.spyOn(task, "say").mockImplementation(async (...args: Parameters) => { + if (args[0] === "api_req_retried") { + // The user cancels right after the retry branch ran: the abort + // request lands before any re-add could run, through the public + // run-state API (abort is getter-only and has no setter). + task.requestAbort(false) + throw new Error("cancelled") + } + return realSay(...args) + }) + + async function* truncatedStream(): AsyncGenerator { + yield { type: "text", text: "partial answer" } + throw new OutputTokenLimitError() + } + + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => truncatedStream()) + + // The loop ends through the cancellation-aware catch path, which + // reports true to the parent loop; no unexpected rejection occurs. + const endState = await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + expect(attemptApiRequestSpy).toHaveBeenCalled() + // The abort request genuinely engaged the run state (the previous + // getter-only assignment threw before any cancellation existed). + expect(task.abort).toBe(true) + expect(endState).toBe(true) + + // The removal stayed in memory: no persisted state may lack the + // saved turn, or a resumed task finds a tool_use without its + // tool_result (PR 2696 review round 9). + const savedInputs = mockSaveApiMessages.mock.calls.map( + ([arg]) => arg.messages as Array<{ role?: string; content?: unknown }>, + ) + expect(savedInputs.length).toBeGreaterThan(0) + for (const messages of savedInputs) { + expect( + messages.some( + (m) => + m.role === "user" && + Array.isArray(m.content) && + (m.content as { text?: string }[]).some((b) => b?.text === "long request"), + ), + ).toBe(true) + } + }) + it("uses authoritative replacement for explicit API history overwrites", async () => { const task = new Task({ provider: mockProvider, @@ -1478,6 +1717,68 @@ describe("Task persistence", () => { }, ]) }) + + it("keeps a trailing degradation marker in the saved history when resuming", async () => { + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + historyItem: { + id: "marker-resume", + number: 3, + ts: Date.now(), + task: "Marker resume", + tokensIn: 10, + tokensOut: 5, + totalCost: 0.001, + }, + startTask: false, + initialStatus: "interrupted", + }) + const initiateTaskLoopSpy = vi + .spyOn(getTaskPersistenceAccess(task), "initiateTaskLoop") + .mockResolvedValue(undefined) + vi.spyOn(task, "ask").mockResolvedValue({ response: "noButtonClicked" }) + + // The persisted history ends with a degradation marker carrying + // the original tool_result content a later rewind restores. + mockReadApiMessages.mockResolvedValue([ + { + role: "assistant", + content: [{ type: "tool_use", id: "toolu_mr_1", name: "read_file", input: { path: "a.txt" } }], + }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_mr_1", content: "" }], + }, + { + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + ts: 111, + isTruncationMarker: true, + truncationId: "trunc-mr-1", + degradedOriginals: [{ index: 1, blockIndex: 0, content: [{ type: "text", text: "4MB output" }] }], + }, + ]) + + mockProvider.taskHistoryStore.get = vi.fn().mockReturnValue({ + id: "marker-resume", + status: "interrupted", + }) + + await getTaskPersistenceAccess(task).resumeTaskFromHistory() + + // The marker must survive the resume: the saved history keeps it + // with its metadata, and the resumed turn does not copy its text + // (PR 2696 review round 7). + const saved = task.apiConversationHistory + expect(saved.at(-1)?.isTruncationMarker).toBe(true) + expect((saved.at(-1) as { degradedOriginals?: unknown[] }).degradedOriginals).toHaveLength(1) + const newUserContent = await initiateTaskLoopSpy.mock.calls[0][0] + const texts = newUserContent + .filter((block) => block.type === "text") + .map((block) => (block as { text: string }).text) + expect(texts.join("\n")).not.toContain("Tool result degradation") + }) }) describe("pending action resume", () => { diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index af0b407b50..bafafc97a5 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -54,6 +54,7 @@ import { readFileTool } from "../../tools/ReadFileTool" import { attemptCompletionTool } from "../../tools/AttemptCompletionTool" import { writeToFileTool } from "../../tools/WriteToFileTool" import { manageContext } from "../../context-management" +import { ContextManagementNoProgressError } from "../../context-management" type TaskTestAccess = { getSystemPrompt: ( @@ -686,7 +687,7 @@ describe("Cline", () => { expect(askSpy).toHaveBeenCalledWith("api_req_failed", expect.stringContaining("Output token limit reached")) }) - it("retries from a fresh attempt count when the user confirms", async () => { + it("re-adds the saved user turn exactly once when the user confirms", async () => { const task = await createAutoApprovedTask() vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) const attemptApiRequestSpy = vi @@ -699,7 +700,167 @@ describe("Cline", () => { await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) - expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 0]) + // The retry bumps the attempt count; re-insertion of the saved + // turn is tracked by userMessageWasRemoved, not by the count + // (PR 2696 review round 7). + expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 1]) + // The failed attempt saved the turn; the confirmed retry must not + // persist a second copy. + const savedTurns = task.apiConversationHistory.filter( + (m) => + m.role === "user" && + Array.isArray(m.content) && + m.content.some((b) => (b as { text?: string }).text === "long request"), + ) + expect(savedTurns).toHaveLength(1) + }) + + it("keeps the recovery marker when the confirmed retry removes the saved turn", async () => { + const task = await createAutoApprovedTask() + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => { + // Context recovery ran before the stream failed: the marker + // (role "user") now trails the saved turn, so the history + // tail is not this attempt's turn. + task.apiConversationHistory.push({ + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + ts: Date.now() + 1, + isTruncationMarker: true, + truncationId: "trunc-retry", + degradedOriginals: [{ index: 0, blockIndex: 0, content: "original" }], + }) + return truncatedStream() + }) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "done" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + + // The retry must remove the saved turn, not the marker: the marker + // carries the degradedOriginals a later rewind restores (PR 2696 + // review round 8). + const marker = task.apiConversationHistory.find((m) => m.isTruncationMarker) + expect(marker?.truncationId).toBe("trunc-retry") + expect(marker?.degradedOriginals?.[0]?.content).toBe("original") + const savedTurns = task.apiConversationHistory.filter( + (m) => + m.role === "user" && + Array.isArray(m.content) && + m.content.some((b) => (b as { text?: string }).text === "long request"), + ) + expect(savedTurns).toHaveLength(1) + expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 1]) + }) + }) + describe("context management no-progress mid-stream", () => { + async function* noProgressStream(): AsyncGenerator { + yield { type: "text", text: "partial answer" } + throw new ContextManagementNoProgressError( + "Unable to reduce context: tool result degradation did not reduce the recounted tokens.", + ) + } + + async function createAutoApprovedTask() { + vi.spyOn(mockProvider, "getState").mockResolvedValue( + providerStateWith({ autoApprovalEnabled: true, requestDelaySeconds: 0 }), + ) + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + vi.spyOn(task.diffViewProvider, "reset").mockResolvedValue(undefined) + vi.spyOn(getTaskTestAccess(task), "safeEnsureModelFetched").mockResolvedValue(stubModelInfo) + vi.spyOn(getTaskTestAccess(task), "presentAssistantMessageSafe").mockImplementation(() => {}) + return task + } + + it("asks once instead of auto-retrying, even with auto-approval", async () => { + const task = await createAutoApprovedTask() + const askSpy = vi + .spyOn(task, "ask") + .mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) + const backoffSpy = vi.spyOn(getTaskTestAccess(task), "backoffAndAnnounce") + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementation(() => noProgressStream()) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + + expect(attemptApiRequestSpy).toHaveBeenCalledOnce() + expect(backoffSpy).not.toHaveBeenCalled() + expect(askSpy).toHaveBeenCalledWith("api_req_failed", expect.stringContaining("Unable to reduce context")) + }) + + it("re-adds the saved user turn exactly once when the user confirms", async () => { + const task = await createAutoApprovedTask() + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => noProgressStream()) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "done" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) + + // The retry bumps the attempt count; re-insertion of the saved + // turn is tracked by userMessageWasRemoved, not by the count + // (PR 2696 review round 7). + expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 1]) + // The failed attempt saved the turn; the confirmed retry must not + // persist a second copy. + const savedTurns = task.apiConversationHistory.filter( + (m) => + m.role === "user" && + Array.isArray(m.content) && + m.content.some((b) => (b as { text?: string }).text === "long request"), + ) + expect(savedTurns).toHaveLength(1) + }) + + it("keeps a tool-result turn un-duplicated across a confirmed retry", async () => { + // A tool_result turn duplicates as plain text on the second save + // (prepareUserMessage converts the orphan), so the confirmed + // retry must remove the saved turn before re-adding it once + // (PR 2696 review round 7, thread on Task.ts:4870). + const task = await createAutoApprovedTask() + vi.spyOn(task, "ask").mockResolvedValue({ response: "yesButtonClicked" } satisfies TaskAskResult) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementationOnce(() => noProgressStream()) + .mockImplementationOnce(() => asyncStreamFrom([{ type: "text", text: "done" }])) + .mockImplementation(() => { + throw new Error("stop after retry response") + }) + + await task.recursivelyMakeClineRequests([ + { type: "tool_result", tool_use_id: "call_np_1", content: "large tool output" }, + ]) + + expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 1]) + // The saved turn keeps no raw tool_result (prepareUserMessage + // converts an orphan to "Tool result:" text), so count the user + // turns carrying the converted payload: the failed attempt saved + // one; the confirmed retry must not persist a second copy. + const savedTurns = task.apiConversationHistory.filter( + (m) => + m.role === "user" && + Array.isArray(m.content) && + m.content.some( + (b) => + (b as { text?: string }).text?.includes("Tool result:") && + (b as { text?: string }).text?.includes("large tool output"), + ), + ) + expect(savedTurns).toHaveLength(1) }) }) @@ -3366,6 +3527,173 @@ describe("Cline", () => { expect(reported.newContextTokens).toBeGreaterThan(0) expect(reported.newContextTokens).toBeLessThan(reported.prevContextTokens) }) + + it("does not report no-progress when a condense failure leaves the history below the limit", async () => { + // A failed condensation with the history still under the fallback + // truncation limit leaves the context usable: the handler must not + // treat the unchanged history as a no-progress round and stop the + // request (PR 2696 review round 7). + const { task } = await createOverflowingTask(providerStateWith()) + const original = task.apiConversationHistory + vi.mocked(manageContext).mockResolvedValueOnce({ + messages: original, + prevContextTokens: 100_000, + summary: "", + cost: 0, + error: "condense backend down", + }) + + // Before the noProgress flag, the unchanged history plus the + // error threw ContextManagementNoProgressError here. + await expect( + getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo), + ).resolves.toBeUndefined() + }) + + it("rejects with ContextManagementNoProgressError on a true no-progress round", async () => { + // Regression evidence (PR 2696 review round 10, pre-merge check): + // a genuine no-progress reduction must stop the emergency handler + // with ContextManagementNoProgressError instead of falling through, + // and the round must not rewrite the history the caller came with. + const { task } = await createOverflowingTask(providerStateWith()) + const original = task.apiConversationHistory + vi.mocked(manageContext).mockResolvedValueOnce({ + messages: original, + prevContextTokens: 100_000, + summary: "", + cost: 0, + noProgress: true, + error: "Unable to reduce context: no candidates past the threshold", + }) + + await expect(getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo)).rejects.toThrow( + ContextManagementNoProgressError, + ) + expect(task.apiConversationHistory).toBe(original) + // The stated no-progress contract: recovery must not rewrite + // history. The identity assert alone passes even if recovery + // called the writer before throwing. + expect(task.overwriteApiConversationHistory).not.toHaveBeenCalled() + }) + + it("runs the real history overwrite when the emergency fallback truncates", async () => { + const { task } = await createOverflowingTask(providerStateWith()) + // Undo the helper's overwrite mock: the fallback must exercise the + // real write path, not a double (PR 2696 review round 8). + vi.mocked(task.overwriteApiConversationHistory).mockRestore() + // Enough visible messages for the 50% fallback to hide a pair. + task.apiConversationHistory = ["a", "b", "c", "d", "e"].map((text, index) => ({ + role: index % 2 === 0 ? ("user" as const) : ("assistant" as const), + content: [{ type: "text" as const, text }], + ts: index + 1, + })) + const original = task.apiConversationHistory + vi.mocked(summarizeConversation).mockResolvedValueOnce({ + messages: task.apiConversationHistory, + summary: "", + cost: 0, + error: "Condensing failed: rate limited", + }) + + await getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo) + + // The real overwrite replaced the history array: identity changed + // and the truncation marker is in the live history. + expect(task.apiConversationHistory).not.toBe(original) + expect(task.apiConversationHistory.some((m) => m.isTruncationMarker)).toBe(true) + }) + + // Automatic request path: manageContext runs inside attemptApiRequest + // when auto-condense is on and the context crosses the threshold. Both + // review paths must behave like the emergency handler (PR 2696 + // review round 8). + const setupAutomaticPath = async () => { + vi.spyOn(mockProvider, "getState").mockResolvedValue(providerStateWith({ mode: "code" })) + const task = new Task({ + provider: mockProvider, + apiConfiguration: mockApiConfig, + task: "test task", + startTask: false, + }) + await task.getTaskMode() + vi.spyOn(getTaskTestAccess(task), "getSystemPrompt").mockResolvedValue("mock system prompt") + vi.spyOn(task, "getTokenUsage").mockReturnValue({ + totalCost: 0, + totalTokensIn: 0, + totalTokensOut: 0, + contextTokens: 100_000, + }) + vi.spyOn(task.api, "getModel").mockReturnValue({ + id: "ctx-model", + info: { contextWindow: 50_000, maxTokens: 1024, supportsPromptCache: false } as ModelInfo, + }) + const state = await mockProvider.getState() + vi.spyOn(mockProvider, "getState").mockResolvedValue({ + ...state, + apiConfiguration: mockApiConfig, + mode: "code", + autoCondenseContext: true, + autoCondenseContextPercent: 80, + requestDelaySeconds: 0, + customModes: [], + experiments: {}, + disabledTools: [], + customSupportPrompts: {}, + autoApprovalEnabled: true, + profileThresholds: {}, + currentApiConfigName: "default", + }) + task.apiConversationHistory = [{ role: "user", content: [{ type: "text", text: "x" }], ts: Date.now() }] + return task + } + + it("proceeds past a condense failure on the automatic request path", async () => { + const task = await setupAutomaticPath() + const original = task.apiConversationHistory + vi.mocked(manageContext).mockResolvedValueOnce({ + messages: original, + prevContextTokens: 100_000, + summary: "", + cost: 0, + error: "condense backend down", + }) + const stream = (async function* () { + yield { type: "text", text: "ok" } as ApiStreamChunk + })() + const createMessageSpy = vi.spyOn(task.api, "createMessage").mockReturnValue(stream) + + await expect(task.attemptApiRequest().next()).resolves.toEqual({ + done: false, + value: { type: "text", text: "ok" }, + }) + // The condense error did not stop the automatic request path: the + // request went out and the history is unchanged. + expect(createMessageSpy).toHaveBeenCalledOnce() + expect(task.apiConversationHistory).toBe(original) + }) + + it("stops the automatic request path on a true no-progress round", async () => { + const task = await setupAutomaticPath() + const original = task.apiConversationHistory + vi.mocked(manageContext).mockResolvedValueOnce({ + messages: original, + prevContextTokens: 100_000, + summary: "", + cost: 0, + error: "Unable to reduce context: tool result degradation did not reduce the recounted tokens.", + truncationId: "trunc-np", + messagesRemoved: 0, + newContextTokensAfterTruncation: 100_000, + noProgress: true, + }) + const createMessageSpy = vi.spyOn(task.api, "createMessage").mockImplementation(() => { + throw new Error("no request may leave the automatic path on no progress") + }) + + await expect(task.attemptApiRequest().next()).rejects.toThrow(ContextManagementNoProgressError) + expect(createMessageSpy).not.toHaveBeenCalled() + expect(task.apiConversationHistory).toBe(original) + }) }) it("uses the task mode when manually condensing after focused state changes", async () => { @@ -7993,6 +8321,9 @@ describe("Cline", () => { expect.objectContaining({ content: expect.arrayContaining([{ type: "text", text: "expanded input" }]), }), + // The retry re-add passes the persist-merge flag (round 9). + undefined, + true, ) }) diff --git a/src/core/task/messageCounting.ts b/src/core/task/messageCounting.ts index 98ba0c4904..e16a66773a 100644 --- a/src/core/task/messageCounting.ts +++ b/src/core/task/messageCounting.ts @@ -1,10 +1,21 @@ /** - * Add non-empty user content on the first attempt. Retries keep the saved turn. - * Empty initial content resumes a turn that is already in history. + * Whether the current turn's user message should be added to API conversation + * history (and counted towards the per-task message-count telemetry summary). + * + * Added when: + * 1. This is the first attempt (retryAttempt === 0) AND the content is non-empty, OR + * 2. The message was removed in a previous iteration (userMessageWasRemoved === true) + * + * Empty content on a first attempt signals a delegation resume, where the user message + * with tool_result and env details is already in history -- adding it again would create + * a duplicate (and inflate the message count). Retries without a removal keep the saved + * turn: they resume it from history instead of persisting a second copy (#2701). */ export function shouldAddUserMessageToHistory(params: { retryAttempt: number | undefined isEmptyUserContent: boolean + userMessageWasRemoved?: boolean | undefined }): boolean { - return (params.retryAttempt ?? 0) === 0 && !params.isEmptyUserContent + const { retryAttempt, isEmptyUserContent, userMessageWasRemoved } = params + return ((retryAttempt ?? 0) === 0 && !isEmptyUserContent) || Boolean(userMessageWasRemoved) } diff --git a/src/utils/__tests__/tiktoken.spec.ts b/src/utils/__tests__/tiktoken.spec.ts index 6b782dbb26..ba887bf9c2 100644 --- a/src/utils/__tests__/tiktoken.spec.ts +++ b/src/utils/__tests__/tiktoken.spec.ts @@ -1,6 +1,8 @@ // npx vitest utils/__tests__/tiktoken.spec.ts import { tiktoken } from "../tiktoken" +import { Tiktoken } from "tiktoken/lite" +import o200kBase from "tiktoken/encoders/o200k_base" import { Anthropic } from "@anthropic-ai/sdk" type TextContentBlockWithoutText = Omit & { text?: string } @@ -303,4 +305,43 @@ describe("tiktoken", () => { expect(largeResult).toBeGreaterThan(smallResult) }) }) + + describe("long-string estimates (issue 1254 regression evidence)", () => { + const sentence = "The assistant answered the user question with a short paragraph. " + const exactCount = (text: string): number => + new Tiktoken(o200kBase.bpe_ranks, o200kBase.special_tokens, o200kBase.pat_str).encode(text, undefined, []) + .length + + it("encodes a text of exactly 50,000 characters exactly", async () => { + const text = sentence.repeat(Math.ceil(50_000 / sentence.length)).slice(0, 50_000) + const exact = exactCount(text) + + const result = await tiktoken([{ type: "text", text }]) + + // The export applies the fudge factor on top of the encoder count; + // the boundary length must take the exact encode path. + expect(result).toBe(Math.ceil(exact * 1.5)) + }) + + it("estimates 50,001+ characters close to the exact count for uniform text", async () => { + const text = sentence.repeat(Math.ceil(60_000 / sentence.length)).slice(0, 60_000) + const exact = exactCount(text) + + const result = await tiktoken([{ type: "text", text }]) + + // The sampled estimate stays within 5 percent of the exact count + // for uniform natural text. + const estimated = result / 1.5 + expect(Math.abs(estimated - exact) / exact).toBeLessThan(0.05) + }) + + it("completes a 4 MB separator-less run without trapping or hanging", async () => { + const blob = "a".repeat(4 * 1024 * 1024) + + const result = await tiktoken([{ type: "text", text: blob }]) + + expect(result).toBeGreaterThan(0) + expect(result).toBeLessThan(blob.length * 2) + }) + }) }) diff --git a/src/utils/tiktoken.ts b/src/utils/tiktoken.ts index b543873fc6..65547be953 100644 --- a/src/utils/tiktoken.ts +++ b/src/utils/tiktoken.ts @@ -64,14 +64,41 @@ export async function tiktoken(content: Anthropic.Messages.ContentBlockParam[]): encoder = new Tiktoken(o200kBase.bpe_ranks, o200kBase.special_tokens, o200kBase.pat_str) } + // tiktoken's WASM encoder has two failure modes on very long strings + // (issue 1254): a 4 MB single encode traps ("unreachable"), and long + // separator-less runs — minified JSON, base64 blobs — encode + // pathologically slowly (~250 ms per 1 000 chars, so a 4 MB blob would + // hang recovery for minutes). Recovery must never hang on the oversized + // result it exists to shrink, so: short strings encode exactly, and + // longer strings are estimated by measuring tokens-per-char on three + // 10 000-char slices and extrapolating. Natural text stays near-exact + // (uniform density), the pathological worst case is bounded to three + // short encodes, and no encode ever exceeds the trap range. + const ENCODE_DIRECT_CHARS = 50_000 + const SAMPLE_CHARS = 10_000 + const SAMPLE_COUNT = 3 + const estimateTokens = (text: string): number => { + if (text.length <= ENCODE_DIRECT_CHARS) { + return encoder!.encode(text, undefined, []).length + } + let sampleTokens = 0 + let sampleChars = 0 + for (let s = 0; s < SAMPLE_COUNT; s++) { + const start = Math.min(Math.floor((text.length / SAMPLE_COUNT) * s), text.length - SAMPLE_CHARS) + const slice = text.slice(start, start + SAMPLE_CHARS) + sampleTokens += encoder!.encode(slice, undefined, []).length + sampleChars += slice.length + } + return Math.ceil((sampleTokens / sampleChars) * text.length) + } + // Process each content block using the cached encoder. for (const block of content) { if (block.type === "text") { const text = block.text || "" if (text.length > 0) { - const tokens = encoder.encode(text, undefined, []) - totalTokens += tokens.length + totalTokens += estimateTokens(text) } } else if (block.type === "image") { // For images, calculate based on data size. @@ -87,15 +114,13 @@ export async function tiktoken(content: Anthropic.Messages.ContentBlockParam[]): // Serialize tool_use block to text and count tokens const serialized = serializeToolUse(block as Anthropic.Messages.ToolUseBlockParam) if (serialized.length > 0) { - const tokens = encoder.encode(serialized, undefined, []) - totalTokens += tokens.length + totalTokens += estimateTokens(serialized) } } else if (block.type === "tool_result") { // Serialize tool_result block to text and count tokens const serialized = serializeToolResult(block as Anthropic.Messages.ToolResultBlockParam) if (serialized.length > 0) { - const tokens = encoder.encode(serialized, undefined, []) - totalTokens += tokens.length + totalTokens += estimateTokens(serialized) } } }