@devries-cameron20 / t3code Mirror · read-only / commits / 88ea6e86a5
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 01:45 UTC

fix(server): one bad legacy message no longer stops the server from starting (#15920)

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Julius Marminge <julius0216@outlook.com>

shivam committed Oct 20, 2026 at 00:14 UTC 88ea6e86a532eacde3cce6e175d82314e3b8d1fe
2 files changed +201 -44
apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
+164 -2
@@ -1,10 +1,17 @@
1 import { assert, it } from "@effect/vitest";
2 -import { EventId, ThreadId } from "@t3tools/contracts";
2 +import {
3 + ComposerContextId,
4 + EventId,
5 + type OrchestrationMessageContext,
6 + ThreadId,
7 +} from "@t3tools/contracts";
8 import * as DateTime from "effect/DateTime";
9 import * as Effect from "effect/Effect";
10 +import * as Exit from "effect/Exit";
11 import * as Layer from "effect/Layer";
12 import * as Tracer from "effect/Tracer";
13 import * as SqlClient from "effect/sql/SqlClient";
14 +import * as Statement from "effect/sql/Statement";
15
16 import * as SqlitePersistence from "../../persistence/Sqlite.ts";
17 import { listLinkedPullRequestThreads } from "../../pullRequest/linkedThreads.ts";
@@ -36,6 +43,113 @@ const layerTest = Layer.mergeAll(
43 layerProjectionMaintenanceProvided,
44 );
45
46 +const seedPendingTranscripts = Effect.gen(function* () {
47 + const sql = yield* SqlClient.SqlClient;
48 + const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
49 + const threadIds = [ThreadId.make("thread:first"), ThreadId.make("thread:later")];
50 + yield* sql`
51 + INSERT INTO projection_projects (
52 + project_id, title, workspace_root, scripts_json, created_at, updated_at
53 + ) VALUES (
54 + 'project:background', 'Legacy project', '/tmp/legacy-background', '[]',
55 + '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'
56 + )
57 + `;
58 + for (const threadId of threadIds) {
59 + yield* sql`
60 + INSERT INTO projection_threads (
61 + thread_id, project_id, title, model_selection_json, runtime_mode,
62 + interaction_mode, created_at, updated_at
63 + ) VALUES (
64 + ${threadId}, 'project:background', 'Legacy thread',
65 + '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', 'default',
66 + '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'
67 + )
68 + `;
69 + yield* sql`
70 + INSERT INTO projection_thread_messages (
71 + message_id, thread_id, role, text, is_streaming, created_at, updated_at
72 + ) VALUES
73 + (${`${threadId}:old`}, ${threadId}, 'user', 'Old question', 0,
74 + '2026-01-01T01:00:00.000Z', '2026-01-01T01:00:00.000Z'),
75 + (${`${threadId}:latest`}, ${threadId}, 'user', 'Latest question', 0,
76 + '2026-01-02T01:00:00.000Z', '2026-01-02T01:00:00.000Z')
77 + `;
78 + }
79 + yield* importer.reconcileShells;
80 +});
81 +
82 +it.effect(
83 + "keeps hydrating later transcripts after a defect and leaves the failed thread pending",
84 + () =>
85 + Effect.gen(function* () {
86 + const sql = yield* SqlClient.SqlClient;
87 + const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
88 + const projections = yield* ProjectionStore.ProjectionStoreV2;
89 + yield* seedPendingTranscripts;
90 + yield* sql`
91 + UPDATE projection_thread_messages SET created_at = '0000-not-a-date'
92 + WHERE message_id = 'thread:first:old'
93 + `;
94 +
95 + yield* importer.importPendingTranscripts;
96 +
97 + const later = yield* projections.getThreadProjection(ThreadId.make("thread:later"));
98 + assert.deepStrictEqual(
99 + later.messages.map((message) => message.text),
100 + ["Old question", "Latest question"],
101 + );
102 + assert.deepStrictEqual(
103 + yield* sql`
104 + SELECT thread_id, transcript_imported_at, last_error FROM orchestration_v2_legacy_imports
105 + WHERE transcript_imported_at IS NULL OR last_error IS NOT NULL
106 + `,
107 + [
108 + {
109 + thread_id: "thread:first",
110 + transcript_imported_at: null,
111 + last_error: "Transcript hydration failed; retry on next open.",
112 + },
113 + ],
114 + );
115 + }).pipe(Effect.provide(layerTest)),
116 +);
117 +
118 +it.effect("propagates interruption from transcript reads and retry-marker writes", () =>
119 + Effect.gen(function* () {
120 + const sql = yield* SqlClient.SqlClient;
121 + const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
122 + yield* seedPendingTranscripts;
123 + const interrupted = [];
124 + for (const phase of ["transcript", "retry-marker"]) {
125 + const exit = yield* importer.importPendingTranscripts.pipe(
126 + Effect.provideService(Statement.CurrentTransformer, (statement) => {
127 + const [query] = statement.compile();
128 + const readingTranscript = query.includes("FROM projection_thread_messages");
129 + const writingRetryMarker = query.includes("SET last_error =");
130 + if (phase === "retry-marker" && readingTranscript) {
131 + return Effect.die("transcript read failed");
132 + }
133 + if (phase === "transcript" ? readingTranscript : writingRetryMarker) {
134 + return Effect.interrupt;
135 + }
136 + return Effect.succeed(statement);
137 + }),
138 + Effect.exit,
139 + );
140 + interrupted.push(Exit.hasInterrupts(exit));
141 + }
142 + assert.deepStrictEqual(interrupted, [true, true]);
143 + assert.deepStrictEqual(
144 + yield* sql`
145 + SELECT thread_id FROM orchestration_v2_legacy_imports
146 + WHERE transcript_imported_at IS NOT NULL OR last_error IS NOT NULL
147 + `,
148 + [],
149 + );
150 + }).pipe(Effect.provide(layerTest)),
151 +);
152 +
153 it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
154 it.effect("uses the created-thread index for startup migration checks", () =>
155 Effect.gen(function* () {
@@ -214,6 +328,31 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
328 )
329 `;
330
331 + const validContext = {
332 + version: 1,
333 + records: [
334 + {
335 + version: 1,
336 + contextId: ComposerContextId.make("ctx_1"),
337 + kind: "skill",
338 + label: "$test",
339 + name: "test",
340 + },
341 + ],
342 + } satisfies OrchestrationMessageContext;
343 + yield* sql`
344 + UPDATE projection_thread_messages
345 + SET context_json = CASE message_id
346 + WHEN 'message:legacy:2' THEN '{broken-json'
347 + WHEN 'message:legacy:3' THEN '{"version":2,"records":[]}'
348 + ELSE ${JSON.stringify(validContext)}
349 + END
350 + WHERE thread_id = ${threadId}
351 + `;
352 + const sourceMessages = yield* sql`
353 + SELECT * FROM projection_thread_messages WHERE thread_id = ${threadId} ORDER BY message_id
354 + `;
355 +
356 yield* sql`
357 INSERT INTO projection_thread_pull_requests (
358 thread_id, host, repository, number, url, source, linked_at, snapshot_json
@@ -284,6 +423,13 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
423 shellProjection.messages.map((message) => message.id),
424 ["message:legacy:3", "message:legacy:4"],
425 );
426 + assert.deepStrictEqual(
427 + shellProjection.messages.map((message) => [message.text, message.context]),
428 + [
429 + ["Follow-up question", undefined],
430 + ["Partial answer", validContext],
431 + ],
432 + );
433
434 const renamedAt = DateTime.makeUnsafe("2026-01-05T00:00:00.000Z");
435 yield* eventSink.write({
@@ -308,7 +454,7 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
454 ],
455 });
456
311 - const transcriptImport = yield* importer.ensureTranscript(threadId);
457 + const transcriptImport = yield* importer.importPendingTranscripts;
458 assert.equal(yield* importer.pendingThreadCount, 0);
459 assert.deepStrictEqual(transcriptImport, {
460 importedThreadCount: 1,
@@ -326,6 +472,22 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
472 projection.messages.map((message) => message.id),
473 ["message:legacy:1", "message:legacy:2", "message:legacy:3", "message:legacy:4"],
474 );
475 + const expectedMessages = [
476 + ["First question", validContext],
477 + ["First answer", undefined],
478 + ["Follow-up question", undefined],
479 + ["Partial answer", validContext],
480 + ];
481 + assert.deepStrictEqual(
482 + projection.messages.map((message) => [message.text, message.context]),
483 + expectedMessages,
484 + );
485 + assert.deepStrictEqual(
486 + yield* sql`
487 + SELECT * FROM projection_thread_messages WHERE thread_id = ${threadId} ORDER BY message_id
488 + `,
489 + sourceMessages,
490 + );
491 assert.deepStrictEqual(
492 projection.turnItems
493 .filter(
apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+37 -42
@@ -22,6 +22,7 @@ import {
22 TurnItemId,
23 } from "@t3tools/contracts";
24 import * as KeyedLock from "@t3tools/shared/KeyedLock";
25 +import * as Cause from "effect/Cause";
26 import * as Context from "effect/Context";
27 import * as DateTime from "effect/DateTime";
28 import * as Effect from "effect/Effect";
@@ -126,6 +127,7 @@ const decodeLinkedPullRequest = Schema.decodeUnknownOption(ThreadLinkedPullReque
127 const decodeStoredThread = Schema.decodeUnknownOption(
128 Schema.fromJsonString(OrchestrationV2AppThreadJson),
129 );
130 +const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext);
131
132 function parseJson(json: string): unknown {
133 try {
@@ -151,6 +153,11 @@ function attachmentsFor(row: LegacyMessageRow) {
153 return Option.getOrElse(decodeAttachments(parseJson(row.attachments_json)), () => []);
154 }
155
156 +function contextFor(row: LegacyMessageRow) {
157 + if (!row.context_json) return undefined;
158 + return Option.getOrUndefined(decodeMessageContext(parseJson(row.context_json)));
159 +}
160 +
161 function linkedPullRequestFor(row: LegacyThreadRow) {
162 if (row.linked_pull_request_json === null) return null;
163 return Option.getOrNull(decodeLinkedPullRequest(parseJson(row.linked_pull_request_json)));
@@ -248,6 +255,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
255 const createdAt = dateTime(row.created_at);
256 const updatedAt = dateTime(row.updated_at);
257 const attachments = attachmentsFor(row);
258 + const context = contextFor(row);
259 const message: OrchestrationV2ConversationMessage = {
260 createdBy: row.role === "user" ? "user" : "agent",
261 creationSource: "server",
@@ -257,13 +265,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
265 nodeId: null,
266 role: row.role,
267 text: row.text,
260 - ...(row.context_json
261 - ? {
262 - context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
263 - parseJson(row.context_json),
264 - ),
265 - }
266 - : {}),
268 + ...(context !== undefined ? { context } : {}),
269 attachments,
270 streaming: false,
271 createdAt,
@@ -295,13 +297,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
297 messageId,
298 inputIntent: "turn_start",
299 text: row.text,
298 - ...(row.context_json
299 - ? {
300 - context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
301 - parseJson(row.context_json),
302 - ),
303 - }
304 - : {}),
300 + ...(context !== undefined ? { context } : {}),
301 attachments,
302 }
303 : {
@@ -309,13 +305,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
305 type: "assistant_message",
306 messageId,
307 text: row.text,
312 - ...(row.context_json
313 - ? {
314 - context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
315 - parseJson(row.context_json),
316 - ),
317 - }
318 - : {}),
308 + ...(context !== undefined ? { context } : {}),
309 streaming: false,
310 };
311 return [
@@ -786,24 +776,27 @@ const make = Effect.gen(function* () {
776 let importedMessageCount = 0;
777 for (const row of rows) {
778 const result = yield* ensureTranscript(ThreadId.make(row.thread_id)).pipe(
789 - Effect.tapError((error) =>
790 - Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
791 - threadId: row.thread_id,
792 - cause: error,
793 - }),
794 - ),
795 - Effect.catch(() =>
796 - sql`
797 - UPDATE orchestration_v2_legacy_imports
798 - SET last_error = 'Transcript hydration failed; retry on next open.'
799 - WHERE thread_id = ${row.thread_id}
800 - `.pipe(
801 - Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
802 - Effect.orElseSucceed(() => ({
803 - importedThreadCount: 0,
804 - importedMessageCount: 0,
805 - })),
806 - ),
779 + Effect.catchCauseIf(
780 + (cause) => !Cause.hasInterrupts(cause),
781 + (cause) =>
782 + Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
783 + threadId: row.thread_id,
784 + cause,
785 + }).pipe(
786 + Effect.andThen(() =>
787 + sql`
788 + UPDATE orchestration_v2_legacy_imports
789 + SET last_error = 'Transcript hydration failed; retry on next open.'
790 + WHERE thread_id = ${row.thread_id}
791 + `.pipe(
792 + Effect.catchCauseIf(
793 + (cause) => !Cause.hasInterrupts(cause),
794 + () => Effect.void,
795 + ),
796 + ),
797 + ),
798 + Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
799 + ),
800 ),
801 );
802 importedThreadCount += result.importedThreadCount;
@@ -813,9 +806,11 @@ const make = Effect.gen(function* () {
806 return { importedThreadCount, importedMessageCount };
807 }).pipe(
808 Effect.catchCause((cause) =>
816 - Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
817 - Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
818 - ),
809 + Cause.hasInterrupts(cause)
810 + ? Effect.failCause(Cause.fromReasons<never>(cause.reasons.filter(Cause.isInterruptReason)))
811 + : Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
812 + Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
813 + ),
814 ),
815 );
816