Skip to content

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

fix(web): let lifecycle endpoints bypass the startup sync gate and move the sync out of activation (#3822)

OliverBryanta5f890493a37
diff --git a/src/xagent/web/app.py b/src/xagent/web/app.py
index b1da2273e..a32250031 100644
--- a/src/xagent/web/app.py
+++ b/src/xagent/web/app.py
@@ -1,4 +1,6 @@
import asyncio
+import contextvars
+import faulthandler
import functools
import importlib
import json
@@ -6,9 +8,11 @@ import logging
import mimetypes
import os
import random
+import sys
import threading
import time
from collections.abc import Awaitable, Callable, Iterator
+from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager, suppress
from pathlib import PurePosixPath
from typing import Any, cast
@@ -151,7 +155,7 @@ 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
+from .services.writer_workers import drain_workers, run_tracked, run_tracked_in
from .startup_admission import run_host_startup_admissions
# Configure logging when running under gunicorn/uwsgi (no __main__.py)
@@ -276,10 +280,94 @@ _sandbox_idle_sweep_task: asyncio.Task[None] | None = None
FILE_STORAGE_STARTUP_SYNC_EXEMPT_PATHS = frozenset({"/health", "/ready"})
FILE_STORAGE_STARTUP_SYNC_RETRY_INTERVAL_SECONDS = 5.0
FILE_STORAGE_STARTUP_SYNC_GATE_POLL_INTERVAL_SECONDS = 0.25
+# One attempt is logged every progress interval. If it makes no progress (no
+# file or batch completed) for the dump threshold, every thread's stack is
+# dumped; after the stall window it is cancelled and retried from where it got
+# to. A long scan that keeps completing work is never cancelled.
+FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS = 30.0
+FILE_STORAGE_STARTUP_SYNC_DUMP_AFTER_SECONDS = 60.0
+FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS = 600.0
+FILE_STORAGE_STARTUP_SYNC_CANCEL_GRACE_SECONDS = 10.0
+
+# Path prefixes the host app keeps answering while the startup sync runs, so
+# control endpoints (a release host's lifecycle probe) never wait on file I/O.
+_file_storage_startup_sync_exempt_prefixes: set[str] = set()
+_file_storage_sync_executor: ThreadPoolExecutor | None = None
+
+
+def register_file_storage_startup_sync_exempt_prefix(prefix: str) -> None:
+ """Let requests under ``prefix`` bypass the startup file storage sync gate."""
+ normalized = str(prefix or "").strip()
+ if not normalized.startswith("/"):
+ raise ValueError("exempt prefix must start with '/'")
+ _file_storage_startup_sync_exempt_prefixes.add(normalized)
+
+
+def _is_file_storage_startup_sync_exempt(path: str) -> bool:
+ if path in FILE_STORAGE_STARTUP_SYNC_EXEMPT_PATHS:
+ return True
+ return any(
+ path.startswith(prefix) for prefix in _file_storage_startup_sync_exempt_prefixes
+ )
+
+
+def _get_file_storage_sync_executor() -> ThreadPoolExecutor:
+ """Small dedicated pool: a stuck sync cannot starve ``asyncio.to_thread``."""
+ global _file_storage_sync_executor
+ if _file_storage_sync_executor is None:
+ _file_storage_sync_executor = ThreadPoolExecutor(
+ max_workers=2, thread_name_prefix="startup-file-sync"
+ )
+ return _file_storage_sync_executor
+
+
+def get_file_storage_startup_sync_status(app_instance: FastAPI) -> dict[str, Any]:
+ """Cheap, non-blocking view of the startup sync for host lifecycle reports.
+
+ ``state`` is ``disabled`` | ``pending`` | ``running`` | ``failed`` | ``done``;
+ ``gating`` says whether client requests currently wait on it.
+ """
+ state = app_instance.state
+ task = getattr(state, "file_storage_startup_sync_task", None)
+ error = getattr(state, "file_storage_startup_sync_error", None)
+ completed = bool(getattr(state, "file_storage_startup_sync_completed", False))
+ started = getattr(state, "file_storage_startup_sync_started_at", None)
+ finished = getattr(state, "file_storage_startup_sync_finished_at", None)
+ if not get_file_storage_startup_sync_enabled():
+ name = "disabled"
+ elif error is not None:
+ name = "failed"
+ elif completed:
+ name = "done"
+ elif task is not None and not task.done():
+ name = "running"
+ else:
+ name = "pending"
+ elapsed: float | None = None
+ if started is not None:
+ elapsed = round(
+ (finished if finished is not None else time.monotonic()) - started, 3
+ )
+ status: dict[str, Any] = {
+ "state": name,
+ "elapsed_seconds": elapsed,
+ "gating": bool(getattr(state, "file_storage_startup_sync_gating", True)),
+ }
+ if error is not None:
+ status["error"] = type(error).__name__
+ return status
+
+
+# Carries the attempt's cancel/progress control into the sync thread without
+# widening the signature hosts and tests patch.
+_file_storage_sync_control: contextvars.ContextVar[Any] = contextvars.ContextVar(
+ "file_storage_sync_control", default=None
+)
def run_startup_file_storage_sync() -> None:
"""Synchronize DB-registered local files into durable S3 storage."""
+ control = _file_storage_sync_control.get()
if not get_file_storage_startup_sync_enabled():
logger.info("Startup file storage sync is disabled")
return
@@ -288,21 +376,102 @@ def run_startup_file_storage_sync() -> None:
sync_registered_files_to_durable_storage,
)
- result = sync_registered_files_to_durable_storage()
+ if control is None:
+ result = sync_registered_files_to_durable_storage()
+ else:
+ result = sync_registered_files_to_durable_storage(control=control)
+ if result.locked:
+ # An earlier attempt's thread is still inside the sync (it was
+ # cancelled at its deadline but has not reached a checkpoint).
+ # Reporting success here would mark the sync complete.
+ raise RuntimeError(
+ "Startup file storage sync is still running from a previous attempt"
+ )
if result.failed:
raise RuntimeError(
f"Startup file storage sync failed for {result.failed} registered file(s)"
)
+def _dump_all_thread_stacks(reason: str) -> None:
+ logger.error("Dumping all thread stacks to stderr: %s", reason)
+ try:
+ faulthandler.dump_traceback(file=sys.stderr, all_threads=True)
+ except Exception: # noqa: BLE001
+ logger.exception("Could not dump thread stacks")
+
+
+async def _run_bounded_file_storage_sync_attempt(resume: Any = None) -> None:
+ """One sync attempt with progress logs, a stack dump and a stall timeout."""
+ from .services.startup_file_storage_sync import StartupSyncControl
+
+ control = StartupSyncControl(resume)
+ started = time.monotonic()
+
+ def _attempt() -> None:
+ token = _file_storage_sync_control.set(control)
+ try:
+ run_startup_file_storage_sync()
+ finally:
+ _file_storage_sync_control.reset(token)
+
+ future = asyncio.ensure_future(
+ run_tracked_in(_get_file_storage_sync_executor(), _attempt)
+ )
+ dumped = False
+ try:
+ while True:
+ done, _ = await asyncio.wait(
+ {future},
+ timeout=FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS,
+ )
+ if done:
+ return future.result()
+ now = time.monotonic()
+ elapsed = now - started
+ idle = now - control.last_progress
+ logger.warning(
+ "Startup file storage sync still running: elapsed=%.0fs "
+ "no_progress=%.0fs scanned=%s phase=%s",
+ elapsed,
+ idle,
+ control.scanned,
+ control.phase,
+ )
+ if not dumped and idle >= FILE_STORAGE_STARTUP_SYNC_DUMP_AFTER_SECONDS:
+ dumped = True
+ _dump_all_thread_stacks(
+ f"startup file storage sync made no progress for {idle:.0f}s"
+ )
+ if idle >= FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS:
+ control.cancel.set()
+ done, _ = await asyncio.wait(
+ {future}, timeout=FILE_STORAGE_STARTUP_SYNC_CANCEL_GRACE_SECONDS
+ )
+ if done:
+ future.exception() # cancelled at a checkpoint; retrieve it
+ raise TimeoutError(
+ "Startup file storage sync made no progress for "
+ f"{idle:.0f}s (scanned={control.scanned} phase={control.phase})"
+ )
+ except BaseException:
+ control.cancel.set()
+ raise
+
+
async def _run_file_storage_startup_sync_with_retries(
app_instance: FastAPI,
*,
retry_interval_seconds: float,
) -> None:
+ app_instance.state.file_storage_startup_sync_started_at = time.monotonic()
+ app_instance.state.file_storage_startup_sync_finished_at = None
+ from .services.startup_file_storage_sync import StartupSyncResume
+
+ resume = StartupSyncResume() # survives retries: a stall does not rescan
while True:
try:
- await run_tracked(run_startup_file_storage_sync)
+ await _run_bounded_file_storage_sync_attempt(resume)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001
@@ -318,6 +487,7 @@ async def _run_file_storage_startup_sync_with_retries(
else:
app_instance.state.file_storage_startup_sync_error = None
app_instance.state.file_storage_startup_sync_completed = True
+ app_instance.state.file_storage_startup_sync_finished_at = time.monotonic()
return
@@ -325,12 +495,21 @@ def start_file_storage_startup_sync_task(
app_instance: FastAPI,
*,
retry_interval_seconds: float | None = None,
+ gating: bool = True,
) -> asyncio.Task[Any] | None:
- """Start durable file storage startup sync without blocking app startup."""
+ """Start durable file storage startup sync without blocking app startup.
+
+ ``gating=False`` runs the same sync in the background while client
+ requests and ``/ready`` proceed; only a standby whose read-only preflight
+ found nothing to write uses it.
+ """
global _file_storage_startup_sync_task
app_instance.state.file_storage_startup_sync_task = None
app_instance.state.file_storage_startup_sync_error = None
+ app_instance.state.file_storage_startup_sync_gating = gating
+ app_instance.state.file_storage_startup_sync_started_at = None
+ app_instance.state.file_storage_startup_sync_finished_at = None
if not get_file_storage_startup_sync_enabled():
logger.info("Startup file storage sync is disabled")
@@ -365,6 +544,10 @@ def start_file_storage_startup_sync_task(
else:
app_instance.state.file_storage_startup_sync_error = None
app_instance.state.file_storage_startup_sync_completed = True
+ if app_instance.state.file_storage_startup_sync_finished_at is None:
+ app_instance.state.file_storage_startup_sync_finished_at = (
+ time.monotonic()
+ )
task.add_done_callback(_record_file_storage_sync_result)
logger.info("Started background startup file storage sync task")
@@ -1262,6 +1445,8 @@ def start_temp_file_cleanup_task(
async def wait_for_file_storage_startup_sync(app_instance: FastAPI) -> None:
"""Wait until durable file storage startup sync has completed successfully."""
+ if not getattr(app_instance.state, "file_storage_startup_sync_gating", True):
+ return
while True:
error = getattr(app_instance.state, "file_storage_startup_sync_error", None)
if error is not None:
@@ -1315,7 +1500,7 @@ class FileStorageStartupSyncGateMiddleware:
return
path = str(scope.get("path") or "")
- if path in FILE_STORAGE_STARTUP_SYNC_EXEMPT_PATHS:
+ if _is_file_storage_startup_sync_exempt(path):
await self.app(scope, receive, send)
return
if scope_type == "http" and str(scope.get("method") or "").upper() == "OPTIONS":
@@ -1384,6 +1569,9 @@ async def readiness_check() -> JSONResponse:
"""
task = getattr(app.state, "file_storage_startup_sync_task", None)
error = getattr(app.state, "file_storage_startup_sync_error", None)
+ if not getattr(app.state, "file_storage_startup_sync_gating", True):
+ task = None
+ error = None
if error is not None:
return JSONResponse(
@@ -1975,6 +2163,62 @@ async def _open_admission() -> None:
release_hold.reopen()
+async def _run_file_storage_preflight(app_instance: FastAPI) -> None:
+ """Standby: classify registered files read-only, before activation.
+
+ The result lets activation skip the gated write pass when every file is
+ already durable. Any failure leaves no result, which activation reads as
+ "unknown" and answers with the full gated sync.
+ """
+ from .services.startup_file_storage_sync import (
+ StartupSyncControl,
+ preflight_registered_files,
+ )
+
+ control = StartupSyncControl()
+ app_instance.state.file_storage_preflight_control = control
+ app_instance.state.file_storage_preflight_result = None
+ try:
+ result = await asyncio.get_running_loop().run_in_executor(
+ _get_file_storage_sync_executor(),
+ functools.partial(preflight_registered_files, control=control),
+ )
+ except asyncio.CancelledError:
+ control.cancel.set()
+ raise
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "Standby file storage preflight failed; activation will run the full sync"
+ )
+ return
+ app_instance.state.file_storage_preflight_result = result
+
+
+def _start_file_storage_preflight(app_instance: FastAPI) -> None:
+ app_instance.state.file_storage_preflight_task = None
+ app_instance.state.file_storage_preflight_result = None
+ if not get_file_storage_startup_sync_enabled():
+ return
+ app_instance.state.file_storage_preflight_task = asyncio.create_task(
+ _run_file_storage_preflight(app_instance)
+ )
+
+
+def _file_storage_sync_should_gate(app_instance: FastAPI) -> bool:
+ """Whether client requests wait for the post-activation sync.
+
+ Only a standby whose preflight finished before activation and found every
+ registered file already durable (or unreachable locally, which the sync
+ skips) starts the sync in the background. Anything else -- a normal start,
+ a preflight that is unfinished, failed or found files to write -- keeps the
+ gate: those files must be durable before clients are served, as before.
+ """
+ if getattr(app_instance.state, "file_storage_preflight_task", None) is None:
+ return True
+ result = getattr(app_instance.state, "file_storage_preflight_result", None)
+ return result is None or not result.clean
+
+
async def _start_local_runtime_loops(app_instance: FastAPI) -> None:
# Reopen process-local task admission before any trigger, command, or
# channel ingress can create background execution work for this lifespan.
@@ -1983,7 +2227,14 @@ async def _start_local_runtime_loops(app_instance: FastAPI) -> None:
if not get_shared_task_execution_enabled():
background_task_manager.start_accepting()
- start_file_storage_startup_sync_task(app_instance)
+ if _file_storage_sync_should_gate(app_instance):
+ start_file_storage_startup_sync_task(app_instance)
+ else:
+ logger.info(
+ "Standby preflight found every registered file durable; the startup "
+ "file storage sync runs in the background without gating requests"
+ )
+ start_file_storage_startup_sync_task(app_instance, gating=False)
if not get_shared_task_execution_enabled():
start_trigger_dispatcher_task(app_instance)
start_task_lease_recovery_task(app_instance)
@@ -2016,6 +2267,7 @@ async def _initialize_database_and_admit_runtime(app_instance: FastAPI) -> None:
"local runtime loops",
functools.partial(_start_local_runtime_loops, app_instance),
)
+ _start_file_storage_preflight(app_instance)
return
await _admit_database_and_host(app_instance, bound=False)
@@ -2608,6 +2860,13 @@ async def _stop_runtime_loops() -> None:
await _sandbox_idle_sweep_task
_sandbox_idle_sweep_task = None
+ preflight_task = getattr(app.state, "file_storage_preflight_task", None)
+ if preflight_task is not None and not preflight_task.done():
+ preflight_task.cancel()
+ with suppress(asyncio.CancelledError):
+ await preflight_task
+ app.state.file_storage_preflight_task = None
+
if _file_storage_startup_sync_task and not _file_storage_startup_sync_task.done():
logger.info("Cancelling background startup file storage sync task...")
_file_storage_startup_sync_task.cancel()
diff --git a/src/xagent/web/services/startup_file_storage_sync.py b/src/xagent/web/services/startup_file_storage_sync.py
index 36671ff24..115f0ed45 100644
--- a/src/xagent/web/services/startup_file_storage_sync.py
+++ b/src/xagent/web/services/startup_file_storage_sync.py
@@ -137,12 +137,140 @@ _StartupSyncCursor = tuple[int, int]
_SessionFactory = Callable[[], Session]
+class StartupSyncCancelled(RuntimeError):
+ """The sync was told to stop (deadline exceeded or process shutdown)."""
+
+
+class StartupSyncResume:
+ """Where the last attempt got to, kept across the retry loop's attempts.
+
+ ``cursor`` is the last candidate that finished without a failure; a retry
+ continues after it instead of rescanning every user. It never moves past a
+ failed candidate, so that candidate is attempted again.
+ """
+
+ def __init__(self) -> None:
+ self.cursor: tuple[int, int] | None = None
+
+
+class StartupSyncControl:
+ """Cooperative cancel flag, progress marker and resume point for one attempt.
+
+ The sync thread calls :meth:`checkpoint` before each file's storage I/O
+ and between batches, so a watchdog can stop it at the next boundary and
+ can tell a long but progressing scan from a stalled one
+ (:attr:`last_progress`). A single storage or database call that never
+ returns cannot be interrupted from here; the watchdog's thread dump is what
+ makes that case diagnosable.
+ """
+
+ def __init__(self, resume: StartupSyncResume | None = None) -> None:
+ self.cancel = threading.Event()
+ self.scanned = 0
+ self.phase = "starting"
+ self.resume = resume if resume is not None else StartupSyncResume()
+ self.last_progress = time.monotonic()
+
+ def checkpoint(self, phase: str | None = None, *, progress: bool = True) -> None:
+ if phase is not None:
+ self.phase = phase
+ if self.cancel.is_set():
+ raise StartupSyncCancelled("Startup file storage sync was cancelled")
+ if progress:
+ self.last_progress = time.monotonic()
+
+
+@dataclass(frozen=True)
+class StartupFileStoragePreflight:
+ """Outcome of the read-only pass: does any registered file need a write?"""
+
+ scanned: int = 0
+ needs_write: int = 0
+ skipped_missing_local: int = 0
+ skipped_backend: bool = False
+
+ @property
+ def clean(self) -> bool:
+ return self.needs_write == 0
+
+
+def preflight_registered_files(
+ *,
+ storage: FsspecFileStorage | Any | None = None,
+ batch_size: int = 500,
+ session_factory: _SessionFactory | None = None,
+ control: StartupSyncControl | None = None,
+) -> StartupFileStoragePreflight:
+ """Classify every registered file without writing storage or the database.
+
+ Uses the same candidate scan and per-user listing as the real sync and the
+ same "already durable" test, but never adopts, uploads or persists. A
+ standby runs it before activation so activation can skip the write pass
+ when nothing needs writing.
+ """
+ backend = _detect_backend(storage)
+ if backend != "s3":
+ return StartupFileStoragePreflight(skipped_backend=True)
+
+ factory = session_factory or _resolve_session_factory(None, None)
+ scanned = 0
+ needs_write = 0
+ skipped_missing_local = 0
+ cursor: _StartupSyncCursor | None = None
+ current_user_id: int | None = None
+ remote_objects: dict[str, Any] = {}
+ user_storage: ScopedFileStorage | None = None
+ while True:
+ if control is not None:
+ control.checkpoint("preflight scan")
+ candidates, next_cursor = _load_startup_sync_candidates(
+ factory, after=cursor, limit=max(1, int(batch_size))
+ )
+ if not candidates:
+ break
+ for candidate, _version in candidates:
+ if control is not None:
+ control.checkpoint() # before this candidate's storage I/O
+ scanned += 1
+ if candidate.user_id != current_user_id or user_storage is None:
+ current_user_id = candidate.user_id
+ user_storage = _user_scoped_storage(storage, candidate.user_id)
+ remote_objects = _list_remote_objects_for_user(user_storage)
+ key = _expected_storage_key(candidate)
+ if key in remote_objects:
+ if not _has_complete_durable_metadata(candidate):
+ needs_write += 1 # adoption persists the row
+ continue
+ local_path = Path(candidate.storage_path)
+ if not local_path.exists() or not local_path.is_file():
+ skipped_missing_local += 1
+ continue
+ needs_write += 1
+ cursor = next_cursor
+ if control is not None:
+ control.scanned = scanned
+ result = StartupFileStoragePreflight(
+ scanned=scanned,
+ needs_write=needs_write,
+ skipped_missing_local=skipped_missing_local,
+ )
+ logger.info(
+ "Startup file storage preflight complete: scanned=%s needs_write=%s "
+ "skipped_missing_local=%s",
+ result.scanned,
+ result.needs_write,
+ result.skipped_missing_local,
+ )
+ return result
+
+
def sync_registered_files_to_durable_storage(
db: Session | None = None,
*,
storage: FsspecFileStorage | Any | None = None,
batch_size: int = 500,
session_factory: _SessionFactory | None = None,
+ control: StartupSyncControl | None = None,
) -> StartupFileStorageSyncResult:
"""Reconcile DB registrations without holding a connection during storage I/O.
@@ -168,11 +296,12 @@ def sync_registered_files_to_durable_storage(
file_lock = None
try:
SessionLocal = _resolve_session_factory(db, session_factory)
- file_lock = _acquire_file_lock_after_contention()
+ file_lock = _acquire_file_lock_after_contention(control)
return _sync_registered_files(
SessionLocal,
storage=storage,
batch_size=batch_size,
+ control=control,
)
finally:
if file_lock is not None:
@@ -199,9 +328,13 @@ def _resolve_session_factory(
return get_session_local()
-def _acquire_file_lock_after_contention() -> Any:
+def _acquire_file_lock_after_contention(
+ control: StartupSyncControl | None = None,
+) -> Any:
file_lock = _acquire_file_lock()
while file_lock is None:
+ if control is not None:
+ control.checkpoint("waiting for sync lock holder", progress=False)
logger.info(
"Startup file storage sync is already running in another process; waiting"
)
@@ -236,6 +369,7 @@ def _sync_registered_files(
*,
storage: FsspecFileStorage | Any | None,
batch_size: int,
+ control: StartupSyncControl | None = None,
) -> StartupFileStorageSyncResult:
scanned = 0
already_present = 0
@@ -244,11 +378,16 @@ def _sync_registered_files(
failed = 0
resolved_batch_size = max(1, int(batch_size))
- cursor: _StartupSyncCursor | None = None
+ cursor: _StartupSyncCursor | None = (
+ control.resume.cursor if control is not None else None
+ )
+ previous: _StartupFileStorageCandidate | None = None
current_user_id: int | None = None
user_storage: ScopedFileStorage | None = None
remote_objects: dict[str, Any] = {}
while True:
+ if control is not None:
+ control.checkpoint("sync scan")
candidates, next_cursor = _load_startup_sync_candidates(
session_factory,
after=cursor,
@@ -257,6 +396,15 @@ def _sync_registered_files(
if not candidates:
break
for candidate, expected_version in candidates:
+ if control is not None:
+ # The previous candidate finished cleanly: a retry resumes
+ # after it. Frozen once any file failed, so that file (and
+ # whatever follows) is attempted again.
+ if previous is not None and failed == 0:
+ control.resume.cursor = (previous.user_id, previous.id)
+ control.checkpoint() # before this candidate's storage I/O
+ control.scanned = scanned + 1
+ previous = candidate
scanned += 1
user_id = candidate.user_id
if user_id != current_user_id or user_storage is None:
@@ -367,6 +515,8 @@ def _sync_registered_files(
uploaded += 1
cursor = next_cursor
+ if control is not None and failed == 0 and next_cursor is not None:
+ control.resume.cursor = next_cursor
result = StartupFileStorageSyncResult(
scanned=scanned,
diff --git a/src/xagent/web/services/writer_workers.py b/src/xagent/web/services/writer_workers.py
index 416e73e18..175012c2d 100644
--- a/src/xagent/web/services/writer_workers.py
+++ b/src/xagent/web/services/writer_workers.py
@@ -15,6 +15,7 @@ import contextvars
import functools
import threading
from collections.abc import Callable, Iterator
+from concurrent.futures import Executor
from contextlib import contextmanager
from typing import Any, TypeVar
@@ -30,6 +31,34 @@ _active = 0
async def run_tracked(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
"""``asyncio.to_thread``, counted until the thread itself returns.
+ See :func:`run_tracked_in` for the same accounting on a dedicated executor.
+ """
+ return await _run_tracked(None, fn, args, kwargs)
+
+
+async def run_tracked_in(
+ executor: Executor,
+ fn: Callable[..., T],
+ /,
+ *args: Any,
+ **kwargs: Any,
+) -> T:
+ """:func:`run_tracked` on ``executor`` instead of the default one.
+
+ A bounded executor keeps one stuck job from exhausting the loop's default
+ thread pool, which every ``asyncio.to_thread`` caller shares.
+ """
+ return await _run_tracked(executor, fn, args, kwargs)
+
+
+async def _run_tracked(
+ executor: Executor | None,
+ fn: Callable[..., T],
+ args: tuple[Any, ...],
+ kwargs: dict[str, Any],
+) -> T:
+ """Run ``fn`` in a thread, counted until the thread itself returns.
+
Cancelling the await before the thread started drops the work and the
count; once it started the thread keeps its count until it finishes.
"""
@@ -52,7 +81,12 @@ async def run_tracked(fn: Callable[..., T], /, *args: Any, **kwargs: Any) -> T:
with _lock:
_active += 1
try:
- return await asyncio.to_thread(runner)
+ if executor is None:
+ return await asyncio.to_thread(runner)
+ context = contextvars.copy_context()
+ return await asyncio.get_running_loop().run_in_executor(
+ executor, functools.partial(context.run, runner)
+ )
finally:
with _lock:
if not state["started"]:
diff --git a/tests/web/test_blocking_call_inventory.py b/tests/web/test_blocking_call_inventory.py
index 47959f544..128437404 100644
--- a/tests/web/test_blocking_call_inventory.py
+++ b/tests/web/test_blocking_call_inventory.py
@@ -81,11 +81,16 @@ ALLOWED: dict[str, tuple[int, str]] = {
"web/api/workforces.py": (2, HTTP),
# -- web: lifecycle and telemetry -------------------------------------------
"web/app.py": (
- 2,
- "Two calls: the startup check of the auth-attempt storage, which is "
- "awaited before the lifespan starts any writer, and the temp-file "
+ 4,
+ "Four calls: the startup check of the auth-attempt storage, which is "
+ "awaited before the lifespan starts any writer; the temp-file "
"walk, which deletes temp files only and is stopped through its own "
- "event (documented in retire_writers).",
+ "event (documented in retire_writers); the dedicated "
+ "'startup-file-sync' pool, whose only writing job (the startup file "
+ "storage sync) is submitted through run_tracked_in and so is counted "
+ "until its thread returns; and the standby preflight, a read-only "
+ "classification that writes nothing and is stopped through its "
+ "StartupSyncControl cancel event.",
),
"web/worker.py": (
4,
diff --git a/tests/web/test_startup_sync_lifecycle_bypass.py b/tests/web/test_startup_sync_lifecycle_bypass.py
new file mode 100644
index 000000000..2e5aa6f42
--- /dev/null
+++ b/tests/web/test_startup_sync_lifecycle_bypass.py
@@ -0,0 +1,731 @@
+"""The startup file-storage sync gate must never hold a host's control paths.
+
+Covers the 2026-11 incident: a prewarmed standby's activation started the
+sync, the gate held the host's lifecycle probe behind it, and a sync that stood
+still left the host blind. Also covers the read-only standby preflight that
+keeps a fully-synced standby from gating at all, and the sync's own bounds.
+"""
+
+import asyncio
+import threading
+import time
+from importlib import import_module
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from xagent.core.file_storage.types import StoredObject
+from xagent.web.models.database import Base
+from xagent.web.models.uploaded_file import UploadedFile
+from xagent.web.models.user import User
+from xagent.web.services import startup_file_storage_sync as sync_module
+from xagent.web.services.startup_file_storage_sync import (
+ StartupFileStoragePreflight,
+ StartupSyncCancelled,
+ StartupSyncControl,
+ preflight_registered_files,
+)
+
+app_module = import_module("xagent.web.app")
+
+
[email protected](autouse=True)
+def _isolated_prefixes(monkeypatch):
+ monkeypatch.setattr(app_module, "_file_storage_startup_sync_exempt_prefixes", set())
+ monkeypatch.setattr(
+ app_module, "get_file_storage_startup_sync_enabled", lambda: True
+ )
+
+
+def _app_with_stuck_sync(*, finish_after: float | None = None) -> FastAPI:
+ test_app = FastAPI()
+ test_app.add_middleware(app_module.FileStorageStartupSyncGateMiddleware)
+
+ @test_app.on_event("startup")
+ async def _startup() -> None:
+ async def _sync() -> None:
+ await asyncio.sleep(finish_after if finish_after is not None else 3600)
+
+ test_app.state.file_storage_startup_sync_task = asyncio.create_task(_sync())
+
+ @test_app.get("/internal/thin-gate/lifecycle")
+ async def _lifecycle() -> dict[str, str]:
+ return {"status": "ok"}
+
+ @test_app.get("/api/client")
+ async def _client() -> dict[str, str]:
+ return {"status": "served"}
+
+ return test_app
+
+
+# --- M1: host-registered exemptions ------------------------------------------
+
+
+def test_registered_prefix_answers_while_sync_is_stuck():
+ app_module.register_file_storage_startup_sync_exempt_prefix("/internal/thin-gate/")
+ with TestClient(_app_with_stuck_sync()) as client:
+ started = time.monotonic()
+ response = client.get("/internal/thin-gate/lifecycle")
+ assert response.status_code == 200
+ assert time.monotonic() - started < 1.0
+
+
+def test_registered_prefix_answers_after_sync_failed():
+ app_module.register_file_storage_startup_sync_exempt_prefix("/internal/thin-gate/")
+ test_app = _app_with_stuck_sync()
+ with TestClient(test_app) as client:
+ test_app.state.file_storage_startup_sync_error = RuntimeError("s3 down")
+ assert client.get("/internal/thin-gate/lifecycle").status_code == 200
+ assert client.get("/api/client").status_code == 503
+
+
+def test_unregistered_path_is_still_held_until_sync_completes():
+ app_module.register_file_storage_startup_sync_exempt_prefix("/internal/thin-gate/")
+ with TestClient(_app_with_stuck_sync(finish_after=0.3)) as client:
+ started = time.monotonic()
+ response = client.get("/api/client")
+ assert response.status_code == 200
+ assert time.monotonic() - started >= 0.25
+
+
+def test_without_registration_lifecycle_is_held():
+ """Pins the incident: the default gate holds every non-exempt path."""
+ with TestClient(_app_with_stuck_sync(finish_after=0.3)) as client:
+ started = time.monotonic()
+ assert client.get("/internal/thin-gate/lifecycle").status_code == 200
+ assert time.monotonic() - started >= 0.25
+
+
+def test_prefix_must_be_absolute():
+ with pytest.raises(ValueError):
+ app_module.register_file_storage_startup_sync_exempt_prefix("internal/")
+
+
+def test_prefix_match_is_a_prefix_not_a_substring():
+ app_module.register_file_storage_startup_sync_exempt_prefix("/internal/thin-gate/")
+ assert app_module._is_file_storage_startup_sync_exempt("/internal/thin-gate/x")
+ assert not app_module._is_file_storage_startup_sync_exempt(
+ "/api/internal/thin-gate/x"
+ )
+ assert not app_module._is_file_storage_startup_sync_exempt("/internal/thin-gates")
+
+
+# --- status accessor ----------------------------------------------------------
+
+
+async def test_status_reports_running_failed_done_with_elapsed(monkeypatch):
+ test_app = FastAPI()
+ assert (
+ app_module.get_file_storage_startup_sync_status(test_app)["state"] == "pending"
+ )
+
+ release = asyncio.Event()
+
+ async def _attempt(*_args) -> None:
+ await release.wait()
+
+ monkeypatch.setattr(app_module, "_run_bounded_file_storage_sync_attempt", _attempt)
+ task = app_module.start_file_storage_startup_sync_task(test_app)
+ await asyncio.sleep(0.05)
+ running = app_module.get_file_storage_startup_sync_status(test_app)
+ assert running["state"] == "running"
+ assert running["gating"] is True
+ assert running["elapsed_seconds"] >= 0.04
+
+ test_app.state.file_storage_startup_sync_error = RuntimeError("boom")
+ assert (
+ app_module.get_file_storage_startup_sync_status(test_app)["state"] == "failed"
+ )
+ test_app.state.file_storage_startup_sync_error = None
+
+ release.set()
+ await task
+ done = app_module.get_file_storage_startup_sync_status(test_app)
+ assert done["state"] == "done"
+ assert done["elapsed_seconds"] is not None
+
+
+def test_status_disabled(monkeypatch):
+ monkeypatch.setattr(
+ app_module, "get_file_storage_startup_sync_enabled", lambda: False
+ )
+ assert (
+ app_module.get_file_storage_startup_sync_status(FastAPI())["state"]
+ == "disabled"
+ )
+
+
+# --- S2: preflight and non-gating background sync ------------------------------
+
+
+class _Storage:
+ backend = "s3"
+
+ def __init__(self, keys=()):
+ self.keys = set(keys)
+ self.put_calls = []
+
+ def list(self, prefix):
+ return [
+ StoredObject(backend="s3", key=k, uri=f"s3://b/{k}", size=1)
+ for k in sorted(self.keys)
+ if k.startswith(prefix.rstrip("/") + "/")
+ ]
+
+ def put_file(self, *a, **k): # pragma: no cover - must never run
+ self.put_calls.append(a)
+ raise AssertionError("preflight must not write storage")
+
+
+def _db(tmp_path):
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ factory = sessionmaker(bind=engine)
+ with factory() as db:
+ user = User(username="u", password_hash="h", is_admin=False)
+ db.add(user)
+ db.commit()
+ return factory, int(user.id)
+
+
+def _row(factory, user_id, path: Path, file_id, **kw):
+ with factory() as db:
+ db.add(
+ UploadedFile(
+ file_id=file_id,
+ user_id=user_id,
+ filename=path.name,
+ storage_path=str(path),
+ mime_type="text/plain",
+ file_size=0,
+ storage_status=kw.pop("storage_status", "legacy"),
+ **kw,
+ )
+ )
+ db.commit()
+
+
+def _durable_row(factory, user_id, path, file_id):
+ key = f"users/{user_id}/uploads/{file_id}/{path.name}"
+ _row(
+ factory,
+ user_id,
+ path,
+ file_id,
+ storage_backend="s3",
+ storage_key=key,
+ storage_status="available",
+ checksum="c",
+ )
+ return key
+
+
+def test_preflight_clean_when_every_file_is_already_durable(tmp_path):
+ factory, uid = _db(tmp_path)
+ local = tmp_path / "a.txt"
+ local.write_text("x")
+ key = _durable_row(factory, uid, local, "f1")
+ gone = tmp_path / "gone.txt" # missing locally and remotely: nothing to write
+ _row(factory, uid, gone, "f2")
+ storage = _Storage({key})
+
+ result = preflight_registered_files(storage=storage, session_factory=factory)
+
+ assert result.clean
+ assert result.scanned == 2
+ assert result.skipped_missing_local == 1
+ assert storage.put_calls == []
+
+
+def test_preflight_reports_file_missing_remote_but_present_locally(tmp_path):
+ factory, uid = _db(tmp_path)
+ local = tmp_path / "a.txt"
+ local.write_text("x")
+ _row(factory, uid, local, "f1")
+ result = preflight_registered_files(storage=_Storage(), session_factory=factory)
+ assert not result.clean and result.needs_write == 1
+
+
+def test_preflight_reports_remote_present_but_row_incomplete(tmp_path):
+ factory, uid = _db(tmp_path)
+ local = tmp_path / "a.txt"
+ local.write_text("x")
+ _row(factory, uid, local, "f1")
+ key = f"users/{uid}/uploads/f1/a.txt"
+ result = preflight_registered_files(
+ storage=_Storage({key}), session_factory=factory
+ )
+ assert result.needs_write == 1
+
+
+def test_preflight_writes_nothing_to_the_database(tmp_path):
+ factory, uid = _db(tmp_path)
+ local = tmp_path / "a.txt"
+ local.write_text("x")
+ _row(factory, uid, local, "f1")
+ key = f"users/{uid}/uploads/f1/a.txt"
+ preflight_registered_files(storage=_Storage({key}), session_factory=factory)
+ with factory() as db:
+ row = db.query(UploadedFile).one()
+ assert row.storage_status == "legacy" and row.storage_key is None
+
+
+def test_preflight_honours_cancel(tmp_path):
+ factory, uid = _db(tmp_path)
+ local = tmp_path / "a.txt"
+ local.write_text("x")
+ _row(factory, uid, local, "f1")
+ control = StartupSyncControl()
+ control.cancel.set()
+ with pytest.raises(StartupSyncCancelled):
+ preflight_registered_files(
+ storage=_Storage(), session_factory=factory, control=control
+ )
+
+
+ ("task", "result", "expected_gate"),
+ [
+ (None, None, True), # normal start: never ran a preflight
+ (object(), None, True), # preflight unfinished or failed
+ (object(), StartupFileStoragePreflight(scanned=3, needs_write=1), True),
+ (object(), StartupFileStoragePreflight(scanned=3, needs_write=0), False),
+ ],
+)
+def test_should_gate_only_when_preflight_proved_nothing_to_write(
+ task, result, expected_gate
+):
+ test_app = FastAPI()
+ test_app.state.file_storage_preflight_task = task
+ test_app.state.file_storage_preflight_result = result
+ assert app_module._file_storage_sync_should_gate(test_app) is expected_gate
+
+
+async def test_clean_standby_activation_never_gates_requests(monkeypatch):
+ """Activation with a clean preflight: sync runs in background, gate open."""
+ test_app = FastAPI()
+ test_app.state.file_storage_preflight_task = object()
+ test_app.state.file_storage_preflight_result = StartupFileStoragePreflight(
+ scanned=9
+ )
+ release = asyncio.Event()
+
+ async def _attempt(*_args) -> None:
+ await release.wait()
+
+ monkeypatch.setattr(app_module, "_run_bounded_file_storage_sync_attempt", _attempt)
+ monkeypatch.setattr(app_module, "get_shared_task_execution_enabled", lambda: True)
+ for name in (
+ "start_uploaded_file_recovery_task",
+ "start_orphan_upload_gc_task",
+ "start_retention_purge_task",
+ "start_task_cleanup_retry_task",
+ ):
+ monkeypatch.setattr(app_module, name, Mock())
+
+ await app_module._start_local_runtime_loops(test_app)
+ try:
+ assert test_app.state.file_storage_startup_sync_gating is False
+ # Sync still running, yet the wait returns at once and /ready is not 503.
+ await asyncio.wait_for(
+ app_module.wait_for_file_storage_startup_sync(test_app), timeout=0.5
+ )
+ assert not test_app.state.file_storage_startup_sync_task.done()
+ finally:
+ release.set()
+ await test_app.state.file_storage_startup_sync_task
+
+
+async def test_standby_with_files_to_write_still_gates(monkeypatch):
+ test_app = FastAPI()
+ test_app.state.file_storage_preflight_task = object()
+ test_app.state.file_storage_preflight_result = StartupFileStoragePreflight(
+ scanned=9, needs_write=2
+ )
+ release = asyncio.Event()
+
+ async def _attempt(*_args) -> None:
+ await release.wait()
+
+ monkeypatch.setattr(app_module, "_run_bounded_file_storage_sync_attempt", _attempt)
+ monkeypatch.setattr(app_module, "get_shared_task_execution_enabled", lambda: True)
+ for name in (
+ "start_uploaded_file_recovery_task",
+ "start_orphan_upload_gc_task",
+ "start_retention_purge_task",
+ "start_task_cleanup_retry_task",
+ ):
+ monkeypatch.setattr(app_module, name, Mock())
+
+ await app_module._start_local_runtime_loops(test_app)
+ try:
+ assert test_app.state.file_storage_startup_sync_gating is True
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(
+ app_module.wait_for_file_storage_startup_sync(test_app), timeout=0.4
+ )
+ finally:
+ release.set()
+ await test_app.state.file_storage_startup_sync_task
+
+
+def test_non_gating_sync_does_not_fail_requests_when_it_errors():
+ test_app = FastAPI()
+ test_app.state.file_storage_startup_sync_gating = False
+ test_app.state.file_storage_startup_sync_error = RuntimeError("s3 down")
+ asyncio.run(app_module.wait_for_file_storage_startup_sync(test_app))
+
+
+# --- S1: bounded sync -----------------------------------------------------------
+
+
+async def test_attempt_logs_progress_dumps_stacks_and_cancels_when_stalled(monkeypatch):
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS", 0.05
+ )
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_DUMP_AFTER_SECONDS", 0.1)
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS", 0.3)
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_CANCEL_GRACE_SECONDS", 2.0
+ )
+ dump = Mock()
+ monkeypatch.setattr(app_module, "_dump_all_thread_stacks", dump)
+ saw_cancel = threading.Event()
+
+ def _stuck_sync() -> None:
+ control = app_module._file_storage_sync_control.get()
+ while True:
+ try:
+ control.checkpoint("stuck", progress=False)
+ except StartupSyncCancelled:
+ saw_cancel.set()
+ raise
+ time.sleep(0.01)
+
+ monkeypatch.setattr(app_module, "run_startup_file_storage_sync", _stuck_sync)
+
+ with pytest.raises(TimeoutError, match="no progress"):
+ await app_module._run_bounded_file_storage_sync_attempt()
+
+ dump.assert_called_once()
+ assert saw_cancel.wait(1.0)
+
+
+async def test_attempt_runs_on_dedicated_executor_not_the_default_one(monkeypatch):
+ names: list[str] = []
+ monkeypatch.setattr(
+ app_module,
+ "run_startup_file_storage_sync",
+ lambda: names.append(threading.current_thread().name),
+ )
+ await app_module._run_bounded_file_storage_sync_attempt()
+ assert names and names[0].startswith("startup-file-sync")
+
+
+async def test_saturated_default_executor_does_not_stall_the_sync(monkeypatch):
+ loop = asyncio.get_running_loop()
+ gate = threading.Event()
+ from concurrent.futures import ThreadPoolExecutor
+
+ small = ThreadPoolExecutor(max_workers=1)
+ loop.set_default_executor(small)
+ blocker = loop.run_in_executor(None, gate.wait) # default pool now full
+ ran = threading.Event()
+ monkeypatch.setattr(app_module, "run_startup_file_storage_sync", ran.set)
+ try:
+ await asyncio.wait_for(app_module._run_bounded_file_storage_sync_attempt(), 2.0)
+ assert ran.is_set()
+ finally:
+ gate.set()
+ await blocker
+ small.shutdown(wait=True)
+
+
+def test_locked_result_from_an_earlier_attempt_is_not_success(monkeypatch):
+ monkeypatch.setattr(
+ sync_module,
+ "sync_registered_files_to_durable_storage",
+ Mock(return_value=sync_module.StartupFileStorageSyncResult(locked=True)),
+ )
+ token = app_module._file_storage_sync_control.set(StartupSyncControl())
+ try:
+ with pytest.raises(RuntimeError, match="previous attempt"):
+ app_module.run_startup_file_storage_sync()
+ finally:
+ app_module._file_storage_sync_control.reset(token)
+
+
+def test_stuck_sync_does_not_stop_lifecycle_from_answering(monkeypatch):
+ """End to end through the real middleware with the real retry loop."""
+ app_module.register_file_storage_startup_sync_exempt_prefix("/internal/thin-gate/")
+ test_app = FastAPI()
+ test_app.add_middleware(app_module.FileStorageStartupSyncGateMiddleware)
+ release = threading.Event()
+ monkeypatch.setattr(
+ app_module, "run_startup_file_storage_sync", lambda: release.wait(30)
+ )
+
+ @test_app.on_event("startup")
+ async def _startup() -> None:
+ app_module.start_file_storage_startup_sync_task(test_app)
+
+ @test_app.get("/internal/thin-gate/lifecycle")
+ async def _lifecycle() -> dict:
+ return app_module.get_file_storage_startup_sync_status(test_app)
+
+ @test_app.get("/api/client")
+ async def _client() -> dict:
+ return {}
+
+ try:
+ with TestClient(test_app) as client:
+ started = time.monotonic()
+ body = client.get("/internal/thin-gate/lifecycle").json()
+ assert time.monotonic() - started < 1.0
+ assert body["state"] == "running"
+ release.set()
+ assert client.get("/api/client").status_code == 200
+ finally:
+ release.set()
+
+
+async def test_ready_is_not_held_by_a_non_gating_sync(monkeypatch):
+ import xagent.web.models.database as database_module
+ import xagent.web.services.interaction_rollout as ir
+
+ monkeypatch.setattr(
+ ir,
+ "_policy",
+ ir.InteractionRolloutPolicy(
+ mode="legacy",
+ native_sources=frozenset(),
+ native_protocol_version=1,
+ shared_task_execution=True,
+ ),
+ )
+ monkeypatch.setattr(database_module, "_SessionLocal", None)
+ state = app_module.app.state
+ task = asyncio.create_task(asyncio.sleep(30))
+ monkeypatch.setattr(state, "file_storage_startup_sync_task", task, raising=False)
+ monkeypatch.setattr(state, "file_storage_startup_sync_error", None, raising=False)
+ try:
+ monkeypatch.setattr(
+ state, "file_storage_startup_sync_gating", True, raising=False
+ )
+ assert (await app_module.readiness_check()).status_code == 503
+ monkeypatch.setattr(
+ state, "file_storage_startup_sync_gating", False, raising=False
+ )
+ assert (await app_module.readiness_check()).status_code == 200
+ finally:
+ task.cancel()
+
+
+# --- review: stall (not total) timeout, resume, cancel before storage I/O --------
+
+
+class _SlowListStorage(_Storage):
+ """Every per-user listing succeeds but takes a while (listings cache off)."""
+
+ def __init__(self, keys=(), delay=0.1, on_list=None):
+ super().__init__(keys)
+ self.delay = delay
+ self.list_prefixes: list[str] = []
+ self.on_list = on_list
+
+ def list(self, prefix):
+ self.list_prefixes.append(prefix)
+ if self.on_list is not None:
+ self.on_list(len(self.list_prefixes))
+ time.sleep(self.delay)
+ return super().list(prefix)
+
+
+def _many_user_db(tmp_path, users=8):
+ # A file database: the sync runs on executor threads.
+ engine = create_engine(f"sqlite:///{tmp_path}/sync.sqlite")
+ Base.metadata.create_all(engine)
+ factory = sessionmaker(bind=engine)
+ keys = set()
+ ids = []
+ with factory() as db:
+ for n in range(users):
+ user = User(username=f"u{n}", password_hash="h", is_admin=False)
+ db.add(user)
+ db.commit()
+ ids.append(int(user.id))
+ for uid in ids:
+ path = tmp_path / f"f{uid}.txt"
+ path.write_text("x")
+ keys.add(_durable_row(factory, uid, path, f"file{uid}"))
+ return factory, keys
+
+
+async def test_steadily_progressing_scan_longer_than_the_stall_window_completes(
+ monkeypatch, tmp_path
+):
+ """Regression: a total deadline restarted a healthy long scan forever."""
+ factory, keys = _many_user_db(tmp_path, users=8)
+ storage = _SlowListStorage(keys, delay=0.1) # ~0.8 s in total
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS", 0.05
+ )
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS", 0.3)
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_DUMP_AFTER_SECONDS", 60)
+ monkeypatch.setenv(
+ "XAGENT_FILE_STORAGE_STARTUP_SYNC_LOCK_FILE", str(tmp_path / "l.lock")
+ )
+ real = sync_module.sync_registered_files_to_durable_storage
+ monkeypatch.setattr(
+ sync_module,
+ "sync_registered_files_to_durable_storage",
+ lambda **kw: real(storage=storage, session_factory=factory, **kw),
+ )
+ test_app = FastAPI()
+ task = app_module.start_file_storage_startup_sync_task(
+ test_app, retry_interval_seconds=0
+ )
+ await asyncio.wait_for(task, 10)
+
+ assert test_app.state.file_storage_startup_sync_completed is True
+ assert test_app.state.file_storage_startup_sync_error is None
+ # one pass: no restarts, each user listed exactly once
+ assert len(storage.list_prefixes) == 8
+ await asyncio.wait_for(app_module.wait_for_file_storage_startup_sync(test_app), 1)
+
+
+async def test_retry_after_a_stall_resumes_instead_of_restarting(monkeypatch, tmp_path):
+ factory, keys = _many_user_db(tmp_path, users=6)
+ stall_once = {"done": False}
+
+ def on_list(call_number):
+ if call_number == 4 and not stall_once["done"]:
+ stall_once["done"] = True
+ time.sleep(0.6) # a real stall inside the 4th listing
+
+ storage = _SlowListStorage(keys, delay=0.01, on_list=on_list)
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS", 0.05
+ )
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS", 0.3)
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_CANCEL_GRACE_SECONDS", 0.05
+ )
+ monkeypatch.setattr(app_module, "_dump_all_thread_stacks", Mock())
+ monkeypatch.setenv(
+ "XAGENT_FILE_STORAGE_STARTUP_SYNC_LOCK_FILE", str(tmp_path / "l.lock")
+ )
+ real = sync_module.sync_registered_files_to_durable_storage
+ monkeypatch.setattr(
+ sync_module,
+ "sync_registered_files_to_durable_storage",
+ lambda **kw: real(storage=storage, session_factory=factory, **kw),
+ )
+ test_app = FastAPI()
+ task = app_module.start_file_storage_startup_sync_task(
+ test_app, retry_interval_seconds=0.7
+ )
+ await asyncio.wait_for(task, 15)
+
+ assert test_app.state.file_storage_startup_sync_completed is True
+ # The stalled attempt finished user 4 before it saw the cancel, and the
+ # retry continued after it: every user is listed exactly once (a restart
+ # 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
+
+
+async def test_a_real_stall_still_trips_the_timeout_and_dumps_stacks(monkeypatch):
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_PROGRESS_INTERVAL_SECONDS", 0.05
+ )
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_DUMP_AFTER_SECONDS", 0.1)
+ monkeypatch.setattr(app_module, "FILE_STORAGE_STARTUP_SYNC_STALL_SECONDS", 0.3)
+ monkeypatch.setattr(
+ app_module, "FILE_STORAGE_STARTUP_SYNC_CANCEL_GRACE_SECONDS", 0.05
+ )
+ dump = Mock()
+ monkeypatch.setattr(app_module, "_dump_all_thread_stacks", dump)
+ release = threading.Event()
+ monkeypatch.setattr(
+ app_module, "run_startup_file_storage_sync", lambda: release.wait(10)
+ )
+ try:
+ with pytest.raises(TimeoutError, match="no progress"):
+ await app_module._run_bounded_file_storage_sync_attempt()
+ dump.assert_called_once()
+ finally:
+ release.set()
+
+
+def test_cancel_during_the_first_listing_stops_before_the_next_users_listing(tmp_path):
+ factory, keys = _many_user_db(tmp_path, users=3)
+ control = StartupSyncControl()
+ storage = _SlowListStorage(keys, delay=0, on_list=lambda n: control.cancel.set())
+ with pytest.raises(StartupSyncCancelled):
+ preflight_registered_files(
+ storage=storage, session_factory=factory, control=control
+ )
+ assert len(storage.list_prefixes) == 1
+
+
+def test_cancel_during_the_first_listing_stops_the_sync_too(tmp_path, monkeypatch):
+ factory, keys = _many_user_db(tmp_path, users=3)
+ control = StartupSyncControl()
+ storage = _SlowListStorage(keys, delay=0, on_list=lambda n: control.cancel.set())
+ monkeypatch.setenv(
+ "XAGENT_FILE_STORAGE_STARTUP_SYNC_LOCK_FILE", str(tmp_path / "l.lock")
+ )
+ with pytest.raises(StartupSyncCancelled):
+ sync_module.sync_registered_files_to_durable_storage(
+ storage=storage, session_factory=factory, control=control
+ )
+ assert len(storage.list_prefixes) == 1
+
+
+def test_resume_cursor_never_moves_past_a_failed_file(tmp_path, monkeypatch):
+ factory, keys = _many_user_db(tmp_path, users=3)
+ with factory() as db: # user 1's row is not durable and its upload fails
+ row = db.query(UploadedFile).order_by(UploadedFile.id).first()
+ row.storage_status = "legacy"
+ row.storage_key = None
+ row.checksum = None
+ row.storage_backend = None
+ db.commit()
+ # Read the identity while the session is open: the row detaches on exit.
+ first_user_key = (
+ f"users/{row.user_id}/uploads/{row.file_id}/{Path(row.storage_path).name}"
+ )
+ storage = _SlowListStorage(keys - {first_user_key}, delay=0)
+
+ def failing_put(*args, **kwargs):
+ raise RuntimeError("s3 down")
+
+ storage.put_file = failing_put
+ monkeypatch.setenv(
+ "XAGENT_FILE_STORAGE_STARTUP_SYNC_LOCK_FILE", str(tmp_path / "l.lock")
+ )
+ control = StartupSyncControl()
+
+ result = sync_module.sync_registered_files_to_durable_storage(
+ storage=storage, session_factory=factory, control=control
+ )
+
+ assert result.failed == 1
+ assert control.resume.cursor is None # a retry starts at the failed file