Skip to content

Observability: telemetry stats API + structured logging redesign (#5) - #115

Merged
EdmondDantes merged 45 commits into
mainfrom
5-telemetry-api-metrics-tracing-structured-logs
Jul 13, 2026
Merged

EdmondDantes merged 45 commits into
mainfrom
5-telemetry-api-metrics-tracing-structured-logs

Conversation

@EdmondDantes

Copy link
Copy Markdown
Contributor

Closes #5.

Part A — cross-worker stats

  • HttpServer::getStats() (opt-in via setStatsEnabled(true)): each pool worker owns one slot in a process-wide, cache-line-aligned counter slab and bumps it lock-free; getStats() walks the slab from any thread → {enabled, workers, totals}.
  • Totals include total_requests, per-status-class responses_2xx/3xx/4xx/5xx_total (classified exactly once, the four sum to the total), per-protocol gauges conns_active_h1/h2/h3.
  • No embedded exporters — metrics are a plain PHP array, export is userland (scope locked in the issue discussion).

Part B — logging redesign

  • Multi-sink fan-out (setLogSinks, up to 8): per-sink severity floor + formatter + async transport; fast gate is the min floor (one branch when off); one failing sink never blocks the others. Emit formats once per distinct formatter.
  • Formatters: plain, logfmt, json (OTel Logs field names), pretty (coloured console, NO_COLOR/CLICOLOR_FORCE/isatty), syslog (bare RFC 5424), and template — user-controlled line layout ('{ts:Y-m-d H:i:s.v} [{level}] {msg}{attrs}', compiled once at sink build).
  • Transports: stream, file (path reopened per pool worker), stdout/stderr, syslog over tcp (RFC 6587 octet framing), udp/udg (one record per datagram — framing is a transport property, moved out of the formatter). Batched writer: 64 KiB ring per sink, flush at 32 KiB high-water or a 200 ms timer; emit never suspends.
  • Sink-type / formatter registry (plugin seam): built-ins register at MINIT through the same API a plugin extension would use; config validation and translation consult the registry; error messages list what's actually registered.
  • Structured access log ('category' => 'access'): one record per completed request (method, path, status, proto, bytes, duration_ms, remote, W3C trace context) across H1/H2/H3, sendFile and reactor-pool paths. Default category is app, so per-request logging is strictly opt-in. Profiler-gated: off = one predicted branch; on ≈ 5–6 µs/record worst-case (remote cached per connection, ISO-8601 second-cache).
  • onLog / php sink: records delivered to a PHP callback as structured arrays (the userland-OTLP seam); callback exceptions absorbed, re-entrancy guarded.
  • Pool-mode fix: the frozen config snapshot previously dropped all logging config — sink specs are now flattened into the snapshot and rebuilt per worker.

Verification

  • 134 phpt green (core + telemetry + h1 + h2 + h3 access), incl. new tests 019–029, h2/051, h3/051 (real curl-h2c / h3client round-trips).
  • ASAN/UBSAN batched run over core+telemetry: 0 sanitizer-reported errors (remaining failures are the documented vfork-interceptor × uv_spawn false-SEGV class).
  • wrk profiler runs at each ⚠ stage: no regression with logging off; access-log cost measured and documented in docs/OBSERVABILITY_PLAN.md.

Deferred by design (tracked in the plan doc): A6 histograms, file rotation (external logrotate), GELF/Fluent/OTLP sinks (plugins on the registry), datagram sendmmsg batching.

Contiguous cache-line-aligned slab, one slot per worker, sized to the pool
at start(). Lock-free reads (no CAS), admin mutex only on claim/retire —
mirrors g_worker_registry. Created/freed in start_pool (not gated behind the
reactor pool). Selftest + phpt; valgrind-clean.
Add server->counters_live (embedded slice for a standalone/parent server, the
shared slab slot for a pool worker). Worker claims its slot at start() before
any conn caches the pointer; retires on teardown. Hot-path bumps are unchanged
(still via the cached conn->counters pointer) — wrk 4-worker H1 median 181.8k
vs 182.6k baseline, no regression. Integration phpt proves per-slot totals sum
to requests served.
New HttpServerConfig::setStatsEnabled/getStatsEnabled (default off, distinct
from telemetry_enabled). start_pool allocates the slab only when enabled;
propagated through the shared config freeze. phpt 003 + 002 updated.
New HttpServer::getStats() — throws when stats disabled, else returns
{enabled, workers, totals}. Pool mode walks the slab lock-free and sums each
worker slot; single-worker reports its own counters. Shared counters->zval
helper for worker entries + totals. getTelemetry() left as-is. phpt 004.
responses_{2xx,3xx,4xx,5xx}_total folded into http_server_count_request(c,
status) so every counted request classifies exactly once -> the four buckets
sum to total_requests. conns_active_h1/h2/h3 gauge via conn_active_inc/dec:
++ at ALPN detection / H3 conn establish, -- at close (WebSocket maps back to
h1). phpt 005 reconciles the mix; 4-worker H1 wrk 178.0k vs 177.7k baseline.
@EdmondDantes EdmondDantes linked an issue Jul 11, 2026 that may be closed by this pull request
@github-actions

github-actions Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Total lines: 81.70% → 81.94% (+0.25 pp)

File Baseline Current Δ Touched
src/core/http_connection.c 75.02% 75.26% +0.24 pp ●
src/core/http_connection.h 81.82% 81.82% +0.00 pp ●
src/core/http_connection_tls.c 73.39% 73.46% +0.07 pp ●
src/core/http_protocol_strategy.c 78.87% 79.17% +0.29 pp ●
src/core/reactor_pool_test_hooks.c 100.00% 100.00% +0.00 pp ●
src/core/response_wire.c 92.81% 93.33% +0.52 pp ●
src/core/stats_registry.c 0.00% 89.22% +89.22 pp ●
src/core/worker_dispatch.c 75.93% 76.20% +0.28 pp ●
src/http1/http1_stream.c 69.49% 70.00% +0.51 pp ●
src/http1/http_parser.c 83.97% 84.06% +0.09 pp ●
src/http2/http2_session.c 88.63% 88.68% +0.04 pp ●
src/http2/http2_strategy.c 79.40% 84.18% +4.77 pp ●
src/http2/http2_stream.c 93.88% 94.00% +0.12 pp ●
src/http3/http3_callbacks.c 81.58% 82.43% +0.85 pp ●
src/http3/http3_connection.c 82.58% 82.88% +0.30 pp ●
src/http3/http3_dispatch.c 79.95% 82.09% +2.14 pp ●
src/http3/http3_listener.c 76.79% 76.28% -0.52 pp ●
src/http3/http3_packet.c 91.00% 90.43% -0.57 pp ●
src/http3/http3_static_response.c 10.74% 68.35% +57.62 pp ●
src/http3/http3_stream.c 91.95% 92.22% +0.27 pp ●
src/http_request.c 83.90% 83.77% -0.14 pp ●
src/http_server_class.c 70.87% 71.60% +0.73 pp ●
src/http_server_config.c 92.49% 90.99% -1.50 pp ●
src/log/http_log.c 68.29% 69.76% +1.46 pp ●
src/send_file.c 86.11% 85.88% -0.24 pp ●
src/static/http_static.c 88.75% 88.70% -0.05 pp ●
src/websocket/php_websocket.c 77.25% 77.36% +0.11 pp ●

❌ Regression in touched files (> 1.0 pp drop)

  • src/http_server_config.c dropped -1.50 pp

Add [coverage-drop-ok] to a commit message in this PR to override.

…emconv

Logging:
- fix UAF tearing down a sink with a write in flight (orphaned writer kept a
  back-pointer into the freed server object)
- fix corrupted records past 4 distinct formatters (scratch slot reused
  without re-stamping its length)
- remove onLog / the 'php' sink: emits fire from IO callbacks and from H3
  reactor threads, which have no TSRM context, so the log path must not
  re-enter the VM. Userland exporters drain a json file/socket sink instead.
- decouple src/log from the protocols: http_log_emit_access takes a POD, so
  the layer no longer includes http1/http_parser.h nor switches on http_major

Client address:
- snapshot the peer at accept instead of getpeername() at request completion,
  which silently returned nothing once the client had reset
- carry it on http_request_t so it reaches pool workers and the sendFile
  engine, which previously logged no IP at all
- add HttpRequest::getRemoteAddress()/getRemotePort() (bare IP + separate
  port, per REMOTE_ADDR / RFC 3875); align WebSocket::getRemoteAddress()

Access log now uses stable OTel HTTP semconv names (http.request.method,
url.path, http.response.status_code, network.protocol.version,
http.server.request.duration in seconds, client.address/client.port).

Stats: replace the word-wise aggregate (strict-aliasing UB; size_t
active_requests broke every field after it on 32-bit) with a counter field
table guarded by a static assert; relaxed-atomic cross-thread reads;
h2_ping_rtt_ns takes max, not sum.
Counters now carry an aggregation kind (SUM / GAUGE / MAX):
- retiring a worker folds its monotonic totals into the registry, so a
  reload() no longer resets getStats() and a scraper never sees a counter
  run backwards
- gauges are summed over live workers only — a dead worker holds no open
  connections, so its last value must not linger as a phantom
- h2_ping_rtt_ns takes the max; summing round-trip times is meaningless

Also fixes an uninitialised registry: pemalloc left the new retired-totals
block full of garbage, so total_requests reported a pointer-sized number.

HTTP/3: getHttp3Stats() copied the whole per-listener stats block while the
reactor thread was writing it, so a report could mix fields from either side
of an update. Reads are now per-field relaxed atomics, driven by a field
table with a static assert instead of ~60 hand-kept appends.
…nd to end

examples/observability-server.php renders getStats() as a Prometheus endpoint
and writes a JSON access log in OTel semantic conventions. No embedded exporter:
the array goes in, the text format comes out, swap it for anything else.

examples/docker/observability/ brings up Prometheus + Grafana with a dashboard
built to show why the counter kinds matter — totals keep climbing across a
reload(), gauges fall back to what is really open. smoke-test.sh asserts every
hop (server -> /metrics -> scrape -> Grafana datasource + dashboard); it passes.

The example is also written around two traps: a pool worker has its own function
table, so the handler reaches its renderer through use() rather than calling a
named function; and the 'file' log sink is the one that survives into a worker.
…ic format

- Text formatters (plain/pretty/template/syslog) escape control bytes as \xXX.
  Request-derived fields (method, path) reach them unfiltered; a raw control
  byte would forge a log line, or inject an ANSI sequence into a pretty console.
  Defense-in-depth: the H1/H2/H3 parsers reject control bytes in the target
  today, but a formatter must not trust its input. json/logfmt already quote.

- Drop 'syslog' from the public formatter registry. It emits no record framing
  (that is the syslog transport's job), so on a plain stream the records would
  run together. It stays pinned by the syslog sink type; 'format' => 'syslog'
  on any other sink is now rejected at config time.

- Surface a failed stats slab instead of silently reporting the parent as a
  lone worker; check tsrm_mutex_alloc in http_stats_registry_create.
…cs-tracing-structured-logs

# Conflicts:
#	CHANGELOG.md
Both remote-address tests validated the IP with filter_var(FILTER_VALIDATE_IP),
which needs ext/filter — absent from the CI PHP build, so they failed there while
passing locally. Replace with a bare-ipv4 regex; the exact-match against
127.0.0.1 already carries the real assertion.
http_parser.h now includes log/http_log.h (for http_access_rec_t), so the
weak stub's hand-rolled forward declaration conflicts with the real prototype.
Use the real signature.
- conns_active_h1/h2 underflowed on every HTTPS conn: the TLS/ALPN handshake
  path installed the strategy but skipped the active-gauge increment while
  close still decremented. Increment in tls_on_handshake_done.
- a long request target corrupted the access log: an over-length record was
  truncated including its trailing newline and merged with the next record on a
  stream sink. sb_end_line() forces the separator even on truncation.
- level=OFF sinks revived at INFO under the worker pool (freeze->load had no
  OFF case). OFF now round-trips.
- pool-mode access records lost http.server.request.duration: the worker
  stamped the ctx, not the request. Copy the window onto the request.
- static hard-zero serve path counted requests but never logged them: the
  send-file engine got a NULL server. Thread the server through
  try_serve_mounts (NULL only on the transport reactor thread).
- resetTelemetry() zeroed the live occupancy gauges, underflowing the next
  close. Preserve conns_active_*, active_requests, h2_streams_active.
- Windows build: the relaxed 64-bit counter reads used __atomic_load_n with no
  MSVC fallback. Route through a portable http_relaxed_load_u64 helper.

New tests: telemetry/007 (tls conn gauge), telemetry/008 (reset preserves
gauge), core/058 (log truncation newline), core/059 (OFF sink under pool),
core/060 (access-log duration under pool), static/019 (static access log).
Full phpt suite 344/0-FAIL.

Also: pre-push hook now reviews comment quality (non-obvious WHY only), not
line count.
- rename getStatsEnabled() -> isStatsEnabled() for parity with the is*Enabled
  bool getters (isTelemetryEnabled). Never shipped — feature-branch only.
- USAGE.md §7: getStats() returns a nested {enabled, workers, totals} array,
  not a flat one; document setStatsEnabled() (throws without it) and the
  setLogSinks() multi-sink API (types, formats, categories).
- braces on the conn_active_dec guards (CODING_STANDARDS §13a.2).

Full server+ws suite 314/0-FAIL.
Bug #4: a sendFile was counted and access-logged as 200 — the handler only
queues the send, and the engine stamps the real status (206/304/416/404/500)
later. Counting + the access record move to one seam, http_request_telemetry(),
called once per request at each protocol's teardown (H1 finalize; H2 dispose /
dispose_tail / static-done; H3 dispose_tail / reactor sendfile cleanup; pool
worker dispose, gated on the marshalled sendFile the reactor accounts). Replaces
5 *_log_access wrappers + the engine's 6 self-accounting tails (which also
resolved a worker's sink from the reactor thread). Bailouts stay uncounted via a
handler_bailout flag on the H2/H3 stream and the worker ctx.

getStats() now folds the reactor listeners' counter slices into totals and
reports them under a new `reactors` key: a request served end-to-end on a
transport thread (static hard-zero, the reactor half of a pooled sendFile) has
no worker slot and was counted where nothing read it.

Two pre-existing H3 bugs found by the new tests (both verified on a clean tree):

- Ranged responses sent the WRONG BYTES: 206 + correct Content-Range, body from
  offset 0. The pump stored body_offset and never seeked. H2 always did.
- Under the reactor pool, any file past the 64 KiB slurp threshold and EVERY
  ranged request hung forever: the pump ran as a PHP coroutine and needed a
  server object + async scope, which a transport reactor has neither of.

The H3 pump is now a callback FSM (like H2's) and runs on any thread: EOF only
marks the stream, and teardown fires from the stream close — retiring it inside
its own read callback frees the file io while nghttp3 still owns every queued
chunk. Re-entrancy (a drain delivering an ACK back into try_read) is fenced.
The reactor no longer touches the worker's request: the 4 conditional headers
the engine reads travel on the SEND_FILE wire and the reactor builds its own
persistent stand-in — those request fields belong to the worker's allocation
domain, and freeing them from the reactor corrupts its heap.

h3client: H3CLIENT_HEADER="name: value" to drive ranged/conditional requests.
Tests: sendfile/005 (h1), h2/052, h3/052 (range bytes), h3/053 (pool: range +
200 KB file + reactor counters). 348 green; ASAN clean.
The sink's descriptor, its in-flight write and its flush timer now live on ONE
consumer thread; every other thread (workers, transport reactors, the parent) is
a producer that formats a record on its own stack and copies the bytes into its
OWN ring for that sink. SPSC per ring: no lock, no CAS on the emit path — a
release store of the write index is the whole synchronisation. Flush policy
unchanged (32 KiB high-water / 200 ms timer); overflow still drops whole records.

Why: a transport reactor could count a request but never log it — it has no PHP
context and must not touch a worker's descriptor. It can fill a ring. So under
the reactor pool a marshalled sendFile (delivered by the reactor, which is the
only place the final status exists) now reaches the access log. `stream` sinks
also start working under a pool, and a file sink is one fd instead of one per
worker. The reactor gets the parent's log_state through http3_reactor_ctx_t.

Lifecycle: the io + writer + timer are created ON the log thread (they must be
born on the loop that drives them); the descriptor is resolved on the thread that
owns the PHP stream. Stop is a handshake — the stopping thread marks the sink
closing and waits on a trigger the log thread fires once the rings are drained
and the transport is down, capped by the existing 3 s budget.

Fixed while testing: HTTP/1 streaming never bumped streaming_responses_total
(H2/H3 count it on the first chunk; H1 counted only calls and bytes).

Tests: telemetry/009 asserts getStats reports exactly the counter table — the
drift guard that caught the H1 gap — plus streaming counters and gauge drain;
telemetry/010 asserts totals == sum(workers) + sum(reactors) key by key under a
3-worker pool; h3/053 now asserts the reactor's access record for a pooled
sendFile. 350 green; ASAN 0 errors.
… drop metric

Three fixes, each found by testing the log thread rather than by reading it.

1. A syslog sink over TCP wrote blockingly. Every log descriptor was wrapped as
   an async FILE, so its writes were handed to the blocking IO pool — the pool
   that also serves sendFile. A receiver that stopped reading parked a pool
   thread per write. The io type now comes from the descriptor (getsockopt
   SO_TYPE/SO_DOMAIN): inet stream -> TCP, AF_UNIX stream -> PIPE, else FILE.
   Datagram sinks stay FILE on purpose: a send() to a UDP/unix-dgram peer does
   not wait on a slow receiver, so there is nothing to unblock. Verified the TCP
   branch is really taken (core/023 reports type=TCP), not silently falling back.

2. A static mount under the reactor pool read files SYNCHRONOUSLY on the
   transport thread: http3_reactor_try_static never installed the streaming ops
   on the response it built, so send_file() found no protocol op and took its
   "sync fallback" — blocking the reactor loop and buffering the whole file in
   memory, whatever its size. Installing h3_stream_ops routes it through the
   callback pump instead. New test h3/054 (pool + StaticHandler, 1 KiB and
   200 KB, asserting bytes, reactor counters and static_zero_coroutine_total) —
   the static counters being zero is what exposed it.

3. Log records dropped by a full ring were invisible outside a rate-limited
   stderr line. New counter log_records_dropped_total, bumped per producer thread
   into its OWN counters slice (http_log_set_thread_drop_counter, wired for the
   parent/worker at start_logging and for a reactor at connection create), so the
   count is race-free and attributed. Test hook _http_log_flood added.

Comment review: trimmed two of my own comments down to what actually protects the
code (the peer field's placement rationale; the sf_request hazard).

351 green.
Sinks are still per server clone: a worker still opens its own, and still cannot
open a 'stream' sink (a PHP resource does not cross threads). What the log thread
actually changed is that the PARENT's sinks became reachable from the transport
reactors — which is what the access record for a pooled sendFile needed. Sharing
one sink set across the pool (one fd per sink instead of one per worker) is a
follow-up it makes possible but does not do.
… bad H3CLIENT_HEADER

The plan still described sinks as owned by the thread that started them (B1-B7).
Added stage B8: the log thread, the per-producer SPSC rings, the io type taken
from the descriptor, the drop metric — and, honestly, what it does NOT do (sinks
are still per server clone, so a worker still cannot open a 'stream' sink and a
file sink is still one fd per worker) plus the known shutdown bug (#121).

h3client silently dropped an H3CLIENT_HEADER whose name did not fit its buffer or
had no colon — the request then went out without the header the test asked for and
failed somewhere else entirely. It now says so on stderr (and takes 127 bytes).
…cess

If the file is truncated (or a read fails) after the headers are on the wire, the
body pump flagged a clean EOF. The peer then saw a 200 with a short body and no
error: a silently truncated file, reported as a complete one. Proven with a real
HTTP/3 client (aioquic), truncating a 3 MB file mid-transfer:

  before:  status=200 bytes=2572288/3145728 outcome=CLEAN_END
  after:   status=200 bytes=2804526/3145728 outcome=RESET(err=258)

258 = H3_INTERNAL_ERROR. Resetting the write side is the only way HTTP/3 can say
"this transfer failed" once a status and a Content-Length have gone out. The
teardown still waits for the stream close the reset triggers — releasing the file
io from inside its own read completion would free it while nghttp3 still owns the
queued chunks.

tests/h3client/h3probe.py: the aioquic probe used above. h3client cannot show this
(it stalls past ~1 MB and does not surface RESET_STREAM) — hence a real client.

160 green across h3/static/sendfile/core.
CI hung on h3/039 (reactor-pool static): the test client, not the server. The
count nghttp3_conn_read_stream reports back covers framing only — DATA is
deferred-consume, so the application must extend the QUIC windows for the payload
itself. h3client never did, so the stream window ran out, the server waited for a
MAX_STREAM_DATA that never came, and any response past the initial window stalled.

It went unnoticed while reactor static was read synchronously and answered from one
buffer; making it stream through the pump (479ebeb — the fix for blocking reads on
the transport thread) is what exposed the client's gap.

The server has this exact rule spelled out in http3_callbacks.c
(h3_extend_body_window: "nghttp3's consumed count excludes DATA payload").

h3client now serves a 3 MB body it used to stall on. 351 green.
The log sink picks its io type from the descriptor; the domain check used
SO_DOMAIN, which clang on macOS does not know (CI: MACOS_ARM64_*, "use of
undeclared identifier"). Read the address family with getsockname() instead —
same answer, portable.

Also brings back tests/h3client/h3probe.py, the independent aioquic client
(h3client shares ngtcp2+nghttp3 with the server, so a shared misreading of the
spec hides a bug from both); it reports status/bytes/outcome, where outcome tells
a RESET apart from a clean end. It is being wired into a test next.

syslog tcp/dgram + log-config tests green locally.
h3/053 and h3/054 hung in CI (129 s timeout) while passing locally — a timing
race the slower DEBUG build loses. The static/sendFile sender parks once the
stream's unsent bytes reach its ceiling, and its only wake-ups were the peer's
ACK and a window extension. But the data reader taking those bytes off the queue
is itself progress: the queue drops below the ceiling and nobody says so, and the
sender waits for an event that may be a whole ack-delay away — or, when the ACK
lands in the same batch it was already accounted for, never.

The reader now fires the stream's write event as it consumes, which is the exact
moment refilling becomes possible.

57 h3 tests green locally.
Two independent bugs, both surfacing as the h3/054 CI hang.

Listener: a peer that vanished mid-response drew an ICMP port-unreachable,
IP_RECVERR queued it and epoll reported POLLERR — which libuv answers by
removing the fd from the loop for good (uv__poll_io: uv__io_stop +
uv__handle_stop), leaving the listener deaf for the whole process. Re-arm the
poll (stop() first — libuv stopped the handle behind ext/async's back, so
start() alone is a no-op) and drain the error queue. New poll_rearms counter
in getHttp3Stats(); test h3/055 triggers a real ICMP via Version Negotiation.

Static/sendFile body: h3_stream_append_chunk took its coroutine backpressure
path when a chunk did not fit the cwnd. On a transport thread the current
coroutine is non-NULL and IS_SCHEDULER_CONTEXT is 0, so the guard passed and
ZEND_ASYNC_SUSPEND() ran inside a libuv callback and never returned — the
transfer froze at the read-ahead ceiling with the peer's ACKs arriving and
nothing left to wake the sender. The sender carries its own backpressure, so
append never suspends on its behalf. Renamed static_pump -> static_body_state.
@EdmondDantes
EdmondDantes merged commit 0b338c4 into main Jul 13, 2026
9 checks passed
@EdmondDantes
EdmondDantes deleted the 5-telemetry-api-metrics-tracing-structured-logs branch July 13, 2026 13:19
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.

Telemetry API (metrics, tracing, structured logs)

1 participant