Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions src/math/mathProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export type MathProcessStopReceipt = Readonly<{ status: 'stopped' } | { status:
'process-group-active' | 'process-group-unavailable' | 'process-session-active' }>;

const sessionExitTicks = new WeakMap<ChildProcess, number>();
const trackedSessions = new WeakSet<ChildProcess>();
const childExited = (child: ChildProcess) => typeof child.exitCode === 'number' || typeof child.signalCode === 'string';
const noteSessionExit = (child: ChildProcess): void => {
if (sessionExitTicks.has(child)) return;
Expand All @@ -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 };
Expand All @@ -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[];
Expand Down
3 changes: 2 additions & 1 deletion src/math/mathProofEnvironment.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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();
Expand Down
14 changes: 10 additions & 4 deletions src/solver/declarationArtifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -281,7 +282,8 @@ export function createDeclarationArtifactChecker(input: Omit<StoppedDeclarationC
async tryBatch(declarations: DeclarationSubmission['declarations']) {
try { return await check(declarations, true); }
catch (error) {
if (error instanceof DeclarationSubmissionError) return [];
// Each candidate then records its own check failure, as it did before batching.
if (error instanceof DeclarationSubmissionError || error instanceof DeclarationArtifactCheckError) return [];
throw error;
}
},
Expand Down Expand Up @@ -357,16 +359,20 @@ async function checkArtifacts(input: TeamDeclarationCheckInput, schema: typeof d
collectDeclarationReferences: true }).catch(error => {
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);
Expand Down
12 changes: 8 additions & 4 deletions src/solver/verificationCheckpoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = <T>(input: Context, run: () => Promise<T>): Promise<T> => context.run(input, run);

/** Bound the complete verification separately from solving; only the identical input gets more time on resume. */
Expand All @@ -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;
}
Expand Down
13 changes: 13 additions & 0 deletions tests/mathProcess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number>(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 });
Expand Down
40 changes: 40 additions & 0 deletions tests/singleContinuationSeed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
Expand Down
Loading