Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

gateway多副本情况下,主动向DB拉取最新的配置

caozhenhua00004adfd108817e
diff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.py
index 9e79944940..d5c7586f46 100644
--- a/jiuwenswarm/gateway/app_gateway.py
+++ b/jiuwenswarm/gateway/app_gateway.py
@@ -2639,6 +2639,16 @@ async def _run_with_telemetry(
)
await channel_manager.start_dispatch()
+
+ config_poll_scheduler = None
+ try:
+ from jiuwenswarm.gateway.config_poll import get_config_poll_scheduler
+
+ config_poll_scheduler = get_config_poll_scheduler()
+ await config_poll_scheduler.start()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[App] gateway config poll scheduler failed to start: %s", exc)
+
# cron jobs 的 work_mode 补全已改为惰性迁移:scheduler.start() → reload() →
# list_jobs() 读取时按需推断并写回磁盘(见 CronJobStore.list_jobs),无需启动全量扫描。
# default/default scheduler already started via get_controller above.
@@ -2704,6 +2714,11 @@ async def _run_with_telemetry(
except asyncio.CancelledError:
pass
finally:
+ if config_poll_scheduler is not None:
+ try:
+ await config_poll_scheduler.stop()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("[App] gateway config poll scheduler stop failed: %s", exc)
if prewarm_sync_debounce_task is not None:
prewarm_sync_debounce_task.cancel()
try:
diff --git a/jiuwenswarm/gateway/config_poll/__init__.py b/jiuwenswarm/gateway/config_poll/__init__.py
new file mode 100644
index 0000000000..484d3781f1
--- /dev/null
+++ b/jiuwenswarm/gateway/config_poll/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Gateway 企业配置库轮询:多副本从共享库同步 Gateway 自身配置。"""
+
+from .scheduler import ConfigPollScheduler, get_config_poll_scheduler
+
+__all__ = ("ConfigPollScheduler", "get_config_poll_scheduler")
diff --git a/jiuwenswarm/gateway/config_poll/appliers.py b/jiuwenswarm/gateway/config_poll/appliers.py
new file mode 100644
index 0000000000..8619164db7
--- /dev/null
+++ b/jiuwenswarm/gateway/config_poll/appliers.py
@@ -0,0 +1,96 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any, Awaitable, Callable
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class TableApplyContext:
+ rows: list[dict[str, Any]]
+ removed_channel_ids: frozenset[str] = frozenset()
+
+
+ApplyTableFn = Callable[[str, TableApplyContext], Awaitable[None]]
+
+
+def _enabled_log_masking_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ enabled_rows: list[dict[str, Any]] = []
+ for row in rows:
+ enabled = row.get("enabled", True)
+ if isinstance(enabled, int):
+ enabled = bool(enabled)
+ if enabled:
+ enabled_rows.append(row)
+ enabled_rows.sort(
+ key=lambda item: (-int(item.get("priority") or 0), int(item.get("id") or 0)),
+ )
+ return enabled_rows
+
+
+async def apply_logging_config_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
+ _ = jiuwenclaw_id
+ from jiuwenswarm.common.utils import (
+ _logging_config_row_to_dict,
+ apply_logging_config_payload,
+ )
+
+ row = ctx.rows[0] if ctx.rows else None
+ if len(ctx.rows) > 1:
+ logger.warning(
+ "[ConfigPoll] logging_config expected one row, got %d; using first",
+ len(ctx.rows),
+ )
+ apply_logging_config_payload(
+ _logging_config_row_to_dict(row) if row is not None else None,
+ )
+ logger.info("[ConfigPoll] logging_config applied rows=%d", len(ctx.rows))
+
+
+async def apply_log_masking_rule_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
+ _ = jiuwenclaw_id
+ from jiuwenswarm.infrastructure.log_masking.engine import LogMaskingEngine
+
+ rows = _enabled_log_masking_rows(ctx.rows)
+ LogMaskingEngine.reload_from_rows(rows, db_authoritative=True)
+ logger.info("[ConfigPoll] log_masking_rule applied rows=%d", len(rows))
+
+
+async def apply_channel_config_table(jiuwenclaw_id: str, ctx: TableApplyContext) -> None:
+ _ = jiuwenclaw_id
+ try:
+ from jiuwenclaw.gateway.channel_config_overlay import ChannelConfigChange
+ from jiuwenclaw.gateway.channel_config_reload import maybe_trigger_channel_config_reload
+ except ImportError as exc:
+ raise RuntimeError(
+ "channel_config reload unavailable; manager_ws_client not loaded"
+ ) from exc
+
+ for channel_id in sorted(ctx.removed_channel_ids):
+ await maybe_trigger_channel_config_reload(
+ ChannelConfigChange.remove({"channel_id": channel_id})
+ )
+
+ for record in ctx.rows:
+ status = str(record.get("status") or "").strip().lower()
+ if status == "active":
+ await maybe_trigger_channel_config_reload(ChannelConfigChange.upsert(record))
+ else:
+ await maybe_trigger_channel_config_reload(ChannelConfigChange.remove(record))
+
+ logger.info(
+ "[ConfigPoll] channel_config reloaded rows=%d removed=%d",
+ len(ctx.rows),
+ len(ctx.removed_channel_ids),
+ )
+
+
+TABLE_APPLIERS: dict[str, ApplyTableFn] = {
+ "channel_config": apply_channel_config_table,
+ "logging_config": apply_logging_config_table,
+ "log_masking_rule": apply_log_masking_rule_table,
+}
diff --git a/jiuwenswarm/gateway/config_poll/db.py b/jiuwenswarm/gateway/config_poll/db.py
new file mode 100644
index 0000000000..635120829f
--- /dev/null
+++ b/jiuwenswarm/gateway/config_poll/db.py
@@ -0,0 +1,108 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import logging
+from datetime import datetime, timezone
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+POLL_TABLES: tuple[str, ...] = (
+ "channel_config",
+ "logging_config",
+ "log_masking_rule",
+)
+_POLL_TABLES = frozenset(POLL_TABLES)
+
+
+def _normalize_updated_at(value: Any) -> datetime | None:
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ dt = value
+ else:
+ text = str(value).strip()
+ if not text:
+ return None
+ normalized = text.replace("Z", "+00:00")
+ try:
+ dt = datetime.fromisoformat(normalized)
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ return dt.replace(tzinfo=timezone.utc)
+ return dt.astimezone(timezone.utc)
+
+
+def row_key(table: str, row: dict[str, Any]) -> str:
+ if table == "channel_config":
+ return str(row.get("channel_id") or "").strip()
+ if table == "log_masking_rule":
+ return str(row.get("rule_id") or "").strip()
+ return str(row.get("jiuwenclaw_id") or row.get("id") or "default").strip()
+
+
+def row_stamp(row: dict[str, Any]) -> str:
+ ts = _normalize_updated_at(row.get("updated_at"))
+ return ts.isoformat() if ts is not None else ""
+
+
+def row_snapshot(table: str, rows: list[dict[str, Any]]) -> dict[str, str]:
+ snapshot: dict[str, str] = {}
+ for row in rows:
+ key = row_key(table, row)
+ if not key:
+ continue
+ snapshot[key] = row_stamp(row)
+ return snapshot
+
+
+def _row_to_dict(row: Any) -> dict[str, Any]:
+ if isinstance(row, dict):
+ return dict(row)
+ out: dict[str, Any] = {}
+ for key in ("id", "jiuwenclaw_id", "updated_at", "created_at", "status"):
+ if hasattr(row, key):
+ out[key] = getattr(row, key)
+ if hasattr(row, "__dict__"):
+ for key, value in vars(row).items():
+ if not key.startswith("_"):
+ out.setdefault(key, value)
+ return out
+
+
+async def _list_records_via_ee_handler(
+ table: str,
+ jiuwenclaw_id: str,
+) -> list[dict[str, Any]] | None:
+ try:
+ from jiuwenclaw.infrastructure.module_importer import import_manager_ws_client_module
+
+ db_mod = import_manager_ws_client_module("infrastructure.db")
+ ensure_db_handler = getattr(db_mod, "ensure_db_handler", None)
+ if ensure_db_handler is None:
+ return None
+ handler = await ensure_db_handler()
+ rows = await handler.list_records(table, {"jiuwenclaw_id": jiuwenclaw_id})
+ return [_row_to_dict(row) for row in rows]
+ except Exception as exc: # noqa: BLE001
+ logger.debug("[ConfigPoll] EE DB handler unavailable for %s: %s", table, exc)
+ return None
+
+
+async def list_table_records(table: str, jiuwenclaw_id: str) -> list[dict[str, Any]]:
+ if table not in _POLL_TABLES:
+ logger.warning("[ConfigPoll] unsupported table: %s", table)
+ return []
+ jid = str(jiuwenclaw_id or "").strip()
+ if not jid:
+ return []
+
+ ee_rows = await _list_records_via_ee_handler(table, jid)
+ if ee_rows is not None:
+ return ee_rows
+
+ from jiuwenswarm.server.runtime.enterprise_config import gateway_db
+
+ return await gateway_db.list_records(table, filters={"jiuwenclaw_id": jid})
diff --git a/jiuwenswarm/gateway/config_poll/scheduler.py b/jiuwenswarm/gateway/config_poll/scheduler.py
new file mode 100644
index 0000000000..652637265d
--- /dev/null
+++ b/jiuwenswarm/gateway/config_poll/scheduler.py
@@ -0,0 +1,125 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+
+from jiuwenswarm.common.config import get_config
+
+from .db import POLL_TABLES
+from .syncer import ConfigPollSyncer
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_POLL_INTERVAL_SECONDS = 10.0
+
+_scheduler: ConfigPollScheduler | None = None
+
+
+def _parse_bool(raw: object, *, default: bool) -> bool:
+ if raw is None:
+ return default
+ if isinstance(raw, bool):
+ return raw
+ text = str(raw).strip().lower()
+ if text in ("1", "true", "yes", "on"):
+ return True
+ if text in ("0", "false", "no", "off"):
+ return False
+ return default
+
+
+def config_poll_enabled() -> bool:
+ if not os.getenv("AGENT_RUNTIME", "").strip():
+ return False
+ env = os.getenv("GATEWAY_CONFIG_POLL_ENABLED")
+ if env is not None and str(env).strip():
+ return _parse_bool(env, default=True)
+ poll = (get_config().get("gateway") or {}).get("config_poll") or {}
+ if isinstance(poll, dict) and "enabled" in poll:
+ return _parse_bool(poll.get("enabled"), default=True)
+ return True
+
+
+def config_poll_interval_seconds() -> float:
+ env = os.getenv("GATEWAY_CONFIG_POLL_INTERVAL_SECONDS", "").strip()
+ if env:
+ return max(1.0, float(env))
+ poll = (get_config().get("gateway") or {}).get("config_poll") or {}
+ if isinstance(poll, dict) and poll.get("interval_seconds") is not None:
+ return max(1.0, float(poll["interval_seconds"]))
+ return DEFAULT_POLL_INTERVAL_SECONDS
+
+
+class ConfigPollScheduler:
+ """周期拉取共享库配置;启停模式与 ``GatewayHeartbeatService`` 一致。"""
+
+ def __init__(
+ self,
+ *,
+ enabled: bool | None = None,
+ interval_seconds: float | None = None,
+ ) -> None:
+ self._enabled = config_poll_enabled() if enabled is None else enabled
+ self._interval_seconds = (
+ config_poll_interval_seconds()
+ if interval_seconds is None
+ else max(1.0, float(interval_seconds))
+ )
+ self._syncer = ConfigPollSyncer()
+ self._running = False
+ self._task: asyncio.Task[None] | None = None
+
+ async def start(self) -> None:
+ if not self._enabled:
+ logger.info("[ConfigPoll] disabled; scheduler not started")
+ return
+ if self._running:
+ return
+ self._running = True
+ self._task = asyncio.create_task(self._run_loop(), name="gateway-config-poll")
+ logger.info(
+ "[ConfigPoll] scheduler started interval=%ss tables=%s",
+ self._interval_seconds,
+ ",".join(POLL_TABLES),
+ )
+
+ async def stop(self) -> None:
+ self._running = False
+ task = self._task
+ if task is None:
+ return
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ self._task = None
+ logger.info("[ConfigPoll] scheduler stopped")
+
+ async def run_once(self) -> None:
+ await self._syncer.run_once()
+
+ async def _run_loop(self) -> None:
+ while self._running:
+ try:
+ await self._syncer.run_once()
+ except asyncio.CancelledError:
+ break
+ except Exception: # noqa: BLE001
+ logger.exception("[ConfigPoll] poll loop iteration failed")
+ if not self._running:
+ break
+ try:
+ await asyncio.sleep(self._interval_seconds)
+ except asyncio.CancelledError:
+ break
+
+
+def get_config_poll_scheduler() -> ConfigPollScheduler:
+ global _scheduler
+ if _scheduler is None:
+ _scheduler = ConfigPollScheduler()
+ return _scheduler
diff --git a/jiuwenswarm/gateway/config_poll/syncer.py b/jiuwenswarm/gateway/config_poll/syncer.py
new file mode 100644
index 0000000000..a0852dae46
--- /dev/null
+++ b/jiuwenswarm/gateway/config_poll/syncer.py
@@ -0,0 +1,73 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import logging
+
+from jiuwenswarm.server.runtime.enterprise_config import gateway_db
+
+from .appliers import TABLE_APPLIERS, TableApplyContext
+from .db import POLL_TABLES, list_table_records, row_snapshot
+
+logger = logging.getLogger(__name__)
+
+if frozenset(TABLE_APPLIERS) != frozenset(POLL_TABLES):
+ raise RuntimeError(
+ f"[ConfigPoll] TABLE_APPLIERS keys {sorted(TABLE_APPLIERS)} "
+ f"!= POLL_TABLES {list(POLL_TABLES)}"
+ )
+
+
+class ConfigPollSyncer:
+ """按行拉取全表,用 ``row_key -> updated_at`` 判断行更新或行删除。"""
+
+ def __init__(self) -> None:
+ self._last_rows: dict[str, dict[str, str]] = {}
+
+ async def run_once(self) -> None:
+ jiuwenclaw_id = gateway_db.resolve_jiuwenclaw_id()
+ if not jiuwenclaw_id:
+ logger.debug("[ConfigPoll] skip: jiuwenclaw_id unset")
+ return
+
+ for table in POLL_TABLES:
+ apply_fn = TABLE_APPLIERS.get(table)
+ if apply_fn is None:
+ logger.warning("[ConfigPoll] no applier registered for table=%s", table)
+ continue
+ try:
+ await self._sync_table(table, jiuwenclaw_id, apply_fn)
+ except Exception: # noqa: BLE001
+ logger.exception(
+ "[ConfigPoll] sync failed table=%s jiuwenclaw_id=%s",
+ table,
+ jiuwenclaw_id,
+ )
+
+ async def _sync_table(
+ self,
+ table: str,
+ jiuwenclaw_id: str,
+ apply_fn,
+ ) -> None:
+ rows = await list_table_records(table, jiuwenclaw_id)
+ current = row_snapshot(table, rows)
+ previous = self._last_rows.get(table, {})
+ if current == previous:
+ return
+
+ removed_channel_ids = frozenset()
+ if table == "channel_config":
+ removed_channel_ids = frozenset(previous.keys()) - frozenset(current.keys())
+
+ ctx = TableApplyContext(rows=rows, removed_channel_ids=removed_channel_ids)
+ await apply_fn(jiuwenclaw_id, ctx)
+ self._last_rows[table] = current
+
+ logger.info(
+ "[ConfigPoll] table synced table=%s jiuwenclaw_id=%s rows=%d removed=%d",
+ table,
+ jiuwenclaw_id,
+ len(current),
+ len(removed_channel_ids),
+ )
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 46451af123..69b98811fb 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -724,6 +724,11 @@ gateway:
# 分布式下用于实例标识;空则启动时自动生成
instance_id: ${GATEWAY_INSTANCE_ID:-}
+ # 企业版 Gateway 多副本:从共享库轮询 Gateway 自身配置(channel/logging/log_masking)
+ config_poll:
+ enabled: ${GATEWAY_CONFIG_POLL_ENABLED:-false}
+ interval_seconds: ${GATEWAY_CONFIG_POLL_INTERVAL_SECONDS:-10}
+
# AgentClient 配置 - Gateway 连接到 AgentServer 的方式
# type: websocket(默认) | yuanrong(直接函数调用) | agentos_router(AgentOS 扩展)
agent_client:
diff --git a/tests/unit_tests/gateway/test_config_poll.py b/tests/unit_tests/gateway/test_config_poll.py
new file mode 100644
index 0000000000..492e247f54
--- /dev/null
+++ b/tests/unit_tests/gateway/test_config_poll.py
@@ -0,0 +1,291 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+import asyncio
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from jiuwenswarm.gateway.config_poll.appliers import TableApplyContext
+from jiuwenswarm.gateway.config_poll.scheduler import (
+ ConfigPollScheduler,
+ config_poll_enabled,
+ config_poll_interval_seconds,
+)
+from jiuwenswarm.gateway.config_poll.syncer import ConfigPollSyncer
+
+
+def test_config_poll_disabled_without_agent_runtime(monkeypatch) -> None:
+ monkeypatch.delenv("AGENT_RUNTIME", raising=False)
+ monkeypatch.delenv("GATEWAY_CONFIG_POLL_ENABLED", raising=False)
+ assert config_poll_enabled() is False
+
+
+def test_config_poll_enabled_with_agent_runtime(monkeypatch) -> None:
+ monkeypatch.setenv("AGENT_RUNTIME", "enterprise")
+ monkeypatch.delenv("GATEWAY_CONFIG_POLL_ENABLED", raising=False)
+ with patch(
+ "jiuwenswarm.gateway.config_poll.scheduler.get_config",
+ return_value={"gateway": {}},
+ ):
+ assert config_poll_enabled() is True
+ assert config_poll_interval_seconds() >= 1.0
+
+
+def test_config_poll_respects_yaml_enabled_false(monkeypatch) -> None:
+ monkeypatch.setenv("AGENT_RUNTIME", "enterprise")
+ monkeypatch.delenv("GATEWAY_CONFIG_POLL_ENABLED", raising=False)
+ with patch(
+ "jiuwenswarm.gateway.config_poll.scheduler.get_config",
+ return_value={"gateway": {"config_poll": {"enabled": False}}},
+ ):
+ assert config_poll_enabled() is False
+
+
+async def test_syncer_applies_when_row_updated_at_changes() -> None:
+ ts1 = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ ts2 = datetime(2026, 1, 2, tzinfo=timezone.utc)
+ apply_mock = AsyncMock()
+ syncer = ConfigPollSyncer()
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "logging_config":
+ return []
+ ts = ts1 if "logging_config" not in syncer._last_rows else ts2
+ return [{"updated_at": ts.isoformat()}]
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"logging_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ apply_mock.assert_awaited_once()
+ assert syncer._last_rows["logging_config"] == {"default": ts1.isoformat()}
+
+ await syncer.run_once()
+ assert apply_mock.await_count == 2
+ assert syncer._last_rows["logging_config"] == {"default": ts2.isoformat()}
+
+
+async def test_syncer_skips_when_snapshot_unchanged() -> None:
+ ts = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ apply_mock = AsyncMock()
+ syncer = ConfigPollSyncer()
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "logging_config":
+ return []
+ return [{"updated_at": ts.isoformat()}]
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"logging_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ await syncer.run_once()
+ apply_mock.assert_awaited_once()
+
+
+async def test_syncer_applies_when_all_rows_deleted() -> None:
+ ts = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ apply_mock = AsyncMock()
+ syncer = ConfigPollSyncer()
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "logging_config":
+ return []
+ if "logging_config" not in syncer._last_rows:
+ return [{"updated_at": ts.isoformat()}]
+ return []
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"logging_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ await syncer.run_once()
+ assert apply_mock.await_count == 2
+ assert syncer._last_rows["logging_config"] == {}
+
+
+async def test_syncer_detects_deleted_channel_row() -> None:
+ ts = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ apply_mock = AsyncMock()
+ syncer = ConfigPollSyncer()
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "channel_config":
+ return []
+ if "channel_config" not in syncer._last_rows:
+ return [
+ {
+ "channel_id": "c1",
+ "status": "active",
+ "updated_at": ts.isoformat(),
+ }
+ ]
+ return [
+ {
+ "channel_id": "c2",
+ "status": "active",
+ "updated_at": ts.isoformat(),
+ }
+ ]
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"channel_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ await syncer.run_once()
+ assert apply_mock.await_count == 2
+ second_ctx = apply_mock.await_args_list[1].args[1]
+ assert second_ctx.removed_channel_ids == frozenset({"c1"})
+
+
+async def test_syncer_keeps_snapshot_when_apply_fails() -> None:
+ ts = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ apply_mock = AsyncMock(side_effect=RuntimeError("boom"))
+ syncer = ConfigPollSyncer()
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "logging_config":
+ return []
+ return [{"updated_at": ts.isoformat()}]
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"logging_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ assert apply_mock.await_count == 1
+ assert "logging_config" not in syncer._last_rows
+
+ apply_mock.side_effect = None
+ await syncer.run_once()
+ assert apply_mock.await_count == 2
+ assert syncer._last_rows["logging_config"] == {"default": ts.isoformat()}
+
+
+async def test_syncer_normalizes_updated_at_for_snapshot() -> None:
+ ts = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ apply_mock = AsyncMock()
+ syncer = ConfigPollSyncer()
+ calls = {"n": 0}
+
+ async def _rows(table: str, _jid: str) -> list[dict]:
+ if table != "logging_config":
+ return []
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return [{"updated_at": ts}]
+ return [{"updated_at": ts.isoformat()}]
+
+ with patch(
+ "jiuwenswarm.gateway.config_poll.syncer.gateway_db.resolve_jiuwenclaw_id",
+ return_value="jid-1",
+ ), patch(
+ "jiuwenswarm.gateway.config_poll.syncer.list_table_records",
+ side_effect=_rows,
+ ), patch.dict(
+ "jiuwenswarm.gateway.config_poll.syncer.TABLE_APPLIERS",
+ {"logging_config": apply_mock},
+ clear=False,
+ ):
+ await syncer.run_once()
+ await syncer.run_once()
+ apply_mock.assert_awaited_once()
+
+
+async def test_apply_logging_config_table_uses_passed_rows() -> None:
+ from jiuwenswarm.gateway.config_poll.appliers import apply_logging_config_table
+
+ with patch(
+ "jiuwenswarm.common.utils.apply_logging_config_payload",
+ ) as apply_payload:
+ await apply_logging_config_table(
+ "jid-1",
+ TableApplyContext(
+ rows=[{"level": "DEBUG", "gateway": "WARNING"}],
+ ),
+ )
+ apply_payload.assert_called_once_with(
+ {
+ "level": "DEBUG",
+ "gateway": "WARNING",
+ "console_level": None,
+ "channel": None,
+ "agent_server": None,
+ "full": None,
+ }
+ )
+
+
+async def test_scheduler_start_stop() -> None:
+ scheduler = ConfigPollScheduler(enabled=True, interval_seconds=0.05)
+ run_once = AsyncMock()
+ scheduler._syncer.run_once = run_once # type: ignore[method-assign]
+
+ await scheduler.start()
+ await asyncio.sleep(0.12)
+ await scheduler.stop()
+
+ assert run_once.await_count >= 1
+
+
+async def test_scheduler_disabled_does_not_start_loop() -> None:
+ scheduler = ConfigPollScheduler(enabled=False, interval_seconds=0.05)
+ run_once = AsyncMock()
+ scheduler._syncer.run_once = run_once # type: ignore[method-assign]
+
+ await scheduler.start()
+ await asyncio.sleep(0.08)
+ await scheduler.stop()
+
+ run_once.assert_not_awaited()
diff --git a/tests/unit_tests/gateway/test_config_poll_db.py b/tests/unit_tests/gateway/test_config_poll_db.py
new file mode 100644
index 0000000000..6d1908b33a
--- /dev/null
+++ b/tests/unit_tests/gateway/test_config_poll_db.py
@@ -0,0 +1,31 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from jiuwenswarm.gateway.config_poll.db import row_snapshot, row_stamp
+
+
+def test_row_snapshot_uses_stable_updated_at_stamp() -> None:
+ ts = datetime(2026, 1, 1, 12, 0, tzinfo=timezone.utc)
+ snap_a = row_snapshot("logging_config", [{"updated_at": ts}])
+ snap_b = row_snapshot("logging_config", [{"updated_at": ts.isoformat()}])
+ assert snap_a == snap_b == {"default": ts.isoformat()}
+
+
+def test_row_snapshot_detects_delete_and_update() -> None:
+ ts1 = datetime(2026, 1, 1, tzinfo=timezone.utc)
+ ts2 = datetime(2026, 1, 2, tzinfo=timezone.utc)
+ before = row_snapshot(
+ "channel_config",
+ [{"channel_id": "c1", "updated_at": ts1.isoformat()}],
+ )
+ after_update = row_snapshot(
+ "channel_config",
+ [{"channel_id": "c1", "updated_at": ts2.isoformat()}],
+ )
+ after_delete = row_snapshot("channel_config", [])
+ assert before != after_update
+ assert before != after_delete
+ assert row_stamp({"updated_at": None}) == ""