Skip to content

Commit e61c1c3

Browse files
fix(sessions): scope transcript fuse to reset window
1 parent 4a6f99c commit e61c1c3

4 files changed

Lines changed: 255 additions & 36 deletions

File tree

‎src/auto-reply/reply/agent-runner-memory.test.ts‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { EmbeddedAgentRunResult } from "../../agents/embedded-agent-runner/
1010
import type { SessionEntry } from "../../config/sessions.js";
1111
import {
1212
loadSessionEntry,
13+
readSessionTranscriptActiveStats,
1314
readTranscriptStatsSync,
1415
upsertSessionEntryCore,
1516
} from "../../config/sessions/session-accessor.js";
@@ -3270,15 +3271,33 @@ describe("runMemoryFlushIfNeeded", () => {
32703271
});
32713272
});
32723273

3273-
it("leaves an under-limit SQLite Codex session to native token compaction", async () => {
3274+
it("leaves a reset SQLite Codex session below the byte fuse for native compaction", async () => {
32743275
const storePath = path.join(rootDir, "sqlite-codex-under-byte-guard.json");
32753276
const sessionKey = "agent:main:main";
32763277
const scope = { agentId: "main", sessionId: "session", sessionKey, storePath };
32773278
await upsertSessionEntryCore(scope, { sessionId: "session", updatedAt: 10 });
32783279
await replaceTranscriptEvents(scope, [
3279-
{ message: { role: "user", content: "small" }, type: "message" },
3280+
{
3281+
type: "message",
3282+
id: "discarded-old",
3283+
parentId: null,
3284+
message: { role: "user", content: "x".repeat(20_000) },
3285+
},
3286+
{
3287+
type: "reset",
3288+
id: "reset-boundary",
3289+
parentId: "discarded-old",
3290+
timestamp: "2026-08-15T00:00:00.000Z",
3291+
reason: "new",
3292+
},
3293+
{
3294+
type: "message",
3295+
id: "fresh-turn",
3296+
parentId: "reset-boundary",
3297+
message: { role: "user", content: "small" },
3298+
},
32803299
]);
3281-
expect(readTranscriptStatsSync(scope).sizeBytes).toBeLessThan(10 * 1024);
3300+
expect(readSessionTranscriptActiveStats(scope).sizeBytes).toBeLessThan(10 * 1024);
32823301

32833302
const sessionEntry: SessionEntry = {
32843303
sessionId: "session",
@@ -3307,7 +3326,7 @@ describe("runMemoryFlushIfNeeded", () => {
33073326
sessionKey,
33083327
}),
33093328
defaultModel: "gpt-5.5",
3310-
agentCfgContextTokens: 350_000,
3329+
agentCfgContextTokens: 1_000_000,
33113330
sessionEntry,
33123331
sessionStore: { [sessionKey]: sessionEntry },
33133332
sessionKey,

‎src/config/sessions/session-accessor.sqlite-active-events.test.ts‎

Lines changed: 156 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,162 @@ describe("SQLite active transcript event projection", () => {
154154
});
155155
});
156156

157+
it("stops counting discarded transcript bytes after a reset", async () => {
158+
await persistSessionTranscriptTurn(scope, {
159+
messages: [
160+
{
161+
eventId: "discarded-old",
162+
parentId: null,
163+
message: { role: "user", content: `discarded ${"x".repeat(20_000)}` },
164+
},
165+
],
166+
touchSessionEntry: false,
167+
});
168+
await appendTranscriptEvent(scope, {
169+
type: "reset",
170+
id: "reset-boundary",
171+
parentId: "discarded-old",
172+
timestamp: "2026-08-15T00:00:00.000Z",
173+
reason: "new",
174+
});
175+
await persistSessionTranscriptTurn(scope, {
176+
messages: [
177+
{
178+
eventId: "post-reset",
179+
parentId: "reset-boundary",
180+
message: { role: "user", content: "fresh turn" },
181+
},
182+
],
183+
touchSessionEntry: false,
184+
});
185+
186+
expect(readSessionTranscriptActiveStats(scope)).toMatchObject({ eventCount: 1 });
187+
expect(readSessionTranscriptActiveStats(scope).sizeBytes).toBeLessThan(1_000);
188+
});
189+
190+
it("counts paired reset tool results without counting discarded orphan results", async () => {
191+
const assistantMessage = {
192+
role: "assistant" as const,
193+
api: "openai-responses" as const,
194+
provider: "openai",
195+
model: "gpt-5.6-sol",
196+
content: [{ type: "toolCall" as const, id: "call-1", name: "read", arguments: {} }],
197+
stopReason: "toolUse" as const,
198+
timestamp: Date.parse("2026-08-15T00:00:00.000Z"),
199+
usage: {
200+
input: 1,
201+
output: 1,
202+
cacheRead: 0,
203+
cacheWrite: 0,
204+
totalTokens: 2,
205+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
206+
},
207+
};
208+
await persistSessionTranscriptTurn(scope, {
209+
messages: [
210+
{
211+
eventId: "discarded-old",
212+
parentId: null,
213+
message: { role: "user", content: `discarded ${"x".repeat(12_000)}` },
214+
},
215+
{
216+
eventId: "kept-user",
217+
parentId: "discarded-old",
218+
message: { role: "user", content: "kept question" },
219+
},
220+
{ eventId: "kept-assistant", parentId: "kept-user", message: assistantMessage },
221+
{
222+
eventId: "kept-result",
223+
parentId: "kept-assistant",
224+
message: {
225+
role: "toolResult",
226+
toolCallId: "call-1",
227+
toolName: "read",
228+
content: [{ type: "text", text: `paired ${"p".repeat(3_000)}` }],
229+
isError: false,
230+
timestamp: Date.parse("2026-08-15T00:00:01.000Z"),
231+
},
232+
},
233+
{
234+
eventId: "discarded-orphan",
235+
parentId: "kept-result",
236+
message: {
237+
role: "toolResult",
238+
toolCallId: "orphan-call",
239+
toolName: "read",
240+
content: [{ type: "text", text: `orphan ${"o".repeat(20_000)}` }],
241+
isError: false,
242+
timestamp: Date.parse("2026-08-15T00:00:02.000Z"),
243+
},
244+
},
245+
],
246+
touchSessionEntry: false,
247+
});
248+
await appendTranscriptEvent(scope, {
249+
type: "reset",
250+
id: "reset-boundary",
251+
parentId: "discarded-orphan",
252+
timestamp: "2026-08-15T00:00:03.000Z",
253+
reason: "new",
254+
firstKeptEntryId: "kept-user",
255+
});
256+
await persistSessionTranscriptTurn(scope, {
257+
messages: [
258+
{
259+
eventId: "post-reset",
260+
parentId: "reset-boundary",
261+
message: { role: "user", content: "fresh turn" },
262+
},
263+
],
264+
touchSessionEntry: false,
265+
});
266+
267+
const stats = readSessionTranscriptActiveStats(scope);
268+
expect(stats.eventCount).toBe(4);
269+
expect(stats.sizeBytes).toBeGreaterThan(3_000);
270+
expect(stats.sizeBytes).toBeLessThan(8_000);
271+
272+
await persistSessionTranscriptTurn(scope, {
273+
messages: [
274+
{
275+
eventId: "second-post-reset",
276+
parentId: "post-reset",
277+
message: { role: "assistant", content: "fresh answer" },
278+
},
279+
],
280+
touchSessionEntry: false,
281+
});
282+
const parseSpy = vi.spyOn(JSON, "parse");
283+
try {
284+
expect(readSessionTranscriptActiveStats(scope).eventCount).toBe(5);
285+
expect(parseSpy).not.toHaveBeenCalled();
286+
} finally {
287+
parseSpy.mockRestore();
288+
}
289+
});
290+
291+
it("keeps counting genuinely oversized post-reset events", async () => {
292+
await appendTranscriptEvent(scope, {
293+
type: "reset",
294+
id: "reset-boundary",
295+
parentId: null,
296+
timestamp: "2026-08-15T00:00:00.000Z",
297+
reason: "new",
298+
});
299+
await persistSessionTranscriptTurn(scope, {
300+
messages: [
301+
{
302+
eventId: "post-reset",
303+
parentId: "reset-boundary",
304+
message: { role: "user", content: "x".repeat(20_000) },
305+
},
306+
],
307+
touchSessionEntry: false,
308+
});
309+
310+
expect(readSessionTranscriptActiveStats(scope).sizeBytes).toBeGreaterThan(20_000);
311+
});
312+
157313
it("defers mixed legacy and canonical rebuilds off request stacks", async () => {
158314
await persistSessionTranscriptTurn(scope, {
159315
messages: [

‎src/config/sessions/session-accessor.sqlite-active-events.ts‎

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type {
1616
import {
1717
readTranscriptProjectionGeneration,
1818
readVisibleMessageRange,
19+
readVisibleTranscriptStats,
1920
resolveVisibleMessagePositionRange,
2021
resolveVisibleMessagePositions,
2122
} from "./session-accessor.sqlite-reset-window.js";
@@ -148,35 +149,12 @@ export function readRecentSessionTranscriptActiveEvents(
148149
});
149150
}
150151

151-
/** Reads active-path event count and JSONL byte size without materializing payloads. */
152+
/** Reads logical transcript event count and JSONL byte size. */
152153
export function readSessionTranscriptActiveStats(scope: SessionTranscriptReadScope): {
153154
eventCount: number;
154155
sizeBytes: number;
155156
} {
156-
return withCurrentProjectionSnapshot(scope, (projection) => {
157-
const db = getActiveTranscriptKysely(projection.database);
158-
const row = executeSqliteQueryTakeFirstSync(
159-
projection.database.db,
160-
db
161-
.selectFrom("session_transcript_active_events as active")
162-
.innerJoin("transcript_events as event", (join) =>
163-
join
164-
.onRef("event.session_id", "=", "active.session_id")
165-
.onRef("event.seq", "=", "active.event_seq"),
166-
)
167-
.select((eb) => [
168-
eb.fn.count<number>("active.event_seq").as("event_count"),
169-
/* kysely-allow-raw: JSONL size includes one terminating newline per event. */
170-
sql<number>`COALESCE(SUM(LENGTH(CAST(event.event_json AS BLOB))), 0)
171-
+ COUNT(*)`.as("size_bytes"),
172-
])
173-
.where("active.session_id", "=", projection.resolved.sessionId),
174-
);
175-
return {
176-
eventCount: row?.event_count ?? 0,
177-
sizeBytes: row?.size_bytes ?? 0,
178-
};
179-
});
157+
return withCurrentProjectionSnapshot(scope, readVisibleTranscriptStats);
180158
}
181159

182160
/** Reads one append-stable forward page from the materialized active-message projection. */

0 commit comments

Comments
 (0)