diff --git a/packages/problem-utils/src/helpers/readTestCases.ts b/packages/problem-utils/src/helpers/readTestCases.ts index 913eafe..9e03949 100644 --- a/packages/problem-utils/src/helpers/readTestCases.ts +++ b/packages/problem-utils/src/helpers/readTestCases.ts @@ -1,7 +1,8 @@ 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 @@ -9,6 +10,8 @@ const SHARED_TEST_CASE_NAME = '_shared'; * 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 }; @@ -43,7 +46,7 @@ export async function readTestCases(directory: string): Promise< } const testCases: Awaited> = [...idSet] - .filter((id) => id !== SHARED_TEST_CASE_NAME) + .filter((id) => id !== SHARED_TEST_CASE_ID) .toSorted() .map((id) => ({ id, @@ -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; diff --git a/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts b/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts new file mode 100644 index 0000000..1b9eab0 --- /dev/null +++ b/packages/problem-utils/src/helpers/selectDebugInputFilePaths.ts @@ -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 `.in`/`.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(); + 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/.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[] { + 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]; +} diff --git a/packages/problem-utils/src/index.ts b/packages/problem-utils/src/index.ts index 49043e4..46d96b8 100644 --- a/packages/problem-utils/src/index.ts +++ b/packages/problem-utils/src/index.ts @@ -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'; diff --git a/packages/problem-utils/src/presets/stdio.ts b/packages/problem-utils/src/presets/stdio.ts index 4ca18e9..4fc4baa 100644 --- a/packages/problem-utils/src/presets/stdio.ts +++ b/packages/problem-utils/src/presets/stdio.ts @@ -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, @@ -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 { const problemMarkdownFrontMatter = await readProblemMarkdownFrontMatter(problemDir); @@ -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); @@ -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 { + 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'); + } +} diff --git a/test/e2e/stdioDebugInputFiles.test.ts b/test/e2e/stdioDebugInputFiles.test.ts new file mode 100644 index 0000000..e9441a3 --- /dev/null +++ b/test/e2e/stdioDebugInputFiles.test.ts @@ -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 = { + '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 }); + } + } +);