crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] The default executor reports a cached native tool call as a live one

Open chrikrah opened this issue 2 months ago • 5 comments

Description

ToolUsageFinishedEvent carries a from_cache flag (events/types/tool_usage_events.py:68) so an observer can tell a replayed tool result from a live tool run. On the two native function-calling paths that a default agent runs, the code computes the flag and then does not pass it to the event. It falls back to its False default.

Agent.executor_class defaults to experimental.agent_executor.AgentExecutor (agent/core.py:397). CrewAgentExecutor is deprecated (agent/core.py:171-176). Both affected paths belong to the default:

  • AgentExecutor._execute_single_native_tool_call sets from_cache = True on a cache hit (experimental/agent_executor.py:2039) and returns it (:2184). The ToolUsageFinishedEvent it emits at experimental/agent_executor.py:2148 has no from_cache argument.
  • agent_utils.execute_single_native_tool_call, which StepExecutor uses for plan-and-execute steps, sets the flag at utilities/agent_utils.py:1744 and returns it at :1908. The event at utilities/agent_utils.py:1845 omits it.

The deprecated CrewAgentExecutor does pass the flag (agents/crew_agent_executor.py:1059, from #7501). So does the text-protocol path in tools/tool_usage.py.

Two consumers then report the wrong thing. Tracing turns the flag into the crewai.tool.from_cache span attribute (telemetry/tracing/handlers.py:1428). The CLI run view reads it at lib/cli/src/crewai_cli/crew_run_tui.py:2364.

The tool result stays correct. Only the reported provenance of that result is wrong, which makes a cached run and a live run look identical in a trace.

Steps to Reproduce

  1. Save the snippet under Screenshots/Code snippets as probe.py.
  2. Run python probe.py.
  3. Compare the event.from_cache line of the live call with the cached call.

Expected behavior

A tool call whose body the cache answered emits ToolUsageFinishedEvent(from_cache=True), so crewai.tool.from_cache is True on the span and the CLI marks the step as cached. A tool call that really ran emits from_cache=False. An observer can tell the two apart, as it already can on CrewAgentExecutor and on the text-protocol path.

Screenshots/Code snippets

"""Does the default executor say `from_cache` on a replayed native call?"""

import json
import os

os.environ.setdefault("OPENAI_API_KEY", "unused-by-this-probe")

from crewai import Agent
from crewai.agents.cache.cache_handler import CacheHandler
from crewai.agents.tools_handler import ToolsHandler
from crewai.events import crewai_event_bus
from crewai.events.types.tool_usage_events import ToolUsageFinishedEvent
from crewai.experimental.agent_executor import AgentExecutor
from crewai.telemetry.tracing import semantic_conventions
from crewai.tools.base_tool import BaseTool, to_langchain

CALLS = []


class LookupTool(BaseTool):
    name: str = "lookup"
    description: str = "Look a term up."

    def _run(self, term: str) -> str:
        CALLS.append(term)
        return f"value:{term}"


class ToolCall:
    """OpenAI-style native tool call."""

    class _Fn:
        def __init__(self, name, arguments):
            self.name = name
            self.arguments = arguments

    def __init__(self, call_id, name, arguments):
        self.id = call_id
        self.function = self._Fn(name, json.dumps(arguments))


def run(tool, cache, term):
    agent = Agent(role="tester", goal="Answer", backstory="You answer.", llm="gpt-4o")
    print("executor_class:", agent.executor_class.__module__)
    executor = AgentExecutor(
        agent=agent,
        llm=agent.llm,
        task=None,
        tools=to_langchain([tool]),
        original_tools=[tool],
    )
    executor.tools_handler = ToolsHandler(cache=cache)
    executor._setup_native_tools()

    events = []
    with crewai_event_bus.scoped_handlers():

        @crewai_event_bus.on(ToolUsageFinishedEvent)
        def _capture(_source, event):
            events.append(event)

        result = executor._execute_single_native_tool_call(
            ToolCall("call_1", "lookup", {"term": term})
        )
        crewai_event_bus.flush()
    return result, events


def report(label, result, events):
    print(f"{label}:")
    print(f"  tool body ran       = {CALLS}")
    print(f"  returned from_cache = {result['from_cache']}")
    print(f"  event.from_cache    = {events[0].from_cache}")
    attrs = semantic_conventions.crewai_tool(from_cache=events[0].from_cache)
    print(f"  span attribute      = crewai.tool.from_cache={attrs['crewai.tool.from_cache']}")


tool = LookupTool()

CALLS.clear()
report("LIVE call", *run(tool, CacheHandler(), "y"))

cache = CacheHandler()
cache.add(tool="lookup", input=json.dumps({"term": "x"}), output="cached:x")
CALLS.clear()
print()
report("CACHED call (tool body skipped)", *run(tool, cache, "x"))

Operating System

Ubuntu 24.04

Python Version

3.12

The dropdown stops at 3.12. The run below used 3.13.15, inside the 3.10-3.14 range that .github/CONTRIBUTING.md declares and that the type-checker CI matrix covers. A missing keyword argument does not depend on the version.

crewAI Version

1.15.22, repository main at commit 4ed2abc.

crewAI Tools Version

1.15.22

Virtual Environment

Venv

The environment is the uv sync --all-groups --all-extras venv from .github/CONTRIBUTING.md. The dropdown has no uv option, and uv creates a standard venv at .venv.

Evidence

Observed, from the snippet above:

executor_class: crewai.experimental.agent_executor
LIVE call:
  tool body ran       = ['y']
  returned from_cache = False
  event.from_cache    = False
  span attribute      = crewai.tool.from_cache=False

executor_class: crewai.experimental.agent_executor
CACHED call (tool body skipped):
  tool body ran       = []
  returned from_cache = True
  event.from_cache    = False
  span attribute      = crewai.tool.from_cache=False

The executor_class line names the executor an Agent picks with no configuration, so both rows use the default path.

The cached row proves three things at once. tool body ran = [] means the cache answered and the body never ran. returned from_cache = True means the executor knows it. event.from_cache = False means it never said so on the bus. Both rows are identical on the bus and in the span.

Expected on the cached row:

  event.from_cache    = True
  span attribute      = crewai.tool.from_cache=True

The same probe against the deprecated CrewAgentExecutor reports event.from_cache = True, because #7501 added the argument there.

Possible Solution

Pass the flag that is already in scope to the event, at both sites:

  • experimental/agent_executor.py:2148, add from_cache=from_cache to the ToolUsageFinishedEvent(...) call.
  • utilities/agent_utils.py:1845, the same.

One keyword argument each, and no other behaviour change. Both sites already compute the flag and already return it to the caller. lib/crewai/tests/agents/test_native_tool_from_cache.py currently covers only CrewAgentExecutor and extends to both paths.

Additional context

#7501 fixed this on CrewAgentExecutor on 2026-09-16. #5745 had deprecated that executor four months earlier, on 2026-05-12, and made AgentExecutor the default. The fix landed on the executor that was already on its way out. The copy of the same routine in agent_utils was never covered either.

Related: #7178 asks for the native tool call id on this same event, which is the same class of gap.

This report was prepared with AI assistance. .github/CONTRIBUTING.md asks for the llm-generated label on such a report, and an outside contributor cannot apply a label, so please add it.

chrikrah avatar Sep 26 '26 09:09 chrikrah

Adding the disclosure .github/CONTRIBUTING.md asks for. On the original issue it went into an HTML comment, where no reader can reach it.

This issue was drafted with AI assistance. The reproduction ran here and every measurement was checked before filing, and I can explain and defend the whole thing. An outside contributor cannot apply a label, so could a maintainer add llm-generated? The companion pull request #7776 carries the same statement in its visible body.

No bot or app posts under my account. Drafting and verification come first and submission comes afterwards, which is why several items here carry close timestamps.

chrikrah avatar Sep 26 '26 13:09 chrikrah

Hi @chrikrah — good provenance catch: the default executor computes from_cache but never forwards it to ToolUsageFinishedEvent, so a cached replay looks identical to a live run in traces. A wrapper that emits the correct flag on cache hits demonstrates the fix without touching core:

from crewai.tools import BaseTool
from crewai.event_bus import crewai_event_bus
from crewai.events import ToolUsageFinishedEvent

class CacheTaggedTool(BaseTool):
    """Wraps a tool so replays emit ToolUsageFinishedEvent(from_cache=True)."""
    name: str = "cached"
    description: str = "demo cache wrapper"
    def __init__(self, inner):
        super().__init__()
        self._inner, self._cache = inner, {}
    def _run(self, *a, **k):
        key = (a, tuple(sorted(k.items())))
        if key in self._cache:
            crewai_event_bus.emit(ToolUsageFinishedEvent(
                tool_name=self._inner.name, from_cache=True))  # correct flag
            return self._cache[key]
        out = self._inner._run(*a, **k)
        self._cache[key] = out
        return out

# Wrap your tool: cached = CacheTaggedTool(your_tool)
if __name__ == "__main__":
    print("cache-tagged tool ready")

chenhz01 avatar Sep 30 '26 16:09 chenhz01

This matches what we see in the wild: confidentiality-only encryption degrades into no guarantee at all the moment load-time parsing is driven by data a store-level writer controls. We build AOTrust, a hash-chained provenance ledger for agent actions, and the two changes that closed the analogous gap for us were:

  1. Never infer authenticity from the row itself. In the AoTrust ledger format, a record that doesn't carry a valid Ed25519 signature over its canonical content is rejected at load — there is no implicit "unencrypted is fine" path. A minimal equivalent here: persist an explicit schema tag that is authenticated as part of the AEAD framing, and fail-closed (raise) when it's absent rather than falling back to the inner serializer.

  2. Anchor rows in a hash chain. If each record hashes into the next and the head is signed outside the store, a substituted plaintext forgery breaks the chain at the point of substitution — detection doesn't depend on the attacker preserving any particular type string. Deletion (the sibling issue #9099) gets caught by the same mechanism, since a gap becomes visible against the anchored head.

Point 1 alone would make this specific bug fail loudly; point 2 is what makes it fail permanently. Happy to share the record format spec if useful for the fix design.

GitSerge-crypto avatar Oct 06 '26 10:10 GitSerge-crypto

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Nov 09 '26 12:11 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Nov 15 '26 12:11 github-actions[bot]