"""Real subprocess regression checks without MinerU/model downloads.""" from pathlib import Path import subprocess import sys import time from types import SimpleNamespace import psutil import pytest from deeptutor.services.parsing import progress from deeptutor.services.parsing.engines.mineru import local def _await_settled(pid: int, timeout: float = 0.25) -> bool: """Whether an owned descendant is gone, or killed and awaiting reaping. The tree is SIGKILLed, so the only thing left to observe is reaping, and that is done by init for an orphaned grandchild. An immediate ``pid_exists`` check races that window: it failed 2 of 8 whole-file runs on 40c051b7 and 5 of 8 on f7aed0744. A zombie pid is a settled tree; a running pid is a leak. The timeout only covers signal delivery, never reaping, so it must stay small: the fixture child lives 2s, and a window of 1s would let a missed kill die of old age and pass while ``elapsed`` approaches its 1.5s bound. """ deadline = time.monotonic() + timeout while True: try: status = psutil.Process(pid).status() except psutil.NoSuchProcess: return True except psutil.AccessDenied: # A pid owned by another user cannot be inspected. That is not a # leak claim this helper can make, so do not turn it into an error # mid-test; report "not settled yet" and let the deadline decide. if time.monotonic() >= deadline: return False time.sleep(0.02) continue if status in {psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD}: return True if time.monotonic() >= deadline: return False time.sleep(0.02) def _await_marker(pattern: str, root: Path, *, timeout: float = 30.0, what: str = "marker"): """Wait for a fixture marker and return its path, or fail with a real reason. Every test below asks the spawned CLI to write a small file (``child.pid``, ``deadline.txt``, ``lesson.md``) and then reads it. Unpacking ``glob()`` directly conflated two very different situations: the product never started, and the runner was merely slow. That ambiguity is what made the CI failures unreadable — ``ValueError: not enough values to unpack (expected 1, got 0)`` says nothing about which one happened (#2435 discussion). A loaded ``windows-latest`` runner can take seconds to get a fresh interpreter to its first write, so the wait is generous and the assertion errs toward "environment was slow", not "product is broken". """ deadline = time.monotonic() + timeout while True: matches = sorted(root.glob(pattern)) if matches: return matches[0] if time.monotonic() >= deadline: raise AssertionError( f"{what} never appeared ({pattern} under {root}); " "the fixture CLI did not reach its first write " f"within {timeout:g}s — treat this as a slow or wedged runner, " "not as a cleanup leak" ) time.sleep(0.02) def run_fixture(tmp_path, monkeypatch, code, run=None, idle=0.05, timeout=30, extra_env=None): source = tmp_path / "lesson.pdf" source.write_bytes(b"controlled fixture") popen = subprocess.Popen def spawn(cmd, **kwargs): if cmd[0] != sys.executable: return popen(cmd, **kwargs) output = cmd[cmd.index("-o") + 1] return popen([sys.executable, "-c", code, output], **kwargs) monkeypatch.setattr(local.subprocess, "Popen", spawn) monkeypatch.setattr(progress, "current_run", lambda: run or SimpleNamespace(check=lambda: None)) monkeypatch.setattr(local, "_LOCAL_PARSE_IDLE_TIMEOUT_SECONDS", idle) monkeypatch.setattr(local, "_LOCAL_PARSE_TIMEOUT_SECONDS", timeout) monkeypatch.delenv("MINERU_TASK_RESULT_TIMEOUT_SECONDS", raising=False) started = time.monotonic() result = local.parse_document_with_mineru_result( source, tmp_path / "out", cli_command=sys.executable, extra_env=extra_env, ) return result, time.monotonic() - started def test_quiet_inference_is_not_killed_for_log_silence(tmp_path, monkeypatch): """A child that writes nothing for a while is not a stall. The assertion is about the *idle* threshold (0.05s here), not about wall clock: the child sleeps 0.7s and then publishes. Bound generously, because a contended runner can take several seconds to start an interpreter — the old ``elapsed < 2`` left roughly 2x headroom over the local 0.9s and failed on CI. """ code = ( "import sys,time,pathlib; time.sleep(0.7); " "p=pathlib.Path(sys.argv[1]); (p/'lesson.md').write_text('# parsed',encoding='utf-8')" ) result, elapsed = run_fixture(tmp_path, monkeypatch, code) assert result.ok, result assert elapsed < 15, f"parse took {elapsed:.1f}s; expected near-immediate success" def test_explicit_client_timeout_also_bounds_parent_runtime(tmp_path, monkeypatch): code = ( "import os,sys,time,pathlib; p=pathlib.Path(sys.argv[1]); " "record=p/'deadline.tmp'; " "record.write_text(os.environ['MINERU_TASK_RESULT_TIMEOUT_SECONDS']); " "record.rename(p/'deadline.txt'); time.sleep(60)" ) def wait_for_deadline_record() -> Path: return _await_marker( ".mineru-attempt-*/output/deadline.txt", tmp_path / "out", what="CLI deadline record", ) # Let the fixture record the configuration before the parent can time out. result, elapsed = run_fixture( tmp_path, monkeypatch, code, run=SimpleNamespace(check=wait_for_deadline_record), extra_env={"MINERU_TASK_RESULT_TIMEOUT_SECONDS": "1.2"}, ) assert result.reason is local.LocalParseReason.TIMEOUT assert "1.2 seconds" in result.detail assert elapsed < 20, f"deadline enforcement took {elapsed:.1f}s" assert wait_for_deadline_record().read_text() == "1.2" def test_parent_exit_does_not_wait_for_descendant_stdout(tmp_path, monkeypatch): # The grandchild outlives the bound below on purpose: if it died sooner, a # reader that waited for inherited stdout would finish inside the allowed # elapsed time and the test would pass while the regression was present # (review on #3089). The bound must therefore stay well under this sleep. grandchild_sleep = 60 allowed_elapsed = 20 code = ( "import sys,subprocess,pathlib; p=pathlib.Path(sys.argv[1]); " f"c=subprocess.Popen([sys.executable,'-c','import time; time.sleep({grandchild_sleep})']," "stdout=sys.stdout,stderr=sys.stderr); " "(p/'child.pid').write_text(str(c.pid)); " "(p/'lesson.md').write_text('# parsed',encoding='utf-8')" ) # Outlives the whole test on a slow runner: a short-lived decoy could die of # old age while this case is still starting interpreters, and the assertion # below would then report "cleanup touched an unrelated process" for a # process that simply finished on its own. unrelated = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"]) try: result, elapsed = run_fixture(tmp_path, monkeypatch, code, idle=10) assert result.ok, result # The point is that the parent's own exit is not gated on the grandchild # holding the inherited stdout. Since the grandchild lives # ``grandchild_sleep`` seconds, any run that finished in less than that # could not have waited for it — so the bound is derived from the # fixture rather than from a guessed absolute, which is what made the # old ``elapsed < 1.5`` fragile on a slow runner. assert elapsed < allowed_elapsed, ( f"parse took {elapsed:.1f}s; the parent exit was probably waiting " f"for the descendant's inherited stdout (the descendant lives " f"{grandchild_sleep}s)" ) child_file = _await_marker("lesson/child.pid", tmp_path / "out", what="owned child pid") child = int(child_file.read_text()) assert _await_settled(child), "Owned child survived cleanup" assert unrelated.poll() is None, "Cleanup touched an unrelated process" finally: unrelated.terminate() unrelated.wait(timeout=5) @pytest.mark.parametrize("cancelled", [False, True]) def test_deadline_and_cancellation_settle_the_owned_tree(tmp_path, monkeypatch, cancelled): """Whichever interrupts the parse, the owned tree is settled afterwards. This is the test that flakes on CI, and the cause was a timing premise, not a slow machine. The fixture's child has to start an interpreter, spawn a grandchild and write ``child.pid`` before ``check()`` has anything to report, all inside the 0.8s deadline. Measure the budget: ``local.py`` starts its clock *before* ``cli_process`` builds the Job Object, suspends a new process, resumes it and queries its threads, so on a contended runner the child may not exist yet when the deadline expires. The cancellation case then failed with ``TIMEOUT is not CANCELLED``. The production ordering is right and is left alone: ``run.check()`` runs *before* the deadline comparison, so an available cancellation always wins. What the test must do is make that cancellation available in time, and stop asserting how fast the machine started an interpreter. """ # The grandchild must exist *before* either interruption fires, otherwise # the test reads a marker after the fixture was already killed and the race # just moves rather than being removed (review on #3089). # # Both branches therefore synchronise through ``check()``: it waits for # ``child.pid`` and only then either raises (cancellation) or returns and # lets the deadline comparison run. Waiting there does not eat the deadline # in a way that changes the outcome — ``local.py`` measures the deadline # from its own clock, and the point of the test is that the deadline is # enforced *after* the tree exists, not that the runner was fast. code = ( "import sys,subprocess,pathlib,time; p=pathlib.Path(sys.argv[1]); " "c=subprocess.Popen([sys.executable,'-c','import time; time.sleep(10)']); " "(p/'child.pid').write_text(str(c.pid)); time.sleep(10)" ) def check(): _await_marker( ".mineru-attempt-*/output/child.pid", tmp_path / "out", timeout=30, what="owned child pid before the interruption", ) if cancelled: raise progress.IndexingCancelled("controlled cancellation") result, elapsed = run_fixture( tmp_path, monkeypatch, code, run=SimpleNamespace(check=check), timeout=0.8, ) assert result.reason is ( local.LocalParseReason.CANCELLED if cancelled else local.LocalParseReason.TIMEOUT ) # Conditional: the cancel branch only interrupts after the marker wait, and # in both branches the child may still be starting on a busy runner. assert elapsed < 15, f"parse took {elapsed:.1f}s" child_file = _await_marker( ".mineru-attempt-*/output/child.pid", tmp_path / "out", what="owned child pid" ) assert _await_settled(int(child_file.read_text())) def test_settled_rejects_a_running_child() -> None: """Both answers, with real processes: a live pid is not settled. The cleanup assertions above only ever see the settled answer, so without this they would keep passing if the helper lost its running/zombie distinction and the original flake came back. """ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"]) try: assert _await_settled(child.pid, timeout=0.05) is False child.kill() # Not reaped here: an unreaped kill is the zombie the flake was about. assert _await_settled(child.pid) is True finally: child.kill() child.wait(timeout=5) @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") def test_group_probe_distinguishes_live_and_unreaped_members(): from deeptutor.services.parsing.engines.mineru._process import _process_group_alive process = subprocess.Popen( [sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True ) try: assert _process_group_alive(process.pid) process.kill() deadline = time.monotonic() + 2 while psutil.Process(process.pid).status() != psutil.STATUS_ZOMBIE: assert time.monotonic() < deadline time.sleep(0.01) assert not _process_group_alive(process.pid) finally: process.kill() process.wait(timeout=5) @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") def test_permission_error_never_confirms_group_cleanup(monkeypatch): from deeptutor.services.parsing.engines.mineru import _process def denied(*_args): raise PermissionError monkeypatch.setattr(_process.os, "killpg", denied) assert _process._process_group_alive(12345) @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") @pytest.mark.parametrize("backend", ["darwin", "linux"]) @pytest.mark.parametrize("reaped", [True, False]) def test_empty_member_snapshot_rechecks_group_existence(monkeypatch, backend, reaped): """Distinguish a group reaped during enumeration from one hidden by it.""" from deeptutor.services.parsing.engines.mineru import _process monkeypatch.setattr(_process, "sys", SimpleNamespace(platform=backend)) process = subprocess.Popen( [sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True ) snapshots = [] def before_snapshot(): snapshots.append(process.pid) if reaped: process.kill() process.wait(timeout=5) if backend == "darwin": original = subprocess.check_output def snapshot(*args, **kwargs): before_snapshot() return original(*args, **kwargs) if reaped else "" monkeypatch.setattr(_process.subprocess, "check_output", snapshot) else: original = psutil.process_iter def snapshot(*args, **kwargs): before_snapshot() return original(*args, **kwargs) if reaped else iter(()) monkeypatch.setattr(psutil, "process_iter", snapshot) try: assert _process._process_group_alive(process.pid) is not reaped assert snapshots == [process.pid], "must exercise the signal/enumeration race" finally: process.kill() process.wait(timeout=5) @pytest.mark.skipif(sys.platform != "darwin", reason="Darwin reports EPERM for zombie groups") def test_cleanup_accepts_zombie_group_reaped_during_snapshot(tmp_path, monkeypatch): """Exercise real EPERM recovery without inventing a permission error.""" from deeptutor.services.parsing.engines.mineru import _process snapshots = [] original = subprocess.check_output process = None def snapshot(*args, **kwargs): snapshots.append(process.pid) # Reap the zombie only after the group's signal-0 probe. The real ps # snapshot then contains no members, and signal 0 will report ESRCH. process.wait(timeout=5) return original(*args, **kwargs) try: with _process.cli_process( [sys.executable, "-c", "import time; time.sleep(30)"], tmp_path / "child.log", {} ) as process: process.kill() assert _await_settled(process.pid, timeout=2) monkeypatch.setattr(_process.subprocess, "check_output", snapshot) assert snapshots == [process.pid] finally: if process is not None: process.kill() process.wait(timeout=5) @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") def test_unsettled_tree_is_reported_as_cleanup_failed(tmp_path, monkeypatch): """A tree that never settles gets its own reason and is not published (#2426). The probe is patched rather than the exception: ``_process_group_alive`` answering "still alive" is exactly what a wedged tree looks like, so this runs the real settle loop, its real deadline and the real handler in ``local.py``. Injecting ``ProcessTreeNotSettled`` from the context manager, as an earlier attempt did, would skip all three. Driving it with a real unkillable child is not practical: ``SIGKILL`` cannot be blocked, so a genuine process would settle in practice. The loop is therefore exercised here, and the "can a tree really hang" question stays open — stated in the PR rather than implied by a green test. """ from deeptutor.services.parsing.engines.mineru import _process monkeypatch.setattr(_process, "_PROCESS_SETTLE_SECONDS", 0.2) monkeypatch.setattr(_process, "_process_group_alive", lambda _pgid: True) result, elapsed = run_fixture( tmp_path, monkeypatch, "import pathlib,sys; p=pathlib.Path(sys.argv[1]); " "(p/'lesson.md').write_text('# parsed',encoding='utf-8')", idle=10, ) assert not result.ok assert result.reason is local.LocalParseReason.CLEANUP_FAILED, result.reason assert "ProcessTreeNotSettled" in result.detail # A deliberately short deadline, so the poll ends instead of waiting 5s. assert elapsed < 3 # Publication is withheld: the attempt was never renamed into the visible # location, so a late write cannot land in a result a caller already has. assert not (tmp_path / "out" / "lesson").exists() (state_file,) = (tmp_path / "out").glob(".mineru-attempt-*/state.json") assert '"cleanup_failed"' in state_file.read_text() @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") def test_other_failures_keep_reporting_exception(tmp_path, monkeypatch): """The new reason is narrow: an unrelated failure is still ``EXCEPTION``.""" def boom(*_args, **_kwargs): raise ValueError("something else broke") # ``local`` binds ``cli_process`` at import, so patch it there rather than # in ``_process``. monkeypatch.setattr(local, "cli_process", boom) result, _ = run_fixture(tmp_path, monkeypatch, "import time; time.sleep(0.1)") assert not result.ok assert result.reason is local.LocalParseReason.EXCEPTION, result.reason @pytest.mark.skipif(sys.platform == "win32", reason="POSIX process groups") def test_settled_tree_still_publishes(tmp_path, monkeypatch): """The normal path is untouched: a settling tree publishes and succeeds.""" from deeptutor.services.parsing.engines.mineru import _process calls: list[int] = [] def settles(pgid: int) -> bool: calls.append(pgid) return False # First poll: already empty. monkeypatch.setattr(_process, "_process_group_alive", settles) result, elapsed = run_fixture( tmp_path, monkeypatch, "import pathlib,sys; p=pathlib.Path(sys.argv[1]); " "(p/'lesson.md').write_text('# parsed',encoding='utf-8')", idle=10, ) assert result.ok, result assert calls, "the settle probe must be consulted even when it clears at once" assert (tmp_path / "out" / "lesson" / "lesson.md").read_text() == "# parsed" assert elapsed < 3