From 9031a86a1488849bf96b10d885efbeea8610f623 Mon Sep 17 00:00:00 2001 From: raymondginger2018-sudo Date: Fri, 27 Nov 2026 21:58:59 +0800 Subject: [PATCH] feat(schedule): gate spend on progress, spend only after writeback Two optional control-plane layers on top of the keepalive scheduler, both inert by default so existing callers behave exactly as before: - SpendGate is asked before each turn and adds the signal the continuation gate cannot see: a brake on runs that reported no progress (RunOutcome.progress_made is False). Fail-closed: an unset field never defaults to "run". - run_turn orders one turn as execute -> typed result -> validation -> durable writeback -> spend, so quota is never spent on a turn that did not write back. Asking for spend without a writeback raises instead of silently spending. - core/schedule/should_run.py (new): ShouldRunDecision + SpendGate - core/schedule/turn_transaction.py (new): TurnReceipt + run_turn - core/schedule/scheduler.py: consult the gate between runs - core/schedule/__init__.py: export both layers - tests/test_schedule.py: 23 cases (11 gate, 7 transaction, 3 scheduler) --- core/schedule/__init__.py | 32 ++- core/schedule/scheduler.py | 101 +++++++- core/schedule/should_run.py | 184 ++++++++++++++ core/schedule/turn_transaction.py | 159 ++++++++++++ tests/test_schedule.py | 387 +++++++++++++++++++++++++++++- 5 files changed, 852 insertions(+), 11 deletions(-) create mode 100644 core/schedule/should_run.py create mode 100644 core/schedule/turn_transaction.py diff --git a/core/schedule/__init__.py b/core/schedule/__init__.py index 63eb7b5df..6e014bcec 100644 --- a/core/schedule/__init__.py +++ b/core/schedule/__init__.py @@ -1,18 +1,42 @@ """Scheduling & keepalive (P3) — run loops repeatedly, safely. -Two pieces: +Four pieces: - :mod:`core.schedule.keepalive` — the *continuation gate* (ClawTeam's lesson): a long-horizon job continues only when it exited cleanly AND has not reached its goal AND is under its run cap. This is what prevents both premature death (stopping while there's still work) and runaway (looping forever). +- :mod:`core.schedule.should_run` — the *pre-turn spend gate* (2026-09-19): a + typed, fail-closed decision envelope that adds the signal the continuation + gate cannot see — whether the recent runs bought any progress at all. +- :mod:`core.schedule.turn_transaction` — the *turn transaction* (2026-09-19): + orders one turn as execute → typed result → validation → durable writeback → + spend, so quota is never spent on a turn that did not write back. - :mod:`core.schedule.scheduler` — a minimal interval runner that invokes a - task and consults the gate between runs (self-wakeup / keepalive), with an + task and consults the gates between runs (self-wakeup / keepalive), with an injectable clock/sleep so it is deterministically testable. """ from core.schedule.keepalive import Continuation, ContinuationDecision -from core.schedule.scheduler import run_scheduled +from core.schedule.scheduler import RunOutcome, run_scheduled +from core.schedule.should_run import ShouldRunDecision, SpendGate +from core.schedule.turn_transaction import ( + PHASES, + TurnReceipt, + ValidationResult, + run_turn, +) -__all__ = ["Continuation", "ContinuationDecision", "run_scheduled"] +__all__ = [ + "PHASES", + "Continuation", + "ContinuationDecision", + "RunOutcome", + "ShouldRunDecision", + "SpendGate", + "TurnReceipt", + "ValidationResult", + "run_scheduled", + "run_turn", +] diff --git a/core/schedule/scheduler.py b/core/schedule/scheduler.py index a3583b18e..511f26785 100644 --- a/core/schedule/scheduler.py +++ b/core/schedule/scheduler.py @@ -5,15 +5,31 @@ the whole self-wakeup behavior is deterministically testable without real wall-clock waits — and a runaway is impossible because the gate's ``max_runs`` always bounds the loop. + +Two optional control-plane layers sit on top (2026-09-19), both **inert by +default** so existing callers behave exactly as before: + +- ``spend_gate`` (:class:`core.schedule.should_run.SpendGate`) is asked *before* + each turn. It adds the one signal the keepalive gate cannot see: a brake on + runs that report no progress (``RunOutcome.progress_made is False``). +- ``writeback`` / ``spend`` route every turn through + :func:`core.schedule.turn_transaction.run_turn`, which enforces that quota is + spent only after a validated, durable writeback. Asking for ``spend`` without + a ``writeback`` raises rather than quietly spending. + +See docs/2026-09-19_调研-LOOPX与DEEPCODE适配评估-report.md for the contracts +these two layers mirror. """ from __future__ import annotations import asyncio +from collections.abc import Awaitable, Callable from dataclasses import dataclass -from typing import Awaitable, Callable from core.schedule.keepalive import Continuation +from core.schedule.should_run import ShouldRunDecision, SpendGate +from core.schedule.turn_transaction import TurnReceipt, ValidationResult, run_turn @dataclass @@ -23,11 +39,36 @@ class RunOutcome: goal_reached: bool clean_exit: bool = True detail: str = "" + # Progress is what the *task* can honestly claim; ``None`` means "not + # reported" and is treated as neither progress nor stagnation. + progress_made: bool | None = None # A task receives the 0-based run index and returns its outcome. ScheduledTask = Callable[[int], Awaitable[RunOutcome]] RunHook = Callable[[int, RunOutcome], None] +TurnHook = Callable[[int, RunOutcome], Awaitable[None]] +DecisionHook = Callable[[ShouldRunDecision], None] + + +async def _run_one_turn( + task: ScheduledTask, + *, + runs: int, + validate: Callable[[RunOutcome], Awaitable[ValidationResult]] | None, + writeback: TurnHook | None, + spend: TurnHook | None, +) -> TurnReceipt: + """One turn through the transaction; hooks see the 1-based run number.""" + turn_no = runs + 1 + return await run_turn( + execute=lambda: task(runs), + validate=validate, + writeback=None + if writeback is None + else lambda outcome: writeback(turn_no, outcome), + spend=None if spend is None else lambda outcome: spend(turn_no, outcome), + ) async def run_scheduled( @@ -37,24 +78,74 @@ async def run_scheduled( gate: Continuation, sleep: Callable[[float], Awaitable[None]] = asyncio.sleep, on_run: RunHook | None = None, + spend_gate: SpendGate | None = None, + validate: Callable[[RunOutcome], Awaitable[ValidationResult]] | None = None, + writeback: TurnHook | None = None, + spend: TurnHook | None = None, + on_decision: DecisionHook | None = None, ) -> list[RunOutcome]: """Run ``task`` repeatedly until the keepalive gate closes. A task that raises is recorded as an unclean exit (the gate then stops — a crash is not blindly retried). Returns the outcome of every run. + + When ``spend_gate`` is given it may close the loop *before* the next turn; + ``on_decision`` sees every decision, including the refusal that stopped it. + When ``writeback``/``spend`` are given, each turn goes through the turn + transaction, so a failed writeback means the spend hook never fires. """ + if spend is not None and writeback is None: + raise ValueError( + "run_scheduled: `spend` requires `writeback` — quota is only spent " + "after a durable writeback (see core.schedule.turn_transaction)" + ) + outcomes: list[RunOutcome] = [] runs = 0 + stagnant = 0 + last_clean_exit = True + last_goal_reached = False + while True: - try: - outcome = await task(runs) - except Exception as exc: # noqa: BLE001 - a crash is an unclean exit, not fatal - outcome = RunOutcome(False, clean_exit=False, detail=str(exc)) + if spend_gate is not None: + decision = spend_gate.should_run( + runs_done=runs, + clean_exit=last_clean_exit, + goal_reached=last_goal_reached, + stagnant_runs=stagnant, + ) + if on_decision is not None: + on_decision(decision) + if not decision.should_run: + break + + receipt = await _run_one_turn( + task, runs=runs, validate=validate, writeback=writeback, spend=spend + ) + if receipt.executed and isinstance(receipt.result, RunOutcome): + outcome = receipt.result + else: + # A crashed turn, or a task that did not return a RunOutcome: both + # are unclean exits, which the keepalive gate already refuses to + # retry blindly. + outcome = RunOutcome( + False, + clean_exit=False, + detail=receipt.reason or "task did not return a RunOutcome", + ) + runs += 1 outcomes.append(outcome) if on_run is not None: on_run(runs, outcome) + last_clean_exit = outcome.clean_exit + last_goal_reached = outcome.goal_reached + if outcome.progress_made is False: + stagnant += 1 + elif outcome.progress_made is True: + stagnant = 0 + decision = gate.should_continue( runs_done=runs, clean_exit=outcome.clean_exit, diff --git a/core/schedule/should_run.py b/core/schedule/should_run.py new file mode 100644 index 000000000..5809b6a7b --- /dev/null +++ b/core/schedule/should_run.py @@ -0,0 +1,184 @@ +"""Pre-turn spend gate (P0) — a typed, fail-closed decision envelope. + +The keepalive gate (:mod:`core.schedule.keepalive`) answers *may I go again?* +from three signals: clean exit, goal reached, run cap. It cannot answer the +question a long-horizon loop actually burns money on: **is there any useful +state transition left to buy?** A loop that exits cleanly every single time and +never reaches its goal passes the keepalive gate until the cap runs out — that +is exactly the shape of the 2026-09 compaction incident, where every turn +"succeeded" while the context grew monotonically (~330M prompt tokens). + +This gate closes that hole the way LoopX's ``quota should-run`` does +(primary source: docs/2026-09-19_调研-LOOPX与DEEPCODE适配评估-report.md §6.3): + +- the answer is a **typed envelope** — ``decision`` / ``state`` / ``reason`` / + ``recommended_action`` — so a caller never parses prose to decide; +- it is **fail-closed**: missing, negative or contradictory input yields + ``should_run=False``. There is no input combination that defaults to "run"; +- a *refusal* is a first-class outcome carrying the same fields as an approval. + +Honest limit: the progress clause refuses only on **evidence** of stagnation — +``stagnant_runs`` counted by the caller from a real signal. A caller with no +progress signal passes 0, and the loop falls back to the run cap. This gate +never upgrades a guess into permission, nor into a refusal. + +Not here on purpose: quota accounting, leases, writeback. Those belong to the +turn transaction (:mod:`core.schedule.turn_transaction`). +""" + +from __future__ import annotations + +from dataclasses import dataclass + +# The envelope's states. ``ready`` is the only one that permits a run; the rest +# name *why* the loop stopped, and each maps to a different operator action. +STATE_READY = "ready" +STATE_COMPLETE = "complete" +STATE_EXHAUSTED = "exhausted" +STATE_NO_PROGRESS = "blocked_no_progress" +STATE_UNHEALTHY = "blocked_health" +STATE_INVALID = "blocked_validation" + + +@dataclass(frozen=True) +class ShouldRunDecision: + """The typed answer to "may this loop spend another turn?".""" + + should_run: bool + decision: str + state: str + reason: str + recommended_action: str + waiting_on: str | None = None + runs_done: int | None = None + + def as_dict(self) -> dict[str, object]: + """Flat dict for logs/ledgers — same shape as LoopX's JSON envelope.""" + return { + "decision": self.decision, + "should_run": self.should_run, + "state": self.state, + "reason": self.reason, + "recommended_action": self.recommended_action, + "waiting_on": self.waiting_on, + "runs_done": self.runs_done, + } + + +def _deny( + state: str, + reason: str, + recommended_action: str, + runs_done: int, + waiting_on: str | None, +) -> ShouldRunDecision: + return ShouldRunDecision( + should_run=False, + decision="skip", + state=state, + reason=reason, + recommended_action=recommended_action, + waiting_on=waiting_on, + runs_done=runs_done, + ) + + +@dataclass(frozen=True) +class SpendGate: + """Permission gate consulted *before* each turn. + + ``max_runs`` is the same hard runaway backstop the keepalive gate uses. + ``max_stagnant_runs`` is the new brake: stop after N consecutive runs that + reported no progress. ``0`` disables the brake (the default) so existing + callers keep their exact behavior until they opt in. + """ + + max_runs: int = 24 + max_stagnant_runs: int = 0 + + def should_run( + self, + *, + runs_done: int, + clean_exit: bool, + goal_reached: bool, + stagnant_runs: int = 0, + waiting_on: str | None = None, + ) -> ShouldRunDecision: + """Decide whether the next turn may run. + + Precedence is deliberate: unreadable input, then done, then unhealthy, + then out of budget, then stalled, then run. + """ + if ( + runs_done < 0 + or stagnant_runs < 0 + or self.max_runs < 0 + or self.max_stagnant_runs < 0 + ): + return _deny( + STATE_INVALID, + ( + "invalid counters " + f"(runs_done={runs_done}, stagnant_runs={stagnant_runs}, " + f"max_runs={self.max_runs}, max_stagnant_runs={self.max_stagnant_runs})" + ), + "fix the caller's bookkeeping before spending another turn", + runs_done, + waiting_on, + ) + + if not clean_exit and goal_reached: + return _deny( + STATE_INVALID, + "contradictory outcome: goal reached on a run that did not exit cleanly", + "re-check how the run outcome was recorded", + runs_done, + waiting_on, + ) + + if goal_reached: + return _deny( + STATE_COMPLETE, + "goal reached", + "stop scheduling this goal", + runs_done, + waiting_on, + ) + + if not clean_exit: + return _deny( + STATE_UNHEALTHY, + "previous run did not exit cleanly", + "inspect the crash before spending another turn", + runs_done, + waiting_on, + ) + + if runs_done >= self.max_runs: + return _deny( + STATE_EXHAUSTED, + f"reached run cap ({self.max_runs})", + "raise the run cap, or replan the goal", + runs_done, + waiting_on, + ) + + if self.max_stagnant_runs and stagnant_runs >= self.max_stagnant_runs: + return _deny( + STATE_NO_PROGRESS, + f"no progress for {stagnant_runs} consecutive run(s)", + "replan, or ask the owner a concrete question and wait", + runs_done, + waiting_on or "owner", + ) + + return ShouldRunDecision( + should_run=True, + decision="run", + state=STATE_READY, + reason="healthy, under the run cap, progress not exhausted", + recommended_action="spend the turn", + waiting_on=waiting_on, + runs_done=runs_done, + ) diff --git a/core/schedule/turn_transaction.py b/core/schedule/turn_transaction.py new file mode 100644 index 000000000..ce9b861c2 --- /dev/null +++ b/core/schedule/turn_transaction.py @@ -0,0 +1,159 @@ +"""Turn transaction (P1) — spend only after a validated durable writeback. + +LoopX's turn contract (primary source: ``loopx/control_plane/ +turn_transaction_contract.json``, schema ``loopx_turn_transaction_contract_v0``) +names seven phases:: + + host_execute → typed_result → validation → durable_writeback + → quota_spend → scheduler_apply → scheduler_ack + +DEEPCODE has no scheduler_apply/ack split yet, so this module implements the +first five — the part that protects money. The ordering *is* the feature: + +**quota is spent only after the turn's result has been validated and durably +written back.** A crash, an untyped result, a validation failure or a failed +writeback all end the turn *before* the spend phase. + +Why this matters here specifically: the 2026-09 compaction incident burned +~330M prompt tokens because a turn could "succeed" every time while nothing +durable changed. "No progress, no spend" stated as an ordering invariant is +what makes that impossible to repeat silently. A spend failure is *not* rolled +back either — durable work stays durable; only the meter is left unsettled. + +The four callables are injected and async, matching the async loop that drives +them, so the contract is testable without a host, a clock or a quota service — +the same convention :mod:`core.schedule.scheduler` uses for its sleep function. +""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TypeVar + +# The phase names, in the order the contract requires them to happen. +PHASES: tuple[str, ...] = ( + "host_execute", + "typed_result", + "validation", + "durable_writeback", + "quota_spend", +) + +_T = TypeVar("_T") + + +@dataclass(frozen=True) +class ValidationResult: + """Whether a turn's result is well-formed enough to be written back.""" + + ok: bool + reason: str = "" + + +@dataclass(frozen=True) +class TurnReceipt: + """What actually happened, in order. ``spent`` is the headline field.""" + + phases: tuple[str, ...] + outcome: str + executed: bool = False + validated: bool = False + written_back: bool = False + spent: bool = False + reason: str = "" + # The executed result, passed through for the caller's own use. Untyped on + # purpose: it is a dynamic pass-through, not a contract this module reads. + result: object | None = None + + +async def run_turn( + *, + execute: Callable[[], Awaitable[_T]], + validate: Callable[[_T], Awaitable[ValidationResult]] | None = None, + writeback: Callable[[_T], Awaitable[None]] | None = None, + spend: Callable[[_T], Awaitable[None]] | None = None, +) -> TurnReceipt: + """Run one turn under the writeback-before-spend ordering. + + ``validate`` defaults to accepting (no validator = the host asserts its own + result is typed); ``writeback``/``spend`` default to absent, in which case + the turn stops before the phase that has no hook. Asking to ``spend`` + without a ``writeback`` is a wiring error and raises instead of quietly + spending. + """ + if spend is not None and writeback is None: + raise ValueError( + "spend requires a writeback: quota is only spent after a durable writeback" + ) + + phases: list[str] = ["host_execute"] + try: + result = await execute() + except Exception as exc: # noqa: BLE001 - a crashed turn is a typed outcome + return TurnReceipt(tuple(phases), "execute_failed", reason=str(exc)) + + phases.append("typed_result") + phases.append("validation") + if validate is not None: + verdict = await validate(result) + if not verdict.ok: + return TurnReceipt( + tuple(phases), + "invalid_result", + executed=True, + reason=verdict.reason, + result=result, + ) + + if writeback is None: + return TurnReceipt( + tuple(phases), "no_writeback", executed=True, validated=True, result=result + ) + + phases.append("durable_writeback") + try: + await writeback(result) + except Exception as exc: # noqa: BLE001 - a failed writeback blocks the spend + return TurnReceipt( + tuple(phases), + "writeback_failed", + executed=True, + validated=True, + reason=str(exc), + result=result, + ) + + if spend is None: + return TurnReceipt( + tuple(phases), + "spend_skipped", + executed=True, + validated=True, + written_back=True, + result=result, + ) + + phases.append("quota_spend") + try: + await spend(result) + except Exception as exc: # noqa: BLE001 - the writeback stands; the meter did not + return TurnReceipt( + tuple(phases), + "spend_failed", + executed=True, + validated=True, + written_back=True, + reason=str(exc), + result=result, + ) + + return TurnReceipt( + tuple(phases), + "spent", + executed=True, + validated=True, + written_back=True, + spent=True, + result=result, + ) diff --git a/tests/test_schedule.py b/tests/test_schedule.py index f85cbcc56..6541a03a4 100644 --- a/tests/test_schedule.py +++ b/tests/test_schedule.py @@ -1,4 +1,9 @@ -"""Tests for the keepalive gate + interval scheduler (deterministic).""" +"""Tests for the keepalive gate + interval scheduler (deterministic). + +Also covers the two control-plane pieces added 2026-09-19 +(``should_run`` pre-turn gate, ``turn_transaction`` writeback-before-spend +ordering) — see docs/2026-09-19_调研-LOOPX与DEEPCODE适配评估-report.md. +""" from __future__ import annotations @@ -14,6 +19,12 @@ from core.schedule.keepalive import Continuation # noqa: E402 from core.schedule.scheduler import RunOutcome, run_scheduled # noqa: E402 +from core.schedule.should_run import SpendGate # noqa: E402 +from core.schedule.turn_transaction import ( # noqa: E402 + PHASES, + ValidationResult, + run_turn, +) # -- gate -------------------------------------------------------------------- @@ -105,6 +116,376 @@ async def task(i): assert slept == [5.0] # slept once, between run 1 and run 2 (not after the last) +# -- pre-turn spend gate (P0) ------------------------------------------------- +# +# LoopX's `quota should-run` semantics, reduced to what a DEEPCODE loop can +# actually know: the answer is a *typed envelope*, and every path that is not +# provably healthy / exhausted / stagnant is a refusal. + + +def test_spend_gate_allows_a_healthy_run(): + d = SpendGate(max_runs=10).should_run( + runs_done=0, clean_exit=True, goal_reached=False + ) + assert d.should_run and d.decision == "run" and d.state == "ready" + + +def test_spend_gate_stops_when_goal_reached(): + d = SpendGate(max_runs=10).should_run( + runs_done=2, clean_exit=True, goal_reached=True + ) + assert not d.should_run and d.state == "complete" and d.decision == "skip" + + +def test_spend_gate_stops_on_unclean_exit(): + d = SpendGate(max_runs=10).should_run( + runs_done=1, clean_exit=False, goal_reached=False + ) + assert not d.should_run and d.state == "blocked_health" + + +def test_spend_gate_stops_at_run_cap(): + d = SpendGate(max_runs=3).should_run( + runs_done=3, clean_exit=True, goal_reached=False + ) + assert not d.should_run and d.state == "exhausted" + + +def test_spend_gate_stops_on_stagnation(): + d = SpendGate(max_runs=10, max_stagnant_runs=3).should_run( + runs_done=3, clean_exit=True, goal_reached=False, stagnant_runs=3 + ) + assert not d.should_run and d.state == "blocked_no_progress" + # A stalled loop needs an owner decision, not another automatic turn. + assert d.waiting_on == "owner" + assert d.recommended_action # never an empty envelope + + +def test_spend_gate_stagnation_below_threshold_still_runs(): + d = SpendGate(max_runs=10, max_stagnant_runs=3).should_run( + runs_done=2, clean_exit=True, goal_reached=False, stagnant_runs=2 + ) + assert d.should_run + + +def test_spend_gate_progress_brake_is_off_at_zero(): + """max_stagnant_runs=0 disables the brake (the CLI default: opt-in).""" + d = SpendGate(max_runs=10, max_stagnant_runs=0).should_run( + runs_done=5, clean_exit=True, goal_reached=False, stagnant_runs=99 + ) + assert d.should_run + + +def test_spend_gate_rejects_negative_counters(): + d = SpendGate().should_run(runs_done=-1, clean_exit=True, goal_reached=False) + assert not d.should_run and d.state == "blocked_validation" + + +def test_spend_gate_rejects_contradictory_input(): + """A crash cannot have reached the goal — refuse rather than guess.""" + d = SpendGate().should_run(runs_done=1, clean_exit=False, goal_reached=True) + assert not d.should_run and d.state == "blocked_validation" + + +def test_spend_gate_never_defaults_to_run(): + """Fail-closed sweep: no bad input yields permission to spend.""" + g = SpendGate(max_runs=5, max_stagnant_runs=2) + bad = [ + {"runs_done": 0, "clean_exit": False, "goal_reached": False}, + {"runs_done": 0, "clean_exit": False, "goal_reached": True}, + {"runs_done": 99, "clean_exit": True, "goal_reached": False}, + {"runs_done": 3, "clean_exit": True, "goal_reached": False, "stagnant_runs": 2}, + {"runs_done": 1, "clean_exit": True, "goal_reached": True}, + {"runs_done": -1, "clean_exit": True, "goal_reached": False}, + { + "runs_done": 1, + "clean_exit": True, + "goal_reached": False, + "stagnant_runs": -1, + }, + ] + for kwargs in bad: + d = g.should_run(**kwargs) + assert not d.should_run, kwargs + assert d.decision == "skip" and d.reason and d.recommended_action, kwargs + assert set(d.as_dict()) == { + "decision", + "should_run", + "state", + "reason", + "recommended_action", + "waiting_on", + "runs_done", + } + + +# -- turn transaction (P1): writeback before spend ---------------------------- + + +def test_turn_transaction_spends_only_after_writeback(): + order: list[str] = [] + + async def execute(): + order.append("execute") + return {"change": 1} + + async def validate(result): + order.append("validate") + return ValidationResult(True) + + async def writeback(result): + order.append("writeback") + + async def spend(result): + order.append("spend") + + receipt = asyncio.run( + run_turn(execute=execute, validate=validate, writeback=writeback, spend=spend) + ) + assert order == ["execute", "validate", "writeback", "spend"] + assert receipt.phases == PHASES + assert receipt.spent and receipt.written_back and receipt.outcome == "spent" + + +def test_turn_transaction_does_not_spend_when_writeback_fails(): + spent: list[bool] = [] + + async def execute(): + return 1 + + async def writeback(result): + raise OSError("disk full") + + async def spend(result): # pragma: no cover - must never run + spent.append(True) + + receipt = asyncio.run(run_turn(execute=execute, writeback=writeback, spend=spend)) + assert spent == [] # the invariant under test + assert not receipt.spent and not receipt.written_back + assert receipt.outcome == "writeback_failed" + assert receipt.phases == ( + "host_execute", + "typed_result", + "validation", + "durable_writeback", + ) + + +def test_turn_transaction_does_not_write_back_or_spend_on_invalid_result(): + touched: list[str] = [] + + async def execute(): + return "untyped" + + async def validate(result): + return ValidationResult(False, "result was not a typed change record") + + async def writeback(result): # pragma: no cover - must never run + touched.append("writeback") + + async def spend(result): # pragma: no cover - must never run + touched.append("spend") + + receipt = asyncio.run( + run_turn(execute=execute, validate=validate, writeback=writeback, spend=spend) + ) + assert touched == [] + assert receipt.outcome == "invalid_result" + assert receipt.phases == ("host_execute", "typed_result", "validation") + + +def test_turn_transaction_records_execute_failure(): + async def execute(): + raise RuntimeError("host crashed") + + async def spend(result): # pragma: no cover - must never run + raise AssertionError("spend ran after a failed execute") + + async def writeback(result): # pragma: no cover - must never run + raise AssertionError("writeback ran after a failed execute") + + receipt = asyncio.run(run_turn(execute=execute, writeback=writeback, spend=spend)) + assert receipt.outcome == "execute_failed" + assert receipt.phases == ("host_execute",) + assert not receipt.executed and not receipt.written_back and not receipt.spent + + +def test_turn_transaction_keeps_writeback_when_spend_fails(): + written: list[str] = [] + + async def execute(): + return "ok" + + async def writeback(result): + written.append(result) + + async def spend(result): + raise TimeoutError("quota service down") + + receipt = asyncio.run(run_turn(execute=execute, writeback=writeback, spend=spend)) + assert written == ["ok"] # durable work is not rolled back by a spend failure + assert receipt.written_back and not receipt.spent + assert receipt.outcome == "spend_failed" + + +def test_turn_transaction_refuses_spend_without_writeback(): + """Wiring guard: spending with nowhere to write back is a contract error.""" + + async def execute(): + return 1 + + async def spend(result): # pragma: no cover - guard fires first + raise AssertionError("unreachable") + + with pytest.raises(ValueError, match="writeback"): + asyncio.run(run_turn(execute=execute, spend=spend)) + + +def test_turn_transaction_without_spend_hook_stops_after_writeback(): + async def execute(): + return 1 + + async def writeback(result): + return None + + receipt = asyncio.run(run_turn(execute=execute, writeback=writeback)) + assert receipt.written_back and not receipt.spent + assert receipt.outcome == "spend_skipped" + assert receipt.phases == ( + "host_execute", + "typed_result", + "validation", + "durable_writeback", + ) + + +# -- scheduler wiring: the gate and the ordering are enforced in the loop ------ + + +def test_scheduler_stops_on_stagnation(): + """The loop that used to spin to max_runs now stops on no progress.""" + + async def task(i): + return RunOutcome(goal_reached=False, progress_made=False) + + outcomes = asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=10), + sleep=_nosleep, + spend_gate=SpendGate(max_runs=10, max_stagnant_runs=2), + ) + ) + assert len(outcomes) == 2 # stopped by the progress brake, not by the cap + + +def test_scheduler_resets_stagnation_when_progress_resumes(): + async def task(i): + # progress on run 2 resets the counter, so the brake never trips + return RunOutcome(goal_reached=False, progress_made=(i == 1)) + + outcomes = asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=4), + sleep=_nosleep, + spend_gate=SpendGate(max_runs=4, max_stagnant_runs=2), + ) + ) + assert len(outcomes) == 4 # cap still bounds it; brake did not fire + + +def test_scheduler_reports_denied_decision(): + seen: list[object] = [] + + async def task(i): + return RunOutcome(goal_reached=False, progress_made=False) + + asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=10), + sleep=_nosleep, + spend_gate=SpendGate(max_runs=10, max_stagnant_runs=1), + on_decision=seen.append, + ) + ) + assert [d.should_run for d in seen] == [True, False] + assert seen[-1].state == "blocked_no_progress" + + +def test_scheduler_spends_only_after_writeback(): + order: list[str] = [] + + async def task(i): + return RunOutcome(goal_reached=(i == 1)) + + async def writeback(n, outcome): + order.append("writeback") + + async def spend(n, outcome): + order.append("spend") + + asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=10), + sleep=_nosleep, + writeback=writeback, + spend=spend, + ) + ) + assert order == ["writeback", "spend", "writeback", "spend"] + + +def test_scheduler_refuses_spend_without_writeback_hook(): + async def task(i): + return RunOutcome(goal_reached=True) + + async def spend(n, outcome): # pragma: no cover - guard fires first + raise AssertionError("unreachable") + + with pytest.raises(ValueError, match="writeback"): + asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=1), + sleep=_nosleep, + spend=spend, + ) + ) + + +def test_scheduler_does_not_spend_when_writeback_fails(): + spent: list[bool] = [] + + async def task(i): + return RunOutcome(goal_reached=True) + + async def writeback(n, outcome): + raise OSError("disk full") + + async def spend(n, outcome): # pragma: no cover - must never run + spent.append(True) + + asyncio.run( + run_scheduled( + task, + interval=0, + gate=Continuation(max_runs=1), + sleep=_nosleep, + writeback=writeback, + spend=spend, + ) + ) + assert spent == [] + + # -- `deepcode schedule` ----------------------------------------------------- @@ -115,7 +496,9 @@ def scheduled(monkeypatch): calls: list[dict] = [] - async def fake_run_scheduled(task, *, interval, gate, on_run=None): + async def fake_run_scheduled( + task, *, interval, gate, on_run=None, spend_gate=None, on_decision=None + ): calls.append({"interval": interval, "max_runs": gate.max_runs}) return [RunOutcome(goal_reached=True)]