From 96ca9aee9b3e968db8bb9d627d4b208bef123d4d Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 09:25:07 +0100 Subject: [PATCH 01/14] fix(context-management): issue #1254 zero-progress truncation no longer reports success --- .../tla/CondenseTruncate.NoPairDeg.cfg | 9 + .../tla/CondenseTruncate.ZeroOK.cfg | 9 + docs/architecture/tla/CondenseTruncate.cfg | 2 +- docs/architecture/tla/CondenseTruncate.tla | 316 ++++++++++-------- src/core/context-management/index.ts | 96 +++++- 5 files changed, 294 insertions(+), 138 deletions(-) create mode 100644 docs/architecture/tla/CondenseTruncate.NoPairDeg.cfg create mode 100644 docs/architecture/tla/CondenseTruncate.ZeroOK.cfg 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.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..aae2586eec 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 NoZeroProgressSuccess BoundedRecovery diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 85c4d69801..8ef359fab0 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -1,96 +1,86 @@ ---- 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. +\* 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. -\* 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. +\* Truncation hides only messages that the sink already hides. +\* 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 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. An +\* oversized history then retries forever. PR 1617 was withdrawn; its review findings +\* (identity of degraded copies, hidden-content token accounting, one progress measure +\* for success) guided this design; no code of that PR is reused. Degradation must not +\* orphan either half of a tool_use/tool_result 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. +\* 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 code +\* on 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: the live code before this fix (issue 1254). +\* NoPairDeg degrades a tool result and also tags its paired tool use. Other mode values +\* use the Fixed arms. +\* LiveMsg correction (PR 2647 round 3): the first version approximated the sink with tag matching; the real rule is position-aware. +\* Round 4 (PR 2647, thread 4657986893): excluding the summary from the candidates split +\* tool_use/tool_result pairs, and the Messages API rejects a split pair. The summary is +\* the first candidate and skip-first keeps it. +\* Mutation round (PR 2647): the getExistingSummaryIds guard cannot be expressed here +\* (IDs abstracted away). Four boundary mutants were equivalent; the code pins them. +\* Not modeled: the token budget that starts a recovery round, real token sizes (the +\* weight is countable units), the truncation marker text, and cleanupAfterTruncation. +\* A rewind that orphans tags is the Rewind action. Eligibility here also requires a live +\* paired tool use; the code checks visibility only, and 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 with 4191 distinct states. ZeroOK fails +\* NoZeroProgressSuccess with 5 states. NoPairDeg fails DegradationPreservesPair with 13 +\* states. UnfixedRemoved and UnfixedCount fail with 92 states each. CoarseSelection +\* fails with 17, CoarseCount with 2517, MatchedSelection with 64, MatchedSummary with +\* 816, MatchedCount with 1143. Every variant models a rule that the fix replaces. +\* Findings: covered 4, added 4, gap 5. The two failures of issue 1823 are covered. +\* PR 2647 rounds 2-4 added the Rewind action, the boundary VisMsg, SummaryUntagged and +\* the skip-first rule (threads 4657855243, 4657986893). Issue 1254 adds the four new +\* invariants, with ZeroOK as the reproduction of the live code and NoPairDeg as the pair +\* sabotage. Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the +\* recovery budget, and the weaker code eligibility. +\* 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. The unit tests replay both rules. 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] +Msg == [cond : BOOLEAN, trunc : BOOLEAN, mark : BOOLEAN, summ : BOOLEAN, stale : BOOLEAN, tres : BOOLEAN, big : BOOLEAN] +FreshMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] +SummaryMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> TRUE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] +MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] +ToolResMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> TRUE, big |-> TRUE] -VARIABLES n, msgs, last, repValid, repTokens -vars == <> +VARIABLES n, msgs, last, repValid, repTokens, phase, stall, prevWt, degIdx +vars == <> \* The latest summary, when one exists. SumIdxSet == {i \in 1..n : msgs[i].summ} @@ -112,49 +102,39 @@ 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}) + +\* 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 +149,23 @@ 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 + /\ UNCHANGED <> + +\* 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 /\ UNCHANGED <> -\* The condense source: every untagged message gets condenseParent, then a summary -\* follows. A fresh tag always has a live summary (stale = FALSE). +\* 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 +173,16 @@ 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 /\ UNCHANGED <> -\* 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 +191,10 @@ 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 \* 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 +206,54 @@ 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 /\ UNCHANGED last +\* 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 + /\ LET Vis == {i \in 1..n : VisMsg(Mode, i)} + vc == Cardinality(Vis) + IN /\ vc >= 1 + /\ RemovedCount(vc) = 0 + /\ LET Deg == {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big /\ LiveMsg(i - 1)} + IN \/ /\ Deg # {} + /\ Mode # "ZeroOK" + /\ LET d == CHOOSE x \in Deg : TRUE + dm == IF Mode = "NoPairDeg" + THEN [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE], + ![d - 1] = [msgs[d - 1] EXCEPT !.trunc = TRUE]] + ELSE [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE]] + IN /\ msgs' = dm + /\ phase' = "ok" /\ stall' = 0 /\ prevWt' = LiveWeight /\ degIdx' = d + /\ repValid' = FALSE + /\ UNCHANGED <> + \/ /\ (Deg = {} \/ Mode = "ZeroOK") + /\ phase' = IF Mode = "ZeroOK" THEN "ok" ELSE "err" + /\ stall' = stall + 1 + /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ repValid' = FALSE + /\ UNCHANGED <> + 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 -Next == \/ AddMsg \/ Condense \/ Truncate \/ Rewind +Next == \/ AddMsg \/ AddToolPair \/ Condense \/ Truncate \/ Rewind \/ Recover 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 \* 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 +274,28 @@ 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 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" + ==== diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index 4ab38053ee..f63a016c9f 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -73,6 +73,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 +130,83 @@ 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 }[] = [] + messages.forEach((msg, index) => { + if (msg.truncationParent || msg.isTruncationMarker) return + const content = msg.content + if (!Array.isArray(content)) return + for (const block of content) { + 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) + ? JSON.stringify(b.content).length + : 0 + // Only oversized results are eligible for degradation. + 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 }) + } + } + } + } + }) + + if (eligible.length === 0) { + return { + messages, + truncationId, + messagesRemoved: 0, + noProgress: true, + } + } + + // Degrade the largest eligible tool result (one step per round). + eligible.sort((a, b) => b.size - a.size) + const targetIndex = eligible[0].index + 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) => { + if (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 + }) + return { - messages, + messages: degradedMessages, truncationId, messagesRemoved: 0, + degraded: true, } } @@ -399,6 +475,22 @@ export async function manageContext({ if (prevContextTokens > allowedTokens) { 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, + } + } + // 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 From 6d1b9b33448eb4ebce4827bbc68e7a38746c2fbb Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 10:54:27 +0100 Subject: [PATCH 02/14] fix(context-management): degradation scans only live candidates and clears the selected block (#1254) PR 2696 review round 1: the degradation scan now starts at the latest-summary boundary the recount uses, an empty tool_result array is never a candidate, the clear touches only the selected block, and a degraded round reports the controlled error unless the recounted tokens shrink. Spec: DegSelectionLive, DegradationKeepsOtherBlocks, fake-big shape, PreScan/EmptyOK/AllBlocks sabotage cfgs; TLC base pass, 12 variants fail. --- .../tla/CondenseTruncate.AllBlocks.cfg | 9 ++ .../tla/CondenseTruncate.EmptyOK.cfg | 9 ++ .../tla/CondenseTruncate.PreScan.cfg | 9 ++ docs/architecture/tla/CondenseTruncate.cfg | 2 +- docs/architecture/tla/CondenseTruncate.tla | 135 +++++++++++------- .../__tests__/context-management.spec.ts | 29 ++++ .../__tests__/truncation.spec.ts | 100 +++++++++++++ src/core/context-management/index.ts | 49 +++++-- 8 files changed, 284 insertions(+), 58 deletions(-) create mode 100644 docs/architecture/tla/CondenseTruncate.AllBlocks.cfg create mode 100644 docs/architecture/tla/CondenseTruncate.EmptyOK.cfg create mode 100644 docs/architecture/tla/CondenseTruncate.PreScan.cfg 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.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.cfg b/docs/architecture/tla/CondenseTruncate.cfg index aae2586eec..e8760821d4 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 SuccessIsMonotonic DegradationPreservesPair NoZeroProgressSuccess BoundedRecovery +INVARIANTS TypeOK RemovedIsLive CountExact SelectionMatchesLive SummaryUntagged SuccessIsMonotonic DegradationPreservesPair DegSelectionLive DegradationKeepsOtherBlocks NoZeroProgressSuccess BoundedRecovery diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 8ef359fab0..a0fd3ca9b0 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -8,20 +8,18 @@ \* 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. -\* Failure 2: the count after truncation ignores condenseParent, so it counts messages that -\* the sink already hides and overstates the live context. +\* 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. An -\* oversized history then retries forever. PR 1617 was withdrawn; its review findings -\* (identity of degraded copies, hidden-content token accounting, one progress measure -\* for success) guided this design; no code of that PR is reused. Degradation must not -\* orphan either half of a tool_use/tool_result pair, and a stalled round ends in Error. +\* 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 @@ -34,50 +32,63 @@ \* 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. \* 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 code -\* on 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: the live code before this fix (issue 1254). -\* NoPairDeg degrades a tool result and also tags its paired tool use. Other mode values -\* use the Fixed arms. -\* LiveMsg correction (PR 2647 round 3): the first version approximated the sink with tag matching; the real rule is position-aware. -\* Round 4 (PR 2647, thread 4657986893): excluding the summary from the candidates split -\* tool_use/tool_result pairs, and the Messages API rejects a split pair. The summary is -\* the first candidate and skip-first keeps it. -\* Mutation round (PR 2647): the getExistingSummaryIds guard cannot be expressed here -\* (IDs abstracted away). Four boundary mutants were equivalent; the code pins them. -\* Not modeled: the token budget that starts a recovery round, real token sizes (the -\* weight is countable units), the truncation marker text, and cleanupAfterTruncation. -\* A rewind that orphans tags is the Rewind action. Eligibility here also requires a live -\* paired tool use; the code checks visibility only, and a pre-existing sliding-window -\* split of a pair is out of scope for issue 1254. +\* 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. 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 with 4191 distinct states. ZeroOK fails -\* NoZeroProgressSuccess with 5 states. NoPairDeg fails DegradationPreservesPair with 13 -\* states. UnfixedRemoved and UnfixedCount fail with 92 states each. CoarseSelection -\* fails with 17, CoarseCount with 2517, MatchedSelection with 64, MatchedSummary with -\* 816, MatchedCount with 1143. Every variant models a rule that the fix replaces. -\* Findings: covered 4, added 4, gap 5. The two failures of issue 1823 are covered. -\* PR 2647 rounds 2-4 added the Rewind action, the boundary VisMsg, SummaryUntagged and -\* the skip-first rule (threads 4657855243, 4657986893). Issue 1254 adds the four new -\* invariants, with ZeroOK as the reproduction of the live code and NoPairDeg as the pair -\* sabotage. Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the -\* recovery budget, and the weaker code eligibility. +\* 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. +\* Findings: covered 4, added 7, gap 5. 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). +\* Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the recovery +\* budget, and residual code eligibility details. \* 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. The unit tests replay both rules. +\* 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. The unit tests replay every rule. EXTENDS Naturals, FiniteSets CONSTANTS Mode, MaxMsgs -Msg == [cond : BOOLEAN, trunc : BOOLEAN, mark : BOOLEAN, summ : BOOLEAN, stale : BOOLEAN, tres : BOOLEAN, big : BOOLEAN] -FreshMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] -SummaryMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> TRUE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] -MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, stale |-> FALSE, tres |-> FALSE, big |-> FALSE] -ToolResMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> FALSE, summ |-> FALSE, stale |-> FALSE, tres |-> TRUE, big |-> TRUE] +\* 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, phase, stall, prevWt, degIdx vars == <> @@ -104,7 +115,9 @@ LiveCount == Cardinality({i \in 1..n : LiveMsg(i)}) \* 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}) +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 @@ -164,6 +177,18 @@ AddToolPair == /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ UNCHANGED <> +\* 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 + /\ UNCHANGED <> + \* The condense source: every untagged message gets condenseParent, then a \* summary follows. A fresh tag always has a live summary (stale = FALSE). Condense == @@ -221,14 +246,20 @@ Recover == vc == Cardinality(Vis) IN /\ vc >= 1 /\ RemovedCount(vc) = 0 - /\ LET Deg == {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big /\ LiveMsg(i - 1)} + /\ 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 {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big /\ LiveMsg(i - 1)} IN \/ /\ Deg # {} /\ Mode # "ZeroOK" /\ LET d == CHOOSE x \in Deg : TRUE dm == IF Mode = "NoPairDeg" THEN [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE], ![d - 1] = [msgs[d - 1] EXCEPT !.trunc = TRUE]] - ELSE [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE]] + ELSE IF Mode = "AllBlocks" + THEN [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE, !.big2 = FALSE]] + ELSE [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE, !.fake = FALSE]] IN /\ msgs' = dm /\ phase' = "ok" /\ stall' = 0 /\ prevWt' = LiveWeight /\ degIdx' = d /\ repValid' = FALSE @@ -245,7 +276,7 @@ Init == /\ n = 1 /\ repValid = FALSE /\ repTokens = 0 /\ phase = "run" /\ stall = 0 /\ prevWt = 0 /\ degIdx = 0 -Next == \/ AddMsg \/ AddToolPair \/ Condense \/ Truncate \/ Rewind \/ Recover +Next == \/ AddMsg \/ AddToolPair \/ AddFakePair \/ Condense \/ Truncate \/ Rewind \/ Recover Spec == Init /\ [][Next]_vars TypeOK == /\ n \in 1..MaxMsgs @@ -290,6 +321,14 @@ DegradationPreservesPair == /\ ~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. +DegradationKeepsOtherBlocks == degIdx = 0 \/ msgs[degIdx].big2 + \* 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 diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index e706133e7e..9eb5900f62 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -269,6 +269,35 @@ describe("Context Management", () => { * Tests for the manageContext function */ describe("manageContext", () => { + it("reports the controlled error when degradation cannot shrink the recounted tokens", async () => { + // The recounted total includes the system prompt, which + // prevContextTokens omits, so a huge prompt with a tiny history makes + // a successful degradation impossible: the round must stall with the + // controlled error instead of reporting success (issue 1254). + 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", + }) + + expect(result.error).toBeDefined() + expect(result.messagesRemoved).toBe(0) + expect(result.newContextTokensAfterTruncation).toBeGreaterThanOrEqual(63) + }) 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..aeddae1a08 100644 --- a/src/core/context-management/__tests__/truncation.spec.ts +++ b/src/core/context-management/__tests__/truncation.spec.ts @@ -766,3 +766,103 @@ 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 }[] + + 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("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") + }) +}) diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index f63a016c9f..92f4a1399f 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -135,21 +135,27 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe // 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 }[] = [] + 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 - for (const block of content) { + 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) + : Array.isArray(b.content) && b.content.length > 0 ? JSON.stringify(b.content).length : 0 - // Only oversized results are eligible for degradation. + // 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 @@ -168,11 +174,11 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe } } if (paired) { - eligible.push({ index, size }) + eligible.push({ index, size, blockIndex }) } } } - } + }) }) if (eligible.length === 0) { @@ -184,15 +190,23 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe } } - // Degrade the largest eligible tool result (one step per round). + // 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 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) => { - if (block && typeof block === "object" && (block as { type?: string }).type === "tool_result") { + 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 @@ -531,6 +545,23 @@ 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. + if (truncationResult.degraded && newContextTokensAfterTruncation >= prevContextTokens) { + return { + messages: truncationResult.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, + } + } + return { messages: truncationResult.messages, prevContextTokens, From 5b5fb353fb3c4c33b7f09c2c30978e7ceba5cec9 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 11:39:51 +0100 Subject: [PATCH 03/14] fix(context-management): failed truncation rounds keep the original history (#1254) A degraded round that cannot shrink the recounted tokens reported the cleared tool_result content to the caller, which would persist the loss; the failed round now returns the original messages. Evidence: noProgress and degraded-success manageContext cases, tool_use pairing negatives, marker exclusion, and the original-history assertion on the stall case. Spec ratchet (CondenseTruncate): the recovery scan now accepts either oversized block (Failure 9, thread 4693277487), recovery selects one block per round with the unselected block preserved, and ErrExhaustsCandidates pins an honest Error stop. New OnlyBig sabotage fails on the unfixed single-block scan; base cfg passes with repeated one-block recovery reachable (6691 states). --- .../tla/CondenseTruncate.OnlyBig.cfg | 10 +++ docs/architecture/tla/CondenseTruncate.cfg | 2 +- docs/architecture/tla/CondenseTruncate.tla | 70 ++++++++++++++----- .../__tests__/context-management.spec.ts | 67 ++++++++++++++++++ .../__tests__/truncation.spec.ts | 44 ++++++++++++ src/core/context-management/index.ts | 4 +- 6 files changed, 176 insertions(+), 21 deletions(-) create mode 100644 docs/architecture/tla/CondenseTruncate.OnlyBig.cfg 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.cfg b/docs/architecture/tla/CondenseTruncate.cfg index e8760821d4..027de8ba61 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 SuccessIsMonotonic DegradationPreservesPair DegSelectionLive DegradationKeepsOtherBlocks NoZeroProgressSuccess BoundedRecovery +INVARIANTS TypeOK RemovedIsLive CountExact SelectionMatchesLive SummaryUntagged SuccessIsMonotonic DegradationPreservesPair DegSelectionLive DegradationKeepsOtherBlocks NoZeroProgressSuccess BoundedRecovery ErrExhaustsCandidates diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index a0fd3ca9b0..777099e918 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -42,13 +42,21 @@ \* 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. \* 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. Other modes use the Fixed arms. +\* AllBlocks also clears the second oversized block. OnlyBig scans only the first +\* oversized block. 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 @@ -60,13 +68,15 @@ \* 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. -\* Findings: covered 4, added 7, gap 5. Issue 1823 failures are covered; PR 2647 rounds +\* Findings: covered 4, added 8, gap 6. 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. \* Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the recovery -\* budget, and residual code eligibility details. +\* budget, the caller persist path for a failed round, and residual code eligibility. \* 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 @@ -74,7 +84,9 @@ \* 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. The unit tests replay every rule. +\* oversized block vanishes. OnlyBig gives Init, AddToolPair, Recover twice: the +\* second round reports Error while the second block still weighs. The unit tests +\* replay every rule. EXTENDS Naturals, FiniteSets @@ -90,8 +102,10 @@ MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, st 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, phase, stall, prevWt, degIdx -vars == <> +VARIABLES n, msgs, last, repValid, repTokens, phase, stall, prevWt, degIdx, degClr2 +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} @@ -162,7 +176,7 @@ 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 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> \* A tool turn: an assistant tool use and a user tool result, adjacent. The @@ -174,7 +188,7 @@ AddToolPair == ELSE IF i = n + 2 THEN ToolResMsg ELSE msgs[i]] /\ repValid' = FALSE - /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> \* An empty-content tool turn: the serialized empty array passes the size @@ -186,7 +200,7 @@ AddFakePair == ELSE IF i = n + 2 THEN FakeToolResMsg ELSE msgs[i]] /\ repValid' = FALSE - /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> \* The condense source: every untagged message gets condenseParent, then a @@ -198,7 +212,7 @@ 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 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> \* The code under test. It hides half of the visible messages after the first @@ -219,7 +233,7 @@ Truncate == /\ 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 + /\ phase' = "ok" /\ stall' = 0 /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ degClr2' = FALSE \* 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. @@ -232,7 +246,7 @@ Rewind == /\ msgs' = [i \in 1..(k - 1) |-> IF msgs[i].cond THEN [msgs[i] EXCEPT !.stale = TRUE] ELSE msgs[i]] /\ repValid' = FALSE /\ repTokens' = 0 - /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 + /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED last \* One recovery round of manageContext (issue 1254) on a zero-removal history. @@ -250,31 +264,39 @@ Recover == 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 {i \in 1..n : LiveMsg(i) /\ msgs[i].tres /\ msgs[i].big /\ 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] = [msgs[d] EXCEPT !.big = FALSE], + 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 [msgs EXCEPT ![d] = [msgs[d] EXCEPT !.big = FALSE, !.fake = 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 <> \/ /\ (Deg = {} \/ Mode = "ZeroOK") /\ phase' = IF Mode = "ZeroOK" THEN "ok" ELSE "err" /\ stall' = stall + 1 - /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ repValid' = FALSE + /\ prevWt' = LiveWeight /\ degIdx' = 0 /\ degClr2' = FALSE /\ repValid' = FALSE /\ UNCHANGED <> Init == /\ n = 1 /\ msgs = [i \in 1..1 |-> FreshMsg] /\ last = [rep |-> 0, lost |-> 0] /\ repValid = FALSE /\ repTokens = 0 - /\ phase = "run" /\ stall = 0 /\ prevWt = 0 /\ degIdx = 0 + /\ phase = "run" /\ stall = 0 /\ prevWt = 0 /\ degIdx = 0 /\ degClr2 = FALSE Next == \/ AddMsg \/ AddToolPair \/ AddFakePair \/ Condense \/ Truncate \/ Rewind \/ Recover Spec == Init /\ [][Next]_vars @@ -285,6 +307,7 @@ TypeOK == /\ n \in 1..MaxMsgs /\ 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 \* 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. @@ -326,8 +349,17 @@ DegradationPreservesPair == 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. -DegradationKeepsOtherBlocks == degIdx = 0 \/ msgs[degIdx].big2 +\* 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. diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index 9eb5900f62..7c80297dc7 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -297,6 +297,73 @@ describe("Context Management", () => { expect(result.error).toBeDefined() expect(result.messagesRemoved).toBe(0) expect(result.newContextTokensAfterTruncation).toBeGreaterThanOrEqual(63) + // A failed round must not persist the cleared tool_result content + // (Persistence Integrity, review round 2). + expect(result.messages).toStrictEqual(history) + }) + + 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) + expect(result.messages).toStrictEqual(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).toStrictEqual([ + history[0], + history[1], + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "" }] }, + ]) + expect(result.newContextTokensAfterTruncation).toBeLessThan(result.prevContextTokens) }) const createModelInfo = (contextWindow: number, maxTokens?: number): ModelInfo => ({ contextWindow, diff --git a/src/core/context-management/__tests__/truncation.spec.ts b/src/core/context-management/__tests__/truncation.spec.ts index aeddae1a08..368c0137a0 100644 --- a/src/core/context-management/__tests__/truncation.spec.ts +++ b/src/core/context-management/__tests__/truncation.spec.ts @@ -844,6 +844,50 @@ describe("degradation candidate selection (PR 2696 review round 1)", () => { } }) + 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). diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index 92f4a1399f..208219e8e3 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -549,8 +549,10 @@ export async function manageContext({ // success (issue 1254); otherwise the caller would retry a round that // cannot make progress. if (truncationResult.degraded && newContextTokensAfterTruncation >= prevContextTokens) { + // The round failed: handing back the degraded history would persist + // cleared tool_result content, so the caller keeps the original. return { - messages: truncationResult.messages, + messages, prevContextTokens, summary: "", cost, From 29c5531947dd47a5b55b5426088d0052da934c95 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 11:59:51 +0100 Subject: [PATCH 04/14] test(context-management): multi-round degradation chain + identity assertions (#1254) --- .../__tests__/context-management.spec.ts | 11 ++++-- .../__tests__/truncation.spec.ts | 38 +++++++++++++++++++ 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index 7c80297dc7..d20da45f8c 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -297,9 +297,10 @@ describe("Context Management", () => { expect(result.error).toBeDefined() expect(result.messagesRemoved).toBe(0) expect(result.newContextTokensAfterTruncation).toBeGreaterThanOrEqual(63) - // A failed round must not persist the cleared tool_result content - // (Persistence Integrity, review round 2). - expect(result.messages).toStrictEqual(history) + // A failed round must not persist the cleared tool_result content; + // Task callers persist by array identity, not by equal content + // (Persistence Integrity, review rounds 2-3). + expect(result.messages).toBe(history) }) it("returns the no-progress outcome when nothing is removable or degradable", async () => { @@ -329,7 +330,9 @@ describe("Context Management", () => { expect(result.error).toBeDefined() expect(result.messagesRemoved).toBe(0) expect(result.newContextTokensAfterTruncation).toBe(result.prevContextTokens) - expect(result.messages).toStrictEqual(history) + // 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 () => { diff --git a/src/core/context-management/__tests__/truncation.spec.ts b/src/core/context-management/__tests__/truncation.spec.ts index 368c0137a0..0483534daa 100644 --- a/src/core/context-management/__tests__/truncation.spec.ts +++ b/src/core/context-management/__tests__/truncation.spec.ts @@ -909,4 +909,42 @@ describe("degradation candidate selection (PR 2696 review round 1)", () => { expect(blocks[0].content).toBe("") expect(blocks[1].content).toBe("keep me") }) + + 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. + 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(5) + + 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("") + }) }) From a7a115026453473ec1ff4f809be1e17a10859f66 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 16:10:45 +0100 Subject: [PATCH 05/14] =?UTF-8?q?fix(context-management):=20answer=20PR=20?= =?UTF-8?q?2696=20review=20round=205=20=E2=80=94=20stop=20both=20paths,=20?= =?UTF-8?q?preserve=20originals,=20fair=20recount=20(#1254)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit taltas review threads 4695751055/65/75: 1. No-progress outcome (thread 4695751055): both Task request paths now throw ContextManagementNoProgressError after reporting, so an unreducible history is never resent unchanged. The generator-level manageContext try has no catch, so the error propagates without a retry loop. 2. Preserve originals for rewind (thread 4695751065): a degrade now appends a hidden truncation marker carrying degradedOriginals (index, blockIndex, content). The marker is excluded from every API-bound slice (isTruncationMarker) and from merge; originals deliberately do NOT ride on the cleared block because native providers (Anthropic, Bedrock) serialize content blocks as-is and would send them back. 3. Same token counter on both sides (thread 4695751075): the degraded success check now compares the fresh recount against an estimate of the ORIGINAL effective slice with the same estimator, instead of the API-reported prevContextTokens that omits the system prompt and can undercount mid-history oversized results. Red-verified: 5 tests fail on pre-fix source, 100/100 pass with the fix (incl. condense + task-persistence suites); tsc + eslint clean; TLC CondenseTruncate base 5254 states pass, all 13 sabotage cfgs fail. --- docs/architecture/tla/CondenseTruncate.tla | 8 ++ .../__tests__/context-management.spec.ts | 81 ++++++++++++++++--- .../__tests__/truncation.spec.ts | 23 +++++- src/core/context-management/index.ts | 78 +++++++++++++++++- src/core/task-persistence/apiMessages.ts | 6 ++ src/core/task/Task.ts | 19 ++++- 6 files changed, 198 insertions(+), 17 deletions(-) diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 777099e918..75992fbad5 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -49,6 +49,14 @@ \* 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). \* 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 diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index d20da45f8c..7cd6c6edf1 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -269,11 +269,15 @@ describe("Context Management", () => { * Tests for the manageContext function */ describe("manageContext", () => { - it("reports the controlled error when degradation cannot shrink the recounted tokens", async () => { + it("accepts a prompt-dominated degradation that shrinks the shared-estimate recount", async () => { // The recounted total includes the system prompt, which - // prevContextTokens omits, so a huge prompt with a tiny history makes - // a successful degradation impossible: the round must stall with the - // controlled error instead of reporting success (issue 1254). + // prevContextTokens omits. Under the old mixed-counter comparison + // this scenario always stalled with the controlled error — even a + // genuinely shrinking degradation was rejected because the fresh + // recount (prompt + history) exceeded the API-reported total + // (history only). Both sides now use the same estimator over the + // effective slice (issue 1254 review, taltas thread 4695751075), + // so a real shrink succeeds no matter how large the prompt is. const history: ApiMessage[] = [ { role: "user", content: "task" }, { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "probe", input: {} }] }, @@ -294,13 +298,58 @@ describe("Context Management", () => { currentProfileId: "default", }) - expect(result.error).toBeDefined() + expect(result.error).toBeUndefined() expect(result.messagesRemoved).toBe(0) - expect(result.newContextTokensAfterTruncation).toBeGreaterThanOrEqual(63) - // A failed round must not persist the cleared tool_result content; - // Task callers persist by array identity, not by equal content - // (Persistence Integrity, review rounds 2-3). - expect(result.messages).toBe(history) + // The degraded copy replaces the history: the caller persists it by + // array identity, not by equal content (Persistence Integrity, + // review rounds 2-3). + expect(result.messages).not.toBe(history) + // The original result survives on the hidden degradation marker so a + // rewind can restore the un-degraded history (issue 1254 review, + // taltas thread 4695751065). + const marker = result.messages[result.messages.length - 1] + expect(marker.isTruncationMarker).toBe(true) + expect(marker.degradedOriginals?.[0]?.content).toBe("x") + }) + + it("accepts a degradation that shrinks the shared-estimate recount even when prevContextTokens is lower than the true total", async () => { + // prevContextTokens (totalTokens + lastMessageTokens) can sit far + // below the real history size: the caller may pass a stale or zero + // cumulative total, and it never includes a mid-history oversized + // tool result. Comparing the fresh recount against it rejected + // reductions that genuinely shrank the history (issue 1254 review, + // taltas thread 4695751075). Both sides must use the same estimator + // over the effective slice: the recount drops the cleared result, + // the original-slice estimate keeps it, so the round succeeds. + 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.error).toBeUndefined() + // The degraded copy replaces the history: the caller persists it by + // array identity (Persistence Integrity, review rounds 2-3). + expect(result.messages).not.toBe(history) }) it("returns the no-progress outcome when nothing is removable or degradable", async () => { @@ -361,11 +410,21 @@ describe("Context Management", () => { expect(result.error).toBeUndefined() expect(result.messagesRemoved).toBe(0) - expect(result.messages).toStrictEqual([ + 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) }) const createModelInfo = (contextWindow: number, maxTokens?: number): ModelInfo => ({ diff --git a/src/core/context-management/__tests__/truncation.spec.ts b/src/core/context-management/__tests__/truncation.spec.ts index 0483534daa..03592662ac 100644 --- a/src/core/context-management/__tests__/truncation.spec.ts +++ b/src/core/context-management/__tests__/truncation.spec.ts @@ -773,7 +773,8 @@ describe("degradation candidate selection (PR 2696 review round 1)", () => { { 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 }[] + 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 @@ -908,6 +909,18 @@ describe("degradation candidate selection (PR 2696 review round 1)", () => { 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", () => { @@ -934,11 +947,15 @@ describe("degradation candidate selection (PR 2696 review round 1)", () => { 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. + // 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(5) + 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 diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index 208219e8e3..0be674b327 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. * @@ -196,6 +209,10 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe 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 @@ -216,6 +233,33 @@ export function truncateConversation(messages: ApiMessage[], fracToRemove: numbe 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: degradedMessages, truncationId, @@ -487,6 +531,18 @@ 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) { @@ -547,8 +603,26 @@ 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. - if (truncationResult.degraded && newContextTokensAfterTruncation >= prevContextTokens) { + // 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. + 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) + } + } + if (truncationResult.degraded && newContextTokensAfterTruncation >= prevEstimatedTokens) { // The round failed: handing back the degraded history would persist // cleared tool_result content, so the caller keeps the original. return { 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 c5d177e8b2..0520d3bd09 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 { @@ -5713,6 +5718,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 (truncateResult.messages === this.apiConversationHistory && truncateResult.error) { + throw new ContextManagementNoProgressError(truncateResult.error) + } } finally { // Notify webview that context management is complete (removes in-progress spinner) // IMPORTANT: Must always be sent to dismiss the spinner, even on error @@ -5970,6 +5981,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 (truncateResult.messages === this.apiConversationHistory && truncateResult.error) { + throw new ContextManagementNoProgressError(truncateResult.error) + } } finally { // Notify webview that context management is complete (sets isCondensing = false) // This removes the in-progress spinner and allows the completed result to show From cae3f1086a500ec0319a882e0f64d1bd888aecf7 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 17:14:21 +0100 Subject: [PATCH 06/14] fix(utils): sample long strings in the tiktoken estimate; 4 MB results no longer trap or hang (#1254) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The WASM encoder has two failure modes on very long strings: - a single 4 MB encode traps ("unreachable"), so estimateTokenCount threw before recovery could run; - long separator-less runs (minified JSON, base64 blobs) encode pathologically slowly (~250 ms per 1 000 chars — a 4 MB blob would hang the recovery the issue demands for minutes; measured: 300k same-char encode = 77 s, natural 900k = 386 ms). Strings up to 50k chars encode exactly. Longer strings are estimated from tokens-per-char on three 10k slices, extrapolated linearly: natural text stays near-exact (uniform density), the pathological worst case is bounded to three short encodes, and no encode enters the trap range. The issue's 4 MB acceptance case now passes through manageContext with the real counter: one degradation round clears it, the original survives on the hidden marker, and the history stays bounded. --- src/utils/tiktoken.ts | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) 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) } } } From b3cd000f3ebaeb809f87d436c084f2329593265d Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 17:24:44 +0100 Subject: [PATCH 07/14] =?UTF-8?q?fix(context-management):=20PR=202696=20ro?= =?UTF-8?q?und=206=20=E2=80=94=20restore=20degraded=20originals=20on=20rew?= =?UTF-8?q?ind,=20check=20no-progress=20before=20overwrite,=20stop=20the?= =?UTF-8?q?=20retry=20loop,=20skip=20the=20plain-truncation=20recount=20(#?= =?UTF-8?q?1254)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit round 6 (review 6060356811): - message-manager rewind now restores degradedOriginals before dropping a doomed marker (was: original content lost permanently). - no-progress identity check evaluated BEFORE overwriteApiConversationHistory (was: ensureMessageIdentifiers aliasing false-flagged successful rounds). - ContextManagementNoProgressError handled before the generic retry branch (was: infinite auto-retry on both request paths). - original-history recount moved inside the degradation branch (plain truncation no longer re-tokenizes removed results). TLA: CondenseTruncate caller transition + ErrStopsRequests invariant (NoStop sabotage), recount comparison recorded as gap; header ratchet covered 4 / added 9 / gap 7. check.sh: base PASS, 14/14 variants FAIL. Tests: restore-on-rewind, no-progress consumer stop x2, recount-skip, 4 MB acceptance — all red-verified. eslint (repo-standard relative invocation) clean on all touched files; tsc --noEmit clean. --- .../tla/CondenseTruncate.NoStop.cfg | 9 +++ docs/architecture/tla/CondenseTruncate.cfg | 2 +- docs/architecture/tla/CondenseTruncate.tla | 57 +++++++++++-- .../__tests__/context-management.spec.ts | 81 +++++++++++++++++++ src/core/context-management/index.ts | 54 +++++++------ src/core/message-manager/index.spec.ts | 47 +++++++++++ src/core/message-manager/index.ts | 50 ++++++++++++ src/core/task/Task.ts | 40 ++++++++- src/core/task/__tests__/Task.spec.ts | 56 +++++++++++++ 9 files changed, 360 insertions(+), 36 deletions(-) create mode 100644 docs/architecture/tla/CondenseTruncate.NoStop.cfg 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.cfg b/docs/architecture/tla/CondenseTruncate.cfg index 027de8ba61..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 SuccessIsMonotonic DegradationPreservesPair DegSelectionLive DegradationKeepsOtherBlocks NoZeroProgressSuccess BoundedRecovery ErrExhaustsCandidates +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 75992fbad5..500b7527a5 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -57,6 +57,12 @@ \* 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 @@ -64,7 +70,8 @@ \* 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. Other modes use the Fixed arms. +\* 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 @@ -82,9 +89,15 @@ \* 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. +\* 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. \* Gaps: marker text, getExistingSummaryIds guard, scan and clamp guards, the recovery -\* budget, the caller persist path for a failed round, and residual code eligibility. +\* 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). +\* Findings: covered 4, added 9, gap 7. \* 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 @@ -93,8 +106,9 @@ \* 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. The unit tests -\* replay every rule. +\* 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 @@ -110,8 +124,8 @@ MarkerMsg == [cond |-> FALSE, trunc |-> FALSE, mark |-> TRUE, summ |-> FALSE, st 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, phase, stall, prevWt, degIdx, degClr2 -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. @@ -186,6 +200,7 @@ AddMsg == /\ 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. @@ -198,6 +213,7 @@ AddToolPair == /\ repValid' = FALSE /\ phase' = "run" /\ stall' = 0 /\ prevWt' = 0 /\ degIdx' = 0 /\ degClr2' = FALSE /\ UNCHANGED <> + /\ UNCHANGED resentErr \* 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. @@ -210,6 +226,7 @@ AddFakePair == /\ 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). @@ -222,6 +239,7 @@ Condense == /\ 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. @@ -242,6 +260,7 @@ Truncate == /\ 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. @@ -256,6 +275,20 @@ Rewind == /\ 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 @@ -294,19 +327,23 @@ Recover == /\ 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 /\ phase = "run" /\ stall = 0 /\ prevWt = 0 /\ degIdx = 0 /\ degClr2 = FALSE + /\ resentErr = FALSE Next == \/ AddMsg \/ AddToolPair \/ AddFakePair \/ Condense \/ Truncate \/ Rewind \/ Recover + \/ CallerRespond Spec == Init /\ [][Next]_vars TypeOK == /\ n \in 1..MaxMsgs @@ -316,6 +353,7 @@ TypeOK == /\ n \in 1..MaxMsgs /\ 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. @@ -377,4 +415,9 @@ NoZeroProgressSuccess == phase = "ok" => stall = 0 \* 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 7cd6c6edf1..fcc0c58ed8 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -352,6 +352,87 @@ describe("Context Management", () => { expect(result.messages).not.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 diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index 0be674b327..884a25a7ae 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -610,31 +610,37 @@ export async function manageContext({ // 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. - 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) + // 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) + } } - } - if (truncationResult.degraded && newContextTokensAfterTruncation >= prevEstimatedTokens) { - // 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, + if (newContextTokensAfterTruncation >= prevEstimatedTokens) { + // 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, + } } } diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index 770b8347cf..ecbc711ceb 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -394,6 +394,53 @@ 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("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..a1378cc526 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -192,6 +192,56 @@ 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 marker is written at degraded.ts + 1, so the + // degraded message is located by ts; restored messages are new + // objects routed through the final history write. + const restoreOps = new Map>() + for (const marker of apiHistory) { + if ( + !( + marker.isTruncationMarker && + marker.truncationId && + removedIds.truncationIds.has(marker.truncationId) + ) + ) { + continue + } + if (marker.ts === undefined || !Array.isArray(marker.degradedOriginals)) { + continue + } + const degradedTs = marker.ts - 1 + const ops = restoreOps.get(degradedTs) ?? [] + for (const original of marker.degradedOriginals) { + ops.push({ blockIndex: original.blockIndex, content: original.content }) + } + restoreOps.set(degradedTs, ops) + } + if (restoreOps.size > 0) { + apiHistory = apiHistory.map((msg) => { + const ops = restoreOps.get(msg.ts ?? Number.NaN) + 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/Task.ts b/src/core/task/Task.ts index 0520d3bd09..ab83f4a94c 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4845,6 +4845,24 @@ export class Task extends EventEmitter implements TaskLike { throw new Error("API request failed") } + await this.say("api_req_retried") + stack.push({ + userContent: currentUserContent, + includeFileDetails: false, + retryAttempt: 0, + }) + 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") + } + await this.say("api_req_retried") stack.push({ userContent: currentUserContent, @@ -5714,6 +5732,13 @@ 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.error : undefined if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) } @@ -5721,8 +5746,8 @@ export class Task extends EventEmitter implements TaskLike { // 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 (truncateResult.messages === this.apiConversationHistory && truncateResult.error) { - throw new ContextManagementNoProgressError(truncateResult.error) + if (noProgressError) { + throw new ContextManagementNoProgressError(noProgressError) } } finally { // Notify webview that context management is complete (removes in-progress spinner) @@ -5977,6 +6002,13 @@ 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.error : undefined if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) } @@ -5984,8 +6016,8 @@ export class Task extends EventEmitter implements TaskLike { // 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 (truncateResult.messages === this.apiConversationHistory && truncateResult.error) { - throw new ContextManagementNoProgressError(truncateResult.error) + if (noProgressError) { + throw new ContextManagementNoProgressError(noProgressError) } } finally { // Notify webview that context management is complete (sets isCondensing = false) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 8a7bffa7dc..856e08887a 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -42,6 +42,7 @@ import { McpServerManager } from "../../../services/mcp/McpServerManager" import { readFileTool } from "../../tools/ReadFileTool" import { writeToFileTool } from "../../tools/WriteToFileTool" import { manageContext } from "../../context-management" +import { ContextManagementNoProgressError } from "../../context-management" type TaskTestAccess = { getSystemPrompt: (requestState: ProviderState | undefined, requestModelInfo?: ModelInfo) => Promise @@ -678,6 +679,61 @@ describe("Cline", () => { expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 0]) }) }) + 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("retries from a fresh attempt count 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" }]) + + expect(attemptApiRequestSpy.mock.calls.slice(0, 2).map(([retryAttempt]) => retryAttempt)).toEqual([0, 0]) + }) + }) describe("native tool-call request isolation", () => { it("derives readiness only from a closed, idle, fully paired tool turn", () => { From 148b55a8afa9de042d2d474bc9a61e39c89812d1 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 18:20:39 +0100 Subject: [PATCH 08/14] =?UTF-8?q?fix(context-management):=20PR=202696=20ro?= =?UTF-8?q?und=207=20=E2=80=94=20restore=20degraded=20results=20before=20t?= =?UTF-8?q?he=20cutoff=20filter=20and=20without=20a=20timestamp,=20disting?= =?UTF-8?q?uish=20condense=20errors=20from=20no-progress,=20save=20confirm?= =?UTF-8?q?ed-retry=20turns=20once=20(#1254)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/tla/CondenseTruncate.tla | 19 +++- .../__tests__/context-management.spec.ts | 69 +++++++++++++ src/core/context-management/index.ts | 9 ++ src/core/message-manager/index.spec.ts | 99 +++++++++++++++++++ src/core/message-manager/index.ts | 40 ++++++-- src/core/task/Task.ts | 48 ++++++++- .../task/__tests__/Task.persistence.spec.ts | 62 ++++++++++++ src/core/task/__tests__/Task.spec.ts | 91 ++++++++++++++++- 8 files changed, 414 insertions(+), 23 deletions(-) diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 500b7527a5..95f847c6fb 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -83,21 +83,30 @@ \* 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. -\* Findings: covered 4, added 8, gap 6. 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). +\* 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. +\* (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). -\* Findings: covered 4, added 9, gap 7. +\* 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. +\* 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 diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index fcc0c58ed8..a7e693b167 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -508,6 +508,75 @@ describe("Context Management", () => { }) 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/index.ts b/src/core/context-management/index.ts index 884a25a7ae..e3c52aeee2 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -428,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 } /** @@ -558,6 +565,7 @@ export async function manageContext({ truncationId: truncationResult.truncationId, messagesRemoved: 0, newContextTokensAfterTruncation: prevContextTokens, + noProgress: true, } } @@ -640,6 +648,7 @@ export async function manageContext({ truncationId: truncationResult.truncationId, messagesRemoved: 0, newContextTokensAfterTruncation, + noProgress: true, } } } diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index ecbc711ceb..be0279ad52 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -442,6 +442,105 @@ describe("MessageManager", () => { }) }) + 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("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 a1378cc526..667c35623e 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) */ @@ -195,11 +196,19 @@ export class MessageManager { // 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 marker is written at degraded.ts + 1, so the - // degraded message is located by ts; restored messages are new + // 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 (const marker of apiHistory) { + const restoreOps = new Map>() + for (let markerIndex = 0; markerIndex < originalHistory.length; markerIndex++) { + const marker = originalHistory[markerIndex] if ( !( marker.isTruncationMarker && @@ -209,19 +218,32 @@ export class MessageManager { ) { continue } - if (marker.ts === undefined || !Array.isArray(marker.degradedOriginals)) { + if (!Array.isArray(marker.degradedOriginals)) { continue } - const degradedTs = marker.ts - 1 - const ops = restoreOps.get(degradedTs) ?? [] + let degraded: ApiMessage | undefined + if (marker.ts !== undefined) { + const degradedTs = marker.ts - 1 + degraded = originalHistory.find((m) => m.ts === degradedTs) + } + 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(degradedTs, ops) + restoreOps.set(degraded, ops) } if (restoreOps.size > 0) { apiHistory = apiHistory.map((msg) => { - const ops = restoreOps.get(msg.ts ?? Number.NaN) + const ops = restoreOps.get(msg) if (!ops || !Array.isArray(msg.content)) { return msg } diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index ab83f4a94c..69f63b86ad 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -3367,7 +3367,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. @@ -4845,11 +4853,24 @@ 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) { + const lastSaved = this.apiConversationHistory[this.apiConversationHistory.length - 1] + if (lastSaved.role === "user") { + this.apiConversationHistory.pop() + this.messageCounts.user-- + removedSavedUserTurn = true + } + } 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) { @@ -4863,11 +4884,24 @@ 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) { + const lastSaved = this.apiConversationHistory[this.apiConversationHistory.length - 1] + if (lastSaved.role === "user") { + this.apiConversationHistory.pop() + this.messageCounts.user-- + removedSavedUserTurn = true + } + } await this.say("api_req_retried") stack.push({ userContent: currentUserContent, includeFileDetails: false, - retryAttempt: 0, + retryAttempt: (currentItem.retryAttempt ?? 0) + 1, + userMessageWasRemoved: removedSavedUserTurn, }) continue } else { @@ -5738,7 +5772,9 @@ export class Task extends EventEmitter implements TaskLike { // array, so a check after the overwrite would false-flag every // successful round (issue 1254 review). const noProgressError = - truncateResult.messages === this.apiConversationHistory ? truncateResult.error : undefined + truncateResult.messages === this.apiConversationHistory && truncateResult.noProgress + ? truncateResult.error + : undefined if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) } @@ -6008,7 +6044,9 @@ export class Task extends EventEmitter implements TaskLike { // array, so a check after the overwrite would false-flag every // successful round (issue 1254 review). const noProgressError = - truncateResult.messages === this.apiConversationHistory ? truncateResult.error : undefined + truncateResult.messages === this.apiConversationHistory && truncateResult.noProgress + ? truncateResult.error + : undefined if (truncateResult.messages !== this.apiConversationHistory) { await this.overwriteApiConversationHistory(truncateResult.messages) } diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 86df5615db..905fdeb417 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -1350,6 +1350,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 856e08887a..6e485c1f5b 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -663,7 +663,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 @@ -676,7 +676,19 @@ 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) }) }) describe("context management no-progress mid-stream", () => { @@ -718,7 +730,7 @@ describe("Cline", () => { expect(askSpy).toHaveBeenCalledWith("api_req_failed", expect.stringContaining("Unable to reduce context")) }) - 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 @@ -731,7 +743,56 @@ 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 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) }) }) @@ -2695,6 +2756,28 @@ 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("uses the task mode when manually condensing after focused state changes", async () => { From 4366c03d1b89a5d4257d23353eff8b05ca4f9f08 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 19:12:30 +0100 Subject: [PATCH 09/14] =?UTF-8?q?fix(context-management):=20PR=202696=20ro?= =?UTF-8?q?und=208=20=E2=80=94=20keep=20recovery=20markers=20across=20conf?= =?UTF-8?q?irmed=20retries,=20persist=20the=20turn=20removal=20with=20merg?= =?UTF-8?q?e=3Dfalse,=20restore=20chained=20timestamp-free=20degradations?= =?UTF-8?q?=20via=20the=20recorded=20index,=20require=20caller-visible=20s?= =?UTF-8?q?hrink=20for=20degraded=20success,=20guard=20the=20TLA=20Recover?= =?UTF-8?q?=20action=20after=20an=20error=20(#1254)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/architecture/tla/CondenseTruncate.tla | 6 + .../__tests__/context-management.spec.ts | 193 ++++++------- src/core/context-management/index.ts | 11 +- src/core/message-manager/index.spec.ts | 271 ++++++++++++------ src/core/message-manager/index.ts | 42 ++- src/core/task/Task.ts | 56 +++- .../task/__tests__/Task.persistence.spec.ts | 78 +++++ src/core/task/__tests__/Task.spec.ts | 203 +++++++++++-- src/utils/__tests__/tiktoken.spec.ts | 41 +++ 9 files changed, 669 insertions(+), 232 deletions(-) diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 95f847c6fb..00d9a4acae 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -306,6 +306,12 @@ CallerRespond == \* 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 diff --git a/src/core/context-management/__tests__/context-management.spec.ts b/src/core/context-management/__tests__/context-management.spec.ts index a7e693b167..cd0d2de67f 100644 --- a/src/core/context-management/__tests__/context-management.spec.ts +++ b/src/core/context-management/__tests__/context-management.spec.ts @@ -269,15 +269,16 @@ describe("Context Management", () => { * Tests for the manageContext function */ describe("manageContext", () => { - it("accepts a prompt-dominated degradation that shrinks the shared-estimate recount", async () => { - // The recounted total includes the system prompt, which - // prevContextTokens omits. Under the old mixed-counter comparison - // this scenario always stalled with the controlled error — even a - // genuinely shrinking degradation was rejected because the fresh - // recount (prompt + history) exceeded the API-reported total - // (history only). Both sides now use the same estimator over the - // effective slice (issue 1254 review, taltas thread 4695751075), - // so a real shrink succeeds no matter how large the prompt is. + 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: {} }] }, @@ -298,29 +299,23 @@ describe("Context Management", () => { currentProfileId: "default", }) - expect(result.error).toBeUndefined() + // 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) - // The degraded copy replaces the history: the caller persists it by - // array identity, not by equal content (Persistence Integrity, - // review rounds 2-3). - expect(result.messages).not.toBe(history) - // The original result survives on the hidden degradation marker so a - // rewind can restore the un-degraded history (issue 1254 review, - // taltas thread 4695751065). - const marker = result.messages[result.messages.length - 1] - expect(marker.isTruncationMarker).toBe(true) - expect(marker.degradedOriginals?.[0]?.content).toBe("x") - }) - - it("accepts a degradation that shrinks the shared-estimate recount even when prevContextTokens is lower than the true total", async () => { - // prevContextTokens (totalTokens + lastMessageTokens) can sit far - // below the real history size: the caller may pass a stale or zero - // cumulative total, and it never includes a mid-history oversized - // tool result. Comparing the fresh recount against it rejected - // reductions that genuinely shrank the history (issue 1254 review, - // taltas thread 4695751075). Both sides must use the same estimator - // over the effective slice: the recount drops the cleared result, - // the original-slice estimate keeps it, so the round succeeds. + 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 }, @@ -346,10 +341,8 @@ describe("Context Management", () => { currentProfileId: "default", }) - expect(result.error).toBeUndefined() - // The degraded copy replaces the history: the caller persists it by - // array identity (Persistence Integrity, review rounds 2-3). - expect(result.messages).not.toBe(history) + expect(result.noProgress).toBe(true) + expect(result.messages).toBe(history) }) it("reproduces the 4 MB tool-result case from the issue acceptance criteria", async () => { @@ -508,74 +501,74 @@ describe("Context Management", () => { }) 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) }] }, - ] + 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) - }) + 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", + }) - 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" }, - ] + expect(result.error).toBeDefined() + expect(result.noProgress).toBe(true) + // The caller keeps ITS array: identity, not just equal content. + expect(result.messages).toBe(history) + }) - 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) - }) + 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, diff --git a/src/core/context-management/index.ts b/src/core/context-management/index.ts index e3c52aeee2..f69c0bf08b 100644 --- a/src/core/context-management/index.ts +++ b/src/core/context-management/index.ts @@ -635,7 +635,16 @@ export async function manageContext({ prevEstimatedTokens += await estimateTokenCount([{ type: "text", text: content }], apiHandler) } } - if (newContextTokensAfterTruncation >= prevEstimatedTokens) { + // 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 { diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index be0279ad52..691a10b2ee 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -442,104 +442,185 @@ describe("MessageManager", () => { }) }) - 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 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 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: "" }, + ], + }, + { + 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 }], + }, + { + role: "user", + content: [ + { type: "tool_use", id: "t5", name: "probe", input: {} }, + { type: "tool_result", tool_use_id: "t5", content: "" }, + ], + }, + { + ts: 61, + role: "user", + content: "[Tool result degradation: oversized result cleared to reduce context]", + isTruncationMarker: true, + truncationId: truncationIdB, + degradedOriginals: [{ index: 4, 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. The marker.ts - 1 lookup resolves + // to the earlier marker (now excluded) and the predecessor fallback + // picks a marker too — only the recorded original-history index + // restores the second block (PR 2696 review round 8). + 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("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 667c35623e..f4ec402211 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -209,13 +209,11 @@ export class MessageManager { 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) - ) - ) { + if (!( + marker.isTruncationMarker && + marker.truncationId && + removedIds.truncationIds.has(marker.truncationId) + )) { continue } if (!Array.isArray(marker.degradedOriginals)) { @@ -224,7 +222,35 @@ export class MessageManager { let degraded: ApiMessage | undefined if (marker.ts !== undefined) { const degradedTs = marker.ts - 1 - degraded = originalHistory.find((m) => m.ts === degradedTs) + // 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) { + // Stable link: the marker records the degraded message's + // original-history index. Degradation rounds only append + // markers, so those positions stay valid across rounds; the + // predecessor fallback below 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 && markerIndex > 0) { const previous = originalHistory[markerIndex - 1] diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 69f63b86ad..d85fb2176f 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4858,11 +4858,31 @@ export class Task extends EventEmitter implements TaskLike { // re-adds it exactly once via userMessageWasRemoved. let removedSavedUserTurn = false if (shouldAddUserMessage && this.apiConversationHistory.length > 0) { - const lastSaved = this.apiConversationHistory[this.apiConversationHistory.length - 1] - if (lastSaved.role === "user") { - this.apiConversationHistory.pop() + // 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 + // Persist the reduction with merge=false so the disk + // file drops the removed record. The default merge + // keeps disk-only records, and the retry's re-add + // would then persist two user turns for one request + // (issue 1254 review round 8, persistence integrity). + await this.saveApiConversationHistory(false) } } await this.say("api_req_retried") @@ -4879,21 +4899,41 @@ export class Task extends EventEmitter implements TaskLike { // 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) { - const lastSaved = this.apiConversationHistory[this.apiConversationHistory.length - 1] - if (lastSaved.role === "user") { - this.apiConversationHistory.pop() + // 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 + // Persist the reduction with merge=false so the disk + // file drops the removed record. The default merge + // keeps disk-only records, and the retry's re-add + // would then persist two user turns for one request + // (issue 1254 review round 8, persistence integrity). + await this.saveApiConversationHistory(false) } } await this.say("api_req_retried") diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 905fdeb417..1a1e05e25e 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -15,6 +15,8 @@ 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 type { ApiStreamChunk } from "../../../api/transform/stream" import { PendingActionSettlementError, Task } from "../Task" import { parseMentions } from "../../mentions" import { ClineProvider } from "../../webview/ClineProvider" @@ -329,6 +331,82 @@ 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("uses authoritative replacement for explicit API history overwrites", async () => { const task = new Task({ provider: mockProvider, diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 6e485c1f5b..e5f5944c0c 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -690,6 +690,48 @@ describe("Cline", () => { ) 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 { @@ -721,7 +763,9 @@ describe("Cline", () => { .spyOn(task, "ask") .mockResolvedValue({ response: "noButtonClicked" } satisfies TaskAskResult) const backoffSpy = vi.spyOn(getTaskTestAccess(task), "backoffAndAnnounce") - const attemptApiRequestSpy = vi.spyOn(task, "attemptApiRequest").mockImplementation(() => noProgressStream()) + const attemptApiRequestSpy = vi + .spyOn(task, "attemptApiRequest") + .mockImplementation(() => noProgressStream()) await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]) @@ -2757,27 +2801,146 @@ describe("Cline", () => { 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", + 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() }) - // Before the noProgress flag, the unchanged history plus the - // error threw ContextManagementNoProgressError here. - await expect( - getTaskTestAccess(task).handleContextWindowExceededError(ctxModelInfo), - ).resolves.toBeUndefined() - }) + 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 () => { 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) + }) + }) }) From 1f35269fb96b73127347abe16ec4989933cf5ee5 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 20:12:30 +0100 Subject: [PATCH 10/14] fix(context-management): restore from the recorded link before the timestamp fallback and persist the retry turn replacement in one merge=false write (#1254) --- docs/architecture/tla/CondenseTruncate.tla | 4 + src/core/message-manager/index.spec.ts | 74 +++++++++++++++---- src/core/message-manager/index.ts | 52 ++++++------- src/core/task/Task.ts | 44 +++++++---- .../task/__tests__/Task.persistence.spec.ts | 60 +++++++++++++++ src/core/task/__tests__/Task.spec.ts | 3 + 6 files changed, 184 insertions(+), 53 deletions(-) diff --git a/docs/architecture/tla/CondenseTruncate.tla b/docs/architecture/tla/CondenseTruncate.tla index 00d9a4acae..ad1cec53fb 100644 --- a/docs/architecture/tla/CondenseTruncate.tla +++ b/docs/architecture/tla/CondenseTruncate.tla @@ -106,6 +106,10 @@ \* 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 diff --git a/src/core/message-manager/index.spec.ts b/src/core/message-manager/index.spec.ts index 691a10b2ee..2ef4f03e71 100644 --- a/src/core/message-manager/index.spec.ts +++ b/src/core/message-manager/index.spec.ts @@ -573,6 +573,13 @@ describe("MessageManager", () => { { 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", @@ -581,29 +588,23 @@ describe("MessageManager", () => { truncationId: truncationIdA, degradedOriginals: [{ index: 2, blockIndex: 1, content: originalA }], }, - { - role: "user", - content: [ - { type: "tool_use", id: "t5", name: "probe", input: {} }, - { type: "tool_result", tool_use_id: "t5", content: "" }, - ], - }, { ts: 61, role: "user", content: "[Tool result degradation: oversized result cleared to reduce context]", isTruncationMarker: true, truncationId: truncationIdB, - degradedOriginals: [{ index: 4, blockIndex: 1, content: originalB }], + 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. The marker.ts - 1 lookup resolves - // to the earlier marker (now excluded) and the predecessor fallback - // picks a marker too — only the recorded original-history index - // restores the second block (PR 2696 review round 8). + // 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] @@ -622,6 +623,53 @@ describe("MessageManager", () => { 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 f4ec402211..846793778e 100644 --- a/src/core/message-manager/index.ts +++ b/src/core/message-manager/index.ts @@ -220,7 +220,33 @@ export class MessageManager { continue } let degraded: ApiMessage | undefined - if (marker.ts !== 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 @@ -228,30 +254,6 @@ export class MessageManager { // this marker cleared (issue 1254 review round 8). degraded = originalHistory.find((m) => m.ts === degradedTs && !m.isTruncationMarker) } - if (!degraded) { - // Stable link: the marker records the degraded message's - // original-history index. Degradation rounds only append - // markers, so those positions stay valid across rounds; the - // predecessor fallback below 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 && markerIndex > 0) { const previous = originalHistory[markerIndex - 1] if (Array.isArray(previous.content)) { diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index d85fb2176f..7b4f0a046a 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -1447,7 +1447,11 @@ export class Task extends EventEmitter implements TaskLike { * Appends an API turn and records whether an assistant turn reached persistent storage. * If the message resolves a pending action, retries the save on initial failure before clearing the action. */ - private async addToApiConversationHistory(message: Anthropic.MessageParam, reasoning?: string): Promise { + private async addToApiConversationHistory( + message: Anthropic.MessageParam, + reasoning?: string, + persistMerge = true, + ): Promise { const resolvesPendingAction = this.pendingAction && message.role === "user" && @@ -1465,7 +1469,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() } @@ -4160,7 +4164,15 @@ export class Task extends EventEmitter implements TaskLike { 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++ } @@ -4877,12 +4889,13 @@ export class Task extends EventEmitter implements TaskLike { this.apiConversationHistory.splice(turnIndex, 1) this.messageCounts.user-- removedSavedUserTurn = true - // Persist the reduction with merge=false so the disk - // file drops the removed record. The default merge - // keeps disk-only records, and the retry's re-add - // would then persist two user turns for one request - // (issue 1254 review round 8, persistence integrity). - await this.saveApiConversationHistory(false) + // 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") @@ -4928,12 +4941,13 @@ export class Task extends EventEmitter implements TaskLike { this.apiConversationHistory.splice(turnIndex, 1) this.messageCounts.user-- removedSavedUserTurn = true - // Persist the reduction with merge=false so the disk - // file drops the removed record. The default merge - // keeps disk-only records, and the retry's re-add - // would then persist two user turns for one request - // (issue 1254 review round 8, persistence integrity). - await this.saveApiConversationHistory(false) + // 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") diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index 1a1e05e25e..c7eec11dd3 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -407,6 +407,66 @@ describe("Task persistence", () => { expect(saved.some((m) => m.isTruncationMarker && m.truncationId === "trunc-disk")).toBe(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: + // abort is set before any re-add could run. + ;(task as unknown as { abort: boolean }).abort = true + 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()) + + await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]).catch(() => undefined) + expect(attemptApiRequestSpy).toHaveBeenCalled() + + // 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, diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index e5f5944c0c..08226294f4 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -7106,6 +7106,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, ) }) From 111cc4c34ed2dd245ce8228cd3e6b27b9b3f0f88 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 20:43:57 +0100 Subject: [PATCH 11/14] test(persistence): request cancellation through requestAbort in the abort-window test The abort-window test assigned the getter-only abort property, which throws TypeError before any cancellation engages; the outer catch resolves true, so the persistence assertions passed without testing cancellation. Request the abort through requestAbort(false) instead, assert the run state reports aborted and the loop ends through the cancellation-aware catch path, and drop the catch that accepted an unexpected rejection. Red-verified: with the old assignment the new abort assertion fails (expected false to be true). --- src/core/task/__tests__/Task.persistence.spec.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index c7eec11dd3..c72423ae1e 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -428,9 +428,10 @@ describe("Task persistence", () => { 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: - // abort is set before any re-add could run. - ;(task as unknown as { abort: boolean }).abort = true + // 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) @@ -445,8 +446,14 @@ describe("Task persistence", () => { .spyOn(task, "attemptApiRequest") .mockImplementationOnce(() => truncatedStream()) - await task.recursivelyMakeClineRequests([{ type: "text", text: "long request" }]).catch(() => undefined) + // 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 From e807d9621d47c8091948343a67a59ed5189f740f Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 21:30:25 +0100 Subject: [PATCH 12/14] test(task): pin the emergency no-progress stop and the untouched history it leaves behind --- src/core/task/__tests__/Task.spec.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index 08226294f4..cc06310b64 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -2823,6 +2823,28 @@ describe("Cline", () => { ).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) + }) + 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 From 4712f357cdd531e28fd831f45848eb645859c625 Mon Sep 17 00:00:00 2001 From: Phil Date: Wed, 25 Nov 2026 22:22:07 +0100 Subject: [PATCH 13/14] fix(task): keep history saves authoritative after a failed replacement A failed merge=false replacement write left the disk holding the stale turn while memory held the replacement under a new message id; the next merge write would dedupe by id and persist both copies. A latch in saveApiConversationHistory now keeps every save authoritative until one lands, so both confirmed-retry branches (output-limit and no-progress) can no longer duplicate the turn through a later merge. Failed-write tests cover both branches; the no-progress test also pins that recovery never calls the history writer. --- src/core/task/Task.ts | 16 +++- .../task/__tests__/Task.persistence.spec.ts | 94 +++++++++++++++++++ src/core/task/__tests__/Task.spec.ts | 4 + 3 files changed, 113 insertions(+), 1 deletion(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 7b4f0a046a..66a2b957ac 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -556,6 +556,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 @@ -1639,16 +1646,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: structuredClone(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 } } diff --git a/src/core/task/__tests__/Task.persistence.spec.ts b/src/core/task/__tests__/Task.persistence.spec.ts index c72423ae1e..d7c8e52f47 100644 --- a/src/core/task/__tests__/Task.persistence.spec.ts +++ b/src/core/task/__tests__/Task.persistence.spec.ts @@ -16,6 +16,7 @@ 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" @@ -407,6 +408,99 @@ describe("Task persistence", () => { 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([]) diff --git a/src/core/task/__tests__/Task.spec.ts b/src/core/task/__tests__/Task.spec.ts index cc06310b64..46c161ca17 100644 --- a/src/core/task/__tests__/Task.spec.ts +++ b/src/core/task/__tests__/Task.spec.ts @@ -2843,6 +2843,10 @@ describe("Cline", () => { 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 () => { From bea1c8ea82f31be1fd3b5ffd459c278bc9f2654f Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 15:58:00 +0100 Subject: [PATCH 14/14] fix(task): keep both retry contracts in the merge with main The merge with upstream/main dropped the userMessageWasRemoved input from shouldAddUserMessageToHistory and the StackItem field (main's #2701 rewrite), and left main's source object on the third positional slot of addToApiConversationHistory. Restore both contracts: the param is optional, so main's two-argument callers and its retry-dedupe tests hold, while confirmed output-limit / no-progress retries re-add the removed turn through the authoritative merge=false write again. --- src/core/task/Task.ts | 3 +++ src/core/task/messageCounting.ts | 17 ++++++++++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index d546a124fc..9505c57989 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -4048,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[] = [ @@ -4158,6 +4159,7 @@ export class Task extends EventEmitter implements TaskLike { const shouldAddUserMessage = shouldAddUserMessageToHistory({ retryAttempt: currentItem.retryAttempt, isEmptyUserContent, + userMessageWasRemoved: currentItem.userMessageWasRemoved, }) if (shouldAddUserMessage) { // A confirmed retry re-adds the removed turn here: merge=false @@ -5329,6 +5331,7 @@ export class Task extends EventEmitter implements TaskLike { await this.addToApiConversationHistory( { role: "assistant", content: assistantContent }, reasoningMessage || undefined, + undefined, { api: requestApi, apiConfiguration: requestApiConfiguration }, ) 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) }