Skip to content

fix(#6457): recognize COMMIT/ROLLBACK/END over the Postgres simple-query protocol - #6542

Merged
robfrank merged 2 commits into
mainfrom
fix/6457-postgres-simple-query-an-aborted-begin
Aug 21, 2026
Merged

robfrank merged 2 commits into
mainfrom
fix/6457-postgres-simple-query-an-aborted-begin

Conversation

@robfrank

Copy link
Copy Markdown
Collaborator

Closes #6457

Problem

Over the Postgres simple-query ('Q') wire protocol, once a statement erred inside an explicit BEGIN block the session became permanently wedged, with three separate defects in PostgresNetworkExecutor:

  1. writeReadyForQueryMessage() never reported the aborted status 'E' - only 'T' (in a transaction) or 'I' (idle) - so a client had no wire-level signal the transaction had failed.
  2. queryCommand() recognized only BEGIN, never COMMIT/ROLLBACK/END. There was no statement over the simple-query path that could ever end an aborted block, and even without a prior error a plain COMMIT/ROLLBACK fell through to the SQL engine as an ordinary (failing) statement, leaving explicitTransactionStarted stuck true forever.
  3. While aborted, queryCommand() silently returned for every statement - no ErrorResponse, no CommandComplete - so the client couldn't tell its statement never ran, and writes made before the error were left in limbo.

Fix

postgresw/src/main/java/com/arcadedb/postgres/PostgresNetworkExecutor.java:

  • writeReadyForQueryMessage() now reports 'E' whenever errorInTransaction is set (checked before the explicitTransactionStarted/'T' branch).
  • The normal (non-aborted) dispatch chain in queryCommand() gains COMMIT/COMMIT TRANSACTION/END/END TRANSACTION and ROLLBACK/ROLLBACK TRANSACTION handling, committing or rolling back the underlying transaction and clearing explicitTransactionStarted (previously never cleared on a plain COMMIT/ROLLBACK).
  • The errorInTransaction branch now recognizes those same end-of-transaction keywords: it rolls back and clears the aborted state, matching real Postgres semantics where a COMMIT of a failed transaction acts as a ROLLBACK (with a warning) rather than trying to persist writes that already failed. Every other statement while aborted now gets an ErrorResponse with SQLSTATE 25P02 ("current transaction is aborted, commands ignored until end of transaction block") instead of being silently swallowed.
  • getTag() gains COMMIT/ROLLBACK tags for CommandComplete.

Test plan

New IT postgresw/src/test/java/com/arcadedb/postgres/Issue6457AbortedTransactionSimpleQueryIT.java speaks the simple-query wire protocol directly over a raw socket (not through the JDBC driver) so the exact ReadyForQuery status byte and ErrorResponse content can be asserted on:

  1. An aborted transaction reports status 'E', refuses further statements with SQLSTATE 25P02 until ROLLBACK, and the session is fully usable again afterward.
  2. COMMIT of an aborted transaction acts as ROLLBACK and discards the writes made before the error.
  3. A plain COMMIT with no prior error is recognized over the simple-query protocol, ends the transaction (status back to 'I'), and persists the writes.

Verification run (isolated -Dmaven.repo.local, port 2480 freed from the local brew arcadedb service beforehand and restarted after):

  • mvn -pl postgresw verify -Dit.test=Issue6457AbortedTransactionSimpleQueryIT -DskipITs=false: new IT green, 3/3.
  • mvn -pl postgresw verify -DskipITs=false (full module, unit + IT): all green, 408 unit tests + 169 integration tests, 0 failures/errors - no regressions from the COMMIT/ROLLBACK/END dispatch changes.

…ery protocol

Over the simple-query ('Q') wire protocol, once a statement failed inside an
explicit BEGIN block the session became permanently wedged:

- queryCommand() recognized only BEGIN, never COMMIT/ROLLBACK/END, so there
  was no statement that could ever end an aborted transaction block.
- While aborted, every subsequent statement was silently swallowed (no
  ErrorResponse, no CommandComplete), leaving the client with no signal its
  statement never ran.
- writeReadyForQueryMessage() never reported the aborted status 'E', so even
  a client checking the wire-level transaction status had no way to detect
  the failure.

This also affected the non-aborted path: a plain COMMIT/ROLLBACK fell
through to the SQL engine as an ordinary statement and never cleared
explicitTransactionStarted, so ReadyForQuery kept reporting 'T' after commit.

Fix, matching real Postgres semantics:
- queryCommand()'s normal dispatch now recognizes COMMIT/COMMIT TRANSACTION/
  END/END TRANSACTION and ROLLBACK/ROLLBACK TRANSACTION, committing or rolling
  back the underlying transaction and clearing explicitTransactionStarted.
- While aborted, COMMIT/ROLLBACK/END now roll back and clear the aborted
  state (a COMMIT of a failed transaction acts as a ROLLBACK, per Postgres),
  while every other statement gets an ErrorResponse with SQLSTATE 25P02
  ("current transaction is aborted") instead of being swallowed.
- writeReadyForQueryMessage() reports 'E' whenever errorInTransaction is set.
- getTag() gains COMMIT/ROLLBACK tags for CommandComplete.

Verified with a new IT that speaks the wire protocol directly over a raw
socket to assert on the ReadyForQuery status byte and ErrorResponse content.
@mergify

mergify Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@claude

claude Bot commented Aug 21, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped bug fix. The three defects described in the PR body all check out against the code, and the fix for each is exactly where you'd expect it:

  • writeReadyForQueryMessage() now checks errorInTransaction before the explicitTransactionStarted branch, so 'E' is reported correctly (PostgresNetworkExecutor.java:717).
  • The aborted-transaction branch in queryCommand() no longer silently returns: it now routes COMMIT/ROLLBACK/END to a clean rollback-with-"ROLLBACK"-tag path, empty statements to emptyQueryResponse(), and everything else to a 25P02 ErrorResponse (:582-603). That matches real Postgres semantics, where a COMMIT of a failed transaction is silently downgraded to a ROLLBACK.
  • The non-aborted dispatch chain gains COMMIT/ROLLBACK handling that actually calls database.commit()/database.rollback() and clears explicitTransactionStarted (:648-657), fixing the previous behavior where a plain COMMIT fell through to the SQL engine as a failing statement.

The new helpers (isCommitStatement, isRollbackStatement, isTransactionEndStatement) are small, well-named, and the comments explain the non-obvious why (Postgres's COMMIT-of-aborted-tx-acts-like-ROLLBACK behavior) rather than restating the code, per the repo's comment conventions.

Test coverage

Strong. Driving the simple-query protocol over a raw socket instead of through the JDBC driver is the right call here since it lets the test assert on the exact ReadyForQuery status byte and ErrorResponse SQLSTATE, which is exactly what was broken. The three scenarios (refuse-until-rollback, commit-acts-as-rollback-and-discards-writes, plain-commit-persists) cover the reported defects well.

Minor / non-blocking suggestions

  1. COMMIT WORK / ROLLBACK WORK / END WORK are valid SQL-standard forms some clients send, but isCommitStatement/isRollbackStatement don't match them (only bare and ... TRANSACTION forms). Not required for this fix, but worth a follow-up if any target client uses the WORK keyword.
  2. The extended query protocol (Parse/Bind/Execute path) has a similarly-shaped gap: around :1895-1906, the Parse dispatch recognizes BEGIN/COMMIT but not ROLLBACK, so a bare ROLLBACK sent over the extended protocol still falls through to the SQL parser and fails. Since issue Postgres simple-query: an aborted BEGIN block wedges the session (ReadyForQuery never 'E', COMMIT/ROLLBACK unrecognized, statements silently swallowed) #6457 is explicitly scoped to the simple-query protocol, this is fine to leave out of this PR, but might be worth tracking as a follow-up since it's the same class of bug.
  3. Nit: getTag()'s isTransactionEndStatement-driven "ROLLBACK" tag for an aborted COMMIT is correct (matches real psql behavior), but it might be worth a one-line comment at the writeCommandComplete("ROLLBACK", 0) call site itself (not just on the helper) since a future reader skimming just queryCommand() could otherwise wonder why a COMMIT request writes a "ROLLBACK" tag.

Performance / security

No concerns. The added checks are cheap string comparisons on an already-uppercased string, no new allocations of note, and there's no new user-controlled input reaching anything sensitive (SQL execution, file I/O, etc.) beyond what already existed.

Nice fix, this closes a real "wedged session" bug with good regression coverage.

@codacy-production

codacy-production Bot commented Aug 21, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 24 complexity

Metric Results
Complexity 24

View in Codacy

🟢 Coverage 83.87% diff coverage · -6.50% coverage variation

Metric Results
Coverage variation ✅ -6.50% coverage variation
Diff coverage ✅ 83.87% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (03cb038) 163714 130755 79.87%
Head commit (d3ee423) 196545 (+32831) 144206 (+13451) 73.37% (-6.50%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#6542) 31 26 83.87%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Per review feedback on PR #6542: add a one-line comment at the
writeCommandComplete("ROLLBACK", 0) call site itself, not just on the
isTransactionEndStatement() helper, since a reader skimming only
queryCommand() could otherwise wonder why a COMMIT/END request writes a
"ROLLBACK" CommandComplete tag.
@claude

claude Bot commented Aug 21, 2026

Copy link
Copy Markdown

Review

Solid, well-scoped fix for #6457. The three defects described in the PR body line up with what's in the diff, and the new IT talks to the wire protocol over a raw socket so it can actually assert on the ReadyForQuery status byte and the ErrorResponse SQLSTATE, which is the right level for this kind of bug.

Correctness

  • The invariant errorInTransaction ⟹ explicitTransactionStarted (enforced by setErrorInTx(), which only sets errorInTransaction when explicitTransactionStarted is already true) is relied on correctly in the aborted branch, so unconditionally clearing explicitTransactionStarted = false there is safe.
  • database.rollback() swallows TransactionException internally (LocalDatabase.rollback()), so the database.isTransactionActive() guards before commit()/rollback() are belt-and-suspenders rather than load-bearing - not a problem, just noting they're not strictly required for correctness.
  • Treating COMMIT of an aborted transaction as a ROLLBACK (and always emitting the "ROLLBACK" tag regardless of which keyword the client sent) matches real Postgres semantics, and the comment at the writeCommandComplete("ROLLBACK", 0) call site (added in the follow-up commit) makes that non-obvious behavior clear at the point someone would actually trip over it.

Minor / non-blocking observations

  • isCommitStatement/isRollbackStatement/isTransactionEndStatement only match exact keyword strings ("END", "COMMIT TRANSACTION", etc.). Real Postgres also accepts END WORK/COMMIT WORK and tolerates arbitrary internal whitespace. This isn't a regression (the pre-existing BEGIN/BEGIN TRANSACTION check has the same limitation), so it's fine to leave as-is, but worth keeping in mind if a client sends one of those variants.
  • The extended-query (Parse/Bind/Execute) path has the same "silently return while errorInTransaction" pattern at the bindCommand handler (~line 1762) that this PR fixes for the simple-query path. Out of scope for this PR since Postgres simple-query: an aborted BEGIN block wedges the session (ReadyForQuery never 'E', COMMIT/ROLLBACK unrecognized, statements silently swallowed) #6457 and the new IT are specifically about the simple-query protocol, but it looks like the same class of bug would reproduce there - might be worth a follow-up issue.

Test coverage
Good - three targeted scenarios (aborted-then-refused-then-ROLLBACK, COMMIT-of-aborted-acts-as-ROLLBACK-and-discards-writes, plain-COMMIT-persists) each verified against actual wire bytes rather than through the JDBC driver, which is what makes the status-byte and SQLSTATE assertions possible. assertTimeoutPreemptively guards against a hang if the fix regresses and the server stops responding.

Performance / security
No concerns - the added work per statement is a handful of string comparisons against already-uppercased text, consistent with the existing BEGIN handling, and no new external input is parsed beyond fixed keyword matching.

@codecov

codecov Bot commented Aug 21, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 61.29032% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.20%. Comparing base (03cb038) to head (d3ee423).
⚠️ Report is 68 commits behind head on main.

Files with missing lines Patch % Lines
...com/arcadedb/postgres/PostgresNetworkExecutor.java 61.29% 5 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #6542      +/-   ##
==========================================
+ Coverage   71.16%   71.20%   +0.03%     
==========================================
  Files        1865     1866       +1     
  Lines      163714   164158     +444     
  Branches    34575    34688     +113     
==========================================
+ Hits       116508   116882     +374     
- Misses      33000    33038      +38     
- Partials    14206    14238      +32     

☔ 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.

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.

Postgres simple-query: an aborted BEGIN block wedges the session (ReadyForQuery never 'E', COMMIT/ROLLBACK unrecognized, statements silently swallowed)

1 participant