Repository navigation
fix(review): lock the PR review worktree lease against concurrent sessions #9211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
baa828e
95db313
6f3a68e
2a7d9a5
80e69da
e865fbc
0da76ba
2473f80
5c852cd
01f6755
b4d4f1d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,6 +12,12 @@ import { | |
| isEmptyDiff, | ||
| isCollapsedFromUpstream, | ||
| } from './fetch-pr.js'; | ||
| import { | ||
| clearReviewWorktreeLease, | ||
| createReviewWorktreeLease, | ||
| readReviewWorktreeLease, | ||
| reviewLeaseHeldByAnotherSession, | ||
| } from '../../services/review-worktree-lease.js'; | ||
| import { classifyHeavy } from './lib/heavy.js'; | ||
| import { PARSE_ARGS_REPORT } from './lib/paths.js'; | ||
|
|
||
|
|
@@ -217,6 +223,8 @@ const producerMocks = vi.hoisted(() => ({ | |
| }), | ||
| gh: vi.fn(), | ||
| git: vi.fn(), | ||
| execFileSync: vi.fn(), | ||
| releaseWorktree: vi.fn(() => ({ existed: false, freed: true })), | ||
| writeStderrLine: vi.fn(), | ||
| })); | ||
|
|
||
|
|
@@ -240,8 +248,8 @@ vi.mock('node:child_process', async (importOriginal) => { | |
| const actual = await importOriginal<typeof import('node:child_process')>(); | ||
| return { | ||
| ...actual, | ||
| default: { ...actual, execFileSync: vi.fn() }, | ||
| execFileSync: vi.fn(), | ||
| default: { ...actual, execFileSync: producerMocks.execFileSync }, | ||
| execFileSync: producerMocks.execFileSync, | ||
| }; | ||
| }); | ||
|
|
||
|
|
@@ -251,7 +259,12 @@ vi.mock('../../utils/stdioHelpers.js', () => ({ | |
| })); | ||
|
|
||
| vi.mock('../../services/review-worktree-lease.js', () => ({ | ||
| clearReviewWorktreeLease: vi.fn(), | ||
| createReviewWorktreeLease: vi.fn(), | ||
| readReviewWorktreeLease: vi.fn((): unknown => null), | ||
| reviewLeaseHeldByAnotherSession: vi.fn((): boolean => false), | ||
| reviewLeasePath: (repositoryRoot: string, target: string) => | ||
| `${repositoryRoot}/.qwen/tmp/qwen-review-lease-${target}.json`, | ||
| })); | ||
|
|
||
| vi.mock('./lib/gh.js', () => ({ | ||
|
|
@@ -265,7 +278,7 @@ vi.mock('./lib/git.js', () => ({ | |
| gitOpt: vi.fn(() => null), | ||
| gitRaw: vi.fn(() => Buffer.from('')), | ||
| refExists: vi.fn(() => false), | ||
| releaseWorktree: vi.fn(() => ({ existed: false, freed: true })), | ||
| releaseWorktree: producerMocks.releaseWorktree, | ||
| })); | ||
|
|
||
| vi.mock('./lib/merge-base.js', () => ({ | ||
|
|
@@ -334,6 +347,121 @@ describe('fetch-pr report assembly', () => { | |
| expect(report.host).toBe('ghe.example.com'); | ||
| }); | ||
|
|
||
| // The lease is also a lock (#9205): a concurrent same-PR fetch-pr used to | ||
| // stale-clean the holder's worktree before failing on, destroying it. The | ||
| // refusal must precede every destructive step, including the lease write. | ||
| describe('lease lock', () => { | ||
| const foreignLease = { | ||
| sessionId: 'session-other', | ||
| promptId: 'prompt-other', | ||
| target: 'pr-42', | ||
| repositoryRoot: process.cwd(), | ||
| worktreePath: '.qwen/tmp/review-pr-42', | ||
| branch: 'qwen-review/pr-42', | ||
| }; | ||
|
|
||
| it('refuses with an actionable error when another session holds the lease', async () => { | ||
| vi.mocked(readReviewWorktreeLease).mockReturnValueOnce(foreignLease); | ||
| vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(true); | ||
|
|
||
| await expect(reportFor({})).rejects.toThrow( | ||
| 'PR #42 is already being reviewed by another session ' + | ||
| '(session session-other)', | ||
| ); | ||
| // The lock must consult THIS PR's lease: mockReturnValueOnce is | ||
| // argument-blind, so an unwired target leaves the race undetected. | ||
| expect(vi.mocked(readReviewWorktreeLease)).toHaveBeenCalledWith( | ||
| process.cwd(), | ||
| 'pr-42', | ||
| ); | ||
| // Nothing was touched on the way out. | ||
| expect(vi.mocked(createReviewWorktreeLease)).not.toHaveBeenCalled(); | ||
| expect(producerMocks.git).not.toHaveBeenCalled(); | ||
| expect(producerMocks.gh).not.toHaveBeenCalled(); | ||
| expect(producerMocks.releaseWorktree).not.toHaveBeenCalled(); | ||
| expect(producerMocks.execFileSync).not.toHaveBeenCalled(); | ||
| expect(producerMocks.writeFileSync).not.toHaveBeenCalled(); | ||
|
Comment on lines
+477
to
+483
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] The refusal test's comment promises "the refusal must precede every destructive step", but its negative-space assertions omit Witness: Fix: hoist expect(producerMocks.releaseWorktree).not.toHaveBeenCalled();中文说明[建议] 拒绝测试的注释承诺"拒绝必须先于所有破坏性步骤",但其"什么都没发生"断言遗漏了 证据:变异体(cleanStale 上移)对原测试 修复:把 — qwen3.8-max via Qwen Code /review (v0.21.11) |
||
| }); | ||
|
|
||
| it('names the lease file to delete when the holder session is gone', async () => { | ||
| vi.mocked(readReviewWorktreeLease).mockReturnValueOnce(foreignLease); | ||
| vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(true); | ||
|
|
||
| await expect(reportFor({})).rejects.toThrow( | ||
| 'qwen-review-lease-pr-42.json', | ||
| ); | ||
| }); | ||
|
|
||
| it('lets the holding session re-fetch its own lease', async () => { | ||
| // Ownership is per session, not per prompt: a later round re-fetches | ||
| // while its own earlier prompt's lease is still on disk. | ||
| vi.mocked(readReviewWorktreeLease).mockReturnValueOnce({ | ||
| ...foreignLease, | ||
| sessionId: 'session-self', | ||
| promptId: 'prompt-earlier', | ||
| }); | ||
| vi.mocked(reviewLeaseHeldByAnotherSession).mockReturnValueOnce(false); | ||
|
|
||
| await reportFor({}); | ||
|
|
||
| expect(vi.mocked(createReviewWorktreeLease)).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); | ||
|
|
||
| // A handled failure after the lease write must roll the lease back with the | ||
| // rest of the state: the lock refuses any later session that finds another | ||
| // session's lease, so one left behind blocks every later review of this PR | ||
| // until it is deleted by hand. | ||
| describe('lease rollback on failure', () => { | ||
| it('clears the lease when the PR fetch fails', async () => { | ||
| producerMocks.git.mockImplementation(() => { | ||
| throw new Error('network down'); | ||
| }); | ||
|
|
||
| await expect(reportFor({})).rejects.toThrow( | ||
| 'Failed to fetch PR #42 from remote "origin"', | ||
| ); | ||
| expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith( | ||
| process.cwd(), | ||
| 'pr-42', | ||
| ); | ||
| }); | ||
|
|
||
| it('clears the lease when the metadata fetch fails', async () => { | ||
| producerMocks.gh.mockImplementation(() => { | ||
| throw new Error('gh unavailable'); | ||
| }); | ||
|
|
||
| await expect(reportFor({})).rejects.toThrow( | ||
| 'Failed to fetch PR #42 metadata', | ||
| ); | ||
| expect(producerMocks.execFileSync).toHaveBeenCalledWith( | ||
| 'git', | ||
| ['branch', '-D', 'qwen-review/pr-42'], | ||
| { stdio: 'pipe' }, | ||
| ); | ||
| expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith( | ||
| process.cwd(), | ||
| 'pr-42', | ||
| ); | ||
| }); | ||
|
|
||
| it('clears the lease when the worktree add fails', async () => { | ||
| producerMocks.git.mockImplementation((...args: string[]) => { | ||
| if (args[0] === 'worktree') throw new Error('disk full'); | ||
| return args[0] === 'rev-parse' ? 'f00df00d' : ''; | ||
| }); | ||
|
|
||
| await expect(reportFor({})).rejects.toThrow( | ||
| 'Failed to create worktree at', | ||
| ); | ||
| expect(vi.mocked(clearReviewWorktreeLease)).toHaveBeenCalledWith( | ||
| process.cwd(), | ||
| 'pr-42', | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| it('preserves the earliest window opening across drift restarts of the same PR', async () => { | ||
| // A drift restart reruns fetch-pr and overwrites this report; the audit | ||
| // boundary must keep reaching back to the abandoned attempt's opening. | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -30,7 +30,13 @@ import { execFileSync } from 'node:child_process'; | |
| import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'; | ||
| import { dirname, resolve } from 'node:path'; | ||
| import { writeStdoutLine, writeStderrLine } from '../../utils/stdioHelpers.js'; | ||
| import { createReviewWorktreeLease } from '../../services/review-worktree-lease.js'; | ||
| import { | ||
| clearReviewWorktreeLease, | ||
| createReviewWorktreeLease, | ||
| readReviewWorktreeLease, | ||
| reviewLeaseHeldByAnotherSession, | ||
| reviewLeasePath, | ||
| } from '../../services/review-worktree-lease.js'; | ||
| import { ensureAuthenticated, gh, setGhHost } from './lib/gh.js'; | ||
| import type { ReviewEffort } from './parse-args.js'; | ||
| import { git, gitOpt, gitRaw, refExists, releaseWorktree } from './lib/git.js'; | ||
|
|
@@ -189,10 +195,33 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> { | |
|
|
||
| const ref = reviewBranch(prNumber); | ||
| const wt = worktreePath(prNumber); | ||
|
|
||
| // The lease is also a lock. The worktree path is fixed per PR number, so | ||
| // the stale-clean below would remove a worktree ANOTHER session is actively | ||
| // reviewing — that is precisely how #9205 destroyed a round-4 review mid-run. | ||
| // Refuse before touching anything; the refusal must precede both the lease | ||
| // write and `cleanStale`, because a fetch-pr that fails AFTER either one | ||
| // has still clobbered the holder's lease and state. Same-session re-fetches | ||
| // (drift restarts, later rounds of a multi-prompt review) pass: ownership | ||
| // is per session, not per prompt. | ||
| const leaseTarget = `pr-${prNumber}`; | ||
| const holder = readReviewWorktreeLease(process.cwd(), leaseTarget); | ||
| if (reviewLeaseHeldByAnotherSession(holder)) { | ||
|
Comment on lines
+642
to
+643
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] fetch-pr has no test that an existing lease held by the SAME session lets the fetch proceed — cleanup has the symmetric "proceeds when the lease belongs to this session" test, but this suite only exercises "no lease" and "foreign lease refuses". — Failure scenario: probe-verified surviving mutant — Witness: under the Fix: add a lease-lock test where 中文说明[建议] fetch-pr 没有测试"同一会话已持有租约时 fetch 应继续"——cleanup 有对称的"租约属于本会话时继续"测试,但 fetch-pr 的锁测试只覆盖"无租约"和"他会话租约拒绝"两种情况。— 失败场景:经探针验证的存活变异体—— 证据: 修复:新增锁测试—— — qwen3.8-max via Qwen Code /review (v0.21.11) |
||
| throw new Error( | ||
| `PR #${prNumber} is already being reviewed by another session ` + | ||
| `(session ${holder.sessionId}). Same-PR reviews share one worktree ` + | ||
| `path and cannot run concurrently, so this run refuses rather than ` + | ||
| `destroy the other session's state. Wait for that session to finish ` + | ||
| `— its cleanup releases the lease — or, only if that session is ` + | ||
| `gone, delete ${reviewLeasePath(process.cwd(), leaseTarget)} and ` + | ||
| `re-run.`, | ||
| ); | ||
| } | ||
|
|
||
| createReviewWorktreeLease({ | ||
| sessionId: process.env['QWEN_CODE_SESSION_ID'], | ||
|
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [Suggestion] When fetch-pr fails after writing the lease, it rolls back the branch ref but not the lease — every post-lease-write failure path ( Fix: call tryRemove(() => execFileSync('git', ['branch', '-D', ref], ...));
clearReviewWorktreeLease(process.cwd(), leaseTarget);A same-session retry rewrites the lease freely, so this is safe. 中文说明[建议] fetch-pr 在写入租约之后失败时只回滚分支引用、不回滚租约——写租约之后的所有失败路径( 修复:在写租约之后的失败路径上调用 — qwen3.8-max via Qwen Code /review (v0.21.11) |
||
| promptId: process.env['QWEN_CODE_PROMPT_ID'], | ||
| target: `pr-${prNumber}`, | ||
| target: leaseTarget, | ||
| repositoryRoot: process.cwd(), | ||
| worktreePath: wt, | ||
| branch: ref, | ||
|
|
@@ -205,6 +234,10 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> { | |
| try { | ||
| git('fetch', remote, `pull/${prNumber}/head:${ref}`); | ||
| } catch (err) { | ||
| // Roll back the lease too: the lock above refuses any later session that | ||
| // finds another session's lease, so one left behind by a handled failure | ||
| // would block every later review of this PR until deleted by hand. | ||
| clearReviewWorktreeLease(process.cwd(), leaseTarget); | ||
| throw new Error( | ||
| `Failed to fetch PR #${prNumber} from remote "${remote}": ${(err as Error).message}`, | ||
| ); | ||
|
|
@@ -226,10 +259,11 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> { | |
| ); | ||
| meta = JSON.parse(json) as PrMetadata; | ||
| } catch (err) { | ||
| // Roll back the fetched ref so the next run starts clean. | ||
| // Roll back the fetched ref and the lease so the next run starts clean. | ||
| tryRemove(() => | ||
| execFileSync('git', ['branch', '-D', ref], { stdio: 'pipe' }), | ||
| ); | ||
| clearReviewWorktreeLease(process.cwd(), leaseTarget); | ||
| throw new Error( | ||
| `Failed to fetch PR #${prNumber} metadata: ${(err as Error).message}`, | ||
| ); | ||
|
|
@@ -243,6 +277,7 @@ async function runFetchPr(args: FetchPrArgs): Promise<void> { | |
| tryRemove(() => | ||
| execFileSync('git', ['branch', '-D', ref], { stdio: 'pipe' }), | ||
| ); | ||
| clearReviewWorktreeLease(process.cwd(), leaseTarget); | ||
| throw new Error( | ||
| `Failed to create worktree at ${wt}: ${(err as Error).message}`, | ||
| ); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[Suggestion] Neither lock test verifies which lease target the command reads —
mockReturnValueOnceis argument-blind, so the lock's target wiring is untested. The same shape exists incleanup.test.ts's skip test (readReviewWorktreeLeaseis never argument-asserted there either). — Failure scenario: probe-verified surviving mutant —readReviewWorktreeLease(process.cwd(), leaseTarget)→readReviewWorktreeLease(process.cwd(), 'pr-999')keeps 38/38 fetch-pr tests and 29/29 cleanup tests green; the'qwen-review-lease-pr-42.json'assertion only pins the target passed toreviewLeasePathfor the error message (a separate call). In production the lock consults an unrelated PR's lease file, the same-PR race goes undetected, and the concurrent same-PR worktree destruction recurs.Witness:
Fix: assert the wiring in both suites:
中文说明
[建议] 两个锁测试都没有验证命令读取的是哪个租约目标——
mockReturnValueOnce对参数不敏感,因此锁的目标接线未被测试。cleanup.test.ts的跳过测试存在同样的形态(那里的readReviewWorktreeLease同样从未被参数断言)。— 失败场景:经探针验证的存活变异体——readReviewWorktreeLease(process.cwd(), leaseTarget)→readReviewWorktreeLease(process.cwd(), 'pr-999')仍使 fetch-pr 38/38、cleanup 29/29 测试全绿;'qwen-review-lease-pr-42.json'断言只钉住了传给reviewLeasePath用于报错文案的目标(另一次调用)。在生产中锁会去查一个无关 PR 的租约文件,同 PR 竞态无法被检测到,并发同 PR 审查互相删除 worktree 的问题会复现。证据:'pr-999' 变异体下
Tests 38 passed (38)(存活);加上下方断言后AssertionError: expected "spy" to be called with arguments ... - "pr-42", + "pr-999"(被杀)。修复:在两个测试套件中断言接线(fetch-pr 用 'pr-42',cleanup 用 'pr-123')。
— qwen3.8-max via Qwen Code /review (v0.21.11)