[BUG] Guardrail retry drops the context of the previously-successful upstream task that the retried task depends on
Description
I have a crew with two tasks, each run by its own agent:
research_task(researcher agent) successfully outputs the account facts, including the service codeACCT-8841.case_note_task(writer agent) depends on that output (context=[research_task]), hasguardrail_max_retries=1,and a guardrail requiring the note to cite the service code.
I found that when case_note_task fails its guardrail (I injected a failure into the writer's first LLM call), the retry silently drops the upstream context: the declared context is replaced by the validation-error text, so the retry prompt no longer contains ACCT-8841. Finally, the writer works with a lost context and output a wrong answer.
Steps to Reproduce
Run the following code with a true API key, Model, API url (I used deepseek-v4.1-flash as test)
from __future__ import annotations
from crewai import Agent, Crew, Process, Task
from crewai.llms.base_llm import BaseLLM
from openai import OpenAI
from pydantic import PrivateAttr
CLIENT = OpenAI(
api_key="",
base_url="",
)
# for other model-provider, can be also ok
class DeepSeekText(BaseLLM):
"""Text-path transport to the real DeepSeek model (no native tool calling)."""
def __init__(self) -> None:
super().__init__(model="deepseek-chat")
def supports_function_calling(self) -> bool:
return False
def call(self, messages, tools=None, callbacks=None, available_functions=None, from_task=None, from_agent=None, **kwargs): # noqa: ANN001, ANN003, E501
payload = [
{"role": m.get("role", "user"), "content": str(m.get("content") or "")}
for m in messages
]
response = CLIENT.chat.completions.create(
model="deepseek-chat", messages=payload, temperature=0
)
return response.choices[0].message.content or ""
async def acall(self, messages, **kwargs): # noqa: ANN001, ANN003
return self.call(messages, **kwargs)
# inject an error at the second agent first run
class FirstCallErrors(DeepSeekText):
"""The first call returns a mocked error payload; later calls are real."""
_calls: int = PrivateAttr(default=0)
def call(self, messages, tools=None, callbacks=None, available_functions=None, from_task=None, from_agent=None, **kwargs): # noqa: ANN001, ANN003, E501
self._calls += 1
if self._calls == 1:
return (
"ERROR: upstream provider request failed while drafting the note "
"(mocked failure). No case note content was produced."
)
return super().call(messages, tools=tools, callbacks=callbacks, **kwargs)
# a simple guardrial, only check whether there are error in the output
def case_policy_guardrail(output): # noqa: ANN001
#print(output)
"""Guardrail: the reply must be the note itself, not a provider error payload."""
if "(mocked failure)" not in output.raw:
return (True, output) # return the output itself - a string would replace it
return (False, "the reply is a provider error message, not the requested note")
researcher = Agent(
role="account researcher", goal="Pull the account facts", backstory="b", llm=DeepSeekText()
)
writer = Agent(
role="case-note writer", goal="Write internal case notes", backstory="b", llm=FirstCallErrors()
)
research = Task(
description=(
"Pull the account facts for the delayed-shipment case: account service code "
"ACCT-8841, shipment SHP-2207 delayed to Friday, customer Ms. Lin."
),
expected_output="account facts",
agent=researcher,
)
note = Task(
description=(
"Write the internal case-handling note for this delay case, citing the account "
"service code from the research step."
),
expected_output="internal case note citing the account service code",
agent=writer,
context=[research],
guardrail=case_policy_guardrail,
guardrail_max_retries=3,
)
crew = Crew(
agents=[researcher, writer], tasks=[research, note], process=Process.sequential, verbose=False
)
res = crew.kickoff()
print(res)
Expected behavior
When the writer task (note) fails and is retried, the retry should keep the output of the upstream task it depends on, so that it can complete the task successfully.
That is, we can see the Crew finally output an answer with containing string like "ACCT-8841"
Screenshots/Code snippets
See "Step to reproduce" and "Evidence"
Operating System
Ubuntu 22.04
Python Version
3.11
crewAI Version
1.15.28
crewAI Tools Version
1.15.28
Virtual Environment
Conda
Evidence
When running the bug reproduce tests, and print the final result, there are not Account information about ACCT-8841:
**INTERNAL CASE-HANDLING NOTE — DELAY CASE**
**Case Reference:** DELAY-2024-____ (assign per local register)
**Case Type:** Service delay / account handling
**Date Opened:** [date]
**Case Handler:** [name]
**Status:** Open — pending resolution
However, when replace the FirstCallErrors in writer agent with DeepSeekText, the account info exists:
**Internal Case-Handling Note**
**Case Type:** Delayed Shipment
**Account Service Code:** ACCT-8841
**Account Holder / Customer:** Ms. Lin
**Shipment Reference:** SHP-2207
**Shipment Status:** Delayed
**Revised Delivery Date:** Friday
Possible Solution
For the initial attempt, the crew aggregates the task's declared context and passes it down the whole way: Crew._execute_tasks computes it and hands it to execute_sync. The guardrail retry, however, is handled in Task._invoke_guardrail_function, a function that never receives that context (its signature only takes task_output, agent, tools, guardrail, guardrail_index). When the verdict fails, it builds a brand-new context from the validation template and passes that to the agent:
# crewai/task.py:
context = I18N_DEFAULT.errors("validation_error").format(
guardrail_result_error=guardrail_result.error,
task_output=task_output.raw,
)
...
So the declared context is silently lost.
For fix, I think the retry should save the declared context instead of rebuilding it.
### Additional context
None
I lost context, in the exact sense this issue is about — context being silently replaced on retry. Here's the triage.
The failure class is context substitution on retry: the retry path overwrites a dependency's upstream output with the guardrail's own failure signal instead of appending to it.
Root cause, grounded in the repro: the guardrail returns (False, "the reply is a provider error message, not the requested note"), and that string is what ends up driving the retried prompt — "the declared context is replaced by the validation-error text, so the retry prompt no longer contains ACCT-8841." That means whatever assembles the retry prompt treats the guardrail's error message as a full substitute for task context rather than as an addendum to it. Likely the retry code path does something like task.context = guardrail_error or rebuilds the prompt from (description, guardrail_feedback) while dropping the context=[research_task] output that normally gets interpolated in on the first attempt only.
The deterministic check that would catch this: before dispatching any retried LLM call, assert that every task listed in context=[...] still has its original output string present verbatim (or at minimum non-empty and unchanged) in the composed retry prompt. Concretely, snapshot research_task.output.raw right after the first successful execution, and on each guardrail retry diff the final prompt payload against that snapshot — fail the test if the snapshot substring is missing. That's a boundary check at the retry-prompt-assembly function, not a logging addition, and it would have caught this pre-release since the bug is 100% reproducible on first guardrail failure.
Honest uncertainty: I'm inferring the prompt-assembly mechanism from the symptom, not from reading crewAI's retry code directly — someone should confirm whether Task._execute_core's retry branch rebuilds self.context or just the prompt string, since the fix differs (don't mutate context vs. don't drop it when formatting).
Advisory SFA-2026-2709FFD63B · Full redacted write-up: https://impartshadow.github.io/echo-site/failure-cases/bug-guardrail-retry-drops-the-context-of-the-previou-2709ffd63b.html If this diagnosis is useful, react 👍 to this comment; if it is wrong, react 👎 — I use the verdict to choose what I investigate next.
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.
The linked PRs have been open for quite a while. Could a maintainer take a look and confirm whether this issue has been fixed?