Skip to content

Commit e154d64

Browse files
committed
fix(history): preserve provider config before paginated transition refusal
1 parent d30c7ec commit e154d64

12 files changed

Lines changed: 120 additions & 1 deletion

‎src/codex/history-provider.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,42 @@ function assertLegacyHistoryWritable(path: string): void {
245245
}
246246
}
247247

248+
/** Read-only preflight before the injector changes provider definitions.
249+
* Native paginated history cannot participate in the legacy relabel protocol.
250+
* Returning a refusal preserves the existing config as well as the rollout.
251+
*/
252+
export function preflightCodexHistoryInjection(
253+
providerTableMode: boolean,
254+
resumeHistory: boolean,
255+
stateDbPath = resolveCodexStateDbPath(),
256+
): string | null {
257+
if (!existsSync(stateDbPath)) return null;
258+
let db: Database | undefined;
259+
try {
260+
db = new Database(stateDbPath, { readonly: true });
261+
const columns = db.query<{ name: string }, []>("PRAGMA table_info(threads)").all();
262+
const paginatedColumn = columns.some(column => column.name === "history_mode");
263+
const rows = db.query<{ rollout_path: string; history_mode: string | null }, []>(`
264+
SELECT rollout_path, ${paginatedColumn ? "history_mode" : "NULL AS history_mode"}
265+
FROM threads
266+
WHERE ${providerTableMode
267+
? resumeHistory ? "model_provider IN ('openai', 'opencodex')" : "0"
268+
: "model_provider = 'opencodex'"}
269+
`).all();
270+
for (const row of rows) {
271+
if (row.history_mode === "paginated") return "history_paginated_requires_native_writer";
272+
assertLegacyHistoryWritable(row.rollout_path);
273+
}
274+
return null;
275+
} catch (error) {
276+
return error instanceof CodexHistoryIntegrityError
277+
? error.message
278+
: "history_injection_preflight_unavailable";
279+
} finally {
280+
db?.close();
281+
}
282+
}
283+
248284
function integrityFailureResult(error: CodexHistoryIntegrityError): CodexHistorySyncResult {
249285
return {
250286
rows: error.progress.rows,

‎src/codex/inject.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ import {
4646
} from "./journal";
4747
import { withCatalogWriteSerialization } from "./catalog-write-serialization";
4848
import { restoreCodexCatalogWithPermit } from "./catalog/sync";
49-
import { syncCodexHistoryProvider, type CodexHistoryFailureReason } from "./history-provider";
49+
import { preflightCodexHistoryInjection, syncCodexHistoryProvider, type CodexHistoryFailureReason } from "./history-provider";
5050
import {
5151
describeHistoryJobFailure,
5252
deriveCodexHistoryOperation,
@@ -75,6 +75,7 @@ import {
7575
parseTomlString,
7676
readRootTomlString,
7777
resolveCodexConfigPath,
78+
resolveCodexStateDbPath,
7879
tomlString,
7980
} from "./paths";
8081
import { resolveEffectiveProjectModelProvider } from "./project-config-warnings";
@@ -929,6 +930,10 @@ export async function injectCodexConfig(
929930
}
930931

931932
const rawContent = readFileSync(CODEX_CONFIG_PATH, "utf-8");
933+
const preflightTableMode = usesProviderTable(routingTarget);
934+
const compactionOnly = routingTarget.clientCompaction === true
935+
&& routingTarget.desktopAuthless !== true
936+
&& routingTarget.requiresAdmissionToken !== true;
932937
const activeProvider = externalCodexModelProvider(rawContent);
933938
if (activeProvider) {
934939
// A launcher may have journaled before the provider manager took ownership. Never let shutdown
@@ -1138,6 +1143,29 @@ export async function injectCodexConfig(
11381143
);
11391144
content = applyEol(content, eol);
11401145

1146+
// Resolve storage from the normalized candidate. Owned duplicate catalog keys
1147+
// are repairable above and must not make this read-only preflight throw.
1148+
const historyPreflight = (): string | null => {
1149+
try {
1150+
return preflightCodexHistoryInjection(
1151+
preflightTableMode,
1152+
config?.syncResumeHistory !== false && !compactionOnly,
1153+
resolveCodexStateDbPath({ readConfig: () => content }),
1154+
);
1155+
} catch {
1156+
return "history_injection_preflight_unavailable";
1157+
}
1158+
};
1159+
const historyPreflightError = historyPreflight();
1160+
if (historyPreflightError) {
1161+
return {
1162+
success: false,
1163+
message: `Codex config injection refused: ${historyPreflightError}. `
1164+
+ "Existing provider definitions and conversation files were preserved. "
1165+
+ "Paginated history requires native-writer coordination; do not run legacy recovery or retry this transition blindly.",
1166+
};
1167+
}
1168+
11411169
/*
11421170
* The witness, built from the FINAL bytes. Everything it hashes is either the
11431171
* output about to be written or evidence that can be re-read under the lock;
@@ -1228,6 +1256,8 @@ export async function injectCodexConfig(
12281256
}
12291257

12301258
const applyNativeArtifacts = (): void => {
1259+
const historyError = historyPreflight();
1260+
if (historyError) throw new Error(historyError);
12311261
writeJournal({
12321262
currentStateIsNative: journalBaselineIsNative(),
12331263
configContent: baselineContent,

‎structure/catalog.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -265,3 +265,5 @@ provider wire mapping; unpinned native requests retain their existing pass-throu
265265
## Paginated history writer boundary
266266

267267
Catalog convergence can include a provider-history transition. Paginated history refusal is an explicit incomplete transition, not successful migration; see [Codex Home](codex-home.md#paginated-history-writer-boundary).
268+
269+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/codex-home.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,3 +227,5 @@ a deliberate user choice:
227227
## Paginated history writer boundary
228228

229229
`src/codex/history-provider.ts` rejects provider-history changes with `history_paginated_requires_native_writer` when a target begins with an ordinal-bearing record or declares `history_mode=paginated`. Apply, manifest-backed restore, and explicit legacy recovery preflight all selected targets before changing database rows or manifests. The append boundary checks again. Codex owns ordinal allocation and the live projection cursor; reading the last ordinal and appending N+1 is not safe concurrent coordination. Legacy unnumbered rollouts retain their existing behavior. This guard prevents the observed stable-format corruption; it does not implement native-writer integration or guarantee a concurrent legacy-to-paginated conversion is excluded.
230+
231+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/config.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,5 @@ Client connection metadata stores a stable `apiKeyId` and a non-secret rotation
196196
## Paginated history writer boundary
197197

198198
Authless routing cannot relabel paginated history through the legacy file writer. A refused history transition must be reported; provider-definition retention during that refusal remains an integration concern. See [Codex Home](codex-home.md#paginated-history-writer-boundary).
199+
200+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/gui-and-management-api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,3 +508,5 @@ survives availability drift, while complete/native custom orders await explicit
508508
## Paginated history writer boundary
509509

510510
Settings convergence must surface paginated-history refusal rather than claim history was migrated. See [Codex Home](codex-home.md#paginated-history-writer-boundary).
511+
512+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/ops/docs-and-release.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,3 +304,5 @@ The Remote Hub guide and affected CLI, server-config, management-API, and dashbo
304304
## Paginated history writer boundary
305305

306306
History-provider regression coverage includes numbered rollout apply/restore refusal without changing source bytes or provenance. See [Codex Home](../codex-home.md#paginated-history-writer-boundary).
307+
308+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/providers/openai-tiers.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,3 +372,5 @@ successful main usage refresh clears the runtime mark.
372372
## Paginated history writer boundary
373373

374374
Provider account selection does not authorize relabeling paginated Codex records; the [history writer boundary](../codex-home.md#paginated-history-writer-boundary) applies independently of account mode.
375+
376+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/runtime.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,5 @@ not an authentication or entitlement decision.
189189
## Paginated history writer boundary
190190

191191
Provider-history transitions refuse paginated rollout writes before changing history state; see [Codex Home](codex-home.md#paginated-history-writer-boundary).
192+
193+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

‎structure/subagents.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,3 +199,5 @@ Native Codex advertisements still follow display priority; private guidance rank
199199
## Paginated history writer boundary
200200

201201
History metadata for parent or child threads follows the same [paginated writer boundary](codex-home.md#paginated-history-writer-boundary); a child source does not authorize external ordinal allocation.
202+
203+
Injection now preflights affected paginated threads before writing config/profile/journal, using the normalized config candidate to resolve SQLite storage. It rechecks immediately before artifact writes; this preserves provider definitions on a stable-format refusal but does not replace native-writer coordination for concurrent format changes.

0 commit comments

Comments
 (0)