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(runtime): avoid the subagent history lock inversion

n99357702819c74e314d53
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index fe58393872..eda5ccadee 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -2327,6 +2327,7 @@ function AppContent() {
useTodoStore.getState().removeRuntime(deletedSessionId);
useHarnessStore.getState().removeRuntime(deletedSessionId);
useGoalStore.getState().removeRuntime(deletedSessionId);
+ useSubagentStore.getState().removeRuntime(deletedSessionId);
}
if (routeSessionId && deletedSessionIds.has(routeSessionId)) {
@@ -2356,6 +2357,7 @@ function AppContent() {
useTodoStore.getState().removeRuntime(deleteTarget.session_id);
useHarnessStore.getState().removeRuntime(deleteTarget.session_id);
useGoalStore.getState().removeRuntime(deleteTarget.session_id);
+ useSubagentStore.getState().removeRuntime(deleteTarget.session_id);
const deletingCurrent = sessionIdRef.current === deleteTarget.session_id;
setDeleteTarget(null);
await useWorkspaceStore.getState().refreshSessionWorkspace(deletedSession);
diff --git a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts
index 0ab7243dba..a1579cb233 100644
--- a/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts
+++ b/jiuwenswarm/channels/web/frontend/src/multi-session/state/newConversationLifecycle.ts
@@ -4,6 +4,7 @@ import {
useGoalStore,
useHarnessStore,
useSessionStore,
+ useSubagentStore,
useTodoStore,
} from '../../stores';
import type { AgentMode, Session } from '../../types';
@@ -44,6 +45,7 @@ export function resetNewConversationRuntime(settings: ConversationRuntimeSetting
useTodoStore.getState().removeRuntime(NEW_CONVERSATION_ID);
useHarnessStore.getState().removeRuntime(NEW_CONVERSATION_ID);
useGoalStore.getState().removeRuntime(NEW_CONVERSATION_ID);
+ useSubagentStore.getState().removeRuntime(NEW_CONVERSATION_ID);
applyRuntimeSettings(NEW_CONVERSATION_ID, settings);
if (preservedDraft) {
useChatStore.getState().setInputValue(NEW_CONVERSATION_ID, preservedDraft);
diff --git a/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts
index 77a8d3b647..96211d79e6 100644
--- a/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts
+++ b/jiuwenswarm/channels/web/frontend/src/stores/subagentStore.ts
@@ -423,7 +423,7 @@ function replaceActivity(runtime: SubagentRuntime, incoming: SubagentActivity):
const existingById = runtime.activitiesBySubagentId[incoming.subagent_id] ?? {};
if (existingById[incoming.activity_id]) return runtime;
- return {
+ return capActivities({
...runtime,
activitiesBySubagentId: {
...runtime.activitiesBySubagentId,
@@ -435,7 +435,31 @@ function replaceActivity(runtime: SubagentRuntime, incoming: SubagentActivity):
cacheOnlySubagentIds: Object.fromEntries(
Object.entries(runtime.cacheOnlySubagentIds).filter(([subagentId]) => subagentId !== incoming.subagent_id),
),
- };
+ });
+}
+
+function capActivities(runtime: SubagentRuntime): SubagentRuntime {
+ const entries: Array<{ subagentId: string; activity: SubagentActivity }> = [];
+ for (const [subagentId, items] of Object.entries(runtime.activitiesBySubagentId)) {
+ for (const activity of Object.values(items)) {
+ entries.push({ subagentId, activity });
+ }
+ }
+ if (entries.length <= MAX_PERSISTED_ACTIVITIES) return runtime;
+ const keep = new Set(
+ entries
+ .sort((left, right) => compareBySequence(left.activity, right.activity))
+ .slice(-MAX_PERSISTED_ACTIVITIES)
+ .map(item => `${item.subagentId}\0${item.activity.activity_id}`),
+ );
+ const activitiesBySubagentId: Record<string, Record<string, SubagentActivity>> = {};
+ for (const item of entries) {
+ if (!keep.has(`${item.subagentId}\0${item.activity.activity_id}`)) continue;
+ const bucket = activitiesBySubagentId[item.subagentId] ?? {};
+ bucket[item.activity.activity_id] = item.activity;
+ activitiesBySubagentId[item.subagentId] = bucket;
+ }
+ return { ...runtime, activitiesBySubagentId };
}
function replaceResult(runtime: SubagentRuntime, incoming: SubagentResult): SubagentRuntime {
diff --git a/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs b/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs
index ff6281ac77..c73b9a6da3 100644
--- a/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs
+++ b/jiuwenswarm/channels/web/frontend/tests/subagentStore.test.mjs
@@ -469,6 +469,22 @@ test('a successful parent cancel settles only still-running subagents locally',
assert.equal(cancelled.subagentsById['idle-agent'].turn_outcome, 'completed');
});
+test('live activities keep the same tail cap as persisted storage', () => {
+ let runtime = createEmptySubagentRuntime(sessionId);
+ runtime = applySubagentUpdated(runtime, event(1));
+ for (let sequence = 0; sequence < 501; sequence += 1) {
+ runtime = applySubagentActivity(runtime, {
+ event_type: 'chat.subagent_activity',
+ session_id: sessionId,
+ activity: activity(`activity-${sequence}`, sequence),
+ });
+ }
+ const kept = selectSubagentActivities(runtime, 'agent-a');
+ assert.equal(kept.length, 500);
+ assert.equal(kept[0].activity_id, 'activity-1');
+ assert.equal(kept[kept.length - 1].activity_id, 'activity-500');
+});
+
test('live activities deduplicate by derived id and remain sequence ordered', () => {
let runtime = createEmptySubagentRuntime(sessionId);
runtime = applySubagentUpdated(runtime, event(1));
diff --git a/jiuwenswarm/server/runtime/session/session_history.py b/jiuwenswarm/server/runtime/session/session_history.py
index 08469a159d..cd5fbacaca 100644
--- a/jiuwenswarm/server/runtime/session/session_history.py
+++ b/jiuwenswarm/server/runtime/session/session_history.py
@@ -28,6 +28,7 @@ _SUBAGENT_WRITE_QUEUE: queue.Queue[
] = queue.Queue(maxsize=20000)
_SUBAGENT_WORKER_STARTED = False
_SUBAGENT_WORKER_LOCK = threading.Lock()
+_SUBAGENT_SHUTDOWN_FLUSH_TIMEOUT_S = 5.0
_LEGACY_HISTORY_FILENAME = "history.json"
_JSONL_HISTORY_FILENAME = "history.jsonl"
_LEGACY_HISTORY_ENV = "JIUWENSWARM_USE_LEGACY_HISTORY_JSON"
@@ -623,7 +624,10 @@ def load_history_records(
*,
subagent_id: str | None = None,
) -> list[dict[str, Any]]:
- _flush_subagent_history_writes()
+ # Parent reads must not join the child writer. truncate holds _FILE_LOCK
+ # around the parent read, and that writer needs the same lock.
+ if subagent_id:
+ _flush_subagent_history_writes()
return _read_history(
get_read_history_path(
session_id,
@@ -949,10 +953,20 @@ def _ensure_subagent_history_worker_started() -> None:
_SUBAGENT_WORKER_STARTED = True
-def _flush_subagent_history_writes() -> None:
+def _flush_subagent_history_writes(*, timeout: float | None = None) -> None:
+ """Wait for queued child-history writes.
+
+ A full wait is for child reads, and it must run outside ``_FILE_LOCK``.
+ Shutdown passes ``timeout`` so a stuck writer cannot hold process exit.
+ """
if not _SUBAGENT_WORKER_STARTED:
return
- _SUBAGENT_WRITE_QUEUE.join()
+ if timeout is None:
+ _SUBAGENT_WRITE_QUEUE.join()
+ return
+ deadline = time.monotonic() + timeout
+ while _SUBAGENT_WRITE_QUEUE.unfinished_tasks > 0 and time.monotonic() < deadline:
+ time.sleep(0.01)
def _ensure_worker_started() -> None:
@@ -1209,7 +1223,7 @@ def shutdown() -> None:
logger.warning("history shutdown flush 失败: %s", exc)
try:
_force_flush_all_pending()
- _flush_subagent_history_writes()
+ _flush_subagent_history_writes(timeout=_SUBAGENT_SHUTDOWN_FLUSH_TIMEOUT_S)
except Exception as exc: # noqa: BLE001
logger.warning("history shutdown 强制暂留落盘失败: %s", exc)
deadline = time.monotonic() + 5.0
@@ -1463,7 +1477,8 @@ def append_compact_history_records(
def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, Any]:
"""截断会话历史到指定位置(线程安全)。
- 先等待异步写入队列刷盘,再持锁截断当前激活的历史文件。
+ 先等父会话写队列落盘,再持锁读取并重写父历史。
+ 持锁期间不 join 子会话写队列,避免和子 writer 抢 ``_FILE_LOCK``。
返回截断结果 dict,包含 remaining / removed 计数。
"""
sid = (session_id or "default").strip() or "default"
@@ -1473,7 +1488,7 @@ def truncate_history_records(*, session_id: str, cut_index: int) -> dict[str, An
with _FILE_LOCK:
if not fpath.exists():
return {"remaining_records": 0, "removed_records": 0}
- history = load_history_records(sid)
+ history = _read_history(fpath)
if not isinstance(history, list):
return {"remaining_records": 0, "removed_records": 0}
total = len(history)
diff --git a/tests/unit_tests/agentserver/test_subagent_history_routing.py b/tests/unit_tests/agentserver/test_subagent_history_routing.py
index 8123e782ba..1266989827 100644
--- a/tests/unit_tests/agentserver/test_subagent_history_routing.py
+++ b/tests/unit_tests/agentserver/test_subagent_history_routing.py
@@ -4,6 +4,9 @@
from __future__ import annotations
+import threading
+import time
+
from jiuwenswarm.common.schema.message import EventType
from jiuwenswarm.gateway.channel_manager.web.web_ws_transport import (
_WEB_FULL_PAYLOAD_EVENT_TYPES,
@@ -110,6 +113,66 @@ def test_empty_subagent_activity_is_persistable(tmp_path, monkeypatch) -> None:
assert rows[0]["event_type"] == "chat.subagent_activity"
+def test_parent_history_does_not_wait_on_blocked_child_writer(tmp_path, monkeypatch) -> None:
+ """Parent load and rewind must not join the child writer."""
+ monkeypatch.setattr(session_history, "get_agent_sessions_dir", lambda: tmp_path)
+ session_history.append_history_record(
+ session_id="parent1",
+ request_id="r-parent",
+ channel_id="web",
+ role="user",
+ content="hello",
+ timestamp=1.0,
+ )
+ session_history.flush_session_history("parent1")
+
+ release = threading.Event()
+ started = threading.Event()
+ original = session_history._write_subagent_items_sync
+
+ def _block_child_write(session_id, subagent_id, items, sessions_root):
+ started.set()
+ assert release.wait(2)
+ original(session_id, subagent_id, items, sessions_root)
+
+ monkeypatch.setattr(session_history, "_write_subagent_items_sync", _block_child_write)
+ session_history._batch_write_subagent_items(
+ "parent1",
+ "sa-1",
+ [{"content": "queued-child", "role": "assistant"}],
+ None,
+ )
+ assert started.wait(2)
+
+ truncate_thread: threading.Thread | None = None
+ try:
+ started_at = time.monotonic()
+ parent_rows = session_history.load_history_records("parent1")
+ assert time.monotonic() - started_at < 0.5
+ assert [row.get("content") for row in parent_rows] == ["hello"]
+
+ result: dict = {}
+
+ def _truncate() -> None:
+ result.update(session_history.truncate_history_records(
+ session_id="parent1",
+ cut_index=1,
+ ))
+
+ truncate_thread = threading.Thread(target=_truncate)
+ truncate_thread.start()
+ truncate_thread.join(1.0)
+ assert not truncate_thread.is_alive()
+ assert result["remaining_records"] == 1
+ finally:
+ release.set()
+ if truncate_thread is not None:
+ truncate_thread.join(2)
+
+ child_rows = session_history.load_history_records("parent1", subagent_id="sa-1")
+ assert any(row.get("content") == "queued-child" for row in child_rows)
+
+
def test_web_allowlist_includes_subagent_activity() -> None:
assert EventType.CHAT_SUBAGENT_ACTIVITY.value == "chat.subagent_activity"
assert "chat.subagent_activity" in _WEB_FULL_PAYLOAD_EVENT_TYPES