Skip to content

Commit 358bc25

Browse files
authored
test: qualify managed calendar Task lifecycle across restarts (#7706)
Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com>
1 parent b685891 commit 358bc25

3 files changed

Lines changed: 184 additions & 0 deletions

File tree

‎docs/product/periodic-reports.md‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,6 +1052,24 @@ instance. `observed.json` records artifact, completion, retained history and
10521052
actual post-setup model calls. This qualifies neither live-model understanding,
10531053
complete Chat-process restart nor production delivery.
10541054

1055+
For a controller-restart check, stop that wake owner, await accepted work, then
1056+
write a unique operation token to `restart-runtime` in the same output directory.
1057+
The fixture closes the old controller and reconstructs the normal controller,
1058+
Chat store and transport over the original physical state, keeping its HTTP URL.
1059+
`restart-readback.json` verifies the original Session, actor and message history
1060+
and that restarting itself added no model or delivery effect. The wake owner
1061+
remains stopped until `stop-existing-wake` is removed. Reusing a token within
1062+
that fixture lifetime does not restart again. Missing stop or pending original
1063+
work writes `restart-rejected.json` and leaves the controller running; that
1064+
token cannot apply later after the condition changes. This is an isolated controller
1065+
restart inside the fixture process, not an OS-process or installed-service test.
1066+
1067+
`test_same_calendar_task_lifecycle_retains_results_and_rejects_late_dispatch`
1068+
joins settings changes, pause/cancel, restart, original result readback,
1069+
withdrawn Agent registration, late dispatch and three distinct calendar windows
1070+
in one File/SQLite journey. Paused and withdrawn stages must add no model call
1071+
or reply; each admitted window must have exactly one original Core result.
1072+
10551073
Callers can discover eligible references on demand with
10561074
`GET /api/chat/sessions/<original-session-id>/native-turn?calendar_task_sources=true`.
10571075
The `calendar_task_sources` view reads the original Goal's canonical completed

‎examples/personal-workspace-browser/steward_report_fixture.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ def fail_report(_adapter, _prompt, event_sink):
151151
"calendar_task_configuration": configuration} if args.managed_calendar_task else {})}))
152152
wake, outbound, delivery = None, None, None
153153
owner_start_count = 0
154+
restart_tokens = set()
155+
restart_refusals = set()
154156
try:
155157
while not stop.wait(.2):
156158
server.assets_dir = current_assets if (output / "use-current-assets").exists() else baseline_assets
@@ -159,6 +161,58 @@ def fail_report(_adapter, _prompt, event_sink):
159161
if owners_stopped and wake:
160162
wake.close()
161163
wake = None
164+
restart_file = output / "restart-runtime"
165+
restart_token = restart_file.read_text().strip() if restart_file.is_file() else None
166+
if (args.managed_calendar_task and restart_token
167+
and restart_token not in restart_tokens | restart_refusals):
168+
with runtime.lock:
169+
restart_busy = (not owners_stopped or store.load_session(sid).get("active_turn_id")
170+
or any(not done.is_set() for done in runtime.turn_done_events.values()))
171+
if restart_busy:
172+
restart_refusals.add(restart_token)
173+
(output / "restart-rejected.json").write_text(json.dumps({
174+
"operation": restart_token, "reason": "stop_wake_and_await_original_work",
175+
"session_id": sid, "runtime_restarted": False, "synthetic_only": True}))
176+
if (args.managed_calendar_task and restart_token
177+
and restart_token not in restart_tokens | restart_refusals):
178+
# Disposable QA only: reconstruct the normal controller over
179+
# its original physical state, never reseed the fixture or
180+
# retain a second wake/model owner across the restart.
181+
from loopx.chat_actions import ChatActionService
182+
from loopx.chat_action_store import ChatActionStore
183+
from loopx.chat_runtime import ChatRuntimeController
184+
from loopx.chat_store import ChatSessionStore
185+
from loopx.extensions.lark.private_conversations import LarkPrivateConversations
186+
history, prior_session = store.messages(sid), store.load_session(sid)
187+
prior_calls, prior_writes = capture.read_bytes(), list(provider.writes)
188+
server.shutdown()
189+
old_runtime = runtime
190+
old_runtime.close()
191+
store = ChatSessionStore(store.root.parent)
192+
runtime = ChatRuntimeController(store=store, codex_bin=old_runtime.codex_bin,
193+
project_contexts=old_runtime.project_contexts, registry_path=old_runtime.registry_path)
194+
transport = LarkPrivateConversations(controller=runtime, runtime_root=store.root.parent,
195+
runner=provider, cli_bin="lark-cli")
196+
runtime.manager_scope_resolver = transport.bindings.steward_scope
197+
transport.core.actions = ChatActionService(store=ChatActionStore(store.root / "actions"),
198+
registry_path=runtime.registry_path, chat_store=store, runtime_controller=runtime,
199+
workspace_roots=[workspace])
200+
local_tasks = SessionCalendarTasks(runtime)
201+
local_owner = local_tasks
202+
server.chat_store, server.runtime_controller = store, runtime
203+
server.lark_private_conversations = transport
204+
server.action_service, server.action_store = transport.core.actions, transport.core.actions.store
205+
threading.Thread(target=server.serve_forever, daemon=True).start()
206+
assert old_runtime.closed.is_set()
207+
assert store.load_session(sid) == prior_session and store.messages(sid) == history
208+
assert local_owner.selected(sid)["actor"] == actor
209+
assert capture.read_bytes() == prior_calls and provider.writes == prior_writes
210+
restart_tokens.add(restart_token)
211+
(output / "restart-readback.json").write_text(json.dumps({
212+
"operation": restart_token, "runtime_restarts": len(restart_tokens),
213+
"session_id": sid, "actor": actor, "message_count": len(history),
214+
"prior_runtime_closed": True, "history_and_identity_preserved": True,
215+
"model_or_delivery_replayed": False, "synthetic_only": True}))
162216
if wake is None and not owners_stopped and (output / "start-existing-owners").exists():
163217
wake = DelegationWakeService(runtime, interval=.1).start()
164218
owner_start_count += 1
@@ -181,6 +235,8 @@ def fail_report(_adapter, _prompt, event_sink):
181235
"provider_history_pages": sum("+chat-messages-list" in call for call in provider.calls),
182236
"existing_wake_owner_running": wake is not None,
183237
"existing_wake_owner_starts": owner_start_count,
238+
"runtime_restarts": len(restart_tokens),
239+
"runtime_restart_rejections": len(restart_refusals),
184240
**({"managed_source_present": artifact.exists(),
185241
"managed_session": store.load_session(managed_session["session_id"])} if args.managed_session else {}),
186242
**({"managed_report": True,

‎tests/test_managed_session_calendar_tasks.py‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,116 @@ def lost_response(**kwargs):
547547
recovered.close()
548548

549549

550+
@pytest.mark.parametrize("provider", ["file", "sqlite"])
551+
def test_same_calendar_task_lifecycle_retains_results_and_rejects_late_dispatch(
552+
steward, tmp_path, monkeypatch, provider):
553+
from loopx.chat_runtime import ChatRuntimeController
554+
from loopx.chat_store import ChatSessionStore
555+
from loopx.capabilities.native_chat.steward_managed_mode import ManagedSessionTurn
556+
from loopx.extensions.lark.private_conversations import LarkPrivateConversations
557+
558+
session, actor, _, capture, workspace, config = setup_task(steward, tmp_path, monkeypatch, provider)
559+
store, runtime, bot, _, binding, _, original_workspace = steward
560+
sid, goal_id = session["session_id"], actor["goal_id"]
561+
actor = SessionCalendarTasks(runtime).selected(sid)["actor"]
562+
point = fixed_clock(monkeypatch)
563+
point[0] = datetime(2020, 1, 1, 8, 59, 59, tzinfo=timezone.utc)
564+
initial = capture.read_bytes(), store.messages(sid), list(bot.writes)
565+
later = {**config, "schedule": {**config["schedule"], "rrule": "FREQ=DAILY;BYHOUR=10;BYMINUTE=0"}}
566+
with settings_server(steward) as request:
567+
for proposed in (config, later, {**later, "enabled": False}, None, config):
568+
apply_configuration(request, goal_id, proposed)
569+
getattr(runtime, "_steward_monitor_next_check", {}).clear()
570+
assert not pump_steward_monitors(runtime)
571+
assert read_cadence_journal(runtime_root=runtime.coordination_runtime_root, goal_id=goal_id) is None
572+
assert (capture.read_bytes(), store.messages(sid), list(bot.writes)) == initial
573+
point[0] += timedelta(seconds=2)
574+
runtime._steward_monitor_next_check.clear()
575+
first = finish(runtime, pump_steward_monitors(runtime)[0])
576+
assert first["response"]["native_loopx"]["status"] == "committed", first
577+
runtime._steward_monitor_next_check.clear()
578+
assert not pump_steward_monitors(runtime)
579+
original_result = store.load_turn(sid, first["turn_id"])
580+
completion = SessionCalendarTasks(runtime).health(sid)["completion"]
581+
apply_configuration(request, goal_id, {**config, "enabled": False})
582+
583+
# A new runtime reads the same physical store, actor, paused plan and body.
584+
runtime.close()
585+
recovered = ChatRuntimeController(store=ChatSessionStore(store.root.parent), codex_bin=runtime.codex_bin,
586+
project_contexts=runtime.project_contexts, registry_path=runtime.registry_path)
587+
transport = LarkPrivateConversations(controller=recovered, runtime_root=store.root.parent,
588+
runner=bot, cli_bin="lark-cli")
589+
resumed = (recovered.store, recovered, bot, transport, binding, capture, original_workspace)
590+
try:
591+
service = SessionCalendarTasks(recovered)
592+
assert service.selected(sid)["actor"] == actor
593+
assert service.health(sid)["completion"] == completion and not service.health(sid)["enabled"]
594+
paused = capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)
595+
point[0] += timedelta(days=1)
596+
assert not pump_steward_monitors(recovered)
597+
assert (capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)) == paused
598+
with settings_server(resumed) as request:
599+
apply_configuration(request, goal_id, config)
600+
recovered._steward_monitor_next_check.clear()
601+
second = finish(recovered, pump_steward_monitors(recovered)[0])
602+
assert second["response"]["native_loopx"]["status"] == "committed", second
603+
assert second["turn_id"] != first["turn_id"]
604+
assert recovered.store.load_turn(sid, first["turn_id"]) == original_result
605+
recovered._steward_monitor_next_check.clear()
606+
assert not pump_steward_monitors(recovered)
607+
apply_configuration(request, goal_id, later)
608+
point[0] = datetime(2020, 1, 2, 10, 0, 1, tzinfo=timezone.utc)
609+
# Freeze through the real calendar owner, before any model dispatch.
610+
with monkeypatch.context() as waiting:
611+
waiting.setattr(ManagedSessionTurn, "submit", lambda *_a, **_kw: (None, False))
612+
assert service.frontier(sid) == (None, False)
613+
window = read_cadence_journal(runtime_root=recovered.coordination_runtime_root, goal_id=goal_id)["window"]
614+
pending = service._todo(actor, window)
615+
before = capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)
616+
registry_bytes = recovered.registry_path.read_bytes()
617+
registry = json.loads(registry_bytes)
618+
goal = next(row for row in registry["goals"] if row["id"] == goal_id)
619+
goal["coordination"]["registered_agents"] = ["peer"]
620+
recovered.registry_path.write_text(json.dumps(registry))
621+
try:
622+
assert not pump_steward_monitors(recovered)
623+
with pytest.raises(ValueError):
624+
ManagedSessionTurn(recovered).submit(sid, agent_id=actor["agent_id"],
625+
operation_id="task." + window["window_id"], todo_id=pending["todo_id"], scheduled_window=window)
626+
finally:
627+
# Restore only this disposable counterfactual, never live grants.
628+
recovered.registry_path.write_bytes(registry_bytes)
629+
apply_configuration(request, goal_id, {**later, "enabled": False})
630+
with pytest.raises(ValueError, match="subscription changed"):
631+
ManagedSessionTurn(recovered).submit(sid, agent_id=actor["agent_id"],
632+
operation_id="task." + window["window_id"], todo_id=pending["todo_id"], scheduled_window=window)
633+
assert (capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)) == before
634+
apply_configuration(request, goal_id, later)
635+
recovered._steward_monitor_next_check.clear()
636+
third = finish(recovered, pump_steward_monitors(recovered)[0])
637+
assert third["response"]["native_loopx"]["status"] == "committed", third
638+
assert third["loopx_request"]["todo_id"] == pending["todo_id"]
639+
assert len({row["loopx_request"]["schedule_window_id"] for row in (first, second, third)}) == 3
640+
assert json.loads((workspace / "total.json").read_text()) == {"total": 42}
641+
final = capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)
642+
apply_configuration(request, goal_id, None)
643+
point[0] += timedelta(days=1)
644+
recovered._steward_monitor_next_check.clear()
645+
assert not pump_steward_monitors(recovered)
646+
assert (capture.read_bytes(), recovered.store.messages(sid), list(bot.writes)) == final
647+
assert recovered.store.load_turn(sid, first["turn_id"]) == original_result
648+
calls = [json.loads(line) for line in capture.read_bytes()[len(initial[0]):].splitlines()]
649+
assert sum(row.get("method") == "turn/start" for row in calls) == 3
650+
messages = recovered.store.messages(sid)
651+
assert messages[:len(initial[1])] == initial[1]
652+
for turn in (first, second, third):
653+
replies = [row for row in messages if row["role"] == "agent" and row.get("turn_id") == turn["turn_id"]]
654+
assert len(replies) == 1 and replies[0]["text"] == turn["response"]["message"]
655+
assert bot.writes == initial[2]
656+
finally:
657+
recovered.close()
658+
659+
550660
@pytest.mark.parametrize("provider", ["file", "sqlite"])
551661
@pytest.mark.parametrize("fault", ["malformed-message", "non-object-message", "conflicting-result", "duplicate-result", "none"])
552662
def test_calendar_completion_requires_complete_unambiguous_original_return(

0 commit comments

Comments
 (0)