Skip to content

Commit c4ddff2

Browse files
committed
fix: native session usage stays zero after /new
Carry the claimed writer independently of optional ordered context telemetry. Preserve unknown/zero chronology and exact-writer fencing; repair live admission, directory ownership, tool-event capability and cache-contract fixtures. Fixes #133346. Related to #133260.
1 parent 3efa9e8 commit c4ddff2

19 files changed

Lines changed: 406 additions & 148 deletions

‎docs/reference/session-management-compaction.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ Two different concepts:
195195
1. **Model context window**: hard cap per model (tokens visible to the model). Comes from the model catalog and can be overridden via config.
196196
2. **Session store counters**: rolling stats written into the session row (used for `/status` and dashboards). `contextTokens` is a runtime estimate/reporting value - do not treat it as a strict guarantee.
197197

198+
Completed turns update session counters even when no compaction occurred. An ordered context replacement takes precedence over earlier model usage; if its size is unknown, the counters are marked stale instead of borrowing an older request's total. A superseded run cannot overwrite the current writer's counters.
199+
198200
More on limits: [/reference/token-use](/reference/token-use).
199201

200202
## Compaction: what it is

‎src/agents/agent-command.compaction-rotation.test.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,9 +36,9 @@ registerAgentCommandCompactionTestHooks();
3636

3737
async function commitAttemptCompaction(
3838
params: Parameters<typeof state.runAgentAttemptMock>[0],
39-
accounting: Pick<CompactionAccountingFact, "count" | "currentContextTokens"> = {
39+
accounting: Pick<CompactionAccountingFact, "count" | "currentContextSnapshot"> = {
4040
count: 1,
41-
currentContextTokens: 42,
41+
currentContextSnapshot: { tokens: 42 },
4242
},
4343
) {
4444
const target = params.sessionTarget;
@@ -219,7 +219,7 @@ describe("agentCommand compaction transcript rotation", () => {
219219

220220
it.each([42, 95_000, 0, undefined])(
221221
"keeps successor context %s from the private ordered fact, not public snapshots",
222-
async (currentContextTokens) => {
222+
async (tokens) => {
223223
const storePath = requireStorePath();
224224
const rotatedSessionFile = formatSqliteSessionFileMarker({
225225
agentId: "main",
@@ -228,7 +228,10 @@ describe("agentCommand compaction transcript rotation", () => {
228228
});
229229
const usage = { input: 100_000, output: 3_000, cacheRead: 20_000, cacheWrite: 1_000 };
230230
state.runAgentAttemptMock.mockImplementationOnce(async (params) => {
231-
const accepted = await commitAttemptCompaction(params, { count: 1, currentContextTokens });
231+
const accepted = await commitAttemptCompaction(params, {
232+
count: 1,
233+
currentContextSnapshot: { tokens },
234+
});
232235
await appendTranscriptMessage(accepted.sessionTarget, {
233236
message: { role: "assistant", content: "first answer after rotation", timestamp: 1 },
234237
});
@@ -270,9 +273,9 @@ describe("agentCommand compaction transcript rotation", () => {
270273
outputTokens: usage.output,
271274
cacheRead: usage.cacheRead,
272275
cacheWrite: usage.cacheWrite,
273-
totalTokensFresh: currentContextTokens !== undefined,
276+
totalTokensFresh: tokens !== undefined,
274277
});
275-
expect(entry.totalTokens).toBe(currentContextTokens);
278+
expect(entry.totalTokens).toBe(tokens);
276279
await expect(
277280
loadTranscriptEvents({ agentId: "main", sessionId: "rotated-session", storePath }),
278281
).resolves.toContainEqual(
@@ -299,7 +302,7 @@ describe("agentCommand compaction transcript rotation", () => {
299302
params.onCompactionAccounting?.({
300303
kind: "durable",
301304
count: 0,
302-
currentContextTokens: 95_000,
305+
currentContextSnapshot: { tokens: 95_000 },
303306
target: {
304307
...params.sessionTarget,
305308
lifecycleRevision: entry.lifecycleRevision,
@@ -355,7 +358,7 @@ describe("agentCommand compaction transcript rotation", () => {
355358
released = true;
356359
},
357360
});
358-
await commitAttemptCompaction(params, { count: 2, currentContextTokens: 42 });
361+
await commitAttemptCompaction(params, { count: 2, currentContextSnapshot: { tokens: 42 } });
359362
controller.abort(aborted);
360363
throw aborted;
361364
});

‎src/agents/agent-command.embedded-maintenance.test.ts‎

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,28 @@ describe("agentCommand embedded maintenance", () => {
204204
expect(findStoredSessionEntry(sessionKey)?.pendingFinalDelivery).toBeUndefined();
205205
});
206206

207-
it.each([false, true])(
208-
"refreshes count-zero retry context only for its retained writer (replacement=%s)",
209-
async (replaceWriter) => {
207+
it.each([
208+
{
209+
retry: "model context",
210+
replaceWriter: false,
211+
initialTokens: 42,
212+
currentContextSnapshot: { tokens: 95_000 },
213+
},
214+
{
215+
retry: "model context",
216+
replaceWriter: true,
217+
initialTokens: 42,
218+
currentContextSnapshot: { tokens: 95_000 },
219+
},
220+
{
221+
retry: "custody only after unknown compaction",
222+
replaceWriter: false,
223+
initialTokens: undefined,
224+
currentContextSnapshot: undefined,
225+
},
226+
])(
227+
"keeps count-zero retry $retry on its retained writer (replacement=$replaceWriter)",
228+
async ({ replaceWriter, initialTokens, currentContextSnapshot }) => {
210229
const sessionId = "retry-context-owner";
211230
const sessionKey = `agent:main:explicit:${sessionId}`;
212231
const storePath = requireStorePath();
@@ -221,7 +240,7 @@ describe("agentCommand embedded maintenance", () => {
221240
params.onCompactionAccounting?.({
222241
kind: "durable",
223242
count: 1,
224-
currentContextTokens: 42,
243+
currentContextSnapshot: { tokens: initialTokens },
225244
target: {
226245
...target,
227246
lifecycleRevision: entry.lifecycleRevision,
@@ -256,25 +275,39 @@ describe("agentCommand embedded maintenance", () => {
256275
params.onCompactionAccounting?.({
257276
kind: "durable",
258277
count: 0,
259-
currentContextTokens: 95_000,
278+
...(currentContextSnapshot ? { currentContextSnapshot } : {}),
260279
target: {
261280
...target,
262281
lifecycleRevision: entry.lifecycleRevision,
263282
activeWriterRunId: entry.activeWriterRunId,
264283
},
265284
});
266-
return makeResult({ sessionId, text: "retry answer", runner: "embedded" });
285+
const result = makeResult({ sessionId, text: "retry answer", runner: "embedded" });
286+
if (!currentContextSnapshot) {
287+
const usage = { input: 95_000, output: 10 };
288+
result.meta.agentMeta = {
289+
...result.meta.agentMeta!,
290+
promptTokens: 95_000,
291+
usage,
292+
lastCallUsage: usage,
293+
};
294+
}
295+
return result;
267296
});
268297

269298
await agentCommand({ message: "continue", sessionId, sessionKey });
270299

271300
expect(state.runAgentAttemptMock).toHaveBeenCalledTimes(2);
272-
expect(findStoredSessionEntry(sessionKey)).toMatchObject({
301+
const stored = findStoredSessionEntry(sessionKey);
302+
expect(stored).toMatchObject({
273303
sessionId,
274304
compactionCount: replaceWriter ? 7 : 1,
275-
totalTokens: replaceWriter ? 777 : 95_000,
276-
totalTokensFresh: true,
305+
totalTokensFresh: replaceWriter || currentContextSnapshot !== undefined,
277306
});
307+
expect(stored?.totalTokens).toBe(replaceWriter ? 777 : currentContextSnapshot?.tokens);
308+
if (!currentContextSnapshot) {
309+
expect(stored).toMatchObject({ inputTokens: 95_000, outputTokens: 10 });
310+
}
278311
expect(loadSessionEntry({ sessionKey, storePath })?.activeWriterRunId).toBe(
279312
replaceWriter ? "replacement-writer" : retainedWriter,
280313
);
@@ -332,7 +365,7 @@ describe("agentCommand embedded maintenance", () => {
332365
params.onCompactionAccounting?.({
333366
kind: "durable",
334367
count: testCase.compactionCount,
335-
currentContextTokens: undefined,
368+
currentContextSnapshot: { tokens: undefined },
336369
target: {
337370
...target,
338371
lifecycleRevision: entry.lifecycleRevision,

‎src/agents/command/compaction-accounting.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ export function createCommandCompactionAccounting(params: {
3535
return accounting;
3636
},
3737
beginCandidate() {
38-
if (accounting) {
38+
if (accounting?.currentContextSnapshot) {
3939
// Only an ordered fact from this candidate can restore current context.
40-
accounting = { ...accounting, currentContextTokens: undefined };
40+
accounting = { ...accounting, currentContextSnapshot: { tokens: undefined } };
4141
}
4242
let candidateFact: CompactionAccountingFact | undefined;
4343
return {
@@ -52,7 +52,7 @@ export function createCommandCompactionAccounting(params: {
5252
}
5353
candidateFact = fact;
5454
if (fact?.kind === "durable") {
55-
// The first model-only fact binds finalization; later unrelated zeros cannot rebind it.
55+
// The first writer fact binds finalization; later unrelated zeros cannot rebind it.
5656
params.onDurableFact(fact);
5757
}
5858
},
@@ -64,7 +64,12 @@ export function createCommandCompactionAccounting(params: {
6464
const carriedCount = hasSameCompactionWriter(accounting?.target, fact.target)
6565
? (accounting?.count ?? 0)
6666
: 0;
67-
accounting = { ...fact, count: carriedCount + fact.count };
67+
accounting = {
68+
...fact,
69+
count: carriedCount + fact.count,
70+
currentContextSnapshot:
71+
fact.currentContextSnapshot ?? accounting?.currentContextSnapshot,
72+
};
6873
if (fact.count > 0 && params.persistCounts) {
6974
await incrementCompactionCount({
7075
agentId: fact.target.agentId,
@@ -74,7 +79,7 @@ export function createCommandCompactionAccounting(params: {
7479
storePath: fact.target.storePath,
7580
expectedSession: fact.target,
7681
amount: fact.count,
77-
tokensAfter: fact.currentContextTokens,
82+
tokensAfter: fact.currentContextSnapshot?.tokens,
7883
});
7984
params.refreshSessionEntry(fact.target.sessionKey);
8085
}

‎src/agents/command/session-store.test.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ describe("updateSessionStoreAfterAgentRun", () => {
224224
compactionAccounting: {
225225
kind: "durable",
226226
count: 0,
227-
currentContextTokens: 42,
227+
currentContextSnapshot: { tokens: 42 },
228228
target: {
229229
agentId: "main",
230230
sessionId: owner.sessionId,
@@ -1502,7 +1502,7 @@ describe("updateSessionStoreAfterAgentRun", () => {
15021502
compactionAccounting: {
15031503
kind: "durable",
15041504
count,
1505-
currentContextTokens: tokens,
1505+
currentContextSnapshot: { tokens },
15061506
target: {
15071507
agentId: "main",
15081508
sessionId,
@@ -1571,7 +1571,7 @@ describe("updateSessionStoreAfterAgentRun", () => {
15711571
compactionAccounting: {
15721572
kind: "durable",
15731573
count: 0,
1574-
currentContextTokens: 42,
1574+
currentContextSnapshot: { tokens: 42 },
15751575
target: {
15761576
agentId: "main",
15771577
sessionId,
@@ -1670,7 +1670,7 @@ describe("updateSessionStoreAfterAgentRun", () => {
16701670
compactionAccounting: {
16711671
kind: "durable",
16721672
count: 1,
1673-
currentContextTokens: tokens,
1673+
currentContextSnapshot: { tokens },
16741674
target: {
16751675
agentId: "main",
16761676
sessionId,

‎src/agents/command/session-store.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -219,16 +219,17 @@ export async function updateSessionStoreAfterAgentRun(params: {
219219
}
220220
}
221221
if (!preserveUserFacingRunState) {
222-
const totalTokens = params.compactionAccounting
223-
? params.compactionAccounting.currentContextTokens
222+
const currentContextSnapshot = params.compactionAccounting?.currentContextSnapshot;
223+
const totalTokens = currentContextSnapshot
224+
? currentContextSnapshot.tokens
224225
: hasUsage
225226
? deriveSessionTotalTokens({ lastCallUsage, contextTokens, promptTokens })
226227
: undefined;
227228
if (totalTokens !== undefined) {
228229
next.totalTokens = totalTokens;
229230
next.totalTokensFresh = true;
230231
next.totalTokensVersion = SESSION_TOTAL_TOKENS_VERSION;
231-
} else if (params.compactionAccounting || hasUsage) {
232+
} else if (currentContextSnapshot || hasUsage) {
232233
next.totalTokens = undefined;
233234
next.totalTokensFresh = false;
234235
next.totalTokensVersion = undefined;

0 commit comments

Comments
 (0)