:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(usage-ingestion): survive GOAWAY on idle grpc connections (#95018)
Ben White54f84b737cc0
diff --git a/nodejs/src/common/usage-ingestion/client.test.ts b/nodejs/src/common/usage-ingestion/client.test.tsindex 310b77c0c8b1..aca45fc8ff52 100644--- a/nodejs/src/common/usage-ingestion/client.test.ts+++ b/nodejs/src/common/usage-ingestion/client.test.ts@@ -79,19 +79,52 @@ describe('UsageIngestionClient', () => {expect(headers).toEqual([{ 'x-client-name': 'cdp' }])})- it('counts the whole chunk as failed when the call itself fails', async () => {+ // A retryable code gets the whole budget before the chunk is written off, and a code the+ // service already decided on gets no retry at all.+ test.each([+ { name: 'a code the service decided on', code: Code.NotFound, label: 'NotFound', calls: 1 },+ { name: 'a code the transport raised', code: Code.Canceled, label: 'Canceled', calls: 3 },+ ])('counts the whole chunk as failed for $name', async ({ code, label, calls: expected }) => {;(client as any).client = {ingestBillingUsage: () => {calls += 1- return Promise.reject(new ConnectError('nope', Code.NotFound))+ return Promise.reject(new ConnectError('nope', code))},}await client.ingest([record(7), record(8)])- expect(calls).toBe(1)+ expect(calls).toBe(expected)expect(await counted('usage_ingestion_records_failed_total')).toEqual([- expect.objectContaining({ labels: expect.objectContaining({ error_code: 'NotFound' }), value: 2 }),+ expect.objectContaining({ labels: expect.objectContaining({ error_code: label }), value: 2 }),+ ])+ })++ // The service ends every connection with GOAWAY at max_connection_age, and connect-node+ // reports the flush that races the teardown as Canceled or Internal. Dropping those loses+ // usage the service never saw, so they have to be retried like any other transport failure.+ test.each([+ { name: 'Canceled from a GOAWAY teardown', code: Code.Canceled, label: 'Canceled' },+ { name: 'Internal from a destroyed session', code: Code.Internal, label: 'Internal' },+ ])('retries $name until the call succeeds', async ({ code, label }) => {+ acceptedRecordIds = ['record-7']+ ;(client as any).client = {+ ingestBillingUsage: () => {+ calls += 1+ return calls < 3+ ? Promise.reject(new ConnectError('gone', code))+ : Promise.resolve({ acceptedRecordIds })+ },+ }++ await client.ingest([record(7)])++ expect(calls).toBe(3)+ expect(await counted('usage_ingestion_records_sent_total')).toEqual([expect.objectContaining({ value: 1 })])+ // A retry that lands drops nothing, so the retries read on their own counter.+ expect(await counted('usage_ingestion_records_failed_total')).toEqual([])+ expect(await counted('usage_ingestion_retries_total')).toEqual([+ expect.objectContaining({ labels: expect.objectContaining({ error_code: label }), value: 2 }),])})})diff --git a/nodejs/src/common/usage-ingestion/client.ts b/nodejs/src/common/usage-ingestion/client.tsindex da21508d42fa..243fb856f8d8 100644--- a/nodejs/src/common/usage-ingestion/client.ts+++ b/nodejs/src/common/usage-ingestion/client.ts@@ -9,6 +9,7 @@ import {UsageIngestion,} from '~/common/generated/usage-ingestion/usage_ingestion/v1/service_pb'import { logger } from '~/common/utils/logger'+import { delay } from '~/common/utils/utils'const usageRecordsSentCounter = new Counter({name: 'usage_ingestion_records_sent_total',@@ -22,7 +23,28 @@ const usageRecordsFailedCounter = new Counter({labelNames: ['producer_id', 'usage_key', 'error_code'],})-const RETRYABLE_CODES = new Set([Code.Unavailable, Code.DeadlineExceeded, Code.ResourceExhausted, Code.Aborted])+const usageRetriesCounter = new Counter({+ name: 'usage_ingestion_retries_total',+ help: 'Ingest calls retried after a transient error. A retry that succeeds drops no records.',+ labelNames: ['producer_id', 'error_code'],+})++// Canceled and Internal are how connect-node reports a connection that went away underneath the+// call: the service ends every connection with GOAWAY at max_connection_age, and a flush that+// races that teardown never reaches the service. Retrying is safe because recordId makes ingest+// idempotent. Unlike personhog this set includes Canceled, because no caller passes an abort+// signal here, so Canceled can only mean the transport went away.+const RETRYABLE_CODES = new Set([+ Code.Unavailable,+ Code.DeadlineExceeded,+ Code.ResourceExhausted,+ Code.Aborted,+ Code.Canceled,+ Code.Internal,+])++const MAX_ATTEMPTS = 3+const RETRY_BACKOFF_MS = 100/*** The record IDs the service left out of its accepted list. The service skips a record it can@@ -135,7 +157,10 @@ export class UsageIngestionClient {}} catch (error) {const code = error instanceof ConnectError ? error.code : Code.Unknown- if (attempt === 0 && RETRYABLE_CODES.has(code)) {+ if (attempt + 1 < MAX_ATTEMPTS && RETRYABLE_CODES.has(code)) {+ usageRetriesCounter.inc({ producer_id: this.producerId, error_code: Code[code] ?? 'unknown' })+ // Backoff so a burst of connection churn does not eat every attempt at once.+ await delay(RETRY_BACKOFF_MS * 2 ** attempt)await this.ingestChunk(chunk, attempt + 1)return}diff --git a/nodejs/src/common/usage-ingestion/goaway.test.ts b/nodejs/src/common/usage-ingestion/goaway.test.tsnew file mode 100644index 000000000000..a842f2fe4435--- /dev/null+++ b/nodejs/src/common/usage-ingestion/goaway.test.ts@@ -0,0 +1,62 @@+import { Http2SessionManager } from '@connectrpc/connect-node'+import http2 from 'http2'+import { AddressInfo } from 'net'++// usage-ingestion ends every connection with GOAWAY once it reaches max_connection_age. The+// usage client is idle between flushes, so connect-node destroys the session with a deferred+// error. A flush that arrives before the socket has closed removes the error listeners, and+// without patches/@connectrpc__connect-node@*.patch the error crashes the process+// (https://github.com/connectrpc/connect-es/issues/1768).+describe('Http2SessionManager GOAWAY on an idle connection', () => {+ let server: http2.Http2Server+ const serverSessions: http2.ServerHttp2Session[] = []++ beforeAll(async () => {+ server = http2.createServer()+ server.on('session', (session) => serverSessions.push(session))+ server.on('stream', (stream) => stream.respond({ ':status': 200 }))+ await new Promise<void>((resolve) => server.listen(0, resolve))+ })++ afterAll(async () => {+ serverSessions.forEach((session) => session.destroy())+ await new Promise<void>((resolve) => server.close(() => resolve()))+ })++ it('does not raise the deferred connection error when a request follows the GOAWAY', async () => {+ const { port } = server.address() as AddressInfo+ const manager = new Http2SessionManager(`http://127.0.0.1:${port}`)+ const closeStream = (stream: http2.ClientHttp2Stream): Promise<void> =>+ new Promise((resolve) => {+ stream.once('close', () => resolve())+ stream.close(http2.constants.NGHTTP2_NO_ERROR)+ })+ try {+ const firstRequest = await manager.request('POST', '/', {}, {})+ const conn = (manager as unknown as { s: { conn: http2.ClientHttp2Session } }).s.conn+ await closeStream(firstRequest)+ expect(manager.state()).toBe('idle')++ // Node emits the deferred error right after this socket closes. Jest reports it as an+ // unhandled error when the patch is missing, so the test only has to outlive it.+ const socket = conn.socket+ const socketClosed = new Promise<void>((resolve) => socket.prependOnceListener('close', () => resolve()))++ serverSessions[0].goaway(http2.constants.NGHTTP2_NO_ERROR)+ await new Promise<void>((resolve) => conn.once('goaway', () => resolve()))+ expect(conn.destroyed).toBe(true)++ const secondRequest = await manager.request('POST', '/', {}, {})+ await socketClosed+ await new Promise<void>((resolve) => setImmediate(resolve))+ expect(manager.state()).toBe('open')+ const response = await new Promise<http2.IncomingHttpHeaders>((resolve) =>+ secondRequest.once('response', resolve)+ )+ expect(response[':status']).toBe(200)+ await closeStream(secondRequest)+ } finally {+ manager.abort()+ }+ })+})diff --git a/patches/@[email protected] b/patches/@[email protected]new file mode 100644index 000000000000..bcffe6bc11bf--- /dev/null+++ b/patches/@[email protected]@@ -0,0 +1,38 @@+diff --git a/dist/cjs/http2-session-manager.js b/dist/cjs/http2-session-manager.js+index 1df02ec9a15e173e13eb8a3a1ed0b56db9be4659..b324e7a8590ca8a3bb7a5a15142958ae9774e1f3 100644+--- a/dist/cjs/http2-session-manager.js++++ b/dist/cjs/http2-session-manager.js+@@ -470,6 +470,14 @@ function ready(conn, options) {+ // destroying the session), but later versions do not.+ // We call conn.destroy() because calling conn.close() ourselves is ineffective+ // here - it appears that the method is already being called, see https://github.com/nodejs/node/blob/198affc63973805ce5102d246f6b7822be57f5fc/lib/internal/http2/core.js#L681++ conn.once("error", () => {++ // conn.destroy() defers the error until the socket has closed. If the++ // manager exits the "ready" state before that (for example because a++ // new request sees the destroyed connection and reconnects), our error++ // listeners are removed in onExitState(), and the deferred error would++ // be raised as an uncaught exception, crashing the process.++ // We attach this one to swallow uncaught exceptions.++ });+ conn.destroy(new connect_1.ConnectError("received GOAWAY without any open streams", connect_1.Code.Canceled), http2.constants.NGHTTP2_NO_ERROR);+ return;+ }+diff --git a/dist/esm/http2-session-manager.js b/dist/esm/http2-session-manager.js+index 4d4517b737039e014d11a077cc540f9d29eab359..ea24c3df8f1ee883b8ee3544f4b8f9f15be1c0da 100644+--- a/dist/esm/http2-session-manager.js++++ b/dist/esm/http2-session-manager.js+@@ -466,6 +466,14 @@ function ready(conn, options) {+ // destroying the session), but later versions do not.+ // We call conn.destroy() because calling conn.close() ourselves is ineffective+ // here - it appears that the method is already being called, see https://github.com/nodejs/node/blob/198affc63973805ce5102d246f6b7822be57f5fc/lib/internal/http2/core.js#L681++ conn.once("error", () => {++ // conn.destroy() defers the error until the socket has closed. If the++ // manager exits the "ready" state before that (for example because a++ // new request sees the destroyed connection and reconnects), our error++ // listeners are removed in onExitState(), and the deferred error would++ // be raised as an uncaught exception, crashing the process.++ // We attach this one to swallow uncaught exceptions.++ });+ conn.destroy(new ConnectError("received GOAWAY without any open streams", Code.Canceled), http2.constants.NGHTTP2_NO_ERROR);+ return;+ }diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex d5ec8a2e256a..a73fd3e1591a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -186,6 +186,9 @@ overrides:'@tiptap/extension-underline': 3.20.6patchedDependencies:+ '@connectrpc/[email protected]':+ hash: a8248109885bda6ff3ce8663332190cabec9ca5da4deab47603ea6b1dbca27c4+ path: patches/@[email protected]hash: 2e3e09d22bbc20d8961e0392c318f12ffada0babb6422f03b5538af8b2707852path: patches/[email protected]@@ -1512,7 +1515,7 @@ importers:version: 2.1.1(@bufbuild/[email protected])'@connectrpc/connect-node':specifier: ^2.1.1- version: 2.1.1(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))+ version: 2.1.1(patch_hash=a8248109885bda6ff3ce8663332190cabec9ca5da4deab47603ea6b1dbca27c4)(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))'@dsnp/parquetjs':specifier: ^1.8.7version: 1.8.7@@ -25793,7 +25796,7 @@ snapshots:dependencies:commander: 14.0.3- '@connectrpc/[email protected](@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))':+ '@connectrpc/[email protected](patch_hash=a8248109885bda6ff3ce8663332190cabec9ca5da4deab47603ea6b1dbca27c4)(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))':dependencies:'@bufbuild/protobuf': 2.11.0'@connectrpc/connect': 2.1.1(@bufbuild/[email protected])diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 7c7ac5bc13dc..18cd1627a405 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -102,6 +102,7 @@ overrides:'@tiptap/extension-underline': 3.20.6patchedDependencies:+ '@connectrpc/[email protected]': patches/@[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected][email protected]: patches/[email protected]