File size: 17,017 Bytes
5fed0fc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
import fs from 'fs/promises';
import path from 'path';
import { toNs, toBytes, fileExists } from './utils.js';
import { GoJudgeClient } from './gojudge.js';
import { ProblemManager } from './problem_manager.js';
export class JudgeEngine {
constructor(config) {
this.problemManager = new ProblemManager({
problemsRoot: config.problemsRoot,
gjAddr: config.gjAddr,
testlibPath: config.testlibPath
});
this.goJudge = new GoJudgeClient(config.gjAddr);
this.submissionManager = config.submissionManager;
this.testlibPath = config.testlibPath || '/lib/testlib';
// In-memory queue and results
this.queue = [];
this.results = new Map();
// Start worker threads
this.startWorkers(config.workers || 4);
}
// Submit a task
async submit(pid, lang, code) {
const sid = await this.submissionManager.nextSubmissionId();
this.results.set(sid, { status: 'queued' });
const { bucketDir, subDir } = this.submissionManager.submissionPaths(sid);
await fs.mkdir(bucketDir, { recursive: true });
await fs.mkdir(subDir, { recursive: true });
if(this.queue.length >= 1024 * 512){
this.queue.push({ sid, pid, lang });
await fs.writeFile(
path.join(subDir, `source.code`),
code
);
}else{
this.queue.push({ sid, pid, lang, code });
}
await fs.writeFile(
path.join(subDir, 'meta.json'),
JSON.stringify({ sid, pid, lang, ts: Date.now() }, null, 2)
);
return sid;
}
// Get the result
getResult(sid) {
const r = this.results.get(sid);
if (r) {
// Only delete the result from the cache if it's a final state
if (r.status === 'done' || r.status === 'error') {
this.results.delete(sid);
}
return r;
}
try {
const { subDir } = this.submissionManager.submissionPaths(sid);
const txt = fs.readFileSync(path.join(subDir, 'result.json'), 'utf8');
return JSON.parse(txt);
} catch {
return null;
}
}
// Clear the results cache
clearResults() {
this.results.clear();
}
// Judge a single test case
async judgeCase({ runSpec, caseItem, problem, checkerId }) {
// Read input and answer files
const inf = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), caseItem.input);
let ans;
try {
const ansFile = caseItem.output.replace(/\.out$/, '.ans');
ans = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), ansFile);
} catch {
ans = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), caseItem.output);
}
// Run the contestant's program
const runRes = await this.goJudge.runOne({
args: runSpec.runArgs,
env: ['PATH=/usr/bin:/bin'],
files: [{ content: inf }, { name: 'stdout', max: 128 * 1024 * 1024 }, { name: 'stderr', max: 64 * 1024 * 1024 }],
cpuLimit: toNs(caseItem.time),
clockLimit: toNs(caseItem.time) * 2,
memoryLimit: toBytes(caseItem.memory),
stackLimit: toBytes(caseItem.memory),
addressSpaceLimit: true,
procLimit: 128,
copyIn: { ...runSpec.preparedCopyIn }
});
let extra = '';
if (runRes.status === 'Signalled') {
extra = `(signal=${runRes.error || 'unknown'})`;
}
if (runRes.status !== 'Accepted') {
return {
ok: false,
status: runRes.status,
time: runRes.runTime,
memory: runRes.memory,
msg: (runRes.files?.stderr || '' ) + extra
};
}
const out = runRes.files?.stdout ?? '';
// Run the checker (testlib)
const chkRes = await this.goJudge.runOne({
args: ['chk', 'in.txt', 'out.txt', 'ans.txt'],
env: ['PATH=/usr/bin:/bin'],
files: [{ content: '' }, { name: 'stdout', max: 1024 * 1024 }, { name: 'stderr', max: 1024 * 1024 }],
cpuLimit: 10e9, // 10 seconds
clockLimit: 20e9,
memoryLimit: 256 << 20,
stackLimit: 256 << 20,
procLimit: 128,
copyIn: {
'chk': { fileId: checkerId },
'in.txt': { content: inf },
'out.txt': { content: out },
'ans.txt': { content: ans }
}
});
const ok = chkRes.status === 'Accepted' && chkRes.exitStatus === 0;
return {
ok,
status: ok ? 'Accepted' : 'Wrong Answer',
time: runRes.runTime,
memory: runRes.memory,
msg: chkRes.files?.stdout || chkRes.files?.stderr || ''
};
}
async judgeInteractiveCase({ runSpec, caseItem, problem, interactorId }) {
const inf = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), caseItem.input);
let ans;
try {
const ansFile = caseItem.output.replace(/\.out$/, '.ans');
ans = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), ansFile);
} catch {
ans = await this.problemManager.readTestFile(problem.pdir.split('/').pop(), caseItem.output);
}
// Run interactive judging
const interactRes = await this.goJudge.run({
cmd: [
{ // Contestant's program
args: runSpec.runArgs,
env: ['PATH=/usr/bin:/bin'],
files: [null, null, { name: 'stderr', max: 1024*1024 }],
cpuLimit: toNs(caseItem.time),
clockLimit: toNs(caseItem.time) * 2,
memoryLimit: toBytes(caseItem.memory),
stackLimit: toBytes(caseItem.memory),
procLimit: 128,
copyIn: { ...runSpec.preparedCopyIn },
},
{ // Interactor
args: ['interactor', 'in.txt', 'tout.txt', 'ans.txt'],
env: ['PATH=/usr/bin:/bin'],
files: [null, null, { name: 'stderr', max: 1024*1024 }],
cpuLimit: toNs(caseItem.time) * 4,
clockLimit: toNs(caseItem.time) * 4 * 2,
memoryLimit: toBytes(caseItem.memory) * 4,
stackLimit: toBytes(caseItem.memory) * 4,
procLimit: 128,
copyIn: {
'interactor': { fileId: interactorId },
'in.txt': { content: inf },
'ans.txt': { content: ans }
}
}
],
pipeMapping: [
{ in: { index: 0, fd: 1 }, out: { index: 1, fd: 0 } },
{ in: { index: 1, fd: 1 }, out: { index: 0, fd: 0 } }
]
});
const submissionRes = interactRes[0];
const interactorRes = interactRes[1];
if (submissionRes.status === 'Accepted' && interactorRes.status === 'Accepted' && interactorRes.exitStatus === 0 && submissionRes.exitStatus === 0 ) {
return {
ok: true,
status: 'Accepted',
time: submissionRes.runTime,
memory: Math.max(submissionRes.memory, interactorRes.memory),
msg: (interactorRes.files?.stdout || '') + (interactorRes.files?.stderr || '')
};
}
if (submissionRes.status !== 'Accepted') {
let extra = (submissionRes.status === 'Signalled') ? ` (signal=${submissionRes.error || 'unknown'})` : '';
return { ok: false, status: submissionRes.status, time: submissionRes.runTime, memory: submissionRes.memory, msg: (submissionRes.files?.stderr || '') + extra };
}
if (interactorRes.status !== 'Accepted') {
return { ok: false, status: interactorRes.status, time: submissionRes.runTime, memory: submissionRes.memory, msg: (interactorRes.files?.stderr || '') };
}
// Default to WA if interactor exits non-zero
return { ok: false, status: 'Wrong Answer', time: submissionRes.runTime, memory: submissionRes.memory, msg: (interactorRes.files?.stderr || '') };
}
// Start worker threads
startWorkers(workerCount) {
for (let i = 0; i < workerCount; i++) {
this.startWorker();
}
}
async judgeDefault(problem, sid, pid, lang, code, subDir) {
let cleanupIds = [];
let checkerCleanup, checkerId;
try {
// Prepare contestant's program
const runSpec = await this.goJudge.prepareProgram({ lang, code, mainName: problem.filename || null });
cleanupIds.push(...(runSpec.cleanupIds || []));
// Prepare checker
const checkerBinPath = path.join(problem.pdir, `${problem.checker}.bin`);
let checkerResult;
if (await fileExists(checkerBinPath)) {
checkerResult = await this.goJudge.copyInBin(checkerBinPath);
} else if (problem.checker) {
const chkSrc = await this.problemManager.readCheckerSource(pid, problem.checker);
checkerResult = await this.goJudge.prepareChecker(chkSrc, this.testlibPath);
}
checkerId = checkerResult.binId || checkerResult.checkerId;
checkerCleanup = checkerResult.cleanup;
// Run all cases
let totalScore = 0;
let totalScoreUnbounded = 0;
const caseResults = [];
for (const c of problem.cases) {
const r = await this.judgeCase({ runSpec, caseItem: c, problem, checkerId });
const matchBounded = r.msg.match(/Ratio: ([\d.]+)/);
const matchUnbounded = r.msg.match(/RatioUnbounded: ([\d.]+)/);
r.scoreRatio = matchBounded ? parseFloat(matchBounded[1]) : (r.ok ? 1.0 : 0);
r.scoreRatioUnbounded = matchUnbounded ? parseFloat(matchUnbounded[1]) : r.scoreRatio;
totalScore += r.scoreRatio;
totalScoreUnbounded += r.scoreRatioUnbounded;
caseResults.push(r);
}
// The overall "passed" status depends on all cases achieving a perfect score ratio
const passed = caseResults.every(r => r.scoreRatio === 1.0);
const overallResult = passed ? 'Correct Answer' : 'Wrong Answer';
const finalScore = problem.cases.length > 0 ? (totalScore / problem.cases.length) * 100 : 0;
const finalScoreUnbounded = problem.cases.length > 0 ? (totalScoreUnbounded / problem.cases.length) * 100 : 0;
// Remap individual case statuses based on scoreRatio
const finalCases = caseResults.map(caseResult => ({
...caseResult,
status: caseResult.scoreRatio === 1.0 ? 'Correct' : 'Wrong Answer'
}));
const final = {
status: 'done',
passed,
result: overallResult,
score: finalScore,
scoreUnbounded: finalScoreUnbounded,
cases: finalCases
};
this.results.set(sid, final);
await fs.writeFile(path.join(subDir, 'result.json'), JSON.stringify(final, null, 2));
} catch (e) {
const err = { status: 'error', error: String(e) };
this.results.set(sid, err);
await fs.writeFile(path.join(subDir, 'result.json'), JSON.stringify(err, null, 2));
} finally {
for (const id of cleanupIds) await this.goJudge.deleteFile(id);
if (checkerCleanup) await checkerCleanup();
}
}
async judgeInteractive(problem, sid, pid, lang, code, subDir) {
let cleanupIds = [];
let interactorCleanup, interactorId;
try {
// Prepare program and interactor
const runSpec = await this.goJudge.prepareProgram({ lang, code, mainName: problem.filename || null });
cleanupIds.push(...(runSpec.cleanupIds || []));
const interactorBinPath = path.join(problem.pdir, `${problem.interactor}.bin`);
let interactorResult;
if (await fileExists(interactorBinPath)) {
interactorResult = await this.goJudge.copyInBin(interactorBinPath);
} else if (problem.interactor) {
const interSrc = await this.problemManager.readInteractorSource(pid, problem.interactor);
interactorResult = await this.goJudge.prepareInteractor(interSrc, this.testlibPath);
}
interactorId = interactorResult.binId || interactorResult.interactorId;
interactorCleanup = interactorResult.cleanup;
// Run all cases and calculate score
let totalScore = 0;
let totalScoreUnbounded = 0;
const caseResults = [];
for (const c of problem.cases) {
const r = await this.judgeInteractiveCase({ runSpec, caseItem: c, problem, interactorId });
// Parse score ratio from interactor message
const matchBounded = r.msg.match(/Ratio: ([\d.]+)/);
const matchUnbounded = r.msg.match(/RatioUnbounded: ([\d.]+)/);
r.scoreRatio = matchBounded ? parseFloat(matchBounded[1]) : (r.ok ? 1.0 : 0);
r.scoreRatioUnbounded = matchUnbounded ? parseFloat(matchUnbounded[1]) : r.scoreRatio;
totalScore += r.scoreRatio;
totalScoreUnbounded += r.scoreRatioUnbounded;
caseResults.push(r);
}
const passed = caseResults.every(r => r.scoreRatio === 1.0);
const overallResult = passed ? 'Correct Answer' : 'Wrong Answer';
const finalScore = problem.cases.length > 0 ? (totalScore / problem.cases.length) * 100 : 0;
const finalScoreUnbounded = problem.cases.length > 0 ? (totalScoreUnbounded / problem.cases.length) * 100 : 0;
// Remap individual case statuses for clarity
const finalCases = caseResults.map(caseResult => ({
...caseResult,
status: caseResult.scoreRatio === 1.0 ? 'Correct' : 'Wrong Answer'
}));
const final = {
status: 'done',
passed,
result: overallResult,
score: finalScore,
scoreUnbounded: finalScoreUnbounded,
cases: finalCases
};
this.results.set(sid, final);
await fs.writeFile(path.join(subDir, 'result.json'), JSON.stringify(final, null, 2));
} catch (e) {
const err = { status: 'error', error: String(e) };
this.results.set(sid, err);
await fs.writeFile(path.join(subDir, 'result.json'), JSON.stringify(err, null, 2));
} finally {
for (const id of cleanupIds) await this.goJudge.deleteFile(id);
if (interactorCleanup) await interactorCleanup();
}
}
// A single worker thread
async startWorker() {
while (true) {
const job = this.queue.shift();
if (!job) {
await new Promise(r => setTimeout(r, 50));
continue;
}
let { sid, pid, lang, code } = job;
const { subDir } = this.submissionManager.submissionPaths(sid);
if (typeof code !== 'string') {
code = await fs.readFile(path.join(subDir, 'source.code'), 'utf8');
} else {
await fs.writeFile(path.join(subDir, 'source.code'), code);
}
const problem = await this.problemManager.loadProblem(pid);
switch (problem.cfg.type) {
case 'interactive':
await this.judgeInteractive(problem, sid, pid, lang, code, subDir);
break;
case 'leetcode':
throw new Error('LeetCode problems are not supported for now.');
default:
await this.judgeDefault(problem, sid, pid, lang, code, subDir);
break;
}
}
}
getSourceFileName(lang) {
switch (lang) {
case 'cpp': return 'main.cpp';
case 'py':
case 'pypy': return 'main.py';
case 'java': return 'Main.java';
default: return 'main.txt';
}
}
}
|