mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-02 03:29:23 +08:00
* test(parsing): stop racing interpreter startup in the MinerU lifecycle checks
The Windows `import-check` job flakes on `dev`. It failed at 2026-11-30 03:12
and 03:32 on `79a66cb3` and `6b00f010`, passed on the same step 90 minutes
later in another run, and passed on `218dbe31` the evening before. Nothing
between those runs touched `.github/`, `tests/services/parsing/`,
`tests/runtime/` or the MinerU engine, so the workflow and the code under test
were identical in the green and red runs.
Reproduced, and the cause is a timing premise in the tests, not the runner.
The race
--------
`test_deadline_and_cancellation_settle_the_owned_tree[True]` sets
`timeout=0.8` and only cancels once the fixture child has spawned a grandchild
and written `child.pid`:
def check():
if cancelled and list(...glob(".../child.pid")):
raise IndexingCancelled(...)
`local.py` starts its clock before `cli_process()`, which on Windows creates a
Job Object, spawns a suspended interpreter, resumes it and queries its threads.
That work plus two more interpreter startups has to fit inside the same 0.8s.
When it does not, the deadline wins before the marker exists and the assertion
reports `TIMEOUT is not CANCELLED`.
Measured on an idle machine the marker lands in 0.067-0.085s, so the margin
looked comfortable. Delaying only the child's first write, with no CPU
contention at all:
startup delay | result | expected | verdict
0.0s | cancelled | cancelled | pass
0.5s | cancelled | cancelled | pass
0.7s | timeout | cancelled | FAIL
0.9s | timeout | cancelled | FAIL
1.2s | timeout | cancelled | FAIL
CPU contention alone reproduced the same signature
`assert <LocalParseReason.TIMEOUT> is <LocalParseReason.CANCELLED>` at line 138,
plus `assert 2.087 < 2` and `assert 3.757 < 1.5` on neighbouring cases.
The production ordering is correct and is left alone: `run.check()` is
evaluated before the deadline comparison, so an available cancellation always
wins. What the tests must not do is depend on how fast the runner started a
Python interpreter.
What changed
------------
- `_await_marker()` waits for a fixture marker with a real timeout and a
message that distinguishes "the CLI never started" from "the runner was
slow". Bare `(path,) = glob(...)` unpacking turned both into
`ValueError: not enough values to unpack (expected 1, got 0)`, which is what
made these CI failures unreadable.
- The cancellation case waits for the recorded child before raising, so the
interruption is decided by policy rather than by interpreter startup. A 3s
startup delay now passes where 0.7s used to fail.
- Wall-clock bounds that were only guarding "did not wait for the descendant"
were widened off the interpreter-startup budget (`elapsed < 2` -> `< 15`,
`elapsed < 1.5` -> `< 10`, `elapsed < 2.5` -> `< 15`). The idle-threshold and
deadline assertions that carry the actual meaning are unchanged.
- `_await_settled()` treats `psutil.AccessDenied` as "not settled yet" instead
of raising mid-test.
- The decoy process in `test_parent_exit_does_not_wait_for_descendant_stdout`
lives 120s instead of 10s, so a slow run cannot make it die of old age and be
reported as "cleanup touched an unrelated process".
- `test_detached_venv_launcher_has_no_console` asserts the marker exists before
reading it, instead of raising `FileNotFoundError` after its 15s wait.
Observability
-------------
The Windows step now runs with `-rA --durations=15`. Without them the job
reported only "Process completed with exit code 1" with no test name, which is
why these failures needed a local reproduction to attribute.
Verification
------------
- `pytest -q -rA --durations=15 tests/services/parsing/test_mineru_process_lifecycle.py tests/runtime/test_launcher.py::test_detached_venv_launcher_has_no_console`
-> 7 passed, 10 skipped (the skips are POSIX/Darwin-only cases).
- Deliberate-startup-delay harness: 0.0/0.5/0.9/1.5/3.0s all report
`cancelled` after the change; 0.7s+ reported `timeout` before it.
- `ruff check` and `ruff format --check` clean on both files; workflow YAML
parses.
No production code is changed.
* test(parsing): synchronise the deadline fixtures with grandchild startup
Addresses review on #3089. Two real defects:
1. The deadline case of test_deadline_and_cancellation_settle_the_owned_tree
still raced. Only the cancellation branch waited for `child.pid`; the
deadline branch killed the fixture at 0.8s and then read a marker that was
never written, so a 1.3s startup delay produced `TIMEOUT` and then a failed
marker read. Both branches now synchronise through `check()`: it waits for
the recorded grandchild and only then either raises (cancellation) or returns
and lets the deadline comparison run. The timeout assertion is preserved.
test_explicit_client_timeout_also_bounds_parent_runtime had the same shape —
it read `deadline.txt` after a 1.2s kill. The record is written before the
child parks, so it exists whenever the child started at all, and the read now
reports "CLI did not start" instead of an unpacking error.
2. test_parent_exit_does_not_wait_for_descendant_stdout had lost its teeth: the
new 10s bound exceeded the grandchild's 2s sleep, so an implementation that
waited for inherited stdout could finish inside the bound and pass. The
grandchild now lives 60s and the bound is 20s, derived from the fixture, so
waiting for it fails the test again.
Verified with a 1.3s pre-startup delay (the reviewer's repro): both lifecycle
cases report the expected reason and the tree is settled. 0.0/1.3/2.0/3.0s all
pass. `7 passed, 10 skipped`; ruff clean.
* test: wait for the MinerU deadline record before enforcing the timeout
---------
Co-authored-by: Qiuner <wdst3635@163.com>
461 lines
19 KiB
Python
461 lines
19 KiB
Python
"""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
|