Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions core/schedule/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
101 changes: 96 additions & 5 deletions core/schedule/scheduler.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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,
Expand Down
184 changes: 184 additions & 0 deletions core/schedule/should_run.py
Original file line number Diff line number Diff line change
@@ -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,
)
Loading
Loading