GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(server): trim bulky payloads to keep the state database small · mediavee/t3code@b9c8275

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps
    • server/src
      • orchestration-v2
        • EventSink.ts
        • ProjectionMaintenance.test.ts
        • ProjectionMaintenance.ts
        • payloadRetention.ts
      • persistence
        • DatabaseStorage.test.ts
        • DatabaseStorage.ts
        • Migrations
          • ForkIndexes.ts
    • web/src
      • components/chat
        • TimelineWorkEntryRow.tsx
        • V2ItemInspector.tsx
      • i18n/translations
        • de.json
        • en.json
        • es.json
        • fr.json
        • ja.json
        • ko.json
        • pt-BR.json
        • ru.json
        • sv.json
        • zh.json
      • session-logic.ts
  • docs/user
    • background-service.md
  • packages
    • client-runtime/src/work-log
      • itemDetail.ts
    • contracts/src
      • orchestrationV2.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/EventSink.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/EventSink.ts
+2-1Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { replayAndBufferProjectedLiveEvents } from "./LiveStreamBudget.ts";
3232
import type { UnsequencedProjectEvent } from "../persistence/OrchestrationEventStore.ts";
3333
import { projectStoredEventForWire } from "./WireProjection.ts";
3434
import { makeRunOutcomeRecorder, type RunOutcome } from "./RunMetrics.ts";
35+
import { withTruncatedCommandOutput } from "./payloadRetention.ts";
3536

3637
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
3738
import * as EffectOutbox from "./EffectOutbox.ts";
@@ -414,7 +415,7 @@ const layerBase: Layer.Layer<
414415
event.type === "turn-item.updated"
415416
? turnItemPositions
416417
.normalize(
417-
event.payload,
418+
withTruncatedCommandOutput(event.payload),
418419
event.payload.runId === null ? undefined : runOrdinals.get(event.payload.runId),
419420
)
420421
.pipe(Effect.map((payload) => ({ ...event, payload })))
Collapse file

‎apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/ProjectionMaintenance.test.ts
+266Lines changed: 266 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { assert, it } from "@effect/vitest";
22
import {
33
EventId,
4+
MessageId,
45
NodeId,
56
PlanId,
67
type OrchestrationV2AppThread,
@@ -27,6 +28,8 @@ import * as EventSink from "./EventSink.ts";
2728
import * as EventStore from "./EventStore.ts";
2829
import * as ProjectionMaintenance from "./ProjectionMaintenance.ts";
2930
import * as ProjectionStore from "./ProjectionStore.ts";
31+
import * as ProjectionReplay from "./testkit/ProjectionReplay.ts";
32+
import { COMMAND_OUTPUT_LIMIT } from "./payloadRetention.ts";
3033
import * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts";
3134

3235
const database = SqlitePersistence.layerMemory;
@@ -38,6 +41,7 @@ const layerTest = Layer.mergeAll(
3841
OrchestrationEventStore.layer.pipe(Layer.provide(database)),
3942
EventSink.layer.pipe(Layer.provide(stores)),
4043
ProjectionMaintenance.layer.pipe(Layer.provide(stores)),
44+
ProjectionReplay.layer.pipe(Layer.provide(stores)),
4145
);
4246

4347
const providerInstanceId = ProviderInstanceId.make("codex");
@@ -383,3 +387,265 @@ it.effect("keeps an anchor that a row appended during the pass borrows from", ()
383387
}),
384388
).pipe(Effect.provide(layerTest)),
385389
);
390+
391+
function retentionItems(
392+
threadId: ThreadId,
393+
now: DateTime.Utc,
394+
): ReadonlyArray<OrchestrationV2TurnItem> {
395+
const base = (key: string, ordinal: number) => ({
396+
id: TurnItemId.make(`turn-item:${threadId}:${key}`),
397+
threadId,
398+
runId: null,
399+
nodeId: null,
400+
providerThreadId: null,
401+
providerTurnId: null,
402+
nativeItemRef: null,
403+
parentItemId: null,
404+
ordinal,
405+
status: "completed" as const,
406+
title: key,
407+
startedAt: now,
408+
completedAt: now,
409+
updatedAt: now,
410+
});
411+
return [
412+
{
413+
...base("question", 1),
414+
type: "user_message",
415+
messageId: MessageId.make(`message:${threadId}:question`),
416+
inputIntent: "turn_start",
417+
text: "What changed?",
418+
attachments: [],
419+
createdBy: "user",
420+
creationSource: "web",
421+
},
422+
{ ...base("command", 2), type: "command_execution", input: "ls", output: "a\nb", exitCode: 0 },
423+
{ ...base("reasoning", 3), type: "reasoning", text: "Thinking it over", streaming: false },
424+
{
425+
...base("edit", 4),
426+
type: "file_change",
427+
fileName: "a.ts",
428+
additions: 1,
429+
deletions: 0,
430+
diffStr: "+const a = 1;",
431+
},
432+
{
433+
...base("tool", 5),
434+
type: "dynamic_tool",
435+
toolName: "read",
436+
input: { path: "a" },
437+
output: "x",
438+
},
439+
{
440+
...base("sent", 6),
441+
type: "dynamic_tool",
442+
toolName: "send_to_user",
443+
input: { message: "Look" },
444+
output: { sentMessage: "Look" },
445+
},
446+
{ ...base("running", 7), status: "running", type: "reasoning", text: "Still", streaming: true },
447+
{
448+
...base("recording", 9),
449+
type: "dynamic_tool",
450+
toolName: "preview_recording_stop",
451+
input: {},
452+
output: { path: "recording.webm" },
453+
},
454+
{
455+
...base("answer", 8),
456+
type: "assistant_message",
457+
messageId: MessageId.make(`message:${threadId}:answer`),
458+
text: "It changed a.ts",
459+
streaming: false,
460+
},
461+
];
462+
}
463+
464+
const writeRetentionThread = Effect.fn(function* (threadId: ThreadId, unarchive: boolean) {
465+
const sink = yield* EventSink.EventSinkV2;
466+
const now = yield* DateTime.now;
467+
const thread = makeThread(threadId, now);
468+
const event = (
469+
key: string,
470+
type: "thread.archived" | "thread.unarchived",
471+
archivedAt: DateTime.Utc | null,
472+
) =>
473+
({
474+
id: EventId.make(`event:${threadId}:${key}`),
475+
type,
476+
threadId,
477+
occurredAt: now,
478+
payload: { ...thread, archivedAt },
479+
}) satisfies OrchestrationV2DomainEvent;
480+
yield* sink.write({
481+
events: [
482+
{ ...threadCreated(thread, now), id: EventId.make(`event:${threadId}:created`) },
483+
...retentionItems(threadId, now).map(
484+
(payload) =>
485+
({
486+
id: EventId.make(`event:${threadId}:${payload.title}`),
487+
type: "turn-item.updated",
488+
threadId,
489+
occurredAt: now,
490+
payload,
491+
}) satisfies OrchestrationV2DomainEvent,
492+
),
493+
event("archived", "thread.archived", now),
494+
...(unarchive ? [event("unarchived", "thread.unarchived", null)] : []),
495+
],
496+
});
497+
});
498+
499+
const storedPayloads = (threadId: ThreadId) =>
500+
Effect.flatMap(
501+
SqlClient.SqlClient,
502+
(sql) => sql<{ readonly source: string; readonly title: string; readonly payload: string }>`
503+
SELECT 'projection' AS source, json_extract(payload_json, '$.title') AS title,
504+
payload_json AS payload
505+
FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}
506+
UNION ALL
507+
SELECT 'event', json_extract(payload_json, '$.title'), payload_json
508+
FROM orchestration_events
509+
WHERE stream_id = ${threadId} AND event_type = 'turn-item.updated'
510+
ORDER BY 1, 2
511+
`,
512+
).pipe(
513+
Effect.map((rows) =>
514+
rows.map((row) => ({ ...row, payload: JSON.parse(row.payload) as Record<string, unknown> })),
515+
),
516+
);
517+
518+
it.effect("drops tool details of threads archived for 14 days and keeps their conversation", () =>
519+
Effect.gen(function* () {
520+
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
521+
const projections = yield* ProjectionStore.ProjectionStoreV2;
522+
const replay = yield* ProjectionReplay.ProjectionReplay;
523+
const archived = ThreadId.make("thread:retention-archived");
524+
const unarchived = ThreadId.make("thread:retention-unarchived");
525+
yield* writeRetentionThread(archived, false);
526+
yield* writeRetentionThread(unarchived, true);
527+
const before = yield* storedPayloads(archived);
528+
const unarchivedBefore = yield* storedPayloads(unarchived);
529+
530+
yield* TestClock.adjust("13 days");
531+
assert.equal((yield* maintenance.trimPayloads()).trimmedThreadCount, 0);
532+
assert.deepEqual(yield* storedPayloads(archived), before);
533+
534+
yield* TestClock.adjust("2 days");
535+
assert.deepEqual(yield* maintenance.trimPayloads(), {
536+
truncatedOutputCount: 0,
537+
trimmedThreadCount: 1,
538+
trimmedItemCount: 4,
539+
});
540+
const trimmed = yield* storedPayloads(archived);
541+
const expected = before.map(({ source, title, payload }) => {
542+
const removed: Record<string, unknown> = { ...payload, detailsRemoved: true };
543+
switch (title) {
544+
case "command":
545+
delete removed.output;
546+
return { source, title, payload: removed };
547+
case "tool":
548+
delete removed.output;
549+
return { source, title, payload: { ...removed, input: null } };
550+
case "reasoning":
551+
return { source, title, payload: { ...removed, text: "" } };
552+
case "edit":
553+
delete removed.diffStr;
554+
return { source, title, payload: removed };
555+
default:
556+
return { source, title, payload };
557+
}
558+
});
559+
assert.deepEqual(trimmed, expected);
560+
assert.deepEqual(yield* storedPayloads(unarchived), unarchivedBefore);
561+
// The server's read path still decodes the trimmed items.
562+
const projection = yield* projections.getThreadProjection(archived);
563+
assert.include(JSON.stringify(projection), '"detailsRemoved":true');
564+
565+
assert.deepEqual(yield* maintenance.trimPayloads(), {
566+
truncatedOutputCount: 0,
567+
trimmedThreadCount: 0,
568+
trimmedItemCount: 0,
569+
});
570+
assert.deepEqual(yield* storedPayloads(archived), trimmed);
571+
572+
// Replaying the remaining events neither fails nor brings the details back.
573+
assert.isTrue((yield* replay.rebuild).valid);
574+
assert.deepEqual(yield* storedPayloads(archived), trimmed);
575+
assert.deepEqual(yield* storedPayloads(unarchived), unarchivedBefore);
576+
assert.equal((yield* maintenance.trimPayloads()).trimmedThreadCount, 1);
577+
assert.deepEqual(yield* storedPayloads(archived), trimmed);
578+
}).pipe(Effect.provide(layerTest)),
579+
);
580+
581+
it.effect("truncates long command output as it is written and once for older rows", () =>
582+
Effect.gen(function* () {
583+
const sink = yield* EventSink.EventSinkV2;
584+
const maintenance = yield* ProjectionMaintenance.ProjectionMaintenanceV2;
585+
const sql = yield* SqlClient.SqlClient;
586+
const now = yield* DateTime.now;
587+
const threadId = ThreadId.make("thread:truncation");
588+
const head = "h".repeat(16 * 1024);
589+
const tail = "t".repeat(16 * 1024);
590+
const withOutput = (key: string, output: string) =>
591+
({
592+
id: EventId.make(`event:truncation:${key}`),
593+
type: "turn-item.updated",
594+
threadId,
595+
occurredAt: now,
596+
payload: {
597+
...retentionItems(threadId, now)[1]!,
598+
id: TurnItemId.make(`turn-item:truncation:${key}`),
599+
title: key,
600+
output,
601+
} as OrchestrationV2TurnItem,
602+
}) satisfies OrchestrationV2DomainEvent;
603+
const middle = "m".repeat(COMMAND_OUTPUT_LIMIT - head.length - tail.length);
604+
const limit = head + middle + tail;
605+
const over = `${head}${middle}m${tail}`;
606+
yield* sink.write({
607+
events: [
608+
threadCreated(makeThread(threadId, now), now),
609+
withOutput("limit", limit),
610+
withOutput("over", over),
611+
],
612+
});
613+
const truncated = `${head}\n\n[… 32,769 characters removed: the full output was 65,537 characters …]\n\n${tail}`;
614+
const outputs = () =>
615+
sql<{ readonly title: string; readonly output: string }>`
616+
SELECT json_extract(payload_json, '$.title') AS title,
617+
json_extract(payload_json, '$.output') AS output
618+
FROM orchestration_v2_projection_turn_items WHERE thread_id = ${threadId}
619+
UNION ALL
620+
SELECT json_extract(payload_json, '$.title'), json_extract(payload_json, '$.output')
621+
FROM orchestration_events
622+
WHERE stream_id = ${threadId} AND event_type = 'turn-item.updated'
623+
`.pipe(
624+
// Compare by identity, not content: a failing diff of 64 KiB strings is unreadable.
625+
Effect.map((rows) =>
626+
rows
627+
.map(
628+
(row) =>
629+
`${row.title}:${row.output === limit ? "limit" : row.output === truncated ? "truncated" : row.output.length}`,
630+
)
631+
.sort(),
632+
),
633+
);
634+
const expected = ["limit:limit", "limit:limit", "over:truncated", "over:truncated"];
635+
assert.deepEqual(yield* outputs(), expected);
636+
637+
// Rows written before truncation existed.
638+
yield* sql`
639+
UPDATE orchestration_v2_projection_turn_items
640+
SET payload_json = json_set(payload_json, '$.output', ${over})
641+
WHERE json_extract(payload_json, '$.title') = 'over'
642+
`;
643+
yield* sql`
644+
UPDATE orchestration_events SET payload_json = json_set(payload_json, '$.output', ${over})
645+
WHERE json_extract(payload_json, '$.title') = 'over'
646+
`;
647+
assert.equal((yield* maintenance.trimPayloads()).truncatedOutputCount, 1);
648+
assert.deepEqual(yield* outputs(), expected);
649+
assert.equal((yield* maintenance.trimPayloads()).truncatedOutputCount, 0);
650+
}).pipe(Effect.provide(layerTest)),
651+
);

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.