Skip to content

Commit 8240f2a

Browse files
fix(persistence): repair previously serialized model options
Add migration 097 to repair model option arrays that migration 026 already stored as JSON strings in projections and affected event payloads. Preserve canonical values and unrelated data, including invalid non-array strings. Cover already-migrated databases, v2 project baselines, boolean and empty arrays, repeat startup, and byte-identical canonical records. Implemented and reviewed with GPT-6 Astra Pro in ChatGPT.
1 parent e3f7b4d commit 8240f2a

4 files changed

Lines changed: 164 additions & 1 deletion

File tree

‎apps/server/src/persistence/Migrations.test.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ const learningQueueMigration = [93, "ProjectKnowledgeLearningQueue"] as const;
3030
const summaryPositionMigration = [94, "ConversationSummaryPosition"] as const;
3131
const retireRouteInstancesMigration = [95, "RetireInferenceRouteInstances"] as const;
3232
const knowledgeViewsMigration = [96, "ProjectKnowledgeViews"] as const;
33+
const serializedModelOptionsMigration = [97, "RepairSerializedModelSelectionOptions"] as const;
3334

3435
it.effect("upgrades attempt receipts atomically and preserves distinct steering messages", () =>
3536
Effect.gen(function* () {
@@ -61,6 +62,7 @@ it.effect("upgrades attempt receipts atomically and preserves distinct steering
6162
summaryPositionMigration,
6263
retireRouteInstancesMigration,
6364
knowledgeViewsMigration,
65+
serializedModelOptionsMigration,
6466
]);
6567
assert.deepStrictEqual(yield* sql`SELECT * FROM project_knowledge_deliveries`, before);
6668
yield* sql`INSERT INTO project_knowledge_deliveries (
@@ -109,7 +111,10 @@ it.effect.each(["original", "unexpected"] as const)(
109111
);
110112
return;
111113
}
112-
assert.deepStrictEqual(yield* runMigrations(), [[95, "RetireInferenceRouteInstances"]]);
114+
assert.deepStrictEqual(yield* runMigrations(), [
115+
retireRouteInstancesMigration,
116+
serializedModelOptionsMigration,
117+
]);
113118
assert.deepStrictEqual(yield* sql`SELECT * FROM project_knowledge_views`, before);
114119
assert.deepStrictEqual(
115120
(yield* sql<{ migration_id: number; name: string }>`
@@ -251,6 +256,7 @@ it.effect("rebuilds knowledge facts as saved or forgotten, atomically and in pla
251256
summaryPositionMigration,
252257
retireRouteInstancesMigration,
253258
knowledgeViewsMigration,
259+
serializedModelOptionsMigration,
254260
]);
255261

256262
const cleared = new Set([
@@ -342,6 +348,7 @@ it.effect("rebuilds knowledge facts as saved or forgotten, atomically and in pla
342348
const savedCommands = yield* commands;
343349
const savedRuns = yield* sql`SELECT * FROM project_knowledge_assisted_runs`;
344350
const savedSchema = yield* schema;
351+
yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id = 97`;
345352
yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id = 95`;
346353
yield* sql`DROP TABLE project_knowledge_views`;
347354
yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id = 96`;
@@ -394,6 +401,7 @@ it.effect("rebuilds knowledge facts as saved or forgotten, atomically and in pla
394401
summaryPositionMigration,
395402
retireRouteInstancesMigration,
396403
knowledgeViewsMigration,
404+
serializedModelOptionsMigration,
397405
]);
398406
assert.deepStrictEqual(yield* facts, savedFacts);
399407
assert.deepStrictEqual(yield* history, savedHistory);
@@ -749,6 +757,7 @@ describe("runMigrations", () => {
749757
summaryPositionMigration,
750758
retireRouteInstancesMigration,
751759
knowledgeViewsMigration,
760+
serializedModelOptionsMigration,
752761
],
753762
);
754763
yield* assertConsolidatedSchema;
@@ -796,6 +805,7 @@ describe("runMigrations", () => {
796805
summaryPositionMigration,
797806
retireRouteInstancesMigration,
798807
knowledgeViewsMigration,
808+
serializedModelOptionsMigration,
799809
],
800810
);
801811
assert.deepStrictEqual(yield* runMigrations(), [
@@ -816,6 +826,7 @@ describe("runMigrations", () => {
816826
summaryPositionMigration,
817827
retireRouteInstancesMigration,
818828
knowledgeViewsMigration,
829+
serializedModelOptionsMigration,
819830
]);
820831
yield* assertConsolidatedSchema;
821832
assert.deepStrictEqual(
@@ -858,6 +869,7 @@ describe("runMigrations", () => {
858869
summaryPositionMigration,
859870
retireRouteInstancesMigration,
860871
knowledgeViewsMigration,
872+
serializedModelOptionsMigration,
861873
]);
862874

863875
yield* assertConsolidatedSchema;
@@ -970,6 +982,7 @@ describe("runMigrations", () => {
970982
summaryPositionMigration,
971983
retireRouteInstancesMigration,
972984
knowledgeViewsMigration,
985+
serializedModelOptionsMigration,
973986
]);
974987
yield* assertConsolidatedSchema;
975988
assert.deepStrictEqual(yield* sql`SELECT secret_name, fenced FROM peer_environment_links`, [
@@ -1031,6 +1044,7 @@ describe("runMigrations", () => {
10311044
summaryPositionMigration,
10321045
retireRouteInstancesMigration,
10331046
knowledgeViewsMigration,
1047+
serializedModelOptionsMigration,
10341048
]);
10351049
assert.deepStrictEqual(yield* history, migrationManifest);
10361050
assert.deepStrictEqual(
@@ -1097,6 +1111,7 @@ describe("runMigrations", () => {
10971111
summaryPositionMigration,
10981112
retireRouteInstancesMigration,
10991113
knowledgeViewsMigration,
1114+
serializedModelOptionsMigration,
11001115
]);
11011116
assert.deepStrictEqual(yield* history, migrationManifest);
11021117
assert.deepStrictEqual(yield* sql`SELECT * FROM cross_environment_launches`, routes);

‎apps/server/src/persistence/Migrations.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ import Migration0092 from "./Migrations/092_ProjectKnowledgeSavedLifecycle.ts";
103103
import Migration0094 from "./Migrations/094_ConversationSummaryPosition.ts";
104104
import Migration0095 from "./Migrations/095_RetireInferenceRouteInstances.ts";
105105
import Migration0096 from "./Migrations/096_ProjectKnowledgeViews.ts";
106+
import Migration0097 from "./Migrations/097_RepairSerializedModelSelectionOptions.ts";
106107

107108
const migrationEntries = [
108109
[1, "OrchestrationEvents", Migration0001],
@@ -202,6 +203,7 @@ const migrationEntries = [
202203
[94, "ConversationSummaryPosition", Migration0094],
203204
[95, "RetireInferenceRouteInstances", Migration0095],
204205
[96, "ProjectKnowledgeViews", Migration0096],
206+
[97, "RepairSerializedModelSelectionOptions", Migration0097],
205207
] as const;
206208

207209
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);

‎apps/server/src/persistence/Migrations/026_CanonicalizeModelSelectionOptions.test.ts‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@ import { assert, it } from "@effect/vitest";
22
import * as Effect from "effect/Effect";
33
import * as Layer from "effect/Layer";
44
import * as SqlClient from "effect/sql/SqlClient";
5+
import * as Schema from "effect/Schema";
6+
import { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
57

68
import { runMigrations } from "../Migrations.ts";
79
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
810

911
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layer({ filename: ":memory:" })));
12+
const decodeModelSelection = Schema.decodeUnknownSync(ModelSelection);
1013

1114
layer("026_CanonicalizeModelSelectionOptions", (it) => {
1215
it.effect("converts legacy object-shape options into array-shape on projections and events", () =>
@@ -439,6 +442,109 @@ layer("026_CanonicalizeModelSelectionOptions", (it) => {
439442

440443
assert.isUndefined(payloads["event-activity-append"].modelSelection);
441444
assert.isUndefined(payloads["event-activity-append"].defaultModelSelection);
445+
446+
yield* runMigrations({ toMigrationInclusive: 96 });
447+
const upgradedEvents = yield* sql<{ readonly id: string; readonly value: string }>`
448+
SELECT event_id AS id, payload_json AS value FROM orchestration_events ORDER BY event_id`;
449+
const upgradedPayloads = Object.fromEntries(
450+
upgradedEvents.map(({ id, value }) => [id, JSON.parse(value)]),
451+
);
452+
const serializedProject = JSON.stringify({
453+
...payloads["event-project-created"].defaultModelSelection,
454+
options: JSON.stringify(payloads["event-project-created"].defaultModelSelection.options),
455+
});
456+
const serializedThread = JSON.stringify({
457+
...payloads["event-thread-created"].modelSelection,
458+
options: JSON.stringify(payloads["event-thread-created"].modelSelection.options),
459+
});
460+
yield* sql`UPDATE projection_projects SET default_model_selection_json = ${serializedProject}
461+
WHERE project_id = 'project-legacy'`;
462+
yield* sql`UPDATE projection_threads SET model_selection_json = ${serializedThread}
463+
WHERE thread_id = 'thread-legacy'`;
464+
for (const [eventId, payload] of Object.entries(upgradedPayloads)) {
465+
const key = "defaultModelSelection" in payload ? "defaultModelSelection" : "modelSelection";
466+
if (payload[key]?.options === undefined || eventId.includes("already-array")) continue;
467+
const serialized = JSON.stringify({
468+
...payload,
469+
[key]: { ...payload[key], options: JSON.stringify(payload[key].options) },
470+
});
471+
yield* sql`UPDATE orchestration_events SET payload_json = ${serialized}
472+
WHERE event_id = ${eventId}`;
473+
}
474+
yield* sql`UPDATE projection_threads
475+
SET model_selection_json = ${JSON.stringify({ provider: "codex", model: "gpt-5.4", options: "[]" })}
476+
WHERE thread_id = 'thread-empty-options'`;
477+
const unchanged = ["invalid JSON", '{"reasoningEffort":"high"}', '"high"', "null"];
478+
for (const [index, options] of unchanged.entries()) {
479+
yield* sql`INSERT INTO projection_projects ${sql.insert({
480+
project_id: `project-unchanged-${index}`,
481+
title: "Unrelated invalid options",
482+
workspace_root: `/tmp/unchanged-${index}`,
483+
default_model_selection_json: JSON.stringify({
484+
provider: "codex",
485+
model: "gpt-5.4",
486+
options,
487+
}),
488+
scripts_json: "[]",
489+
created_at: "2026-01-01T00:00:00.000Z",
490+
updated_at: "2026-01-01T00:00:00.000Z",
491+
})}`;
492+
}
493+
494+
yield* runMigrations();
495+
yield* runMigrations();
496+
497+
const repairedProjects = yield* sql<{ readonly id: string; readonly value: string | null }>`
498+
SELECT project_id AS id, default_model_selection_json AS value FROM projection_projects
499+
ORDER BY project_id`;
500+
assert.deepStrictEqual(
501+
repairedProjects.map(({ id, value }) => [id, value === null ? null : JSON.parse(value)]),
502+
[
503+
...projectRows.map((row) => [
504+
row.projectId,
505+
row.defaultModelSelection === null ? null : JSON.parse(row.defaultModelSelection),
506+
]),
507+
...unchanged.map((options, index) => [
508+
`project-unchanged-${index}`,
509+
{ provider: "codex", model: "gpt-5.4", options },
510+
]),
511+
],
512+
);
513+
const repairedThreads = yield* sql<{ readonly id: string; readonly value: string }>`
514+
SELECT thread_id AS id, model_selection_json AS value FROM projection_threads
515+
WHERE thread_id IN ('thread-legacy', 'thread-empty-options') ORDER BY thread_id`;
516+
assert.deepStrictEqual(
517+
repairedThreads.map(({ id, value }) => [id, decodeModelSelection(JSON.parse(value))]),
518+
[
519+
[
520+
"thread-empty-options",
521+
{ instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4", options: [] },
522+
],
523+
[
524+
"thread-legacy",
525+
{
526+
instanceId: ProviderInstanceId.make("claudeAgent"),
527+
model: "claude-opus-4-6",
528+
options: payloads["event-thread-created"].modelSelection.options,
529+
},
530+
],
531+
],
532+
);
533+
const repairedEvents = yield* sql<{ readonly id: string; readonly value: string }>`
534+
SELECT event_id AS id, payload_json AS value FROM orchestration_events ORDER BY event_id`;
535+
assert.deepStrictEqual(
536+
Object.fromEntries(repairedEvents.map(({ id, value }) => [id, JSON.parse(value)])),
537+
upgradedPayloads,
538+
);
539+
assert.strictEqual(
540+
repairedProjects.find(({ id }) => id === "project-already-array")?.value,
541+
projectRows.find(({ projectId }) => projectId === "project-already-array")
542+
?.defaultModelSelection,
543+
);
544+
assert.strictEqual(
545+
repairedEvents.find(({ id }) => id === "event-thread-already-array")?.value,
546+
upgradedEvents.find(({ id }) => id === "event-thread-already-array")?.value,
547+
);
442548
}),
443549
);
444550
});
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import * as Effect from "effect/Effect";
2+
import * as SqlClient from "effect/sql/SqlClient";
3+
4+
export default Effect.gen(function* () {
5+
const sql = yield* SqlClient.SqlClient;
6+
const locations = [
7+
["projection_threads", "model_selection_json", "$.options", null],
8+
["projection_projects", "default_model_selection_json", "$.options", null],
9+
[
10+
"orchestration_events",
11+
"payload_json",
12+
"$.modelSelection.options",
13+
["thread.created", "thread.meta-updated", "thread.turn-start-requested"],
14+
],
15+
[
16+
"orchestration_events",
17+
"payload_json",
18+
"$.defaultModelSelection.options",
19+
["project.created", "project.meta-updated"],
20+
],
21+
] as const;
22+
23+
// Migration 026 could lose SQLite's JSON subtype across its scalar subqueries.
24+
for (const [table, column, property, eventTypes] of locations) {
25+
yield* sql`
26+
UPDATE ${sql(table)}
27+
SET ${sql(column)} = json_replace(
28+
${sql(column)}, ${property}, json(json_extract(${sql(column)}, ${property}))
29+
)
30+
WHERE ${eventTypes === null ? sql`1` : sql.in("event_type", eventTypes)}
31+
AND CASE WHEN json_valid(${sql(column)}) THEN
32+
CASE WHEN json_type(${sql(column)}, ${property}) = 'text' THEN
33+
CASE WHEN json_valid(json_extract(${sql(column)}, ${property})) THEN
34+
json_type(json_extract(${sql(column)}, ${property})) = 'array'
35+
END
36+
END
37+
END
38+
`;
39+
}
40+
});

0 commit comments

Comments
 (0)