Repository navigation
Add diagnostics_channel TracingChannel support - #31
MiichelleZhou wants to merge 7 commits into
Conversation
Enables instrumentation libraries (OpenTelemetry, etc.) to subscribe to structured events without monkey-patching. Uses TracingChannel for async context propagation and plain channels for simple events. Channels: - pg:query (TracingChannel) — query lifecycle with result enrichment - pg:connection (TracingChannel) — client connect lifecycle - pg:pool:connect (TracingChannel) — pool checkout lifecycle - pg:pool:release (plain) — client released back to pool - pg:pool:remove (plain) — client removed from pool All instrumentation is guarded by hasSubscribers for zero overhead when unused. Gracefully degrades to no-ops on Node < 19.9 or non-Node environments. Closes #3619 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
TracingChannel is not available on Node 18 LTS. Skip the tracing-dependent tests gracefully instead of failing. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Node 18 backported TracingChannel but without the aggregated `hasSubscribers` getter (it returns `undefined` instead of a boolean). Raw truthiness checks treat `undefined` as "no subscribers" which silently disables tracing on Node 18. Replace all `channel.hasSubscribers` guards with `shouldTrace(channel)` which checks `hasSubscribers !== false` — treating `undefined` (Node 18) as "might have subscribers, trace unconditionally" and `false` (Node 20+) as "definitely no subscribers, skip". Also removes the now-unnecessary test skip logic since TracingChannel does exist on Node 18. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Node 18 backported TracingChannel but with a buggy implementation — unsubscribing and resubscribing to the same channel crashes internally (`_subscribers` becomes undefined). Node 16 has no TracingChannel at all. Gate tests on `hasStableTracingChannel` which checks both that `dc.tracingChannel` exists AND that the aggregated `hasSubscribers` getter returns a boolean (only true on Node 19.9+/20.5+). TracingChannel tests: skipped on Node 16/18, run on Node 20+ Plain channel tests (release/remove): run on all versions Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
…omise type tracePromise wraps the result in a native Promise, which breaks clients configured with a custom Promise implementation (e.g. bluebird). Switch to traceCallback inside the user's this._Promise constructor so the returned promise type is always correct. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
/devin review |
PR Summary by QodoAdd diagnostics channels for pg queries and pool lifecycles
AI Description
Diagram
High-Level Assessment
Files changed (6)
|
| @@ -1,5 +1,6 @@ | |||
| 'use strict' | |||
| const EventEmitter = require('events').EventEmitter | |||
| const { poolConnectChannel, poolReleaseChannel, poolRemoveChannel, shouldTrace } = require('./diagnostics') | |||
There was a problem hiding this comment.
🔴 Published pools fail to load
Installing the published pool leaves ./diagnostics out of the package, so require('./diagnostics') fails at startup. The published file list includes only index.js and esm.
Learn more
The package manager packs only files selected by the pool package's files field. That field lists index.js and esm but omits the new diagnostics module. A published install thus has the importing file but not its required module, and consumers cannot load the pool.
Example: After publishing the current pool package, an application importing pg reaches the pool import and gets Cannot find module './diagnostics' instead of a usable pool.
Recommended fix: Add diagnostics.js to the files array in packages/pg-pool/package.json, then verify the packed tarball contains it with a package dry run.
Was this helpful? React with 👍 or 👎 to provide feedback.
| const origCb = query.callback | ||
| const enrichedCb = (err, res) => { | ||
| if (res) context.result = { rowCount: res.rowCount, command: res.command } | ||
| return origCb(err, res) | ||
| } | ||
| queryChannel.traceCallback( | ||
| (tracedCb) => { | ||
| query.callback = tracedCb | ||
| enqueue() |
There was a problem hiding this comment.
🟡 Timed-out queries leave traces unfinished
When a query times out, queryCallback bypasses traceCallback and the timer replaces its wrapped callback with a no-op. Subscribers receive neither the timeout error nor completion, leaving the query trace open.
Learn more
The query timeout setup saves the original callback in queryCallback before this tracing wrapper replaces query.callback. On timeout, the timer calls the saved callback directly and then sets query.callback to a no-op. The wrapper installed here never runs, even if the backend later responds, so the tracing channel emits a start without an error or asyncEnd.
Example: A query_timeout of 10 milliseconds fires while SELECT pg_sleep(1) runs. The application receives Query read timeout, but a tracing subscriber still holds the query as active.
Recommended fix: Route timeout completion through the traced callback exactly once, while preserving timer cancellation and suppression of any later backend callback. Cover both queued and active query timeouts.
Was this helpful? React with 👍 or 👎 to provide feedback.
| this._pulseQueryQueue() | ||
| } | ||
|
|
||
| if (shouldTrace(queryChannel) && query.callback) { |
There was a problem hiding this comment.
🟡 Evented queries disappear from tracing
Calling client.query(new Query(...)) without a callback skips traceCallback. These queries finish through Query events, so pg:query subscribers receive no lifecycle events.
Learn more
A submittable query object can be returned from client.query with no callback. The Query implementation reports its outcome through error and end events instead. The new guard skips all instrumentation for that supported API, even when pg:query has subscribers.
Example: const q = client.query(new pg.Query('SELECT 1')); q.on('end', done) completes normally, but subscribers receive no pg:query:start or terminal event.
Recommended fix: Instrument queries without callbacks through their event lifecycle, without adding a callback that changes row accumulation or error-event behavior. Cover successful and failed evented queries.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if (res) context.result = { rowCount: res.rowCount, command: res.command } | ||
| return origCb(err, res) |
There was a problem hiding this comment.
🟡 Multi-statement traces lose result fields
For multi-statement queries, traceCallback replaces context.result with the array returned by Query. Subscribers cannot read result.command or result.rowCount from the trace.
Learn more
The result returned for multiple statements is an array of results, as Query records. Although enrichedCb assigns a structured context.result, Node's traceCallback then writes its second callback argument to context.result after enrichedCb returns. With multiple statements, the published context therefore has an array rather than the exposed command and rowCount properties.
Example: Running SELECT 1; SELECT 2 returns two result objects. The asyncEnd subscriber sees context.result as an array, and context.result.command is undefined.
Recommended fix: Define a result shape for multi-statement queries and emit it at a point that Node's traceCallback does not overwrite, or use a separate context property for stable metadata. Test the actual asyncEnd payload.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
|
||
| if (shouldTrace(queryChannel) && query.callback) { | ||
| const context = { | ||
| query: { text: query.text, name: query.name, rowMode: query._rowMode }, |
There was a problem hiding this comment.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit b922f0d. Configure here.
| @@ -1,5 +1,6 @@ | |||
| 'use strict' | |||
| const EventEmitter = require('events').EventEmitter | |||
| const { poolConnectChannel, poolReleaseChannel, poolRemoveChannel, shouldTrace } = require('./diagnostics') | |||
There was a problem hiding this comment.
Pool diagnostics file not published
High Severity
index.js now requires ./diagnostics, but pg-pool's package files list still only includes index.js and esm. Published installs will throw Cannot find module './diagnostics' as soon as the pool is loaded.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit b922f0d. Configure here.
| context, | ||
| null, | ||
| enrichedCb | ||
| ) |
There was a problem hiding this comment.
Query timeout skips tracing end
Medium Severity
When query_timeout fires, the original callback is invoked and query.callback is replaced with a noop, so the traceCallback wrapper never runs. Subscribers get start without error or asyncEnd, which leaves APM spans open.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit b922f0d. Configure here.


This PR introduces tracing channels support to
pg-poolandpgquerying methods as discussed in #3619I haven't yet run a benchmark, but without active tracing or subscribers the overhead is non-existent so existing users shouldn't be affected. The overhead would come from the consumers of the diag channels published here which is done anyways via monkey patching.
I added the following channels:
pg:querypgpg:connectionpgpg:pool:connectpg-poolpg:pool:releasepg-poolpg:pool:removepg-poolI understand there may be hesitation given that AI tooling was used in the implementation. To be clear, this isn't a drive-by contribution. I designed the channel layout, wrote the proposal document, and iterated through multiple rounds to handle real edge cases (Node 18 compat, preserving custom Promise types, hasSubscribers guards). The AI assisted with the code, but the approach and decisions are mine.
Usage
Instrumentations will only need to subscribe to tracing channels to create traces, logs or metrics:
This is part of a broader initiative to bring TracingChannel support to the most widely used Node.js database and cache libraries. The same pattern has already been merged and shipped in:
I have been directly involved in those prior implementations and I'm happy to own this through to release, address any feedback, and provide whatever support is needed. Would love to hear your thoughts.
Supersedes #3624.
Note
Medium Risk
Instrumentation wraps connect, query, and pool checkout/release hot paths; behavior should be unchanged without subscribers, but callback wrapping on those paths warrants careful review when tracing is active.
Overview
Adds Node.js
diagnostics_channelinstrumentation topgandpg-poolso APM/tracing tools can subscribe without monkey-patching.pgexposespg:queryandpg:connectionTracingChannels, wired through newdiagnostics.jshelpers that no-op whendiagnostics_channelis missing and useshouldTrace(hasSubscribers !== false) for Node 18.Client.connect()and callback-basedClient.query()paths wrap work withtraceCallbackand attach connection/query/client (and result) metadata on completion.pg-pooladdspg:pool:connect(TracingChannel with pool stats and client reuse info), pluspg:pool:releaseandpg:pool:removechannels that publish on release and removal (including release errors).Unit tests cover channel payloads and skip unstable TracingChannel behavior on older Node versions.
Reviewed by Cursor Bugbot for commit b922f0d. Configure here.