From 8d8573e53ab1a06f685955c8578cfb9d26cd603d Mon Sep 17 00:00:00 2001 From: paula-alves Date: Fri, 4 Dec 2026 11:20:16 +0000 Subject: [PATCH] fix(sports): filter pg client not-queryable as transient (BIT-33527) A pooled pg Client that had a connection error (socket closed, server restart, network blip) is marked not-queryable by node-postgres before Prisma's adapter-pg runs the next query on it. The message "Client has encountered a connection error and is not queryable" has no Prisma error code, so the existing isPrismaConnectionClosed (P1017) check does not catch it. The rejection escapes to the SportsWorker fillRegister and tick catch blocks, logs as warn, and pages the error loop. - Add isPgClientNotQueryable to lib/pg.ts and downgrade the error to info in fillRegister and tick (same pattern as BIT-32810, BIT-32083). - Add the message to isTransientDatabaseError in reporter.ts so any other code path that lets it propagate to a generic log.error is also suppressed (same safety-net pattern as BIT-33537 for P2037). - Add unit tests for the new helper and the reporter filter. Paperclip-Issue: BIT-33527 --- apps/api/src/lib/pg.test.ts | 24 +++++++++++++++++++++++- apps/api/src/lib/pg.ts | 12 ++++++++++++ apps/api/src/lib/reporter.ts | 2 +- apps/api/src/sports/service.ts | 10 ++++++++-- apps/api/test/reporter.test.ts | 3 ++- 5 files changed, 46 insertions(+), 5 deletions(-) diff --git a/apps/api/src/lib/pg.test.ts b/apps/api/src/lib/pg.test.ts index b0c2503..eae3abf 100644 --- a/apps/api/src/lib/pg.test.ts +++ b/apps/api/src/lib/pg.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js"; +import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "./pg.js"; class PrismaLike extends Error { constructor(readonly code: string, message: string) { @@ -138,6 +138,28 @@ describe("isPrismaTransactionClosed", () => { }); }); +describe("isPgClientNotQueryable", () => { + it("matches the raw pg client.js message (BIT-33527)", () => { + const err = new Error("Client has encountered a connection error and is not queryable"); + expect(isPgClientNotQueryable(err)).toBe(true); + }); + + it("matches the message when wrapped in a Prisma raw-query failure", () => { + const err = new Error("Invalid `prisma.$queryRaw()` invocation:\n\nRaw query failed. Code: `N/A`. Message: `Client has encountered a connection error and is not queryable`"); + expect(isPgClientNotQueryable(err)).toBe(true); + }); + + it("does not match a server-closed (P1017) error", () => { + expect(isPgClientNotQueryable(new PrismaLike("P1017", "Server has closed the connection."))).toBe(false); + }); + + it("does not match an unrelated query error", () => { + expect(isPgClientNotQueryable(new PrismaLike("P2002", "Unique constraint failed"))).toBe(false); + expect(isPgClientNotQueryable(null)).toBe(false); + expect(isPgClientNotQueryable("string")).toBe(false); + }); +}); + describe("retryOnConnectionClosed", () => { it("retries once when the first attempt throws P1017 and returns the second result", async () => { let calls = 0; diff --git a/apps/api/src/lib/pg.ts b/apps/api/src/lib/pg.ts index aec216a..13ea3c2 100644 --- a/apps/api/src/lib/pg.ts +++ b/apps/api/src/lib/pg.ts @@ -76,6 +76,18 @@ export function isPrismaTransactionClosed(err: unknown): boolean { return /Transaction already closed/i.test(err.message); } +/** + * A pooled `pg` Client had a connection error (socket closed, server restart, network blip) and was marked + * not-queryable by node-postgres before Prisma's adapter-pg ran the next query on it. The message comes from + * `pg/lib/client.js` and has no Prisma error code, so the `isPrismaConnectionClosed` (P1017) check does not + * catch it. The pool discards the dead client and hands out a fresh one on the next attempt, so this is + * transient and must not page the error loop (BIT-33527). + */ +export function isPgClientNotQueryable(err: unknown): boolean { + if (!(err instanceof Error)) return false; + return /Client has encountered a connection error and is not queryable/i.test(err.message); +} + /** * Runs `fn`, retrying it once when Postgres closed the connection before the query (`P1017`). The pool hands out a * fresh client on the next attempt, so a single retry clears the blip without surfacing it to the caller's diff --git a/apps/api/src/lib/reporter.ts b/apps/api/src/lib/reporter.ts index 24c2cd2..81b8c45 100644 --- a/apps/api/src/lib/reporter.ts +++ b/apps/api/src/lib/reporter.ts @@ -27,7 +27,7 @@ function isTransientDatabaseError(err: unknown): boolean { if (!(err instanceof Error)) return false; const code = (err as { code?: unknown }).code; if (code === "P1001" || code === "P1017" || code === "P2037" || code === "ECONNREFUSED") return true; - return /57P01|57P03|53300|remaining connection slots are reserved|too many clients already|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection|ECONNREFUSED/i.test(err.message); + return /57P01|57P03|53300|remaining connection slots are reserved|too many clients already|the database system is shutting down|the database system is starting up|Can't reach database server|Server has closed the connection|Client has encountered a connection error and is not queryable|ECONNREFUSED/i.test(err.message); } export type ReportLevel = "critical" | "error" | "warning" | "info"; diff --git a/apps/api/src/sports/service.ts b/apps/api/src/sports/service.ts index 577b598..d17646b 100644 --- a/apps/api/src/sports/service.ts +++ b/apps/api/src/sports/service.ts @@ -8,7 +8,7 @@ import type { IngestLogger } from "../ingest/service.js"; import { DEFAULT_CODE_LIST } from "../library/iptc.js"; import { badRequest, notFound } from "../lib/errors.js"; import { waitUntil } from "../lib/idle.js"; -import { isPostgresAdminShutdown, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js"; +import { isPostgresAdminShutdown, isPgClientNotQueryable, isPrismaConnectionClosed, isPrismaServerUnreachable, isPrismaTooManyConnections, isPrismaTransactionClosed, isPrismaTransactionTimeout, retryOnConnectionClosed } from "../lib/pg.js"; import type { LocalStorage, UrlSigner } from "../storage/storage.js"; import { type CodeClash, type SquadForCodes, buildCodeLines, hasGeneratedBlock, mergeGenerated, slugify, toTsv } from "./codegen.js"; import { fetchYouthCamps, youthAbbrev } from "./fpa-youth.js"; @@ -2724,6 +2724,8 @@ export class SportsWorker { this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction rolled back (connection blip or deadlock)"); } else if (isPrismaTransactionTimeout(err)) { this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, transaction start timed out (pool contention)"); + } else if (isPgClientNotQueryable(err)) { + this.opts.log.info({ err: (err as Error).message }, "sports: tick skipped, pooled pg client was not queryable (connection blip)"); } else { this.opts.log.warn({ err }, "sports: tick failed"); } @@ -2746,7 +2748,11 @@ export class SportsWorker { } if (!this.stopped && saved >= 0 && this.opts.afterRegister) await this.opts.afterRegister(); } catch (err) { - this.opts.log.warn({ err }, "sports: register not filled"); + if (isPgClientNotQueryable(err)) { + this.opts.log.info({ err: (err as Error).message }, "sports: register not filled, pooled pg client was not queryable (connection blip)"); + } else { + this.opts.log.warn({ err }, "sports: register not filled"); + } } finally { this.filling = false; } diff --git a/apps/api/test/reporter.test.ts b/apps/api/test/reporter.test.ts index 9d085fe..9199ab4 100644 --- a/apps/api/test/reporter.test.ts +++ b/apps/api/test/reporter.test.ts @@ -108,7 +108,8 @@ describe("errors to errors.bitreport.pt", () => { log.error({ err: mk("Raw query failed. Code: `53300`. Message: `remaining connection slots are reserved for roles with the SUPERUSER attribute`", "P2010") }, "health: query failed"); log.error({ err: mk("Invalid `prisma.cloudSource.findUnique()` invocation:\n\nToo many database connections opened: sorry, too many clients already", "P2037") }, "archive: viewer source lookup failed"); log.error({ err: mk("connect ECONNREFUSED 127.0.0.1:5432", "ECONNREFUSED") }, "realtime error"); - reporter.reportError(mk("Database error. Code: 57P03. Message: the database system is shutting down"), "worker"); + log.error({ err: mk("Client has encountered a connection error and is not queryable") }, "sports: register not filled"); + reporter.reportError(mk("Client has encountered a connection error and is not queryable"), "worker"); reporter.reportError(mk("connect ECONNREFUSED 127.0.0.1:5432", "ECONNREFUSED"), "api"); log.error({ err: new Error("render crashed") }, "real error"); await reporter.flush();