fix(api): evict a session of the key that holds the most at max_sessions

This commit is contained in:
imSp4rky
2026-11-24 16:56:21 -07:00
parent 7735c43061
commit d954f61100
4 changed files with 22 additions and 6 deletions
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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. |
+12
View File
@@ -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
+7 -3
View File
@@ -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()