Skip to content

fix(server): idle compaction runs when a queued message is removed after the run completes - #43777

Open
skap3214 wants to merge 1 commit into
pingdotgg:mainfrom
skap3214:fix/idle-compaction-after-queued-cancel
Open

skap3214 wants to merge 1 commit into
pingdotgg:mainfrom
skap3214:fix/idle-compaction-after-queued-cancel

Conversation

@skap3214

@skap3214 skap3214 commented Nov 26, 2026 •

Copy link
Copy Markdown

Problem

With idle compaction set to "Before the cache expires (beta)", a Claude thread is never compacted when a follow-up message is still queued at the moment the run completes and is then removed or steered.

IdleCompactionService starts its check only on run.updated with status completed. At that moment the queued run has the highest ordinal, so idleCompactionWindow returns null and the check ends without a timer. The removal that follows emits run.updated with status cancelled, which starts nothing. The thread stays uncompacted, and the next message after the cache expires pays a full uncached read.

#29904 fixed the order where the queued message is cancelled before the run completes. This is the opposite order.

Steps: on a Claude thread above the 200K floor, queue a follow-up while a turn runs, let the turn complete, then remove the queued message (or steer it) before it starts. Expected: /compact is sent about 2 minutes before the cache expires. Actual: nothing is sent.

Change

IdleCompactionService.start now also starts compactWhenDue on run.updated with status cancelled and startedAt === null. The check already ignores such runs when it picks the latest run, so its existing retarget branch takes over the completed run and waits for that run's window.

A queued message that is still queued keeps blocking compaction, as #29904 intends. If the cancel arrives while the previous run is still running, the check finds no completed latest run and ends, and the later completed event arms the timer as before.

Scope

A bug in idle compaction. Production code is +5 −1 in one file. There is no issue for it: I searched issues and pull requests for this order and found none, and the fix is one condition on an existing event filter.

Verification

macOS 27.0.1, Apple silicon, Node 26.12.1, on main d023407.

  • How I found it: the event log of a real thread on nightly 0.1.12-nightly.20261123.5124. A follow-up was queued while a run was in progress. The run completed with 310,245 tokens in context and a cache expiry one hour later. The queued run was cancelled 0.6 seconds after that, with startedAt null. No /compact was dispatched in the next 104 minutes, and the next user message ran against an expired cache.
  • New test in IdleCompaction.test.ts, "compacts when a queued message is removed or steered after the run completes": the completed event is read while the follow-up is queued, then the queued run is cancelled without starting. On main the test fails with expected [] to deeply equal ["server:idle-compact:idle-thread:run-1"]. With the change it passes, and the other 14 tests in the file still pass (15 of 15).
  • vp run check:changed passes (format, lint, knip, graphql, typecheck, tests).
  • Server-only change with no visible surface, so there are no captures. Runtime transcript from a real server on each side: a fresh T3 home with idleCompaction: "beforeCacheExpires", one real claudeAgent turn (Haiku) with a follow-up queued behind it, and the follow-up cancelled through t3_queue 0.07 seconds after the turn completed, before it started. The turn is below the 200K-token floor, so neither side sends /compact. The transcript shows whether the service looks at the thread again after the cancel: on main it does not, here it does. The unit test above covers the dispatch.
Transcript (before: main d023407, after: this branch de58496)
## Before: this checkout with IdleCompactionService.ts from main d023407be8 (the only production file this PR changes)
driver: cancelled the queued follow-up after run 1 completed
--- run events (seconds from run 1 completed) ---
  -8.932s  run.created run 1 preparing
  -8.882s  run.updated run 1 starting
  -8.682s  run.created run 2 queued
  -8.297s  run.updated run 1 running
  +0.000s  run.updated run 1 completed
  +0.072s  run.updated run 2 cancelled (never started)
--- idle-compaction spans (seconds from run 1 completed) ---
  +0.005s  IdleCompactionService.compactWhenDue  Success
compactWhenDue checks: 1

## After: this branch de58496427
driver: cancelled the queued follow-up after run 1 completed
--- run events (seconds from run 1 completed) ---
  -8.969s  run.created run 1 preparing
  -8.924s  run.updated run 1 starting
  -8.725s  run.created run 2 queued
  -8.322s  run.updated run 1 running
  +0.000s  run.updated run 1 completed
  +0.073s  run.updated run 2 cancelled (never started)
--- idle-compaction spans (seconds from run 1 completed) ---
  +0.005s  IdleCompactionService.compactWhenDue  Success
  +0.089s  IdleCompactionService.compactWhenDue  Success
compactWhenDue checks: 2
Driver script (scratch, not committed)

transcript.sh:

#!/usr/bin/env bash
# Runtime transcript for the idle-compaction fix (scratch, not committed).
# usage: transcript.sh <before|after> <port> [files]
# Fresh T3 home, idle compaction "beforeCacheExpires", one real Claude turn with a
# follow-up queued behind it. The follow-up is cancelled after the turn completes and
# before it starts. Prints the thread's run events and the idle-compaction spans.
# The project holds many small untracked files so the end-of-turn checkpoint takes a
# few seconds, which keeps the follow-up queued long enough to cancel it.
set -uo pipefail
label=$1 port=$2 files=${3:-12000}
W=${SCRATCH:?scratch dir holding mcp.py}
repo=${REPO:?t3code checkout}
svc=apps/server/src/orchestration-v2/IdleCompactionService.ts
run=$W/runs/$label-$(date -u +%Y%m%dT%H%M%SZ); home=$run/home; proj=$run/project
mkdir -p "$home/userdata" "$proj"
git -C "$proj" init -q && git -C "$proj" -c user.name=t -c user.email=t@t commit -q --allow-empty -m init
python3 - "$proj" "$files" <<'PY'
import os, sys
root, n = sys.argv[1], int(sys.argv[2])
for i in range(n):
    d = os.path.join(root, f"d{i // 500}"); os.makedirs(d, exist_ok=True)
    open(os.path.join(d, f"f{i}"), "w").write(f"{i}\n")
PY
printf '{"idleCompaction":"beforeCacheExpires"}\n' > "$home/userdata/settings.json"
cd "$repo"
if [ "$label" = before ]; then
  cp "$svc" "$run/service.fixed.ts"
  git show origin/main:"$svc" > "$svc"
  trap 'cp "$run/service.fixed.ts" "$repo/$svc"' EXIT
fi
echo "side: $label | branch head $(git rev-parse --short HEAD), main $(git rev-parse --short origin/main) | $svc differs from main: $(git diff --quiet origin/main -- "$svc" && echo no || echo yes)"
cd "$repo/apps/server"
node src/bin.ts serve --base-dir "$home" --port "$port" "$proj" > "$run/server.log" 2>&1 &
pid=$!
for _ in $(seq 1 90); do curl -fsS "http://127.0.0.1:$port/.well-known/t3/environment" >/dev/null 2>&1 && break; sleep 1; done
node src/bin.ts project add --base-dir "$home" "$proj" > "$run/project-add.log" 2>&1 || cat "$run/project-add.log"
token=$(node src/bin.ts auth session issue --base-dir "$home" --ttl 30m --label transcript --subject mcp-client --token-only 2>"$run/token.err")
ORIGIN="http://127.0.0.1:$port" TOKEN="$token" DB="$home/userdata/statev2.sqlite" START="$run/thread-start.json" PROJ="$proj" W="$W" python3 - <<'PY'
import json, os, sqlite3, sys, time
sys.path.insert(0, os.environ["W"])
from mcp import Mcp
m = Mcp(os.environ["ORIGIN"], os.environ["TOKEN"])
projects = m.call("t3_project_list", {})["projects"]
project = next(p for p in projects if os.path.realpath(p.get("workspaceRoot", "")) == os.path.realpath(os.environ["PROJ"]))
launched = m.call("t3_thread_launch", {"projectId": project.get("projectId") or project["id"], "title": "idle compaction transcript", "runtimeMode": "approval-required",
    "modelSelection": {"instanceId": "claudeAgent", "model": "claude-haiku-5-5"}, "message": "Reply with the single word one."})
thread = launched.get("threadId") or launched.get("thread", {}).get("threadId") or launched.get("id")
if not thread: print("launch output:", json.dumps(launched)[:500]); sys.exit(1)
m.call("t3_thread_send", {"threadId": thread, "message": "Reply with the single word two.", "mode": "queue"})
db = sqlite3.connect("file:" + os.environ["DB"] + "?mode=ro", uri=True, timeout=5)
def runs():
    return db.execute("select ordinal, run_id, status from orchestration_v2_projection_runs where thread_id=? order by ordinal", (thread,)).fetchall()
deadline = time.time() + 180; outcome = "timeout"
while time.time() < deadline:
    try: r = runs()
    except sqlite3.OperationalError: time.sleep(0.05); continue
    if len(r) >= 2 and r[0][2] == "completed":
        if r[1][2] == "queued":
            try:
                m.call("t3_queue", {"action": "cancel", "threadId": thread, "queuedRunId": r[1][1]}); outcome = "cancelled the queued follow-up after run 1 completed"
            except Exception as e: outcome = "cancel failed: " + repr(e)[:300]
        else: outcome = "follow-up was no longer queued (status %s) when run 1 completed" % r[1][2]
        break
    if len(r) >= 1 and r[0][2] in ("failed", "cancelled"): outcome = "run 1 ended as " + r[0][2]; break
    time.sleep(0.03)
print("driver:", outcome)
open(os.path.join(os.path.dirname(os.environ["START"]), "thread.id"), "w").write(thread)
PY
sleep 6
kill "$pid"; while kill -0 "$pid" 2>/dev/null; do sleep 0.3; done
THREAD=$(cat "$run/thread.id" 2>/dev/null) DB="$home/userdata/statev2.sqlite" TRACE="$home/userdata/logs/server.trace.ndjson" python3 - <<'PY'
import json, os, sqlite3, datetime as dt
thread = os.environ["THREAD"]
db = sqlite3.connect("file:" + os.environ["DB"] + "?mode=ro", uri=True)
ev = db.execute("select occurred_at, event_type, json_extract(payload_json,'$.ordinal'), json_extract(payload_json,'$.status'), json_extract(payload_json,'$.startedAt') from orchestration_events where stream_id=? and event_type in ('run.created','run.updated') order by sequence", (thread,)).fetchall()
t0 = None
for at, typ, ordinal, status, started in ev:
    if ordinal == 1 and status == "completed" and t0 is None: t0 = dt.datetime.fromisoformat(at.replace("Z", "+00:00"))
print("--- run events (seconds from run 1 completed) ---")
seen = set()
for at, typ, ordinal, status, started in ev:
    key = (typ, ordinal, status)
    if key in seen: continue
    seen.add(key)
    t = dt.datetime.fromisoformat(at.replace("Z", "+00:00"))
    rel = "%+8.3fs" % (t - t0).total_seconds() if t0 else at
    print(f"{rel}  {typ:11s} run {ordinal} {status}" + (" (never started)" if status == "cancelled" and started is None else ""))
print("--- idle-compaction spans (seconds from run 1 completed) ---")
n = 0
for line in open(os.environ["TRACE"], errors="ignore"):
    if "IdleCompaction" not in line: continue
    try: s = json.loads(line)
    except Exception: continue
    name = s.get("name", "")
    if not name.startswith("IdleCompactionService.compactWhenDue"): continue
    st = dt.datetime.fromtimestamp(int(s["startTimeUnixNano"]) / 1e9, dt.timezone.utc)
    rel = "%+8.3fs" % (st - t0).total_seconds() if t0 else st.isoformat()
    print(f"{rel}  {name}  {s.get('exit', {}).get('_tag', '')}"); n += 1
print(f"compactWhenDue checks: {n}")
PY
echo "run dir: $run"

mcp.py:

"""Minimal MCP-over-HTTP client for the scratch driver (stdlib only)."""
import json, urllib.request

class Mcp:
    def __init__(self, origin, token):
        self.url = origin.rstrip("/") + "/mcp"; self.token = token; self.sid = None; self.n = 0
        r = self.rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "idle-transcript", "version": "0"}})
        self.notify("notifications/initialized")
        self.info = r
    def _post(self, body):
        h = {"content-type": "application/json", "accept": "application/json, text/event-stream", "authorization": "Bearer " + self.token}
        if self.sid: h["mcp-session-id"] = self.sid
        req = urllib.request.Request(self.url, data=json.dumps(body).encode(), headers=h, method="POST")
        with urllib.request.urlopen(req, timeout=60) as resp:
            self.sid = resp.headers.get("mcp-session-id") or self.sid
            raw = resp.read().decode()
            ctype = resp.headers.get("content-type", "")
        if not raw.strip(): return None
        if "text/event-stream" in ctype:
            out = None
            for line in raw.splitlines():
                if line.startswith("data:"):
                    try: m = json.loads(line[5:].strip())
                    except Exception: continue
                    if isinstance(m, dict) and ("result" in m or "error" in m): out = m
            return out
        return json.loads(raw)
    def rpc(self, method, params=None):
        self.n += 1
        m = self._post({"jsonrpc": "2.0", "id": self.n, "method": method, "params": params or {}})
        if m is None: raise RuntimeError("no response to " + method)
        if "error" in m: raise RuntimeError(json.dumps(m["error"]))
        return m["result"]
    def notify(self, method):
        try: self._post({"jsonrpc": "2.0", "method": method})
        except Exception: pass
    def call(self, tool, args):
        r = self.rpc("tools/call", {"name": tool, "arguments": args})
        if r.get("isError"): raise RuntimeError(tool + ": " + json.dumps(r.get("content"))[:600])
        return r.get("structuredContent", r)
  • Not checked: a real /compact dispatch on a thread above 200K tokens after an idle wait of about an hour (the unit test covers that path).

Written by Claude Fable 5.2 in Claude Code, run in T3 Code.

🤖 Generated with Claude Code

…ter the run completes

A follow-up still queued when a run completes is the thread's latest run, so
the completed run's idle-compaction check ends without a timer. Removing or
steering that queued message afterwards emitted only a cancelled update, which
started nothing, so the thread never compacted before its cache expired.

A cancelled update for a run that never started now starts the same check,
which retargets the completed run.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@github-actions github-actions Bot added vouch:unvouched Author is not yet trusted in the VOUCHED list. size:XS 0-9 changed lines (additions + deletions). labels Nov 26, 2026
@coderabbitai

coderabbitai Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The idle-compaction service now schedules a timer when a run is cancelled before starting. A test covers cancellation of a queued follow-up run and checks which run is dispatched after the test clock advances.

Changes: Idle compaction

Layer / File(s) Summary
Schedule timers for cancelled runs
apps/server/src/orchestration-v2/IdleCompactionService.ts, apps/server/src/orchestration-v2/IdleCompaction.test.ts
The run-update filter schedules compaction for completed runs and cancelled runs with no start time. The test cancels a queued follow-up run and verifies that only run-1 is dispatched.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Suggested reviewers: juliusmarminge, stienswout

Merge Risk: Minimal · up to de584

This change lets idle compaction run after a queued follow-up is removed or steered once the prior run has completed. The change is narrow and tested, and no concrete merge-blocking risk was found. The real Claude session behavior was not exercised, as the author notes.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the fix and the affected behavior: idle compaction now runs when a queued message is removed after the run completes. The change adds a cancelled-run trigger in IdleCompactionService.s…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Description check Passed The description follows the repository template closely. It has Problem, Change, Scope, and Verification sections, and each is substantive. The Problem section explains the bug, the event order, and r…
Full details: Title check

Explanation

The title names the fix and the affected behavior: idle compaction now runs when a queued message is removed after the run completes. The change adds a cancelled-run trigger in IdleCompactionService.start, which matches this title. The title follows conventional commit format and is specific enough for a reviewer scanning history.

Full details: Description check

Explanation

The description follows the repository template closely. It has Problem, Change, Scope, and Verification sections, and each is substantive. The Problem section explains the bug, the event order, and reproduction steps. The Change section explains the one-condition fix and why the existing retarget branch takes over. The Scope section states this is a bug fix, links no issue, and explains why none exists. The Verification section lists the environment, a failing-then-passing unit test, the repo check command, and a runtime transcript before and after the change. It also states what was not checked: a real /compact dispatch above 200K tokens after about an hour idle. The template's title guidance (conventional commit title) is not visible in the provided description, since the PR title was not included in the context. The model and harness attribution is present at the end. The description is mostly complete and specific, so it passes.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between b0e87e0 and de58496.

Files selected for processing: 2

  • apps/server/src/orchestration-v2/IdleCompaction.test.ts
  • apps/server/src/orchestration-v2/IdleCompactionService.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

This branch has not been deployed

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

Labels

size:XS 0-9 changed lines (additions + deletions). vouch:unvouched Author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant