Skip to content

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

feat(web): serving generation record and generation guards for singletons (#3819)

OliverBryantf84bca4c3c28
diff --git a/src/xagent/migrations/versions/20261115_serving_generation.py b/src/xagent/migrations/versions/20261115_serving_generation.py
new file mode 100644
index 000000000..1d03e2de3
--- /dev/null
+++ b/src/xagent/migrations/versions/20261115_serving_generation.py
@@ -0,0 +1,40 @@
+"""Add the serving generation record.
+
+One row names the backend generation that may claim new singleton work while
+two generations overlap during a release. Expand-only: a new table, nothing else.
+
+Revision ID: 20261115_serving_generation
+Revises: 20261114_oauth_revocation_fences
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20261115_serving_generation"
+down_revision = "20261115_user_oauth_issuer"
+branch_labels = None
+depends_on = None
+
+
+def upgrade() -> None:
+ # Offline SQL generation cannot inspect: it emits the CREATE TABLE.
+ if not op.get_context().as_sql and sa.inspect(op.get_bind()).has_table(
+ "serving_generation"
+ ):
+ return
+ op.create_table(
+ "serving_generation",
+ sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
+ sa.Column("generation", sa.String(length=255), nullable=False),
+ sa.Column(
+ "updated_at",
+ sa.DateTime(timezone=True),
+ server_default=sa.func.now(),
+ nullable=False,
+ ),
+ sa.CheckConstraint("id = 1", name="ck_serving_generation_single_row"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("serving_generation")
diff --git a/src/xagent/web/app.py b/src/xagent/web/app.py
index f8da930f4..5f6b2efd7 100644
--- a/src/xagent/web/app.py
+++ b/src/xagent/web/app.py
@@ -127,6 +127,7 @@ from .services.conversation_storage_rollout import (
report_unobserved_execution_events,
validate_conversation_storage_rollout_at_startup,
)
+from .services.generation import start_allowed, tick_allowed
from .services.interaction_rollout import (
get_interaction_rollout_policy,
is_native_schema_ready,
@@ -641,6 +642,9 @@ async def _run_trigger_dispatcher(
next_preview_run_reap_at = 0.0
tick_paused = False
while True:
+ if not await tick_allowed("trigger-dispatcher"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
# Trigger production pauses at the tick boundary while a planned
# restart holds new execution: a tick already past this point runs to
# its end (and is counted until then), a later one neither scans due
@@ -740,6 +744,8 @@ def start_trigger_dispatcher_task(app_instance: FastAPI) -> asyncio.Task[Any] |
if os.getenv("PYTEST_CURRENT_TEST"):
logger.info("Skipping trigger dispatcher (test environment)")
return None
+ if not start_allowed("trigger-dispatcher"):
+ return None
poll_interval_seconds = get_trigger_dispatcher_interval_seconds()
batch_size = get_trigger_dispatcher_batch_size()
@@ -772,6 +778,8 @@ def start_task_lease_recovery_task(
if not consumes_task_commands():
return None
+ if not start_allowed("task-lease-recovery"):
+ return None
existing_task = cast(
asyncio.Task[Any] | None,
@@ -846,6 +854,8 @@ def start_task_auto_resume_task(
if not consumes_task_commands():
return None
+ if not start_allowed("task-auto-resume"):
+ return None
existing_task = cast(
asyncio.Task[Any] | None,
@@ -2769,6 +2779,15 @@ async def _start_commands_and_channels() -> None:
app.state.task_command_dispatcher_task = _task_command_dispatcher_task
logger.info("Task command dispatch configured")
+ # Chat intake claims new conversations: only the serving generation takes
+ # it. A restarted old generation must not start receiving again. This is
+ # the cheap early refusal; when the record cannot be read it lets the start
+ # through, and the channel managers' own sync (which every start path,
+ # including channel CRUD, goes through) keeps the channels dormant until
+ # this generation is confirmed as the serving one.
+ if not start_allowed("chat-channels"):
+ return
+
# Start configured chat channels.
try:
from .channels.feishu.bot import get_feishu_channel
diff --git a/src/xagent/web/channels/feishu/bot.py b/src/xagent/web/channels/feishu/bot.py
index d1b4c6e63..56a6ad6f8 100644
--- a/src/xagent/web/channels/feishu/bot.py
+++ b/src/xagent/web/channels/feishu/bot.py
@@ -62,6 +62,11 @@ from ...services.db_runtime import (
)
from ...services.execution_result_projection import project_execution_result_for_channel
from ...services.file_turn import normalize_attachments_for_persistence
+from ...services.generation import (
+ current_generation,
+ other_generation_serves,
+ tick_allowed,
+)
from ...services.llm_utils import AutoModelUnavailableError
from ...services.managed_task_lease import ManagedTaskLease
from ...services.shared_channel_execution import SharedChannelTurn
@@ -1490,8 +1495,14 @@ class FeishuChannelManager:
return
while get_channel_ingress_enabled():
await self._sync_bots_async()
+ # With generations on, a sync that found this process not serving
+ # must be retried until serving is confirmed, even when shared
+ # execution is off (which otherwise ends the loop after one sync).
if not get_shared_task_execution_enabled():
- return
+ if current_generation() is None:
+ return
+ await asyncio.sleep(30)
+ continue
for bot in tuple(self.bots.values()):
if bot.channel_id is not None:
await recover_channel_results(
@@ -1509,6 +1520,14 @@ class FeishuChannelManager:
if not get_channel_ingress_enabled():
return
async with self._sync_lock:
+ # Chat intake belongs to the serving generation. An unreadable
+ # record counts as not serving, so nothing new opens until serving
+ # is confirmed; only a record that names another generation closes
+ # what this one already runs (a read blip must not drop intake).
+ if not await tick_allowed("feishu-channels"):
+ if await other_generation_serves("feishu-channels"):
+ await self.stop()
+ return
active_app_ids = set()
channel_info_by_appid: Dict[str, Dict] = {}
diff --git a/src/xagent/web/channels/slack/bot.py b/src/xagent/web/channels/slack/bot.py
index 5349da4ae..67191d086 100644
--- a/src/xagent/web/channels/slack/bot.py
+++ b/src/xagent/web/channels/slack/bot.py
@@ -73,6 +73,11 @@ from ...services.file_turn import (
build_uploaded_files_context,
normalize_attachments_for_persistence,
)
+from ...services.generation import (
+ current_generation,
+ other_generation_serves,
+ tick_allowed,
+)
from ...services.llm_utils import AutoModelUnavailableError
from ...services.managed_task_lease import ManagedTaskLease
from ...services.shared_channel_execution import (
@@ -1492,8 +1497,14 @@ class SlackChannelManager:
return
while get_channel_ingress_enabled():
await self._sync_bots_async()
+ # With generations on, a sync that found this process not serving
+ # must be retried until serving is confirmed, even when shared
+ # execution is off (which otherwise ends the loop after one sync).
if not get_shared_task_execution_enabled():
- return
+ if current_generation() is None:
+ return
+ await asyncio.sleep(30)
+ continue
for bot in (*self.bots.values(), *self.oauth_bots.values()):
if bot.channel_id is not None:
await recover_channel_results(
@@ -1514,6 +1525,14 @@ class SlackChannelManager:
if not get_channel_ingress_enabled():
return
async with self._sync_lock:
+ # Chat intake belongs to the serving generation. An unreadable
+ # record counts as not serving, so nothing new opens until serving
+ # is confirmed; only a record that names another generation closes
+ # what this one already runs (a read blip must not drop intake).
+ if not await tick_allowed("slack-channels"):
+ if await other_generation_serves("slack-channels"):
+ await self.stop()
+ return
try:
# One load, partitioned on the declared installation_mode.
# Capability probing (which keys happen to be present) is not
diff --git a/src/xagent/web/channels/telegram/bot.py b/src/xagent/web/channels/telegram/bot.py
index fd95b1ab7..273cfe70d 100644
--- a/src/xagent/web/channels/telegram/bot.py
+++ b/src/xagent/web/channels/telegram/bot.py
@@ -88,6 +88,11 @@ from ...services.file_turn import (
build_uploaded_files_context,
normalize_attachments_for_persistence,
)
+from ...services.generation import (
+ current_generation,
+ other_generation_serves,
+ tick_allowed,
+)
from ...services.managed_task_lease import ManagedTaskLease
from ...services.shared_channel_execution import (
SharedChannelTurn,
@@ -3218,8 +3223,14 @@ class TelegramChannelManager:
return
while get_channel_ingress_enabled():
await self._sync_bots_async()
+ # With generations on, a sync that found this process not serving
+ # must be retried until serving is confirmed, even when shared
+ # execution is off (which otherwise ends the loop after one sync).
if not get_shared_task_execution_enabled():
- return
+ if current_generation() is None:
+ return
+ await asyncio.sleep(30)
+ continue
for bot in tuple(self.bots.values()):
if bot.channel_id is not None:
await recover_channel_results(
@@ -3238,6 +3249,14 @@ class TelegramChannelManager:
if not get_channel_ingress_enabled():
return
async with self._sync_lock:
+ # Chat intake belongs to the serving generation. An unreadable
+ # record counts as not serving, so nothing new opens until serving
+ # is confirmed; only a record that names another generation closes
+ # what this one already runs (a read blip must not drop intake).
+ if not await tick_allowed("telegram-channels"):
+ if await other_generation_serves("telegram-channels"):
+ await self.stop()
+ return
active_tokens = set()
channel_info_by_token: Dict[str, Dict] = {}
diff --git a/src/xagent/web/composio_auth.py b/src/xagent/web/composio_auth.py
index 9b4aaa71e..8adef2b97 100644
--- a/src/xagent/web/composio_auth.py
+++ b/src/xagent/web/composio_auth.py
@@ -1163,9 +1163,13 @@ async def run_reconcile_loop(
"""
import asyncio
+ from .services.generation import tick_allowed
from .services.writer_workers import run_tracked
while not stop_event.is_set():
+ if not await tick_allowed("composio-reconcile"):
+ await asyncio.sleep(interval_seconds)
+ continue
try:
await run_tracked(reconcile_orphan_accounts_isolated, stop_event=stop_event)
except asyncio.CancelledError:
@@ -1189,9 +1193,13 @@ async def run_missing_account_loop(
"""
import asyncio
+ from .services.generation import tick_allowed
from .services.writer_workers import run_tracked
while not stop_event.is_set():
+ if not await tick_allowed("composio-missing-account"):
+ await asyncio.sleep(interval_seconds)
+ continue
try:
await run_tracked(
tombstone_missing_composio_accounts_isolated, stop_event=stop_event
diff --git a/src/xagent/web/models/__init__.py b/src/xagent/web/models/__init__.py
index 036ad5189..f247eccbf 100644
--- a/src/xagent/web/models/__init__.py
+++ b/src/xagent/web/models/__init__.py
@@ -22,6 +22,7 @@ from .oauth_revocation_fence import OAuthRevocationFence
from .oidc_consumed_token import OidcConsumedToken
from .public_mcp import PublicMCPApp, PublicMCPAppAudit
from .sandbox import DurableSandboxLifecycle, SandboxInfo, SandboxSnapshot
+from .serving_generation import ServingGeneration
from .skill import UserSkill, UserSkillFile
from .system_setting import SystemSetting
from .task import DAGExecution, Task, TaskConnectorRuntimeContext
@@ -88,6 +89,7 @@ __all__ = [
"TaskAdmissionPacing",
"TaskAdmissionBucket",
"TaskAdmissionTicket",
+ "ServingGeneration",
"TaskExecutionCommand",
"TaskInputReceipt",
"ApiIdempotencyKey",
diff --git a/src/xagent/web/models/serving_generation.py b/src/xagent/web/models/serving_generation.py
new file mode 100644
index 000000000..a276698e5
--- /dev/null
+++ b/src/xagent/web/models/serving_generation.py
@@ -0,0 +1,19 @@
+"""The single-row record naming the generation that may claim singleton work."""
+
+from sqlalchemy import CheckConstraint, Column, DateTime, Integer, String
+from sqlalchemy.sql import func
+
+from .database import Base
+
+
+class ServingGeneration(Base): # type: ignore
+ __tablename__ = "serving_generation"
+ __table_args__ = (
+ CheckConstraint("id = 1", name="ck_serving_generation_single_row"),
+ )
+
+ id = Column(Integer, primary_key=True, nullable=False)
+ generation = Column(String(255), nullable=False)
+ updated_at = Column(
+ DateTime(timezone=True), server_default=func.now(), nullable=False
+ )
diff --git a/src/xagent/web/services/generation.py b/src/xagent/web/services/generation.py
new file mode 100644
index 000000000..3d30cf868
--- /dev/null
+++ b/src/xagent/web/services/generation.py
@@ -0,0 +1,163 @@
+"""Backend generation identity and the serving generation record.
+
+While two backend generations overlap during a release, exactly one of them may
+claim new singleton work (triggers, auto-resume, lease recovery, chat intake and
+the maintenance loops). The record names it; a process compares it with its own
+identity, ``XAGENT_GENERATION``.
+
+- ``XAGENT_GENERATION`` unset or empty: generations are off and every check
+ passes, which is the behaviour before this module existed.
+- No ``serving_generation`` row: every check passes (nothing has been handed
+ over yet).
+- Otherwise a process serves only while the row names its own generation.
+
+Fail direction: a database error never reads as "serving". ``is_serving()``
+returns ``False`` and logs, so a singleton skips the tick and tries again on the
+next one. ``tick_allowed()`` is the guard the loops call; ``start_allowed()`` is
+the start-time form, which only refuses on a definite answer (the row names
+another generation) so that a restart during a database blip still starts the
+loop and lets the per-tick guard hold it back until the database answers.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+from typing import Any, cast
+
+from sqlalchemy import CursorResult, update
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.sql import func
+
+logger = logging.getLogger(__name__)
+
+GENERATION_ENV = "XAGENT_GENERATION"
+_RECORD_ID = 1
+
+
+def current_generation() -> str | None:
+ """This process's generation, or ``None`` when generations are off."""
+ value = os.getenv(GENERATION_ENV, "").strip()
+ return value or None
+
+
+def serving_generation() -> str | None:
+ """The generation the record names, or ``None`` when the row is missing.
+
+ Raises on a database error; callers decide the fail direction.
+ """
+ from ..models.database import get_session_local
+ from ..models.serving_generation import ServingGeneration
+
+ with get_session_local()() as db:
+ row = db.get(ServingGeneration, _RECORD_ID)
+ return str(row.generation) if row is not None else None
+
+
+def set_serving_generation(new: str, expected: str | None) -> bool:
+ """Move the record from ``expected`` to ``new`` in one conditional write.
+
+ ``expected=None`` means the row must be missing (it is then created).
+ Returns ``False`` when the record did not hold ``expected``, including a lost
+ race on the first insert; it never overwrites a value it did not expect.
+ """
+ from ..models.database import get_session_local
+ from ..models.serving_generation import ServingGeneration
+
+ if not new:
+ raise ValueError("a serving generation must be non-empty")
+ with get_session_local()() as db:
+ if expected is None:
+ db.add(ServingGeneration(id=_RECORD_ID, generation=new))
+ try:
+ db.commit()
+ except IntegrityError:
+ db.rollback()
+ return False
+ return True
+ result = db.execute(
+ update(ServingGeneration)
+ .where(
+ ServingGeneration.id == _RECORD_ID,
+ ServingGeneration.generation == expected,
+ )
+ .values(generation=new, updated_at=func.now())
+ )
+ db.commit()
+ return bool(cast(CursorResult[Any], result).rowcount == 1)
+
+
+def is_serving() -> bool:
+ """Whether this process may claim new singleton work right now.
+
+ ``True`` when generations are off, the row is missing, or the row names this
+ process's generation. ``False`` on a database error (fail closed).
+ """
+ mine = current_generation()
+ if mine is None:
+ return True
+ try:
+ serving = serving_generation()
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "component=serving-generation could not read the record; "
+ "treating this process as not serving",
+ exc_info=True,
+ )
+ return False
+ return serving is None or serving == mine
+
+
+def _definitely_not_serving() -> bool:
+ """``True`` only when the record is readable and names another generation."""
+ mine = current_generation()
+ if mine is None:
+ return False
+ try:
+ serving = serving_generation()
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "component=serving-generation could not read the record at start; "
+ "starting and letting the per-tick guard decide",
+ exc_info=True,
+ )
+ return False
+ return serving is not None and serving != mine
+
+
+async def tick_allowed(component: str) -> bool:
+ """Per-tick guard for a singleton loop; ``False`` means skip this tick."""
+ if current_generation() is None:
+ return True
+ allowed = await asyncio.to_thread(is_serving)
+ if not allowed:
+ logger.debug(
+ "component=%s skipped a tick: not the serving generation", component
+ )
+ return allowed
+
+
+async def other_generation_serves(component: str) -> bool:
+ """``True`` only when the record is readable and names another generation.
+
+ For callers that must close something already running: an unreadable record
+ is not enough to tear down a live intake, so it answers ``False`` there
+ (and the caller simply opens nothing new, via ``tick_allowed``).
+ """
+ if current_generation() is None:
+ return False
+ other = await asyncio.to_thread(_definitely_not_serving)
+ if other:
+ logger.info("component=%s: another generation is serving", component)
+ return other
+
+
+def start_allowed(component: str) -> bool:
+ """Start-time guard: ``False`` only when another generation definitely serves."""
+ if _definitely_not_serving():
+ logger.info(
+ "component=%s not started: another generation is serving", component
+ )
+ return False
+ return True
diff --git a/src/xagent/web/services/orphan_upload_gc.py b/src/xagent/web/services/orphan_upload_gc.py
index 9968467a2..b386d93cf 100644
--- a/src/xagent/web/services/orphan_upload_gc.py
+++ b/src/xagent/web/services/orphan_upload_gc.py
@@ -31,6 +31,7 @@ from sqlalchemy.orm import Session
from ..models.uploaded_file import UploadedFile
from .db_runtime import is_database_pool_timeout, run_db_io_cancellation_safe
+from .generation import tick_allowed
from .kb_reference_protection import guard_cleanup_claim
from .uploaded_file_cleanup import run_uploaded_file_cleanup
from .uploaded_file_cleanup_resources import build_cleanup_manifest
@@ -354,6 +355,9 @@ async def run_orphan_upload_gc_loop(
"""
cursor: OrphanUploadSweepCursor | None = None
while True:
+ if not await tick_allowed("orphan-upload-gc"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
backlog_remaining = False
try:
cursor = await _run_gc_tick(
diff --git a/src/xagent/web/services/task_auto_resume.py b/src/xagent/web/services/task_auto_resume.py
index bb4bea442..c84f82db2 100644
--- a/src/xagent/web/services/task_auto_resume.py
+++ b/src/xagent/web/services/task_auto_resume.py
@@ -80,6 +80,7 @@ from ..models.task_auto_recovery import (
from ..models.task_command import TaskExecutionCommand
from ..utils.db_timezone import format_datetime_for_api
from .db_runtime import is_database_pool_timeout, run_db_io_cancellation_safe
+from .generation import tick_allowed
from .ops_signals import (
TASK_AUTO_RESUME_UNAVAILABLE,
clear_degradation,
@@ -1878,6 +1879,9 @@ async def run_task_auto_resume_loop(*, poll_interval_seconds: int) -> None:
failures = 0
last_failure_log = float("-inf")
while True:
+ if not await tick_allowed("task-auto-resume"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
try:
report = await run_db_io_cancellation_safe(
lambda: run_auto_resume_tick(now=utc_now())
diff --git a/src/xagent/web/services/task_cleanup_obligations.py b/src/xagent/web/services/task_cleanup_obligations.py
index 1f6bf64c1..16bc87e73 100644
--- a/src/xagent/web/services/task_cleanup_obligations.py
+++ b/src/xagent/web/services/task_cleanup_obligations.py
@@ -61,6 +61,7 @@ from ...config import get_task_cleanup_max_attempts
from ...core.task_runtime import TaskRuntimeContext
from ..models.task import Task
from ..models.task_cleanup_obligation import TaskCleanupObligation
+from .generation import tick_allowed
from .task_runtime import delete_task_extensions
from .task_workspace_cleanup import (
WorkspaceCleanupTarget,
@@ -953,6 +954,9 @@ async def run_cleanup_obligation_loop(
"""
while True:
+ if not await tick_allowed("task-cleanup-retry"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
backlog = False
try:
report = await run_cleanup_obligation_batch(
diff --git a/src/xagent/web/services/task_lease_recovery.py b/src/xagent/web/services/task_lease_recovery.py
index 3ab7724ae..1b96d7dde 100644
--- a/src/xagent/web/services/task_lease_recovery.py
+++ b/src/xagent/web/services/task_lease_recovery.py
@@ -15,6 +15,7 @@ from ..models.chat_message import TaskChatMessage
from ..models.task import Task, TaskStatus, task_status_predicate
from .chat_history_service import DELIVERY_DISPATCHED, DELIVERY_PENDING
from .db_runtime import is_database_pool_timeout, run_db_io_cancellation_safe
+from .generation import tick_allowed
from .ops_signals import (
CHECKPOINT_LEGACY_POINTER_AMBIGUOUS,
CHECKPOINT_RECOVERY_UNAVAILABLE,
@@ -747,6 +748,12 @@ async def run_task_lease_recovery_loop(
secret_cursor: int | None = None
while True:
+ # Recovery takes over other processes' tasks; only the serving
+ # generation may. The delivery reconciliation below is skipped too:
+ # the serving generation does it.
+ if not await tick_allowed("task-lease-recovery"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
try:
recovered = await recover_expired_task_leases_until_cutoff(
cutoff=datetime.now(timezone.utc),
diff --git a/src/xagent/web/services/task_retention_purge.py b/src/xagent/web/services/task_retention_purge.py
index 7b8390da8..99d8839a8 100644
--- a/src/xagent/web/services/task_retention_purge.py
+++ b/src/xagent/web/services/task_retention_purge.py
@@ -126,6 +126,7 @@ from ..models.task import (
)
from ..models.task_interaction import TaskInteractionRequest
from .expired_tasks import record_task_expiry_no_commit
+from .generation import tick_allowed
from .task_cleanup_obligations import (
CleanupObligation,
captured_workspace_obligation,
@@ -859,6 +860,12 @@ async def run_retention_purge_loop(
return
while not stop.is_set():
pause = get_retention_sweep_interval_seconds()
+ if not await tick_allowed("retention-purge"):
+ try:
+ await asyncio.wait_for(stop.wait(), timeout=pause)
+ except TimeoutError:
+ pass
+ continue
try:
limit = get_retention_batch_size()
report = await run_tracked(
diff --git a/src/xagent/web/services/uploaded_file_recovery.py b/src/xagent/web/services/uploaded_file_recovery.py
index d37ec6a5f..bebec9244 100644
--- a/src/xagent/web/services/uploaded_file_recovery.py
+++ b/src/xagent/web/services/uploaded_file_recovery.py
@@ -13,6 +13,7 @@ from sqlalchemy.orm import Session
from ..models.uploaded_file import UploadedFile
from .db_runtime import is_database_pool_timeout, run_db_io_cancellation_safe
+from .generation import tick_allowed
from .uploaded_file_cleanup import run_uploaded_file_cleanup
from .uploaded_file_store import (
StoragePresence,
@@ -195,6 +196,9 @@ async def run_uploaded_file_compensation_recovery_loop(
cursor: UploadedFileCompensationRecoveryCursor | None = None
while True:
+ if not await tick_allowed("uploaded-file-recovery"):
+ await asyncio.sleep(poll_interval_seconds)
+ continue
try:
cutoff = datetime.now(timezone.utc) - timedelta(seconds=stale_after_seconds)
result = await run_db_io_cancellation_safe(
diff --git a/tests/migrations/test_20261115_serving_generation.py b/tests/migrations/test_20261115_serving_generation.py
new file mode 100644
index 000000000..652adbb88
--- /dev/null
+++ b/tests/migrations/test_20261115_serving_generation.py
@@ -0,0 +1,74 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import sqlalchemy as sa
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from alembic.script import ScriptDirectory
+
+from tests.shared.postgres_disposable import load_migration_module
+from xagent.db.config import create_alembic_config
+from xagent.web.models.database import Base
+
+MIGRATION = load_migration_module(
+ Path(__file__).parents[2]
+ / "src/xagent/migrations/versions/20261115_serving_generation.py"
+)
+
+
+def _run(connection, fn) -> None:
+ with Operations.context(MigrationContext.configure(connection)):
+ fn()
+
+
+def test_upgrade_adds_only_the_single_row_table(tmp_path) -> None:
+ engine = sa.create_engine(f"sqlite:///{tmp_path / 'm.db'}")
+ with engine.begin() as connection:
+ _run(connection, MIGRATION.upgrade)
+ _run(connection, MIGRATION.upgrade) # idempotent
+ inspector = sa.inspect(connection)
+ assert inspector.get_table_names() == ["serving_generation"]
+ model = Base.metadata.tables["serving_generation"]
+ assert {c["name"] for c in inspector.get_columns("serving_generation")} == set(
+ model.columns.keys()
+ )
+ connection.execute(
+ sa.text("INSERT INTO serving_generation (id, generation) VALUES (1, 'a')")
+ )
+ try:
+ connection.execute(
+ sa.text(
+ "INSERT INTO serving_generation (id, generation) VALUES (2, 'b')"
+ )
+ )
+ except sa.exc.IntegrityError:
+ pass
+ else: # pragma: no cover
+ raise AssertionError("a second row must be refused")
+ with engine.begin() as connection:
+ _run(connection, MIGRATION.downgrade)
+ assert "serving_generation" not in sa.inspect(connection).get_table_names()
+
+
+def test_revision_chains_onto_the_previous_head(tmp_path) -> None:
+ engine = sa.create_engine(f"sqlite:///{tmp_path / 'h.db'}")
+ script = ScriptDirectory.from_config(create_alembic_config(engine))
+ revision = script.get_revision("20261115_serving_generation")
+ assert revision.down_revision == "20261115_user_oauth_issuer"
+ assert len(script.get_heads()) == 1
+
+
+def test_offline_sql_generation_emits_the_create_table() -> None:
+ from io import StringIO
+
+ buffer = StringIO()
+ context = MigrationContext.configure(
+ dialect_name="postgresql", opts={"as_sql": True, "output_buffer": buffer}
+ )
+ with Operations.context(context):
+ MIGRATION.upgrade()
+ sql = buffer.getvalue()
+ assert "CREATE TABLE serving_generation" in sql
+ assert "ck_serving_generation_single_row" in sql
+ assert "ALTER" not in sql and "INSERT" not in sql
diff --git a/tests/web/services/test_generation.py b/tests/web/services/test_generation.py
new file mode 100644
index 000000000..863a41349
--- /dev/null
+++ b/tests/web/services/test_generation.py
@@ -0,0 +1,182 @@
+"""Generation identity and the serving generation record."""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from tests.shared.db_teardown import drop_all_tables
+from xagent.web.models.database import get_db, get_engine, init_db
+from xagent.web.services import generation
+from xagent.web.services.generation import (
+ current_generation,
+ is_serving,
+ serving_generation,
+ set_serving_generation,
+ start_allowed,
+ tick_allowed,
+)
+
+
+def db(tmp_path, monkeypatch):
+ monkeypatch.delenv(generation.GENERATION_ENV, raising=False)
+ init_db(db_url=f"sqlite:///{tmp_path / 'generation.db'}")
+ session = next(get_db())
+ try:
+ yield session
+ finally:
+ session.close()
+ drop_all_tables(get_engine())
+
+
+def test_generations_off_means_every_check_passes(db, monkeypatch) -> None:
+ assert current_generation() is None
+ assert is_serving()
+ assert start_allowed("x")
+ assert set_serving_generation("blue", None)
+ # Another generation serving changes nothing while generations are off.
+ assert is_serving()
+ monkeypatch.setenv(generation.GENERATION_ENV, " ")
+ assert current_generation() is None
+ assert is_serving()
+
+
+def test_missing_row_passes_then_row_decides(db, monkeypatch) -> None:
+ monkeypatch.setenv(generation.GENERATION_ENV, "green")
+ assert serving_generation() is None
+ assert is_serving()
+ assert set_serving_generation("blue", None)
+ assert serving_generation() == "blue"
+ assert not is_serving()
+ assert not start_allowed("x")
+ monkeypatch.setenv(generation.GENERATION_ENV, "blue")
+ assert is_serving()
+ assert start_allowed("x")
+
+
+def test_compare_and_swap_never_overwrites_an_unexpected_value(db) -> None:
+ assert set_serving_generation("blue", None)
+ # Creating again while the row exists loses.
+ assert not set_serving_generation("green", None)
+ # A stale expectation loses and leaves the value alone.
+ assert not set_serving_generation("green", "other")
+ assert serving_generation() == "blue"
+ assert set_serving_generation("green", "blue")
+ assert serving_generation() == "green"
+ assert not set_serving_generation("blue", "blue")
+ with pytest.raises(ValueError):
+ set_serving_generation("", "green")
+
+
+def test_database_error_is_never_serving(db, monkeypatch) -> None:
+ monkeypatch.setenv(generation.GENERATION_ENV, "green")
+
+ def boom() -> str | None:
+ raise RuntimeError("database down")
+
+ monkeypatch.setattr(generation, "serving_generation", boom)
+ assert not is_serving()
+ # The start-time form only refuses on a definite answer.
+ assert start_allowed("x")
+ assert not asyncio.run(tick_allowed("x"))
+
+
+def test_database_error_with_generations_off_still_passes(db, monkeypatch) -> None:
+ def boom() -> str | None:
+ raise RuntimeError("database down")
+
+ monkeypatch.setattr(generation, "serving_generation", boom)
+ assert is_serving()
+ assert asyncio.run(tick_allowed("x"))
+
+
+async def _run_briefly(coro) -> None:
+ task = asyncio.create_task(coro)
+ await asyncio.sleep(0.15)
+ task.cancel()
+ (outcome,) = await asyncio.gather(task, return_exceptions=True)
+ # Cancellation is how the helper stops the loop; the sentinel is how the
+ # fake tick stops it. Anything else is a real failure and must surface.
+ if isinstance(outcome, BaseException) and not isinstance(
+ outcome, asyncio.CancelledError
+ ):
+ if str(outcome) != "stop after the first tick":
+ raise outcome
+
+
[email protected]("serving", [False, True])
+async def test_lease_recovery_and_auto_resume_loops_honor_the_record(
+ db, monkeypatch, serving
+) -> None:
+ from xagent.web.services import task_auto_resume, task_lease_recovery
+
+ monkeypatch.setenv(generation.GENERATION_ENV, "green")
+ assert set_serving_generation("green" if serving else "blue", None)
+ calls: list[str] = []
+
+ async def fake_recover(**_kw):
+ calls.append("recover")
+ return 0
+
+ def fake_tick(*, now):
+ calls.append("resume")
+ raise RuntimeError("stop after the first tick")
+
+ monkeypatch.setattr(
+ task_lease_recovery, "recover_expired_task_leases_until_cutoff", fake_recover
+ )
+ monkeypatch.setattr(task_auto_resume, "run_auto_resume_tick", fake_tick)
+ await _run_briefly(
+ task_lease_recovery.run_task_lease_recovery_loop(
+ poll_interval_seconds=0, batch_size=1
+ )
+ )
+ await _run_briefly(
+ task_auto_resume.run_task_auto_resume_loop(poll_interval_seconds=0)
+ )
+ # Each loop is guarded on its own, so each must be seen on its own.
+ assert ("recover" in calls) is serving
+ assert ("resume" in calls) is serving
+
+
+async def test_singleton_starters_refuse_when_another_generation_serves(
+ db, monkeypatch
+) -> None:
+ from xagent.web import app as app_module
+
+ monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False)
+ monkeypatch.setenv(generation.GENERATION_ENV, "green")
+ assert set_serving_generation("blue", None)
+ monkeypatch.setattr(app_module, "get_trigger_dispatcher_enabled", lambda: True)
+ assert app_module.start_trigger_dispatcher_task(app_module.app) is None
+ assert app_module.start_task_lease_recovery_task(app_module.app) is None
+ assert app_module.start_task_auto_resume_task(app_module.app) is None
+
+
+def test_generations_off_never_reads_the_database(monkeypatch) -> None:
+ """Every host today: no query, no failure mode, no log on any tick."""
+ monkeypatch.delenv(generation.GENERATION_ENV, raising=False)
+
+ def forbidden() -> str | None:
+ raise AssertionError("the record must not be read while generations are off")
+
+ monkeypatch.setattr(generation, "serving_generation", forbidden)
+ assert is_serving()
+ assert start_allowed("x")
+ assert asyncio.run(tick_allowed("x"))
+
+
+def test_generations_off_logs_nothing(monkeypatch, caplog) -> None:
+ monkeypatch.delenv(generation.GENERATION_ENV, raising=False)
+ monkeypatch.setattr(
+ generation, "serving_generation", lambda: (_ for _ in ()).throw(RuntimeError())
+ )
+ with caplog.at_level("DEBUG", logger=generation.logger.name):
+ is_serving()
+ start_allowed("x")
+ asyncio.run(tick_allowed("x"))
+ assert caplog.records == []
diff --git a/tests/web/test_blocking_call_inventory.py b/tests/web/test_blocking_call_inventory.py
index 1c80d7021..3dd9c5c76 100644
--- a/tests/web/test_blocking_call_inventory.py
+++ b/tests/web/test_blocking_call_inventory.py
@@ -160,6 +160,8 @@ ALLOWED: dict[str, tuple[int, str]] = {
"(an embedding host constructs it); it is not part of any loop "
"retire_writers stops.",
),
+ # Only reads the serving-generation row (is_serving never writes).
+ "web/services/generation.py": (2, READ),
"web/services/gmail_triggers.py": (
5,
"Gmail Pub/Sub webhook collection (collect_gmail_pubsub_events): "
diff --git a/tests/web/test_channel_generation_fence.py b/tests/web/test_channel_generation_fence.py
new file mode 100644
index 000000000..267091fe0
--- /dev/null
+++ b/tests/web/test_channel_generation_fence.py
@@ -0,0 +1,219 @@
+"""Chat intake belongs to the serving generation only.
+
+``start_allowed`` lets a start through when the record cannot be read, so the
+real fence for the chat channels has to live in the shared manager sync that
+every start path goes through: the manager's own loop, channel create/update
+and the Slack OAuth/deactivation sync. An unreadable record keeps the channels
+dormant; they open only once this generation is confirmed as the serving one.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+import pytest
+
+from xagent.web.channels.feishu import bot as feishu_bot
+from xagent.web.channels.slack import bot as slack_bot
+from xagent.web.channels.telegram import bot as telegram_bot
+from xagent.web.services import generation
+from xagent.web.services.channel_runtime import ChannelConfigSnapshot
+
+
+def _snapshot(items: tuple[tuple[str, str], ...]) -> ChannelConfigSnapshot:
+ return ChannelConfigSnapshot(channel_id=1, channel_name="c", config_items=items)
+
+
+def _arm(monkeypatch: pytest.MonkeyPatch, kind: str) -> tuple[Any, list[str], Any]:
+ """Return (manager, started, api_sync) with one active channel configured."""
+ started: list[str] = []
+
+ async def record(*_a: Any, **_k: Any) -> None:
+ started.append(kind)
+
+ if kind == "telegram":
+ mod, manager = telegram_bot, telegram_bot.TelegramChannelManager()
+ items = (("bot_token", "tg-token"),)
+ manager._start_bot_for_token = record # type: ignore[method-assign]
+ elif kind == "feishu":
+ mod, manager = feishu_bot, feishu_bot.FeishuChannelManager()
+ items = (("app_id", "app"), ("app_secret", "secret"))
+ manager._start_bot_for_appid = record # type: ignore[method-assign]
+ else:
+ mod, manager = slack_bot, slack_bot.SlackChannelManager()
+ items = (("bot_token", "xoxb"), ("app_token", "xapp"))
+ manager._start_bot_for_token = record # type: ignore[method-assign]
+
+ async def load(**_k: Any) -> tuple[ChannelConfigSnapshot, ...]:
+ return (_snapshot(items),)
+
+ monkeypatch.setattr(mod, "load_active_channel_configs", load)
+ monkeypatch.setattr(mod, "get_channel_ingress_enabled", lambda: True)
+ return manager, started, mod
+
+
+KINDS = ["telegram", "feishu", "slack"]
+
+
[email protected]("kind", KINDS)
+async def test_sync_keeps_channels_dormant_until_serving_is_confirmed(
+ monkeypatch, kind
+) -> None:
+ """Startup read error, then recovery with another generation serving."""
+ monkeypatch.setenv(generation.GENERATION_ENV, "blue")
+ manager, started, _ = _arm(monkeypatch, kind)
+ record: dict[str, Any] = {"value": RuntimeError("db blip")}
+
+ def read() -> str | None:
+ if isinstance(record["value"], Exception):
+ raise record["value"]
+ return record["value"]
+
+ monkeypatch.setattr(generation, "serving_generation", read)
+
+ # The record is unreadable: fail closed, nothing opens.
+ await manager._sync_bots_async()
+ assert started == []
+ # Recovered, and green serves: still nothing opens for blue.
+ record["value"] = "green"
+ await manager._sync_bots_async()
+ assert started == []
+ # Blue becomes the serving generation: now the sync opens the channel.
+ record["value"] = "blue"
+ await manager._sync_bots_async()
+ assert started == [kind]
+
+
[email protected]("kind", KINDS)
+async def test_direct_sync_from_the_api_respects_the_record(monkeypatch, kind) -> None:
+ """Channel create/update and Slack OAuth call the sync helpers directly."""
+ from xagent.web.api import channel as channel_api
+
+ monkeypatch.setenv(generation.GENERATION_ENV, "blue")
+ _, started, _ = _arm(monkeypatch, kind)
+ # The helpers resolve the process-wide manager; arm that one.
+ mod = {"telegram": telegram_bot, "feishu": feishu_bot, "slack": slack_bot}[kind]
+ getter = getattr(mod, f"get_{kind}_channel")
+ manager = getter()
+ for attr in ("_start_bot_for_token", "_start_bot_for_appid"):
+ if hasattr(manager, attr):
+
+ async def record(*_a: Any, **_k: Any) -> None:
+ started.append(kind)
+
+ monkeypatch.setattr(manager, attr, record)
+ monkeypatch.setattr(generation, "serving_generation", lambda: "green")
+ trigger = getattr(channel_api, f"trigger_{kind}_sync")
+ await trigger()
+ assert started == []
+
+
[email protected]("kind", KINDS)
+async def test_a_generation_that_stops_serving_closes_its_running_bots(
+ monkeypatch, kind
+) -> None:
+ monkeypatch.setenv(generation.GENERATION_ENV, "blue")
+ manager, started, _ = _arm(monkeypatch, kind)
+ stopped: list[str] = []
+
+ async def stop() -> None:
+ stopped.append(kind)
+
+ manager.stop = stop # type: ignore[method-assign]
+ serving = {"value": "blue"}
+ monkeypatch.setattr(generation, "serving_generation", lambda: serving["value"])
+ await manager._sync_bots_async()
+ assert started == [kind] and stopped == []
+ # A read blip keeps what is running: it only refuses to open anything new.
+ monkeypatch.setattr(
+ generation,
+ "serving_generation",
+ lambda: (_ for _ in ()).throw(RuntimeError("blip")),
+ )
+ await manager._sync_bots_async()
+ assert stopped == []
+ monkeypatch.setattr(generation, "serving_generation", lambda: serving["value"])
+ serving["value"] = "green"
+ await manager._sync_bots_async()
+ assert stopped == [kind]
+ assert started == [kind] # nothing new opened
+
+
+def _forbid_record_reads(monkeypatch: pytest.MonkeyPatch) -> None:
+ def forbidden() -> str | None:
+ raise AssertionError("generations are off: the record must not be read")
+
+ monkeypatch.setattr(generation, "serving_generation", forbidden)
+
+
[email protected]("kind", KINDS)
+async def test_generations_off_sync_reads_and_logs_nothing_new(
+ monkeypatch, caplog, kind
+) -> None:
+ monkeypatch.delenv(generation.GENERATION_ENV, raising=False)
+ manager, started, _ = _arm(monkeypatch, kind)
+ _forbid_record_reads(monkeypatch)
+ with caplog.at_level("DEBUG", logger=generation.logger.name):
+ await manager._sync_bots_async()
+ assert started == [kind]
+ # Other loggers (the managers' own sync line) keep logging as before; the
+ # fence itself must add nothing.
+ assert [r for r in caplog.records if r.name == generation.logger.name] == []
+
+
[email protected]("kind", KINDS)
+async def test_generations_off_start_returns_after_one_sync_without_shared_mode(
+ monkeypatch, kind
+) -> None:
+ monkeypatch.delenv(generation.GENERATION_ENV, raising=False)
+ manager, started, mod = _arm(monkeypatch, kind)
+ monkeypatch.setattr(mod, "get_shared_task_execution_enabled", lambda: False)
+ _forbid_record_reads(monkeypatch)
+ await asyncio.wait_for(manager.start(), timeout=5)
+ assert started == [kind]
+
+
[email protected]("kind", KINDS)
+async def test_manager_loop_keeps_retrying_until_serving_is_confirmed(
+ monkeypatch, kind
+) -> None:
+ monkeypatch.setenv(generation.GENERATION_ENV, "blue")
+ manager, started, mod = _arm(monkeypatch, kind)
+ monkeypatch.setattr(mod, "get_shared_task_execution_enabled", lambda: False)
+ reads = iter([RuntimeError("blip"), "green", "blue"])
+
+ def read() -> str | None:
+ value = next(reads)
+ if isinstance(value, Exception):
+ raise value
+ return value
+
+ monkeypatch.setattr(generation, "serving_generation", read)
+ sleeps: list[float] = []
+ real_sleep = asyncio.sleep
+
+ async def fast_sleep(delay: float) -> None:
+ # Only the manager's 30s retry interval is replaced; the test's own
+ # yields keep their real behaviour.
+ if delay == 30:
+ sleeps.append(delay)
+ delay = 0
+ await real_sleep(delay)
+
+ monkeypatch.setattr(asyncio, "sleep", fast_sleep)
+ task = asyncio.create_task(manager.start())
+ for _ in range(200):
+ if started:
+ break
+ await real_sleep(0.01)
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ assert started == [kind]
+ assert sleeps and set(sleeps) == {30}