Skip to content

Commit 4da0eb1

Browse files
fix(state): converge legacy startup migrations (#107002)
* fix(state): converge legacy startup migrations Co-authored-by: Eva <[email protected]> * refactor(state): split legacy migration helpers * fix(memory): persist legacy source acknowledgements * fix(state): remove stale migration imports * fix(memory): recognize numbered migration archives * fix(matrix): downgrade archived migration residue * fix(memory): satisfy migration lint --------- Co-authored-by: Eva <[email protected]>
1 parent a0cab8c commit 4da0eb1

17 files changed

Lines changed: 882 additions & 307 deletions

‎extensions/codex/doctor-contract-api.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -703,7 +703,8 @@ describe("codex doctor contract", () => {
703703

704704
const result = await fixture.migration.migrateLegacyState({ ...fixture.params, context });
705705

706-
expect(result.warnings).toEqual([
706+
expect(result.warnings).toEqual([]);
707+
expect(result.notices).toEqual([
707708
expect.stringContaining("session owner changed before Codex ownership could be recorded"),
708709
]);
709710
await expect(fs.access(fixture.sidecarPath)).resolves.toBeUndefined();
@@ -761,7 +762,8 @@ describe("codex doctor contract", () => {
761762

762763
const result = await fixture.migration.migrateLegacyState({ ...fixture.params, context });
763764

764-
expect(result.warnings).toEqual([
765+
expect(result.warnings).toEqual([]);
766+
expect(result.notices).toEqual([
765767
expect.stringContaining("session owner changed before Codex ownership could be recorded"),
766768
]);
767769
await expect(fs.access(fixture.sidecarPath)).resolves.toBeUndefined();
@@ -979,7 +981,8 @@ describe("codex doctor contract", () => {
979981
const result = await fixture.migration.migrateLegacyState(fixture.params);
980982

981983
expect(result.changes).toEqual([]);
982-
expect(result.warnings).toEqual([expect.stringContaining("owned by agent harness pi")]);
984+
expect(result.warnings).toEqual([]);
985+
expect(result.notices).toEqual([expect.stringContaining("owned by agent harness pi")]);
983986
await expect(fs.access(fixture.sidecarPath)).resolves.toBeUndefined();
984987
await expect(openBindingStore(fixture.env).entries()).resolves.toEqual([]);
985988

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import fs from "node:fs/promises";
2+
3+
async function pathExists(filePath: string): Promise<boolean> {
4+
try {
5+
await fs.access(filePath);
6+
return true;
7+
} catch {
8+
return false;
9+
}
10+
}
11+
12+
async function firstFreeArchivePath(sourcePath: string): Promise<string> {
13+
for (let index = 2; ; index++) {
14+
const candidate = `${sourcePath}.migrated.${index}`;
15+
if (!(await pathExists(candidate))) {
16+
return candidate;
17+
}
18+
}
19+
}
20+
21+
export async function archiveBindingSidecar(sourcePath: string): Promise<void> {
22+
const archivePath = `${sourcePath}.migrated`;
23+
if (!(await pathExists(archivePath))) {
24+
await fs.rename(sourcePath, archivePath);
25+
return;
26+
}
27+
const [sourceBytes, archiveBytes] = await Promise.all([
28+
fs.readFile(sourcePath),
29+
fs.readFile(archivePath),
30+
]);
31+
if (sourceBytes.equals(archiveBytes)) {
32+
await fs.rm(sourcePath, { force: true });
33+
return;
34+
}
35+
await fs.rename(sourcePath, await firstFreeArchivePath(sourcePath));
36+
}

‎extensions/codex/src/migration/session-binding-sidecars.ts‎

Lines changed: 24 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
CODEX_APP_SERVER_BINDING_MAX_ENTRIES,
1515
CODEX_APP_SERVER_BINDING_NAMESPACE,
1616
} from "../app-server/session-binding-meta.js";
17+
import { archiveBindingSidecar } from "./session-binding-sidecar-archive.js";
1718

1819
const LEGACY_BINDING_SUFFIX = ".codex-app-server.json";
1920
const CODEX_AGENT_HARNESS_ID = "codex";
@@ -66,6 +67,7 @@ type BindingOwnerCollection = {
6667
type SourceMigrationResult = {
6768
archived: boolean;
6869
importedKeys: number;
70+
notice?: string;
6971
warning?: string;
7072
};
7173

@@ -429,6 +431,11 @@ async function migrateSource(
429431
importedKeys,
430432
warning: `Left Codex binding sidecar in place because ${reason}: ${source.sidecarPath}`,
431433
});
434+
const retainNotice = (reason: string): SourceMigrationResult => ({
435+
archived: false,
436+
importedKeys,
437+
notice: `Left Codex binding sidecar in place because ${reason}: ${source.sidecarPath}`,
438+
});
432439
const owner = candidates.length === 1 ? candidates[0] : undefined;
433440
try {
434441
return await withFileLock(source.sidecarPath, LEGACY_BINDING_LOCK_OPTIONS, async () => {
@@ -467,7 +474,10 @@ async function migrateSource(
467474
return retain(`${candidates.length} matching session owners make ownership ambiguous`);
468475
}
469476
if (owner?.agentHarnessId && owner.agentHarnessId !== CODEX_AGENT_HARNESS_ID) {
470-
return retain(`its session is owned by agent harness ${owner.agentHarnessId}`);
477+
// Explicit foreign ownership is a complete decision, not an unsafe
478+
// migration conflict. Preserve the sidecar for that harness without
479+
// blocking every later Gateway startup.
480+
return retainNotice(`its session is owned by agent harness ${owner.agentHarnessId}`);
471481
}
472482
const sourceSessionFile =
473483
typeof raw.sessionFile === "string" && raw.sessionFile.trim()
@@ -611,7 +621,10 @@ async function migrateSource(
611621
return retain(`${ownershipWarning}; its stale session binding could not be retired`);
612622
}
613623
}
614-
return retain(ownershipWarning);
624+
// Imported active session state is retired before reaching here.
625+
// The remaining sidecar may belong to the new owner, so preserve it
626+
// as a note; failed retirement and revalidation stay warnings above.
627+
return retainNotice(ownershipWarning);
615628
}
616629
for (const entry of entries) {
617630
if (!hasExpected(await store.lookup(entry.key), entry.value)) {
@@ -808,32 +821,6 @@ async function pathExists(filePath: string): Promise<boolean> {
808821
}
809822
}
810823

811-
async function firstFreeArchivePath(sourcePath: string): Promise<string> {
812-
for (let index = 2; ; index++) {
813-
const candidate = `${sourcePath}.migrated.${index}`;
814-
if (!(await pathExists(candidate))) {
815-
return candidate;
816-
}
817-
}
818-
}
819-
820-
async function archiveBindingSidecar(sourcePath: string): Promise<void> {
821-
const archivePath = `${sourcePath}.migrated`;
822-
if (await pathExists(archivePath)) {
823-
const [sourceBytes, archiveBytes] = await Promise.all([
824-
fs.readFile(sourcePath),
825-
fs.readFile(archivePath),
826-
]);
827-
if (sourceBytes.equals(archiveBytes)) {
828-
await fs.rm(sourcePath, { force: true });
829-
return;
830-
}
831-
await fs.rename(sourcePath, await firstFreeArchivePath(sourcePath));
832-
return;
833-
}
834-
await fs.rename(sourcePath, archivePath);
835-
}
836-
837824
export const stateMigrations: PluginDoctorStateMigration[] = [
838825
{
839826
id: "codex-app-server-sidecars-to-plugin-state",
@@ -851,6 +838,7 @@ export const stateMigrations: PluginDoctorStateMigration[] = [
851838
async migrateLegacyState(params) {
852839
const changes: string[] = [];
853840
const warnings: string[] = [];
841+
const notices: string[] = [];
854842
const { sources, surfaces } = await collectLegacyBindingSources(params);
855843
if (sources.length === 0) {
856844
return { changes, warnings };
@@ -876,6 +864,9 @@ export const stateMigrations: PluginDoctorStateMigration[] = [
876864
if (result.warning) {
877865
warnings.push(result.warning);
878866
}
867+
if (result.notice) {
868+
notices.push(result.notice);
869+
}
879870
if (result.archived) {
880871
migrated++;
881872
} else {
@@ -892,7 +883,11 @@ export const stateMigrations: PluginDoctorStateMigration[] = [
892883
`Migrated ${partialImports} safe Codex app-server binding row(s) to plugin state; retained legacy sidecars needing review`,
893884
);
894885
}
895-
return { changes, warnings };
886+
return {
887+
changes,
888+
warnings,
889+
...(notices.length > 0 ? { notices } : {}),
890+
};
896891
},
897892
},
898893
];

‎extensions/matrix/doctor-contract-api.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,51 @@ describe("matrix doctor contract state migrations", () => {
117117
expect(store.hasSavedSync()).toBe(true);
118118
expect(store.hasSavedSyncFromCleanShutdown()).toBe(true);
119119
await expect(store.getSavedSyncToken()).resolves.toBe("legacy-token");
120-
expect(fs.existsSync(path.join(storageRootDir, "bot-storage.json"))).toBe(false);
120+
const sourcePath = path.join(storageRootDir, "bot-storage.json");
121+
const archivePath = `${sourcePath}.migrated`;
122+
expect(fs.existsSync(sourcePath)).toBe(false);
123+
124+
fs.copyFileSync(archivePath, sourcePath);
125+
await expect(migration.migrateLegacyState(createMigrationParams(stateDir))).resolves.toEqual({
126+
changes: [`Removed already-archived Matrix sync cache legacy source ${sourcePath}`],
127+
warnings: [],
128+
notices: [
129+
`Kept existing Matrix sync cache in SQLite and archived the legacy source for ${storageRootDir}`,
130+
],
131+
});
132+
133+
fs.writeFileSync(
134+
sourcePath,
135+
JSON.stringify({
136+
version: 1,
137+
savedSync: {
138+
nextBatch: "newer-legacy-token",
139+
accountData: [],
140+
roomsData: { join: {}, invite: {}, leave: {}, knock: {} },
141+
},
142+
cleanShutdown: true,
143+
}),
144+
);
145+
await expect(migration.migrateLegacyState(createMigrationParams(stateDir))).resolves.toEqual({
146+
changes: [`Archived Matrix sync cache legacy source -> ${sourcePath}.migrated.2`],
147+
warnings: [],
148+
notices: [
149+
`Kept existing Matrix sync cache in SQLite and archived the legacy source for ${storageRootDir}`,
150+
],
151+
});
152+
await expect(migration.migrateLegacyState(createMigrationParams(stateDir))).resolves.toEqual({
153+
changes: [],
154+
warnings: [],
155+
});
156+
157+
fs.writeFileSync(sourcePath, `${fs.readFileSync(`${sourcePath}.migrated.2`, "utf8")} `, "utf8");
158+
fs.mkdirSync(`${sourcePath}.migrated.3`);
159+
const failedArchive = await migration.migrateLegacyState(createMigrationParams(stateDir));
160+
expect(failedArchive.changes).toEqual([]);
161+
expect(failedArchive.warnings).toEqual([
162+
expect.stringContaining("Failed archiving Matrix sync cache legacy source"),
163+
]);
164+
expect(failedArchive.notices).toBeUndefined();
121165
});
122166

123167
it("migrates Matrix storage metadata JSON to SQLite plugin state", async () => {

0 commit comments

Comments
 (0)