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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ How a missing expectation is treated depends on the harness:
- `commandJudgePreset` without a `test` option checks whatever expectations exist, and a test case with neither only has to run within the limits. A `test` option replaces that comparison; it receives `testCase.output`, `testCase.fileOutputPath` and `cwd` and can call the exported `judgeAgainstExpectations` (or `compareStdoutAsSpaceSeparatedTokens` and `compareExpectedOutputFiles`). A custom `readTestCases` may return any test case type with `id` (plus optional `input` and `fileInputPath`); the default verdict judges any case that exposes a string `output` or `fileOutputPath`, which the default reader's `CommandTestCase` does.
- `guiCommandJudgePreset` passes the expectations to the problem's `test`, which decides everything.
- `llmJudgePreset` runs no program, so it copies no `.fin/`; it hands `<id>.in` as the prompt input and the whole entry (including `fileOutputPath`) to the problem's `test`.
- `stdioDebugPreset` by default copies the answer directory to a temporary directory and builds and runs it there together with `_shared.fin/` and the first example case's `.fin/` (the case's files win; hidden cases' inputs are never handed to learner code), so the answer directory is left untouched (its `node_modules`, and those of its ancestors, are linked into the copy rather than duplicated); files the program writes are reported only through `requiredOutputFilePaths`. Callers that already own a disposable answer directory can pass `{ disposableWorkingDirectory: true }` as the second argument to build and run directly there; they must remove it themselves, including when the harness is terminated.
- `stdioDebugPreset` by default copies the answer directory to a temporary directory and builds and runs it there together with `_shared.fin/` and the `.fin/` of the first example case that has input files (the case's files win; hidden cases' inputs are never handed to learner code), so the answer directory is left untouched (its `node_modules`, and those of its ancestors, are linked into the copy rather than duplicated); files the program writes are reported only through `requiredOutputFilePaths`. Callers that already own a disposable answer directory can pass `{ disposableWorkingDirectory: true }` as the second argument to build and run directly there; they must remove it themselves, including when the harness is terminated.
- `evaluationJudgePreset` does not use `test_cases/`.

`readTestCases` is exported for harnesses that enumerate `test_cases/` themselves.
Expand Down
32 changes: 15 additions & 17 deletions packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,25 @@ const FILE_INPUT_EXTENSION = '.fin';
* @returns The selected paths, in the given order.
*/
export function selectDebugInputFilePaths(problemFilePaths: readonly string[]): string[] {
const pathToTestCaseId = new Map<string, string>();
for (const filePath of problemFilePaths) {
const [directoryName, entryName, ...rest] = path.posix.normalize(filePath).split('/');
if (directoryName !== TEST_CASES_DIRECTORY_NAME || !entryName?.endsWith(FILE_INPUT_EXTENSION)) continue;
if (rest.length === 0) continue;
pathToTestCaseId.set(filePath, entryName.slice(0, -FILE_INPUT_EXTENSION.length));
}
const selectedIds = new Set(selectDebugFileInputTestCaseIds(pathToTestCaseId.values()));
const fileInputTestCaseIds = new Set(
problemFilePaths.flatMap((filePath) => parseFileInputTestCaseId(filePath) ?? [])
);
const exampleId = [...fileInputTestCaseIds]
.toSorted()
.find((id) => id !== SHARED_TEST_CASE_ID && EXAMPLE_TEST_CASE_ID_PATTERN.test(id));
return problemFilePaths.filter((filePath) => {
const id = pathToTestCaseId.get(filePath);
return id !== undefined && selectedIds.has(id);
const id = parseFileInputTestCaseId(filePath);
return id === SHARED_TEST_CASE_ID || (id !== undefined && id === exampleId);
});
}

/**
* The ids of the `test_cases/<id>.fin/` directories a debug run receives, in the order they are copied
* (later ones overwrite earlier ones), given the ids of every such directory (`_shared` included).
* The test case id of a problem-relative path of a file inside a `test_cases/<id>.fin/` directory,
* or `undefined` for any other path.
*/
export function selectDebugFileInputTestCaseIds(fileInputTestCaseIds: Iterable<string>): string[] {
const ids = [...new Set(fileInputTestCaseIds)].toSorted();
const sharedIds = ids.filter((id) => id === SHARED_TEST_CASE_ID);
const exampleId = ids.find((id) => id !== SHARED_TEST_CASE_ID && EXAMPLE_TEST_CASE_ID_PATTERN.test(id));
return exampleId === undefined ? sharedIds : [...sharedIds, exampleId];
export function parseFileInputTestCaseId(problemFilePath: string): string | undefined {
const [directoryName, entryName, ...rest] = path.posix.normalize(problemFilePath).split('/');
if (directoryName !== TEST_CASES_DIRECTORY_NAME || !entryName?.endsWith(FILE_INPUT_EXTENSION)) return;
if (rest.length === 0) return;
return entryName.slice(0, -FILE_INPUT_EXTENSION.length);
}
40 changes: 30 additions & 10 deletions packages/problem-utils/src/presets/stdio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
readProblemMarkdownFrontMatter,
} from '../helpers/readProblemMarkdownFrontMatter.js';
import { readTestCases, SHARED_TEST_CASE_ID } from '../helpers/readTestCases.js';
import { selectDebugFileInputTestCaseIds } from '../helpers/selectDebugInputFilePaths.js';
import { parseFileInputTestCaseId, selectDebugInputFilePaths } from '../helpers/selectDebugInputFilePaths.js';
import { spawnWithTimeout } from '../helpers/spawnWithTimeout.js';
import { MAX_STDOUT_LENGTH } from '../helpers/stdioJudgeRules.js';
import {
Expand Down Expand Up @@ -259,8 +259,9 @@ async function hasExpectedFiles(fileOutputPath: string | undefined): Promise<boo

/**
* A preset debug function using stdin and stdout as test cases. The answer directory is copied to a
* temporary directory where it is built and run together with `_shared.fin/` and the first example
* case's `.fin/`; files the program writes are reported only through `requiredOutputFilePaths`.
* temporary directory where it is built and run together with the files `selectDebugInputFilePaths`
* selects: `_shared.fin/` and the `.fin/` of the first example case that has input files. Files the
* program writes are reported only through `requiredOutputFilePaths`.
* Callers that own and remove the working directory can set `disposableWorkingDirectory` to run
* directly there; they are responsible for cleanup even when the harness is terminated.
*
Expand Down Expand Up @@ -443,24 +444,43 @@ async function debugInWorkingDirectory(problemDir: string, cwd: string, params:
}

/**
* A debug run has no test case of its own: it gets the learner-visible input files, placed the way
* the judge does. Clients that ship only those files rely on `selectDebugInputFilePaths`, which
* shares this selection rule.
* A debug run has no test case of its own: it gets the `.fin/` directories whose files
* `selectDebugInputFilePaths` selects, copied the way the judge copies a test case's input files.
*/
async function copyDebugFileInputs(problemDir: string, cwd: string): Promise<void> {
const testCases = await readTestCases(path.join(problemDir, 'test_cases'));
const idToFileInputPath = new Map(
testCases.flatMap((testCase) => (testCase.fileInputPath ? [[testCase.id, testCase.fileInputPath] as const] : []))
Comment thread
exKAZUu marked this conversation as resolved.
Resolved
);
const hasCaseFileInput = idToFileInputPath.size > 0;
if (testCases.shared?.fileInputPath) idToFileInputPath.set(SHARED_TEST_CASE_ID, testCases.shared.fileInputPath);

const ids = selectDebugFileInputTestCaseIds(idToFileInputPath.keys());
for (const id of ids) {
const problemFilePaths = await listFileInputFilePaths(idToFileInputPath);
const selectedIds = new Set(
selectDebugInputFilePaths(problemFilePaths).flatMap((filePath) => parseFileInputTestCaseId(filePath) ?? [])
);
const exampleId = [...selectedIds].find((id) => id !== SHARED_TEST_CASE_ID);
// The example's files go last so that they overwrite shared files at the same path, as in judging.
for (const id of [...selectedIds].toSorted((a, b) => Number(a === exampleId) - Number(b === exampleId))) {
const fileInputPath = idToFileInputPath.get(id);
if (fileInputPath) await copyTestCaseFileInput(fileInputPath, cwd);
}
if (hasCaseFileInput && ids.every((id) => id === SHARED_TEST_CASE_ID)) {
const hasCaseFileInput = problemFilePaths.some(
(filePath) => parseFileInputTestCaseId(filePath) !== SHARED_TEST_CASE_ID
);
if (exampleId === undefined && hasCaseFileInput) {
console.error('debug: no example test case has input files, so the program runs without them');
}
}

async function listFileInputFilePaths(idToFileInputPath: ReadonlyMap<string, string>): Promise<string[]> {
const problemFilePaths: string[] = [];
for (const [id, fileInputPath] of idToFileInputPath) {
const dirents = await fs.promises.readdir(fileInputPath, { recursive: true, withFileTypes: true });
for (const dirent of dirents) {
if (dirent.isDirectory()) continue;
const pathInFileInput = path.relative(fileInputPath, path.join(dirent.parentPath, dirent.name));
problemFilePaths.push(`test_cases/${id}.fin/${pathInFileInput}`);
}
}
return problemFilePaths;
}
86 changes: 55 additions & 31 deletions test/e2e/stdioDebugInputFiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,36 +41,60 @@ test(
selectDebugInputFilePaths(['./test_cases/example_2.fin/visible.txt', './test_cases/test_1.fin/secret.txt'])
).toEqual(['./test_cases/example_2.fin/visible.txt']);

await fs.mkdir('.tmp', { recursive: true });
const root = await fs.mkdtemp(path.resolve('.tmp/stdio-debug-input-'));
try {
for (const [filePath, data] of Object.entries(problemFiles)) {
await fs.mkdir(path.dirname(path.join(root, filePath)), { recursive: true });
await fs.writeFile(path.join(root, filePath), data);
}
const answer = path.join(root, 'answer');
await fs.mkdir(answer);
await fs.writeFile(
path.join(answer, 'main.js'),
String.raw`import fs from 'node:fs'; console.log(fs.readdirSync('.', { recursive: true }).filter((p) => p !== 'main.js' && fs.statSync(p).isFile()).toSorted().map((p) => p + '=' + fs.readFileSync(p, 'utf8').trim()).join('\n'));`
);
await fs.writeFile(
path.join(root, 'debug.ts'),
`import { stdioDebugPreset } from ${JSON.stringify(path.resolve('packages/problem-utils/src/presets/stdio.ts'))};\nawait stdioDebugPreset(import.meta.dirname);\n`
);
const run = childProcess.spawnSync('bun', ['run', 'debug.ts', answer, JSON.stringify({ stdin: '' })], {
cwd: root,
encoding: 'utf8',
timeout: 20_000,
});
expect(run.status, run.stderr).toBe(0);
const line = run.stdout.split('\n').find((value) => value.startsWith(TEST_CASE_RESULT_PREFIX));
expect(line).toBeDefined();
const result = testCaseResultSchema.parse(JSON.parse(line!.slice(TEST_CASE_RESULT_PREFIX.length)));
// The example's files overwrite the shared ones at the same path, as in judging.
expect(result.stdout).toBe('members.csv=example 2 members\nnested/notes.txt=shared\nvisible.txt=example 2\n');
} finally {
await fs.rm(root, { recursive: true, force: true });
}
// The example's files overwrite the shared ones at the same path, as in judging.
expect(await runDebug(problemFiles)).toBe(
'members.csv=example 2 members\nnested/notes.txt=shared\nvisible.txt=example 2\n'
);
}
);

test(
'a debug run skips an example whose input directory is empty, as selectDebugInputFilePaths does',
{ timeout: 30_000 },
async () => {
const files = {
'problem.md': '---\n---\n',
'test_cases/example_2.fin/visible.txt': 'example 2\n',
'test_cases/test_1.fin/secret.txt': 'hidden\n',
};
expect(selectDebugInputFilePaths(Object.keys(files))).toEqual(['test_cases/example_2.fin/visible.txt']);
// Git cannot track an empty directory, so only the fixture can create one.
expect(await runDebug(files, ['test_cases/example_1.fin'])).toBe('visible.txt=example 2\n');
}
);

async function runDebug(
problemFiles: Record<string, string>,
emptyDirectories: readonly string[] = []
): Promise<string | undefined> {
await fs.mkdir('.tmp', { recursive: true });
const root = await fs.mkdtemp(path.resolve('.tmp/stdio-debug-input-'));
try {
for (const [filePath, data] of Object.entries(problemFiles)) {
await fs.mkdir(path.dirname(path.join(root, filePath)), { recursive: true });
await fs.writeFile(path.join(root, filePath), data);
}
for (const directory of emptyDirectories) await fs.mkdir(path.join(root, directory), { recursive: true });
const answer = path.join(root, 'answer');
await fs.mkdir(answer);
await fs.writeFile(
path.join(answer, 'main.js'),
String.raw`import fs from 'node:fs'; console.log(fs.readdirSync('.', { recursive: true }).filter((p) => p !== 'main.js' && fs.statSync(p).isFile()).toSorted().map((p) => p + '=' + fs.readFileSync(p, 'utf8').trim()).join('\n'));`
);
await fs.writeFile(
path.join(root, 'debug.ts'),
`import { stdioDebugPreset } from ${JSON.stringify(path.resolve('packages/problem-utils/src/presets/stdio.ts'))};\nawait stdioDebugPreset(import.meta.dirname);\n`
);
const run = childProcess.spawnSync('bun', ['run', 'debug.ts', answer, JSON.stringify({ stdin: '' })], {
cwd: root,
encoding: 'utf8',
timeout: 20_000,
});
expect(run.status, run.stderr).toBe(0);
const line = run.stdout.split('\n').find((value) => value.startsWith(TEST_CASE_RESULT_PREFIX));
expect(line).toBeDefined();
return testCaseResultSchema.parse(JSON.parse(line!.slice(TEST_CASE_RESULT_PREFIX.length))).stdout;
} finally {
await fs.rm(root, { recursive: true, force: true });
}
}
Loading