Skip to content

Commit 1806084

Browse files
fix(observe): Handle asyncio.CancelledError in exception blocks (#1566)
Fixes langfuse/langfuse#12650 This catches and records the async task being cancelled—either directly or because it timed out—which will raise an asyncio.CancelledError to stop execution. Also fix sync wrappers as well. Note that asyncio.CancelledError can cross async-sync boundaries, such as `run_coroutine_threadsafe().result()` or a sync helper function that re-raises cancellation that was previously suppressed/deferred. Co-authored-by: Hassieb Pakzad <68423100+hassiebp@users.noreply.github.com>
1 parent 51e0b7f commit 1806084

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

langfuse/_client/observe.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ async def async_wrapper(*args: Tuple[Any], **kwargs: Dict[str, Any]) -> Any:
327327
langfuse_span_or_generation.update(output=result)
328328

329329
return result
330-
except Exception as e:
330+
except (Exception, asyncio.CancelledError) as e:
331331
langfuse_span_or_generation.update(
332332
level="ERROR", status_message=str(e) or type(e).__name__
333333
)
@@ -445,7 +445,7 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
445445
langfuse_span_or_generation.update(output=result)
446446

447447
return result
448-
except Exception as e:
448+
except (Exception, asyncio.CancelledError) as e:
449449
langfuse_span_or_generation.update(
450450
level="ERROR", status_message=str(e) or type(e).__name__
451451
)
@@ -586,7 +586,7 @@ def __next__(self) -> Any:
586586

587587
raise # Re-raise StopIteration
588588

589-
except Exception as e:
589+
except (Exception, asyncio.CancelledError) as e:
590590
self.span.update(
591591
level="ERROR", status_message=str(e) or type(e).__name__
592592
).end()
@@ -653,7 +653,7 @@ async def __anext__(self) -> Any:
653653
self.span.update(output=output).end()
654654

655655
raise # Re-raise StopAsyncIteration
656-
except Exception as e:
656+
except (Exception, asyncio.CancelledError) as e:
657657
self.span.update(
658658
level="ERROR", status_message=str(e) or type(e).__name__
659659
).end()

0 commit comments

Comments
 (0)