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(context): 识别ModelArts输入超限并启用flash溢出兜底

openJiuwen-bot405a5203c792
diff --git a/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
index 4093ac927d..71f3ca9711 100644
--- a/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/context_overflow_recovery_rail.py
@@ -14,6 +14,87 @@ from openjiuwen.core.common.logging import logger
# 0.85 表示压缩后上下文最多占模型窗口的 85%,预留 15% 给 LLM 输出
RECOVERY_THRESHOLD_RATIO = 0.85
+# 主动预压缩阈值:上一轮真实 input_tokens 达到窗口的 90% 时,
+# 在本次模型调用前先 force_compact,避免等到服务端 400 才补救。
+PROACTIVE_TRIGGER_RATIO = 0.90
+
+# 华为 MaaS 超限变体: "input token limit is 1048576"
+_MODELARTS_INPUT_TOKEN_LIMIT_PATTERN = re.compile(
+ r"input\s+token\s+limit\s+is\s+(\d+)", re.IGNORECASE
+)
+
+# 路由前下发的档位关键字,不能当作真实模型名去查窗口
+_TIER_MODEL_KEYWORDS = frozenset({"auto", "fast", "balanced", "extreme"})
+
+# 不同 provider 的 usage 字段差异:OpenAI 风格只暴露 prompt_tokens
+_PROMPT_TOKEN_KEYS = ("input_tokens", "prompt_tokens", "total_tokens")
+
+
+def _coerce_positive_int(value: Any) -> int:
+ try:
+ parsed = int(value)
+ except (TypeError, ValueError):
+ return 0
+ return max(0, parsed)
+
+
+def _get_int_field(config: Any, key: str) -> int:
+ if config is None:
+ return 0
+ if isinstance(config, dict):
+ return _coerce_positive_int(config.get(key))
+ return _coerce_positive_int(getattr(config, key, None))
+
+
+def _has_positive_model_window(mapping: Any, model_name: str) -> bool:
+ """判断模型是否在窗口映射中(精确匹配 + 大小写不敏感匹配)。"""
+ if not isinstance(mapping, dict) or not model_name:
+ return False
+
+ value = mapping.get(model_name)
+ if isinstance(value, int) and value > 0:
+ return True
+
+ normalized = model_name.lower()
+ for candidate, candidate_value in mapping.items():
+ if not isinstance(candidate, str) or candidate.lower() != normalized:
+ continue
+ if isinstance(candidate_value, int) and candidate_value > 0:
+ return True
+ return False
+
+
+def _usage_mapping(usage: Any) -> dict[str, Any]:
+ """把 dict / Pydantic / dataclass 形态的 usage 统一成 dict。"""
+ if isinstance(usage, dict):
+ return usage
+ model_dump = getattr(usage, "model_dump", None)
+ if callable(model_dump):
+ try:
+ dumped = model_dump()
+ if isinstance(dumped, dict):
+ return dumped
+ except Exception: # noqa: BLE001
+ logger.debug(
+ "[ContextOverflowRecovery] usage model_dump failed; fallback to dict/getattr",
+ exc_info=True,
+ )
+ try:
+ mapped = dict(usage)
+ except (TypeError, ValueError):
+ return {}
+ return mapped if isinstance(mapped, dict) else {}
+
+
+def _usage_field(usage: Any, key: str) -> Any:
+ if isinstance(usage, dict):
+ return usage.get(key)
+ mapped = _usage_mapping(usage)
+ if key in mapped:
+ return mapped.get(key)
+ # SimpleNamespace / 自定义对象没有 model_dump 时仍保留 getattr 兜底
+ return getattr(usage, key, None)
+
def _parse_token_limits(exc: Exception) -> tuple[int | None, int | None]:
"""从 413 错误解析 limit_tokens 和 actual_tokens。
@@ -22,6 +103,11 @@ def _parse_token_limits(exc: Exception) -> tuple[int | None, int | None]:
"""
msg = str(exc)
+ # 华为 MaaS: "input token limit is N"
+ m = _MODELARTS_INPUT_TOKEN_LIMIT_PATTERN.search(msg)
+ if m:
+ return None, int(m.group(1))
+
# Anthropic: "prompt is too long: N tokens > M maximum"
m = re.search(r'(\d+)\s*tokens?\s*>\s*(\d+)', msg, re.IGNORECASE)
if m:
@@ -41,20 +127,37 @@ def _parse_token_limits(exc: Exception) -> tuple[int | None, int | None]:
def _get_config_context_limit(ctx: AgentCallbackContext) -> int:
- """从 config 读 context_window_limit_tokens 作为 fallback。
+ """从 config 读显式上下文窗口上限。
- Returns 0 if not found (triggers circuit_break_with_model_hint).
+ 兼容历史字段 ``context_window_limit_tokens`` 与当前真实生效的
+ ``react.context_engine_config.context_window_tokens``。
"""
agent = getattr(ctx, "agent", None)
if agent is None:
return 0
- deep_config = getattr(agent, "deep_config", None)
- if deep_config is None:
- return 0
- # context_window_limit_tokens 在 deep_config 或 yaml 中
- limit = getattr(deep_config, "context_window_limit_tokens", None)
- if isinstance(limit, int) and limit > 0:
- return limit
+
+ for attr in ("deep_config", "_config", "_model_request_config"):
+ config = getattr(agent, attr, None)
+ if config is None:
+ continue
+
+ limit = _get_int_field(config, "context_window_limit_tokens")
+ if limit > 0:
+ return limit
+
+ limit = _get_int_field(config, "context_window_tokens")
+ if limit > 0:
+ return limit
+
+ context_engine_config = (
+ config.get("context_engine_config")
+ if isinstance(config, dict)
+ else getattr(config, "context_engine_config", None)
+ )
+ limit = _get_int_field(context_engine_config, "context_window_tokens")
+ if limit > 0:
+ return limit
+
return 0
@@ -84,6 +187,178 @@ class ContextOverflowRecoveryRail(DeepAgentRail):
self._context_engineering_rail: Optional[Any] = None
self._logged_missing_full_compact_bridge_api = False
+ # ------------------------------------------------------------------
+ # before_model_call: proactive compaction
+ # ------------------------------------------------------------------
+
+ async def before_model_call(self, ctx: AgentCallbackContext) -> None:
+ """在模型调用前用上一轮真实 usage 做一次主动预压缩。
+
+ 日常压缩器按本地 tokenizer 估算,遇到中文/工具/附件时可能显著低估真实
+ prompt(本次线上 751K vs 实际 1.047M)。这里直接使用服务端返回的
+ ``usage.input_tokens`` 作为基线,达到 90% 时提前 force_compact,
+ 避免请求一路发到服务端 1M 硬上限才 400。
+
+ 每个 invoke 最多触发一次(通过 ``ctx.extra`` 标记),压缩失败或
+ usage 不可用时不改变原有行为。解析不到真实模型窗口时直接跳过,
+ 不会用 agent-core 的 200000 默认值误触发;该场景仍由
+ ``on_model_exception`` 的响应式恢复兜底。
+ """
+ if ctx.extra.get("_context_overflow_proactive_done"):
+ return
+
+ limit = self._resolve_model_context_limit(ctx)
+ if limit <= 0:
+ return
+
+ used = self._last_prompt_tokens(ctx)
+ if used <= 0 or used < int(limit * PROACTIVE_TRIGGER_RATIO):
+ return
+
+ threshold_override = int(limit * RECOVERY_THRESHOLD_RATIO)
+ if self._set_force_compact_flag(ctx, threshold_override=threshold_override):
+ ctx.extra["_context_overflow_proactive_done"] = True
+ logger.warning(
+ "[ContextOverflowRecovery] Proactive compact before model call: "
+ "used_tokens=%d limit_tokens=%d threshold_override=%d",
+ used,
+ limit,
+ threshold_override,
+ )
+ else:
+ logger.warning(
+ "[ContextOverflowRecovery] Proactive compact skipped: "
+ "used_tokens=%d limit_tokens=%d (FullCompactProcessor unavailable)",
+ used,
+ limit,
+ )
+
+ @staticmethod
+ def _last_prompt_tokens(ctx: AgentCallbackContext) -> int:
+ """从历史消息的 usage_metadata 取最近一次真实 prompt token 数。
+
+ 兼容 dict / Pydantic / 普通对象三种 usage 形态,并按
+ input_tokens → prompt_tokens → total_tokens 回退(与 StreamEventRail 一致)。
+ """
+ inputs = getattr(ctx, "inputs", None)
+ messages = list(getattr(inputs, "messages", None) or [])
+ for message in reversed(messages):
+ usage = getattr(message, "usage_metadata", None)
+ if not usage:
+ continue
+ for key in _PROMPT_TOKEN_KEYS:
+ value = _coerce_positive_int(_usage_field(usage, key))
+ if value > 0:
+ return value
+ if messages:
+ logger.debug(
+ "[ContextOverflowRecovery] no usage_metadata found in %d messages; "
+ "proactive compact skipped",
+ len(messages),
+ )
+ return 0
+
+ @staticmethod
+ def _resolve_model_name(ctx: AgentCallbackContext) -> str:
+ """优先取路由后的真实模型名,避免把 fast/auto 档位关键字当模型名。"""
+ extra = getattr(ctx, "extra", None)
+ if isinstance(extra, dict):
+ run_context = extra.get("run_context")
+ run_context_extra = getattr(run_context, "extra", None)
+ if isinstance(run_context_extra, dict):
+ routed = str(
+ run_context_extra.get("model_routing_applied_model") or ""
+ ).strip()
+ if routed:
+ return routed
+
+ agent = getattr(ctx, "agent", None)
+ for attr in ("_model_request_config", "_config", "deep_config"):
+ config = getattr(agent, attr, None)
+ if config is None:
+ continue
+ name = (
+ config.get("model_name")
+ if isinstance(config, dict)
+ else getattr(config, "model_name", "")
+ )
+ name = str(name or "").strip()
+ if name:
+ return name
+ return ""
+
+ @staticmethod
+ def _is_known_model(
+ model_name: str,
+ model_windows: dict[str, int] | None,
+ default_windows: dict[str, int],
+ ) -> bool:
+ """判断模型是否真的在窗口表里,避免把 200000 默认值当成真实窗口。"""
+ return _has_positive_model_window(
+ model_windows, model_name
+ ) or _has_positive_model_window(default_windows, model_name)
+
+ @classmethod
+ def _resolve_model_context_limit(cls, ctx: AgentCallbackContext) -> int:
+ """按“显式窗口 → 模型窗口表 → 配置”解析真实上下文窗口。
+
+ 解析不到真实模型窗口时返回 0,放弃主动预压缩,避免用 agent-core
+ 的 200000 默认值在远未接近真实窗口时反复触发 FullCompact。
+ """
+ context = getattr(ctx, "context", None)
+ explicit_limit = _coerce_positive_int(
+ getattr(context, "_context_window_tokens", None)
+ )
+ model_windows = getattr(context, "_model_context_window_tokens", None)
+ if not isinstance(model_windows, dict):
+ model_windows = None
+
+ if explicit_limit <= 0:
+ explicit_limit = _get_config_context_limit(ctx)
+ if explicit_limit > 0:
+ return explicit_limit
+
+ model_name = cls._resolve_model_name(ctx)
+ if not model_name or model_name.lower() in _TIER_MODEL_KEYWORDS:
+ logger.debug(
+ "[ContextOverflowRecovery] no routed model name (model=%r); "
+ "proactive compact skipped",
+ model_name,
+ )
+ return 0
+
+ try:
+ from openjiuwen.core.context_engine.context.context_utils import (
+ DEFAULT_CONTEXT_MAX_TOKENS,
+ MODEL_DEFAULT_CONTEXT_WINDOW_TOKENS,
+ ContextUtils,
+ )
+
+ resolved = _coerce_positive_int(
+ ContextUtils.resolve_context_max(
+ model_name=model_name,
+ model_context_window_tokens=model_windows,
+ )
+ )
+ if resolved <= 0:
+ return 0
+ if resolved == DEFAULT_CONTEXT_MAX_TOKENS and not cls._is_known_model(
+ model_name, model_windows, MODEL_DEFAULT_CONTEXT_WINDOW_TOKENS
+ ):
+ logger.debug(
+ "[ContextOverflowRecovery] unknown context window for model=%s; "
+ "proactive compact skipped",
+ model_name,
+ )
+ return 0
+ return resolved
+ except Exception: # noqa: BLE001
+ logger.debug(
+ "[ContextOverflowRecovery] resolve model context limit failed",
+ exc_info=True,
+ )
+ return 0
+
# ------------------------------------------------------------------
# on_model_exception: core recovery logic
# ------------------------------------------------------------------
@@ -152,7 +427,8 @@ class ContextOverflowRecoveryRail(DeepAgentRail):
"maximum context length", # OpenAI: "maximum context length is N"
"maximum input length", # 华为: "maximum input length M"
"must less than the maximum input",
- "context length exceeded"
+ "context length exceeded",
+ "input token limit", # 华为 ModelArts.81001: "input token limit is N"
)
error_key = "Error code: 400"
error_code = "ModelArts.81001"
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index d9bdff8cc2..a3bf652b87 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -16,9 +16,10 @@ config.yaml。父类只提供通用工具工厂与生命周期扩展点,不感
部署组合提示:OfficeClaw 交互请求由 Relay 显式发送 ``mode=flash`` 选型,
不再由 ``flash.enabled`` 将普通 Agent 请求自动转换为 Flash;其它渠道和后台
来源沿用各自的既有路由策略。具体准入与会话续接由 ``_shared`` 的模式解析负责。
-flash 白名单不含 ``_llm_retry_rail`` / ``_context_overflow_recovery_rail``
-等健壮性 rail,长文档 / 弱网任务的容错弱于
-normal,部署时仍需评估所选 Flash profile 的能力边界。
+flash 白名单包含 ``_context_overflow_recovery_rail``(仅上下文溢出兜底,
+正常路径零开销),但不含 ``_llm_retry_rail`` 等重试类健壮性 rail,
+长文档 / 弱网任务的容错仍弱于 normal,部署时需评估所选 Flash profile
+的能力边界。
flash 行为由类常量定义:
- :data:`_FLASH_REACT_OVERRIDE` — react/evolution 覆盖(``enable_task_loop=false``
@@ -261,6 +262,9 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
"_subagent_rail",
"_permission_rail",
"_context_processor_rail",
+ # 上下文溢出兜底:413/ModelArts.81001 input-token-limit 时
+ # 由该 rail 设置 force_compact 并在重试前压缩上下文。正常请求不触发。
+ "_context_overflow_recovery_rail",
# _filesystem_rail: SlimSysOperationRail(flash override),init() 注册
# Read/Write/Edit/Glob/Grep/Bash,不注册 powershell/list_files;
# 丢掉=无文件/shell 能力。
diff --git a/tests/unit_tests/agentserver/test_context_overflow_recovery_rail.py b/tests/unit_tests/agentserver/test_context_overflow_recovery_rail.py
new file mode 100644
index 0000000000..8931bb312e
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_context_overflow_recovery_rail.py
@@ -0,0 +1,290 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Unit tests for ContextOverflowRecoveryRail.
+
+Covers the Huawei MaaS overflow variant ``input token limit is N`` and the
+proactive compaction hook added for flash mode.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.agents.harness.common.rails.context_overflow_recovery_rail import (
+ RECOVERY_THRESHOLD_RATIO,
+ ContextOverflowRecoveryRail,
+ _parse_token_limits,
+)
+
+MODELARTS_INPUT_TOKEN_LIMIT_ERROR = (
+ "[181001] model call failed, reason: openAI API async stream error: "
+ "BadRequestError: Error code: 400 - {'error': {'code': 'ModelArts.81001', "
+ "'message': 'input token limit is 1048576', 'param': None, "
+ "'type': 'invalid_request_error'}, 'error_code': 'ModelArts.81001', "
+ "'error_msg': 'input token limit is 1048576'}"
+)
+
+
+class _FakeFullCompactProcessor:
+ def __init__(self) -> None:
+ self.force_compact = False
+ self.overflow_threshold_override: int | None = None
+
+ @staticmethod
+ def processor_type() -> str:
+ return "FullCompactProcessor"
+
+ def set_force_compact(self, value: bool = True) -> None:
+ self.force_compact = value
+
+ def set_overflow_threshold_override(self, value: int) -> None:
+ self.overflow_threshold_override = value
+
+
+def _make_ctx(
+ *,
+ input_tokens: int,
+ processor: _FakeFullCompactProcessor,
+ model_name: str = "deepseek-v4.1-flash",
+ usage=None,
+):
+ if usage is None:
+ usage = SimpleNamespace(input_tokens=input_tokens)
+ message = SimpleNamespace(usage_metadata=usage)
+ return SimpleNamespace(
+ extra={},
+ inputs=SimpleNamespace(messages=[message]),
+ context=SimpleNamespace(_processors=[processor]),
+ agent=SimpleNamespace(_config=SimpleNamespace(model_name=model_name)),
+ exception=None,
+ )
+
+
+class _ModelDumpUsage:
+ def model_dump(self):
+ return {"input_tokens": 1_000_000}
+
+
+def test_detects_modelarts_input_token_limit_with_status_code():
+ exc = Exception(MODELARTS_INPUT_TOKEN_LIMIT_ERROR)
+ exc.status_code = 400
+
+ assert ContextOverflowRecoveryRail._is_context_overflow_error(exc) is True
+
+
+def test_detects_modelarts_input_token_limit_without_status_code():
+ exc = Exception(MODELARTS_INPUT_TOKEN_LIMIT_ERROR)
+
+ assert ContextOverflowRecoveryRail._is_context_overflow_error(exc) is True
+
+
+def test_does_not_treat_chat_template_error_as_overflow():
+ exc = Exception(
+ "ModelArts.81001 chat template failed: Error code: 400 invalid_request_error"
+ )
+ exc.status_code = 400
+
+ assert ContextOverflowRecoveryRail._is_context_overflow_error(exc) is False
+
+
+def test_parse_modelarts_input_token_limit():
+ assert _parse_token_limits(Exception(MODELARTS_INPUT_TOKEN_LIMIT_ERROR)) == (
+ None,
+ 1048576,
+ )
+
+
+def test_threshold_override_uses_parsed_limit():
+ assert ContextOverflowRecoveryRail._resolve_threshold_override(None, 1048576) == int(
+ 1048576 * RECOVERY_THRESHOLD_RATIO
+ )
+
+
+async def test_proactive_compact_sets_force_compact_once_per_invoke():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(input_tokens=1_000_000, processor=processor)
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+ assert processor.overflow_threshold_override == int(
+ 1048576 * RECOVERY_THRESHOLD_RATIO
+ )
+ assert ctx.extra["_context_overflow_proactive_done"] is True
+
+ processor.force_compact = False
+ await rail.before_model_call(ctx)
+ assert processor.force_compact is False
+
+
+async def test_proactive_compact_skips_below_threshold():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(input_tokens=800_000, processor=processor)
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is False
+ assert processor.overflow_threshold_override is None
+ assert ctx.extra.get("_context_overflow_proactive_done") is None
+
+
+async def test_proactive_compact_skips_without_usage_metadata():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(input_tokens=0, processor=processor)
+ ctx.inputs.messages = [SimpleNamespace(content="no usage")]
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is False
+
+
+async def test_proactive_compact_reads_dict_usage():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=0,
+ processor=processor,
+ usage={"input_tokens": 1_000_000},
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_reads_prompt_tokens_fallback():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=0,
+ processor=processor,
+ usage={"prompt_tokens": 1_000_000},
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_reads_model_dump_usage():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=0,
+ processor=processor,
+ usage=_ModelDumpUsage(),
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_skips_unknown_model():
+ """未知模型不能落到 agent-core 的 200000 默认窗口上。"""
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="custom-enterprise-alias",
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is False
+
+
+async def test_proactive_compact_skips_tier_keyword_model():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="fast",
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is False
+
+
+async def test_proactive_compact_uses_explicit_context_window():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="custom-enterprise-alias",
+ )
+ ctx.context._context_window_tokens = 1048576
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_uses_model_window_mapping():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="custom-enterprise-alias",
+ )
+ ctx.context._model_context_window_tokens = {"custom-enterprise-alias": 1048576}
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_uses_context_engine_config_window():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="custom-enterprise-alias",
+ )
+ ctx.agent._config.context_engine_config = SimpleNamespace(
+ context_window_tokens=1048576
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
+
+
+async def test_proactive_compact_prefers_routed_model_name():
+ rail = ContextOverflowRecoveryRail(max_recovery_attempts=3)
+ processor = _FakeFullCompactProcessor()
+ ctx = _make_ctx(
+ input_tokens=1_000_000,
+ processor=processor,
+ model_name="fast",
+ )
+ ctx.extra["run_context"] = SimpleNamespace(
+ extra={"model_routing_applied_model": "deepseek-v4.1-flash"}
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert processor.force_compact is True
diff --git a/tests/unit_tests/agentserver/test_flash_adapter_rails.py b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
index 5f36cb7ec4..5cae4e9cd4 100644
--- a/tests/unit_tests/agentserver/test_flash_adapter_rails.py
+++ b/tests/unit_tests/agentserver/test_flash_adapter_rails.py
@@ -107,6 +107,16 @@ def test_keep_whitelist_keeps_protected_and_drops_others():
}
+def test_context_overflow_recovery_rail_is_in_flash_keep():
+ """Flash must keep the reactive context-overflow recovery rail.
+
+ Huawei MaaS returns ``ModelArts.81001 input token limit is ...`` when the
+ prompt exceeds the model window. Without this rail flash cannot force a
+ compaction and the raw error reaches the user.
+ """
+ assert "_context_overflow_recovery_rail" in JiuwenSwarmFlashAdapter._FLASH_RAIL_KEEP
+
+
def test_model_routing_rail_is_in_flash_keep():
"""Flash must retain ModelRoutingRail for auto-gear routing.