Skip to content

Fix concurrency issues around close() - #177

Merged
simolus3 merged 6 commits into
mainfrom
fix-close
Aug 4, 2026
Merged

Fix concurrency issues around close()#177
simolus3 merged 6 commits into
mainfrom
fix-close

Conversation

@simolus3

@simolus3 simolus3 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

This fixes two issues reported in #172.

Crashes on race between close() and other operations

Emitting a closed SQLite connection as a connection lease crashes the process (as a precondition). This is better than the use-after-free it would have been otherwise, but it shouldn't be possible to reach that state. Unfortunately, it can happen when:

  1. We call close().
  2. Another task runs an operation on the database. Because close() did not complete yet, DatabaseInitializationAction.ensureInitialized() works and the operation can continue. It waits for a connection, though.
  3. The original task closes connections and returns, returning closed connections into the async semaphore.
  4. The second task now obtains the closed connection, crashing.

The fix is what we do on most other SDKs too: Check for closed connections after we've obtained their handle from an async semaphore.

Cancelling close()

When a call to close() is cancelled before it actually closes connections, it would previously leave the database in a state where everything throws even though connections are still open.

This fixes the issue by only marking the database as closed when connections are actually closed. There's still a race condition here where while a database is being closed, queries would throw but if the throw is cancelled the database keeps working afterwards. I think that should be harmless overall, though.

AI use: Original issue report is likely generated by AI. Changes are manual, with minor revisions after a review with Claude Code.

@simolus3
simolus3 marked this pull request as ready for review August 3, 2026 14:01
@simolus3
simolus3 requested a review from stevensJourney August 3, 2026 14:01
Comment thread Sources/PowerSync/Implementation/AsyncConnectionPool.swift Outdated

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

:shipit:

@simolus3
simolus3 merged commit 821a99f into main Aug 4, 2026
8 checks passed
@simolus3
simolus3 deleted the fix-close branch August 4, 2026 09:42
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