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

fix(trajectory): connect team sink and gateway update fan-out

guozirui16d388b8d2fc8
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.py
index 44b78dd6b1..274ac6171e 100644
--- a/jiuwenswarm/agents/harness/team/team_manager.py
+++ b/jiuwenswarm/agents/harness/team/team_manager.py
@@ -66,6 +66,8 @@ from jiuwenswarm.common.config import (
get_skill_evolution_enabled,
)
from jiuwenswarm.agents.harness.observability_runtime import build_observability_config
+from jiuwenswarm.observability.config import load_trajectory_store_settings # noqa: E402
+from jiuwenswarm.observability.runtime import sync_trajectory_runtime # noqa: E402
from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargs
from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (
MemberInfo,
@@ -138,6 +140,9 @@ def sync_team_observability() -> None:
Evolution also requests the provider when the explicit switch is disabled.
"""
global _observability_active, _runtime_managed_observability
+
+ config = get_config()
+ trajectory_settings = load_trajectory_store_settings(config)
try:
unified_active = bool(_get_unified_runtime().is_unified_active())
except Exception as exc:
@@ -160,17 +165,24 @@ def sync_team_observability() -> None:
"on unified path: %s",
exc,
)
+ try:
+ sync_trajectory_runtime(trajectory_settings, demand="team")
+ except Exception as exc:
+ logger.warning("[TeamObservability] trajectory runtime init failed: %s", exc)
return
if _runtime_managed_observability:
_observability_active = False
_runtime_managed_observability = False
- config = get_config()
cfg = config.get("team_observability", {}) or {}
evolution_requested = get_skill_evolution_enabled(config)
- want_enabled = bool(cfg.get("enabled", False)) or evolution_requested
+ want_enabled = bool(cfg.get("enabled", False)) or trajectory_settings.enabled or evolution_requested
if not want_enabled:
+ try:
+ sync_trajectory_runtime(trajectory_settings, demand="team")
+ except Exception as exc:
+ logger.warning("[TeamObservability] trajectory runtime stop failed: %s", exc)
if _observability_active:
shutdown_team_observability()
return
@@ -185,6 +197,10 @@ def sync_team_observability() -> None:
provider_existed = team_observability.acquire_observability(obs_cfg)
was_active = _observability_active
_observability_active = True
+ try:
+ sync_trajectory_runtime(trajectory_settings, demand="team")
+ except Exception as exc:
+ logger.warning("[TeamObservability] trajectory runtime init failed: %s", exc)
if not was_active and not provider_existed:
if cfg.get("exporter", "otlp_grpc") == "file":
logger.info(
diff --git a/jiuwenswarm/gateway/channel_manager/web/web_connect.py b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
index 637897618d..f0f6241f7c 100644
--- a/jiuwenswarm/gateway/channel_manager/web/web_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/web/web_connect.py
@@ -33,6 +33,8 @@ from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (
_WEB_CONNECTION_USER_ID_ATTR,
)
+_TRAJECTORY_HINT_COALESCE_SECONDS = 0.05
+
# Backward-compatible re-exports for invoke.py and tests.
_HANDLER_BEFORE_CALLBACK_METHODS = HANDLER_BEFORE_CALLBACK_METHODS
_MethodHandlerInvocation = MethodHandlerInvocation
@@ -63,6 +65,8 @@ class WebChannel(BaseChannel):
self._trajectory_event_loop: asyncio.AbstractEventLoop | None = None
self._trajectory_listener_registered = False
self._trajectory_update_listener = self._on_trajectory_updates
+ self._trajectory_pending_updates: dict[tuple[str, str], Any] = {}
+ self._trajectory_send_task: asyncio.Task[None] | None = None
# ── Compatibility shims (invoke / handlers access private attrs) ──
@@ -288,15 +292,50 @@ class WebChannel(BaseChannel):
trajectory_update_broker.unregister(self._trajectory_update_listener)
self._trajectory_listener_registered = False
self._trajectory_event_loop = None
+ task = self._trajectory_send_task
+ if task is not None and not task.done():
+ task.cancel()
+ self._trajectory_send_task = None
+ self._trajectory_pending_updates.clear()
def _on_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
loop = self._trajectory_event_loop
if loop is None or loop.is_closed():
return
- loop.call_soon_threadsafe(self._schedule_trajectory_updates, updates)
+ loop.call_soon_threadsafe(self.schedule_trajectory_updates, updates)
+
+ def schedule_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
+ """Queue committed hints from the local sink or the Gateway push path."""
+ self._schedule_trajectory_updates(updates)
def _schedule_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
- asyncio.create_task(self._send_trajectory_updates(updates))
+ for update in updates:
+ session_id = str(getattr(update, "session_id", "") or "").strip()
+ trace_id = str(getattr(update, "trace_id", "") or "").strip()
+ if not session_id or not trace_id:
+ continue
+ key = (session_id, trace_id)
+ current = self._trajectory_pending_updates.get(key)
+ revision = int(getattr(update, "revision", 0))
+ if current is not None:
+ current_revision = int(getattr(current, "revision", 0))
+ if revision < current_revision:
+ continue
+ if revision == current_revision and getattr(current, "lifecycle", "") == "final":
+ continue
+ self._trajectory_pending_updates[key] = update
+ if self._trajectory_pending_updates and self._trajectory_send_task is None:
+ self._trajectory_send_task = asyncio.create_task(self._flush_trajectory_updates())
+
+ async def _flush_trajectory_updates(self) -> None:
+ try:
+ await asyncio.sleep(_TRAJECTORY_HINT_COALESCE_SECONDS)
+ while self._trajectory_pending_updates:
+ updates = tuple(self._trajectory_pending_updates.values())
+ self._trajectory_pending_updates.clear()
+ await self._send_trajectory_updates(updates)
+ finally:
+ self._trajectory_send_task = None
async def _send_trajectory_updates(self, updates: tuple[Any, ...]) -> None:
for update in updates:
diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.py
index fd02a9e51c..f4b239a171 100644
--- a/jiuwenswarm/gateway/message_handler/message_handler.py
+++ b/jiuwenswarm/gateway/message_handler/message_handler.py
@@ -2942,6 +2942,26 @@ class MessageHandler(FileTransferMixin, ABC):
except Exception as e:
logger.exception("[MessageHandler] server_push 解析失败: %s", e)
return
+ payload = chunk.payload
+ if isinstance(payload, dict) and payload.get("event_type") == "trace.updated":
+ from jiuwenswarm.observability.models import CommittedTraceUpdate
+
+ try:
+ update = CommittedTraceUpdate(
+ session_id=str(payload["session_id"]),
+ trace_id=str(payload["trace_id"]),
+ revision=int(payload["revision"]),
+ store_epoch=payload.get("store_epoch"),
+ lifecycle=str(payload.get("lifecycle") or "final"),
+ )
+ except (KeyError, TypeError, ValueError):
+ logger.warning("[MessageHandler] ignored invalid trace update push")
+ return
+ web_channel = self._resolve_web_channel()
+ schedule = getattr(web_channel, "schedule_trajectory_updates", None)
+ if callable(schedule):
+ schedule((update,))
+ return
rid = str(chunk.request_id or "")
sid_raw = wire.get("session_id")
if sid_raw is not None and str(sid_raw).strip():
diff --git a/tests/unit_tests/observability/test_trajectory_gateway_hints.py b/tests/unit_tests/observability/test_trajectory_gateway_hints.py
index 753aa81c10..ca5e8368eb 100644
--- a/tests/unit_tests/observability/test_trajectory_gateway_hints.py
+++ b/tests/unit_tests/observability/test_trajectory_gateway_hints.py
@@ -97,6 +97,22 @@ async def test_gateway_routes_cross_process_hint_into_webchannel_coalescer() ->
),
)
]
+ invalid_wire = build_server_push_wire(
+ {
+ "request_id": "trajectory:session-1:trace:invalid",
+ "channel_id": "web",
+ "session_id": "session-1",
+ "is_complete": False,
+ "payload": {
+ "event_type": "trace.updated",
+ "session_id": "session-1",
+ "trace_id": "b" * 32,
+ "revision": "invalid",
+ },
+ }
+ )
+ await handler._handle_agent_server_push(invalid_wire)
+ assert len(scheduled) == 1
test_logger.info("Gateway handed the cross-process hint to WebChannel")
diff --git a/tests/unit_tests/observability/test_trajectory_updates.py b/tests/unit_tests/observability/test_trajectory_updates.py
index b3966e2917..79db62e25c 100644
--- a/tests/unit_tests/observability/test_trajectory_updates.py
+++ b/tests/unit_tests/observability/test_trajectory_updates.py
@@ -5,7 +5,7 @@
from __future__ import annotations
import logging
-from dataclasses import dataclass
+from types import SimpleNamespace
import pytest
@@ -16,11 +16,6 @@ from jiuwenswarm.observability.updates import TrajectoryUpdateBroker
test_logger = logging.getLogger("tests.trajectory_updates")
-@dataclass(frozen=True)
-class _RoutingKey:
- session_id: str
-
-
class _WebSocket:
closed = False
@@ -58,10 +53,13 @@ async def test_webchannel_routes_trace_update_to_matching_session_only() -> None
channel = WebChannel.__new__(WebChannel)
first_ws = _WebSocket()
other_ws = _WebSocket()
- channel._clients_by_key = {
- _RoutingKey(session_id="session-1"): [first_ws],
- _RoutingKey(session_id="session-2"): [other_ws],
- }
+ channel.ws = SimpleNamespace(
+ clients={first_ws, other_ws},
+ peers_for_session_ws=lambda session_id: (
+ {first_ws} if session_id == "session-1" else {other_ws}
+ ),
+ )
+ channel.delivery = SimpleNamespace(peers_for_session=lambda _session_id: set())
sent: list[tuple[object, str, dict[str, object]]] = []
async def _send_event(ws, event, payload) -> None: