crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

Outer retry in ToolUsage cannot tell "not executed" from "unknown": one timeout can still write twice after #9345

Open lucafranco1994pot-cloud opened this issue 1 week ago • 11 comments

Thank you to everyone working on #9341 and #9345. This is a follow-up question, kept separate so that #9345 stays focused.

Check: base 89a63c5 with tool_usage.py taken from #9345's head. Sync local-tool path (not the MCP path). The test tool raises the same TimeoutError on its first invocation; if invoked again it writes once and returns "ok". "Writes" are entries in an in-memory list of the test tool, not database rows.

First invocation Max parsing attempts Recorded writes What the caller sees
raises before writing 3 1 "ok"
raises before writing 1 0 generic tool error
writes, then raises 3 2 "ok"
writes, then raises 1 1 generic tool error

So #9345 removes the replay inside one attempt, but one timeout can still lead to two writes through the outer retry, and the caller sees "ok" for both. Turning the outer retry off avoids the duplicate in the third row but gives up recovery in the first. The exception alone does not tell ToolUsage which row it is in.

Question: how should the outer retry behave when the outcome of a tool call is unknown? I can turn the four rows into a deterministic pytest fixture if that is useful.

Limits: toy tool, local path only, one deterministic run per row.

Found with ATLAS, an AI finder and checker. Thanks again for the work on this

lucafranco1994pot-cloud avatar Nov 25 '26 18:11 lucafranco1994pot-cloud

Hi — I'd like to take this on. I can reproduce the double-write from the table in the issue (tool raises TimeoutError before/after writing, outer retry re-invokes it). Plan: track whether the tool actually executed in the attempt and skip the outer retry when the first invocation already wrote, so one timeout can't produce two writes — plus a regression test covering the raise-before-write and write-then-raise cases. Could you confirm this is accepted, and whether you'd prefer the fix in the outer retry guard or inside the attempt handling?

jaisogani-ai avatar Nov 25 '26 21:11 jaisogani-ai

Rows 3 and 4 are the case to design for. The tool wrote, then raised, and from outside that looks the same as row 1. ToolUsage can track that the tool was invoked. It cannot see whether the tool wrote, so "skip the retry when the first invocation already wrote" needs the tool to say so.

I would give the retry a rule that needs no answer. Split tools by whether they declare themselves safe to repeat. A read, or a write keyed by an id the caller supplies, retries as today. Anything else treats a timeout as "unknown": no automatic retry, and the model is told the call may have taken effect and to check first.

A tool can move itself into the safe group by taking a key made before the first attempt and returning the stored result when it sees the key again. Then row 3 stays one write.

An "ok" for a second write is worse than a visible error.

gioherazo avatar Nov 26 '26 00:11 gioherazo

Rows 3 and 4 are the right case to design for, and @gioherazo names the core limit correctly: ToolUsage can track that the tool was invoked, it cannot see whether the tool wrote. Where I would push back is on the fix being a declaration.

"Safe to repeat" is a claim made by the tool before anything goes wrong. Row 3 is what a wrong claim looks like in practice: the second write lands and the caller sees "ok". A declaration the retry trusts is the same shape as the timeout it is trying to recover from, a signal that says nothing about the effect that already happened.

What the retry can actually decide on is a per-attempt outcome record from the tool itself: took effect, did not take effect, or cannot say. Retry on "did not". Stop on "took effect". On "cannot say", do not retry blind and do not report success either: surface the unknown and let the caller check before anything writes again. That third state is the one the current table has no column for, and it is the row that matters.

The idempotency key works, but the key is not the mechanism. The mechanism is the lookup: the second attempt finds the first attempt's stored result and returns it instead of writing again. If that store dies with the process that timed out, the key has nothing to find and the outcome is honestly "cannot say" again. So the record of the effect has to live somewhere that survives the failure that caused the timeout.

That is the split we measured on #9341: count effects, not invocations. Row 3 has one call that errored and two writes. Any rule that reads calls sees a retry; a rule that reads recorded effects sees a duplicate. The outcome record above is the piece AER-1 standardizes for Zambo (Brennan Zambo's execution receipt work): one verifiable receipt per attempt, stating what the attempt did, that a retry can read before it decides.

Happy to turn the four rows plus the "cannot say" row into the pytest fixture @lucafranco1994pot-cloud offered, with the effect count as the assertion.

zambodotdev avatar Nov 26 '26 00:11 zambodotdev

Thank you, @jaisogani-ai, @gioherazo and @zambodotdev, for the careful reading and the concrete suggestions. @zambodotdev, you asked for the four rows plus the "cannot say" row as a pytest fixture with the effect count as the assertion. That is section 3 below. Sections 1 and 2 extend the fixture from #9341 and answer the other two comments.

Found with ATLAS, an AI finder and checker.

All three files run as they are, each is a single file. Measured on PR #9345 head (b536264); file 3 needs #9345.

  • Files 1 and 2 together: 20 passed, 5 xfailed (strict).
  • File 3: 9 passed.
  • File 3 on main: 7 of 9 fail. I did not check why.

What the rows show (measured)

One logical operation = write A, B, C. The assertion counts effects (each write is recorded as call number + item), not invocations.

row situation effects per item caller is told
r1 raise before write, 3 attempts 1,1,1 ok
r2 raise before write, 1 attempt 0,0,0 error
r3 write, then raise, 3 attempts 2,2,2 ok
r4 write, then raise, 1 attempt 1,1,1 error
r5 every attempt writes then raises, 3 3,3,3 error
r6 A,B written, then raise; retry writes A,B,C 2,2,1 ok
r7 late write after timeout 2,2,2 ok
r8 write, then raise, async path 2,2,2 ok

In r7 the ledger looks clean at the moment of return. The duplicate appears only after the late writer finishes (the test checks both moments).

1. test_outcome_rows.py

test_outcome_rows.py
"""crewAI #9799: effect-ledger rows for the outer retry in ToolUsage.

One logical operation = write A, B and C. Every write is recorded as
(call number, item). Checked separately: missing effects, duplicated effects,
and what the caller is told. "current" tests pin today's behaviour (PR #9345
head b536264); "desired" tests state the invariant and are xfail(strict)
where today's code breaks it, so a fix shows up as a failing xfail.
Limits: toy tool, local sync/async path, one deterministic run per row.
"""

from __future__ import annotations

import asyncio
import pytest
import threading
from dataclasses import dataclass, field
from unittest.mock import MagicMock

from crewai.tools import BaseTool
from crewai.tools.tool_calling import ToolCalling
from crewai.tools.tool_usage import ToolUsage

ITEMS = ("A", "B", "C")  # one logical operation = write A, B and C


@dataclass
class Rig:
    script: dict[int, str]
    default: str = "full_ok"
    ledger: list[tuple[int, str]] = field(default_factory=list)
    calls: int = 0
    release: threading.Event = field(default_factory=threading.Event)
    threads: list[threading.Thread] = field(default_factory=list)
    errors: list[str] = field(default_factory=list)

    def write(self, call_no: int, items: tuple[str, ...] = ITEMS) -> None:
        for item in items:
            self.ledger.append((call_no, item))


def make_usage(rig: Rig, attempts: int) -> ToolUsage:
    class ScriptedTool(BaseTool):
        name: str = "scripted_tool"
        description: str = "Scripted tool that writes A, B, C"

        def _run(self, value: str) -> str:
            rig.calls += 1
            n = rig.calls
            mode = rig.script.get(n, rig.default)
            if mode == "raise_before":
                raise TimeoutError("timeout")
            if mode == "full_then_raise":
                rig.write(n)
                raise TimeoutError("timeout")
            if mode == "partial_then_raise":
                rig.write(n, ("A", "B"))
                raise TimeoutError("timeout")
            if mode == "late_then_raise":
                def later() -> None:
                    if not rig.release.wait(30):
                        rig.errors.append("late writer was never released")
                        return
                    rig.write(n)

                t = threading.Thread(target=later, daemon=True)
                t.start()
                rig.threads.append(t)
                raise TimeoutError("timeout")
            rig.write(n)
            return "ok"

    usage = ToolUsage(
        tools_handler=None,
        tools=[ScriptedTool().to_structured_tool()],
        task=None,
        function_calling_llm=MagicMock(),
        agent=None,
        action=MagicMock(),
    )
    usage._max_parsing_attempts = attempts
    return usage


CALLING = ToolCalling(tool_name="scripted_tool", arguments={"value": "x"})
TOOL_STRING = 'Action: scripted_tool\nAction Input: {"value": "x"}'


def invoke(usage: ToolUsage, use_async: bool) -> str:
    if use_async:
        return asyncio.run(usage.ause(calling=CALLING, tool_string=TOOL_STRING))
    return usage.use(calling=CALLING, tool_string=TOOL_STRING)


def analyze(ledger: list[tuple[int, str]]) -> dict[str, object]:
    counts = {i: sum(1 for _, x in ledger if x == i) for i in ITEMS}
    return {
        "ledger": list(ledger),
        "counts": counts,
        "missing": sorted(i for i, c in counts.items() if c == 0),
        "duplicated": sorted(i for i, c in counts.items() if c > 1),
    }


# name -> (script, default, attempts, async, late)
ROWS: dict[str, tuple[dict[int, str], str, int, bool, bool]] = {
    "r1 raise before write, 3 attempts": ({1: "raise_before"}, "full_ok", 3, False, False),
    "r2 raise before write, 1 attempt": ({1: "raise_before"}, "full_ok", 1, False, False),
    "r3 write then raise, 3 attempts": ({1: "full_then_raise"}, "full_ok", 3, False, False),
    "r4 write then raise, 1 attempt": ({1: "full_then_raise"}, "full_ok", 1, False, False),
    "r5 every attempt writes then raises, 3": ({}, "full_then_raise", 3, False, False),
    "r6 partial (A,B) then raise, 3": ({1: "partial_then_raise"}, "full_ok", 3, False, False),
    "r7 late write after timeout, 3": ({1: "late_then_raise"}, "full_ok", 3, False, True),
    "r8 write then raise, 3, async path": ({1: "full_then_raise"}, "full_ok", 3, True, False),
}


def measure(name: str) -> dict[str, object]:
    script, default, attempts, use_async, late = ROWS[name]
    rig = Rig(script=script, default=default)
    out = invoke(make_usage(rig, attempts), use_async)
    res: dict[str, object] = {"caller_ok": out.strip() == "ok", "calls": rig.calls}
    res.update(analyze(rig.ledger))
    if late:
        res["at_return"] = analyze(rig.ledger)
        rig.release.set()
        for t in rig.threads:
            t.join(5)
        if rig.errors or any(t.is_alive() for t in rig.threads):  # RuntimeError, so xfail cannot hide it
            raise RuntimeError(f"late writer did not finish cleanly: {rig.errors}")
        res.update(analyze(rig.ledger))  # settled state: all late writers have finished
        res["settled"] = True
    return res


CURRENT = {
    "r1 raise before write, 3 attempts": dict(caller_ok=True, calls=2, counts={'A': 1, 'B': 1, 'C': 1}, missing=[], duplicated=[]),
    "r2 raise before write, 1 attempt": dict(caller_ok=False, calls=1, counts={'A': 0, 'B': 0, 'C': 0}, missing=["A", "B", "C"], duplicated=[]),
    "r3 write then raise, 3 attempts": dict(caller_ok=True, calls=2, counts={'A': 2, 'B': 2, 'C': 2}, missing=[], duplicated=["A", "B", "C"]),
    "r4 write then raise, 1 attempt": dict(caller_ok=False, calls=1, counts={'A': 1, 'B': 1, 'C': 1}, missing=[], duplicated=[]),
    "r5 every attempt writes then raises, 3": dict(caller_ok=False, calls=3, counts={'A': 3, 'B': 3, 'C': 3}, missing=[], duplicated=["A", "B", "C"]),
    "r6 partial (A,B) then raise, 3": dict(caller_ok=True, calls=2, counts={'A': 2, 'B': 2, 'C': 1}, missing=[], duplicated=["A", "B"]),
    "r7 late write after timeout, 3": dict(caller_ok=True, calls=2, counts={'A': 2, 'B': 2, 'C': 2}, missing=[], duplicated=["A", "B", "C"]),
    "r8 write then raise, 3, async path": dict(caller_ok=True, calls=2, counts={'A': 2, 'B': 2, 'C': 2}, missing=[], duplicated=["A", "B", "C"]),
}


def desired_ok(res: dict) -> bool:
    """No duplicated effect, and an "ok" for the caller means exactly once."""
    if res["duplicated"]:
        return False
    return not (res["caller_ok"] and res["missing"])


@pytest.mark.parametrize("name", list(ROWS))
def test_current_behaviour(name: str) -> None:
    res = measure(name)
    for key, want in CURRENT[name].items():
        assert res[key] == want, (name, key, res)


def test_late_write_is_invisible_at_return() -> None:
    """r7: at return the ledger looks clean; the duplicate lands only afterwards."""
    res = measure("r7 late write after timeout, 3")
    assert res["at_return"]["duplicated"] == []  # type: ignore[index]
    assert res["duplicated"] == ["A", "B", "C"]  # after the late write is released


KNOWN_FAIL = {n for n in ROWS if n[:2] in {"r3", "r5", "r6", "r7", "r8"}}


@pytest.mark.parametrize(
    "name",
    [
        pytest.param(n, marks=pytest.mark.xfail(strict=True, raises=AssertionError, reason="duplicate effect today"))
        if n in KNOWN_FAIL
        else n
        for n in ROWS
    ],
)
def test_desired_no_duplicate_effect(name: str) -> None:
    assert desired_ok(measure(name))

2. A tool-side check keeps the effect at one (compare-and-set)

@gioherazo, @jaisogani-ai: a tool that takes an expected version (if_version) and rejects the write when the file moved. ToolUsage re-sends identical arguments, so every retry carries the same token. Measured on PR head and on main: 8 passed on both.

  • Response lost after commit: one line in the file, the caller gets a conflict message, not "ok".
  • Late write after a timeout: rejected, one line.
  • Version kept in a separate file and bumped after the data write ("stored"): a crash between the two steps gives two lines. If the version is derived from the content ("derived"), the same crash is safe. The record has to be the effect itself, or live in the same atomic step. The crash tests use a real child process (os._exit(137), not an external SIGKILL), then a fresh object retries with the same token.
  • A conflict does not prove who wrote the line (k6: another writer edits in between, no duplicate and no lost update, but the caller cannot tell the two cases apart from the message alone).
test_versioned_write_rows.py
"""crewAI #9799: a tool that checks an expected version at write time.

Real-world shape: "append a line to a file, but only if the file is still at the
version I read" (compare-and-set). The caller reads the version BEFORE the first
attempt and passes it as an argument, so every retry of ToolUsage resends the
same token (ToolUsage re-sends identical arguments).

Question per row: how many copies of the line end up in the file, and what does
the caller get back? Two stores are compared:
  derived: version = hash of the content (the record IS the effect)
  stored : version kept in a separate file, bumped after the data write
A conflict is returned as a normal result (with the current version), not raised.
Limits: toy file store, local sync path, deterministic, tool-side pattern only
(a tool without such a check is not protected by this).
"""

from __future__ import annotations

import hashlib
import subprocess
import sys
import threading
from pathlib import Path
from unittest.mock import MagicMock

import pytest

from crewai.tools import BaseTool
from crewai.tools.tool_calling import ToolCalling
from crewai.tools.tool_usage import ToolUsage

LINE = "deploy done"


class Store:
    def __init__(self, root: Path, mode: str) -> None:
        self.data, self.ver, self.mode = root / "notes.txt", root / "notes.version", mode
        self.lock = threading.Lock()
        if not self.data.exists():
            self.data.write_text("")
            self.ver.write_text("0")

    def read(self) -> str:
        return self.data.read_text()

    def version(self) -> str:
        if self.mode == "derived":
            return hashlib.sha256(self.read().encode()).hexdigest()[:12]
        return self.ver.read_text()

    def lines(self) -> list[str]:
        return [x for x in self.read().split("\n") if x]

    def append(self, line: str, if_version: str, crash_between: bool = False) -> str:
        with self.lock:
            if self.version() != if_version:
                return f"conflict: file changed, current version {self.version()}"
            self.data.write_text(self.read() + line + "\n")
            if crash_between:
                raise TimeoutError("crash between data write and version bump")
            if self.mode == "stored":
                self.ver.write_text(str(int(self.ver.read_text()) + 1))
            return "ok"


class Rig:
    def __init__(self, store: Store, script: dict[int, str]) -> None:
        self.store, self.script, self.calls = store, script, 0
        self.release = threading.Event()
        self.late_results: list[str] = []
        self.threads: list[threading.Thread] = []
        self.errors: list[str] = []

    def usage(self, attempts: int = 3) -> ToolUsage:
        rig = self

        class AppendNote(BaseTool):
            name: str = "append_note"
            description: str = "Append one line if the file is still at if_version"

            def _run(self, line: str, if_version: str) -> str:
                rig.calls += 1
                mode = rig.script.get(rig.calls, "normal")
                s = rig.store
                if mode == "before":
                    raise TimeoutError("timeout before write")
                if mode == "lost_response":
                    s.append(line, if_version)
                    raise TimeoutError("response lost")
                if mode == "lost_then_other_writer":
                    s.append(line, if_version)
                    s.append("other writer", s.version())  # someone else edits meanwhile
                    raise TimeoutError("response lost")
                if mode == "crash_between":
                    s.append(line, if_version, crash_between=True)
                if mode == "late":
                    def later() -> None:
                        if not rig.release.wait(30):
                            rig.errors.append("late writer was never released")
                            return
                        rig.late_results.append(s.append(line, if_version))

                    t = threading.Thread(target=later, daemon=True)
                    t.start()
                    rig.threads.append(t)
                    raise TimeoutError("timeout, write still running")
                return s.append(line, if_version)

        u = ToolUsage(
            tools_handler=None,
            tools=[AppendNote().to_structured_tool()],
            task=None,
            function_calling_llm=MagicMock(),
            agent=None,
            action=MagicMock(),
        )
        u._max_parsing_attempts = attempts
        return u


def call(usage: ToolUsage, version: str) -> str:
    return usage.use(
        calling=ToolCalling(tool_name="append_note", arguments={"line": LINE, "if_version": version}),
        tool_string='Action: append_note\nAction Input: {"line": "deploy done", "if_version": "%s"}' % version,
    )


def run(tmp_path: Path, mode: str, script: dict[int, str]) -> tuple[Store, Rig, str]:
    store = Store(tmp_path, mode)
    version = store.version()  # read BEFORE the first attempt
    rig = Rig(store, script)
    out = call(rig.usage(), version)
    return store, rig, out


def test_k1_response_lost_after_commit(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "derived", {1: "lost_response"})
    assert store.lines() == [LINE]  # one effect
    assert "conflict" in out  # caller is told to check, not "ok"
    assert out.strip() != "ok"


def test_k2_timeout_before_write_retry_lands(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "derived", {1: "before"})
    assert store.lines() == [LINE]
    assert out.strip() == "ok"


def test_k3_late_write_is_rejected(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "derived", {1: "late"})
    assert out.strip() == "ok" and store.lines() == [LINE]
    rig.release.set()
    for t in rig.threads:
        t.join(5)
    if rig.errors or any(t.is_alive() for t in rig.threads):
        raise RuntimeError(f"late writer did not finish cleanly: {rig.errors}")
    assert store.lines() == [LINE]  # the late write found a moved version
    assert rig.late_results and rig.late_results[0].startswith("conflict")


def test_k4_stored_version_crash_between_duplicates(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "stored", {1: "crash_between"})
    assert store.lines() == [LINE, LINE]  # record kept apart from the effect: duplicate
    assert out.strip() == "ok"


def test_k5_derived_version_crash_between_is_safe(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "derived", {1: "crash_between"})
    assert store.lines() == [LINE]
    assert "conflict" in out


def test_k6_other_writer_edit_between_attempts_sequential(tmp_path: Path) -> None:
    store, rig, out = run(tmp_path, "derived", {1: "lost_then_other_writer"})
    assert store.lines() == [LINE, "other writer"]  # no duplicate, no lost update
    assert "conflict" in out


CRASH_CODE = """
import os, sys
sys.path.insert(0, sys.argv[1])
from pathlib import Path
from test_versioned_write_rows import Store, LINE
s = Store(Path(sys.argv[2]), sys.argv[3])
try:
    s.append(LINE, sys.argv[4], crash_between=True)
finally:
    os._exit(137)  # abrupt exit after the data write, before the version bump
"""


def crash_in_child(tmp_path: Path, mode: str, version: str) -> int:
    """A child process writes the line, then exits abruptly (os._exit, not an external SIGKILL)."""
    here = str(Path(__file__).parent)
    return subprocess.run(
        [sys.executable, "-c", CRASH_CODE, here, str(tmp_path), mode, version]
    ).returncode


def test_k7_real_process_crash_then_retry_with_same_token(tmp_path: Path) -> None:
    store = Store(tmp_path, "derived")
    version = store.version()  # read before the first attempt
    assert crash_in_child(tmp_path, "derived", version) == 137
    restarted = Store(tmp_path, "derived")  # fresh object, only the files survived
    out = call(Rig(restarted, {}).usage(), version)
    assert restarted.lines() == [LINE] and "conflict" in out


def test_k8_real_process_crash_with_stored_version_duplicates(tmp_path: Path) -> None:
    store = Store(tmp_path, "stored")
    version = store.version()
    assert crash_in_child(tmp_path, "stored", version) == 137
    restarted = Store(tmp_path, "stored")
    out = call(Rig(restarted, {}).usage(), version)
    assert restarted.lines() == [LINE, LINE] and out.strip() == "ok"

3. The four rows plus "cannot say", read through an outcome record (for @zambodotdev)

Setup: ToolUsage runs with one parsing attempt, and a small reference loop in the test file (not crewAI code) decides after each attempt by reading the record: retry only on "did not take effect", stop on "took effect", and on "cannot say" neither retry nor report success. The record here is derived from the journal of writes, so it survives the failed call. Each attempt gets an id as a tool argument.

row situation label calls effects A,B,C
z1 raise before write, 3 attempts took effect 2 1,1,1
z2 raise before write, 1 attempt did not 1 0,0,0
z3 write, then raise, 3 attempts took effect 1 1,1,1
z4 same, 1 attempt took effect 1 1,1,1
z5 write, then raise, record lost cannot say 1 1,1,1

Compared with the plain loop (r3: 2,2,2, caller told "ok"), the effect stays at one in z3 and the answer is the same in z4 (caller told it took effect, not "error"). z5 is the "cannot say" row: no retry, and the caller is not told "ok".

Two observations that I could not fit into three states, offered as questions, not as claims about AER-1:

  • Partial: A,B written, C not. With only three states the record reads "took effect" and C is missing (p1: 1,1,0). With a fourth state "partial" it is reported as partial (p2).
  • Attempt still open: a late write after the timeout. With three states the record reads "did not", the retry duplicates (l1: 2,2,2). With a state "open" (the attempt may still write) there is no retry and the effect stays at one (l2: 1,1,1).

@zambodotdev, does AER-1 have a place for these two (the draft summaries I read, -18/-19, list readback outcomes and negative records; I did not read -26)? Or would you map them onto "cannot say"?

test_outcome_record_rows.py
"""crewAI #9799: the four rows plus "cannot say", read through a per-attempt outcome record.

Zambo's proposal: after each attempt the retry reads an outcome record
(took effect / did not take effect / cannot say) and decides: retry on "did not",
stop on "took effect", and on "cannot say" neither retry blindly nor report success.
Assertion: the number of effects (not invocations) and what the caller is told.

ToolUsage is run with ONE parsing attempt (no inner retry), and the outer retry is a
small reference loop in this file that reads the record. Each attempt gets an id
passed as a tool argument (ToolUsage itself provides no per-attempt key).
The record is derived from the journal of writes (the record IS the effect), so it
survives a failed call. Two rules are compared:
  naive : three states only (did not / took effect / cannot say)
  full  : adds "partial" (some but not all items written) and "open" (attempt may
          still write), both of which stop the retry and are reported
Limits: toy tool, local sync path, deterministic, reference loop is not crewAI code.
Needs #9345 (one invocation per ToolUsage attempt).
"""

from __future__ import annotations

import threading
from collections import Counter
from unittest.mock import MagicMock

import pytest

from crewai.tools import BaseTool
from crewai.tools.tool_calling import ToolCalling
from crewai.tools.tool_usage import ToolUsage

ITEMS = ("A", "B", "C")  # one logical operation = write A, B and C


class Journal:
    def __init__(self, lost: set[int]) -> None:
        self.writes: list[tuple[int, str]] = []  # (attempt, item)
        self.open: set[int] = set()  # attempts that may still write
        self.lost = lost  # attempts whose outcome record is unavailable
        self.release = threading.Event()
        self.threads: list[threading.Thread] = []
        self.errors: list[str] = []

    def write(self, attempt: int, items: tuple[str, ...] = ITEMS) -> None:
        self.writes.extend((attempt, i) for i in items)

    def outcome(self, attempt: int, full: bool) -> str:
        if attempt in self.lost:
            return "cannot_say"
        items = {i for a, i in self.writes if a == attempt}
        if full and attempt in self.open:
            return "open"
        if not items:
            return "did_not"
        if full and items != set(ITEMS):
            return "partial"
        return "took_effect"


def make_usage(journal: Journal, modes: dict[int, str]) -> ToolUsage:
    class WriteABC(BaseTool):
        name: str = "write_abc"
        description: str = "Writes A, B and C for one attempt"

        def _run(self, op_id: str, attempt: str) -> str:
            a = int(attempt)
            mode = modes.get(a, "ok")
            if mode == "raise_before":
                raise TimeoutError("timeout")
            if mode == "write_raise":
                journal.write(a)
                raise TimeoutError("timeout")
            if mode == "partial_raise":
                journal.write(a, ("A", "B"))
                raise TimeoutError("timeout")
            if mode == "late_raise":
                journal.open.add(a)

                def later() -> None:
                    if not journal.release.wait(30):
                        journal.errors.append("late writer was never released")
                        return
                    journal.write(a)
                    journal.open.discard(a)

                t = threading.Thread(target=later, daemon=True)
                t.start()
                journal.threads.append(t)
                raise TimeoutError("timeout")
            journal.write(a)
            return "ok"

    u = ToolUsage(
        tools_handler=None,
        tools=[WriteABC().to_structured_tool()],
        task=None,
        function_calling_llm=MagicMock(),
        agent=None,
        action=MagicMock(),
    )
    u._max_parsing_attempts = 1  # no inner retry; the outer loop below decides
    return u


def run_operation(modes: dict[int, str], max_attempts: int, full: bool, lost: set[int] | None = None) -> dict:
    journal = Journal(lost or set())
    label, calls = "did_not", 0
    for attempt in range(1, max_attempts + 1):
        usage = make_usage(journal, modes)
        usage.use(
            calling=ToolCalling(tool_name="write_abc", arguments={"op_id": "op1", "attempt": str(attempt)}),
            tool_string='Action: write_abc\nAction Input: {"op_id": "op1", "attempt": "%d"}' % attempt,
        )
        calls += 1
        oc = journal.outcome(attempt, full)
        if oc == "did_not":
            label = "did_not"
            continue  # safe to retry
        label = {"took_effect": "took_effect", "partial": "partial", "open": "unknown", "cannot_say": "unknown"}[oc]
        break
    journal.release.set()  # let any late writer finish, then count
    for t in journal.threads:
        t.join(5)
    if journal.errors or any(t.is_alive() for t in journal.threads):  # RuntimeError, not AssertionError
        raise RuntimeError(f"late writer did not finish cleanly: {journal.errors}")
    counts = Counter(i for _, i in journal.writes)
    return {"label": label, "calls": calls, "counts": {i: counts.get(i, 0) for i in ITEMS}}


def eff(a: int, b: int, c: int) -> dict[str, int]:
    return {"A": a, "B": b, "C": c}


# name -> (modes per attempt, max attempts, full rule, lost records, expected)
ROWS = {
    "z1 raise before write, 3 attempts: retry lands once":
        ({1: "raise_before"}, 3, False, None, dict(label="took_effect", calls=2, counts=eff(1, 1, 1))),
    "z2 raise before write, 1 attempt: nothing written, caller told so":
        ({1: "raise_before"}, 1, False, None, dict(label="did_not", calls=1, counts=eff(0, 0, 0))),
    "z3 write then raise, 3 attempts: stop on took-effect":
        ({1: "write_raise"}, 3, False, None, dict(label="took_effect", calls=1, counts=eff(1, 1, 1))),
    "z4 write then raise, 1 attempt: caller told it took effect":
        ({1: "write_raise"}, 1, False, None, dict(label="took_effect", calls=1, counts=eff(1, 1, 1))),
    "z5 cannot say: write then raise, record lost, 3 attempts":
        ({1: "write_raise"}, 3, False, {1}, dict(label="unknown", calls=1, counts=eff(1, 1, 1))),
    "p1 partial (A,B), three states only: C missing, caller told took effect":
        ({1: "partial_raise"}, 3, False, None, dict(label="took_effect", calls=1, counts=eff(1, 1, 0))),
    "p2 partial (A,B), with partial state: reported as partial":
        ({1: "partial_raise"}, 3, True, None, dict(label="partial", calls=1, counts=eff(1, 1, 0))),
    "l1 late write, three states only: retried, duplicates":
        ({1: "late_raise"}, 3, False, None, dict(label="took_effect", calls=2, counts=eff(2, 2, 2))),
    "l2 late write, with open state: no retry, one effect":
        ({1: "late_raise"}, 3, True, None, dict(label="unknown", calls=1, counts=eff(1, 1, 1))),
}


@pytest.mark.parametrize("name", list(ROWS))
def test_effect_count_and_label(name: str) -> None:
    modes, attempts, full, lost, want = ROWS[name]
    got = run_operation(modes, attempts, full, lost)
    assert got == want, (name, got)

Limits

  • Toy tools, local sync/async path only. The MCP path is not covered.
  • Deterministic runs, one per row. Not a statement about real-world frequency.
  • The base runs used a newer crewai-core than the PR branch.
  • In file 3 the reference loop and the journal are mine, not crewAI code, and the "record" there is derived from the writes themselves. It shows what the retry could decide if such a record existed and survived. It does not show that ToolUsage can provide one today.
  • A tool-side version check (section 2) protects only tools that have one.

Thank you again to everyone in the thread for the pointers.

lucafranco1994pot-cloud avatar Nov 26 '26 16:11 lucafranco1994pot-cloud

@lucafranco1994pot-cloud thank you, this is exactly what I asked for: the four rows plus the "cannot say" row as a pytest fixture with the effect count as the assertion, and sections 1 and 2 besides. Read back against your measured table:

The assertion that survives is the effect count, not the invocation count, and the caller's told-status diverges from the effect record in both directions. r3: told "ok" at 2,2,2. r5: told "error" at 3,3,3, every attempt wrote. r7 is the sharpest row in the set: at the moment of return the ledger looks clean, and the duplicate lands only after the late writer finishes, so even a correct read can be an early read. r6 is the duplicate-effect case in miniature: A and B land twice, C once, caller told "ok". Section 3 then shows the fix in both directions: z3 holds the effect at one where r3 doubled it, and z4 tells the caller it took effect where r4 said "error".

File 3 on main deserves to be stated plainly for the maintainers: 9 of 9 pass on the PR #9345 head (b536264), 7 of 9 fail on main. That is the fixture doing its job. It separates the two behaviors and pins which one a given build has.

Section 2 lands on the same split from the tool side: where the version is stored apart from the effect, the crash between the two steps duplicates (k4, k8); where the version is derived from the content, the same crash is safe (k5, k7). The record has to be the effect itself, or in the same atomic step as it.

On your two questions, partial and open:

Partial has a place, but not as a fourth label on the whole operation. The records are per attempt and per step, so a partial write decomposes: A and B carry took-effect records, C carries did-not, and "partial" is what the reader computes from the set. p1 is the failure mode of grading the operation with one label: the record reads "took effect" while C is missing. At step granularity the missing C is in the record itself, not hidden by the label.

Open maps onto "cannot say", with the reason carried in the record. An attempt that may still write has produced no settled outcome, and reading it as "did not" is exactly the l1 bug: the retry duplicates. Your l2 already treats open as unknown and stops; the mapping asks only that the reason (attempt still open) travel with the cannot-say, and that the outcome settle to took-effect or did-not once the attempt closes. For reference, the draft summaries you read are -18/-19; the current revision is -26.

The honest boundary, which your Limits section already states: file 3's journal is a reference loop, not crewAI code, so the fixture shows what a retry could decide if a per-attempt record existed and survived. Which of these rows a caller can settle after the fact depends entirely on whether that record exists, and "cannot say" is the honest answer only when the record shows the attempts that were made. What it can never honestly do is arrive dressed as an "ok".

zambodotdev avatar Nov 26 '26 16:11 zambodotdev

Thanks @zambodotdev and @gioherazo for the framing (effect / no effect / unknown). We found this with ATLAS, an AI finder and verifier, and measured where else a tool can run again.

Same toy tool, scripted fake LLM, crewai 1.15.45. Effects = journal writes of the tool, not invocations. The tool writes first and then raises, so every attempt that gets that far counts.

scenario 1.15.45 with #9345 file with begin/done journal
raises after its effect, then succeeds (ReAct) 2 2 1
raises after its effect, always 6 3 1
native tool calling: error after the effect, model calls again 2 2 1
LLM call fails after the tool ran (max_retry_limit) 2 2 1
guardrail rejects the output once 2 2 1
process dies after the effect, new process resumes with Crew.from_checkpoint 2 2 1
two different orders 2 2 2
same order id, changed amount 2 2 1, conflict reported

Why 6 vs 3: 1.15.45 replays the call inside each of the 3 attempts, #9345 removes that replay. The LLM-error and guardrail rows do not show up as retries in the events (two normal started/finished pairs, run_attempts 1), and in the native path the model only sees Error executing tool: timeout.

The journal column is a demonstration in these cases, not a claim about all paths: identity = the order id, plus a fingerprint of the arguments. done -> return the recorded result; begin without done -> raise "outcome unknown"; same id with a different fingerprint -> raise a conflict; error proven before any effect -> retry allowed. A key on the id alone silently swallows the changed amount (negative test in the file).

Limits: toy tool, scripted LLM (no real model run), one Python version (3.13), ReAct and native paths. Crew.akickoff gives the same numbers but runs the sync ToolUsage._use (_ause was never called, and we found no caller in the package). Parallel native tool calls not measured.

Single file below (21 tests, pass on 1.15.45 and with the #9345 file; pip install crewai pytest pytest-xdist, then pytest -q -n 6 test_retry_layers.py). @zambodotdev you offered to help with the fixture: happy to adapt it to whatever layout you prefer.

test_retry_layers.py
"""Single-file fixture: counts EFFECTS (journal writes of a toy tool) at every place in CrewAI that can run a tool again.
Scripted fake LLM, no API calls.   Run: pip install crewai pytest pytest-xdist ; pytest -q -n 6 test_retry_layers.py
guard 0 = plain tool | guard 1 = tool with a begin/done journal (identity = order id, plus a fingerprint of the arguments)
guard 2 = same journal keyed by identity only (negative test: shows why the fingerprint is needed)."""
import glob, hashlib, json, os, subprocess, sys, tempfile
import pytest

# row: (tool modes, effects plain, effects journal)    plain value in () = with PR #9345 if different
ROWS = {
 "ok":                              (["ok"], {1}, 1),
 "raise_before_then_ok":            (["raise_before", "ok"], {1}, 1),
 "raise_after_then_ok":             (["raise_after", "ok"], {2}, 1),
 "raise_after_always":              (["raise_after"], {6, 3}, 1),   # 6 on 1.15.45, 3 with the PR #9345 file
 "native_error_then_model_retries": (["raise_after", "ok"], {2}, 1),
 "llm_error_after_effect":          (["ok"], {2}, 1),
 "guardrail_rejects_once":          (["ok"], {2}, 1),
 "two_different_orders":            (["ok"], {2}, 2),
 "same_id_changed_amount":          (["ok"], {2}, 1),
}

def _child(out, row, guard, phase="first"):
    import threading, time, uuid
    from crewai import Agent, Task, Crew
    from crewai.llms.base_llm import BaseLLM
    from crewai.tools import BaseTool
    from pydantic import BaseModel
    ckpt = row == "checkpoint_resume"
    modes = ROWS[row][0] if row in ROWS else ["ok"]
    native = row == "native_error_then_model_retries"
    lock, st = threading.Lock(), {"calls": 0}
    def wr(name, obj):
        with lock, open(os.path.join(out, name), "a") as f:
            f.write(json.dumps(obj) + "\n"); f.flush(); os.fsync(f.fileno())
    def jget(k):
        f = os.path.join(out, "journal.jsonl")
        recs = [json.loads(l) for l in open(f)] if os.path.exists(f) else []
        return next((r for r in reversed(recs) if r["k"] == k), None)
    class NotExecuted(Exception): pass       # raised by the tool author before any effect
    class OutcomeUnknown(Exception): pass    # an earlier attempt may have taken effect
    class IdentityConflict(Exception): pass  # same order id, different arguments
    def effect(order, amount, pre_exc):
        m = modes[min(st["calls"], len(modes) - 1)]; st["calls"] += 1
        if m == "raise_before": raise pre_exc("timeout")
        wr("effects.jsonl", {"order": order, "amount": amount, "phase": phase, "t": str(uuid.uuid4())})
        if ckpt and order == "B1" and phase == "first": os._exit(1)     # process dies after the effect
        if m == "raise_after": raise RuntimeError("timeout")
        return "ok"
    class In(BaseModel): order: str; amount: int = 10
    class Charge(BaseTool):
        name: str = "charge_card"; description: str = "Charge the card for an order."; args_schema: type[BaseModel] = In
        def _run(self, order: str, amount: int = 10) -> str:
            if guard == "0": return effect(order, amount, RuntimeError)
            fp = hashlib.sha256(json.dumps({"order": order, "amount": amount}, sort_keys=True).encode()).hexdigest()[:12]
            rec = jget(order)
            if rec and rec["s"] == "none": rec = None      # proven no effect: a retry is safe
            if rec:
                if guard == "1" and rec["fp"] != fp:
                    wr("outcomes.jsonl", {"order": order, "amount": amount, "outcome": "conflict"})
                    raise IdentityConflict(f"order {order} was already used with different arguments")
                if rec["s"] == "done":
                    wr("outcomes.jsonl", {"order": order, "amount": amount, "outcome": "replayed", "recorded_fp": rec["fp"], "fp": fp})
                    return rec["r"]
                wr("outcomes.jsonl", {"order": order, "amount": amount, "outcome": "unknown"})
                raise OutcomeUnknown(f"outcome for order {order} is unknown, verify before retrying")
            wr("journal.jsonl", {"k": order, "s": "begin", "fp": fp, "r": None})
            try: r = effect(order, amount, NotExecuted)
            except NotExecuted:
                wr("journal.jsonl", {"k": order, "s": "none", "fp": fp, "r": None})
                raise
            wr("journal.jsonl", {"k": order, "s": "done", "fp": fp, "r": r}); return r
    def act(o, a=10): return f'Thought: go\nAction: charge_card\nAction Input: {{"order": "{o}", "amount": {a}}}'
    FIN = "Thought: done\nFinal Answer: done"
    TC = [{"id": "c1", "type": "function", "function": {"name": "charge_card", "arguments": json.dumps({"order": "A1", "amount": 10})}}]
    class Fake(BaseLLM):
        n: int = 0
        def __init__(self): super().__init__(model="fake")
        def call(self, messages, tools=None, **kw):
            self.n += 1; n = self.n
            wr("llm.jsonl", {"llm_call": n})
            txt = " ".join(str(m.get("content")) for m in messages) if isinstance(messages, list) else str(messages)
            if ckpt: return FIN if "Observation: ok" in txt else act("B1" if "Charge order B1" in txt else "A1")
            if native: return TC if n in (1, 2) else "Final Answer: done"
            if row == "llm_error_after_effect":
                if n == 2: raise RuntimeError("llm connection lost")
                return act("A1") if n in (1, 3) else FIN
            if row == "guardrail_rejects_once": return act("A1") if n in (1, 3) else FIN
            if row == "two_different_orders": return act("A1") if n == 1 else act("A2") if n == 2 else FIN
            if row == "same_id_changed_amount": return act("A1", 10) if n == 1 else act("A1", 25) if n == 2 else FIN
            return act("A1") if n == 1 else FIN
        def supports_function_calling(self): return native
        def get_context_window_size(self): return 8000
    gd = {"n": 0}
    def gr(o):
        gd["n"] += 1
        return (False, "rejected once") if gd["n"] == 1 else (True, o)
    ag = Agent(role="Cashier", goal="charge", backstory="x", llm=Fake(), tools=[Charge()], verbose=False)
    if ckpt:
        from crewai.state.checkpoint_config import CheckpointConfig
        ck = os.path.join(out, "ckpt")
        if phase == "first":
            t1 = Task(description="Charge order A1", expected_output="done", agent=ag)
            t2 = Task(description="Charge order B1", expected_output="done", agent=ag)
            crew = Crew(agents=[ag], tasks=[t1, t2], verbose=False, checkpoint=CheckpointConfig(location=ck, on_events=["task_completed"]))
        else:
            files = sorted(glob.glob(os.path.join(ck, "**", "*.json"), recursive=True), key=os.path.getmtime)
            crew = Crew.from_checkpoint(CheckpointConfig(location=ck, restore_from=files[-1]))
            for a in crew.agents: a.llm = Fake(); a.tools = [Charge()]   # checkpoint keeps LLM and tools by name only
    else:
        kw = {"guardrail": gr} if row == "guardrail_rejects_once" else {}
        crew = Crew(agents=[ag], tasks=[Task(description="Charge order A1", expected_output="done", agent=ag, **kw)], verbose=False)
    crew.kickoff(); time.sleep(1.0)

def _run(row, guard):
    out = tempfile.mkdtemp()
    phases = ["first", "resume"] if row == "checkpoint_resume" else ["first"]
    for ph in phases:
        subprocess.run([sys.executable, __file__, out, row, str(guard), ph], capture_output=True, text=True, timeout=240)
    rd = lambda n: [json.loads(l) for l in open(os.path.join(out, n))] if os.path.exists(os.path.join(out, n)) else []
    return rd("effects.jsonl"), rd("outcomes.jsonl")

@pytest.mark.parametrize("row", list(ROWS))
def test_plain_tool_runs_again(row):
    eff, _ = _run(row, 0); assert len(eff) in ROWS[row][1], row

@pytest.mark.parametrize("row", list(ROWS))
def test_journal_tool(row):
    eff, out = _run(row, 1); assert len(eff) == ROWS[row][2], row
    if row == "same_id_changed_amount": assert out and {o["outcome"] for o in out} == {"conflict"}   # visible, not swallowed

def test_identity_only_key_swallows_changed_amount():     # negative test: why the fingerprint is needed
    eff, out = _run("same_id_changed_amount", 2)
    assert len(eff) == 1 and out and out[0]["outcome"] == "replayed" and out[0]["recorded_fp"] != out[0]["fp"]

def test_checkpoint_resume_plain_runs_task_again():
    eff, _ = _run("checkpoint_resume", 0); assert [e["order"] for e in eff] == ["A1", "B1", "B1"]

def test_checkpoint_resume_journal_reports_unknown():
    eff, out = _run("checkpoint_resume", 1)
    assert [e["order"] for e in eff] == ["A1", "B1"] and any(o["outcome"] == "unknown" for o in out)

if __name__ == "__main__":
    _child(*sys.argv[1:])

lucafranco1994pot-cloud avatar Nov 26 '26 20:11 lucafranco1994pot-cloud

Read the file against the table, row for row. They agree: the ROWS dict carries the same numbers the table prints ({6, 3} on raise_after_always is the 6 vs 3 split, the conflict row asserts the outcome set is exactly {"conflict"}, and the identity-only negative test lands on "replayed" with the recorded fingerprint different from the presented one). So the second delivery holds up the same way the first one did.

The journal column is the framing turned into code, and two rows carry it:

  • Every duplicate in the set collapses to 1, and the one case that must never collapse, same id with a changed amount, comes back as a visible conflict instead of a silent replay. The fingerprint is the load-bearing piece: keyed on the id alone, the journal replays a charge for a different amount and reports it as the recorded result. A record has to bind what was asked, not just which id it ran under.
  • The checkpoint row is where the third state earns its keep. Plain, the resumed process runs B1 again ([A1, B1, B1] in the file's own test). With the journal, the begin-without-done record raises "outcome unknown" and nothing re-runs. On a resume, that refusal to guess is the whole game.

And the events point is worth underlining for whoever reads this thread later: the LLM-error and guardrail rows retry with nothing showing as a retry in the events (two normal started/finished pairs, run_attempts 1), and the native path's model sees only "Error executing tool: timeout". An observer reading the event stream would swear each tool ran once. The effect count says otherwise on the first two columns. In the journal column the count reads 1, and the tell there is the outcome record: a replayed line where the second call came in.

On layout, since you asked: keep the single file, it is the right shape. Two small things. Put the ROWS key next to each scenario name in the table, so the table-to-test mapping is one-to-one without opening the file. And footnote the checkpoint row: its 2 / 2 / 1 counts B1's landings, while the run's full effect list is [A1, B1, B1]; a reader taking the 2 as the run total will trip on the file's own assertion. Everything else stands as-is.

zambodotdev avatar Nov 26 '26 20:11 zambodotdev

i built toolcall_guard to handle this distinction. it records an attempt under a stable operation key before running the tool. on retry, a recorded success replays its saved result; an uncertain outcome is flagged for reconciliation rather than blindly retried.

it's an MIT-licensed developer preview, not an exactly-once guarantee. the CrewAI integration hasn't had independent review yet. code and tests: https://github.com/rishisai0811/toolcall-guard

rishisai0811 avatar Nov 28 '26 06:11 rishisai0811

You nailed the core issue in the title: on a ReadTimeout or dropped response, the client is in an unknown outcome state—it cannot know whether the upstream server committed before the timeout or never received the request.

One extra nuance we hit when testing CrewAI (1.6.1) under both 502-after-commit and pre-commit 503 faults:

Relying on the outer LLM/executor loop to retry either risks duplicate writes (if the retry runs without a stable Idempotency-Key) or gets blocked by same-input loop guards on legitimate transient 503s (dropping the operation completely). The cleanest boundary is keeping bounded retries inside the tool wrapper itself paired with a deterministic Idempotency-Key derived from the task/run ID + operation arguments—so pre-commit 503s recover automatically and post-commit timeouts/502s deduplicate cleanly on the server.

Disclosure: I maintain agent-fault-check (Apache-2.0). If it helps reproduce this timeout/502-after-commit race deterministically in CI, here's our minimal CrewAI harness + chaos-spec.yaml: https://github.com/evhu-dev/agent-fault-check/tree/main/examples/benchmarks

evhu-dev avatar Nov 30 '26 05:11 evhu-dev

This is the exact Two Generals boundary that breaks outer-loop agent retries, especially the open-attempt / late-write case after a timeout. Once a tool call times out after leaving the process, the retry layer cannot distinguish "never arrived" from "still in flight" or "committed, ACK lost," so any blind retry or capability refund risks a duplicate write.

The only reliable pattern I've found is moving retry custody outside the agent loop: mint a single-spend fencing token / epoch key per side-effecting call, quarantine indeterminate timeouts ("cannot say" / open) instead of auto-retrying, and require a read-back reconciliation against the target system's ground truth before releasing the lock. Wrote up the failure mode and fenced-retry pattern with reproducible test traces here if useful: https://supranon.com/notes/fenced-retry-custody

TealGrapes93 avatar Nov 30 '26 16:11 TealGrapes93

Four cells, whole problem. The writes-then-raises row shows the caller sees "ok" while two writes landed, and the table format is exactly what a regression suite for retry semantics needs. The repro is synthetic with in-memory writes, so the open question is frequency in the wild. Has this pattern hit a real deployment for you yet?

xka0085-byte avatar Dec 01 '26 08:12 xka0085-byte