Skip to content

Commit eb09eb3

Browse files
fix(scheduler): keep Python scheduler reads from migrating legacy state
A Python read of scheduler state is a projection: the follow-up hint rebuild reads the stored state before the native transaction applies the heartbeat receipt fence. That read used the store's default, which migrates a legacy scheduler-state file into the canonical hashed path, so a follow-up that is then rejected as `heartbeat_receipt_stale` had already deleted the legacy file and written a new one. A blocked preview or execute must leave the legacy layout untouched; migration belongs to the native commit that holds the scheduler lock after every fence passes, which already asks for `migrate_legacy: false`. `load_scheduler_state` now reads legacy state without migrating it. Readers see the same value; only the write under the lock moves the file. Refs #8605 Signed-off-by: GZY-SUPER-HACKER <162807803+GZY-SUPER-HACKER@users.noreply.github.com>
1 parent 8089c39 commit eb09eb3

2 files changed

Lines changed: 87 additions & 2 deletions

File tree

‎loopx/control_plane/scheduler/state.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,7 @@ def _store_result(
252252
agent_id: str,
253253
surface: str,
254254
state_key: str,
255+
migrate_legacy: bool | None = None,
255256
) -> Mapping[str, Any]:
256257
params: dict[str, Any] = {
257258
"schema_version": SCHEDULER_STATE_STORE_REQUEST_SCHEMA,
@@ -265,6 +266,8 @@ def _store_result(
265266
}
266267
if state is not None:
267268
params["state"] = state
269+
if migrate_legacy is not None:
270+
params["migrate_legacy"] = migrate_legacy
268271
try:
269272
result = effect_runtime_result(f"scheduler.state.{operation}", params)
270273
except EffectRuntimeRejected as exc:
@@ -290,6 +293,11 @@ def load_scheduler_state(
290293
) -> dict[str, Any] | None:
291294
if not agent_id:
292295
return None
296+
# Python reads are projections (quota should-run hints and the scheduler
297+
# follow-up hint rebuild). Legacy state stays read-only until the native
298+
# commit holds every applicable authority fence and migrates it under the
299+
# scheduler lock; a read here must not move or delete the legacy file
300+
# before a receipt/authority fence can reject the caller.
293301
result = _store_result(
294302
"load",
295303
runtime_root,
@@ -298,6 +306,7 @@ def load_scheduler_state(
298306
agent_id=agent_id,
299307
surface=surface,
300308
state_key=state_key,
309+
migrate_legacy=False,
301310
)
302311
state = result.get("state")
303312
if state is not None and not isinstance(state, dict):

‎tests/control_plane/test_scheduler_stale_receipt_gate.py‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88

99
from __future__ import annotations
1010

11+
import hashlib
12+
import json
13+
import re
1114
from pathlib import Path
1215

1316
import pytest
@@ -18,6 +21,7 @@
1821
)
1922
from loopx.control_plane.scheduler.state import (
2023
APP_AUTOMATION_STATEFUL_BACKOFF_STATE_KEY as APP_KEY,
24+
build_scheduler_state,
2125
load_scheduler_state,
2226
scheduler_state_path,
2327
)
@@ -58,12 +62,12 @@ def _should_run(
5862

5963

6064
def _ack(
61-
registry: Path, runtime: Path, project: Path, turn: str
65+
registry: Path, runtime: Path, project: Path, turn: str, *, execute: bool = True
6266
) -> tuple[int, dict]:
6367
return run_json_cli_result(
6468
"quota", "scheduler-ack-current", "--goal-id", GOAL,
6569
"--agent-id", SCOPED_AGENT_ID, "--codex-app",
66-
"--turn-instance-id", turn, "--execute",
70+
"--turn-instance-id", turn, *(["--execute"] if execute else []),
6771
registry_path=registry, runtime_root=runtime, cwd=project,
6872
)
6973

@@ -119,3 +123,75 @@ def test_fresh_receipt_still_commits_the_ack(
119123
)
120124
assert state is not None
121125
assert state["last_applied_rrule"]
126+
127+
128+
def _legacy_segment(value: str) -> str:
129+
"""Mirror the legacy (unbounded) scheduler path segment normalization."""
130+
131+
safe = re.sub(r"[^0-9A-Za-z_.-]+", "-", value.strip())
132+
return re.sub(r"^[-._]+|[-._]+$", "", safe) or "default"
133+
134+
135+
def _legacy_state_path(
136+
runtime: Path, *, goal_id: str, agent_id: str, surface: str, state_key: str
137+
) -> Path:
138+
return (
139+
runtime
140+
/ "goals"
141+
/ _legacy_segment(goal_id)
142+
/ "scheduler-state"
143+
/ _legacy_segment(agent_id)
144+
/ _legacy_segment(surface)
145+
/ f"{hashlib.sha256(state_key.encode('utf-8')).hexdigest()[:16]}.json"
146+
)
147+
148+
149+
@pytest.mark.parametrize("execute", [True, False])
150+
def test_stale_receipt_rejection_does_not_migrate_legacy_scheduler_state(
151+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, execute: bool
152+
) -> None:
153+
"""The rejected follow-up rebuilds a hint, but the hint read is read-only.
154+
155+
Migration belongs to the native commit that holds the scheduler lock after
156+
every receipt fence passes; a blocked preview or execute must leave the
157+
legacy layout byte-identical and create no canonical state file.
158+
"""
159+
160+
registry, runtime, project = _fixture(tmp_path, monkeypatch)
161+
_should_run(registry, runtime, project, TURN_1)
162+
legacy_path = _legacy_state_path(
163+
runtime,
164+
goal_id=GOAL,
165+
agent_id=SCOPED_AGENT_ID,
166+
surface="codex_app",
167+
state_key=APP_KEY,
168+
)
169+
legacy_path.parent.mkdir(parents=True, exist_ok=True)
170+
legacy_state = build_scheduler_state(
171+
goal_id=GOAL,
172+
agent_id=SCOPED_AGENT_ID,
173+
state_key=APP_KEY,
174+
reset_token="legacy-reset",
175+
identity_signature="legacy-identity",
176+
progression_index=1,
177+
progression_minutes=[30, 60],
178+
last_applied_rrule="FREQ=MINUTELY;INTERVAL=30",
179+
updated_at="2026-01-01T12:00:00Z",
180+
)
181+
legacy_bytes = json.dumps(legacy_state, sort_keys=True).encode("utf-8")
182+
legacy_path.write_bytes(legacy_bytes)
183+
canonical_path = scheduler_state_path(
184+
runtime, goal_id=GOAL, agent_id=SCOPED_AGENT_ID, state_key=APP_KEY
185+
)
186+
assert legacy_path != canonical_path
187+
assert not canonical_path.exists()
188+
189+
_supercede(runtime, TURN_2)
190+
code, result = _ack(registry, runtime, project, TURN_1, execute=execute)
191+
192+
assert code == 1, result
193+
assert result["status"] == "heartbeat_receipt_stale"
194+
assert result["state"] == "blocked_receipt"
195+
assert result["scheduler_state_mutated"] is False
196+
assert legacy_path.read_bytes() == legacy_bytes
197+
assert not canonical_path.exists()

0 commit comments

Comments
 (0)