Skip to content

Commit 5d3875d

Browse files
t3dotggmaria-rcksclaude
authored
feat(server): compact idle Claude threads before the prompt cache expires (beta) (#21682)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent a752363 commit 5d3875d

14 files changed

Lines changed: 566 additions & 7 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1011,6 +1011,21 @@ describe("ClaudeAdapterV2 context usage", () => {
10111011
undefined,
10121012
);
10131013
});
1014+
1015+
it("dates cache expiry from the request start, not the response end", () => {
1016+
const usage = ClaudeAdapterV2.claudeProviderTurnTokenUsage(
1017+
{
1018+
input_tokens: 1,
1019+
output_tokens: 1,
1020+
cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 300 },
1021+
},
1022+
CLAUDE_TEST_MODEL_SELECTION,
1023+
"2026-08-29T00:03:00.000Z",
1024+
"",
1025+
DateTime.makeUnsafe("2026-08-29T00:00:00.000Z"),
1026+
);
1027+
assert.strictEqual(usage.promptCacheExpiresAt, "2026-08-29T00:05:00.000Z");
1028+
});
10141029
});
10151030

10161031
describe("ClaudeAdapterV2 session permissions", () => {

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -242,11 +242,17 @@ export function claudeProviderTurnTokenUsage(
242242
modelSelection: ModelSelection,
243243
updatedAt: string,
244244
autoCompactWindow = "",
245+
requestedAt?: DateTime.Utc,
245246
) {
246247
const inputTokens = claudeMessageInputTokens(usage);
247248
const outputTokens = usage.output_tokens;
248249
const promptCacheTtlMs = claudePromptCacheTtlMs(usage.cache_creation);
249250
const maxTokens = claudeContextWindow(modelSelection);
251+
// The cache lifetime starts with the request, not when its response ends.
252+
const promptCacheExpiresAt =
253+
promptCacheTtlMs === undefined || requestedAt === undefined
254+
? undefined
255+
: DateTime.formatIso(DateTime.add(requestedAt, { milliseconds: promptCacheTtlMs }));
250256
return {
251257
usedTokens: inputTokens + outputTokens,
252258
maxTokens,
@@ -256,6 +262,7 @@ export function claudeProviderTurnTokenUsage(
256262
reasoningOutputTokens: 0,
257263
...(promptCacheTtlMs === undefined ? {} : { promptCacheTtlMs }),
258264
...claudeAutoCompactThreshold(autoCompactWindow, maxTokens),
265+
...(promptCacheExpiresAt === undefined ? {} : { promptCacheExpiresAt }),
259266
updatedAt,
260267
};
261268
}
@@ -3254,7 +3261,12 @@ interface ActiveClaudeTurnContext {
32543261
// assistant snapshots repeat message_start usage, which some proxies send
32553262
// as zeros, so they only fill in input the stream has not reported. A
32563263
// compaction makes the usage stale (null) without forgetting the request.
3257-
streamUsage: { readonly messageId: string; usage: ClaudeMessageUsage | null } | null;
3264+
// `requestedAt` is when a streamed request started; its prompt cache lifetime starts then.
3265+
streamUsage: {
3266+
readonly messageId: string;
3267+
requestedAt?: DateTime.Utc;
3268+
usage: ClaudeMessageUsage | null;
3269+
} | null;
32583270
readonly toolCalls: Map<string, ActiveClaudeToolCall>;
32593271
// A successful status can precede the boundary that supplies its token counts.
32603272
compaction: Extract<OrchestrationV2TurnItem, { type: "compaction" }> | null;
@@ -4121,13 +4133,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
41214133
const emitContextUsage = Effect.fnUntraced(function* (
41224134
context: ActiveClaudeTurnContext,
41234135
usage: ClaudeMessageUsage,
4136+
requestStarted = false,
41244137
) {
41254138
const now = yield* DateTime.now;
4139+
// Only message_start marks the request start; an assistant snapshot
4140+
// arrives after generation, so it leaves the cache expiry unknown.
4141+
if (requestStarted && context.streamUsage !== null) context.streamUsage.requestedAt = now;
41264142
const tokenUsage = claudeProviderTurnTokenUsage(
41274143
usage,
41284144
context.input.modelSelection,
41294145
DateTime.formatIso(now),
41304146
adapterOptions.settings.autoCompactWindow,
4147+
context.streamUsage?.requestedAt,
41314148
);
41324149
if (tokenUsage.inputTokens <= 0) return;
41334150
yield* emitProviderEvent({
@@ -7388,7 +7405,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
73887405
const usage: ClaudeMessageUsage | undefined = event.message.usage;
73897406
context.streamUsage =
73907407
usage === undefined ? null : { messageId: event.message.id, usage };
7391-
if (usage !== undefined) yield* emitContextUsage(context, usage);
7408+
if (usage !== undefined) yield* emitContextUsage(context, usage, true);
73927409
} else if (event.type === "message_delta") {
73937410
const usage: typeof event.usage | undefined = event.usage;
73947411
const stream = context.streamUsage;
Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import {
3+
DEFAULT_SERVER_SETTINGS,
4+
EventId,
5+
MessageId,
6+
NodeId,
7+
ProjectId,
8+
ProviderDriverKind,
9+
ProviderInstanceId,
10+
ProviderThreadId,
11+
ProviderTurnId,
12+
RunId,
13+
ThreadId,
14+
type OrchestrationV2DomainEvent,
15+
type OrchestrationV2ServerCommand,
16+
} from "@t3tools/contracts";
17+
import * as DateTime from "effect/DateTime";
18+
import * as Effect from "effect/Effect";
19+
import * as Layer from "effect/Layer";
20+
import * as Queue from "effect/Queue";
21+
import * as Stream from "effect/Stream";
22+
import { TestClock } from "effect/testing";
23+
24+
import * as SqlitePersistence from "../persistence/Sqlite.ts";
25+
import * as ServerSettings from "../serverSettings.ts";
26+
import { idleCompactionWindow, type IdleCompactionRecords } from "./IdleCompaction.ts";
27+
import * as IdleCompactionService from "./IdleCompactionService.ts";
28+
import * as Orchestrator from "./Orchestrator.ts";
29+
import * as ProjectionStore from "./ProjectionStore.ts";
30+
31+
const NOW_MS = Date.parse("2026-10-19T12:00:00.000Z");
32+
const MINUTE_MS = 60_000;
33+
const at = (offset = 0) => DateTime.makeUnsafe(NOW_MS + offset);
34+
const threadId = ThreadId.make("idle-thread");
35+
const runId = RunId.make("run-1");
36+
const instanceId = ProviderInstanceId.make("claudeAgent");
37+
const providerThreadId = ProviderThreadId.make("provider-thread");
38+
const modelSelection = { instanceId, model: "claude-opus-5-5" };
39+
40+
function records(
41+
usage: { readonly usedTokens?: number; readonly cacheExpiresInMs?: number } = {},
42+
): { -readonly [Key in keyof IdleCompactionRecords]: IdleCompactionRecords[Key] } {
43+
const messageId = MessageId.make("message-1");
44+
const nodeId = NodeId.make("root-node");
45+
return {
46+
thread: {
47+
id: threadId,
48+
projectId: ProjectId.make("project"),
49+
title: "Idle thread",
50+
createdBy: "user",
51+
creationSource: "web",
52+
providerInstanceId: instanceId,
53+
modelSelection,
54+
runtimeMode: "full-access",
55+
interactionMode: "default",
56+
branch: null,
57+
worktreePath: null,
58+
activeProviderThreadId: providerThreadId,
59+
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
60+
forkedFrom: null,
61+
createdAt: at(-MINUTE_MS),
62+
updatedAt: at(),
63+
archivedAt: null,
64+
settledOverride: null,
65+
settledAt: null,
66+
lastVisitedAt: at(),
67+
deletedAt: null,
68+
},
69+
runs: [
70+
{
71+
id: runId,
72+
threadId,
73+
ordinal: 1,
74+
providerInstanceId: instanceId,
75+
modelSelection,
76+
providerThreadId,
77+
userMessageId: messageId,
78+
rootNodeId: nodeId,
79+
activeAttemptId: null,
80+
status: "completed",
81+
requestedAt: at(-MINUTE_MS),
82+
startedAt: at(-MINUTE_MS),
83+
completedAt: at(),
84+
checkpointId: null,
85+
contextHandoffId: null,
86+
},
87+
],
88+
messages: [
89+
{
90+
id: messageId,
91+
threadId,
92+
runId,
93+
nodeId,
94+
role: "user",
95+
text: "Explain this code",
96+
attachments: [],
97+
streaming: false,
98+
createdBy: "user",
99+
creationSource: "web",
100+
createdAt: at(-MINUTE_MS),
101+
updatedAt: at(-MINUTE_MS),
102+
},
103+
],
104+
providerThreads: [
105+
{
106+
id: providerThreadId,
107+
driver: ProviderDriverKind.make("claudeAgent"),
108+
providerInstanceId: instanceId,
109+
providerSessionId: null,
110+
appThreadId: threadId,
111+
ownerNodeId: nodeId,
112+
nativeThreadRef: null,
113+
nativeConversationHeadRef: null,
114+
status: "idle",
115+
firstRunOrdinal: 1,
116+
lastRunOrdinal: 1,
117+
handoffIds: [],
118+
forkedFrom: null,
119+
pendingBackgroundTasks: [],
120+
createdAt: at(-MINUTE_MS),
121+
updatedAt: at(),
122+
},
123+
],
124+
providerTurns: [
125+
{
126+
id: ProviderTurnId.make("provider-turn-1"),
127+
providerThreadId,
128+
nodeId,
129+
runAttemptId: null,
130+
nativeTurnRef: null,
131+
ordinal: 1,
132+
status: "completed",
133+
startedAt: at(-MINUTE_MS),
134+
completedAt: at(),
135+
tokenUsage: {
136+
usedTokens: usage.usedTokens ?? 250_000,
137+
...(usage.cacheExpiresInMs === undefined
138+
? {}
139+
: { promptCacheExpiresAt: DateTime.formatIso(at(usage.cacheExpiresInMs)) }),
140+
updatedAt: DateTime.formatIso(at()),
141+
},
142+
},
143+
],
144+
runtimeRequests: [],
145+
turnItems: [],
146+
contextTransfers: [],
147+
};
148+
}
149+
150+
describe("idleCompactionWindow", () => {
151+
it("starts two minutes before the cache Claude reported expires", () => {
152+
expect(idleCompactionWindow(records({ cacheExpiresInMs: 60 * MINUTE_MS }), NOW_MS)).toEqual({
153+
runId,
154+
startMs: NOW_MS + 58 * MINUTE_MS,
155+
endMs: NOW_MS + 60 * MINUTE_MS,
156+
});
157+
// A 5m cache whose last request started 3 minutes before the run ended.
158+
const late = records({ cacheExpiresInMs: 2 * MINUTE_MS });
159+
expect(idleCompactionWindow(late, NOW_MS)).toMatchObject({ startMs: NOW_MS });
160+
expect(idleCompactionWindow(late, NOW_MS + 2 * MINUTE_MS)).toBeNull();
161+
});
162+
163+
it("skips small contexts, unknown expiry, other providers, switched threads, and compactions", () => {
164+
const cache = { cacheExpiresInMs: 60 * MINUTE_MS };
165+
expect(idleCompactionWindow(records({ ...cache, usedTokens: 199_999 }), NOW_MS)).toBeNull();
166+
expect(idleCompactionWindow(records(), NOW_MS)).toBeNull();
167+
const codex = records(cache);
168+
codex.providerThreads = [
169+
{ ...codex.providerThreads[0]!, driver: ProviderDriverKind.make("codex") },
170+
];
171+
expect(idleCompactionWindow(codex, NOW_MS)).toBeNull();
172+
const switched = records(cache);
173+
switched.thread = { ...switched.thread, providerInstanceId: ProviderInstanceId.make("codex") };
174+
expect(idleCompactionWindow(switched, NOW_MS)).toBeNull();
175+
const compacted = records(cache);
176+
compacted.messages = [{ ...compacted.messages[0]!, text: "/compact" }];
177+
expect(idleCompactionWindow(compacted, NOW_MS)).toBeNull();
178+
const archived = records(cache);
179+
archived.thread = { ...archived.thread, archivedAt: at() };
180+
expect(idleCompactionWindow(archived, NOW_MS)).toBeNull();
181+
});
182+
});
183+
184+
const seed = Effect.fn("seedIdleThread")(function* (value: IdleCompactionRecords) {
185+
const store = yield* ProjectionStore.ProjectionStoreV2;
186+
const event = { threadId, occurredAt: at() };
187+
yield* store.apply({
188+
...event,
189+
id: EventId.make("e1"),
190+
type: "thread.created",
191+
payload: value.thread,
192+
});
193+
yield* store.apply({
194+
...event,
195+
id: EventId.make("e2"),
196+
type: "run.created",
197+
payload: value.runs[0]!,
198+
});
199+
yield* store.apply({
200+
...event,
201+
id: EventId.make("e3"),
202+
type: "message.updated",
203+
payload: value.messages[0]!,
204+
});
205+
yield* store.apply({
206+
...event,
207+
id: EventId.make("e4"),
208+
type: "provider-thread.updated",
209+
payload: value.providerThreads[0]!,
210+
});
211+
yield* store.apply({
212+
...event,
213+
id: EventId.make("e5"),
214+
type: "provider-turn.updated",
215+
payload: value.providerTurns[0]!,
216+
});
217+
});
218+
219+
it.effect("sends /compact as T3 Code once the cache is about to expire", () =>
220+
Effect.gen(function* () {
221+
yield* TestClock.setTime(NOW_MS);
222+
const value = records({ cacheExpiresInMs: 5 * MINUTE_MS });
223+
yield* seed(value);
224+
const events = yield* Queue.unbounded<OrchestrationV2DomainEvent>();
225+
const commands = yield* Queue.unbounded<OrchestrationV2ServerCommand>();
226+
const reads = yield* Queue.unbounded<void>();
227+
const store = yield* ProjectionStore.ProjectionStoreV2;
228+
const dependencies = Layer.mergeAll(
229+
Layer.succeed(ProjectionStore.ProjectionStoreV2, {
230+
...store,
231+
getThreadRecords: (...args) =>
232+
store.getThreadRecords(...args).pipe(Effect.tap(() => Queue.offer(reads, undefined))),
233+
}),
234+
Layer.mock(ServerSettings.ServerSettingsService)({
235+
getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, compactIdleThreads: true }),
236+
}),
237+
Layer.mock(Orchestrator.OrchestratorV2)({
238+
streamDomainEvents: Stream.fromQueue(events),
239+
dispatch: (command) =>
240+
Queue.offer(commands, command).pipe(Effect.as({ sequence: 1, storedEvents: [] })),
241+
}),
242+
);
243+
yield* Effect.gen(function* () {
244+
const service = yield* IdleCompactionService.make;
245+
yield* service.start();
246+
yield* Queue.offer(events, {
247+
id: EventId.make("completed"),
248+
type: "run.updated",
249+
threadId,
250+
occurredAt: at(),
251+
payload: value.runs[0]!,
252+
});
253+
yield* Queue.take(reads);
254+
yield* TestClock.adjust("2 minutes");
255+
expect(yield* Queue.size(commands)).toBe(0);
256+
yield* TestClock.adjust("1 minute");
257+
expect(yield* Queue.take(commands)).toMatchObject({
258+
type: "message.dispatch",
259+
threadId,
260+
text: "/compact",
261+
createdBy: "agent",
262+
creationSource: "server",
263+
});
264+
}).pipe(Effect.provide(dependencies));
265+
}).pipe(
266+
Effect.provide(ProjectionStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory))),
267+
Effect.scoped,
268+
),
269+
);

0 commit comments

Comments
 (0)