Skip to content

[BUG] Plan-and-Execute replans again after every parallel batch because earlier failures are counted again #9135

Open

Description

Description

AgentExecutor._should_replan asks for a replan when two or more todos have status failed, or have a result that starts with Error:.
A replan keeps failed todos as history (TodoList.replace_pending_todos), so those same todos are counted again on every later check.

After the first replan, the next _should_replan call returns True again, even when every step of the new plan succeeded.
Each of these replans calls the planner, increments replan_count and replaces the pending steps of the plan that was working.
This repeats until replan_count reaches max_replans (3 by default).
The docstring says "Multiple consecutive todo failures"; the code counts every failure in the history.

Steps to Reproduce

  1. Run an agent with planning=True and a plan whose steps run in parallel (several steps ready at once).
  2. Let two steps fail, so after_parallel_execution asks for a replan.
  3. Let the replanned steps all succeed.
  4. after_parallel_execution returns needs_replan again.

Without an LLM:

import importlib.util
from types import SimpleNamespace
from unittest.mock import patch
from crewai.utilities.planning_types import PlanStep, TodoItem, TodoList
from crewai.utilities.reasoning_handler import AgentReasoningOutput, ReasoningPlan

# _build_executor makes an AgentExecutor without validation (a plain test helper).
spec = importlib.util.spec_from_file_location(
    "t", "lib/crewai/tests/agents/test_agent_executor.py"
)
t = importlib.util.module_from_spec(spec)
spec.loader.exec_module(t)

executor = t._build_executor(
    agent=SimpleNamespace(verbose=False, planning_config=None), task=None
)
executor.state.todos = TodoList(items=[
    TodoItem(step_number=1, description="fetch a", status="failed", result="Error: timeout"),
    TodoItem(step_number=2, description="fetch b", status="failed", result="Error: timeout"),
    TodoItem(step_number=3, description="report"),
])
plan = AgentReasoningOutput(plan=ReasoningPlan(plan="use a mirror", ready=True, steps=[
    PlanStep(step_number=4, description="fetch a from mirror"),
    PlanStep(step_number=5, description="fetch b from mirror"),
]))
executor.state.replan_count += 1
with patch("crewai.utilities.reasoning_handler.AgentReasoning") as reasoning:
    reasoning.return_value.handle_agent_reasoning.return_value = plan
    executor._trigger_replan("two fetches failed")
for todo in executor.state.todos.get_pending_todos():
    todo.status = "completed"          # the new steps succeed
print(executor._should_replan())
print(t.AgentExecutor.after_parallel_execution(executor))

Expected behavior

The two failures were given to the planner by the first replan.
The new plan has no failures, so _should_replan() returns (False, "") and after_parallel_execution returns all_todos_complete.
Two new failures still trigger a replan.

Screenshots/Code snippets

Output on main:

(True, 'Multiple todos failed (2 failures)')
needs_replan

Operating System

Windows 11

Python Version

3.13 (the form lists 3.10 to 3.12, nothing in the code depends on it)

crewAI Version

1.15.35 (main at 6bd60b2).

crewAI Tools Version

1.15.35

Virtual Environment

Venv (uv)

Evidence

Tests added on the fix branch, run against unfixed code:

FAILED test_agent_executor.py::TestReplanDoesNotRecountHandledFailures::test_successful_batch_after_a_replan_does_not_replan_again
  assert (True, 'Multi...(2 failures)') == (False, '')
FAILED ...::test_one_new_failure_is_not_enough_to_replan_again
  assert (True, 'Multi...(3 failures)') == (False, '')
FAILED ...::test_two_new_failures_still_trigger_a_replan
  assert '2 failures' in 'Multiple todos failed (4 failures)'

The last line shows the count growing: the two old failures plus the two new ones.

Possible Solution

Keep the ids of the failed and errored todos each replan was given (state.replanned_failure_ids, set in _trigger_replan, cleared where replan_count is reset).
_should_replan then counts only todos that are not in that set.

Additional context

_should_replan is called from after_parallel_execution and from check_more_todos.
Sequential steps replan through the observer (handle_step_observed_*), which does not use this check, so the effect shows up when steps run in parallel.
Searches run (no match for this bug):

Activity

  1. belalshafeq commented on Nov 5, 2026

    @belalshafeq

    Excellent catch on the state bleeding here. The replanned_failure_ids set is exactly the right way to handle this without losing the historical context of what failed initially.

    It's wild how much state management is required just to keep these parallel planners from spinning. Even with this patched, you still have the problem of external handoff loops (Agent A sending the exact same payload back to Agent B) which won't trigger a replan failure, but will silently drain your API budget in the background.

    Curious if you've run into those external ping-pong loops in your parallel setups, or are you mostly sticking to single-agent planner architectures right now?

  2. zongsm-cmyk commented on Nov 6, 2026

    @zongsm-cmyk

    To prevent this replan runaway cascade in production multi-agent runs, tracking the set of already-handled failure IDs across execution epochs is the cleanest architectural fix.

    Here is the concrete patch pattern for AgentExecutor:

    # 1. In AgentExecutor._trigger_replan:
    handled_ids = {
        t.step_number for t in self.state.todos.items 
        if t.status == 'failed' or (t.result and str(t.result).startswith('Error:'))
    }
    if not hasattr(self.state, 'replanned_failure_ids'):
        self.state.replanned_failure_ids = set()
    self.state.replanned_failure_ids.update(handled_ids)
    
    # 2. In AgentExecutor._should_replan:
    replanned_ids = getattr(self.state, 'replanned_failure_ids', set())
    unhandled_failures = [
        t for t in self.state.todos.items 
        if (t.status == 'failed' or (t.result and str(t.result).startswith('Error:')))
        and t.step_number not in replanned_ids
    ]
    if len(unhandled_failures) >= 2:
        return True, f"Multiple new todos failed ({len(unhandled_failures)} failures)"
    return False, ""

    In high-concurrency production deployments, unhandled state bleeding between planner loops is the leading cause of runaway agent doom loops and unexpected API budget exhaustion. We benchmarked and open-sourced an anti-doom-loop guardrail suite and regression test harness for agent executors here:
    👉 https://github.com/zongsm-cmyk/llm-reliability-rescue-demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions