From 0088cb14c5c820aeb16550fb8fda0662dfd1db1a Mon Sep 17 00:00:00 2001 From: Alberto Leal Date: Tue, 17 Nov 2026 11:48:36 -0500 Subject: [PATCH] fix(worker): Report task failures inside the task's Sentry scope A task runs in its own Sentry isolation scope, opened in _execute_activation. The failure reports in run_worker ran after that scope had closed. So the tags, contexts and trace that a task set did not reach the task's error events. Open the task's isolation scope in run_worker, around the task call and the failure reports. Each task still gets a fresh fork of the worker scope, so nothing reaches the next task. --- clients/python/src/examples/tasks.py | 17 ++ .../taskbroker_client/worker/workerchild.py | 170 +++++++++--------- clients/python/tests/worker/test_worker.py | 113 ++++++++++++ 3 files changed, 219 insertions(+), 81 deletions(-) diff --git a/clients/python/src/examples/tasks.py b/clients/python/src/examples/tasks.py index c3474660..8bcc61e6 100644 --- a/clients/python/src/examples/tasks.py +++ b/clients/python/src/examples/tasks.py @@ -9,6 +9,7 @@ from time import sleep from typing import Any +import sentry_sdk from arroyo.backends.kafka import FutureTrackingProducer, KafkaPayload, KafkaProducer from arroyo.types import Topic from redis import StrictRedis @@ -78,6 +79,22 @@ def timed_task(sleep_seconds: float | str, *args: list[Any], **kwargs: dict[str, logger.debug("timed_task complete") +@exampletasks.register( + name="examples.tagged", + retry=Retry(times=3, on=(RuntimeError,), times_exceeded=LastAction.Discard), +) +def tagged_task(tag: str, action: str) -> None: + """Set Sentry scope data, then do `action`: "pass", "raise" (retried), "fail" or "sleep".""" + sentry_sdk.set_tag("example.task_tag", tag) + sentry_sdk.set_context("example", {"tag": tag}) + if action == "raise": + raise RuntimeError("oh no") + if action == "fail": + raise ValueError("nope") + if action == "sleep": + sleep(3) + + @exampletasks.register( name="examples.will_timeout_without_reporting", processing_deadline_duration=1, diff --git a/clients/python/src/taskbroker_client/worker/workerchild.py b/clients/python/src/taskbroker_client/worker/workerchild.py index 7ca5ee9e..57cf0c19 100644 --- a/clients/python/src/taskbroker_client/worker/workerchild.py +++ b/clients/python/src/taskbroker_client/worker/workerchild.py @@ -503,88 +503,93 @@ def check_task_future_completion( next_state = TASK_ACTIVATION_STATUS_FAILURE # Use time.time() so we can measure against activation.received_at execution_start_time = time.time() - try: - with timeout_alarm(inflight.activation.processing_deadline_duration, handle_alarm): - _execute_activation(task_func, inflight.activation, app.context_hooks) - next_state = TASK_ACTIVATION_STATUS_COMPLETE - except ProcessingDeadlineExceeded as err: - if task_func.report_timeout_errors: - with sentry_sdk.isolation_scope() as scope: - scope.fingerprint = [ - "taskworker.processing_deadline_exceeded", - inflight.activation.namespace, - inflight.activation.taskname, - ] - # Override transaction names inherited from worker startup. - sentry_sdk.get_current_scope().set_transaction_name( - inflight.activation.taskname - ) - _log_task_failed(inflight.activation, err, processing_pool_name) - metrics.incr( - "taskworker.worker.processing_deadline_exceeded", - tags={ - "processing_pool": processing_pool_name, - "namespace": inflight.activation.namespace, - "taskname": inflight.activation.taskname, - }, - ) - retry = task_func.retry - if retry and retry.should_retry(inflight.activation.retry_state, err): - next_state = TASK_ACTIVATION_STATUS_RETRY - else: - next_state = TASK_ACTIVATION_STATUS_FAILURE - except Exception as err: - retry = task_func.retry - captured_error = False - should_capture_error = not isinstance(err, task_func.silenced_exceptions) - if retry: - if retry.should_retry(inflight.activation.retry_state, err): - logger.info( - "taskworker.task.retry", - extra={ - "namespace": inflight.activation.namespace, - "taskname": inflight.activation.taskname, - "processing_pool": processing_pool_name, - "error": str(err), - }, - ) - next_state = TASK_ACTIVATION_STATUS_RETRY - elif retry.max_attempts_reached(inflight.activation.retry_state): + # The task's isolation scope also covers failure reporting below, so the + # tags, contexts and trace that the task sets reach its error events. + with sentry_sdk.isolation_scope(): + try: + with timeout_alarm( + inflight.activation.processing_deadline_duration, handle_alarm + ): + _execute_activation(task_func, inflight.activation, app.context_hooks) + next_state = TASK_ACTIVATION_STATUS_COMPLETE + except ProcessingDeadlineExceeded as err: + if task_func.report_timeout_errors: with sentry_sdk.isolation_scope() as scope: - # Only report to Sentry when the underlying error is not silenced. - if should_capture_error: - retry_error = NoRetriesRemainingError( - f"{inflight.activation.taskname} has consumed all of its retries" - ) - retry_error.__cause__ = err - scope.fingerprint = [ - "taskworker.no_retries_remaining", - inflight.activation.namespace, - inflight.activation.taskname, - ] - sentry_sdk.get_current_scope().set_transaction_name( - inflight.activation.taskname + scope.fingerprint = [ + "taskworker.processing_deadline_exceeded", + inflight.activation.namespace, + inflight.activation.taskname, + ] + # Override transaction names inherited from worker startup. + sentry_sdk.get_current_scope().set_transaction_name( + inflight.activation.taskname + ) + _log_task_failed(inflight.activation, err, processing_pool_name) + metrics.incr( + "taskworker.worker.processing_deadline_exceeded", + tags={ + "processing_pool": processing_pool_name, + "namespace": inflight.activation.namespace, + "taskname": inflight.activation.taskname, + }, + ) + retry = task_func.retry + if retry and retry.should_retry(inflight.activation.retry_state, err): + next_state = TASK_ACTIVATION_STATUS_RETRY + else: + next_state = TASK_ACTIVATION_STATUS_FAILURE + except Exception as err: + retry = task_func.retry + captured_error = False + should_capture_error = not isinstance(err, task_func.silenced_exceptions) + if retry: + if retry.should_retry(inflight.activation.retry_state, err): + logger.info( + "taskworker.task.retry", + extra={ + "namespace": inflight.activation.namespace, + "taskname": inflight.activation.taskname, + "processing_pool": processing_pool_name, + "error": str(err), + }, + ) + next_state = TASK_ACTIVATION_STATUS_RETRY + elif retry.max_attempts_reached(inflight.activation.retry_state): + with sentry_sdk.isolation_scope() as scope: + # Only report to Sentry when the underlying error is not silenced. + if should_capture_error: + retry_error = NoRetriesRemainingError( + f"{inflight.activation.taskname} has consumed all of its retries" + ) + retry_error.__cause__ = err + scope.fingerprint = [ + "taskworker.no_retries_remaining", + inflight.activation.namespace, + inflight.activation.taskname, + ] + sentry_sdk.get_current_scope().set_transaction_name( + inflight.activation.taskname + ) + sentry_sdk.capture_exception(retry_error) + # Emit a structured worker log without logger.exception so this + # branch does not create a second Sentry error event. + _log_task_retry_exhausted( + inflight.activation, err, processing_pool_name ) - sentry_sdk.capture_exception(retry_error) - # Emit a structured worker log without logger.exception so this - # branch does not create a second Sentry error event. - _log_task_retry_exhausted( - inflight.activation, err, processing_pool_name + # In this branch, all exceptions should be either + # captured or silenced. + captured_error = True + + if ( + should_capture_error + and not captured_error + and next_state != TASK_ACTIVATION_STATUS_RETRY + ): + with sentry_sdk.isolation_scope(): + sentry_sdk.get_current_scope().set_transaction_name( + inflight.activation.taskname ) - # In this branch, all exceptions should be either - # captured or silenced. - captured_error = True - - if ( - should_capture_error - and not captured_error - and next_state != TASK_ACTIVATION_STATUS_RETRY - ): - with sentry_sdk.isolation_scope(): - sentry_sdk.get_current_scope().set_transaction_name( - inflight.activation.taskname - ) - _log_task_failed(inflight.activation, err, processing_pool_name) + _log_task_failed(inflight.activation, err, processing_pool_name) clear_current_task() processed_task_count += 1 @@ -654,7 +659,11 @@ def _execute_activation( activation: TaskActivation, context_hooks: Sequence[ContextHook] = (), ) -> None: - """Invoke a task function with the activation parameters.""" + """ + Invoke a task function with the activation parameters. + + Call this inside the task's isolation scope. + """ parameters = load_parameters(activation) args = parameters.get("args", []) @@ -667,7 +676,6 @@ def _execute_activation( "taskworker.worker.memory_change", tags={"namespace": activation.namespace, "taskname": activation.taskname}, ), - sentry_sdk.isolation_scope(), start_segment( name=activation.taskname, op="queue.task.taskworker", diff --git a/clients/python/tests/worker/test_worker.py b/clients/python/tests/worker/test_worker.py index 9d8e9f67..79a89ebb 100644 --- a/clients/python/tests/worker/test_worker.py +++ b/clients/python/tests/worker/test_worker.py @@ -2829,6 +2829,119 @@ def test_child_process_error_event_uses_task_transaction( assert event["transaction"] == taskname +TAGGED_TASK_TRACE_ID = "a" * 32 + + +def _tagged_task( + tag: str, + action: str, + deadline: int = 2, + retry_state: RetryState | None = None, +) -> InflightTaskActivation: + return InflightTaskActivation( + host="localhost:50051", + receive_timestamp=0, + activation=TaskActivation( + id="tagged", + namespace="examples", + taskname="examples.tagged", + parameters_bytes=msgpack.packb( + {"args": [tag, action], "kwargs": {}}, use_bin_type=True + ), + processing_deadline_duration=deadline, + retry_state=retry_state or RetryState(), + headers={"sentry-trace": f"{TAGGED_TASK_TRACE_ID}-{'b' * 16}"}, + ), + ) + + +def _run_child_capturing_events( + *tasks: InflightTaskActivation, +) -> tuple[list[ProcessingResult], list[dict[str, Any]]]: + """Run `tasks` in one worker child. Return their results and the Sentry error events.""" + todo: queue.Queue[InflightTaskActivation] = queue.Queue() + processed: queue.Queue[ProcessingResult] = queue.Queue() + for task in tasks: + todo.put(task) + + # Inspect each fully processed error event, then drop it instead of sending it. + capture_event = mock.Mock(return_value=None) + with ( + sentry_sdk.Client( + dsn="https://public@example.com/1", + default_integrations=False, + integrations=[LoggingIntegration()], + transport=mock.Mock(spec=Transport), + before_send=capture_event, + traces_sample_rate=0, + trace_lifecycle="stream", + ) as client, + sentry_sdk.isolation_scope() as scope, + ): + scope.set_client(client) + child_process( + "examples.app:app", + todo, + processed, + Event(), + max_task_count=len(tasks), + processing_pool_name="test", + process_type="fork", + skip_awaiting_futures=False, + future_checking_frequency=0.1, + ) + + results = [processed.get_nowait() for _ in tasks] + events = [call.args[0] for call in capture_event.call_args_list] + return results, events + + +@pytest.mark.usefixtures("restore_signal_handlers") +@pytest.mark.parametrize( + ("action", "deadline", "retry_state"), + [ + pytest.param("fail", 2, RetryState(), id="exception"), + pytest.param("raise", 2, RetryState(attempts=2, max_attempts=3), id="retry-exhausted"), + pytest.param("sleep", 1, RetryState(), id="timeout"), + ], +) +def test_child_process_error_event_has_task_scope_data( + action: str, deadline: int, retry_state: RetryState +) -> None: + results, events = _run_child_capturing_events( + _tagged_task("from-task", action, deadline, retry_state) + ) + + assert [result.status for result in results] == [TASK_ACTIVATION_STATUS_FAILURE] + [event] = events + assert event["tags"]["example.task_tag"] == "from-task" + assert event["contexts"]["example"] == {"tag": "from-task"} + assert event["contexts"]["trace"]["trace_id"] == TAGGED_TASK_TRACE_ID + + +@pytest.mark.usefixtures("restore_signal_handlers") +@pytest.mark.parametrize( + ("first_action", "first_status", "event_count"), + [ + pytest.param("pass", TASK_ACTIVATION_STATUS_COMPLETE, 1, id="after-success"), + pytest.param("fail", TASK_ACTIVATION_STATUS_FAILURE, 2, id="after-failure"), + ], +) +def test_child_process_task_scope_data_does_not_reach_next_task( + first_action: str, first_status: int, event_count: int +) -> None: + results, events = _run_child_capturing_events( + _tagged_task("from-first-task", first_action), FAIL_TASK + ) + + assert [result.status for result in results] == [first_status, TASK_ACTIVATION_STATUS_FAILURE] + # A successful task makes no event. The last event is from FAIL_TASK, which sets no scope data. + assert len(events) == event_count + assert "example.task_tag" not in events[-1].get("tags", {}) + assert "example" not in events[-1]["contexts"] + assert events[-1]["contexts"]["trace"]["trace_id"] != TAGGED_TASK_TRACE_ID + + @mock.patch("taskbroker_client.worker.workerchild.capture_checkin") def test_child_process_decompression(mock_capture_checkin: mock.MagicMock) -> None: