Skip to content
Merged
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
5 changes: 4 additions & 1 deletion .github/docker/ci/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,9 @@ RUN set -eux; \

RUN set -eux; \
pie_packages=(); \
if ! php -r 'exit(extension_loaded("excimer") ? 0 : 1);'; then \
pie_packages+=(wikimedia/excimer); \
fi; \
if ! php -r 'exit(extension_loaded("redis") && version_compare((string) phpversion("redis"), "6.3.0", ">=") ? 0 : 1);'; then \
pie_packages+=(phpredis/phpredis); \
fi; \
Expand Down Expand Up @@ -145,7 +148,7 @@ RUN set -eux; \
else \
test "$(php -r 'echo phpversion("swoole");')" = "${SWOOLE_VERSION}"; \
fi; \
php -r '$extensions = ["bcmath", "ctype", "curl", "dom", "fileinfo", "filter", "gd", "gmp", "imagick", "intl", "mbstring", "openssl", "pcntl", "pdo", "pdo_mysql", "pdo_pgsql", "pdo_sqlite", "posix", "protobuf", "redis", "session", "sockets", "sqlite3", "swoole", "tokenizer", "zlib"]; foreach ($extensions as $extension) { if (! extension_loaded($extension)) { fwrite(STDERR, "Missing required extension: {$extension}\n"); exit(1); } } foreach (["imagewebp", "imageavif"] as $function) { if (! function_exists($function)) { fwrite(STDERR, "Missing required GD function: {$function}()\n"); exit(1); } } if (version_compare((string) phpversion("redis"), "6.3.0", "<")) { fwrite(STDERR, "Redis extension 6.3.0 or newer is required for full integration coverage.\n"); exit(1); } if ((bool) ini_get("swoole.use_shortname")) { fwrite(STDERR, "Swoole short names must be disabled.\n"); exit(1); }'; \
php -r '$extensions = ["bcmath", "ctype", "curl", "dom", "excimer", "fileinfo", "filter", "gd", "gmp", "imagick", "intl", "mbstring", "openssl", "pcntl", "pdo", "pdo_mysql", "pdo_pgsql", "pdo_sqlite", "posix", "protobuf", "redis", "session", "sockets", "sqlite3", "swoole", "tokenizer", "zlib"]; foreach ($extensions as $extension) { if (! extension_loaded($extension)) { fwrite(STDERR, "Missing required extension: {$extension}\n"); exit(1); } } foreach (["imagewebp", "imageavif"] as $function) { if (! function_exists($function)) { fwrite(STDERR, "Missing required GD function: {$function}()\n"); exit(1); } } if (version_compare((string) phpversion("redis"), "6.3.0", "<")) { fwrite(STDERR, "Redis extension 6.3.0 or newer is required for full integration coverage.\n"); exit(1); } if ((bool) ini_get("swoole.use_shortname")) { fwrite(STDERR, "Swoole short names must be disabled.\n"); exit(1); }'; \
php -r "if (version_compare((string) phpversion('protobuf'), '${PROTOBUF_VERSION}', '<')) { fwrite(STDERR, 'protobuf extension ${PROTOBUF_VERSION} or newer is required for native OTLP coverage.' . PHP_EOL); exit(1); }"; \
php -r 'foreach (["avif", "heic"] as $format) { $image = new Imagick; try { $image->newImage(1, 1, "white"); $image->setImageFormat($format); if ($image->getImageBlob() === "") { fwrite(STDERR, "Imagick produced an empty {$format} image.\n"); exit(1); } } finally { $image->clear(); $image->destroy(); } }'; \
composer --version --no-ansi; \
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
"psr/log": "^3.0",
"psr/simple-cache": "^3.0",
"psy/psysh": "dev-main",
"sentry/sentry": "^4.34",
"sentry/sentry": "^4.38.0",
"spomky-labs/otphp": "^11.0",
"symfony/console": "^8.1.10",
"symfony/dom-crawler": "^8.1",
Expand Down
56 changes: 56 additions & 0 deletions docs/plans/2026-11-24-sentry-profiling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Sentry profiling in Hypervel workers

## Outcome

Applications can enable transaction profiling to see where a particular request or job ran, or continuous profiling to inspect a worker over time. Preserve Sentry's configuration, sampling, payload format, and application-supplied collectors. Profiling stays opt-in. The Hypervel Hub owns coroutine-local scopes and sampling decisions. The PHP SDK owns continuous recording, transactions, serialization, transport and client reports.

## Transaction profiles

Require sentry/sentry ^4.38.0 in both Composer manifests, matching the current Laravel integration and including SDK reporting for rejected transaction profiles and continuous chunks. Version 4.35 added the per-transaction factory in [SDK PR 2253](https://github.com/getsentry/sentry-php/pull/2253). Version 4.36 handles coalesced event counts and empty-stack idle markers. Set a default factory on the builder only when Excimer is loaded and the user has supplied none. Create a fresh collector when the SDK selects a transaction. Let the stock SDK handle a missing extension.

Capture the runtime context from CoroutineRuntimeContextStorage when recording starts. Match it by object identity so attached child coroutines count as request work while detached work runs independently. Without an active context, match the exact starting coroutine ID, including the main execution outside Swoole. No worker-wide table or per-request registration is needed. Direct SDK clients can supply their own factory.

Use released Excimer's real-time clock, a 0.0101-second period and a stack depth of 128, matching the SDK. Record the wall-clock start time when creating the native profiler, whose timestamps are offsets from construction. Excimer synchronously invokes its flush callback after capturing a sample. Flushing one sample at a time lets the callback decide ownership before extracting the trace. Excimer preserves the original epoch across rotations.

```php
$belongsToTransaction = $context === null
? Coroutine::id() === $coroutineId
: $storage->get() === $context;
```

Keep native timestamp, event count and trace fields on owned samples. After an owned sample, remember the timestamp of the first foreign sample. Emit one empty stack at that timestamp only when another owned sample arrives. Sentry's renderer weights a sample up to its successor and recognizes empty stacks as idle. This preserves gaps and the minimum of two real samples. Keep frame arrays once per profile, keyed by their serialized fields. Release the frame dictionary on stop.

Bound storage for long jobs. The SDK discards profiles when their last formatted sample is over 30 seconds. Its converter may backdate a coalesced sample, but never earlier than its predecessor's raw timestamp. Once the preceding raw entry is itself over 30 seconds, preserve only the two adjacent entries and discard subsequent samples. Either predecessor, including an idle marker, preserves the SDK's own rejection and client report. Free the frame dictionary at that point.

The callback must have no reference back to its native profiler. Excimer 1.2.7 retains callbacks outside PHP's cycle traversal. A bound callback referencing the collector can keep an abandoned timer alive even after cycle collection. Release the timer on stop, pass the samples to the SDK Profile and leave formatting to Sentry. Stop and detach discarded HTTP profilers for both normal termination and cancellation. Clear request state before invoking application code. Follow SDK logging for ordinary failures and propagate coroutine cancellation.

### Measured cost

On PHP 8.4.27, Swoole 6.3.0 RC2, Excimer 1.2.7 and SDK 4.37.1, paired synthetic runs used one pinned CPU, identical work and real SDK payload conversion. With eight overlapping CPU/I/O requests all profiled, the median was 0.834 CPU seconds and 23.70 requests/second for stock Sentry, and 0.833 seconds and 23.59 requests/second for the collector sharing repeated frames. A recognizable foreign stack occurred in 96 of 144 stock profiles and zero of 144 filtered profiles. In a 72-frame CPU workload with two alternating call paths lasting about 3.8 seconds, incremental peak PHP memory was 0.42 MiB for stock Sentry, 11.25 MiB with raw traces, 6.01 MiB reusing the immediately previous trace, and 1.36 MiB sharing frames. These are local transaction-profiler measurements. Production overhead depends on concurrency, depth and sampling settings.

## Continuous profiling

The [Laravel 4.31.0 integration](https://github.com/getsentry/sentry-laravel/blob/4.31.0/src/Sentry/Laravel/ServiceProvider.php#L439) forwards user options and uses the SDK Hub directly. Hypervel's coroutine-aware Hub must perform the corresponding SDK calls. Notify the process profiler when a client is first bound and when rebound. For a sampled root with trace lifecycle, register its span ID, then put the active profiler ID and SDK thread metadata on the transaction. Preserve the upstream warning for trace lifecycle with tracing disabled. The SDK owns stop-on-finish, final runtime-context cleanup, overlapping-root tracking and fork detection. Explicit middleware discard must release the root as well. Expose the SDK lifecycle and session rate in package configuration and explain manual worker profiling, automatic trace lifecycle and the precedence of transaction profiling. The continuous recording contains all work in the worker, including overlapping requests.

```php
$continuousProfiler->startForRootSpan((string) $transaction->getSpanId());
$profilerId = $continuousProfiler->getProfilerId();
```

### SDK delivery ordering

A separate upstream change owns a verified SDK defect. When a stop yields during delivery, a concurrent root can be attached to the stopping session and then cleared. With stock SDK 4.37.1 and 4.38.0, two roots produced one chunk during this interleaving and two chunks with sequential delivery. Complete the outgoing batch and retire its recording state before calling transport code and preserve a newly started session and queued chunks. Keep the usual no-client, manual, fork and failure behavior. Cover stop during a yielding or reentrant transport with an upstream regression. Hypervel uses released APIs throughout. Track the first fixed SDK release for the dependency minimum.

## Transport admission

The SDK catches transport exceptions inside `Client::captureEvent()`. If a request waits for a pooled HTTP transport and is canceled there, the SDK drops the event and the request can continue. In `HttpPoolTransport::send()`, use `tryBorrow()` to take an idle transport or create one within the configured limit. Skip the event immediately when every transport is busy or the pool is closed. Start a delivery coroutine only after checkout succeeds. Remove the Sentry-specific `wait_timeout` option and document the effect of `max_objects` on bursts.

Expose `tryBorrow(): ?object` on the Hypervel object pool contract. Share the ordinary checkout path for ownership, expiration, factories and concurrent closure. Return null only when capacity is unavailable. The regular `borrow()` retains its deadline and timeout exception.

## Verification and delivery

- Reproduce request contamination using the existing native Excimer test with its skip removed. Assert the owning request's stacks and an idle gap across unrelated work. Exercise attached and detached children, missing runtime context, collector cleanup and the duration boundary. Feed retained samples with both real and idle predecessors to the SDK formatter and verify that it drops each for excess duration.
- Exercise the generic pool at capacity, after release and after close. Exercise a real SDK capture with the only transport already checked out and verify that the caller completes before yielding.
- Verify application factory precedence, failed start and factory cancellation through the Hub, ignored-route cleanup, continuous profile IDs on overlapping roots, final-owner cleanup, and client binding before or after manual profiling starts. Isolate process-wide SDK session sampling between test cases.
- Install Excimer in the existing CI image using its PIE package. Exercise the relevant package with the extension both enabled and absent. Keep any remaining native pre-collection optimization in the todo entry, alongside the upstream release follow-up.
- Run each edited test file immediately. At the review boundary run formatting, full static analysis and targeted suites sequentially. Trace the final diff through provider registration, scope inheritance, middleware, queue and scheduler call sites, cancellation, SDK lifecycle and package installation. Obtain independent code review and commit whole files by concern. Keep both branches local until the owner authorizes publication.
7 changes: 2 additions & 5 deletions docs/todo.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,11 +158,8 @@ Remove older ways of doing things once a modern equivalent fully replaces them,

## Sentry

- Make Sentry profiles record only the profiled transaction's work. Excimer samples whichever coroutine's PHP stack is running when it takes a sample, so a transaction profile currently includes work from other coroutines in the same worker, such as concurrent requests. Profiling stays disabled by default, with a config comment and documentation warning, until this is fixed. Use released dependencies only.
- Once a `sentry/sentry` release includes the per-transaction profiler factory ([sentry-php#2253](https://github.com/getsentry/sentry-php/pull/2253)), raise the package's SDK minimum and supply a Hypervel profiler through it. The integration requires this hook.
- Once a released Excimer includes `ExcimerProfiler::setSampleFilter()` ([Excimer change 1354126](https://gerrit.wikimedia.org/r/c/mediawiki/php/excimer/+/1354126)), have that profiler accept only samples taken in its own coroutine, through a static closure that captures the coroutine ID rather than the profiler, and flush the log normally when it stops. Without the filter, the profiler must flush after every sample and discard samples from other coroutines after their stacks have been collected.
- Child coroutines started during the transaction, such as `parallel()` calls, run under other coroutine IDs. Decide whether their samples belong in the profile and test the chosen behavior.
- Add tests for attribution under concurrent coroutines, starting and stopping with the transaction, and cleanup when a transaction never finishes, then measure sampling overhead under concurrent load. Remove the comment and warning only after these pass.
- Once a released Excimer includes `ExcimerProfiler::setSampleFilter()` ([Excimer change 1354126](https://gerrit.wikimedia.org/r/c/mediawiki/php/excimer/+/1354126)), compare native filtering with the transaction collector under concurrent load. Preserve request context ownership, idle intervals and SDK drop reporting.
- Raise the Sentry SDK minimum once a release fixes continuous profiling shutdown when a new recording starts during profile-chunk delivery. The SDK owns this fix.

## Notifications

Expand Down
5 changes: 5 additions & 0 deletions src/contracts/src/ObjectPool/ObjectPool.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ interface ObjectPool
*/
public function borrow(): object;

/**
* Borrow an object without waiting for capacity, or return null if the pool is full.
*/
public function tryBorrow(): ?object;

/**
* Release an object back to the object pool.
*/
Expand Down
2 changes: 2 additions & 0 deletions src/docs/pools.md
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ try {
$pool->release($client);
```

Call `tryBorrow()` to take an idle object or create one without waiting for pool capacity. It returns `null` when the pool is full. A closed pool or a failing factory still throws. Release or discard a successfully borrowed object as usual.

Use `release()` only when the object remains healthy. Use `discard()` after a protocol or network failure, or when a failed reset may have left it in an unknown state. The pool rejects foreign objects, repeated releases or discards, and factories that return an object the pool already manages.

<a name="leases"></a>
Expand Down
21 changes: 17 additions & 4 deletions src/docs/sentry.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [Sentry Logs](#sentry-logs)
- [Performance Monitoring](#performance-monitoring)
- [Sampling](#sampling)
- [Profiling](#profiling)
- [Distributed Tracing](#distributed-tracing)
- [Queued Jobs](#queued-jobs)
- [AI Monitoring](#ai-monitoring)
Expand Down Expand Up @@ -257,10 +258,22 @@ class SentrySampler

Returning `1.0` when the parent transaction was sampled keeps distributed traces complete. HTTP transactions are sampled before routing, so their name is still the request path.

Profiling may be configured with `SENTRY_PROFILES_SAMPLE_RATE` or a `profiles_sampler` callback. Profiles are only collected for sampled transactions.
<a name="profiling"></a>
### Profiling

> [!WARNING]
> Profiling is disabled by default. A profile can include work from other requests running at the same time in the same worker, whether profiling is enabled with `SENTRY_PROFILES_SAMPLE_RATE` or a `profiles_sampler` callback. Error reporting and tracing are not affected.
Install the Excimer PHP extension to collect profiles. Profiling is disabled by default.

To see where an individual request or job spends its execution time, set `SENTRY_PROFILES_SAMPLE_RATE` to a value between `0` and `1`, or supply a `profiles_sampler` callback. Sentry selects profiles from transactions already sampled for tracing. Hypervel includes work performed in child coroutines that share the request's Sentry context, such as children started with `parallel()`. Detached work and concurrent requests are excluded. A transaction started outside a Sentry context records only its own coroutine. Applications that supply their own `profiler_factory` control which samples they collect.

To see what an entire worker is executing, use continuous profiling. Leave `profiles_sample_rate` and `profiles_sampler` unset, then set the session sample rate. These settings record the worker while at least one sampled transaction is active.

```ini
SENTRY_TRACES_SAMPLE_RATE=0.1
SENTRY_PROFILE_SESSION_SAMPLE_RATE=1.0
SENTRY_PROFILE_LIFECYCLE=trace
```

Overlapping transactions share a recording, so a continuous profile linked from a trace can show other requests running in the same worker. To control the recording yourself, use the default `manual` lifecycle and call `\Sentry\profiler()->start()` and `\Sentry\profiler()->stop()` at the worker boundaries you want to measure. Transaction profiling takes precedence whenever a transaction profile sample rate or sampler is configured.

<a name="distributed-tracing"></a>
### Distributed Tracing
Expand Down Expand Up @@ -572,7 +585,7 @@ The builder uses Hypervel's pooled transport by default. Setting your own transp

Buffered logs and metrics are flushed when their execution finishes. Sentry envelopes are then sent from detached coroutines using a bounded pool of reusable HTTP transports. Requests, queued jobs, scheduled tasks, and WebSocket callbacks do not wait for event delivery, and commands use the same non-blocking delivery by default. Sends started outside a coroutine complete before returning so short-lived CLI processes cannot exit while an accepted send is still running.

If no transport becomes available within `sentry.pool.wait_timeout`, or the pool has closed, the event is skipped. Unexpected transport creation errors reach the Sentry SDK's error handling instead of being treated as pool exhaustion.
If every transport is busy or the pool has closed, the event is skipped immediately. Increase `sentry.pool.max_objects` to allow more concurrent sends during bursts. Unexpected transport creation errors reach the Sentry SDK's error handling instead of being treated as pool exhaustion.

Graceful worker shutdown performs a bounded drain after the worker-exit coordinator is released, then closes the transport pool. Delivery during a worker exit is best effort because Swoole may terminate outstanding reactor work after its shutdown deadline.

Expand Down
Loading