Skip to content

Protect Transaction#close in Database#runAsync from cancellation - #13754

Open
jkt-signal wants to merge 4 commits into
apple:mainfrom
jkt-signal:protect-transaction-close-future
Open

jkt-signal wants to merge 4 commits into
apple:mainfrom
jkt-signal:protect-transaction-close-future

Conversation

@jkt-signal

Copy link
Copy Markdown
Contributor

FDBDatabase#runAsync returns a future on a complicated chain of retry and cleanup logic to create a transaction, run the user-supplied closure, commit the transaction, and close it. The final future actually returned is the result of CompletableFuture#whenComplete(/* close the open transaction */).

Unfortunately, this means that if the returned future is cancelled, the whenComplete callback is also not called, resulting in the last-opened transaction not being closed, and in turn Transaction not closed warnings appearing on stderr.

This change fixes that problem by swapping the order of two CompletableFuture method calls, moving the whenComplete above a CompletableFuture#thenApply call that fixes up the return value to what runAsync's future is expected to supply. Cancelling that future is not a problem, since the fixed-up return value would be clobbered by the resulting CancellationException anyway, and CompletableFuture cancellation does not propagate to parent futures' tasks.

We also add a unit test verifying the behavior of db.runAsync(something).cancel(true) with respect to closing opened transactions. This test reliably fails without the change to FDBDatabase and passes with it.

@jkt-signal
jkt-signal force-pushed the protect-transaction-close-future branch 2 times, most recently from 8910301 to f163296 Compare July 20, 2026 19:25
@gxglass gxglass closed this Jul 31, 2026
@gxglass gxglass reopened this Jul 31, 2026
@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@foundationdb-ci

This comment has been minimized.

@jkt-signal

jkt-signal commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor Author

I believe the two failing tests are unrelated to this change (one is in the C API bindings which I have not touched, and one is a build failure with no additional information that I suspect to be a timeout).

How can I request the required review from a second approver?

@saintstack saintstack closed this Sep 2, 2026
@saintstack saintstack reopened this Sep 2, 2026

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

From local LLM, there are other locations that could do with the fix. What you think?

Review: PR #13754 — Protect Transaction#close in Database#runAsync from cancellation

Verdict: not yet — the 2-line production fix is correct and I'd take it as-is, but the new test can call Database_dispose(0), and the same bug exists at three other sites.

The diagnosis is correct, and precisely so

The mechanism is subtler than "cancellation skips callbacks," and the PR body gets it right. In the JDK, uniWhenComplete guards its action with if (result == null) — the action runs only if the dependent stage isn't already complete. So:

  • Before: X.thenApply(fixup).whenComplete(close) — the returned future is the whenComplete stage. cancel(true) completes it, so when X later finishes, the action is skipped. Transaction leaked.
  • After: X.whenComplete(close).thenApply(fixup) — the returned future is the thenApply stage. Cancelling it leaves the whenComplete stage untouched, so close() still runs when X completes.

The swap is also type- and exception-preserving: the whenComplete lambda ignores both arguments, whenComplete passes the upstream result through unchanged, and fixup (o -> returnValue.get()) ignores its input, so the intermediate type is irrelevant. Exceptional completion propagates identically in both orders, including when close() itself throws.

readAsync delegates to runAsync (FDBDatabase.java:110-113), so it's covered by the same change — worth noting explicitly, since a reviewer would otherwise wonder.

Worth stating: the fix bounds the leak, it doesn't eliminate the wait

CompletableFuture cancellation doesn't propagate upstream, so after runFuture.cancel(true) the underlying retry/commit chain keeps running and the transaction closes only when it completes. That's strictly better than never closing, but a caller cancelling because they want to abandon a slow transaction still won't get the handle released promptly. The PR title ("protect from cancellation") is accurate; the description could say that the close is deferred rather than immediate, so nobody reads this as making cancellation eager.

Incomplete: three sibling sites have the identical bug

// RangeQuery.java:89-90
FutureResults range = tr.getRange_internal(...);
return range.thenApply(result -> result.get().values)
        .whenComplete((result, e) -> range.close());

// MappedRangeQuery.java:92
return range.thenApply(result -> result.get().values).whenComplete((result, e) -> range.close());

// FDBTransaction.java:741  (onError)
return f.thenApply(v -> tr).whenComplete((v, t) -> { if (t != null) { tr.close(); } });

All three are thenApply(...).whenComplete(close) with the returned future being the whenComplete stage — same skip, same leak, same one-line fix.

The first two matter more than the one being fixed: they leak native FutureResults/FutureMappedResults handles, and abandoning a range query is far more common than cancelling runAsync. The onError one leaks a transaction that transfer() just handed over, so nobody else owns it.

I'd want these in this PR — three reordered lines, identical reasoning, and you already have the model loaded. If you'd rather keep the change surgical, please at least file them, because the next person to hit a FutureResults leak will have no reason to connect it to this fix.

Test defect: Database_dispose(0)

The anonymous FDBDatabase subclass overrides createTransaction and setOption but not closeInternal. So:

FDBDatabase.finalize() → checkUnclosed("Database") → close() → closeInternal(0) → Database_dispose(0) — a JNI call with a null handle, at GC time.

FakeFDBTransaction overrides closeInternal at line 150 for exactly this reason, so the precedent is already in the codebase and was missed here. Two consequences:

  1. A latent, nondeterministic JVM crash whenever GC happens to finalize the fake database. It may never fire in a short run, which is the worst failure mode.
  2. checkUnclosed prints Database not closed to stderr — ironic in a PR whose stated goal is eliminating Transaction not closed warnings.

Fix: override closeInternal to a no-op in the anonymous subclass, and close the database in the test (try-with-resources, since Database is AutoCloseable).

On the dismissed CI failure

You wrote that the foundationdb-pr-clang failure (ctest … exit status 8) is unrelated because "one is in the C API bindings which I have not touched." That's plausible, and the macOS failure is clearly the ci.lock timeout. But this PR introduces a native wrapper constructed with a null pointer that gets disposed at finalization — which is exactly the shape of thing that produces a confusing native-side ctest failure. I can't see the log from here, so I'm not claiming they're connected; I'm saying "unrelated" should be established by naming the failing test rather than inferred. Fixing the closeInternal override first and re-running is the cheap way to settle it.

Otherwise the test is good

Using an inline executor (command.run()) makes it fully deterministic — someLongOperation.complete(null) drives the whole chain synchronously, so there's no sleep and no flake. And it genuinely fails without the production change, which is the property that matters. Registering it in tests.cmake is correct, and the "does not require a running server" javadoc is a useful orientation note.

Minor: EXECUTOR should be final; assertTrue would read better with a message.

Process note

To answer your question in-thread: FDB requires two approvals, and the usual route is to ping a maintainer directly on the PR rather than through any UI affordance.

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-clang-ide on Linux RHEL 9

  • Commit ID: f163296
  • Duration 0:30:52
  • Result: ✅ SUCCEEDED
  • Error: N/A
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-clang-arm on Linux RHEL 9

  • Commit ID: f163296
  • Duration 0:46:02
  • Result: ✅ SUCCEEDED
  • Error: N/A
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-clang on Linux RHEL 9

  • Commit ID: f163296
  • Duration 0:52:38
  • Result: ❌ FAILED
  • Error: Error while executing command: if python3 -m joshua.joshua list --stopped | grep ${ENSEMBLE_ID} | grep -q 'pass=10[0-9][0-9][0-9]'; then echo PASS; else echo FAIL && exit 1; fi. Reason: exit status 1
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-macos-m1 on macOS 14.x

  • Commit ID: f163296
  • Duration 0:57:51
  • Result: ✅ SUCCEEDED
  • Error: N/A
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr on Linux RHEL 9

  • Commit ID: f163296
  • Duration 0:58:29
  • Result: ❌ FAILED
  • Error: Error while executing command: if python3 -m joshua.joshua list --stopped | grep ${ENSEMBLE_ID} | grep -q 'pass=10[0-9][0-9][0-9]'; then echo PASS; else echo FAIL && exit 1; fi. Reason: exit status 1
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-cluster-tests on Linux RHEL 9

  • Commit ID: f163296
  • Duration 1:31:38
  • Result: ✅ SUCCEEDED
  • Error: N/A
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)
  • Cluster Test Logs zip file of the test logs (available for 30 days)

@foundationdb-ci

Copy link
Copy Markdown
Contributor

Result of foundationdb-pr-macos on macOS 14.x

  • Commit ID: f163296
  • Duration 1:35:36
  • Result: ✅ SUCCEEDED
  • Error: N/A
  • Build Log terminal output (available for 30 days)
  • Build Workspace zip file of the working directory (available for 30 days)

@jkt-signal
jkt-signal force-pushed the protect-transaction-close-future branch from f163296 to 60d7e27 Compare September 29, 2026 18:54
@jkt-signal

Copy link
Copy Markdown
Contributor Author

Apologies for abandoning this; I missed the LLM review comments among the CI notes.

I've made the equivalent change in the extra callsites listed and fixed the test to not call Database_dispose.

@jkt-signal

Copy link
Copy Markdown
Contributor Author

@gxglass @saintstack this seems to have fallen by the wayside; any chance I can get some eyes on it?

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.

4 participants