Skip to content

feat(realtime): telemetry for the pub/sub event handler - #15113

Merged
ArnabChatterjee20k merged 2 commits into
fix/realtime-permission-ingest-fail-closedfrom
feat/realtime-pubsub-telemetry-on-ingest
Oct 30, 2026
Merged

ArnabChatterjee20k merged 2 commits into
fix/realtime-permission-ingest-fail-closedfrom
feat/realtime-pubsub-telemetry-on-ingest

Conversation

@ArnabChatterjee20k

Copy link
Copy Markdown
Member

Issue / Description

Closes #15107. Stacked on #15086.

The realtime pub/sub handler has almost no telemetry of its own. If it keeps reading events from Redis but stops delivering them, the only sign is that realtime.server.arrival_delay and realtime.server.message.sent go flat, and nothing says why. Two places also throw failures away silently: the arrival-delay and delivery-delay catch (\Throwable) {} blocks.

Solution

New instruments, created through the telemetry adapter the same way the MQTT broker's are (mqtt.messages.dropped with a reason, mqtt.messages.failed, …):

Instrument Type Meaning
realtime.server.events.received counter every event the handler is called with
realtime.server.events.dropped counter, reason no_subscriber: nobody on this worker matched; invalid_payload: not a JSON event
realtime.server.events.failed counter, stage an error in that step: arrival, delivery_delay, or whatever step handle() was in when it threw
realtime.server.event.stage observable gauge, stage + workerId seconds the event being handled has spent in its current step (decode, arrival, permissions, deliver, close, tail), 0 when idle

How to read them when delivery stops:

  • events.received flat: nothing is reaching the handler.
  • event.stage climbing: the handler is blocked, and the stage label names the step.
  • events.failed rising: events throw. The stage label shows where; this used to be silent for arrival and delivery delay.
  • events.received rising, events.dropped{reason=no_subscriber} equal to it: events are handled but match nobody on the worker.

The two silent catch blocks still don't stop delivery. They now count the failure.

A payload that isn't a JSON object is now counted and dropped up front, instead of failing further down with a TypeError.

Tests

  • New tests/unit/Realtime/Event/HandlerTest.php, with a named RecordingAdapter and the telemetry Test adapter:
    • an event with no subscribers is counted as received and dropped, and records its arrival;
    • an event with a bad timestamp is counted as failed instead of silently swallowed (this fails on the base branch, which has no such counter);
    • a payload that isn't JSON is counted as dropped;
    • the stage gauge reads 0 with stage=idle after an event.
  • One realtime.event span per event, with project id, event name, result no_subscriber, 0 receivers and resolved_at ≥ arrived_at; no span for a payload that isn't an event.
  • php -l, Pint and Rector on all changed files. I couldn't run PHPUnit locally (no Swoole), so CI's unit job is the first run.

🤖 Generated with Claude Code

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Span every realtime event, reversing prior firehose exclusion — Handler.php:74
🧹 Nitpicks (2) — 🟢 2 low
  • 🟢 Events with only expired receivers are neither dropped nor delivered (Handler.php:582) — The eventsDropped counter records no_subscriber only when $receivers === [] (src/Appwrite/Realtime/Event/Handler.php:582), while the span's realtime.result reports no_subscriber whenever $total === 0 (src/Appwrite/Realtime/Event/Handler.php:623).
  • 🟢 eventsFailed counts benign timestamp errors as failures (Handler.php:134) — eventsFailed is incremented in the recordArrival and delivery-delay catch blocks for invalid-timestamp payloads (src/Appwrite/Realtime/Event/Handler.php:134), after which the event continues processing and can still complete as delivered — the span is not marked failed and the replaced code explicitly ignored these errors.

This PR instruments the realtime event handler with observability: a stage-duration observable gauge, three counters (received, dropped, failed), and per-event spans in Handler, wired up from app/realtime.php.

Files Change
app/realtime.php Registers the four telemetry instruments in the worker's register and passes them into the event Handler.
src/Appwrite/Realtime/Event/Handler.php Tracks the event-processing stage, counts received/dropped/failed events, emits per-event spans, and converts previously swallowed timestamp errors into failure metrics.
tests/unit/Realtime/Event/HandlerTest.php New unit tests covering span emission, counter semantics, and the idle gauge.
tests/unit/Realtime/Event/RecordingAdapter.php New recording test double implementing the websocket adapter contract.
tests/unit/Realtime/Event/RecordingExporter.php New recording test double implementing the span exporter contract.

Reviewed commit: a054079

@ghost

ghost commented Oct 30, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This change adds per-worker realtime event counters and a stage-duration gauge, records failures from the arrival and delivery-delay paths, and adds event spans. It also adds unit coverage for event counts, dropped payloads, span attributes, and the idle gauge state.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 5
File Change
app/realtime.php Registers the new realtime telemetry instruments and passes them to the event handler.
src/Appwrite/Realtime/Event/Handler.php Tracks event stages, records received/dropped/failed events, and adds per-event spans.
tests/unit/Realtime/Event/HandlerTest.php Covers event telemetry, invalid payloads, spans, and the idle gauge.
tests/unit/Realtime/Event/RecordingAdapter.php Adds a named WebSocket adapter fake for the handler tests.
tests/unit/Realtime/Event/RecordingExporter.php Adds a span exporter that retains finished spans for assertions.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Reject JSON arrays as invalid event payloads Verifier: The decoding observation is correct, but no reachable source of a JSON-array event was found. The sole publisher to the realtime channel, Realtime::send() at src/Appwrite/Messaging/Adapter/Realtime.php:625–636, always encodes a fixed associative envelope with project, permissionsChanged and data fields. The new guard handles decoding failures and non-array results; it does not establish full event-schema validation. Array-root payloads already reached the event path before this change, so this asks for additional defensive validation against an input not produced by the code.

Reviewed a054079 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ArnabChatterjee20k
ArnabChatterjee20k merged commit bdcbb44 into fix/realtime-permission-ingest-fail-closed Oct 30, 2026
16 of 17 checks passed
@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

@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

Comment thread src/Appwrite/Realtime/Event/Handler.php Resolved

@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 per-event telemetry to the realtime firehose worker: stage gauge, received/dropped/failed counters, and per-event spans, plus unit-test fakes.

Key findings

  • 🟡 Span every realtime event, reversing prior firehose exclusion — Handler.php:74

Comment on lines +74 to +78
$span = Span::init('realtime.event');
$span
->set('project.id', $event['project'] ?? '')
->set('realtime.event.name', $event['data']['events'][0] ?? '')
->set('realtime.arrived_at', $arrivedAt);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 performance · medium

Span every realtime event, reversing prior firehose exclusion

handle() now creates and finishes a realtime.event span for every decoded event (src/Appwrite/Realtime/Event/Handler.php:74), while the code it replaces stated spans were kept to failed events only so the firehose stayed out of logs and telemetry. At realtime throughput this exports one span per event, multiplying collector load, and the coverage is inconsistent: the invalid_payload early return drops the event with only a counter and no span. Confirm the always-on policy explicitly, or restore failure-only span emission.

📋 Prompt for AI Agents

In src/Appwrite/Realtime/Event/Handler.php around lines 68-115, the realtime.event span is now initialised for every event and finished with realtime.result/resolved_at attributes, but the replaced code commented that only failed events got a span to keep the firehose out of logs. Either restructure so the span is created and finished only when the catch block runs, preserving the counters (eventsReceived, eventsDropped, eventsFailed) unchanged, or — if per-event spans are intended — also create and finish a span on the invalid_payload early-return path (lines 68-72) so every terminal outcome is observable in traces.

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.

Valid, fixed in 2c82ac1 on #15086's branch.

The span is no longer exported for every event. app/realtime.php now finishes realtime.event only when:

  • the event failed (the error is attached),
  • it took 1s or longer, or
  • its project matches _APP_TRACE_PROJECT_ID, so one project can be traced on demand.

Every other event's span is dropped without being exported. The counters (realtime.server.events.received, events.dropped{reason}, events.failed{stage}) still cover the whole firehose, so nothing is lost for alerting.

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 current diff (Handler.php) still shows the span created and finished for every valid decoded event — the selective export logic described (1s threshold, project-ID filter, failure-only) is not visible in any of the diffs provided. The fix may have landed in commit 2c82ac1 on a separate branch, but that code is not in the evidence available here. Based solely on what is shown, the original issue — a span emitted for every event — remains present in this diff.

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.

This PR was merged at a054079665, before the fix, so its diff will always show the old code. The fix is 2c82ac1816, pushed afterwards to the branch this PR merged into (#15086):

Hansi already confirmed the same fix on #15086: #15086 (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.

The diffs provided in this review thread — both Handler.php and app/realtime.php — still show the span created and finished for every valid decoded event, with no selective export logic (failure-only, 1s threshold, or project-ID filter) visible. The fix described (commit 2c82ac1, where Handler::handle() no longer owns the span and the subscribe closure in app/realtime.php applies conditional export) is not present in any of the evidence shown here. Since this is the final verification tier and the fix is not visible in the supplied diffs, I cannot resolve the finding based on the available evidence alone.

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing fix/realtime-permission-ingest-fail-closed (before) → feat/realtime-pubsub-telemetry-on-ingest (after).

Metric Before After Change
🚀 Requests/sec 204.51 206.9 ⚪ +1.2%
⏱️ Latency P50 82.96 ms 83.75 ms ⚪ +1%
⏱️ Latency P95 203.09 ms 193.73 ms ⚪ -4.6%
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 83.75 193.73 12,768 206.9 -9.36
Account 154.14 285.22 672 11.14 +3.56
TablesDB 79.44 144.3 6,944 114.42 -21.55
Storage 81.47 186.53 3,360 57.36 +6.18
Functions 118.58 236.27 1,792 31.36 +7.22

Top API waits (after)

API request Max wait (ms)
functions.variables.create 440.15
functions.create 417.38
account.name.update 408.37
storage.buckets.create 380.91
storage.files.view 369.98

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