Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(tracing): atexit_flush=True process-exit safety net (#91)

Chris3d18b5620631
diff --git a/cubepi/tracing/tracer.py b/cubepi/tracing/tracer.py
index 9a96e92..bf9c6b6 100644
--- a/cubepi/tracing/tracer.py
+++ b/cubepi/tracing/tracer.py
@@ -8,6 +8,7 @@ the agent's event stream.
from __future__ import annotations
+import atexit
import contextlib
import uuid
from typing import TYPE_CHECKING, Any, AsyncIterator, Callable
@@ -72,6 +73,8 @@ class Tracer:
record_content: bool = False,
redact: "Callable[[str, Any], Any] | None" = None,
resource: Resource | None = None,
+ atexit_flush: bool = True,
+ atexit_flush_timeout_seconds: float = 5.0,
) -> None:
self._record_content = record_content
self._redact = redact
@@ -101,6 +104,20 @@ class Tracer:
schema_url=SCHEMA_URL,
)
self._shutdown = False
+ self._atexit_flush_timeout_ms = int(atexit_flush_timeout_seconds * 1000)
+ self._atexit_unregister: Callable[[], None] | None = None
+ if atexit_flush:
+ # Safety net for callers that forget ``await tracer.shutdown()``:
+ # at process exit, sync-flush any buffered spans through
+ # BatchSpanProcessor. Idempotent — ``shutdown()`` flips
+ # ``self._shutdown`` so this becomes a no-op when the user
+ # cleaned up properly. Matches the Traceloop SDK pattern.
+ #
+ # Limitations: ``atexit`` does NOT run on SIGKILL, kernel
+ # OOM kill, or os._exit(). For guaranteed delivery under
+ # those conditions, use SimpleSpanProcessor instead.
+ atexit.register(self._atexit_flush)
+ self._atexit_unregister = lambda: atexit.unregister(self._atexit_flush)
# -- public API ---------------------------------------------------
@@ -209,6 +226,38 @@ class Tracer:
await self.force_flush(timeout_seconds=timeout_seconds)
self._provider.shutdown()
self._shutdown = True
+ # Remove the atexit hook now that the user has cleaned up
+ # explicitly — keeps the interpreter's atexit table from
+ # growing unbounded when many Tracers are constructed (e.g.
+ # in tests) and prevents a redundant flush at interpreter
+ # shutdown.
+ if self._atexit_unregister is not None:
+ try:
+ self._atexit_unregister()
+ except Exception:
+ pass
+ self._atexit_unregister = None
+
+ def _atexit_flush(self) -> None:
+ """Process-exit safety net: sync-flush any buffered spans.
+
+ Runs in the interpreter's atexit handler chain — no event
+ loop available, so we call ``provider.force_flush``
+ synchronously (BatchSpanProcessor's flush is sync; it blocks
+ the calling thread until the queue drains or the timeout
+ elapses).
+
+ Idempotent with ``shutdown()`` — if the user cleaned up
+ explicitly, ``_shutdown`` is True and we no-op.
+ """
+ if self._shutdown:
+ return
+ try:
+ self._provider.force_flush(timeout_millis=self._atexit_flush_timeout_ms)
+ except Exception:
+ # atexit hooks must never raise — would corrupt interpreter
+ # shutdown for everything else.
+ pass
@contextlib.asynccontextmanager
async def attached(self, agent: "Agent") -> AsyncIterator["Tracer"]:
diff --git a/tests/tracing/test_recorder.py b/tests/tracing/test_recorder.py
index 0721fe9..48e1e8e 100644
--- a/tests/tracing/test_recorder.py
+++ b/tests/tracing/test_recorder.py
@@ -931,6 +931,127 @@ class TestLifecycle:
assert tracer is not None
+class TestAtexitFlush:
+ """``Tracer(atexit_flush=True)`` registers a process-exit hook
+ that sync-flushes any buffered spans through BatchSpanProcessor.
+ Safety net for callers who forget ``await tracer.shutdown()`` —
+ matches the Traceloop SDK pattern. atexit doesn't run on
+ SIGKILL / os._exit but covers normal Ctrl-C / unhandled
+ exception / sys.exit paths."""
+
+ def test_registers_atexit_when_enabled(self, monkeypatch):
+ registered: list = []
+ unregistered: list = []
+ import atexit as _atexit
+
+ monkeypatch.setattr(_atexit, "register", lambda f: registered.append(f))
+ monkeypatch.setattr(_atexit, "unregister", lambda f: unregistered.append(f))
+
+ tracer = Tracer(service_name="t", exporters=[])
+ assert tracer._atexit_flush in registered
+ assert tracer._atexit_unregister is not None
+ # Sanity: the unregister callback removes the same function.
+ tracer._atexit_unregister()
+ assert tracer._atexit_flush in unregistered
+
+ def test_disabled_when_opted_out(self, monkeypatch):
+ registered: list = []
+ import atexit as _atexit
+
+ monkeypatch.setattr(_atexit, "register", lambda f: registered.append(f))
+ tracer = Tracer(service_name="t", exporters=[], atexit_flush=False)
+ assert tracer._atexit_flush not in registered
+ assert tracer._atexit_unregister is None
+
+ async def test_atexit_flush_calls_provider_force_flush(self):
+ flushed: list = []
+
+ class _FakeProvider:
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ flushed.append(timeout_millis)
+ return True
+
+ def shutdown(self) -> None:
+ pass
+
+ tracer = Tracer(service_name="t", exporters=[], atexit_flush=False)
+ tracer._provider = _FakeProvider() # type: ignore[assignment]
+ tracer._atexit_flush_timeout_ms = 5000
+ tracer._atexit_flush()
+ assert flushed == [5000]
+
+ async def test_atexit_flush_noop_after_shutdown(self):
+ flushed: list = []
+
+ class _FakeProvider:
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ flushed.append(timeout_millis)
+ return True
+
+ def shutdown(self) -> None:
+ pass
+
+ tracer = Tracer(service_name="t", exporters=[], atexit_flush=False)
+ tracer._provider = _FakeProvider() # type: ignore[assignment]
+ await tracer.shutdown()
+ flushed.clear()
+ tracer._atexit_flush()
+ assert flushed == [], "atexit hook must no-op after explicit shutdown"
+
+ def test_atexit_flush_swallows_exceptions(self):
+ """atexit handlers must NEVER raise — would corrupt
+ interpreter shutdown for every other registered handler."""
+
+ class _BoomProvider:
+ def force_flush(self, timeout_millis: int = 30_000) -> bool:
+ raise RuntimeError("flush boom")
+
+ def shutdown(self) -> None:
+ pass
+
+ tracer = Tracer(service_name="t", exporters=[], atexit_flush=False)
+ tracer._provider = _BoomProvider() # type: ignore[assignment]
+ # Must NOT raise.
+ tracer._atexit_flush()
+
+ async def test_shutdown_swallows_unregister_failure(self, monkeypatch):
+ """If ``atexit.unregister`` raises (e.g. mocked away or Python
+ version edge case), ``shutdown()`` must still complete — the
+ unregister is best-effort cleanup."""
+ import atexit as _atexit
+
+ def _bad_unregister(_f):
+ raise RuntimeError("unregister boom")
+
+ monkeypatch.setattr(_atexit, "register", lambda f: None)
+ monkeypatch.setattr(_atexit, "unregister", _bad_unregister)
+ tracer = Tracer(service_name="t", exporters=[])
+ # Replace the unregister callback with one that hits the
+ # patched atexit.unregister.
+ tracer._atexit_unregister = lambda: _atexit.unregister(tracer._atexit_flush)
+ # Must NOT raise.
+ await tracer.shutdown()
+
+ async def test_shutdown_unregisters_atexit_hook(self, monkeypatch):
+ unregistered: list = []
+ import atexit as _atexit
+
+ monkeypatch.setattr(_atexit, "register", lambda f: None)
+ monkeypatch.setattr(_atexit, "unregister", lambda f: unregistered.append(f))
+
+ tracer = Tracer(service_name="t", exporters=[])
+ hook = tracer._atexit_flush
+ await tracer.shutdown()
+ assert hook in unregistered, (
+ "shutdown() must unregister the atexit hook to keep the "
+ "atexit table from growing across many Tracer instances"
+ )
+ # Idempotent: a second shutdown does not double-unregister.
+ unregistered.clear()
+ await tracer.shutdown()
+ assert unregistered == []
+
+
class TestJsonlExporter:
async def test_writes_jsonl_files(self, tmp_path):
from cubepi.tracing.exporters import JsonlSpanExporter