Skip to content

[FIX] Postgres: Prevent transaction/connection leaks and protect UID/ModSeq invariants - #3237

Draft
prosgarz35 wants to merge 3 commits into
apache:masterfrom
prosgarz35:morebugs
Draft

prosgarz35 wants to merge 3 commits into
apache:masterfrom
prosgarz35:morebugs

Conversation

@prosgarz35

Copy link
Copy Markdown
Contributor

Description

This PR provides surgical fixes for critical operational issues in the PostgreSQL backend stack (backends-common/postgres and mailbox/postgres):

1. Rollback transaction on timeout (PostgresExecutor.java)

  • Problem: When a reactive timeout (jooqReactiveTimeout) was triggered inside executeTransaction(...), handleTimeout(connection, e) cancelled the running query via cancelRunningQuery(connection), but omitted rolling back the uncommitted transaction. As a result, the connection remained in an open/in-progress transaction state (idle in transaction), locking table rows and holding connections from the R2DBC pool until eviction.
  • Fix: Added handleTransactionTimeout(connection, timeoutException) which cancels the running query and explicitly rolls back the transaction before propagating the TimeoutException.

2. Null-safe check in preparedStatementConflictException (PostgresExecutor.java)

  • Problem: In preparedStatementConflictException(), checking throwable.getMessage().contains(...) without verifying getMessage() != null could throw an unexpected NullPointerException during retry filtering if the root cause exception lacked a message.
  • Fix: Added null-guard check throwable.getMessage() != null.

3. Ensure connection release on error/cancel in schema management (PostgresTableManager.java)

  • Problem: Mono.usingWhen calls in schema initialization (initializePostgresExtension, initializeTables, listExistTables, truncate, initializeTableIndexes) only registered the normal completion release callback (asyncCleanup). In the event of an error or downstream cancellation during table or index creation, the acquired R2DBC connections were not properly closed/returned to the pool.
  • Fix: Configured onError and onCancel callbacks to guarantee connection closure across all execution paths.

4. Protect UID and ModSeq monotonic invariants (PostgresUidProvider, PostgresModSeqProvider, PostgresMessageMapper)

  • Problem: incrementAndGetLastUid and incrementAndGetModSeq used .defaultIfEmpty(MessageUid.MIN_VALUE) and .defaultIfEmpty(ModSeq.first()). If a mailbox was concurrently deleted or not found, the operation silently fell back to UID 1 or ModSeq 1. This broke RFC 3501 strict monotonic ordering guarantees and could corrupt client sync state.
  • Fix: Replaced .defaultIfEmpty(...) fallbacks with .switchIfEmpty(Mono.error(new MailboxNotFoundException(...))) across PostgresUidProvider, PostgresModSeqProvider, and PostgresMessageMapper.setNewUidAndModSeq.

Testing

  • Clean compilation and build verified across:
    • backends-common/postgres
    • mailbox/postgres
    • server/apps/postgres-app

@chibenwa chibenwa 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.

Mono.usingWhen already applies task cleanup in case of error or cancelation.
This commit is thus useless.

.flatMap(Result::getRowsUpdated)
.then(),
Connection::close,
(connection, error) -> connection.close(),

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.

Likely log the error as this is a terminal exception, here it is lost

.flatMap(table -> createAndAlterTable(table, dsl, connection))))
.then(),
connection -> postgresExecutor.connectionFactory().closeConnection(connection),
(connection, error) -> postgresExecutor.connectionFactory().closeConnection(connection),

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.

Likely log the error as this is a terminal exception, here it is lost

.map(r -> r.get(0, String.class))
.collectList(),
connection -> postgresExecutor.connectionFactory().closeConnection(connection),
(connection, error) -> postgresExecutor.connectionFactory().closeConnection(connection),

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.

Likely log the error as this is a terminal exception, here it is lost

.doOnError(e -> LOGGER.error("Error while truncating table {}", table.getName(), e)))
.then()),
connection -> postgresExecutor.connectionFactory().closeConnection(connection),
(connection, error) -> postgresExecutor.connectionFactory().closeConnection(connection),

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.

Likely log the error as this is a terminal exception, here it is lost

.flatMap(index -> createTableIndex(index, dsl))))
.then(),
connection -> postgresExecutor.connectionFactory().closeConnection(connection),
(connection, error) -> postgresExecutor.connectionFactory().closeConnection(connection),

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.

Likely log the error as this is a terminal exception, here it is lost

Comment on lines +330 to +339
private <T> Mono<T> handleTransactionTimeout(Connection connection, TimeoutException timeoutException) {
LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, timeoutException);
return cancelRunningQuery(connection)
.then(Mono.from(connection.rollbackTransaction())
.onErrorResume(e -> {
LOGGER.warn("Failed to rollback the timed out Postgres transaction", e);
return Mono.empty();
}))
.then(Mono.error(timeoutException));
}

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.

A coding agent did output to me that r2dbc already does a transaction cleanup.

Do we have a test reproducing the issue ?

private Mono<Void> setNewUidAndModSeq(MailboxMessage mailboxMessage) {
return mailboxDAO.incrementAndGetLastUidAndModSeq(mailboxMessage.getMailboxId())
.defaultIfEmpty(Pair.of(MessageUid.MIN_VALUE, ModSeq.first()))
.switchIfEmpty(Mono.error(new MailboxNotFoundException(mailboxMessage.getMailboxId())))

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.

As far as I am aware of, we cannot distinguish "new mailbox with not yet a UID" from "mailbox that do not exist yet"

Taken in isolation, this code path could look like a minor bug. But without an existing mailbox this get never called.

I propose we actually drop it.

Comment on lines -90 to +91
.defaultIfEmpty(ModSeq.first());
.switchIfEmpty(Mono.error(new MailboxNotFoundException(mailboxId)));

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.

Idem

@chibenwa

Copy link
Copy Markdown
Contributor

Hello @prosgarz35
This PR seems mostly irrelevant for the reasons I indicated.
Objections closing it? Or did I miss something?
Best regards,
Benoit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants