From d954f61100597341328f5062f9b5cf8f69a48dd1 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Tue, 24 Nov 2026 16:56:21 -0700 Subject: [PATCH] fix(api): evict a session of the key that holds the most at max_sessions --- docs/dev/rest-api/remote-sessions.md | 4 ++-- docs/reference/configuration/services.md | 2 +- tests/remote/unit/test_session_store.py | 12 ++++++++++++ unshackle/core/api/session_store.py | 10 +++++++--- 4 files changed, 22 insertions(+), 6 deletions(-) diff --git a/docs/dev/rest-api/remote-sessions.md b/docs/dev/rest-api/remote-sessions.md index f7c6a8e9..9f5861b1 100644 --- a/docs/dev/rest-api/remote-sessions.md +++ b/docs/dev/rest-api/remote-sessions.md @@ -381,7 +381,7 @@ generally never touch this directly, but it explains behaviour you might observe | Behavior | Value | Notes | |---|---|---| | Idle session TTL | **300s** (5 min) default | Refreshed on every request to the session and when a `titles` or `tracks` request ends. A remote session does not expire while a request works on it | -| Max concurrent sessions | **100** default | Oldest (least recently used) is evicted when full. A remote session that a request works on goes last | +| Max concurrent sessions | **100** default | When full, the least recently used remote session of the API key that holds the most is evicted. A remote session that a request works on goes last | | Auth/input timeout | **600s** (10 min) | Sessions still authenticating or awaiting a prompt use this longer window instead of the TTL | | Cleanup sweep | every 60s | Expired sessions are removed and their input prompts cancelled | @@ -568,7 +568,7 @@ Source: `unshackle/core/api/session_store.py`. A singleton you get from - **Config-driven limits.** `serve.session_ttl` (default `300`) and `serve.max_sessions` (default `100`) are read as properties, so config changes take effect without recreating the store. -- **`create()`** evicts the least-recently-accessed remote session when at capacity, +- **`create()`** evicts the least-recently-accessed remote session of the API key that holds the most when at capacity, then stores a new `SessionEntry`. It defaults `auth_status` to `AUTHENTICATED`, and the `create` handler overrides it to `AUTHENTICATING`. - **`get()`** refreshes `last_accessed` through `touch()`. It returns `None` (and diff --git a/docs/reference/configuration/services.md b/docs/reference/configuration/services.md index 76fa5d2d..dcc9f4cf 100644 --- a/docs/reference/configuration/services.md +++ b/docs/reference/configuration/services.md @@ -162,7 +162,7 @@ is the [REST API](../../dev/rest-api/index.md) section. These are the config key | `remote_only` | bool | `false` | Expose only the remote service session endpoints (health, services, search, session) and disable the rest of the REST API. | | `dashboard` | dict | *(unset)* | Developer dashboard: `key` is the API key for the read-only `/api/dashboard/` endpoints (status, remote sessions, remote session logs, jobs, keys, services, health, logs, SSE events). Unset leaves those routes unregistered. See [dashboard endpoints](../../dev/rest-api/dashboard.md). | | `session_ttl` | int (s) | `300` | Seconds a remote session can stay idle before it expires. A remote client sends keep-alive requests to its remote session during a download, so the remote session does not expire during a long download. | -| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. | +| `max_sessions` | int or null | `100` | Maximum concurrent remote sessions; at the cap the server evicts the oldest remote session of the API key that holds the most. Set it to `null` or `0` for no limit, which is also what `/api/dashboard/status` then reports, so a dashboard can tell "no cap" from a cap that happens to sit at the default. | | `history_limit` | int | `100` | How many finished jobs to retain in history. | | `compression_level` | int | `1` | gzip level for responses. | | `services_refresh_interval` | int (s) | `0` | How often the server pulls the git-backed service repositories in `directories.services` and hot-reloads the services that changed. `0` turns it off. A service with a running or queued job, or a live remote session, is staged and swaps to the new code as soon as its last job and session finish. | diff --git a/tests/remote/unit/test_session_store.py b/tests/remote/unit/test_session_store.py index ec3bed13..457f160b 100644 --- a/tests/remote/unit/test_session_store.py +++ b/tests/remote/unit/test_session_store.py @@ -145,6 +145,18 @@ async def test_max_sessions_evicts_oldest(store: SessionStore, monkeypatch: pyte assert (await store.get("c")) is c +async def test_max_sessions_evicts_the_oldest_session_of_the_key_that_holds_the_most( + store: SessionStore, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(type(store), "max_sessions", property(lambda _: 3)) + await store.create("EXAMPLE", _FakeService(), session_id="a-1", owner_key="KEY-A") + for n in (1, 2, 3): + await asyncio.sleep(0.01) + await store.create("EXAMPLE", _FakeService(), session_id=f"b-{n}", owner_key="KEY-B") + + assert set(store._sessions) == {"a-1", "b-2", "b-3"} + + async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None: from datetime import datetime, timedelta, timezone diff --git a/unshackle/core/api/session_store.py b/unshackle/core/api/session_store.py index 2753b1cb..0a63b59c 100644 --- a/unshackle/core/api/session_store.py +++ b/unshackle/core/api/session_store.py @@ -11,7 +11,7 @@ from __future__ import annotations import asyncio import logging import uuid -from collections import deque +from collections import Counter, deque from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Deque, Dict, List, Optional @@ -170,8 +170,12 @@ class SessionStore: max_sessions = self.max_sessions if max_sessions is not None and len(self._sessions) >= max_sessions: sessions = self._sessions - oldest_id = min(sessions, key=lambda k: (sessions[k].in_use, sessions[k].last_accessed)) - log.warning(f"Max sessions reached ({max_sessions}), evicting oldest: {oldest_id}") + held = Counter(s.owner_key for s in sessions.values()) + oldest_id = min( + sessions, + key=lambda k: (sessions[k].in_use, -held[sessions[k].owner_key], sessions[k].last_accessed), + ) + log.warning(f"Max sessions reached ({max_sessions}), evicting oldest of the busiest key: {oldest_id}") evicted = self._sessions.pop(oldest_id) if evicted.input_bridge: evicted.input_bridge.cancel()