fix(serve): apply staged service reloads when sessions end, with a max staging age

A staged tag was only retried on the refresh tick or a job completion, so a service with steady remote sessions never swapped in. Session end, expiry and eviction now trigger a single-flight apply, the tick applies after the pull, and serve.services_staged_max_age swaps an overdue tag in even while busy.
This commit is contained in:
imSp4rky
2026-09-22 10:40:49 -06:00
parent 6e681af513
commit d239964f0b
8 changed files with 267 additions and 20 deletions
+39 -15
View File
@@ -747,21 +747,7 @@ class DownloadQueueManager:
def schedule_pending_reload(self) -> None:
"""Swap in staged service updates whose last job has finished, off the event loop."""
from unshackle.core import services
if not services.PENDING:
return
async def run() -> None:
try:
applied = await asyncio.to_thread(services.apply_pending, busy_services())
if applied:
log.info(f"Services reloaded after job completion: {', '.join(applied)}")
publish_service_event("applied", applied)
except Exception:
log.exception("Applying pending service reloads failed")
asyncio.get_running_loop().create_task(run())
schedule_pending_reload()
@staticmethod
def put(queue: asyncio.Queue, item: Optional[Dict[str, Any]]) -> None:
@@ -1210,3 +1196,41 @@ def busy_services() -> set[str]:
if stats.mode != "remote_only":
busy |= get_download_manager().busy_services()
return busy
_reload_task: Optional[asyncio.Task[None]] = None
def schedule_pending_reload(tag: Optional[str] = None) -> None:
"""Swap in staged service updates whose last job or remote session has ended, off the event loop.
Runs on every job completion and remote session removal, because a busy service on a popular
tag can otherwise stay staged across every periodic refresh tick. With ``tag``, the reload only
runs when ``PENDING`` holds that tag.
"""
global _reload_task
from unshackle.core import services
if not services.PENDING or (tag is not None and tag not in services.PENDING):
return
# apply_pending computes its ready set before it takes RELOAD_LOCK, so concurrent
# session ends would each re-import the same tag; one in-flight task covers them all.
if _reload_task is not None and not _reload_task.done():
return
async def run() -> None:
try:
applied = await asyncio.to_thread(services.apply_pending, busy_services())
if applied:
log.info(f"Services reloaded after their jobs and sessions ended: {', '.join(applied)}")
publish_service_event("applied", applied)
except Exception:
log.exception("Applying pending service reloads failed")
_reload_task = asyncio.get_running_loop().create_task(run())
def clear(_: asyncio.Task[None]) -> None:
global _reload_task
_reload_task = None
_reload_task.add_done_callback(clear)
+14
View File
@@ -95,6 +95,13 @@ class SessionEntry:
}
def _schedule_pending_reload(service_tag: str) -> None:
"""Apply staged service reloads now that a remote session ended; the task runs after the store lock releases."""
from unshackle.core.api.download_manager import schedule_pending_reload
schedule_pending_reload(service_tag)
def _publish(action: str, entry: SessionEntry, reason: Optional[str] = None) -> None:
data = {"action": action, **entry.summary()}
if reason:
@@ -145,6 +152,7 @@ class SessionStore:
evicted.input_bridge.cancel()
self.cleanup_cache_dir(evicted.cache_tag)
_publish("delete", evicted, "evicted")
_schedule_pending_reload(evicted.service_tag)
session_id = session_id or str(uuid.uuid4())
entry = SessionEntry(
@@ -173,6 +181,7 @@ class SessionStore:
log.info(f"Session {sanitize_log(session_id)} expired (elapsed={elapsed:.0f}s, ttl={self.ttl}s)")
self.cleanup_cache_dir(entry.cache_tag)
_publish("delete", self._sessions.pop(session_id), "expired")
_schedule_pending_reload(entry.service_tag)
return None
entry.touch()
@@ -196,6 +205,7 @@ class SessionStore:
self.cleanup_cache_dir(entry.cache_tag)
_publish("delete", entry, "closed")
log.info(f"Deleted session {sanitize_log(session_id)}")
_schedule_pending_reload(entry.service_tag)
return True
return False
@@ -211,12 +221,16 @@ class SessionStore:
expired.append(sid)
elif elapsed > self.ttl:
expired.append(sid)
ended_tags: set[str] = set()
for sid in expired:
entry = self._sessions.pop(sid)
if entry.input_bridge:
entry.input_bridge.cancel()
self.cleanup_cache_dir(entry.cache_tag)
_publish("delete", entry, "expired")
ended_tags.add(entry.service_tag)
for tag in ended_tags:
_schedule_pending_reload(tag)
if expired:
log.info(f"Cleaned up {len(expired)} expired sessions")
return len(expired)
+14 -3
View File
@@ -272,13 +272,24 @@ def failed_tags(errors: Iterable[str]) -> set[str]:
return {err.split(":", 1)[0] for err in errors if ":" in err}
def staged_max_age() -> float:
"""Seconds a staged tag may wait for its jobs and sessions before it swaps in anyway; 0 waits forever."""
return float((config.serve or {}).get("services_staged_max_age", 0) or 0)
def apply_pending(busy: set[str] | None = None) -> list[str]:
"""Reload every staged tag whose service is no longer busy; returns the tags now running.
A tag whose re-import failed is not one of them: the old module keeps serving, so calling
it applied would tell the dashboard that code is live when it is not.
A tag staged for longer than ``serve.services_staged_max_age`` reloads even while busy:
its live sessions keep the old class objects they already hold, and a popular tag would
otherwise never see a quiet moment. A tag whose re-import failed is not counted as
running: the old module keeps serving, so calling it applied would tell the dashboard
that code is live when it is not.
"""
ready = sorted(PENDING - (busy or set()))
max_age = staged_max_age()
now = time.time()
overdue = {tag for tag, since in PENDING_SINCE.items() if max_age and now - since >= max_age}
ready = sorted((PENDING - (busy or set())) | (PENDING & overdue))
if not ready:
return []
errors = reload_services(ready)