Skip to content

fix(tracer): ensure coroutine spans are closed and tagged on failure#7729

Open
wregis wants to merge 1 commit intohyperf:masterfrom
wregis:fix-tracer-coroutine-aspect
Open

fix(tracer): ensure coroutine spans are closed and tagged on failure#7729
wregis wants to merge 1 commit intohyperf:masterfrom
wregis:fix-tracer-coroutine-aspect

Conversation

@wregis
Copy link
Copy Markdown
Contributor

@wregis wregis commented Mar 31, 2026

Description

This PR fixes a critical observability and memory management issue in the hyperf/tracer component when tracing coroutines (CoroutineAspect).

Motivation

Currently, if a coroutine executed via Co::create() throws an unhandled exception or is abruptly terminated, the tracer span is never finished ($child->finish()) and never flushed ($tracer->flush()).
This causes three main issues:

  1. Memory Leaks: Unflushed spans remain in the worker's memory buffer.
  2. Incomplete Traces: Orphaned spans that disappear from tracing UI (Jaeger/Zipkin).
  3. Missing Error Context: Exceptions happening inside the coroutine are not tagged (error=true) in the span, making troubleshooting difficult.

Changes made

  • Wrapped the callable execution in a try/catch/finally block to capture exceptions, add the error tag, and log the exception details to the span.
  • Implemented Co::defer as a fallback to guarantee the span is closed even if the coroutine lifecycle is interrupted by flow-control functions like Co::exit().
  • Used a lightweight \stdClass object to keep track of the span's finished state. This prevents multiple executions of finish()/flush() and avoids using variable references (&$finished) inside closures, which is a known anti-pattern in Swoole and triggers static analysis warnings.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

@wregis wregis force-pushed the fix-tracer-coroutine-aspect branch from a2851c8 to df43a07 Compare March 31, 2026 20:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant