"""Reaper unit tests — injected clock, no processes, no sleeping. DESIGN.md §6.5 layer 1: "tests pass a fake clock and assert which session is selected and when". This is where nearly all of the reaping logic is covered. """ from __future__ import annotations import asyncio from hhstreamd.clock import ManualClock from hhstreamd.reaper import Reaper, deadlines, next_deadline, select_expired, sleep_for from hhstreamd.registry import State class FakeSession: """The minimum the reaper needs: an id, liveness and a deadline.""" def __init__(self, sid: str, last_activity: float, timeout: float, state: str = State.READY): self.id = sid self.last_activity_boottime = last_activity self.idle_timeout_s = timeout self.state = state @property def live(self) -> bool: return self.state not in {State.EXITED, State.KILLED, State.REAPED} def deadline(self): if not self.live or not self.idle_timeout_s: return None return self.last_activity_boottime + self.idle_timeout_s # --------------------------------------------------------------------------- # selection # --------------------------------------------------------------------------- def test_empty_set_has_no_deadline_and_sleeps_indefinitely(): assert deadlines([]) == {} assert next_deadline([]) is None assert select_expired([], now=10_000.0) == [] # None means "sleep until woken" — zero wakeups on a quiet server. assert sleep_for([], now=10_000.0) is None def test_next_deadline_is_the_earliest_across_sessions(): sessions = [ FakeSession("a", last_activity=1000.0, timeout=10800.0), # 11800 FakeSession("b", last_activity=5000.0, timeout=60.0), # 5060 <- earliest FakeSession("c", last_activity=2000.0, timeout=3600.0), # 5600 ] assert next_deadline(sessions) == 5060.0 assert sleep_for(sessions, now=5000.0) == 60.0 def test_select_expired_returns_only_the_passed_deadlines_oldest_first(): sessions = [ FakeSession("late", last_activity=100.0, timeout=10.0), # 110 FakeSession("later", last_activity=100.0, timeout=5.0), # 105 FakeSession("future", last_activity=100.0, timeout=1000.0), # 1100 ] assert select_expired(sessions, now=120.0) == ["later", "late"] assert select_expired(sessions, now=104.0) == [] def test_deadline_is_inclusive_so_an_exactly_due_session_is_reaped(): session = FakeSession("a", last_activity=100.0, timeout=10.0) assert select_expired([session], now=110.0) == ["a"] assert sleep_for([session], now=110.0) == 0.0 def test_a_terminal_session_has_no_deadline(): for state in (State.EXITED, State.KILLED, State.REAPED): session = FakeSession("a", last_activity=0.0, timeout=1.0, state=state) assert session.deadline() is None assert select_expired([session], now=1e9) == [] def test_a_zero_timeout_disables_expiry_rather_than_expiring_immediately(): session = FakeSession("a", last_activity=0.0, timeout=0.0) assert next_deadline([session]) is None assert select_expired([session], now=1e9) == [] def test_sleep_for_never_goes_negative(): session = FakeSession("a", last_activity=0.0, timeout=10.0) assert sleep_for([session], now=1_000_000.0) == 0.0 # --------------------------------------------------------------------------- # the Reaper object, with the clock injected at construction # --------------------------------------------------------------------------- def make_reaper(clock: ManualClock, sessions: list[FakeSession]): reaped: list[str] = [] async def on_expire(session_id: str) -> None: reaped.append(session_id) for session in sessions: if session.id == session_id: session.state = State.REAPED return Reaper(now=clock.boottime, sessions=lambda: sessions, on_expire=on_expire), reaped def test_clock_is_injected_and_nothing_expires_until_it_moves(): clock = ManualClock(boottime=1000.0) sessions = [FakeSession("a", last_activity=1000.0, timeout=10800.0)] reaper, reaped = make_reaper(clock, sessions) assert reaper.next_deadline() == 11800.0 assert reaper.sleep_for() == 10800.0 assert reaper.expired() == [] clock.advance(10799.0) assert reaper.expired() == [] clock.advance(1.0) # exactly three hours of idleness assert reaper.expired() == ["a"] assert reaped == [] # selection alone does not tear anything down def test_tick_reaps_the_expired_and_leaves_the_rest(): clock = ManualClock(boottime=0.0) sessions = [ FakeSession("doomed", last_activity=0.0, timeout=60.0), FakeSession("safe", last_activity=0.0, timeout=3600.0), ] reaper, reaped = make_reaper(clock, sessions) clock.advance(61.0) assert asyncio.run(reaper.tick()) == ["doomed"] assert reaped == ["doomed"] assert sessions[1].state == State.READY # The reaped session now has no deadline, so the next one is the survivor's. assert reaper.next_deadline() == 3600.0 def test_adopt_with_an_already_expired_deadline_is_reaped_on_the_first_pass(): """DESIGN.md §2.4 item 6: the arithmetic survives a daemon restart. A record adopted at boottime 50000 whose last activity was at 1000 with a one-hour timeout is already 13 hours overdue. It must be selected immediately, not scheduled another hour out. """ clock = ManualClock(boottime=50_000.0) sessions = [FakeSession("adopted", last_activity=1000.0, timeout=3600.0)] reaper, reaped = make_reaper(clock, sessions) assert reaper.sleep_for() == 0.0 assert asyncio.run(reaper.tick()) == ["adopted"] assert reaped == ["adopted"] def test_a_touch_pushes_the_deadline_out(): clock = ManualClock(boottime=0.0) session = FakeSession("a", last_activity=0.0, timeout=100.0) reaper, _ = make_reaper(clock, [session]) clock.advance(99.0) assert reaper.expired() == [] session.last_activity_boottime = clock.boottime() # what `touch` does clock.advance(99.0) assert reaper.expired() == [] clock.advance(2.0) assert reaper.expired() == ["a"] def test_run_reaps_when_the_deadline_arrives_and_then_sleeps_indefinitely(): """Exercise the real asyncio task without waiting for a real timeout.""" async def scenario(): clock = ManualClock(boottime=0.0) sessions = [FakeSession("a", last_activity=0.0, timeout=10_000.0)] reaper, reaped = make_reaper(clock, sessions) task = reaper.start() await asyncio.sleep(0) # let the first pass run assert reaped == [] clock.advance(10_001.0) # three hours pass in a nanosecond reaper.wake() for _ in range(20): await asyncio.sleep(0) if reaped: break assert reaped == ["a"] # Nothing left to expire: the task is parked, not spinning. assert reaper.sleep_for() is None await reaper.stop() assert task.done() asyncio.run(scenario()) def test_a_failing_teardown_does_not_kill_the_reaper_task(): async def scenario(): clock = ManualClock(boottime=0.0) sessions = [FakeSession("a", last_activity=0.0, timeout=1.0)] calls = [] async def on_expire(session_id: str) -> None: calls.append(session_id) raise RuntimeError("teardown exploded") reaper = Reaper(now=clock.boottime, sessions=lambda: sessions, on_expire=on_expire) clock.advance(2.0) assert await reaper.tick() == [] # the failure is swallowed and logged assert calls == ["a"] assert reaper.expired() == ["a"] # still expired; it will be retried asyncio.run(scenario())