AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

`Abatch_as_completed` Does Not Cancel Pending Tasks On Exception Or Early Exit

The async generator `abatch_as_completed` creates asyncio tasks for all inputs but fails to cancel tasks that are still pending when the generator exits due to an exception or early break. This causes background tasks to continue running, potentially incurring extra API costs and resource usage.

highConfidence 92%LangChainEmbeddingsMemoryAffected Vlangchain-Core 1.2.12

Origin Analysis

The `abatch_as_completed` method in `langchain_core.runnables.base.Runnable` creates a list of asyncio tasks but lacks a `try/finally` block to cancel pending tasks. The synchronous `batch_as_completed` already cancels pending futures in a `finally` block, but the async counterpart does not.
```python import asyncio from langchain_core.runnables import RunnableLambda async def llm_call(prompt: str) -> str: if prompt == "bad": await asyncio.sleep(0.05) raise RuntimeError("429 rate limit") await asyncio.sleep(0.25) print(f"CHARGED: {prompt}") return f"ok:{prompt}" r = RunnableLambda(llm_call) async def main(): try: async for _, out in r.abatch_as_completed( ["bad", "a", "b"], config={"max_concurrency": 3}, ): print("got:", out) except Exception as e: print("caught:", repr(e)) await asyncio.sleep(0.6) await main() ``` Observed: after exception, tasks "a" and "b" still run and print "CHARGED", indicating they were not cancelled.

Fixing Code Block

Edge Case Audit

Cancelling tasks may cause `CancelledError` to be raised inside the underlying coroutine, which could lead to incomplete cleanup if the coroutine does not handle cancellation properly. Some async libraries may not respond immediately to cancellation, so a short delay may still occur. This change also alters behavior: previously tasks would continue in the background; now they will be cancelled, which may surprise users who relied on side effects. If this causes issues, revert to the previous implementation. Also ensure that the event loop is running when the generator is closed, as the finally block now uses `await`.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state