Skip to content

[Bug]: MinerU CLI cleanup never waits for the process group, so descendants outlive the parse #2426

Closed

Description

@AleFlyX

What happens

cli_process() in deeptutor/services/parsing/engines/mineru/_process.py is
documented as settling the CLI tree "on every exit", but on POSIX it never
waits for the descendants it signals. The finally branch signals the group
and then waits only for the direct child:

elif process is not None:
    for sig in (signal.SIGTERM, signal.SIGKILL):
        try:
            os.killpg(process.pid, sig)
        except ProcessLookupError:
            break
if process is not None:
    process.wait(timeout=5)

os.killpg() queues the signal and returns; it does not wait for delivery or
for any target to exit. process.wait() reaps the direct child, which the CLI
often exits from on its own well before the signal arrives. Every process the
CLI spawned into the same group can therefore still be running when
cli_process() returns and the parser output is published.

This is not a test artefact. Measuring right after killpg() + parent wait()
returns, across 10 runs of a parent that spawns one child and exits:

run 0: pid_exists=True  status=running
...
run 4: pid_exists=True  status=zombie
...
run 9: pid_exists=True  status=running
状态分布: Counter({'running': 9, 'zombie': 1})

9 of 10 survivors were still running, not zombies awaiting a reap, so
this is live processes outliving the parse rather than a bookkeeping
artefact.

Why it surfaces as a CI failure

tests/services/parsing/test_mineru_process_lifecycle.py::test_parent_exit_does_not_wait_for_descendant_stdout
asserts the settled state:

child = int((tmp_path / "out" / "lesson" / "child.pid").read_text())
assert not psutil.pid_exists(child), "Owned child escaped cleanup"

The assertion is correct — the code is what does not hold up its end. The test
passes on an idle machine because the child (time.sleep(2)) usually dies
before the assertion runs, and fails when the runner is loaded and the killed
child has not been scheduled to exit yet. Reproduced locally by adding CPU
contention:

  • idle, 12 runs: 0 failures
  • with background CPU load, 12 runs: 2 failures, same message as CI

result.ok is True in the failing runs, i.e. parsing itself succeeded and
only the cleanup check failed.

Impact

The observable effect is that a timed-out, cancelled or failed MinerU attempt
can leave inference processes running after the parse has returned. On a long
indexing job that means memory and CPU held by work nobody is waiting for, and
on repeated attempts it accumulates. It also makes the Windows and POSIX
branches disagree: the Windows path polls the job object until
ActiveProcesses reaches zero and raises if the tree does not settle within 5
seconds, while the POSIX path returns immediately after reaping the direct
child.

Suggested fix

After reaping the direct child, poll the group until it is empty rather than
assuming the signal completed:

process.wait(timeout=5)
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
    try:
        os.killpg(process.pid, 0)   # probe: does the group still have members?
    except ProcessLookupError:
        break
    except PermissionError:
        break
    time.sleep(0.02)
else:
    raise RuntimeError("MinerU process-tree cleanup did not settle")

killpg(pgid, 0) succeeds while the group has any member and raises
ProcessLookupError once it is empty, which gives the POSIX path the same
"settle or fail loudly" contract the Windows path already enforces.

Measured with the same harness:

cleanup survivors
current 10/10
with the group poll 0/10

Caveats worth weighing in review:

  • Process-group reuse. A pgid can in principle be recycled, but only after
    the group is empty, and this runs immediately after reaping the leader, so
    the window is small. The Windows branch already makes the stronger
    assumption that the job object identifies the tree.
  • process.wait() racing a still-live group is fine on its own; the poll
    is what closes the gap, not the wait.
  • The probe itself was verified on this platform. killpg(pgid, 0) raises
    ProcessLookupError once the group is empty, and a zombie member does not
    keep the group alive, so the poll terminates instead of spinning until the
    deadline. Both cases checked directly.

Environment

  • DeepTutor v1.7.1 (f7aed0744)
  • Ubuntu 24.04 / Linux, Python 3.11–3.14
  • Observed on GitHub Actions; the same test also failed on an unrelated open PR
    (fix(web): recover from synchronous socket construction failures #2405), and three other open PRs show different flaky Python failures on the
    same runs, so the broader CI signal is noisy — but this particular test fails
    for a reason in the product code, not only in the test.

Related

  • tests/services/parsing/test_mineru_process_lifecycle.py
  • Windows counterpart in the same file that already waits for settlement

Activity

  1. zeweihan commented on Nov 4, 2026

    @zeweihan

    One additional failure boundary is worth making explicit: tree settlement should be part of the attempt's commit protocol, not just best-effort cleanup after a result is already visible. Reaping the direct child does not prove that a descendant has stopped writing to the attempt's output directory or inherited descriptors.

    A useful acceptance matrix would be:

    1. Start an attempt in its own temporary output directory. A descendant ignores SIGTERM and schedules a late marker write.
    2. On timeout or cancellation, escalate to SIGKILL and wait for group settlement using one overall monotonic deadline.
    3. Publish/rename the output into the visible result location only after settlement succeeds. A late marker must never appear in a published result.
    4. If the group does not settle by the deadline, return a distinct cleanup_failed state (or preserve the original failure with a cleanup annotation), rather than allowing result.ok=True or a subsequent retry to treat the attempt as fully finished.
    5. Exercise success, parser failure, timeout, and caller cancellation, each with both an empty group and a surviving grandchild. Assert the same terminal-state and publication invariants on POSIX and Windows.

    This separates “the parse produced bytes” from “the attempt is safe to commit.” It also prevents retries from sharing CPU/memory or output paths with work from a supposedly terminal attempt. Your proposed group poll supplies the missing settlement signal; making publication conditional on that signal would close the remaining late-write/result-visibility race.

  2. AleFlyX commented on Nov 4, 2026

    @AleFlyX
    CollaboratorAuthor

    Good boundary. I checked these against the code rather than reasoning about
    them.

    The ordering was already intended. local.py opens the CLI in a
    with cli_process(...) block (line 254) and renames the attempt into the visible
    result location at line 360, after the block. The comment above it says "Settle
    the owned process tree before validating/publishing artifacts", so that was the
    intent; the PR makes the settle actually happen rather than assuming killpg()
    completed.

    The terminal state is still wrong, though. If the group does not settle,
    cli_process raises RuntimeError from inside the with, which skips the rename
    at line 360, and the caller's except turns it into
    LocalParseResult.failure(LocalParseReason.EXCEPTION, ...). So a stuck tree
    reports ok=False with reason EXCEPTION — indistinguishable from a parser
    crash, and not the distinct cleanup_failed state you describe. The retry
    decision differs between the two, and an EXCEPTION label erases that.

    The raise is also hard to reach as things stand: the second signal is SIGKILL,
    which cannot be ignored, so the group settles on the first poll in every case I
    tried. That makes cleanup_failed a correctness item rather than a live bug —
    but withholding publication should be an explicit outcome of the settle, not
    something that happens because the exception was raised at a convenient line.

    A descendant that escapes the group still defeats the poll. I reproduced
    this directly: a descendant started with start_new_session=True keeps its
    output handle, and after cli_process returned it appended to the already
    published markdown:

    after settle:    '# partial'
    after 1.2s:      '# partial| LATE'
    

    That is the late-write race you describe, and a process-group poll cannot see
    it. Nothing in deeptutor/ currently spawns with start_new_session, so this is
    latent rather than the path behind the CI failure; that failure is descendants
    still inside the group that had not exited yet. A parser CLI that shells out to
    setsid, or to a helper that daemonizes, would reach this case without any
    change on our side.

    I agree the invariant should be "the attempt is safe to commit" rather than
    "the parse produced bytes". On top of the settlement this PR adds, the remaining
    pieces would be:

    1. a distinct terminal reason for an unsettled tree, so a caller can tell
      "cleanup failed" from "the parser crashed" — the retry decision differs, and
      an EXCEPTION label erases that;
    2. publication gated on settlement rather than following it — with the current
      ordering, that means cli_process reporting settlement as a value the
      publisher checks, instead of raising past it;
    3. for the escaped-descendant case, a marking the poll alone cannot provide —
      PR_SET_CHILD_SUBREAPER, a cgroup, or a job-object-equivalent on POSIX.
      That is a much larger change than this fix and I would not fold it into this
      PR.

    On the matrix: 1 and 2 are testable today, and I can write them as a follow-up
    against test_mineru_process_lifecycle.py, which already builds fixtures for
    success, failure, timeout and cancellation — the empty-group and
    surviving-grandchild variants are mostly parametrisation. Item 5 I would want a
    maintainer's read on before writing it. The Windows branch settles a job object
    and the POSIX branch settles a process group, and those two have different escape
    surfaces, so asserting the same terminal state across both may claim more than
    each mechanism can deliver.

    I would keep this issue open for the commit-protocol part rather than closing
    it on #2428. #2428 addresses settlement; the publication gate and the distinct
    terminal state are separate pieces of work.

  3. AleFlyX commented on Nov 6, 2026

    @AleFlyX
    CollaboratorAuthor

    Status: settlement has landed, the terminal state is in review

    Updating my comment above — the code moved since it was written, and two of the
    items in it now have an outcome.

    Settlement is in dev. #2428 merged on 2026-11-06 (e022fc957): POSIX now
    polls the process group until it is empty, with the same five-second deadline
    the Windows branch already applied to its job object. The CI failure that
    surfaced the bug — test_parent_exit_does_not_wait_for_descendant_stdout — is
    green on dev.

    The probe was revised after the merge, in 39f744114 (integrated via #2466):

    • PermissionError from killpg() no longer counts as settled. It used to
      return False directly, which could publish while the group's state was
      unknown; it now falls through to a psutil scan.
    • A group containing only zombies counts as settled, explicitly. Darwin gets its
      own /bin/ps -Ao pgid=,stat= path, because getpgid() cannot resolve an
      unreaped zombie there and the shell reports EPERM.

    So the two POSIX targets now settle with different mechanisms. I read that as
    evidence for the parity point below rather than as an implementation detail.

    Where zeweihan's five items stand

    item state
    settlement signal done (#2428)
    distinct cleanup_failed terminal state #2485, open, CI green
    publication gated on settlement already the ordering; #2485 asserts it
    late-write marker must not appear in a published result holds for same-group descendants; fails for escaped ones
    identical terminal state on POSIX and Windows I do not think we should claim this

    On item 2. #2485 is the resubmission of the earlier closed attempt. It
    raises a dedicated ProcessTreeNotSettled from both settle loops, maps it to
    LocalParseReason.CLEANUP_FAILED, and gives that reason its own message — with
    the retry hint included, which the closed attempt dropped. Its test patches the
    probe rather than injecting the exception, so the settle loop, the deadline and
    the handler all run, and it asserts the published directory never appears. It
    carries Refs #2426, not Closes.

    On item 4. The escaped-descendant case I described above is unchanged: a
    child that calls setsid leaves the group and no group poll can see it, so a
    late write can still land in a published result. I do not think it belongs in
    #2485, and I am not proposing to build a supervisor for it yet: the options are
    PR_SET_CHILD_SUBREAPER, a cgroup, or a job-object equivalent, and each is a
    much larger change than a hypothetical trigger warrants. What I would do
    instead is publish the boundary — say in cli_process that the poll covers the
    group, not the session — plus a reproducer marked xfail, so the next reader
    does not assume more than it delivers.

    On item 5. You asked for the same terminal state on both platforms; I do not
    think we can honestly assert that. A process group can be left by setsid; a
    job object can be left by breakaway. They are not the same guarantee, and one
    assertion across both would either overstate POSIX or understate Windows. The
    commitment I would write instead is: settles within the deadline on the
    mechanism that platform owns, and publication is withheld otherwise, with
    per-platform tests. Happy to be corrected if you read the two as equivalent.

    I would keep this issue open for items 4 and 5, and let #2485 settle only item 2.

  4. pancacake commented on Nov 14, 2026

    @pancacake
    Collaborator

    Fixed on local dev (92a26ae3cc198aaf1ad32420e1b83dbd40f8ddbc). fix(storage): isolate attachment writes and settle document parsing. Validated with targeted regression tests and compatibility checks.

    will be fixed in the next releases!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions