From 2420f53f111b5ea1e8c3294fcf5add9ee4ef33db Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:29:37 +0800 Subject: [PATCH] Isolate timed-out declaration batches and stop sweeping untracked sessions Since #54 a batch of same-file declarations shares one verification deadline. When the batch timed out, every attribution was blocked and the check rejected the first declaration instead of retrying in isolation. In continuation seeding, tryBatch rethrew that error and aborted the seed. A batch that only hit its deadline, or that reached a verification checkpoint, now falls back to per-declaration checks with their own deadlines. tryBatch also falls back on other batch check failures, so each candidate records its own result as before batching. Since #55, a child first tracked after it had exited got the current uptime as its exit tick. A later session that reused its pid as sid could then pass the continuity check and be SIGKILLed. Only an exit observed while tracked now bounds the session, and the detached proof-environment helper is tracked at spawn. Co-Authored-By: Claude Opus 5.5 --- src/math/mathProcess.ts | 11 +++++--- src/math/mathProofEnvironment.ts | 3 ++- src/solver/declarationArtifacts.ts | 14 +++++++--- src/solver/verificationCheckpoint.ts | 12 ++++++--- tests/mathProcess.test.ts | 13 +++++++++ tests/singleContinuationSeed.test.ts | 40 ++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 13 deletions(-) diff --git a/src/math/mathProcess.ts b/src/math/mathProcess.ts index 8b9702d7..34c7b1e9 100644 --- a/src/math/mathProcess.ts +++ b/src/math/mathProcess.ts @@ -74,6 +74,7 @@ export type MathProcessStopReceipt = Readonly<{ status: 'stopped' } | { status: 'process-group-active' | 'process-group-unavailable' | 'process-session-active' }>; const sessionExitTicks = new WeakMap(); +const trackedSessions = new WeakSet(); const childExited = (child: ChildProcess) => typeof child.exitCode === 'number' || typeof child.signalCode === 'string'; const noteSessionExit = (child: ChildProcess): void => { if (sessionExitTicks.has(child)) return; @@ -87,9 +88,11 @@ const noteSessionExit = (child: ChildProcess): void => { /** Record when an owned detached child exits so a later session sweep can prove its session id was not reused. */ export function trackMathProcessSession(child: ChildProcess): void { - if (process.platform !== 'linux' || sessionExitTicks.has(child)) return; - if (childExited(child)) noteSessionExit(child); - else if (typeof child.once === 'function') child.once('exit', () => noteSessionExit(child)); + if (process.platform !== 'linux' || trackedSessions.has(child)) return; + trackedSessions.add(child); + // A child that already exited has no observed exit time: reading the clock now would admit + // any process started since, including members of an unrelated session that reused the sid. + if (!childExited(child) && typeof child.once === 'function') child.once('exit', () => noteSessionExit(child)); } type SessionMember = { pid: number; start: string }; @@ -111,7 +114,7 @@ function leakedSessionMembers(child: ChildProcess): SessionMember[] { // A live /proc entry is a recycled pid, except our own leader before the runtime reaps it. const leader = readSessionMember(String(sid), sid); if (leader ? leader.state !== 'Z' || leader.ppid !== process.pid : fs.existsSync(`/proc/${sid}`)) return []; - noteSessionExit(child); + // Only an exit observed while tracked bounds the session; untracked children are not swept. const exitTicks = sessionExitTicks.get(child); if (exitTicks === undefined) return []; let entries: string[]; diff --git a/src/math/mathProofEnvironment.ts b/src/math/mathProofEnvironment.ts index de405ba7..67d4d897 100644 --- a/src/math/mathProofEnvironment.ts +++ b/src/math/mathProofEnvironment.ts @@ -1,5 +1,5 @@ import fs from 'node:fs'; -import { closeMathProcess } from './mathProcess'; +import { closeMathProcess, trackMathProcessSession } from './mathProcess'; import path from 'node:path'; import crypto from 'node:crypto'; import net from 'node:net'; @@ -465,6 +465,7 @@ async function prepareEnvironment( stdio: ['pipe', 'pipe', 'pipe'], } ); + trackMathProcessSession(child); // Heartbeats keep long image builds visible; stdout keeps draining shutdown diagnostics without retaining them. const heartbeat = setInterval(() => report(imagePhase, { cacheHit: Boolean(cached) }), 5000); child.stderr.resume(); diff --git a/src/solver/declarationArtifacts.ts b/src/solver/declarationArtifacts.ts index 0e89dcf5..26b0c344 100644 --- a/src/solver/declarationArtifacts.ts +++ b/src/solver/declarationArtifacts.ts @@ -14,6 +14,7 @@ import { captureProofReferences, type ProofReferences } from './proofReferences' import { hasDeterministicLeanFailure, hasLeanResourceLimitFailure, proofReuseEnvironment } from './proofReuse'; import { allowedKnowledgeFile, locateKnowledgeDeclaration } from './theoremKnowledge'; import type { CooperativeTask } from './tasks'; +import { verificationDeadlineExpired, VerificationCheckpointError } from './verificationCheckpoint'; /** A research request is advisory. Only the host's stopped-writer check publishes evidence. */ export const DECLARATION_SUBMISSION_FILE = 'declaration-submission.json'; @@ -281,7 +282,8 @@ export function createDeclarationArtifactChecker(input: Omit { if (error instanceof Error && error.message === 'math_declaration_artifact_declaration_missing') throw new DeclarationSubmissionError(error.message, { cause: error }); + // A batch shares one deadline. Each declaration gets its own deadline in isolation. + if (batched && error instanceof VerificationCheckpointError) return undefined; throw error; }); + if (!result) return; if (!result.passed) { if (!batched) throw new DeclarationArtifactCheckError(first, result.verification); const index = result.attributions.findIndex(item => !item.passed); const failure = result.attributions[index]!; - // A shared file can fail because of an unrelated draft declaration. Retry in isolation - // and keep the per-declaration diagnostic. Operational failures still stop the check. + // A shared file can fail because of an unrelated draft declaration, and a batch shares + // one deadline. Retry in isolation and keep the per-declaration diagnostic. + // Other operational failures still stop the check. if (failure.verification.status === 'failed' && (hasDeterministicLeanFailure(result.verification) || - hasLeanResourceLimitFailure(result.verification))) return; + hasLeanResourceLimitFailure(result.verification)) || verificationDeadlineExpired(result.verification)) return; throw new DeclarationArtifactCheckError(group[index]!, failure.verification); } const sourceDigest = snapshot.sourceDigest ??= ownedSourceDigest(problem, worktree, commit); diff --git a/src/solver/verificationCheckpoint.ts b/src/solver/verificationCheckpoint.ts index 18af8f8d..3cb06a4c 100644 --- a/src/solver/verificationCheckpoint.ts +++ b/src/solver/verificationCheckpoint.ts @@ -16,6 +16,13 @@ export class VerificationCheckpointError extends Error { constructor(readonly checkpoint: VerificationCheckpoint) { super('math_verification_checkpoint'); } } +/** Only the verification deadline expired; unconfirmed process cleanup keeps the infrastructure failure path. */ +export function verificationDeadlineExpired(result: MathematicsVerifierBatchResult): boolean { + return result.results.some(receipt => receipt.status === 'blocked' && + /^(?:Lean verification timed out\.|Formal verification batch deadline exceeded\.?)$/u.test(receipt.error ?? '')) && + !result.results.some(receipt => receipt.cleanupError || receipt.status === 'unavailable'); +} + export const withVerificationCheckpoints = (input: Context, run: () => Promise): Promise => context.run(input, run); /** Bound the complete verification separately from solving; only the identical input gets more time on resume. */ @@ -38,14 +45,11 @@ export async function checkpointVerification(request: MathematicsVerifierBatchRe let result: MathematicsVerifierBatchResult; try { result = await verify({ ...request, timeoutMs, batchTimeoutMs: Math.min(request.batchTimeoutMs ?? Infinity, timeoutMs) }); } finally { clearInterval(heartbeat); } - const expired = result.results.some(receipt => receipt.status === 'blocked' && - /^(?:Lean verification timed out\.|Formal verification batch deadline exceeded\.?)$/u.test(receipt.error ?? '')); const diagnostics = result.results.filter(receipt => receipt.status !== 'kernel_verified').slice(0, 8).map(receipt => ({ receiptId: receipt.receiptId, status: receipt.status, error: receipt.error?.slice(0, 1024), stderrPreview: receipt.stderrPreview?.slice(0, 1024), cleanupError: receipt.cleanupError?.slice(0, 1024), })); - // Unconfirmed process cleanup must keep the existing infrastructure failure path. - if (!expired || result.results.some(receipt => receipt.cleanupError || receipt.status === 'unavailable')) { + if (!verificationDeadlineExpired(result)) { current.emit('verification_finished', { ...details, status: result.status, elapsedMs: Date.now() - startedAt, diagnostics }); return result; } diff --git a/tests/mathProcess.test.ts b/tests/mathProcess.test.ts index 6d5f4dc7..2cdf748b 100644 --- a/tests/mathProcess.test.ts +++ b/tests/mathProcess.test.ts @@ -122,6 +122,19 @@ describe('process lifecycle and bounded output', () => { } finally { try { process.kill(pid, 'SIGKILL'); } catch { /* reaped */ } } }); + it.skipIf(process.platform !== 'linux')('does not sweep a session first tracked after its leader exited', async () => { + // Without an observed exit time, a live member may belong to a later session that reused the sid. + const child = spawn('/bin/bash', ['-c', 'set -m; sleep 30 >/dev/null 2>&1 & echo $!; exit 0'], + { detached: true, stdio: ['ignore', 'pipe', 'ignore'] }); + const pid = await new Promise(resolve => child.stdout!.once('data', chunk => resolve(Number(String(chunk).trim())))); + try { + await new Promise(resolve => child.once('close', resolve)); + expect(alive(pid)).toBe(true); + expect(await confirmMathProcessStopped(child, 0)).toEqual({ status: 'stopped' }); + expect(alive(pid)).toBe(true); + } finally { try { process.kill(pid, 'SIGKILL'); } catch { /* reaped */ } } + }); + it('does not report a missing executable as started', async () => { const result = await runMathProcess('/nonexistent/math-command', [], { cwd: os.tmpdir(), timeoutMs: 1000 }); expect(result).toMatchObject({ started: false, errorCode: 'ENOENT', timedOut: false }); diff --git a/tests/singleContinuationSeed.test.ts b/tests/singleContinuationSeed.test.ts index ee71f559..98c2b58b 100644 --- a/tests/singleContinuationSeed.test.ts +++ b/tests/singleContinuationSeed.test.ts @@ -12,6 +12,7 @@ import { freezeContinuationInput, readContinuationContents, readContinuationPage import { readDeclarationArtifacts } from '../src/solver/declarationArtifacts'; import { committedSource, commitSolverSources, git } from '../src/solver/problem'; import { taskVersion, type CooperativeTask } from '../src/solver/tasks'; +import { withVerificationCheckpoints } from '../src/solver/verificationCheckpoint'; import { localExample, solverState } from './helpers/solver'; import { failedBatch, receiptBatch } from './helpers/verifier'; import { readMathAgentSkill } from '../src/runtime/codexSkills'; @@ -150,6 +151,45 @@ describe('single researcher continuation', () => { expect(fs.readFileSync(path.join(f.worktree, f.problem.projectRelative, 'Submission.lean'), 'utf8')).toBe(source); }); + it('retries helpers one at a time when their shared batch exceeds the verification deadline', async () => { + const f = fixture(); addHistoricalHelper(f, 'other_helper'); + host.verify.mockImplementationOnce((request: MathematicsVerifierBatchRequest) => { + const batch = receiptBatch(request, { sessionId: 'slow-check', receiptId: index => `slow-${index}` }); + return { ...batch, status: 'blocked', results: batch.results.map(result => + ({ ...result, status: 'blocked', error: 'Formal verification batch deadline exceeded.' })) }; + }); + expect(await f.seed()).toMatchObject({ stage: 'complete', checked: ['other_helper', 'saved'], failed: [] }); + expect(host.verify.mock.calls.map(([request]) => request.items.map(item => item.theoremName))) + .toEqual([['Tutorial.other_helper', 'Tutorial.saved_helper'], ['Tutorial.other_helper'], ['Tutorial.saved_helper']]); + }); + + it('retries helpers one at a time when their shared batch reaches a verification checkpoint', async () => { + const f = fixture(); addHistoricalHelper(f, 'other_helper'); + host.verify.mockImplementationOnce((request: MathematicsVerifierBatchRequest) => { + const batch = receiptBatch(request, { sessionId: 'slow-check', receiptId: index => `slow-${index}` }); + return { ...batch, status: 'blocked', results: batch.results.map(result => + ({ ...result, status: 'blocked', error: 'Lean verification timed out.' })) }; + }); + const events: string[] = []; + const report = await withVerificationCheckpoints({ environmentDigest: mathDigest('env'), problemReceiptDigest: mathDigest('problem'), + checkpoints: [], save: () => {}, emit: event => { events.push(event); } }, + () => seedSingleSolverContinuation({ ...f.options, timeoutMs: 60_000 })); + expect(report).toMatchObject({ stage: 'complete', checked: ['other_helper', 'saved'], failed: [] }); + expect(events.filter(event => event === 'verification_checkpoint')).toHaveLength(1); + expect(host.verify).toHaveBeenCalledTimes(3); + }); + + it('records each helper failure when an operational batch failure repeats in isolation', async () => { + const f = fixture(); addHistoricalHelper(f, 'other_helper'); + host.verify.mockImplementation((request: MathematicsVerifierBatchRequest) => { + const batch = receiptBatch(request, { sessionId: 'down', receiptId: index => `down-${index}` }); + return { ...batch, status: 'blocked', results: batch.results.map(result => + ({ ...result, status: 'blocked', error: 'Lean worker crashed.' })) }; + }); + expect(await f.seed()).toMatchObject({ stage: 'complete', checked: [], failed: ['other_helper', 'saved'] }); + expect(host.verify).toHaveBeenCalledTimes(3); + }); + it('does not reinterpret a historical conditional helper as an unconditional candidate', async () => { const f = fixture(); f.archived.cooperation!.tasks[0].integratedCheck!.conditions = [{ taskId: 'condition', taskDigest: mathDigest('condition') }]; writeSolverRunState(f.sourceStateFile, f.archived);