Skip to content

Commit 92a6c74

Browse files
committed
fix(codex): converge retained raw binding rows
1 parent ff1c358 commit 92a6c74

3 files changed

Lines changed: 219 additions & 6 deletions

File tree

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

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,156 @@ describe("codex doctor contract", () => {
353353
await fs.rm(fixture.stateDir, { recursive: true, force: true });
354354
});
355355

356+
it("normalizes a partial raw conversation import before copying the session row", async () => {
357+
const threadId = "thread-partial-import";
358+
const sessionId = "partial-import";
359+
const sessionKey = "agent:main:partial-import";
360+
const emptyConversation: StoredCodexAppServerBinding = {
361+
version: 1,
362+
state: "active",
363+
binding: {
364+
threadId,
365+
cwd: "",
366+
dynamicToolsFingerprint: "",
367+
},
368+
};
369+
const rawFingerprint = "x".repeat(
370+
65_535 - Buffer.byteLength(JSON.stringify(emptyConversation)),
371+
);
372+
const rawConversation: StoredCodexAppServerBinding = {
373+
...emptyConversation,
374+
binding: {
375+
...emptyConversation.binding,
376+
dynamicToolsFingerprint: rawFingerprint,
377+
},
378+
};
379+
const rawSession = { ...rawConversation, sessionId };
380+
expect(Buffer.byteLength(JSON.stringify(rawConversation))).toBe(65_535);
381+
expect(Buffer.byteLength(JSON.stringify(rawSession))).toBeGreaterThan(65_536);
382+
383+
const fixture = await createBindingMigrationFixture({
384+
name: sessionId,
385+
sessionIndex: {
386+
[sessionKey]: {
387+
sessionId,
388+
sessionFile: `${sessionId}.jsonl`,
389+
},
390+
},
391+
threadId,
392+
binding: { dynamicToolsFingerprint: rawFingerprint },
393+
});
394+
const conversationKey = bindingStoreKey({
395+
kind: "conversation",
396+
bindingId: legacyCodexConversationBindingId(fixture.transcriptPath),
397+
});
398+
const sessionBindingKey = bindingStoreKey({
399+
kind: "session",
400+
agentId: "main",
401+
sessionId,
402+
sessionKey,
403+
});
404+
const store = openBindingStore(fixture.env);
405+
await store.register(conversationKey, rawConversation);
406+
407+
await expect(fixture.migration.migrateLegacyState(fixture.params)).resolves.toEqual({
408+
changes: [
409+
"Migrated 1 Codex app-server binding sidecar(s) to plugin state and archived the legacy sources",
410+
],
411+
warnings: [],
412+
});
413+
414+
const expectedFingerprint = hashCodexAppServerBindingFingerprint(rawFingerprint);
415+
await expect(store.lookup(conversationKey)).resolves.toMatchObject({
416+
state: "active",
417+
binding: { dynamicToolsFingerprint: expectedFingerprint },
418+
});
419+
await expect(store.lookup(sessionBindingKey)).resolves.toMatchObject({
420+
state: "active",
421+
sessionId,
422+
binding: { dynamicToolsFingerprint: expectedFingerprint },
423+
});
424+
await expect(fs.access(fixture.sidecarPath)).rejects.toThrow();
425+
await expect(fs.access(`${fixture.sidecarPath}.migrated`)).resolves.toBeUndefined();
426+
await expect(fixture.migration.migrateLegacyState(fixture.params)).resolves.toEqual({
427+
changes: [],
428+
warnings: [],
429+
});
430+
431+
await fs.rm(fixture.stateDir, { recursive: true, force: true });
432+
});
433+
434+
it("normalizes retained raw conversation and session rows before comparison", async () => {
435+
const threadId = "thread-retained-import";
436+
const sessionId = "retained-import";
437+
const sessionKey = "agent:main:retained-import";
438+
const rawFingerprint = "x".repeat(60_000);
439+
const rawConversation: StoredCodexAppServerBinding = {
440+
version: 1,
441+
state: "active",
442+
binding: {
443+
threadId,
444+
cwd: "",
445+
dynamicToolsFingerprint: rawFingerprint,
446+
},
447+
};
448+
const rawSession: StoredCodexAppServerBinding = {
449+
...rawConversation,
450+
sessionId,
451+
};
452+
expect(Buffer.byteLength(JSON.stringify(rawSession))).toBeLessThan(65_536);
453+
454+
const fixture = await createBindingMigrationFixture({
455+
name: sessionId,
456+
sessionIndex: {
457+
[sessionKey]: {
458+
sessionId,
459+
sessionFile: `${sessionId}.jsonl`,
460+
},
461+
},
462+
threadId,
463+
binding: { dynamicToolsFingerprint: rawFingerprint },
464+
});
465+
const conversationKey = bindingStoreKey({
466+
kind: "conversation",
467+
bindingId: legacyCodexConversationBindingId(fixture.transcriptPath),
468+
});
469+
const sessionBindingKey = bindingStoreKey({
470+
kind: "session",
471+
agentId: "main",
472+
sessionId,
473+
sessionKey,
474+
});
475+
const store = openBindingStore(fixture.env);
476+
await store.register(conversationKey, rawConversation);
477+
await store.register(sessionBindingKey, rawSession);
478+
479+
await expect(fixture.migration.migrateLegacyState(fixture.params)).resolves.toEqual({
480+
changes: [
481+
"Migrated 1 Codex app-server binding sidecar(s) to plugin state and archived the legacy sources",
482+
],
483+
warnings: [],
484+
});
485+
486+
const expectedFingerprint = hashCodexAppServerBindingFingerprint(rawFingerprint);
487+
await expect(store.lookup(conversationKey)).resolves.toMatchObject({
488+
state: "active",
489+
binding: { dynamicToolsFingerprint: expectedFingerprint },
490+
});
491+
await expect(store.lookup(sessionBindingKey)).resolves.toMatchObject({
492+
state: "active",
493+
sessionId,
494+
binding: { dynamicToolsFingerprint: expectedFingerprint },
495+
});
496+
await expect(fs.access(fixture.sidecarPath)).rejects.toThrow();
497+
await expect(fs.access(`${fixture.sidecarPath}.migrated`)).resolves.toBeUndefined();
498+
await expect(fixture.migration.migrateLegacyState(fixture.params)).resolves.toEqual({
499+
changes: [],
500+
warnings: [],
501+
});
502+
503+
await fs.rm(fixture.stateDir, { recursive: true, force: true });
504+
});
505+
356506
it("matches an owner through the contained fallback for a stale session file locator", async () => {
357507
const sessionKey = "agent:main:stale-locator";
358508
const fixture = await createBindingMigrationFixture({

‎extensions/codex/src/app-server/session-binding.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,6 +418,21 @@ function normalizeLegacyBindingFingerprints(
418418
return normalized;
419419
}
420420

421+
export function normalizeStoredCodexAppServerBindingFingerprints(
422+
value: unknown,
423+
): StoredCodexAppServerBinding | undefined {
424+
const stored = readStoredCodexAppServerBinding(value);
425+
if (!stored || stored.state !== "active") {
426+
return stored;
427+
}
428+
const binding = normalizeLegacyBindingFingerprints(
429+
stored.binding as unknown as Record<string, unknown>,
430+
);
431+
return binding === stored.binding
432+
? stored
433+
: readStoredCodexAppServerBinding({ ...stored, binding });
434+
}
435+
421436
/** Encodes a migrated sidecar binding as one canonical plugin-state row. */
422437
export function createStoredCodexAppServerBinding(
423438
value: unknown,

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

Lines changed: 54 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -415,7 +415,12 @@ async function migrateSource(
415415
]);
416416
const raw = JSON.parse(contents) as Record<string, unknown>;
417417
const [
418-
{ bindingStoreKey, createStoredCodexAppServerBinding, readStoredCodexAppServerBinding },
418+
{
419+
bindingStoreKey,
420+
createStoredCodexAppServerBinding,
421+
normalizeStoredCodexAppServerBindingFingerprints,
422+
readStoredCodexAppServerBinding,
423+
},
419424
{ legacyCodexConversationBindingId },
420425
] = await Promise.all([
421426
import("../app-server/session-binding.js"),
@@ -458,17 +463,53 @@ async function migrateSource(
458463
bindingId: legacyCodexConversationBindingId(sessionFile),
459464
}),
460465
);
466+
const normalizeStoredRow = async (
467+
key: string,
468+
current: MigratedBindingRow,
469+
): Promise<{ value?: MigratedBindingRow; warning?: string }> => {
470+
const parsed = readStoredCodexAppServerBinding(current);
471+
if (!parsed) {
472+
return { warning: `canonical plugin state is invalid at ${key}` };
473+
}
474+
const normalized = normalizeStoredCodexAppServerBindingFingerprints(parsed);
475+
if (!normalized) {
476+
return { warning: `canonical plugin state is invalid at ${key}` };
477+
}
478+
if (isDeepStrictEqual(parsed, normalized)) {
479+
return { value: parsed };
480+
}
481+
if (parsed.lease && parsed.lease.expiresAt > Date.now()) {
482+
return { warning: `canonical plugin state is leased at ${key}` };
483+
}
484+
const update = store.update;
485+
if (!update) {
486+
return { warning: `canonical plugin state could not be normalized at ${key}` };
487+
}
488+
await update(key, (candidate) => {
489+
const candidateParsed = readStoredCodexAppServerBinding(candidate);
490+
if (!candidateParsed || !isDeepStrictEqual(candidateParsed, parsed)) {
491+
return undefined;
492+
}
493+
return normalized;
494+
});
495+
const persisted = readStoredCodexAppServerBinding(await store.lookup(key));
496+
if (!persisted || !isDeepStrictEqual(persisted, normalized)) {
497+
return { warning: `canonical plugin state changed at ${key}` };
498+
}
499+
importedKeys++;
500+
return { value: normalized };
501+
};
461502
let currentConversation: MigratedBindingRow | undefined;
462503
for (const key of conversationKeys) {
463504
const current = await store.lookup(key);
464505
if (current === undefined) {
465506
continue;
466507
}
467-
const parsed = readStoredCodexAppServerBinding(current);
468-
if (!parsed) {
469-
return retain(`canonical plugin state is invalid at ${key}`);
508+
const result = await normalizeStoredRow(key, current);
509+
if (result.warning || !result.value) {
510+
return retain(result.warning ?? `canonical plugin state is invalid at ${key}`);
470511
}
471-
currentConversation ??= parsed;
512+
currentConversation ??= result.value;
472513
}
473514
const stored = currentConversation ?? baseStored;
474515
const sessionKey = owner
@@ -500,7 +541,14 @@ async function migrateSource(
500541
};
501542
for (const entry of entries) {
502543
const current = await store.lookup(entry.key);
503-
if (current !== undefined && !hasExpected(current, entry.value)) {
544+
if (current === undefined) {
545+
continue;
546+
}
547+
const result = await normalizeStoredRow(entry.key, current);
548+
if (result.warning || !result.value) {
549+
return retain(result.warning ?? `canonical plugin state is invalid at ${entry.key}`);
550+
}
551+
if (!hasExpected(result.value, entry.value)) {
504552
return retain(`canonical plugin state changed at ${entry.key}`);
505553
}
506554
}

0 commit comments

Comments
 (0)