From 300e67bcef9e3a5ddcd8ae9530290f9054994e08 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sun, 29 Nov 2026 02:17:32 +0800 Subject: [PATCH] Re-confirm a proof writer's stop after close cancels pending work stopProofWriter asked stopForFreeze once. When an interrupted turn left a host callback pending, the answer was turn-not-settled; the function then closed the session, which cancels the callback and stops the process, but threw math_writer_stop_unconfirmed anyway and failed the whole run. A balance-7 research run hit this: the Lead's native followup_task to an idle member blocked while the host prepared that member's workspace, the soft-slice wait-limit interrupted the Lead turn, and the still-pending followup callback made the freeze unconfirmed. stopProofWriter now persists the quarantine first as before, closes, and asks stopForFreeze again. If the writer is confirmed stopped it clears the quarantine and emits proof_ready_freeze_confirmed / team_writer_stop_confirmed; otherwise, or if close fails, it keeps the quarantine and throws as before. Co-Authored-By: Claude Opus 5.5 --- src/solver/agentTeam.ts | 6 ++- src/solver/proofWriter.ts | 23 ++++++++-- src/solver/research.ts | 9 ++-- tests/codexSessionAgentControl.test.ts | 17 ++++++++ tests/proofWriter.test.ts | 60 ++++++++++++++++++++++++++ 5 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 tests/proofWriter.test.ts diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index f253ed0b..85b6fecd 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -502,7 +502,8 @@ export class AgentResearchTeam { if (!session) return; await stopProofWriter({ session, record: worker, workerId: worker.id, close: async () => { await session.close(); this.nativeIdle.delete(worker.id); }, save: () => this.input.save(), - deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }) }); + deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }), + confirmed: reason => this.input.emit('team_writer_stop_confirmed', { workerId: worker.id, reason }) }); this.nativeControl.writerStopped(worker.id); worker.writerProcess = undefined; this.input.save(); } @@ -984,7 +985,8 @@ export class AgentResearchTeam { if (signal.aborted && !closingSession) await current.interrupt().catch(() => {}); await stopProofWriter({ session: current, record: worker, workerId: worker.id, close: async () => { await closeSession(current); entry.session = undefined; usage.sessionClosed(sessionId); }, - save: () => this.input.save(), deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }) }); + save: () => this.input.save(), deferred: reason => this.input.emit('team_writer_stop_deferred', { workerId: worker.id, reason }), + confirmed: reason => this.input.emit('team_writer_stop_confirmed', { workerId: worker.id, reason }) }); this.nativeControl.writerStopped(worker.id); worker.writerProcess = undefined; } diff --git a/src/solver/proofWriter.ts b/src/solver/proofWriter.ts index 1559c956..53a2f60a 100644 --- a/src/solver/proofWriter.ts +++ b/src/solver/proofWriter.ts @@ -17,17 +17,32 @@ export async function stopProofWriter(input: { close: () => Promise; save: () => void; deferred: (reason: string) => void; + /** The writer was confirmed stopped only after `close` cancelled its pending work. */ + confirmed?: (reason: string) => void; }): Promise { - let stopped: Awaited>> | undefined; - try { stopped = await input.session.stopForFreeze?.(); } - catch { stopped = { status: 'unconfirmed', reason: 'shutdown-failed' }; } + const stopped = await confirmStopped(input.session); if (stopped?.status !== 'stopped') { const reason = stopped?.reason ?? 'writer-stop-confirmation-unavailable'; + // Persist the quarantine before closing, so a crash during shutdown cannot reuse a live writer. input.record.writerStopUnconfirmed = { at: Date.now(), reason }; input.deferred(reason); input.save(); - try { await input.close(); } catch { /* Persisted quarantine controls subsequent reuse. */ } + let closed = true; + try { await input.close(); } catch { closed = false; /* Persisted quarantine controls subsequent reuse. */ } + // An interrupted turn can leave host callbacks pending. Closing cancels them and + // stops the process, so ask again instead of failing a writer that has stopped. + if (closed && (await confirmStopped(input.session))?.status === 'stopped') { + input.record.writerStopUnconfirmed = undefined; + input.save(); + input.confirmed?.(reason); + return; + } throw new Error('math_writer_stop_unconfirmed:' + input.workerId + ':' + reason); } await input.close(); } + +async function confirmStopped(session: MathAgentSession) { + try { return await session.stopForFreeze?.(); } + catch { return { status: 'unconfirmed', reason: 'shutdown-failed' } as const; } +} diff --git a/src/solver/research.ts b/src/solver/research.ts index b0793245..86bd502f 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -777,7 +777,8 @@ export async function runResearchLead(input: { // The planner's response never becomes a proof candidate. Stop its process before // pausing the execution clock and wait in the host, outside any model turn. await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, close, save, - deferred: reason => emit('proof_ready_freeze_deferred', { reason }) }); + deferred: reason => emit('proof_ready_freeze_deferred', { reason }), + confirmed: reason => emit('proof_ready_freeze_confirmed', { reason }) }); team.leadWriterStopped(); state.writerProcess = undefined; save(); if (planApprovalStatus(state) === 'pending') { retries = 0; @@ -795,7 +796,8 @@ export async function runResearchLead(input: { if (request) { if (skillMode) { await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, - close, save, deferred: reason => emit('proof_ready_freeze_deferred', { reason }) }); + close, save, deferred: reason => emit('proof_ready_freeze_deferred', { reason }), + confirmed: reason => emit('proof_ready_freeze_confirmed', { reason }) }); if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } } else await close(); @@ -814,7 +816,8 @@ export async function runResearchLead(input: { // The runtime has settled the turn and stopped new requests. Reap all remaining // writer processes before the ordinary source freeze and independent host check. await stopProofWriter({ session: turnSession, record: research, workerId: worker.id, close, save, - deferred: reason => emit('proof_ready_freeze_deferred', { ...singleSubmission, reason }) }); + deferred: reason => emit('proof_ready_freeze_deferred', { ...singleSubmission, reason }), + confirmed: reason => emit('proof_ready_freeze_confirmed', { ...singleSubmission, reason }) }); if (team) { team.leadWriterStopped(); state.writerProcess = undefined; save(); } access.assertHarnessCurrent?.(); if (access.researchSkill) assertMathAgentSkillsCurrent([access.researchSkill]); diff --git a/tests/codexSessionAgentControl.test.ts b/tests/codexSessionAgentControl.test.ts index 5db3b80d..a872db8d 100644 --- a/tests/codexSessionAgentControl.test.ts +++ b/tests/codexSessionAgentControl.test.ts @@ -8,6 +8,7 @@ import type { NativeAgentControlOptions } from '../src/runtime/nativeAgentContro import { nativeAgentControlModelCatalog } from '../src/runtime/nativeAgentControl'; import { readMathAgentSkill } from '../src/runtime/agentSkills'; import { deferred } from './helpers/async'; +import { stopProofWriter } from '../src/solver/proofWriter'; const fixture = String.raw` const fs = require('node:fs'), path = require('node:path'), readline = require('node:readline'); @@ -321,6 +322,22 @@ describe('native AgentControl stdio integration without model calls', () => { expect((await session.stopForFreeze!()).status).toBe('stopped'); }); + it('lets the proof writer freeze once shutdown cancels a host callback left by the turn', async () => { + host = { request: async (request, _connection, { signal }) => { + if (request.operation === 'recordUsage') await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })); + return { result: { sessionId: request.sessionId } }; + } }; + session = await createCodexMathSession({ ...options, nativeAgentControl: host, + environment: { ...options.environment, HOLD_HOST_CALLBACK: '1' } }); + expect(await session.run('Finish with a pending lifecycle report.', 'task', directory, () => {})).toBe('completed'); + const record: { writerStopUnconfirmed?: { at: number; reason: string } } = {}; + const events: string[] = [], current = session; + await stopProofWriter({ session: current, record, workerId: 'lead', close: () => current.close(), save: () => {}, + deferred: reason => events.push('deferred:' + reason), confirmed: reason => events.push('confirmed:' + reason) }); + expect(events).toEqual(['deferred:turn-not-settled', 'confirmed:turn-not-settled']); + expect(record.writerStopUnconfirmed).toBeUndefined(); + }); + it('waits for the native terminal handoff and guard release before reporting a completed writer', async () => { let release!: () => void, entered!: () => void; const blocked = new Promise(resolve => { release = resolve; }); diff --git a/tests/proofWriter.test.ts b/tests/proofWriter.test.ts new file mode 100644 index 00000000..785d025a --- /dev/null +++ b/tests/proofWriter.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { MathAgentSession } from '../src/runtime/agentSession'; +import { stopProofWriter } from '../src/solver/proofWriter'; + +type Stop = Awaited>>; +const unsettled: Stop = { status: 'unconfirmed', reason: 'turn-not-settled' }; + +function writer(stops: Stop[], close: () => Promise = async () => {}) { + const stopForFreeze = vi.fn(async () => stops.shift() ?? unsettled); + const record: { writerStopUnconfirmed?: { at: number; reason: string } } = {}; + const saved: (typeof record.writerStopUnconfirmed)[] = []; + const events: string[] = []; + const closeSpy = vi.fn(close); + const input = { session: { stopForFreeze } as unknown as MathAgentSession, record, workerId: 'lead', close: closeSpy, + save: () => { saved.push(record.writerStopUnconfirmed && { ...record.writerStopUnconfirmed }); }, + deferred: (reason: string) => events.push('deferred:' + reason), confirmed: (reason: string) => events.push('confirmed:' + reason) }; + return { input, record, saved, events, stopForFreeze, close: closeSpy }; +} + +describe('stopProofWriter', () => { + it('closes a settled writer once without quarantine', async () => { + const w = writer([{ status: 'stopped' }]); + await stopProofWriter(w.input); + expect(w.close).toHaveBeenCalledOnce(); + expect(w.stopForFreeze).toHaveBeenCalledOnce(); + expect(w.events).toEqual([]); + expect(w.saved).toEqual([]); + }); + + it('accepts a writer confirmed stopped after close cancels its pending work', async () => { + const w = writer([unsettled, { status: 'stopped' }]); + await stopProofWriter(w.input); + expect(w.close).toHaveBeenCalledOnce(); + expect(w.events).toEqual(['deferred:turn-not-settled', 'confirmed:turn-not-settled']); + // The quarantine is durable while shutdown runs and cleared only after confirmation. + expect(w.saved[0]).toMatchObject({ reason: 'turn-not-settled' }); + expect(w.saved.at(-1)).toBeUndefined(); + expect(w.record.writerStopUnconfirmed).toBeUndefined(); + }); + + it('keeps the quarantine when the writer is still unconfirmed after close', async () => { + const w = writer([unsettled, { status: 'unconfirmed', reason: 'shutdown-failed' }]); + await expect(stopProofWriter(w.input)).rejects.toThrow('math_writer_stop_unconfirmed:lead:turn-not-settled'); + expect(w.record.writerStopUnconfirmed).toMatchObject({ reason: 'turn-not-settled' }); + expect(w.events).toEqual(['deferred:turn-not-settled']); + }); + + it('does not trust a second answer when close itself failed', async () => { + const w = writer([unsettled, { status: 'stopped' }], async () => { throw new Error('close failed'); }); + await expect(stopProofWriter(w.input)).rejects.toThrow('math_writer_stop_unconfirmed:lead:turn-not-settled'); + expect(w.stopForFreeze).toHaveBeenCalledOnce(); + expect(w.record.writerStopUnconfirmed).toMatchObject({ reason: 'turn-not-settled' }); + }); + + it('treats a throwing confirmation as unconfirmed', async () => { + const w = writer([]); + w.stopForFreeze.mockRejectedValue(new Error('rpc closed')); + await expect(stopProofWriter(w.input)).rejects.toThrow('math_writer_stop_unconfirmed:lead:shutdown-failed'); + }); +});