Skip to content

Commit b8fd757

Browse files
committed
fix(codex): verify history worker schedule
1 parent 2468502 commit b8fd757

4 files changed

Lines changed: 80 additions & 6 deletions

File tree

‎src/codex/history-job.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import type {
2525
} from "./history-worker";
2626
import { historyBackupPathFor } from "./history-provider";
2727
import { getCodexHome } from "./paths";
28+
import { readCodexTransitionStateAtHome } from "./transition-state";
2829

2930
/** Where Codex keeps its resume history, and the manifest that shadows it. */
3031
const STATE_DB_FILE = "state_5.sqlite";
@@ -154,7 +155,10 @@ export async function runCodexHistoryJob(
154155
options: { readonly timeoutMs?: number } = {},
155156
): Promise<CodexHistoryJobOutcome> {
156157
const requestId = randomUUID();
157-
const jobId = randomUUID();
158+
const durable = readCodexTransitionStateAtHome(request.canonicalCodexHome);
159+
const jobId = durable.kind === "ready" && durable.state.currentTxId
160+
? durable.state.currentTxId
161+
: randomUUID();
158162
const timeoutMs = options.timeoutMs ?? WORKER_TIMEOUT_MS;
159163

160164
// `skip` writes nothing, so spawning a thread to decide that would be pure

‎src/codex/history-worker.ts‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import {
2929
writeLegacyOpenaiHistoryRecovery,
3030
type HistoryWriteTarget,
3131
} from "./internal/history-writer";
32+
import { readCodexTransitionStateAtHome } from "./transition-state";
3233

3334
/**
3435
* The durable operation, mirrored into the request for diagnostics only.
@@ -106,23 +107,38 @@ export function isHistoryWorkerRunMessage(data: unknown): data is HistoryWorkerR
106107
export function runHistoryUnitUnderLock(
107108
message: HistoryWorkerRunMessage,
108109
): HistoryWorkerResult {
109-
const { requestId, jobId, operation } = message;
110+
const { requestId, jobId } = message;
110111
const target: HistoryWriteTarget = {
111112
canonicalStateDbPath: message.canonicalStateDbPath,
112113
canonicalBackupPath: message.canonicalBackupPath,
113114
};
114115

115-
if (operation === "skip") {
116+
if (message.operation === "skip") {
116117
return { type: "done", requestId, jobId, outcome: "skipped", rows: 0, files: 0 };
117118
}
118119

119120
const acquired = withHistoryWriteSerialization(
120121
message.canonicalCodexHome,
121122
message.canonicalStateDbPath,
122123
permit => {
123-
if (operation === "recover-legacy-openai") {
124+
// Legacy recovery is an explicit maintenance command, not a scheduled
125+
// convergence transition. It remains distinct from generic restore.
126+
if (message.operation === "recover-legacy-openai") {
124127
return writeLegacyOpenaiHistoryRecovery(permit, target);
125128
}
129+
const durable = readCodexTransitionStateAtHome(message.canonicalCodexHome);
130+
if (durable.kind !== "ready") return { refused: "history_schedule_unavailable" } as const;
131+
const { state } = durable;
132+
if (state.currentTxId !== jobId || state.history.txId !== jobId || !state.historySchedule) {
133+
return { refused: "history_job_overtaken" } as const;
134+
}
135+
const operation = message.operation;
136+
const expectedDirection = operation === "apply-opencodex" || operation === "migrate-openai"
137+
? "apply"
138+
: operation === "restore-openai" ? "remove" : null;
139+
if (expectedDirection === null || state.historySchedule.direction !== expectedDirection) {
140+
return { refused: "history_operation_mismatch" } as const;
141+
}
126142
// apply-opencodex routes history to opencodex; migrate/restore return it to
127143
// native. The provider is derived from the operation, never from a caller.
128144
const provider = operation === "apply-opencodex" ? "opencodex" : "openai";
@@ -134,6 +150,9 @@ export function runHistoryUnitUnderLock(
134150
return { type: "blocked", requestId, jobId, reason: acquired.reason };
135151
}
136152
const result = acquired.value;
153+
if ("refused" in result) {
154+
return { type: "error", requestId, jobId, message: result.refused };
155+
}
137156
if (result.failed === true) {
138157
return { type: "error", requestId, jobId, message: "history_transition_failed" };
139158
}

‎src/codex/transition-state.ts‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -526,8 +526,7 @@ export const readCodexTransitionState: ReadCodexTransitionState = () => {
526526
}
527527
};
528528

529-
function readCommittedState(): TransitionStateRead {
530-
const path = currentCoordinatorDatabasePath();
529+
function readCommittedState(path = currentCoordinatorDatabasePath()): TransitionStateRead {
531530
let database: Database | undefined;
532531
try {
533532
database = new Database(path, { readonly: true });
@@ -540,6 +539,19 @@ function readCommittedState(): TransitionStateRead {
540539
}
541540
}
542541

542+
/** Read the durable coordinator for an already-canonical Codex home. */
543+
export function readCodexTransitionStateAtHome(canonicalCodexHome: string): TransitionStateRead {
544+
try {
545+
const path = resolveCodexCoordinatorDatabasePath(
546+
resolveEffectiveUserIdentity(),
547+
realpathSync.native(canonicalCodexHome),
548+
);
549+
return readCommittedState(path);
550+
} catch (error) {
551+
return mapReadError(error);
552+
}
553+
}
554+
543555
export const beginCodexTransition: BeginCodexTransition = (expected, next) => {
544556
let transaction: CodexCoordinatorTransactionController | undefined;
545557
try {

‎tests/codex-history-worker.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@ import {
1010
runHistoryUnitUnderLock,
1111
type HistoryWorkerRunMessage,
1212
} from "../src/codex/history-worker";
13+
import { openCodexCoordinatorTransaction } from "../src/codex/transition-state";
14+
import {
15+
resolveCodexCoordinatorDatabasePath,
16+
resolveEffectiveUserIdentity,
17+
} from "../src/codex/user-identity";
1318

1419
const repoRoot = resolve(import.meta.dir, "..");
1520
const sandboxes: string[] = [];
@@ -142,6 +147,40 @@ test("the unit runs the real transition under H", () => {
142147
expect(row?.model_provider).toBe("openai");
143148
});
144149

150+
test("a stale message cannot choose history direction", () => {
151+
const fixture = makeFixture("ocx-history-worker-stale-");
152+
const coordinatorPath = resolveCodexCoordinatorDatabasePath(
153+
resolveEffectiveUserIdentity(),
154+
fixture.codexHome,
155+
);
156+
const coordinator = openCodexCoordinatorTransaction(coordinatorPath);
157+
const begun = coordinator.capability.beginTransition(
158+
{ nativeGeneration: 0, currentTxId: null },
159+
{
160+
txId: "current-restore-job",
161+
direction: "remove",
162+
authoritySnapshotId: "snapshot-1",
163+
nextRetryAt: null,
164+
},
165+
);
166+
expect(begun.kind).toBe("updated");
167+
coordinator.commit();
168+
coordinator.close();
169+
170+
const result = runHistoryUnitUnderLock(runMessage(fixture, {
171+
jobId: "stale-apply-job",
172+
operation: "apply-opencodex",
173+
}));
174+
175+
expect(result).toMatchObject({ type: "error", message: "history_job_overtaken" });
176+
const db = new Database(fixture.stateDb, { readonly: true });
177+
const row = db.query<{ model_provider: string }, []>(
178+
"SELECT model_provider FROM threads WHERE id = 'thread-1'",
179+
).get();
180+
db.close();
181+
expect(row?.model_provider).toBe("opencodex");
182+
});
183+
145184
/**
146185
* The reason the unit lives in a Worker at all: while another process holds H,
147186
* this one reports a typed block instead of stalling its own thread.

0 commit comments

Comments
 (0)