crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

ToolUsage retries a failed tool call twice per outer attempt, not once (schema-args-filter fallback in _use/_ause)

Open giskard09 opened this issue 2 months ago • 11 comments

Summary

ToolUsage._use/_ause (crewai/tools/tool_usage.py) has two independent retry paths, not one. The outer loop (_run_attempts / _max_parsing_attempts, default 3) is the retry surface I expected. But inside a single outer attempt, there's a second, inner try/except around the actual tool call:

if calling.arguments:
    try:
        acceptable_args = tool.args_schema.model_json_schema()["properties"].keys()
        arguments = {k: v for k, v in calling.arguments.items() if k in acceptable_args}
        result = tool.invoke(input=arguments, config=fingerprint_config)
    except Exception:
        arguments = calling.arguments
        result = tool.invoke(input=arguments, config=fingerprint_config)

(sync path, lines 613-629; the async path in _ause is the same shape, lines 356-372.)

This except Exception catches any exception from the first tool.invoke() call — not just a schema/argument-filtering problem. If the tool's own function body raises (a real runtime error, not an argument mismatch), this block re-invokes tool.invoke() a second time with unfiltered arguments, inside the same outer attempt. So every outer attempt calls the tool's underlying function twice, not once — and with the default _max_parsing_attempts=3, a single tool call that always fails ends up invoking the tool 6 times total, not 3.

For a tool with an idempotent effect this is harmless (just wasted calls). For a tool with a non-idempotent side effect (writes a row, sends a request, increments a counter) that happens to raise after the effect lands, this doubles the duplicate-effect exposure of the outer retry loop.

Repro (crewai==1.15.21, no LLM needed — this reaches ToolUsage directly, downstream of tool-call parsing):

import os
os.environ.setdefault("OTEL_SDK_DISABLED", "true")
os.environ.setdefault("CREWAI_DISABLE_TELEMETRY", "true")

from crewai.tools.structured_tool import CrewStructuredTool
from crewai.tools.tool_calling import ToolCalling
from crewai.tools.tool_usage import ToolUsage

calls = []

def my_tool(logical_id: str) -> str:
    calls.append(logical_id)
    raise RuntimeError("boom")

tool = CrewStructuredTool.from_function(func=my_tool, name="my_tool", description="demo tool")

class _Action:
    tool = "my_tool"
    tool_input = {"logical_id": "abc"}

usage = ToolUsage(
    tools_handler=None, tools=[tool], task=None,
    function_calling_llm=None, agent=None, action=_Action(),
)
usage._max_parsing_attempts = 3

calling = ToolCalling(tool_name="my_tool", arguments={"logical_id": "abc"})
usage.use(calling=calling, tool_string="my_tool(logical_id=abc)")

print(f"python-level invocations: {len(calls)}")       # 6
print(f"outer run_attempts reported: {usage._run_attempts}")  # 4

Output (independently re-run against a fresh install before filing this):

python-level invocations: 6
outer run_attempts reported: 4

Expected vs actual

I'd expect _max_parsing_attempts=3 to mean the tool function is called at most 3 times for a call that keeps failing (matching what _run_attempts reports). Instead it's called up to 6 times, because the inner fallback fires independently on any exception, not only ones that indicate the first arguments dict was wrong.

Context

Found this while building a standalone worked example reproducing a duplicate-effect scenario for a tool with a real side effect (SQLite write) that fails after the effect commits — the inner fallback showed up as an unexpected 2x multiplier on the duplicate count. Repro and full writeup: https://github.com/giskard09/argentum-core/tree/main/examples/conformance/crewai-unguarded-retry (not required to reproduce this — the snippet above is self-contained).

Not sure if the inner fallback's intent was "retry only on schema-filtering exceptions" and it's accidentally too broad, or if it's deliberate — happy to be pointed at the right context if this is expected behavior.

giskard09 avatar Sep 14 '26 04:09 giskard09

One distinction worth making here: retry permission is not permission to re-execute the side effect.

If a tool invocation can pass through both an outer retry loop and an inner exception/fallback retry, then the runtime needs a single logical effect identity that survives those control-flow retries. Otherwise each retry frame can legitimately think it is making "the" attempt while the external system sees multiple payments/emails/trades.

For side-effecting tools I would separate:

logical effect -> fresh authority check -> one-shot permit -> external effect -> receipt

Then retry logic can retry orchestration, transport, parsing, or receipt recovery, but it cannot mint a second effect unless a new logical effect is explicitly authorized.

A useful invariant is: one logical effect may have many runtime attempts, but at most one consumed execution permit.

That also handles the ambiguous-failure case. If the tool throws after the external system may already have committed, the runtime should not blindly re-fire. It should first reconcile against the effect identity / receipt and only execute again if non-execution is proven or a new permit is issued.

Minimal regression cases I would add:

  1. outer retry + inner fallback still produces one external side effect;
  2. exception after external commit does not automatically re-execute;
  3. replay/resume cannot reuse a consumed permit;
  4. changed args create a new logical effect and require a new authority decision;
  5. gate/receipt state unavailable for an effectful tool fails closed or escalates rather than assuming safe retry.

The bug here is therefore slightly broader than duplicate invocation count: retry control flow is currently able to cross the consequence boundary more than once for one logical action.

nsolland avatar Sep 14 '26 17:09 nsolland

This is the same distinction you named in autogen#7405, applied to exactly the bug this issue reports — and we already have a worked reproduction, so I can be precise about what it covers and what it doesn't rather than agree in the abstract.

examples/conformance/crewai-unguarded-retry (built earlier today for a different requester, same underlying bug) runs an idempotency-ref-v1 guard against CrewAI's real, unmocked retry engine — both vectors, outer _run_attempts and the inner fallback this issue reports. Result: 6 duplicate effects unguarded, exactly 1 guarded, PENDING_GUARD/RECONCILED_GUARD both observed live, anchored on Base mainnet (tx in PROVENANCE.md).

Against your five cases specifically:

  • (1) outer+inner retry, one effect — covered, that's the headline result above.
  • (2) exception after external commit doesn't auto re-fire — covered: a second attempt hitting an existing PENDING record refuses to run rather than guessing.
  • (3) replay/resume can't reuse a consumed permit — only half true today. COMMITTED blocks a second attempt within the same process, but the guard state is an in-memory dict. A resume after a real process restart loses it entirely. Real gap, not simulated in our worked example.
  • (4) changed args require a new logical effect / new authority decision — not covered, and possibly a real tension: our idempotency_ref is deliberately keyed only on the caller-fixed logical_action_id, never on args, specifically so retries with reconstructed args still match. Nothing checks that the args are actually the same across attempts sharing that id. If they legitimately differ, we'd currently treat it as the same effect anyway.
  • (5) unavailable gate state fails closed — likely true by construction (no evidence → stays blocked, never assumes safe), but not a case our conformance suite actually exercises.

(3) and (4) look like real additions to the regression set worth having, not just for CrewAI — happy to build fixtures for both against our own guard if that's useful, independent of whatever gets proposed for crewAI itself.

giskard09 avatar Sep 14 '26 21:09 giskard09

The five-case breakdown is a useful boundary map. Heimel's merged test covers the stale-authority/consumed-permit shape, but not changed-argument equivalence across a model-regenerated retry. That should remain a separate fixture: the logical action ID must not be allowed to substitute for an exact canonical-arguments digest, and a mismatch should require a new authority decision rather than reuse the old permit.

nsolland avatar Sep 15 '26 08:09 nsolland

Right, and that's a distinct failure from Heimel's — theirs catches a permit that's stale or already spent, this one is a permit that's still valid but bound to the wrong content.

Built it against gap #4 the way you described it: logical_action_id deliberately doesn't look at arguments (idempotency-ref.md's own false-negative concern about superficial model rewording), so a second attempt with the same ID but a materially different amount sails through the existing guard as RECONCILED_GUARD — silent reuse of attempt 1's effect, attempt 2's real request just disappears.

ArgumentBoundGuard wraps the existing guard with an args-digest bound on first attempt; any later attempt with a different digest is refused with ARGUMENT_MISMATCH_REQUIRES_NEW_DECISION before the wrapped guard is even reached. Two real (unmocked) ToolUsage.use() calls, amount 100 then 250, same logical_action_id: naive case shows the silent substitution, guarded case shows the explicit refusal — same non-commit on the real request either way, but one buries it and one surfaces it.

It's a plain SHA-256 digest binding, not a full decision_binding_ref yet — that wiring is next, not done here. examples/conformance/crewai-unguarded-retry/GAP4_ARGUMENT_MISMATCH.md has the write-up, args_binding_guard.py + the two case files + verify_argument_mismatch.py are the fixture (PR#87, commit 951b03e).

Gap #3 (resume-after-restart) still open, no fixture yet.

giskard09 avatar Sep 15 '26 12:09 giskard09

I’d like to implement the narrow retry fix here. I’ll pin the current behavior first with deterministic sync and async regressions that count the underlying tool body invocations when it raises: one outer attempt must not invoke the tool twice. Then I’ll separate schema/argument-filter preparation from actual tool execution so only preparation failures can fall back to unfiltered arguments; exceptions raised by the tool itself propagate to the existing outer retry logic instead of triggering an immediate second side effect. No new idempotency subsystem or retry-policy changes in this PR.

anupamking01 avatar Sep 15 '26 18:09 anupamking01

@giskard09 this retry bug is a clean test for the boundary I’m trying to validate: framework retry behavior can re-enter a tool, while the external side effect needs its own stable identity and outcome.

I published a small non-production runtime: https://github.com/shimjaemandu/reality-layer

The intended seam is not “hide the CrewAI bug.” It is: one logical external action gets a stable action_id; if the first attempt’s effect is uncertain, outcome becomes UNKNOWN; a retry cannot become a fresh side effect until reconciliation/evidence resolves it.

Would you be willing to put one harmless synthetic side-effect tool behind that boundary and tell me whether it actually contains the duplicate-execution risk, or whether the framework/app still needs just as much glue?

Contract: https://github.com/shimjaemandu/reality-layer/blob/main/docs/EXTERNAL-RUNTIME.md

shimjaemandu avatar Sep 22 '26 13:09 shimjaemandu

seems nastier than just “too many retries” to me. the inner fallback is treating a tool-body failure and an argument-filtering failure like the same event. once tool.invoke() has actually started, wouldnt retrying it inside that same catch already be unsafe because u no longer know whether the side effect happened before the exception? id probably narrow the catch boundary so the fallback can only happen before execution. curious if theres a reason invocation itself needs to sit inside that block

Maas-Dorian avatar Sep 23 '26 04:09 Maas-Dorian

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 Oct 23 '26 12:10 github-actions[bot]

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

github-actions[bot] avatar Oct 29 '26 12:10 github-actions[bot]

Following up on today's inactivity closure. The discussion does not show that the duplicate-invocation behavior was resolved, and #7452, #7454, #7458 and #7590 are still open proposals for this issue.

Could a maintainer reopen/triage this issue and identify which existing PR should carry the fix? I would like to help validate that synchronous and asynchronous paths perform at most one actual tool invocation per outer attempt, and that argument-filtering fallback cannot repeat an invocation after the tool body has already started. I have not run those regressions against the competing PRs yet.

I will coordinate with the selected author rather than open another overlapping implementation.

anupamking01 avatar Oct 29 '26 18:10 anupamking01

+1 to reopening — this is still open (confirmed against examples/conformance/crewai-unguarded-retry), not resolved by any of #7452/#7454/#7458/#7590, none of which appear validated against a shared regression yet. Happy to help validate: a fixture asserting at most one tool-body invocation per outer attempt, across sync and async paths, would settle which PR (if any) actually closes the gap.

giskard09 avatar Oct 29 '26 18:10 giskard09