aidev-bkplugin 2.2.2rc58__tar.gz → 2.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/PKG-INFO +2 -2
  2. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/checkpoint/bk_django_saver.py +62 -8
  3. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_execution.py +2 -6
  4. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/approval_resume.py +15 -15
  5. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/chat_tracing.py +1 -0
  6. aidev_bkplugin-2.2.3/aidev_bkplugin/services/event_tracing.py +39 -0
  7. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/settings.py +4 -0
  8. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/pyproject.toml +2 -2
  9. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/database_events/test_tracing.py +3 -1
  10. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/packages/test_bk_django_saver.py +54 -2
  11. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/packages/test_bk_django_saver_async.py +19 -0
  12. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_approval_resume.py +9 -3
  13. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_approval_resume_tracing.py +25 -1
  14. aidev_bkplugin-2.2.3/tests/services/test_chat_tracing.py +23 -0
  15. aidev_bkplugin-2.2.3/tests/services/test_event_tracing.py +27 -0
  16. aidev_bkplugin-2.2.2rc58/aidev_bkplugin/services/event_tracing.py +0 -39
  17. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/__init__.py +0 -0
  18. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/apps.py +0 -0
  19. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/constants.py +0 -0
  20. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/enums.py +0 -0
  21. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/management/__init__.py +0 -0
  22. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/management/commands/__init__.py +0 -0
  23. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/management/commands/upgrade_sessions.py +0 -0
  24. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/migrations/0001_initial.py +0 -0
  25. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/migrations/0002_event_delivery.py +0 -0
  26. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/migrations/__init__.py +0 -0
  27. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/models.py +0 -0
  28. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/openapi/__init__.py +0 -0
  29. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/openapi/urls.py +0 -0
  30. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/openapi/views.py +0 -0
  31. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/__init__.py +0 -0
  32. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/apigw/__init__.py +0 -0
  33. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/apigw/permissions.py +0 -0
  34. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/checkpoint/__init__.py +0 -0
  35. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/drf/__init__.py +0 -0
  36. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/drf/authentication.py +0 -0
  37. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/drf/decorators.py +0 -0
  38. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/drf/exception.py +0 -0
  39. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/packages/drf/renderers.py +0 -0
  40. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/permissions.py +0 -0
  41. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/private/__init__.py +0 -0
  42. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/private/permissions.py +0 -0
  43. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/private/urls.py +0 -0
  44. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/private/views.py +0 -0
  45. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/serializers/__init__.py +0 -0
  46. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/serializers/agent.py +0 -0
  47. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/serializers/chat_completion.py +0 -0
  48. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/serializers/llm.py +0 -0
  49. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/serializers/user_operation.py +0 -0
  50. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/__init__.py +0 -0
  51. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_bkplugin.py +0 -0
  52. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_builder.py +0 -0
  53. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_config.py +0 -0
  54. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_helpers.py +0 -0
  55. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/agent_session.py +0 -0
  56. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/database_event_bus.py +0 -0
  57. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/event_resource_manager.py +0 -0
  58. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/execution.py +0 -0
  59. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/llm.py +0 -0
  60. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/metric_runtime.py +0 -0
  61. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/otel_metrics.py +0 -0
  62. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/services/user_operation.py +0 -0
  63. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/tasks.py +0 -0
  64. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/urls.py +0 -0
  65. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/utils.py +0 -0
  66. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/__init__.py +0 -0
  67. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/agent.py +0 -0
  68. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/base.py +0 -0
  69. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/chat.py +0 -0
  70. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/chat_group.py +0 -0
  71. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/flow_agent.py +0 -0
  72. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/llm.py +0 -0
  73. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/session.py +0 -0
  74. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/aidev_bkplugin/views/user_operation.py +0 -0
  75. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/readme.md +0 -0
  76. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/__init__.py +0 -0
  77. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/apps.py +0 -0
  78. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/conftest.py +0 -0
  79. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/database_events/__init__.py +0 -0
  80. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/database_events/conftest.py +0 -0
  81. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/database_events/test_bus.py +0 -0
  82. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/database_events/test_resource_manager.py +0 -0
  83. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/packages/__init__.py +0 -0
  84. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/packages/drf/test_renderers_trace.py +0 -0
  85. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/private/__init__.py +0 -0
  86. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/private/test_private_views.py +0 -0
  87. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/__init__.py +0 -0
  88. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/agent/__init__.py +0 -0
  89. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/agent/conftest.py +0 -0
  90. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/agent/test_agent_config_fetcher.py +0 -0
  91. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/agent/test_builder.py +0 -0
  92. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/agent/test_session_manager.py +0 -0
  93. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_agent_completion.py +0 -0
  94. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_agui_handler.py +0 -0
  95. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_bkplugin.py +0 -0
  96. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_execution.py +0 -0
  97. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_llm.py +0 -0
  98. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_otel_metrics.py +0 -0
  99. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_resume_consumer.py +0 -0
  100. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_thread_chat_completion.py +0 -0
  101. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/services/test_user_operation.py +0 -0
  102. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/settings.py +0 -0
  103. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/test_apps.py +0 -0
  104. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/test_constants.py +0 -0
  105. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/test_management_metrics.py +0 -0
  106. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/__init__.py +0 -0
  107. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_agent_view.py +0 -0
  108. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_chat_agent_code_propagation.py +0 -0
  109. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_chat_completion_serializer.py +0 -0
  110. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_chat_flow_agent.py +0 -0
  111. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_chat_stream_status.py +0 -0
  112. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_session_pv_files_views.py +0 -0
  113. {aidev_bkplugin-2.2.2rc58 → aidev_bkplugin-2.2.3}/tests/views/test_session_view.py +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: aidev-bkplugin
3
- Version: 2.2.2rc58
3
+ Version: 2.2.3
4
4
  Summary: AiDev Agent Bkplugin builtin functions
5
5
  Requires-Python: <3.12,>=3.11
6
- Requires-Dist: aidev-agent>=2.2.2rc58
6
+ Requires-Dist: aidev-agent>=2.2.3
7
7
  Requires-Dist: blueapps<5.0,>=4.15.1
8
8
  Requires-Dist: django<5.0,>=4.2.28
9
9
  Provides-Extra: opentelemetry
@@ -19,15 +19,17 @@ to the current version of the project delivered to anyone in the future.
19
19
  from __future__ import annotations
20
20
 
21
21
  import json
22
+ import logging
22
23
  import random
23
24
  import threading
24
25
  import time
25
26
  from collections.abc import AsyncIterator, Iterator, Sequence
26
- from contextlib import contextmanager
27
+ from contextlib import contextmanager, suppress
27
28
  from typing import Any, Callable, Optional, Tuple, cast
28
29
 
29
30
  from asgiref.sync import sync_to_async
30
- from django.db import OperationalError, close_old_connections, connections, router, transaction
31
+ from django.conf import settings
32
+ from django.db import InterfaceError, OperationalError, close_old_connections, connections, router, transaction
31
33
  from langchain_core.runnables import RunnableConfig
32
34
  from langgraph.checkpoint.base import (
33
35
  WRITES_IDX_MAP,
@@ -43,7 +45,11 @@ from langgraph.checkpoint.base import (
43
45
  from langgraph.checkpoint.serde.jsonplus import JsonPlusSerializer
44
46
  from langgraph.checkpoint.serde.types import ChannelProtocol
45
47
 
48
+ logger = logging.getLogger(__name__)
49
+
46
50
  RETRYABLE_DATABASE_ERROR_CODES = {1205, 1213}
51
+ # 服务端或中间代理关闭连接后,客户端要到下一次使用时才发现;语句本身没有问题,重建连接即可恢复。
52
+ CONNECTION_LOST_DATABASE_ERROR_CODES = {2006, 2013, 2055}
47
53
  CHECKPOINT_WRITE_MAX_RETRIES = 3
48
54
  CHECKPOINT_WRITE_RETRY_DELAY_SECONDS = 0.05
49
55
  _SQLITE_WRITE_LOCKS: dict[str, threading.RLock] = {}
@@ -69,23 +75,63 @@ def _database_write_lock(model):
69
75
  yield
70
76
 
71
77
 
72
- def _is_retryable_database_error(exc: OperationalError, model) -> bool:
78
+ def _is_connection_lost_error(exc: Exception) -> bool:
79
+ """判断异常是否来自已经失效的数据库连接。
80
+
81
+ ``InterfaceError`` 表示驱动层连接已不可用(例如 socket 已被置空),
82
+ ``CONNECTION_LOST_DATABASE_ERROR_CODES`` 表示连接在使用中被对端关闭。
83
+ """
84
+ if isinstance(exc, InterfaceError):
85
+ return True
86
+ error_code = exc.args[0] if exc.args else None
87
+ return error_code in CONNECTION_LOST_DATABASE_ERROR_CODES
88
+
89
+
90
+ def _is_retryable_database_error(exc: Exception, model) -> bool:
73
91
  error_code = exc.args[0] if exc.args else None
74
92
  if error_code in RETRYABLE_DATABASE_ERROR_CODES:
75
93
  return True
94
+ if _is_connection_lost_error(exc):
95
+ return True
76
96
  _, vendor = _database_vendor(model)
77
97
  return vendor == "sqlite" and "database is locked" in str(exc).lower()
78
98
 
79
99
 
80
- def _run_database_write_with_retry(operation: Callable[[], None], model) -> None:
100
+ def _discard_connection(model) -> None:
101
+ """丢弃写库当前线程持有的连接,确保重试不会复用同一个坏 socket。
102
+
103
+ 只靠 ``close_old_connections()`` 不够:它依赖 ``CONN_MAX_AGE`` 是否到期以及驱动 ping 的结果,
104
+ 而 pymysql 的 ``ping()`` 默认会自动重连并把连接判定为可用。
105
+ """
106
+ alias, _ = _database_vendor(model)
107
+ with suppress(Exception):
108
+ connections[alias].close()
109
+
110
+
111
+ def _is_best_effort_write() -> bool:
112
+ """连接持续不可用时,是否放弃本次写入而不是让整轮会话失败。"""
113
+ return bool(getattr(settings, "CHECKPOINT_WRITE_BEST_EFFORT", True))
114
+
115
+
116
+ def _run_database_write_with_retry(operation: Callable[[], None], model, description: str = "") -> None:
81
117
  for attempt in range(CHECKPOINT_WRITE_MAX_RETRIES):
82
118
  try:
83
119
  operation()
84
120
  return
85
- except OperationalError as exc:
121
+ except (OperationalError, InterfaceError) as exc:
122
+ connection_lost = _is_connection_lost_error(exc)
86
123
  exhausted = attempt == CHECKPOINT_WRITE_MAX_RETRIES - 1
87
- if not _is_retryable_database_error(exc, model) or exhausted:
124
+ if not _is_retryable_database_error(exc, model):
88
125
  raise
126
+ if exhausted:
127
+ if not (connection_lost and _is_best_effort_write()):
128
+ raise
129
+ # 推理结果由平台侧单独持久化,这里放弃写入只影响 interrupt / resume 的可恢复性,
130
+ # 比让已经产出回答的会话整体失败更可接受。
131
+ logger.exception("放弃 checkpoint 写入,数据库连接持续不可用:%s", description)
132
+ return
133
+ if connection_lost:
134
+ _discard_connection(model)
89
135
  close_old_connections()
90
136
  time.sleep(CHECKPOINT_WRITE_RETRY_DELAY_SECONDS * (2**attempt))
91
137
 
@@ -687,7 +733,11 @@ class BKDjangoSaver(BaseCheckpointSaver[str]):
687
733
 
688
734
  # SQLite 只允许单写者;跨 saver 实例串行本进程写入,MySQL 等数据库仍保持并行。
689
735
  with self.lock, _database_write_lock(self.checkpoint_model):
690
- _run_database_write_with_retry(save_checkpoint, self.checkpoint_model)
736
+ _run_database_write_with_retry(
737
+ save_checkpoint,
738
+ self.checkpoint_model,
739
+ f"checkpoint thread_id={thread_id} checkpoint_id={checkpoint['id']}",
740
+ )
691
741
 
692
742
  return {
693
743
  "configurable": {
@@ -750,7 +800,11 @@ class BKDjangoSaver(BaseCheckpointSaver[str]):
750
800
  )
751
801
 
752
802
  with self.lock, _database_write_lock(self.writes_model):
753
- _run_database_write_with_retry(save_writes, self.writes_model)
803
+ _run_database_write_with_retry(
804
+ save_writes,
805
+ self.writes_model,
806
+ f"writes thread_id={thread_id} checkpoint_id={checkpoint_id} task_id={task_id}",
807
+ )
754
808
 
755
809
  def delete_thread(self, thread_id: str) -> None:
756
810
  """删除与线程ID关联的所有检查点和写入记录
@@ -34,13 +34,9 @@ logger = getLogger(__name__)
34
34
 
35
35
 
36
36
  def build_execute_kwargs(_execute_kwargs: dict, username: str | None = None) -> ExecuteKwargs:
37
- """``dict`` → ``ExecuteKwargs``,并补齐 caller_/executor 等字段;按需注入 OTel trace context。"""
37
+ """``dict`` → ``ExecuteKwargs``,补齐 executor / caller_executor;按需注入 OTel trace context。"""
38
38
  execute_kwargs = ExecuteKwargs.model_validate(_execute_kwargs)
39
- execute_kwargs.caller_bk_biz_env = execute_kwargs.caller_bk_biz_env or "domestic_biz"
40
- execute_kwargs.caller_bk_app_code = execute_kwargs.caller_bk_app_code or "bkaidev"
41
- execute_kwargs.executor = execute_kwargs.executor or username or "anonymous"
42
- execute_kwargs.caller_executor = execute_kwargs.caller_executor or username or "anonymous"
43
- execute_kwargs.caller_order_type = execute_kwargs.caller_order_type or "ai_chat"
39
+ execute_kwargs.apply_session_caller_defaults(username or "anonymous")
44
40
  if not execute_kwargs.caller_trace_context and trace is not None:
45
41
  current_span = trace.get_current_span()
46
42
  if current_span is not None and current_span.get_span_context().is_valid:
@@ -14,12 +14,11 @@ import threading
14
14
  import time
15
15
  from logging import getLogger
16
16
 
17
- from aidev_agent.pydantic_models import ExecuteKwargs
18
17
  from aidev_agent.services.agent.approval import ApprovalStateHandler
19
18
  from aidev_agent.utils.tracing import propagated_trace_context, recording_span, trace_headers
20
19
 
21
20
  from aidev_bkplugin.services.agent_builder import AgentBuilder
22
- from aidev_bkplugin.services.agent_execution import AgentExecutor
21
+ from aidev_bkplugin.services.agent_execution import AgentExecutor, build_execute_kwargs
23
22
  from aidev_bkplugin.services.agent_session import SessionManager
24
23
 
25
24
  logger = getLogger(__name__)
@@ -96,7 +95,7 @@ def _approval_resume_worker(session_code: str, username: str, graph_thread_id: s
96
95
  # 上下文覆盖生成器构造和排空,保证延迟发布的恢复事件也关联到审批回调。
97
96
  with (
98
97
  propagated_trace_context(approve_info.get("approval_trace_context")),
99
- recording_span("bkplugin.approval.resume", record_exception=False),
98
+ recording_span("bkplugin.approval.resume", record_exception=False, use_global_tracer=True),
100
99
  ):
101
100
  _resume_approval(session_code, username, graph_thread_id, interrupts, approve_info)
102
101
 
@@ -156,18 +155,19 @@ def _resume_approval(
156
155
  builder = AgentBuilder(username=username)
157
156
  agent_instance = builder.by_session_code(session_code)
158
157
 
159
- execute_kwargs = ExecuteKwargs(
160
- stream=True,
161
- session_code=session_code,
162
- thread_id=graph_thread_id,
163
- resume=resume_items,
164
- caller_trace_context=trace_headers(),
165
- # 不传 executor:审批 approvers 来自工具审批配置(ItsmTicketCreator 读
166
- # target.approval.approvers),与调用人无关——提单人(username)不可成为
167
- # 审批身份(禁止自审批)。缺省时建单请求不带 X-BKAIDEV-USER 头。
168
- # 后台 drain(无 SSE 下游,下方 for _ in generator 自行排空):标记 background_only,
169
- # 使消费者读到 EOD 时不立即清理队列,保留缓存历史供前端在清理窗口内接管续流。
170
- background_only=True,
158
+ # 与 chat 一样走 build_execute_kwargs。executor / caller_bk_* 由 execute()
159
+ # 从 session.property.caller_context 回填;此处 username 只作空字段兜底。
160
+ # 审批人仍来自工具配置 target.approval.approvers。
161
+ execute_kwargs = build_execute_kwargs(
162
+ {
163
+ "stream": True,
164
+ "session_code": session_code,
165
+ "thread_id": graph_thread_id,
166
+ "resume": resume_items,
167
+ "caller_trace_context": trace_headers(),
168
+ "background_only": True,
169
+ },
170
+ username,
171
171
  )
172
172
 
173
173
  logger.info(
@@ -26,6 +26,7 @@ def chat_request_span(function):
26
26
  "bkplugin.chat.request",
27
27
  kind=SpanKind.INTERNAL if SpanKind else None,
28
28
  record_exception=False,
29
+ use_global_tracer=True,
29
30
  ),
30
31
  ):
31
32
  return function(self, request, *args, **kwargs)
@@ -0,0 +1,39 @@
1
+ """Durable event spans without message bodies, recipient identities or baggage."""
2
+
3
+ from contextlib import contextmanager
4
+
5
+ from aidev_agent.utils.tracing import propagated_trace_context, recording_span
6
+
7
+ try:
8
+ from opentelemetry.trace import SpanKind, StatusCode
9
+ except ImportError:
10
+ SpanKind = StatusCode = None
11
+
12
+
13
+ @contextmanager
14
+ def event_span(name: str, envelope: dict, *, producer: bool = False, attributes: dict | None = None):
15
+ value = envelope.get("value") or {}
16
+ kind = None
17
+ if SpanKind is not None:
18
+ kind = SpanKind.PRODUCER if producer else SpanKind.CONSUMER
19
+ with (
20
+ propagated_trace_context(value.get("traceContext")),
21
+ recording_span(
22
+ name,
23
+ kind=kind,
24
+ use_global_tracer=True,
25
+ record_exception=False,
26
+ attributes={
27
+ "messaging.system": "database",
28
+ "event.name": envelope.get("name", ""),
29
+ **(attributes or {}),
30
+ },
31
+ ) as span,
32
+ ):
33
+ try:
34
+ yield span
35
+ except Exception as error:
36
+ span.set_attribute("error.type", type(error).__name__)
37
+ if StatusCode is not None:
38
+ span.set_status(StatusCode.ERROR)
39
+ raise
@@ -16,6 +16,10 @@ AIDEV_AGENT_MAX_PENDING = int(os.environ.get("BKAPP_AIDEV_AGENT_MAX_PENDING", 32
16
16
  AIDEV_AGENT_CLEANUP_MAX_WORKERS = int(os.environ.get("BKAPP_AIDEV_AGENT_CLEANUP_MAX_WORKERS", 2))
17
17
  AIDEV_AGENT_CLEANUP_MAX_PENDING = int(os.environ.get("BKAPP_AIDEV_AGENT_CLEANUP_MAX_PENDING", 32))
18
18
 
19
+ # checkpoint 写入重试耗尽且连接仍不可用时,放弃本次写入而不是让整轮会话失败。
20
+ # 关闭后连接抖动会重新变成会话级错误,只在需要严格保证 interrupt / resume 可恢复时使用。
21
+ CHECKPOINT_WRITE_BEST_EFFORT = os.environ.get("BKAPP_CHECKPOINT_WRITE_BEST_EFFORT", "1") == "1"
22
+
19
23
  # 客服渠道
20
24
  CHAT_GROUP_ENABLED = os.environ.get("CHAT_GROUP_ENABLED") == "1"
21
25
  CHAT_GROUP_STAFF = os.environ.get("CHAT_GROUP_STAFF")
@@ -1,11 +1,11 @@
1
1
  [project]
2
2
  name = "aidev-bkplugin"
3
- version = "2.2.2rc58"
3
+ version = "2.2.3"
4
4
  description = "AiDev Agent Bkplugin builtin functions"
5
5
  readme = "readme.md"
6
6
  requires-python = "<3.12,>=3.11"
7
7
  dependencies = [
8
- "aidev-agent>=2.2.2rc58",
8
+ "aidev-agent>=2.2.3",
9
9
  "blueapps>=4.15.1, <5.0",
10
10
  "django>=4.2.28,<5.0",
11
11
  ]
@@ -10,7 +10,9 @@ def spans(monkeypatch):
10
10
  exporter = InMemorySpanExporter()
11
11
  provider = TracerProvider()
12
12
  provider.add_span_processor(SimpleSpanProcessor(exporter))
13
- monkeypatch.setattr(tracing, "_agent_tracer", provider.get_tracer("test"))
13
+ tracer = provider.get_tracer("test")
14
+ monkeypatch.setattr(tracing, "_agent_tracer", tracer)
15
+ monkeypatch.setattr(tracing.trace, "get_tracer", lambda _: tracer)
14
16
  yield exporter
15
17
  provider.shutdown()
16
18
 
@@ -4,7 +4,7 @@ import threading
4
4
 
5
5
  import pytest
6
6
  from aidev_bkplugin.packages.checkpoint.bk_django_saver import BKDjangoSaver, _database_write_lock, bulk_upsert
7
- from django.db import OperationalError, connection, models
7
+ from django.db import InterfaceError, OperationalError, connection, models
8
8
 
9
9
 
10
10
  class WriteForTest(models.Model):
@@ -59,7 +59,7 @@ def test_put_retries_transient_database_lock_error(mocker, saver, checkpoint_arg
59
59
 
60
60
 
61
61
  def test_put_does_not_retry_other_database_error(mocker, saver, checkpoint_args):
62
- error = OperationalError(2006, "server has gone away")
62
+ error = OperationalError(1146, "table doesn't exist")
63
63
  saver.checkpoint_model.objects.update_or_create.side_effect = error
64
64
  sleep = mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.time.sleep")
65
65
 
@@ -71,6 +71,58 @@ def test_put_does_not_retry_other_database_error(mocker, saver, checkpoint_args)
71
71
  sleep.assert_not_called()
72
72
 
73
73
 
74
+ @pytest.mark.parametrize(
75
+ "error",
76
+ [
77
+ OperationalError(2013, "Lost connection to MySQL server during query"),
78
+ OperationalError(2006, "MySQL server has gone away"),
79
+ InterfaceError(0, ""),
80
+ ],
81
+ )
82
+ def test_put_retries_lost_database_connection(mocker, saver, checkpoint_args, error):
83
+ saver.checkpoint_model.objects.update_or_create.side_effect = [error, (mocker.Mock(), True)]
84
+ connections = mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.connections")
85
+ close_old_connections = mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.close_old_connections")
86
+ sleep = mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.time.sleep")
87
+
88
+ saver.put(*checkpoint_args)
89
+
90
+ assert saver.checkpoint_model.objects.update_or_create.call_count == 2
91
+ # 失效连接必须被显式关闭,否则重试会继续复用同一个坏 socket
92
+ connections.__getitem__.return_value.close.assert_called_once_with()
93
+ close_old_connections.assert_called_once_with()
94
+ sleep.assert_called_once_with(0.05)
95
+
96
+
97
+ def test_put_gives_up_when_database_connection_stays_unavailable(mocker, saver, checkpoint_args):
98
+ saver.checkpoint_model.objects.update_or_create.side_effect = OperationalError(2013, "lost connection")
99
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.connections")
100
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.close_old_connections")
101
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.time.sleep")
102
+ logger = mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.logger")
103
+
104
+ saved = saver.put(*checkpoint_args)
105
+
106
+ assert saved["configurable"]["checkpoint_id"] == "checkpoint-id"
107
+ assert saver.checkpoint_model.objects.update_or_create.call_count == 3
108
+ logger.exception.assert_called_once()
109
+
110
+
111
+ def test_put_raises_lost_connection_when_best_effort_disabled(mocker, saver, checkpoint_args, settings):
112
+ settings.CHECKPOINT_WRITE_BEST_EFFORT = False
113
+ error = OperationalError(2013, "lost connection")
114
+ saver.checkpoint_model.objects.update_or_create.side_effect = error
115
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.connections")
116
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.close_old_connections")
117
+ mocker.patch("aidev_bkplugin.packages.checkpoint.bk_django_saver.time.sleep")
118
+
119
+ with pytest.raises(OperationalError) as exc_info:
120
+ saver.put(*checkpoint_args)
121
+
122
+ assert exc_info.value is error
123
+ assert saver.checkpoint_model.objects.update_or_create.call_count == 3
124
+
125
+
74
126
  def test_put_raises_after_database_lock_retries_exhausted(mocker, saver, checkpoint_args):
75
127
  error = OperationalError(1213, "deadlock")
76
128
  saver.checkpoint_model.objects.update_or_create.side_effect = error
@@ -17,6 +17,7 @@ import uuid
17
17
  import pytest
18
18
  from aidev_bkplugin.models import Checkpoint, Write
19
19
  from aidev_bkplugin.packages.checkpoint.bk_django_saver import BKDjangoSaver
20
+ from django.db import OperationalError
20
21
  from langgraph.checkpoint.base import empty_checkpoint
21
22
 
22
23
  # transaction=True:a* 方法在别的线程/连接里读写,数据必须真实提交才可见
@@ -63,6 +64,24 @@ async def test_aget_tuple_returns_none_for_unknown_thread(saver, thread_id):
63
64
  assert await saver.aget_tuple(_config(thread_id)) is None
64
65
 
65
66
 
67
+ async def test_aput_recovers_from_lost_database_connection(mocker, saver, thread_id):
68
+ """连接中断只应触发重建连接后的重试,不能让已经完成推理的会话失败。"""
69
+ config = _config(thread_id)
70
+ checkpoint = empty_checkpoint()
71
+ update_or_create = mocker.patch.object(
72
+ Checkpoint.objects,
73
+ "update_or_create",
74
+ wraps=Checkpoint.objects.update_or_create,
75
+ side_effect=[OperationalError(2013, "Lost connection to MySQL server during query"), mocker.DEFAULT],
76
+ )
77
+
78
+ saved = await saver.aput(config, checkpoint, {"source": "input"}, {})
79
+
80
+ assert update_or_create.call_count == 2
81
+ assert saved["configurable"]["checkpoint_id"] == checkpoint["id"]
82
+ assert await Checkpoint.objects.filter(thread_id=thread_id).acount() == 1
83
+
84
+
66
85
  async def test_aput_writes_are_visible_through_aget_tuple(saver, thread_id):
67
86
  saved = await saver.aput(_config(thread_id), empty_checkpoint(), {}, {})
68
87
 
@@ -18,8 +18,14 @@ def test_polling_does_not_duplicate_explicit_cancellation(monkeypatch, status):
18
18
  monkeypatch.setattr(mod, "AgentBuilder", builder)
19
19
  monkeypatch.setattr(mod, "AgentExecutor", executor)
20
20
  monkeypatch.setattr(mod, "SessionManager", MagicMock())
21
- mod._approval_resume_worker(
22
- "session-1", "alice", "graph-1", [{"id": "approval-1", "reason": "aidev:tool_approval"}]
23
- )
21
+ mod._approval_resume_worker("session-1", "user", "graph-1", [{"id": "approval-1", "reason": "aidev:tool_approval"}])
24
22
  assert builder.call_count == (0 if status == "cancelled" else 1)
25
23
  assert executor.return_value.execute_with_save.call_count == (0 if status == "cancelled" else 1)
24
+ if status == "cancelled":
25
+ return
26
+ kwargs = executor.return_value.execute_with_save.call_args.args[1]
27
+ assert kwargs.caller_bk_app_code is None
28
+ assert kwargs.caller_bk_biz_env is None
29
+ assert kwargs.caller_order_type is None
30
+ assert kwargs.executor == "user"
31
+ assert kwargs.caller_executor == "user"
@@ -16,7 +16,9 @@ def resume_case(monkeypatch):
16
16
  exporter = InMemorySpanExporter()
17
17
  provider = TracerProvider()
18
18
  provider.add_span_processor(SimpleSpanProcessor(exporter))
19
- monkeypatch.setattr(tracing, "_agent_tracer", provider.get_tracer("test"))
19
+ tracer = provider.get_tracer("test")
20
+ monkeypatch.setattr(tracing, "_agent_tracer", tracer)
21
+ monkeypatch.setattr(tracing.trace, "get_tracer", lambda _: tracer)
20
22
  monkeypatch.setattr(ApprovalStateHandler, "check_resume", lambda *_: True)
21
23
  monkeypatch.setattr(approval_resume, "AgentBuilder", MagicMock())
22
24
  executor = MagicMock()
@@ -57,3 +59,25 @@ def test_approval_reader_keeps_callback_context_from_same_record(monkeypatch, ne
57
59
  ApprovalStateHandler().fetch_approve_result("session")["approval_trace_context"]
58
60
  == fields["approval_trace_context"]
59
61
  )
62
+
63
+
64
+ def test_approval_resume_span_uses_application_service_name(resume_case, monkeypatch):
65
+ from opentelemetry.sdk.resources import Resource
66
+
67
+ exporter, _ = resume_case
68
+ module_exporter = InMemorySpanExporter()
69
+ module_provider = TracerProvider(resource=Resource.create({"service.name": "ai-skill-stag-default"}))
70
+ module_provider.add_span_processor(SimpleSpanProcessor(module_exporter))
71
+ monkeypatch.setattr(tracing.trace, "get_tracer", lambda _: module_provider.get_tracer("module"))
72
+ monkeypatch.setattr(
73
+ ApprovalStateHandler,
74
+ "_get_latest_interrupt_record",
75
+ lambda *_: {"property": {"builtin_property": {"approve_result": "approved"}}},
76
+ )
77
+ try:
78
+ approval_resume._approval_resume_worker("session", "author", "thread", [{"id": "approval"}])
79
+ resumed = next(span for span in module_exporter.get_finished_spans() if span.name == "bkplugin.approval.resume")
80
+ assert resumed.resource.attributes["service.name"] == "ai-skill-stag-default"
81
+ assert not any(span.name == "bkplugin.approval.resume" for span in exporter.get_finished_spans())
82
+ finally:
83
+ module_provider.shutdown()
@@ -0,0 +1,23 @@
1
+ from unittest.mock import MagicMock, patch
2
+
3
+ from aidev_bkplugin.services import chat_tracing
4
+
5
+
6
+ def test_chat_request_span_uses_application_module_tracer():
7
+ view = MagicMock()
8
+ request = MagicMock(headers={})
9
+ handler = MagicMock(return_value="response")
10
+
11
+ with (
12
+ patch("aidev_bkplugin.services.chat_tracing.trace_headers", return_value={"traceparent": "active"}),
13
+ patch("aidev_bkplugin.services.chat_tracing.recording_span") as recording_span,
14
+ ):
15
+ result = chat_tracing.chat_request_span(handler)(view, request)
16
+
17
+ assert result == "response"
18
+ recording_span.assert_called_once_with(
19
+ "bkplugin.chat.request",
20
+ kind=chat_tracing.SpanKind.INTERNAL if chat_tracing.SpanKind else None,
21
+ record_exception=False,
22
+ use_global_tracer=True,
23
+ )
@@ -0,0 +1,27 @@
1
+ from aidev_agent.utils import tracing
2
+ from aidev_bkplugin.services.event_tracing import event_span
3
+ from opentelemetry.sdk.resources import Resource
4
+ from opentelemetry.sdk.trace import TracerProvider
5
+ from opentelemetry.sdk.trace.export import SimpleSpanProcessor
6
+ from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
7
+
8
+
9
+ def test_event_span_uses_application_service_name(monkeypatch):
10
+ agent_exporter = InMemorySpanExporter()
11
+ module_exporter = InMemorySpanExporter()
12
+ agent_provider = TracerProvider(resource=Resource.create({"service.name": "ai-skill-stag"}))
13
+ module_provider = TracerProvider(resource=Resource.create({"service.name": "ai-skill-stag-default"}))
14
+ agent_provider.add_span_processor(SimpleSpanProcessor(agent_exporter))
15
+ module_provider.add_span_processor(SimpleSpanProcessor(module_exporter))
16
+ monkeypatch.setattr(tracing, "_agent_tracer", agent_provider.get_tracer("agent"))
17
+ monkeypatch.setattr(tracing.trace, "get_tracer", lambda _: module_provider.get_tracer("module"))
18
+ try:
19
+ with event_span("database_event.publish", {"name": "AIDEV_CHAT_RESUME_READY"}, producer=True):
20
+ pass
21
+ published = module_exporter.get_finished_spans()[0]
22
+ assert published.name == "database_event.publish"
23
+ assert published.resource.attributes["service.name"] == "ai-skill-stag-default"
24
+ assert not agent_exporter.get_finished_spans()
25
+ finally:
26
+ agent_provider.shutdown()
27
+ module_provider.shutdown()
@@ -1,39 +0,0 @@
1
- """Durable event spans without message bodies, recipient identities or baggage."""
2
-
3
- from contextlib import contextmanager
4
-
5
- from aidev_agent.utils.tracing import get_agent_tracer, propagated_trace_context
6
-
7
- try:
8
- from opentelemetry.trace import SpanKind, StatusCode
9
- except ImportError:
10
- SpanKind = StatusCode = None
11
-
12
-
13
- @contextmanager
14
- def event_span(name: str, envelope: dict, *, producer: bool = False, attributes: dict | None = None):
15
- value = envelope.get("value") or {}
16
- with propagated_trace_context(value.get("traceContext")):
17
- tracer = get_agent_tracer(__name__)
18
- if tracer is None:
19
- yield None
20
- return
21
- options = {
22
- "attributes": {
23
- "messaging.system": "database",
24
- "event.name": envelope.get("name", ""),
25
- **(attributes or {}),
26
- },
27
- "record_exception": False,
28
- "set_status_on_exception": False,
29
- }
30
- if SpanKind is not None:
31
- options["kind"] = SpanKind.PRODUCER if producer else SpanKind.CONSUMER
32
- with tracer.start_as_current_span(name, **options) as span:
33
- try:
34
- yield span
35
- except Exception as error:
36
- span.set_attribute("error.type", type(error).__name__)
37
- if StatusCode is not None:
38
- span.set_status(StatusCode.ERROR)
39
- raise