Skip to content

Commit d1ec066

Browse files
committed
fix(server): roll back started extensions when startup fails
If extension A started and B raised in on_startup, A's on_shutdown never ran, and a failed first-run bind_control_plane() left the runtime half up with database_bound already true, so a retry did nothing. run_startup_hooks now returns the extensions whose startup finished and, when one raises, shuts the started ones down in reverse order before re-raising. stop() shuts down only those. Opening the control plane (in start() and bind_control_plane()) tears the runtime down and closes the database on failure, so the bind can be retried.
1 parent 27902ae commit d1ec066

4 files changed

Lines changed: 157 additions & 38 deletions

File tree

‎docs/extensions.md‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,13 @@ extension = Extension()
4444
Rules:
4545

4646
- Extensions load once per process, sorted by entry point name. An extension
47-
that fails to import is logged and skipped. An exception in `on_startup`
48-
stops the server from starting. A failing `on_shutdown` is logged, and the
49-
other extensions still shut down.
47+
that fails to import is logged and skipped.
48+
- An exception in `on_startup` stops the server from starting. The extensions
49+
that already started get `on_shutdown` in reverse order, then the runtime
50+
is stopped and the database closed, so a failed first-run database bind can
51+
be retried. `on_shutdown` runs only for extensions whose startup finished
52+
(an extension without `on_startup` counts as started).
53+
- A failing `on_shutdown` is logged, and the other extensions still shut down.
5054
- Public paths must start with `/api/`. A route listed there must
5155
authenticate the caller itself.
5256
- Agent tools, skills, middleware hooks, and IM channels belong in harness

‎src/octop/infra/extensions.py‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from __future__ import annotations
2727

2828
import logging
29+
from collections.abc import Sequence
2930
from dataclasses import dataclass, field
3031
from functools import cache
3132
from importlib.metadata import entry_points
@@ -109,15 +110,35 @@ def extension_public_paths() -> PublicPaths:
109110
)
110111

111112

112-
async def run_startup_hooks(server: Any) -> None:
113-
for ext_name, hook in extension_hooks("on_startup"):
114-
logger.info("octop extension %r: starting", ext_name)
115-
await hook(server)
113+
async def run_startup_hooks(server: Any) -> tuple[str, ...]:
114+
"""Start extensions in load order; return the names that started.
116115
117-
118-
async def run_shutdown_hooks(server: Any) -> None:
119-
"""Run in reverse load order; one failing hook does not stop the others."""
120-
for ext_name, hook in reversed(extension_hooks("on_shutdown")):
116+
An extension without ``on_startup`` counts as started, so its
117+
``on_shutdown`` still runs at stop. If one raises, the extensions that
118+
already started are shut down in reverse order and the error propagates.
119+
"""
120+
started: list[str] = []
121+
for ext in load_extensions():
122+
hook = getattr(ext.obj, "on_startup", None)
123+
if callable(hook):
124+
logger.info("octop extension %r: starting", ext.name)
125+
try:
126+
await hook(server)
127+
except Exception:
128+
logger.exception("octop extension %r: on_startup failed", ext.name)
129+
await run_shutdown_hooks(server, started)
130+
raise
131+
started.append(ext.name)
132+
return tuple(started)
133+
134+
135+
async def run_shutdown_hooks(server: Any, started: Sequence[str]) -> None:
136+
"""Shut down ``started`` extensions in reverse order; one failure does not stop the rest."""
137+
hooks = dict(extension_hooks("on_shutdown"))
138+
for ext_name in reversed(started):
139+
hook = hooks.get(ext_name)
140+
if hook is None:
141+
continue
121142
try:
122143
await hook(server)
123144
except Exception:

‎src/octop/infra/server.py‎

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def __init__(self, home: Path | None = None) -> None:
329329
self._started_at: int | None = None
330330
self.instance_id = uuid.uuid4().hex
331331
self._serve_background = True
332-
self._extensions_started = False
332+
self._started_extensions: tuple[str, ...] = ()
333333
self._sso_service: SsoService | None = None
334334
self._ldap_service: LdapAuthService | None = None
335335
self._ldap_bind_throttle: LdapBindThrottle | None = None
@@ -451,14 +451,7 @@ async def start(self, *, serve_background: bool = True) -> None:
451451
logger.info("control-plane database deferred until setup wizard chooses a backend")
452452
return
453453

454-
db = open_database(config, self.paths)
455-
run_migrations(db)
456-
self.services = build_shared_services(db=db, paths=self.paths, config=config)
457-
from octop.infra.auth.captcha import boot_from_services # noqa: PLC0415
458-
459-
boot_from_services(self.services.settings_repo, self.services.secret_repo)
460-
self._ensure_jwt_secret()
461-
await self._boot_runtime(config)
454+
await self._open_control_plane(config)
462455
self._started = True
463456
assert self.user_manager is not None
464457
self._emit_wizard_password(user_count=self.user_manager.count())
@@ -474,22 +467,32 @@ async def bind_control_plane(self) -> None:
474467
return
475468
config = load_config(self.paths.config)
476469
self.config = config
470+
await self._open_control_plane(config)
471+
logger.info(
472+
"control-plane database bound driver=%s",
473+
config.database.driver,
474+
)
475+
476+
async def _open_control_plane(self, config: OctopConfig) -> None:
477+
"""Open the DB and boot the runtime; on failure, undo it so a retry starts clean."""
477478
db = open_database(config, self.paths)
478479
try:
479480
run_migrations(db)
481+
self.services = build_shared_services(db=db, paths=self.paths, config=config)
482+
from octop.infra.auth.captcha import boot_from_services # noqa: PLC0415
483+
484+
boot_from_services(self.services.settings_repo, self.services.secret_repo)
485+
self._ensure_jwt_secret()
486+
await self._boot_runtime(config)
480487
except Exception:
481-
db.close()
488+
if self.services is None:
489+
db.close()
490+
else:
491+
try:
492+
await self._teardown_runtime()
493+
except Exception:
494+
logger.exception("cleanup after a failed control-plane boot failed")
482495
raise
483-
self.services = build_shared_services(db=db, paths=self.paths, config=config)
484-
from octop.infra.auth.captcha import boot_from_services # noqa: PLC0415
485-
486-
boot_from_services(self.services.settings_repo, self.services.secret_repo)
487-
self._ensure_jwt_secret()
488-
await self._boot_runtime(config)
489-
logger.info(
490-
"control-plane database bound driver=%s",
491-
config.database.driver,
492-
)
493496

494497
async def _boot_runtime(self, config: OctopConfig) -> None:
495498
assert self.services is not None
@@ -711,8 +714,7 @@ async def _resume_bridges() -> None:
711714

712715
from octop.infra.extensions import run_startup_hooks # noqa: PLC0415
713716

714-
await run_startup_hooks(self)
715-
self._extensions_started = True
717+
self._started_extensions = await run_startup_hooks(self)
716718

717719
async def refresh_plugin_channels(self) -> None:
718720
"""Reconcile only changed kinds and report registration failures to callers."""
@@ -801,11 +803,19 @@ async def stop(self) -> None:
801803
if not self._started:
802804
return
803805
try:
804-
if self._extensions_started:
806+
await self._teardown_runtime()
807+
finally:
808+
self._started = False
809+
logger.info("octop server stopped")
810+
811+
async def _teardown_runtime(self) -> None:
812+
"""Stop extensions and the runtime, close the DB, and clear both handles."""
813+
try:
814+
started, self._started_extensions = self._started_extensions, ()
815+
if started:
805816
from octop.infra.extensions import run_shutdown_hooks # noqa: PLC0415
806817

807-
self._extensions_started = False
808-
await run_shutdown_hooks(self)
818+
await run_shutdown_hooks(self, started)
809819
from octop.infra.connectors.gateway import agently_auth
810820

811821
await agently_auth.close()
@@ -824,8 +834,6 @@ async def stop(self) -> None:
824834
self.services.db.close()
825835
self.services = None
826836
self.app_runtime = None
827-
self._started = False
828-
logger.info("octop server stopped")
829837

830838
# ----- helpers -----
831839

‎tests/unit/infra/test_extensions.py‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,3 +116,89 @@ async def test_undeclared_route_still_needs_jwt(demo: _Demo, tmp_path: Path) ->
116116

117117
assert ping.status_code == 200
118118
assert private.status_code == 401
119+
120+
121+
class _Recorder:
122+
def __init__(self, name: str, log: list[str], *, fail: bool = False) -> None:
123+
self.name = name
124+
self.log = log
125+
self.fail = fail
126+
127+
async def on_startup(self, server: Any) -> None:
128+
if self.fail:
129+
raise RuntimeError(f"{self.name} failed")
130+
self.log.append(f"{self.name}.startup")
131+
132+
async def on_shutdown(self, server: Any) -> None:
133+
assert server.services is not None, "database must still be open"
134+
self.log.append(f"{self.name}.shutdown")
135+
136+
137+
@pytest.fixture()
138+
def a_ok_b_fails(monkeypatch: pytest.MonkeyPatch) -> Iterator[tuple[list[str], _Recorder]]:
139+
log: list[str] = []
140+
b = _Recorder("b", log, fail=True)
141+
entries = [
142+
_entry("a", _Recorder("a", log)),
143+
_entry("b", b),
144+
_entry("c", _Recorder("c", log)),
145+
]
146+
monkeypatch.setattr(extensions, "entry_points", lambda group: entries)
147+
load_extensions.cache_clear()
148+
extension_public_paths.cache_clear()
149+
yield log, b
150+
load_extensions.cache_clear()
151+
extension_public_paths.cache_clear()
152+
153+
154+
@pytest.mark.asyncio
155+
async def test_failed_first_bind_shuts_down_started_extensions_and_can_retry(
156+
a_ok_b_fails: tuple[list[str], _Recorder], tmp_path: Path
157+
) -> None:
158+
log, b = a_ok_b_fails
159+
server = OctopServer(home=tmp_path)
160+
await server.start()
161+
assert not server.database_bound
162+
163+
with pytest.raises(RuntimeError, match="b failed"):
164+
await ensure_control_plane_bound(server)
165+
166+
# A started and was shut down; C never started, so it is not shut down.
167+
assert log == ["a.startup", "a.shutdown"]
168+
assert not server.database_bound
169+
assert server.services is None and server.app_runtime is None
170+
171+
b.fail = False
172+
await server.bind_control_plane()
173+
assert server.database_bound
174+
await server.stop()
175+
assert log[2:] == [
176+
"a.startup",
177+
"b.startup",
178+
"c.startup",
179+
"c.shutdown",
180+
"b.shutdown",
181+
"a.shutdown",
182+
]
183+
184+
185+
@pytest.mark.asyncio
186+
async def test_failed_startup_shuts_down_started_extensions(
187+
a_ok_b_fails: tuple[list[str], _Recorder], tmp_path: Path
188+
) -> None:
189+
log, b = a_ok_b_fails
190+
# Bind once so the next start() opens the database directly.
191+
b.fail = False
192+
first = OctopServer(home=tmp_path)
193+
await first.start()
194+
await ensure_control_plane_bound(first)
195+
await first.stop()
196+
log.clear()
197+
198+
b.fail = True
199+
server = OctopServer(home=tmp_path)
200+
with pytest.raises(RuntimeError, match="b failed"):
201+
await server.start()
202+
203+
assert log == ["a.startup", "a.shutdown"]
204+
assert server.services is None and server.app_runtime is None

0 commit comments

Comments
 (0)