Skip to content

fix(database,android): stop a pending transaction handler from blocking the database forever - #18836

Draft
Lyokone wants to merge 2 commits into
mainfrom
fix/database-android-transaction-hang
Draft

Lyokone wants to merge 2 commits into
mainfrom
fix/database-android-transaction-hang

Conversation

@Lyokone

@Lyokone Lyokone commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

databaseReferenceRunTransaction runs the Dart transaction handler from Transaction.Handler.doTransaction, which the RTDB SDK calls on its run-loop thread. The plugin posted the call to the main thread and then blocked that thread on an unbounded CountDownLatch.await() until Dart replied.

Nothing replies when the engine is destroyed, or its messenger detached, while the handler is pending: once detached, FlutterJNI.dispatchPlatformMessage logs "FlutterJNI was detached from native C++. Could not send." and drops the message, so the reply callback never runs. The run-loop thread then stays blocked, and every later operation on that database instance hangs: reads, writes, listeners and other transactions. FirebaseDatabase instances are shared by the process, so a transaction started from a background engine (for example a messaging background handler) that is torn down mid-transaction also freezes the database for the main engine.

This PR:

  • waits at most 30 seconds for the handler, then fails the transaction: runTransaction throws FirebaseException(code: 'deadline-exceeded'). The Dart handler is synchronous, so a live engine replies at once; the timeout is reached when the isolate is paused in a debugger, the main thread is blocked, or the reply is lost (hot restart, detach). 30 seconds and the code match cloud_firestore's transaction timeout on Android (TransactionStreamHandler, semaphore.tryAcquire(timeout)).
  • releases every pending wait in onDetachedFromEngine, like cloud_firestore releases its semaphore in onCancel, so the database recovers at once rather than after the timeout. That transaction, and any the SDK reruns after the detach (without calling Dart), fail with cancelled.
  • resets the detached state when the plugin is attached again.

A timed-out or released handler is never reported as committed: false, which stays reserved for a handler that returns Transaction.abort(). The failure is recorded on the RTDB Transaction.Handler and reported from onComplete: throwing from doTransaction would not work, because the SDK turns the exception into DatabaseError.USER_CODE_EXCEPTION with a stack trace as message, which surfaces in Dart as unknown.

The wait lives in callTransactionHandler, the RTDB handler in transactionHandler(request, callback), and the plugin takes the main-thread executor and the timeout through an internal constructor, so the JUnit tests can drive them. The no-argument constructor used by the plugin registrant is unchanged.

Review fixes

  • A timeout or detach no longer looks like a normal abort: deadline-exceeded / cancelled, as above.
  • The timeout comment now names what actually reaches it (debugger pauses, a blocked main thread, replies lost during hot restart or detach).
  • isDetached is reset on attach.
  • The "did not reply" warning is only logged when the result is really missing; a reply that lands just after the timeout is used.
  • The tests no longer build FlutterPluginBinding reflectively; they call the internal initPluginInstance / detachFromEngine that onAttachedToEngine / onDetachedFromEngine delegate to.

Follow-ups (not in this PR)

Tests

New JUnit tests in FirebaseDatabasePluginTest (android/src/test), now run by android-unit-tests (:firebase_database:testDebugUnitTest). They drive the plugin's RTDB Transaction.Handler (doTransaction, then onComplete, as the SDK does), with the real Pigeon FirebaseDatabaseFlutterApi on a fake BinaryMessenger that only replies when told to, and check what is reported to Dart:

Test Before (first commit: timeout with a silent abort, isDetached never reset) After
transaction_commitsTheValueFromDart pass pass
transaction_abortedByDartCompletesWithoutAnError pass pass
transaction_failsWithDeadlineExceededWhenDartNeverReplies fails: success reported (committed: false) pass
detachFromEngine_failsAPendingTransaction fails: success reported pass
transaction_failsWithoutCallingDartAfterDetach fails: success reported pass
initPluginInstance_callsDartAgainAfterADetach fails: Dart never called pass

With the original unbounded wait, the timeout and detach cases hang (JUnit 10 s timeout), as measured for the first commit.

Not covered by e2e: destroying an engine while its handler is pending can't be timed reliably from a Dart test.

Related Issues

None found.

Checklist

  • I read the Contributor Guide and followed the process outlined there for submitting PRs.
  • My PR includes unit or integration tests for all changed/updated/fixed behaviors (See Contributor Guide).
  • All existing and new tests are passing.
  • I updated/added relevant documentation (doc comments with ///).
  • The analyzer (melos run analyze) does not report any problems on my PR.
  • I read and followed the Flutter Style Guide.
  • I signed the CLA.
  • I am willing to follow-up on review comments in a timely manner.

Breaking Change

  • No, this is not a breaking change.

…ng the database forever

doTransaction blocked the RTDB run-loop thread on an unbounded
CountDownLatch.await() until Dart replied. When the engine is destroyed,
or its messenger detached, while the handler is pending, nothing replies:
FlutterJNI drops messages once detached. The run-loop thread then stays
blocked and every later operation on that database hangs, including in
other engines of the process.

Wait at most 30 seconds, as cloud_firestore does for its transactions,
then abort the transaction. onDetachedFromEngine releases pending waits
at once, and later calls abort without calling Dart.
@gemini-code-assist

Copy link
Copy Markdown
Contributor
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize the Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counterproductive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

A transaction whose Dart handler did not reply within 30 seconds, or was
released because the plugin detached from its engine, resolved with
`committed: false` and no error, exactly like a handler that returned
`Transaction.abort()`. A debugger pause longer than the timeout silently
aborted valid transactions.

`runTransaction` now throws a `FirebaseException` instead: code
`deadline-exceeded` on timeout (as cloud_firestore does), or `cancelled`
when the engine detached first. The failure is recorded on the handler
and reported from onComplete, because the RTDB SDK turns an exception
thrown from doTransaction into an uncoded "user code" error.

Also:
- reset the detached state when the plugin is attached again, so a
  re-attached plugin calls Dart again instead of aborting every
  transaction;
- use a reply that arrives just after the timeout, and only log when the
  result is really missing;
- correct the comment on the timeout, which is reached by debugger
  pauses, blocked main threads and replies lost during hot restart or
  detach.

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.

1 participant