Repository navigation
Observability: telemetry stats API + structured logging redesign (#5) - #115
Merged
EdmondDantes merged 45 commits intoJul 13, 2026
Merged
Conversation
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.
…cs-tracing-structured-logs
Contributor
CoverageTotal lines: 81.70% → 81.94% (+0.25 pp)
❌ Regression in touched files (> 1.0 pp drop)
Add |
…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.
This was referenced Jul 13, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #5.
Part A — cross-worker stats
HttpServer::getStats()(opt-in viasetStatsEnabled(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}.total_requests, per-status-classresponses_2xx/3xx/4xx/5xx_total(classified exactly once, the four sum to the total), per-protocol gaugesconns_active_h1/h2/h3.Part B — logging redesign
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.plain,logfmt,json(OTel Logs field names),pretty(coloured console,NO_COLOR/CLICOLOR_FORCE/isatty),syslog(bare RFC 5424), andtemplate— user-controlled line layout ('{ts:Y-m-d H:i:s.v} [{level}] {msg}{attrs}', compiled once at sink build).stream,file(path reopened per pool worker),stdout/stderr,syslogover 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.'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 isapp, 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/phpsink: records delivered to a PHP callback as structured arrays (the userland-OTLP seam); callback exceptions absorbed, re-entrancy guarded.Verification
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
sendmmsgbatching.