Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(video-lesson): isolate render checks and clean up cancelled processes

Bingxi Zhao (Frank)9237139fb84f
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 369d6bd32..75abd4762 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -351,10 +351,30 @@ jobs:
PYTHONPATH: ${{ github.workspace }}
DEEPTUTOR_TEST_REDIS_URL: redis://127.0.0.1:6379/0
+ video-lesson-sandbox:
+ name: Video lesson isolation
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: "22"
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ - name: Install test dependencies
+ run: pip install -r requirements/server.txt pytest pytest-asyncio
+ - name: Check real rendering, isolation, cancellation and timeout
+ env:
+ DEEPTUTOR_TEST_VIDEO_SANDBOX: "1"
+ DEEPTUTOR_REMOTION_RUNTIME: ${{ runner.temp }}/remotion
+ PYTHONPATH: ${{ github.workspace }}
+ run: pytest -q tests/agents/video_lesson/test_isolation.py tests/services/sandbox/test_process_cancellation.py
+
test-summary:
name: Test Summary
runs-on: ubuntu-24.04
- needs: [chat-engine, lint, web-tests, multi-worker-web, import-check, python-tests]
+ needs: [chat-engine, lint, web-tests, multi-worker-web, import-check, python-tests, video-lesson-sandbox]
if: always()
steps:
@@ -365,6 +385,7 @@ jobs:
echo "| Check | Status |" >> $GITHUB_STEP_SUMMARY
echo "|-------|--------|" >> $GITHUB_STEP_SUMMARY
echo "| TypeScript chat engine | ${{ needs.chat-engine.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
+ echo "| Video lesson isolation | ${{ needs.video-lesson-sandbox.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Lint and format | ${{ needs.lint.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Web node tests | ${{ needs.web-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
echo "| Four-worker browser acceptance | ${{ needs.multi-worker-web.result == 'success' && '✅ Passed' || needs.multi-worker-web.result == 'skipped' && '⏭️ Fixture not configured' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
@@ -372,5 +393,5 @@ jobs:
echo "| Python tests (3.11/3.12/3.13/3.14) | ${{ needs.python-tests.result == 'success' && '✅ Passed' || '❌ Failed' }} |" >> $GITHUB_STEP_SUMMARY
- name: Fail if tests failed
- if: needs.chat-engine.result == 'failure' || needs.lint.result == 'failure' || needs.web-tests.result == 'failure' || needs.multi-worker-web.result == 'failure' || needs.import-check.result == 'failure' || needs.python-tests.result == 'failure'
+ if: needs.video-lesson-sandbox.result != 'success' || needs.chat-engine.result == 'failure' || needs.lint.result == 'failure' || needs.web-tests.result == 'failure' || needs.multi-worker-web.result == 'failure' || needs.import-check.result == 'failure' || needs.python-tests.result == 'failure'
run: exit 1
diff --git a/AGENTS.md b/AGENTS.md
index ced395780..76df4e09b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -77,7 +77,6 @@ Multi-stage pipelines that own the turn:
| `math_animator` | concept_analysis → concept_design → code_generation → code_retry → summary → render_output |
| `mastery_path` | responding (Guided Learning — chat loop + mastery tools, gated per topic type) |
| `immersive_reading` | responding (document- or timestamp-grounded media reading loop) |
-
| `video_lesson` | code_generation → render_check → render_output (Remotion lesson played live in the browser, with TTS narration) |
All capabilities converge on `emit_capability_result()` in
diff --git a/README.md b/README.md
index 0c3e51055..bc3afbb61 100644
--- a/README.md
+++ b/README.md
@@ -388,6 +388,7 @@ pip install -e ".[video-learning]" # compatibility extra; captions ship in the
pip install -e ".[matrix]" # Matrix channel without E2EE/libolm
pip install -e ".[matrix-e2e]" # Matrix E2EE; requires libolm
pip install -e ".[math-animator]" # Manim addon; requires LaTeX/ffmpeg/system libs
+pip install -e ".[edge-tts]" # Optional free speech provider and video-lesson narration
```
</details>
@@ -395,6 +396,8 @@ pip install -e ".[math-animator]" # Manim addon; requires LaTeX/ffmpeg/system
<details>
<summary><b>Frontend dependency tweaks & dev-server troubleshooting</b></summary>
+**Video Lesson:** choose Video Lesson in chat or run `deeptutor run video_lesson "Explain a concept"`. The backend needs Node.js 22+, npm, and access to a running Docker daemon using Linux containers. First use downloads pinned Remotion packages and a Node container image. Frame checks run without network access, host mounts, or host credentials, and stop when the turn is cancelled; there is no unsandboxed fallback. The resulting lesson plays in the browser, with captions when optional narration is unavailable.
+
**Changing frontend dependencies:** run `npm install --legacy-peer-deps` to refresh `web/package-lock.json`, then commit both `web/package.json` and `web/package-lock.json`.
**Stuck dev server:** if `deeptutor start --dev` reports an existing frontend that isn't responding, stop the PID it prints. If no Next.js process is actually running, the lock files are stale — remove them and retry:
@@ -1007,7 +1010,7 @@ The repo ships a root [`SKILL.md`](SKILL.md) — a compact handover doc for the
| `deeptutor stop [--home PATH]` | Stop a launcher started with `--detach` |
| `deeptutor serve [--port PORT]` | Start only the FastAPI backend |
| `deeptutor workspace show/set/reset` | Inspect, select, or restore the per-user Content Workspace |
-| `deeptutor run <capability> <message>` | Run a single capability turn (`chat`, `ask_questions`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `mastery_path`, `immersive_reading`, `audio_overview`); add `--format json` for NDJSON output |
+| `deeptutor run <capability> <message>` | Run a single capability turn (`chat`, `ask_questions`, `deep_solve`, `deep_question`, `deep_research`, `visualize`, `math_animator`, `video_lesson`, `mastery_path`, `immersive_reading`, `audio_overview`); add `--format json` for NDJSON output |
| `deeptutor chat` | Interactive REPL with capability, tool, KB, notebook, and history controls |
| `deeptutor partner list/create/start/stop` | Manage IM-connected partners |
| `deeptutor kb list/info/create/connect-kiwix/add/search/eval/eval-diff/set-default/delete/list-sources/sync` | Manage knowledge bases, connect Kiwix archives, score and compare retrieval runs, and synchronize registered GitHub/web sources (with source add/remove commands) |
diff --git a/deeptutor/agents/video_lesson/capability.py b/deeptutor/agents/video_lesson/capability.py
index e0e3100b8..dacc56e05 100644
--- a/deeptutor/agents/video_lesson/capability.py
+++ b/deeptutor/agents/video_lesson/capability.py
@@ -136,6 +136,7 @@ class VideoLessonCapability(TurnCapability):
finally:
if not runtime_ready.done():
runtime_ready.cancel()
+ await asyncio.gather(runtime_ready, return_exceptions=True)
if draft is None or build is None or not build.ok:
last = attempts[-1]["errors"] if attempts else []
diff --git a/deeptutor/agents/video_lesson/remotion/build.mjs b/deeptutor/agents/video_lesson/remotion/build.mjs
index 1c2c13f0b..0a8ef15b2 100644
--- a/deeptutor/agents/video_lesson/remotion/build.mjs
+++ b/deeptutor/agents/video_lesson/remotion/build.mjs
@@ -1,5 +1,5 @@
// Compile a model-written Remotion lesson (Lesson.tsx + the shipped kit) into a browser player
-// script. Before bundling, sample frames are rendered in a permission-restricted Node process so
+// script. Before bundling, sample frames are rendered in a network-isolated Docker container so
// runtime errors come back to the model instead of reaching the learner.
//
// node build.mjs <Lesson.tsx> <out.js>
@@ -8,7 +8,7 @@
// esbuild (see package.json next to this file). Prints one JSON line: {ok, stage, errors, frames}.
import {createRequire} from "node:module";
-import {mkdtempSync, writeFileSync, rmSync} from "node:fs";
+import {mkdtempSync, writeFileSync, readFileSync, rmSync} from "node:fs";
import {tmpdir} from "node:os";
import {dirname, join, resolve} from "node:path";
import {spawnSync} from "node:child_process";
@@ -95,10 +95,23 @@ try {
rmSync(tmp, {recursive: true, force: true});
report({ok: false, stage: "compile", errors: fmtErrors(e)});
}
-// Model code runs here: no file writes, child processes, workers or native addons.
-const run = spawnSync(process.execPath, ["--permission", `--allow-fs-read=${tmp}`, join(tmp, "check.mjs")],
- {encoding: "utf8", timeout: 180000});
+// No generated code executes in this process. The Python host owns a hardened
+// container and removes it on success, timeout, failure, or cancellation.
+const docker = process.env.DEEPTUTOR_RENDER_DOCKER;
+const container = process.env.DEEPTUTOR_RENDER_CONTAINER;
+if (!docker || !/^dt-lesson-[a-f0-9]{32}$/.test(container || "")) {
+ rmSync(tmp, {recursive: true, force: true});
+ report({ok: false, stage: "sandbox", errors: ["An isolated render container is required"]});
+}
+const run = spawnSync(docker, ["start", "--attach", "--interactive", container], {
+ input: readFileSync(join(tmp, "check.mjs")), encoding: "utf8",
+ timeout: Number(process.env.DEEPTUTOR_RENDER_TIMEOUT_MS) || 180000,
+ maxBuffer: 1024 * 1024,
+});
rmSync(tmp, {recursive: true, force: true});
+if (run.error || run.signal || run.status !== 0) {
+ report({ok: false, stage: "render", errors: [(run.error?.message || run.stderr || "Render process failed").slice(-1500)]});
+}
let checked;
try { checked = JSON.parse(run.stdout.trim().split("\n").pop()); }
catch { report({ok: false, stage: "render", errors: [(run.stderr || run.stdout || "no output").slice(-1500)]}); }
diff --git a/deeptutor/agents/video_lesson/runtime.py b/deeptutor/agents/video_lesson/runtime.py
index b3b6e844e..ecf6293e8 100644
--- a/deeptutor/agents/video_lesson/runtime.py
+++ b/deeptutor/agents/video_lesson/runtime.py
@@ -2,7 +2,7 @@
The model writes ``Lesson.tsx`` against the shipped kit (``remotion/kit.tsx``).
``build.mjs`` compiles it with esbuild, renders sample frames in a
-permission-restricted Node process, and bundles it with ``@remotion/player``.
+network-isolated, read-only Docker container, and bundles it with ``@remotion/player``.
The page this module writes is self-contained: the learner's browser plays the
composition live, so no video file is ever encoded on the server.
"""
@@ -16,13 +16,21 @@ import json
import os
from pathlib import Path
import shutil
+import uuid
from deeptutor.services.path_service import get_path_service
+from deeptutor.services.sandbox.backends import RestrictedSubprocessBackend
+from deeptutor.services.sandbox.spec import ExecRequest, ExecResult, ResourceLimits
ASSETS_DIR = Path(__file__).resolve().parent / "remotion"
KIT_FILES = ("kit.tsx", "china_outline.json", "voice.ts")
BUILD_TIMEOUT_S = 600
INSTALL_TIMEOUT_S = 900
+# Official multi-platform Node 22 image, pinned so render checks use one runtime.
+RENDER_IMAGE = (
+ "node:22-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d"
+)
+RENDER_TIMEOUT_S = 180
_install_lock = asyncio.Lock()
@@ -67,40 +75,78 @@ def _installed(root: Path) -> bool:
return True
+async def _run_tool(
+ argv: list[str], *, timeout: int, cwd: Path | None = None, env: dict[str, str] | None = None
+) -> ExecResult:
+ """Run trusted tooling with bounded output and cancellation of its process tree.
+
+ Model code never runs through this host subprocess backend. Only the
+ compiler and Docker client do; the frame-check bundle goes to the container.
+ """
+ docker_env = {
+ key: os.environ[key]
+ for key in ("DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "XDG_RUNTIME_DIR")
+ if key in os.environ
+ }
+ return await RestrictedSubprocessBackend(inherit_virtualenv=False).exec(
+ ExecRequest.of_argv(
+ argv,
+ workdir=str(cwd) if cwd else "",
+ env={**docker_env, **(env or {})},
+ limits=ResourceLimits(timeout_s=timeout, max_output_chars=64_000),
+ )
+ )
+
+
+def _docker() -> str:
+ docker = shutil.which("docker")
+ if not docker:
+ raise VideoLessonRuntimeError(
+ "Video lessons need Docker with a running Linux-container daemon for isolated render checks."
+ )
+ return docker
+
+
+def _require_success(result: ExecResult, action: str) -> None:
+ if not result.ok or result.exit_code != 0:
+ detail = result.error or result.stderr or result.stdout
+ if result.timed_out:
+ detail = "timed out"
+ raise VideoLessonRuntimeError(f"{action} failed: {detail[-1500:]}")
+
+
async def ensure_runtime() -> Path:
- """Install the pinned npm packages on first use; later calls return immediately."""
+ """Prepare pinned tooling and the isolated renderer; never fall back to host execution."""
_node()
+ docker = _docker()
root = runtime_dir()
- if _installed(root):
- return root
async with _install_lock:
- if _installed(root):
- return root
- npm = shutil.which("npm")
- if not npm:
- raise VideoLessonRuntimeError(
- "Video lessons need npm to install Remotion on first use."
+ if not _installed(root):
+ npm = shutil.which("npm")
+ if not npm:
+ raise VideoLessonRuntimeError("Video lessons need npm to install Remotion.")
+ root.mkdir(parents=True, exist_ok=True)
+ shutil.copy(ASSETS_DIR / "package.json", root / "package.json")
+ result = await _run_tool(
+ [npm, "install", "--no-audit", "--no-fund", "--omit=dev"],
+ timeout=INSTALL_TIMEOUT_S,
+ cwd=root,
+ )
+ _require_success(result, "Installing Remotion")
+ if not _installed(root):
+ raise VideoLessonRuntimeError(
+ "Installed Remotion packages do not match the manifest."
+ )
+ result = await _run_tool([docker, "info", "--format", "{{.OSType}}"], timeout=15)
+ _require_success(result, "Connecting to the Docker sandbox")
+ if result.stdout.strip() != "linux":
+ raise VideoLessonRuntimeError("Video lesson render checks need Linux containers.")
+ image = await _run_tool([docker, "image", "inspect", RENDER_IMAGE], timeout=15)
+ if not image.ok or image.exit_code != 0:
+ _require_success(
+ await _run_tool([docker, "pull", RENDER_IMAGE], timeout=INSTALL_TIMEOUT_S),
+ "Preparing the isolated Node renderer",
)
- root.mkdir(parents=True, exist_ok=True)
- shutil.copy(ASSETS_DIR / "package.json", root / "package.json")
- proc = await asyncio.create_subprocess_exec(
- npm,
- "install",
- "--no-audit",
- "--no-fund",
- "--omit=dev",
- cwd=root,
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.STDOUT,
- )
- try:
- out, _ = await asyncio.wait_for(proc.communicate(), timeout=INSTALL_TIMEOUT_S)
- except asyncio.TimeoutError as exc:
- proc.kill()
- raise VideoLessonRuntimeError("Installing Remotion timed out.") from exc
- if proc.returncode != 0 or not _installed(root):
- tail = out.decode("utf-8", errors="replace")[-1500:]
- raise VideoLessonRuntimeError(f"Installing Remotion failed:\n{tail}")
return root
@@ -119,31 +165,76 @@ def prepare_workdir(work_dir: Path, code: str, voice: str | None = None) -> Path
return lesson
+def _container_argv(docker: str, name: str) -> list[str]:
+ # No bind mounts, host environment, published ports, or Docker socket.
+ # The self-contained check bundle is streamed over stdin by build.mjs.
+ return [
+ docker,
+ "create",
+ "--name",
+ name,
+ "--interactive",
+ "--init",
+ "--network",
+ "none",
+ "--read-only",
+ "--cap-drop",
+ "ALL",
+ "--security-opt",
+ "no-new-privileges",
+ "--user",
+ "65534:65534",
+ "--pids-limit",
+ "64",
+ "--memory",
+ "512m",
+ "--memory-swap",
+ "512m",
+ "--cpus",
+ "1",
+ RENDER_IMAGE,
+ "node",
+ "--input-type=module",
+ ]
+
+
async def build_lesson(lesson: Path, bundle: Path) -> BuildResult:
- """Compile, frame-check and bundle one lesson. Failures come back as data for the model."""
+ """Compile on the host; execute generated code only in a disposable container."""
root = await ensure_runtime()
- proc = await asyncio.create_subprocess_exec(
- _node(),
- str(ASSETS_DIR / "build.mjs"),
- str(lesson),
- str(bundle),
- env={**os.environ, "DEEPTUTOR_REMOTION_RUNTIME": str(root)},
- stdout=asyncio.subprocess.PIPE,
- stderr=asyncio.subprocess.PIPE,
- )
+ docker = _docker()
+ name = "dt-lesson-" + uuid.uuid4().hex
try:
- out, err = await asyncio.wait_for(proc.communicate(), timeout=BUILD_TIMEOUT_S)
- except asyncio.TimeoutError:
- proc.kill()
+ _require_success(
+ await _run_tool(_container_argv(docker, name), timeout=30),
+ "Creating the isolated renderer",
+ )
+ result = await _run_tool(
+ [_node(), str(ASSETS_DIR / "build.mjs"), str(lesson), str(bundle)],
+ timeout=BUILD_TIMEOUT_S,
+ env={
+ "DEEPTUTOR_REMOTION_RUNTIME": str(root),
+ "DEEPTUTOR_RENDER_DOCKER": docker,
+ "DEEPTUTOR_RENDER_CONTAINER": name,
+ "DEEPTUTOR_RENDER_TIMEOUT_MS": str(RENDER_TIMEOUT_S * 1000),
+ },
+ )
+ finally:
+ # Killing the Docker client does not stop a daemon-owned container.
+ # Always remove this turn's container, including cancelled create/start calls.
+ cleanup = await _run_tool([docker, "rm", "--force", name], timeout=15)
+ if not cleanup.ok or (
+ cleanup.exit_code and "no such container" not in cleanup.stderr.lower()
+ ):
+ _require_success(cleanup, "Removing the isolated renderer")
+ if result.timed_out:
return BuildResult(False, "timeout", [f"build did not finish within {BUILD_TIMEOUT_S}s"])
- lines = out.decode("utf-8", errors="replace").strip().splitlines()
+ lines = result.stdout.strip().splitlines()
try:
data = json.loads(lines[-1])
except (IndexError, json.JSONDecodeError):
- detail = (err.decode("utf-8", errors="replace") or "no output")[-1500:]
- return BuildResult(False, "build", [detail])
+ return BuildResult(False, "build", [(result.error or result.stderr or "no output")[-1500:]])
return BuildResult(
- ok=bool(data.get("ok")),
+ ok=bool(data.get("ok")) and result.ok and result.exit_code == 0,
stage=str(data.get("stage", "")),
errors=[str(e) for e in data.get("errors") or []],
frames=list(data.get("frames") or []),
diff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.py
index e628aefe0..9fb4959af 100644
--- a/deeptutor/app/facade.py
+++ b/deeptutor/app/facade.py
@@ -128,14 +128,14 @@ class DeepTutorApp:
),
)
if resolved == "video_lesson":
- available = shutil.which("node") is not None and shutil.which("npm") is not None
+ available = all(shutil.which(tool) is not None for tool in ("node", "npm", "docker"))
return CapabilityAvailability(
name=resolved,
available=available,
install_hint=(
""
if available
- else "Install Node.js 22+ (with npm); Remotion is installed on first use."
+ else "Install Node.js 22+ (with npm) and Docker with a running Linux-container daemon. Remotion and the isolated renderer are prepared on first use."
),
)
return CapabilityAvailability(name=resolved, available=True)
diff --git a/deeptutor/services/sandbox/backends.py b/deeptutor/services/sandbox/backends.py
index 40b93ddb2..0a09927ac 100644
--- a/deeptutor/services/sandbox/backends.py
+++ b/deeptutor/services/sandbox/backends.py
@@ -444,9 +444,8 @@ async def _capture_limited(
async def _terminate_process_tree(process: asyncio.subprocess.Process) -> None:
- if process.returncode is not None:
- return
-
+ # A leader can exit while its descendants keep stdout/stderr open.
+ # Its POSIX group must still be terminated on timeout or cancellation.
if sys.platform != "win32":
killed_group = False
try:
@@ -454,10 +453,13 @@ async def _terminate_process_tree(process: asyncio.subprocess.Process) -> None:
killed_group = True
except (ProcessLookupError, PermissionError):
pass
- if not killed_group:
+ if not killed_group and process.returncode is None:
process.kill()
return
+ if process.returncode is not None:
+ return
+
# ``Process.kill`` only terminates powershell.exe; taskkill's /T flag also
# tears down python/compiler children started by it.
try:
@@ -491,13 +493,15 @@ async def _communicate(
asyncio.gather(wait_task, stdout_task, stderr_task),
timeout=timeout_s,
)
- except asyncio.TimeoutError:
+ except (asyncio.TimeoutError, asyncio.CancelledError) as exc:
for task in (wait_task, stdout_task, stderr_task):
task.cancel()
await asyncio.gather(wait_task, stdout_task, stderr_task, return_exceptions=True)
await _terminate_process_tree(process)
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(process.wait(), timeout=5.0)
+ if isinstance(exc, asyncio.CancelledError):
+ raise
return ExecResult(timed_out=True, exit_code=124)
return ExecResult(
stdout=_decode_process_output(stdout),
diff --git a/tests/agents/video_lesson/test_isolation.py b/tests/agents/video_lesson/test_isolation.py
new file mode 100644
index 000000000..ea7fd54a8
--- /dev/null
+++ b/tests/agents/video_lesson/test_isolation.py
@@ -0,0 +1,147 @@
+"""Real container checks; CI enables these with DEEPTUTOR_TEST_VIDEO_SANDBOX=1."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+
+import pytest
+
+from deeptutor.agents.video_lesson import runtime
+
+pytestmark = [
+ pytest.mark.asyncio,
+ pytest.mark.skipif(
+ os.environ.get("DEEPTUTOR_TEST_VIDEO_SANDBOX") != "1",
+ reason="requires Docker and the Remotion npm runtime",
+ ),
+]
+
+CONFIG = "export const LESSON = {durationInFrames:60, fps:30, width:1920, height:1080};\n"
+VALID = CONFIG + 'export const Lesson = () => <div>{"A safe lesson. ".repeat(50)}</div>;'
+
+
+async def test_real_render_and_runtime_error(tmp_path: Path) -> None:
+ lesson = runtime.prepare_workdir(tmp_path, VALID)
+ result = await runtime.build_lesson(lesson, tmp_path / "player.js")
+ assert result.ok and len(result.frames) == 25
+ assert (tmp_path / "player.js").stat().st_size > 0
+ lesson.write_text(CONFIG + 'export const Lesson = () => {throw new Error("fixture failure")};')
+ result = await runtime.build_lesson(lesson, tmp_path / "player.js")
+ assert not result.ok and any("fixture failure" in error for error in result.errors)
+
+
+async def test_model_cannot_read_host_secrets_files_or_connect_to_network(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ marker = tmp_path / "host-secret.txt"
+ marker.write_text("dummy-host-secret")
+ monkeypatch.setenv("DT_REVIEW_SENTINEL", "dummy-environment-secret")
+ code = """import React from "react";
+let probe = Promise.resolve();
+if (typeof process !== "undefined") {
+ if (process.env.DT_REVIEW_SENTINEL) throw new Error("host environment leaked");
+ const fs = process.getBuiltinModule("fs");
+ if (fs.existsSync(HOST_FILE)) throw new Error("host file exposed");
+ let writable = false;
+ try { fs.writeFileSync("/tmp/should-not-exist", "x"); writable = true; } catch {}
+ if (writable) throw new Error("container filesystem is writable");
+ probe = fetch("http://1.1.1.1", {signal: AbortSignal.timeout(500)}).then(
+ () => {throw new Error("outbound network allowed");}, () => undefined);
+}
+export const Lesson = () => {
+ React.use(probe);
+ return <div>{"Isolated lesson. ".repeat(50)}</div>;
+};
+""".replace("HOST_FILE", json.dumps(str(marker)))
+ lesson = runtime.prepare_workdir(tmp_path, CONFIG + code)
+ result = await runtime.build_lesson(lesson, tmp_path / "player.js")
+ assert result.ok, result.errors
+ assert marker.read_text() == "dummy-host-secret"
+
+
+async def test_cancelled_render_removes_running_container(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ await runtime.ensure_runtime()
+ original = runtime._run_tool
+ created = asyncio.Event()
+ names: list[str] = []
+
+ async def observe(argv, **kwargs):
+ result = await original(argv, **kwargs)
+ if "create" in argv:
+ names.append(argv[argv.index("--name") + 1])
+ created.set()
+ return result
+
+ monkeypatch.setattr(runtime, "_run_tool", observe)
+ lesson = runtime.prepare_workdir(
+ tmp_path, CONFIG + "export const Lesson = () => { while (true) {} };"
+ )
+ task = asyncio.create_task(runtime.build_lesson(lesson, tmp_path / "player.js"))
+ try:
+ await asyncio.wait_for(created.wait(), 30)
+ for _ in range(100):
+ state = await original(
+ [runtime._docker(), "inspect", "--format", "{{.State.Running}}", names[0]],
+ timeout=5,
+ )
+ if state.stdout.strip() == "true":
+ break
+ await asyncio.sleep(0.05)
+ else:
+ pytest.fail("renderer never started")
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, 20)
+ state = await original([runtime._docker(), "inspect", names[0]], timeout=5)
+ assert state.exit_code != 0 and "no such" in state.stderr.lower()
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ for name in names:
+ await original([runtime._docker(), "rm", "--force", name], timeout=10)
+
+
+async def test_timed_out_render_is_rejected_and_removed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(runtime, "RENDER_TIMEOUT_S", 1)
+ original = runtime._run_tool
+ names: list[str] = []
+
+ async def observe(argv, **kwargs):
+ if "create" in argv:
+ names.append(argv[argv.index("--name") + 1])
+ return await original(argv, **kwargs)
+
+ monkeypatch.setattr(runtime, "_run_tool", observe)
+ lesson = runtime.prepare_workdir(
+ tmp_path, CONFIG + "export const Lesson = () => { while (true) {} };"
+ )
+ result = await runtime.build_lesson(lesson, tmp_path / "player.js")
+ assert not result.ok and result.stage == "render"
+ state = await original([runtime._docker(), "inspect", names[0]], timeout=5)
+ assert state.exit_code != 0 and "no such" in state.stderr.lower()
+
+
+async def test_build_script_refuses_to_execute_without_container(tmp_path: Path) -> None:
+ root = await runtime.ensure_runtime()
+ lesson = runtime.prepare_workdir(tmp_path, VALID)
+ result = await runtime._run_tool(
+ [
+ runtime._node(),
+ str(runtime.ASSETS_DIR / "build.mjs"),
+ str(lesson),
+ str(tmp_path / "player.js"),
+ ],
+ timeout=30,
+ env={"DEEPTUTOR_REMOTION_RUNTIME": str(root)},
+ )
+ assert result.exit_code != 0
+ assert json.loads(result.stdout.strip().splitlines()[-1])["stage"] == "sandbox"
+ assert not (tmp_path / "player.js").exists()
diff --git a/tests/agents/video_lesson/test_runtime.py b/tests/agents/video_lesson/test_runtime.py
index 0403592e2..f87c79779 100644
--- a/tests/agents/video_lesson/test_runtime.py
+++ b/tests/agents/video_lesson/test_runtime.py
@@ -37,3 +37,12 @@ def test_write_page_inlines_the_bundle_safely(tmp_path: Path) -> None:
def test_prepare_workdir_writes_the_voice_module(tmp_path: Path) -> None:
prepare_workdir(tmp_path / "source", "", voice="export const VOICE = {s1: {}};")
assert "s1" in (tmp_path / "source" / "voice.ts").read_text(encoding="utf-8")
+
+
+def test_video_lesson_requires_a_docker_runtime(monkeypatch) -> None:
+ import pytest
+ from deeptutor.agents.video_lesson import runtime
+
+ monkeypatch.setattr(runtime.shutil, "which", lambda _name: None)
+ with pytest.raises(runtime.VideoLessonRuntimeError, match="Docker"):
+ runtime._docker()
diff --git a/tests/services/sandbox/test_process_cancellation.py b/tests/services/sandbox/test_process_cancellation.py
new file mode 100644
index 000000000..fb8e77451
--- /dev/null
+++ b/tests/services/sandbox/test_process_cancellation.py
@@ -0,0 +1,58 @@
+"""Cancellation must stop a tool process and the descendants holding its pipes."""
+
+from __future__ import annotations
+
+import asyncio
+import os
+from pathlib import Path
+import signal
+import sys
+
+import pytest
+
+from deeptutor.services.sandbox.backends import RestrictedSubprocessBackend
+from deeptutor.services.sandbox.spec import ExecRequest
+
+
[email protected](sys.platform == "win32", reason="POSIX process-group regression")
[email protected]("leader_exits", [False, True])
+async def test_cancel_kills_tool_and_child(tmp_path: Path, leader_exits: bool) -> None:
+ heartbeat = tmp_path / "heartbeat"
+ pidfile = tmp_path / "child.pid"
+ child = (
+ "import time; from pathlib import Path; "
+ f"p=Path({str(heartbeat)!r}); "
+ "exec('while True:\\n p.write_text(str(time.monotonic_ns()))\\n time.sleep(.02)')"
+ )
+ parent = (
+ "import subprocess,sys,time; from pathlib import Path; "
+ f"p=subprocess.Popen([sys.executable,'-c',{child!r}]); "
+ f"Path({str(pidfile)!r}).write_text(str(p.pid)); time.sleep(60)"
+ )
+ if leader_exits:
+ parent = parent.replace("time.sleep(60)", "sys.exit(0)")
+ task = asyncio.create_task(
+ RestrictedSubprocessBackend().exec(ExecRequest.of_argv([sys.executable, "-c", parent]))
+ )
+ try:
+ for _ in range(100):
+ if heartbeat.exists():
+ break
+ await asyncio.sleep(0.02)
+ assert heartbeat.exists(), "child did not start"
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, 5)
+ stopped = heartbeat.read_text()
+ await asyncio.sleep(0.15)
+ assert heartbeat.read_text() == stopped, "child survived tool cancellation"
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ if pidfile.exists():
+ try:
+ os.kill(int(pidfile.read_text()), signal.SIGKILL)
+ except ProcessLookupError:
+ pass