Skip to content

The agent that grows with you

refactor(data-use): carry the requirement on the dispatch result, not a global store

Siddharth Balyan086984caf576
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index 5209cbf477c..cb58137a2ac 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -473,6 +473,7 @@ class _ManagedToolResult:
middleware_trace: list[dict[str, Any]]
blocked: bool
dispatched: bool
+ data_use: frozenset[str] = frozenset()
class _ToolTimeoutResult(str):
@@ -751,8 +752,12 @@ def _dispatch_authorized_once(
prepare_current_terminal(ref)
_advance_start_order(lambda: _begin_tool_execution(agent, ref, display_index))
from agent.tool_progress_relay import bound_tool_progress
- with bound_tool_progress(agent.tool_progress_callback, ref.name, ref.call_id):
- return _run_with_activity_heartbeat(agent, ref.name, lambda: execute(ref.args))
+ from tools.connectors.data_use import collect_data_use
+ with bound_tool_progress(agent.tool_progress_callback, ref.name, ref.call_id), collect_data_use() as data_use:
+ try:
+ return _run_with_activity_heartbeat(agent, ref.name, lambda: execute(ref.args))
+ finally:
+ state.data_use = frozenset(data_use)
def _run_agent_tool_execution_middleware(
@@ -1076,6 +1081,7 @@ def _commit_tool_result(
blocked: bool,
effect_disposition,
observed: bool = False,
+ data_use: frozenset[str] = frozenset(),
error_preview: Callable[[Any], Any] = lambda result: result,
success_log_chars: Optional[int] = None,
verbose_text: Callable[[Any], Any] = lambda result: result,
@@ -1162,8 +1168,7 @@ def _commit_tool_result(
tool_message["display_metadata"] = metadata
except Exception as callback_error:
logging.debug("Tool result metadata callback error: %s", callback_error)
- from tools.connectors.data_use import take_data_use
- stamp_data_use(tool_message, take_data_use(getattr(agent, "_current_turn_id", "") or "", tool_call_id))
+ stamp_data_use(tool_message, sorted(data_use))
messages.append(tool_message)
if not _flush_session_db_after_tool_progress(agent, messages, stage=f"tool result {function_name}"):
return None
@@ -1253,6 +1258,7 @@ class _ToolOutcome:
duration: float
is_error: bool
blocked: bool
+ data_use: frozenset[str] = frozenset()
def _start_order_gate_timeout(batch_timeout: float | None) -> float:
@@ -1345,6 +1351,7 @@ class _ConcurrentBatch:
# propagate_context_to_thread() at the submit site below (GHSA-qg5c-hvr5-hjgr, #13617).
start = time.time()
blocked = dispatched = False
+ data_use: frozenset[str] = frozenset()
try:
managed = _run_agent_tool_execution_middleware(
agent,
@@ -1363,7 +1370,7 @@ class _ConcurrentBatch:
authorization_gate=self.authorization_gate,
)
result, ref.args, ref.trace = managed.result, managed.args, managed.middleware_trace
- blocked, dispatched = managed.blocked, managed.dispatched
+ blocked, dispatched, data_use = managed.blocked, managed.dispatched, managed.data_use
except _BatchAbandoned:
logger.info("tool %s abandoned at start-order gate; skipping dispatch", ref.name)
return None
@@ -1388,7 +1395,7 @@ class _ConcurrentBatch:
logger.info(
"tool %s completed (%.2fs, %d chars)", ref.name, duration, result_chars
)
- return _ToolOutcome(ref, result, duration, is_error, blocked)
+ return _ToolOutcome(ref, result, duration, is_error, blocked, data_use)
def run_worker(self, index: int, start_order: int) -> None:
"""Worker function executed in a thread."""
@@ -1558,7 +1565,7 @@ def _append_batch_results(agent, messages: list, effective_task_id: str, batch:
committed = _commit_tool_result(
agent, messages, ref, function_result,
budget=budget, tool_duration=tool_duration, is_error=is_error, blocked=blocked,
- effect_disposition=effect_disposition, observed=r is not None,
+ effect_disposition=effect_disposition, observed=r is not None, data_use=r.data_use if r else frozenset(),
error_preview=lambda res: _multimodal_text_summary(res)[:200],
)
if committed is None:
@@ -1833,7 +1840,7 @@ def _publish_sequential_result(agent, messages: list, ref: _ToolCallRef, managed
committed = _commit_tool_result(
agent, messages, ref, function_result,
budget=budget, tool_duration=tool_duration, is_error=_is_error_result, blocked=managed.blocked,
- effect_disposition="unknown" if _execution_timed_out else None, observed=True,
+ effect_disposition="unknown" if _execution_timed_out else None, observed=True, data_use=managed.data_use,
error_preview=lambda res: res[:200] if isinstance(res, str) and not agent.verbose_logging else res,
success_log_chars=_result_len,
verbose_text=_multimodal_text_summary,
diff --git a/tests/agent/test_tool_call_incremental_persistence.py b/tests/agent/test_tool_call_incremental_persistence.py
index 9e10dc624c0..141a325745c 100644
--- a/tests/agent/test_tool_call_incremental_persistence.py
+++ b/tests/agent/test_tool_call_incremental_persistence.py
@@ -502,28 +502,28 @@ def test_tool_result_is_durable_before_ui_completion_on_abnormal_exit(
assert durable[2]["content"] == "repository result"
-def test_connector_data_use_rides_the_tool_message_and_survives_a_reload(tmp_path):
- """The requirement dispatch recorded lands on the tool message as metadata (content untouched)
[email protected]("executor_mode", ["sequential", "concurrent"])
+def test_connector_data_use_rides_the_tool_message_and_survives_a_reload(tmp_path, executor_mode):
+ """A requirement recorded during dispatch lands on the tool message as metadata (content untouched)
and comes back from the session DB on resume."""
from tools.connectors.data_use import record_data_use
agent = _make_agent()
db_path = tmp_path / "state.db"
db = _attach_real_session_db(agent, db_path, "data-use")
- agent._current_turn_id = "turn-1"
messages = [{"role": "user", "content": "read my mail"},
{"role": "assistant", "content": "", "tool_calls": [
{"id": "mail-call", "type": "function", "function": {"name": "web_search", "arguments": "{}"}}]}]
agent._flush_messages_to_session_db(messages)
def _dispatch(name, args, task_id, **kwargs):
- record_data_use(kwargs["turn_id"], kwargs["tool_call_id"], ["no_training"])
+ record_data_use(["no_training"])
return '{"results": [{"response": "inbox"}]}'
try:
with (patch("model_tools.handle_function_call", side_effect=_dispatch),
patch("agent.tool_executor.maybe_persist_tool_result", side_effect=lambda **kw: kw["content"])):
- agent._execute_tool_calls_sequential(
+ getattr(agent, f"_execute_tool_calls_{executor_mode}")(
SimpleNamespace(content="", tool_calls=[_mock_tool_call(call_id="mail-call")]), messages, "task-1")
finally:
db.close()
diff --git a/tests/tools/test_connector_dispatch_policy.py b/tests/tools/test_connector_dispatch_policy.py
index d3b496108a0..bd912697dfa 100644
--- a/tests/tools/test_connector_dispatch_policy.py
+++ b/tests/tools/test_connector_dispatch_policy.py
@@ -123,9 +123,9 @@ def test_disabled_connections_cannot_be_called_through_a_stale_schema(monkeypatc
assert "not available" in result["error"]
-def test_a_connector_batch_records_the_union_of_data_use_and_keeps_it_out_of_the_result(monkeypatch):
+def test_a_connector_batch_collects_the_union_of_data_use_and_keeps_it_out_of_the_result(monkeypatch):
import model_tools
- from tools.connectors import take_data_use
+ from tools.connectors.data_use import collect_data_use
from tools.connectors.gateway import bridge, config
from tools.registry import invalidate_check_fn_cache
@@ -141,11 +141,12 @@ def test_a_connector_batch_records_the_union_of_data_use_and_keeps_it_out_of_the
monkeypatch.setattr(bridge, "_default_client_factory", lambda call=None: Client())
calls = [{"name": f"connectors__{c}__READ", "arguments": {}} for c in requires]
- raw = model_tools.handle_function_call(
- "tool_call", {"calls": calls}, enabled_toolsets=["connections"], session_id="s", tool_call_id="batch-1",
- turn_id="turn-1", skip_pre_tool_call_hook=True, skip_tool_request_middleware=True,
- skip_tool_execution_middleware=True)
+ with collect_data_use() as data_use:
+ raw = model_tools.handle_function_call(
+ "tool_call", {"calls": calls}, enabled_toolsets=["connections"], session_id="s", tool_call_id="batch-1",
+ turn_id="turn-1", skip_pre_tool_call_hook=True, skip_tool_request_middleware=True,
+ skip_tool_execution_middleware=True)
assert "data_use" not in raw
assert [r["response"] for r in json.loads(raw)["results"]] == ["row", "row", "row"]
- assert take_data_use("turn-1", "batch-1") == ["no_training", "zero_retention"]
+ assert data_use == {"no_training", "zero_retention"}
diff --git a/tools/connectors/__init__.py b/tools/connectors/__init__.py
index 379c65e4d36..51f4ce054b2 100644
--- a/tools/connectors/__init__.py
+++ b/tools/connectors/__init__.py
@@ -23,7 +23,6 @@ _LAZY_EXPORTS: dict[str, str] = {
"ensure_guest_identity": "tools.connectors.gateway.config",
"guest_identity_pending": "tools.connectors.gateway.config",
"is_connector_name": "tools.connectors.gateway.names",
- "take_data_use": "tools.connectors.data_use",
"manage_connections": "tools.connectors.tool",
}
diff --git a/tools/connectors/data_use.py b/tools/connectors/data_use.py
index 5cb706bb1f0..6f312510239 100644
--- a/tools/connectors/data_use.py
+++ b/tools/connectors/data_use.py
@@ -1,35 +1,30 @@
-"""Data-use requirements of connector results, handed from dispatch to the tool message.
+"""Data-use requirements of connector results, collected while one tool call dispatches.
-The result string the model reads never carries them: dispatch records the requirement here under the
-call's ``(turn_id, tool_call_id)`` and the agent's tool executor takes it when it builds the tool message,
-storing it as that message's ``data_use`` metadata (``agent.message_metadata.DATA_USE``).
+The executor binds a sink around each dispatch and connector dispatch adds to it, so a batch's entries
+union into the wrapper's sink and the requirement never rides the model-visible result string.
"""
from __future__ import annotations
-import threading
-from typing import Iterable, Optional
+import contextlib
+import contextvars
+from typing import Iterable, Iterator, Optional
-_LOCK = threading.Lock()
-_PENDING: dict[tuple[str, str], frozenset[str]] = {}
-# Callers outside the agent's tool executor (execute_code RPC, MCP serve) never take; keep that bounded.
-_MAX_PENDING = 512
+_sink: contextvars.ContextVar[Optional[set[str]]] = contextvars.ContextVar("connector_data_use", default=None)
-def record_data_use(turn_id: Optional[str], tool_call_id: Optional[str], requires: Iterable[str]) -> None:
- wanted = frozenset(requires)
- if not tool_call_id or not wanted:
- return
- with _LOCK:
- key = (turn_id or "", tool_call_id)
- _PENDING[key] = _PENDING.pop(key, frozenset()) | wanted
- while len(_PENDING) > _MAX_PENDING:
- _PENDING.pop(next(iter(_PENDING)))
+def collect_data_use() -> Iterator[set[str]]:
+ sink: set[str] = set()
+ token = _sink.set(sink)
+ try:
+ yield sink
+ finally:
+ _sink.reset(token)
-def take_data_use(turn_id: Optional[str], tool_call_id: Optional[str]) -> list[str]:
- """The requirement recorded for this call (sorted), removing it; ``[]`` when none was recorded."""
- if not tool_call_id:
- return []
- with _LOCK:
- return sorted(_PENDING.pop((turn_id or "", tool_call_id), ()))
+def record_data_use(requires: Iterable[str]) -> None:
+ """No-op outside an agent dispatch (execute_code RPC, MCP serve): no message is built there."""
+ sink = _sink.get()
+ if sink is not None:
+ sink.update(requires)
diff --git a/tools/connectors/dispatch.py b/tools/connectors/dispatch.py
index 9e52d41ef6c..6dc225f4f53 100644
--- a/tools/connectors/dispatch.py
+++ b/tools/connectors/dispatch.py
@@ -16,7 +16,7 @@ def dispatch_connector_call(name, arguments, tool_call_id, turn_id=None, task_id
entries = run_remote(partition.remote, tool_call_id, availability=None, client_factory=None, turn_id=turn_id,
task_id=task_id)
entry = entries[0]
- record_data_use(turn_id, tool_call_id, entry.get("data_use") or ())
+ record_data_use(entry.get("data_use") or ())
return json.dumps({key: value for key, value in entry.items() if key in {"response", "error", "account"}},
ensure_ascii=False)
@@ -26,7 +26,6 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,
from dataclasses import replace
from model_tools import handle_function_call, suppress_post_tool_call_hook
- from tools.connectors.data_use import record_data_use, take_data_use
from tools.interrupt import is_interrupted
if len(calls) > MAX_CALLS_PER_DISPATCH:
@@ -37,7 +36,6 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,
from tools.tool_search_validation import local_batch_error
return tool_error(local_batch_error(calls))
entries = list(partition.errors)
- requires: set[str] = set()
for offset, plan in enumerate(partition.remote):
if is_interrupted():
# Check before every entry so /stop prevents unstarted remote side effects.
@@ -56,8 +54,6 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,
skip_tool_execution_middleware=False,
enabled_toolsets=enabled_toolsets, disabled_toolsets=disabled_toolsets,
)
- # The batch is one tool message: it carries the union of its entries' requirements.
- requires.update(take_data_use(entry_ids.turn_id, entry_ids.tool_call_id))
try:
value = json.loads(payload) if isinstance(payload, str) else payload
except ValueError:
@@ -71,5 +67,4 @@ def dispatch_connector_batch(calls, ids, *, user_task, enabled_tools,
if isinstance(value, dict) and value.get("account"):
entry["account"] = value["account"]
entries.append(entry)
- record_data_use(ids.turn_id, ids.tool_call_id, requires)
return json.dumps(assemble_results(len(calls), entries), ensure_ascii=False)