Skip to content

fix(dataconnect): prevent pg-gateway desync on empty PGlite responses - #11633

Open
fredzqm wants to merge 1 commit into
firebase:mainfrom
fredzqm:agent/fix-pglite-extended-query-desync
Open

fredzqm wants to merge 1 commit into
firebase:mainfrom
fredzqm:agent/fix-pglite-extended-query-desync

Conversation

@fredzqm

@fredzqm fredzqm commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Description

When a parameterized SQL query fails during PostgreSQL Extended Query Protocol Parse or Bind, PGlite discards trailing pipelined frames (Describe/Execute) until Sync and returns an empty Uint8Array(0). Previously, PostgresServer's onMessage generator in src/emulator/dataconnect/pgliteServer.ts yielded zero items and returned undefined, causing pg-gateway to fall through to handleRegularMessage() and inject a bogus ErrorResponse (SQLSTATE 123: "Message code not yet implemented") plus an extra ReadyForQuery (Z).

This wire desync caused lib/pq to fail with pq: unexpected message 'E'; expected ReadyForQuery (masking real PostgreSQL errors as INTERNAL and triggering ECONNRESET/EPIPE), and permanently wedged PGlite in 25P02 if triggered inside a @transaction when Terminate ran DEALLOCATE ALL.

Changes

  • Yield new Uint8Array(0) when PGlite intentionally produces no response bytes for a non-Terminate frame so pg-gateway marks the message handled instead of falling through to handleRegularMessage().
  • On Terminate, log the frame, execute DEALLOCATE ALL via db.exec(), and run ROLLBACK + retry DEALLOCATE ALL strictly when DEALLOCATE ALL fails with 25P02 (leaving healthy concurrent transactions untouched).
  • Close the per-connection pglite-debug.log stream on socket close and guard writes against already-ended streams.
  • Add regression unit tests in src/emulator/dataconnect/pgliteServer.spec.ts covering Parse/Bind errors, pg.Client reuse, concurrent transactions on Terminate, 25P02 recovery, debug-mode Terminate without 25P01 warnings, and closed debug log stream safety.

Scenarios Tested

  • eslint --config .eslintrc.js src/emulator/dataconnect/pgliteServer.ts src/emulator/dataconnect/pgliteServer.spec.ts (0 errors)
  • tsc --project tsconfig.compile.json --noEmit (0 errors)
  • nyc mocha --forbid-only src/emulator/dataconnect/pgliteServer.spec.ts (7/7 passing)

Prepared with the Firebase SQL Connect team agent and reviewed by @fredzqm.

When a parameterized query fails during PostgreSQL Extended Query
Protocol Parse or Bind, PGlite discards trailing pipelined messages
(such as Describe or Execute) until Sync and returns an empty
Uint8Array(0). Previously, PostgresServer's onMessage generator yielded
nothing and returned undefined, causing pg-gateway to fall through to
handleRegularMessage() and emit a spurious ErrorResponse (SQLSTATE 123:
"Message code not yet implemented") plus an extra ReadyForQuery. This
desynchronized lib/pq and pg clients, triggered TCP RST/ECONNRESET, and
left PGlite wedged in SQLSTATE 25P02 when a client terminated inside an
aborted transaction.

Fix this in src/emulator/dataconnect/pgliteServer.ts:
- Yield an empty Uint8Array(0) when PGlite returns no messages on a
  non-Terminate frame so pg-gateway treats the frame as handled.
- On Terminate, log the frame, run DEALLOCATE ALL via db.exec(), and
  roll back strictly on SQLSTATE 25P02 so healthy concurrent
  transactions are untouched while aborted sessions recover cleanly.
- Close the per-connection pglite-debug.log stream on socket close and
  ignore writes after stream end to prevent ERR_STREAM_WRITE_AFTER_END.
- Add unit tests in src/emulator/dataconnect/pgliteServer.spec.ts.

Change-Id: Ic19bef5008c05709035f1c0e8b2b32bf8a29c96e

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request improves the robustness of the PGlite emulator server by properly handling client terminations, rolling back aborted transactions to prevent subsequent connections from getting stuck, and ensuring correct signaling to pg-gateway when no output is produced. It also adds comprehensive unit tests in pgliteServer.spec.ts. The review feedback focuses on aligning the code with the repository's TypeScript guidelines by converting isPgErrorCode into a proper type guard and replacing unsafe 'as any' type assertions with type-safe Buffer.from() conversions.

Comment on lines +353 to +355
function isPgErrorCode(err: unknown, code: string): boolean {
return typeof err === "object" && err !== null && "code" in err && err.code === code;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To adhere to the TypeScript guidelines in the repository style guide (which recommends defining proper interfaces/types or using type guards), we should make isPgErrorCode a proper TypeScript type guard by using the err is { code: string } return type. This allows the TypeScript compiler to safely narrow the type of err in blocks where this function returns true.

function isPgErrorCode(err: unknown, code: string): err is { code: string } {
  return (
    typeof err === "object" &&
    err !== null &&
    "code" in err &&
    typeof err.code === "string" &&
    err.code === code
  );
}
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

/** Logs a raw Postgres frontend wire frame to pglite-debug.log. */
logRequest(request: Uint8Array): void {
this.writeLog(
`\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(request as any as Buffer),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid using as any as an escape hatch to cast Uint8Array to Buffer. Instead, use the standard and type-safe Buffer.from(request) to perform the conversion, adhering to the repository style guide's TypeScript guidelines.

Suggested change
`\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(request as any as Buffer),
`\n[-> ${codeToFrontendMessageName(request[0])}] ` + decoder.write(Buffer.from(request)),
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

for await (const bm of getMessages(response)) {
this.pgliteDebugLog.write(
this.writeLog(
`\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(bm as any as Buffer)}`,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Avoid using as any as an escape hatch to cast Uint8Array to Buffer. Instead, use the standard and type-safe Buffer.from(bm) to perform the conversion, adhering to the repository style guide's TypeScript guidelines.

Suggested change
`\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(bm as any as Buffer)}`,
`\n[<- ${codeTogBackendMessageName(bm[0])}] ${decoder.write(Buffer.from(bm))}`,
References
  1. Never use any or unknown as an escape hatch. Define proper interfaces/types or use type guards. (link)

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 3 lines in your changes missing coverage. Please review.
⚠️ Please upload report for BASE (main@df2c7f4). Learn more about missing BASE report.

Files with missing lines Patch % Lines
src/emulator/dataconnect/pgliteServer.ts 87.50% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##             main   #11633   +/-   ##
=======================================
  Coverage        ?   61.56%           
=======================================
  Files           ?      870           
  Lines           ?    51215           
  Branches        ?    10353           
=======================================
  Hits            ?    31531           
  Misses          ?    18528           
  Partials        ?     1156           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
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.

2 participants