From e813737506b021b4c7b4d78f102560d0bcdb3ca5 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Mon, 30 Nov 2026 17:06:15 -0700 Subject: [PATCH] fix(remote): measure the idle time of a remote session on a monotonic clock --- docs/dev/rest-api/remote-sessions.md | 5 ++-- tests/remote/unit/test_remote_loopback.py | 14 ++++----- .../remote/unit/test_server_cdm_max_height.py | 5 ++-- tests/remote/unit/test_session_lifetime.py | 14 +++++---- tests/remote/unit/test_session_store.py | 29 +++++++++++++++---- unshackle/core/api/session_store.py | 23 +++++++++------ 6 files changed, 59 insertions(+), 31 deletions(-) diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index 29617902..46e8b76e 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -624,7 +624,7 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from - **Expiry.** `get()` and `cleanup_expired()` use one rule. A remote session that no request holds expires when it is idle for longer than `ttl`. While its login runs (`AUTHENTICATING`), the limit is the larger of `ttl` and `AUTH_INPUT_TIMEOUT`. -- **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` and +- **`get()`** refreshes `last_accessed` and `idle_since` through `touch()`. It returns `None` and deletes the entry when the remote session has expired. - **`cleanup_expired()`** runs every 60s and removes each expired remote session. - **Removal.** Eviction, expiry and `delete()` end the remote session the same way: they cancel its @@ -649,7 +649,8 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from | `cache_tag` | Per-session cache directory tag | | `input_bridge` | `InputBridge` for interactive auth, if any | | `auth_status` / `auth_error` | Current `AuthStatus`, read from `input_bridge` (`AUTHENTICATED` without one), and last error message | -| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives TTL and LRU eviction | +| `created_at` / `last_accessed` | Timestamps; `last_accessed` drives LRU eviction | +| `idle_since` | Monotonic time of the last access; it drives the TTL, so a step of the system clock expires no remote session | ### Per-session cache namespacing diff --git a/tests/remote/unit/test_remote_loopback.py b/tests/remote/unit/test_remote_loopback.py index 75f166c3..32be00df 100644 --- a/tests/remote/unit/test_remote_loopback.py +++ b/tests/remote/unit/test_remote_loopback.py @@ -7,7 +7,6 @@ import json import logging import threading from collections.abc import Callable, Iterator -from datetime import UTC, datetime from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Event, Semaphore, Thread @@ -160,6 +159,11 @@ def server(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch, tmp_ app = web.Application(middlewares=[record, cors_middleware, no_5xx_middleware, api_key_authentication]) app["config"] = {"users": [KEY, OTHER_KEY]} setup_routes(app, remote_only=True) + + async def close_store(_: web.Application) -> None: + await session_store.get_session_store().close() + + app.on_cleanup.append(close_store) loop = asyncio.new_event_loop() runner = web.AppRunner(app) loop.run_until_complete(runner.setup()) @@ -220,10 +224,6 @@ def example_messages(caplog: pytest.LogCaptureFixture) -> list[str]: return [r.getMessage() for r in caplog.records if r.name == "EXAMPLE"] -def idle_seconds(entry: Any) -> float: - return (datetime.now(UTC) - entry.last_accessed).total_seconds() - - @pytest.mark.parametrize( "server,channel", [(True, "none"), (False, "refused"), (True, "failed")], @@ -496,7 +496,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey session_id = service._session_id entry = store.peek(session_id) assert wait_until(lambda: entry.channel.attached, 5) - assert wait_until(lambda: idle_seconds(entry) > 3 * ttl, 10) + assert wait_until(lambda: entry.idle_seconds > 3 * ttl, 10) assert on_loop(server, store.cleanup_expired()) == 0 assert store.peek(session_id) is entry assert count(server, "GET", SESSION_ROUTE, session_id) == 0 @@ -504,7 +504,7 @@ def test_an_open_channel_keeps_the_session_alive(server: SimpleNamespace, monkey service.lifetime.close_channel() assert wait_until(lambda: not entry.channel.attached, 5) - assert wait_until(lambda: idle_seconds(entry) > 2 * ttl, 10) + assert wait_until(lambda: entry.idle_seconds > 2 * ttl, 10) assert on_loop(server, store.cleanup_expired()) == 1 assert store.peek(session_id) is None assert count(server, "GET", SESSION_ROUTE, session_id) == 0 diff --git a/tests/remote/unit/test_server_cdm_max_height.py b/tests/remote/unit/test_server_cdm_max_height.py index c5bc4e27..03559dea 100644 --- a/tests/remote/unit/test_server_cdm_max_height.py +++ b/tests/remote/unit/test_server_cdm_max_height.py @@ -1,5 +1,6 @@ """A per-key height cap on the server CDM hands licensing above it to the client's own device.""" +import atexit import json import logging from datetime import datetime @@ -15,7 +16,7 @@ from tests.core.key_resolver import key_table, resolver from tests.remote.key_source import CAPPED, PR_DEVICE, MemoryKeySource, one_title, remote_session from tests.remote.sessions import launch_session, session_entry from unshackle.commands.dl import dl -from unshackle.core import remote_channel +from unshackle.core import remote_channel, remote_lifetime from unshackle.core.api import handlers, job_admission, key_policy, server_keys from unshackle.core.api.errors import APIError from unshackle.core.api.key_policy import KeyPolicy @@ -636,7 +637,7 @@ def created(answer, monkeypatch): svc.client = SimpleNamespace(post=lambda path, data: {"session_id": "sess", **answer}) channel = SimpleNamespace(keep_alive=lambda: None, drain_logs=lambda: None, in_flight=None) monkeypatch.setattr(remote_channel, "open_channel", lambda service: channel) - monkeypatch.setattr("atexit.register", lambda hook: None) + monkeypatch.setattr(remote_lifetime, "atexit", SimpleNamespace(register=id, unregister=atexit.unregister)) svc.authenticate() return svc diff --git a/tests/remote/unit/test_session_lifetime.py b/tests/remote/unit/test_session_lifetime.py index d8741e8d..6124492d 100644 --- a/tests/remote/unit/test_session_lifetime.py +++ b/tests/remote/unit/test_session_lifetime.py @@ -3,7 +3,6 @@ from __future__ import annotations import asyncio -import atexit import contextlib import signal import subprocess @@ -31,7 +30,7 @@ from tests.remote.unit.test_remote_loopback import ( from tests.remote.unit.test_remote_service_helpers import blob from tests.remote.unit.test_session_reopen import SERVER, make_service from tests.remote.unit.test_tunnel import wait_until -from unshackle.core import remote_channel, remote_service +from unshackle.core import remote_channel, remote_lifetime, remote_service from unshackle.core.api import handlers, routes, session_store from unshackle.core.api.download_manager import busy_services from unshackle.core.api.session_store import SessionEntry @@ -640,8 +639,13 @@ def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: lis @pytest.fixture def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]: hooks: list[Any] = [] - monkeypatch.setattr(atexit, "register", hooks.append) - monkeypatch.setattr(atexit, "unregister", lambda hook: hooks.remove(hook) if hook in hooks else None) + + def unregister(hook: Any) -> None: + if hook in hooks: + hooks.remove(hook) + + fake = SimpleNamespace(register=hooks.append, unregister=unregister) + monkeypatch.setattr(remote_lifetime, "atexit", fake) # other modules register hooks of their own meanwhile return hooks @@ -994,7 +998,7 @@ def test_an_end_of_another_thread_stops_the_opening( return {} if at == "hook": - monkeypatch.setattr(atexit, "register", lambda hook: end() and None or exit_hooks.append(hook)) + monkeypatch.setattr(remote_lifetime.atexit, "register", lambda hook: end() and None or exit_hooks.append(hook)) elif at == "create": monkeypatch.setattr(remote_service, "launch_keys", end) else: diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index fe70a196..8f41191a 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -50,10 +50,12 @@ async def test_get_returns_none_for_missing(store: SessionStore) -> None: async def test_get_touches_last_accessed(store: SessionStore) -> None: entry = await store.create("DEMO", _FakeService()) before = entry.last_accessed + entry.idle_since -= 100 await asyncio.sleep(0.01) fetched = await store.get(entry.session_id) assert fetched is entry assert fetched.last_accessed > before + assert fetched.idle_seconds < 100 async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None: @@ -99,7 +101,7 @@ async def test_get_and_the_sweep_share_one_expiry_rule( bridge = InputBridge() bridge.login_status = status entry = await store.create("EXAMPLE", _FakeService(), session_id="s", input_bridge=bridge) - entry.last_accessed = datetime.now(UTC) - timedelta(seconds=idle) + entry.idle_since = time.monotonic() - idle if via == "get": assert (await store.get("s") is None) is expires @@ -108,10 +110,25 @@ async def test_get_and_the_sweep_share_one_expiry_rule( assert store.session_count == int(not expires) +@pytest.mark.parametrize("step", [1, -1], ids=["forward", "back"]) +@pytest.mark.parametrize("idle", [0, 1], ids=["active", "idle"]) +async def test_a_step_of_the_wall_clock_changes_no_expiry( + store: SessionStore, monkeypatch: pytest.MonkeyPatch, step: int, idle: int +) -> None: + entry = await store.create("EXAMPLE", _FakeService(), session_id="s") + entry.idle_since -= idle * (store.ttl + 100) + stepped = datetime.now(UTC) + timedelta(seconds=step * 2 * (store.ttl + 100)) + monkeypatch.setattr(session_store_module, "datetime", SimpleNamespace(now=lambda tz: stepped)) + + assert entry.summary()["idle_seconds"] // (store.ttl + 100) == idle + assert await store.cleanup_expired() == idle + assert await store.get("s") is (None if idle else entry) + + async def test_session_with_work_in_progress_does_not_expire(store: SessionStore) -> None: """A request that holds the lock for longer than the TTL keeps its session and cache directory.""" entry = await store.create("EXAMPLE", _FakeService(), session_id="busy") - entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100) + entry.idle_since = time.monotonic() - store.ttl - 100 async with entry.lock: assert await store.cleanup_expired() == 0 assert await store.get("busy") is entry @@ -204,7 +221,7 @@ async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: py monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append)) entry = await store.create("EXAMPLE", _FakeService()) entry.cache_tag = "_sessions/k/s/EXAMPLE" - entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100) + entry.idle_since = time.monotonic() - store.ttl - 100 assert await store.get(entry.session_id) is None assert removed == ["_sessions/k/s/EXAMPLE"] @@ -285,7 +302,7 @@ async def test_inline_expiry_applies_staged_service_reload( applied = _stage_reload(monkeypatch, {"EXAMPLE"}) entry = await store.create("EXAMPLE", _FakeService()) - entry.last_accessed = datetime.now(UTC) - timedelta(seconds=store.ttl + 100) + entry.idle_since = time.monotonic() - store.ttl - 100 assert await store.get(entry.session_id) is None await asyncio.sleep(0.05) assert applied == [set()] @@ -296,9 +313,9 @@ async def test_cleanup_expired_applies_staged_service_reload_once( ) -> None: """A cleanup sweep that drops several sessions on one tag schedules one reload for that tag.""" applied = _stage_reload(monkeypatch, {"EXAMPLE"}) - stale = datetime.now(UTC) - timedelta(seconds=store.ttl + 100) + stale = time.monotonic() - store.ttl - 100 for sid in ("a", "b"): - (await store.create("EXAMPLE", _FakeService(), session_id=sid)).last_accessed = stale + (await store.create("EXAMPLE", _FakeService(), session_id=sid)).idle_since = stale assert await store.cleanup_expired() == 2 await asyncio.sleep(0.05) diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index 75399304..b10758f1 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -13,6 +13,7 @@ import builtins import contextlib import hmac import logging +import time import uuid from collections import Counter, deque from collections.abc import AsyncIterator @@ -72,6 +73,7 @@ class SessionEntry: actions: deque[dict[str, Any]] = field(default_factory=lambda: deque(maxlen=500)) created_at: datetime = field(default_factory=lambda: datetime.now(UTC)) last_accessed: datetime = field(default_factory=lambda: datetime.now(UTC)) + idle_since: float = field(default_factory=time.monotonic) # expiry reads no wall clock, which can step def __post_init__(self) -> None: if self.input_bridge is not None: @@ -91,8 +93,13 @@ class SessionEntry: self.tracks_by_title[title_id] = title_tracks def touch(self) -> None: - """Update last_accessed timestamp.""" + """Update last_accessed timestamp and restart the idle time.""" self.last_accessed = datetime.now(UTC) + self.idle_since = time.monotonic() + + @property + def idle_seconds(self) -> float: + return time.monotonic() - self.idle_since @property def in_use(self) -> bool: @@ -140,7 +147,7 @@ class SessionEntry: "created_ts": self.created_at.timestamp(), "last_accessed_ts": self.last_accessed.timestamp(), "age_seconds": int((now - self.created_at).total_seconds()), - "idle_seconds": int((now - self.last_accessed).total_seconds()), + "idle_seconds": int(self.idle_seconds), } @@ -325,11 +332,10 @@ class SessionStore: if entry is None: return None - now = datetime.now(UTC) - if not self._expired(entry, now): + if not self._expired(entry): entry.touch() return entry - elapsed = (now - entry.last_accessed).total_seconds() + elapsed = entry.idle_seconds limit = self._idle_limit(entry) log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={limit:.0f}s)") cache_tag = self._retire(entry, "expired") @@ -358,8 +364,7 @@ class SessionStore: async def cleanup_expired(self) -> int: """Remove all expired sessions. Returns count of removed sessions.""" async with self._lock: - now = datetime.now(UTC) - expired = [entry for entry in self._sessions.values() if self._expired(entry, now)] + expired = [entry for entry in self._sessions.values() if self._expired(entry)] cache_tags = [self._retire(entry, "expired") for entry in expired] if expired: log.info(f"Cleaned up {len(expired)} expired sessions") @@ -370,9 +375,9 @@ class SessionStore: """The idle limit of a remote session: the TTL, or max(TTL, AUTH_INPUT_TIMEOUT) while its login runs.""" return max(self.ttl, AUTH_INPUT_TIMEOUT) if entry.auth_status == AuthStatus.AUTHENTICATING else self.ttl - def _expired(self, entry: SessionEntry, now: datetime) -> bool: + def _expired(self, entry: SessionEntry) -> bool: """The one expiry rule: no request holds the remote session and it is idle past its limit.""" - return not entry.in_use and (now - entry.last_accessed).total_seconds() > self._idle_limit(entry) + return not entry.in_use and entry.idle_seconds > self._idle_limit(entry) def _retire(self, entry: SessionEntry, reason: str | None) -> str | None: """End a remote session under the store lock and return its cache tag, for removal outside the lock.