Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
fix(studio): prevent OXC validator subprocess hangs (#9759)
Kenshifa66693f989d
diff --git a/studio/backend/core/data_recipe/local_callable_validators.py b/studio/backend/core/data_recipe/local_callable_validators.pyindex 143895d7814..dc0deafdf5c 100644--- a/studio/backend/core/data_recipe/local_callable_validators.py+++ b/studio/backend/core/data_recipe/local_callable_validators.py@@ -32,6 +32,7 @@ _OXC_CODE_SHAPES = {"auto", "module", "snippet"}_OXC_TOOL_DIR = Path(__file__).resolve().parent / "oxc-validator"_OXC_RUNNER_PATH = _OXC_TOOL_DIR / "validate.mjs"+_OXC_TIMEOUT_S = 30from utils.native_path_leases import child_env_without_native_path_secret@@ -231,6 +232,8 @@ def _run_oxc_batch("mode": validation_mode,"code_shape": code_shape,"codes": code_values,+ # The wrapper bounds oxlint with this; a kill here would leave the grandchild.+ "timeout_ms": int(_OXC_TIMEOUT_S * 1000),}# Resolve a usable Node (system or the isolated install, which is not on the# user's PATH); a bare "node" would fail for isolated-Node users.@@ -262,8 +265,12 @@ def _run_oxc_batch(capture_output = True,check = False,env = env,+ timeout = _OXC_TIMEOUT_S,**_windows_hidden_subprocess_kwargs(),)+ except subprocess.TimeoutExpired:+ logger.warning("OXC validation timed out after %ss", _OXC_TIMEOUT_S)+ return _fallback_results(len(code_values), "OXC validation timed out")except (OSError, ValueError) as exc:logger.warning("OXC subprocess launch failed: %s", exc)return _fallback_results(len(code_values), f"OXC launch failed: {exc}")diff --git a/studio/backend/core/data_recipe/oxc-validator/validate.mjs b/studio/backend/core/data_recipe/oxc-validator/validate.mjsindex ad61fb5a9ec..9eb6565d7dd 100644--- a/studio/backend/core/data_recipe/oxc-validator/validate.mjs+++ b/studio/backend/core/data_recipe/oxc-validator/validate.mjs@@ -5,6 +5,7 @@ import { spawnSync } from "node:child_process";import { mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { basename, dirname, join } from "node:path";+import { performance } from "node:perf_hooks";import { fileURLToPath } from "node:url";import { parseSync } from "oxc-parser";@@ -20,6 +21,13 @@ const CODE_SHAPES = new Set(["auto", "module", "snippet"]);const SNIPPET_PREFIX = "(() => {\n";const SNIPPET_SUFFIX = "\n})();\nexport {};\n";const OXLINT_SUPPRESSED_RULES = ["no-unused-vars", "no-new-array"];+// The caller kills only this wrapper, so a wedged oxlint has to die here or it is orphaned.+// It gets the caller's budget minus what this process spent, on the same monotonic basis.+const OXLINT_DEFAULT_BUDGET_MS = 30_000;+// Covers the spawn, which precedes this process, plus its own wind-down.+const OXLINT_BUDGET_MARGIN_MS = 2_000;+// Below this, starting oxlint would only hand the caller's kill an orphan.+const OXLINT_MIN_TIMEOUT_MS = 1_000;const TOOL_DIR = dirname(fileURLToPath(import.meta.url));function mapLang(value) {@@ -47,6 +55,11 @@ function mapMode(value) {return "syntax";}+function mapBudgetMs(value) {+ const parsed = Number(value);+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : OXLINT_DEFAULT_BUDGET_MS;+}+function mapCodeShape(value) {const normalized = String(value || "").trim().toLowerCase();if (CODE_SHAPES.has(normalized)) {@@ -374,7 +387,7 @@ function fallbackLintResults(entries, message) {);}-function runLintBatch(entries) {+function runLintBatch(entries, budgetMs) {if (entries.length === 0) {return new Map();}@@ -395,9 +408,16 @@ function runLintBatch(entries) {"json",tempDir,];+ const timeoutMs = Math.floor(budgetMs - OXLINT_BUDGET_MARGIN_MS - performance.now());+ if (timeoutMs < OXLINT_MIN_TIMEOUT_MS) {+ return fallbackLintResults(entries, "oxlint skipped: validation budget exhausted");+ }const exec = spawnSync(oxlintBin, oxlintArgs, {encoding: "utf8",cwd: TOOL_DIR,+ timeout: timeoutMs,+ // SIGTERM is ignorable, and spawnSync then waits out the child regardless.+ killSignal: "SIGKILL",});if (exec.error) {return fallbackLintResults(@@ -496,7 +516,7 @@ function readStdin() {});}-function runValidation({ codes, lang, mode, codeShape }) {+function runValidation({ codes, lang, mode, codeShape, oxlintBudgetMs }) {if (mode === "syntax") {return codes.map((code, index) =>validateSyntaxOne({ code, lang, index, codeShape }).result,@@ -507,7 +527,7 @@ function runValidation({ codes, lang, mode, codeShape }) {const entries = codes.map((code, index) =>resolveLintEntry({ code, lang, index, codeShape }),);- const lintMap = runLintBatch(entries);+ const lintMap = runLintBatch(entries, oxlintBudgetMs);return entries.map((entry) =>lintMap.get(entry.index) ??@@ -525,7 +545,7 @@ function runValidation({ codes, lang, mode, codeShape }) {const lintTargets = syntaxRuns.filter((run) => run.result.is_valid === true).map((run) => run.lintEntry);- const lintMap = runLintBatch(lintTargets);+ const lintMap = runLintBatch(lintTargets, oxlintBudgetMs);return syntaxRuns.map((run) => {if (run.result.is_valid !== true) {@@ -566,7 +586,8 @@ async function main() {const mode = mapMode(payload?.mode);const codeShape = mapCodeShape(payload?.code_shape);const codes = Array.isArray(payload?.codes) ? payload.codes : [];- const out = runValidation({ codes, lang, mode, codeShape });+ const oxlintBudgetMs = mapBudgetMs(payload?.timeout_ms);+ const out = runValidation({ codes, lang, mode, codeShape, oxlintBudgetMs });process.stdout.write(JSON.stringify(out));}diff --git a/studio/backend/tests/test_local_callable_validators.py b/studio/backend/tests/test_local_callable_validators.pynew file mode 100644index 00000000000..f2661800784--- /dev/null+++ b/studio/backend/tests/test_local_callable_validators.py@@ -0,0 +1,77 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import json+import re+import subprocess+from pathlib import Path++from core.data_recipe import local_callable_validators as validators+++def test_oxc_batch_falls_back_when_node_times_out(monkeypatch, tmp_path):+ runner = tmp_path / "validate.mjs"+ runner.touch()+ calls = []++ def fake_run(*args, **kwargs):+ calls.append((args, kwargs))+ raise subprocess.TimeoutExpired(cmd = args[0], timeout = kwargs["timeout"])++ monkeypatch.setattr(validators, "_OXC_RUNNER_PATH", runner)+ monkeypatch.setattr(validators, "resolve_node_executable", lambda: "node")+ monkeypatch.setattr(validators, "ensure_dir", lambda path: tmp_path)+ monkeypatch.setattr(validators, "oxc_validator_tmp_root", lambda: tmp_path)+ monkeypatch.setattr(validators, "child_env_without_native_path_secret", lambda: {})+ monkeypatch.setattr(validators, "_windows_hidden_subprocess_kwargs", lambda: {})+ monkeypatch.setattr(validators.subprocess, "run", fake_run)++ results = validators._run_oxc_batch(+ node_lang = "js",+ validation_mode = "syntax",+ code_shape = "auto",+ code_values = ["const value = 1;", "const value = 2;"],+ )++ assert len(calls) == 1+ assert calls[0][1]["timeout"] == validators._OXC_TIMEOUT_S+ # The wrapper needs the same budget: oxlint is a grandchild this kill cannot reach.+ assert json.loads(calls[0][1]["input"])["timeout_ms"] == validators._OXC_TIMEOUT_S * 1000+ assert len(results) == 2+ assert all(result["is_valid"] is False for result in results)+ assert all(result["error_count"] == 1 for result in results)+ assert [result["error_message"] for result in results] == [+ "OXC validation timed out",+ "OXC validation timed out",+ ]+++def test_the_wrapper_kills_oxlint_against_the_remaining_caller_budget():+ # Python's timeout SIGKILLs only the wrapper, so oxlint has to die inside validate.mjs,+ # against what is left of the caller's budget. On the source: no JS test runner ships.+ source = validators._OXC_RUNNER_PATH.read_text(encoding = "utf-8")++ assert re.search(+ r"mapBudgetMs\(payload\?\.timeout_ms\)", source+ ), "the oxlint budget must come from the timeout_ms the caller sends"++ # performance.now() is monotonic ms since process start, the same basis as the caller's+ # timeout; Date.now() would drift from it on a wall-clock step.+ remaining = re.search(r"const timeoutMs = ([^;]+);", source)+ assert remaining, "runLintBatch must compute what is left of the caller's budget"+ assert "performance.now()" in remaining.group(1)+ assert "Date.now()" not in remaining.group(1)++ fallback_budget = re.search(r"const OXLINT_DEFAULT_BUDGET_MS = ([\d_]+);", source)+ assert fallback_budget, "validate.mjs must declare OXLINT_DEFAULT_BUDGET_MS"+ assert (+ int(fallback_budget.group(1).replace("_", "")) == validators._OXC_TIMEOUT_S * 1000+ ), "the fallback budget must match the wait this process actually gives the wrapper"++ options = re.search(r"spawnSync\(oxlintBin, oxlintArgs, \{(.*?)\}\)", source, re.S)+ assert options, "oxlint must still be launched through spawnSync(oxlintBin, oxlintArgs, ...)"+ assert "timeout: timeoutMs" in options.group(+ 1+ ), "oxlint's bound must be the computed remainder, not a constant"+ # SIGTERM is ignorable, and spawnSync then waits out the child anyway.+ assert 'killSignal: "SIGKILL"' in options.group(1)