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
11 changes: 7 additions & 4 deletions packages/problem-utils/src/helpers/readTestCases.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import fs from 'node:fs';
import path from 'node:path';

const SHARED_TEST_CASE_NAME = '_shared';
/** The `test_cases/` entry name (`_shared.fin/`) whose input files every run receives besides its own case's. */
export const SHARED_TEST_CASE_ID = '_shared';

/**
* Read the test cases of a `test_cases/` directory. A test case id is the name of every
* `<id>.in` / `<id>.out` file and `<id>.fin/` / `<id>.fout/` directory; any of them may be absent,
* and what an absent part means is up to the harness (the presets document their rules).
* Other entries (e.g. `.json` configuration read by a custom `judge.ts`) are ignored.
*/
// code-gauge-allow functionCognitiveComplexity 26 -- one pass over the directory entries classifies every entry kind; splitting it would only pass the five maps around
// code-gauge-allow functionNcss 33 -- one pass over the directory entries classifies every entry kind; splitting it would only pass the five maps around
export async function readTestCases(directory: string): Promise<
{ id: string; input?: string; output?: string; fileInputPath?: string; fileOutputPath?: string }[] & {
shared?: { fileInputPath?: string };
Expand Down Expand Up @@ -43,7 +46,7 @@ export async function readTestCases(directory: string): Promise<
}

const testCases: Awaited<ReturnType<typeof readTestCases>> = [...idSet]
.filter((id) => id !== SHARED_TEST_CASE_NAME)
.filter((id) => id !== SHARED_TEST_CASE_ID)
.toSorted()
.map((id) => ({
id,
Expand All @@ -53,8 +56,8 @@ export async function readTestCases(directory: string): Promise<
fileOutputPath: idToFileOutputPath.get(id),
}));

if (idSet.has(SHARED_TEST_CASE_NAME)) {
testCases.shared = { fileInputPath: idToFileInputPath.get(SHARED_TEST_CASE_NAME) };
if (idSet.has(SHARED_TEST_CASE_ID)) {
testCases.shared = { fileInputPath: idToFileInputPath.get(SHARED_TEST_CASE_ID) };
}

return testCases;
Expand Down
45 changes: 45 additions & 0 deletions packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import path from 'node:path';

import { SHARED_TEST_CASE_ID } from './readTestCases.js';
import { EXAMPLE_TEST_CASE_ID_PATTERN } from './stdioJudgeRules.js';

const TEST_CASES_DIRECTORY_NAME = 'test_cases';
const FILE_INPUT_EXTENSION = '.fin';

/**
* Select, from the files of a problem directory, the input files that the stdio debug preset hands
* to the debugged program: every file (of any name) in `test_cases/_shared.fin/` and in the `.fin/`
* directory of the first example test case, in sorted id order, that has one. The `<id>.in`/`<id>.out`
* entries directly under `test_cases/`, hidden test cases' `.fin/` files, and every file outside
* `test_cases/` are never selected, so a client can ship the result (plus `problem.md`) to debug a
* problem without exposing anything the debug run would not expose anyway.
*
* @param problemFilePaths Paths relative to the problem directory, separated by `/`
* (e.g. `test_cases/_shared.fin/members.csv` or `./test_cases/_shared.fin/members.csv`).
* @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()));
return problemFilePaths.filter((filePath) => {
const id = pathToTestCaseId.get(filePath);
return id !== undefined && selectedIds.has(id);
});
}

/**
* 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).
*/
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];
}
1 change: 1 addition & 0 deletions packages/problem-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from './helpers/readTestCases.js';
export * from './helpers/removeCommentsInSourceCode.js';
export * from './helpers/runCommandInTemporaryPackageManagerProject.js';
export * from './helpers/runPythonInTemporaryUvProject.js';
export { selectDebugInputFilePaths } from './helpers/selectDebugInputFilePaths.js';
export * from './helpers/sourceCodeGrammars.js';
export * from './helpers/startHttpServer.js';
export * from './learningMaterial/validateContest.js';
Expand Down
44 changes: 29 additions & 15 deletions packages/problem-utils/src/presets/stdio.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ import {
judgesTestCasesWithoutExpectations,
readProblemMarkdownFrontMatter,
} from '../helpers/readProblemMarkdownFrontMatter.js';
import { readTestCases } from '../helpers/readTestCases.js';
import { readTestCases, SHARED_TEST_CASE_ID } from '../helpers/readTestCases.js';
import { selectDebugFileInputTestCaseIds } from '../helpers/selectDebugInputFilePaths.js';
import { spawnWithTimeout } from '../helpers/spawnWithTimeout.js';
import { EXAMPLE_TEST_CASE_ID_PATTERN, MAX_STDOUT_LENGTH } from '../helpers/stdioJudgeRules.js';
import { MAX_STDOUT_LENGTH } from '../helpers/stdioJudgeRules.js';
import {
copyProblemDirToTemporaryRoot,
forciblyRemoveDirectory,
Expand Down Expand Up @@ -310,6 +311,8 @@ export async function stdioDebugPreset(
}
}

// code-gauge-allow functionCognitiveComplexity 26 -- the build, run, and verdict steps of one debug run share its limits and results
// code-gauge-allow functionNcss 56 -- the build, run, and verdict steps of one debug run share its limits and results
async function debugInWorkingDirectory(problemDir: string, cwd: string, params: DebugParams): Promise<void> {
const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir);

Expand Down Expand Up @@ -396,19 +399,7 @@ async function debugInWorkingDirectory(problemDir: string, cwd: string, params:
}
}

// A debug run has no test case of its own: it gets the shared input files and the `.fin/` of the
// first example case (the cases a learner may see), placed the way the judge does. Hidden cases'
// input files are never handed to learner code.
const testCases = await readTestCases(path.join(problemDir, 'test_cases'));
if (testCases.shared?.fileInputPath) await copyTestCaseFileInput(testCases.shared.fileInputPath, cwd);
const exampleFileInputPath = testCases.find(
(testCase) => EXAMPLE_TEST_CASE_ID_PATTERN.test(testCase.id) && testCase.fileInputPath
)?.fileInputPath;
if (exampleFileInputPath) {
await copyTestCaseFileInput(exampleFileInputPath, cwd);
} else if (testCases.some((testCase) => testCase.fileInputPath)) {
console.error('debug: no example test case has input files, so the program runs without them');
}
await copyDebugFileInputs(problemDir, cwd);

const timeoutSeconds = Math.max(DEBUG_DEFAULT_TIMEOUT_SECONDS, (problemMarkdownFrontMatter.timeLimitMs ?? 0) / 1000);

Expand Down Expand Up @@ -450,3 +441,26 @@ async function debugInWorkingDirectory(problemDir: string, cwd: string, params:
outputFiles: outputFiles.length > 0 ? outputFiles : undefined,
});
}

/**
* 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.
*/
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] : []))
);
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 fileInputPath = idToFileInputPath.get(id);
if (fileInputPath) await copyTestCaseFileInput(fileInputPath, cwd);
}
if (hasCaseFileInput && ids.every((id) => id === SHARED_TEST_CASE_ID)) {
console.error('debug: no example test case has input files, so the program runs without them');
}
}
76 changes: 76 additions & 0 deletions test/e2e/stdioDebugInputFiles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import childProcess from 'node:child_process';
import fs from 'node:fs/promises';
import path from 'node:path';

import { expect, test } from 'vitest';

import { selectDebugInputFilePaths } from '../../packages/problem-utils/src/index.js';
import {
TEST_CASE_RESULT_PREFIX,
testCaseResultSchema,
} from '../../packages/problem-utils/src/types/testCaseResult.js';

const problemFiles: Record<string, string> = {
'problem.md': '---\n---\n',
'model_answers/js/main.js': 'console.log("answer");',
'test_cases/_shared.fin/members.csv': 'name\n',
'test_cases/_shared.fin/nested/notes.txt': 'shared\n',
'test_cases/example_1.in': '1\n',
'test_cases/example_1.out': '1\n',
'test_cases/example_3.fin/later.txt': 'example 3\n',
'test_cases/example_2.fin/members.csv': 'example 2 members\n',
'test_cases/example_2.fin/visible.txt': 'example 2\n',
'test_cases/a_hidden.fin/secret.txt': 'hidden\n',
'test_cases/test_1.fin/secret.txt': 'hidden\n',
'test_cases/test_1.in': '1\n',
'test_cases/test_1.out': '1\n',
};

test(
'a debug run receives exactly the input files selectDebugInputFilePaths selects',
{ timeout: 30_000 },
async () => {
const selectedPaths = selectDebugInputFilePaths(Object.keys(problemFiles));
expect(selectedPaths).toEqual([
'test_cases/_shared.fin/members.csv',
'test_cases/_shared.fin/nested/notes.txt',
'test_cases/example_2.fin/members.csv',
'test_cases/example_2.fin/visible.txt',
]);
expect(
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 });
}
}
);
Loading