Skip to content

fix(codex): 核验初始化后的原生引擎身份 - #2518

Merged
deepcoldy merged 2 commits into
deepcoldy:masterfrom
uestcwangci:fix/codex-native-engine-root-20261029
Nov 2, 2026
Merged

deepcoldy merged 2 commits into
deepcoldy:masterfrom
uestcwangci:fix/codex-native-engine-root-20261029

Conversation

@uestcwangci

@uestcwangci uestcwangci commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

npm 形态的 Codex 由常驻 Node launcher 拉起原生引擎。旧 runner 把 launcher 当作 app-server 根,后续发布真正引擎时会被误判为换身份,出现 current_execution_unverified。

等待 initialize 与进程捕获完成后才发布身份,从唯一核验的 processIdentity 选择 enginePid,并重读出生令牌。初始化中的替换客户端不发布 launcher。初始化窗口测试使用可配置延迟,在替换 launcher 实际启动后断开控制端点强制 re-auth,检查首条签名状态无 appServerProcess,窗口内无真实 launcher PID;保留最新主干空闲恢复与 worker 重连用例。

已普通 merge 最新 master 58ea44e,保留分支历史,无 rebase/force-push。当前 head ccd0a79。只涉及 Linux Codex App 引擎出证与相应集成测试,其他 CLI/后端授权范围不变,无环境专用策略。

验证:

  • 完整 bun run build 通过(含类型、Dashboard、dist 与嵌入资产审计)。
  • Node/Vitest 原生 runner 与五组身份/证明/hygiene测试共6文件241项通过;Bun1.4.3隔离HOME/TMP、180000ms超时,完整runner114项通过。
  • 删除 initialized 门、回退 child.pid 两种隔离变异均在 Node/Bun 的初始化窗口断言真实失败,4/4检出。
  • 当前head首跑CI全部通过。已整合主干和另外两条身份修复部署本地3.56.0-story-integrated.2;9个bot、Dashboard及supervisor均加载新二进制。隔离二进制smoke和关键链路通过,DashboardHTTP200、历史可读。存量忙碌runner有两条prepared输入时,既有warm恢复无法唯一绑定原turn,当前轮仍fail-closed且等待空闲升级,未声称它已verified;没有强停或重放。

未自动合并、打tag或正式发布。capture 失败时 getter 回退 child.pid 的既有 P3 边界保留后续处理。后台专属登记见 #2519。

@deepcoldy

Copy link
Copy Markdown
Owner

提醒一下:本 PR 也改了 test/codex-app-runner.integration.test.ts 里「registers native engines across idle recovery on the authenticated worker path」这条用例。这条用例的偶发(#2520)有一份测试侧修复 #2523,即将合入,它改的也是这条用例的等待条件和 scope。#2523 合入后本 PR 大概率需要 rebase 解冲突,请合并时以 #2523 落地后的写法为基础。

@deepcoldy

deepcoldy commented Oct 29, 2026 •

Copy link
Copy Markdown
Owner

自动评审最终意见(最终以维护者审阅为准):

维护者已复核,结论为修后可合,无阻断项。src 修复确认正确:npm 形态下常驻 Node launcher 再拉起原生 app-server,旧实现把 launcher 当执行引擎出证,会让 worker 把随后发布的真原生引擎误判为「旧进程仍存活却换了身份」而 fail-closed;改为 initialize 完成后从 captureCodexAppProcessIdentity 的唯一核验结果取 enginePid、每次出证重读出生 tick、初始化窗口内不出 appServerProcess,与 worker 侧校验自洽。

原初审提出的唯一 P2(初始化窗口的新行为没有仓库内测试钉住)已由维护者在上一条评论给出测试补丁(仅改 test 文件,可直接 git apply):让 node-launcher 夹具的启动延迟可配,在空闲重连初始化窗口内强制一次控制连接重新接受,确定性断言窗口内第一条签名状态不带 appServerProcess、且窗口内不得把 launcher pid 当引擎根。该补丁已被变异复验:摘掉 initialized 门或把出证回退为 child.pid 时,vitest 与 bun test 双引擎都真实失败(fail-closed 换身份误判的同一形状),补丁在树上时双引擎全绿。

两个非阻断 P3,不影响本 PR 合入,建议后续处理:

  1. captureCodexAppProcessIdentity 返回 undefined(候选歧义/枚举中消失)时,getter 静默回退为 child.pid(npm 形态即 launcher)出证,与 attestation「歧义保持未证明」的契约不完全一致;建议后续收紧为仅当子进程 exe basename 为 codex 时才回退。
  2. 出生 tick 比对守卫属纵深防御(worker 侧会独立按进程树和出生 token 重新锚定),维持现状。

合入前需要作者按顺序完成两件事(顺序不能反:补丁的上下文含 master 已合入的 #2523/#2526,直接在当前 head 上 apply 会有冲突):

  1. 先 rebase 到最新 master(当前为 dd1f9ee;src 文件无冲突,测试文件需解一次同用例冲突,维护者本地已验证解法);
  2. rebase 完成后再 git apply 上一条维护者评论中的测试补丁;应用后可用 git hash-object test/codex-app-runner.integration.test.ts 自校验,结果应为 5b8278f83 开头;src/codex-app-runner.ts 无需改动,其 blob 应保持为 246f46815。

推送新 head 后 CI 需在新 head 首跑全绿(含 bun-test),随后即可合入,不需要改 src。

@deepcoldy

Copy link
Copy Markdown
Owner

复审结论:src 修复方向认可;原先的 P2(初始化窗口无测试钉守)已可用确定性用例咬红,补丁见下。

P2 复现与修法

原来摘掉 codex-app-runner.ts 的 initialized 门后,本文件 109 条在 vitest / bun test 双引擎全绿,因为既有用例两次控制端点接受都在 initialize() 之后。生产窗口真实存在:控制端点重接受(controlAcceptanceCount > 1 那条 settle)与空闲 settle 都可能落在替换 client 的 initialize() 里,那时 launcher 还活着、原生引擎尚未 spawn。

确定性用例:把 node-launcher 形态的 launcher 延迟做成可配(FAKE_CODEX_LAUNCH_DELAY_MS),在杀掉旧引擎、投递下一轮的瞬间主动断开已接受的控制连接,强制 re-auth。重接受的 settle 必然落在 initialize() 窗口内,此时:

  • 窗口内第一条 signed state 必须不带 appServerProcess;
  • 且窗口内任何 state 都不得把 runner 的 child.pid(launcher)当作引擎根。

变异复验(同一份测试):

变异 vitest bun test
原实现(摘 initialized 门) 红 ×3/3 红 ×2/2
出证回退到 child.pid(不认 enginePid) 红 红
原 PR 代码 绿 ×5/5 绿

红的方式是真实失败而非超时断言:expected { pid, procStart } to be undefined,随后 worker 侧 fail-closed: ... published an invalid or changed app-server process(launcher → 真引擎的"换身份"误判),正是本 PR 要修的形状。

测试改动(仅 test 文件,未动 src)要点:

// node-launcher 形态:launcher 延迟可配,窗口宽到足以容纳一次 re-auth
+ await new Promise(resolve => setTimeout(resolve, Number(process.env.FAKE_CODEX_LAUNCH_DELAY_MS ?? '100')));

const expectNoRootDuringReplacementInitialization = async (collector, running) => {
  const before = collector.states.length;
  await collector.restartEndpoint();                       // 断开已接受连接 → 触发 re-auth
  await waitFor(running, () => collector.states.length > before, 60_000);
  const windowStates = collector.states.slice(before);
  expect(windowStates.length).toBeGreaterThan(0);
  expect(windowStates[0].appServerProcess).toBeUndefined();  // initialize() 窗口内不得出证
  expect(windowStates.filter(s => s.appServerProcess).map(s => s.appServerProcess.pid))
    .not.toContain(running.child.pid);                       // 尤其不得把 launcher 当引擎根
};

control.authCount 的期望相应按形态区分(launcher 形态多一次 re-auth)。

其余

  • P3-1(出生 tick 守卫)在补丁后仍然双引擎全绿,维持先前判断:verifyCodexAppEngineIdentity 会独立按进程树 + token 重新锚定,属纵深防御,不阻断。
  • P3-2(capture 返回 undefined 时回退 child.pid)建议仍在后续处理,不阻断本 PR。
  • 本地树状态:bun run build 绿;test/codex-app-runner.integration.test.ts vitest 109/109(连续两轮);bun test(隔离 HOME/TMP)107 pass,2 fail(polls locators…、resets the keep-pending ceiling…,两者在未改动的基线上同样 5s 超时,与本 PR 无关);test-hygiene + 三个 attestation/identity 用例 127/127。
  • PR 当前 CONFLICTING,落地前需按最新 master rebase;rebase 后需新 head 首跑重绿。

@deepcoldy

Copy link
Copy Markdown
Owner

P2 补丁(仅 test/codex-app-runner.integration.test.ts,可直接 git apply;基于你 rebase 前的 PR 头):

diff --git a/test/codex-app-runner.integration.test.ts b/test/codex-app-runner.integration.test.ts
index a014cff6a..5b8278f83 100644
--- a/test/codex-app-runner.integration.test.ts
+++ b/test/codex-app-runner.integration.test.ts
@@ -1969,7 +1969,7 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
         + `import { spawn } from 'node:child_process';\n`
         // Keep the launcher alive across an idle-settle timer before the
         // native server exists, including after idle engine recovery.
-        + `await new Promise(resolve => setTimeout(resolve, 100));\n`
+        + `await new Promise(resolve => setTimeout(resolve, Number(process.env.FAKE_CODEX_LAUNCH_DELAY_MS ?? '100')));\n`
         + `const child = spawn(${JSON.stringify(fakeCodex)}, process.argv.slice(2), { stdio: 'inherit' });\n`
         + `for (const signal of ['SIGTERM', 'SIGINT', 'SIGHUP']) process.on(signal, () => child.kill(signal));\n`
         + `child.on('exit', code => process.exit(code ?? 1));\n`);
@@ -2041,7 +2041,11 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
     };
     await control.listen();
     harness = startRunner(codexBin, dir, logPath, '0.144.6', 'success', control.bootstrap.path,
-      { env: { FAKE_CODEX_PID_PATH: pidPath, FAKE_CODEX_FINISH_GATE: finishGate } });
+      { env: { FAKE_CODEX_PID_PATH: pidPath, FAKE_CODEX_FINISH_GATE: finishGate,
+        // Wide enough that the control re-acceptance below lands inside the
+        // replacement client's initialize() window, before the launcher has
+        // spawned the native engine.
+        ...(launchMode === 'node-launcher' ? { FAKE_CODEX_LAUNCH_DELAY_MS: '1200' } : {}) } });
     const enginePublications = () => published.filter((entry: any) => entry?.enginePid !== undefined);
     const waitForNative = async (predicate: () => boolean) => {
       await waitFor(harness!, () => rejected.length > 0 || predicate(), 60_000).catch(error => {
@@ -2053,6 +2057,33 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
       });
       expect(rejected).toEqual([]);
     };
+    // A replacement client is created and assigned to `client` before its
+    // initialize() RPC returns, and signed state can be emitted inside that
+    // window: an idle settle, or the control re-acceptance edge
+    // (`controlAcceptanceCount > 1`). Such a state must carry NO engine root.
+    // Attesting the npm launcher there freezes it as the engine root, and the
+    // real native engine's next state then reads as an unauthorized swap, so
+    // the worker runs failCodexAppControlGeneration. This drops the accepted
+    // control socket to force that re-authentication while the slow launcher
+    // has not spawned the native engine yet.
+    const expectNoRootDuringReplacementInitialization = async (
+      collector: ControlCollector, running: Harness,
+    ): Promise<void> => {
+      const before = collector.states.length;
+      await collector.restartEndpoint();
+      await waitFor(running, () => collector.states.length > before, 60_000);
+      const windowStates = collector.states.slice(before);
+      expect(windowStates.length).toBeGreaterThan(0);
+      // The first state of the window is the one emitted by the re-acceptance,
+      // while the replacement client is still inside initialize(): it must not
+      // claim any engine root at all.
+      expect(windowStates[0].appServerProcess).toBeUndefined();
+      // And the spawned child is the npm launcher, kept alive by the delay above
+      // so it is still the only process this client has. Publishing it is the
+      // defect that turns the real engine into an "unauthorized swap".
+      const rooted = windowStates.filter(state => state.appServerProcess !== undefined);
+      expect(rooted.map(state => state.appServerProcess.pid)).not.toContain(running.child.pid);
+    };
     // The runner settles idle 20ms after a turn. "The last state is idle" was
     // already true from the startup state, so the engine could be killed
     // before that settle. When the runner then noticed the exit first, its
@@ -2071,6 +2102,7 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
       expect(control.states.at(-1)?.appServerProcess).toEqual({
         pid: enginePublications()[0].enginePid, procStart: enginePublications()[0].engineProcStart,
       });
+      let probeInitWindow = false;
       for (const [index, turnId] of ['om_native_before', 'om_native_after', 'om_native_next'].entries()) {
         if (index === 1) {
           const pid = Number(readFileSync(pidPath, 'utf8'));
@@ -2079,12 +2111,17 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
             try { process.kill(pid, 0); return false; }
             catch (error) { if ((error as NodeJS.ErrnoException).code === 'ESRCH') return true; throw error; }
           });
+          probeInitWindow = launchMode === 'node-launcher';
         }
         // Production reserves a local liveness slot BEFORE the runner discovers
         // the dead engine. This must not be confused with native execution.
         tracker.begin(turnId);
         authority.beginWork();
         harness.child.stdin.write(`${CONTROL_PREFIX}${encodeRunnerInput(turnId, { text: turnId }, turnId)}\r`);
+        if (probeInitWindow) {
+          probeInitWindow = false;
+          await expectNoRootDuringReplacementInitialization(control, harness!);
+        }
         await waitForNative(() => control.finals.length === index + 1);
         tracker.completeCurrent();
         await waitForNative(idleAfterLastFinal);
@@ -2107,7 +2144,7 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
         && marker.kind === 'activity' && marker.payload.phase === 'submitted');
       expect(boundaryIndex).toBeGreaterThan(-1);
       expect(submittedAfter).toBeGreaterThan(boundaryIndex);
-      expect(control.authCount).toBe(1);
+      expect(control.authCount).toBe(launchMode === 'node-launcher' ? 2 : 1);
       expect(control.finals.map(final => final.turnId)).toEqual(['om_native_before', 'om_native_after', 'om_native_next']);
       // Replace the observing worker during native work. The signed state must
       // bind the exact persisted reply turn, rather than guessing from busy.
@@ -2131,7 +2168,7 @@ describe('codex-app-runner app-server protocol integration', { timeout: 120_000,
       writeFileSync(finishGate, 'ready');
       await waitForNative(() => control.finals.length === 4);
       tracker.completeCurrent();
-      expect(control.authCount).toBe(2);
+      expect(control.authCount).toBe(launchMode === 'node-launcher' ? 3 : 2);
       expect(rejected).toEqual([]);
       expect(readRequests(logPath).filter(request => request.method === 'thread/start')).toHaveLength(1);
       expect(readRequests(logPath).filter(request => request.method === 'thread/resume')).toHaveLength(1);

@deepcoldy

Copy link
Copy Markdown
Owner

复验记录(本地候选树,等新 head 后重申)

候选树:dd1f9ee77(最新 master)+ PR src + 合并后的 test + P2 补丁。
src/codex-app-runner.ts blob = 246f4681,与作者 head b407ff9fc 的 src blob 逐字相同;测试文件 blob 5b8278f8。

一个应用顺序的提醒(重要)

P2 补丁是基于 rebase 后的树生成的(其上下文含 #2523/#2526 合入 master 的 idleAfterLastFinal / clearCodexAppEngineIdentity 钩子),实测:

目标树 补丁
565b7d388(rebase 到 dd1f9ee 之后) applies
b407ff9fc(当前远端 head,基于旧 master) conflicts

所以作者的动作顺序必须是:先 rebase 到最新 master,再 git apply 补丁;反过来会冲突。应用后测试文件应得到 blob 5b8278f8(可 git hash-object 自校验)。

关于两条 bun 用例失败(修正我先前的归因)

我先前写成「共享机 CPU 争抢的偶发」,更准确的原因已定位:裸 bun test 的默认 per-test 超时是 5s,而仓库/CI 的调用方式是 scripts/run-bun-tests.mjs,它带 --timeout=180000。这两条用例本身耗时约 5s+(slow-drip 断言就要求 ≥4.5s),所以在裸调用下必然超时:

树 裸 bun test CI 调用形态 --timeout=180000
master dd1f9ee77(未含本 PR) FAIL ×2 PASS ×2
候选树(含补丁) FAIL ×2 PASS ×2

master 与本候选树表现完全一致 ⟹ 与本 PR 无关,是调用方式差异,不是产物问题,也不是随机抖动。

本轮验证结果(候选树)

  • bun run build 绿;tsc --noEmit 绿
  • test/codex-app-runner.integration.test.ts:vitest 109/109;bun test --timeout=180000 109/109
  • test-hygiene + codex-app-engine-identity + codex-app-process-attestation + worker-codex-app-engine-root + worker-codex-app-process-attestation:127/127
  • 变异(摘 initialized 门):vitest 红 3/3(expected { pid, procStart } to be undefined),bun 红 —— 与上一轮一致
  • worktree 已复原干净,未推送任何内容

关于 G1

当前远端 head 仍是 b407ff9fc,仍是 CONFLICTING,所以「在最终 head OID 上重申可合」这一项现在无法完成。我在此对候选树的 src blob 246f4681 表态:该 src 内容可合(0 P1 / 0 P2,2 个 P3 不阻断)。

作者 push 出新 head 后,请把新 OID 贴到本群,我会在新 head 上核对 src blob 是否仍为 246f4681、测试文件是否含补丁、以及新 head 的 CI 结果,然后给出最终 head 上的重申。

@deepcoldy

Copy link
Copy Markdown
Owner

最终重申(head ccd0a79b6):可合

已在 ccd0a79b6d90252a6f9865cca3eb9b7c7318fa47 上独立核对,三项硬校验全部通过。

① src:走例外口径,PR 自身改动逐字未变 —— 通过

src/codex-app-runner.ts blob ee406304e69f69e2eb6bd0712101a3f48d82e8af(≠ 旧 246f4681,因 master #2473 在同文件加容量续跑)。

我不只对比了行文本,还做了机器级比较:把 git diff 651a7d399 b407ff9fc -- src/… 与 git diff 58ea44ee4b ccd0a79b6 -- src/… 去掉 index 行后做字符串相等断言,结果 IDENTICAL。净改动 +14/−3,内容只含:initialized 字段、getter 的初始化门 + enginePid 选择 + 出生 tick 复核、initialize() 末尾置位。master 的 #2473 侧改动完整保留(merge-tree 输出 result 100644 ee406304,与 PR 侧 blob 一致)。

② test:P2 用例在,且加强版消除了我原版的时间竞态 —— 通过

blob ae67d03ccf(与 5b8278f8 合法不同:master #2473 也动了该文件,用例数 109→114)。

作者的加强我读了实现,确实比我原版更稳,理由成立:

  • 我原版靠「投递顺序」隐式保证 restartEndpoint() 落在 initialize() 窗口内,只靠 launcher 的 1200ms 延迟兜时间窗;
  • 新版让 launcher 先把自身 pid 写入 FAKE_CODEX_LAUNCHER_PID_PATH,探针显式 waitFor(launcher pid !== previousLauncherPid)——即等到替换后的新 launcher 已存在、原生 server 尚未 spawn这个确定状态,再 restartEndpoint()。这把「窗口内」从时序假设变成了显式同步点。
  • 断言保持两条:窗口首条 state 无 appServerProcess;窗口内任何 state 不带 launcherPid(现在用的是读到的真实新 launcher pid,而不是 harness.child.pid,更精确)。
  • authCount 按形态区分 2/1 与 3/2。

master 侧既有资产核对未丢失:#2523/#2526 的 idleAfterLastFinal(2)、clearCodexAppEngineIdentity(2) 在;#2473 的三个新用例(capacity / native failed terminal / steered group)各 1 处均在。删除行集合逐个看过,全部是本 PR 有意替换的那几行,无 master 侧内容被吞。

③ 变异:新树上摘门必红,且只有 launcher 形态红 —— 通过

在新树(ee406304)上摘 initialized 门:

  • vitest:node-launcher 形态 3/3 全红,失败点 test:2197 expected { pid, procStart } to be undefined,调用栈 expectNoRootDuringReplacementInitialization ← test:2242
  • bun test --timeout=180000:同红(1 pass / 1 fail,native 形态仍通过)
  • 恢复后 git hash-object src/codex-app-runner.ts = ee406304…,工作树干净

形状符合预期:只有「launcher 被当引擎根」那条路径红,native 形态不受影响——钉住的正是要修的误判。

其余

  • bun run build 绿(另跑 tsc --noEmit 绿)
  • test/codex-app-runner.integration.test.ts:vitest 114/114;bun test --timeout=180000 114/114
  • CI run 41380602442:headSha == ccd0a79b6、attempt 1、conclusion success,10 项全绿(build / test / test 1-4/4 / bun-test 35m54s / bun-binary ×3),gh run list --commit 仅此一条 run,非重跑
  • git merge-tree --write-tree f082ae60ab ccd0a79b6 exit 0、无 conflict;master 自 58ea44ee4b 起只动 traex-* 五个文件,与本 PR 两文件零交集
  • 2 个 P3 维持不阻断:capture 歧义时回退 launcher 出证(建议 followup 收紧为仅 exe basename=codex);出生 tick 守卫有 worker 侧独立锚定,属纵深防御
  • 本地复查完毕已切回干净状态,未推送任何内容

结论不变:0 P1 / 0 P2 / 2 P3(不阻断)。对 ccd0a79b6 表态可合,可用 squash-pr 合入,保留 uestcwangci 署名,不 tag、不部署。

@deepcoldy
deepcoldy merged commit fda858c into deepcoldy:master Nov 2, 2026
10 checks passed
@github-actions

github-actions Bot commented Nov 2, 2026

Copy link
Copy Markdown

@uestcwangci @deepcoldy 合入 master 后的 Midscene E2E 失败:Dashboard Midscene 失败;Feishu live Midscene 失败。

这次运行覆盖 fda858c。

@deepcoldy

Copy link
Copy Markdown
Owner

已合入 master(squash 为 fda858c),感谢贡献!

评审中确认的两个非阻断项记录在此,供后续跟进(不影响本次合入):

  1. AppServerClient.executionIdentity 在 captureCodexAppProcessIdentity 返回 undefined(候选歧义或枚举过程中进程消失)时会静默回退为 spawn 的直接子进程出证;npm 形态下该子进程是 Node launcher,与 attestation 服务「歧义保持未证明」的契约不完全一致。后续可考虑仅当该子进程 exe basename 为 codex 时才允许回退。
  2. 出生 tick 比对守卫与 worker 侧 verifyCodexAppEngineIdentity 的进程树+token 重新锚定构成纵深防御,维持现状即可。

欢迎继续提交。

@iluhcm

iluhcm commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

这个版本什么时候发布?我也遇到了。本来提了PR,重复了。

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

🚀 Released in v3.57.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants