diff --git a/conserver/main.py b/conserver/main.py index c793f311..bf29148a 100644 --- a/conserver/main.py +++ b/conserver/main.py @@ -8,6 +8,7 @@ operations for improved throughput with I/O-bound workloads. """ +import contextvars import importlib import logging import multiprocessing @@ -228,7 +229,6 @@ def __init__(self, chain_details: ChainConfig, vcon_id: str, context: Optional[D self.chain_details = chain_details self.context = context self._span = None - self._span_context_manager = None self._correlation_set = False def process(self) -> None: @@ -242,9 +242,20 @@ def process(self) -> None: storage.* spans for this vcon nest under one trace. A span link to the producer's trace is attached when self.context carries one; otherwise the span is created without a link. + + The span is ended and detached however the chain finishes. When a + link raises, the span records the exception and takes status ERROR, + and the exception goes on to the caller, which moves the vCon to the + DLQ. Left open, the span would stay current in this worker thread and + parent every chain the thread runs after it. """ - self._span_context_manager = self._create_span_from_context() - self._span = self._span_context_manager.__enter__() + with self._create_span_from_context() as span: + self._span = span + self._run_chain() + span.set_status(Status(StatusCode.OK)) + + def _run_chain(self) -> None: + """Run the links, then egress and storage, inside the span ``process`` holds open.""" vcon_started = time.time() logger.debug( "Started processing vCon %s with chain %s", @@ -287,15 +298,6 @@ def process(self) -> None: chain_attrs = {"chain.name": self.chain_details["name"]} record_histogram("conserver.main_loop.vcon_processing_time", vcon_processing_time, attributes=chain_attrs) increment_counter("conserver.main_loop.count_vcons_processed", attributes=chain_attrs) - - # End the vcon_processing span we opened at the top of run(). - try: - current_span = trace.get_current_span() - if current_span: - current_span.set_status(Status(StatusCode.OK)) - self._span_context_manager.__exit__(None, None, None) - except Exception as e: - logger.debug(f"Failed to end span: {e}") def _set_correlation_attributes(self, vcon_dict) -> None: """Put ``tenant.id`` and ``call.session_id`` on the chain span. @@ -492,9 +494,11 @@ def _process_storage_parallel(self, storage_backends: List[str]) -> None: ) with ThreadPoolExecutor(max_workers=len(storage_backends)) as executor: - # Submit all storage operations concurrently + # Submit all storage operations concurrently. Pool threads start with an + # empty context, so each write runs in its own copy of this thread's + # context, which carries the chain span for its storage span to nest under. future_to_storage = { - executor.submit(self._process_storage, storage_name): storage_name + executor.submit(contextvars.copy_context().run, self._process_storage, storage_name): storage_name for storage_name in storage_backends } diff --git a/conserver/tests/test_chain_span_context.py b/conserver/tests/test_chain_span_context.py new file mode 100644 index 00000000..0527dd68 --- /dev/null +++ b/conserver/tests/test_chain_span_context.py @@ -0,0 +1,273 @@ +"""The chain span in a worker thread: a chain whose link raises, the next chain, and parallel storage. + +A failed chain has to end its ``vcon_processing.`` span, mark it ERROR and detach it before +``_handle_vcon`` returns. Otherwise the span stays current in that worker thread and every later chain +the thread runs becomes its child. Storage writes run in a thread pool when parallel storage is on, and +their spans still belong under the chain span. + +Redis, the queue, storage and the link modules are mocks. Spans go to an in-memory exporter. The +correlation attributes are stubbed here; reading them from a vCon is covered in +``common/tests/test_otel_correlation.py``. The vCon fixtures are minimal and carry no lawful_basis +attachment: nothing here reads or depends on one. +""" + +import gc +import logging +import threading +from concurrent.futures import ThreadPoolExecutor +from types import SimpleNamespace +from unittest.mock import MagicMock, call, patch + +import pytest +from opentelemetry import trace +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 + +FAILED_UUID = "0192f0f0-0000-7000-8000-00000000000a" +NEXT_UUID = "0192f0f0-0000-7000-8000-00000000000b" +CORRELATION = {"tenant.id": "4242", "call.session_id": "session-abc-123"} + +FAILING_CHAIN = { + "name": "failing_chain", + "links": ["failing_link"], + "storages": [], + "egress_lists": [], + "ingress_lists": ["failing_ingress"], +} +PASSING_CHAIN = { + "name": "passing_chain", + "links": ["passing_link"], + "storages": [], + "egress_lists": [], + "ingress_lists": ["passing_ingress"], +} + + +class LinkFailure(RuntimeError): + pass + + +def _vcon_dict(uuid): + return {"uuid": uuid, "vcon": "0.4.0", "parties": [], "dialog": [], "attachments": [], "analysis": []} + + +def _finished(exporter, name): + return [s for s in exporter.get_finished_spans() if s.name == name] + + +def _in_one_worker_thread(fn): + """Run ``fn`` in a single pool thread, as a worker does with CONSERVER_VCON_CONCURRENCY above 1. + + Garbage collection is off while it runs. A failed request sits in a reference cycle through the + exception's traceback, and when the collector reaches it, it closes the abandoned span and detaches + its context at an arbitrary later moment. With the collector off, the test sees what the code does + on its own. + """ + was_enabled = gc.isenabled() + gc.disable() + try: + with ThreadPoolExecutor(max_workers=1) as pool: + return pool.submit(fn).result() + finally: + if was_enabled: + gc.enable() + + +@pytest.fixture(autouse=True) +def keep_loggers_enabled(): + """Importing main runs fileConfig, which disables loggers that already exist. Put them back so + other test modules still see their log output.""" + manager = logging.root.manager + before = {name: getattr(lg, "disabled", False) for name, lg in manager.loggerDict.items()} + yield + for name, disabled in before.items(): + manager.loggerDict[name].disabled = disabled + + +@pytest.fixture +def worker(): + """main with its I/O replaced by mocks and its spans going to an in-memory exporter.""" + import main + from vcon import Vcon + + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + + failing_module = MagicMock() + failing_module.run.side_effect = LinkFailure("a link that raises") + passing_module = MagicMock() + passing_module.run.side_effect = lambda vcon_id, link_name, options: vcon_id + vcon_redis = MagicMock() + vcon_redis.return_value.get_vcon.side_effect = lambda uuid: Vcon(_vcon_dict(uuid)) + queue = MagicMock() + storage = MagicMock() + correlation = MagicMock(return_value=dict(CORRELATION)) + config = { + "links": { + "failing_link": {"module": "failing_module", "options": {}}, + "passing_link": {"module": "passing_module", "options": {}}, + } + } + + with ( + patch.object(main, "config", config), + patch.dict(main.imported_modules, {"failing_module": failing_module, "passing_module": passing_module}), + patch("main.get_tracer", side_effect=lambda name: provider.get_tracer(name)), + patch("main.tracing_enabled", return_value=True), + patch("main.vcon_correlation_attributes", correlation), + patch("main.VconRedis", vcon_redis), + patch("main.r", MagicMock()), + patch("main.queue", queue), + patch("main.retrieve_context", return_value=None), + patch("main.Storage", storage), + ): + yield SimpleNamespace( + main=main, + spans=exporter, + queue=queue, + storage=storage, + correlation=correlation, + failing_module=failing_module, + ) + provider.shutdown() + + +def _fail(worker): + worker.main._handle_vcon("Worker-1", "failing_ingress", FAILED_UUID, FAILING_CHAIN) + + +def _pass(worker, chain=PASSING_CHAIN): + worker.main._handle_vcon("Worker-1", "passing_ingress", NEXT_UUID, chain) + + +def test_failed_chain_detaches_and_ends_its_span_before_handle_vcon_returns(worker): + def run(): + _fail(worker) + return trace.get_current_span(), [s.name for s in worker.spans.get_finished_spans()] + + current, finished_on_return = _in_one_worker_thread(run) + + worker.queue.enqueue_dlq.assert_called_once_with("failing_ingress", FAILED_UUID) + assert ( + not current.get_span_context().is_valid + ), f"span {getattr(current, 'name', current)!r} is still current in the worker thread" + assert ( + "vcon_processing.failing_chain" in finished_on_return + ), f"chain span not ended when _handle_vcon returned; finished: {finished_on_return}" + + +def test_next_chain_in_the_same_thread_gets_a_root_span_in_a_new_trace(worker): + def run(): + _fail(worker) + _pass(worker) + + _in_one_worker_thread(run) + + [next_span] = _finished(worker.spans, "vcon_processing.passing_chain") + failed_trace_ids = {s.context.trace_id for s in _finished(worker.spans, "link.failing_link")} + assert next_span.parent is None, f"next chain span has parent {next_span.parent.span_id:016x}; expected a root span" + assert next_span.context.trace_id not in failed_trace_ids + + +def test_failed_chain_span_is_error_with_the_exception_recorded(worker): + _in_one_worker_thread(lambda: _fail(worker)) + + chain_spans = _finished(worker.spans, "vcon_processing.failing_chain") + assert len(chain_spans) == 1, "the failed chain span was never ended" + chain_span = chain_spans[0] + assert chain_span.status.status_code is StatusCode.ERROR, f"status is {chain_span.status.status_code}" + exceptions = [e for e in chain_span.events if e.name == "exception"] + assert len(exceptions) == 1 + assert exceptions[0].attributes["exception.type"].endswith("LinkFailure") + assert exceptions[0].attributes["exception.message"] == "a link that raises" + + +@pytest.mark.parametrize("interrupt", [KeyboardInterrupt, SystemExit]) +def test_interrupt_from_a_link_still_ends_and_detaches_the_chain_span_on_its_way_out(worker, interrupt): + worker.failing_module.run.side_effect = interrupt() + + def run(): + try: + _fail(worker) + except interrupt: + # Look while the exception is still alive. Dropping it can free an abandoned span and + # close it by accident, which would hide a missing exit. + return trace.get_current_span(), [s.name for s in worker.spans.get_finished_spans()] + pytest.fail(f"{interrupt.__name__} did not reach the caller") + + current, finished_when_caught = _in_one_worker_thread(run) + + assert ( + not current.get_span_context().is_valid + ), f"span {getattr(current, 'name', current)!r} is still current in the worker thread" + assert ( + "vcon_processing.failing_chain" in finished_when_caught + ), f"chain span not ended when {interrupt.__name__} reached the caller; finished: {finished_when_caught}" + + +def test_egress_context_is_taken_inside_the_chain_span(worker): + chain = {**PASSING_CHAIN, "egress_lists": ["next_ingress"]} + with patch("main.store_context_sync") as store_context: + _in_one_worker_thread(lambda: _pass(worker, chain)) + + [chain_span] = _finished(worker.spans, "vcon_processing.passing_chain") + store_context.assert_called_once() + _redis, egress_list, vcon_id, context = store_context.call_args.args + assert (egress_list, vcon_id) == ("next_ingress", NEXT_UUID) + assert context["trace_id"] == format(chain_span.context.trace_id, "032x") + assert context["span_id"] == format(chain_span.context.span_id, "016x") + worker.queue.enqueue.assert_called_once_with("next_ingress", NEXT_UUID) + + +def test_parallel_storage_spans_nest_under_the_chain_span(worker): + chain = {**PASSING_CHAIN, "storages": ["store_a", "store_b"]} + # Each write waits for the other, so both are in flight at once and run on two pool threads. + # Without the wait the first write usually finishes before the second is submitted and the pool reuses + # one thread for both. + both_in_flight = threading.Barrier(2, timeout=5) + write_threads = {} + + def open_backend(name): + def save(vcon_id): + write_threads[name] = threading.current_thread().name + both_in_flight.wait() + + return SimpleNamespace(save=save) + + worker.storage.side_effect = open_backend + + def run(): + with patch("main.is_parallel_storage_enabled", return_value=True): + _pass(worker, chain) + return threading.current_thread().name + + chain_thread = _in_one_worker_thread(run) + + assert len(set(write_threads.values())) == 2, f"writes ran on {write_threads}" + assert chain_thread not in write_threads.values() + [chain_span] = _finished(worker.spans, "vcon_processing.passing_chain") + storage_spans = [s for s in worker.spans.get_finished_spans() if s.name.startswith("storage.")] + assert sorted(s.name for s in storage_spans) == ["storage.store_a", "storage.store_b"] + for span in storage_spans: + assert span.parent is not None, f"{span.name} is a root span" + assert span.parent.span_id == chain_span.context.span_id + assert span.context.trace_id == chain_span.context.trace_id + assert sorted(worker.storage.call_args_list) == [call("store_a"), call("store_b")] + worker.queue.enqueue_dlq.assert_not_called() + + +def test_successful_chain_span_is_ok_with_correlation_attributes(worker): + _in_one_worker_thread(lambda: _pass(worker)) + + [chain_span] = _finished(worker.spans, "vcon_processing.passing_chain") + assert chain_span.status.status_code is StatusCode.OK + attrs = dict(chain_span.attributes) + assert attrs["vcon.uuid"] == NEXT_UUID + for key, value in CORRELATION.items(): + assert attrs[key] == value + worker.correlation.assert_called_once() + assert worker.correlation.call_args.args[0]["uuid"] == NEXT_UUID + worker.queue.enqueue_dlq.assert_not_called()