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
+2
View File
@@ -4,6 +4,7 @@ from models.audit import AuditLog
from models.auto_update import AutoUpdate
from models.backup_destination import BackupDestination
from models.backup_schedule import BackupSchedule
from models.runtime_state import ImageStatus, LoginAttempt, StackLock
from models.setting import Setting, Webhook
from models.stack import Stack
from models.user import User
@@ -11,4 +12,5 @@ from models.user import User
__all__ = [
"User", "Stack", "AuditLog", "Setting", "Webhook", "Agent",
"BackupDestination", "BackupSchedule", "AutoUpdate",
"StackLock", "ImageStatus", "LoginAttempt",
]
+76
View File
@@ -0,0 +1,76 @@
"""Runtime state that used to live in module-level dicts.
Three things were kept in process memory: which stacks are mid-deploy, the
registry digests behind the "update available" badges, and the login rate
limiter's counters. All three assumed exactly one uvicorn worker — nothing said
so, and ``--workers 2`` would have silently given each worker its own copy —
and all three were lost on restart.
They are tables now. SQLite is already here; this needs no new dependency.
Note that ``services/compose_service.py`` and ``services/update_service.py``
are shared with the agent, which has no database at all — so these tables are
only ever touched from the central app's own routers and background loops.
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Optional
from sqlmodel import Field, SQLModel
def _now() -> datetime:
return datetime.now(timezone.utc)
class StackLock(SQLModel, table=True):
"""A stack is mid-operation and must not be touched concurrently.
``docker compose`` has no locking of its own, so two simultaneous ``update``
calls — two browser tabs, or auto-update racing a manual click — would both
run ``pull`` and ``up`` against the same project and fight over recreating
containers.
``expires_at`` is what keeps a crashed worker from locking a stack forever:
an expired row is simply taken over by the next caller.
"""
stack_id: str = Field(primary_key=True)
action: str # "update", "start", "backup", …
#: Free-form owner, for the log when a lock is stolen. Not a security control.
owner: str = ""
acquired_at: datetime = Field(default_factory=_now)
expires_at: datetime
class ImageStatus(SQLModel, table=True):
"""Cached result of one image's registry digest check.
Persisted so a restart does not blank every update badge until the next
background sweep (up to an hour), and so ``notified`` survives with it —
otherwise every restart re-announced the same pending updates.
"""
image: str = Field(primary_key=True)
update_available: bool = False
current_digest: Optional[str] = None
remote_digest: Optional[str] = None
checked_at: float = 0.0
error: Optional[str] = None
#: Whether an "update available" notification already went out for this
#: image at its current state.
notified: bool = False
class LoginAttempt(SQLModel, table=True):
"""One login attempt, for the rate limiter.
In memory this reset on every restart, so an attacker could clear their own
budget by getting the process to restart — and with more than one worker the
limit multiplied by the worker count. Rows are pruned as they age out.
"""
id: Optional[int] = Field(default=None, primary_key=True)
ip: str = Field(index=True)
at: datetime = Field(default_factory=_now, index=True)