Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(harness): keep the scheduler job id out of a cron enqueue (#1524)
Qi Qief9fef766028
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 4cf33948f..9b3b9105a 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -5825,6 +5825,23 @@ class ScheduledTaskService:await self._run_runtime_sync(self.store.load)self.reconcile_jobs()+ async def _reconcile_rejected_cron_fire(self, task_id: str) -> None:+ """Re-register the schedule after a cron generation's enqueue was refused."""++ # A refusal is either benign -- an earlier scheduler fire is still queued+ # -- or the stale-generation case this callback could not see: the mirror+ # read above may predate a cron -> ``at`` edit committed on another+ # connection, so the guard let the fire through and the storage CAS was+ # the layer that caught it. Only the second needs the scheduler, and only+ # this callback can ask for it: the cron job that keeps firing IS the+ # stale generation, so nothing else would install the DateTrigger. Force a+ # fresh mirror, then reconcile only when the definition is no longer the+ # cron this job was registered for.+ await self._run_runtime_sync(self.store.load)+ task = self.store.get_task(task_id)+ if task is None or task.schedule_type != "cron":+ self.reconcile_jobs()+async def _run_task(self,task_id: str,@@ -5844,14 +5861,32 @@ class ScheduledTaskService:if expected_run_at is not None:await self._reconcile_rejected_one_shot_fire(task_id)return- if expected_run_at is not None and (- task.schedule_type != "at"- or task.run_at != expected_run_at- or task.timezone != expected_timezone- or task.updated_at != expected_updated_at- ):- await self._reconcile_rejected_one_shot_fire(task_id)+ # The registration's own shape says what this callback fired for, and the+ # refreshed definition has to still be that thing. A one-shot must match+ # the exact schedule identity it registered. A cron registration must at+ # least still find a cron definition: enqueueing against a definition that+ # became a one-shot would spend a fire its run_at has not reached, and+ # would not retire it, so that same one-shot would run again later.+ if expected_run_at is not None:+ if (+ task.schedule_type != "at"+ or task.run_at != expected_run_at+ or task.timezone != expected_timezone+ or task.updated_at != expected_updated_at+ ):+ await self._reconcile_rejected_one_shot_fire(task_id)+ return+ elif expected_job_id is not None and task.schedule_type != "cron":+ # refresh_task above already consumed any invalidation; hand the+ # replacement schedule back to the scheduler that owns it.+ self.reconcile_jobs()return+ # Every registered job carries its APScheduler job id so the callback can+ # reject a stale generation above. Only a one-shot fire carries it further:+ # downstream the job id is one field of the schedule identity that retires+ # the definition, and the store requires that identity whole or absent. A+ # cron fire has no run_at, so it must not present a partial one.+ enqueue_job_id = expected_job_id if expected_run_at is not None else Nonetry:queued = await self._run_runtime_sync(self.request_store.enqueue_task_run,@@ -5862,7 +5897,7 @@ class ScheduledTaskService:expected_run_at=expected_run_at,expected_timezone=expected_timezone,expected_updated_at=expected_updated_at,- expected_job_id=expected_job_id,+ expected_job_id=enqueue_job_id,)except Exception as exc:if expected_run_at is None or expected_job_id is None:@@ -5892,6 +5927,8 @@ class ScheduledTaskService:self._wake_runtime_work(RuntimeWorkLane.REQUESTS)elif expected_run_at is not None:await self._reconcile_rejected_one_shot_fire(task_id)+ elif expected_job_id is not None:+ await self._reconcile_rejected_cron_fire(task_id)def _request_partition_key(self, request: TaskExecutionRequest) -> str:lock_key = self._execution_lock_key(request)diff --git a/storage/background.py b/storage/background.pyindex 26d5d2ce4..a508df1f3 100644--- a/storage/background.py+++ b/storage/background.py@@ -4028,9 +4028,16 @@ class SQLiteBackgroundTaskStore:# is stale and owns no enqueue at all.return Noneif scheduled_one_shot and expected_run_at is None:- raise ValueError(- "scheduler one-shot enqueue requires its expected run_at and timezone"- )+ # The mirror image of the branch above: an APScheduler cron+ # generation whose definition has since become a one-shot. It+ # carries no schedule identity, so nothing here could retire+ # the replacement -- enqueueing would spend a fire the new+ # run_at has not reached and leave that one-shot still armed.+ # A stale generation owns no enqueue, so reject rather than+ # raise: the only caller is a scheduler callback, where an+ # exception is swallowed by the executor and the definition+ # keeps no record of the fire at all.+ return Noneif (scheduled_one_shot and definition["retired_at"] is not None):diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex f42bff2c9..63f89d411 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -4355,6 +4355,33 @@ scenarios:# atomically records the runtime reservation while mismatched bound Runs stay# protected by the existing hard refusal.test: tests/test_internal_server.py::test_hfr_482_create_per_run_delivery_adopts_reserved_session+ - id: HFR-483+ name: a registered cron fire enqueues from its own scheduler arguments+ status: covered+ kind: regression+ layer: contract+ backend: shared+ # Every registered job carries its APScheduler job id for the stale-generation+ # guard, but only an at job carries a run_at. Firing the arguments the+ # scheduler actually registered proves a cron fire never presents the job id+ # as half of the one-shot schedule identity the enqueue requires whole.+ test: tests/test_scheduled_tasks.py::test_hfr_483_registered_job_fires_through_its_own_scheduler_arguments+ - id: HFR-484+ name: an in-flight cron fire cannot spend a replacement one-shot+ status: covered+ kind: concurrency+ layer: contract+ backend: shared+ # A cron registration carries no schedule identity, so a fire that races an+ # edit to at could spend a run_at the definition has not reached and leave it+ # armed. The callback rejects on a fresh mirror; the storage CAS is the+ # authority when the mirror lags. Either way the replacement schedule is+ # handed back to the scheduler, because the cron job that keeps firing is+ # itself the stale generation and nothing else would register the one-shot.+ # That reconcile is gated on the schedule having actually changed, so a fire+ # refused for a merely backlogged predecessor leaves its registration alone.+ # An edit that keeps the definition recurring still runs, at its refreshed value.+ test: tests/test_scheduled_tasks.py::test_hfr_484_in_flight_cron_fire_cannot_spend_a_replacement_one_shotmanual_evidence:- local Incus backend process death after prompt acceptance- local Incus controller restart with persisted queued successordiff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 6c1993997..d75c4a3a0 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -130,7 +130,9 @@ class _StubScheduler:return self.jobs.get(job_id)def add_job(self, func, trigger, id, replace_existing, coalesce, max_instances, args):- self.jobs[id] = SimpleNamespace(id=id, trigger=trigger, args=args)+ # ``func`` is retained so a test can fire a registered job exactly the way+ # APScheduler does: ``await job.func(*job.args)``.+ self.jobs[id] = SimpleNamespace(id=id, func=func, trigger=trigger, args=args)def remove_job(self, job_id):self.jobs.pop(job_id, None)@@ -11210,6 +11212,261 @@ def test_hfr_477_stale_scheduler_enqueue_cannot_consume_a_replacement_generationassert store.refresh_task(task.id).schedule_type == "cron"[email protected]("schedule", ["cron", "at"])+def test_hfr_483_registered_job_fires_through_its_own_scheduler_arguments(+ tmp_path: Path,+ monkeypatch,+ schedule: str,+) -> None:+ """HFR-483 -- every registered schedule enqueues from the args it registered.++ ``reconcile_jobs`` gives every job its APScheduler job id so the callback can+ reject a stale generation, but only an ``at`` job carries a run_at. Firing the+ registered arguments -- rather than a hand-built call -- is what proves a cron+ job never presents the job id as half of a one-shot schedule identity.+ """++ _binding_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ run_at = (+ (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()+ if schedule == "at"+ else None+ )+ task = store.add_task(+ session_key="",+ prompt="daily digest",+ schedule_type=schedule,+ cron="0 11 * * *" if schedule == "cron" else None,+ run_at=run_at,+ timezone_name="UTC",+ session_policy="create_per_run",+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=TaskExecutionStore(),+ )+ service.scheduler = _StubScheduler()+ service.reconcile_jobs()++ jobs = service.scheduler.get_jobs()+ assert len(jobs) == 1+ job = jobs[0]+ assert job.args[0] == task.id+ assert job.args[4] == job.id+ if schedule == "cron":+ assert job.id == task.id+ assert tuple(job.args[1:4]) == (None, None, None)+ else:+ assert tuple(job.args[1:4]) == (run_at, "UTC", task.updated_at)++ asyncio.run(job.func(*job.args))++ pending = service.request_store.list_pending()+ assert [(request.task_id, request.source_kind) for request in pending] == [+ (task.id, "scheduler")+ ]+ refreshed = store.refresh_task(task.id)+ assert refreshed is not None+ if schedule == "cron":+ # A recurring definition survives its own fire; only a one-shot is consumed.+ assert refreshed.enabled is True+ assert refreshed.retired_at is None+ else:+ assert refreshed.enabled is False+ assert refreshed.retired_at is not None++[email protected]("mirror", ["fresh", "stale"])+def test_hfr_484_in_flight_cron_fire_cannot_spend_a_replacement_one_shot(+ tmp_path: Path,+ monkeypatch,+ mirror: str,+) -> None:+ """HFR-484 -- a cron callback that races an edit to ``at`` enqueues nothing.++ A cron registration carries no schedule identity, so nothing downstream could+ retire the replacement. Enqueueing would spend a fire the new run_at has not+ reached and leave that one-shot still armed to run a second time.++ Both layers are exercised because ``refresh_task`` is a mirror read and can+ legitimately lag a writer on another connection (HFR-277). ``fresh`` rejects+ in the callback; ``stale`` falls through to the storage CAS, which is the+ real authority. Both must end with the replacement schedule registered.+ """++ _binding_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ prompt="daily digest",+ schedule_type="cron",+ cron="0 11 * * *",+ timezone_name="UTC",+ session_policy="create_per_run",+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=TaskExecutionStore(),+ )+ service.scheduler = _StubScheduler()+ service.reconcile_jobs()+ cron_job = service.scheduler.get_job(task.id)+ assert cron_job is not None++ writer = store if mirror == "fresh" else ScheduledTaskStore()+ run_at = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()+ replacement = writer.update_task(+ task.id,+ name=task.name,+ session_key=task.session_key,+ session_id=task.session_id,+ prompt=task.prompt,+ schedule_type="at",+ post_to=task.post_to,+ deliver_key=task.deliver_key,+ cron=None,+ run_at=run_at,+ timezone_name="UTC",+ agent_name=task.agent_name,+ session_policy=task.session_policy,+ )++ # The already-dispatched cron callback still carries the cron registration.+ asyncio.run(cron_job.func(*cron_job.args))++ assert service.request_store.list_pending() == []+ refreshed = ScheduledTaskStore().get_task(task.id)+ assert refreshed is not None+ assert refreshed.enabled is True+ assert refreshed.retired_at is None+ assert refreshed.run_at == run_at+ # Either way the rejected fire hands the replacement schedule back to the+ # scheduler. Nothing else can: the cron job that keeps firing IS the stale+ # generation, so a rejection that left it installed would strand the+ # one-shot -- unregistered, and never fired.+ jobs = service.scheduler.get_jobs()+ assert len(jobs) == 1+ assert tuple(jobs[0].args[1:4]) == (run_at, "UTC", replacement.updated_at)+++def test_hfr_484_cron_fire_runs_the_definition_current_at_fire_time(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """HFR-484 -- a cron fire racing a benign edit runs the refreshed definition.++ ``refresh_task`` is deliberate: a recurring schedule has no fire to spend, so+ the useful reading of "run this definition now" is the definition as it stands+ at fire time. This is the counterpart to the rejection above -- an edit that+ keeps the definition recurring must not silently drop the fire.+ """++ _binding_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ prompt="original prompt",+ schedule_type="cron",+ cron="0 11 * * *",+ timezone_name="UTC",+ session_policy="create_per_run",+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=TaskExecutionStore(),+ )+ service.scheduler = _StubScheduler()+ service.reconcile_jobs()+ cron_job = service.scheduler.get_job(task.id)+ assert cron_job is not None++ writer = ScheduledTaskStore()+ writer.update_task(+ task.id,+ name=task.name,+ session_key=task.session_key,+ session_id=task.session_id,+ prompt="edited prompt",+ schedule_type="cron",+ post_to=task.post_to,+ deliver_key=task.deliver_key,+ cron="0 11 * * *",+ run_at=None,+ timezone_name="UTC",+ agent_name=task.agent_name,+ session_policy=task.session_policy,+ )++ asyncio.run(cron_job.func(*cron_job.args))++ pending = service.request_store.list_pending()+ assert [(request.task_id, request.prompt) for request in pending] == [+ (task.id, "edited prompt")+ ]+ refreshed = store.refresh_task(task.id)+ assert refreshed is not None+ assert refreshed.enabled is True+ assert refreshed.retired_at is None+++def test_hfr_484_backlogged_cron_fire_leaves_its_own_registration_alone(+ tmp_path: Path,+ monkeypatch,+) -> None:+ """HFR-484 -- a refused cron fire only reconciles when the schedule changed.++ Successor suppression refuses a fire whose predecessor has not started yet,+ and that refusal looks exactly like the stale-generation one at the callback.+ Reconciling on every refusal would re-register a live cron job -- and reset+ its next fire -- each time the queue is merely backed up, so the reconcile+ is gated on the reloaded definition no longer being that cron.+ """++ _binding_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ prompt="daily digest",+ schedule_type="cron",+ cron="0 11 * * *",+ timezone_name="UTC",+ session_policy="create_per_run",+ )+ service = ScheduledTaskService(+ controller=SimpleNamespace(platform_settings_managers={}),+ store=store,+ request_store=TaskExecutionStore(),+ )+ service.scheduler = _StubScheduler()+ service.reconcile_jobs()+ cron_job = service.scheduler.get_job(task.id)+ assert cron_job is not None++ # The predecessor fire is queued and unstarted, so the next one is refused.+ service.request_store.enqueue_task_run(+ task.id,+ source_kind="scheduler",+ task=task,+ suppress_scheduler_successor=True,+ )+ reconciled = 0++ def _count_reconcile() -> None:+ nonlocal reconciled+ reconciled += 1++ monkeypatch.setattr(service, "reconcile_jobs", _count_reconcile)++ asyncio.run(cron_job.func(*cron_job.args))++ assert reconciled == 0+ assert len(service.request_store.list_pending()) == 1++def test_hfr_477_consumed_terminal_outcome_belongs_to_the_consuming_run(tmp_path: Path,monkeypatch,