场景 114 · Codex Use Case

从事故调查到经过测试的修复

向 Codex Cloud 提供脱敏事故材料和可用测试环境,调查证据、复现有依据的代码缺陷,交付聚焦补丁、回归测试及部署和回滚交接。

EngineeringCode
Investigate an incident and test a fixEngineeringCodeQuality

原文核对:2026-11-10 · 中文正文 · 英文提示词与演示

场景定位

向 Codex Cloud 提供脱敏事故材料和可用测试环境,调查证据、复现有依据的代码缺陷,交付聚焦补丁、回归测试及部署和回滚交接。

难度
中级
时间跨度
长时间运行

适合用于

  • 调查已稳定事故的小型工程团队。
  • 拥有脱敏证据和安全复现输入的应用缺陷调查。
  • 在可用的隔离测试环境中审阅聚焦修复的团队。

起步提示词

英文原文 · 可复制后按实际材料修改

Investigate [incident ID] in [repository/service] using [path to sanitized incident packet]. Work in the published cloud environment selected for this task.

The packet identifies the incident time window, affected release SHA, expected behavior, observed behavior, relevant log and trace excerpts, and safe reproduction inputs. Read AGENTS.md and the repository's setup and testing instructions first. Check that the checkout matches the affected release, or explain the difference before drawing conclusions.

Build a short timeline with file and line references to the packet and source code. Separate observations, hypotheses, and evidence gaps. Test the strongest hypothesis in the isolated test environment. If you cannot reproduce the failure or lack decisive evidence, return an investigation with the next diagnostic step; do not claim a confirmed root cause or make a speculative fix.

If the evidence supports a code defect, add a regression test and run it against the original code to demonstrate the failure. Make the smallest fix, rerun that test, then run the relevant broader tests, lint, and type checks available in this repository. Record the commands, exit codes, and any checks you could not run.

Prepare a branch diff, a draft pull-request description, test-evidence.md, and a deployment and rollback handoff. Include the supported cause, unresolved uncertainty, and behavior changed. Use one evidence row per criterion: revision and environment versions, baseline command/exit/log, final command/exit/log, actual result, and pass/fail/blocked/not-run status with limitations. Keep the PR description as a local draft for review.

For this duplicate-webhook example, name the before-commit and after-commit failure points, prove duplicate contention with independent database connections, and state isolation, receipt-retention, and mixed-version rollout assumptions.

For this duplicate-webhook example, before proposing that retained deliveries resume, identify legacy orders without matching receipts after old consumers have drained. Hold affected event keys using the existing queue or quarantine procedure. Add a seeded orphan-with-pending-retry test that proves no second order or success acknowledgment occurs while held. Reconcile only from trusted immutable event identity, canonical payload, and committed-order evidence; keep missing or conflicting evidence quarantined for owner review. Do not invent fingerprints, delete receipts, or replay an unresolved legacy event.

Use only the supplied packet and repository unless I identify another approved source. Access only the explicitly approved read-only monitoring source, if supplied. Write code and task artifacts only in this repository; use only its isolated test database. Do not connect directly to production application or database hosts, or modify production systems. Do not replay production events, modify live data or monitoring, create or post external updates, merge, or deploy.

在准备好的云端环境中,让 Codex 调查一个边界明确的事故。目标是提供工程师可以审阅的成果:有依据的解释、修复前失败的回归测试、聚焦补丁,以及实际运行的测试证据。

适合事故已得到初步控制、剩余工作是理解并修复应用缺陷的阶段。如果证据不足以确定原因,应明确记录调查过程和下一步诊断,而不是给出未经证实的结论。

准备环境与事故材料

  1. 在网页或桌面应用选择 Work in > Cloud,并选取已发布环境。
  2. 创建新环境时选择 Create environment,选择 GitHub 仓库,请 Codex 准备运行时、依赖和隔离测试服务。
  3. 检查设置报告,解决失败检查,Publish 后再启动新任务。
  • 遵循当前 Cloud 环境指南。
  • 将仓库约定放在 AGENTS.md 中。

依赖或服务设置变化时,编辑可复用环境,测试并重新发布,然后在新任务中验证。

仓库刷新不会重新执行安装或启动命令;已有任务保留各自状态。

网络目标和测试凭据应分别配置;允许网络访问并不等于获得服务权限。

在新任务中确认目标代码、依赖、检查和可丢弃的测试数据库可用,记录起始提交与测试基线。

初始调查应自包含。将脱敏材料放入仓库或提供给任务,并由工程师提前整理和检查:

输入应包含的内容
事故摘要事故 ID、UTC 时间窗口、预期和实际行为、已知影响与当前状态;区分确认数量与估算。
发布身份已部署提交 SHA、部署时间、不含密钥的相关配置,以及已知的最近正常版本。
关联证据日志和追踪片段,包含时间戳、事件 ID、请求 ID、追踪 ID 和文件引用;脱敏时保持标识符一致。
安全复现测试请求体、相关夹具和执行疑似路径的说明,避免调用线上服务。
仓库指引相关路径、数据库引擎、测试命令、允许的改动和负责审阅的工程师。

材料中不得包含访问令牌、客户载荷或个人数据。

监控集成可选。使用时仅授予相关项目及时间窗口的只读访问;文件式流程不依赖它。仓库指令应将测试凭据与生产配置分开。

运行起始提示词

使用本页提示词,将占位符替换为事故 ID、仓库和材料路径。首次结果应将证据与受影响代码关联,解释可复现的部分并指出缺失信息。

只有证据支持代码缺陷时才继续实现修复;否则先审阅调查并补充输入。看似合理的解释、最近的一次改动,或在其他版本上成功的测试,都不足以确定事故原因。

示例:Webhook 重试产生重复订单

使用可运行的事故示例练习。下载内容包含事故材料、可复现缺陷的处理器、修正处理器和 PostgreSQL 测试。

服务接收 order.created Webhook,写入订单并记录事件已处理。事故中一次重试似乎创建了第二笔订单;团队已稳定服务,希望获得待审阅补丁。

示例使用 JavaScript、Node.js 测试运行器和 PostgreSQL。可丢弃夹具中的 event_receipts 表具有非空身份列,并在 (provider, account_id, event_id) 上建立不可延迟的唯一约束。

该结构允许先认领事件再创建订单,并保留规范化载荷指纹,以识别同一事件键被冲突复用的情况。

如果实际应用在认领时必须具有订单外键,或没有这种冲突证据,应暂停并单独决定数据库结构和设计。

证据中记录精确运行时、依赖锁、PostgreSQL 版本、事务隔离级别和回执表结构。下载夹具固定 Node.js 24.19.0、PostgreSQL 17.6 和 pg 8.23.1。

使用提供的 Compose 设置时,环境需有可运行的 Docker daemon,发布前验证 docker info。数据库只接受公开测试凭据,并绑定本地回环接口。改编测试时使用应用真实的数据库引擎及相关设置。

示例假设 PostgreSQL READ COMMITTED、稳定的提供方事件 ID,以及覆盖重试和重放窗口的回执保留期。

修正处理器将回执和订单写入置于同一事务。夹具建立临时数据库及 delivery_holds 表以模拟已有队列的隔离流程;该表属于测试设施,不是建议给应用增加的迁移。

应用修复不新增队列、数据库服务、数据库迁移或监控集成。假设不成立时,应暂停并调整范围。

运行示例

解压 ZIP,打开目录,使用 Docker Compose:

官方代码示例
docker compose -p codex-incident-rehearsal up -d --wait postgres
docker compose -p codex-incident-rehearsal run --rm runner node main.mjs baseline
docker compose -p codex-incident-rehearsal run --rm runner node main.mjs regression
docker compose -p codex-incident-rehearsal run --rm runner
docker compose -p codex-incident-rehearsal down --volumes

基线命令应以退出码 1 结束:重试断言观察到两笔订单和一条回执,而非各一条。回归命令对修正处理器运行同一断言,应以退出码 0 结束。

最后一个测试命令执行完整矩阵,包括独立连接、数据库锁竞争和历史孤立订单隔离。

如果安装提供的是 docker-compose,请替换 docker compose。按顺序执行命令;套件只重置有标记的测试 schema。

检查事务处理器

以下节选来自下载文件 main.mjs。解压后运行完整文件,测试和夹具设置均已包含。

官方代码示例
async function fixed(client, input, hook = async (_boundary) => {}) {
  await assertNotHeld(client, input);
  await hook("beforeClaim");
  await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
  let committed = false;
  try {
    const claimed = await client.query(
      `INSERT INTO event_receipts(provider, account_id, event_id, payload_fingerprint)
       VALUES ($1,$2,$3,$4)
       ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING event_id`,
      [...key(input), fingerprint(input)]
    );
    trace("receipt-claim-result", client, input, {
      inserted: claimed.rowCount === 1,
    });
    if (claimed.rowCount === 1) {
      await hook("afterClaim");
      await writeOrder(client, input);
      await hook("afterOrder");
    } else {
      // A new READ COMMITTED statement sees the winner after its commit.
      await checkReceipt(client, input);
    }
    await client.query("COMMIT");
    committed = true;
    trace("transaction-committed", client, input);
    await hook("afterCommit");
    trace("acknowledged", client, input, acknowledgment);
    return acknowledgment;
  } catch (error) {
    if (!committed) {
      await client.query("ROLLBACK");
      trace("transaction-rolled-back-no-ack", client, input);
    } else {
      trace("committed-response-lost-no-ack", client, input);
    }
    throw error;
  }
}

1. 提供精简事故材料

按以下文件组织材料:

官方代码示例
incidents/INC-DEMO-014/incident.md
incidents/INC-DEMO-014/logs.ndjson
incidents/INC-DEMO-014/release.json
incidents/INC-DEMO-014/order-created.sanitized.json

示例 release.json 标识发布提交 4a1c9e7d2b6f8a0c3d5e7f9012a4b6c8d0e2f413,部署于 2026-09-22T11:58:00Z。事故发生在同日 12:03:00Z–12:05:00Z,报告一项提供方事件关联两笔内部订单。自己的材料应区分确认影响数量和估算。

脱敏日志包含这些关联观察:

UTC 时间关联信息观察
12:03:04.110事件 evt_demo_042、账户 acct_demo_01、请求 req_demo_a、追踪 trace_demo_a首次投递进入 Webhook 处理器。
12:03:04.145相同事件与首次追踪订单 ord_demo_101 已提交。
12:03:04.150同一工作进程记录回执写入成功或响应前,进程退出;仅凭片段无法证明回执不存在。
12:03:14.203相同提供方/账户/事件,请求 req_demo_b、追踪 trace_demo_b重试进入处理器,日志显示未找到匹配回执。
12:03:14.241相同事件与第二次追踪订单 ord_demo_102 已提交,并记录了回执。

各次投递保留稳定事件 ID,每次使用不同的请求和追踪 ID。只保留请求级标识会掩盖重试与原事件的关系。

2. 追踪证据并检验假设

事故报告提出“重试风暴导致重复”,Codex 应将它视为假设。观察到两次投递不能证明风暴;重试本来就是 Webhook 处理器应容忍的正常条件。

受影响实现先查询回执,再提交订单,随后在另一事务中写回执。两次提交之间的空档是更有力的解释:进程失败会留下无回执订单,重试便可能重复创建;并发投递也可能在任一方写回执前都通过独立检查。

要求 Codex 追踪实际处理器和事务边界,引用代码行。确认材料中的发布版本与被测代码一致;如果不同,说明这如何限制结论。

3. 修改前先复现

使用示例 Webhook 和隔离 PostgreSQL 添加回归测试。在原处理器订单写入后、回执写入前加入仅用于测试的失败钩子。

依据真实事务边界确认此时原订单已提交。重试相同的提供方/账户/事件,断言恰好一笔订单和一条匹配回执;有缺陷的实现应因出现两笔订单而失败。

修复后在订单语句之后、共享事务提交之前执行对应钩子;失败尝试必须不留下订单或回执。

重试并断言各一条记录。不同版本保持相同业务断言,记录各版本钩子位置。

先在原实现上运行新测试,预期因两笔订单而失败。保存命令、起始提交、退出码和断言输出;若未出现预期失败,先查明差异再修改。

注入异常只能验证应用事务行为,不能复现所有主机、网络或数据库故障,应明确记录这一限制。

4. 实施证据支持的最小修复

针对此缺陷,在同一连接、同一事务中认领回执并写订单。利用现有唯一键及 INSERT ... ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING ...。

只有成功插入回执的一次投递能写订单,提交后才确认成功;失败事务回滚两次写入。不要捕获唯一性错误后继续使用已中止事务。

竞争投递可能等待首个事务。若首个事务提交,第二次认领不插入记录;应在 READ COMMITTED 下执行新的 SELECT,验证已存事件身份及载荷策略,然后返回既定重复确认,不再写订单。

若首个事务回滚,竞争者可以认领并处理。跳过插入后找不到回执、身份冲突或临时数据库错误,都必须进入既定重试或错误路径,不能虚构成功。

更严格的隔离级别下,序列化失败需要遵循仓库有限次数的整事务重试策略。参阅 PostgreSQL 的 INSERT 冲突行为与事务隔离说明。

内存集合或分离的“检查再插入”无法抵御并发进程和重启。事件键范围应匹配提供方身份契约;同一事件携带冲突身份或载荷时,应报告不一致,不能默认为有效重复。

示例业务变更全部位于同一数据库。如果真实处理器还发送邮件、扣款或调用外部服务,该事务并不能保证外部副作用幂等。扩大修复前先确认边界和系统既有投递或幂等机制。

5. 验证变更后的行为

同时提供原始失败与修复后结果,在明确事务边界设置测试钩子,并通过独立连接检查已提交状态。示例本地通过 11 项 PostgreSQL 测试,下载中的 test-evidence.md 记录结果及云端、部署仍需检查的项目。应在自己的发布环境运行套件,并实际测试提交时断连后,才能依赖该恢复路径。

检查或失败位置要求的行为
首次投递与已提交重复首次产生一笔订单和一条回执;重复事件返回约定确认,数量不变;记录精确状态和响应体。
认领回执前失败不创建任何记录,不返回成功;重试后各一条。
认领后、写订单前失败回滚回执,不产生订单;重试可正常认领并处理。
写订单后、提交前失败回滚两条记录;对应原实现“已提交订单但缺少回执”的缺陷,重试后各一条。
提交后、确认前模拟响应丢失,两条记录仍已提交;重试返回重复确认,不新增订单。
提交结果未知单独模拟提交附近连接丢失,不以普通异常代替;不能声称未经证实的成功。无论首次提交或回滚,相同稳定事件键的重试都应安全;未测传输故障应标记未运行。
并发重复:首个事务提交使用两个独立连接或进程竞争同一事件键。认领后暂停胜出者,在释放前启动竞争者并确认实际发生锁竞争,然后释放;最终双方走预期确认路径,订单和回执各一条。
并发重复:首个事务回滚重复受控并发,但使认领者在提交前失败;竞争者在回滚后认领并产生各一条记录,核对两次响应与最终状态。
事件身份与载荷冲突不同事件、不同账户或提供方下的相同事件 ID 保持独立;相同范围 ID 却载荷冲突时走约定冲突路径,不产生第二订单或静默确认不同工作。
历史无回执订单与待重试事件预置已提交但无回执的历史订单,恢复重试前识别并暂停其事件键。暂停中的重试不返回成功、不新增记录;可信对账后允许重复确认且订单和回执各一条,证据缺失或冲突时继续暂停。
更广泛服务检查运行相关集成测试、lint 和类型检查,区分新增失败、已有失败和无法运行的检查。

通过屏障、锁存器和有限超时协调并发,不能靠 sleep 或仅同时发起两个 Promise。清理测试时释放被阻塞进程并使用可丢弃夹具。异常测试本身不能证明突然进程死亡、传输丢失或生产并发行为。

示例在固定版本运行器中执行 node main.mjs baseline、node main.mjs regression 和 node main.mjs。结构化输出记录事务边界、已提交记录数、确认状态与响应体,以及观察到的阻塞后端 ID。

改编流程时使用仓库真实定义的命令并报告实际结果。跳过检查或缺少依赖必须写入交接,说明对可信度的影响。

审阅交接

共享证据记录

为每项验收标准使用事故流程的证据格式,根据实际输出填写。以下只是模板,不是通过结果。基线尚不存在的新测试,要与已有测试失败区分。

官方代码示例
Criterion / test: [specific behavior and test location]
Environment: [published setup reference; runtime, database and dependency versions]
Before: [revision + test-only diff ID; command; exit code; observed assertion; log path]
After: [final revision or base + diff ID; command; exit code; observed assertion; log path]
Status: [pass / fail / blocked / not run]
Limits / reviewer action: [untested behavior, blocker, or decision required]

将失败和通过运行绑定到真实被测状态,包括在原版本上加入的测试改动。保留日志、响应夹具和最终差异。最终版本变化后应更新证据,未运行或被阻塞检查不能算通过。

要求 Codex 在仓库保留代码差异和以下审阅材料:

  • incident-investigation.md:时间线、证据引用、已检验假设、有依据的原因和剩余不确定性。
  • test-evidence.md:基线提交、失败回归输出、修复提交或差异、通过的针对性检查、更广泛检查及限制。
  • pr-draft.md:简述缺陷、行为变化、测试证据和剩余风险。
  • deployment-handoff.md:已验证的结构、隔离级别和回执保留假设,发布负责人,发布前检查,重复订单及确认/错误指标,以及下述发布和回滚门槛。

接受补丁前,确认原代码不能通过新测试、修复后能通过,且差异解决的是已证明缺陷。Webhook 示例要检查事件键范围、事务边界、并发覆盖和事务外副作用。历史重复订单需单独处理,防止新重复不会修复历史记录。

计划部署与回滚

补丁只保护运行修正处理器的进程。旧进程仍可能先写订单再认领回执,因此混合版本灰度不能证明缺陷已消除。

发布负责人必须选择经过测试的混合版本策略,或已有的运行手册:暂停输入、排空在途旧进程、更新所有消费者,再无损恢复保留的投递。

选择后者前确认提供方或队列的重试与保留行为,不要假设暂停必然无损。

恢复投递前,识别已提交但没有匹配回执的历史订单。暂停并排空旧消费者只能防止新增旧式写入,不能修复已有记录。利用已有队列或隔离流程暂停所有受影响事件键;无法确认完整身份时,继续暂停相关投递或事故窗口内投递,交负责人审阅,不能宣称检查完成。

只有可信、不可变的提供方/账户/事件身份、规范化载荷证据和已提交业务记录能够确定此前实际行为时,才对账暂停的事件键。

按批准的对账流程补记匹配回执,不重复执行业务变更,然后解除该事件键的暂停。

证据缺失、载荷冲突或存在多笔业务记录时,继续隔离并交负责人审阅。重建指纹时,重试载荷不能替代原始事件的可信证据。

只有每个受影响事件键均已对账,或其暂停在所有消费者中持续生效,恢复前门槛才算通过。

在预发布环境预置历史订单及待重试事件,验证暂停能阻止新订单和成功确认;可信对账后,重试可收到重复确认且订单仍只有一笔。还要演练未解决情况,继续暂停且不虚构回执。将此门槛连同暂停/排空、消费者版本、保留和回滚检查一起交接。

发布前验证唯一约束存在且有效,各消费者使用一致的回执键与载荷策略,回执清理不会重新打开重放窗口,且外部副作用仍在本补丁范围之外。

在预发布环境演练选定顺序和失败进程重试。记录负责人确定的观察窗口及重复订单、Webhook 错误、确认延迟、锁等待、重试积压的停止阈值,不自行编造生产阈值。

回退到旧处理器可能再次产生重复订单。回滚交接必须说明控制措施(如获批暂停/排空流程)、安全版本和决定恢复处理的负责人。保留回执,不要删除它们以解除重试阻塞。历史重复订单需单独审阅修复。

工程师负责部署决策和生产修复。隔离测试通过是审阅证据,不是生产健康的证明。审阅草稿后创建 PR,运行正常 CI 和评审,再按团队控制流程部署。

在同一任务中继续

通过聚焦的后续请求消除不确定性或改进交接:

官方代码示例
Review the patch against two concurrent deliveries and a retry after a worker failure. Show which behaviors the tests establish and which remain untested. Keep the change limited to this handler and its regression tests; update the handoff with any remaining risk.

如果首次运行无法复现事故:

官方代码示例
Stop implementation. List the hypotheses the evidence rules out, the strongest remaining hypothesis, and the smallest additional sanitized input or isolated experiment needed to distinguish it. Keep the root cause unconfirmed.
展开英文原文对照

Give Codex Cloud a sanitized incident packet and a working test environment. Investigate the evidence, reproduce a supported code defect, and return a focused patch with regression-test evidence and a deployment and rollback handoff.

Give Codex one bounded incident to investigate in a prepared cloud environment. The goal is a result an engineer can review: a supported explanation, a regression test that fails before the fix, a focused patch, and evidence from the tests that ran.

This works well after the immediate incident has been stabilized and the remaining job is to understand and fix an application defect. If the available evidence cannot establish the cause, a useful result is a clear account of the investigation and the next diagnostic step.

Prepare the environment and incident packet

  1. In the web or desktop app, choose Work in > Cloud and select a published environment.
  2. To create one, select Create environment, choose the GitHub repositories, and ask Codex to prepare the runtime, dependencies, and isolated test services.
  3. Review the setup report, resolve failed checks, and Publish before starting a new task.
  • Follow the current Cloud environment guide.
  • Keep repository guidance in AGENTS.md.

If dependencies change or service setup changes, edit the reusable environment, test it, and Republish; then validate the updated environment in a new task.

Repository refresh does not rerun install/start commands, and existing tasks retain their own state.

Configure required network destinations and test credentials separately; allowing a destination does not grant service access.

Confirm that the affected checkout, dependencies, checks, and disposable test database work in the new task. Record the starting commit and test baseline.

Keep the initial investigation self-contained. Place a sanitized packet in the repository or make its files available to the task. An engineer should assemble and check it before starting:

InputWhat to include
Incident summaryIncident ID, UTC time window, expected and observed behavior, known impact, and current status. Distinguish confirmed counts from estimates.
Release identityThe deployed commit SHA, deployment time, relevant configuration values without secrets, and the last known good release if available.
Correlated evidenceLog and trace excerpts with timestamps, event IDs, request IDs, trace IDs, and file references. Preserve identifiers consistently when sanitizing.
Safe reproductionTest request bodies, relevant fixtures, and instructions for exercising the suspected path without calling live services.
Repository guidanceRelevant paths, database engine, test commands, permitted changes, and the engineer who will review the result.

Do not include access tokens, customer payloads, or personal data in the packet.

A monitoring integration is optional. If you use one, grant read-only access to the relevant project and time window; the file-based workflow does not require it. Repository instructions should keep test credentials separate from production configuration.

Run the starter prompt

Use the starter prompt on this page and replace its placeholders with your incident ID, repository, and packet path. The first result should connect the evidence to the affected code, explain what can be reproduced, and identify missing information.

Ask Codex to continue through implementation only when the evidence supports a code defect. Otherwise, review the investigation and provide the missing input. A plausible explanation, a recent code change, or a successful test on a different release is not enough to establish the cause.

Example: A retried webhook creates a duplicate order

Use the runnable incident sample to practice the investigation. It includes a prepared incident packet, a handler with a reproducible defect, the corrected handler, and PostgreSQL tests.

The service receives an order.created webhook, writes an order, and records that the event has been processed. During an incident, a retry appears to create a second order. The team has already stabilized the service and wants a patch for review.

The sample uses JavaScript, Node.js’s test runner, and PostgreSQL. Its disposable fixture has an event_receipts table with non-null identity columns and a non-deferrable unique key on (provider, account_id, event_id).

The schema permits a receipt claim before the order exists and retains the canonical payload fingerprint needed to detect conflicting reuse of the same event key.

If your application instead requires an order foreign key at claim time or lacks this conflict evidence, stop for a separate schema/design decision.

Record the exact runtime, dependency lock, PostgreSQL version, transaction isolation level, and receipt schema in the evidence. The downloadable fixture pins Node.js 24.19.0, PostgreSQL 17.6, and pg 8.23.1.

For the supplied Compose setup, prepare an environment with a working Docker daemon and verify docker info before publishing it. Its database accepts only public test credentials and is bound to the local loopback interface. Use your application’s database engine and relevant settings when adapting the test.

This example assumes PostgreSQL READ COMMITTED, stable provider event IDs, and receipt retention covering the provider’s retry/replay window.

The fixed handler places receipt and order writes in one database transaction. The fixture provisions a disposable database and a delivery_holds table to model an existing queue’s quarantine procedure; that table is test infrastructure, not a proposed application migration.

The application fix adds no queue, database service, schema migration, or monitoring integration. If those assumptions do not hold, stop and revise the scope.

Run the sample

Extract the ZIP, open its directory, and use Docker with Compose:

官方代码示例
docker compose -p codex-incident-rehearsal up -d --wait postgres
docker compose -p codex-incident-rehearsal run --rm runner node main.mjs baseline
docker compose -p codex-incident-rehearsal run --rm runner node main.mjs regression
docker compose -p codex-incident-rehearsal run --rm runner
docker compose -p codex-incident-rehearsal down --volumes

The baseline command must exit with code 1: the retry assertion observes two orders and one receipt instead of one of each. The regression command runs the same assertion against the corrected handler and must exit with code 0.

The final test command exercises the full matrix, including independent connections, database lock contention, and legacy-orphan quarantine.

If your installation provides docker-compose, use that spelling in place of docker compose. Run these commands sequentially; the suite resets only its marked test schema.

Inspect the transaction handler

This excerpt comes from main.mjs in the download. Run the complete files after extracting the ZIP; the tests and fixture setup are included there.

官方代码示例
async function fixed(client, input, hook = async (_boundary) => {}) {
  await assertNotHeld(client, input);
  await hook("beforeClaim");
  await client.query("BEGIN ISOLATION LEVEL READ COMMITTED");
  let committed = false;
  try {
    const claimed = await client.query(
      `INSERT INTO event_receipts(provider, account_id, event_id, payload_fingerprint)
       VALUES ($1,$2,$3,$4)
       ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING event_id`,
      [...key(input), fingerprint(input)]
    );
    trace("receipt-claim-result", client, input, {
      inserted: claimed.rowCount === 1,
    });
    if (claimed.rowCount === 1) {
      await hook("afterClaim");
      await writeOrder(client, input);
      await hook("afterOrder");
    } else {
      // A new READ COMMITTED statement sees the winner after its commit.
      await checkReceipt(client, input);
    }
    await client.query("COMMIT");
    committed = true;
    trace("transaction-committed", client, input);
    await hook("afterCommit");
    trace("acknowledged", client, input, acknowledgment);
    return acknowledgment;
  } catch (error) {
    if (!committed) {
      await client.query("ROLLBACK");
      trace("transaction-rolled-back-no-ack", client, input);
    } else {
      trace("committed-response-lost-no-ack", client, input);
    }
    throw error;
  }
}

1. Provide a compact packet

Use these files as the packet outline:

官方代码示例
incidents/INC-DEMO-014/incident.md
incidents/INC-DEMO-014/logs.ndjson
incidents/INC-DEMO-014/release.json
incidents/INC-DEMO-014/order-created.sanitized.json

In this scenario, release.json identifies the example release SHA 4a1c9e7d2b6f8a0c3d5e7f9012a4b6c8d0e2f413, deployed at 2026-09-22T11:58:00Z. The incident window is 12:03:00Z–12:05:00Z on the same day. The packet reports two internal orders associated with one provider event. When preparing your own packet, include confirmed impact counts and identify any estimates.

The sanitized logs contain these correlated observations:

UTC timeCorrelationObservation
12:03:04.110Event evt_demo_042, account acct_demo_01, request req_demo_a, trace trace_demo_aFirst delivery enters the webhook handler.
12:03:04.145Same event and first traceOrder ord_demo_101 is committed.
12:03:04.150Same workerWorker exits before a receipt-write success or response is recorded. The excerpt alone does not prove the receipt is absent.
12:03:14.203Same provider/account/event, request req_demo_b, trace trace_demo_bA retry enters the handler. The handler logs that no matching receipt was found.
12:03:14.241Same event and second traceOrder ord_demo_102 is committed and a receipt is recorded.

Keep a stable event ID across deliveries and distinct request and trace IDs per delivery. A per-request identifier would hide the relationship between the retry and the original event.

2. Trace the evidence and test the hypothesis

The incident report proposes that a retry storm caused the duplicate. Codex should treat that as a hypothesis. Two observed deliveries do not establish a storm, and retries are a normal condition a webhook handler must tolerate.

In the sample’s affected implementation, source inspection reveals this sequence: look up a receipt, commit the order, then write the receipt in a separate transaction. The gap between the two commits is a stronger explanation. A worker failure in that gap can leave an order without a receipt, so a retry can create another order. Concurrent deliveries can also both pass a separate check before either writes its receipt.

Have Codex trace the actual handler and transaction boundaries and cite the relevant lines. It should confirm the packet’s release matches the code under test, or explain why testing a different commit limits the conclusion.

3. Reproduce before changing the handler

Add a regression test using the sample webhook and the isolated PostgreSQL database. Put a test-only failure hook immediately after the order write and before the receipt-write step in the original handler.

Confirm from the real transaction boundaries that the original order has committed at that point. Retry the same provider/account/event and assert exactly one order and one matching receipt; the seeded implementation should fail with two orders.

After the fix, exercise the corresponding hook after the order statement but before the shared transaction commits; the failed attempt must leave zero orders and zero receipts.

Retry and assert one of each. Keep the same business assertion across revisions and record the hook location on each revision.

Run the new test on the original implementation first. For the seeded defect in this sample, the expected failure is two orders instead of one. Save the command, starting commit, exit code, and assertion output. If that failure does not occur, investigate the mismatch before editing the handler.

An injected exception exercises the application’s transaction behavior. Record that it does not reproduce every possible host, network, or database failure.

4. Make the smallest supported fix

For this specific defect, claim the event receipt and write the order within one transaction on one database connection. Use the existing unique key with INSERT ... ON CONFLICT (provider, account_id, event_id) DO NOTHING RETURNING ....

Only the delivery that inserts the receipt may write the order; acknowledge success only after commit. A failed transaction rolls back both writes. Do not catch a uniqueness error and continue using an aborted transaction.

A competing delivery may wait for the first transaction. If the first commits, the second claim inserts nothing: issue a fresh SELECT under READ COMMITTED, verify the stored event identity/payload policy, and return the existing duplicate acknowledgment without writing an order.

If the first transaction rolls back, the competitor can claim and process the event. A missing receipt after a skipped insert, an identity conflict, or a transient database error must follow the documented retry/error path, not a fabricated success.

Under stricter isolation, serialization failures require the repository’s bounded whole-transaction retry policy. See PostgreSQL’s INSERT conflict behavior and transaction isolation.

Neither an in-memory set nor a separate “check then insert” protects against concurrent workers or restarts. Scope the key to the provider’s event-identity contract. If a supposedly identical event carries conflicting identity or payload information, surface that inconsistency rather than silently treating it as a valid duplicate.

The demo’s business mutation is entirely within the same database. If the real handler also sends email, charges a card, or calls another service, this transaction alone does not make those external effects idempotent. Identify that boundary and the system’s existing delivery or idempotency mechanism before expanding the fix.

5. Verify the changed behavior

Ask for both the original failure and the post-fix result. Use test-only hooks at named transaction boundaries and inspect committed state from a separate connection. The sample passes eleven local PostgreSQL tests; test-evidence.md in the download records those results and the checks still needed for Cloud execution and deployment. Run the suite in your published environment and test actual connection loss during commit before relying on that recovery path.

Check / failure pointRequired behavior
First delivery and committed duplicateThe first creates one order and one receipt; a repeated event returns the agreed acknowledgment and leaves counts unchanged. Record exact status/body.
Before receipt claimFailure creates neither row and returns no success acknowledgment. A retry creates one of each.
After claim, before order writeFailure rolls back the receipt; no order exists. A retry can claim and process normally.
After order write, before commitFailure rolls back both rows. This is the fixed-code counterpart of the original committed-order/missing-receipt defect; a retry leaves one of each.
After commit, before acknowledgmentSimulate a lost response. Both rows remain committed. A retry returns the duplicate acknowledgment without another order.
Commit outcome unknownModel a connection loss around commit separately from an ordinary exception. Return no unsupported success claim; a retry with the same stable event key must be safe whether the first transaction committed or rolled back. If this transport case was not exercised, mark it not run.
Concurrent duplicate: first transaction commitsTwo independent connections/workers contend on the same event key. Hold the winner after claim; start the competitor before releasing it. Verify the competitor actually contends, then release the winner. Both complete through the expected acknowledgment path; exactly one order and one receipt exist.
Concurrent duplicate: first transaction rolls backRepeat the controlled overlap, but fail the claimant before commit. The competitor claims after rollback and creates one order and one receipt. Check both responses and final state.
Event identity and payload conflictDifferent events and the same event ID under different accounts/providers remain independent. For an event with the same scoped ID but a conflicting canonical payload, follow the agreed conflict path; do not create a second order or silently acknowledge different work.
Legacy order without receipt and pending retrySeed a committed legacy order without a receipt. Identify and hold its event key before retries resume. A held retry returns no success acknowledgment and creates no row. Trusted reconciliation permits the duplicate acknowledgment with one existing order and one receipt; missing or conflicting evidence keeps the key held.
Broader service checksRun relevant integration tests, lint, and type checking. Separate new failures, pre-existing failures, and checks that could not run.

Coordinate concurrency with barriers/latches and bounded timeouts, not sleeps or a bare pair of promises. Release blocked workers in test cleanup and use disposable fixtures. An exception test alone does not prove abrupt process death, transport loss, or production concurrency behavior.

The sample uses node main.mjs baseline, node main.mjs regression, and node main.mjs inside the pinned runner. Its structured output records transaction boundaries, committed row counts, acknowledgment status/body, and observed blocking backend IDs.

When adapting the workflow, use the commands actually defined by your repository and report their real results. A skipped check or unavailable dependency belongs in the handoff, with its impact on confidence.

Review the handoff

Shared evidence record

Use the incident workflow’s evidence format for each acceptance criterion. Populate it from observed output; the fields below are a template, not passing results. For a new test that does not exist at baseline, distinguish “not yet present” from a failed existing check.

官方代码示例
Criterion / test: [specific behavior and test location]
Environment: [published setup reference; runtime, database and dependency versions]
Before: [revision + test-only diff ID; command; exit code; observed assertion; log path]
After: [final revision or base + diff ID; command; exit code; observed assertion; log path]
Status: [pass / fail / blocked / not run]
Limits / reviewer action: [untested behavior, blocker, or decision required]

Keep red and green runs tied to their actual tested states, including test-only changes on the original revision. Keep the logs, response fixtures, and final diff with the handoff. A changed final revision needs updated evidence; checks that were not run or were blocked cannot count as passing.

Ask Codex to leave the code diff and these review artifacts in the repository:

  • incident-investigation.md: timeline, evidence references, hypotheses tested, supported cause, and remaining uncertainty.
  • test-evidence.md: baseline commit, failing regression output, fix commit or diff, passing targeted checks, broader checks, and limitations.
  • pr-draft.md: a concise explanation of the defect, changed behavior, test evidence, and remaining risk.
  • deployment-handoff.md: verified schema/isolation/receipt-retention assumptions, named rollout owner, pre-deployment checks, duplicate-order and acknowledgment/error metrics, and the rollout/rollback gates below.

Before accepting the patch, verify that the original code fails the new test, the fix passes it, and the diff addresses the demonstrated defect. In the webhook example, inspect event-key scope, transaction boundaries, concurrency coverage, and any effects outside the transaction. Review existing duplicate orders separately; preventing new duplicates does not repair historical records.

Plan deployment and rollback

A code patch protects only workers running the corrected handler. Old workers can still write an order before claiming a receipt, so a mixed-version canary is not evidence that the defect is eliminated.

The deployment owner must choose either a tested mixed-version strategy or an existing runbook that pauses ingestion, drains in-flight old workers, updates every consumer, and resumes retained deliveries without loss.

Confirm the provider/queue retry and retention behavior before choosing the latter; do not assume pausing is lossless.

Before resuming retained deliveries, identify committed legacy orders with no matching receipt. Pausing and draining old consumers prevents new legacy writes; it does not repair those existing orders. Hold every affected event key with the existing queue or quarantine procedure. If legacy records cannot establish a complete event identity, keep the affected deliveries or those from the affected time window paused for owner review rather than declaring the scan complete.

Reconcile a held key only when trusted immutable provider/account/event identity, canonical payload evidence, and the committed business record establish what already happened.

Under the approved reconciliation procedure, record the matching receipt without repeating the business mutation, then release that key’s hold.

Keep affected keys quarantined for owner review when evidence is missing, payloads conflict, or multiple business records exist. A retry payload cannot substitute for trusted evidence of the original event when reconstructing its fingerprint.

The pre-resume gate passes only when each affected key is reconciled or its hold remains enforced across all consumers.

Seed a legacy order and its pending retry in staging. Verify the hold prevents another order and any success acknowledgment; after trusted reconciliation, the retry may receive the duplicate acknowledgment while the existing order count stays at one. Rehearse an unresolved case too: it must remain held without a fabricated receipt. Keep this gate in the deployment handoff alongside pause/drain, consumer-version, retention, and rollback checks.

Before rollout, verify the existing unique constraint is present and valid, the receipt key/payload policy is consistent across all consumers, receipt cleanup cannot reopen the replay window, and external effects remain outside this patch.

In staging, rehearse the selected sequence and failed-worker retry. Record the owner’s observation window and stop thresholds for duplicate orders, webhook errors, acknowledgment latency, lock waits, and retry backlog; do not invent production thresholds.

Reverting to the old handler can reintroduce duplicate orders. The rollback handoff must name the containment step (for example, the approved pause/drain procedure), the safe revision, and the owner who decides when processing can resume. Preserve receipts; do not delete them to unblock retries. Historical duplicate orders require a separately reviewed remediation.

The engineer owns the deployment decision and any production remediation. A passing isolated test is evidence for review, not proof that production is healthy. Create the pull request, run your normal CI and review process, and deploy through your team’s established controls after reviewing the draft.

Continue in the same task

Use a focused follow-up to resolve uncertainty or improve the handoff:

官方代码示例
Review the patch against two concurrent deliveries and a retry after a worker failure. Show which behaviors the tests establish and which remain untested. Keep the change limited to this handler and its regression tests; update the handoff with any remaining risk.

If the first run could not reproduce the incident:

官方代码示例
Stop implementation. List the hypotheses the evidence rules out, the strongest remaining hypothesis, and the smallest additional sanitized input or isolated experiment needed to distinguish it. Keep the root cause unconfirmed.