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)