Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions clients/python/src/examples/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
170 changes: 89 additions & 81 deletions clients/python/src/taskbroker_client/worker/workerchild.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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", [])
Expand All @@ -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",
Expand Down
113 changes: 113 additions & 0 deletions clients/python/tests/worker/test_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
Loading