Skip to content

The agent that grows with you

refactor(cron): detached-worker teardown as a sibling module, no guards around a real Future

kshitijk4poor40488a4e5460
diff --git a/cron/scheduler.py b/cron/scheduler.py
index a30ca59aab0..3a1b3839521 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -1999,103 +1999,6 @@ def _finalize_cron_session(session_db, agent, job_id: str, job_name: str, cron_s
logger.debug("Job '%s': failed to close SQLite session store: %s", job_id, e)
-def _finalize_cron_session_db(
- session_db, agent, job_id: str, job_name: str, cron_session_id: str,
-) -> None:
- """Finalize a cron session exactly once before releasing its registry reference."""
- _finalize_cron_session(session_db, agent, job_id, job_name, cron_session_id)
-
-
-def _teardown_detached_cron_worker(
- session_db, agent, job_id: str, job_name: str, cron_session_id: str,
-) -> None:
- """Release a timed-out worker's agent and SessionDB after it finishes."""
- try:
- if session_db:
- _finalize_cron_session_db(
- session_db, agent, job_id, job_name, cron_session_id)
- except BaseException as exc:
- logger.error(
- "Job '%s': detached worker session teardown failed: %s",
- job_id,
- exc,
- exc_info=(type(exc), exc, exc.__traceback__),
- )
- finally:
- _teardown_cron_agent(agent, job_id)
-
-
-def _defer_cron_worker_teardown_if_running(
- worker_state: dict,
- session_db,
- agent,
- job_id: str,
- job_name: str,
- cron_session_id: str,
-) -> bool:
- """Keep the agent and SessionDB alive until a timed-out worker finishes.
-
- ``ThreadPoolExecutor.shutdown(wait=False)`` does not stop a running
- ``run_conversation`` call. Closing its SessionDB from ``run_job``'s
- ``finally`` would therefore recreate the close-vs-write race this module
- is meant to prevent. The real Future always supports ``add_done_callback``;
- unknown test doubles are handled conservatively by waiting before inline
- cleanup rather than closing a possibly-live handle.
- """
- future = worker_state.get("future")
- if future is None:
- return False
- done = getattr(future, "done", None)
- if callable(done):
- try:
- if bool(done()):
- return False
- except Exception as exc:
- logger.warning(
- "Job '%s': could not determine worker completion; deferring teardown: %s",
- job_id,
- exc,
- )
-
- add_done_callback = getattr(future, "add_done_callback", None)
- if not callable(add_done_callback):
- logger.error(
- "Job '%s': worker future cannot register teardown callback; waiting for worker",
- job_id,
- )
- try:
- future.result()
- except BaseException as exc:
- logger.debug("Job '%s': detached worker completed with: %s", job_id, exc)
- return False
-
- if worker_state.get("teardown_registered"):
- return True
- worker_state["teardown_registered"] = True
-
- def _finish_detached_worker(_future) -> None:
- _teardown_detached_cron_worker(
- session_db, agent, job_id, job_name, cron_session_id)
-
- try:
- add_done_callback(_finish_detached_worker)
- except Exception as exc:
- # A real concurrent.futures.Future does not reject this call. If a
- # custom future does, wait rather than releasing a live SQLite handle.
- worker_state["teardown_registered"] = False
- logger.error(
- "Job '%s': failed to register detached-worker teardown; waiting: %s",
- job_id,
- exc,
- )
- try:
- future.result()
- except BaseException as result_exc:
- logger.debug("Job '%s': detached worker completed with: %s", job_id, result_exc)
- return False
- return True
-
-
def _run_doc_header(job: dict, title: str, job_id: str, prompt: str) -> str:
"""Header of the persisted run document (title, ids, schedule, prompt)."""
return (
@@ -2477,17 +2380,12 @@ def run_job(
return False, output, "", error_msg
finally:
- # A watchdog timeout only stops waiting; executor.shutdown(wait=False)
- # cannot interrupt a worker already inside run_conversation. Keep both
- # the agent and its registry-owned SessionDB alive until that worker's
- # Future completes, otherwise its late persistence can race close/WAL
- # checkpoint teardown.
- _worker_teardown_deferred = _defer_cron_worker_teardown_if_running(
- _worker_state, _session_db, agent, job_id, job_name, _cron_session_id)
+ from cron.scheduler_detached_worker import defer_teardown_to_running_worker
+ _worker_teardown_deferred = defer_teardown_to_running_worker(
+ _worker_state.get("future"), _session_db, agent, job_id, job_name, _cron_session_id)
scope.exit()
if _session_db and not _worker_teardown_deferred:
- _finalize_cron_session_db(
- _session_db, agent, job_id, job_name, _cron_session_id)
+ _finalize_cron_session(_session_db, agent, job_id, job_name, _cron_session_id)
# Tear down the ephemeral agent or the gateway leaks fds per tick (EMFILE). With deferred
# teardown, hand the live agent back: delivery needs a live async client.
# Release subprocesses, terminal sandboxes, browser daemons, and the main OpenAI/httpx client held
diff --git a/cron/scheduler_detached_worker.py b/cron/scheduler_detached_worker.py
new file mode 100644
index 00000000000..921a5e6f200
--- /dev/null
+++ b/cron/scheduler_detached_worker.py
@@ -0,0 +1,34 @@
+"""Cron: teardown of a worker that outlived its ``run_job``.
+
+``ThreadPoolExecutor.shutdown(wait=False)`` after an inactivity timeout does not stop a
+worker already inside ``run_conversation``. Finalizing its SessionDB from ``run_job``'s
+``finally`` would close a handle the worker is still writing to — the checkpoint/WAL-unlink
+overlap behind #102827. The worker's Future owns the teardown instead.
+"""
+
+from __future__ import annotations
+
+import concurrent.futures
+from typing import Optional
+
+
+def defer_teardown_to_running_worker(
+ future: Optional[concurrent.futures.Future], session_db, agent, job_id: str, job_name: str,
+ cron_session_id: str,
+) -> bool:
+ """Return True when the worker is still running and its Future will finalize the session
+ and tear the agent down on completion; False when the caller must do it now."""
+ if future is None or future.done():
+ return False
+ from cron.scheduler import _finalize_cron_session, _teardown_cron_agent
+
+ def _finish(_future) -> None:
+ try:
+ if session_db:
+ _finalize_cron_session(session_db, agent, job_id, job_name, cron_session_id)
+ finally:
+ _teardown_cron_agent(agent, job_id)
+
+ # Runs inline if the worker finished between done() and here — still exactly once.
+ future.add_done_callback(_finish)
+ return True
diff --git a/tests/cron/test_cleanup_timeout.py b/tests/cron/test_cleanup_timeout.py
index 6981c24a45d..02758d98cf7 100644
--- a/tests/cron/test_cleanup_timeout.py
+++ b/tests/cron/test_cleanup_timeout.py
@@ -11,11 +11,8 @@ import time
from concurrent.futures import Future
from unittest.mock import MagicMock, patch
-from cron.scheduler import (
- _defer_cron_worker_teardown_if_running,
- _teardown_cron_agent,
- run_job,
-)
+from cron.scheduler import _teardown_cron_agent, run_job
+from cron.scheduler_detached_worker import defer_teardown_to_running_worker
_RUNTIME = {
@@ -100,32 +97,24 @@ def test_agent_teardown_is_bounded():
def test_detached_worker_teardown_waits_for_future():
- """A timed-out worker keeps its agent and SessionDB until completion."""
+ """A timed-out worker keeps its agent and SessionDB until its Future completes."""
future = Future()
- worker_state = {"future": future}
fake_db = MagicMock()
agent = MagicMock()
- with patch("cron.scheduler._teardown_detached_cron_worker") as teardown_worker:
- assert _defer_cron_worker_teardown_if_running(
- worker_state,
- fake_db,
- agent,
- "detached-worker",
- "detached worker",
- "cron_detached-worker",
- ) is True
- teardown_worker.assert_not_called()
+ with patch("cron.scheduler._finalize_cron_session") as finalize, \
+ patch("cron.scheduler._teardown_cron_agent") as teardown_agent:
+ assert defer_teardown_to_running_worker(
+ future, fake_db, agent, "detached-worker", "detached worker", "cron_detached-worker") is True
+ finalize.assert_not_called()
+ teardown_agent.assert_not_called()
future.set_result({"final_response": "late"})
- teardown_worker.assert_called_once_with(
- fake_db,
- agent,
- "detached-worker",
- "detached worker",
- "cron_detached-worker",
- )
+ finalize.assert_called_once_with(fake_db, agent, "detached-worker", "detached worker", "cron_detached-worker")
+ teardown_agent.assert_called_once_with(agent, "detached-worker")
+ assert defer_teardown_to_running_worker(
+ future, fake_db, agent, "detached-worker", "detached worker", "cron_detached-worker") is False
def test_dispatch_guard_releases_after_sessiondb_finalization_hang(tmp_path):