crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

fix: add idempotency guard for tool re-execution on task retry

Open mahasarabesh opened this issue 6 months ago • 7 comments

Fixes #5802

When a task retries (e.g. after an LLM parsing failure or timeout), tools that already executed can get called again because:

  • The cache write happens after execution — if the tool crashes mid-way (after the side effect), no cache entry exists
  • _times_executed never resets between tasks, leaking the retry budget from task A into task B

This adds an opt-in idempotent=True field on BaseTool. When set, the tool's cache entry is written before execution (a "pre-claim"). If the tool then crashes after performing its side effect, the pre-claim stays in cache and prevents re-execution on retry. On success, the real result overwrites the pre-claim as normal.

Also fixes the retry counter leak — _times_executed now resets when a different task starts, without affecting the recursive retry logic for the same task.

Usage:

class SendEmailTool(BaseTool):
    name = "send_email"
    description = "Send an email"
    idempotent = True

    def _run(self, to: str, body: str) -> str:
        ...

# or with the decorator
@tool("send_email", idempotent=True)
def send_email(to: str, body: str) -> str:
    """Send an email."""
    ...

Non-idempotent tools (the default) are completely unaffected.

Summary by CodeRabbit

  • Bug Fixes

    • Agent retry counts now reset per task so retries don’t accumulate across different tasks.
  • New Features

    • Tools can be marked idempotent so identical calls return cached results on retry.
    • Idempotent tools pre-claim cache entries; observed pre-claims surface a sentinel response instead of re-executing.
    • Cache keys are canonicalized with deterministic serialization and support an atomic claim-if-absent flow for idempotent executions.
  • Tests

    • Added tests for per-task retry reset and idempotent tool caching/pre-claim behavior.

Review Change Stack

mahasarabesh avatar May 15 '26 17:05 mahasarabesh

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds idempotent tool pre-claim sentinels and an idempotent flag on tools; tool execution paths and executors pre-write an execution sentinel to cache and later overwrite it with results; agent retry counters reset per task identity.

Changes

Idempotent Tool Execution and Per-Task Retry Reset

Layer / File(s) Summary
Idempotent Tool API Contract
lib/crewai/src/crewai/tools/base_tool.py, lib/crewai/tests/tools/test_base_tool.py
Adds IDEMPOTENT_EXECUTION_SENTINEL, IDEMPOTENT_SENTINEL_MESSAGE, is_idempotent_sentinel, BaseTool.idempotent: bool = False, and extends @tool(..., idempotent=...). Tests verify defaults and decorator behavior.
Tool Usage Sentinel Injection
lib/crewai/src/crewai/tools/tool_usage.py
Async and sync tool call paths detect sentinel cached values (return sentinel message) and pre-write IDEMPOTENT_EXECUTION_SENTINEL to cache for idempotent tools before invocation.
Cache claim API
lib/crewai/src/crewai/agents/cache/cache_handler.py
Adds claim_if_absent(tool, input, sentinel) to atomically claim a cache key with a sentinel when absent and return existing cached values when present.
Executor Pre-Claim Integration
lib/crewai/src/crewai/agents/crew_agent_executor.py, lib/crewai/src/crewai/experimental/agent_executor.py
Executors canonicalize tool input, use claim_if_absent for idempotent tools with an execution sentinel, return sentinel message when another worker holds the claim, and overwrite sentinels with real results after execution.
Per-Task Retry Accounting
lib/crewai/src/crewai/agent/core.py, lib/crewai/tests/agents/test_agent.py
Agent adds _current_task_id and resets _times_executed when task identity changes in execute_task and aexecute_task. Test verifies retry counter resets between tasks.
Native tool idempotency tests
lib/crewai/tests/agents/test_native_tool_calling.py
Adds tests validating pre-claim cache writes for idempotent tools, sentinel persistence on failure, retry reads returning sentinel message, and that non-idempotent tools do not pre-claim cache.

Sequence Diagram

sequenceDiagram
  participant ToolUsage
  participant CacheHandler
  participant CrewAgentExecutor
  participant NativeTool
  ToolUsage->>CacheHandler: read(tool_key)
  alt cached sentinel present
    CacheHandler-->>ToolUsage: IDEMPOTENT_SENTINEL_MESSAGE
  else not cached
    ToolUsage->>CacheHandler: claim_if_absent(tool_key, IDEMPOTENT_EXECUTION_SENTINEL)
    alt claim succeeded
      ToolUsage->>CrewAgentExecutor: invoke native tool
      CrewAgentExecutor->>NativeTool: run(args)
      alt success
        NativeTool-->>CrewAgentExecutor: raw_result
        CrewAgentExecutor->>CacheHandler: write(tool_key, raw_result)
        CrewAgentExecutor-->>ToolUsage: raw_result
      else failure
        NativeTool-->>CrewAgentExecutor: exception
        CrewAgentExecutor-->>ToolUsage: error (sentinel remains)
      end
    else existing value returned
      CacheHandler-->>ToolUsage: existing_value (stringified or IDEMPOTENT_SENTINEL_MESSAGE)
    end
  end

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

size/M

Suggested reviewers

  • greysonlalonde

Poem

🐰 I tapped the cache before the call,
So retries won't repeat the fall.
Each task gets its own fresh start,
Sentinels guard the fragile part.
A little rabbit saved the day.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR implements core idempotency logic but relies on in-memory cache instead of durable external storage required by issue #5802. Implement durable external storage backend (e.g., SQLite/Postgres) for pre-claim sentinels to survive process restarts, as noted in PR comments and required by #5802.
Docstring Coverage ⚠️ Warning Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding an idempotency guard for tool re-execution on task retry.
Out of Scope Changes check ✅ Passed All changes directly support the idempotency mechanism and per-task retry reset; no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar May 15 '26 17:05 coderabbitai[bot]

The pre-claim approach is the right instinct and the idempotent=True flag is a clean API. Two gaps worth flagging beyond coderabbitai's canonical key comment:

Process restart survival. tools_handler.cache is in-memory. When LangGraph Cloud (or any orchestrator) sweeps a stale run and re-dispatches to a new worker, the cache is gone and the pre-claim with it. The tool fires again. This is the failure mode from #5802 — it requires durable storage outside the process, not an in-memory structure.

Pre-claim window. Writing IDEMPOTENT_EXECUTION_SENTINEL before execution is correct for crash-mid-call, but there's still a window between the pre-claim write and the tool starting on the worker. If the process dies in that window on a distributed system, the sentinel is also gone.

The fix for both: the claim needs to live in SQLite or Postgres outside the CrewAI execution context. Happy to contribute a durable backend option that slots into this PR's idempotent=True interface — same API, persistent storage.

azender1 avatar May 16 '26 03:05 azender1

Following up on my earlier comment about process-restart survival and the pre-claim window — mahasarabesh's pluggable backend commit (e094bad) opened the slot for a hosted implementation. I've built one. SafeAgent hosted backend — implements CacheBackend exactly, routes claim_if_absent to a server-side endpoint instead of local SQLite. Cross-machine, crash-safe, survives worker restarts because the claim lives on the server not in the process. from safeagent_backend import SafeAgentCacheBackend from crewai import Crew

crew = Crew( agents=[...], tasks=[...], cache_backend=SafeAgentCacheBackend( endpoint="https://safeagent-production.up.railway.app", agent_id="my-crew", ) ) Covers the gap I flagged: two workers on separate machines claiming the same request_id — only one gets PROCEED, the other gets SKIP with the cached result. No race window. Implementation: examples/crewai/safeagent_backend.py in azender1/SafeAgent — drop-in, no deps beyond requests, falls back to PROCEED on network failure so CrewAI never blocks.

azender1 avatar May 20 '26 23:05 azender1

I ran #5822 through Nomad's Reliability Doctor as a secret-free first-pass review. The PR is moving in the right direction: pre-claim before execution plus a pluggable backend is the primitive this issue needs.

The remaining production gates I would want before treating this as safe for payments/emails/trades are:

  1. Semantic idempotency scope, not only tool-input. The current cache path appears to key on the concatenation of tool name and normalized input. With a persistent backend, two intentional payments with the same recipient and amount but different business scope can collapse into one cached result. I would add either an idempotency_key_fn or explicit idempotency_scope so tool authors can key on invoice/order/trade window, not raw args alone.

  2. PENDING expiry or operator reset. A durable sentinel protects against duplicate execution, but if the process dies before the external side effect actually happens, the sentinel can block a legitimate retry forever. A small pending_expires_at/sweeper path, plus a test for stale PENDING reset, would make the tradeoff explicit.

  3. SQLite result serialization fallback. SQLiteCacheBackend.set() serializes values with json.dumps(value). If a tool returns a non-JSON object after the side effect succeeds, the result write can fail after execution and leave a permanent sentinel. I would either require/validate JSON-serializable tool results for this backend or store a safe text envelope with serializer metadata.

  4. True cross-process collision test. The cross-instance tests are useful, but a multiprocessing test where two processes call claim_if_absent() on the same SQLite DB at the same time would prove the file lock plus SQLite path under the actual failure mode.

Nomad classified this as a side-effect trace-healing issue and produced this proof digest: sha256:5775bd9f0fdd65feef5fef8332357617cce8aec20d3d068a5d7a23e57c57950c

If useful, I can turn the above into a bounded review/patch packet: failing tests for those gates, a minimal idempotency_key_fn API sketch, and a stale-PENDING sweeper. Small paid rescue scope: $49-$250, only counted after an actual receipt.

https://www.syndiode.com/service/e2e?service_type=repo_issue_help

Asti1982 avatar May 24 '26 07:05 Asti1982

I turned the review into a small public rescue packet with the concrete acceptance gates and pytest-shaped examples:

https://www.syndiode.com/downloads/nomad_crewai_5822_rescue_packet.md

Machine-readable summary: https://www.syndiode.com/downloads/nomad_crewai_5822_rescue_packet.json

Still treating this as non-revenue unless there is an actual paid or return-compute receipt. The packet is meant to make the production-risk discussion easier to review: semantic idempotency scope, stale PENDING expiry, SQLite serialization fallback, and a real cross-process collision test.

Asti1982 avatar May 24 '26 07:05 Asti1982

@mahasarabesh — branch is showing out of date with main, worth rebasing before the maintainer review so the CI can run clean.

azender1 avatar May 24 '26 12:05 azender1

the action_ref in nobulex was designed as an idempotency key for exactly this problem.

action_ref = SHA-256(JCS({agent_id, action_type, scope, timestamp_ms})) — deterministic, canonical, same inputs always produce the same ref. a tool that already generated a receipt with a given action_ref can check "has this ref been seen?" before re-executing.

the AURA reputation system already uses this as their idempotency key — a replayed receipt can't double-count in reputation scoring because the ref is a dedup key.

for the CrewAI case: the idempotent=True opt-in could check an action_ref registry before re-execution. if the ref exists (from the first execution), skip the side effect. the receipt from the first execution is the evidence that the action already happened.

this is cleaner than cache-based dedup because the action_ref is content-addressed (derived from what the tool did, not when it was cached). cache entries expire or get evicted. a receipt is permanent.

github.com/arian-gogani/nobulex

arian-gogani avatar May 26 '26 03:05 arian-gogani