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
2 changes: 1 addition & 1 deletion scripts/mathematics/runNativeSkillBaseline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ export async function runNativeSkillBaseline(argv: string[]): Promise<number> {
emit('proof_check_started');
check = await checkSolverProof(problem, worktree, prepared.environment, lease.signal, undefined, Infinity);
emit('proof_checked', { commit: check.commit, passed: check.passed });
if (check.passed) evaluation = await evaluateSolverProof(problem, worktree, check, prepared.environment,
if (check.passed) evaluation = await evaluateSolverProof(problem, check, prepared.environment,
lease.signal, { timeoutMs: Infinity });
} catch (cause) {
error = cause instanceof Error && /^math_/u.test(cause.message) ? cause.message : 'native_comparison_verifier_unavailable';
Expand Down
2 changes: 1 addition & 1 deletion scripts/test-codex-backend-delivery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ export async function verifyNativeProofDelivery(input: { repository: string; exe
assert.ok(state.agentTeam!.leadExposures?.some(exposure => exposure.kind === 'inspected' && exposure.deliveryId === reference.id));
assert.ok(state.agentTeam!.leadExposures?.some(exposure => exposure.kind === 'adopted' && exposure.deliveryId === reference.id));
assert.equal(git(receipt.workspaceRoot, ['rev-parse', 'HEAD']), problem.baseCommit, 'Research must not publish into the original workspace.');
const evaluation = await evaluateSolverProof(problem, worktree, winner.check, environment, signal,
const evaluation = await evaluateSolverProof(problem, winner.check, environment, signal,
{ timeoutMs: Infinity, teamContributions: true });
assert.equal(evaluation.status, 'passed');
const contributions = buildAgentTeamContributions(state, evaluation);
Expand Down
13 changes: 9 additions & 4 deletions src/runtime/executionDeadline.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { scheduleMathTimeout } from '../math/mathTimers';

/** A finite execution allowance that excludes time explicitly spent waiting for a person. */
export class ExecutionDeadline {
private timer?: ReturnType<typeof setTimeout>;
private cancelTimer?: () => void;
private activeSince = Date.now();
private usedMs = 0;
private waitedMs = 0;
Expand All @@ -19,7 +21,7 @@ export class ExecutionDeadline {
const now = Date.now();
if (waiting) {
this.usedMs = this.executionMs();
clearTimeout(this.timer);
this.cancelTimer?.();
// A late pause must not revive an execution allowance that already ran out.
if (this.usedMs >= this.limitMs) { this.stopped = true; this.expire(); return; }
this.waitingSince = now;
Expand All @@ -37,10 +39,13 @@ export class ExecutionDeadline {
this.waitedMs = this.waitingMs();
this.waitingSince = undefined;
this.stopped = true;
clearTimeout(this.timer);
this.cancelTimer?.();
}

private arm() {
if (Number.isFinite(this.limitMs)) this.timer = setTimeout(() => { this.stop(); this.expire(); }, this.remainingMs());
this.cancelTimer = scheduleMathTimeout(() => {
this.stop();
this.expire();
}, this.remainingMs());
}
}
28 changes: 18 additions & 10 deletions src/solver/cooperationCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,17 +406,25 @@ export abstract class CooperationCore {
...proposedDefinitionContractChecks(this.archive, identity, now)]) {
const previous = this.archive.nextChecks?.find(record => record.id === proposed.record.id);
if (previous) {
// A pause or removed downstream path can expire an unfinished definition check.
// When that exact question becomes relevant again, resume its one existing record.
if (previous.origin === 'definition-contract' && previous.status === 'stale' && !previous.outcome) {
const node = this.archive.tasks.find(item => item.nextCheckId === previous.id);
if (currentNextCheck({ ...previous, status: 'pending' }, this.archive, identity)) {
previous.status = 'pending';
if (node) { node.task = { ...node.task, status: 'active' }; this.moveTask(node, 'pending', 'reopened'); }
else this.archive.tasks.push(proposed.node);
this.input.emit('next_check_resumed', { checkId: previous.id, taskId: previous.taskId });
}
if (previous.status !== 'stale' || previous.outcome) continue;
const nodeIndex = this.archive.tasks.findIndex(item => item.nextCheckId === previous.id);
if (previous.origin === 'definition-contract') {
// An unfinished definition check can resume when the same question becomes relevant again.
if (!currentNextCheck({ ...previous, status: 'pending' }, this.archive, identity)) continue;
previous.status = 'pending';
const node = this.archive.tasks[nodeIndex];
if (node) { node.task = { ...node.task, status: 'active' }; this.moveTask(node, 'pending', 'reopened'); }
else this.archive.tasks.push(proposed.node);
} else {
// A republished gap needs a current delivery and a fresh assignment.
const { record, node } = proposed;
if (record.gapDeliveryId === previous.gapDeliveryId || !currentNextCheck(record, this.archive, identity)) continue;
Object.assign(previous, { status: 'pending', gapDeliveryId: record.gapDeliveryId, scope: record.scope,
check: record.check, proofSearchSeed: record.proofSearchSeed });
if (nodeIndex < 0) this.archive.tasks.push(node);
else this.archive.tasks[nodeIndex] = { ...node, attempts: this.archive.tasks[nodeIndex].attempts };
}
this.input.emit('next_check_resumed', { checkId: previous.id, taskId: previous.taskId });
continue;
}
// A model task cannot take ownership of the host's deterministic check id.
Expand Down
14 changes: 9 additions & 5 deletions src/solver/evaluation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { MATH_PROOF_ENVIRONMENT_ENV } from '../math/mathProofEnvironment';
import { runMathematicsSandboxedCommand, type MathematicsSandboxCommandResult } from '../math/verifier';
import { runPersistedLeanEvalOfficialGate } from '../math/leanEvalBootstrap';
import { checkSolverProof, type ProofCheck } from './modules/evidence';
import { git, type SolverProblem } from './problem';
import { git, withSolverWorktree, type SolverProblem } from './problem';

/** Execution failures cannot decide whether a mathematical submission is correct. */
export function evaluatorExecutionFailure(result: Pick<MathematicsSandboxCommandResult,
Expand All @@ -24,7 +24,7 @@ export function evaluatorExecutionFailure(result: Pick<MathematicsSandboxCommand
}

/** S3: final acceptance stays independent of replaceable research modules. */
export async function evaluateSolverProof(problem: SolverProblem, worktree: string, receipt: ProofCheck,
export async function evaluateSolverProof(problem: SolverProblem, receipt: ProofCheck,
env: NodeJS.ProcessEnv, signal: AbortSignal, options: { command?: string; timeoutMs: number; teamContributions?: boolean }): Promise<Record<string, unknown>> {
const deadline = Date.now() + options.timeoutMs;
const controller = new AbortController();
Expand Down Expand Up @@ -54,9 +54,13 @@ export async function evaluateSolverProof(problem: SolverProblem, worktree: stri
assertActive();
if (!finalCheck.passed || finalCheck.commit !== receipt.commit || finalCheck.sourceDigest !== receipt.sourceDigest)
throw new Error('math_integrated_proof_mismatch');
if (options.command) {
const result = await runMathematicsSandboxedCommand({ checkoutRoot: worktree, projectRelative: problem.projectRelative,
command: '/bin/sh', args: ['-c', options.command], timeoutMs: options.timeoutMs, env, signal: evaluationSignal });
const command = options.command;
if (command) {
const result = await withSolverWorktree(problem.workspace, finalCheck.commit, checkoutRoot => {
assertActive();
return runMathematicsSandboxedCommand({ checkoutRoot, projectRelative: problem.projectRelative,
command: '/bin/sh', args: ['-c', command], timeoutMs: options.timeoutMs, env, signal: evaluationSignal });
});
assertActive();
const reason = evaluatorExecutionFailure(result);
return { status: reason ? 'error' : result.exitCode === 0 ? 'passed' : 'failed',
Expand Down
14 changes: 6 additions & 8 deletions src/solver/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { VerificationCheckpointError, withVerificationCheckpoints } from './veri
import { parseArgs } from 'node:util';
import { readMathBuildManifest } from '../math/mathBuildManifest';
import { MathGitError } from '../math/mathGit';
import { scheduleMathTimeout } from '../math/mathTimers';
import { canonicalMathJson, mathDigest, readMathJson, readMathText, withMathRuntimeLease, writeMathJsonDurable, type MathLease } from '../math/mathRuntimeIo';
import { projectMathematicsRuntimeEnvironment, resolveMathematicsRuntimeEnvironment } from '../math/mathRuntimeEnvironment';
import { checkResolvedLeanToolchainReadiness } from '../math/leanToolchainReadiness';
Expand Down Expand Up @@ -248,7 +249,7 @@ export async function runSolver(args: string[], root: string, customModules?: So
let preparing = true;
let deadline = Infinity;
let executionClock: ExecutionDeadline | undefined;
let timer: ReturnType<typeof setTimeout> | undefined = Number.isFinite(preparationMs) ? setTimeout(abort, preparationMs) : undefined;
const cancelPreparation = scheduleMathTimeout(abort, preparationMs);
let ownedState: SolverRunState | undefined;
let proofEnvironment: Awaited<ReturnType<typeof prepareMathProofEnvironment>> | undefined;
let continuationSeeding = false;
Expand Down Expand Up @@ -371,7 +372,7 @@ export async function runSolver(args: string[], root: string, customModules?: So
}
return;
}
clearTimeout(timer); timer = undefined;
cancelPreparation();
try {
await disposeProofEnvironment();
await generateSolverExplanations({ problem: state.problem, worktree, directory, root, buildManifest: buildFile,
Expand Down Expand Up @@ -685,13 +686,12 @@ export async function runSolver(args: string[], root: string, customModules?: So
return 0;
}
signal.throwIfAborted();
clearTimeout(timer);
cancelPreparation();
preparing = false;
state.solveStartedAt = Date.now();
state.solveFinishedAt = undefined;
state.solveWaitingMs = 0;
deadline = state.solveStartedAt + maxRunMs;
timer = undefined;
executionClock = new ExecutionDeadline(maxRunMs, abort);
const executionBudget = {
remainingMs: () => executionClock!.remainingMs(),
Expand All @@ -716,8 +716,6 @@ export async function runSolver(args: string[], root: string, customModules?: So
profile,
signal, deadline, executionBudget, maxTurns, maxTurnMs, maxTotalTokens, proofTimeoutMs,
freshContinuationChecks, prepareTeamWorker, save, emit }));
clearTimeout(timer);
timer = undefined;
executionClock.stop();
state.solveWaitingMs = executionClock.waitingMs();
state.solveFinishedAt = Date.now();
Expand All @@ -727,7 +725,7 @@ export async function runSolver(args: string[], root: string, customModules?: So
readMathBuildManifest(buildFile, root, bundleRoot);
const evaluationStarted = Date.now();
emit('evaluation_started', { workerId: state.winningWorker ?? 'solver' });
evaluation = await evaluateSolverProof(state.problem, winner.worktree, winner.check, env, signal,
evaluation = await evaluateSolverProof(state.problem, winner.check, env, signal,
{ command: values['evaluator-command'], timeoutMs: evaluatorMs,
teamContributions: state.agentTeam?.transport === 'native-agent-control' && state.agentTeam.deliveries.length > 0 });
emit('evaluation_finished', { status: evaluation.status, durationMs: Date.now() - evaluationStarted });
Expand Down Expand Up @@ -799,7 +797,7 @@ export async function runSolver(args: string[], root: string, customModules?: So
return controller.signal.aborted ? 4 : 1;
} finally {
executionClock?.stop();
clearTimeout(timer);
cancelPreparation();
hostSignal?.removeEventListener('abort', hostAbort);
process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort);
}
Expand Down
21 changes: 20 additions & 1 deletion tests/agentTeamProof.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,25 @@ describe('agent-owned declaration deliveries with real Lean', () => {
expect(f.state.check).toBeUndefined();
}, 90_000);

it('evaluates the checked commit even if the worker keeps editing afterward', async () => {
const f = fixture();
const verifiedSource = original.replaceAll('by sorry', 'by trivial');
fs.writeFileSync(f.source(f.worktree), verifiedSource);
const checked = await checkSolverProof(f.problem, f.worktree, f.common.env, f.common.signal);
expect(checked.passed).toBe(true);
const laterSource = verifiedSource.replaceAll('by trivial', 'by exact True.intro');
fs.writeFileSync(f.source(f.worktree), laterSource);

const evaluation = await evaluateSolverProof(f.problem, checked, f.common.env, f.common.signal, {
command: "grep -qFx 'theorem original : True := by trivial' Submission.lean",
timeoutMs: 30_000,
});

expect(evaluation).toMatchObject({ status: 'passed', method: 'external-command', result: { exitCode: 0 } });
expect(git(f.problem.workspace, ['rev-parse', 'HEAD'])).toBe(checked.commit);
expect(fs.readFileSync(f.source(f.worktree), 'utf8')).toBe(laterSource);
}, 30_000);

it('matches versions and separates final direct, transitive, absent and unknown references', async () => {
const f = fixture(), problem = f.problem, lead = path.join(f.directory, 'runtime/worktree');
git(problem.workspace, ['worktree', 'add', '--quiet', '--detach', lead, problem.baseCommit]);
Expand All @@ -177,7 +196,7 @@ describe('agent-owned declaration deliveries with real Lean', () => {
fs.writeFileSync(f.source(lead), edited);
state.check = await checkSolverProof(problem, lead, f.common.env, f.common.signal);
expect(state.check.passed).toBe(true);
const evaluation = await evaluateSolverProof(problem, lead, state.check, f.common.env, f.common.signal, { timeoutMs: 30_000, teamContributions: true });
const evaluation = await evaluateSolverProof(problem, state.check, f.common.env, f.common.signal, { timeoutMs: 30_000, teamContributions: true });
expect(evaluation.status).toBe('passed');
const report = buildAgentTeamContributions(state, evaluation), relations = (r: typeof report) =>
Object.fromEntries(r.declarations.map(d => [d.name, d.targets.map(t => t.relation)]));
Expand Down
2 changes: 1 addition & 1 deletion tests/agentTeamSolver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ describe.skipIf(process.platform !== 'linux')('Agent team through native tool RP
expect(source).toContain('exact combined n'); expect(source).not.toContain('sorry');
expect(git(receipt.workspaceRoot, ['rev-parse', 'HEAD'])).toBe(problem.baseCommit);

const evaluation = await evaluateSolverProof(problem, winner!.worktree, winner!.check,
const evaluation = await evaluateSolverProof(problem, winner!.check,
environment, controller.signal, { timeoutMs: 30_000 });
expect(evaluation).toMatchObject({ status: 'passed', method: 'host-lean-kernel-all-targets',
verification: { passed: true, commit: winner!.check.commit, verification: { status: 'kernel_verified' } } });
Expand Down
7 changes: 4 additions & 3 deletions tests/evaluatorExecution.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import type { SolverProblem } from '../src/solver/problem';
const host = vi.hoisted(() => ({ run: vi.fn(), check: vi.fn(), git: vi.fn(), official: vi.fn() }));
vi.mock('../src/math/verifier', () => ({ runMathematicsSandboxedCommand: host.run }));
vi.mock('../src/solver/modules/evidence', () => ({ checkSolverProof: host.check }));
vi.mock('../src/solver/problem', () => ({ git: host.git }));
vi.mock('../src/solver/problem', () => ({ git: host.git,
withSolverWorktree: (_workspace: string, _commit: string, run: (checkout: string) => Promise<unknown>) => run('/fixture/snapshot') }));
vi.mock('../src/math/leanEvalBootstrap', () => ({ runPersistedLeanEvalOfficialGate: host.official }));

const commandResult = (changes: Partial<MathematicsSandboxCommandResult> = {}): MathematicsSandboxCommandResult => ({
Expand All @@ -16,7 +17,7 @@ const commandResult = (changes: Partial<MathematicsSandboxCommandResult> = {}):
});
const receipt = { passed: true, commit: 'candidate', sourceDigest: 'source', verification: {} } as ProofCheck;
const problem = { kind: 'lean-task', workspace: '/fixture/main', projectRelative: 'generated/problem', baseCommit: 'base' } as SolverProblem;
const evaluate = (input = problem) => evaluateSolverProof(input, '/fixture/worker', receipt, {},
const evaluate = (input = problem) => evaluateSolverProof(input, receipt, {},
new AbortController().signal, { command: 'original-comparator comparator.json', timeoutMs: Infinity });

beforeEach(() => {
Expand Down Expand Up @@ -82,7 +83,7 @@ describe('external evaluator execution failures', () => {
stderrPreview: "could not execute external process 'lean'\n" };
host.official.mockResolvedValue({ comparison });
const value = await evaluateSolverProof({ ...problem, kind: 'lean-eval', sourceRepository: '/fixture/source' },
'/fixture/worker', receipt, {}, new AbortController().signal, { timeoutMs: Infinity });
receipt, {}, new AbortController().signal, { timeoutMs: Infinity });
expect(value).toEqual({ status: 'error', reason: 'math_evaluator_environment_unavailable',
method: 'official-comparator', official: true, comparison });
expect(host.run).not.toHaveBeenCalled();
Expand Down
13 changes: 8 additions & 5 deletions tests/evaluatorRun.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,19 @@ describe('evaluator failure attribution in persisted run results', () => {
expect(host.evaluate).not.toHaveBeenCalled();
});

it('still interrupts preparation when an explicit finite deadline expires', async () => {
it.each([1, 2_147_484])('interrupts preparation at its explicit %s-second deadline', async seconds => {
vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] });
let observed: { timeoutMs: number; abortedBeforeDeadline: boolean; abortedAtDeadline: boolean } | undefined;
host.prepare.mockImplementation(async ({ timeoutMs, signal }) => {
expect(timeoutMs).toBeGreaterThan(0);
expect(timeoutMs).toBeLessThanOrEqual(1000);
await vi.advanceTimersByTimeAsync(1001);
await vi.advanceTimersByTimeAsync(seconds * 1000 - 1);
const abortedBeforeDeadline = signal.aborted;
await vi.advanceTimersByTimeAsync(1);
observed = { timeoutMs, abortedBeforeDeadline, abortedAtDeadline: signal.aborted };
signal.throwIfAborted();
throw new Error('fixture_finite_preparation_should_abort');
});
expect(await runSolver([...args, '--prepare-timeout-seconds', '1', '--startup-only'], directory)).toBe(4);
expect(await runSolver([...args, '--prepare-timeout-seconds', String(seconds), '--startup-only'], directory)).toBe(4);
expect(observed).toEqual({ timeoutMs: seconds * 1000, abortedBeforeDeadline: false, abortedAtDeadline: true });
expect(JSON.parse(fs.readFileSync(output, 'utf8'))).toMatchObject({ status: 'limit_reached', reason: 'math_preparation_stopped' });
expect(vi.getTimerCount()).toBe(0);
expect(host.research).not.toHaveBeenCalled();
Expand Down
18 changes: 18 additions & 0 deletions tests/executionDeadline.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,22 @@ describe('execution time with human approval waits', () => {
expect(vi.getTimerCount()).toBe(0);
clock.stop();
});

it('uses the full long execution allowance across a pause without expiring at the timer limit', async () => {
const limitMs = 3_000_000_000;
const expire = vi.fn(), clock = new ExecutionDeadline(limitMs, expire);
await vi.advanceTimersByTimeAsync(125);
expect(expire).not.toHaveBeenCalled();
clock.setWaiting(true);
await vi.advanceTimersByTimeAsync(limitMs);
expect(expire).not.toHaveBeenCalled();
expect(clock.remainingMs()).toBe(limitMs - 125);
clock.setWaiting(false);
await vi.advanceTimersByTimeAsync(limitMs - 126);
expect(expire).not.toHaveBeenCalled();
expect(clock.remainingMs()).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(expire).toHaveBeenCalledOnce();
expect(vi.getTimerCount()).toBe(0);
});
});
Loading
Loading