Files
stackpilot/backend/tests/test_agent_removal.py
T
menzeljandClaude Opus 5 51d1998307
CI / check (push) Successful in 7m17s
CI / build-and-push (push) Successful in 1m45s
Remove the remote-host (agent) integration (0.48.0)
StackPilot now manages exactly one Docker host: the one it runs on. The
stackpilot-agent sidecar and everything that proxied to it are gone — 4721
lines deleted against 657 added.

Deleted outright: agent/ (image, compose, env), agent_app.py, models/agent.py,
routers/agents.py (1200 lines), services/agent_service.py, the agent API client,
RemoteStackDetail, the host components and AgentStacksSection. That removes 57
API routes and the three /ws/agent-* proxies.

Threaded out everywhere else, which was the bulk of the work. Every API module
carried an optional agentId that switched the base path; every page that listed
Docker objects rendered one section per host behind a HostHeader; Files had a
host switcher; the New Stack editor and the template dialog had host selectors;
schedules, auto-update policies and stack summaries carried agent_id. All of it
is gone, and the typechecker drove the sweep — 85 files touched, tsc and the
build clean.

Two things the removal exposed as dead weight rather than merely unused:

compose_service kept an in-process busy set purely because the agent needed a
lock and has no database. With the agent gone that was a second source of truth
next to the real DB lock, so it is deleted; compute_status now reports only what
the containers say and the two callers that want "updating" overlay the lock.
StacksTable's linkBase prop only ever existed to point at /hosts/{id}/stacks.

The dashboard's "Hosts 1/1 online" KPI can no longer say anything else, so the
tile and the KPIs behind it are gone and the row is five wide.

Upgrading matters here. An existing install still has an agent table holding
each remote host's URL and bearer token — full Docker control of that host,
sitting in the database with nothing left to use it. _drop_removed_schema drops
it on first start, and drops the agent_id columns where the SQLite build
supports DROP COLUMN. Each statement runs in its own transaction on purpose: a
failed DDL poisons the transaction it is in, so sharing one would let an
unsupported column drop take the table drop down with it. test_agent_removal
covers both branches plus the fresh-install and idempotent cases, and an
end-to-end run against a seeded pre-0.48 database confirms the table is gone and
every /api/agents route answers 404.

Docstrings that justified a design by "shared with the agent, which has no
database" were rewritten rather than left lying: update_service's persistence
callback and image_status_store are still the right split (registry logic stays
testable without a database), but for that reason now, not the old one. The
README's multi-host sections are removed and an upgrade note explains what to do
with running agent containers; ROADMAP keeps its history behind a note saying
the feature it describes no longer exists.

CI no longer builds or pushes stackpilot-agent.

735 tests pass, ruff and tsc clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dk43rmEeRfYi5wsLDbmfyG
2026-08-31 14:11:54 +02:00

202 lines
6.5 KiB
Python

"""Cleaning up after the removed multi-host integration.
The agent sidecar and everything that proxied to it were removed in 0.48.0.
Upgrading installs still carry the schema it left behind, and one part of that
is not merely dead weight: the ``agent`` table held each remote host's URL and
its bearer token, which is full Docker control of that host. Leaving those in
the database for a feature that no longer exists would be worse than dropping
them, so ``_drop_removed_schema`` drops the table outright.
The ``agent_id`` columns are only dropped where the SQLite build supports it
(DROP COLUMN needs 3.35+); they are nullable and unread, so leaving them is
harmless.
"""
from __future__ import annotations
import pytest
from sqlalchemy import create_engine, inspect, text
@pytest.fixture
def pre_048_db(tmp_path, monkeypatch):
"""A database as an install running 0.47.0 would have it."""
import database
import models # noqa: F401 — populates SQLModel.metadata
engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}")
with engine.begin() as conn:
conn.execute(
text(
"""
CREATE TABLE agent (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL,
url VARCHAR NOT NULL,
token VARCHAR NOT NULL,
status VARCHAR NOT NULL,
hostname VARCHAR,
last_seen DATETIME,
created_at DATETIME NOT NULL
)
"""
)
)
conn.execute(
text(
"INSERT INTO agent (id, name, url, token, status, created_at) VALUES"
" (1, 'nas', 'http://10.0.0.5:5010', 'super-secret-agent-token',"
" 'online', '2026-01-01')"
)
)
conn.execute(
text(
"""
CREATE TABLE autoupdate (
id INTEGER NOT NULL PRIMARY KEY,
stack_id VARCHAR NOT NULL,
agent_id INTEGER,
enabled BOOLEAN NOT NULL,
redeploy BOOLEAN NOT NULL,
last_run DATETIME,
last_status VARCHAR,
last_result VARCHAR,
created_at DATETIME NOT NULL
)
"""
)
)
conn.execute(
text(
"INSERT INTO autoupdate (id, stack_id, agent_id, enabled, redeploy,"
" created_at) VALUES (1, 'jellyfin', NULL, 1, 1, '2026-01-01')"
)
)
monkeypatch.setattr(database, "engine", engine)
return engine
def test_the_agent_table_and_its_tokens_are_dropped(pre_048_db):
import database
assert "agent" in inspect(pre_048_db).get_table_names()
database._drop_removed_schema()
assert "agent" not in inspect(pre_048_db).get_table_names(), (
"the agent table holds host URLs and bearer tokens for a feature that no "
"longer exists — it must not survive the upgrade"
)
def test_surviving_rows_are_untouched(pre_048_db):
"""Dropping the agent schema must not disturb the policies that remain."""
import database
database._drop_removed_schema()
with pre_048_db.begin() as conn:
row = conn.execute(
text("SELECT stack_id, enabled FROM autoupdate WHERE id = 1")
).one()
assert row.stack_id == "jellyfin"
assert row.enabled
def test_the_agent_id_column_is_dropped_where_sqlite_allows_it(pre_048_db):
import sqlite3
import database
database._drop_removed_schema()
columns = {c["name"] for c in inspect(pre_048_db).get_columns("autoupdate")}
supports_drop = tuple(int(p) for p in sqlite3.sqlite_version.split(".")) >= (3, 35, 0)
if supports_drop:
assert "agent_id" not in columns
else: # pragma: no cover - depends on the host's SQLite
assert "agent_id" in columns, "the fallback must leave the column alone"
def test_an_unsupported_drop_column_does_not_block_the_table_drop(
pre_048_db, monkeypatch
):
"""A failed DDL poisons its transaction.
If the table drop and the column drops shared one, a SQLite too old for
DROP COLUMN would take the agent table — tokens and all — down with it.
"""
import database
from sqlalchemy.exc import OperationalError
real_execute = database.text
def exploding_text(sql):
if "DROP COLUMN" in sql:
raise OperationalError("DROP COLUMN", {}, Exception("near \"DROP\""))
return real_execute(sql)
monkeypatch.setattr(database, "text", exploding_text)
database._drop_removed_schema()
assert "agent" not in inspect(pre_048_db).get_table_names(), (
"the table drop must not be collateral damage of an unsupported column drop"
)
def test_running_it_twice_is_harmless(pre_048_db):
"""It runs on every start, not just the first one after the upgrade."""
import database
database._drop_removed_schema()
database._drop_removed_schema()
assert "agent" not in inspect(pre_048_db).get_table_names()
def test_a_fresh_install_is_unaffected(db):
"""Nothing to drop, and no error for trying."""
import database
database._drop_removed_schema()
assert "agent" not in inspect(database.engine).get_table_names()
# --------------------------------------------------------------------------- #
# Nothing agent-shaped is left in the running application
# --------------------------------------------------------------------------- #
def test_no_route_mentions_agents(app):
from fastapi.routing import APIRoute
leftovers = [
r.path
for r in app.routes
if "agent" in getattr(r, "path", "").lower()
]
assert not leftovers, f"remote-host routes still registered: {leftovers}"
assert not any(
isinstance(r, APIRoute) and "/api/agents" in r.path for r in app.routes
)
def test_no_agent_model_is_registered():
from sqlmodel import SQLModel
import models # noqa: F401
assert "agent" not in SQLModel.metadata.tables
def test_the_agent_modules_are_gone():
"""Import guards, so a stray file cannot quietly come back."""
import importlib
for name in ("agent_app", "models.agent", "routers.agents", "services.agent_service"):
with pytest.raises(ModuleNotFoundError):
importlib.import_module(name)
def test_no_agent_token_setting():
from config import settings
assert not hasattr(settings, "AGENT_TOKEN")