Skip to content

The agent that grows with you

fix(cron): deliver completed self-removing runs

KoNit-K31b400116789
diff --git a/cron/jobs.py b/cron/jobs.py
index 5894a56fb31..7d28d7b529b 100644
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@ -112,6 +112,35 @@ class _CronStorePaths:
_cron_store_override: ContextVar[Optional[_CronStorePaths]] = ContextVar(
"cron_store_override", default=None)
+
+class _SelfRemovalDelivery:
+ """Mutable run-local marker shared with the agent's copied ContextVar context."""
+
+ def __init__(self, job_id: str):
+ self.job_id = job_id
+ self.removed = False
+
+
+_self_removal_delivery: ContextVar[Optional[_SelfRemovalDelivery]] = ContextVar(
+ "self_removal_delivery", default=None)
+
+
+def self_removal_delivery_scope(job_id: str):
+ """Permit this run's final delivery after it removes its own job record."""
+ marker = _SelfRemovalDelivery(job_id)
+ token = _self_removal_delivery.set(marker)
+ try:
+ yield marker
+ finally:
+ _self_removal_delivery.reset(token)
+
+
+def self_removal_delivery_allowed(job_id: str) -> bool:
+ """Whether the active run deleted exactly its own job record."""
+ marker = _self_removal_delivery.get()
+ return bool(marker is not None and marker.job_id == job_id and marker.removed)
+
# Import-time snapshot so deliberate re-pointing of CRON_DIR/JOBS_FILE/OUTPUT_DIR (the documented
# escape hatch for tests/embedders) is distinguishable from the constants merely being stale.
_IMPORT_STORE = _CronStorePaths(CRON_DIR, JOBS_FILE, OUTPUT_DIR)
@@ -353,8 +382,11 @@ def _under_fire_fence(job_id: str, fn: Callable[[], Any]) -> Any:
@contextlib.contextmanager
-def fire_claim_fence(job_id: str, *, expected_owner: str):
- """Hold a per-job fence while an owner performs an external side effect."""
+def fire_claim_fence(job_id: str, *, expected_owner: str, allow_self_removed: bool = False):
+ """Hold a per-job fence while an owner performs an external side effect.
+
+ A missing record is accepted only for the active run that removed this exact job.
+ """
with _fire_job_lock(job_id) as acquired:
if not acquired:
yield False
@@ -363,6 +395,8 @@ def fire_claim_fence(job_id: str, *, expected_owner: str):
job = next((item for item in load_jobs() if item.get("id") == job_id), None)
claim = job.get("fire_claim") if isinstance(job, dict) else None
owns_claim = isinstance(claim, dict) and claim.get("by") == expected_owner
+ if not owns_claim and job is None and allow_self_removed:
+ owns_claim = self_removal_delivery_allowed(job_id)
yield owns_claim
@@ -2255,6 +2289,9 @@ def remove_job(job_id: str) -> bool:
# Resolve BEFORE saving so a legacy unsafe ID fails closed without a half-applied removal.
job_output_dir = _job_output_dir(canonical_id)
save_jobs(jobs, removed_ids={canonical_id})
+ marker = _self_removal_delivery.get()
+ if marker is not None and marker.job_id == canonical_id:
+ marker.removed = True
if job_output_dir.exists():
shutil.rmtree(job_output_dir)
try:
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 23f0c4a0ede..21f1496ebe5 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -476,7 +476,7 @@ def _resolve_job_reasoning_config(job: dict, cfg: dict, model: str) -> dict | No
from cron.jobs import (
_ensure_cron_dir, advance_next_runs, claim_dispatch, claim_job_for_fire, fire_claim_fence,
clear_run_claim, get_due_jobs, heartbeat_fire_claim, heartbeat_run_claim, mark_job_run,
- save_job_output, use_cron_store)
+ save_job_output, self_removal_delivery_allowed, self_removal_delivery_scope, use_cron_store)
from cron.executions import (
_TERMINAL_STATES, HANDOFF_ADOPTION_GRACE_SECONDS, create_execution, finish_execution,
get_execution, mark_execution_handoff_pending, mark_execution_running,
@@ -2521,20 +2521,21 @@ def run_one_job(
_running_fire_owners.setdefault(job["id"], {})[execution_token] = (
fire_owner or None, profile_home)
try:
- return _run_with_fire_claim_heartbeat(
- job,
- lambda lost_ownership: _run_one_job_body(
+ with self_removal_delivery_scope(job["id"]):
+ return _run_with_fire_claim_heartbeat(
job,
- adapters=adapters,
- loop=loop,
- verbose=verbose,
- extra_prompt=extra_prompt,
- fire_claim_lost=(
- _CombinedCancelEvent(lost_ownership, cancel_event)
- if cancel_event is not None
- else lost_ownership
- ),
- execution_token=execution_token))
+ lambda lost_ownership: _run_one_job_body(
+ job,
+ adapters=adapters,
+ loop=loop,
+ verbose=verbose,
+ extra_prompt=extra_prompt,
+ fire_claim_lost=(
+ _CombinedCancelEvent(lost_ownership, cancel_event)
+ if cancel_event is not None
+ else lost_ownership
+ ),
+ execution_token=execution_token))
finally:
with _running_lock:
executions = _running_fire_owners.get(job["id"])
@@ -2634,13 +2635,18 @@ class _FireOwnership:
def side_effect_fence(self):
if self.owner is None:
return contextlib.nullcontext(True)
- return fire_claim_fence(self.job["id"], expected_owner=self.owner)
+ return fire_claim_fence(
+ self.job["id"], expected_owner=self.owner,
+ allow_self_removed=self_removal_delivery_allowed(self.job["id"]),
+ )
def lost(self) -> bool:
if self.fire_claim_lost is not None and self.fire_claim_lost.is_set():
return True
if self.owner is None:
return False
+ if self_removal_delivery_allowed(self.job["id"]):
+ return False
try:
if heartbeat_fire_claim(self.job["id"], expected_owner=self.owner):
return False
@@ -2788,7 +2794,7 @@ def _finish_completed_run(d: _RunDelivery, fire_owner: Optional[str], execution_
if d.blocked_config:
mark_kwargs["status"] = "blocked_config"
marked = mark_job_run(job["id"], d.success, d.error, **mark_kwargs)
- if fire_owner is not None and not marked:
+ if fire_owner is not None and not marked and not self_removal_delivery_allowed(job["id"]):
finish_execution(
execution_id, success=False,
error="Fire claim ownership lost before terminal completion.")
diff --git a/tests/cron/test_script_claim_heartbeat.py b/tests/cron/test_script_claim_heartbeat.py
index 4cde43b3813..79a4bfb7798 100644
--- a/tests/cron/test_script_claim_heartbeat.py
+++ b/tests/cron/test_script_claim_heartbeat.py
@@ -418,6 +418,42 @@ def test_lost_fire_claim_stops_stale_delivery(monkeypatch):
mark_run.assert_not_called()
+def test_self_removed_job_still_delivers_its_completed_response(tmp_path, monkeypatch):
+ """Removing itself during a run releases its record, not this run's final response."""
+ import cron.jobs as jobs
+ import cron.scheduler as scheduler
+
+ def _run_job(job, **_kwargs):
+ assert jobs.remove_job(job["id"])
+ return True, "saved output", "final response", None
+
+ delivered = MagicMock(return_value=None)
+ finished = MagicMock()
+ monkeypatch.setattr(scheduler, "run_job", _run_job)
+ monkeypatch.setattr(scheduler, "claim_dispatch", lambda *_args: True)
+ monkeypatch.setattr(scheduler, "mark_execution_running", lambda *_args: {})
+ monkeypatch.setattr(scheduler, "finish_execution", finished)
+ monkeypatch.setattr(scheduler, "save_job_output", lambda *_args: "output.md")
+ monkeypatch.setattr(scheduler, "_deliver_result", delivered)
+
+ with jobs.use_cron_store(tmp_path):
+ job = jobs.create_job(
+ prompt="work", schedule="every 5m", name="remove self", deliver="telegram")
+ assert jobs.claim_job_for_fire(job["id"])
+ claimed = jobs.get_job(job["id"])
+ claimed["execution_id"] = "self-removal-execution"
+
+ with patch("agent.secret_scope.set_secret_scope", return_value=None), \
+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None), \
+ patch("agent.secret_scope.reset_secret_scope"):
+ assert scheduler.run_one_job(claimed) is True
+
+ delivered.assert_called_once()
+ finished.assert_called_once_with(
+ "self-removal-execution", success=True, error=None, delivery_outcome="delivered")
+ assert jobs.get_job(job["id"]) is None
+
+
def test_initially_lost_fire_claim_finishes_execution_without_running(monkeypatch):
"""A stale claimed snapshot rejected before body entry must close its ledger row."""
import cron.scheduler as scheduler