diff --git a/backend/controllers/submissionController.js b/backend/controllers/submissionController.js index b635dce..58bbdae 100644 --- a/backend/controllers/submissionController.js +++ b/backend/controllers/submissionController.js @@ -138,6 +138,9 @@ export const runCode = async (req, res) => { return res.status(202).json(jobStatus); } catch (error) { + if (error.statusCode === 429 || error.code === 'QUEUE_FULL') { + return res.status(429).json({ message: error.message || 'Execution queue is full. Please try again shortly.' }); + } res.status(500).json({ message: error.message }); } }; @@ -237,32 +240,15 @@ export const submitCode = async (req, res) => { // Check if this user already solved this question before (for isFirstAccepted) const user = await User.findById(userId); - const alreadySolved = user.solvedQuestions.some( + const alreadySolved = user ? user.solvedQuestions.some( (id) => id.toString() === question._id.toString() - ); + ) : false; const isFirstAccepted = isAccepted && !alreadySolved; - const submission = await Submission.create({ - user: userId, - question: question._id, - code, - language, - status: overallVerdict, - passedCount, - totalCount, - errorMessage: firstErrorMessage, - runTime: runTimeMax, - isFirstAccepted - }); - - // Auto-update Question stats (totalSubmissions + totalAccepted) - await updateQuestionStats(question._id, isAccepted); - - // Update User statistics - user.submissionsCount += 1; - - if (isAccepted) { - if (!alreadySolved) { + // Update user statistics in memory + if (user) { + user.submissionsCount += 1; + if (isAccepted && !alreadySolved) { user.solvedQuestions.push(question._id); // Update solved difficulty counts @@ -273,7 +259,24 @@ export const submitCode = async (req, res) => { } } - await user.save(); + // Parallelize genuinely independent database writes + const [submission] = await Promise.all([ + Submission.create({ + user: userId, + question: question._id, + code, + language, + status: overallVerdict, + passedCount, + totalCount, + errorMessage: firstErrorMessage, + runTime: runTimeMax, + isFirstAccepted + }), + updateQuestionStats(question._id, isAccepted), + user ? user.save() : Promise.resolve() + ]); + return submission; }; @@ -281,6 +284,9 @@ export const submitCode = async (req, res) => { return res.status(202).json(jobStatus); } catch (error) { + if (error.statusCode === 429 || error.code === 'QUEUE_FULL') { + return res.status(429).json({ message: error.message || 'Execution queue is full. Please try again shortly.' }); + } res.status(500).json({ message: error.message }); } }; diff --git a/backend/tests/benchmark_pipeline_baseline.js b/backend/tests/benchmark_pipeline_baseline.js new file mode 100644 index 0000000..55d59de --- /dev/null +++ b/backend/tests/benchmark_pipeline_baseline.js @@ -0,0 +1,144 @@ +import { runLocalCodeMulti } from '../utils/localRunner.js'; +import User from '../models/User.js'; + +const questionData = { + visibleTestCases: [ + { input: '4 10\n2 3 5 7', output: '10' }, + { input: '3 9\n4 8 6', output: '8' }, + { input: '3 5\n1 2 3', output: '5' } + ], + hiddenTestCases: [ + { input: '2 5\n2 4', output: '4' }, + { input: '1 100\n50', output: '50' }, + { input: '5 20\n1 2 3 4 5', output: '15' }, + { input: '4 15\n5 5 5 5', output: '15' }, + { input: '3 10\n10 20 30', output: '10' }, + { input: '4 11\n2 4 6 8', output: '10' } + ] +}; + +const allTestCases = [...questionData.visibleTestCases, ...questionData.hiddenTestCases]; +const inputs = allTestCases.map(tc => tc.input); + +const cppCode = '#include \n#include \nusing namespace std;\nint main() { int n; long long max_sum; if (!(cin >> n >> max_sum)) return 0; vector costs(n); for (int i = 0; i < n; i++) cin >> costs[i]; vector dp(max_sum + 1, false); dp[0] = true; for (int i = 0; i < n; i++) { long long c = costs[i]; for (long long j = max_sum; j >= c; j--) { if (dp[j - c]) dp[j] = true; } } for (long long j = max_sum; j >= 0; j--) { if (dp[j]) { cout << j << endl; break; } } return 0; }'; + +const javaCode = 'import java.util.Scanner;\npublic class Main {\n public static void main(String[] args) {\n Scanner sc = new Scanner(System.in);\n if (!sc.hasNextInt()) return;\n int n = sc.nextInt();\n int maxSum = sc.nextInt();\n int[] costs = new int[n];\n for (int i = 0; i < n; i++) costs[i] = sc.nextInt();\n boolean[] dp = new boolean[maxSum + 1];\n dp[0] = true;\n for (int c : costs) {\n for (int j = maxSum; j >= c; j--) {\n if (dp[j - c]) dp[j] = true;\n }\n }\n for (int j = maxSum; j >= 0; j--) {\n if (dp[j]) { System.out.println(j); break; }\n }\n }\n}'; + +const pythonCode = 'import sys\ninput_data = sys.stdin.read().split()\nif input_data:\n n, max_sum = int(input_data[0]), int(input_data[1])\n costs = [int(x) for x in input_data[2:2+n]]\n dp = [False] * (max_sum + 1)\n dp[0] = True\n for c in costs:\n for j in range(max_sum, c - 1, -1):\n if dp[j - c]:\n dp[j] = True\n for j in range(max_sum, -1, -1):\n if dp[j]:\n print(j)\n break\n'; + +export async function runFullBenchmark(label = 'Baseline', customOptions = {}) { + console.log(`\n================================================================`); + console.log(` NQTCoder Benchmark: ${label}`); + console.log(`================================================================\n`); + + const mockUser = User.hydrate({ + _id: '507f1f77bcf86cd799439011', + username: 'benchmark_student', + email: 'student@nqtcoder.dev', + password: '$2a$10$abcdefghijklmnopqrstuu', + submissionsCount: 5, + solvedQuestions: [], + solvedCount: { easy: 2, medium: 2, hard: 1 } + }); + + const runLang = async (langName, code, langId) => { + console.log(`--- Benchmarking 5 Full Runs for ${langName} (9 Test Cases) ---`); + const runs = []; + for (let r = 1; r <= 5; r++) { + const tStart = performance.now(); + + // 1. Request / Auth simulation + const tAuth = 1.0; + + // 2. Queue scheduling simulation + const tQueue = 0.5; + + // 3. Execution (Compile + 9 Test Cases) + const tExecStart = performance.now(); + const execRes = await runLocalCodeMulti(code, langId, inputs, 2); + const tExec = performance.now() - tExecStart; + + // 4. Result verdict check + let passed = 0; + for (let i = 0; i < allTestCases.length; i++) { + if (execRes.results && execRes.results[i]?.stdout?.trim() === allTestCases[i].output.trim()) { + passed++; + } + } + + // 5. DB Persistence simulation (User pre-save hook with fix) + const tUserSaveStart = performance.now(); + mockUser.submissionsCount += 1; + mockUser.solvedCount.medium += 1; + await new Promise((resolve) => { + mockUser.schema.s.hooks.execPre('save', mockUser, () => resolve()); + }); + const tUserSave = performance.now() - tUserSaveStart; + const tDbTotal = tUserSave + 40.0; // ~40ms network write + + // 6. Polling simulation + const pollingInterval = customOptions.pollingDelay || 1000; + // Fixed 1000ms polling vs adaptive: + let tPollingLag = 500.0; // average fixed 1000ms delay lag + if (customOptions.adaptivePolling) { + // Adaptive schedule: [0, 150, 250, 400, 600, 1000] + // If execution finishes at tExec, the next poll tick triggers in ~75ms on average + tPollingLag = 75.0; + } + + const totalBackend = tAuth + tQueue + tExec + tDbTotal; + const totalUserPerceived = totalBackend + tPollingLag; + + runs.push({ + run: r, + backendTime: totalBackend, + pollingLag: tPollingLag, + userPerceivedTime: totalUserPerceived, + execTime: tExec, + dbTime: tDbTotal, + passed + }); + + console.log(` Run #${r}: Backend = ${totalBackend.toFixed(1)} ms | Polling Lag = ${tPollingLag.toFixed(1)} ms | User-Perceived = ${totalUserPerceived.toFixed(1)} ms (Passed: ${passed}/9)`); + } + + const calcStats = (arr) => { + const sorted = [...arr].sort((a, b) => a - b); + const min = sorted[0]; + const max = sorted[sorted.length - 1]; + const avg = sorted.reduce((a, b) => a + b, 0) / sorted.length; + const med = sorted[Math.floor(sorted.length / 2)]; + const p95 = sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * 0.95))]; + return { min, max, avg, med, p95 }; + }; + + const backendStats = calcStats(runs.map(r => r.backendTime)); + const userStats = calcStats(runs.map(r => r.userPerceivedTime)); + + return { + langName, + backendStats, + userStats, + runs + }; + }; + + const pyResults = await runLang('Python', pythonCode, 'python'); + const cppResults = await runLang('C++', cppCode, 'cpp'); + const javaResults = await runLang('Java', javaCode, 'java'); + + console.log(`\n================================================================`); + console.log(` ${label.toUpperCase()} SUMMARY RESULTS (AVERAGE OF 5 RUNS) `); + console.log(`================================================================`); + console.log(`Python: Backend = ${pyResults.backendStats.avg.toFixed(1)} ms | Perceived = ${pyResults.userStats.avg.toFixed(1)} ms (Median: ${pyResults.userStats.med.toFixed(1)} ms)`); + console.log(`C++: Backend = ${cppResults.backendStats.avg.toFixed(1)} ms | Perceived = ${cppResults.userStats.avg.toFixed(1)} ms (Median: ${cppResults.userStats.med.toFixed(1)} ms)`); + console.log(`Java: Backend = ${javaResults.backendStats.avg.toFixed(1)} ms | Perceived = ${javaResults.userStats.avg.toFixed(1)} ms (Median: ${javaResults.userStats.med.toFixed(1)} ms)`); + console.log(`================================================================\n`); + + return { pyResults, cppResults, javaResults }; +} + +// Auto-run if executed directly +if (process.argv[1]?.endsWith('benchmark_pipeline_baseline.js')) { + runFullBenchmark('Pre-Optimization Baseline').catch(console.error); +} diff --git a/backend/tests/load_test_queue.js b/backend/tests/load_test_queue.js new file mode 100644 index 0000000..be55d66 --- /dev/null +++ b/backend/tests/load_test_queue.js @@ -0,0 +1,146 @@ +import { compilerQueue, QueueCapacityError } from '../utils/compilerQueue.js'; +import { runLocalCodeMulti } from '../utils/localRunner.js'; + +const pyCode = 'import sys\ninput_data = sys.stdin.read().split()\nif input_data:\n n, max_sum = int(input_data[0]), int(input_data[1])\n costs = [int(x) for x in input_data[2:2+n]]\n dp = [False] * (max_sum + 1)\n dp[0] = True\n for c in costs:\n for j in range(max_sum, c - 1, -1):\n if dp[j - c]:\n dp[j] = True\n for j in range(max_sum, -1, -1):\n if dp[j]:\n print(j)\n break\n'; +const cppCode = '#include \n#include \nusing namespace std;\nint main() { int n; long long max_sum; if (!(cin >> n >> max_sum)) return 0; vector costs(n); for (int i = 0; i < n; i++) cin >> costs[i]; vector dp(max_sum + 1, false); dp[0] = true; for (int i = 0; i < n; i++) { long long c = costs[i]; for (long long j = max_sum; j >= c; j--) { if (dp[j - c]) dp[j] = true; } } for (long long j = max_sum; j >= 0; j--) { if (dp[j]) { cout << j << endl; break; } } return 0; }'; + +const sampleInputs = [ + '4 10\n2 3 5 7', + '3 9\n4 8 6', + '3 5\n1 2 3', + '2 5\n2 4', + '1 100\n50', + '5 20\n1 2 3 4 5', + '4 15\n5 5 5 5', + '3 10\n10 20 30', + '4 11\n2 4 6 8' +]; + +async function pollJob(jobId) { + const t0 = performance.now(); + while (true) { + const job = compilerQueue.getJobStatus(jobId); + if (!job) throw new Error('Job not found'); + if (job.status === 'completed') { + return { elapsed: performance.now() - t0, result: job.result, status: 'completed' }; + } + if (job.status === 'failed') { + return { elapsed: performance.now() - t0, error: job.error, status: 'failed' }; + } + await new Promise(r => setTimeout(r, 100)); + } +} + +async function runLoadTestScenario(name, submissionCount, lang = 'python') { + console.log(`\n================================================================`); + console.log(` LOAD SCENARIO: ${name} (${submissionCount} Submissions, Lang: ${lang})`); + console.log(`================================================================`); + + const initialMemory = process.memoryUsage().rss / (1024 * 1024); + const codeToRun = lang === 'cpp' ? cppCode : pyCode; + const submissions = []; + const rejected = []; + const tStartAll = performance.now(); + + for (let i = 0; i < submissionCount; i++) { + const submitStart = performance.now(); + try { + const runFn = async () => { + const tStartExec = performance.now(); + const res = await runLocalCodeMulti(codeToRun, lang, sampleInputs, 2); + const execDuration = performance.now() - tStartExec; + return { res, execDuration }; + }; + + const jobStatus = compilerQueue.enqueue(runFn); + submissions.push({ + index: i + 1, + jobId: jobStatus.jobId, + submitTime: submitStart + }); + } catch (err) { + if (err instanceof QueueCapacityError || err.statusCode === 429) { + rejected.push({ index: i + 1, error: err.message }); + } else { + throw err; + } + } + } + + console.log(` Enqueued: ${submissions.length} jobs | Rejected (HTTP 429): ${rejected.length} jobs`); + + // Wait for all enqueued submissions to complete + const results = await Promise.all( + submissions.map(async (s) => { + const pollRes = await pollJob(s.jobId); + const totalJobLatency = performance.now() - s.submitTime; + return { + index: s.index, + totalLatency: totalJobLatency, + backendDuration: pollRes.result?.execDuration || 0, + status: pollRes.status + }; + }) + ); + + const totalTime = performance.now() - tStartAll; + const finalMemory = process.memoryUsage().rss / (1024 * 1024); + + const latencies = results.map(r => r.totalLatency).sort((a, b) => a - b); + const min = latencies[0] || 0; + const max = latencies[latencies.length - 1] || 0; + const avg = latencies.reduce((a, b) => a + b, 0) / (latencies.length || 1); + const p50 = latencies[Math.floor(latencies.length * 0.5)] || 0; + const p95 = latencies[Math.floor(latencies.length * 0.95)] || 0; + const throughputPerMin = ((results.length / totalTime) * 60000).toFixed(1); + + console.log(` Completed: ${results.filter(r => r.status === 'completed').length}/${results.length}`); + console.log(` Total Scenario Time: ${(totalTime / 1000).toFixed(2)}s`); + console.log(` Throughput Rate: ${throughputPerMin} submissions/minute`); + console.log(` Latency Metrics: Min: ${min.toFixed(0)}ms | p50: ${p50.toFixed(0)}ms | Avg: ${avg.toFixed(0)}ms | p95: ${p95.toFixed(0)}ms | Max: ${max.toFixed(0)}ms`); + console.log(` Memory Impact (RSS): Initial: ${initialMemory.toFixed(1)}MB -> Final: ${finalMemory.toFixed(1)}MB (Delta: ${(finalMemory - initialMemory).toFixed(1)}MB)`); + + return { + name, + submissionCount, + completed: results.length, + rejected: rejected.length, + throughputPerMin, + min, + p50, + avg, + p95, + max, + rssDelta: finalMemory - initialMemory + }; +} + +async function runAllLoadTests() { + console.log('================================================================'); + console.log(' NQTCoder Queue Load & Concurrency Benchmark Suite '); + console.log('================================================================'); + + // Scenario 1: 1 Single User + await runLoadTestScenario('Single User Baseline', 1, 'python'); + + // Scenario 2: 2 Simultaneous Submissions + await runLoadTestScenario('2 Concurrent Submissions', 2, 'python'); + + // Scenario 3: 5 Queued Submissions Burst + await runLoadTestScenario('5 Queued Burst (Python)', 5, 'python'); + + // Scenario 4: 10 Queued Submissions Burst + await runLoadTestScenario('10 Queued Burst (Python)', 10, 'python'); + + // Scenario 5: 20 Queued Submissions Burst + await runLoadTestScenario('20 Queued Burst (Python)', 20, 'python'); + + // Scenario 6: Overload Capacity Test (35 Submissions with MAX_QUEUE_SIZE=30) + await runLoadTestScenario('35 Overload Test (Capacity Limit Check)', 35, 'python'); + + console.log('\n================================================================'); + console.log(' LOAD TESTING SUITE COMPLETE '); + console.log('================================================================\n'); +} + +runAllLoadTests().catch(console.error); diff --git a/backend/utils/compilerQueue.js b/backend/utils/compilerQueue.js index 3df5957..17ed29c 100644 --- a/backend/utils/compilerQueue.js +++ b/backend/utils/compilerQueue.js @@ -1,11 +1,24 @@ import crypto from 'crypto'; +export class QueueCapacityError extends Error { + constructor(message = 'Execution queue is full. Please try again shortly.') { + super(message); + this.name = 'QueueCapacityError'; + this.statusCode = 429; + this.code = 'QUEUE_FULL'; + } +} + class CompilerQueue { constructor() { this.queue = []; this.jobs = new Map(); this.activeJobsCount = 0; - this.MAX_RUNNING = Number(process.env.MAX_RUNNING) || 2; + + // Explicit queue configuration + this.MAX_RUNNING = Number(process.env.MAX_EXECUTION_WORKERS) || Number(process.env.MAX_RUNNING) || 1; + this.MAX_QUEUE_SIZE = Number(process.env.MAX_QUEUE_SIZE) || 30; // Maximum WAITING jobs + this.QUEUE_WAIT_TIMEOUT_MS = Number(process.env.QUEUE_WAIT_TIMEOUT_MS) || 45000; // 45s // Evict old jobs from jobs Map after 10 minutes to prevent memory leak setInterval(() => { @@ -19,6 +32,11 @@ class CompilerQueue { } enqueue(runFn) { + // Check queue capacity (maximum waiting jobs) + if (this.queue.length >= this.MAX_QUEUE_SIZE) { + throw new QueueCapacityError(`Execution queue is full (${this.queue.length} jobs waiting). Please try again shortly.`); + } + const jobId = crypto.randomUUID(); const job = { jobId, @@ -48,7 +66,7 @@ class CompilerQueue { if (job.status === 'queued') { const position = this.queue.findIndex(j => j.jobId === jobId) + 1; - const estimatedWait = Math.max(1, position * 3); // simple formula: 3s per position + const estimatedWait = Math.max(1, position * 2); // estimated 2s per position return { jobId, status: 'queued', @@ -62,7 +80,7 @@ class CompilerQueue { jobId, status: 'running', position: 0, - estimatedWait: 3 + estimatedWait: 2 }; } @@ -88,6 +106,16 @@ class CompilerQueue { job.status = 'running'; job.startedAt = Date.now(); + // Check if job timed out while waiting in queue + if (Date.now() - job.queuedAt > this.QUEUE_WAIT_TIMEOUT_MS) { + job.status = 'failed'; + job.error = 'Queue wait timeout exceeded. The compiler server is under heavy load, please retry.'; + job.finishedAt = Date.now(); + this.activeJobsCount--; + process.nextTick(() => this.processQueue()); + return; + } + try { const result = await job.runFn(); job.status = 'completed'; @@ -102,12 +130,15 @@ class CompilerQueue { process.nextTick(() => this.processQueue()); } } + // Returns live snapshot of queue for server load indicator getQueueLoad() { return { waiting: this.queue.length, running: this.activeJobsCount, - total: this.queue.length + this.activeJobsCount + total: this.queue.length + this.activeJobsCount, + maxWorkers: this.MAX_RUNNING, + maxQueueSize: this.MAX_QUEUE_SIZE }; } } diff --git a/backend/utils/localRunner.js b/backend/utils/localRunner.js index df61e62..a0b995a 100644 --- a/backend/utils/localRunner.js +++ b/backend/utils/localRunner.js @@ -1,4 +1,4 @@ -import { spawn, execSync, exec } from 'child_process'; +import { spawn, execFile, execSync, exec } from 'child_process'; import { promisify } from 'util'; import fs from 'fs'; import path from 'path'; @@ -8,14 +8,41 @@ const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const TEMP_DIR = path.join(__dirname, '..', 'temp'); +const MAX_OUTPUT_BYTES = Number(process.env.MAX_OUTPUT_BYTES) || 65536; // 64 KB +const JAVA_MAX_HEAP = process.env.JAVA_MAX_HEAP || '128m'; +const JAVA_INITIAL_HEAP = process.env.JAVA_INITIAL_HEAP || '16m'; + // Ensure temp directory exists if (!fs.existsSync(TEMP_DIR)) { fs.mkdirSync(TEMP_DIR, { recursive: true }); } +/** + * Prunes stale orphaned temporary execution directories older than maxAgeMs. + */ +export const pruneTempDirectory = (maxAgeMs = 10 * 60 * 1000) => { + try { + if (!fs.existsSync(TEMP_DIR)) return; + const now = Date.now(); + const entries = fs.readdirSync(TEMP_DIR); + for (const entry of entries) { + const entryPath = path.join(TEMP_DIR, entry); + try { + const stats = fs.statSync(entryPath); + if (now - stats.mtimeMs > maxAgeMs) { + fs.rmSync(entryPath, { recursive: true, force: true }); + } + } catch (e) {} + } + } catch (e) {} +}; + +// Initial startup prune & 5-minute periodic prune +pruneTempDirectory(); +setInterval(() => pruneTempDirectory(), 5 * 60 * 1000); + // Check if a compiler/executable is available on the system const isCommandAvailable = (cmd) => { - // If the command contains path separators, check if it exists directly on disk if (cmd.includes('/') || cmd.includes('\\')) { try { if (fs.existsSync(cmd)) return true; @@ -40,54 +67,143 @@ const isCommandAvailable = (cmd) => { }; /** - * Runs a command with a child process, feeds stdin, handles timeouts + * Terminates process and process group cleanly + */ +const killProcessTree = (proc) => { + if (!proc || !proc.pid) return; + try { + if (process.platform === 'win32') { + proc.kill(); + } else { + try { + process.kill(-proc.pid, 'SIGKILL'); + } catch (e) { + proc.kill('SIGKILL'); + } + } + } catch (e) {} +}; + +/** + * Executes a compiler command with explicit argument array and no shell interpolation + */ +const execCompilerAsync = (cmd, args, options = {}) => { + return new Promise((resolve) => { + execFile(cmd, args, { cwd: options.cwd || TEMP_DIR, maxBuffer: 1024 * 1024 }, (err, stdout, stderr) => { + if (err) { + resolve({ + success: false, + stdout: stdout || '', + stderr: (stderr || err.message || '').toString() + }); + } else { + resolve({ + success: true, + stdout: stdout || '', + stderr: stderr || '' + }); + } + }); + }); +}; + +/** + * Runs a command with a child process, feeds stdin, handles timeouts, and enforces streaming output limits */ const runProcess = (cmd, args, input, timeoutSec, options = {}) => { return new Promise((resolve) => { - const processInstance = spawn(cmd, args, { cwd: options.cwd || TEMP_DIR }); + let processInstance; + try { + processInstance = spawn(cmd, args, { + cwd: options.cwd || TEMP_DIR, + detached: process.platform !== 'win32' + }); + } catch (err) { + return resolve({ + status: 'Runtime Error', + stdout: '', + error: err.message + }); + } + let stdout = ''; let stderr = ''; + let stdoutBytes = 0; + let stderrBytes = 0; let timedOut = false; + let outputLimitExceeded = false; + let resolved = false; + + const safeResolve = (val) => { + if (resolved) return; + resolved = true; + clearTimeout(timeout); + resolve(val); + }; const timeout = setTimeout(() => { timedOut = true; - try { - processInstance.kill(); - } catch (e) {} - resolve({ + killProcessTree(processInstance); + safeResolve({ status: 'Time Limit Exceeded', - stdout: '', + stdout: stdout.substring(0, MAX_OUTPUT_BYTES), error: `Time limit of ${timeoutSec}s exceeded.` }); }, timeoutSec * 1000); if (input) { - processInstance.stdin.write(input); - processInstance.stdin.end(); + try { + processInstance.stdin.write(input); + processInstance.stdin.end(); + } catch (e) {} } else { - processInstance.stdin.end(); + try { + processInstance.stdin.end(); + } catch (e) {} } processInstance.stdout.on('data', (data) => { + if (outputLimitExceeded || timedOut) return; + stdoutBytes += data.length; + if (stdoutBytes > MAX_OUTPUT_BYTES) { + outputLimitExceeded = true; + killProcessTree(processInstance); + safeResolve({ + status: 'Output Limit Exceeded', + stdout: stdout.substring(0, MAX_OUTPUT_BYTES), + error: `Output limit of ${Math.round(MAX_OUTPUT_BYTES / 1024)}KB exceeded.` + }); + return; + } stdout += data.toString(); }); processInstance.stderr.on('data', (data) => { + if (outputLimitExceeded || timedOut) return; + stderrBytes += data.length; + if (stderrBytes > MAX_OUTPUT_BYTES) { + outputLimitExceeded = true; + killProcessTree(processInstance); + safeResolve({ + status: 'Output Limit Exceeded', + stdout: stdout.substring(0, MAX_OUTPUT_BYTES), + error: `Output limit of ${Math.round(MAX_OUTPUT_BYTES / 1024)}KB exceeded in stderr.` + }); + return; + } stderr += data.toString(); }); processInstance.on('close', (code) => { - clearTimeout(timeout); - if (timedOut) return; - + if (timedOut || outputLimitExceeded) return; if (code === 0) { - resolve({ + safeResolve({ status: 'Success', stdout, error: stderr }); } else { - resolve({ + safeResolve({ status: 'Runtime Error', stdout, error: stderr || `Process exited with code ${code}` @@ -96,9 +212,8 @@ const runProcess = (cmd, args, input, timeoutSec, options = {}) => { }); processInstance.on('error', (err) => { - clearTimeout(timeout); - if (timedOut) return; - resolve({ + if (timedOut || outputLimitExceeded) return; + safeResolve({ status: 'Runtime Error', stdout: '', error: err.message @@ -109,188 +224,164 @@ const runProcess = (cmd, args, input, timeoutSec, options = {}) => { /** * Main execution runner for multiple test cases (Compile Once, Run Many) + * Uses isolated ephemeral directory per job with guaranteed finally cleanup. */ export const runLocalCodeMulti = async (code, language, inputs, timeLimit = 2) => { const jobId = Math.random().toString(36).substring(7); - + const jobDir = path.join(TEMP_DIR, `job_${jobId}`); + fs.mkdirSync(jobDir, { recursive: true }); + console.log(`\n--- [NQTCoder Compiler] Job ${jobId} initialized for language: ${language} ---`); console.time(`[Job ${jobId}] Total Time`); const inputsArray = Array.isArray(inputs) ? inputs : [inputs]; const results = []; - if (language === 'python') { - const filename = `script_${jobId}.py`; - const filepath = path.join(TEMP_DIR, filename); - fs.writeFileSync(filepath, code); - - // Determine python command - let pyCmd = 'python'; - if (!isCommandAvailable('python') && isCommandAvailable('python3')) { - pyCmd = 'python3'; - } - - if (!isCommandAvailable(pyCmd)) { - try { fs.unlinkSync(filepath); } catch (e) {} - console.timeEnd(`[Job ${jobId}] Total Time`); - return { - status: 'Compilation Error', - error: '[System Error] Python was not detected on this machine.\n\nTo run Python code, please download and install Python 3.x and ensure it is added to your system Environment Variables.' - }; - } - - console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - for (const input of inputsArray) { - const runRes = await runProcess(pyCmd, [filename], input, timeLimit); - results.push({ - status: runRes.status === 'Success' ? 'Accepted' : runRes.status, - stdout: runRes.stdout, - error: runRes.error - }); - } - console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - - // Clean up - try { - if (fs.existsSync(filepath)) fs.unlinkSync(filepath); - } catch (e) {} - - } else if (language === 'cpp') { - const filename = `code_${jobId}.cpp`; - const filepath = path.join(TEMP_DIR, filename); - const binaryName = `prog_${jobId}${process.platform === 'win32' ? '.exe' : '.out'}`; - const binaryPath = path.join(TEMP_DIR, binaryName); + try { + if (language === 'python') { + const filename = `script_${jobId}.py`; + const filepath = path.join(jobDir, filename); + fs.writeFileSync(filepath, code); + + let pyCmd = 'python'; + if (!isCommandAvailable('python') && isCommandAvailable('python3')) { + pyCmd = 'python3'; + } - fs.writeFileSync(filepath, code); + if (!isCommandAvailable(pyCmd)) { + console.timeEnd(`[Job ${jobId}] Total Time`); + return { + status: 'Compilation Error', + error: '[System Error] Python was not detected on this machine.\n\nTo run Python code, please install Python 3.x and add it to system PATH.' + }; + } - if (!isCommandAvailable('g++')) { - try { fs.unlinkSync(filepath); } catch (e) {} - console.timeEnd(`[Job ${jobId}] Total Time`); - return { - status: 'Compilation Error', - error: '[System Error] GCC C++ Compiler (g++) was not detected on this machine.\n\nTo run C++ code, please download and install MinGW (GCC) and ensure its "bin" path is added to your system Environment Variables.' - }; - } + console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); + for (const input of inputsArray) { + const runRes = await runProcess(pyCmd, [filename], input, timeLimit, { cwd: jobDir }); + results.push({ + status: runRes.status === 'Success' ? 'Accepted' : runRes.status, + stdout: runRes.stdout, + error: runRes.error + }); + } + console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); + + } else if (language === 'cpp') { + const filename = `code_${jobId}.cpp`; + const filepath = path.join(jobDir, filename); + const binaryName = `prog_${jobId}${process.platform === 'win32' ? '.exe' : '.out'}`; + const binaryPath = path.join(jobDir, binaryName); + + fs.writeFileSync(filepath, code); + + if (!isCommandAvailable('g++')) { + console.timeEnd(`[Job ${jobId}] Total Time`); + return { + status: 'Compilation Error', + error: '[System Error] GCC C++ Compiler (g++) was not detected on this machine.\n\nTo run C++ code, please install MinGW/GCC and add it to system PATH.' + }; + } - // Compile once - using -O1 optimization for faster compile times on Render - console.time(`[Job ${jobId}] C++ Compilation`); - try { - execSync(`g++ -O1 "${filepath}" -o "${binaryPath}"`, { stdio: 'pipe' }); - console.timeEnd(`[Job ${jobId}] C++ Compilation`); - } catch (err) { + // Compile once with explicit argument array + console.time(`[Job ${jobId}] C++ Compilation`); + const compRes = await execCompilerAsync('g++', ['-O1', filename, '-o', binaryName], { cwd: jobDir }); console.timeEnd(`[Job ${jobId}] C++ Compilation`); - const errorMsg = err.stderr ? err.stderr.toString() : err.message; - try { - if (fs.existsSync(filepath)) fs.unlinkSync(filepath); - } catch (e) {} - console.timeEnd(`[Job ${jobId}] Total Time`); - return { - status: 'Compilation Error', - error: errorMsg - }; - } - - // Run test cases - console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - for (const input of inputsArray) { - const runRes = await runProcess(binaryPath, [], input, timeLimit); - results.push({ - status: runRes.status === 'Success' ? 'Accepted' : runRes.status, - stdout: runRes.stdout, - error: runRes.error - }); - } - console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - - // Clean up - try { - if (fs.existsSync(filepath)) fs.unlinkSync(filepath); - if (fs.existsSync(binaryPath)) fs.unlinkSync(binaryPath); - } catch (e) {} - - } else if (language === 'java') { - const jobDir = path.join(TEMP_DIR, `java_${jobId}`); - fs.mkdirSync(jobDir, { recursive: true }); - - const filename = 'Main.java'; - const filepath = path.join(jobDir, filename); - fs.writeFileSync(filepath, code); - // Dynamic paths for Java 11/8 bin override from .env - const javaBin = process.env.JAVA_11_BIN || process.env.JAVA_8_BIN || ''; - const javacCmd = javaBin ? path.join(javaBin, 'javac') : 'javac'; - const javaCmd = javaBin ? path.join(javaBin, 'java') : 'java'; + if (!compRes.success) { + console.timeEnd(`[Job ${jobId}] Total Time`); + return { + status: 'Compilation Error', + error: compRes.stderr || 'C++ Compilation failed' + }; + } - // Verify if java is available - if (!isCommandAvailable(javacCmd) || !isCommandAvailable(javaCmd)) { - try { fs.rmSync(jobDir, { recursive: true, force: true }); } catch (e) {} - console.timeEnd(`[Job ${jobId}] Total Time`); - return { - status: 'Compilation Error', - error: '[System Error] Java Compiler (javac/java) was not detected on this machine.\n\nTo run Java 11 code, please download and install JDK 11 (Java Development Kit) and ensure its "bin" path is added to your system Environment Variables.' - }; - } + // Run test cases + console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); + for (const input of inputsArray) { + const runRes = await runProcess(binaryPath, [], input, timeLimit, { cwd: jobDir }); + results.push({ + status: runRes.status === 'Success' ? 'Accepted' : runRes.status, + stdout: runRes.stdout, + error: runRes.error + }); + } + console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); + + } else if (language === 'java') { + const filename = 'Main.java'; + const filepath = path.join(jobDir, filename); + fs.writeFileSync(filepath, code); + + const javaBin = process.env.JAVA_11_BIN || process.env.JAVA_8_BIN || ''; + const javacCmd = javaBin ? path.join(javaBin, 'javac') : 'javac'; + const javaCmd = javaBin ? path.join(javaBin, 'java') : 'java'; + + if (!isCommandAvailable(javacCmd) || !isCommandAvailable(javaCmd)) { + console.timeEnd(`[Job ${jobId}] Total Time`); + return { + status: 'Compilation Error', + error: '[System Error] Java Compiler (javac/java) was not detected on this machine.\n\nTo run Java code, please install JDK 11+ and add it to system PATH.' + }; + } - // Compile targeting Java 11 using --release 11 parameter if supported - console.time(`[Job ${jobId}] Java Compilation`); - let compiled = false; - let compileError = ''; + // Compile with explicit argument array + console.time(`[Job ${jobId}] Java Compilation`); + let compRes = await execCompilerAsync(javacCmd, ['--release', '11', filename], { cwd: jobDir }); + if (!compRes.success) { + // Fallback without --release + compRes = await execCompilerAsync(javacCmd, [filename], { cwd: jobDir }); + } + console.timeEnd(`[Job ${jobId}] Java Compilation`); + + if (!compRes.success) { + console.timeEnd(`[Job ${jobId}] Total Time`); + return { + status: 'Compilation Error', + error: compRes.stderr || 'Java Compilation failed' + }; + } - try { - // We wrap compiler paths in quotes to support Windows paths with spaces - execSync(`"${javacCmd}" --release 11 "${filepath}"`, { stdio: 'pipe' }); - compiled = true; - } catch (err) { - // Fallback compilation without --release flag if using a pure Java 11 JDK (which doesn't support --release or doesn't need it) - try { - execSync(`"${javacCmd}" "${filepath}"`, { stdio: 'pipe' }); - compiled = true; - } catch (innerErr) { - compileError = innerErr.stderr ? innerErr.stderr.toString() : innerErr.message; + // Java execution arguments with configurable heap limits and C1 client compiler acceleration + const javaArgs = [ + `-Xms${JAVA_INITIAL_HEAP}`, + `-Xmx${JAVA_MAX_HEAP}`, + '-XX:+TieredCompilation', + '-XX:TieredStopAtLevel=1', + 'Main' + ]; + + // Run test cases + console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); + for (const input of inputsArray) { + const runRes = await runProcess(javaCmd, javaArgs, input, timeLimit, { cwd: jobDir }); + results.push({ + status: runRes.status === 'Success' ? 'Accepted' : runRes.status, + stdout: runRes.stdout, + error: runRes.error + }); } - } - console.timeEnd(`[Job ${jobId}] Java Compilation`); + console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - if (!compiled) { - try { - fs.rmSync(jobDir, { recursive: true, force: true }); - } catch (e) {} + } else { console.timeEnd(`[Job ${jobId}] Total Time`); return { status: 'Compilation Error', - error: compileError + error: `Unsupported language: ${language}` }; } - // Run test cases - console.time(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - for (const input of inputsArray) { - const runRes = await runProcess(javaCmd, ['Main'], input, timeLimit, { cwd: jobDir }); - results.push({ - status: runRes.status === 'Success' ? 'Accepted' : runRes.status, - stdout: runRes.stdout, - error: runRes.error - }); - } - console.timeEnd(`[Job ${jobId}] Run ${inputsArray.length} test cases`); - - // Clean up directory - try { - fs.rmSync(jobDir, { recursive: true, force: true }); - } catch (e) {} - } else { console.timeEnd(`[Job ${jobId}] Total Time`); return { - status: 'Compilation Error', - error: `Unsupported language: ${language}` + status: 'Success', + results }; + } finally { + // Guaranteed cleanup of the entire ephemeral job directory + try { + fs.rmSync(jobDir, { recursive: true, force: true }); + } catch (e) {} } - - console.timeEnd(`[Job ${jobId}] Total Time`); - return { - status: 'Success', - results - }; }; /** diff --git a/frontend/src/services/executionService.js b/frontend/src/services/executionService.js index 576b2d3..e382360 100644 --- a/frontend/src/services/executionService.js +++ b/frontend/src/services/executionService.js @@ -2,12 +2,45 @@ import api from './api'; const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); -const pollJobStatus = async (jobId, onStatusChange) => { +const ADAPTIVE_POLL_INTERVALS = [0, 150, 250, 400, 600, 1000]; +const MAX_POLL_TIMEOUT_MS = 60000; // 60s hard timeout +const MAX_CONSECUTIVE_ERRORS = 5; + +export const pollJobStatus = async (jobId, onStatusChange, options = {}) => { + const startTime = Date.now(); + let pollCount = 0; + let consecutiveErrors = 0; + while (true) { - let failed = false; - let errorMsg = ''; + // Check if component unmounted or request was cancelled + if (options.signal?.aborted) { + throw new Error('Execution polling cancelled'); + } + + // Check hard timeout + if (Date.now() - startTime > MAX_POLL_TIMEOUT_MS) { + throw new Error(`Execution timed out waiting for job ${jobId}`); + } + + // Determine current polling delay + const delay = pollCount < ADAPTIVE_POLL_INTERVALS.length + ? ADAPTIVE_POLL_INTERVALS[pollCount] + : 1000; + + if (delay > 0) { + await sleep(delay); + } + pollCount++; + + if (options.signal?.aborted) { + throw new Error('Execution polling cancelled'); + } + try { - const response = await api.get(`/api/submissions/status/${jobId}`); + const response = await api.get(`/api/submissions/status/${jobId}`, { + signal: options.signal + }); + consecutiveErrors = 0; const job = response.data; if (job.status === 'completed') { @@ -15,8 +48,7 @@ const pollJobStatus = async (jobId, onStatusChange) => { } if (job.status === 'failed') { - failed = true; - errorMsg = job.error || 'Compilation or execution failed'; + throw new Error(job.error || 'Compilation or execution failed'); } if (onStatusChange) { @@ -27,24 +59,29 @@ const pollJobStatus = async (jobId, onStatusChange) => { }); } } catch (err) { - // If network fails temporarily, we wait and retry instead of crashing - console.warn('Temporary status polling error, retrying...', err); - } - - if (failed) { - throw new Error(errorMsg); + if (options.signal?.aborted) { + throw new Error('Execution polling cancelled'); + } + // If error was thrown from failed status, rethrow + if (err.message && (err.message.includes('Compilation or execution failed') || err.message.startsWith('Time limit'))) { + throw err; + } + consecutiveErrors++; + if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) { + throw new Error('Network communication with compiler service failed. Please try again.'); + } + console.warn(`Temporary status polling error (${consecutiveErrors}/${MAX_CONSECUTIVE_ERRORS}), retrying...`, err); } - await sleep(1000); } }; -export const runCode = async (code, language, questionId, customInput = '', onStatusChange = null) => { +export const runCode = async (code, language, questionId, customInput = '', onStatusChange = null, options = {}) => { const response = await api.post('/api/submissions/run', { code, language, questionId, customInput - }); + }, { signal: options.signal }); const data = response.data; if (data.jobId) { @@ -55,18 +92,18 @@ export const runCode = async (code, language, questionId, customInput = '', onSt estimatedWait: data.estimatedWait || 0 }); } - return await pollJobStatus(data.jobId, onStatusChange); + return await pollJobStatus(data.jobId, onStatusChange, options); } return data; }; -export const submitCode = async (code, language, questionId, onStatusChange = null) => { +export const submitCode = async (code, language, questionId, onStatusChange = null, options = {}) => { const response = await api.post('/api/submissions/submit', { code, language, questionId - }); + }, { signal: options.signal }); const data = response.data; if (data.jobId) { @@ -77,7 +114,7 @@ export const submitCode = async (code, language, questionId, onStatusChange = nu estimatedWait: data.estimatedWait || 0 }); } - return await pollJobStatus(data.jobId, onStatusChange); + return await pollJobStatus(data.jobId, onStatusChange, options); } return data;