Skip to content

Commit f986584

Browse files
fix(cache-warming): Compact on idle when the request snapshot is too large to store (#3921)
Fixes #3913. Compaction on idle runs at a warmup slot. Before this change, an idle period whose request snapshot was over a limit (`snapshot_too_large` or `images_too_large`) got no warm state, so it got no slot and never compacted on idle. Those are the largest prefixes. Compaction on idle needs only the prefix tokens, the model, and the request overhead. It does not need the snapshot. What changes: - At or above the background compaction mark, with idle compaction on, an idle period with an unstored snapshot now keeps its warm state and its first slot. The warm state records why nothing was stored (`snapshotSkipReason`). - At that slot, `compactOnIdle` runs with `canWarm: false`, so `chooseIdleCompaction` chooses only between compact and stop. When the slot does not compact, it skips with the snapshot skip reason, and the idle period stops. No warmup is sent, and no later slot is scheduled. Without a warmup, the cache expires after that slot. - These periods still count as unwarmed in the idle period savings. They also record their reply gap now, like any period with warm state. Their return behaviour is the same as other periods in the segment. - `design/context-compaction.md` moves this from Gaps to Rules. The public config reference adds one sentence about it. <!-- junior-request-attribution:start --> via @BYK. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:agent%3Af0fe57f3091b65450742b236c6b5bf89 --> -- [View Session](https://junior-prod.sentry.dev/conversations/agent%3Af0fe57f3091b65450742b236c6b5bf89) [[Sentry]](https://sentry.sentry.io/explore/conversations/agent%3Af0fe57f3091b65450742b236c6b5bf89/?project=4510944073809921) <!-- junior-session-footer:end --> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: BYK <[email protected]>
1 parent 1645b3e commit f986584

11 files changed

Lines changed: 302 additions & 192 deletions

File tree

‎.oxlintrc.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@
152152
},
153153
{
154154
"files": [
155-
"packages/junior/src/chat/cache-warming/warmup.ts",
155+
"packages/junior/src/chat/cache-warming/recorder.ts",
156156
"packages/junior/src/chat/pi/traced-stream.ts",
157157
"packages/junior/src/chat/sandbox/egress/vercel.ts"
158158
],

‎design/context-compaction.md‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ prompt cache warm while a person is away, so that a return is fast and cheap.
7272
- A slot that the timer floor covers warms, so the timer's Turn reads the
7373
cache. With too few gaps, the warmup rule does not warm, so a return
7474
writes P either way, and compaction wins.
75+
- An idle period whose request snapshot is too large to store gets no
76+
warmups. At or above the background compaction mark, it still gets its
77+
first warmup slot, because compaction on idle needs no snapshot. That
78+
slot can only compact or stop, and it sends no warmup. Then the idle
79+
period stops.
7580
- After compaction on idle, Junior sends no warmups in that idle period.
7681
The compacted prefix is not in the cache, so its warmup would be a cache
7782
write. A return writes it once either way, so no return chance pays for
@@ -80,10 +85,3 @@ prompt cache warm while a person is away, so that a return is fast and cheap.
8085
Run holds the Conversation, Junior warms instead.
8186
- Compaction on idle runs only while cache warming is on.
8287
`JUNIOR_IDLE_COMPACTION_ENABLED=false` turns off only compaction on idle.
83-
84-
## Gaps
85-
86-
- An idle period whose request snapshot is too large to store gets no
87-
warmups, so it does not compact on idle either. This breaks "at or above
88-
the background compaction mark, an idle Conversation compacts instead of
89-
warming".

‎packages/docs/src/content/docs/reference/config-and-env.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ likely to cost less than that write.
422422
turn reads a much smaller prefix, but it gets a summary in place of
423423
history that it would have kept in that turn, which can make an answer
424424
worse. When no summary is ready, or a turn runs, Junior warms as usual.
425+
A request that is too large to store for warmups gets no warmups. It
426+
still gets one check for a ready summary, which swaps it in or stops.
425427
`JUNIOR_IDLE_COMPACTION_ENABLED=false` turns this off. The default is
426428
`true`.
427429
- While warming is on, Junior sends model requests with the short cache

‎packages/junior/src/chat/agent/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ import {
7070
isAssistantMessage,
7171
} from "@/chat/pi/transcript";
7272
import { createTracedStreamFn } from "@/chat/pi/traced-stream";
73-
import { createCacheWarmingRecorder } from "@/chat/cache-warming/warmup";
73+
import { createCacheWarmingRecorder } from "@/chat/cache-warming/recorder";
7474
import { shouldEmitDevAgentTrace } from "@/chat/runtime/dev-agent-trace";
7575
import {
7676
isTurnInputCommitLostError,
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
/**
2+
* The cache warming recorder of one agent run. It sees each model request of
3+
* the run, records the finished calls, and starts the idle period when the
4+
* Turn ends. `warmup.ts` owns the idle period and its warmups.
5+
*/
6+
import type { AssistantMessage } from "@earendil-works/pi-ai/compat";
7+
// oxlint-disable-next-line no-restricted-imports -- The agent loop stream. Its Turn records the cost.
8+
import { streamSimple } from "@earendil-works/pi-ai/compat";
9+
import { getChatConfig } from "@/chat/config";
10+
import { logWarn } from "@/chat/logging";
11+
import type { AgentRequestStreamFn } from "@/chat/pi/agent-history";
12+
import type { ToolDefinitionsKey } from "@/chat/tool-support/registry";
13+
import { CACHE_RETENTION, type ModelRequest } from "./request";
14+
import { createToolWaitWarmer } from "./tool-wait";
15+
import {
16+
ANSWER_TOOL_ENDINGS,
17+
recordModelCall,
18+
stopIdleWarmups,
19+
type CacheWarmingTurn,
20+
type TurnEnding,
21+
} from "./warmup";
22+
23+
/** Records the model calls of one agent run and schedules cache warmups. */
24+
export interface CacheWarmingRecorder {
25+
/**
26+
* Wrap the stream function so the recorder sees each model request. The
27+
* wrapper also sets the cache retention that warming assumes while warming
28+
* is on.
29+
*/
30+
wrap(base?: AgentRequestStreamFn): AgentRequestStreamFn;
31+
/** Record the finished assistant message of the last model request. */
32+
record(message: AssistantMessage): Promise<void>;
33+
/** Mark that the tools of the last request returned. */
34+
toolsReturned(): void;
35+
/**
36+
* Mark that an answer tool call of the last request ended the run. After
37+
* `reply`, `noReply` or `reportBlocked`, `stop` starts the idle period from
38+
* that request, as a final response would.
39+
*/
40+
answerToolEnded(toolName: string): void;
41+
/** Stop the warmups of this run. Call it when the run ends. */
42+
stop(): Promise<void>;
43+
}
44+
45+
/**
46+
* Create a recorder for one agent run. A failure to record only loses cache
47+
* warming, so it is logged and does not stop the run.
48+
*/
49+
export function createCacheWarmingRecorder(
50+
conversationId: string,
51+
turn: CacheWarmingTurn,
52+
definitionsKey: ToolDefinitionsKey,
53+
): CacheWarmingRecorder {
54+
let lastRequest: ModelRequest | undefined;
55+
// The last finished call, for an idle period that an answer tool starts.
56+
let lastCall:
57+
| { request: ModelRequest; message: AssistantMessage }
58+
| undefined;
59+
let answerToolEnding: TurnEnding | undefined;
60+
// After the first call of the run ends the idle period, the next mid-turn
61+
// calls have nothing to record. This keeps them free of state reads.
62+
let idleEnded = false;
63+
let warmupsStopped: Promise<void> | undefined;
64+
const toolWait = createToolWaitWarmer(conversationId);
65+
return {
66+
wrap:
67+
(base = streamSimple) =>
68+
(model, context, options) => {
69+
if (!warmupsStopped && getChatConfig().cacheWarmingEnabled) {
70+
warmupsStopped = stopIdleWarmups(conversationId);
71+
}
72+
// The tools returned, so this request reads the cache.
73+
toolWait.stop();
74+
// With warming off, Pi's own retention applies.
75+
const cacheRetention =
76+
options?.cacheRetention ??
77+
(getChatConfig().cacheWarmingEnabled ? CACHE_RETENTION : undefined);
78+
lastRequest = {
79+
model,
80+
// Copy the list, so later changes to the run do not change it.
81+
context: { ...context, messages: [...context.messages] },
82+
...(options?.reasoning
83+
? { reasoning: options.reasoning }
84+
: undefined),
85+
...(cacheRetention ? { cacheRetention } : undefined),
86+
startedAtMs: Date.now(),
87+
};
88+
return base(
89+
model,
90+
context,
91+
cacheRetention ? { ...options, cacheRetention } : options,
92+
);
93+
},
94+
record: async (message) => {
95+
const request = lastRequest;
96+
lastRequest = undefined;
97+
await warmupsStopped;
98+
if (!getChatConfig().cacheWarmingEnabled || !request) {
99+
return;
100+
}
101+
try {
102+
await toolWait.record(request, message);
103+
} catch (error) {
104+
logWarn("cache_warming.tool_wait.record_failed", {
105+
"exception.message":
106+
error instanceof Error ? error.message : String(error),
107+
});
108+
}
109+
if (message.stopReason === "error" || message.stopReason === "aborted") {
110+
return;
111+
}
112+
lastCall = { request, message };
113+
if (idleEnded && message.stopReason !== "stop") {
114+
return;
115+
}
116+
idleEnded = message.stopReason !== "stop";
117+
try {
118+
await recordModelCall(
119+
conversationId,
120+
turn,
121+
definitionsKey,
122+
request,
123+
message,
124+
message.stopReason === "stop" ? "reply" : undefined,
125+
);
126+
} catch (error) {
127+
logWarn("cache_warming.model_call.record_failed", {
128+
"exception.message":
129+
error instanceof Error ? error.message : String(error),
130+
});
131+
}
132+
},
133+
toolsReturned: toolWait.toolsReturned,
134+
answerToolEnded: (toolName) => {
135+
answerToolEnding = ANSWER_TOOL_ENDINGS[toolName];
136+
},
137+
stop: async () => {
138+
try {
139+
await toolWait.end(answerToolEnding !== undefined);
140+
} catch (error) {
141+
logWarn("cache_warming.tool_wait.record_failed", {
142+
"exception.message":
143+
error instanceof Error ? error.message : String(error),
144+
});
145+
}
146+
// The answer tool call stopped the run, so no final response came. Its
147+
// request holds the prefix that the next Turn reads.
148+
if (!answerToolEnding || !lastCall) return;
149+
try {
150+
await recordModelCall(
151+
conversationId,
152+
turn,
153+
definitionsKey,
154+
lastCall.request,
155+
lastCall.message,
156+
answerToolEnding,
157+
);
158+
} catch (error) {
159+
logWarn("cache_warming.model_call.record_failed", {
160+
"exception.message":
161+
error instanceof Error ? error.message : String(error),
162+
});
163+
}
164+
},
165+
};
166+
}

‎packages/junior/src/chat/cache-warming/snapshot.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,9 @@ function snapshotContext(
110110
};
111111
}
112112

113+
/** Why a snapshot over a limit stored nothing. */
114+
export type SnapshotSkipReason = "snapshot_too_large" | "images_too_large";
115+
113116
/**
114117
* Store the snapshot of a request context with its images under hash keys.
115118
* Stores nothing and returns a `skipReason` when the snapshot without its
@@ -121,9 +124,7 @@ export async function saveSnapshot(
121124
key: string,
122125
context: Context,
123126
ttlMs: number,
124-
): Promise<
125-
SnapshotSize & { skipReason?: "snapshot_too_large" | "images_too_large" }
126-
> {
127+
): Promise<SnapshotSize & { skipReason?: SnapshotSkipReason }> {
127128
const images = new Map<string, string>();
128129
// Spreading the part keeps `data` at its key position, so the loaded
129130
// snapshot serializes the same way as the original context.

0 commit comments

Comments
 (0)