Skip to content
TypeScript

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

shivam88ea6e86a532
diff --git a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
index 869cb27629c..f10013467de 100644
--- a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
+++ b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.test.ts
@@ -1,10 +1,17 @@
import { assert, it } from "@effect/vitest";
-import { EventId, ThreadId } from "@t3tools/contracts";
+import {
+ ComposerContextId,
+ EventId,
+ type OrchestrationMessageContext,
+ ThreadId,
+} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
+import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Tracer from "effect/Tracer";
import * as SqlClient from "effect/sql/SqlClient";
+import * as Statement from "effect/sql/Statement";
import * as SqlitePersistence from "../../persistence/Sqlite.ts";
import { listLinkedPullRequestThreads } from "../../pullRequest/linkedThreads.ts";
@@ -36,6 +43,113 @@ const layerTest = Layer.mergeAll(
layerProjectionMaintenanceProvided,
);
+const seedPendingTranscripts = Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
+ const threadIds = [ThreadId.make("thread:first"), ThreadId.make("thread:later")];
+ yield* sql`
+ INSERT INTO projection_projects (
+ project_id, title, workspace_root, scripts_json, created_at, updated_at
+ ) VALUES (
+ 'project:background', 'Legacy project', '/tmp/legacy-background', '[]',
+ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'
+ )
+ `;
+ for (const threadId of threadIds) {
+ yield* sql`
+ INSERT INTO projection_threads (
+ thread_id, project_id, title, model_selection_json, runtime_mode,
+ interaction_mode, created_at, updated_at
+ ) VALUES (
+ ${threadId}, 'project:background', 'Legacy thread',
+ '{"instanceId":"codex","model":"gpt-5.4"}', 'full-access', 'default',
+ '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z'
+ )
+ `;
+ yield* sql`
+ INSERT INTO projection_thread_messages (
+ message_id, thread_id, role, text, is_streaming, created_at, updated_at
+ ) VALUES
+ (${`${threadId}:old`}, ${threadId}, 'user', 'Old question', 0,
+ '2026-01-01T01:00:00.000Z', '2026-01-01T01:00:00.000Z'),
+ (${`${threadId}:latest`}, ${threadId}, 'user', 'Latest question', 0,
+ '2026-01-02T01:00:00.000Z', '2026-01-02T01:00:00.000Z')
+ `;
+ }
+ yield* importer.reconcileShells;
+});
+
+it.effect(
+ "keeps hydrating later transcripts after a defect and leaves the failed thread pending",
+ () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ yield* seedPendingTranscripts;
+ yield* sql`
+ UPDATE projection_thread_messages SET created_at = '0000-not-a-date'
+ WHERE message_id = 'thread:first:old'
+ `;
+
+ yield* importer.importPendingTranscripts;
+
+ const later = yield* projections.getThreadProjection(ThreadId.make("thread:later"));
+ assert.deepStrictEqual(
+ later.messages.map((message) => message.text),
+ ["Old question", "Latest question"],
+ );
+ assert.deepStrictEqual(
+ yield* sql`
+ SELECT thread_id, transcript_imported_at, last_error FROM orchestration_v2_legacy_imports
+ WHERE transcript_imported_at IS NULL OR last_error IS NOT NULL
+ `,
+ [
+ {
+ thread_id: "thread:first",
+ transcript_imported_at: null,
+ last_error: "Transcript hydration failed; retry on next open.",
+ },
+ ],
+ );
+ }).pipe(Effect.provide(layerTest)),
+);
+
+it.effect("propagates interruption from transcript reads and retry-marker writes", () =>
+ Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const importer = yield* LegacyV1ThreadImporter.LegacyV1ThreadImporter;
+ yield* seedPendingTranscripts;
+ const interrupted = [];
+ for (const phase of ["transcript", "retry-marker"]) {
+ const exit = yield* importer.importPendingTranscripts.pipe(
+ Effect.provideService(Statement.CurrentTransformer, (statement) => {
+ const [query] = statement.compile();
+ const readingTranscript = query.includes("FROM projection_thread_messages");
+ const writingRetryMarker = query.includes("SET last_error =");
+ if (phase === "retry-marker" && readingTranscript) {
+ return Effect.die("transcript read failed");
+ }
+ if (phase === "transcript" ? readingTranscript : writingRetryMarker) {
+ return Effect.interrupt;
+ }
+ return Effect.succeed(statement);
+ }),
+ Effect.exit,
+ );
+ interrupted.push(Exit.hasInterrupts(exit));
+ }
+ assert.deepStrictEqual(interrupted, [true, true]);
+ assert.deepStrictEqual(
+ yield* sql`
+ SELECT thread_id FROM orchestration_v2_legacy_imports
+ WHERE transcript_imported_at IS NOT NULL OR last_error IS NOT NULL
+ `,
+ [],
+ );
+ }).pipe(Effect.provide(layerTest)),
+);
+
it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
it.effect("uses the created-thread index for startup migration checks", () =>
Effect.gen(function* () {
@@ -214,6 +328,31 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
)
`;
+ const validContext = {
+ version: 1,
+ records: [
+ {
+ version: 1,
+ contextId: ComposerContextId.make("ctx_1"),
+ kind: "skill",
+ label: "$test",
+ name: "test",
+ },
+ ],
+ } satisfies OrchestrationMessageContext;
+ yield* sql`
+ UPDATE projection_thread_messages
+ SET context_json = CASE message_id
+ WHEN 'message:legacy:2' THEN '{broken-json'
+ WHEN 'message:legacy:3' THEN '{"version":2,"records":[]}'
+ ELSE ${JSON.stringify(validContext)}
+ END
+ WHERE thread_id = ${threadId}
+ `;
+ const sourceMessages = yield* sql`
+ SELECT * FROM projection_thread_messages WHERE thread_id = ${threadId} ORDER BY message_id
+ `;
+
yield* sql`
INSERT INTO projection_thread_pull_requests (
thread_id, host, repository, number, url, source, linked_at, snapshot_json
@@ -284,6 +423,13 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
shellProjection.messages.map((message) => message.id),
["message:legacy:3", "message:legacy:4"],
);
+ assert.deepStrictEqual(
+ shellProjection.messages.map((message) => [message.text, message.context]),
+ [
+ ["Follow-up question", undefined],
+ ["Partial answer", validContext],
+ ],
+ );
const renamedAt = DateTime.makeUnsafe("2026-01-05T00:00:00.000Z");
yield* eventSink.write({
@@ -308,7 +454,7 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
],
});
- const transcriptImport = yield* importer.ensureTranscript(threadId);
+ const transcriptImport = yield* importer.importPendingTranscripts;
assert.equal(yield* importer.pendingThreadCount, 0);
assert.deepStrictEqual(transcriptImport, {
importedThreadCount: 1,
@@ -326,6 +472,22 @@ it.layer(layerTest)("LegacyV1ThreadImporter", (it) => {
projection.messages.map((message) => message.id),
["message:legacy:1", "message:legacy:2", "message:legacy:3", "message:legacy:4"],
);
+ const expectedMessages = [
+ ["First question", validContext],
+ ["First answer", undefined],
+ ["Follow-up question", undefined],
+ ["Partial answer", validContext],
+ ];
+ assert.deepStrictEqual(
+ projection.messages.map((message) => [message.text, message.context]),
+ expectedMessages,
+ );
+ assert.deepStrictEqual(
+ yield* sql`
+ SELECT * FROM projection_thread_messages WHERE thread_id = ${threadId} ORDER BY message_id
+ `,
+ sourceMessages,
+ );
assert.deepStrictEqual(
projection.turnItems
.filter(
diff --git a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
index ced91b12fcc..c07eca4048b 100644
--- a/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
+++ b/apps/server/src/orchestration-v2/legacy/LegacyV1ThreadImporter.ts
@@ -22,6 +22,7 @@ import {
TurnItemId,
} from "@t3tools/contracts";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
+import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -126,6 +127,7 @@ const decodeLinkedPullRequest = Schema.decodeUnknownOption(ThreadLinkedPullReque
const decodeStoredThread = Schema.decodeUnknownOption(
Schema.fromJsonString(OrchestrationV2AppThreadJson),
);
+const decodeMessageContext = Schema.decodeUnknownOption(OrchestrationMessageContext);
function parseJson(json: string): unknown {
try {
@@ -151,6 +153,11 @@ function attachmentsFor(row: LegacyMessageRow) {
return Option.getOrElse(decodeAttachments(parseJson(row.attachments_json)), () => []);
}
+function contextFor(row: LegacyMessageRow) {
+ if (!row.context_json) return undefined;
+ return Option.getOrUndefined(decodeMessageContext(parseJson(row.context_json)));
+}
+
function linkedPullRequestFor(row: LegacyThreadRow) {
if (row.linked_pull_request_json === null) return null;
return Option.getOrNull(decodeLinkedPullRequest(parseJson(row.linked_pull_request_json)));
@@ -248,6 +255,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
const createdAt = dateTime(row.created_at);
const updatedAt = dateTime(row.updated_at);
const attachments = attachmentsFor(row);
+ const context = contextFor(row);
const message: OrchestrationV2ConversationMessage = {
createdBy: row.role === "user" ? "user" : "agent",
creationSource: "server",
@@ -257,13 +265,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
nodeId: null,
role: row.role,
text: row.text,
- ...(row.context_json
- ? {
- context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
- parseJson(row.context_json),
- ),
- }
- : {}),
+ ...(context !== undefined ? { context } : {}),
attachments,
streaming: false,
createdAt,
@@ -295,13 +297,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
messageId,
inputIntent: "turn_start",
text: row.text,
- ...(row.context_json
- ? {
- context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
- parseJson(row.context_json),
- ),
- }
- : {}),
+ ...(context !== undefined ? { context } : {}),
attachments,
}
: {
@@ -309,13 +305,7 @@ function messageEvents(row: LegacyMessageRow): ReadonlyArray<OrchestrationV2Doma
type: "assistant_message",
messageId,
text: row.text,
- ...(row.context_json
- ? {
- context: Schema.decodeUnknownSync(OrchestrationMessageContext)(
- parseJson(row.context_json),
- ),
- }
- : {}),
+ ...(context !== undefined ? { context } : {}),
streaming: false,
};
return [
@@ -786,24 +776,27 @@ const make = Effect.gen(function* () {
let importedMessageCount = 0;
for (const row of rows) {
const result = yield* ensureTranscript(ThreadId.make(row.thread_id)).pipe(
- Effect.tapError((error) =>
- Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
- threadId: row.thread_id,
- cause: error,
- }),
- ),
- Effect.catch(() =>
- sql`
- UPDATE orchestration_v2_legacy_imports
- SET last_error = 'Transcript hydration failed; retry on next open.'
- WHERE thread_id = ${row.thread_id}
- `.pipe(
- Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
- Effect.orElseSucceed(() => ({
- importedThreadCount: 0,
- importedMessageCount: 0,
- })),
- ),
+ Effect.catchCauseIf(
+ (cause) => !Cause.hasInterrupts(cause),
+ (cause) =>
+ Effect.logWarning("Failed to hydrate migrated v1 thread transcript", {
+ threadId: row.thread_id,
+ cause,
+ }).pipe(
+ Effect.andThen(() =>
+ sql`
+ UPDATE orchestration_v2_legacy_imports
+ SET last_error = 'Transcript hydration failed; retry on next open.'
+ WHERE thread_id = ${row.thread_id}
+ `.pipe(
+ Effect.catchCauseIf(
+ (cause) => !Cause.hasInterrupts(cause),
+ () => Effect.void,
+ ),
+ ),
+ ),
+ Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
+ ),
),
);
importedThreadCount += result.importedThreadCount;
@@ -813,9 +806,11 @@ const make = Effect.gen(function* () {
return { importedThreadCount, importedMessageCount };
}).pipe(
Effect.catchCause((cause) =>
- Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
- Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
- ),
+ Cause.hasInterrupts(cause)
+ ? Effect.failCause(Cause.fromReasons<never>(cause.reasons.filter(Cause.isInterruptReason)))
+ : Effect.logWarning("Legacy v1 transcript background import stopped", { cause }).pipe(
+ Effect.as({ importedThreadCount: 0, importedMessageCount: 0 }),
+ ),
),
);