fix(tui_gateway): the live hosted-room settle survives plain lease expiry, and the lease keeper names the interface's types

The gateway driver's settle_task passes allow_expired_lease through to the store, and the runtime's in-process terminal callback settles with it on, as main's does: plain expiry of the attempt's own lease no longer discards a completed result, while a reclaimed or released lease or a moved room authority still fences it.

The lease keeper takes DriverLease, DriverStateError, StaleLeaseError and RoomUnavailableError from the persistence interface. The gateway driver module no longer defines the error classes, so a renewal that found the lease lost raised AttributeError on the keeper's thread instead of recording the loss for the turn.

Main's tests for this area run on the interface with main's assertions: the two live settlement cases of the driver tests, the wait-budget case and the lease keeper cases now open the room through a store handle. New cases pin the runtime's live settle past plain expiry and after a reclaim, and the keeper handing a loss found on its thread to the turn without renewing again.
This commit is contained in:
yoniebans
2026-11-10 01:41:43 +01:00
parent cd1c8104e2
commit d3079f9e48
7 changed files with 126 additions and 62 deletions

View File

@@ -197,11 +197,18 @@ def start_task(
def settle_task(
store, attempt: TaskAttempt, *, placement: HostedPlacement, settlement_id: Any, status: TerminalStatus,
result: Any, clock: Clock) -> dict[str, Any]:
"""Commit one terminal result if every lease and task fence still matches."""
result: Any, clock: Clock, allow_expired_lease: bool = False) -> dict[str, Any]:
"""Commit one terminal result if every lease and task fence still matches.
``allow_expired_lease`` serves the live in-process terminal callback only: plain expiry of our
own unreleased, un-reclaimed lease must not discard an already-completed first-party result, so
the post-replay check drops only its ``expires_at > now`` term. Reclaim, release and authority
transfer still fence; historical harvest paths keep the strict check.
"""
settlement_id, now = _settlement(settlement_id, status, result, clock)
return store.hosted_room_driver.settle_task(
attempt, placement=placement, settlement_id=settlement_id, status=status, result=result, now=now)
attempt, placement=placement, settlement_id=settlement_id, status=status, result=result, now=now,
allow_expired_lease=allow_expired_lease)
def settle_stopping_task(

View File

@@ -423,10 +423,11 @@ def test_live_settlement_commits_after_plain_lease_expiry(db):
lease,
expected_cancel_generation=0,
clock=clock,
placement="profile",
)
clock.advance(5) # plain expiry of our own unreleased, un-reclaimed lease
with pytest.raises(driver.StaleLeaseError):
with pytest.raises(StaleLeaseError):
driver.settle_task(
db,
attempt,
@@ -434,6 +435,7 @@ def test_live_settlement_commits_after_plain_lease_expiry(db):
status="settled",
result={"text": "late"},
clock=clock,
placement="profile",
)
settled = driver.settle_task(
db,
@@ -443,10 +445,11 @@ def test_live_settlement_commits_after_plain_lease_expiry(db):
result={"text": "late"},
clock=clock,
allow_expired_lease=True,
placement="profile",
)
assert settled["status"] == "settled"
assert driver.get_task(db, identity)["status"] == "settled"
assert driver.get_task(db, identity, placement="profile")["status"] == "settled"
def test_live_settlement_after_expiry_still_fences_on_reclaim(db):
@@ -460,13 +463,14 @@ def test_live_settlement_after_expiry_still_fences_on_reclaim(db):
lease,
expected_cancel_generation=0,
clock=clock,
placement="profile",
)
clock.advance(5)
second = _lease(db, clock, process="process-b")
driver.recover_room(db, second, clock=clock)
driver.recover_room(db, second, clock=clock, placement="profile")
with pytest.raises(driver.StaleLeaseError):
with pytest.raises(StaleLeaseError):
driver.settle_task(
db,
attempt,
@@ -475,8 +479,9 @@ def test_live_settlement_after_expiry_still_fences_on_reclaim(db):
result={"text": "late"},
clock=clock,
allow_expired_lease=True,
placement="profile",
)
assert driver.get_task(db, identity)["status"] == "indeterminate"
assert driver.get_task(db, identity, placement="profile")["status"] == "indeterminate"
@pytest.mark.parametrize("status", ["settled", "failed"])

View File

@@ -0,0 +1,55 @@
"""The runtime's live terminal settle past plain expiry of its own room lease (hosted-room driver).
Topical sibling of ``test_hosted_room_driver_runtime.py``, which stays inside its file-line cap.
"""
from __future__ import annotations
from pathlib import Path
from gateway import hosted_room_driver as state
from tests.tui_gateway import test_hosted_room_driver_runtime as runtime_fixtures
from tests.tui_gateway.test_hosted_room_driver_runtime import BINDING, ROOM_ID, FakeSessionRPC, _admit, _identity, _runtime
db = runtime_fixtures.db
store = runtime_fixtures.store_fixture
def _started_attempt(store, runtime):
identity = _identity()
_admit(store, identity)
lease = state.acquire_lease(
store, placement="profile", room_id=ROOM_ID, gateway_id=BINDING.gateway_id,
authority_epoch=BINDING.authority_epoch, process_generation=runtime.process_generation,
ttl_seconds=runtime.lease_ttl_seconds, clock=runtime.clock)
return state.start_task(
store, identity, lease, placement="profile", expected_cancel_generation=0, clock=runtime.clock)
def test_live_terminal_settle_commits_after_plain_expiry_of_its_own_lease(db: Path, store):
now = [1_000.0]
runtime = _runtime(store, FakeSessionRPC(), clock=lambda: now[0])
attempt = _started_attempt(store, runtime)
now[0] = attempt.lease.expires_at # our own lease lapsed, unreleased and not reclaimed
runtime._on_terminal(BINDING, attempt, {"status": "settled", "text": "Done."})
task = state.get_task(store, attempt.identity, placement="profile")
assert task["status"] == "settled"
assert task["result"]["text"] == "Done."
def test_live_terminal_settle_is_discarded_once_another_process_reclaims_the_lease(db: Path, store):
now = [1_000.0]
runtime = _runtime(store, FakeSessionRPC(), clock=lambda: now[0])
attempt = _started_attempt(store, runtime)
now[0] = attempt.lease.expires_at
successor = state.acquire_lease(
store, placement="profile", room_id=ROOM_ID, gateway_id=BINDING.gateway_id,
authority_epoch=BINDING.authority_epoch, process_generation="process-b", ttl_seconds=60,
clock=runtime.clock)
state.recover_room(store, successor, placement="profile", clock=runtime.clock)
runtime._on_terminal(BINDING, attempt, {"status": "settled", "text": "Done."})
assert state.get_task(store, attempt.identity, placement="profile")["status"] == "indeterminate"

View File

@@ -8,16 +8,10 @@ inside its file-line cap (see root AGENTS.md).
from __future__ import annotations
import threading
import time
from pathlib import Path
import pytest
from gateway import hosted_rooms
from tests.tui_gateway import test_hosted_room_driver_runtime as runtime_fixtures
from tests.tui_gateway.test_hosted_room_driver_runtime import (
BINDING,
PROFILE,
ROOM_ID,
FakeSessionRPC,
_admit,
_identity,
@@ -25,26 +19,15 @@ from tests.tui_gateway.test_hosted_room_driver_runtime import (
_wait_for,
)
@pytest.fixture
def db(tmp_path: Path) -> Path:
path = tmp_path / "state.db"
hosted_rooms.create_room(
path,
room_id=ROOM_ID,
name="Release room",
members=[{"profile": PROFILE, "handle": PROFILE}],
authority_gateway_id=BINDING.gateway_id,
now=time.time(),
)
return path
db = runtime_fixtures.db
store = runtime_fixtures.store_fixture
def test_wait_for_terminal_sleep_budget_stays_inside_the_renewal_window(db: Path):
def test_wait_for_terminal_sleep_budget_stays_inside_the_renewal_window(db: Path, store):
identity = _identity()
_admit(db, identity)
_admit(store, identity)
rpc = FakeSessionRPC(auto_complete=False)
runtime = _runtime(db, rpc, turn_timeout_seconds=30)
runtime = _runtime(store, rpc, turn_timeout_seconds=30)
waits: list[float] = []
class RecordingWake(threading.Event):

View File

@@ -17,21 +17,17 @@ from types import SimpleNamespace
import pytest
from gateway import hosted_room_driver as state
from gateway import hosted_rooms
from persistence.gateway.hosted_rooms import TERMINAL_STATUSES, DriverLease, StaleLeaseError
from tests.tui_gateway import test_hosted_room_driver_runtime as runtime_fixtures
from tests.tui_gateway.test_hosted_room_driver_runtime import BINDING, PROFILE, ROOM_ID, _identity, _wait_for
from tui_gateway.hosted_room_driver import HostedRoomRuntime
from tui_gateway.hosted_room_lease_keeper import LeaseKeeper
from tui_gateway.hosted_room_server_rpc import HostedRoomServerRPC
TTL = 0.6
@pytest.fixture
def db(tmp_path: Path) -> Path:
path = tmp_path / "state.db"
hosted_rooms.create_room(
path, room_id=ROOM_ID, name="Release room", members=[{"profile": PROFILE, "handle": PROFILE}],
authority_gateway_id=BINDING.gateway_id, now=time.time())
return path
db = runtime_fixtures.db
store = runtime_fixtures.store_fixture
def _server(submits: list, *, finish_after: float):
@@ -54,26 +50,26 @@ def _server(submits: list, *, finish_after: float):
_pending_approval_request_payload=lambda _session_key: None)
def _run(db: Path, turn_lock, submits: list, clock=time.time) -> dict:
def _run(store, turn_lock, submits: list, clock=time.time) -> dict:
identity = _identity()
state.admit_task(db, identity, clock=time.time, payload={
state.admit_task(store, identity, placement="profile", clock=time.time, payload={
"target_profile": PROFILE, "target_member_id": "member-ops", "prompt": "Ship it.",
"source_event_seq": 1})
runtime = HostedRoomRuntime(
db_path=db, rooms=[BINDING], rpc=HostedRoomServerRPC(_server(submits, finish_after=TTL)),
store=store, placement="profile", rooms=[BINDING], rpc=HostedRoomServerRPC(_server(submits, finish_after=TTL)),
turn_lock=turn_lock, clock=clock, lease_ttl_seconds=TTL, poll_interval_seconds=0.01,
active_poll_interval_seconds=0.02)
runtime.start()
try:
_wait_for(lambda: (
state.get_task(db, identity)["status"] in state.TERMINAL_STATUSES
state.get_task(store, identity, placement="profile")["status"] in TERMINAL_STATUSES
or runtime.status()["last_error"] is not None), timeout=10.0)
finally:
assert runtime.stop(timeout=5.0)
return {"task": state.get_task(db, identity), "last_error": runtime.status()["last_error"]}
return {"task": state.get_task(store, identity, placement="profile"), "last_error": runtime.status()["last_error"]}
def test_turn_settles_when_the_profile_lock_wait_and_the_run_outlast_the_lease(db: Path):
def test_turn_settles_when_the_profile_lock_wait_and_the_run_outlast_the_lease(db: Path, store):
@contextlib.contextmanager
def busy_lock(_profile):
# health: allow HX013 -- the lock wait outlasting the lease ttl IS the behaviour under test
@@ -81,14 +77,14 @@ def test_turn_settles_when_the_profile_lock_wait_and_the_run_outlast_the_lease(d
yield
submits: list = []
outcome = _run(db, busy_lock, submits)
outcome = _run(store, busy_lock, submits)
assert len(submits) == 1
assert outcome["last_error"] is None
assert outcome["task"]["status"] == "settled"
def test_turn_is_fenced_before_submit_when_the_lease_is_taken_over_during_the_wait(db: Path):
def test_turn_is_fenced_before_submit_when_the_lease_is_taken_over_during_the_wait(db: Path, store):
offset = [0.0]
def clock():
@@ -98,19 +94,19 @@ def test_turn_is_fenced_before_submit_when_the_lease_is_taken_over_during_the_wa
def lock_while_another_process_reclaims(_profile):
offset[0] += TTL * 2 # this process stalls past its lease; another process reclaims it
state.acquire_lease(
db, room_id=ROOM_ID, gateway_id=BINDING.gateway_id, authority_epoch=BINDING.authority_epoch,
process_generation="process-b", ttl_seconds=3600, clock=clock)
store, placement="profile", room_id=ROOM_ID, gateway_id=BINDING.gateway_id,
authority_epoch=BINDING.authority_epoch, process_generation="process-b", ttl_seconds=3600, clock=clock)
yield
submits: list = []
outcome = _run(db, lock_while_another_process_reclaims, submits, clock=clock)
outcome = _run(store, lock_while_another_process_reclaims, submits, clock=clock)
assert submits == []
assert outcome["task"]["status"] != "settled"
assert "fenced" in (outcome["last_error"] or "")
def test_ambiguous_submit_recovers_the_room_when_the_keeper_renewal_lands_late(db: Path, monkeypatch):
def test_ambiguous_submit_recovers_the_room_when_the_keeper_renewal_lands_late(db: Path, store, monkeypatch):
"""A keeper renewal committed before the turn's own renewal but cached after it must not
roll the cached expiry back: the ambiguous deferral would end before the row expires, the
next scan would renew the same generation in place, and the attempt would stay running."""
@@ -145,19 +141,35 @@ def test_ambiguous_submit_recovers_the_room_when_the_keeper_renewal_lands_late(d
raise RuntimeError("connection reset after send")
identity = _identity()
state.admit_task(db, identity, clock=time.time, payload={
state.admit_task(store, identity, placement="profile", clock=time.time, payload={
"target_profile": PROFILE, "target_member_id": "member-ops", "prompt": "Ship it.",
"source_event_seq": 1})
runtime = HostedRoomRuntime(
db_path=db, rooms=[BINDING], rpc=HostedRoomServerRPC(_server([], finish_after=TTL)),
store=store, placement="profile", rooms=[BINDING], rpc=HostedRoomServerRPC(_server([], finish_after=TTL)),
turn_lock=lock_released_after_the_keeper_tick, clock=time.time, lease_ttl_seconds=TTL,
poll_interval_seconds=0.01, active_poll_interval_seconds=0.02)
resolve = runtime._transport_for
runtime._transport_for = lambda binding, task: AmbiguousSubmit(resolve(binding, task))
runtime.start()
try:
_wait_for(lambda: state.get_task(db, identity)["status"] != "running" and submitted.is_set(),
_wait_for(lambda: state.get_task(store, identity, placement="profile")["status"] != "running" and submitted.is_set(),
timeout=TTL * 8)
finally:
assert runtime.stop(timeout=5.0)
assert state.get_task(db, identity)["status"] == "indeterminate"
assert state.get_task(store, identity, placement="profile")["status"] == "indeterminate"
def test_keeper_records_a_lease_lost_on_its_thread_and_fences_the_turn_with_it():
lease = DriverLease(ROOM_ID, BINDING.gateway_id, BINDING.authority_epoch, "process-a", 1, 100.0)
renewals: list[str] = []
def renew(_lease):
renewals.append(threading.current_thread().name)
raise StaleLeaseError("driver lease is stale or expired")
with LeaseKeeper(lease, renew, interval=0.01) as keeper:
_wait_for(lambda: renewals, timeout=5.0)
keeper._thread.join(timeout=5.0)
with pytest.raises(StaleLeaseError):
keeper.renew_now()
assert len(renewals) == 1 # the turn's renew_now raised the keeper's loss without renewing again

View File

@@ -770,7 +770,7 @@ class HostedRoomRuntime:
self._recovered_leases = {k for k in self._recovered_leases if k[0] != binding.room_id}
return lease
def _cache_lease(self, lease: state.DriverLease) -> state.DriverLease:
def _cache_lease(self, lease: DriverLease) -> DriverLease:
"""Cache ``lease`` unless the cache already holds a later expiry of the same generation.
A LeaseKeeper thread and the turn's thread renew concurrently and commit in either order;
@@ -910,7 +910,9 @@ class HostedRoomRuntime:
try:
self._publish(
binding,
state.settle_task(self.store, attempt, placement=self.placement, **asdict(terminal), clock=self.clock))
state.settle_task(
self.store, attempt, placement=self.placement, **asdict(terminal), clock=self.clock,
allow_expired_lease=True))
except (StaleLeaseError, StaleTaskError):
# Cancellation, disband, or authority transfer can win the durable race, and then the
# model result is discarded; an exact attempt in recovery still takes its reply.

View File

@@ -15,7 +15,7 @@ import threading
from collections.abc import Callable
from agent.memory_provider import spawn_context_thread
from gateway import hosted_room_driver as state
from persistence.gateway.hosted_rooms import DriverLease, DriverStateError, RoomUnavailableError, StaleLeaseError
logger = logging.getLogger(__name__)
@@ -24,12 +24,12 @@ class LeaseKeeper:
"""Renew ``lease`` every ``interval`` seconds on a daemon thread until the context exits."""
def __init__(
self, lease: state.DriverLease, renew: Callable[[state.DriverLease], state.DriverLease], *,
self, lease: DriverLease, renew: Callable[[DriverLease], DriverLease], *,
interval: float,
) -> None:
self.lease, self._renew, self._interval = lease, renew, interval
self._stop = threading.Event()
self._lost: state.DriverStateError | None = None
self._lost: DriverStateError | None = None
self._thread = spawn_context_thread(self._run, name=f"hosted-room-lease-{lease.room_id[:24]}")
def __enter__(self) -> LeaseKeeper:
@@ -50,7 +50,7 @@ class LeaseKeeper:
while not self._stop.wait(self._interval):
try:
self.lease = self._renew(self.lease)
except (state.StaleLeaseError, state.RoomUnavailableError) as exc:
except (StaleLeaseError, RoomUnavailableError) as exc:
self._lost = exc
return
except Exception as exc: # health: allow BLE001 -- transient (sqlite busy); next tick retries