Skip to content

fix(telemetry): serialize overlapping collects under Swoole - #14732

Merged
ChiragAgg5k merged 6 commits into
mainfrom
fix-telemetry-concurrent-collect
Oct 21, 2026
Merged

ChiragAgg5k merged 6 commits into
mainfrom
fix-telemetry-concurrent-collect

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

What

OpenTelemetry::collect() now runs one export at a time inside a Swoole coroutine, using a Utopia\Lock\Mutex. A second caller waits for the in-flight export instead of sharing the HTTP client with it. Outside coroutines nothing changes.

Why

fra1 prod, worker-migrations-xwr8x (cloud 1.51.21): the migration succeeded (Backup succeeded, span finished at 58s), then the pod died with exit 255 and the Job was marked Failed:

Fatal error: Uncaught Swoole\Error: This cURL handle is currently executing in coroutine#6, cannot be operated
  ... ExportingReader->collect()   app/worker.php (workerStop)
[Coroutine-6] ... ExportingReader->collect()   app/worker.php (Timer::tick 60s)
t coroutine action
60s #6 (timer) collect() → OTLP export in flight on the Symfony curl client
~62s lifecycle queue drained → workerStop → Timer::clearAll() (does not stop #6) → collect() on the same handle → Swoole\Error, exit 255

Any KEDA run-to-completion worker that lives past a collect tick can hit this. HTTP/realtime processes share the same adapter.

Tests

testOverlappingCollectsExportOneAtATime: two coroutines collect against a transport that yields mid-send. Without the fix it fails (2 is identical to 1 overlapping sends); with it, both export, one at a time. bin/monorepo check telemetry passes.

Related: appwrite-labs/cloud#6669

A worker's 60s collect tick can still be exporting when workerStop flushes
again. Both exports share the exporter's cURL handle, and Swoole aborts the
process ("This cURL handle is currently executing in coroutine#N"), so a
KEDA worker Job that already finished its message exits 255 and is marked
Failed.
@luxor-code-review

luxor-code-review Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Overlap test pins serialization, never covers the skip path (OpenTelemetryTest.php:129) — testOverlappingCollectsExportOneAtATime (packages/telemetry/tests/Adapter/OpenTelemetryTest.php:82-132) asserts both overlapping collects return true and both export — it proves the collects serialize but cannot distinguish blocking serialization from the non-blocking skip the return false branch in collect() is written for.

This PR makes packages/telemetry's OpenTelemetry adapter serialize metric collection under Swoole coroutines: a per-instance Channel mutex keyed on the current coroutine id lets a second concurrent collect() bail out early rather than running against the same reader concurrently. The test suite adds an overlap scenario driving two coroutines through the adapter and asserting the exporter still receives its sends.

Files Change
packages/telemetry/src/Adapter/OpenTelemetry.php Adds a Channel-based collect mutex with coroutine-id detection and non-reentrancy skip path in collect().
packages/telemetry/tests/Adapter/OpenTelemetryTest.php Adds an overlapping-coroutines test asserting sends still occur under contention.

Reviewed commit: 956b81f

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 21, 2026
@ghost

ghost commented Oct 21, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes only constrain properties and constants that are initialized once and do not alter runtime behavior.

The telemetry adapter now serializes overlapping Swoole collections, with a pooled coroutine-native OTLP transport and retry handling for dropped pooled connections. The package declares PHP 8.3 and the lock dependency, and updates metric export behavior and tests; the latest commits apply readonly declarations to immutable state and type the mock server constant.

Latest changes: The latest commits apply PHP 8.3 readonly declarations to immutable exporter, transport, adapter-test, and test-double state, and add a type to the mock server's HOST constant.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 9
File Change
packages/telemetry/README.md Documents the package's PHP 8.3 minimum and usage.
packages/telemetry/composer.json Declares PHP 8.3+ and adds Utopia Lock as a runtime dependency.
packages/telemetry/src/Adapter/OpenTelemetry.php Serializes Swoole metric collections with a mutex while retaining direct collection outside Swoole.
packages/telemetry/src/Adapter/OpenTelemetry/MetricExporter.php Filters empty metric collections and adjusts gauge timestamps; the exporter wrapper is now a readonly class.
packages/telemetry/src/Adapter/OpenTelemetry/Transport/Swoole.php Implements pooled coroutine-native OTLP HTTP transport with retry handling and readonly configuration/state.
packages/telemetry/src/Adapter/Test.php Makes registration closures readonly in test instruments.
packages/telemetry/tests/Adapter/OpenTelemetryExemplarTest.php Uses a readonly transport test double.
packages/telemetry/tests/Adapter/OpenTelemetryTest.php Covers metric export and overlapping collections using a readonly transport test double.
packages/telemetry/tests/E2E/Adapter/OpenTelemetry/Swoole/MockOtlpServer.php Types the host constant and makes the allocated port readonly in the Swoole integration-test server.

Merged main (e7dc668); no changes to this PR's code since 4ecf42b · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adds coroutine-aware collection locking to the OpenTelemetry telemetry adapter so overlapping collect() calls skip instead of interleaving, with tests.

Key findings

Comment on lines +322 to +324
if (!$this->collecting->push(true)) {
return false;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 bug · medium

Channel::push blocks instead of skipping on contention

The mutex at packages/telemetry/src/Adapter/OpenTelemetry.php:322 calls $this->collecting->push(true) with Swoole's default timeout of -1, which suspends the coroutine when the capacity-1 channel is already full rather than returning false. The return false skip branch is therefore unreachable under contention (only a closed channel yields it), and overlapping callers — the 60s Timer::tick export racing another tick or a shutdown flush — queue behind a hung export, one leaked coroutine per tick with no cap. Callers also never observe the documented skip outcome: false conflates skipped-in-flight with export failure.

📋 Prompt for AI Agents

In packages/telemetry/src/Adapter/OpenTelemetry.php lines 322-324, change $this->collecting->push(true) to $this->collecting->push(true, 0) so the capacity-1 channel fails fast when already held instead of suspending the calling coroutine indefinitely, making the return false skip branch reachable. Then in packages/telemetry/tests/Adapter/OpenTelemetryTest.php (testOverlappingCollectsExportOneAtATime), update the overlapping collect to assert it returns false with no additional send while the first collect is still in flight (use a transport whose send blocks until released), keeping the assertion that the first collect exports exactly once.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking is intended. The case this fixes is shutdown: workerStop must wait for the in-flight tick and then send its final flush; skipping would drop the last interval's metrics. Overlap can't build up either: a tick fires every 60s and an export times out well inside that, so at most one waiter exists. false comes back only when the waiting coroutine is cancelled (e.g. KubernetesJob cancelling stragglers on exit), and nothing was exported in that case.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The use-case argument is reasonable, but it doesn't fully resolve the original concern. If blocking is intentional for the shutdown path, the current code silently blocks all callers indefinitely — including the timer tick racing another tick — with no timeout and no cap on waiters. The return false branch is still unreachable under contention (it only fires on a closed channel), so the code's own documented skip behavior is never exercised in practice.

If the intent is 'shutdown waits, tick skips', those two callers need different treatment — e.g. pass a $wait flag or use push(true, 0) for ticks and push(true, -1) for shutdown. As written, both callers get the blocking path, meaning a hung export during a tick will queue the next tick behind it indefinitely.

The finding remains open until the diff shows either a non-zero timeout for the tick path or a test demonstrating the skip branch is reachable.

@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-telemetry-concurrent-collect (after).

Metric Before After Change
🚀 Requests/sec 189.56 210.61 🟢 +11.1%
⏱️ Latency P50 88.93 ms 81.84 ms 🟢 -8%
⏱️ Latency P95 216.03 ms 190.86 ms 🟢 -11.7%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 81.84 190.86 13,281 210.61 -25.18
Account 149.13 277.42 699 11.6 -40.17
TablesDB 78.19 142.11 7,223 117.4 -30
Storage 77.6 180.61 3,495 58.68 -11.43
Functions 117.13 221.11 1,864 31.97 -18.19

Top API waits (after)

API request Max wait (ms)
account.prefs.update 443.67
functions.variables.update 434.17
account.name.update 433.95
functions.delete 428.09
storage.buckets.create 362.55

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

ghost
ghost previously requested changes Oct 21, 2026

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Tier B · 1 blocking finding to address. Summary

Comment thread packages/telemetry/composer.json Resolved
…P 8.3

Mutex opens a Swoole Channel in its constructor, so building it eagerly
broke the adapter for consumers without ext-swoole. utopia-php/lock needs
PHP 8.3, so the package now declares that minimum.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@ghost
ghost dismissed their stale review October 21, 2026 15:08

The findings that requested changes are resolved. See the summary comment for what is still open.

@ChiragAgg5k
ChiragAgg5k merged commit 7e9ce20 into main Oct 21, 2026
163 of 166 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix-telemetry-concurrent-collect branch October 21, 2026 17:21
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
…ent-collect

fix(telemetry): serialize overlapping collects under Swoole

(cherry picked from commit 7e9ce20)
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