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(telemetry): 解除遥测截断限制——SpanLimits 上限/消息截断参数化/OTLP 下本地 jsonl fan-out
DL1232c40821192996
diff --git a/jiuwenswarm/agents/harness/agent_observability.py b/jiuwenswarm/agents/harness/agent_observability.pyindex 0ca881e7c5..f7e917ba9c 100644--- a/jiuwenswarm/agents/harness/agent_observability.py+++ b/jiuwenswarm/agents/harness/agent_observability.py@@ -62,6 +62,47 @@ _agent_observability_active: bool = False# unless force was ever used._force_ever_enabled: bool = False+# When the shared provider is owned by the unified telemetry runtime (relay+# injects OTEL env), the SDK init path ignores agent-side exporter settings,+# so local jsonl output stops. Attaching the file exporter as a fan-out span+# processor keeps jsonl flowing alongside the unified OTLP export.+_file_exporter_fanout: Any | None = None+++def _attach_file_exporter_fanout(traces_dir: str, cfg: Any) -> None:+ global _file_exporter_fanout+ if _file_exporter_fanout is not None:+ return+ try:+ from opentelemetry import trace+ from opentelemetry.sdk.trace.export import BatchSpanProcessor++ from openjiuwen.extensions.observability.file_exporter import TraceFileExporter+ from openjiuwen.extensions.observability.runtime import SafeSpanProcessor+ from openjiuwen.extensions.observability.setup import is_initialized++ if not is_initialized():+ return+ exporter = TraceFileExporter(+ root_dir=traces_dir,+ retention_days=int(cfg.get("file_retention_days", 7)),+ )+ # 注册并持有包装层(SafeSpanProcessor)而非内层 BatchSpanProcessor:+ # provider 上真正挂的是适配器,on_end 只在适配器自身的 _shutdown_called+ # 置位后才短路——持有内层时对其 shutdown 无法让适配器停转(评审 CR-002)。+ # 直接在全局 provider 上注册:unified runtime 初始化时会+ # set_tracer_provider,与 runtime.add_span_processors 内部使用的是同一+ # 个 provider;自持引用的幂等判断(is not None)强于其对象身份去重。+ adapter = SafeSpanProcessor(BatchSpanProcessor(exporter))+ trace.get_tracer_provider().add_span_processor(adapter)+ _file_exporter_fanout = adapter+ logger.info(+ "[AgentObservability] file exporter attached as fan-out processor: traces_dir=%s",+ traces_dir,+ )+ except Exception as exc:+ logger.warning("[AgentObservability] file exporter fan-out failed: %s", exc)+def sync_agent_observability(*, force: bool = False) -> None:"""Synchronize single-agent observability state with current config.@@ -132,6 +173,8 @@ def sync_agent_observability(*, force: bool = False) -> None:"[AgentObservability] reusing existing observability provider ""(owned by another subsystem)")+ if cfg.get("exporter", "otlp_grpc") == "file":+ _attach_file_exporter_fanout(traces_dir, cfg)elif cfg.get("exporter", "otlp_grpc") == "file":logger.info("[AgentObservability] enabled: exporter=%s traces_dir=%s",@@ -155,12 +198,28 @@ def sync_agent_observability(*, force: bool = False) -> None:def shutdown_agent_observability() -> None:"""Shutdown single-agent observability (on disable or process exit)."""- global _agent_observability_active+ global _agent_observability_active, _file_exporter_fanouttry:if not shutdown_trajectory_runtime(demand="agent"):logger.warning("[AgentObservability] trajectory runtime did not drain cleanly")except Exception as exc:logger.warning("[AgentObservability] trajectory runtime shutdown failed: %s", exc)+ # The fan-out processor must be shut down before the active-flag gate: OTel+ # TracerProvider has no remove API, so a registered processor stays on the+ # shared provider forever. _file_exporter_fanout holds the SafeSpanProcessor+ # adapter (the object actually registered on the provider); its shutdown()+ # sets _shutdown_called FIRST — subsequent on_end calls short-circuit before+ # reaching the inner BatchSpanProcessor — then stops the inner processor on+ # a best-effort basis (inner failure is logged, the gate stays latched).+ # The reference is only cleared on success: a failed shutdown keeps it so a+ # later attach stays a no-op instead of stacking a second processor.+ fanout_processor = _file_exporter_fanout+ if fanout_processor is not None:+ try:+ fanout_processor.shutdown()+ _file_exporter_fanout = None+ except Exception as exc:+ logger.warning("[AgentObservability] file exporter fan-out shutdown failed: %s", exc)if not _agent_observability_active:returntry:diff --git a/jiuwenswarm/telemetry/enrichment/callbacks.py b/jiuwenswarm/telemetry/enrichment/callbacks.pyindex a7c246b8ab..57002d7393 100644--- a/jiuwenswarm/telemetry/enrichment/callbacks.py+++ b/jiuwenswarm/telemetry/enrichment/callbacks.py@@ -993,6 +993,7 @@ class RichTelemetryCallbacks:lambda: self._bounded_json(kwargs.get("inputs"),redact=self._config.redact_prompts,+ max_chars=self._config.attribute_value_max_length,),)if arguments is not None:@@ -1075,6 +1076,7 @@ class RichTelemetryCallbacks:lambda: self._bounded_json(result_value,redact=self._config.redact_completions,+ max_chars=self._config.attribute_value_max_length,),)if result is not None:@@ -2065,14 +2067,14 @@ class RichTelemetryCallbacks:return self._find_tool_span(kwargs)@staticmethod- def _bounded_json(value: Any, *, redact: bool) -> str:+ def _bounded_json(value: Any, *, redact: bool, max_chars: int) -> str:if redact:return "[REDACTED]"try:serialized = json.dumps(value, ensure_ascii=False, default=str)except (TypeError, ValueError):serialized = str(value)- return serialized[:4096]+ return serialized[:max_chars]__all__ = [diff --git a/jiuwenswarm/telemetry/enrichment/messages.py b/jiuwenswarm/telemetry/enrichment/messages.pyindex 36022fb701..bf8a5e93f3 100644--- a/jiuwenswarm/telemetry/enrichment/messages.py+++ b/jiuwenswarm/telemetry/enrichment/messages.py@@ -189,11 +189,11 @@ def message_content(message: Any) -> str:return _safe_string(_get_value(message, "content"))-def _message_entry(message: Any) -> dict[str, Any]:+def _message_entry(message: Any, *, max_chars: int = 4096) -> dict[str, Any]:role = message_role(message)content = message_content(message)if role == "tool":- content = content[:4096]+ content = content[:max_chars]entry: dict[str, Any] = {"role": role,"parts": [{"type": "text", "content": content}],@@ -206,12 +206,15 @@ def _message_entry(message: Any) -> dict[str, Any]:def serialize_input_messages(messages: Any, *, max_chars: int) -> str:return _bounded_json(- [_message_entry(message) for message in _input_message_items(messages)],+ [+ _message_entry(message, max_chars=max_chars)+ for message in _input_message_items(messages)+ ],max_chars=max_chars,)-def _tool_call_entry(tool_call: Any) -> dict[str, Any]:+def _tool_call_entry(tool_call: Any, *, max_chars: int = 4096) -> dict[str, Any]:function = _get_value(tool_call, "function")name = _get_value(tool_call, "name")if not name:@@ -224,7 +227,7 @@ def _tool_call_entry(tool_call: Any) -> dict[str, Any]:"name": _safe_string(name),}if arguments not in (None, ""):- entry["arguments"] = _bounded_value(arguments, max_chars=4096)+ entry["arguments"] = _bounded_value(arguments, max_chars=max_chars)return entry@@ -236,10 +239,12 @@ def serialize_output_message(result: Any, *, max_chars: int) -> str:}tool_calls = _items(_get_value(result, "tool_calls"))if tool_calls:- output["tool_calls"] = [_tool_call_entry(call) for call in tool_calls]+ output["tool_calls"] = [+ _tool_call_entry(call, max_chars=max_chars) for call in tool_calls+ ]reasoning = _safe_string(_get_value(result, "reasoning_content"))if reasoning:- output["parts"].append({"type": "reasoning", "content": reasoning[:4096]})+ output["parts"].append({"type": "reasoning", "content": reasoning[:max_chars]})return _bounded_json([output], max_chars=max_chars)diff --git a/jiuwenswarm/telemetry/provider.py b/jiuwenswarm/telemetry/provider.pyindex 47896c7620..45f06f7dd4 100644--- a/jiuwenswarm/telemetry/provider.py+++ b/jiuwenswarm/telemetry/provider.py@@ -23,7 +23,7 @@ from opentelemetry.sdk.metrics.export import (PeriodicExportingMetricReader,)from opentelemetry.sdk.resources import Resource, SERVICE_NAME-from opentelemetry.sdk.trace import TracerProvider+from opentelemetry.sdk.trace import SpanLimits, TracerProviderfrom opentelemetry.sdk.trace.export import (BatchSpanProcessor,ConsoleSpanExporter,@@ -204,7 +204,13 @@ def build_default_providers(cfg: TelemetryConfig) -> ProviderBundle:def _build_tracer_provider(cfg: TelemetryConfig, resource: Resource) -> TracerProvider:- provider = TracerProvider(resource=resource)+ # SDK default max_attributes=128 silently drops extra attribute entries;+ # align the limit with TelemetryConfig (env OTEL_MAX_ATTRIBUTES). Value+ # length is not truncated by default.+ provider = TracerProvider(+ resource=resource,+ span_limits=SpanLimits(max_attributes=cfg.max_attributes),+ )try:if cfg.traces_exporter == "none":return providerdiff --git a/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py b/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.pyindex 9219e5eba8..a677b3b0a0 100644--- a/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py+++ b/tests/unit_tests/agentserver/test_trajectory_runtime_wiring.py@@ -10,6 +10,8 @@ reaches the exporter pipeline through that path."""import pytest+from typing import Any+from openjiuwen.agent_teams.observability import setup as team_observability_setupfrom openjiuwen.extensions.observability import demand as observability_demandfrom openjiuwen.extensions.observability import setup as shared_observability_setup@@ -30,6 +32,7 @@ def reset_observability_demands():agent_span_context.reset_run_root_spans()agent_observability._agent_observability_active = Falseagent_observability._force_ever_enabled = False+ agent_observability._file_exporter_fanout = Noneteam_manager._observability_active = False_reset()@@ -334,3 +337,174 @@ def test_team_trajectory_disabled_stops_sink(monkeypatch, tmp_path):assert runtime_settings[0][0].enabled is Falseassert runtime_settings[0][1] == {"demand": "team"}assert team_manager._observability_active is True+++class _FakeInnerProcessor:+ """Stand-in for the BatchSpanProcessor wrapped by the fan-out adapter."""++ def __init__(self, *, fail: bool = False) -> None:+ self.on_end_calls = 0+ self.shutdown_calls = 0+ self._fail = fail++ def on_start(self, span: Any, parent_context: Any = None) -> None:+ pass++ def on_end(self, span: Any) -> None:+ self.on_end_calls += 1++ def force_flush(self, timeout_millis: int = 30000) -> bool:+ return True++ def shutdown(self) -> None:+ self.shutdown_calls += 1+ if self._fail:+ raise RuntimeError("fan-out shutdown failed")+++class _BrokenFanout:+ """A fan-out holder whose shutdown() raises before any cleanup."""++ def __init__(self) -> None:+ self.shutdown_calls = 0++ def shutdown(self) -> None:+ self.shutdown_calls += 1+ raise RuntimeError("fan-out shutdown failed")+++def _make_real_adapter(*, fail: bool = False):+ """Real SafeSpanProcessor wrapping a fake inner processor (review CR-002:+ the object registered on the provider is the ADAPTER; the shutdown gate+ lives on the adapter, not the inner processor)."""+ from openjiuwen.extensions.observability.runtime import SafeSpanProcessor++ inner = _FakeInnerProcessor(fail=fail)+ return SafeSpanProcessor(inner), inner+++def test_shutdown_shuts_down_and_gates_the_fanout_adapter(monkeypatch):+ """Regression (PR #7971 review CR-001 + CR-002): shutdown must reach the+ SafeSpanProcessor adapter so its _shutdown_called latch flips — later+ on_end calls short-circuit before the inner processor — and the reference+ is cleared only on success."""+ adapter, inner = _make_real_adapter()+ monkeypatch.setattr(+ agent_observability, "shutdown_trajectory_runtime", lambda **kwargs: True+ )+ monkeypatch.setattr(agent_observability, "release_observability", lambda: None)+ agent_observability._agent_observability_active = True+ agent_observability._file_exporter_fanout = adapter++ agent_observability.shutdown_agent_observability()++ assert inner.shutdown_calls == 1+ assert agent_observability._file_exporter_fanout is None+ assert agent_observability._agent_observability_active is False+ # Adapter short-circuit: spans ending after shutdown never reach the inner.+ adapter.on_end(object())+ assert inner.on_end_calls == 0+++def test_shutdown_fanout_not_gated_by_active_flag(monkeypatch):+ """An orphaned fan-out adapter (state inconsistency) must still be shut+ down — the cleanup sits before the ``_agent_observability_active`` gate."""+ adapter, inner = _make_real_adapter()+ monkeypatch.setattr(+ agent_observability, "shutdown_trajectory_runtime", lambda **kwargs: True+ )+ agent_observability._agent_observability_active = False+ agent_observability._file_exporter_fanout = adapter++ agent_observability.shutdown_agent_observability()++ assert inner.shutdown_calls == 1+ assert agent_observability._file_exporter_fanout is None+++def test_fanout_inner_shutdown_failure_keeps_reference_and_blocks_spans(monkeypatch):+ """The SafeSpanProcessor adapter latches _shutdown_called before the inner+ shutdown runs, so an inner failure still gates on_end — and shutdown()+ itself does not raise (failures are logged inside the adapter)."""+ adapter, inner = _make_real_adapter(fail=True)+ monkeypatch.setattr(+ agent_observability, "shutdown_trajectory_runtime", lambda **kwargs: True+ )+ monkeypatch.setattr(agent_observability, "release_observability", lambda: None)+ agent_observability._agent_observability_active = True+ agent_observability._file_exporter_fanout = adapter++ agent_observability.shutdown_agent_observability()++ assert inner.shutdown_calls == 1+ # Adapter latch flipped despite the inner failure: no further spans pass.+ adapter.on_end(object())+ assert inner.on_end_calls == 0+ # Adapter.shutdown() swallowed the failure, so the reference cleared normally.+ assert agent_observability._file_exporter_fanout is None+ assert agent_observability._agent_observability_active is False+++def test_fanout_holder_shutdown_failure_keeps_reference_and_release(monkeypatch):+ """Defensive path (holder is not the adapter): a raising shutdown keeps+ the reference so a later attach stays a no-op instead of stacking a second+ processor, and the shared provider release still proceeds."""+ broken = _BrokenFanout()+ released = []+ monkeypatch.setattr(+ agent_observability, "shutdown_trajectory_runtime", lambda **kwargs: True+ )+ monkeypatch.setattr(+ agent_observability, "release_observability", lambda: released.append(True)+ )+ agent_observability._agent_observability_active = True+ agent_observability._file_exporter_fanout = broken++ agent_observability.shutdown_agent_observability()++ assert broken.shutdown_calls == 1+ assert agent_observability._file_exporter_fanout is broken+ assert released == [True]+ assert agent_observability._agent_observability_active is False+++def test_attach_registers_the_safe_span_processor_adapter(monkeypatch, tmp_path):+ """_attach_file_exporter_fanout must register (and hold) the+ SafeSpanProcessor adapter on the global tracer provider — the same shape+ runtime.add_span_processors would register — never the bare inner+ BatchSpanProcessor (review CR-002)."""+ from jiuwenswarm.agents.harness import agent_observability as mod+ from openjiuwen.extensions.observability import runtime as obs_runtime+ from openjiuwen.extensions.observability import setup as obs_setup+ from openjiuwen.extensions.observability.file_exporter import TraceFileExporter++ registered = []++ class FakeProvider:+ def add_span_processor(self, processor):+ registered.append(processor)++ monkeypatch.setattr(obs_setup, "is_initialized", lambda: True)+ monkeypatch.setattr(+ "opentelemetry.trace.get_tracer_provider", lambda: FakeProvider()+ )+ monkeypatch.setattr(+ TraceFileExporter, "__init__",+ lambda self, root_dir, retention_days=7: None,+ )++ mod._file_exporter_fanout = None+ try:+ mod._attach_file_exporter_fanout(str(tmp_path / ".trace"), {})++ assert len(registered) == 1+ assert isinstance(registered[0], obs_runtime.SafeSpanProcessor)+ assert mod._file_exporter_fanout is registered[0]+ # Idempotent while attached: a second call must not register another.+ mod._attach_file_exporter_fanout(str(tmp_path / ".trace"), {})+ assert len(registered) == 1+ finally:+ holder = mod._file_exporter_fanout+ mod._file_exporter_fanout = None+ if holder is not None:+ holder.shutdown()diff --git a/tests/unit_tests/telemetry/test_enrichment_helpers.py b/tests/unit_tests/telemetry/test_enrichment_helpers.pyindex 33b21d32d4..042fc4776a 100644--- a/tests/unit_tests/telemetry/test_enrichment_helpers.py+++ b/tests/unit_tests/telemetry/test_enrichment_helpers.py@@ -444,7 +444,11 @@ def test_all_serializers_handle_unserializable_values_and_4096_limit() -> None:assert "<_Opaque>" in definitions-def test_tool_arguments_and_results_are_individually_limited_to_4096_chars() -> None:+def test_tool_arguments_and_results_follow_message_char_budget() -> None:+ """Tool single-item fields (result content / call arguments) share the+ message-level char budget instead of a fixed 4096 cap: with headroom the+ payload passes through untruncated, and a tighter budget truncates each+ item to the budget."""tool_result = json.loads(serialize_input_messages([{"role": "tool", "content": "r" * 5_000}], max_chars=10_000@@ -461,9 +465,27 @@ def test_tool_arguments_and_results_are_individually_limited_to_4096_chars() ->))- assert len(tool_result[0]["parts"][0]["content"]) == 4096- assert isinstance(output[0]["tool_calls"][0]["arguments"], str)- assert len(output[0]["tool_calls"][0]["arguments"]) == 4096+ # Headroom: neither item is truncated; the arguments dict is small enough+ # to fit the budget and is kept structured (see _bounded_value).+ assert len(tool_result[0]["parts"][0]["content"]) == 5_000+ assert output[0]["tool_calls"][0]["arguments"] == {"value": "a" * 5_000}++ tight_result = serialize_input_messages(+ [{"role": "tool", "content": "r" * 5_000}], max_chars=4_000+ )+ tight_output = serialize_output_message(+ {+ "tool_calls": [+ {"name": "tool", "arguments": {"value": "a" * 5_000}}+ ]+ },+ max_chars=4_000,+ )++ # Tight budget: the budget still caps the serialized output (best-effort+ # truncation, same assertion style as the fixed-budget test above).+ assert len(tight_result) == 4_000+ assert len(tight_output) == 4_000@pytest.mark.parametrize(