Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

fix(web): run standby activation's blocking work off the event loop (#3821)

OliverBryantb88f816a084f
diff --git a/src/xagent/web/app.py b/src/xagent/web/app.py
index a32250031..f8da930f4 100644
--- a/src/xagent/web/app.py
+++ b/src/xagent/web/app.py
@@ -155,7 +155,12 @@ from .services.task_lease_recovery import run_task_lease_recovery_loop
from .services.uploaded_file_recovery import (
run_uploaded_file_compensation_recovery_loop,
)
-from .services.writer_workers import drain_workers, run_tracked, run_tracked_in
+from .services.writer_workers import (
+ drain_workers,
+ run_tracked,
+ run_tracked_in,
+ run_tracked_to_completion,
+)
from .startup_admission import run_host_startup_admissions
# Configure logging when running under gunicorn/uwsgi (no __main__.py)
@@ -2139,11 +2144,11 @@ async def _admit_database_and_host(app_instance: FastAPI, *, bound: bool) -> Non
``bound`` is a standby that already bound its engine and passed the
read-only checks: it completes the deferred half instead of ``init_db``.
"""
+ # Blocking (migrations, key validation, schema seed): off the event loop so
+ # lifecycle requests keep being answered, and never cut short by a cancel
+ # that would leave the schema half-initialized.
with _startup_phase("database init"):
- if bound:
- complete_standby_db_init()
- else:
- init_db()
+ await run_tracked_to_completion(complete_standby_db_init if bound else init_db)
# Host checks may rely on the fully migrated database. Nothing below this
# boundary may admit tasks or launch a writer/dispatcher until every check
diff --git a/src/xagent/web/services/standby.py b/src/xagent/web/services/standby.py
index 5b5498bd0..bdabb5ec5 100644
--- a/src/xagent/web/services/standby.py
+++ b/src/xagent/web/services/standby.py
@@ -42,6 +42,55 @@ DeferredStep = Callable[[], Awaitable[None]]
FailureHook = Callable[[], Awaitable[None]]
+_LAG_PROBE_INTERVAL_SECONDS = 0.05
+
+
+class _LoopLagProbe:
+ """Track how late the event loop wakes a short sleep: its worst stall.
+
+ A step that blocks the loop (synchronous database work, a slow admission)
+ makes every request wait, including the host's lifecycle polls. The
+ activation log names the step and its stall so the next one is obvious.
+ """
+
+ def __init__(self) -> None:
+ self.max_lag = 0.0
+ self._expected: float | None = None
+ self._task: asyncio.Task[None] | None = None
+
+ def worst_lag(self) -> float:
+ """Max lag so far, counting a tick that is overdue and not yet seen.
+
+ A stall that ends exactly as a step returns has not woken the probe
+ yet; its overdue tick is the stall.
+ """
+ if self._expected is None:
+ return self.max_lag
+ return max(self.max_lag, asyncio.get_running_loop().time() - self._expected)
+
+ def start(self) -> None:
+ self._task = asyncio.ensure_future(self._run())
+
+ async def _run(self) -> None:
+ loop = asyncio.get_running_loop()
+ while True:
+ self._expected = loop.time() + _LAG_PROBE_INTERVAL_SECONDS
+ await asyncio.sleep(_LAG_PROBE_INTERVAL_SECONDS)
+ self.max_lag = max(self.max_lag, loop.time() - self._expected)
+
+ def stop(self) -> None:
+ """Cancel the probe without awaiting it.
+
+ Deliberately not a coroutine: an await here would be a cancellation
+ point outside activation's failure boundary, where a cancel would skip
+ the FAILED transition and the failure hooks. The cancelled task ends
+ on its own on the next loop iteration.
+ """
+ task, self._task = self._task, None
+ if task is not None:
+ task.cancel()
+
+
class StandbyController:
"""Ordered ledger of the startup steps a standby process postponed."""
@@ -122,6 +171,9 @@ class StandbyController:
self._activated_at = time.time()
steps = list(self._steps)
hooks = self._failure_hooks
+ probe = _LoopLagProbe()
+ probe.start()
+ overall_started = time.monotonic()
try:
for name, step in steps:
if self._phase is not StandbyPhase.ACTIVATING:
@@ -130,7 +182,23 @@ class StandbyController:
logger.info("Standby activation stopped before %s", name)
return
logger.info("Standby activation: %s", name)
- await step()
+ step_started = time.monotonic()
+ probe.max_lag = 0.0
+ try:
+ await step()
+ finally:
+ logger.info(
+ "Standby activation step %s took %.2fs "
+ "(max event loop lag %.3fs)",
+ name,
+ time.monotonic() - step_started,
+ probe.worst_lag(),
+ )
+ # A cancel requested during a step that never suspended is
+ # delivered here, inside the failure boundary, so it takes the
+ # fail-closed path (FAILED, hooks) instead of an ACTIVE process
+ # whose caller was told it was cancelled.
+ await asyncio.sleep(0)
except BaseException:
if self._phase is StandbyPhase.ACTIVATING:
self._activated_at = None
@@ -142,11 +210,16 @@ class StandbyController:
except Exception:
logger.exception("Standby failure hook failed")
raise
+ finally:
+ probe.stop()
# A shutdown that reset the ledger mid-activation owns the phase.
if self._phase is StandbyPhase.ACTIVATING:
self._steps.clear()
self._phase = StandbyPhase.ACTIVE
- logger.info("Standby activation complete")
+ logger.info(
+ "Standby activation complete in %.2fs",
+ time.monotonic() - overall_started,
+ )
def snapshot(self) -> dict[str, object]:
return {
diff --git a/src/xagent/web/services/writer_workers.py b/src/xagent/web/services/writer_workers.py
index 175012c2d..0b98d03f1 100644
--- a/src/xagent/web/services/writer_workers.py
+++ b/src/xagent/web/services/writer_workers.py
@@ -94,6 +94,33 @@ async def _run_tracked(
_active -= 1
+async def run_tracked_to_completion(
+ fn: Callable[..., T], /, *args: Any, **kwargs: Any
+) -> T:
+ """:func:`run_tracked` that a cancel cannot cut short once it was started.
+
+ A cancelled await still waits for the worker thread (and for a thread that
+ had not started yet, which is then started and finished) before the
+ cancellation propagates. For blocking startup work whose half-done state
+ must never be left behind: a migration, a schema seed. The result of a
+ cancelled call is discarded.
+ """
+ task = asyncio.ensure_future(run_tracked(fn, *args, **kwargs))
+ try:
+ return await asyncio.shield(task)
+ except asyncio.CancelledError:
+ # Join the worker however many more times this await is cancelled: the
+ # only exit is the task being done, so no cancel can return early.
+ while not task.done():
+ try:
+ await asyncio.wait({task})
+ except asyncio.CancelledError:
+ continue
+ if not task.cancelled():
+ task.exception() # consumed: the caller is already being cancelled
+ raise
+
+
def start_tracked_thread(
target: Callable[..., Any],
*,
diff --git a/src/xagent/web/startup_admission.py b/src/xagent/web/startup_admission.py
index a095da4b9..5687d1c3b 100644
--- a/src/xagent/web/startup_admission.py
+++ b/src/xagent/web/startup_admission.py
@@ -2,7 +2,9 @@
from __future__ import annotations
-from typing import Protocol
+import inspect
+from collections.abc import Awaitable, Callable
+from typing import Any, Protocol
from fastapi import FastAPI
@@ -10,14 +12,28 @@ _CALLBACKS_STATE_KEY = "_host_startup_admission_callbacks"
class HostStartupAdmissionCallback(Protocol):
- """Async host check that returns on admission and raises on rejection."""
+ """Host check that returns on admission and raises on rejection.
- async def __call__(self) -> None: ...
+ Invoked on the event loop, then awaited if it returned an awaitable: an
+ ``async def``, or a plain callable that builds a coroutine and may touch
+ the running loop while doing so.
+ """
+
+ def __call__(self) -> Awaitable[None] | None: ...
+
+
+class _ThreadedAdmission:
+ """A plain blocking callback the host registered to run in a worker thread."""
+
+ def __init__(self, callback: Callable[[], Any]) -> None:
+ self.callback = callback
def register_host_startup_admission(
app: FastAPI,
- callback: HostStartupAdmissionCallback,
+ callback: HostStartupAdmissionCallback | Callable[[], Any],
+ *,
+ run_in_thread: bool = False,
) -> None:
"""Register a callback to run before this app starts runtime work.
@@ -25,21 +41,45 @@ def register_host_startup_admission(
sequentially in registration order on every application lifespan. Any
exception is terminal for that startup and is propagated unchanged.
+ By default the callback is invoked on the event loop, exactly as it always
+ was. A host whose check does blocking database or file work passes
+ ``run_in_thread=True`` with a plain ``def`` that returns ``None``: it then
+ runs in a tracked worker thread (a cancel waits for it), so it cannot stall
+ the loop that answers lifecycle requests during a standby activation. It
+ must not touch the event loop, and returning an awaitable is rejected.
+
The immutable tuple is stored on the application instance rather than in
module state, so separate app instances and tests cannot leak callbacks
into one another.
"""
+ entry: object = _ThreadedAdmission(callback) if run_in_thread else callback
callbacks = _get_callbacks(app)
- setattr(app.state, _CALLBACKS_STATE_KEY, (*callbacks, callback))
+ setattr(app.state, _CALLBACKS_STATE_KEY, (*callbacks, entry))
async def run_host_startup_admissions(app: FastAPI) -> None:
"""Run a stable snapshot of this app's registered admission callbacks."""
for callback in _get_callbacks(app):
- await callback()
-
-
-def _get_callbacks(app: FastAPI) -> tuple[HostStartupAdmissionCallback, ...]:
+ if isinstance(callback, _ThreadedAdmission):
+ from .services.writer_workers import run_tracked_to_completion
+
+ result = await run_tracked_to_completion(callback.callback)
+ if inspect.isawaitable(result):
+ if inspect.iscoroutine(result):
+ result.close()
+ raise TypeError(
+ "a host startup admission registered with run_in_thread=True "
+ "must be a plain function that returns None, not an awaitable"
+ )
+ continue
+ result = callback()
+ if inspect.isawaitable(result):
+ await result
+
+
+def _get_callbacks(
+ app: FastAPI,
+) -> tuple[HostStartupAdmissionCallback | _ThreadedAdmission, ...]:
callbacks = getattr(app.state, _CALLBACKS_STATE_KEY, ())
return tuple(callbacks)
diff --git a/tests/integration/test_auto_migration_startup.py b/tests/integration/test_auto_migration_startup.py
index 36fe018e3..2755ff70a 100644
--- a/tests/integration/test_auto_migration_startup.py
+++ b/tests/integration/test_auto_migration_startup.py
@@ -785,7 +785,7 @@ async def test_startup_event_skips_when_auto_migrate_disabled(
lambda: runtime_start_order.append("admission"),
)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(
web_app_module,
@@ -914,7 +914,7 @@ async def test_startup_event_triggers_background_auto_migration(
monkeypatch.setenv("LANCEDB_AUTO_MIGRATE", "true")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
@@ -1048,7 +1048,7 @@ async def test_startup_event_no_task_when_no_table_needs_migration(
monkeypatch.setenv("LANCEDB_AUTO_MIGRATE", "true")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
@@ -1386,7 +1386,7 @@ async def test_failed_startup_leaves_no_unsignaled_temp_file_cleanup(
monkeypatch.setenv("SANDBOX_VOLUMES", "/foo:/guest1:ro;/foo:/guest2:ro")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
@@ -1570,7 +1570,7 @@ async def test_startup_event_runs_sandbox_readiness_before_cleanup_and_warmup(
monkeypatch.setenv("LANCEDB_AUTO_MIGRATE", "false")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
@@ -1673,7 +1673,7 @@ async def test_startup_event_raises_on_readiness_conflict_with_probe_true(
monkeypatch.setenv("SANDBOX_VOLUMES", "/foo:/guest1:ro;/foo:/guest2:ro")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
@@ -1748,7 +1748,7 @@ async def test_startup_event_skips_sandbox_readiness_when_manager_is_none(
monkeypatch.setenv("LANCEDB_AUTO_MIGRATE", "false")
monkeypatch.setattr(web_app_module, "init_db", lambda: None)
monkeypatch.setattr(
- web_app_module, "start_file_storage_startup_sync_task", lambda _app: None
+ web_app_module, "start_file_storage_startup_sync_task", lambda _app, **_kw: None
)
monkeypatch.setattr(web_app_module, "_migration_task", None)
monkeypatch.setattr(
diff --git a/tests/web/services/test_standby.py b/tests/web/services/test_standby.py
index 2d569ec62..c9e3dc1b5 100644
--- a/tests/web/services/test_standby.py
+++ b/tests/web/services/test_standby.py
@@ -219,7 +219,7 @@ async def test_startup_in_standby_defers_writes_and_activation_runs_them_in_orde
"start_task_cleanup_retry_task",
):
monkeypatch.setattr(
- app_module, name, lambda _app, name=name: events.append(name)
+ app_module, name, lambda _app, name=name, **_kw: events.append(name)
)
app_module.standby.begin()
diff --git a/tests/web/services/test_standby_startup.py b/tests/web/services/test_standby_startup.py
index fff77d4a4..6fe5303d1 100644
--- a/tests/web/services/test_standby_startup.py
+++ b/tests/web/services/test_standby_startup.py
@@ -107,7 +107,9 @@ def _patch_startup(monkeypatch: pytest.MonkeyPatch, events: list[str]) -> _Sandb
"start_runtime_performance_monitor",
"start_app_process_diagnostics",
):
- monkeypatch.setattr(app_module, name, lambda _a, n=name: events.append(n))
+ monkeypatch.setattr(
+ app_module, name, lambda _a, n=name, **_kw: events.append(n)
+ )
monkeypatch.setattr(
app_module,
"start_temp_file_cleanup_task",
diff --git a/tests/web/test_run_tracked_to_completion.py b/tests/web/test_run_tracked_to_completion.py
new file mode 100644
index 000000000..43ab00529
--- /dev/null
+++ b/tests/web/test_run_tracked_to_completion.py
@@ -0,0 +1,145 @@
+"""Cancellation contract of ``run_tracked_to_completion``.
+
+However many times the awaiting task is cancelled, the helper returns only once
+the worker thread is finished, it consumes the worker's outcome, and the
+tracking count returns to where it was.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import gc
+import threading
+from typing import Any
+
+import pytest
+
+from xagent.web.services import writer_workers
+from xagent.web.services.standby import StandbyController, StandbyPhase
+from xagent.web.services.writer_workers import run_tracked_to_completion
+
+_WAIT = 10.0
+
+
+async def _until(predicate: Any) -> None:
+ async def poll() -> None:
+ while not predicate():
+ await asyncio.sleep(0.005)
+
+ await asyncio.wait_for(poll(), _WAIT)
+
+
+class _Worker:
+ def __init__(self, *, fail: bool = False) -> None:
+ self.started = threading.Event()
+ self.release = threading.Event()
+ self.finished = threading.Event()
+ self.fail = fail
+
+ def __call__(self) -> str:
+ self.started.set()
+ self.release.wait(_WAIT)
+ self.finished.set()
+ if self.fail:
+ raise RuntimeError("worker failed after cancellation")
+ return "done"
+
+
[email protected]("cancels", [1, 2, 5])
+async def test_every_cancel_still_waits_for_the_worker(cancels: int) -> None:
+ baseline = writer_workers._active
+ worker = _Worker()
+ task = asyncio.ensure_future(run_tracked_to_completion(worker))
+ await _until(worker.started.is_set)
+ for _ in range(cancels):
+ task.cancel()
+ await asyncio.sleep(0.02)
+ assert not task.done() and not worker.finished.is_set()
+ worker.release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, _WAIT)
+ assert worker.finished.is_set()
+ await _until(lambda: writer_workers._active == baseline)
+
+
+async def test_activation_failure_handling_waits_for_a_twice_cancelled_worker() -> None:
+ controller = StandbyController()
+ worker = _Worker()
+ hooks: list[str] = []
+
+ async def hook() -> None:
+ hooks.append("failure hook")
+
+ async def step() -> None:
+ await run_tracked_to_completion(worker)
+
+ controller.begin()
+ controller.on_failure(hook)
+ controller.defer("init", step)
+ task = asyncio.ensure_future(controller.activate())
+ await _until(worker.started.is_set)
+ task.cancel()
+ await asyncio.sleep(0.02)
+ task.cancel() # second cancel, while the helper is joining the worker
+ await asyncio.sleep(0.05)
+ assert not task.done() and hooks == []
+ assert controller.phase is StandbyPhase.ACTIVATING
+ worker.release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, _WAIT)
+ assert worker.finished.is_set()
+ assert hooks == ["failure hook"]
+ assert controller.phase is StandbyPhase.FAILED
+
+
+async def test_worker_error_after_cancel_is_consumed_and_cancel_propagates() -> None:
+ loop = asyncio.get_running_loop()
+ seen: list[dict[str, Any]] = []
+ previous = loop.get_exception_handler()
+ loop.set_exception_handler(lambda _loop, ctx: seen.append(ctx))
+ try:
+ worker = _Worker(fail=True)
+ task = asyncio.ensure_future(run_tracked_to_completion(worker))
+ await _until(worker.started.is_set)
+ task.cancel()
+ await asyncio.sleep(0.02)
+ worker.release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, _WAIT)
+ del task
+ gc.collect()
+ await asyncio.sleep(0.05)
+ finally:
+ loop.set_exception_handler(previous)
+ assert seen == []
+
+
+async def test_cancel_right_after_submit_keeps_the_count_consistent() -> None:
+ baseline = writer_workers._active
+ ran = threading.Event()
+
+ def work() -> None:
+ ran.set()
+
+ task = asyncio.ensure_future(run_tracked_to_completion(work))
+ await asyncio.sleep(0) # the thread was submitted, maybe not yet started
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, _WAIT)
+ assert ran.is_set() # started or not, the work is finished, never half-done
+ await _until(lambda: writer_workers._active == baseline)
+
+
+async def test_normal_result_and_error_pass_through() -> None:
+ assert await run_tracked_to_completion(lambda: 7) == 7
+
+ def boom() -> None:
+ raise ValueError("x")
+
+ with pytest.raises(ValueError):
+ await run_tracked_to_completion(boom)
diff --git a/tests/web/test_standby_activation_off_loop.py b/tests/web/test_standby_activation_off_loop.py
new file mode 100644
index 000000000..7cd2ba3a8
--- /dev/null
+++ b/tests/web/test_standby_activation_off_loop.py
@@ -0,0 +1,227 @@
+"""Standby activation keeps the event loop serving while blocking work runs."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import threading
+import time
+from unittest.mock import Mock
+
+import pytest
+from fastapi import FastAPI
+
+from xagent.web import app as app_module
+from xagent.web.services.standby import StandbyController, StandbyPhase
+from xagent.web.startup_admission import (
+ register_host_startup_admission,
+ run_host_startup_admissions,
+)
+
+_BLOCK_SECONDS = 5.0
+
+
+async def _wait_for(event: threading.Event) -> None:
+ deadline = time.monotonic() + _BLOCK_SECONDS
+ while not event.is_set():
+ assert time.monotonic() < deadline, "blocking work never started"
+ await asyncio.sleep(0.005)
+
+
+def _patch_rest_of_admission(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def no_admissions(_app) -> None:
+ return None
+
+ monkeypatch.setattr(app_module, "run_host_startup_admissions", no_admissions)
+ monkeypatch.setattr(
+ "xagent.web.services.trace_database.get_trace_database_runtime", lambda: None
+ )
+
+
[email protected]("bound", [True, False])
+async def test_database_init_does_not_block_the_event_loop(
+ monkeypatch: pytest.MonkeyPatch, bound: bool
+) -> None:
+ started = threading.Event()
+ release = threading.Event()
+ ran_on: list[int] = []
+
+ def blocking_init() -> None:
+ ran_on.append(threading.get_ident())
+ started.set()
+ # Only a loop that keeps running can ever set ``release``.
+ assert release.wait(_BLOCK_SECONDS), "event loop was blocked by init"
+
+ monkeypatch.setattr(app_module, "complete_standby_db_init", blocking_init)
+ monkeypatch.setattr(app_module, "init_db", blocking_init)
+ _patch_rest_of_admission(monkeypatch)
+
+ task = asyncio.ensure_future(
+ app_module._admit_database_and_host(FastAPI(), bound=bound)
+ )
+ await _wait_for(started)
+ ticks = 0
+ for _ in range(5):
+ await asyncio.sleep(0.01)
+ ticks += 1
+ assert ticks == 5 and not task.done()
+ release.set()
+ await asyncio.wait_for(task, _BLOCK_SECONDS)
+ assert ran_on[0] != threading.get_ident()
+
+
+async def test_cancelled_activation_waits_for_database_init_to_finish(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ started = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+
+ def init() -> None:
+ started.set()
+ release.wait(_BLOCK_SECONDS)
+ finished.set()
+
+ monkeypatch.setattr(app_module, "complete_standby_db_init", init)
+ _patch_rest_of_admission(monkeypatch)
+
+ task = asyncio.ensure_future(
+ app_module._admit_database_and_host(FastAPI(), bound=True)
+ )
+ await _wait_for(started)
+ task.cancel()
+ await asyncio.sleep(0.05)
+ # The cancel must not abandon a half-done migration/seed.
+ assert not task.done() and not finished.is_set()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await asyncio.wait_for(task, _BLOCK_SECONDS)
+ assert finished.is_set()
+
+
+async def test_default_path_invokes_every_callback_on_the_event_loop() -> None:
+ app = FastAPI()
+ events: list[tuple[str, bool]] = []
+ main = threading.get_ident()
+
+ def factory():
+ # A decorator/factory style callable: it needs the running loop while
+ # building the awaitable it returns.
+ asyncio.get_running_loop()
+
+ async def run() -> None:
+ events.append(("factory result", threading.get_ident() == main))
+
+ return run()
+
+ def plain() -> None:
+ events.append(("plain", threading.get_ident() == main))
+
+ async def async_check() -> None:
+ events.append(("async", threading.get_ident() == main))
+
+ register_host_startup_admission(app, factory)
+ register_host_startup_admission(app, plain)
+ register_host_startup_admission(app, async_check)
+ register_host_startup_admission(app, Mock())
+ await run_host_startup_admissions(app)
+ assert events == [("factory result", True), ("plain", True), ("async", True)]
+
+
+async def test_opt_in_callback_runs_off_the_loop_in_registration_order() -> None:
+ app = FastAPI()
+ events: list[tuple[str, bool]] = []
+ main = threading.get_ident()
+
+ def threaded() -> None:
+ events.append(("threaded", threading.get_ident() != main))
+
+ async def async_check() -> None:
+ events.append(("async", threading.get_ident() == main))
+
+ register_host_startup_admission(app, async_check)
+ register_host_startup_admission(app, threaded, run_in_thread=True)
+ register_host_startup_admission(app, async_check)
+ await run_host_startup_admissions(app)
+ assert events == [("async", True), ("threaded", True), ("async", True)]
+
+
+async def test_opt_in_callback_returning_an_awaitable_is_rejected_clearly() -> None:
+ app = FastAPI()
+
+ async def coroutine_function() -> None: ...
+
+ register_host_startup_admission(app, coroutine_function, run_in_thread=True)
+ with pytest.raises(TypeError, match="run_in_thread=True"):
+ await run_host_startup_admissions(app)
+
+
+async def test_sync_admission_rejection_propagates_unchanged() -> None:
+ app = FastAPI()
+
+ def reject() -> None:
+ raise RuntimeError("catalog refused")
+
+ register_host_startup_admission(app, reject, run_in_thread=True)
+ with pytest.raises(RuntimeError, match="catalog refused"):
+ await run_host_startup_admissions(app)
+
+
+async def test_activation_logs_step_duration_and_loop_lag(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ controller = StandbyController()
+
+ async def stalls_the_loop() -> None:
+ await asyncio.sleep(0.12) # let the probe take a baseline tick
+ time.sleep(0.3) # synchronous work on the loop
+
+ controller.begin()
+ controller.defer("stalling step", stalls_the_loop)
+ with caplog.at_level(logging.INFO, logger="xagent.web.services.standby"):
+ await controller.activate()
+
+ line = next(
+ r.getMessage() for r in caplog.records if "stalling step took" in r.getMessage()
+ )
+ lag = float(line.rsplit("lag ", 1)[1].rstrip("s)"))
+ assert lag >= 0.2, line
+ assert any("activation complete in" in r.getMessage() for r in caplog.records)
+
+
+async def test_cancel_at_the_end_of_the_last_step_still_closes_activation() -> None:
+ """A cancel landing after the final step must not strand the phase.
+
+ The last step has no suspension of its own, so a cancel requested inside it
+ is delivered at the first suspension after it: whatever activation does
+ next. That point must stay inside the failure boundary, or the phase stays
+ ``ACTIVATING`` and the failure hooks (which reseal admission and stop the
+ started paths) never run.
+ """
+ controller = StandbyController()
+ hooks: list[str] = []
+ holder: dict[str, asyncio.Task[None]] = {}
+
+ async def last_step_requests_cancel() -> None:
+ holder["task"].cancel() # delivered at the next suspension point
+
+ async def hook() -> None:
+ hooks.append("failure hook")
+
+ controller.begin()
+ controller.on_failure(hook)
+ controller.defer("last step", last_step_requests_cancel)
+ holder["task"] = asyncio.ensure_future(controller.activate())
+ with pytest.raises(asyncio.CancelledError):
+ await holder["task"]
+
+ assert controller.phase is StandbyPhase.FAILED
+ assert hooks == ["failure hook"]
diff --git a/tests/web/test_startup_admission.py b/tests/web/test_startup_admission.py
index 0dcd6dfac..6f711b142 100644
--- a/tests/web/test_startup_admission.py
+++ b/tests/web/test_startup_admission.py
@@ -47,7 +47,7 @@ def _patch_runtime_starts(
monkeypatch.setattr(
app_module,
name,
- lambda _app, event=event: events.append(event),
+ lambda _app, event=event, **_kw: events.append(event),
)
diff --git a/tests/web/test_startup_sync_lifecycle_bypass.py b/tests/web/test_startup_sync_lifecycle_bypass.py
index 2e5aa6f42..7752561d6 100644
--- a/tests/web/test_startup_sync_lifecycle_bypass.py
+++ b/tests/web/test_startup_sync_lifecycle_bypass.py
@@ -648,6 +648,8 @@ async def test_retry_after_a_stall_resumes_instead_of_restarting(monkeypatch, tm
# from the beginning would list users 1-3 again).
assert sorted(storage.list_prefixes) == sorted(set(storage.list_prefixes))
assert len(storage.list_prefixes) == 6
+ # The cancelled attempt's thread is still counted until it returns.
+ assert await app_module.drain_workers(10)
@pytest.mark.asyncio
@@ -672,6 +674,9 @@ async def test_a_real_stall_still_trips_the_timeout_and_dumps_stacks(monkeypatch
dump.assert_called_once()
finally:
release.set()
+ # The stalled worker keeps its count until the thread returns; let it
+ # finish so the fixture's leak check does not race its last instructions.
+ assert await app_module.drain_workers(10)
def test_cancel_during_the_first_listing_stops_before_the_next_users_listing(tmp_path):