Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

fix(crawl4ai): keep the streaming span open until the stream ends (#1626)

RichardoMu9654e6c05a4a
diff --git a/sdk/python/src/openlit/instrumentation/crawl4ai/async_crawl4ai.py b/sdk/python/src/openlit/instrumentation/crawl4ai/async_crawl4ai.py
index 6dc42372..073c72b8 100644
--- a/sdk/python/src/openlit/instrumentation/crawl4ai/async_crawl4ai.py
+++ b/sdk/python/src/openlit/instrumentation/crawl4ai/async_crawl4ai.py
@@ -5,12 +5,14 @@ Supports comprehensive 0.7.x operations with business intelligence and enhanced
Includes support for async generators and streaming responses.
"""
+import asyncio
import logging
import time
+from opentelemetry import trace as trace_api
from opentelemetry.trace import SpanKind
from opentelemetry import context as context_api
-from openlit.__helpers import handle_exception
+from openlit.__helpers import handle_exception, safe_detach
from openlit.instrumentation.crawl4ai.utils import (
Crawl4AIInstrumentationContext,
get_operation_name,
@@ -108,9 +110,20 @@ def async_general_wrap(
# For crawl operations, use the new improved naming
span_name = create_crawl_span_name(operation_name, ctx, gen_ai_endpoint)
- with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
- start_time = time.time()
+ # Whether the response streams is only known after awaiting it, so the
+ # span cannot be scoped with ``with``: a streaming response is consumed
+ # by the caller after this coroutine returns, and a context manager
+ # would end the span first, discarding everything the tracked
+ # generator records. The span is started detached. ``finally`` ends it
+ # for every path that does not hand it to the generator, including
+ # ``CancelledError``, which ``except Exception`` does not see. The
+ # generator ends it once the stream is exhausted, closed, or dropped.
+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
+ token = context_api.attach(trace_api.set_span_in_context(span))
+ start_time = time.time()
+ handed_off = False
+ try:
try:
# Set comprehensive span attributes
set_crawl_attributes(span, ctx, operation_name)
@@ -120,7 +133,9 @@ def async_general_wrap(
# Handle async generators (streaming responses)
if hasattr(response, "__aiter__"):
- return await _handle_async_generator(
+ # The tracked generator ends the span once the stream is
+ # exhausted, closed, or discarded.
+ tracked = await _handle_async_generator(
span,
response,
ctx,
@@ -130,8 +145,10 @@ def async_general_wrap(
metrics,
disable_metrics,
)
+ handed_off = True
+ return tracked
- # Handle regular responses
+ # Handle regular responses. The span ends in ``finally``.
return await _handle_regular_response(
span,
response,
@@ -167,8 +184,13 @@ def async_general_wrap(
"Error recording error metrics: %s", metrics_error
)
- # Re-raise the exception to maintain original behavior
+ # Re-raise the exception to maintain original behavior.
+ # ``finally`` ends the span.
raise
+ finally:
+ if not handed_off and span.is_recording():
+ span.end()
+ safe_detach(token)
return async_wrapper()
@@ -289,6 +311,21 @@ async def _handle_async_generator(
def __aiter__(self):
return self
+ def __del__(self):
+ """Export a span abandoned by ``async for`` without ``aclose()``.
+
+ This class is not an async generator. ``break`` compiles to a
+ return, and ``END_ASYNC_FOR`` does not run, so the loop never
+ calls ``aclose()``. The same is true of a return or an exception
+ in the loop body. Dealloc cannot await; closing the inner crawl
+ stays with that generator's own finalizer once this object drops
+ it. Same constraint as the LiteLLM stream wrapper.
+ """
+ try:
+ self._finalize()
+ except Exception: # pylint: disable=broad-except
+ pass
+
async def __anext__(self):
try:
result = await self.generator.__anext__()
@@ -302,50 +339,115 @@ async def _handle_async_generator(
except StopAsyncIteration:
# Generator is complete, finalize metrics
- if not self.completed:
- await self._finalize_metrics()
- self.completed = True
+ self._finalize()
+ raise
+ except (GeneratorExit, asyncio.CancelledError):
+ # Not a crawl failure. Record whatever was consumed and end.
+ # Do not await the inner close here: this task is already
+ # unwinding, and the inner generator is finalized on dealloc.
+ self._finalize()
raise
- except Exception as e:
- # Handle errors in streaming
- handle_exception(self.span, e)
+ except Exception as e: # pylint: disable=broad-except
logger.error("Error in streaming crawl operation: %s", e)
+ try:
+ await self._close_inner_quietly()
+ finally:
+ self._finalize(e)
raise
- async def _finalize_metrics(self):
- """Finalize metrics when streaming is complete."""
+ def _finalize(self, error=None):
+ """Record streaming telemetry exactly once, then end the span.
+
+ The span is not current here: it outlives ``async_wrapper`` so it
+ is still open while the caller consumes this generator. Exhaustion,
+ ``aclose()``, cancellation, and ``__del__`` all come through here.
+ The ``completed`` flag keeps a repeat call a no-op.
+
+ ``error`` is set only for a failure raised by the stream. Cleanup
+ exits leave it unset so a partial crawl is not forced to ERROR.
+ Attributes are written before the status: ``process_crawl_response``
+ must not stamp OK on a failure, because this SDK then ignores ERROR.
+ """
+ if self.completed:
+ return
+ self.completed = True
+ try:
+ self._record(error)
+ except Exception as exc: # pylint: disable=broad-except
+ if error is None:
+ error = exc
+ logger.debug("Error finalizing crawl4ai stream: %s", exc)
+ finally:
+ try:
+ if error is not None:
+ handle_exception(self.span, error)
+ finally:
+ if self.span.is_recording():
+ self.span.end()
+
+ async def _close_inner_quietly(self):
+ """Close the inner stream without masking the error that aborted it."""
+ closer = getattr(self.generator, "aclose", None)
+ if closer is None:
+ return
+ try:
+ await closer()
+ except Exception as exc: # pylint: disable=broad-except
+ logger.warning("Failed to close crawl4ai stream: %s", exc)
+
+ async def aclose(self):
+ """Close the wrapped generator and finalize the span.
+
+ Callers that stop early and still hold the iterator should close
+ it so the span ends before the iterator is discarded. ``async for``
+ does not call this on ``break``. A second call is a no-op.
+ """
+ try:
+ await self._close_inner_quietly()
+ finally:
+ self._finalize()
+
+ def _record(self, error):
+ """Write duration and the pages consumed so far onto the open span."""
end_time = time.time()
duration = end_time - self.start_time
duration_ms = duration * 1000
self.span.set_attribute("gen_ai.client.operation.duration", duration)
# Process aggregated results
- if self.results:
- process_crawl_response(self.span, self.results, self.ctx)
+ if not self.results:
+ return
- # Capture message content for streaming
- capture_message_content_if_enabled(
- self.span, self.ctx, self.results, self.capture_message_content
- )
+ # OK would stick and hide the failure status applied by _finalize.
+ process_crawl_response(
+ self.span, self.results, self.ctx, mark_ok=error is None
+ )
- # Record streaming metrics
- if not self.disable_metrics and self.metrics:
- try:
- metrics_key = f"crawl4ai.{self.operation_name}.stream.duration"
- if metrics_key not in self.metrics:
- self.metrics[metrics_key] = []
- self.metrics[metrics_key].append(duration_ms)
-
- # Record stream completion
- stream_key = f"crawl4ai.{self.operation_name}.stream.completed"
- if stream_key not in self.metrics:
- self.metrics[stream_key] = 0
- self.metrics[stream_key] += 1
-
- except Exception as metrics_error:
- logger.debug(
- "Error recording streaming metrics: %s", metrics_error
- )
+ # Capture message content for streaming
+ capture_message_content_if_enabled(
+ self.span, self.ctx, self.results, self.capture_message_content
+ )
+
+ # A failed stream is not a completed one.
+ if error is not None or self.disable_metrics or not self.metrics:
+ return
+
+ try:
+ metrics_key = f"crawl4ai.{self.operation_name}.stream.duration"
+ if metrics_key not in self.metrics:
+ self.metrics[metrics_key] = []
+ self.metrics[metrics_key].append(duration_ms)
+
+ # Record stream completion
+ stream_key = f"crawl4ai.{self.operation_name}.stream.completed"
+ if stream_key not in self.metrics:
+ self.metrics[stream_key] = 0
+ self.metrics[stream_key] += 1
+
+ except Exception as metrics_error:
+ logger.debug(
+ "Error recording streaming metrics: %s", metrics_error
+ )
# Return the tracked generator
return TrackedAsyncGenerator(
diff --git a/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py b/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
index 8fa84796..c9dcbbe7 100644
--- a/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
@@ -380,7 +380,15 @@ def set_crawl_attributes(
def process_crawl_response(
span, response, ctx: Crawl4AIInstrumentationContext, **kwargs
):
- """Process Crawl4AI response and extract business intelligence."""
+ """Process Crawl4AI response and extract business intelligence.
+
+ ``mark_ok`` defaults to true, which is what every existing caller wants.
+ A streaming failure passes false. This SDK ignores a later ERROR once the
+ status is OK, and OK overwrites ERROR, so the caller stamps the error
+ status itself after the attributes are on the span.
+ """
+
+ mark_ok = kwargs.get("mark_ok", True)
try:
if response is None:
@@ -484,8 +492,10 @@ def process_crawl_response(
response.redirected_url,
)
- # Set success status
- span.set_status(Status(StatusCode.OK))
+ # Set success status. Skipped when the caller still has to record an
+ # error: OK would stick and the failure would export as success.
+ if mark_ok:
+ span.set_status(Status(StatusCode.OK))
except Exception as e:
handle_exception(span, e)
diff --git a/sdk/python/tests/test_crawl4ai_stream_span_lifecycle.py b/sdk/python/tests/test_crawl4ai_stream_span_lifecycle.py
new file mode 100644
index 00000000..8fd1f9a2
--- /dev/null
+++ b/sdk/python/tests/test_crawl4ai_stream_span_lifecycle.py
@@ -0,0 +1,285 @@
+# pylint: disable=protected-access, missing-function-docstring, duplicate-code
+"""Span lifetime for crawl4ai's async streaming path.
+
+A streaming crawl returns a tracked generator that the caller consumes after the
+instrumented coroutine has returned. The span therefore has to stay open until the
+stream is exhausted or closed; if it is scoped to the coroutine, everything the
+generator records afterwards is written to an ended span and silently dropped by
+the SDK.
+
+These tests pin that contract: the streaming span must carry its telemetry, an
+``async for`` that breaks must still export when the iterator is dropped (the
+loop does not call ``aclose()``), a mid-stream failure must keep partial
+telemetry and ERROR, cancellation must still end the span, and the
+non-streaming path must keep ending its span exactly as before.
+"""
+
+import asyncio
+import logging
+from contextlib import contextmanager
+from types import SimpleNamespace
+
+import pytest
+from opentelemetry.sdk.trace import TracerProvider
+from opentelemetry.sdk.trace.export import SimpleSpanProcessor
+from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
+ InMemorySpanExporter,
+)
+from opentelemetry.trace import StatusCode
+
+import openlit
+from openlit._config import OpenlitConfig
+from openlit.instrumentation.crawl4ai import async_crawl4ai as async_mod
+
+openlit.init(
+ environment="openlit-python-testing",
+ application_name="openlit-python-crawl4ai-stream-test",
+)
+
+DURATION = "gen_ai.client.operation.duration"
+
+
[email protected](autouse=True)
+def _reset_config():
+ OpenlitConfig.reset_to_defaults()
+ yield
+ OpenlitConfig.reset_to_defaults()
+
+
+class _DroppedWrites(logging.Handler):
+ """Collects the SDK's complaints about writing to an ended span."""
+
+ def __init__(self):
+ super().__init__()
+ self.records = []
+
+ def emit(self, record):
+ message = record.getMessage()
+ if "ended span" in message:
+ self.records.append(message)
+
+
+@contextmanager
+def _telemetry():
+ exporter = InMemorySpanExporter()
+ provider = TracerProvider()
+ provider.add_span_processor(SimpleSpanProcessor(exporter))
+ handler = _DroppedWrites()
+ sdk_logger = logging.getLogger("opentelemetry.sdk.trace")
+ sdk_logger.addHandler(handler)
+ previous = sdk_logger.level
+ sdk_logger.setLevel(logging.WARNING)
+ try:
+ yield provider.get_tracer(__name__), exporter, handler
+ finally:
+ sdk_logger.removeHandler(handler)
+ sdk_logger.setLevel(previous)
+
+
+def _invoke(tracer, wrapped, metrics=None, disable_metrics=True):
+ return async_mod.async_general_wrap(
+ "crawl",
+ "0.0.0-test",
+ "test-env",
+ "test-app",
+ tracer,
+ pricing_info={},
+ capture_message_content=False,
+ metrics={} if metrics is None else metrics,
+ disable_metrics=disable_metrics,
+ )(wrapped, None, (), {})
+
+
+def _durations(exporter):
+ return [
+ span.attributes[DURATION]
+ for span in exporter.get_finished_spans()
+ if span.attributes and DURATION in span.attributes
+ ]
+
+
+def _page(index):
+ """Minimal crawl result. Dicts have no ``url`` attribute for the wrapper to copy."""
+ return SimpleNamespace(url=f"https://example.test/{index}", success=True)
+
+
+def _streaming_call(items=3):
+ async def call(*_args, **_kwargs):
+ async def generator():
+ for index in range(items):
+ yield _page(index)
+
+ return generator()
+
+ return call
+
+
+def _failing_stream(fail_at=1):
+ async def call(*_args, **_kwargs):
+ async def generator():
+ for index in range(fail_at + 1):
+ if index == fail_at:
+ raise RuntimeError("boom")
+ yield _page(index)
+
+ return generator()
+
+ return call
+
+
+def test_exhausted_stream_records_its_telemetry():
+ """The span must still be open when the generator finalises."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def drive():
+ result = await _invoke(tracer, _streaming_call())
+ assert hasattr(result, "__aiter__"), "expected the tracked generator"
+ # The span must not have been exported yet: the stream is still running.
+ assert not exporter.get_finished_spans(), (
+ "the span ended before the stream was consumed, so everything the "
+ "generator records afterwards is dropped"
+ )
+ consumed = 0
+ async for _ in result:
+ consumed += 1
+ return consumed
+
+ assert asyncio.run(drive()) == 3
+
+ spans = exporter.get_finished_spans()
+ assert _durations(exporter), "the streaming path recorded no duration at all"
+ assert len(spans) == 1
+ assert spans[0].status.status_code is StatusCode.OK
+ assert not dropped.records, (
+ f"the SDK dropped {len(dropped.records)} writes to an ended span: "
+ f"{dropped.records[:3]}"
+ )
+
+
+def test_abandoned_stream_is_still_exported():
+ """``async for`` + ``break`` does not call ``aclose()``. Dropping it must export."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def drive():
+ result = await _invoke(tracer, _streaming_call())
+ async for _ in result:
+ break
+
+ asyncio.run(drive())
+
+ spans = exporter.get_finished_spans()
+ assert spans, "the abandoned stream leaked its span"
+ assert len(spans) == 1
+ assert _durations(exporter), (
+ "an abandoned stream exported a span with no duration recorded"
+ )
+ assert not dropped.records, (
+ f"the SDK dropped {len(dropped.records)} writes to an ended span: "
+ f"{dropped.records[:3]}"
+ )
+
+
+def test_explicit_aclose_exports_once():
+ """A caller that closes early exports one span, and a second close is a no-op."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def drive():
+ result = await _invoke(tracer, _streaming_call())
+ page = await anext(result)
+ assert page.url == "https://example.test/0"
+ await result.aclose()
+ await result.aclose()
+
+ asyncio.run(drive())
+
+ assert len(exporter.get_finished_spans()) == 1
+ assert _durations(exporter)
+ assert not dropped.records
+
+
+def test_mid_stream_error_keeps_partial_telemetry():
+ """A failure after the first page still exports that page, the duration, and ERROR."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def drive():
+ result = await _invoke(tracer, _failing_stream())
+ async for _ in result:
+ pass
+
+ with pytest.raises(RuntimeError, match="boom"):
+ asyncio.run(drive())
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 1, "the mid-stream error leaked its span or ended it twice"
+ assert spans[0].status.status_code is StatusCode.ERROR
+ attrs = dict(spans[0].attributes or {})
+ assert DURATION in attrs, "the error path ended the span before recording duration"
+ assert attrs["gen_ai.crawl.current_url"] == "https://example.test/0"
+ assert attrs["gen_ai.crawl.url_count"] == 1
+ assert not dropped.records
+
+
+def test_cancelled_call_still_ends_its_span():
+ """Cancellation is a BaseException. The span must still export, with status unset."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def call(*_args, **_kwargs):
+ raise asyncio.CancelledError()
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(_invoke(tracer, call))
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 1, "cancelling the crawl leaked its span"
+ assert spans[0].status.status_code is StatusCode.UNSET
+ assert not dropped.records
+
+
+def test_cancelled_iteration_exports_partial_telemetry():
+ """Cancellation after a page is not a crawl failure, and the page is still exported."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def call(*_args, **_kwargs):
+ async def generator():
+ yield _page(0)
+ raise asyncio.CancelledError()
+
+ return generator()
+
+ async def drive():
+ result = await _invoke(tracer, call)
+ async for _ in result:
+ pass
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(drive())
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 1
+ assert spans[0].status.status_code is not StatusCode.ERROR
+ attrs = dict(spans[0].attributes or {})
+ assert DURATION in attrs
+ assert attrs["gen_ai.crawl.current_url"] == "https://example.test/0"
+ assert not dropped.records
+
+
+def test_non_streaming_response_still_ends_its_span():
+ """The ordinary path must be unaffected."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def call(*_args, **_kwargs):
+ return {"success": True}
+
+ asyncio.run(_invoke(tracer, call))
+
+ spans = exporter.get_finished_spans()
+ assert len(spans) == 1
+ assert spans[0].status.status_code is StatusCode.OK
+ assert _durations(exporter)
+ assert not dropped.records
+
+
+def test_failing_call_still_ends_its_span():
+ """An exception must end the span rather than leave it open."""
+ with _telemetry() as (tracer, exporter, dropped):
+ async def call(*_args, **_kwargs):
+ raise RuntimeError("boom")
+
+ with pytest.raises(RuntimeError):
+ asyncio.run(_invoke(tracer, call))
+
+ assert len(exporter.get_finished_spans()) == 1, "the error path leaked its span"
+ assert not dropped.records