From 5962e5a945a735d8ca054a70252d7dd47166cd74 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <3100378030@qq.com> Date: Wed, 25 Nov 2026 22:46:40 +0800 Subject: [PATCH] Fix run recovery, exact check evidence, and proof search histories --- apps/web/client/researchLibraryTrial.tsx | 11 +- apps/web/client/trajectoryView.tsx | 20 ++-- apps/web/collaboration.ts | 2 + apps/web/i18n/errors.ts | 4 +- apps/web/jobs.ts | 55 ++++++---- apps/web/researchLibraryTrialTypes.ts | 2 +- apps/web/researchLibraryTrials.ts | 15 +-- apps/web/runner.ts | 17 +-- apps/web/sample.ts | 10 +- apps/web/server.ts | 20 ++-- apps/web/shared.ts | 5 +- apps/web/storage.ts | 16 ++- apps/web/trajectory.ts | 109 +++++++++++++++----- apps/web/worker.ts | 7 +- apps/web/workerBridge.ts | 62 +++++++---- scripts/test-web-research-library-trials.ts | 29 +++++- scripts/test-web-trajectory.ts | 46 +++++++++ src/math/leanProofSearch.ts | 44 +++++--- src/math/mathRuntimeIo.ts | 6 +- src/math/proofSearchCheckpointPath.ts | 14 +++ src/solver/cooperation.ts | 7 +- src/solver/cooperationCore.ts | 16 +-- src/solver/cooperationInputs.ts | 11 +- src/solver/nextCheckContract.ts | 3 + src/solver/nextChecks.ts | 49 ++++++--- src/solver/proofSearchRecords.ts | 57 ++++++---- src/solver/proofSearchTool.ts | 22 ++-- tests/nextCheckExecution.test.ts | 16 ++- tests/proofSearchRuntime.test.ts | 46 ++++++++- tests/proofSearchTool.test.ts | 25 ++++- tests/webCollaboration.test.ts | 31 +++++- tests/webJobs.test.ts | 17 +++ tests/webLifecyclePersistence.test.ts | 53 ++++++++++ tests/webRunner.test.ts | 15 ++- tests/webTrajectory.test.ts | 24 +++++ tests/webWorkerBridge.test.ts | 59 ++++++++++- 36 files changed, 741 insertions(+), 204 deletions(-) create mode 100644 src/math/proofSearchCheckpointPath.ts diff --git a/apps/web/client/researchLibraryTrial.tsx b/apps/web/client/researchLibraryTrial.tsx index 8f8d0440..b9ce37cf 100644 --- a/apps/web/client/researchLibraryTrial.tsx +++ b/apps/web/client/researchLibraryTrial.tsx @@ -22,7 +22,7 @@ export function LibraryTrial({ release, context }: { release: ResearchAssetRelea : <>{tx('登录后在研究目标中试用', 'Sign in to try this on a research goal')}; } function TrialForm({ release, owner }: { release: ResearchAssetRelease; owner: string }) { - const parameters = new URLSearchParams(location.search), linkedRun = parameters.get('run'), linkedTask = parameters.get('task'); + const parameters = new URLSearchParams(location.search), linkedRun = parameters.get('run'), linkedTask = parameters.get('task'), linkedProject = parameters.get('project'); const [trialId, setTrialId] = useState(parameters.get('trial') ?? ''); const [open, setOpen] = useState(Boolean(linkedRun || trialId)), [selected, setSelected] = useState(''); const [prepared, setPrepared] = useState<{ input: string; item: ResearchLibraryTrial }>(), [confirmed, setConfirmed] = useState(''); @@ -41,7 +41,7 @@ function TrialForm({ release, owner }: { release: ResearchAssetRelease; owner: s } else setPrepared(previous => previous?.item.id === recovery.id && !(previous.item.check && !recovery.check) ? { ...previous, item: recovery } : previous); }, [recovery, matchingRecovery]); const available = targets.data?.items ?? [], requested = available.find(item => item.ref.runId === linkedRun && (!linkedTask || item.ref.taskId === linkedTask) - && (!parameters.get('project') || !item.ref.projectId || item.ref.projectId === parameters.get('project')) + && (!linkedProject || item.ref.projectId === linkedProject) && (!parameters.get('taskVersion') || item.ref.taskVersion === parameters.get('taskVersion')) && (!parameters.get('commit') || item.ref.commit === parameters.get('commit'))); const target = selected ? available.find(item => targetKey(item) === selected) : linkedRun ? requested : available.find(item => item.compatible); const editorReady = !trialId || prepared?.item.id === trialId || Boolean(saved.error) || Boolean(recovery && !matchingRecovery); @@ -51,7 +51,7 @@ function TrialForm({ release, owner }: { release: ResearchAssetRelease; owner: s : { declaration: release.mathematics!.declarations[0]?.name ?? '', proof: '', argumentNotes: '', missingPremises: '' }); const { declaration: name, proof, argumentNotes: argumentsNote, missingPremises: missing } = editor.value; const declaration = release.mathematics!.declarations.find(item => item.name === name); - const input = JSON.stringify([target ? targetKey(target) : undefined, name, proof, argumentsNote, missing]); + const input = JSON.stringify([target ? targetKey(target) : undefined, name, proof.trim(), argumentsNote, missing]); const draft = prepared?.input === input ? prepared.item : undefined; const busy = prepare.busy || check.busy || draft?.status === 'checking'; const loadExample = (example: ResearchCheckedMathExample) => { @@ -74,18 +74,17 @@ function TrialForm({ release, owner }: { release: ResearchAssetRelease; owner: s {targets.data && !available.length &&

{tx('当前没有保存了定理源码的可试用任务。先打开一次研究;项目任务需要候选证明权限。', 'No eligible task with saved theorem source is available. Open a research run first; project tasks require proof submission permission.')}

} {targets.data && Boolean(available.length) &&
{ event.preventDefault(); if (!target || !target.compatible || !declaration || !editor.ready) return; - const submitted = input; void prepare.run>('POST', `${base}/library/${enc(release.assetId)}/releases/${enc(release.version)}/trials`, { releaseDigest: release.digest, target: target.ref, declaration: name, proof, argumentNotes: argumentsNote, missingPremises: missing, }, result => { restored.current = result.item.id; setTrialId(result.item.id); const next = new URL(location.href); next.searchParams.set('trial', result.item.id); history.replaceState(null, '', next); - setPrepared({ input: submitted, item: result.item }); setConfirmed(''); check.reset(); + setPrepared({ input: draftInput(result.item), item: result.item }); setConfirmed(''); check.reset(); }); }}> + {item.projectTitle ?? tx('个人运行', 'Personal run')} · {item.runTitle} · {item.taskTitle} · {item.ref.taskVersion.slice(0, 10)} · {item.ref.commit.slice(0, 10)}{item.compatible ? '' : ` · ${tx('环境不同', 'Different environment')}`})} {linkedRun && !requested && !selected && } {target &&

{target.type}
{target.premises.length > 0 && <>

{tx('任务记录的前提', 'Recorded task premises')}

    {target.premises.map((premise, index) =>
  • )}
} diff --git a/apps/web/client/trajectoryView.tsx b/apps/web/client/trajectoryView.tsx index 1d4f2a04..5fc51951 100644 --- a/apps/web/client/trajectoryView.tsx +++ b/apps/web/client/trajectoryView.tsx @@ -80,14 +80,14 @@ type Item = { step: TrajectoryStep; key: string; index: number }; type Loaded = { status: 'loading' } | { status: 'ready'; revision: number; detail: TrajectoryVersionDetail } | { status: 'failed'; error: string }; /** Where the key for a question comes from; with none, the panel asks for one and keeps it on this page only. */ export type ExplainKey = { source: 'saved'; ending: string } | { source: 'server' } | { source: 'remembered' } | { source: 'none' }; -export type ExplainRequest = { taskId: string; commit: string; taskVersion?: string; question: string; turns: WebExplainTurn[]; apiKey?: string }; +export type ExplainRequest = { taskId: string; commit: string; taskVersion?: string; receiptId: string; checkAt: number; question: string; turns: WebExplainTurn[]; apiKey?: string }; /** What a reader may do with a run of their own: start a new run from a version, and ask why a version failed. */ export type OwnRunActions = { allowed(run: WebRun): boolean; start(run: WebRun, from: WebContinuation): void; explain?: { key(run: WebRun): ExplainKey; ask(run: WebRun, request: ExplainRequest, signal: AbortSignal): Promise }; }; -/** One version's questions and answers, kept on the page; nothing is stored on the server. */ +/** One check's questions and answers, kept on the page; nothing is stored on the server. */ type AskTurn = WebExplainTurn & { truncated?: boolean; usage?: WebExplainAnswer['usage'] }; type AskThread = { turns: AskTurn[]; draft: string; pending?: { question: string; controller: AbortController }; error?: string }; type Built = { key: string; steps: TrajectoryStep[]; keys: string[]; names: Map }; @@ -113,7 +113,7 @@ type Ctx = { run: WebRun; state: RunState; names: Map; tasks: Ma type Content = { title: ComponentChildren; meta?: string[]; badge?: [string, Tone]; body?: ComponentChildren }; const shortName = (name: string) => name.split('.').at(-1) || name; -const detailKey = ({ version, check }: TrajectoryRef) => check?.taskVersion ? `${version.key}\u0000${check.taskVersion}` : version.key; +const detailKey = ({ version, check }: TrajectoryRef) => JSON.stringify([version.key, check?.taskVersion, check?.at, check?.receiptIds[0]]); /** The Lean output of a version's check (`ids`, its receipts; none means all), failed receipts first, each output once. */ function checkEntries(detail: TrajectoryVersionDetail, ids: readonly string[]) { const wanted = new Set(ids), checks = detail.checks.filter(check => !wanted.size || wanted.has(check.id)) @@ -966,7 +966,7 @@ export class TrajectoryView { if (step.kind !== 'attempt' && step.kind !== 'proof') return []; const version = step.ref?.version, saved = version?.source !== undefined, failed = Boolean(version) && step.outcome === 'failed'; return [saved && 'code', saved && step.kind === 'attempt' && step.previous?.version.source !== undefined && 'diff', - failed && 'feedback', failed && this.asks(run) && 'ask'].filter((mode): mode is Mode => Boolean(mode)); + failed && 'feedback', failed && step.ref?.check?.receiptIds[0] && this.asks(run) && 'ask'].filter((mode): mode is Mode => Boolean(mode)); } private asks(run: WebRun) { return Boolean(this.own?.explain && this.own.allowed(run)); } @@ -1100,6 +1100,10 @@ export class TrajectoryView { for (const old of versions.keys()) { if (versions.size <= limits.versions) break; versions.delete(old); } const query = new URLSearchParams({ task: version.taskId, commit: version.commit }); if (check?.taskVersion) query.set('taskVersion', check.taskVersion); + if (check?.receiptIds[0]) { + query.set('receiptId', check.receiptIds[0]); + query.set('checkAt', String(check.at)); + } void this.api<{ version: TrajectoryVersionDetail }>(`/api/runs/${encodeURIComponent(ctx.run.id)}/trajectory/version?${query}`) .then(({ version: detail }) => { versions.set(key, { status: 'ready', revision: version.revision, detail }); }, error => { versions.set(key, { status: 'failed', error: errorText(error) }); }) @@ -1291,7 +1295,7 @@ export class TrajectoryView { } /** - * Questions about a failed version, answered by the run's own model through its provider: each is a call the reader + * Questions about a failed check, answered by the run's own model through its provider: each is a call the reader * pays for, outside the run's budget, and the run never sees it. The thread stays on this page until it is left; * each question carries the last few answers with it. */ @@ -1330,8 +1334,8 @@ export class TrajectoryView { ; } private async send(ctx: Ctx, { version, check }: TrajectoryRef, thread: AskThread, form: HTMLFormElement) { - const explain = this.own?.explain, question = thread.draft.trim(), run = ctx.run; - if (!explain || !question || thread.pending) return; + const explain = this.own?.explain, question = thread.draft.trim(), run = ctx.run, receiptId = check?.receiptIds[0]; + if (!explain || !question || !check || !receiptId || thread.pending) return; const source = explain.key(run).source, typed = this.typedKeys.get(run.providerId) ?? ''; if (source === 'none' && !/^[\x21-\x7e]{8,4096}$/u.test(typed)) { thread.error = t('请填写这个服务商的 API Key'); this.render(); @@ -1343,7 +1347,7 @@ export class TrajectoryView { thread.pending = { question, controller }; thread.error = undefined; thread.draft = ''; this.render(); try { - const answer = await explain.ask(run, { taskId: version.taskId, commit: version.commit, question, + const answer = await explain.ask(run, { taskId: version.taskId, commit: version.commit, receiptId, checkAt: check.at, question, ...(check?.taskVersion ? { taskVersion: check.taskVersion } : {}), turns: thread.turns.slice(-explainLimits.turns).map(turn => ({ question: turn.question, answer: turn.answer })), ...(source === 'none' ? { apiKey: typed } : {}) }, controller.signal); diff --git a/apps/web/collaboration.ts b/apps/web/collaboration.ts index bcf00816..b2969bc3 100644 --- a/apps/web/collaboration.ts +++ b/apps/web/collaboration.ts @@ -211,6 +211,7 @@ export type WebCommand = | { type: 'guidance-withdraw'; id: string; guidanceId: string } | { type: 'plan-approval'; approval: WebPlanApprovalInput } | { type: 'capture' }; +export type WebLibraryRestart = { previousSolverRunId: string; solverRunId: string; round: number }; export type WebCommandResult = { id: string; status: string; baseVersion?: string; planVersion?: string; reason?: string; commandDigest?: string; @@ -220,6 +221,7 @@ export type WebCommandResult = { edit?: WebHumanEdit; observation?: WebObservation; catalog?: unknown; + libraryRestart?: WebLibraryRestart; }; export type WebArchive = { id: string; runId: string; createdAt: string; digest: string; diff --git a/apps/web/i18n/errors.ts b/apps/web/i18n/errors.ts index b2247871..bbcb0294 100644 --- a/apps/web/i18n/errors.ts +++ b/apps/web/i18n/errors.ts @@ -187,7 +187,9 @@ export const errors: Record = { "这个版本没有记录或已超出保留范围。": "This version was not recorded or is no longer kept.", "请检查问题、版本与 API Key。": "Check the question, the version and the API key.", "这次运行的模型服务已不在配置中。": "This run's model provider is no longer configured.", - "这个版本没有未通过的 Lean 检查可以解释。": "This version has no failed Lean check to explain.", + "这个检查没有记录或已超出保留范围。": "This check was not recorded or is no longer kept.", + "这个版本有多次检查,请选择要解释的一次。": "This version was checked more than once. Choose the check to explain.", + "没有未通过的 Lean 检查可以解释。": "There is no failed Lean check to explain.", "该任务版本没有已保存的源码。": "This task version has no saved source.", "检查回执不存在或未保存。": "The check receipt does not exist or was not saved.", "指导回执尚不可用。": "The guidance receipt is not available yet.", diff --git a/apps/web/jobs.ts b/apps/web/jobs.ts index 92913d93..2b185b64 100644 --- a/apps/web/jobs.ts +++ b/apps/web/jobs.ts @@ -2,13 +2,13 @@ import { webProviderExecutionDigest, webProviderHarness, webHarnessResearchError import crypto from 'node:crypto'; import type { WebConfig } from './config'; import type { WebRunner } from './runner'; -import type { WebEvent, WebEventDetails, WebProvider, WebWorkerProvider, WebRun, WebRunInput, WorkerInput, WorkerMessage } from './shared'; +import type { WebEvent, WebEventDetails, WebProvider, WebResult, WebWorkerProvider, WebRun, WebRunInput, WorkerInput, WorkerMessage } from './shared'; import { webResearchModeError, webSkillWithoutCooperation, webDefaultSkillLoading } from './researchMode'; import { normalizeWebTeamPreferences } from './nativeTeamProfiles'; import { personalExpertCardsDigest } from '../../src/solver/personalExperts'; -import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits } from './shared'; +import { isProgressEvent, parseWebFailure, webAgentActionLimits, webLimits, webRunEventLimit } from './shared'; import { recordWebModuleEvent, sanitizeWebEventDetails } from './moduleTelemetry'; -import type { WebCommand, WebCommandResult, WebObservation } from './collaboration'; +import type { WebCommand, WebCommandResult, WebLibraryRestart, WebObservation } from './collaboration'; import { canonicalMathJson } from '../../src/math/mathRuntimeIo'; import { WebStorage, type WebCreation } from './storage'; import { WebKnowledgeService } from './knowledgeService'; @@ -61,7 +61,15 @@ export class WebJobs { if (creation) this.creations.set(JSON.stringify([owner, creation.requestId]), { ...creation, runId: run.id }); const provider: WebWorkerProvider = { id: run.providerId, name: run.providerId, baseUrl: '' }; this.jobs.set(run.id, { owner, run, provider, input: { ...run, apiKey: '' }, controller: new AbortController() }); - if (!terminal(run)) { + if (run.result && (!terminal(run) || run.phase === 'interrupted' && run.result.status === 'evaluated_passed')) { + if (run.phase === 'interrupted') { + delete run.error; + delete run.failure; + delete run.finishedAt; + } + const last = run.events.at(-1); + this.finishResult(run, run.result, last?.type === 'finished' ? last.at : run.updatedAt); + } else if (!terminal(run)) { run.status = 'error'; run.phase = 'interrupted'; run.finishedAt = new Date().toISOString(); run.error = '服务已重启;保留最后观测与已有证据。本次运行未恢复执行。'; run.failure = { kind: 'interrupted' }; @@ -295,7 +303,7 @@ export class WebJobs { for (const listener of this.listeners.get(owner) ?? []) listener(version); }); } - private libraryRestart(job: Job, message: Extract) { + private libraryRestart(job: Job, message: WebLibraryRestart) { const current = job.run.solverAttempt ?? (job.run.observation && { solverRunId: job.run.observation.solverRunId, round: 0, sequence: job.run.observation.sequence }); if (!current || current.solverRunId !== message.previousSolverRunId || @@ -421,6 +429,7 @@ export class WebJobs { const apiKey = job.input.apiKey; const capture = clean(await this.runner.command(id, { type: 'capture' }), apiKey); if (this.jobs.get(id) !== job) throw new WebStorageError(404, '运行不存在或不属于当前会话。'); + if (capture.libraryRestart) this.libraryRestart(job, capture.libraryRestart); if (capture.observation) this.observe(job, capture.observation); if (capture.catalog) job.run.knowledgeCatalogDigest = this.knowledge.importCatalog(owner, capture.catalog).digest; } @@ -442,7 +451,7 @@ export class WebJobs { const event: WebEvent = { sequence, at: run.updatedAt, type, message: message.slice(0, 2_000), ...(details ? { details } : {}) }; recordWebModuleEvent(run, event); run.events.push(event); - if (run.events.length > 200) run.events.shift(); + if (run.events.length > webRunEventLimit) run.events.shift(); this.persist(run); } private pump() { @@ -466,11 +475,27 @@ export class WebJobs { this.changed(job.owner); }); } + private finishResult(run: WebRun, result: WebResult, finishedAt: string, beforeFinished?: () => void) { + run.status = result.status === 'runtime_error' ? 'error' : 'completed'; + run.phase = result.status; + run.finishedAt ??= finishedAt; + delete run.queue; + beforeFinished?.(); + if (run.events.at(-1)?.type === 'finished') { this.persist(run); return; } + const acceptance = !run.formalization ? '完整原题通过独立 Lean 验收' + : !isStatementReviewed(run) ? '候选 Lean 陈述通过独立验收;原题含义尚未审核通过。' + : run.formalization.confirmation === 'manual' ? 'Lean 陈述通过独立 Lean 验收;原题含义已由你确认。Lean 验收不能替代自然语言原意核对。' + : run.formalization.confirmation === 'automatic' ? 'Lean 陈述通过独立 Lean 验收;原题含义仅经模型审核,未经人工确认。Lean 验收不能替代自然语言原意核对。' + : 'Lean 陈述通过独立 Lean 验收;原题含义未记录确认方式,请核对 Lean 陈述。Lean 验收不能替代自然语言原意核对。'; + this.event(run, 'finished', result.status === 'evaluated_passed' ? acceptance : '运行结束,请查看验收状态'); + } private async execute(job: Job) { const key = job.input.apiKey; let messageError: unknown; const handle = (raw: WorkerMessage) => { - if (messageError || this.jobs.get(job.run.id) !== job || terminal(job.run) && !['observation', 'catalog'].includes(raw.type)) return; + if (messageError || this.jobs.get(job.run.id) !== job || terminal(job.run) && + raw.type !== 'observation' && raw.type !== 'catalog' && + !(job.run.status === 'cancelled' && raw.type === 'library_restart')) return; try { const message = clean(raw, key); if (message.type === 'progress') { @@ -529,18 +554,12 @@ export class WebJobs { if (messageError) throw messageError; if (!terminal(job.run)) { if (!job.run.result) throw new Error(job.run.error || '没有收到运行结果。'); - job.run.status = job.run.result.status === 'runtime_error' ? 'error' : 'completed'; const accepted = job.run.result.status === 'evaluated_passed'; - // Transfer credentials only to the explanation queue, before the solver releases them. The queue saves its - // initial records before the finished notification; proof acceptance never depends on explanation success. - if (accepted) try { this.onProofAccepted?.(job.owner, job.run, { apiKey: job.input.apiKey, provider: job.provider }); } - catch { this.event(job.run, 'explanation_queue_failed', '证明已验收,自动讲解未能保存;请稍后重试。'); } - const acceptance = !job.run.formalization ? '完整原题通过独立 Lean 验收' - : !isStatementReviewed(job.run) ? '候选 Lean 陈述通过独立验收;原题含义尚未审核通过。' - : job.run.formalization.confirmation === 'manual' ? 'Lean 陈述通过独立 Lean 验收;原题含义已由你确认。Lean 验收不能替代自然语言原意核对。' - : job.run.formalization.confirmation === 'automatic' ? 'Lean 陈述通过独立 Lean 验收;原题含义仅经模型审核,未经人工确认。Lean 验收不能替代自然语言原意核对。' - : 'Lean 陈述通过独立 Lean 验收;原题含义未记录确认方式,请核对 Lean 陈述。Lean 验收不能替代自然语言原意核对。'; - this.event(job.run, 'finished', accepted ? acceptance : '运行结束,请查看验收状态'); + this.finishResult(job.run, job.run.result, new Date().toISOString(), accepted ? () => { + // The explanation queue receives credentials before the solver releases them. + try { this.onProofAccepted?.(job.owner, job.run, { apiKey: job.input.apiKey, provider: job.provider }); } + catch { this.event(job.run, 'explanation_queue_failed', '证明已验收,自动讲解未能保存;请稍后重试。'); } + } : undefined); if (accepted && isStatementReviewed(job.run)) this.onAccepted?.(job.owner); } } catch (error) { diff --git a/apps/web/researchLibraryTrialTypes.ts b/apps/web/researchLibraryTrialTypes.ts index d1858298..48958b2c 100644 --- a/apps/web/researchLibraryTrialTypes.ts +++ b/apps/web/researchLibraryTrialTypes.ts @@ -8,7 +8,7 @@ export type ResearchLibraryTrialTargetRef = { commit: string; sourceDigest: string; environmentDigest: string; file: string; }; export type ResearchLibraryTrialTarget = { - ref: ResearchLibraryTrialTargetRef; runTitle: string; taskTitle: string; declaration: string; type: string; + ref: ResearchLibraryTrialTargetRef; runTitle: string; projectTitle?: string; taskTitle: string; declaration: string; type: string; environment: 'standard' | 'mathlib'; premises: string[]; compatible: boolean; incompatibility?: string; }; export type ResearchLibraryTrialReceipt = { diff --git a/apps/web/researchLibraryTrials.ts b/apps/web/researchLibraryTrials.ts index 666f57cc..95bdd628 100644 --- a/apps/web/researchLibraryTrials.ts +++ b/apps/web/researchLibraryTrials.ts @@ -112,23 +112,26 @@ export class WebResearchLibraryTrials { } targets(viewer: string, assetId: string, releaseVersion: string): ResearchLibraryTrialTarget[] { this.path(viewer, 'targets'); - const release = this.release(viewer, assetId, releaseVersion), runs = new Map(); - for (const run of this.deps.jobs.list(viewer)) runs.set(run.id, { run }); + const release = this.release(viewer, assetId, releaseVersion); + const runs: { run: WebRun; project?: { id: string; title: string } }[] = this.deps.jobs.list(viewer).map(run => ({ run })); for (let offset = 0;; offset += 100) { const page = this.deps.projects.list(viewer, { limit: 100, offset }); for (const info of page.items) { const project = this.deps.projects.detail(viewer, info.id); if (!project.permissions.member) continue; - for (const binding of project.runs) if (binding.permissions.proof && !runs.has(binding.runId)) { + for (const binding of project.runs) if (binding.permissions.proof) { const resolved = this.deps.projects.resolveBinding(viewer, project.id, binding.runId, 'proof'); - runs.set(binding.runId, { run: resolved.run, projectId: project.id }); + runs.push({ run: resolved.run, project: { id: project.id, title: project.title } }); } } if (page.items.length < 100) break; } - return [...runs.values()].flatMap(({ run, projectId }) => (run.observation?.inspection.tasks ?? []).flatMap(task => { + return runs.flatMap(({ run, project }) => (run.observation?.inspection.tasks ?? []).flatMap(task => { if (!['goal', 'lemma'].includes(task.kind)) return []; - try { return [this.resolve(viewer, { runId: run.id, ...(projectId ? { projectId } : {}), taskId: task.id }, release).target]; } + try { + const target = this.resolve(viewer, { runId: run.id, ...(project ? { projectId: project.id } : {}), taskId: task.id }, release).target; + return project ? [{ ...target, projectTitle: project.title }] : [target]; + } catch (error) { if (error instanceof WebStorageError && [403, 404, 409].includes(error.status)) return []; throw error; } })); } diff --git a/apps/web/runner.ts b/apps/web/runner.ts index 6928d4ea..3baeb8d0 100644 --- a/apps/web/runner.ts +++ b/apps/web/runner.ts @@ -83,9 +83,10 @@ export function isWebObservation(value: unknown): value is WebObservation { value.checks.every(check => object(check) && object(check.record) && ['id', 'taskId', 'taskVersion', 'commit', 'sourceDigest', 'environmentDigest'].every(field => typeof check[field] === 'string')); } +const libraryRestartSchema = z.object({ previousSolverRunId: z.string().min(1).max(128), + solverRunId: z.string().min(1).max(128), round: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); const workerMessageSchema = z.discriminatedUnion('type', [ - z.object({ type: z.literal('library_restart'), previousSolverRunId: z.string().min(1).max(128), - solverRunId: z.string().min(1).max(128), round: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(), + libraryRestartSchema.extend({ type: z.literal('library_restart') }), z.object({ type: z.literal('progress'), event: z.string().min(1).max(100), message: z.string().max(2_000), details: z.custom(isWebEventDetails).optional() }).strict(), z.object({ type: z.literal('error'), message: z.string().min(1).max(2_000), @@ -222,12 +223,15 @@ export class DockerWebRunner implements WebRunner { try { const value: unknown = JSON.parse(output); if (!object(value) || typeof value.id !== 'string' || typeof value.status !== 'string') throw new Error(); - const { observation, sourceBlobs, ...receipt } = value; + const { observation, sourceBlobs, libraryRestart: transition, ...receipt } = value; const observed = observation === undefined ? undefined : readWorkerObservation(observation, sourceBlobs, { runId: id, sources: new Map() }); if (observation !== undefined && !observed) throw new Error(); + const libraryRestart = transition === undefined ? undefined : libraryRestartSchema.parse(transition); + if (libraryRestart && (command.type !== 'capture' || observed?.solverRunId !== libraryRestart.solverRunId)) throw new Error(); if (receipt.catalog) validateTheoremKnowledge(receipt.catalog); - resolve({ ...receipt, ...(observed ? { observation: observed } : {}) } as WebCommandResult); + resolve({ ...receipt, ...(observed ? { observation: observed } : {}), + ...(libraryRestart ? { libraryRestart } : {}) } as WebCommandResult); } catch { reject(new Error('运行环境未返回有效命令回执。')); } }; const timer = setTimeout(() => finish(new Error('命令回执超时,请先查询当前回执再重试。')), 15_000); @@ -408,8 +412,9 @@ export class DockerWebRunner implements WebRunner { // Capture the actual saved checkpoint and source evidence before deleting the container. try { const captured = await this.command(input.id, { type: 'capture' }); - if (captured.observation) onMessage({ type: 'observation', observation: captured.observation }); - if (captured.catalog) onMessage({ type: 'catalog', catalog: captured.catalog }); + if (captured.libraryRestart) forward({ type: 'library_restart', ...captured.libraryRestart }); + if (captured.observation) forward({ type: 'observation', observation: captured.observation }); + if (captured.catalog) forward({ type: 'catalog', catalog: captured.catalog }); } catch { /* A run cancelled during bootstrap may not have a checkpoint yet. */ } await remove(); child.kill('SIGKILL'); diff --git a/apps/web/sample.ts b/apps/web/sample.ts index 644561db..81429141 100644 --- a/apps/web/sample.ts +++ b/apps/web/sample.ts @@ -3,7 +3,7 @@ import type { WebObservation } from './collaboration'; import { projectStoredObservationChecks } from './observationChecks'; import { webArchive } from './storage'; import { webAgentActionLimits, webSampleRunId, type WebAgentAction, type WebEvent, type WebRun } from './shared'; -import { recordedTrajectory, trajectoryPage, trajectoryQuery, trajectoryVersion, trajectoryVersionDetail, trajectoryVersionQuery, type TrajectoryIndex } from './trajectory'; +import { recordedTrajectory, selectTrajectoryChecks, trajectoryPage, trajectoryQuery, trajectoryVersion, trajectoryVersionDetail, trajectoryVersionQuery, type TrajectoryIndex } from './trajectory'; export { webSampleRunId }; @@ -62,9 +62,11 @@ export function webSampleResponse(sample: WebSampleFile, operation: string | und if (operation === 'trajectory/version') { const index = sampleTrajectory(sample); const wanted = trajectoryVersionQuery(query), version = wanted && trajectoryVersion(index, wanted.taskId, wanted.commit); - if (!version || (wanted.taskVersion !== undefined && !version.checks.some(check => check.taskVersion === wanted.taskVersion))) - return { status: wanted ? 404 : 400, body: { error: wanted ? '这个版本没有记录或已超出保留范围。' : '版本参数无效。' } }; - return { status: 200, body: { version: trajectoryVersionDetail(index, version, sequence => sample.observations.find(item => item.sequence === sequence), wanted.taskVersion) } }; + if (!wanted) return { status: 400, body: { error: '版本参数无效。' } }; + const checks = version && selectTrajectoryChecks(version, wanted.taskVersion, wanted.receiptId, wanted.checkAt); + if (!version || !checks?.length) return { status: 404, body: { error: '这个版本没有记录或已超出保留范围。' } }; + return { status: 200, body: { version: trajectoryVersionDetail(index, version, + sequence => sample.observations.find(item => item.sequence === sequence), wanted.taskVersion, checks) } }; } const newestFirst = [...sample.observations].reverse(); const source = /^tasks\/([^/]+)\/source$/u.exec(operation); diff --git a/apps/web/server.ts b/apps/web/server.ts index b4c544c6..5b75d577 100644 --- a/apps/web/server.ts +++ b/apps/web/server.ts @@ -88,10 +88,11 @@ const inputSchema = z.object({ environmentDigest: z.string().regex(/^[a-f0-9]{64}$/u).optional(), file: z.string().min(1).max(1000).regex(/^[^\p{Cc}]*$/u).optional(), label: z.string().trim().min(1).max(webContinuationLabelMax).regex(/^[^\p{Cc}]*$/u) }).strict().optional(), }).strict(); -// A question about one recorded version; its code and Lean's output are read here, never taken from the request. +// A question about one recorded check; its code and Lean's output are read here, never taken from the request. const explainSchema = z.object({ taskId: z.string().min(1).max(200), commit: z.string().regex(/^[A-Za-z0-9]{1,128}$/u), - taskVersion: z.string().min(1).max(200).optional(), + taskVersion: z.string().min(1).max(200).optional(), receiptId: z.string().min(1).max(200).optional(), + checkAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(), question: z.string().trim().min(1).max(webExplainLimits.question), turns: z.array(z.object({ question: z.string().min(1).max(webExplainLimits.question), answer: z.string().min(1).max(webExplainLimits.answer) }).strict()).max(webExplainLimits.turns).default([]), @@ -1218,7 +1219,7 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (operation === 'trajectory/version' && request.method === 'GET') { const query = trajectoryVersionQuery(url.searchParams); if (!query) throw new HttpError(400, '版本参数无效。'); - const version = trajectories.version(owner, run.id, query.taskId, query.commit, query.taskVersion); + const version = trajectories.version(owner, run.id, query.taskId, query.commit, query.taskVersion, query.receiptId, query.checkAt); if (!version) throw new HttpError(404, '这个版本没有记录或已超出保留范围。'); json(response, 200, { version }); return; } @@ -1229,12 +1230,13 @@ export function createWebService(config: WebConfig, runner: WebRunner = new Dock if (!provider) throw new HttpError(409, '这次运行的模型服务已不在配置中。'); const apiKey = parsed.data.apiKey || heldKey(session, provider); if (!apiKey) throw new HttpError(400, '请填写 API Key。'); - const version = trajectories.version(owner, run.id, parsed.data.taskId, parsed.data.commit, parsed.data.taskVersion); - if (!version) throw new HttpError(404, '这个版本没有记录或已超出保留范围。'); - const feedback = failedFeedback(version.checks); - if (!feedback) throw new HttpError(409, '这个版本没有未通过的 Lean 检查可以解释。'); - const objective = run.observation?.plan?.tasks.find(task => task.id === version.taskId)?.objective; - const input = explainInput(run, version, feedback, parsed.data.turns as WebExplainTurn[], parsed.data.question, objective); + const { taskId, commit, taskVersion, receiptId, checkAt, question, turns } = parsed.data; + const selection = trajectories.explanationVersion(owner, run.id, taskId, commit, taskVersion, receiptId, checkAt); + if (selection.status === 'missing') throw new HttpError(404, '这个检查没有记录或已超出保留范围。'); + if (selection.status === 'ambiguous') throw new HttpError(409, '这个版本有多次检查,请选择要解释的一次。'); + const feedback = selection.status === 'found' && failedFeedback(selection.detail.checks); + if (selection.status !== 'found' || !feedback) throw new HttpError(409, '没有未通过的 Lean 检查可以解释。'); + const input = explainInput(run, selection.detail, feedback, turns as WebExplainTurn[], question, selection.detail.objective); // Closing the panel or the tab stops the call; the provider bills what it already produced. const gone = new AbortController(); response.once('close', () => { if (!response.writableFinished) gone.abort(); }); diff --git a/apps/web/shared.ts b/apps/web/shared.ts index d1afa29f..da7a0fdf 100644 --- a/apps/web/shared.ts +++ b/apps/web/shared.ts @@ -1,5 +1,5 @@ import type { ResearchModulePlan, ResearchModuleSlot } from '../../src/solver/modules/policy'; -import type { WebObservation, WebArchive } from './collaboration'; +import type { WebObservation, WebArchive, WebLibraryRestart } from './collaboration'; import type { WebFormalizationBackgroundReview } from './formalizationTypes'; import type { ResearchLibraryProposalOrigin } from './researchLibraryProposalOrigin'; import { webTaskEnvironment } from './environment'; @@ -129,6 +129,7 @@ export type WebEventDetails = { reason?: string; }; export type WebEvent = { sequence: number; at: string; type: string; message: string; details?: WebEventDetails }; +export const webRunEventLimit = 200; export type WebModuleSnapshot = { eventCount: number; firstAt: string; lastEvent: WebEvent; activeWorkers: string[] }; export const webArtifactMaxBytes = 128 * 1024; export type WebArtifact = { @@ -326,7 +327,7 @@ export type WorkerMessage = | { type: 'progress'; event: string; message: string; details?: WebEventDetails } | { type: 'action'; action: WebAgentActionBody } | { type: 'artifact'; artifact: WebArtifact } - | { type: 'library_restart'; previousSolverRunId: string; solverRunId: string; round: number } + | ({ type: 'library_restart' } & WebLibraryRestart) | { type: 'observation'; observation: WebObservation } | { type: 'catalog'; catalog: unknown } | { type: 'result'; result: WebResult } diff --git a/apps/web/storage.ts b/apps/web/storage.ts index 3f8cfc23..3b05faa6 100644 --- a/apps/web/storage.ts +++ b/apps/web/storage.ts @@ -4,6 +4,7 @@ import crypto from 'node:crypto'; import { canonicalMathJson, mathDigest, syncMathDirectory, writeMathFrozen } from '../../src/math/mathRuntimeIo'; import type { WebArchive, WebCheckReceipt, WebCommandResult, WebObservation, WebTaskSource } from './collaboration'; import type { WebAccountIdentity, WebAgentAction, WebEvent, WebExplanation, WebRun, WorkerExplanationCheckpoint } from './shared'; +import { webRunEventLimit } from './shared'; import type { WebShareSnapshot } from './share'; import { archiveObservationCompactor, compactObservation, hydrateArchiveObservation, hydrateObservation, type ArchivedWebObservation, type CompactWebObservation, type CompactWebTaskSource } from './observationSources'; @@ -220,7 +221,20 @@ export class WebStorage { } loadRuns(): StoredRun[] { return this.listRecords(['owners']).flatMap(directory => this.listRecords(['owners', directory, 'runs']) - .map(id => this.readRun(['owners', directory, 'runs', id])) + .map(id => { + const location = ['owners', directory, 'runs', id]; + const stored = this.readRun(location); + if (!stored) return; + // An event may have reached disk just before the summary was replaced. + const events = stored.run.events; + for (let sequence = (events.at(-1)?.sequence ?? 0) + 1; ; sequence++) { + const event = this.getRecord([...location, 'events', `${sequence}.json`]); + if (!event) break; + events.push(event); + if (events.length > webRunEventLimit) events.shift(); + } + return stored; + }) .filter((item): item is StoredRun => Boolean(item))) .sort((a, b) => a.run.createdAt.localeCompare(b.run.createdAt)); } diff --git a/apps/web/trajectory.ts b/apps/web/trajectory.ts index 6e4ccf56..c73a6709 100644 --- a/apps/web/trajectory.ts +++ b/apps/web/trajectory.ts @@ -58,6 +58,8 @@ export type TrajectoryIndex = { instance: string; revision: number; eventCursor: number; observationCursor: number; lastObservedAt?: number; events: WebEvent[]; versions: Map; sources: Map; sourceRevisions: Map; + /** The first observed frame for each receipt, including receipts that joined the check later. */ + receiptFrames: WeakMap; plans: TrajectoryPlan[]; plan?: Map; planVersion?: string; deliveries: Map; guidance: Map; edits: Map; workers: Map; targets: string[]; contextRevision: number; @@ -69,13 +71,23 @@ export type TrajectoryIndex = { let instances = 0; const started = Date.now().toString(36); export function createTrajectoryIndex(): TrajectoryIndex { - return { instance: `${started}-${++instances}`, revision: 0, eventCursor: 0, observationCursor: 0, events: [], versions: new Map(), sources: new Map(), sourceRevisions: new Map(), + return { instance: `${started}-${++instances}`, revision: 0, eventCursor: 0, observationCursor: 0, events: [], versions: new Map(), sources: new Map(), + sourceRevisions: new Map(), receiptFrames: new WeakMap(), plans: [], deliveries: new Map(), guidance: new Map(), edits: new Map(), workers: new Map(), targets: [], contextRevision: 0, retired: new Set(), dropped: { events: 0, versions: 0, plans: 0, deliveries: 0, guidance: 0, edits: 0 } }; } const clip = (value: string | undefined, limit: number) => value === undefined ? undefined : value.length > limit ? `${value.slice(0, limit - 1)}…` : value; const millis = (value: string | number | undefined) => typeof value === 'number' ? value : value === undefined ? NaN : Date.parse(value); +function receiptTime(record: WebCheckReceipt['record']) { + const verification = record.verification as { checkedAt?: string | number } | undefined; + const batch = millis(verification?.checkedAt); + if (Number.isFinite(batch)) return batch; + const individual = millis(record.checkedAt as string | number | undefined); + if (Number.isFinite(individual)) return individual; +} +const originalVerdict = (record: WebCheckReceipt['record']) => + typeof record.originalProblemPassed === 'boolean' ? record.originalProblemPassed : undefined; const versionKey = (taskId: string, commit: string) => `${taskId}\u0000${commit}`; const sourceRevisionKey = (key: string, taskVersion: string) => `${key}\u0000${taskVersion}`; /** Drops the oldest entries over the limit, remembering them so a repeated record is not added again. */ @@ -136,9 +148,7 @@ function foldSource(index: TrajectoryIndex, source: WebTaskSource, observation: function foldCheck(index: TrajectoryIndex, receipt: WebCheckReceipt, observation: number, observedAt: number) { const key = versionKey(receipt.taskId, receipt.commit); if (retired(index, 'versions', key)) return; - const record = receipt.record ?? {}, verification = record.verification as { checkedAt?: unknown } | undefined; - const recorded = millis(verification?.checkedAt as number | undefined) || millis(record.checkedAt as number | undefined); - const at = Number.isFinite(recorded) ? recorded : observedAt; + const record = receipt.record ?? {}, at = receiptTime(record) ?? observedAt; let version = index.versions.get(key); if (!version) { const pending = index.sources.get(key); @@ -149,7 +159,7 @@ function foldCheck(index: TrajectoryIndex, receipt: WebCheckReceipt, observation trim(index, 'versions', index.versions, trajectoryLimits.versions); if (!index.versions.has(key)) return; } - const originalProblemPassed = typeof record.originalProblemPassed === 'boolean' ? record.originalProblemPassed : undefined; + const originalProblemPassed = originalVerdict(record); let check = version.checks.find(item => item.at === at && item.originalProblemPassed === originalProblemPassed && item.taskVersion === receipt.taskVersion); if (check?.receiptIds.includes(receipt.id)) return; if (!check) { @@ -157,12 +167,14 @@ function foldCheck(index: TrajectoryIndex, receipt: WebCheckReceipt, observation check = { at, passed: true, status: 'kernel_verified', receiptIds: [], theorems: [], observation, taskVersion: receipt.taskVersion, ...(typeof record.proofPath === 'string' ? { file: record.proofPath } : {}), ...(originalProblemPassed === undefined ? {} : { originalProblemPassed }) }; + index.receiptFrames.set(check, []); version.checks.push(check); version.checks.sort((a, b) => a.at - b.at); version.firstAt = Math.min(version.firstAt, at); } if (check.receiptIds.length >= trajectoryLimits.receipts) return; check.receiptIds.push(receipt.id); + index.receiptFrames.get(check)!.push(observation); const theorem = typeof record.theoremName === 'string' ? record.theoremName : undefined; if (theorem && !check.theorems.includes(theorem)) check.theorems.push(theorem); if (record.passed !== true && check.passed) { @@ -304,25 +316,52 @@ export function trajectoryPage(index: TrajectoryIndex, query: TrajectoryQuery, b } /** One version's saved file and receipts, read only from the observations the index recorded for it. */ -export type TrajectoryVersionDetail = { taskId: string; commit: string; source?: WebTaskSource; checks: WebCheckReceipt[] }; +export type TrajectoryVersionDetail = { taskId: string; commit: string; source?: WebTaskSource; checks: WebCheckReceipt[]; objective?: string }; +export function selectTrajectoryChecks(version: TrajectoryVersion, taskVersion?: string, receiptId?: string, checkAt?: number) { + return version.checks.filter(check => (taskVersion === undefined || check.taskVersion === taskVersion) && + (checkAt === undefined || check.at === checkAt) && + (receiptId === undefined || check.receiptIds.includes(receiptId))); +} export function trajectoryVersionDetail(index: TrajectoryIndex, version: TrajectoryVersion, - observation: (sequence: number) => WebObservation | undefined, taskVersion?: string): TrajectoryVersionDetail { - const selected = taskVersion === undefined ? version.checks : version.checks.filter(check => check.taskVersion === taskVersion); - const sourceFrame = taskVersion === undefined ? version.source - : index.sourceRevisions.get(sourceRevisionKey(version.key, taskVersion)); - const sequences = [...new Set([...(sourceFrame !== undefined ? [sourceFrame] : []), ...selected.map(check => check.observation)])]; - const receipts = new Set(selected.flatMap(check => check.receiptIds)); - const matches = (item: WebTaskSource | WebCheckReceipt) => item.taskId === version.taskId && item.commit === version.commit && - (taskVersion === undefined || item.taskVersion === taskVersion); + observation: (sequence: number) => WebObservation | undefined, taskVersion?: string, selected = selectTrajectoryChecks(version, taskVersion)): TrajectoryVersionDetail { + const exactVersion = taskVersion ?? (selected.length === 1 ? selected[0]!.taskVersion : undefined); + const sourceFrame = exactVersion === undefined ? version.source : index.sourceRevisions.get(sourceRevisionKey(version.key, exactVersion)); + const identity = (taskVersion: string | undefined, id: string, at: number, verdict: boolean | undefined) => + JSON.stringify([taskVersion, id, at, verdict]); + const matches = (item: WebTaskSource | WebCheckReceipt) => item.taskId === version.taskId && item.commit === version.commit; + const frames = new Map>(); + if (sourceFrame !== undefined) frames.set(sourceFrame, new Map()); + for (const check of selected) for (const [offset, sequence] of (index.receiptFrames.get(check) ?? []).entries()) { + const wanted = frames.get(sequence) ?? new Map(); + wanted.set(identity(check.taskVersion, check.receiptIds[offset]!, check.at, check.originalProblemPassed), check); + frames.set(sequence, wanted); + } let source: WebTaskSource | undefined; + let objective: string | undefined; const checks = new Map(); + // Inspect the check's own frame first for its task description. If the task changed before capture, history can carry it. + const exactCheck = selected.length === 1 ? selected[0] : undefined; + const sequences = [...new Set([...(exactCheck ? [exactCheck.observation] : []), ...frames.keys()])]; for (const sequence of sequences) { const item = observation(sequence); if (!item) continue; - source ??= item.sources.find(matches); - for (const check of item.checks) if (matches(check) && receipts.has(check.id) && !checks.has(check.id)) checks.set(check.id, check); + source ??= item.sources.find(entry => matches(entry) && (exactVersion === undefined || entry.taskVersion === exactVersion)); + if (exactCheck && exactVersion !== undefined) + objective ??= [...item.inspection.tasks, ...item.history ?? []].find(task => task.id === version.taskId && task.version === exactVersion)?.objective; + const wanted = frames.get(sequence); + if (!wanted?.size) continue; + const at = Date.parse(item.observedAt); + for (const check of item.checks) if (matches(check)) { + const time = receiptTime(check.record) ?? at; + const verdict = originalVerdict(check.record); + const key = Number.isFinite(time) ? identity(check.taskVersion, check.id, time, verdict) + : [...wanted].find(([, group]) => group.taskVersion === check.taskVersion && group.originalProblemPassed === verdict && + group.receiptIds.includes(check.id))?.[0]; + if (key && wanted.has(key) && !checks.has(key)) checks.set(key, check); + } } - return { taskId: version.taskId, commit: version.commit, ...(source ? { source } : {}), checks: [...checks.values()].slice(-64) }; + return { taskId: version.taskId, commit: version.commit, ...(source ? { source } : {}), checks: [...checks.values()], + ...(objective ? { objective } : {}) }; } /** Query parameters of the trajectory routes; undefined means the request is malformed. */ @@ -332,11 +371,15 @@ export function trajectoryQuery(params: URLSearchParams): TrajectoryQuery | unde if (instance !== undefined && !/^[a-z0-9-]{1,64}$/u.test(instance)) return; return { after, since, ...(instance ? { instance } : {}) }; } -export function trajectoryVersionQuery(params: URLSearchParams): { taskId: string; commit: string; taskVersion?: string } | undefined { - const taskId = params.get('task') ?? '', commit = params.get('commit') ?? '', taskVersion = params.get('taskVersion'); +export function trajectoryVersionQuery(params: URLSearchParams): { taskId: string; commit: string; taskVersion?: string; receiptId?: string; checkAt?: number } | undefined { + const taskId = params.get('task') ?? '', commit = params.get('commit') ?? '', taskVersion = params.get('taskVersion'), receiptId = params.get('receiptId'); + const checked = params.get('checkAt'), checkAt = checked === null ? undefined : Number(checked); if (!taskId || taskId.length > 200 || !/^[A-Za-z0-9]{1,128}$/u.test(commit) || - (taskVersion !== null && (!taskVersion || taskVersion.length > 200))) return; - return { taskId, commit, ...(taskVersion !== null ? { taskVersion } : {}) }; + (taskVersion !== null && (!taskVersion || taskVersion.length > 200)) || + (receiptId !== null && (!receiptId || receiptId.length > 200)) || + (checkAt !== undefined && (!checked || !Number.isSafeInteger(checkAt) || checkAt < 0))) return; + return { taskId, commit, ...(taskVersion !== null ? { taskVersion } : {}), ...(receiptId !== null ? { receiptId } : {}), + ...(checkAt !== undefined ? { checkAt } : {}) }; } export const trajectoryVersion = (index: TrajectoryIndex, taskId: string, commit: string) => index.versions.get(versionKey(taskId, commit)); @@ -365,16 +408,30 @@ export class WebTrajectories { const { index, behind } = this.read(owner, runId); return trajectoryPage(index, query, behind); } - version(owner: string, runId: string, taskId: string, commit: string, taskVersion?: string): TrajectoryVersionDetail | undefined { + version(owner: string, runId: string, taskId: string, commit: string, taskVersion?: string, receiptId?: string, checkAt?: number): TrajectoryVersionDetail | undefined { + const read = this.readVersion(owner, runId, taskId, commit, taskVersion, receiptId, checkAt); + return read && trajectoryVersionDetail(read.index, read.version, sequence => this.reader.getObservation(owner, runId, sequence), taskVersion, read.checks); + } + explanationVersion(owner: string, runId: string, taskId: string, commit: string, taskVersion?: string, receiptId?: string, checkAt?: number) { + const read = this.readVersion(owner, runId, taskId, commit, taskVersion, receiptId, checkAt, checkAt === undefined); + if (!read) return { status: 'missing' } as const; + const failed = read.checks.filter(check => !check.passed); + if ((receiptId !== undefined && read.checks.length > 1) || failed.length > 1) return { status: 'ambiguous' } as const; + if (!failed.length) return { status: 'passed' } as const; + const detail = trajectoryVersionDetail(read.index, read.version, sequence => this.reader.getObservation(owner, runId, sequence), taskVersion, failed); + return { status: 'found', detail } as const; + } + private readVersion(owner: string, runId: string, taskId: string, commit: string, taskVersion?: string, receiptId?: string, checkAt?: number, complete = false) { const find = (index: TrajectoryIndex) => { const version = trajectoryVersion(index, taskId, commit); - if (taskVersion === undefined || version?.checks.some(check => check.taskVersion === taskVersion)) return version; + if (!version) return; + const checks = selectTrajectoryChecks(version, taskVersion, receiptId, checkAt); + if (checks.length) return { index, version, checks }; }; let read = this.read(owner, runId); // A rebuilt index catches up before answering, a bounded number of chunks at a time. - for (let chunk = 0; read.behind && !find(read.index) && chunk < 50; chunk++) read = this.read(owner, runId); - const version = find(read.index); - return version && trajectoryVersionDetail(read.index, version, sequence => this.reader.getObservation(owner, runId, sequence), taskVersion); + for (let chunk = 0; read.behind && (complete || !find(read.index)) && chunk < 50; chunk++) read = this.read(owner, runId); + return find(read.index); } forget(owner: string, runId: string) { this.indexes.delete(`${owner}\u0000${runId}`); } forgetOwner(owner: string) { for (const key of [...this.indexes.keys()]) if (key.startsWith(`${owner}\u0000`)) this.indexes.delete(key); } diff --git a/apps/web/worker.ts b/apps/web/worker.ts index fe1458ce..28d8961c 100644 --- a/apps/web/worker.ts +++ b/apps/web/worker.ts @@ -357,9 +357,10 @@ async function main(watchdog: ReturnType watchdog.signal.throwIfAborted(); output = round.output; solverRunId = undefined; - writeWebActiveRun({ webRunId: request.id, directory, output }, path.join(workspaceRoot, 'active-run.json')); - bridge = createWebWorkerBridge({ webRunId: request.id, directory, output, apiKey: key, onMessage: send, - ...(round.previousSolverRunId ? { libraryRestart: { previousSolverRunId: round.previousSolverRunId, round: round.round } } : {}) }); + const active = { webRunId: request.id, directory, output, + ...(round.previousSolverRunId ? { libraryRestart: { previousSolverRunId: round.previousSolverRunId, round: round.round } } : {}) }; + writeWebActiveRun(active, path.join(workspaceRoot, 'active-run.json')); + bridge = createWebWorkerBridge({ ...active, apiKey: key, onMessage: send }); sampleArtifact = createWebArtifactSampler({ directory, output, workers: request.input.workers, source: request.input.source, apiKey: key, onArtifact: artifact => { latestArtifact = artifact; diff --git a/apps/web/workerBridge.ts b/apps/web/workerBridge.ts index 93eb1ab6..94454e2a 100644 --- a/apps/web/workerBridge.ts +++ b/apps/web/workerBridge.ts @@ -14,16 +14,20 @@ import { parseCooperationPlan, taskGroup, taskVersion, type TaskRecord } from '. import { allowedKnowledgeFile, buildTheoremKnowledge, validateTheoremKnowledge, type TheoremKnowledgeBase } from '../../src/solver/theoremKnowledge'; import { importKnowledgeRuns } from '../../src/solver/theoremKnowledgeRuns'; import { proofReceiptsMatch, type ProofCheck } from '../../src/solver/modules/evidence'; -import type { WebCheckReceipt, WebCommand, WebCommandResult, WebObservation, WebTaskSource } from './collaboration'; +import type { WebCheckReceipt, WebCommand, WebCommandResult, WebLibraryRestart, WebObservation, WebTaskSource } from './collaboration'; import type { WorkerMessage } from './shared'; import { projectWebDeclarationArtifacts } from './declarationArtifacts'; import { projectWebNativeTeam } from './nativeTeamObservation'; import { maxWorkerObservationBytes, standaloneObservationFrame, type WorkerObservationFrame } from './observationSources'; export const webActiveRunFile = '/work/active-run.json'; +const libraryRestartSchema = z.object({ previousSolverRunId: z.string().min(1).max(128), + round: z.number().int().positive().max(Number.MAX_SAFE_INTEGER) }).strict(); +type LibraryRestart = Omit; const activeRunSchema = z.object({ schema: z.literal('theorem-os.web-active-run.v1'), - webRunId: z.string().min(1).max(128), directory: z.string().min(1), output: z.string().min(1) }).strict(); -type ActiveRun = z.infer; + webRunId: z.string().min(1).max(128), directory: z.string().min(1), output: z.string().min(1), + libraryRestart: libraryRestartSchema.optional() }).strict(); +type ActiveRun = { webRunId: string; directory: string; output: string; libraryRestart?: LibraryRestart }; const metaSchema = z.object({ schema: z.literal('theorem-os.web-bridge.v1'), webRunId: z.string(), solverRunId: z.string(), libraryRound: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(), sequence: z.number().int().nonnegative(), contentDigest: z.string(), @@ -37,14 +41,15 @@ const childOf = (directory: string, file: string) => path.isAbsolute(file) && fi const relativePath = (file: string) => file && !path.isAbsolute(file) && !file.includes('\\') && file.split('/').every(part => part && part !== '.' && part !== '..'); -export function writeWebActiveRun(input: { webRunId: string; directory: string; output: string }, file = webActiveRunFile): void { +export function writeWebActiveRun(input: ActiveRun, file = webActiveRunFile): void { const directory = fs.realpathSync(input.directory), output = path.resolve(input.output); if (!childOf(directory, output)) throw new Error('web_bridge_output_outside_run'); - writeMathJsonDurable(file, { schema: 'theorem-os.web-active-run.v1', webRunId: input.webRunId, directory, output }); + writeMathJsonDurable(file, activeRunSchema.parse({ schema: 'theorem-os.web-active-run.v1', + webRunId: input.webRunId, directory, output, libraryRestart: input.libraryRestart })); } function readActiveRun(file: string): ActiveRun { - const value = activeRunSchema.parse(JSON.parse(readMathText(file, 8_192))); + const value = activeRunSchema.parse(JSON.parse(readMathText(file, 8_192))) as ActiveRun; if (path.resolve(value.directory) !== value.directory || fs.realpathSync(value.directory) !== value.directory || !childOf(value.directory, value.output)) throw new Error('web_bridge_active_run_invalid'); return value; @@ -57,7 +62,6 @@ export function freezeWebKnowledge(directory: string, catalog?: unknown): string return file; } -type LibraryRestart = { previousSolverRunId: string; round: number }; function bridgeMeta(file: string, webRunId: string, solverRunId: string, restart?: LibraryRestart): BridgeMeta | undefined { if (!fs.existsSync(file)) return; const value = metaSchema.parse(JSON.parse(readMathText(file, 32 * 1024))); @@ -141,7 +145,7 @@ function sourceProjection(state: SolverRunState, directory: string) { for (const receipt of proof.verification.results) { if (receipt.proofPath !== node.task.proofPath || receipt.theoremName !== node.task.theoremName) continue; const id = receipt.receiptId || `observation-${mathDigest(canonicalMathJson(receipt))}`; - const key = canonicalMathJson([node.task.id, version, proof.commit, id]); + const key = canonicalMathJson([node.task.id, version, proof.commit, id, proof.verification.checkedAt, original ? proof.passed : null]); if (checkIds.has(key)) continue; // The original-problem check can pass one target while failing the batch. const passed = original ? proofReceiptsMatch({ ...proof.verification, status: receipt.status, results: [receipt] }, proof.commit, [{ @@ -181,13 +185,21 @@ function sourceProjection(state: SolverRunState, directory: string) { } const wholeChecks = [state.check, ...(state.workers ?? []).map(worker => worker.check)] .filter((proof): proof is ProofCheck => proof !== undefined); - for (const node of state.cooperation?.tasks ?? []) if (node.task.kind === 'goal') { - const target = state.problem.targets.find(item => item.proofPath === node.task.proofPath && item.theoremName === node.task.theoremName); - if (!target) continue; - for (const proof of wholeChecks) if (proof.verification.results.some(receipt => - receipt.proofPath === target.proofPath && receipt.theoremName === target.theoremName)) addProof(node, proof, target); + for (const [index, target] of state.problem.targets.entries()) { + const node = state.cooperation?.tasks.find(item => item.task.kind === 'goal' && + item.task.proofPath === target.proofPath && item.task.theoremName === target.theoremName); + // Direct and independent runs use the same frozen target identity as their knowledge evidence. + const task = node?.task ?? { id: `original_goal_${index + 1}`, kind: 'goal' as const, + objective: `Prove ${target.theoremName}`, revision: 0, dependsOn: [], ...target }; + let found = false; + for (const proof of wholeChecks) { + if (proof.verification.results.some(receipt => receipt.proofPath === target.proofPath && receipt.theoremName === target.theoremName)) { + addProof({ task }, proof, target); + found = true; + } else checkPartial = true; + } + if (!node && !found) sourcePartial = true; } - if (!state.cooperation?.tasks.length && state.problem.targets.length) sourcePartial = true; return { sources, checks, coverage: { sources: sourcePartial ? 'partial' as const : 'recorded' as const, checks: checkPartial ? 'partial' as const : 'recorded' as const } }; } @@ -211,9 +223,11 @@ export function createWebWorkerBridge(options: { !options.libraryRestart.previousSolverRunId)) throw new Error('web_bridge_run_identity_changed'); // Each new bridge starts with a self-contained frame. Retain only the previous frame's digests. let emittedSources = new Set(); - async function capture(input: { includeCatalog?: boolean; force?: boolean } = {}) { + let captured = false; + async function capture(input: { includeCatalog?: boolean; force?: boolean; waitMs?: number } = {}) { const messages: WorkerMessage[] = []; - const result = await withMathRuntimeLease({ lockPath: path.join(directory, 'web-bridge.lock'), flockExecutable: '/usr/bin/flock' }, async lease => { + const result = await withMathRuntimeLease({ lockPath: path.join(directory, 'web-bridge.lock'), flockExecutable: '/usr/bin/flock', + waitMs: input.waitMs }, async lease => { const stored = readRunInspection(options.output), { state, stateFile } = stored; if (options.libraryRestart?.previousSolverRunId === state.runId) throw new Error('web_bridge_run_identity_changed'); const { agentTeam, ...report } = buildRunInspection(state, stored.result); @@ -245,8 +259,10 @@ export function createWebWorkerBridge(options: { const contentDigest = mathDigest(canonicalMathJson({ ...frame.observation, observedAt: '' })); const changed = restarted || previous?.contentDigest !== contentDigest; const sequence = (previous?.sequence ?? 0) + Number(changed); - if (restarted) messages.push({ type: 'library_restart', previousSolverRunId: previous!.solverRunId, - solverRunId: state.runId, round: options.libraryRestart!.round }); + const libraryRestart = previous && options.libraryRestart && { ...options.libraryRestart, solverRunId: state.runId }; + // Capture through docker exec can commit the new metadata before the streaming worker does. + const announceRestart = libraryRestart && options.onMessage && !captured; + if (announceRestart) messages.push({ type: 'library_restart', ...libraryRestart }); observation.sequence = sequence; frame.observation.sequence = sequence; let frameJson = JSON.stringify(frame); @@ -291,9 +307,10 @@ export function createWebWorkerBridge(options: { } lease.assertHeld(); if (!previous || canonicalMathJson(previous) !== canonicalMathJson(meta)) writeMathJsonDurable(metaFile, meta); - if (changed || input.force) messages.push({ type: 'observation', observation }); + captured = true; + if (changed || input.force || announceRestart) messages.push({ type: 'observation', observation }); if (catalog) messages.push({ type: 'catalog', catalog }); - return { frame, result: { observation, ...(catalog ? { catalog } : {}) } }; + return { frame, result: { observation, ...(catalog ? { catalog } : {}), ...(libraryRestart ? { libraryRestart } : {}) } }; }); for (const message of messages) { if (!options.onMessage) break; @@ -357,8 +374,9 @@ const commandSchema = z.discriminatedUnion('type', [ export async function handleWebWorkerCommand(value: unknown, options: { activeRunFile?: string } = {}): Promise { const command = commandSchema.parse(value) as WebCommand; const active = readActiveRun(options.activeRunFile ?? webActiveRunFile); - const bridge = createWebWorkerBridge({ webRunId: active.webRunId, directory: active.directory, output: active.output }); - if (command.type === 'capture') return { id: 'capture', status: 'captured', ...await bridge.capture({ includeCatalog: true, force: true }) }; + const bridge = createWebWorkerBridge({ ...active, libraryRestart: command.type === 'capture' ? active.libraryRestart : undefined }); + if (command.type === 'capture') return { id: 'capture', status: 'captured', + ...await bridge.capture({ includeCatalog: true, force: true, waitMs: 5_000 }) }; const { state, stateFile } = readRunInspection(active.output); if (command.type === 'guidance') { try { diff --git a/scripts/test-web-research-library-trials.ts b/scripts/test-web-research-library-trials.ts index aa5c1dd0..ddd79c8a 100644 --- a/scripts/test-web-research-library-trials.ts +++ b/scripts/test-web-research-library-trials.ts @@ -127,10 +127,19 @@ try { const proof = trial.getByRole('textbox', { name: tx('候选 Lean 证明体', 'Candidate Lean proof body'), exact: true }); const argumentsNote = trial.getByRole('textbox', { name: tx('参数如何对应(可选)', 'Argument mapping (optional)'), exact: true }); assert.equal(await proof.inputValue(), 'by\n intro n\n exact Shared.zero n'); - await argumentsNote.fill('Library n maps to task n'); await proof.fill('by\n exact Shared.zero n'); + await argumentsNote.fill('Library n maps to task n'); await proof.fill('by\n exact Shared.zero n\n'); const prepare = trial.getByRole('button', { name: tx('准备并审阅候选', 'Prepare candidate for review'), exact: true }); + const preparedResponse = page.waitForResponse(response => response.request().method() === 'POST' + && new URL(response.url()).pathname === `/api/research/library/${release.assetId}/releases/${release.version}/trials`); phase = `prepare-${width}-${language}`; await prepare.click(); + const prepared = await preparedResponse; assert.equal(prepared.status(), 201); + assert.equal(prepared.request().postDataJSON().proof, 'by\n exact Shared.zero n\n'); + const savedTrial: ResearchLibraryTrial = (await prepared.json()).item; + assert.equal(savedTrial.proof, 'by\n exact Shared.zero n'); + await page.waitForURL(url => url.searchParams.get('trial') === savedTrial.id); + await page.waitForFunction(value => document.querySelector('[data-library-trial] textarea[required]')?.value === value, savedTrial.proof); const review = trial.locator('[data-library-trial-review]'); await review.waitFor(); + assert.equal(JSON.parse(await goals.inputValue())[1], project.id, 'The owner’s project link chooses its binding even when a personal target is available'); assert.equal(compilerCalls.length, initialCalls, 'Preparing a candidate must not call the checker'); await review.getByText('import Submission.Library.Shared', { exact: false }).waitFor(); const check = review.getByRole('button', { name: tx('确认并独立检查', 'Confirm and check independently'), exact: true }); @@ -225,6 +234,22 @@ try { const reviewer = (await peerContext.cookies(origin)).find(item => item.name === 'theoremos_session')!.value; project = service.research.projects.setMember(owner, project.id, service.research.projects.identity(reviewer), { requestId: 'reviewer', expectedRevision: service.research.projects.detail(owner, project.id).revision, role: 'collaborator' }); + phase = `exact-project-target-${width}-${language}`; + let secondProject = service.research.projects.create(owner, { requestId: 'second-project', title: 'Another addition project', visibility: 'members' }); + secondProject = service.research.projects.addVersion(owner, secondProject.id, { requestId: 'second-statement', expectedRevision: secondProject.revision, + statement: 'Addition identity', source: original, environment: 'standard' }); + secondProject = service.research.projects.bindRun(owner, secondProject.id, { requestId: 'second-binding', expectedRevision: secondProject.revision, + runId: run.id, statementVersionId: secondProject.versions[0].id, exposure: 'members', grants: { proof: true } }); + secondProject = service.research.projects.setMember(owner, secondProject.id, service.research.projects.identity(reviewer), { + requestId: 'second-project-reviewer', expectedRevision: secondProject.revision, role: 'collaborator' }); + for (const exactProject of [project, secondProject]) { + const params = new URLSearchParams(entry); + params.set('project', exactProject.id); params.set('entry', release.assetId); params.set('version', release.version); + await peer.goto(`${origin}/library.html?${params}`); + const selectedGoal = peer.locator('[data-library-trial] select').first().locator('option:checked').filter({ hasText: exactProject.title }); + await selectedGoal.waitFor({ state: 'attached' }); + assert.deepEqual(JSON.parse((await selectedGoal.getAttribute('value'))!).slice(0, 5), [run.id, exactProject.id, 'target', 'task-v1', commit]); + } phase = `human-review-${width}-${language}`; await peer.goto(page.url()); const peerFeedback = peer.locator(`#feedback-${candidate.id}`); const frozenEvidence = peerFeedback.locator('[data-library-candidate-evidence]'); await frozenEvidence.locator(':scope > summary').click(); @@ -277,7 +302,7 @@ try { await trial.getByRole('alert').filter({ hasText: tx('任务版本或源码提交已经改变', 'The task version or source commit has changed') }).waitFor(); assert.equal(compilerCalls.length, beforeDiagnostics + 1); checks.push({ width, language, layout, trialId, confirmedCompileCalls: 5, uncertainAttempts: attempts.length, - preparedDoesNotCheck: true, draftAndReceiptRecovered: true, runUnchanged: true, staleSourceRejected: true, + preparedDoesNotCheck: true, trimmedProofReviewable: true, exactProjectTarget: true, draftAndReceiptRecovered: true, runUnchanged: true, staleSourceRejected: true, checkedExampleLoadedWithoutCompiler: true, explicitSharing: true, separateHumanApproval: true, reviewedNewAttemptPrepared: true, actualComposerLaunchIncludesFixedPack: true }); compiler = async value => ({ output: '', exitCode: 0, timedOut: false, checkedTarget: value.candidateTarget?.name }); await context.close(); active = undefined; diff --git a/scripts/test-web-trajectory.ts b/scripts/test-web-trajectory.ts index c084c9c6..cdfa569d 100644 --- a/scripts/test-web-trajectory.ts +++ b/scripts/test-web-trajectory.ts @@ -33,6 +33,7 @@ await fs.access(path.join(root, 'out/web/app.js')).catch(() => { throw new Error await fs.mkdir(output, { recursive: true }); const port = await freePort(), origin = `http://127.0.0.1:${port}`; const sample = loadWebSample()!, recording = withFailedAttempt(sample); +const doubleCheckTask = 'Fixture for explaining two Lean checks of the same commit'; /** A pause in the replay before one of its observations: `reached` once the replay waits there, `release` to go on. */ type Gate = { reached: Promise; arrive: () => void; release: () => void; open: Promise }; const gate = (): Gate => { @@ -52,6 +53,17 @@ const runner: WebRunner = { continued.push(input); send({ type: 'result', result: { status: 'incomplete', proof: input.continuation.source.replace('exact Nat.zero_add n', 'simp'), report: {} } }); return; } + if (input.input.task === doubleCheckTask) { + const frame = recording.observations.find(item => item.checks.some(check => check.id === 'lean-failed-attempt'))!; + const receipt = frame.checks.find(check => check.id === 'lean-failed-attempt')!, now = Date.now(); + const first = { ...receipt, record: { ...receipt.record, verification: { checkedAt: now - 2 } } }; + const second = { ...receipt, + record: { ...receipt.record, verification: { checkedAt: now - 1 }, stdoutPreview: 'Submission.lean:4:44: error: Different diagnostic for this check.' } }; + send({ type: 'observation', observation: { ...frame, observedAt: new Date(now).toISOString(), webRunId: input.id, + sequence: 1, plan: null, guidance: [], deliveries: [], checks: [first, second] } }); + send({ type: 'result', result: { status: 'incomplete', proof: '', report: {} } }); + return; + } let observations = 0; return replaySample(recording, input.id, send, signal, { hold: message => { if (message.type !== 'observation') return undefined; @@ -569,6 +581,40 @@ try { await page.keyboard.press('Escape'); await viewer(page).waitFor({ state: 'detached' }); mark('问为什么 asks the run\'s own model about a failed attempt, with the cost named first, the key asked once, follow-ups carrying the thread and 停止 giving the question back'); + await page.setViewportSize({ width: 1440, height: 900 }); + const rechecked = await postRun({ page }, { ...input, task: doubleCheckTask }, 'same commit recheck fixture'); + await waitForRun({ page }, rechecked.id, candidate => candidate.status === 'completed'); + await selectHistoryRun(page, rechecked.id); + await openTab(page, 'trajectory'); + const full = page.locator('[data-trajectory-detail="full"]'); + if (await full.getAttribute('aria-pressed') === 'false') await full.click(); + const retriesForCommit = step(page, '[data-kind="retries"]'); + await retriesForCommit.waitFor(); + if (await retriesForCommit.getAttribute('data-open') === 'false') await retriesForCommit.locator('.trajectory-fold').click(); + const failedChecks = step(page, '[data-kind="attempt"][data-tone="failed"]'); + const firstCheck = failedChecks.filter({ hasText: 'The rfl tactic failed.' }); + const secondCheck = failedChecks.filter({ hasText: 'Different diagnostic for this check.' }); + await open(page, firstCheck, 'ask'); + await question.fill('What did the first check say?'); + if (await viewer(page).locator('[data-ask-key]').count()) await viewer(page).locator('[data-ask-key]').fill(input.apiKey); + await viewer(page).locator('[data-ask-submit]').click(); + for (let tries = 0; explained.length < 5 && tries < 50; tries++) await page.waitForTimeout(100); + answerNext(); + await viewer(page).locator('.trajectory-ask-answer').waitFor(); + await page.keyboard.press('Escape'); + await viewer(page).waitFor({ state: 'detached' }); + await open(page, secondCheck, 'ask'); + assert.equal(await viewer(page).locator('.trajectory-ask-turn').count(), 0, 'another check of the same commit opens a fresh thread'); + assert.equal(await question.inputValue(), '这一步为什么没通过?应该怎么改?'); + await viewer(page).locator('[data-ask-submit]').click(); + for (let tries = 0; explained.length < 6 && tries < 50; tries++) await page.waitForTimeout(100); + assert.deepEqual(explained[5]!.body.input.map(item => item.role), ['user']); + const revisedContext = explained[5]!.body.input[0]!.content[0]!.text; + assert.match(revisedContext, /Different diagnostic for this check/u); + assert.doesNotMatch(revisedContext, /The rfl tactic failed|What did the first check say/u); + answerNext(); + await viewer(page).locator('.trajectory-ask-answer').waitFor(); + mark('rechecking the same commit keeps its Lean output and Ask Why conversation with the selected check'); assert.deepEqual(errors, []); console.log('Trajectory checks passed: sample, detail level, live following and line guidance, feedback, comparison, time overview, filter, polling, narrow layout, continuing from a version and asking why a step failed.'); } finally { diff --git a/src/math/leanProofSearch.ts b/src/math/leanProofSearch.ts index ef19d7ef..21102a81 100644 --- a/src/math/leanProofSearch.ts +++ b/src/math/leanProofSearch.ts @@ -8,6 +8,7 @@ import { scheduleMathTimeout } from './mathTimers'; import { resolveMathematicsRuntimeEnvironment } from './mathRuntimeEnvironment'; import { prepareLeanSearchProjection, prepareRetainedLeanSearchProjection } from './leanSearchProjection'; import { openPantographSession, readPantographBackend, type ProofSearchSession } from './pantographSession'; +import { localProofSearchPath, projectedProofSearchPath, proofSearchDirectory } from './proofSearchCheckpointPath'; const digest = z.string().regex(/^[a-f0-9]{64}$/u); const identity = z.string().min(1).max(256); @@ -79,13 +80,14 @@ function validateCheckpoint(checkpoint: ProofSearchCheckpoint, basis: ProofSearc throw new Error('proof_search_checkpoint_invalid'); } -function readCheckpoint(project: string, reference: SearchCheckpointReference) { +function readCheckpoint(project: string, reference: SearchCheckpointReference, history?: string) { const file = path.resolve(project, reference.path); assertMathCanonicalPath(file); const bytes = readMathFile(file, checkpointLimit).bytes; if (mathDigest(bytes) !== reference.digest) throw new Error('proof_search_stale_checkpoint_digest'); const value = proofSearchCheckpointSchema.parse(JSON.parse(bytes.toString('utf8'))); const basisDigest = mathDigest(canonicalMathJson(value.basis)); - if (file !== path.join(project, '.lake/proof-search', basisDigest, `${value.generation}.json`)) + if (file !== localProofSearchPath(project, basisDigest, value.generation, history) && + file !== projectedProofSearchPath(project, basisDigest, value.generation, reference.digest, history)) throw new Error('proof_search_stale_checkpoint_path'); validateCheckpoint(value, value.basis); return value; @@ -185,6 +187,8 @@ export type LeanProofSearchStatus = 'candidate' | 'exhausted' | 'budget-exhauste export async function searchLeanBranches(input: { projectRoot: string; file: string; theoremName: string; type: string; scope: LeanProofSearchScope; request: unknown; env?: NodeJS.ProcessEnv; signal?: AbortSignal; + /** Host-assigned history for a search performed as part of an independent check. */ + history?: string; /** An ordinary worker search may start at the current root if its implicit resume has a different basis. */ restartStaleImplicitResume?: boolean; /** Only a host-scoped independent nextCheck may replay the explicitly retained source instead of live owned files. */ @@ -192,6 +196,7 @@ export async function searchLeanBranches(input: { onCheckpoint?: (reference: SearchCheckpointReference) => void; }) { const request = proofSearchRequestSchema.parse(input.request), scope = proofSearchScopeSchema.parse(input.scope); + const history = digest.optional().parse(input.history); const startedAt = Date.now(); const env = resolveMathematicsRuntimeEnvironment(input.env ?? process.env), project = fs.realpathSync(input.projectRoot); const controller = new AbortController(), abort = () => controller.abort(); @@ -212,7 +217,7 @@ export async function searchLeanBranches(input: { if (input.retainedInput) { if (!request.resume || request.resume.digest !== input.retainedInput.checkpointDigest) throw new Error('proof_search_stale_retained_checkpoint'); - const saved = readCheckpoint(project, request.resume); + const saved = readCheckpoint(project, request.resume, history); if (mathDigest(canonicalMathJson(saved.basis)) !== input.retainedInput.basisDigest || canonicalMathJson(saved.basis.scope) !== canonicalMathJson(scope) || canonicalMathJson(saved.basis.target) !== canonicalMathJson({ file: input.file, theoremName: input.theoremName, type: input.type })) @@ -224,20 +229,31 @@ export async function searchLeanBranches(input: { const basis: ProofSearchBasis = { scope, sourceDigest: projection.sourceDigest, projectionDigest: projection.projectionDigest, backendDigest: backend.digest, target: { file: input.file, theoremName: input.theoremName, type: input.type }, environment: projection.environment, sourceFiles: projection.sourceFiles }; - const basisDigest = mathDigest(canonicalMathJson(basis)), directory = path.join(project, '.lake/proof-search', basisDigest); + const basisDigest = mathDigest(canonicalMathJson(basis)), directory = proofSearchDirectory(project, basisDigest, history); assertMathCanonicalPath(directory); fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); await withMathRuntimeLease({ lockPath: path.join(directory, 'writer.lock'), flockExecutable: '/usr/bin/flock' }, async () => { controller.signal.throwIfAborted(); - const generations = fs.readdirSync(directory).filter(name => /^\d+\.json$/u.test(name)).map(name => Number(name.slice(0, -5))); - const latest = generations.length ? Math.max(...generations) : -1; + const names = fs.readdirSync(directory); + const generations = names.filter(name => /^\d+\.json$/u.test(name)).map(name => Number(name.slice(0, -5))); + const latestLocal = generations.length ? Math.max(...generations) : -1; + const projected = names.flatMap(name => { + const match = /^retained-(0|[1-9][0-9]*)-([a-f0-9]{64})\.json$/u.exec(name); + return match ? [{ name, generation: Number(match[1]), digest: match[2]! }] : []; + }).sort((a, b) => b.generation - a.generation)[0]; + const latest = Math.max(latestLocal, projected?.generation ?? -1); const requireLatestResume = () => { - const file = path.join(directory, `${latest}.json`); assertMathCanonicalPath(file); - reference = { path: path.relative(project, file), digest: mathDigest(readMathFile(file, checkpointLimit).bytes) }; - checkpoint = readCheckpoint(project, reference); validateCheckpoint(checkpoint, basis); + if (latestLocal === latest) { + const file = localProofSearchPath(project, basisDigest, latest, history); assertMathCanonicalPath(file); + reference = { path: path.relative(project, file), digest: mathDigest(readMathFile(file, checkpointLimit).bytes) }; + } else { + reference = { path: path.relative(project, path.join(directory, projected!.name)), digest: projected!.digest }; + } + checkpoint = readCheckpoint(project, reference, history); + validateCheckpoint(checkpoint, basis); throw new Error('proof_search_stale_resume_required: use the returned latest checkpoint'); }; if (request.resume) { - checkpoint = readCheckpoint(project, request.resume); + checkpoint = readCheckpoint(project, request.resume, history); if (input.restartStaleImplicitResume && !input.retainedInput && !request.branches.some(branch => branch.from) && canonicalMathJson(checkpoint.basis) !== canonicalMathJson(basis)) checkpoint = undefined; else { @@ -259,7 +275,7 @@ export async function searchLeanBranches(input: { proofSearchCheckpointSchema.parse(value); const text = canonicalMathJson(value); if (Buffer.byteLength(text) > checkpointLimit) throw new Error('proof_search_checkpoint_size_limit'); - const file = path.join(directory, `${value.generation}.json`); assertMathCanonicalPath(file); + const file = localProofSearchPath(project, basisDigest, value.generation, history); assertMathCanonicalPath(file); if (fs.existsSync(file)) throw new Error('proof_search_checkpoint_generation_conflict'); writeMathTextDurable(file, text, 0o400); reference = { path: path.relative(project, file), digest: mathDigest(text) }; @@ -287,12 +303,12 @@ export async function searchLeanBranches(input: { } // Full fragments remain in scratch. The command response is a bounded preview even for long resumed paths. const candidateArtifacts = candidates.map(candidate => { - const relative = `.lake/proof-search/${mathDigest(canonicalMathJson(checkpoint!.basis))}/candidate-${candidate.node}.lean`; - const file = path.join(project, relative); assertMathCanonicalPath(file); + const directory = proofSearchDirectory(project, mathDigest(canonicalMathJson(checkpoint!.basis)), history); + const file = path.join(directory, `candidate-${candidate.node}.lean`); assertMathCanonicalPath(file); writeMathTextDurable(file, candidate.proofSource, 0o400); return { node: candidate.node, proofSource: limitMathOutput(candidate.proofSource, 4000, 'head'), truncated: Buffer.byteLength(candidate.proofSource) > 4000, - artifact: { path: relative, digest: mathDigest(candidate.proofSource), bytes: Buffer.byteLength(candidate.proofSource) } }; + artifact: { path: path.relative(project, file), digest: mathDigest(candidate.proofSource), bytes: Buffer.byteLength(candidate.proofSource) } }; }); const frontier = checkpoint?.nodes.filter(node => node.status === 'open').slice(-8).map(node => ({ node: node.id, preview: limitMathOutput(JSON.stringify(node.view ?? null), 1600, 'head'), diff --git a/src/math/mathRuntimeIo.ts b/src/math/mathRuntimeIo.ts index 8515e225..fc536e42 100644 --- a/src/math/mathRuntimeIo.ts +++ b/src/math/mathRuntimeIo.ts @@ -211,6 +211,7 @@ export async function withMathRuntimeLease( lockPath: string; flockExecutable: string; shared?: boolean; + waitMs?: number; signal?: AbortSignal; }>, operation: (lease: MathLease) => Promise @@ -238,7 +239,8 @@ export async function withMathRuntimeLease( await new Promise((resolve, reject) => { const child = spawn( input.flockExecutable, - [input.shared ? '--shared' : '--exclusive', '--nonblock', '--conflict-exit-code', '73', '3'], + [input.shared ? '--shared' : '--exclusive', ...(input.waitMs ? ['--timeout', String(input.waitMs / 1000)] : ['--nonblock']), + '--conflict-exit-code', '73', '3'], { stdio: ['ignore', 'ignore', 'ignore', descriptor], windowsHide: true } ); let spawnFailed = false; @@ -247,7 +249,7 @@ export async function withMathRuntimeLease( }); const timeout = setTimeout(() => { child.kill('SIGKILL'); - }, 10_000); + }, Math.max(10_000, (input.waitMs ?? 0) + 1_000)); child.once('close', (code) => { clearTimeout(timeout); if (!spawnFailed && code === 0) resolve(); diff --git a/src/math/proofSearchCheckpointPath.ts b/src/math/proofSearchCheckpointPath.ts new file mode 100644 index 00000000..fb511d54 --- /dev/null +++ b/src/math/proofSearchCheckpointPath.ts @@ -0,0 +1,14 @@ +import path from 'node:path'; + +export function proofSearchDirectory(project: string, basis: string, history?: string) { + const root = path.join(project, '.lake/proof-search', basis); + return history ? path.join(root, history) : root; +} + +export function projectedProofSearchPath(project: string, basis: string, generation: number, digest: string, history?: string) { + return path.join(proofSearchDirectory(project, basis, history), `retained-${generation}-${digest}.json`); +} + +export function localProofSearchPath(project: string, basis: string, generation: number, history?: string) { + return path.join(proofSearchDirectory(project, basis, history), `${generation}.json`); +} diff --git a/src/solver/cooperation.ts b/src/solver/cooperation.ts index 1c063789..c5957f84 100644 --- a/src/solver/cooperation.ts +++ b/src/solver/cooperation.ts @@ -1,4 +1,3 @@ -import { proofSearchRecordMatches } from './proofSearchRecords'; import { isAdvisoryTask as advisory } from './tasks'; import fs from 'node:fs'; import path from 'node:path'; @@ -1285,8 +1284,7 @@ export class CooperativeResearch extends CooperationInputs { if (action?.kind === 'lead' && !this.active.has(this.lead.id) && !this.presentedNextCheckOutcomes.has(action)) this.presentedNextCheckOutcomes.set(action, (this.archive.nextChecks ?? []).flatMap(record => record.status === 'awaiting-decision' && record.outcome ? [{ checkId: record.id, outcomeDeliveryId: record.outcome.deliveryId }] : [])); - const searchScope = action?.kind === 'task' ? this.proofSearchScope(action) : undefined; - const searchRecord = searchScope && this.archive.proofSearchRecords?.[searchScope.taskId]; + const searchRecord = action?.kind === 'task' ? this.proofSearchAssignment(action).record : undefined; const guidance = checkpointWorkerId ? readHumanGuidance(path.join(path.dirname(this.lead.worktree), 'state.json'), this.input.state.runId) .filter(item => { if (item.status !== 'delivered' || !item.deliveredTo?.includes(checkpointWorkerId)) return false; @@ -1302,8 +1300,7 @@ export class CooperativeResearch extends CooperationInputs { leadResearchInputIds: this.presentedResearchInputs.get(action)!.shown.map(record => record.id), leadResearchInputCount: this.presentedResearchInputs.get(action)!.total, } : {}), - proofSearchRecords: searchScope && proofSearchRecordMatches(searchRecord, searchScope) - ? { [searchScope.taskId]: searchRecord } : undefined, + proofSearchRecords: searchRecord ? { [searchRecord.taskId]: searchRecord } : undefined, goalProgress: action?.kind === 'lead' || worker?.id === this.lead.id ? this.archive.goalProgress : action?.kind === 'task' ? goalProgressForTask(this.archive.goalProgress, action.task) : undefined, goalPathReview: action?.kind === 'lead' || worker?.id === this.lead.id ? this.goalPathReview() : undefined, diff --git a/src/solver/cooperationCore.ts b/src/solver/cooperationCore.ts index 0ffcbb26..abcf5561 100644 --- a/src/solver/cooperationCore.ts +++ b/src/solver/cooperationCore.ts @@ -43,7 +43,7 @@ import { digest, ReviewRecord, HumanEditRecord, CooperationState, TaskVersions, import { emptyLeadWakes, leadWakePending, reopenLeadWakes, requestLeadWake, type LeadWakeReason } from './leadWakes'; import { MAX_INVALID_TASK_TRANSITIONS, setTaskStatus, type TaskStatus, type TaskTransitionCause } from './taskLifecycle'; import { planApprovalStatus } from './planApproval'; -import { projectProofSearchRecord, proofSearchTargetForAssignment } from './proofSearchRecords'; +import { projectProofSearchRecord, proofSearchCheckForAssignment, proofSearchRecordForAssignment } from './proofSearchRecords'; import { answerGoalProgress, GOAL_PROGRESS_REVIEW_MS, goalProgressTaskContext, observeGoalProgress, resetGoalProgressClock, type GoalProgressDecision } from './goalProgress'; @@ -676,9 +676,9 @@ export abstract class CooperationCore { for (const worker of this.input.workers) { const action = this.active.get(worker.id)?.action; const scoped = this.contextState(action, worker, versions); - const search = action?.kind === 'task' ? projectProofSearchRecord({ - record: this.archive.proofSearchRecords?.[this.proofSearchScope(action).taskId], - scope: this.proofSearchScope(action), + const searchAssignment = action?.kind === 'task' ? this.proofSearchAssignment(action) : undefined; + const search = searchAssignment ? projectProofSearchRecord({ + ...searchAssignment, projectRoot: path.join(worker.worktree, this.input.state.problem.projectRelative), runDirectory: path.dirname(this.lead.worktree), }) : undefined; @@ -746,11 +746,15 @@ export abstract class CooperationCore { this.wake(); } /** An independent scoped check may continue its explicit target's advisory search, never an arbitrary task. */ - protected proofSearchScope(action: Extract) { + protected proofSearchAssignment(action: Extract) { const identity = { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }; const checks = (this.archive.nextChecks ?? []).filter(record => currentNextCheck(record, this.archive, identity)); - return { ...identity, ...proofSearchTargetForAssignment(action.assignment, checks, identity) }; + const check = proofSearchCheckForAssignment(action.assignment, checks, identity); + const { taskId, taskDigest } = check?.scope.target ?? action.assignment; + const scope = { ...identity, taskId, taskDigest }; + return { scope, record: proofSearchRecordForAssignment(this.archive.proofSearchRecords, scope, check), + history: check?.id, requiredBasisDigest: check?.scope.executionBasisDigest }; } /** With --plan-approval, the first accepted plan holds every worker until a human approves its exact version. */ protected planApprovalPending() { diff --git a/src/solver/cooperationInputs.ts b/src/solver/cooperationInputs.ts index 983e170e..086e7548 100644 --- a/src/solver/cooperationInputs.ts +++ b/src/solver/cooperationInputs.ts @@ -567,13 +567,14 @@ export abstract class CooperationInputs extends CooperationPlanning { return; } if (value.kind === 'progress') { - const search = details.searchCheckpoint && retainProofSearchCheckpoint({ + const searchAssignment = details.searchCheckpoint && this.proofSearchAssignment(action); + const search = searchAssignment && retainProofSearchCheckpoint({ + ...searchAssignment, projectRoot: path.join(worker.worktree, this.input.state.problem.projectRelative), - runDirectory: path.dirname(this.lead.worktree), reference: details.searchCheckpoint, - scope: this.proofSearchScope(action), + runDirectory: path.dirname(this.lead.worktree), reference: details.searchCheckpoint!, workerId: worker.id, assignmentKey, }); - const latestSearch = search && latestProofSearchRecord(this.archive.proofSearchRecords?.[search.taskId], search); + const latestSearch = search && latestProofSearchRecord(this.archive.proofSearchRecords?.[action.task.id], search); if (details.mathematicalGap) bindMathematicalGap(details.mathematicalGap, node.task, this.archive, { problemReceiptDigest: this.input.state.problem.receiptDigest, environmentDigest: this.input.state.environmentDigest }); this.reportBlockers(node.task, value.blockers); @@ -581,7 +582,7 @@ export abstract class CooperationInputs extends CooperationPlanning { ...this.dependencies(node.task).filter(dependency => !['integrated', 'completed'].includes(dependency.status)).map(dependency => dependency.task.id)])] as string[]; if (value.needsDecision === true) this.wakeLead('progress-decision-requested'); if (latestSearch) { - (this.archive.proofSearchRecords ??= {})[latestSearch.taskId] = latestSearch; + (this.archive.proofSearchRecords ??= {})[action.task.id] = latestSearch; this.input.emit('proof_search_checkpoint_saved', { taskId: latestSearch.taskId, taskDigest: latestSearch.taskDigest, workerId: worker.id, basisDigest: latestSearch.basisDigest, generation: latestSearch.generation, checkpoint: latestSearch.checkpoint, proofAcceptance: 'not-accepted' }); diff --git a/src/solver/nextCheckContract.ts b/src/solver/nextCheckContract.ts index bd5e1dae..93122bd0 100644 --- a/src/solver/nextCheckContract.ts +++ b/src/solver/nextCheckContract.ts @@ -1,6 +1,7 @@ import { z } from 'zod'; import { nextCheckSchema } from './mathematicalGapContract'; import { knowledgeApplicationReportSchema } from './knowledgeUsageContract'; +import { proofSearchRecordSchema } from './proofSearchRecords'; const hash = z.string().regex(/^[a-f0-9]{64}$/u); const text = z.string().trim().min(1).max(2000); @@ -31,6 +32,8 @@ export const nextCheckRecordSchema = z.object({ origin: z.literal('definition-contract').optional(), id: hash, gapDeliveryId: z.string().min(1).optional(), taskId: z.string().min(1), taskDigest: hash, check: nextCheckSchema, scope: nextCheckScopeSchema, + /** Exact host-adopted checkpoint from which this independent search starts. */ + proofSearchSeed: proofSearchRecordSchema.optional(), status: z.enum(['pending', 'awaiting-decision', 'decided', 'stale']), createdAt: z.number().int().nonnegative(), outcome: checkOutcomeSchema.extend({ deliveryId: z.string().min(1), commit: z.string().optional() }).strict().optional(), diff --git a/src/solver/nextChecks.ts b/src/solver/nextChecks.ts index 9ca8da47..ac1c8474 100644 --- a/src/solver/nextChecks.ts +++ b/src/solver/nextChecks.ts @@ -7,7 +7,7 @@ import { isAdvisoryTask, isFeasibilityReview, taskGroup, taskVersion, type Coope import { independentFeasibilityWorker } from './modules/organization'; import { currentDefinitionContractCheck } from './definitionContractChecks'; import type { ProofRoute } from './proofRoutes'; -import type { ProofSearchRecord } from './proofSearchRecords'; +import { proofSearchRecordMatches, type ProofSearchRecord } from './proofSearchRecords'; type Identity = { problemReceiptDigest: string; environmentDigest: string }; type State = { tasks: readonly TaskRecord[]; deliveries?: readonly DeliveryRecord[]; nextChecks?: readonly NextCheckRecord[]; @@ -29,16 +29,19 @@ export function nextCheckTarget(gap: Gap, state: State): CooperativeTask | undef } /** Check host-adopted identity, not a worker-supplied basis or a host/worker path spelling. */ -function executionSearchBasis(check: NextCheck, target: CooperativeTask, state: State, identity: Identity, - requireCheckpointMatch: boolean): string | undefined | null { +function executionSearchSeed(check: NextCheck, target: CooperativeTask, state: State, identity: Identity, + requireCheckpointMatch: boolean): ProofSearchRecord | undefined | null { const execution = check.execution; if (execution?.kind !== 'proof-search' || !execution.checkpoint && !execution.basis && !execution.node) return; - const record = state.proofSearchRecords?.[target.id]; - if (!record || record.taskId !== target.id || record.taskDigest !== taskVersion(target) || - record.problemReceiptDigest !== identity.problemReceiptDigest || record.environmentDigest !== identity.environmentDigest || - execution.basis && execution.basis !== record.basisDigest || - requireCheckpointMatch && execution.checkpoint && execution.checkpoint.digest !== record.checkpoint.digest) return null; - return record.basisDigest; + const scope = { ...identity, ...reference(target) }; + const matches = (record: ProofSearchRecord | undefined): record is ProofSearchRecord => + proofSearchRecordMatches(record, scope) && (!execution.basis || execution.basis === record.basisDigest); + // A reported digest can identify a retained independent history. Without one, use the owner's history. + const checkpoint = requireCheckpointMatch ? execution.checkpoint : undefined; + if (checkpoint) return Object.values(state.proofSearchRecords ?? {}).find(record => + record.checkpoint.digest === checkpoint.digest && matches(record)) ?? null; + const owner = state.proofSearchRecords?.[target.id]; + return matches(owner) ? owner : null; } const shellQuote = (value: string) => "'" + value.replaceAll("'", "'\"'\"'") + "'"; @@ -57,8 +60,10 @@ function executionInstructions(record: Pick item.id === gap.deliveryId); const scope = { ...identity, parent: reference(gap.scope.source), target: reference(target), consumer: reference(gap.scope.consumer), dependencies: gap.scope.dependencies, gapScopeDigest: hash(gap.scope), ...(gap.commit ? { sourceCommit: gap.commit } : {}), ...(delivery?.sourceDigest ? { sourceDigest: delivery.sourceDigest } : {}), ...(gap.nextCheck.execution ? { executionContext: { file: target.proofPath!, declaration: target.theoremName! } } : {}), - ...(executionBasisDigest ? { executionBasisDigest } : {}) }; + ...(proofSearchSeed ? { executionBasisDigest: proofSearchSeed.basisDigest } : {}) }; // Notes-only commits do not create another investigation of identical mathematical inputs. const execution = gap.nextCheck.execution; const check = execution?.kind === 'proof-search' && execution.checkpoint @@ -97,7 +102,8 @@ export function proposedNextChecks(state: State, identity: Identity, now: number const taskId = `gap_check_${id.slice(0, 40)}`; const task = checkTask({ id, taskId, check: gap.nextCheck, scope }, gap); const record: NextCheckRecord = { id, gapDeliveryId: gap.deliveryId, taskId, taskDigest: taskVersion(task), - check: gap.nextCheck, scope, status: 'pending', createdAt: now }; + check: gap.nextCheck, scope, status: 'pending', createdAt: now, + ...(proofSearchSeed ? { proofSearchSeed } : {}) }; return [{ record, node: { task, status: 'pending' as const, attempts: 0, nextCheckId: id } }]; }); } @@ -115,8 +121,17 @@ export function currentNextCheck(record: NextCheckRecord, state: State, identity if (record.check.execution) { if (!record.scope.executionContext || record.scope.executionContext.file !== target.proofPath || record.scope.executionContext.declaration !== target.theoremName) return false; - const basis = executionSearchBasis(record.check, target, state, identity, false); - if (basis === null || basis !== record.scope.executionBasisDigest) return false; + if (record.proofSearchSeed) { + const { proofSearchSeed: seed } = record, execution = record.check.execution; + if (execution.kind !== 'proof-search' || !record.scope.executionBasisDigest || + !proofSearchRecordMatches(seed, { ...identity, ...reference(target) }) || + seed.basisDigest !== record.scope.executionBasisDigest || + execution.basis && execution.basis !== seed.basisDigest || + execution.checkpoint && execution.checkpoint.digest !== seed.checkpoint.digest) return false; + } else { + const seed = executionSearchSeed(record.check, target, state, identity, false); + if (seed === null || seed?.basisDigest !== record.scope.executionBasisDigest) return false; + } } else if (record.scope.executionContext || record.scope.executionBasisDigest) return false; const gap = state.deliveries?.find(delivery => delivery.id === record.gapDeliveryId); return Boolean(gap && gap.status !== 'superseded' && gap.mathematicalGap?.nextCheck && gap.mathematicalGapScope && diff --git a/src/solver/proofSearchRecords.ts b/src/solver/proofSearchRecords.ts index b7175bf7..b4baa67d 100644 --- a/src/solver/proofSearchRecords.ts +++ b/src/solver/proofSearchRecords.ts @@ -4,15 +4,21 @@ import { z } from 'zod'; import type { NextCheckRecord } from './nextCheckContract'; import { assertMathCanonicalPath } from '../math/paths'; import { canonicalMathJson, mathDigest, parseMathJson, readMathFile, writeMathTextDurable } from '../math/mathRuntimeIo'; +import { localProofSearchPath, projectedProofSearchPath } from '../math/proofSearchCheckpointPath'; -/** Select a host-authorized next-check target from the current projected records, otherwise the assigned task. */ -export function proofSearchTargetForAssignment(assignment: { taskId: string; taskDigest: string }, +export function proofSearchCheckForAssignment(assignment: { taskId: string; taskDigest: string }, currentChecks: readonly NextCheckRecord[], identity: { problemReceiptDigest: string; environmentDigest: string }) { - const check = currentChecks.find(record => record.taskId === assignment.taskId && record.taskDigest === assignment.taskDigest && + return currentChecks.find(record => record.taskId === assignment.taskId && record.taskDigest === assignment.taskDigest && record.status === 'pending' && record.scope.problemReceiptDigest === identity.problemReceiptDigest && record.scope.environmentDigest === identity.environmentDigest && record.check.execution?.kind === 'proof-search' && record.check.execution.taskId === record.scope.target.taskId && record.check.execution.taskDigest === record.scope.target.taskDigest); - return check ? { ...check.scope.target } : { taskId: assignment.taskId, taskDigest: assignment.taskDigest }; +} + +/** The Lean target is shared. The assigned check owns its separate history. */ +export function proofSearchTargetForAssignment(assignment: { taskId: string; taskDigest: string }, + currentChecks: readonly NextCheckRecord[], identity: { problemReceiptDigest: string; environmentDigest: string }) { + return proofSearchCheckForAssignment(assignment, currentChecks, identity)?.scope.target ?? + { taskId: assignment.taskId, taskDigest: assignment.taskDigest }; } /** Search state is advisory process history, never a proof receipt or acceptance cache. */ @@ -47,6 +53,7 @@ export const proofSearchRecordSchema = z.object({ taskId: identity, taskDigest: identity, problemReceiptDigest: identity, environmentDigest: identity, sourceDigest: digest, projectionDigest: digest, backendDigest: digest, basisDigest: digest, generation: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), + history: digest.optional(), workerId: identity, assignmentKey: z.string().min(1).max(4096), createdAt: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), checkpoint: proofSearchCheckpointReferenceSchema, @@ -67,22 +74,22 @@ function parsedCheckpoint(reference: ProofSearchCheckpointReference, file: strin return { checkpoint, basisDigest, bytes }; } -function checkpointPath(projectRoot: string, basisDigest: string, generation: number): string { - return path.join(path.resolve(projectRoot), '.lake', 'proof-search', basisDigest, `${generation}.json`); -} - /** Read only an exact, regular project scratch checkpoint; an arbitrary artifact path is not an input. */ -export function readProofSearchCheckpoint(projectRoot: string, value: ProofSearchCheckpointReference) { +export function readProofSearchCheckpoint(projectRoot: string, value: ProofSearchCheckpointReference, history?: string) { try { const parsed = proofSearchCheckpointReferenceSchema.safeParse(value); if (!parsed.success) throw invalid(); const reference = parsed.data; const file = path.isAbsolute(reference.path) ? reference.path : path.join(path.resolve(projectRoot), reference.path); const scratch = path.join(path.resolve(projectRoot), '.lake', 'proof-search'); - const relative = path.relative(scratch, file).split(path.sep).join('/'); - if (path.resolve(file) !== file || !/^[a-f0-9]{64}\/(?:0|[1-9][0-9]*)\.json$/u.test(relative)) throw invalid(); + const relative = path.relative(scratch, file).split(path.sep), name = relative.pop() ?? ''; + if (history && relative.pop() !== digest.parse(history)) throw invalid(); + if (path.resolve(file) !== file || relative.length !== 1 || !/^[a-f0-9]{64}$/u.test(relative[0]!) || + !/^(?:0|[1-9][0-9]*|retained-(?:0|[1-9][0-9]*)-[a-f0-9]{64})\.json$/u.test(name)) throw invalid(); const result = parsedCheckpoint(reference, file); - if (file !== checkpointPath(projectRoot, result.basisDigest, result.checkpoint.generation)) throw invalid(); + const root = path.resolve(projectRoot); + if (file !== localProofSearchPath(root, result.basisDigest, result.checkpoint.generation, history) && + file !== projectedProofSearchPath(root, result.basisDigest, result.checkpoint.generation, reference.digest, history)) throw invalid(); return { ...result, reference: { path: file, digest: reference.digest } }; } catch { throw invalid(); } } @@ -92,13 +99,26 @@ export function proofSearchRecordMatches(record: ProofSearchRecord | undefined, record.problemReceiptDigest === scope.problemReceiptDigest && record.environmentDigest === scope.environmentDigest); } +/** The host keeps one record per independent task, or starts the check at its pinned seed. */ +export function proofSearchRecordForAssignment(records: Readonly> | undefined, + scope: ProofSearchScope, check?: NextCheckRecord) { + const target = records?.[scope.taskId]; + if (!check) return proofSearchRecordMatches(target, scope) ? target : undefined; + const basis = check.scope.executionBasisDigest; + const own = records?.[check.taskId]; + if (proofSearchRecordMatches(own, scope) && own.history === check.id && (!basis || own.basisDigest === basis)) return own; + const seed = check.proofSearchSeed ?? target; // Older archives only retained the target's latest checkpoint. + if (basis && proofSearchRecordMatches(seed, scope) && seed.basisDigest === basis) return seed; +} + /** Capture the worker's exact bytes before its scratch directory is reset or reassigned. */ export function retainProofSearchCheckpoint(input: { projectRoot: string; runDirectory: string; reference: ProofSearchCheckpointReference; scope: ProofSearchScope; - workerId: string; assignmentKey: string; now?: number; + workerId: string; assignmentKey: string; now?: number; history?: string; requiredBasisDigest?: string; }): ProofSearchRecord { - const { checkpoint, basisDigest, bytes } = readProofSearchCheckpoint(input.projectRoot, input.reference); - if (canonicalMathJson(checkpoint.basis.scope) !== canonicalMathJson(input.scope)) + const { checkpoint, basisDigest, bytes } = readProofSearchCheckpoint(input.projectRoot, input.reference, input.history); + if (canonicalMathJson(checkpoint.basis.scope) !== canonicalMathJson(input.scope) || + input.requiredBasisDigest && basisDigest !== input.requiredBasisDigest) throw new Error('math_proof_search_checkpoint_scope_changed'); const directory = path.join(path.resolve(input.runDirectory), 'proof-search-artifacts'); const usage = toolUsageSchema.safeParse(checkpoint.counters); @@ -113,7 +133,7 @@ export function retainProofSearchCheckpoint(input: { schema: 'theorem-os.proof-search-record.v1', ...input.scope, sourceDigest: checkpoint.basis.sourceDigest, projectionDigest: checkpoint.basis.projectionDigest, backendDigest: checkpoint.basis.backendDigest, basisDigest, generation: checkpoint.generation, - workerId: input.workerId, assignmentKey: input.assignmentKey, createdAt: input.now ?? Date.now(), + history: input.history, workerId: input.workerId, assignmentKey: input.assignmentKey, createdAt: input.now ?? Date.now(), checkpoint: { path: file, digest: input.reference.digest }, ...(usage.success ? { toolUsage: usage.data } : {}), evidence: 'advisory-proof-search', proofAcceptance: 'not-accepted', @@ -130,7 +150,7 @@ export function latestProofSearchRecord(current: ProofSearchRecord | undefined, /** Project host-retained bytes to an accessible worker scratch path; old/missing records remain unusable. */ export function projectProofSearchRecord(input: { - record: ProofSearchRecord | undefined; scope: ProofSearchScope; projectRoot: string; runDirectory: string; + record: ProofSearchRecord | undefined; scope: ProofSearchScope; projectRoot: string; runDirectory: string; history?: string; }): ProofSearchRecord | undefined { if (!proofSearchRecordMatches(input.record, input.scope)) return; try { @@ -142,7 +162,8 @@ export function projectProofSearchRecord(input: { canonicalMathJson(checkpoint.basis.scope) !== canonicalMathJson(input.scope) || checkpoint.basis.sourceDigest !== record.sourceDigest || checkpoint.basis.projectionDigest !== record.projectionDigest || checkpoint.basis.backendDigest !== record.backendDigest) return; - const file = checkpointPath(input.projectRoot, basisDigest, checkpoint.generation); + const file = projectedProofSearchPath(path.resolve(input.projectRoot), basisDigest, record.generation, record.checkpoint.digest, + digest.optional().parse(input.history ?? record.history)); assertMathCanonicalPath(file); fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); assertMathCanonicalPath(file); diff --git a/src/solver/proofSearchTool.ts b/src/solver/proofSearchTool.ts index 6fcdffa8..68d69874 100644 --- a/src/solver/proofSearchTool.ts +++ b/src/solver/proofSearchTool.ts @@ -3,7 +3,7 @@ import path from 'node:path'; import { assertMathCanonicalPath } from '../math/paths'; import { mathDigest, readMathText } from '../math/mathRuntimeIo'; import { proofSearchRequestSchema, searchLeanBranches, type SearchCheckpointReference } from '../math/leanProofSearch'; -import { proofSearchRecordMatches, proofSearchTargetForAssignment } from './proofSearchRecords'; +import { proofSearchCheckForAssignment, proofSearchRecordMatches } from './proofSearchRecords'; import { currentNextCheck } from './nextChecks'; import { assignmentDeliveryFile, taskVersion, type TaskAssignment, type TaskRecord } from './tasks'; import { assertSolverProjectSources, type SolverSourceConstraints } from './problem'; @@ -28,21 +28,24 @@ export function proofSearchToolContext(projectRoot: string, requested: { file?: if (!owner || taskVersion(owner.task) !== delivery.assignment.taskDigest) throw new Error('proof_search_assignment_changed'); const identity = { problemReceiptDigest: delivery.problemReceiptDigest, environmentDigest: delivery.environmentDigest }; const checks = (context.nextChecks ?? []).filter(record => currentNextCheck(record, context, identity)); - const target = proofSearchTargetForAssignment(delivery.assignment, checks, identity); + const check = proofSearchCheckForAssignment(delivery.assignment, checks, identity); + const { taskId, taskDigest } = check?.scope.target ?? delivery.assignment; + const target = { taskId, taskDigest }; const task = tasks.find(node => node.task.id === target.taskId)?.task; if (!task || taskVersion(task) !== target.taskDigest) throw new Error('proof_search_assignment_changed'); if (task.kind !== 'lemma' || task.declaration || task.conditional || !task.type || !task.proofPath || !task.theoremName) throw new Error('proof_search_unsupported_target: materialize a plain helper lemma with its closed task type'); if (!delivery.ownedFiles.includes(task.proofPath) || requested.file && requested.file !== task.proofPath || requested.theoremName && requested.theoremName !== task.theoremName) throw new Error('proof_search_target_outside_assignment'); - const scope = { ...identity, ...target }, saved = context.proofSearchRecords?.[target.taskId]; - const record = proofSearchRecordMatches(saved, scope) ? saved : undefined; - const check = checks.find(item => item.taskId === owner.task.id); - if (check?.scope.executionBasisDigest && record?.basisDigest !== check.scope.executionBasisDigest) + const scope = { ...identity, ...target }; + const projected = context.proofSearchRecords?.[target.taskId], basis = check?.scope.executionBasisDigest; + const seed = check?.proofSearchSeed; + const record = proofSearchRecordMatches(projected, scope) && (!check || projected.history === check.id || + basis && (!seed || projected.checkpoint.digest === seed.checkpoint.digest)) ? projected : undefined; + if (basis && record?.basisDigest !== basis) throw new Error('proof_search_stale_next_check_basis'); return { worktree, project, task, scope, record, assignment: delivery.assignment, - independentSearch: Boolean(check?.check.execution?.kind === 'proof-search' && check.scope.executionBasisDigest && - target.taskId !== owner.task.id) }; + history: check?.id, independentSearch: Boolean(check?.scope.executionBasisDigest) }; } export async function runProofSearchTool(input: { projectRoot: string; request: unknown; @@ -65,7 +68,8 @@ export async function runProofSearchTool(input: { projectRoot: string; request: }; const result = await searchLeanBranches({ projectRoot: context.project, file: context.task.proofPath!, theoremName: context.task.theoremName!, type: context.task.type!, scope: context.scope, request, - restartStaleImplicitResume: Boolean(implicitResume && context.scope.taskId === context.assignment.taskId), + history: context.history, + restartStaleImplicitResume: Boolean(implicitResume && !context.independentSearch), ...(context.independentSearch && context.record ? { retainedInput: { basisDigest: context.record.basisDigest, checkpointDigest: context.record.checkpoint.digest } } : {}), signal: input.signal, env: input.env, onCheckpoint: queueCheckpoint }); diff --git a/tests/nextCheckExecution.test.ts b/tests/nextCheckExecution.test.ts index 2701c259..97c66b64 100644 --- a/tests/nextCheckExecution.test.ts +++ b/tests/nextCheckExecution.test.ts @@ -140,7 +140,8 @@ describe('machine-readable scoped next checks', () => { expect(currentNextCheck(proposed.record, state, identity)).toBe(true); expect(proposedNextChecks(state, identity, 3)).toEqual([]); state.proofSearchRecords[helper.id] = { ...advanced, basisDigest: '5'.repeat(64) }; - expect(currentNextCheck(proposed.record, state, identity)).toBe(false); + expect(currentNextCheck(proposed.record, state, identity)).toBe(true); + expect(currentNextCheck({ ...proposed.record, proofSearchSeed: undefined }, state, identity)).toBe(false); }); it('does not use a worker-reported basis, stale checkpoint or wrong environment to schedule a continuation', () => { @@ -156,6 +157,19 @@ describe('machine-readable scoped next checks', () => { } }); + it('pins a requested independent checkpoint without replacing the owner history', () => { + const owner = checkpointRecord(); + const independent = { ...owner, history: '6'.repeat(64), + checkpoint: { ...owner.checkpoint, digest: '7'.repeat(64) } }; + const state = fixture({ ...baseCheck, execution: search({ checkpoint: independent.checkpoint }) }); + state.proofSearchRecords[helper.id] = owner; + state.proofSearchRecords['previous-check'] = independent; + const { record } = proposedNextChecks(state, identity, 3)[0]!; + expect(record.proofSearchSeed).toBe(independent); + expect(state.proofSearchRecords[helper.id]).toBe(owner); + expect(currentNextCheck(record, state, identity)).toBe(true); + }); + it('expires executable checks on target, source, environment or bound context changes', () => { const original = fixture(), { record } = proposedNextChecks(original, identity, 2)[0]!; const changedSource = structuredClone(original); changedSource.deliveries[0]!.sourceDigest = '0'.repeat(64); diff --git a/tests/proofSearchRuntime.test.ts b/tests/proofSearchRuntime.test.ts index ba7b0e21..dbc36287 100644 --- a/tests/proofSearchRuntime.test.ts +++ b/tests/proofSearchRuntime.test.ts @@ -6,7 +6,8 @@ import { canonicalMathJson, mathDigest, withMathRuntimeLease } from '../src/math import { proofSearchCheckpointSchema, searchLeanBranches, type ProofSearchCheckpoint, type SearchCheckpointReference } from '../src/math/leanProofSearch'; import type { ProofSearchSession } from '../src/math/pantographSession'; -import { projectProofSearchRecord, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; +import { latestProofSearchRecord, projectProofSearchRecord, proofSearchRecordForAssignment, + readProofSearchCheckpoint, retainProofSearchCheckpoint } from '../src/solver/proofSearchRecords'; import { runProofSearchTool } from '../src/solver/proofSearchTool'; import { assignmentDeliveryFile, taskVersion } from '../src/solver/tasks'; @@ -177,6 +178,49 @@ describe('proof-search runtime persistence with fake Lean boundaries', () => { expect(output.dispose).toHaveBeenCalledTimes(1); expect(boundary.retainedProjection).not.toHaveBeenCalled(); }); + it('keeps parallel owner and checker continuations at the same generation independently resumable', async () => { + const first = await savedSearch(), history = mathDigest('independent check'); + const retain = (projectRoot: string, reference: SearchCheckpointReference, workerId: string, history?: string) => + retainProofSearchCheckpoint({ projectRoot, runDirectory: directory, reference, scope, workerId, assignmentKey: workerId, history }); + const seed = retain(project, first.reference, 'owner'); + const independent = makeProject('independent'); + const projectRecord = (projectRoot: string, record: typeof seed, history?: string) => + projectProofSearchRecord({ record, scope, projectRoot, runDirectory: directory, history })!.checkpoint; + const seedCopy = projectRecord(independent, seed, history); + boundary.projection.mockImplementation(({ projectRoot }) => projection(projectRoot)); + boundary.retainedProjection.mockImplementation(({ projectRoot }) => projection(projectRoot)); + boundary.open.mockImplementation(async () => session()); + const from = first.checkpoint.nodes[1]!.id; + const authorization = (reference: SearchCheckpointReference) => + ({ basisDigest: seed.basisDigest, checkpointDigest: reference.digest }); + const [owner, checker] = await Promise.all([ + search({ request: { resume: first.reference, branches: [{ from, tactics: ['rfl'] }] } }), + search({ projectRoot: independent, history, retainedInput: authorization(seedCopy), + request: { resume: seedCopy, branches: [{ from, tactics: ['simp'] }] } }), + ]); + expect(owner.status).toBe('candidate'); + expect(checker).toMatchObject({ status: 'exhausted', sourceBinding: 'host-retained-source-snapshot' }); + const ownerRecord = retain(project, owner.checkpoint!, 'owner'); + const checkerRecord = retain(independent, checker.checkpoint!, 'checker', history); + expect(ownerRecord.generation).toBe(checkerRecord.generation); + expect(ownerRecord.checkpoint.digest).not.toBe(checkerRecord.checkpoint.digest); + const records = { [scope.taskId]: latestProofSearchRecord(seed, ownerRecord), + 'independent-task': latestProofSearchRecord(undefined, checkerRecord) }; + const check = { taskId: 'independent-task', id: history, scope: { executionBasisDigest: seed.basisDigest }, + proofSearchSeed: seed } as NonNullable[2]>; + expect(proofSearchRecordForAssignment(records, scope)).toBe(ownerRecord); + expect(proofSearchRecordForAssignment(records, scope, check)).toBe(checkerRecord); + const ownerCopy = projectRecord(independent, ownerRecord, history); + expect(ownerCopy.path).not.toBe(path.resolve(independent, checker.checkpoint!.path)); + expect(readProofSearchCheckpoint(independent, checker.checkpoint!, history).reference.digest).toBe(checker.checkpoint!.digest); + const migrated = makeProject('checker-restart'), checkerCopy = projectRecord(migrated, checkerRecord, history); + const end = await search({ projectRoot: migrated, history, retainedInput: authorization(checkerCopy), + request: { resume: checkerCopy, branches: [{ from: checker.frontier!.at(-1)!.node, tactics: ['rfl'] }] } }); + expect(end).toMatchObject({ status: 'candidate', proofAcceptance: 'not-accepted' }); + expect(path.dirname(end.candidates[0]!.artifact.path)).toBe(path.dirname(end.checkpoint!.path)); + expect(readCheckpoint(migrated, end.checkpoint!).counters.replay).toBeGreaterThan(checker.counters!.replay); + }); + it('keeps ordinary owner resumes stale when current source changes instead of restoring retained source', async () => { const first = await savedSearch(), changedSource = sources[0]!.source + '-- new owner edit\n'; fs.writeFileSync(path.join(project, target.file), changedSource); diff --git a/tests/proofSearchTool.test.ts b/tests/proofSearchTool.test.ts index 11b38260..3dd6a66e 100644 --- a/tests/proofSearchTool.test.ts +++ b/tests/proofSearchTool.test.ts @@ -8,7 +8,7 @@ import type { DeliveryRecord } from '../src/solver/deliveries'; import { bindMathematicalGap } from '../src/solver/mathematicalGaps'; import type { MathematicalGap } from '../src/solver/mathematicalGapContract'; import type { NextCheckRecord } from '../src/solver/nextCheckContract'; -import { proposedNextChecks } from '../src/solver/nextChecks'; +import { currentNextCheck, proposedNextChecks } from '../src/solver/nextChecks'; import type { ProofSearchRecord } from '../src/solver/proofSearchRecords'; import { proofSearchToolContext, runProofSearchTool } from '../src/solver/proofSearchTool'; import { assignmentDeliveryFile, taskVersion, type CooperativeTask, type TaskAssignment, type TaskRecord } from '../src/solver/tasks'; @@ -155,27 +155,44 @@ describe('proof-search worker tool without Lean or model execution', () => { expect(call.request).toMatchObject({ resume: f.record.checkpoint }); expect(call.request).not.toMatchObject({ resume: { path: '/previous-worker/checkpoint.json' } }); expect(call.retainedInput).toEqual({ basisDigest: f.check.scope.executionBasisDigest, checkpointDigest: f.record.checkpoint.digest }); + expect(call.history).toBe(f.check.id); expect(call.scope.taskId).toBe(helper.id); expect(f.assignment.taskId).not.toBe(helper.id); }); - it('does not authorize retained-source replay for an independent check without executionBasisDigest', async () => { + it('starts a new independent search without the owner checkpoint, then resumes only its own history', async () => { const f = nextCheckFixture(false); expect(f.check.scope.executionBasisDigest).toBeUndefined(); await runProofSearchTool({ projectRoot: f.project, request: request() }); const call = backend.search.mock.calls[0]![0] as SearchInput; expect(call.scope.taskId).toBe(helper.id); - expect(call.request).toMatchObject({ resume: f.record.checkpoint }); + expect(call.request).not.toHaveProperty('resume'); expect(call.retainedInput).toBeUndefined(); + expect(call.history).toBe(f.check.id); + const own = { ...f.record, history: f.check.id, workerId: f.assignment.workerId, + assignmentKey: assignmentDeliveryFile(f.assignment), checkpoint: { ...f.record.checkpoint, digest: 'd'.repeat(64) } }; + f.context.proofSearchRecords[helper.id] = own; + f.write(); + await runProofSearchTool({ projectRoot: f.project, request: request() }); + expect(backend.search.mock.calls[1]![0]).toMatchObject({ request: { resume: own.checkpoint }, history: f.check.id }); + expect((backend.search.mock.calls[1]![0] as SearchInput).retainedInput).toBeUndefined(); }); - it('rejects an obsolete nextCheck continuation instead of granting its old target scope', async () => { + it('rejects a projected record that cannot resume the host-pinned next check', async () => { const f = nextCheckFixture(true); f.context.proofSearchRecords[helper.id] = { ...f.record, basisDigest: '0'.repeat(64) }; f.write(); await expect(runProofSearchTool({ projectRoot: f.project, request: request() })).rejects.toThrow(/proof_search_/u); expect(backend.search).not.toHaveBeenCalled(); }); + it('keeps a pinned check current independently of the owner history', () => { + const f = nextCheckFixture(true); + const seed = f.check.proofSearchSeed; + expect(seed).toEqual(f.record); + f.context.proofSearchRecords[helper.id] = { ...f.record, basisDigest: '0'.repeat(64) }; + expect(currentNextCheck(f.check, f.context, identity)).toBe(true); + }); + it('publishes checkpoint progress to the independent assignment log with a stable id and exact digest', async () => { const f = nextCheckFixture(true); const reference = { path: path.join(f.project, '.lake', 'proof-search', f.record.basisDigest, '1.json'), digest: '7'.repeat(64) }; diff --git a/tests/webCollaboration.test.ts b/tests/webCollaboration.test.ts index 6b17e44b..dcbb9a12 100644 --- a/tests/webCollaboration.test.ts +++ b/tests/webCollaboration.test.ts @@ -451,9 +451,11 @@ describe('real collaboration HTTP and job boundaries without model calls', () => const { owner, request: alice } = await login(), { request: bob } = await login(); const run = (await (await alice('/api/runs', input())).json()).run; await tick(); const failed = observation(run.id); - failed.checks[0]!.record = { passed: false, status: 'failed', theoremName: 'helper', stdoutPreview: 'Submission.lean:1:1: error: The rfl tactic failed.' }; + const firstAt = Date.parse(failed.observedAt), secondAt = firstAt + 1; + failed.checks[0]!.record = { passed: false, status: 'failed', theoremName: 'helper', checkedAt: firstAt, + stdoutPreview: 'Submission.lean:1:1: error: The rfl tactic failed.' }; runner.calls[0].send({ type: 'observation', observation: failed }); - runner.calls[0].finish(); await tick(); + await tick(); const route = `/api/runs/${run.id}/explain`, question = { taskId: 'helper', commit: 'a'.repeat(40), question: 'Why did it fail?' }; expect((await alice(route, question)).status).toBe(400); expect(asked).toHaveLength(0); @@ -474,10 +476,27 @@ describe('real collaboration HTTP and job boundaries without model calls', () => expect(context).toContain(part); expect(asked[0]!.body.input[2]!.content[0]!.text).toBe('Why did it fail?'); + const recheck = observation(run.id, 2), changedPlan = observation(run.id, 3); + recheck.checks[0]!.record = { passed: false, status: 'failed', theoremName: 'helper', checkedAt: secondAt, + stdoutPreview: 'Submission.lean:1:1: error: The second tactic failed.' }; + changedPlan.inspection.tasks[0]!.version = 'version-2'; + changedPlan.inspection.tasks[0]!.objective = changedPlan.plan!.tasks[0]!.objective = 'New objective after both checks'; + changedPlan.checks = []; + runner.calls[0].send({ type: 'observation', observation: recheck }); + runner.calls[0].send({ type: 'observation', observation: changedPlan }); + runner.calls[0].finish(); await tick(); + + const selected = { ...question, apiKey: key, taskVersion: 'version-1', receiptId: 'fixture-check', checkAt: firstAt }; + expect((await alice(route, { ...selected, checkAt: undefined })).status).toBe(409); + expect((await alice(route, { ...selected, receiptId: 'unknown-check' })).status).toBe(404); + expect((await alice(route, { ...selected, taskVersion: 'version-2' })).status).toBe(404); mode = 'hold'; - const stop = new AbortController(), held = alice(route, { ...question, apiKey: key }, stop.signal).catch(() => undefined); + const stop = new AbortController(), held = alice(route, selected, stop.signal).catch(() => undefined); for (let wait = 0; asked.length < 2 && wait < 100; wait++) await new Promise(resolve => setTimeout(resolve, 10)); - const busy = await alice(route, { ...question, apiKey: key }); + expect(asked[1]!.body.input[0]!.content[0]!.text).toContain('The rfl tactic failed.'); + expect(asked[1]!.body.input[0]!.content[0]!.text).toContain('Conditional fixture helper'); + expect(asked[1]!.body.input[0]!.content[0]!.text).not.toMatch(/The second tactic failed|New objective after both checks/u); + const busy = await alice(route, { ...selected, checkAt: secondAt }); expect(busy.status).toBe(429); expect(asked).toHaveLength(2); stop.abort(); await held; @@ -486,8 +505,10 @@ describe('real collaboration HTTP and job boundaries without model calls', () => release(); mode = 'reject'; - const rejected = await alice(route, { ...question, apiKey: key }); + const rejected = await alice(route, { ...selected, checkAt: secondAt }); expect(rejected.status).toBe(502); + expect(asked[2]!.body.input[0]!.content[0]!.text).toContain('The second tactic failed.'); + expect(asked[2]!.body.input[0]!.content[0]!.text).not.toContain('The rfl tactic failed.'); const body = await rejected.text(); expect(body).toContain('模型服务拒绝了这个 API Key。'); expect(body).not.toContain(key); const stored = JSON.stringify([service.storage.getRun(owner, run.id), service.storage.getEvents(owner, run.id)]); diff --git a/tests/webJobs.test.ts b/tests/webJobs.test.ts index bc99e3a3..c1a29578 100644 --- a/tests/webJobs.test.ts +++ b/tests/webJobs.test.ts @@ -161,6 +161,23 @@ describe('web job ownership, scheduling and secret lifetime without provider cal runner.calls[0].finish({ status: 'incomplete', proof: '', report: {} }); await tick(); }); + it('saves the new round evidence delivered during cancellation without accepting a late result', async () => { + const { jobs, runner } = setup(), run = jobs.create('owner', input(), provider); + await tick(); + const { send } = runner.calls[0]!; + send({ type: 'observation', observation: observation(run.id, 'solver-first', 1) }); + jobs.cancel('owner', run.id); + send({ type: 'library_restart', previousSolverRunId: 'unrelated', solverRunId: 'solver-next', round: 1 }); + expect(run.observation?.solverRunId).toBe('solver-first'); + send({ type: 'library_restart', previousSolverRunId: 'solver-first', solverRunId: 'solver-next', round: 1 }); + send({ type: 'observation', observation: observation(run.id, 'solver-next', 2) }); + send({ type: 'result', result: result() }); + expect(run).toMatchObject({ status: 'cancelled', phase: 'cancelled', + observation: { solverRunId: 'solver-next', acceptance: 'not-assessed' } }); + expect(run.result).toBeUndefined(); + expect(jobs.storage.listObservations('owner', run.id).map(item => item.solverRunId)).toEqual(['solver-first', 'solver-next']); + }); + it('starts queued jobs in order, respects concurrency and rejects excess active work', async () => { const { jobs, runner } = setup(2, 4); const runs = Array.from({ length: 4 }, (_, index) => jobs.create('owner', { ...input(), task: `Task ${index}` }, provider)); diff --git a/tests/webLifecyclePersistence.test.ts b/tests/webLifecyclePersistence.test.ts index f12f6828..9ce5103c 100644 --- a/tests/webLifecyclePersistence.test.ts +++ b/tests/webLifecyclePersistence.test.ts @@ -12,6 +12,8 @@ import type { WebRunner } from '../apps/web/runner'; import { createWebService } from '../apps/web/server'; import type { WebRun, WebRunInput, WorkerExplanationInput, WorkerExplanationMessage, WorkerInput, WorkerMessage } from '../apps/web/shared'; import { WebStorage } from '../apps/web/storage'; +import { isAcceptedRun } from '../apps/web/presentation'; +import { mathDigest } from '../src/math/mathRuntimeIo'; import { buildTheoremKnowledge } from '../src/solver/theoremKnowledge'; // Disposable files and a fake worker only. Calls retain the real input reference to check credential cleanup. @@ -97,6 +99,57 @@ function setup(kind: Kind, concurrency = 1, dataRoot?: string) { } afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); +describe('research restart with partially written run state', () => { + const restart = (root: string, writeTail?: (storage: WebStorage) => void) => { + // Copy the crash image so cleanup of the simulated old process cannot write into the restored run. + const crashImage = fs.mkdtempSync(path.join(os.tmpdir(), 'web-lifecycle-crash-')); + cleanups.push(async () => { fs.rmSync(crashImage, { recursive: true, force: true }); }); + fs.cpSync(root, crashImage, { recursive: true }); + const storage = new WebStorage(crashImage); + writeTail?.(storage); + return new WebJobs(new Runner(), { concurrency: 1, queueLimit: 8 }, { storage }); + }; + + it('recovers the durable events before recording an interrupted run', async () => { + const { service, storage } = setup('research'); + const id = service.create('alice'); + await settle(); + const run = storage.getRun('alice', id)!; + const next = { sequence: run.events.at(-1)!.sequence + 1, at: new Date().toISOString(), + type: 'evaluation_started', message: 'The event reached disk before the run summary.' }; + const jobs = restart(storage.root!, crash => { + crash.saveRecord(['owners', mathDigest('alice'), 'runs', id, 'events', `${next.sequence}.json`], next, true); + expect(crash.getRun('alice', id)?.events).toEqual(run.events); + }); + const recovered = jobs.get('alice', id)!; + expect(recovered).toMatchObject({ status: 'error', phase: 'interrupted' }); + expect(recovered.events.slice(-2)).toEqual([next, expect.objectContaining({ sequence: next.sequence + 1, type: 'interrupted' })]); + expect(jobs.storage.listEvents('alice', id)).toEqual(recovered.events); + await jobs.close(); + }); + + it.each([false, true])('preserves saved Lean acceptance across restart (finished event durable: %s)', async eventWritten => { + const { service, storage, runner } = setup('research'); + const id = service.create('alice'); + await settle(); + runner.calls[0]!.late(); // Deliberately leave the runner in cleanup. + const run = storage.getRun('alice', id)!; + expect(run).toMatchObject({ status: 'running', result: { status: 'evaluated_passed', proof } }); + const jobs = restart(storage.root!, eventWritten ? crash => { + const sequence = run.events.at(-1)!.sequence + 1; + crash.saveRecord(['owners', mathDigest('alice'), 'runs', id, 'events', `${sequence}.json`], + { sequence, at: run.updatedAt, type: 'finished', message: '完整原题通过独立 Lean 验收' }, true); + } : undefined); + const recovered = jobs.get('alice', id)!; + expect(isAcceptedRun(recovered)).toBe(true); + expect(recovered).toMatchObject({ status: 'completed', phase: 'evaluated_passed', result: run.result }); + expect(recovered.finishedAt).toBe(run.updatedAt); + expect(jobs.storage.listEvents('alice', id).filter(event => event.type === 'finished')).toHaveLength(1); + expect(recovered.events.some(event => event.type === 'interrupted')).toBe(false); + await jobs.close(); + }); +}); + describe.each(['research', 'formalization', 'explanation'])('%s lifecycle with failed terminal persistence', kind => { it('stops its worker instead of throwing out of an asynchronous message callback when persistence fails', async () => { const { service, storage, runner } = setup(kind); diff --git a/tests/webRunner.test.ts b/tests/webRunner.test.ts index 976fe53b..a02fd156 100644 --- a/tests/webRunner.test.ts +++ b/tests/webRunner.test.ts @@ -317,6 +317,10 @@ async function main() { while (!fs.existsSync(path.join(root, 'approve'))) await new Promise(resolve => setTimeout(resolve, 10)); process.stdout.write(JSON.stringify({ type: 'progress', event: 'plan_approval_wait_ended', message: 'Approved' }) + '\\n'); process.stdout.write(JSON.stringify({ type: 'result', result: { status: 'incomplete', proof: '', report: {} } }) + '\\n'); + } else if (args[0] === 'exec') { + let input = ''; for await (const chunk of process.stdin) input += chunk; + if (JSON.parse(input).type !== 'capture') process.exit(1); + process.stdout.write(fs.readFileSync(path.join(root, 'capture.json'))); } else if (args[0] === 'rm') fs.rmSync(path.join(root, 'container'), { force: true }); else process.exit(1); } @@ -332,6 +336,11 @@ main().catch(() => process.exit(1)); providerId: config.providers[0].id, apiKey: 'sk-offline-fixture', source: 'theorem goal : True := by sorry', task: 'Offline human review fixture', maxRunSeconds, workers: 2, planApproval }, }; + const observation = { ...loadWebSample()!.observations[0]!, webRunId: request.id }; + const libraryRestart = { previousSolverRunId: 'solver-first', solverRunId: observation.solverRunId, round: 1 }; + const frame = standaloneObservationFrame(observation); + fs.writeFileSync(path.join(root, 'capture.json'), JSON.stringify({ id: 'capture', status: 'captured', + libraryRestart, observation: frame.observation, sourceBlobs: frame.sourceBlobs })); let waiting!: () => void; const ready = new Promise(resolve => { waiting = resolve; }), messages: WorkerMessage[] = []; complete = new DockerWebRunner(config).run(request, message => { @@ -351,7 +360,11 @@ main().catch(() => process.exit(1)); expect(calls.filter(args => args[0] === 'rm')).toHaveLength(1); expect(fs.existsSync(path.join(root, 'container'))).toBe(false); expect(messages.map(message => message.type === 'progress' ? message.event : message.type)).toEqual(decision === 'approve' - ? ['plan_approval_wait_started', 'plan_approval_wait_ended', 'result'] : ['plan_approval_wait_started']); + ? ['plan_approval_wait_started', 'plan_approval_wait_ended', 'result'] : ['plan_approval_wait_started', 'library_restart', 'observation']); + if (decision === 'cancel') { + expect(messages.slice(-2)).toEqual([{ type: 'library_restart', ...libraryRestart }, { type: 'observation', observation }]); + expect(calls.map(args => args[0])).toEqual(['create', 'start', 'exec', 'rm']); + } expect(vi.getTimerCount()).toBe(0); } finally { fs.writeFileSync(path.join(root, 'approve'), 'cleanup'); diff --git a/tests/webTrajectory.test.ts b/tests/webTrajectory.test.ts index 788a9399..991ca486 100644 --- a/tests/webTrajectory.test.ts +++ b/tests/webTrajectory.test.ts @@ -64,6 +64,30 @@ describe('web trajectory index', () => { expect(trajectories.page(owner, run.id, { after: 0, since: 0, instance: page.instance }).instance).not.toBe(page.instance); }); + it('loads a check with receipts first seen in different chunks without dropping older receipts', () => { + const frame = sample.observations.find(item => item.checks.length && item.sources.length)!; + const check = frame.checks[0]!; + const observed = Array.from({ length: 70 }, (_, position) => ({ ...frame, sequence: position + 1, + sources: position === 0 ? frame.sources : [], + checks: [{ ...check, id: String(position), record: { ...check.record, verification: { checkedAt: 1_000 } } }] })); + observed.push({ ...frame, sequence: 71, sources: [], + checks: [{ ...check, id: '0', record: { ...check.record, verification: { checkedAt: 2_000 } } }] }); + const trajectories = new WebTrajectories({ + listEventsAfter: () => [], + listObservationsAfter: (_owner, _run, after, limit) => observed.slice(after, after + limit), + getObservation: (_owner, _run, sequence) => observed[sequence - 1], + }); + const ids = observed.slice(0, 70).map(item => item.checks[0]!.id); + // This selector is in the second chunk even though the same check and commit were seen in the first. + const detail = trajectories.version('owner', frame.webRunId, check.taskId, check.commit, check.taskVersion, ids.at(-1))!; + expect(detail.checks.map(receipt => receipt.id)).toEqual(ids); + expect(trajectories.version('owner', frame.webRunId, check.taskId, check.commit, 'other-version', ids.at(-1))).toBeUndefined(); + const recheck = trajectories.version('owner', frame.webRunId, check.taskId, check.commit, check.taskVersion, '0', 2_000)!; + expect(recheck.checks).toEqual(observed[70]!.checks); + const aggregate = trajectories.version('owner', frame.webRunId, check.taskId, check.commit)!; + expect(aggregate.checks.map(receipt => receipt.id)).toEqual([...ids, '0']); + }); + it('validates cursors and version parameters and takes a one-line Lean reason from a failed receipt', () => { expect(trajectoryQuery(new URLSearchParams({ after: '3', since: '2', instance: 'abc-1' }))).toEqual({ after: 3, since: 2, instance: 'abc-1' }); for (const params of [{ after: '-1' }, { since: '1.5' }, { instance: 'A B' }]) expect(trajectoryQuery(new URLSearchParams(params))).toBeUndefined(); diff --git a/tests/webWorkerBridge.test.ts b/tests/webWorkerBridge.test.ts index 0a30918d..3b9e9d2b 100644 --- a/tests/webWorkerBridge.test.ts +++ b/tests/webWorkerBridge.test.ts @@ -11,7 +11,7 @@ import { WebKnowledgeService } from '../apps/web/knowledgeService'; import { WebStorage } from '../apps/web/storage'; import type { WorkerInput, WorkerMessage } from '../apps/web/shared'; import { webWorkerFixture } from './helpers/webWorkerBridge'; -import { mathDigest } from '../src/math/mathRuntimeIo'; +import { mathDigest, withMathRuntimeLease } from '../src/math/mathRuntimeIo'; import { hashMathFormalSourceDeclaration } from '../src/math/leanSource'; import { webGuidanceSchema } from '../apps/web/collaborationValidation'; import { parseWorkerMessage } from '../apps/web/runner'; @@ -150,6 +150,35 @@ describe('isolated Web worker bridge', () => { expect(parseWorkerMessage(JSON.stringify(backup))).toEqual({ type: 'observation', observation: next.observation }); }); + it.each(['single', 'independent'] as const)('captures original proof receipts without a cooperation plan in %s mode', async mode => { + const f = fixture(), target = f.state.problem.targets[0]!; + const { statementHash, leanStatementHash } = f.state.problem.contract; + const { commit, sourceDigest, verification } = f.proof; + const receipt = { ...verification.results[0]!, theoremName: target.theoremName, receiptId: 'original-failed', + status: 'failed' as const, error: 'Lean rejected the original proof', statementHash, leanStatementHash, + sourceDeclarationHash: target.declarationHash }; + const check = { commit, sourceDigest, passed: false, verification: { ...verification, status: 'failed' as const, results: [receipt] } }; + f.state.cooperation = undefined; + if (mode === 'single') { + f.state.workerCount = 1; + f.state.workers = undefined; + f.state.check = check; + } else { + f.state.coordination = 'independent'; + f.state.workers![0]!.check = check; + } + f.save(); + const task = { ...target, id: 'original_goal_1', kind: 'goal' as const, objective: `Prove ${target.theoremName}`, revision: 0, dependsOn: [] }; + const expected = { taskId: task.id, taskVersion: taskVersion(task), commit, sourceDigest }; + const bridge = createWebWorkerBridge({ webRunId: 'web-fixture', directory: f.directory, output: f.output }); + const { observation } = await bridge.capture(); + expect(observation.plan).toBeNull(); + expect(observation.sources).toMatchObject([{ ...expected, source: f.source, file: 'Submission.lean' }]); + expect(observation.checks).toMatchObject([{ ...expected, id: receipt.receiptId, + record: { theoremName: target.theoremName, passed: false, originalProblemPassed: false, error: receipt.error, acceptance: 'not-assessed' } }]); + expect(observation.coverage).toEqual({ sources: 'recorded', checks: 'recorded' }); + }); + it('reports each original target verdict when a shared Lean check only partially passes, including in retained observations', async () => { const f = fixture(), firstTarget = f.state.problem.targets[0]!; const secondTarget = { ...firstTarget, theoremName: 'Original.second', declarationHash: mathDigest('second declaration') }; @@ -241,6 +270,34 @@ describe('isolated Web worker bridge', () => { await expect(original.capture({ force: true })).rejects.toThrow('web_bridge_run_identity_changed'); }); + it.each([false, true])('captures the new round before cleanup even if streaming already sampled it (%s)', async streamingFirst => { + const f = fixture(), messages: WorkerMessage[] = []; + const options = { webRunId: 'web-fixture', directory: f.directory, onMessage: (message: WorkerMessage) => messages.push(message) }; + await createWebWorkerBridge({ ...options, output: f.output }).capture(); + const output = path.join(f.directory, 'rounds', '1', 'result.json'); + fs.mkdirSync(`${output}.runtime`, { recursive: true }); + writeSolverRunState(`${output}.runtime/state.json`, { ...f.state, runId: 'solver-next' }); + const libraryRestart = { previousSolverRunId: f.state.runId, round: 1 }; + const active = { ...options, output, libraryRestart }; + writeWebActiveRun(active, f.activeRunFile); + const next = createWebWorkerBridge(active), start = messages.length; + if (streamingFirst) await next.capture(); + let capture!: ReturnType; + await withMathRuntimeLease({ lockPath: path.join(f.directory, 'web-bridge.lock'), flockExecutable: '/usr/bin/flock' }, async () => { + // The cancellation command must wait for an in-flight observer rather than abandon the evidence. + capture = handleWebWorkerCommand({ type: 'capture' }, { activeRunFile: f.activeRunFile }); + expect(await Promise.race([capture, new Promise(resolve => setTimeout(() => resolve('waiting'), 80))])).toBe('waiting'); + }); + const command = await capture; + expect(command).toMatchObject({ status: 'captured', + libraryRestart: { ...libraryRestart, solverRunId: 'solver-next' }, + observation: { solverRunId: 'solver-next', sequence: 2, acceptance: 'not-assessed' } }); + if (!streamingFirst) await next.capture(); + const streamed = messages.slice(start).filter(message => ['library_restart', 'observation'].includes(message.type)); + expect(streamed).toEqual([expect.objectContaining({ type: 'library_restart', ...libraryRestart, solverRunId: 'solver-next' }), + expect.objectContaining({ type: 'observation', observation: expect.objectContaining({ solverRunId: 'solver-next', sequence: 2 }) })]); + }); + it('projects dependency sources from the same committed owned snapshot, preserving their paths and bytes', async () => { const f = fixture(), dependency = 'Support/Bridge.lean', dependencySource = '-- 原始字节\nnamespace Support\ntheorem bridge : True := by trivial\nend Support\n'; fs.mkdirSync(path.join(f.project, 'Support'));