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(agentserver): 本地 sysop retain 与缓存 invalidate 竞态

zhangxiangyu52bdbb3aa0043d
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index ff52640437..1621b2dd36 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -2769,6 +2769,55 @@ def get_sandbox_runtime() -> dict[str, Any]:
return _ensure_sandbox_runtime_shape(raw)
+
+# =====================================================================
+# Agent 内部读文件后端:local(本机 FS) / sandbox(跟 agent sysop)
+#
+# ``AGENT_FILE_READ_BACKEND``:
+# - ``local``(默认): 读人设/上下文等 rail 强制挂本地 sysop;动手工具仍跟
+# deep_config / agent 原 sysop(开沙箱时为沙箱)。并在 ensure_initialized
+# 前于宿主机初始化工作区,避免沙箱逐个 upload ``.workspace``。
+# - ``sandbox``: 关闭上述分流与本机 workspace init,全部跟 agent sysop /
+# 上游沙箱 DirectoryBuilder。
+# 非法值回落 ``local`` 并打 warning。
+# =====================================================================
+
+_AGENT_FILE_READ_BACKEND_ENV: str = "AGENT_FILE_READ_BACKEND"
+_AGENT_FILE_READ_BACKEND_LOCAL: str = "local"
+_AGENT_FILE_READ_BACKEND_SANDBOX: str = "sandbox"
+_VALID_AGENT_FILE_READ_BACKENDS: frozenset[str] = frozenset(
+ {_AGENT_FILE_READ_BACKEND_LOCAL, _AGENT_FILE_READ_BACKEND_SANDBOX}
+)
+
+
+def get_agent_file_read_backend() -> str:
+ """返回 agent 内部读文件走本地还是沙箱。
+
+ Returns:
+ ``"local"`` 或 ``"sandbox"``;缺省 / 非法均为 ``"local"``。
+ """
+ raw = get_local_config(_AGENT_FILE_READ_BACKEND_ENV)
+ if raw is None:
+ return _AGENT_FILE_READ_BACKEND_LOCAL
+ text = str(raw).strip().lower()
+ if not text:
+ return _AGENT_FILE_READ_BACKEND_LOCAL
+ if text not in _VALID_AGENT_FILE_READ_BACKENDS:
+ logger.warning(
+ "[config] invalid %s=%r, fallback to %s",
+ _AGENT_FILE_READ_BACKEND_ENV,
+ raw,
+ _AGENT_FILE_READ_BACKEND_LOCAL,
+ )
+ return _AGENT_FILE_READ_BACKEND_LOCAL
+ return text
+
+
+def agent_file_read_backend_is_local() -> bool:
+ """``AGENT_FILE_READ_BACKEND`` 是否为本地直连(默认 True)。"""
+ return get_agent_file_read_backend() == _AGENT_FILE_READ_BACKEND_LOCAL
+
+
# ``preserve_file_sharing_mode`` 当前合法取值集合 = ``{"mount"}``; 空值表示
# "未配置, 按默认走"。
_VALID_PRESERVE_FILE_SHARING_MODES = ("mount",)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 66bfbe3aeb..56119482a5 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -462,6 +462,8 @@ from jiuwenswarm.agents.harness.common.tools.xiaoyi_phone_tools import (
)
from jiuwenswarm.common.config import (
_get_evolution_config,
+ agent_file_read_backend_is_local,
+ get_agent_file_read_backend,
get_config,
get_default_models,
get_evolution_enabled,
@@ -2357,6 +2359,8 @@ class JiuWenSwarmDeepAdapter:
self._evolution_watcher_tasks: set[asyncio.Task] = set()
self._sys_operation = None
self._sys_operation_card: SysOperationCard | None = None
+ # 专供 rail 使用的本地 sysop(忽略沙箱配置;与 self._sys_operation 可不同)
+ self._local_sys_operation: SysOperation | None = None
# Ids of the sys operations this adapter currently holds a reference on,
# in acquisition order. ``cleanup`` releases them so a disposed adapter
# stops pinning its SysOperation (and the ~16 tools derived from it) in
@@ -5433,6 +5437,11 @@ class JiuWenSwarmDeepAdapter:
if routing is None:
return
try:
+ from jiuwenswarm.server.runtime.enterprise_config import (
+ invalidate_enterprise_config_caches,
+ )
+
+ invalidate_enterprise_config_caches()
request = AgentRequest(
request_id="enterprise-config-refresh",
channel_id="default",
@@ -6885,10 +6894,30 @@ class JiuWenSwarmDeepAdapter:
The resolved SysOperation, or None when registration failed.
"""
previously_retained = list(self._retained_sys_operation_ids)
+ # 读盘用的本地 sysop 与 agent 沙箱 sysop 可能是两份:重建 agent 时不能
+ # 把仍在用的 local 一并 release,否则 rail 会拿着已注销引用。
+ local_keep_id: str | None = None
+ if self._local_sys_operation is not None:
+ local_keep_id = str(self._local_sys_operation.id)
+
sys_operation = self._resolve_sys_operation()
if sys_operation is not None:
self._retain_sys_operation(str(sys_operation.id))
- self._release_sys_operations(previously_retained)
+
+ to_release = [sid for sid in previously_retained if sid != local_keep_id]
+ # agent 与 local 共用同一张卡时:新 retain 已加上,只丢掉上一轮那一票。
+ same_card_as_local = (
+ sys_operation is not None
+ and local_keep_id is not None
+ and str(sys_operation.id) == local_keep_id
+ )
+ prior_local_retain = (
+ local_keep_id is not None
+ and previously_retained.count(local_keep_id) >= 1
+ )
+ if same_card_as_local and prior_local_retain:
+ to_release.append(local_keep_id)
+ self._release_sys_operations(to_release)
return sys_operation
def _retain_sys_operation(self, sys_operation_id: str) -> None:
@@ -6968,6 +6997,14 @@ class JiuWenSwarmDeepAdapter:
exc,
)
+ # 本地读盘 sysop 若已不在本 adapter retain 列表里,清掉缓存,避免下次
+ # 误以为还能复用已注销实例。
+ local = self._local_sys_operation
+ if local is not None:
+ local_id = str(getattr(local, "id", "") or "")
+ if not local_id or local_id not in self._retained_sys_operation_ids:
+ self._local_sys_operation = None
+
def _resolve_sys_operation(self) -> SysOperation | None:
"""Create a sys operation.
@@ -7041,6 +7078,357 @@ class JiuWenSwarmDeepAdapter:
logger.warning("[JiuWenSwarmDeepAdapter] add sys_operation failed: %s", exc)
return None
+ def _create_local_sys_operation(self) -> SysOperation | None:
+ """只创建/复用本地 SysOperation,给读盘类 rail 用;与沙箱实例分离。"""
+ _t0 = time.monotonic()
+ cached = self._local_sys_operation
+ if cached is not None:
+ cached_id = str(getattr(cached, "id", "") or "")
+ still_held = bool(
+ cached_id and cached_id in self._retained_sys_operation_ids
+ )
+ still_registered = bool(
+ cached_id
+ and Runner.resource_mgr.get_sys_operation(cached_id) is not None
+ )
+ if still_held and still_registered:
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s reuse=1 "
+ "elapsed_ms=%.1f",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return cached
+ # 上一轮 recreate 已 release/unregister:丢掉脏缓存,下面重建。
+ self._local_sys_operation = None
+ existing = self._sys_operation
+ if existing is not None and getattr(existing, "mode", None) == OperationMode.LOCAL:
+ existing_id = str(getattr(existing, "id", "") or "")
+ if existing_id and existing_id not in self._retained_sys_operation_ids:
+ self._retain_sys_operation(existing_id)
+ self._local_sys_operation = existing
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s reuse_agent=1 "
+ "elapsed_ms=%.1f",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return existing
+ try:
+ work_dir = self._workspace_dir or str(get_agent_root_dir())
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] create local-only sys_operation (work_dir=%s)",
+ work_dir,
+ )
+ sysop_card = create_local_sysop_card(work_dir=work_dir)
+ if sysop_card is None:
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s ok=0 "
+ "elapsed_ms=%.1f reason=card_none",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return None
+ isolation_key = self._sys_operation_isolation_key(sysop_card)
+ if isolation_key:
+ registered = self._get_registered_sys_operation_by_isolation_key(
+ isolation_key
+ )
+ if registered is not None:
+ self._retain_sys_operation(str(registered.id))
+ self._local_sys_operation = registered
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s ok=1 "
+ "reuse_registered=1 elapsed_ms=%.1f",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return registered
+ result = Runner.resource_mgr.add_sys_operation(sysop_card)
+ if result.is_err():
+ registered = (
+ self._get_registered_sys_operation_by_isolation_key(isolation_key)
+ if isolation_key
+ else None
+ )
+ if registered is not None:
+ self._retain_sys_operation(str(registered.id))
+ self._local_sys_operation = registered
+ return registered
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] add local sys_operation failed: %s",
+ result.msg(),
+ )
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s ok=0 "
+ "elapsed_ms=%.1f reason=add_err",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return None
+ sysop_obj = Runner.resource_mgr.get_sys_operation(sysop_card.id)
+ if sysop_obj is not None:
+ self._retain_sys_operation(str(sysop_obj.id))
+ self._local_sys_operation = sysop_obj
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s ok=%s "
+ "elapsed_ms=%.1f",
+ self._agent_id,
+ 1 if sysop_obj is not None else 0,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return sysop_obj
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] create local sys_operation failed: %s", exc
+ )
+ logger.info(
+ "[SandboxPerf] create_local_sys_operation: agent_id=%s ok=0 "
+ "elapsed_ms=%.1f reason=exc",
+ self._agent_id,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return None
+
+ def _iter_adapter_rails(self) -> list[Any]:
+ """收集 adapter 上持有的 rail 实例。"""
+ rail_attrs = (
+ "_filesystem_rail",
+ "_skill_rail",
+ "_stream_event_rail",
+ "_task_execution_rail",
+ "_task_planning_rail",
+ "_context_assemble_rail",
+ "_context_processor_rail",
+ "_runtime_prompt_rail",
+ "_response_prompt_rail",
+ "_skill_protocol_prompt_rail",
+ "_security_rail",
+ "_memory_rail",
+ "_external_memory_rail",
+ "_heartbeat_rail",
+ "_skill_evolution_rail",
+ "_subagent_rail",
+ "_disabled_tools_rail",
+ "_permission_rail",
+ "_avatar_rail",
+ "_progressive_tool_rail",
+ "_skill_authorization_rail",
+ "_skill_active_state_rail",
+ "_skill_credential_injection_rail",
+ "_llm_retry_rail",
+ "_skill_create_rail",
+ "_ask_user_rail",
+ )
+ rails: list[Any] = []
+ for attr in rail_attrs:
+ rail = getattr(self, attr, None)
+ if rail is not None:
+ rails.append(rail)
+ return rails
+
+ @staticmethod
+ def _is_sandbox_bound_rail(rail: Any) -> bool:
+ """动手类 rail:必须跟 deep_config / 沙箱 sysop,不能强制本地。"""
+ if isinstance(rail, (SysOperationRail, SkillUseRail)):
+ return True
+ try:
+ if isinstance(rail, ConcurrentSafeSysOperationRail):
+ return True
+ except Exception:
+ pass
+ return type(rail).__name__ in {
+ "SysOperationRail",
+ "FileSystemRail",
+ "ConcurrentSafeFileSystemRail",
+ "ConcurrentSafeSysOperationRail",
+ "SkillUseRail",
+ }
+
+ @staticmethod
+ def _set_rail_sys_operation(rail: Any, sysop: SysOperation) -> bool:
+ """给单个 rail 写入 sys_operation;成功返回 True。"""
+ setter = getattr(rail, "set_sys_operation", None)
+ if callable(setter):
+ setter(sysop)
+ return True
+ if hasattr(rail, "sys_operation"):
+ rail.sys_operation = sysop
+ return True
+ return False
+
+ def _apply_local_sysop_to_all_rails(self) -> None:
+ """按 ``AGENT_FILE_READ_BACKEND`` 把读文件类 rail 切到本地 sysop。"""
+ _t0 = time.monotonic()
+ backend = get_agent_file_read_backend()
+ if not agent_file_read_backend_is_local():
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] AGENT_FILE_READ_BACKEND=%s, skip local "
+ "sysop rail override (agent_id=%s)",
+ backend,
+ self._agent_id,
+ )
+ logger.info(
+ "[SandboxPerf] apply_rail_sysop: agent_id=%s backend=%s skipped=1 "
+ "elapsed_ms=%.1f",
+ self._agent_id,
+ backend,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return
+
+ local_sysop = self._create_local_sys_operation()
+ if local_sysop is None:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] skip applying local sysop to rails: "
+ "local sysop unavailable"
+ )
+ logger.info(
+ "[SandboxPerf] apply_rail_sysop: agent_id=%s backend=%s skipped=1 "
+ "elapsed_ms=%.1f",
+ self._agent_id,
+ backend,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return
+
+ agent_sysop = self._sys_operation
+ if self._instance is not None:
+ deep_cfg = getattr(self._instance, "deep_config", None)
+ if deep_cfg is not None and agent_sysop is not None:
+ deep_cfg.sys_operation = agent_sysop
+
+ rails: list[Any] = []
+ if self._instance is not None:
+ configured = getattr(self._instance, "configured_rails", None)
+ if callable(configured):
+ try:
+ rails.extend(configured() or [])
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] configured_rails() failed: %s", exc
+ )
+ rails.extend(self._iter_adapter_rails())
+
+ seen: set[int] = set()
+ local_applied = 0
+ sandbox_kept = 0
+ for rail in rails:
+ rid = id(rail)
+ if rid in seen:
+ continue
+ seen.add(rid)
+ if self._is_sandbox_bound_rail(rail):
+ if agent_sysop is not None and self._set_rail_sys_operation(
+ rail, agent_sysop
+ ):
+ sandbox_kept += 1
+ continue
+ if self._set_rail_sys_operation(rail, local_sysop):
+ local_applied += 1
+
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] rail sysop: backend=%s local=%d sandbox_bound=%d "
+ "(deep_config keeps agent sysop)",
+ backend,
+ local_applied,
+ sandbox_kept,
+ )
+ logger.info(
+ "[SandboxPerf] apply_rail_sysop: agent_id=%s backend=%s local=%d "
+ "sandbox_bound=%d elapsed_ms=%.1f",
+ self._agent_id,
+ backend,
+ local_applied,
+ sandbox_kept,
+ (time.monotonic() - _t0) * 1000,
+ )
+
+ async def _init_workspace_on_host(self) -> None:
+ """在宿主机初始化工作区,避免沙箱 DirectoryBuilder 串行建目录。
+
+ 仅当 ``AGENT_FILE_READ_BACKEND=local``(默认)时执行。
+ 整段落盘丢 ``asyncio.to_thread``,避免堵事件循环。
+ """
+ _t0 = time.monotonic()
+ backend = get_agent_file_read_backend()
+ if not agent_file_read_backend_is_local():
+ logger.info(
+ "[SandboxPerf] init_workspace_on_host: agent_id=%s backend=%s "
+ "skipped=1 reason=backend_sandbox elapsed_ms=%.1f",
+ self._agent_id,
+ backend,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return
+
+ instance = self._instance
+ if instance is None:
+ return
+ deep_cfg = getattr(instance, "deep_config", None)
+ if deep_cfg is None:
+ return
+ if not getattr(deep_cfg, "auto_create_workspace", True):
+ return
+ workspace = getattr(deep_cfg, "workspace", None)
+ if workspace is None:
+ return
+
+ root_path = getattr(workspace, "root_path", None) or self._workspace_dir
+ if not root_path:
+ return
+
+ directories = list(getattr(workspace, "directories", None) or [])
+ language = str(
+ getattr(workspace, "language", None)
+ or self._resolve_runtime_language()
+ or "cn"
+ )
+ try:
+ from jiuwenswarm.server.runtime.agent_adapter.workspace_host_init import (
+ host_init_workspace_sync,
+ )
+
+ result = await asyncio.to_thread(
+ host_init_workspace_sync,
+ str(root_path),
+ directories,
+ language=language,
+ )
+ status = str((result or {}).get("status") or "")
+ if status == "skipped_marker":
+ logger.info(
+ "[SandboxPerf] init_workspace_on_host: agent_id=%s backend=%s "
+ "skipped=1 reason=marker_exists elapsed_ms=%.1f",
+ self._agent_id,
+ backend,
+ (time.monotonic() - _t0) * 1000,
+ )
+ return
+ logger.info(
+ "[SandboxPerf] init_workspace_on_host: agent_id=%s backend=%s ok=1 "
+ "mode=%s dirs=%d elapsed_ms=%.1f path=%s",
+ self._agent_id,
+ backend,
+ status,
+ int((result or {}).get("dirs") or len(directories)),
+ (time.monotonic() - _t0) * 1000,
+ root_path,
+ )
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] init_workspace_on_host failed: %s",
+ exc,
+ )
+ logger.info(
+ "[SandboxPerf] init_workspace_on_host: agent_id=%s backend=%s ok=0 "
+ "elapsed_ms=%.1f reason=exc",
+ self._agent_id,
+ backend,
+ (time.monotonic() - _t0) * 1000,
+ )
+
+
async def apply_sandbox_runtime_patch(
self, runtime: dict[str, Any], *, files_changed: bool
) -> None:
@@ -9778,6 +10166,11 @@ class JiuWenSwarmDeepAdapter:
self._session_instance_mode = mode
self._session_instance_sub_mode = sub_mode
+ bootstrap_request = None
+ if isinstance(config, dict):
+ bootstrap_request = config.get("request")
+ _rid = getattr(bootstrap_request, "request_id", None) or _LLM_TRACE_REQUEST_ID.get() or "?"
+
await self.set_checkpoint()
await asyncio.sleep(0)
@@ -9945,8 +10338,23 @@ class JiuWenSwarmDeepAdapter:
_apply_llm_io_trace_patch()
+ # AGENT_FILE_READ_BACKEND=local:读盘 rail 切本地 sysop;宿主机先建工作区
+ _t_sysop_apply0 = time.monotonic()
+ self._apply_local_sysop_to_all_rails()
+ await self._init_workspace_on_host()
+ self._apply_local_sysop_to_all_rails()
+
await asyncio.sleep(0)
await self._instance.ensure_initialized()
+ self._apply_local_sysop_to_all_rails()
+ logger.info(
+ "[SandboxPerf] rail_sysop_bind+ensure_init: request_id=%s agent=%s "
+ "backend=%s elapsed_ms=%.1f",
+ _rid,
+ self._agent_name,
+ get_agent_file_read_backend(),
+ (time.monotonic() - _t_sysop_apply0) * 1000,
+ )
initial_runtime_workspace = self._project_dir or str(
get_default_project_session_workspace_dir()
)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
index 6d82bf3571..35dae6b2a3 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/sysop_builder.py
@@ -6,6 +6,7 @@ import hashlib
import json
import logging
import os
+import time
from pathlib import Path
from typing import Any, Literal
@@ -636,10 +637,12 @@ def create_sandbox_sysop_card(
shared_dir: str | Path | None = None,
) -> SysOperationCard | None:
"""Create sandbox SysOperationCard (jiuwenbox or yuanrong)."""
+ _t0 = time.monotonic()
# 触发 sandbox provider 注册(@SandboxRegistry.provider 装饰器副作用)
import openjiuwen.extensions.sys_operation.sandbox.providers # noqa: F401
normalized_type = str(sandbox_type or "").strip().lower()
+ isolation_custom_id = ""
try:
if normalized_type == "yuanrong":
extra_params = _build_yuanrong_extra_params()
@@ -676,8 +679,15 @@ def create_sandbox_sysop_card(
len(extra_params.get("mounts") or []),
extra_params.get("mounts") or [],
)
+ logger.info(
+ "[SandboxPerf] sysop_builder.create_sandbox_card: agent_id=%s "
+ "sandbox_type=yuanrong total_ms=%.1f",
+ isolation_custom_id,
+ (time.monotonic() - _t0) * 1000,
+ )
return sysop_card
+ _t_policy0 = time.monotonic()
policy, upload_list = build_filesystem_policy(
files_runtime,
project_dir=project_dir,
@@ -685,6 +695,7 @@ def create_sandbox_sysop_card(
startup_mode=startup_mode,
shared_dir=shared_dir,
)
+ policy_ms = (time.monotonic() - _t_policy0) * 1000
if is_enterprise():
process_policy = build_process_policy()
if process_policy:
@@ -743,18 +754,50 @@ def create_sandbox_sysop_card(
upload_list or [],
extra_params["policy_mode"],
)
+ logger.info(
+ "[SandboxPerf] sysop_builder.create_sandbox_card: agent_id=%s "
+ "policy_ms=%.1f total_ms=%.1f",
+ isolation_custom_id,
+ policy_ms,
+ (time.monotonic() - _t0) * 1000,
+ )
return sysop_card
except Exception as exc: # noqa: BLE001
logger.warning("[sysop_builder] create sandbox sysop card failed: %s", exc)
+ logger.info(
+ "[SandboxPerf] sysop_builder.create_sandbox_card: agent_id=%s ok=0 "
+ "total_ms=%.1f",
+ isolation_custom_id or "-",
+ (time.monotonic() - _t0) * 1000,
+ )
return None
-def create_local_sysop_card() -> SysOperationCard:
- """构造本地模式 SysOperationCard."""
- logger.info("[sysop_builder] local SysOperationCard created (mode=LOCAL)")
+def create_local_sysop_card(work_dir: str | None = None) -> SysOperationCard:
+ """构造本地模式 SysOperationCard.
+
+ Args:
+ work_dir: 本地 work_dir;为空时不在 ``LocalWorkConfig`` 中显式设置。
+ """
+ _t0 = time.monotonic()
+ work_config = (
+ LocalWorkConfig(work_dir=work_dir, shell_allowlist=None)
+ if work_dir
+ else LocalWorkConfig(shell_allowlist=None)
+ )
+ logger.info(
+ "[sysop_builder] local SysOperationCard created (mode=LOCAL, work_dir=%s)",
+ work_dir or "<default>",
+ )
+ logger.info(
+ "[SandboxPerf] sysop_builder.create_local_sysop_card: work_dir=%s "
+ "elapsed_ms=%.1f",
+ work_dir or "<default>",
+ (time.monotonic() - _t0) * 1000,
+ )
return SysOperationCard(
mode=OperationMode.LOCAL,
- work_config=LocalWorkConfig(shell_allowlist=None),
+ work_config=work_config,
)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/workspace_host_init.py b/jiuwenswarm/server/runtime/agent_adapter/workspace_host_init.py
new file mode 100644
index 0000000000..c53d0fe8ff
--- /dev/null
+++ b/jiuwenswarm/server/runtime/agent_adapter/workspace_host_init.py
@@ -0,0 +1,164 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""宿主机 workspace 初始化(纯盘 IO,供 ``asyncio.to_thread`` 调用).
+
+替代上游 DirectoryBuilder 经沙箱串行 mkdir/upload ``.workspace`` 的路径。
+本模块函数本身是同步的;调用方应丢到线程池,不要直接堵事件循环。
+
+策略:
+1. 根目录已有 ``.workspace`` marker → 直接跳过;
+2. 目标目录为空 → 进程级预置模板 + ``copytree``;
+3. 目标已有部分文件 → 就地 materialize(已存在文件不覆盖)。
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import shutil
+import tempfile
+import threading
+from pathlib import Path
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_TPL_LOCK = threading.Lock()
+_TPL_CACHE: dict[str, Path] = {}
+
+
+def _dirs_fingerprint(directories: list[dict[str, Any]]) -> str:
+ """Stable-ish fingerprint of workspace schema (structure + content)."""
+ h = hashlib.sha1()
+
+ def walk(nodes: list[dict[str, Any]]) -> None:
+ for node in nodes or []:
+ h.update(str(node.get("name", "")).encode("utf-8", errors="replace"))
+ h.update(b"\0")
+ h.update(str(node.get("path", "")).encode("utf-8", errors="replace"))
+ h.update(b"\0")
+ h.update(b"1" if node.get("is_file") else b"0")
+ content = node.get("default_content") or ""
+ if not isinstance(content, str):
+ content = str(content)
+ # 必须哈希正文,否则同长度改文案会命中脏模板。
+ h.update(content.encode("utf-8", errors="replace"))
+ h.update(b"\0")
+ walk(list(node.get("children") or []))
+
+ walk(list(directories or []))
+ return h.hexdigest()[:20]
+
+
+def _materialize_nodes(
+ root: Path,
+ nodes: list[dict[str, Any]],
+ *,
+ parent: Path | None = None,
+) -> None:
+ """按 DirectoryBuilder 语义落盘:目录写 ``.workspace``,文件不存在才写。"""
+ for node in nodes or []:
+ relative_path = node.get("path", "") or ""
+ if parent is not None:
+ full_path = parent / relative_path if relative_path else parent
+ else:
+ full_path = root / relative_path if relative_path else root
+
+ is_file = bool(node.get("is_file", False))
+ if is_file:
+ if not full_path.exists():
+ full_path.parent.mkdir(parents=True, exist_ok=True)
+ content = node.get("default_content") or ""
+ if not isinstance(content, str):
+ content = str(content)
+ full_path.write_text(content, encoding="utf-8")
+ else:
+ full_path.mkdir(parents=True, exist_ok=True)
+ marker = full_path / ".workspace"
+ if not marker.exists():
+ marker.write_text("", encoding="utf-8")
+ children = list(node.get("children") or [])
+ if children:
+ _materialize_nodes(root, children, parent=full_path)
+
+
+def _ensure_workspace_template(
+ language: str,
+ directories: list[dict[str, Any]],
+) -> Path:
+ """进程内预置一份模板目录(同 schema 只建一次)。"""
+ fp = _dirs_fingerprint(directories)
+ lang = (language or "cn").strip() or "cn"
+ key = f"{lang}:{fp}"
+ with _TPL_LOCK:
+ cached = _TPL_CACHE.get(key)
+ if cached is not None and (cached / ".workspace").is_file():
+ return cached
+ base = Path(tempfile.gettempdir()) / "jiuwenswarm_ws_tpl" / key
+ root_marker = base / ".workspace"
+ if root_marker.is_file():
+ _TPL_CACHE[key] = base
+ return base
+ if base.exists():
+ shutil.rmtree(base, ignore_errors=True)
+ base.mkdir(parents=True, exist_ok=True)
+ _materialize_nodes(base, directories)
+ root_marker.write_text("", encoding="utf-8")
+ _TPL_CACHE[key] = base
+ logger.info(
+ "[SandboxPerf] workspace_template ready: key=%s path=%s",
+ key,
+ base,
+ )
+ return base
+
+
+def _copy_template_into(tpl: Path, dest: Path) -> None:
+ """把模板内容拷进空的 dest(dest 已存在且应为空)。"""
+ for item in tpl.iterdir():
+ target = dest / item.name
+ if item.is_dir():
+ shutil.copytree(item, target, dirs_exist_ok=True)
+ else:
+ shutil.copy2(item, target)
+
+
+def host_init_workspace_sync(
+ root: str,
+ directories: list[dict[str, Any]] | None,
+ *,
+ language: str = "cn",
+) -> dict[str, Any]:
+ """同步初始化宿主机 workspace。
+
+ Returns:
+ 状态字典:``status`` 为 skipped_marker / copytree / materialize。
+ """
+ root_path = Path(root)
+ marker = root_path / ".workspace"
+ if marker.exists():
+ return {"status": "skipped_marker", "path": str(root_path)}
+
+ dirs = list(directories or [])
+ root_path.mkdir(parents=True, exist_ok=True)
+ try:
+ is_empty = not any(root_path.iterdir())
+ except OSError:
+ is_empty = False
+
+ if is_empty and dirs:
+ tpl = _ensure_workspace_template(language, dirs)
+ _copy_template_into(tpl, root_path)
+ status = "copytree"
+ else:
+ if dirs:
+ _materialize_nodes(root_path, dirs)
+ status = "materialize"
+
+ if not marker.exists():
+ marker.write_text("", encoding="utf-8")
+ return {
+ "status": status,
+ "path": str(root_path),
+ "dirs": len(dirs),
+ }
diff --git a/jiuwenswarm/server/runtime/enterprise_config/__init__.py b/jiuwenswarm/server/runtime/enterprise_config/__init__.py
index 0de8cb7407..0b73ca93bf 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/__init__.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/__init__.py
@@ -2,10 +2,14 @@
from jiuwenswarm.server.runtime.enterprise_config.loader import (
DEFAULT_AGENT_LOAD_SLOTS,
+ invalidate_enterprise_config_caches,
+ invalidate_template_entity_cache,
load_effective_enterprise_config,
)
__all__ = [
"DEFAULT_AGENT_LOAD_SLOTS",
+ "invalidate_enterprise_config_caches",
+ "invalidate_template_entity_cache",
"load_effective_enterprise_config",
]
diff --git a/jiuwenswarm/server/runtime/enterprise_config/loader.py b/jiuwenswarm/server/runtime/enterprise_config/loader.py
index 3235c82181..1e5df319fc 100644
--- a/jiuwenswarm/server/runtime/enterprise_config/loader.py
+++ b/jiuwenswarm/server/runtime/enterprise_config/loader.py
@@ -2,7 +2,10 @@
from __future__ import annotations
+import asyncio
+import time
from collections.abc import Collection
+from dataclasses import dataclass
from typing import Any
from jiuwenswarm.edition import is_enterprise
@@ -13,6 +16,7 @@ from . import db_queries
from .schemas import (
DEFAULT_AGENT_LOAD_SLOTS,
MODEL_SLOT_KEYS,
+ SLOT_ENTITY_TABLE,
EffectiveEnterpriseConfig,
RoutingContext,
TemplateRefSlot,
@@ -79,11 +83,230 @@ def _any_requested_slot_loaded(
return False
+@dataclass
+class _CacheEntry:
+ value: Any
+ fetched_at: float
+
+
+class _TtlSingleFlightCache:
+ """简单进程级 TTL + 单飞缓存(按 key)。"""
+
+ def __init__(self, ttl_seconds: float = 3600.0) -> None:
+ self._ttl = ttl_seconds
+ self._entries: dict[str, _CacheEntry] = {}
+ self._locks: dict[str, asyncio.Lock] = {}
+ self._meta_lock: asyncio.Lock | None = None
+ self._ops_since_purge = 0
+ self._generation = 0
+
+ def invalidate(self) -> None:
+ self._generation += 1
+ self._entries.clear()
+ self._locks.clear()
+
+ def invalidate_key(self, key: str) -> None:
+ self._entries.pop(key, None)
+
+ def _purge_expired(self) -> None:
+ """丢掉过期条目,避免 TTL 失效后条目长期占内存。"""
+ now = time.monotonic()
+ expired = [
+ key
+ for key, entry in self._entries.items()
+ if now - entry.fetched_at > self._ttl
+ ]
+ for key in expired:
+ self._entries.pop(key, None)
+
+ def _maybe_purge(self) -> None:
+ self._ops_since_purge += 1
+ if self._ops_since_purge < 32:
+ return
+ self._ops_since_purge = 0
+ self._purge_expired()
+
+ async def _lock_for(self, key: str) -> asyncio.Lock:
+ if self._meta_lock is None:
+ self._meta_lock = asyncio.Lock()
+ async with self._meta_lock:
+ lock = self._locks.get(key)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._locks[key] = lock
+ return lock
+
+ def _fresh(self, key: str) -> Any | None:
+ entry = self._entries.get(key)
+ if entry is None:
+ return None
+ if time.monotonic() - entry.fetched_at > self._ttl:
+ self._entries.pop(key, None)
+ return None
+ return entry.value
+
+ async def get_or_fetch(self, key: str, fetcher) -> Any:
+ self._maybe_purge()
+ hit = self._fresh(key)
+ if hit is not None:
+ return hit
+ generation = self._generation
+ lock = await self._lock_for(key)
+ async with lock:
+ hit = self._fresh(key)
+ if hit is not None:
+ return hit
+ value = await fetcher()
+ # invalidate 期间的回填不得写回,否则 reload 仍读到旧行。
+ if generation == self._generation:
+ self._entries[key] = _CacheEntry(
+ value=value, fetched_at=time.monotonic()
+ )
+ return value
+
+
+class TemplateEntityCache:
+ """进程级模板实体缓存:按 (表, template_id) + 单飞补齐 + TTL。"""
+
+ def __init__(self, ttl_seconds: float = 3600.0) -> None:
+ self._ttl = ttl_seconds
+ self._entries: dict[tuple[str, str], _CacheEntry] = {}
+ self._table_locks: dict[str, asyncio.Lock] = {}
+ self._meta_lock: asyncio.Lock | None = None
+ self._ops_since_purge = 0
+ self._generation = 0
+
+ def invalidate(self) -> None:
+ self._generation += 1
+ self._entries.clear()
+ self._table_locks.clear()
+ logger.info("[AgentPerf] template entity cache invalidated")
+
+ def _purge_expired(self) -> None:
+ now = time.monotonic()
+ expired = [
+ key
+ for key, entry in self._entries.items()
+ if now - entry.fetched_at > self._ttl
+ ]
+ for key in expired:
+ self._entries.pop(key, None)
+
+ def _maybe_purge(self) -> None:
+ self._ops_since_purge += 1
+ if self._ops_since_purge < 32:
+ return
+ self._ops_since_purge = 0
+ self._purge_expired()
+
+ async def _lock_for(self, table: str) -> asyncio.Lock:
+ if self._meta_lock is None:
+ self._meta_lock = asyncio.Lock()
+ async with self._meta_lock:
+ lock = self._table_locks.get(table)
+ if lock is None:
+ lock = asyncio.Lock()
+ self._table_locks[table] = lock
+ return lock
+
+ def _fresh_row(self, table: str, template_id: str) -> dict[str, Any] | None:
+ entry = self._entries.get((table, template_id))
+ if entry is None:
+ return None
+ if time.monotonic() - entry.fetched_at > self._ttl:
+ self._entries.pop((table, template_id), None)
+ return None
+ return entry.value
+
+ async def get_by_ids(
+ self,
+ slot: str,
+ template_ids: list[str],
+ ) -> list[dict[str, Any]]:
+ self._maybe_purge()
+ generation = self._generation
+ try:
+ slot_key = TemplateRefSlot(slot)
+ except ValueError as exc:
+ raise ValueError(
+ f"unknown template_ref slot {slot!r} "
+ f"(known: {[s.value for s in TemplateRefSlot]})"
+ ) from exc
+
+ table = SLOT_ENTITY_TABLE[slot_key]
+ id_field = (
+ "policy_id"
+ if slot_key is TemplateRefSlot.A2A_ACCESS_POLICY
+ else "template_id"
+ )
+ refs: list[str] = []
+ for raw in template_ids:
+ tid = str(raw or "").strip()
+ if tid and tid not in refs:
+ refs.append(tid)
+ if not refs:
+ return []
+
+ result: dict[str, dict[str, Any]] = {}
+ missing: list[str] = []
+ for tid in refs:
+ row = self._fresh_row(table, tid)
+ if row is not None:
+ result[tid] = row
+ else:
+ missing.append(tid)
+
+ if missing:
+ lock = await self._lock_for(table)
+ async with lock:
+ still_missing: list[str] = []
+ for tid in missing:
+ row = self._fresh_row(table, tid)
+ if row is not None:
+ result[tid] = row
+ else:
+ still_missing.append(tid)
+ if still_missing:
+ fetched = await db_queries.fetch_templates_by_slot(
+ slot, still_missing
+ )
+ now = time.monotonic()
+ allow_cache_write = generation == self._generation
+ for row in fetched:
+ tid = str(row.get(id_field) or "").strip()
+ if not tid:
+ continue
+ if allow_cache_write:
+ self._entries[(table, tid)] = _CacheEntry(
+ value=row, fetched_at=now
+ )
+ result[tid] = row
+
+ return [result[tid] for tid in refs if tid in result]
+
+
+_template_entity_cache = TemplateEntityCache()
+_resource_row_cache = _TtlSingleFlightCache(ttl_seconds=600.0)
+_agent_template_cache = _TtlSingleFlightCache(ttl_seconds=600.0)
+
+
+def invalidate_template_entity_cache() -> None:
+ _template_entity_cache.invalidate()
+
+
+def invalidate_enterprise_config_caches() -> None:
+ """失效企业配置相关进程缓存(模板实体 + 实例/模板行)。"""
+ _template_entity_cache.invalidate()
+ _resource_row_cache.invalidate()
+ _agent_template_cache.invalidate()
+ logger.info("[AgentPerf] enterprise config caches invalidated")
+
+
async def _fetch_slot_entities(
slot: str,
template_ids: list[str],
) -> list[dict[str, Any]]:
- entities = await db_queries.fetch_templates_by_slot(slot, template_ids)
+ entities = await _template_entity_cache.get_by_ids(slot, template_ids)
requested = {str(tid or "").strip() for tid in template_ids} - {""}
id_field = (
"policy_id"
@@ -105,22 +328,30 @@ async def _fetch_instance_agent_resource(resource_id: str) -> dict[str, Any] | N
rid = str(resource_id or "").strip()
if not rid:
return None
- rows = await db_queries.list_records(
- "instance_agent_resource",
- filters={"enabled": True, "resource_id": rid},
- )
- return rows[0] if rows else None
+
+ async def _load() -> dict[str, Any] | None:
+ rows = await db_queries.list_records(
+ "instance_agent_resource",
+ filters={"enabled": True, "resource_id": rid},
+ )
+ return rows[0] if rows else None
+
+ return await _resource_row_cache.get_or_fetch(f"iar:{rid}", _load)
async def _fetch_agent_template_row(template_id: str) -> dict[str, Any] | None:
tid = str(template_id or "").strip()
if not tid:
return None
- rows = await db_queries.list_records(
- "agent_template",
- filters={"enabled": True, "template_id": tid},
- )
- return rows[0] if rows else None
+
+ async def _load() -> dict[str, Any] | None:
+ rows = await db_queries.list_records(
+ "agent_template",
+ filters={"enabled": True, "template_id": tid},
+ )
+ return rows[0] if rows else None
+
+ return await _agent_template_cache.get_or_fetch(f"at:{tid}", _load)
def _literal_slot_template_id_map(
@@ -270,6 +501,8 @@ __all__ = (
"DEFAULT_AGENT_LOAD_SLOTS",
"EffectiveEnterpriseConfig",
"TemplateRefSlot",
+ "invalidate_enterprise_config_caches",
+ "invalidate_template_entity_cache",
"load_effective_enterprise_config",
"routing_context_from_request",
)
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_sys_operation_release.py b/tests/unit_tests/agentserver/test_deep_adapter_sys_operation_release.py
index 626a45aaa4..6f81ec1d64 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_sys_operation_release.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_sys_operation_release.py
@@ -40,6 +40,9 @@ def _make_adapter() -> JiuWenSwarmDeepAdapter:
"""Create a bare adapter carrying only the sys_operation bookkeeping state."""
adapter = object.__new__(JiuWenSwarmDeepAdapter)
adapter._retained_sys_operation_ids = []
+ adapter._local_sys_operation = None
+ adapter._sys_operation = None
+ adapter._agent_id = "test-agent"
return adapter
@@ -110,6 +113,42 @@ def test_rebuild_on_same_id_keeps_registration(resource_mgr: _FakeResourceMgr) -
assert resource_mgr.removed == ["sandbox_shared"]
+def test_local_sysop_survives_agent_sysop_rebuild(
+ resource_mgr: _FakeResourceMgr,
+) -> None:
+ """沙箱 agent sysop 重建时,读盘用的本地 sysop 不得被连带注销。
+
+ 回归:``_create_sys_operation`` 曾 release 全部 previously_retained,
+ 把仍被 rail 使用的 local sysop 卸掉;缓存命中路径又不再 retain。
+ """
+ adapter = _make_adapter()
+ adapter._local_sys_operation = None
+ adapter._agent_id = "agent-1"
+
+ sandbox = resource_mgr.register(_FakeSysOperation("sandbox_1"))
+ local = resource_mgr.register(_FakeSysOperation("local_1"))
+ adapter._resolve_sys_operation = lambda: sandbox
+
+ assert adapter._create_sys_operation() is sandbox
+ adapter._sys_operation = sandbox
+ adapter._retain_sys_operation("local_1")
+ adapter._local_sys_operation = local
+ assert adapter._retained_sys_operation_ids == ["sandbox_1", "local_1"]
+
+ # 模拟二次 create_instance:只重建 agent sysop
+ assert adapter._create_sys_operation() is sandbox
+
+ assert "local_1" in adapter._retained_sys_operation_ids
+ assert resource_mgr.get_sys_operation("local_1") is local
+ assert "local_1" not in resource_mgr.removed
+ assert adapter._local_sys_operation is local
+
+ # 缓存命中仍可用,且仍在 retain 列表里
+ reused = adapter._create_local_sys_operation()
+ assert reused is local
+ assert "local_1" in adapter._retained_sys_operation_ids
+
+
def test_release_is_noop_without_instance(resource_mgr: _FakeResourceMgr) -> None:
"""The root adapter never builds an agent, so it has nothing to release."""
adapter = _make_adapter()
diff --git a/tests/unit_tests/agentserver/test_enterprise_policy.py b/tests/unit_tests/agentserver/test_enterprise_policy.py
index fab68610cd..4c160a0362 100644
--- a/tests/unit_tests/agentserver/test_enterprise_policy.py
+++ b/tests/unit_tests/agentserver/test_enterprise_policy.py
@@ -9,6 +9,18 @@ from jiuwenswarm.server.runtime.enterprise_config.schemas import (
)
[email protected](autouse=True)
+def _clear_enterprise_config_caches() -> None:
+ """进程级模板/资源缓存会跨用例串味,每个用例前清掉。"""
+ from jiuwenswarm.server.runtime.enterprise_config.loader import (
+ invalidate_enterprise_config_caches,
+ )
+
+ invalidate_enterprise_config_caches()
+ yield
+ invalidate_enterprise_config_caches()
+
+
def test_normalize_template_ref_accepts_list() -> None:
assert normalize_template_ref(None) == {}
assert normalize_template_ref(
diff --git a/tests/unit_tests/agentserver/test_template_entity_cache.py b/tests/unit_tests/agentserver/test_template_entity_cache.py
new file mode 100644
index 0000000000..a648452ac4
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_template_entity_cache.py
@@ -0,0 +1,189 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""进程级 TemplateEntityCache:命中 / 单飞 / TTL / 失效."""
+
+from __future__ import annotations
+
+import asyncio
+import time
+from typing import Any
+
+import pytest
+
+from jiuwenswarm.server.runtime.enterprise_config import loader as loader_mod
+
+
+def template_cache(monkeypatch: pytest.MonkeyPatch):
+ fetch_calls: list[tuple[str, tuple[str, ...]]] = []
+ catalog = {
+ "default_model": {
+ "m1": {"template_id": "m1", "model_id": "model-1"},
+ "m2": {"template_id": "m2", "model_id": "model-2"},
+ },
+ "vision_model": {
+ "m1": {"template_id": "m1", "model_id": "model-1"},
+ },
+ "skill_prebuilt": {
+ "w1": {"template_id": "w1", "skills": []},
+ },
+ }
+
+ async def _fake_fetch(slot: str, template_ids: list[str]) -> list[dict[str, Any]]:
+ fetch_calls.append((slot, tuple(template_ids)))
+ rows = catalog.get(slot, {})
+ return [rows[tid] for tid in template_ids if tid in rows]
+
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.enterprise_config.loader.db_queries.fetch_templates_by_slot",
+ _fake_fetch,
+ )
+ loader_mod.invalidate_template_entity_cache()
+ return loader_mod, fetch_calls
+
+
+async def test_second_fetch_hits_cache(template_cache) -> None:
+ mod, fetch_calls = template_cache
+ first = await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ second = await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+
+ assert first[0]["model_id"] == "model-1"
+ assert second[0]["model_id"] == "model-1"
+ assert len(fetch_calls) == 1
+
+
+async def test_model_slots_share_table_cache(template_cache) -> None:
+ """default_model / vision_model 共用 model_template 表缓存."""
+ mod, fetch_calls = template_cache
+ await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ by_id = await mod._template_entity_cache.get_by_ids("vision_model", ["m1"])
+
+ assert by_id[0]["model_id"] == "model-1"
+ assert len(fetch_calls) == 1
+
+
+async def test_only_missing_ids_are_fetched(template_cache) -> None:
+ mod, fetch_calls = template_cache
+ await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ rows = await mod._template_entity_cache.get_by_ids("default_model", ["m1", "m2"])
+
+ assert {r["template_id"] for r in rows} == {"m1", "m2"}
+ assert fetch_calls[-1] == ("default_model", ("m2",))
+
+
+async def test_invalidate_forces_refetch(template_cache) -> None:
+ mod, fetch_calls = template_cache
+ await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ mod.invalidate_template_entity_cache()
+ await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+
+ assert len(fetch_calls) == 2
+
+
+async def test_ttl_expiry_refetches(template_cache) -> None:
+ mod, fetch_calls = template_cache
+ cache = mod._template_entity_cache
+ await cache.get_by_ids("default_model", ["m1"])
+ entry = cache._entries[("model_template", "m1")]
+ entry.fetched_at = time.monotonic() - (cache._ttl + 1)
+
+ await cache.get_by_ids("default_model", ["m1"])
+ assert len(fetch_calls) == 2
+ # 过期读路径应丢掉旧条目,避免字典无限增长
+ assert ("model_template", "m1") in cache._entries
+ assert time.monotonic() - cache._entries[("model_template", "m1")].fetched_at < 1
+
+
+async def test_purge_expired_removes_stale_entries(template_cache) -> None:
+ mod, _ = template_cache
+ cache = mod._template_entity_cache
+ await cache.get_by_ids("default_model", ["m1"])
+ cache._entries[("model_template", "m1")].fetched_at = (
+ time.monotonic() - (cache._ttl + 1)
+ )
+ cache._purge_expired()
+ assert cache._entries == {}
+
+
+async def test_invalidate_clears_table_locks(template_cache) -> None:
+ mod, _ = template_cache
+ cache = mod._template_entity_cache
+ await cache.get_by_ids("default_model", ["m1"])
+ assert cache._table_locks
+ mod.invalidate_template_entity_cache()
+ assert cache._entries == {}
+ assert cache._table_locks == {}
+
+
+async def test_concurrent_misses_singleflight(template_cache) -> None:
+ mod, fetch_calls = template_cache
+ original = mod.db_queries.fetch_templates_by_slot
+
+ async def _slow(slot: str, template_ids: list[str]):
+ await asyncio.sleep(0.03)
+ return await original(slot, template_ids)
+
+ mod.db_queries.fetch_templates_by_slot = _slow # type: ignore[method-assign]
+ try:
+ results = await asyncio.gather(
+ *(
+ mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ for _ in range(10)
+ )
+ )
+ assert len(fetch_calls) == 1
+ assert all(r[0]["model_id"] == "model-1" for r in results)
+ finally:
+ mod.db_queries.fetch_templates_by_slot = original # type: ignore[method-assign]
+
+
+async def test_invalidate_enterprise_config_caches_clears_template(
+ template_cache,
+) -> None:
+ mod, _ = template_cache
+ await mod._template_entity_cache.get_by_ids("skill_prebuilt", ["w1"])
+ mod.invalidate_enterprise_config_caches()
+ assert mod._template_entity_cache._entries == {}
+
+
+async def test_invalidate_during_fetch_does_not_write_stale(
+ template_cache,
+) -> None:
+ """invalidate 发生在 DB 回填完成前时,旧结果不得写回缓存。"""
+ mod, fetch_calls = template_cache
+ started = asyncio.Event()
+ resume = asyncio.Event()
+ original = mod.db_queries.fetch_templates_by_slot
+
+ async def _gated(slot: str, template_ids: list[str]):
+ started.set()
+ await resume.wait()
+ return await original(slot, template_ids)
+
+ mod.db_queries.fetch_templates_by_slot = _gated # type: ignore[method-assign]
+ try:
+ task = asyncio.create_task(
+ mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ )
+ await started.wait()
+ mod.invalidate_template_entity_cache()
+ resume.set()
+ rows = await task
+ assert rows[0]["model_id"] == "model-1"
+ # 旧 generation 的回填不得落盘;下一次仍应打 DB。
+ assert mod._template_entity_cache._entries == {}
+ fetch_before = len(fetch_calls)
+ await mod._template_entity_cache.get_by_ids("default_model", ["m1"])
+ assert len(fetch_calls) == fetch_before + 1
+ finally:
+ mod.db_queries.fetch_templates_by_slot = original # type: ignore[method-assign]
diff --git a/tests/unit_tests/agentserver/test_workspace_host_init.py b/tests/unit_tests/agentserver/test_workspace_host_init.py
new file mode 100644
index 0000000000..1d64f08a4f
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_workspace_host_init.py
@@ -0,0 +1,76 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""宿主机 workspace 初始化:marker 跳过 / 空盘 copytree / 部分文件 materialize."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from jiuwenswarm.server.runtime.agent_adapter.workspace_host_init import (
+ host_init_workspace_sync,
+)
+
+
+def _sample_dirs() -> list[dict]:
+ return [
+ {
+ "name": "agent",
+ "path": "agent",
+ "is_file": False,
+ "children": [
+ {
+ "name": "SOUL.md",
+ "path": "SOUL.md",
+ "is_file": True,
+ "default_content": "# soul\n",
+ }
+ ],
+ }
+ ]
+
+
+def test_host_init_skips_when_marker_exists(tmp_path: Path) -> None:
+ root = tmp_path / "ws"
+ root.mkdir()
+ (root / ".workspace").write_text("", encoding="utf-8")
+ (root / "noise.txt").write_text("x", encoding="utf-8")
+
+ result = host_init_workspace_sync(str(root), _sample_dirs())
+ assert result["status"] == "skipped_marker"
+ assert not (root / "agent" / "SOUL.md").exists()
+
+
+def test_host_init_copytree_on_empty_dir(tmp_path: Path) -> None:
+ root = tmp_path / "ws"
+ root.mkdir()
+
+ result = host_init_workspace_sync(str(root), _sample_dirs())
+ assert result["status"] == "copytree"
+ assert (root / ".workspace").is_file()
+ assert (root / "agent" / "SOUL.md").read_text(encoding="utf-8") == "# soul\n"
+
+
+def test_host_init_materialize_when_partial(tmp_path: Path) -> None:
+ root = tmp_path / "ws"
+ root.mkdir()
+ (root / "keep.txt").write_text("keep", encoding="utf-8")
+
+ result = host_init_workspace_sync(str(root), _sample_dirs())
+ assert result["status"] == "materialize"
+ assert (root / "keep.txt").read_text(encoding="utf-8") == "keep"
+ assert (root / ".workspace").is_file()
+ assert (root / "agent" / "SOUL.md").is_file()
+
+
+def test_dirs_fingerprint_changes_when_same_length_content_changes() -> None:
+ from jiuwenswarm.server.runtime.agent_adapter.workspace_host_init import (
+ _dirs_fingerprint,
+ )
+
+ base = _sample_dirs()
+ other = _sample_dirs()
+ other[0]["children"][0]["default_content"] = "# Soul\n" # 同长度不同内容
+ assert len(base[0]["children"][0]["default_content"]) == len(
+ other[0]["children"][0]["default_content"]
+ )
+ assert _dirs_fingerprint(base) != _dirs_fingerprint(other)