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
5 changes: 2 additions & 3 deletions src/solver/agentTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import { git, commitSolverSources, solverSourceConstraints, SolverSourceError, w
import { solverSourceFeedback } from './feedback';
import { prepareResearchSkill } from './researchSkill';
import { buildSkillResearchContext, teamTurnTiming } from './skillResearchContext';
import { DeclarationArtifactCheckError, DeclarationSubmissionError } from './declarationArtifacts';
import { hasDeterministicLeanFailure } from './proofReuse';
import { correctableDeclarationCheck, DeclarationArtifactCheckError, DeclarationSubmissionError } from './declarationArtifacts';
import { solverSourceDigest } from './modules/evidence';
import { writeOwnedDeclarationIndex } from './declarationIndex';
import { recordUnconfirmedWriterStartup, stopProofWriter } from './proofWriter';
Expand Down Expand Up @@ -80,7 +79,7 @@ function correctableSourceFailure(error: unknown) {
function correctableProofFailure(error: unknown) {
if (correctableSourceFailure(error)) return true;
if (error instanceof DeclarationSubmissionError) return true;
if (error instanceof DeclarationArtifactCheckError) return hasDeterministicLeanFailure(error.verification);
if (error instanceof DeclarationArtifactCheckError) return correctableDeclarationCheck(error);
return error instanceof Error && /^math_agent_team_proof_(?:undeclared_source_change|declaration_missing|declaration_outside_ownership|import_removed)$/u.test(error.message);
}

Expand Down
5 changes: 5 additions & 0 deletions src/solver/declarationArtifacts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ export class DeclarationArtifactCheckError extends Error {
this.name = 'DeclarationArtifactCheckError';
}
}
/** Lean source diagnostics, or a fixed sandbox limit exhausted by one isolated declaration, are researcher feedback. */
export function correctableDeclarationCheck(error: unknown): boolean {
return error instanceof DeclarationArtifactCheckError && (hasDeterministicLeanFailure(error.verification) ||
error.verification.results.length === 1 && hasLeanResourceLimitFailure(error.verification));
}
type DeclarationArtifactManifest = { schema: 'theorem-os.declaration-artifacts.v1'; runId: string;
problemReceiptDigest: string; environmentDigest: string; artifacts: DeclarationArtifact[] };
const manifestBytes = 32 * 1024 * 1024, manifestRecords = 4096;
Expand Down
5 changes: 2 additions & 3 deletions src/solver/skillProofLifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { canonicalMathJson, mathDigest, writeMathJsonDurable } from '../math/mat
import { assertMathAgentSkillsCurrent, type MathAgentSkill } from '../runtime/agentSkills';
import type { SolverRunState } from './archive';
import { checkDeclarationArtifacts, readDeclarationSubmission, writeDeclarationArtifacts,
DECLARATION_SUBMISSION_FILE, DeclarationArtifactCheckError, DeclarationSubmissionError } from './declarationArtifacts';
DECLARATION_SUBMISSION_FILE, DeclarationArtifactCheckError, DeclarationSubmissionError, correctableDeclarationCheck } from './declarationArtifacts';
import type { ResearchCandidate } from './modules/execution';
import { solverSourceDigest } from './modules/evidence';
import { commitSolverSources, git } from './problem';
import { hasDeterministicLeanFailure } from './proofReuse';
import { VerificationCheckpointError } from './verificationCheckpoint';
import { VerifierFailureError } from './verifierFailure';

Expand Down Expand Up @@ -90,7 +89,7 @@ export function createSkillProofLifecycle(input: {
} catch (error) {
signal.throwIfAborted();
if (error instanceof VerificationCheckpointError) throw error;
if (error instanceof DeclarationArtifactCheckError && !hasDeterministicLeanFailure(error.verification))
if (error instanceof DeclarationArtifactCheckError && !correctableDeclarationCheck(error))
throw new VerifierFailureError({ stage: 'declaration-check', sourceCommit: commit, verification: error.verification }, error);
if (!(error instanceof DeclarationSubmissionError) && !(error instanceof DeclarationArtifactCheckError)) throw error;
const reason = error instanceof Error ? error.message : String(error);
Expand Down
58 changes: 58 additions & 0 deletions tests/agentTeamSourceRecovery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import type { NativeAgentControlConnection } from '../src/runtime/nativeAgentCon
import { readSolverRunState, writeSolverRunState, type SolverRunState } from '../src/solver/archive';
import { AgentResearchTeam } from '../src/solver/agentTeam';
import { readAgentTeamProofDelivery } from '../src/solver/agentTeamProof';
import { LEAN_MEMORY_LIMIT_ERROR } from '../src/math/verifier';
import { DeclarationArtifactCheckError } from '../src/solver/declarationArtifacts';
import { directSolverModules } from '../src/solver/modules';
import { agentLibrary, LIBRARY_ACCESS_FILE, LIBRARY_REQUEST_FILE, type LibraryAccess, writeLibraryAccess } from '../src/solver/libraryAccess';
import { writeLibraryCatalog } from '../src/solver/libraryCatalog';
Expand All @@ -25,6 +27,27 @@ import { solverState } from './helpers/solver';
vi.mock('../src/math/mathBuildManifest', async importOriginal => ({
...await importOriginal<typeof import('../src/math/mathBuildManifest')>(), readMathBuildManifest: vi.fn(),
}));
// The sandbox memory cap cannot be reached cheaply; tests replace one host check with Lean's recorded outcome.
const proofChecks = vi.hoisted(() => ({ check: undefined as unknown, integrate: undefined as unknown }));
vi.mock('../src/solver/agentTeamProof', async importOriginal => {
const actual = await importOriginal<typeof import('../src/solver/agentTeamProof')>();
return { ...actual,
checkAgentTeamProofDelivery: async (input: Parameters<typeof actual.checkAgentTeamProofDelivery>[0]) => {
if (proofChecks.check) throw (proofChecks.check as (value: typeof input) => Error)(input);
return actual.checkAgentTeamProofDelivery(input);
},
integrateAgentTeamProofDelivery: async (input: Parameters<typeof actual.integrateAgentTeamProofDelivery>[0]) => {
if (proofChecks.integrate) throw (proofChecks.integrate as (value: typeof input) => Error)(input);
return actual.integrateAgentTeamProofDelivery(input);
} };
});
function memoryLimit(declaration: typeof declarations[number], commit: string) {
return new DeclarationArtifactCheckError(declaration, {
schema: 'deepscientist.mathematics.verification-batch/v1', status: 'failed', targetCommit: commit,
sessionId: 'memory-limit-verifier', events: [], startedAt: 1, checkedAt: 2, durationMs: 1,
results: [{ status: 'failed', targetCommit: commit, proofPath: declaration.file, theoremName: declaration.name,
receiptId: 'memory-limit', error: LEAN_MEMORY_LIMIT_ERROR, stdoutPreview: 'INTERNAL PANIC: out of memory' }] });
}

const original = 'namespace Recovery\ntheorem goal : True := by sorry\nend Recovery\n';
const helper = 'theorem helper : True := by trivial\n';
Expand Down Expand Up @@ -144,6 +167,7 @@ function fixture({ maxAgents = 2, softSlice, stallInterrupt = false, librarySour

afterEach(async () => {
vi.restoreAllMocks();
proofChecks.check = proofChecks.integrate = undefined;
for (const f of fixtures.splice(0)) {
f.controller.abort(); for (const session of f.sessions) session.complete();
await Promise.allSettled(f.teams.map(team => team.close()));
Expand Down Expand Up @@ -482,6 +506,40 @@ describe('native team source handling', () => {
expect(worker.pendingDelivery).toBeDefined(); expect(f.team.archive.deliveries).toHaveLength(0);
});

it('returns a member nomination that exhausts the Lean memory limit to Lead as correctable feedback', async () => {
const f = fixture(); await f.spawn('member', 'Prove the helper.');
const first = await f.session(0), worker = f.team.archive.workers[0]!;
fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery'));
expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ ok: true });
proofChecks.check = (input: { declarations: typeof declarations; worktree: string }) =>
memoryLimit(input.declarations[0]!, git(input.worktree, ['rev-parse', 'HEAD']));
first.complete(); await idle(f.team);
const task = worker.tasks[0]!;
expect(worker).toMatchObject({ status: 'idle', activity: 'idle', phase: 'prepared' });
expect(task.status).toBe('failed'); expect(task.error).toContain(LEAN_MEMORY_LIMIT_ERROR);
expect(task.failedCheck).toMatchObject({ declaration: declarations[0], results: [expect.objectContaining({ error: LEAN_MEMORY_LIMIT_ERROR })] });
expect(f.team.archive.events.some(event => event.kind === 'failed' && event.to === 'lead' &&
event.text.includes(LEAN_MEMORY_LIMIT_ERROR))).toBe(true);
expect(worker.pendingDelivery).toBeUndefined(); expect(f.team.archive.deliveries).toHaveLength(0);
}, 60_000);

it('fails a Lead adoption that exhausts the Lean memory limit without stopping the team', async () => {
const f = fixture(); await f.spawn('member', 'Prove the helper.');
const first = await f.session(0), worker = f.team.archive.workers[0]!;
fs.writeFileSync(f.source(worker.worktree), original.replace('end Recovery', helper + 'end Recovery'));
expect(await f.call({ operation: 'submit', summary: 'Helper ready.', declarations }, 'member')).toMatchObject({ ok: true });
first.complete(); await idle(f.team);
const delivery = f.team.archive.deliveries[0]!;
expect(await f.call({ operation: 'adopt', deliveryId: delivery.id })).toMatchObject({ ok: true });
proofChecks.integrate = (input: { expectedCommit: string }) => memoryLimit(declarations[0]!, input.expectedCommit);
await expect(f.team.flushAdoptions()).resolves.toBeUndefined();
expect(f.team.archive.adoptions).toEqual([expect.objectContaining({ deliveryId: delivery.id, targetId: 'lead',
status: 'failed', error: expect.stringContaining(LEAN_MEMORY_LIMIT_ERROR) })]);
expect(f.team.archive.events.some(event => event.kind === 'failed' && event.to === 'lead' &&
event.text.includes(LEAN_MEMORY_LIMIT_ERROR))).toBe(true);
expect(git(f.state.worktree, ['rev-parse', 'HEAD'])).toBe(f.problem.baseCommit);
}, 60_000);

it('resumes the exact acknowledged nomination after writer loss but honors an explicit cancellation', async () => {
const f = fixture(); await f.spawn('member', 'Route: test-route\nInvestigate.');
await f.session(0);
Expand Down
17 changes: 11 additions & 6 deletions tests/skillResearchRuntime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import fs from 'node:fs';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { LOCAL_EXAMPLE_PROOF, LOCAL_EXAMPLE_STATEMENT } from '../src/math/localExample';
import { LEAN_MEMORY_LIMIT_ERROR } from '../src/math/verifier';
import { mathDigest } from '../src/math/mathRuntimeIo';
import { readMathAgentSkill } from '../src/runtime/codexSkills';
import type { MathAgentOptions, MathAgentSession } from '../src/runtime/codexSession';
Expand Down Expand Up @@ -504,22 +505,26 @@ describe('skill research runtime', () => {
expect(current.stops).toHaveBeenCalledTimes(1);
});

it.each(['mathematical', 'invocation', 'cleanup'] as const)('classifies a failed helper receipt with %s diagnostics before consuming it', async failure => {
it.each(['mathematical', 'memory-limit', 'invocation', 'cleanup', 'shared-memory-limit'] as const)('classifies a failed helper receipt with %s diagnostics before consuming it', async failure => {
host.declarations.mockImplementationOnce(async input => {
const memory = failure === 'memory-limit' || failure === 'shared-memory-limit';
const result = { status: 'failed' as const, targetCommit: input.commit, proofPath: 'Submission.lean', theoremName: 'Tutorial.helper',
receiptId: 'failed-helper', error: failure === 'invocation' ? 'Process exited without Lean diagnostics'
: memory ? LEAN_MEMORY_LIMIT_ERROR : 'Lean exited with status 1.',
...(failure === 'invocation' ? {} : { stdoutPreview: memory ? 'INTERNAL PANIC: out of memory' : 'Submission.lean:1:1: error: unsolved goals' }),
...(failure === 'cleanup' ? { cleanupError: 'fixture checkout cleanup failed' } : {}) };
throw new DeclarationArtifactCheckError(input.declarations[0], {
schema: 'deepscientist.mathematics.verification-batch/v1', status: 'failed', targetCommit: input.commit,
sessionId: 'failed-helper-verifier', events: [], startedAt: 1, checkedAt: 2, durationMs: 1,
results: [{ status: 'failed', targetCommit: input.commit, proofPath: 'Submission.lean', theoremName: 'Tutorial.helper',
receiptId: 'failed-helper', error: failure === 'invocation' ? 'Process exited without Lean diagnostics' : 'Lean exited with status 1.',
...(failure === 'invocation' ? {} : { stdoutPreview: 'Submission.lean:1:1: error: unsolved goals' }),
...(failure === 'cleanup' ? { cleanupError: 'fixture checkout cleanup failed' } : {}) }],
// A shared invocation does not bind its resource limit to one declaration.
results: failure === 'shared-memory-limit' ? [result, { ...result, theoremName: 'Tutorial.other', receiptId: 'other-helper' }] : [result],
});
});
const current = fixture([f => { requestHelper(f); }, (f, _options, message) => {
expect(message).toContain('Declaration check feedback');
expect(fs.existsSync(f.requestFile)).toBe(false);
}]);
if (failure === 'mathematical') {
if (failure === 'mathematical' || failure === 'memory-limit') {
expect(await current.completion).toBeUndefined();
expect(current.state.pendingDeclarationCheck).toBeUndefined();
expect(JSON.parse(fs.readFileSync(path.join(current.workspace, '.scratch/declaration-feedback.json'), 'utf8')))
Expand Down
Loading