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

feat(gateway): session.create 响应返回前调 runtime rebind,修复双计数与亲和断裂

wangmingqifc2acfe72a47
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
index 73d8d78d60..8f5385e8f7 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/runtime_routed_client.py
@@ -106,6 +106,14 @@ def _is_routeless_envelope(envelope: E2AEnvelope) -> bool:
return method in _ROUTELESS_METHODS
+def _rebind_timeout() -> float:
+ try:
+ value = float(read_env("GATEWAY_RUNTIME_SESSION_REBIND_TIMEOUT", "2"))
+ except (TypeError, ValueError):
+ return 2.0
+ return value if value > 0 else 2.0
+
+
def _default_http_base() -> str:
"""管理类请求(reload_config 等)的默认 Agent HTTP Base。
@@ -197,6 +205,7 @@ class RuntimeRoutedAgentClient(AgentServerClient):
self._pod_connect_lock = asyncio.Lock()
self._rpc_origins: dict[tuple[str, str], str] = {}
self._drop_tasks: set[asyncio.Task[None]] = set()
+ self._last_rebind_warn = 0.0 # rebind 降级告警节流(滚动期旧 runtime 404 防刷屏)
def set_server_push_handler(
self, handler: Callable[[dict[str, Any]], Awaitable[None]] | None
@@ -397,8 +406,63 @@ class RuntimeRoutedAgentClient(AgentServerClient):
await self._ensure_pod_push(base_url)
result = await self._http.send_request(envelope, base_url=base_url)
await self._touch_quiet(session_id, route_id)
+ await self._rebind_after_create(envelope, result, session_id)
return result
+ async def _rebind_after_create(
+ self, envelope: E2AEnvelope, result: AgentResponse, session_id: str,
+ ) -> None:
+ """session.create 响应返回上层之前,把临时路由 key 原子改绑为真实 id。
+
+ 修复(runtime 侧 2026-09-session-create-rebind):create 以临时 key
+ (sess_*/webhttp_*/身份组合串)route 占槽,真实 id 首条 chat.send 会二次
+ 占槽(双计数)且可能落别的 Pod(亲和断裂)。本方法在 ``send_request``
+ 返回前 await——**时序保证**:客户端拿到真实 id 时改绑已完成,chat.send
+ 不可能抢先。
+
+ - 响应 ok:rebind(临时 key → 真实 id),亲和钉在 create 实际服务的 Pod;
+ - 响应失败:rebind(临时 key → 空) 驱逐,立即释放槽位(不等 session_ttl);
+ - 失败/超时一律降级(warning 节流 + 照常返回响应)=旧行为;旧 runtime
+ (无 /api/session/rebind 端点)同走降级,滚动期不阻塞 create。
+ """
+ if str(envelope.method or "") != "session.create":
+ return
+ payload = result.payload if isinstance(result.payload, dict) else {}
+ if result.ok:
+ real = str(payload.get("session_id") or payload.get("sessionId") or "").strip()
+ else:
+ real = ""
+ if real and real == session_id:
+ return
+ try:
+ action = await asyncio.wait_for(
+ self._route.rebind(
+ from_session_id=session_id,
+ to_session_id=real or None,
+ request_id=uuid.uuid4().hex,
+ ),
+ timeout=_rebind_timeout(),
+ )
+ logger.info(
+ "[RuntimeRouted] session.create rebind: from=%s to=%s action=%s",
+ session_id,
+ real or "(evict)",
+ action,
+ )
+ except Exception as exc: # noqa: BLE001 - 降级=现状(临时 key 等 TTL 过期)
+ now = time.monotonic()
+ if now - self._last_rebind_warn >= 60.0:
+ self._last_rebind_warn = now
+ logger.warning(
+ "[RuntimeRouted] session.create rebind failed (degraded, "
+ "temp key expires via session_ttl): %s",
+ exc,
+ )
+ else:
+ logger.debug(
+ "[RuntimeRouted] session.create rebind failed: %s", exc,
+ )
+
async def send_request_stream(
self, envelope: E2AEnvelope
) -> AsyncIterator[AgentResponseChunk]:
diff --git a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
index 1c49320132..4be2246d7b 100644
--- a/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
+++ b/packages/jiuwenclaw-ee/gateway/extensions/runtime_management_extension/session_route_client.py
@@ -85,6 +85,7 @@ class RuntimeSessionRouteClient:
root = self._link_mtls.resolve_endpoint(root, role="runtime")
self._route_url = f"{root}/api/session/route"
self._touch_url = f"{root}/api/session/touch"
+ self._rebind_url = f"{root}/api/session/rebind"
if http_client is not None:
self._http = http_client
self._owns_http = False
@@ -196,6 +197,51 @@ class RuntimeSessionRouteClient:
logger.debug("[SessionRoute] touch: session=%s touched=%s", session_id, touched)
return touched
+ async def rebind(
+ self,
+ *,
+ from_session_id: str,
+ to_session_id: str | None,
+ request_id: str,
+ ) -> str:
+ """session.create 临时 key 原子改绑为真实 id(2026-09-session-create-rebind)。
+
+ ``to_session_id`` 为空 = 驱逐(create 失败立即释放槽位)。返回 runtime 侧
+ action(noop/rubble/evicted/overtaken/rebound);失败上抛 ``RouteError``,
+ 由调用方(routed client 钩子)决定降级——本方法不吞错。
+ """
+ from_session_id = (from_session_id or "").strip()
+ request_id = (request_id or "").strip()
+ to_session_id = (to_session_id or "").strip()
+ if not (from_session_id and request_id):
+ raise FatalRouteError(
+ "rebind requires from_session_id/request_id",
+ code="VALIDATION",
+ )
+ body = await self._post(
+ self._rebind_url,
+ {
+ "type": "rebind",
+ "metadata": {"request_id": request_id, "session_id": from_session_id},
+ "rawdata": {"to": to_session_id},
+ },
+ )
+ rawdata = _rawdata(body)
+ action = str(rawdata.get("action") or "").strip()
+ if not action:
+ raise FatalRouteError(
+ "rebind response missing action",
+ code="VALIDATION",
+ )
+ logger.debug(
+ "[SessionRoute] rebind: from=%s to=%s action=%s request_id=%s",
+ from_session_id,
+ to_session_id or "(evict)",
+ action,
+ request_id,
+ )
+ return action
+
async def _post(self, url: str, envelope: dict) -> dict:
try:
response = await self._http.post(
diff --git a/tests/unit_tests/agentserver/test_statusline_prompt.py b/tests/unit_tests/agentserver/test_statusline_prompt.py
index 224234dd5c..15522dfc00 100644
--- a/tests/unit_tests/agentserver/test_statusline_prompt.py
+++ b/tests/unit_tests/agentserver/test_statusline_prompt.py
@@ -150,7 +150,10 @@ class TestHandleStatuslinePromptCommand:
# --- Exclusion cases (known subcommands should NOT be matched) ---
@pytest.mark.parametrize(
- "subcmd", list(_STATUSLINE_KNOWN_SUBCOMMANDS)
+ # sorted:参数源是 set 字面量,迭代序随每个 xdist worker 的
+ # PYTHONHASHSEED 变化 → 各 worker 收集顺序不同 → pytest-xdist
+ # "Different tests were collected between gw0 and gw1" 中止。
+ "subcmd", sorted(_STATUSLINE_KNOWN_SUBCOMMANDS)
)
@staticmethod
def test_known_subcommands_excluded(subcmd: str):
diff --git a/tests/unit_tests/gateway/test_runtime_routed_client.py b/tests/unit_tests/gateway/test_runtime_routed_client.py
index de1d3ff406..224f7f0927 100644
--- a/tests/unit_tests/gateway/test_runtime_routed_client.py
+++ b/tests/unit_tests/gateway/test_runtime_routed_client.py
@@ -514,6 +514,8 @@ class _FakeRoute:
def __init__(self) -> None:
self.routes: list[dict] = []
self.touches: list[dict] = []
+ self.rebinds: list[dict] = []
+ self.rebind_fail: BaseException | None = None
self.fail_times = 0
async def route(self, **kwargs):
@@ -531,6 +533,12 @@ class _FakeRoute:
self.touches.append(kwargs)
return True
+ async def rebind(self, **kwargs):
+ self.rebinds.append(kwargs)
+ if self.rebind_fail is not None:
+ raise self.rebind_fail
+ return "rebound"
+
async def aclose(self) -> None:
return None
@@ -540,6 +548,8 @@ class _FakeHttp:
self.calls: list[tuple] = []
self.fail_first = False
self.fail_exc: BaseException = httpx.ConnectError("http down")
+ self.response_ok = True
+ self.response_payload: dict = {"ok": True}
async def send_request(self, envelope, *, base_url=None):
self.calls.append(("unary", base_url, envelope.request_id))
@@ -549,8 +559,8 @@ class _FakeHttp:
return AgentResponse(
request_id=str(envelope.request_id),
channel_id="web",
- ok=True,
- payload={"ok": True},
+ ok=self.response_ok,
+ payload=dict(self.response_payload),
)
async def send_request_stream(self, envelope, *, base_url=None):
@@ -965,3 +975,105 @@ async def test_database_enabled_values(agent_resources, stream, enabled):
await chat()
assert not route.routes and not http.calls
await client.disconnect()
+
+
+# ------------------------------------------------ session.create rebind 钩子(2026-09-session-create-rebind)
+
+
+def _create_env(temp_session_id: str = "webhttp_temp1"):
+ from jiuwenswarm.common.request_identity import apply_routing_metadata
+
+ return e2a_from_agent_fields(
+ request_id="req-create-1",
+ channel_id="web",
+ session_id=temp_session_id,
+ req_method=ReqMethod.SESSION_CREATE,
+ params={"create_token": "tok-1", "group_id": "grp-1", "bot_id": "bot-1"},
+ is_stream=False,
+ user_id="user-1",
+ metadata=apply_routing_metadata(
+ {},
+ {"user_id": "user-1", "group_id": "grp-1", "bot_id": "bot-1"},
+ ),
+ )
+
+
+async def test_create_response_rebinds_temp_key_before_return() -> None:
+ """create 响应 ok:send_request 返回前已完成 rebind(临时 key→真实 id)——
+ await 返回时 rebinds 已有记录即时序证明(客户端不可能先于改绑拿到真实 id)。"""
+ route = _FakeRoute()
+ http = _FakeHttp()
+ http.response_payload = {
+ "session_id": "web_real_1", "sessionId": "web_real_1",
+ "projectId": "default", "workMode": "work",
+ }
+ client = RuntimeRoutedAgentClient(
+ route_client=route, http_client=http, touch_interval_seconds=999
+ )
+ await client.connect("")
+ result = await client.send_request(_create_env())
+ assert result.ok is True
+ # rebind 在响应返回给上层之前已发生(时序保证)
+ assert len(route.rebinds) == 1
+ assert route.rebinds[0]["from_session_id"] == "webhttp_temp1"
+ assert route.rebinds[0]["to_session_id"] == "web_real_1"
+ assert route.rebinds[0]["request_id"]
+ await client.disconnect()
+
+
+async def test_create_failure_evicts_temp_key() -> None:
+ """create 响应失败(如 BAD_REQUEST):rebind(to=None) 驱逐临时槽位,
+ 不等 session_ttl 过期。"""
+ route = _FakeRoute()
+ http = _FakeHttp()
+ http.response_ok = False
+ http.response_payload = {"error": "invalid work_mode", "code": "BAD_REQUEST"}
+ client = RuntimeRoutedAgentClient(
+ route_client=route, http_client=http, touch_interval_seconds=999
+ )
+ await client.connect("")
+ result = await client.send_request(_create_env())
+ assert result.ok is False
+ assert len(route.rebinds) == 1
+ assert route.rebinds[0]["from_session_id"] == "webhttp_temp1"
+ assert route.rebinds[0]["to_session_id"] is None
+ await client.disconnect()
+
+
+async def test_create_rebind_failure_degrades_to_legacy_behavior() -> None:
+ """rebind 异常(含旧 runtime 无端点):降级=现状——create 响应照常返回,
+ 不上抛;告警节流(首条 WARNING)。"""
+ route = _FakeRoute()
+ route.rebind_fail = FatalRouteError(
+ "not found", code="VALIDATION", status_code=404
+ )
+ http = _FakeHttp()
+ http.response_payload = {"session_id": "web_real_1"}
+ client = RuntimeRoutedAgentClient(
+ route_client=route, http_client=http, touch_interval_seconds=999
+ )
+ await client.connect("")
+ result = await client.send_request(_create_env())
+ assert result.ok is True # 降级:响应不受 rebind 失败影响
+ assert len(route.rebinds) == 1 # 确实尝试过
+ await client.disconnect()
+
+
+async def test_chat_send_does_not_rebind() -> None:
+ """非 create 方法不触发 rebind(chat.send 的路由 key 即真实 id)。"""
+ route = _FakeRoute()
+ http = _FakeHttp()
+ http.response_payload = {"session_id": "other"}
+ client = RuntimeRoutedAgentClient(
+ route_client=route, http_client=http, touch_interval_seconds=999
+ )
+ await client.connect("")
+ env = _chat_env()
+ env.is_stream = False
+ await client.send_request(env)
+ assert route.rebinds == []
+ await client.disconnect()