Skip to content

Commit 25bcf22

Browse files
committed
Preserve shared frozen modules while extending research libraries
1 parent c84823f commit 25bcf22

5 files changed

Lines changed: 123 additions & 21 deletions

File tree

‎src/solver/libraryAccess.ts‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import fs from 'node:fs';
22
import path from 'node:path';
33
import { z } from 'zod';
4-
import { libraryDeclarationConflict } from '../math/libraryPacks';
4+
import { LIBRARY_PACK_SCHEMA, libraryDeclarationConflict, parseLibraryPack } from '../math/libraryPacks';
55
import { canonicalMathJson, mathDigest, readMathText, writeMathJsonDurable } from '../math/mathRuntimeIo';
66
import { assertMathCanonicalPath } from '../math/paths';
77
import { readLibraryCatalog } from './libraryCatalog';
8-
import { git, type SolverProblem } from './problem';
8+
import { committedSource, git, type SolverProblem } from './problem';
99
import { largestFittingPage, splitsSurrogate } from './textPage';
1010

1111
export const LIBRARY_ACCESS_FILE = 'LIBRARY.json';
@@ -84,15 +84,30 @@ export function requestedLibraryPack(problem: SolverProblem, requestInput: unkno
8484
git(worktree, ['merge-base', '--is-ancestor', problem.baseCommit, request.seedCommit]);
8585
git(worktree, ['merge-base', '--is-ancestor', request.seedCommit, 'HEAD']);
8686
const requested = request.names.map(name => catalog.declaration(name));
87-
for (const [file, digest] of Object.entries(problem.frozenFiles ?? {}))
88-
if (mathDigest(catalog.readModule(file).source) !== digest) throw new Error('math_library_request_existing_module_changed');
87+
const catalogFiles = new Set(catalog.moduleFiles), requiredFiles: string[] = [], retainedSources: Record<string, string> = {};
88+
for (const [file, digest] of Object.entries(problem.frozenFiles ?? {})) {
89+
if (catalogFiles.has(file)) {
90+
if (mathDigest(catalog.readModule(file).source) !== digest) throw new Error('math_library_request_existing_module_changed');
91+
requiredFiles.push(file);
92+
} else {
93+
// Shared releases are not objects in the built-in catalog. Only the frozen seed, never a worker's
94+
// current files, supplies their bytes to the next problem and its independent library checks.
95+
const source = committedSource(worktree, problem.baseCommit, path.posix.join(problem.projectRelative, file));
96+
if (mathDigest(source) !== digest) throw new Error('math_library_request_existing_module_changed');
97+
retainedSources[file] = source;
98+
}
99+
}
89100
if (requested.every(item => problem.frozenFiles?.[item.file] === item.sourceDigest))
90101
throw new Error('math_library_request_already_installed');
91102
// Keep module/prelude visibility and original imports intact when checking declaration conflicts.
92103
const selection = catalog.select({ source: problem.contract.formalStatement, task: '',
93104
environmentDigest: catalog.identity.environmentDigest, automatic: false,
94-
requiredFiles: [...Object.keys(problem.frozenFiles ?? {}), ...requested.map(item => item.file)] });
95-
const pack = catalog.materialize(selection)!;
105+
retainedSources, requiredFiles: [...requiredFiles, ...requested.map(item => item.file)] });
106+
const selected = catalog.materialize(selection)!;
107+
const pack = parseLibraryPack({ schema: LIBRARY_PACK_SCHEMA, modules: [...selected.modules,
108+
...Object.entries(retainedSources).map(([file, source]) => ({ file, source,
109+
origin: { kind: 'upstream', repository: problem.workspace, commit: problem.baseCommit,
110+
file: path.posix.join(problem.projectRelative, file) } }))] });
96111
const conflict = libraryDeclarationConflict(Object.fromEntries(pack.modules.map(module => [module.file, module.source])),
97112
{ 'Submission.lean': problem.contract.formalStatement });
98113
if (conflict) throw new Error(`math_library_catalog_declaration_conflict: ${conflict.libraryFile}`);

‎src/solver/libraryCatalog.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -188,19 +188,23 @@ export function readLibraryCatalog(file: string, expectedDigest?: string) {
188188
return { file, source, origin: structuredClone(module.origin) };
189189
};
190190
const select = (input: { source: string; task: string; environmentDigest: string; rootLimit?: number; automatic?: boolean;
191-
requiredFiles?: readonly string[] }): LibrarySelection => {
191+
requiredFiles?: readonly string[];
192+
/** Additional modules whose exact frozen bytes the host checked against the current problem. */
193+
retainedSources?: Readonly<Record<string, string>> }): LibrarySelection => {
192194
if (input.environmentDigest !== manifest.environmentDigest) throw new Error('math_library_catalog_environment_changed');
193195
const rootLimit = input.automatic === false ? 0 : input.rootLimit ?? 4;
194196
if (!Number.isInteger(rootLimit) || rootLimit < (input.automatic === false ? 0 : 1) || rootLimit > 32) throw new Error('math_library_catalog_root_limit');
195197
const owned = inspectScopedLeanDeclarations(input.source), unavailable = new Set<string>();
196-
const pending = declarationConflictNames(input.source).flatMap(name => declarations.get(name) ?? []);
198+
const retainedSources = input.retainedSources ?? {};
199+
const pending = [input.source, ...Object.values(retainedSources)]
200+
.flatMap(source => declarationConflictNames(source).flatMap(name => declarations.get(name) ?? []));
197201
for (let cursor = 0; cursor < pending.length; cursor++) {
198202
const file = pending[cursor]!;
199203
if (unavailable.has(file)) continue;
200204
unavailable.add(file); pending.push(...(dependents.get(file) ?? []));
201205
}
202206
const selected = new Set<string>(), roots = new Set<string>(), omitted: LibrarySelection['omitted'][number][] = [];
203-
let bytes = 0;
207+
let bytes = Object.values(retainedSources).reduce((sum, source) => sum + Buffer.byteLength(source), 0);
204208
const include = (file: string, required = false) => {
205209
if (unavailable.has(file)) {
206210
if (required) throw new Error(`math_library_catalog_declaration_conflict: ${file}`);
@@ -213,7 +217,7 @@ export function readLibraryCatalog(file: string, expectedDigest?: string) {
213217
closure.add(next); queue.push(...modules.get(next)!.imports);
214218
}
215219
const added = [...closure].reduce((sum, file) => sum + modules.get(file)!.bytes, 0);
216-
if (selected.size + closure.size > MAX_LIBRARY_PACK_MODULES || bytes + added > MAX_LIBRARY_PACK_BYTES) {
220+
if (Object.keys(retainedSources).length + selected.size + closure.size > MAX_LIBRARY_PACK_MODULES || bytes + added > MAX_LIBRARY_PACK_BYTES) {
217221
if (required) throw new Error(`math_library_catalog_installation_budget: ${file}`);
218222
if (omitted.length < 32) omitted.push({ file, reason: 'installation-budget' });
219223
return false;
@@ -224,7 +228,10 @@ export function readLibraryCatalog(file: string, expectedDigest?: string) {
224228
const requiredFiles = [...(input.requiredFiles ?? []),
225229
...mathConstructionImports(input.source).filter(name => name.startsWith('Submission.Library.')).map(localModuleFile)];
226230
for (const file of requiredFiles) {
227-
if (!modules.has(file)) throw new Error(`math_library_catalog_module_missing: ${file}`);
231+
if (!modules.has(file)) {
232+
if (Object.hasOwn(retainedSources, file)) continue;
233+
throw new Error(`math_library_catalog_module_missing: ${file}`);
234+
}
228235
include(file, true);
229236
}
230237
let automatic = 0;

‎tests/libraryAccess.test.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ function sourcePack(files: Record<string, string>): LibraryPack {
4141
origin: { kind: 'upstream', repository: 'offline-access-fixture', commit: 'a'.repeat(40), file: path.basename(file) } })) };
4242
}
4343

44-
function fixture(options: { packs?: LibraryPack[]; frozen?: string[]; source?: string } = {}) {
44+
function fixture(options: { packs?: LibraryPack[]; frozen?: string[]; frozenPack?: LibraryPack; source?: string } = {}) {
4545
const root = temporaryDirectory('library-access-'); roots.push(root);
4646
const packs = options.packs ?? [sourcePack(sources)];
4747
const built = writeLibraryCatalog(path.join(root, 'release'), {
@@ -50,8 +50,8 @@ function fixture(options: { packs?: LibraryPack[]; frozen?: string[]; source?: s
5050
const allModules = new Map(packs.flatMap(pack => pack.modules).map(module => [module.file, module]));
5151
const frozen = options.frozen ?? [foundation, installed];
5252
const receipt = bootstrapLeanTask(path.join(root, 'workspace'), { source: options.source ?? challenge,
53-
task: 'Prove the original target.', ...(frozen.length ? {
54-
libraryPack: { schema: LIBRARY_PACK_SCHEMA, modules: frozen.map(file => allModules.get(file)!) },
53+
task: 'Prove the original target.', ...(options.frozenPack || frozen.length ? {
54+
libraryPack: options.frozenPack ?? { schema: LIBRARY_PACK_SCHEMA, modules: frozen.map(file => allModules.get(file)!) },
5555
} : {}) });
5656
const problem = readSolverProblem(receipt.workspaceRoot, receipt.activeProblemPath);
5757
const access = { file: built.file, digest: built.digest }, worktree = receipt.workspaceRoot;
@@ -180,6 +180,48 @@ describe('agent access to the complete pinned library', () => {
180180
});
181181

182182
describe('host validation of requested frozen continuations', () => {
183+
it('retains shared modules from the exact seed while extending a catalog pack with their original imports intact', () => {
184+
const sharedBase = 'Submission/Library/Shared/Base.lean', shared = 'Submission/Library/Shared/Result.lean';
185+
const sharedSources = {
186+
[sharedBase]: 'import Submission.Library.Access.Installed\nnamespace Shared\nlemma base : True := by trivial\nend Shared\n',
187+
[shared]: 'import Submission.Library.Shared.Base\nnamespace Shared\nlemma result : True := by exact base\nend Shared\n-- 原始共享源码 🙂\n',
188+
};
189+
const f = fixture({ frozenPack: sourcePack({ [foundation]: sources[foundation], [installed]: sources[installed], ...sharedSources }),
190+
source: 'module\npublic import Submission.Library.Shared.Result\n' + challenge });
191+
// A mutable working copy must never become the source of a new frozen problem.
192+
fs.appendFileSync(path.join(f.receipt.projectRoot, shared), '-- later working copy\n');
193+
const before = frozenState(f);
194+
f.library.request(['Access.all_hold'], 'Extend the built-in library without replacing the selected shared library.');
195+
const result = requestedLibraryPack(f.problem, requestValue(f), f.access, f.worktree);
196+
expect(result.selection.modules.map(module => module.file)).toEqual([foundation, installed, requested, support].sort());
197+
expect(result.pack.modules.map(module => module.file).sort()).toEqual([foundation, installed, requested, support, sharedBase, shared].sort());
198+
for (const [file, source] of Object.entries(sharedSources)) {
199+
const module = result.pack.modules.find(module => module.file === file)!;
200+
expect(module.source).toBe(source);
201+
expect(mathDigest(module.source)).toBe(f.problem.frozenFiles![file]);
202+
expect(module.origin).toMatchObject({ commit: f.problem.baseCommit, file: path.posix.join(f.problem.projectRelative, file) });
203+
}
204+
expect(frozenState(f)).toEqual(before);
205+
});
206+
207+
it('rejects a retained shared source whose bytes do not match the trusted frozen identity', () => {
208+
const shared = 'Submission/Library/Shared/Result.lean';
209+
const f = fixture({ frozenPack: sourcePack({ [shared]: 'lemma shared : True := by trivial\n' }) });
210+
f.library.request(['Access.all_hold'], 'Request a new catalog declaration.');
211+
expect(() => requestedLibraryPack({ ...f.problem, frozenFiles: { [shared]: 'b'.repeat(64) } }, requestValue(f), f.access, f.worktree))
212+
.toThrow('math_library_request_existing_module_changed');
213+
});
214+
215+
it.each([
216+
'namespace Access\nlemma all_hold : True := by trivial\nend Access\n',
217+
'namespace Access\nstructure Box where\n value : Nat\nend Access\n',
218+
])('rejects a catalog extension that redeclares a retained shared name: %s', sharedSource => {
219+
const shared = 'Submission/Library/Shared/Conflicting.lean';
220+
const f = fixture({ frozenPack: sourcePack({ [shared]: sharedSource }) });
221+
f.library.request(['Access.all_hold', 'Access.Box'], 'The new catalog modules must not collide with the shared pack.');
222+
expect(() => requestedLibraryPack(f.problem, requestValue(f), f.access, f.worktree)).toThrow('math_library_catalog_declaration_conflict');
223+
});
224+
183225
it('retains the complete old pack, adds the requested dependency closure, and does not select unrelated goal matches', () => {
184226
const f = fixture(), before = frozenState(f);
185227
f.library.request(['Access.all_hold'], 'Use the quantified declaration.');
@@ -264,7 +306,7 @@ describe('host validation of requested frozen continuations', () => {
264306
expect(frozenState(f)).toEqual(before);
265307
});
266308

267-
it('rejects a catalog whose version changes or omits an existing frozen module', () => {
309+
it('rejects changed catalog bytes and retains frozen modules absent from the next catalog', () => {
268310
const f = fixture(), before = frozenState(f);
269311
f.library.request(['Access.all_hold'], 'Need the quantified declaration.');
270312
const request = requestValue(f);
@@ -274,8 +316,8 @@ describe('host validation of requested frozen continuations', () => {
274316
.toThrow('math_library_request_existing_module_changed');
275317
const missing = writeLibraryCatalog(path.join(f.root, 'missing-release'), { id: 'fixture/full-library', revision: 'v3',
276318
environment: 'standard', packs: [sourcePack(Object.fromEntries(Object.entries(sources).filter(([file]) => file !== installed)))] });
277-
expect(() => requestedLibraryPack(f.problem, { ...request, catalogDigest: missing.digest }, { file: missing.file, digest: missing.digest }, f.worktree))
278-
.toThrow('math_library_catalog_module_missing');
319+
const retained = requestedLibraryPack(f.problem, { ...request, catalogDigest: missing.digest }, { file: missing.file, digest: missing.digest }, f.worktree);
320+
expect(retained.pack.modules.find(module => module.file === installed)?.source).toBe(sources[installed]);
279321
expect(frozenState(f)).toEqual(before);
280322
});
281323

@@ -298,15 +340,16 @@ describe('host validation of requested frozen continuations', () => {
298340
expect(frozenState(f)).toEqual(before);
299341
});
300342

301-
it('counts retained modules as well as the new dependency closure toward the installation limit', () => {
343+
it.each(['catalog', 'shared'] as const)('counts retained %s modules as well as the new dependency closure toward the installation limit', origin => {
302344
const dependencies = Object.fromEntries(Array.from({ length: MAX_LIBRARY_PACK_MODULES - 2 }, (_, i) => [
303345
`Submission/Library/AccessBudget/D${i}.lean`, `namespace AccessBudget.D${i}\ndef value : Nat := 0\nend AccessBudget.D${i}\n`,
304346
]));
305347
const entry = 'Submission/Library/AccessBudget/Entry.lean';
306348
const budgetPack = sourcePack({ ...dependencies, [entry]: Object.keys(dependencies)
307349
.map(file => `import ${file.slice(0, -5).replaceAll('/', '.')}\n`).join('') +
308350
'namespace AccessBudget\ntheorem entry : True := trivial\nend AccessBudget\n' });
309-
const f = fixture({ packs: [sourcePack({ [foundation]: sources[foundation], [installed]: sources[installed] }), budgetPack] });
351+
const oldPack = sourcePack({ [foundation]: sources[foundation], [installed]: sources[installed] });
352+
const f = fixture({ packs: origin === 'catalog' ? [oldPack, budgetPack] : [budgetPack], frozenPack: oldPack });
310353
const before = frozenState(f);
311354
const catalog = readLibraryCatalog(f.access.file, f.access.digest);
312355
expect(catalog.select({ source: 'import Submission.Library.AccessBudget.Entry\n', task: '', automatic: false,

‎tests/libraryCatalog.test.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,18 @@ describe('versioned library catalog consumption', () => {
6868
expect(() => f.catalog.materialize(selection)).toThrow('math_library_catalog_source_changed');
6969
});
7070

71+
it('allows only host-retained imports outside the catalog and still rejects unknown imports', () => {
72+
const f = fixture(), shared = 'Submission/Library/Shared/Result.lean';
73+
const source = 'module\npublic import Submission.Library.Shared.Result\n' + challenge;
74+
const input = { source, task: '', automatic: false, environmentDigest: environment.dependencyDigest, requiredFiles: [arithmetic] };
75+
expect(() => f.catalog.select(input)).toThrow('math_library_catalog_module_missing');
76+
const retainedSources = { [shared]: 'namespace Shared\nlemma result : True := by trivial\nend Shared\n' };
77+
expect(f.catalog.select({ ...input, retainedSources }).modules.map(module => module.file)).toEqual([arithmetic, base]);
78+
expect(() => f.catalog.select({ ...input, retainedSources,
79+
source: source.replace('Submission.Library.Shared.Result', 'Submission.Library.Shared.Unknown') }))
80+
.toThrow('math_library_catalog_module_missing');
81+
});
82+
7183
it('excludes declaration conflicts and their consumers before selecting modules', () => {
7284
const f = fixture();
7385
const selection = f.catalog.select({ source: 'namespace Demo\ndef seed : Nat := 4\nend Demo\n' + challenge,

0 commit comments

Comments
 (0)