Skip to content

feat(worker): PLTF-3689 run a job's module in a supervised child process - #698

Closed
aivong-openhands wants to merge 4 commits into
mainfrom
task-queue/scheduled-jobs-child-runner
Closed

aivong-openhands wants to merge 4 commits into
mainfrom
task-queue/scheduled-jobs-child-runner

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Docker Compose installs have no Kubernetes CronJobs, so the seven scheduled jobs need to run on the procrastinate worker there instead (opt-in; Kubernetes keeps its CronJobs). The worker must not run job code on its own event loop: a job that blocks would stop the worker's heartbeats, and procrastinate would then treat the job as stalled and run it again. This PR adds the piece that runs a job safely, without wiring it to any job yet: run_child_job runs the job's existing python -m <module> entry point in a child process and gives it the same guarantees a Kubernetes Job gives its pod.

Summary

  • run_child_job starts python -m <module> in its own process group and retries a non-zero exit up to backoff_limit times, waiting 10 s, doubling, at most 360 s (a Job's pod backoff). One deadline, on a monotonic clock, covers every attempt, the backoffs and the checks before each attempt; a deadline stop is not retried.
  • Before each attempt it asks the caller whether the job is still current, and starts nothing if not. A failed read is retried within the deadline and never starts an attempt.
  • On the deadline or on cancellation by the worker, it sends SIGTERM to the whole group, then SIGKILL after a grace period, and only returns once the child has exited, so a worker slot is never freed while job code still runs.
  • stop_all_children does the same for every running child at once, for a forced stop of the worker: each run_child_job then ends with ChildJobStopped, starts no further attempt, and a backoff or status-read wait in progress ends at once.

Issue Number

PLTF-3689 (OHE-3417).

How to Test

uv run --group test pytest tests/unit/app_server/test_worker_child_job.py

The tests run real child processes from small modules written to a temp dir: success on the first attempt; retries until success; failure after backoff_limit retries; the deadline stopping a hung child and its grandchild, without a retry; a child that ignores SIGTERM killed after the grace period; a backoff longer than the time left ending the job; no attempt once the job is no longer current, before the first attempt or before a retry; failed status reads retried and never starting an attempt, then ending at the deadline; cancellation (twice) returning only after a SIGTERM-ignoring child is gone; the event loop staying responsive while the child busy-loops; and a forced stop ending a running child and its job, ending a backoff at once, and starting nothing afterwards. 22 passed.

Two tests were checked against deliberate breakages: removing the final group SIGKILL fails the deadline test, and freeing the slot on cancellation before the child exits fails the cancellation test.

Video/Screenshots

N/A. No UI change.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

Nothing calls run_child_job yet; #699, stacked on this one, registers the scheduled jobs behind a default-off flag. Child output goes to the worker's stdout/stderr.

This PR was drafted by an AI agent on behalf of the user.


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-cf8fed0

Adds run_child_job: python -m <module> in its own process group, with
in-task retries on a Job's backoff, one monotonic deadline over every
attempt, backoff and status check, a status check before each attempt,
and SIGTERM then SIGKILL of the whole group on the deadline or on
cancellation, holding the slot until the child is gone.
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  openhands/app_server/worker
  child_job.py 151, 224
Project Total  

This report was generated by python-coverage-comment-action

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review of test_worker_child_job.py

Method: hand-written mutants of openhands/app_server/worker/child_job.py, each applied to a clean copy and run against tests/unit/app_server/test_worker_child_job.py. Baseline: 12 passed (about 8 s).

Controls (the PR's own claims)

Mutant Result
Off-by-one: attempts > backoff_limit becomes >= ❌ caught
No group SIGKILL after the grace period (process.kill() on the child only) ❌ caught
Cancellation re-raises without stopping the child ❌ caught
still_current asked only before the first attempt ❌ caught
A failed status read starts an attempt ❌ caught
Second cancellation frees the slot early (continue becomes raise) ❌ caught
Deadline kill falls through to the retry logic ❌ caught

The suite works because it runs real child processes and checks real outcomes: a run counter on disk pins the attempt count exactly, the HANGS module records the grandchild's pid so the group kill is checked with os.kill(pid, 0) and not by inspecting calls, and the cancellation test cancels twice against a SIGTERM-ignoring child, so an early slot release is visible.

Survivors

Mutant Result
M1: each attempt gets the full deadline_seconds, not remaining() ✅ 12 passed
M2: backoff does not double (backoff_base_seconds every time) ✅ 12 passed
M3: backoff not capped at backoff_max_seconds ✅ 12 passed
M4: SIGTERM to the child pid only (process.terminate()), not the group ✅ 12 passed
M5: status read not bounded by the deadline (await still_current() without wait_for) ✅ 12 passed
M6: wall clock (time.time()) instead of time.monotonic() ✅ 12 passed

Hangs

Mutant Result
H1: start_new_session=False (child not in its own group) suite hangs
H2: no grace bound: await process.wait() after SIGTERM, no escalation suite hangs

Both regressions are caught, but as a stuck CI job and not as a failed test: killpg on a pid that is not a group leader raises ProcessLookupError (swallowed), and process.wait() then waits for a child that ignores SIGTERM. pytest-timeout is already a dev dependency. A module-level marker turns both into failures (verified: H1 and H2 fail within the timeout, the clean branch still passes):

# A broken stop path hangs on a child that never exits; fail it instead.
pytestmark = pytest.mark.timeout(30)

M1: one deadline does not cover every attempt

This is the central Job guarantee in the summary ("one deadline ... covers every attempt"). With the mutant, every retry gets a fresh deadline_seconds, so a job with backoff_limit=6 can run for seven times its deadline. No test has more than one attempt that runs for a measurable time, so the timeout passed to _run_once is never checked after the first attempt. The test below makes the second attempt start with less time than it needs; it must be stopped at the deadline (exit_code is None), not left to exit 3 on its own.

# Exits 3 after a short run, so several attempts together outlast the deadline.
SLOW_FAIL = """
    import sys, time
    time.sleep(0.8)
    sys.exit(3)
"""


async def test_one_deadline_covers_every_attempt(tmp_path):
    env = _module(tmp_path, 'job_slow_fail', SLOW_FAIL)

    with pytest.raises(ChildJobDeadlineExceeded) as exceeded:
        await run_child_job(
            'job_slow_fail',
            env=env,
            deadline_seconds=1.2,
            backoff_limit=5,
            still_current=always_current,
            **FAST,
        )

    # The second attempt gets only what the first left, so the deadline stops it.
    assert (exceeded.value.attempts, exceeded.value.exit_code) == (2, None)

Verified: passes on the PR branch; fails with M1 ((2, 3) != (2, None)).

M2, M3: the backoff schedule is not asserted

The retry tests pass with any backoff, because nothing reads the delay. A backoff that does not double hammers a failing dependency every 10 s for the whole deadline; one that is not capped sleeps 10 s × 2^n and eats the deadline after a few retries. child_job.retrying already logs backoff_seconds, so the schedule can be read without timing anything:

from openhands.app_server.worker import child_job


async def test_backoff_doubles_up_to_the_cap(tmp_path, monkeypatch):
    env = _module(tmp_path, 'job_bad', FLAKY) | {'FAIL_TIMES': '99'}
    backoffs: list[float] = []
    monkeypatch.setattr(
        child_job._logger,
        'info',
        lambda msg, extra: backoffs.append(extra['backoff_seconds']),
    )

    with pytest.raises(ChildJobFailed):
        await run_child_job(
            'job_bad',
            env=env,
            deadline_seconds=30,
            backoff_limit=4,
            still_current=always_current,
            **FAST | {'backoff_base_seconds': 0.01, 'backoff_max_seconds': 0.04},
        )

    assert backoffs == [0.01, 0.02, 0.04, 0.04]

Verified: passes on the PR branch; fails with M2 ([0.01, 0.01, 0.01, 0.01]) and with M3 ([0.01, 0.02, 0.04, 0.08]).

M4: SIGTERM must reach the whole group

The existing group tests use a grandchild that ignores SIGTERM, so it only ever dies from the group SIGKILL. SIGTERM to the child pid alone passes every test. In production this means a job's subprocesses never get a chance to shut down cleanly: they are SIGKILLed when the grace period ends. This test uses a child whose SIGTERM handler waits for a grandchild, and a grandchild that records that it received SIGTERM:

# Its SIGTERM handler waits for a grandchild that exits on its own SIGTERM.
GRACEFUL = """
    import os, pathlib, signal, subprocess, sys, time
    state = pathlib.Path(os.environ['STATE_DIR'])
    grandchild = subprocess.Popen([sys.executable, '-c', (
        'import pathlib, signal, sys, time\\n'
        'def term(*_):\\n'
        f'    pathlib.Path({str(state)!r}, "grandchild.term").write_text("1")\\n'
        '    sys.exit(0)\\n'
        'signal.signal(signal.SIGTERM, term)\\n'
        f'pathlib.Path({str(state)!r}, "grandchild.ready").write_text("1")\\n'
        'time.sleep(600)\\n'
    )])
    signal.signal(signal.SIGTERM, lambda *_: sys.exit(grandchild.wait()))
    while not (state / 'grandchild.ready').exists():
        time.sleep(0.01)
    time.sleep(600)
"""


async def test_the_deadline_sends_sigterm_to_the_whole_group(tmp_path):
    env = _module(tmp_path, 'job_graceful', GRACEFUL)

    with pytest.raises(ChildJobDeadlineExceeded):
        await run_child_job(
            'job_graceful',
            env=env,
            deadline_seconds=2,
            backoff_limit=0,
            still_current=always_current,
            **FAST,
        )

    assert (tmp_path / 'grandchild.term').exists()

Verified: passes on the PR branch; fails with M4 (with the mutant, the grandchild never gets SIGTERM, the child waits for it until the grace period ends, and then the group is SIGKILLed).

M5: a hung status read must end at the deadline

test_a_status_read_that_keeps_failing_ends_at_the_deadline covers a read that raises. It does not cover a read that never returns, for example a database call stuck on a dead connection. Without the wait_for, the job holds its worker slot forever. The outer wait_for makes the mutant fail and not hang:

async def test_a_status_read_that_hangs_ends_at_the_deadline(tmp_path):
    env = _module(tmp_path, 'job_ok', FLAKY) | {'FAIL_TIMES': '0'}

    async def hung_read() -> bool:
        await asyncio.sleep(600)
        return True

    with pytest.raises(ChildJobDeadlineExceeded) as exceeded:
        await asyncio.wait_for(
            run_child_job(
                'job_ok',
                env=env,
                deadline_seconds=0.5,
                backoff_limit=3,
                still_current=hung_read,
                **FAST,
            ),
            5,
        )

    assert exceeded.value.attempts == 0
    assert not (tmp_path / 'runs').exists()

Verified: passes on the PR branch; fails with M5 (TimeoutError from the outer wait_for, not ChildJobDeadlineExceeded).

M6: monotonic clock (low priority)

The deadline on time.time() would end a job early, or extend it, on an NTP step. This is a lower-value test because it patches the clock, but it pins the claim in the summary:

async def test_a_wall_clock_step_does_not_end_the_job(tmp_path, monkeypatch):
    env = _module(tmp_path, 'job_ok', FLAKY) | {'FAIL_TIMES': '0'}
    # An NTP step a day forward after the first reading.
    readings = iter([0.0])
    monkeypatch.setattr(time, 'time', lambda: next(readings, 86400.0))

    result = await run_child_job(
        'job_ok',
        env=env,
        deadline_seconds=30,
        backoff_limit=0,
        still_current=always_current,
        **FAST,
    )

    assert result.attempts == 1

Verified: passes on the PR branch; fails with M6 (ChildJobDeadlineExceeded before the first attempt).

All proposed tests together: 17 passed, three runs in a row, about 12 s.

Not a test gap

  • asyncio.create_subprocess_exec is awaited before the try in _run_once. A cancellation that arrives during that await can leave a child that has started but is not stopped. The window is small, but moving the spawn inside the guarded region (or shielding it) would close it.

This comment was generated by an AI assistant on behalf of the user.

… of child jobs

Add tests for the surviving mutants from the review (shared deadline,
backoff doubling and cap, SIGTERM to the whole group, hung status read,
monotonic clock) and a module-level timeout so a broken stop path fails
instead of hanging CI. Spawn the child inside a shielded task so a
cancellation during spawn cannot leave a child running.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Addressed in 19c20a1: added the M1–M6 tests and the module-level pytest.mark.timeout(30) (H1/H2), and moved the child spawn into a shielded task so a cancellation during spawn still stops the child (the 'not a test gap' item). The 17 tests pass except 3 that check a killed grandchild is gone via os.kill(pid, 0); those fail identically on the previous commit in my sandbox (PID 1 does not reap orphans, so the zombie still answers), so CI is the real check for them.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands aivong-openhands left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taste: acceptable. The design is sound (child process group, one monotonic deadline, status check before every attempt) and the real-subprocess tests are strong. Two verified defects remain on 19c20a173, both against guarantees stated in the PR description. I reproduced each against the head.

Findings

  1. 🟠 child_job.py:153: cancellation during the deadline stop leaves the child running. See inline.
  2. 🟡 child_job.py:122: a TimeoutError raised by still_current() is reported as a deadline stop. See inline.

Other

  • Current-head CI: Python Tests on Linux (3.12) and Budget regressions were still pending when I reviewed, so the new tests have not passed in CI yet. The author's note says three grandchild-reaping tests fail in their sandbox and that CI is the real check, so please confirm them green before merging.
  • The PR follows the template.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM
New process-supervision and signal-handling code, but isolated to one new module that nothing calls yet (wired in #699 behind a default-off flag). Finding 1 should be fixed before #699 builds on it, because worker shutdown during a deadline stop is exactly the path that frees a slot while job code still runs.

Verdict: COMMENT (I am posting from the PR author's account, so I cannot request changes). I would not merge until finding 1 is fixed.

Key insight: _run_once protects only the cancellation path with _despite_cancellation. The deadline path, which also stops a child, runs the same _stop unprotected, so the slot guarantee holds in one branch and not the other.

Improve this review? If feedback seems incorrect or irrelevant, update the repository's .agents/skills/custom-codereview-guide.md (with the /codereview trigger), then re-request review. The reviewer reads the guide from the PR head.

Resolve with AI? Install the iterate skill and run /iterate.

Was this review helpful? React with 👍 or 👎.

This review was generated by an AI agent (OpenHands) on behalf of the user.

…eoutError from the status read

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Addressed both findings from the review in f9e3752:

  1. Cancellation during the deadline stop: the deadline stop now runs to completion even if the job is cancelled during the grace period. The cancellation is re-raised only after the child's process group is gone, so a worker slot is not freed while job code still runs. Pinned by test_cancelling_during_the_deadline_stop_still_stops_the_child.
  2. TimeoutError from still_current(): it now counts as the deadline only when remaining() <= 0. Otherwise it is logged and retried like any failed status read. Pinned by test_a_status_read_that_times_out_is_retried_not_the_deadline.

Both new tests fail on the previous head and pass now. Both review threads are resolved.

Testing note: in my sandbox PID 1 does not reap zombies, so the grandchild-reaping tests fail there. With a zombie-aware liveness check, all 19 tests in test_worker_child_job.py pass. Please confirm CI is green on the new head before merging.

This comment was generated by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands aivong-openhands left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taste: good. No material findings on f9e37525f.

The design is simple and each stated guarantee maps to one place in the code: the child runs in its own process group, one monotonic deadline covers the status checks, attempts and backoffs, and _despite_cancellation holds a cancellation back until the child has exited on both the cancel path and the deadline path.

Both concerns from the earlier review on 19c20a173 are fixed on this head, each with a test:

  • Cancellation during the deadline stop: test_cancelling_during_the_deadline_stop_still_stops_the_child.
  • A TimeoutError raised by still_current() is retried, not treated as the deadline: test_a_status_read_that_times_out_is_retried_not_the_deadline.

The earlier mutation survivors (M1-M6) and hang cases (H1/H2) are covered by new tests and the module-level pytest.mark.timeout(30). Current-head CI is green, including Python Tests on Linux (3.12).

Acceptance criteria

  • Runs python -m <module> in its own process group.
  • Retries a non-zero exit up to backoff_limit times with 10 s doubling backoff, capped at 360 s.
  • One monotonic deadline; a deadline stop is not retried.
  • still_current is checked before every attempt, and a failed read never starts one.
  • SIGTERM, then SIGKILL after the grace period; the slot is released only after the child has exited.
  • Tests use real subprocesses; the PR follows the template.

Non-blocking notes (not defects against the stated contract):

  • _stop returns early if returncode is already set, and a child that exits on its own does not have its group swept. Leftover grandchildren survive in those cases. This matches the documented scope (cleanup on deadline or cancellation); revisit in #699 if jobs spawn long-lived helpers.
  • If the spawn itself fails with an exception while a cancellation is arriving, _despite_cancellation(spawning) re-raises that exception instead of CancelledError. Edge case, harmless at worker shutdown.
  • env=dict(env) replaces the whole environment, so the caller in #699 must pass everything the job needs (DB settings, etc.).

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM
New process-supervision and signal-handling code, isolated to one new module that nothing calls yet (#699 wires it in behind a default-off flag). Reviewers should focus on how #699 builds the child's env, the worker-shutdown path, and process-group cleanup under the container's PID 1 (the author noted PID 1 does not reap orphans in their sandbox).

Verdict: COMMENT. I would approve; nothing blocks. I am posting from the PR author's account, so I cannot submit an approval. The PR is still a draft and the "A human has tested these changes" checkbox is unchecked.

Key insight: The deadline path and the cancellation path now share one "hold cancellation until the child group is dead" mechanism, which is what makes the "slot never freed while job code runs" guarantee hold in both branches.

This review was generated by an AI agent (OpenHands) on behalf of the user.

stop_all_children stops each live child's process group (SIGTERM, then
SIGKILL after the grace period) and makes every run_child_job end with
ChildJobStopped: no further attempt, and a backoff or status-read wait in
progress ends at once. The job then finishes as failed instead of being
left running behind a worker that exited.

@jlav jlav left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that this stack is re-inventing functionality that procrastinate already provides for us natively. I'm not understanding why we need to create and manage child processes at all.

periodic can be used to schedule jobs. Why do we need any more machinery than that?

Copy link
Copy Markdown
Contributor Author

You are right. Procrastinate already gives us what this stack builds, and our migration plan also says to use it.

I will close this PR and #699. I will open a new, smaller PR that uses periodic and the other native procrastinate features.

This comment was created by an AI agent (OpenHands) on behalf of @aivong-openhands.

aivong-openhands added a commit that referenced this pull request Oct 19, 2026
…#874)

* feat(worker): PLTF-3689 schedule the CronJob jobs with procrastinate periodic tasks

Each job is a periodic task that calls its existing code in the worker,
off unless OH_WORKER_SCHEDULED_JOBS_<JOB> is true. Replaces the child-process
approach of #698 and #699.

Co-authored-by: openhands <openhands@all-hands.dev>

* chore(worker): tighten scheduled-jobs comments

Co-authored-by: openhands <openhands@all-hands.dev>

* fix(worker): PLTF-3689 don't retry scheduled jobs

A retry returns the failed run to todo, which collides with the next run
already waiting under the same queueing lock. The UniqueViolation left the
failed run doing and holding its lock, so the job stopped until the worker
restarted. The next scheduled run is now the retry.

Co-authored-by: openhands <openhands@all-hands.dev>

* test(worker): PLTF-3689 pin scheduled job wiring per mutation review

- Run every job on a real worker with its CronJob entrypoint recorded, so a
  wrong or missing entrypoint call, a bad lazy import or resend_sync on the
  event loop fails (M1-M5).
- Cover run_budget_maintenance.main() still running the job (M6).
- Cover the worker skipping scheduled_jobs when no job is enabled (M7).
- Time out each test at 60 s so a lost deadline fails instead of hanging (M8).
- Give each worker test only the jobs it runs, so other jobs' periodic runs
  don't depend on the clock.

Co-authored-by: openhands <openhands@all-hands.dev>

* docs(worker): PLTF-3689 note stalled-run overlap in scheduled job comment

Co-authored-by: openhands <openhands@all-hands.dev>

---------

Co-authored-by: openhands <openhands@all-hands.dev>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: feat A new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants