Skip to content

fix(codex): fence device reauth cancellation - #4998

Merged
lidge-jun merged 3 commits into
lidge-jun:devfrom
luvs01:agent/device-reauth-cancel-fence-20260918
Sep 18, 2026
Merged

lidge-jun merged 3 commits into
lidge-jun:devfrom
luvs01:agent/device-reauth-cancel-fence-20260918

Conversation

@luvs01

@luvs01 luvs01 commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Summary

Fence device reauthentication cancellation through the credential commit. Previously a cancel delivered while the prepared commit was in flight could not reach the native-main exclusive claim or the filesystem write, so the in-flight commit could still replace ^Guth.json\ and clear the reauth quarantine — and a late success could then overwrite the cancelled terminal.

  • Propagate the flow \AbortSignal\ into \�eginNativeMainReauth().commit(tokens, { signal }), through \withNativeMainExclusiveClaim, and recheck it inside the claim immediately before the snapshot assertion and atomic write.
  • Pass the same signal from \startMainDeviceReauth\ into \ low.prepared.commit(...).
  • Make \ inish(...)\ strictly first-write-wins so a commit completing after cancellation can no longer flip the flow back to \succeeded.
  • Document the cancellation fencing guarantee in \structure/codex-home.md.

Every macrotask yield inside the commit (claim retry wait, claim-database open) is already signal-fenced by \withNativeMainExclusiveClaim; the claim operation itself is synchronous after the new in-operation recheck, and the claim release is synchronous, so a cancel can only settle before the write — never during or after it.

Verification

  • Head: f9c24b37e4cb4a22fa428c64a3cf262e4d49d469 (tree 688dfe13cf665160fa5d85ed3ebded863099a7f4) on top of dev 6467235a8.
  • Local gates: \�un x tsc --noEmit, \�un run structure:check, \�un run privacy:scan, \�un scripts/file-size-ratchet.ts\ — all pass.
  • Focused tests: \�un test tests/codex-integration/main-device-reauth.test.ts tests/codex-integration/main-device-reauth-api.test.ts\ — 24 tests / 77 assertions pass, including the new "cancelling a commit in flight fences publication" and "an aborted commit cannot replace the native credential" cases.
  • Fork Cross-platform CI run \35291461934\ dispatched on this head.

Review readiness checklist

This PR stays in draft until every box below is ticked. Tick all four boxes once the requirements are met:

  • All CI tests are green on my local testing. Local gates passed on this head (tsc, structure:check, privacy:scan, focused tests on the merged head).

  • I pushed my PR to the latest dev commit. The branch carries dev 4c0124acb, 4 behind tip - inside the 10-commit window.

  • I resolved all correct Codex and CodeRabbit findings. No unresolved review threads on this head.

  • My PR is ready for review.

Remaining gates: fork CI run 35291461934 in progress (known macos control 30-minute cap, #4905).

Summary by CodeRabbit

  • New Features

    • Native reauthentication commits now support cancellation through an optional abort signal.
    • Cancellation while waiting to publish credentials now prevents the credential update.
  • Bug Fixes

    • Already-cancelled reauthentication commits now stop before modifying authentication data.
    • Reauthentication flows correctly report cancellation when interrupted during commit.
  • Documentation

    • Updated guidance to clarify cancellation behavior before and after credential publication.

Propagate the flow AbortSignal into the prepared native-main reauth commit and its exclusive claim so a cancelled flow cannot still replace auth.json or clear the reauth quarantine. Terminal settlements are now strictly first-write-wins: a commit completing after cancellation can no longer flip the flow back to succeeded.
@coderabbitai

coderabbitai Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 098799cd-31e9-47bf-9d77-726d03df0bc7

📥 Commits

Reviewing files that changed from the base of the PR and between 4c0124a and 5c1572b.

📒 Files selected for processing (4)
  • src/codex/main-account.ts
  • src/codex/main-device-reauth.ts
  • structure/codex-home.md
  • tests/codex-integration/main-device-reauth.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.


📝 Walkthrough

Walkthrough

The native reauthentication commit path now accepts an optional AbortSignal. Device-flow cancellation propagates through the exclusive claim and is rechecked before credential publication. Tests and documentation cover cancellation during contention and before the first write.

Changes

Native reauthentication cancellation

Layer / File(s) Summary
Abortable commit claim
src/codex/main-account.ts
beginNativeMainReauth now exposes an optional signal on commit. The signal is passed to withNativeMainExclusiveClaim, and an already-aborted signal prevents credential publication.
Device flow signal propagation and validation
src/codex/main-device-reauth.ts, tests/codex-integration/main-device-reauth.test.ts, structure/codex-home.md
The device flow passes flow.controller.signal to commit. Tests cover cancellation during an in-flight commit and an already-aborted commit. Documentation describes the pre-write cancellation boundary and post-write success behavior.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant ActiveFlow
  participant commit
  participant withNativeMainExclusiveClaim
  participant auth.json
  ActiveFlow->>commit: pass flow.controller.signal
  commit->>withNativeMainExclusiveClaim: wait with signal
  ActiveFlow->>commit: cancel during claim wait
  withNativeMainExclusiveClaim-->>commit: abort
  commit-->>ActiveFlow: cancellation result
  commit->>auth.json: write credentials only after the abort check
Loading

Merge Risk: ⚪ Minimal · up to 5c157

The cancellation fencing, credential-publication boundary, and terminal settlement changes have no identified actionable risk. The change is mergeable after normal CI completion.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely describes the primary change: fixing cancellation fencing in the Codex device reauthentication flow. This matches the changes in src/codex/main-account.ts, src/codex…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 3 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot added the bug Something isn't working label Sep 18, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Deterministic PR hygiene checks passed.

@github-actions

github-actions Bot commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

✅ READY

  • all PR quality gates passed; the review readiness checklist is complete.

Review readiness checklist

  • ✅ All CI tests are green on my local testing.
  • ✅ I pushed my PR to the latest dev commit.
  • ✅ I resolved all correct Codex and CodeRabbit findings.
  • ✅ My PR is ready for review.

4/4 boxes ticked.

This pull request is already Ready for Review.
The review-ready label marks this PR as ready; review automation runs independently.
Maintainers: @lidge-jun @Ingwannu

Threading the abort signal into the commit is right: it lets a cancel abort a
contended 30s claim wait, which the previous recheck could not do. Removing
the publication exception from finish() is not. The signal is checked inside
the claim immediately before a synchronous write, so it cannot be delivered
between that check and the write, but it also cannot fence the gap after it:
claim teardown and promise resolution both yield before finish() runs. A
cancel arriving there made the flow report "cancelled" for an auth.json that
had already been replaced and a reauth quarantine that had already been
cleared.

Restore the exception. The new in-flight cancellation test is unaffected
because its commit rejects on abort and never publishes.
@lidge-jun

Copy link
Copy Markdown
Owner

리뷰 · 우선순위 74 / 80

이 PR은 네이티브 메인 디바이스 재인증(#3898)에서 “취소”가 커밋 중에도 auth.json 교체와 재인증 격리 해제를 막지 못하던 구멍을 막습니다. 지금 비교 기준인 dev HEAD는 e80e571f63 (package 2.59.0, tip #4984 Vietnamese i18n) 입니다. 현재 tip의 src/codex/main-account.ts beginNativeMainReauth().commit은 시그널 없이 withNativeMainExclusiveClaim(..., { waitMs: 30_000 })만 타고, src/codex/main-device-reauth.ts는 grant 직후·쓰기 직전 Abort 재검사만 합니다. claim 대기(최대 30초) 도중에 들어온 cancel은 claim 대기를 끊지 못해, 준비된 커밋이 그대로 디스크에 실릴 수 있습니다.

고치는 축은 세 겹입니다. (1) commit(tokens, { signal })로 flow AbortSignal을 넣고, claim 옵션과 claim 안 쓰기 직전 재검사에 같은 시그널을 겁니다. src/codex/native-main-claim.tswithNativeMainExclusiveClaim은 이미 signal을 받아 busy 대기·재시도를 abort할 수 있어서, 이번 변경은 그 기존 훅을 재인증 커밋에 연결하는 일입니다. (2) startMainDeviceReauthflow.prepared.commit(..., { signal: flow.controller.signal })로 같은 시그널을 넘깁니다. (3) structure/codex-home.md 네이티브 메인 재인증 문단에 “cancel은 claim/쓰기 전에만 막고, 쓰기 이후 cancel은 succeeded가 정직한 단말”을 적습니다.

원래 기여자 커밋(8c70f650)은 finish()의 publication 예외까지 걷어 “순수 first-write-wins”로 바꿨습니다. 메인테이너 후속 f9c24b37가 그 예외를 다시 살렸고, 이유가 맞습니다. 시그널은 claim 대기와 동기 write 직전 재검사까지는 막지만, write 해제·promise settle 사이의 yield에는 닿지 않습니다. 그 틈에 cancel이 오면 credential은 이미 바뀌었는데 단말이 cancelled로 남는 거짓말 상태가 됩니다. 지금 PR head(f9c24b37)는 “비행 중 cancel은 게시를 펜스한다” 테스트와 “이미 abort된 commit은 credential을 못 바꾼다” 테스트를 추가하면서, 게시 이후 cancel은 계속 succeeded를 유지합니다. GUI 쪽 재시도 가능한 cancel 정리는 이미 tip에 올라간 #4594(guiMainReauthCancel)와 맞닿고, 이번 PR은 네이티브 커밋/claim 펜스에 초점을 둡니다.

types.ts/config.ts 스플릿 캠페인과는 무관하고, 중복 랜딩 PR도 보이지 않습니다. Preview deploy는 계획에 없습니다. 점수는 높게 잡습니다. 버그가 tip에 실재하고, claim 시그널 배선·문서·회귀 테스트·메인테이너 후속이 한 줄기로 맞습니다. 다만 브랜치가 아직 draft이고 base가 tip보다 뒤(6467235a8 근처)라 fork CI·rebase 확인이 남습니다.

src/codex/main-account.ts (commit 안 options.signal?.aborted) - abort 직후 throw options.signal.reason인데 reason이 비어 있으면 undefined를 throw합니다. tip의 claim 헬퍼도 같은 패턴이라 일관되지만, AbortError 이름 계약을 테스트가 기대하면 reason 없는 abort fixture를 한 번 더 확인하세요.
tests/codex-integration/main-device-reauth.test.ts - 예전 “in-flight publish wins” 시나리오를 “in-flight cancel fences publication”으로 교체한 것은 맞습니다. 게시 이후 racing cancel은 별도 테스트가 유지되는지(파일에 cancellation after publication returns succeeded) 랜딩 전 한 번 더 돌려 보세요.
PR 상태 - draft + mergeState BLOCKED. fork CI(macos control 30분 캡 #4905) 그린을 보고 ready로 올린 뒤 tip rebase가 필요합니다.
structure/codex-home.md - 취소 펜스 문장은 코드와 일치합니다. ADR-0008 링크 근처 기존 문단과 톤도 맞습니다.

메인테이너의 판단이 필요한 지점

  • draft를 언제 ready로 올릴지(로컬 게이트는 본문에 그린으로 적혀 있음; fork CI 대기 vs tip rebase 우선).
  • f9c24b37 publication 예외 복원이 최종 계약인지(리뷰 기준에서는 복원이 맞고, tip 계약 080과도 맞음).
  • fix(gui): preserve retryable reauth cancellation and settle terminal failures #4594 GUI cancel과 이 네이티브 펜스를 같은 릴리즈 노트에 묶을지.

너의 추천

CI 그린과 tip(e80e571f63) rebase만 확인되면 머지하세요. 메인테이너 후속 커밋이 이미 정직한 단말 계약을 바로잡았고, 시그널을 claim/쓰기에 묶는 축은 tip 버그를 직접 고칩니다. 라벨은 바꾸지 마세요. leftover 원본 PR은 없습니다.

이 댓글은 grok-bot이 작성했습니다

@github-actions
github-actions Bot marked this pull request as ready for review September 18, 2026 04:07
@lidge-jun
lidge-jun merged commit 856fe6e into lidge-jun:dev Sep 18, 2026
13 checks passed
@luvs01
luvs01 deleted the agent/device-reauth-cancel-fence-20260918 branch September 20, 2026 06:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working review-ready

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants