sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] Python model retry backoff ignores Agent cancellation until the delay completes

Open 97Three opened this issue 2 months ago • 2 comments

Checks

  • [x] I have updated to the latest minor and patch version of Strands
  • [x] I have checked the documentation and this is not expected behavior
  • [x] I have searched open and closed Issues and Pull Requests and found no Python duplicate

SDK Language

Python

Strands Version

main at a1e7e4cfd89015d16cf482725d2c17e1e27bc518

Language Runtime Version

Python 3.12.3

Operating System

Ubuntu 24.04 under WSL2, x86_64

Installation Method

git clone

Steps to Reproduce

Run an Agent with a model that is throttled once, then cancel it while the default retry strategy is sleeping:

import asyncio
import time
from typing import Any, AsyncGenerator

from pydantic import BaseModel
from strands import Agent
from strands.event_loop._retry import ModelRetryStrategy
from strands.models.model import Model
from strands.types.exceptions import ModelThrottledException


class ThrottleThenAnswerModel(Model):
    def __init__(self) -> None:
        self.calls = 0
        self.first_call_failed = asyncio.Event()

    def update_config(self, **model_config: Any) -> None:
        pass

    def get_config(self) -> dict[str, Any]:
        return {"model_id": "offline-throttle-model"}

    async def stream(self, *args: Any, **kwargs: Any) -> AsyncGenerator[dict[str, Any], None]:
        self.calls += 1
        if self.calls == 1:
            self.first_call_failed.set()
            raise ModelThrottledException("offline throttle")
        yield {"messageStart": {"role": "assistant"}}
        yield {"messageStop": {"stopReason": "end_turn"}}

    async def structured_output(
        self,
        output_model: type[BaseModel],
        prompt: Any,
        system_prompt: str | None = None,
        **kwargs: Any,
    ) -> AsyncGenerator[dict[str, Any], None]:
        if False:
            yield {}


async def main() -> None:
    model = ThrottleThenAnswerModel()
    agent = Agent(
        model=model,
        retry_strategy=ModelRetryStrategy(max_attempts=2, initial_delay=1, max_delay=1),
        callback_handler=None,
    )

    task = asyncio.create_task(agent.invoke_async("hello"))
    await model.first_call_failed.wait()
    await asyncio.sleep(0.05)

    started = time.monotonic()
    agent.cancel()
    result = await task

    print({
        "cancel_to_return_seconds": round(time.monotonic() - started, 3),
        "model_calls": model.calls,
        "stop_reason": result.stop_reason,
    })


asyncio.run(main())

Observed output:

{'cancel_to_return_seconds': 0.984, 'model_calls': 2, 'stop_reason': 'cancelled'}

Expected Behavior

The invocation settles shortly after agent.cancel() is called. A retry delay already in progress should stop waiting because there is no longer an invocation to retry, and the provider should not be entered for another model attempt.

Actual Behavior

The invocation waits for the remainder of the configured backoff, then enters the model a second time before cancellation is observed. The final stop_reason="cancelled" is correct, but cancellation latency and the extra provider call are not.

With the default retry settings, backoffs grow from 4 seconds to 64 seconds, so an HTTP request whose caller has disconnected can retain resources for a substantial period.

Additional Context

ModelRetryStrategy._handle_after_model_call() waits with a bare await asyncio.sleep(delay) and only sets event.retry = True after the full delay. The cancellation checkpoints in model streaming therefore cannot run while the retry hook is sleeping.

After the sleep completes, the retry loop starts another attempt. stream_messages() constructs model.stream(...) before process_stream() checks the cancellation signal, so a pre-set signal does not prevent the provider entry.

The existing retry tests mock asyncio.sleep and verify the delay sequence, but do not cover cancellation before or during backoff.

Possible Solution

Keep the change focused on the retry and model-entry boundaries:

  1. Make the retry wait observe the Agent cancellation signal without blocking the event loop or stranding executor threads.
  2. Do not request another retry when cancellation is already active, or otherwise route promptly to the normal cancelled result.
  3. Check a pre-set cancellation signal before calling model.stream(...), so cancellation during backoff does not enter the provider again.
  4. Add deterministic offline tests for cancellation during backoff and before a provider call, plus a control test proving normal retries still use the configured delays.

Related Issues

#4250 tracks the equivalent cancellation-latency bug in the TypeScript SDK. This report is scoped to the Python implementation.

97Three avatar Sep 14 '26 13:09 97Three

Interested in aligning Python retry backoff with the TS-side cancellation intent (#4250 / #4291), if maintainers want a community PR (happy to wait for ready for contribution).

Proposed approach: Make the wait in _retry.py cancellation-aware; do not set retry=True once cancelled; re-check cancel before entering model.stream. Tests covering cancel-during-backoff, cancel-before-provider, and that normal retries still delay (not only a mocked sleep sequence).

Please confirm if we should start now or wait for the ready label.

Zsanz3 avatar Sep 15 '26 01:09 Zsanz3

I reproduced this on main (563f57d): with a 3 s backoff, cancel() takes 2.96 s to return and the provider is called a second time. I'd like to fix it the way #4291 did for TypeScript: make the backoff wait in _retry.py return early on cancellation, and check the cancel signal in stream_messages before calling model.stream(). Tests would be offline and cover cancel during backoff, cancel before the provider call, and normal retry delays.

@Zsanz3, you proposed the same approach earlier. Are you still planning to work on it? If not, and a community PR is welcome here, I'm happy to open one.

Drafted with AI assistance and reviewed by me.

gunkaynar avatar Oct 02 '26 02:10 gunkaynar