Skip to content

Compaction's protectedContext floors tailStartId at a long-superseded message, permanently #470

Closed

Description

Summary

After a compaction, tailStartId can get permanently pinned to a long-superseded, never-directly-answered user message from early in the session — even after many later turns are fully, properly answered. In a long-running session this means every subsequent compaction keeps re-summarizing the same huge middle span down to nothing useful, and the "tail" the model actually sees stays stuck at that old point instead of advancing. In our case this made a 100k→120k context bump not help at all: usage stayed pinned "over budget" turn after turn.

Root cause

protectedContext in backend/cli/src/session/compaction.ts (line 440) is documented as:

Return the transcript span that still belongs to the active, unanswered turn. Multiple ordinary user messages can arrive while a provider call is running; none of them are reducible history until a terminal assistant response has observed them.

But the implementation doesn't match that doc comment — it scans forward from the start of the entire transcript, not backward from the current turn:

const start = messages.findIndex((message, index) => {
  if (index > current || message.info.role !== "user") return false
  return !answered.has(message.info.id) && !compacted(message)
})

findIndex returns the first unanswered user message anywhere in history — not the first one still relevant to the current active turn. A common real pattern breaks this: a user message that's immediately superseded by a retry/resend (e.g. after a dropped connection or a "resume" after /compact), where the retry does get answered but the original never gets its own direct reply. answered is keyed by parentID, so the original is never marked answered — it satisfies !answered.has(...) && !compacted(...) forever, and findIndex finds it before anything from the current turn.

Then in selectTail:

if (protectedStart > 0) cut = Math.min(cut, protectedStart)

floors the tail cut at that ancient index, no matter how much later work has been fully resolved.

(Side note on protectedStart > 0, not >= 0: if the orphaned message happens to sit at array index 0 — e.g. the very first message in a synthetic test — this guard skips the floor and the bug doesn't manifest. In a real session there's always earlier history before message N, so this masking doesn't happen in practice; it just means an isolated repro needs a couple of turns before the orphaned message to show the bug, which is what the attached test does.)

Reproduction

Attached: backend/cli/test/session/message-v2.test.ts — new describe("session.compaction.selectTail — protectedContext floor (regression)") block, one test. It builds a realistic history using real Identifier.ascending("message") ids (so id-comparisons behave exactly as in production):

  • 3 earlier, fully-answered turns
  • u1: a request that never gets its own direct reply
  • u2 + a2: an immediate retry of u1 that does get answered
  • 8 further, fully-answered "real work" turns

It calls SessionCompaction.selectTail directly and asserts tailStartId lands in the recent work, not on u1. On main this fails — tailStartId resolves to u1 every time, regardless of how much real work follows.

Full test (also included as a diff against message-v2.test.ts)
describe("session.compaction.selectTail — protectedContext floor (regression)", () => {
  const mk = (
    id: string,
    role: "user" | "assistant",
    parts: MessageV2.Part[],
    extra: Record<string, unknown> = {},
  ): MessageV2.WithParts => ({
    info: {
      id,
      sessionID: "s",
      role,
      time: { created: 0 },
      ...(role === "user"
        ? { agent: "a", model: { providerID: "p", modelID: "m" } }
        : {
            parentID: "p",
            modelID: "m",
            providerID: "p",
            mode: "",
            agent: "a",
            cost: 0,
            tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
          }),
      ...extra,
    } as unknown as MessageV2.WithParts["info"],
    parts: parts as unknown as MessageV2.Part[],
  })
  const txt = (mid: string, t: string) =>
    ({ id: `${mid}t`, sessionID: "s", messageID: mid, type: "text", text: t }) as unknown as MessageV2.Part

  test("a long-superseded, never-directly-answered user message does not permanently floor the tail", async () => {
    const nextId = () => Identifier.ascending("message")
    const earlier = Array.from({ length: 3 }, () => [nextId(), nextId()] as const)
    const u1 = nextId()
    const u2 = nextId()
    const a2 = nextId()
    const work = Array.from({ length: 8 }, () => [nextId(), nextId()] as const)

    const oldestToNewest: MessageV2.WithParts[] = [
      ...earlier.flatMap(([u, a], i) => [
        mk(u, "user", [txt(u, `earlier turn ${i + 1}`)]),
        mk(a, "assistant", [txt(a, `earlier reply ${i + 1}`)], { finish: "stop", parentID: u }),
      ]),
      mk(u1, "user", [txt("u1", "original request — never directly answered")]),
      mk(u2, "user", [txt("u2", "retry of the same request")]),
      mk(a2, "assistant", [txt("a2", "the retry's own reply")], { finish: "stop", parentID: u2 }),
      ...work.flatMap(([wu, wa], i) => [
        mk(wu, "user", [txt(wu, `work request ${i + 1}`)]),
        mk(wa, "assistant", [txt(wa, `work reply ${i + 1}`)], { finish: "stop", parentID: wu }),
      ]),
    ]

    const { tailStartId } = SessionCompaction.selectTail(oldestToNewest, {
      tailTurns: SessionCompaction.TAIL_TURNS,
      tailTokens: 32000,
    })

    expect(tailStartId).not.toBe(u1)
    expect(work.some(([wu]) => wu === tailStartId)).toBe(true)
  })
})

Real-world origin

Found this in session ses_fb982be9affep6vIERU15QM35w (local Ollama model via the research agent, long RNA-seq pipeline task): msg_046c11e5a001E6999UPzmsxh68 is a plain user prompt that never got a direct reply — it was immediately superseded by msg_046c11fa5001djkKKCNNkMhnrt, which was answered (by msg_046c12027001BFOqzSiIZurz4I, parentID = that message). Every compaction afterward kept flooring tailStartId back at the first message, well past 100k+ tokens of genuine follow-up work, even after raising the model's context window.

Suggested fix

Scope the scan to the contiguous unanswered span ending at the current turn, instead of the first unanswered message in all of history — walk backward from current and stop at the first user message that's already terminally answered or already compacted:

let start = -1
for (let index = current; index >= 0; index--) {
  const message = messages[index]
  if (message.info.role !== "user") continue
  if (answered.has(message.info.id) || compacted(message)) break
  start = index
}
if (start < 0) return []
return messages.slice(start)

This preserves the documented intent (protect a run of genuinely-pending retries ending at the current turn) while no longer reaching back to unrelated, long-resolved history. Verified against the full existing test suite (bun test across backend/cli) — no regressions; the 3 pre-existing unrelated failures on main (a stale MCP tool-description string assertion) are unchanged.

Fix

Opened #469 with this fix + the regression test above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions