Lock stacks during compose runs, cache stats, persist runtime state (0.47.0)
CI / check (push) Successful in 7m4s
CI / build-and-push (push) Successful in 1m47s

F7 — Nothing stopped two compose operations landing on the same stack. There
was a busy flag, but is_busy() was only ever read to colour the status column;
no lifecycle handler consulted it before acting. Two tabs, or auto-update
picking up a stack somebody had just clicked, both ran pull + up -d against the
same project and raced over recreating containers.

Lifecycle calls, the two deploy WebSockets and the auto-update pass now take a
real lock; a second caller gets 409 (or an error frame and close 4409) and
auto-update skips and retries next cycle. The lock is a row rather than a set
in one worker's memory, so it holds across workers and across a restart, and it
carries an expiry — a worker killed mid-deploy would otherwise strand the stack
with no fix short of editing the database.

F10 — /api/stacks/stats sampled every running container on every call, one
blocking daemon request each, and both the dashboard and the stacks list poll
it every five seconds. Two tabs on a 40-container host meant a sustained ~16
samples a second. Cached for 4s behind a lock so concurrent callers share one
sweep, the same shape dashboard_service already used for its fleet aggregate.

F11 — Three module dicts assumed exactly one uvicorn worker without saying so
and were lost on restart. The busy set is the lock above. The image update
cache is now mirrored to SQLite, so a restart shows the badges immediately
instead of blanking them for up to an hour, and the already-notified marks come
back with them rather than re-announcing the same updates. The login rate
limiter is a table, so it cannot be cleared by getting the process to restart
and no longer multiplies by the worker count.

The constraint that shaped this: compose_service and update_service are shared
with the agent, which has no database. Neither may import one. So the lock is a
separate service the central app enforces at its own entry points, and update
persistence is an opt-in callback the central app registers in its lifespan —
the agent registers nothing and behaves exactly as before. A test asserts
update_service never imports the database, since that is the kind of thing a
later change breaks silently.

Both new nets were checked by reverting the fix: dropping the lock from
_lifecycle fails six tests, removing the stats cache fails the one that names
the behaviour.

Also wires up cache pruning in the same sweep — without it both the dict and
the table grew one entry per image tag ever run, for the life of the install.

31 new tests (729 total).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
This commit is contained in:
menzelj
2026-08-31 13:43:39 +02:00
co-authored by Claude Opus 5
parent 41a21b5a25
commit 09bed274eb
16 changed files with 1053 additions and 32 deletions
+30 -7
View File
@@ -27,7 +27,15 @@ from models.setting import (
)
from models.auto_update import AutoUpdateRead, AutoUpdateWrite
from models.user import User
from services import audit_service, auto_update_service, compose_service, notify_service, stats_service, update_service
from services import (
audit_service,
auto_update_service,
compose_service,
notify_service,
stack_lock_service,
stats_service,
update_service,
)
from services.convert_service import convert_docker_run
router = APIRouter(prefix="/api/stacks", tags=["stacks"])
@@ -59,13 +67,17 @@ def _get_stack_or_404(session: Session, stack_id: str) -> Stack:
return stack
def _stack_summary(stack: Stack, summaries: dict | None = None) -> dict:
def _stack_summary(
stack: Stack, summaries: dict | None = None, busy: dict[str, str] | None = None
) -> dict:
"""Build a list-row summary.
Pass ``summaries`` (from :func:`compose_service.stack_status_summaries`) to
serve the whole stacks list from a single Docker call. Without it (single
Pass ``summaries`` (from :func:`compose_service.stack_status_summaries`) and
``busy`` (from :func:`stack_lock_service.active`) to serve the whole stacks
list from one Docker call and one query. Without them (single
create/update/clone responses), fall back to one direct query for this stack.
"""
busy = busy or {}
if summaries is None:
try:
containers = compose_service.containers_for_stack(stack.id)
@@ -79,7 +91,7 @@ def _stack_summary(stack: Stack, summaries: dict | None = None) -> dict:
info = summaries.get(stack.id)
total = info["total"] if info else 0
running = info["running"] if info else 0
if compose_service.is_busy(stack.id):
if stack.id in busy:
status = "updating"
else:
status = info["status"] if info else "stopped"
@@ -111,7 +123,8 @@ def list_stacks(
summaries = compose_service.stack_status_summaries()
except DockerError:
summaries = {}
return [_stack_summary(s, summaries) for s in stacks]
busy = stack_lock_service.active(session)
return [_stack_summary(s, summaries, busy) for s in stacks]
@router.post("", status_code=201)
@@ -296,7 +309,17 @@ async def _notify_lifecycle(action_name: str, stack_id: str, ok: bool, detail: s
async def _lifecycle(action_fn, action_name, stack_id, request, session, user):
_get_stack_or_404(session, stack_id)
result = await action_fn(stack_id)
# One compose operation per stack. Without this two tabs (or auto-update
# landing on a stack somebody just clicked) both run pull + up -d against
# the same project and race over recreating containers.
try:
with stack_lock_service.hold(session, stack_id, action_name, user.username):
result = await action_fn(stack_id)
except stack_lock_service.StackBusy as exc:
raise HTTPException(
status_code=409,
detail=f"Stack '{stack_id}' is busy: {exc.action} in progress",
) from exc
audit_service.record(
session, user=user.username, action=f"stack.{action_name}", target=stack_id,
detail=f"rc={result.get('returncode')}", ip=_client_ip(request),