Repository navigation
fix(otel): preserve replay completion telemetry #758
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
128 changes: 128 additions & 0 deletions
128
...aws-durable-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/_flush.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| """Bound caller waiting for provider I/O without moving plugin lifecycle hooks.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import contextvars | ||
| import logging | ||
| import threading | ||
| import time | ||
| from dataclasses import dataclass, field | ||
|
|
||
| from opentelemetry.trace import TracerProvider | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # Match the OTel provider's existing default budget. Some processors ignore | ||
| # that cooperative budget, so the SDK bounds its own wait independently. | ||
| _FLUSH_TIMEOUT_SECONDS = 30.0 | ||
| _lock = threading.Condition(threading.Lock()) | ||
|
|
||
|
|
||
| @dataclass | ||
| class _Attempt: | ||
| done: threading.Event = field(default_factory=threading.Event) | ||
| result: object = None | ||
| error: BaseException | None = None | ||
| timed_out: bool = False | ||
|
|
||
|
|
||
| # Identity keys support custom providers with value equality or no hash. The | ||
| # worker retains its provider until removal, so an active key cannot be reused. | ||
| _active: dict[int, _Attempt] = {} | ||
|
|
||
|
|
||
| def _run(provider: TracerProvider, attempt: _Attempt) -> None: | ||
| provider_id = id(provider) | ||
| try: | ||
| try: | ||
| # force_flush is an optional extension to the API provider. The | ||
| # plugin checks for it before invoking this helper. | ||
| attempt.result = getattr(provider, "force_flush")() | ||
| except BaseException as error: | ||
| # Fatal exceptions completed within the wait are re-raised on the | ||
| # lifecycle owner. A late error cannot be thrown into a returned call. | ||
| attempt.error = error | ||
| with _lock: | ||
| late = attempt.timed_out | ||
| if not late and _active.get(provider_id) is attempt: | ||
| del _active[provider_id] | ||
| _lock.notify_all() | ||
| attempt.done.set() | ||
| if late and attempt.error is not None: | ||
| logger.error( | ||
| "Provider flush failed after the caller stopped waiting", | ||
| exc_info=( | ||
| type(attempt.error), | ||
| attempt.error, | ||
| attempt.error.__traceback__, | ||
| ), | ||
| ) | ||
| finally: | ||
| # Retain the slot through actual completion, even after timeout. There | ||
| # is no queue and no new worker per invocation for a stuck exporter. | ||
| with _lock: | ||
| if _active.get(provider_id) is attempt: | ||
| del _active[provider_id] | ||
| _lock.notify_all() | ||
|
|
||
|
|
||
| def flush_provider(provider: TracerProvider) -> bool: | ||
| """Wait for provider I/O, with one outstanding attempt per provider. | ||
|
|
||
| Start/End and ContextVar-token cleanup stay on their existing owner. Only | ||
| the supplied provider method runs elsewhere, using the post-cleanup Context | ||
| snapshot. Admission and completion share one absolute deadline. Expired | ||
| requests return False without queueing more work; active I/O is never cancelled. | ||
| Each admitted caller starts a new flush after prior I/O completes, since spans | ||
| queued during a prior attempt may not have been included in that attempt. | ||
| This does not bound synchronous span processors' earlier ``on_end`` calls, | ||
| application-owned provider shutdown, or exporter transport I/O itself. | ||
| """ | ||
| deadline = time.monotonic() + _FLUSH_TIMEOUT_SECONDS | ||
| provider_id = id(provider) | ||
| with _lock: | ||
| while provider_id in _active: | ||
| remaining = deadline - time.monotonic() | ||
| if remaining <= 0: | ||
| break | ||
| _lock.wait(remaining) | ||
| if provider_id not in _active and time.monotonic() < deadline: | ||
| attempt = _Attempt() | ||
| _active[provider_id] = attempt | ||
| else: | ||
| attempt = None | ||
| if attempt is None: | ||
| logger.warning("Provider flush admission exceeded the caller wait budget") | ||
| return False | ||
|
|
||
| owner_context = contextvars.copy_context() | ||
| try: | ||
| threading.Thread( | ||
| target=owner_context.run, | ||
| args=(_run, provider, attempt), | ||
| name="durable-otel-flush", | ||
| daemon=True, | ||
| ).start() | ||
| except BaseException: | ||
| with _lock: | ||
| if _active.get(provider_id) is attempt: | ||
| del _active[provider_id] | ||
| _lock.notify_all() | ||
| raise | ||
|
|
||
| completed = attempt.done.wait(max(0.0, deadline - time.monotonic())) | ||
| if not completed: | ||
| with _lock: | ||
| completed = attempt.done.is_set() | ||
| if not completed: | ||
| attempt.timed_out = True | ||
| if not completed: | ||
| logger.warning("Provider flush exceeded the caller wait budget") | ||
| return False | ||
| if attempt.error is not None: | ||
| raise attempt.error | ||
| if attempt.result is False: | ||
| logger.warning("Provider reported an incomplete flush") | ||
| return False | ||
| return True | ||
92 changes: 92 additions & 0 deletions
92
...-execution-sdk-python-otel/src/aws_durable_execution_sdk_python_otel/_invocation_state.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| """Invocation-owned completion metadata and bounded finalization.""" | ||
|
|
||
| from collections.abc import Callable, Mapping | ||
|
|
||
| from aws_durable_execution_sdk_python.plugin import ( | ||
| InvocationStartInfo, | ||
| OperationInfo, | ||
| OperationStatus, | ||
| OperationType, | ||
| ) | ||
|
|
||
|
|
||
| class InvocationFinalization: | ||
| """Defer failures until invocation cleanup, with one ordinary export retry. | ||
|
|
||
| Operation claims and failures use the plugin's registry lock. Finalization | ||
| actions and error reporting run on the invocation owner. Control exceptions | ||
| are held only to finish cleanup; they are never retried or swallowed. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._attempts: dict[str, int] = {} | ||
| self._stopped_operations: set[str] = set() | ||
| self._retryable_operations: set[str] = set() | ||
| self._errors: list[BaseException] = [] | ||
|
|
||
| def claim_operation(self, operation_id: str) -> bool: | ||
| attempts = self._attempts.get(operation_id, 0) | ||
| if attempts >= 2 or operation_id in self._stopped_operations: | ||
| return False | ||
| self._attempts[operation_id] = attempts + 1 | ||
| self._retryable_operations.discard(operation_id) | ||
| return True | ||
|
|
||
| def operation_failed(self, operation_id: str, error: BaseException) -> None: | ||
| self._errors.append(error) | ||
| if not isinstance(error, Exception): | ||
| self._stopped_operations.add(operation_id) | ||
| elif self._attempts[operation_id] < 2: | ||
| self._retryable_operations.add(operation_id) | ||
|
|
||
| def can_retry(self, operation_id: str) -> bool: | ||
| return operation_id in self._retryable_operations | ||
|
|
||
| def run(self, action: Callable[[], None]) -> None: | ||
| try: | ||
| action() | ||
| except BaseException as error: | ||
| self._errors.append(error) | ||
|
|
||
| def raise_errors(self) -> None: | ||
| if len(self._errors) == 1: | ||
| raise self._errors[0] | ||
| if self._errors: | ||
| raise BaseExceptionGroup( | ||
| "OpenTelemetry invocation finalization failed", self._errors | ||
| ) | ||
|
|
||
|
|
||
| def terminal_updates( | ||
| operations: Mapping[str, OperationInfo], | ||
| ) -> dict[str, OperationInfo]: | ||
| """Retain visible terminal updates until their operation hook or invocation End.""" | ||
| return { | ||
| operation_id: operation | ||
| for operation_id, operation in operations.items() | ||
| if operation.status | ||
| in ( | ||
| OperationStatus.SUCCEEDED, | ||
| OperationStatus.FAILED, | ||
| OperationStatus.TIMED_OUT, | ||
| OperationStatus.STOPPED, | ||
| OperationStatus.CANCELLED, | ||
| ) | ||
| } | ||
|
|
||
|
|
||
| def completed_input_parents(info: InvocationStartInfo) -> list[OperationInfo]: | ||
| """Known terminal contexts that may parent input or later checkpoint updates.""" | ||
| return [ | ||
| operation | ||
| for operation in info.operations.values() | ||
| if operation.operation_type is OperationType.CONTEXT | ||
| and operation.status | ||
| in ( | ||
| OperationStatus.SUCCEEDED, | ||
| OperationStatus.FAILED, | ||
| OperationStatus.TIMED_OUT, | ||
| OperationStatus.STOPPED, | ||
| OperationStatus.CANCELLED, | ||
| ) | ||
| ] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Codex AI review · Finding
arf_v1_544qkisfhmjei34ezfmfd3d24g[P3] Return the new flush mechanism to the design phase
Rules 2, “Simplify before you add,” and 3, “Write a design note before the code,” require alternatives and their rejection reasons before adding this feature. The description summarizes daemon workers, provider admission, and a fixed deadline, but does not explain the separate flushing problem and cause or evaluate simpler options. Return to the design phase under rule 8, step 6, and obtain agreement on a note comparing provider-managed timeouts with this additional lifecycle mechanism before continuing implementation.
To suppress repeats, reply
/ai verdict deferred,/ai verdict false-positive, or/ai verdict out-of-scopeon the first nonblank line. Add rationale on later lines. A new/ai verdict acceptedallows future repeats again.