Repository navigation
fix: keep the app running until database work ends - #1396
Conversation
bitkit-core's and the USDT wallet's SQLite databases live in the app group container, and iOS kills an app suspended while it holds a lock on such a file (0xdead10cc). Work on the core and migration queues, and the direct database calls outside them, now hold a background task from when they are queued until they end. Verified: none (unit suite runs next on m1a)
Verified: swiftformat --lint on the file; unit suite rerun pending.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[Medium impact] The PR appears safe to merge; no actionable defects were found. SummaryKeeps wallet database work running briefly after the app enters the background.
No actionable issues found. Physical-device suspension behavior was not verified during this review.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Database work requested] --> B[Request background time]
B --> C[Queue or run the work]
C --> D[Work finishes or throws]
D --> E[End background task once]
B --> F[iOS time expires]
F --> E
G[BackgroundTime released] --> E
Reviews (1) · Last reviewed commit: "fix: build the usdt history lookup witho..." · Reviewed by Greptile |
talosmachina
left a comment
There was a problem hiding this comment.
No findings. The PR holds a UIApplication background task around work on the .core and .migration queues, from the moment it is queued until it ends, and around the direct bitkit-core and USDT database calls outside those queues. The goal is that iOS stops suspending the app while it holds an app-group SQLite lock (0xdead10cc). Reviewed eec1ec16c, full tier. The review is static: an iOS target does not build on this reviewer's Linux host, so I did not build or run it.
What I checked, and 6 candidates I ruled out
Read in full: ServiceQueue.swift, BackgroundTimeTests.swift, and the changed functions in UsdtWalletManager.swift, CoreService.swift, AppReset.swift, BlocktankViewModel.swift. Also Utilities/BackgroundTaskScheduling.swift and the target membership in project.pbxproj.
CI at review time: SwiftFormat, validate and Greptile green. Run Tests and Run Integration Tests still pending.
Ruled out
beginBackgroundTask/endBackgroundTaskcalled off the main thread fromServiceQueue: UIKit documents both as safe to call from a non-main thread.- Notification extension linking
UIApplication.shared:ServiceQueue.swiftandCoreService.swiftare compiled intoBitkitNotification. That target definesBITKIT_NOTIFICATION_EXTENSION, which compiles out both UIKit calls, soduringthere just runs its body. - Expiration before the identifier is stored:
end()setsendedwhile the identifier is still.invalid.initthen seesendedAlreadyand ends the returned identifier through the injectedendclosure, exactly once.testExpirationBeforeTheIdentifierIsStoredStillEndsTheTaskcovers this. - A leaked task when the queued closure never runs or the instance is dropped: each queue closure (and the inner
Taskin the async variants) holds the instance strongly. The expiration handler holds it weakly, anddeinitcallsend(), so a released instance never leaves a task open past expiration. - Lock re-entry:
beginruns outsidelock, andend()callsendTaskafter leaving the lock. So an expiration handler that fires synchronously insidebegincannot deadlock the non-recursiveNSLock. - Isolation change in
UsdtWalletManager: the wrapped calls run in the same isolation as before. The closures are non-Sendable and formed on the main actor, andcheckRecentExecutionstays inside itsTask.detached.
Merge confidence: 4/5. No findings, but the unit suite in CI was still pending at review time, and nothing here built or ran the change. Whether it actually prevents 0xdead10cc can only be shown on a device, which is case 1.
Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed
The extension compiles ServiceQueue.swift, and a build that sets SWIFT_ACTIVE_COMPILATION_CONDITIONS on the command line (the E2E build) drops its BITKIT_NOTIFICATION_EXTENSION flag, so UIApplication.shared failed to compile there. The app now installs the background task calls at launch; elsewhere they do nothing. Verified: none yet (E2E-flag build and unit suite run next).
coreyphillips
left a comment
There was a problem hiding this comment.
Two independent reviews.
needs changing before merge
- E2E builds fail: UIApplication.shared is compiled into the notification extension (Bitkit/Services/ServiceQueue.swift:233-245)
worth doing, does not block
- USDT quoting still commits to the app group SQLite without background time (Bitkit/Managers/UsdtWalletManager.swift:284).
UsdtWalletManager.quote(line 284) callswallet.quoteTransferdirectly on the main actor, andquoteMaximum(line 296) does the same withwallet.quoteMaxTransfer. Neither runs on.coreor insideBackgroundTime.during. In the pinned bitkit-core (045c7ff6), both go throughquote_payment, which callsself.store.save_quoteatsrc/modules/usdt/wallet.rs:404.save_quote(src/modules/usdt/store.rs:61-73) opens a transaction, runs a DELETE and an INSERT, and commits. That commit goes tousdt-<address>.sqliteunderEnv.bitkitCoreStorage, which is in thegroup.bitkitcontainer. It is the same commit/fsync pattern as the 3.0.1 (202) sample. The PR description lists the USDT calls it wraps (history, sync, refresh, restore, execution check, payment proof), and quoting is not among them. I confirmed this by reading the Swift call sites and the bitkit-core source. I did not reproduce a termination. The window is short (the user would have to background the app during a quote on the send screen), so this is non-blocking.
Quoting saves the quote to the USDT wallet's SQLite in the app group, so it now holds background time like the other USDT database calls. Verified: swiftformat --lint; build and unit suite run next.
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR diff against its merge base, at eec1ec1.
1 actionable finding — resolve or provide an evidence-backed rebuttal.
The new BackgroundTime helper and the .core/.migration queue wiring hold up on review. Each task ends once, including on expiry and on release. Locking is safe, and the wrapped USDT, Blocktank and activity calls keep the same isolation as before. The one blocking problem is a build break in the E2E workflows. coreyphillips already reported it in an open review thread on ServiceQueue.swift. I reached the same conclusion on my own. I also confirmed that the base built cleanly with the same compile-flag override in the scheduled E2E Staging run at f17214e, while the e2e-tests build-local job at eec1ec1 fails on the new UIApplication.shared calls.
Existing concern, not introduced here: coreyphillips also noted that UsdtWalletManager.quote/quoteMaximum (Bitkit/Managers/UsdtWalletManager.swift:284, :296) call quoteTransfer/quoteMaxTransfer with no background time. I checked this against the pinned bitkit-core 045c7ff6: those calls reach save_quote, which commits a DELETE+INSERT transaction to the app-group USDT SQLite file (src/modules/usdt/store.rs:61-73, called from wallet.rs:404). The base behaves the same way, so this PR leaves the path uncovered rather than causing a regression. Wrapping it would complete the fix.
Validation: I checked by reading the source and the CI logs only. Unit tests (Run Tests) and integration tests pass at this head; I inspected those results but did not run anything myself. The new BackgroundTimeTests cover begin/end/expiry/release and which queues request background time. No test checks that ServiceQueue ends a task after its work completes, and no E2E build validates the extension. No Android comparison applies, because 0xdead10cc is specific to iOS app-group file locks.
Recommended before device testing: fix the E2E build so an E2E app can be produced. Options: make the extension guard independent of SWIFT_ACTIVE_COMPILATION_CONDITIONS, for example by installing the UIApplication begin/end hooks from app-only code, or switch the workflow overrides to $(inherited) ....
Device testing: not performed in this review. The author's case 1 (repeatedly background the app on a physical device without a debugger during activity loading and an incoming on-chain payment, then check Organizer for no new 0xdead10cc) is still the only check that the fix works, and it has not been run.
Suggested additional test cases
- iOS, physical device without a debugger, regtest, USDT wallet enabled: open USDT send, enter a recipient and amount so a quote is requested, then background the app immediately, several times. Expected: the app is not terminated and Organizer shows no 0xdead10cc. This exercises the unwrapped quote path.
- iOS, physical device without a debugger: start a USDT backup restore and background the app mid-restore. Expected: the restore completes on return or fails cleanly, with no termination.
Findings
- [MEDIUM] Keep UIApplication.shared out of the notification extension in E2E builds — inline at
Bitkit/Services/ServiceQueue.swift:237.
Reviewer model: claude-opus-5-5
Reasoning effort: high
Verified: swiftformat --lint
@coreyphillips @piotr-iohk Addressed in 9306d7a: |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: changes since eec1ec16, including affected code paths, at 6b6a3a38. Baseline: previous review. Inherited coverage: database-queue wiring, notification-target and CI compilation flags, CoreService database reads, the previously wrapped USDT database calls, app reset, and Blocktank refresh.
No new actionable code findings.
No new actionable code findings in the follow-up. didFinishLaunching installs the UIApplication begin/end hooks before other launch work, and BackgroundTime stays a no-op until then, so the notification extension can compile ServiceQueue.swift without calling UIApplication. quote and quoteMaximum hold that task for the whole bitkit-core call. At bitkit-core 045c7ff68529d9ffb8135de3b27916447f64b0c4, quote_payment commits save_quote before returning, so the task covers the sqlite lock. Android at e71a3395b8af6fc56523b22a935449d42251812e calls the same SDK methods with no process-lifetime wrapper; the 0xdead10cc suspension kill is iOS-specific.
Device testing: not performed in this review. This review did not execute the unit suite or build the notification extension.
Suggested additional test cases
- iOS, physical iPhone, no debugger, regtest, USDT enabled. Start a fixed-amount USDT quote and a max quote, and background the app while each quote is still running. The app should stay alive, Organizer should show no new 0xdead10cc, and the quote should finish or fail without leaving the wallet database stuck.
Earlier findings reconciled at this revision: 1 verified fixed.
Reviewer model: grok-4.7
Reasoning effort: xhigh
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 3 new commits (8f1ecd0, 9306d7a, 6b6a3a3). Nothing blocking remains.
addressed
- E2E builds fail: UIApplication.shared is compiled into the notification extension (Bitkit/Services/ServiceQueue.swift:233-245). Fixed: ServiceQueue.swift:237-238 now defaults the hooks to no-ops with no
UIApplicationreference, and BitkitApp.swift:75-78 installs the real ones. BitkitApp.swift is not in the BitkitNotification membership set (project.pbxproj:198-227). The e2e-tests build-local job at 6b6a3a3 (run 45209871639) compiled ServiceQueue.swift for target BitkitNotification withSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG E2E_BUILDand finished with** BUILD SUCCEEDED **. I checked this in the job log. - USDT quoting still commits to the app group SQLite without background time (Bitkit/Managers/UsdtWalletManager.swift:284). Fixed: UsdtWalletManager.swift:284-286 and 298-300 now run
quoteTransferandquoteMaxTransferinsideBackgroundTime.during. A grep finds no other app caller of either. In core 045c7ff6, the unwrappedbalance()andorchestra_destinations()never touch the store.
new since the last review
worth doing, does not block
- New queue test does not show the task is held while the work runs (BitkitTests/BackgroundTimeTests.swift:101-111)
coreyphillips
left a comment
There was a problem hiding this comment.
Rechecked after 3 new commits (caa0cb1, 2be17dd, 35a9bea). Nothing blocking remains.
still open
- New queue test does not show the task is held while the work runs (BitkitTests/BackgroundTimeTests.swift:101-111).
testDatabaseQueueWorkHoldsBackgroundTimeUntilItEndswould pass even ifServiceQueueended the task before running the work. It only checks that one task began and one ended after both awaits return. IfbackgroundTime?.end()moved ahead ofblocking(), the test would still pass, so it does not cover the "until it ends" in its name (BitkitTests/BackgroundTimeTests.swift:101-111). It also readstasks.endedwithout waiting for the core queue. In the synchronous overload (Bitkit/Services/ServiceQueue.swift:59-66),continuation.resumeruns before the deferredend(), so the test can resume first. The.ldkhop that follows makes a failure unlikely: it passed in CI at 6b6a3a3, and I did not reproduce a failure. A body that assertstasks.ended.isEmptywhile it runs would cover the ordering.testDatabaseQueueWorkHoldsBackgroundTimeUntilItEndsat BitkitTests/BackgroundTimeTests.swift:101-111 is byte-identical to 6b6a3a3 (git diff 6b6a3a3 HEAD -- BitkitTests Bitkitis empty). The body still never assertstasks.ended.isEmptywhile it runs, and the test still readstasks.endedwithout waiting for the core queue. The reply in the thread agrees with the point and defers it to a later ldk-node PR. That is neither a fix nor a rebuttal, so the point stays open for this PR, even though it does not block the merge.
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR at 35a9bea, re-reviewed after the merge base changed since the saved assessment.
No new actionable code findings.
No actionable code findings. Work on the .core and .migration queues requests background time when it is queued and ends that task after the work returns, including when the work throws. The same helper covers the direct app-group SQLite calls outside those queues: the activity-seen and closed-channel reads, the first initDb, the database wipe, Blocktank getInfo, and the USDT history, sync, refresh, restore, quote, max-quote, payment-proof, and recent-execution calls. In bitkit-core 045c7ff68529d9ffb8135de3b27916447f64b0c4, quote_payment commits save_quote before it returns, so the quote wrapper covers that lock. balance(), receiveAddress(), and verifyPaymentProof do not write that database.
The earlier notification-extension build failure is gone at this head. ServiceQueue.swift keeps begin/end as no-ops until didFinishLaunching installs the UIApplication hooks, so the extension build does not reference UIApplication.shared. Both threads on that compile error are resolved and outdated: coreyphillips and QA review.
The queue-test thread is marked resolved. testDatabaseQueueWorkHoldsBackgroundTimeUntilItEnds still checks only that one task began and one ended after the awaits return. The queue implementation still ends the task in defer after the work returns. That is a test-coverage gap, and it does not change runtime behavior.
Boltz swap updates still write boltz.db from tasks spawned inside bitkit-core after boltzStartSwapUpdates returns, so this wrapper cannot cover those writes. Work that outlasts the system background budget can still be suspended while a lock is held. Device testing was not performed in this review. This environment has no iOS toolchain, so the unit suite and the notification-extension build were not run here. A code search of bitkit-android 69931fb9 found no equivalent suspension-lock handling; 0xdead10cc is specific to iOS app-group locks.
Ready for device testing of the author's cases 1 and 2 on a physical iPhone with no debugger attached.
Suggested additional test cases
- iOS, physical iPhone, no debugger, regtest: start a USDT backup restore and background the app while it is still running. The app should stay alive, Organizer should show no new
0xdead10cc, and the restore should finish or fail without leaving the wallet database stuck.
Reviewer model: grok-4.7
Reasoning effort: xhigh
|
Reran the failed E2E jobs: the 22:30 UTC run stopped at the merge-checkout check because master moved under it (#1371 merged). No code change. |
{"kind":"bitkit-retarget-execution-v1","repository":"synonymdev/bitkit-ios","pr":1396,"generation":"45353016191-1","sourceSha":"c52c5938ca2b846c9b9d2fec8152eb9c799f2020","sourceRef":"c52c5938ca2b846c9b9d2fec8152eb9c799f2020","owner":"github-actions[bot]"}
|
Merged master in as ee14a57. Its E2E could not run: GitHub's test merge for this PR stayed on the previous master, and the workflow only tests a merge with the current one. The merge is clean, with no code change. |
piotr-iohk
left a comment
There was a problem hiding this comment.
QA review
Scope: full PR at ee14a571, re-reviewed after the merge base changed since the saved assessment.
No new actionable code findings.
No actionable code findings. Work on the .core and .migration queues requests background time when it is queued and ends that task after the work returns, including when the work throws. BackgroundTime.during covers the direct app-group SQLite calls outside those queues: the activity-seen and closed-channel reads, the first initDb, the database wipe, Blocktank getInfo, and the USDT history, sync, refresh, restore, quote, max-quote, payment-proof, and recent-execution calls. In bitkit-core 045c7ff68529d9ffb8135de3b27916447f64b0c4, quote_payment commits save_quote before it returns. balance(), receiveAddress(), and verifyPaymentProof do not write that database. The wrappers return the same values and errors as the underlying calls.
The notification-extension compile error from earlier commits is gone at this head. ServiceQueue.swift keeps begin/end as no-ops until didFinishLaunching installs the UIApplication hooks, and BitkitApp.swift is not in the BitkitNotification target. Both threads on that error are resolved and outdated: coreyphillips and QA review. The local E2E build job at this commit succeeded.
The queue-test thread is marked resolved. testDatabaseQueueWorkHoldsBackgroundTimeUntilItEnds still checks only that one task began and one ended after the awaits return. The queue still ends the task in defer after the work returns, so the running app is unaffected. That leaves a coverage gap.
Boltz swap updates still write boltz.db from tasks spawned inside bitkit-core after boltzStartSwapUpdates returns, so this wrapper cannot cover those writes. Work that outlasts the system background budget can still be suspended while a lock is held. Those are the limits the PR already states.
A code search of bitkit-android 69931fb9 found no 0xdead10cc or beginBackgroundTask handling. That suspension kill is specific to iOS app-group locks.
This review did not run the unit suite or a device. Run Tests was still in progress at this commit when the review was written. Run Integration Tests had succeeded. The author's cases 1 and 2 have not been run.
Ready for device testing of the author's cases 1 and 2 on a physical iPhone with no debugger attached.
Suggested additional test cases
- iOS, physical iPhone, no debugger, regtest: start a USDT backup restore and background the app while it is still running. The app should stay alive, Organizer should show no new
0xdead10cc, and the restore should finish or fail without leaving the wallet database stuck.
Reviewer model: grok-4.7
Reasoning effort: xhigh
pwltr
left a comment
There was a problem hiding this comment.
Reviewed ee14a57. I found two unit-test coverage gaps.
Low: Explicit cleanup masks failures in both expiration tests. In BitkitTests/BackgroundTimeTests.swift:48 and BitkitTests/BackgroundTimeTests.swift:58, a no-op expiration callback still yields the expected task ID because end() runs before the assertion. Check the end log immediately after invoking expiration in the first test and immediately after make() in the second. Then call end() and verify the log still contains exactly one entry.
Low: BitkitTests/BackgroundTimeTests.swift:113 checks usesDatabases directly. The assertions would still pass if a ServiceQueue.background overload stopped requesting background time. Extend the existing hook-based coverage to exercise the other queue categories and overloads through ServiceQueue.background.
Review details
Quick review
Model: Claude Opus 5.5
Reasoning effort: high
General review
Model: GPT-6.2 Sol
Reasoning effort: high
Combined review
Model: GPT-6.2 Sol
Reasoning effort: high
Both are test-only and the app behaves the same, so I'm keeping this approved head and taking them into the ldk-node rc.82 bump PR, together with the queue-test ordering fix from the earlier review (tracked in #1399): assert the end log right after expiration and before |
|
Approved at ee14a57 with nothing blocking; set to merge once the running E2E passes. |
piotr-iohk
left a comment
There was a problem hiding this comment.
Device QA passed on ee14a571 with Bitkit 3.1.1 (204) on an iPhone 13 running iOS 27.0.1, with the debugger detached.
- Activity and incoming Bitcoin: Bitkit recorded a 13,961-sat staging regtest payment on resume. For a separate 13,962-sat payment, the app became inactive while the core queue was handling the receipt. After two more background and foreground cycles, the same process showed all three test payments in history.
- Fixed and maximum USDT quotes: Both requests were in flight when iOS backgrounded the app. A local fixture delayed the network failure by eight seconds. Both quotes returned a retryable error, the same process resumed after each 32-second interval, and the wallet could still read its SQLite history.
- USDT snapshot restore: A test-only entry point called the production restore method on a disposable app-group database. The native import finished 3.48 seconds after iOS entered the background. On return, the app read back all 100,000 synthetic transfers.
The iPhone and the local Xcode Organizer cache showed no new Bitkit crash reports, including 0xdead10cc. All 10 focused simulator tests also passed: eight from the PR and two local probes for expiration timing and queue lifetime. The GitHub E2E workflow was still queued at approval time.
Closes #1126
Keeps the app running until wallet database work ends, so iOS no longer kills it with 0xdead10cc when it goes to the background mid-query.
Description
activity.db,blocktank.dband others) and the USDT wallet'susdt-*.sqlitelive in thegroup.bitkitapp group container. iOS kills an app that is suspended while it holds a lock on such a file (0xdead10cc). Both Organizer samples were bitkit-core SQLite work running onServiceQueue's core queue at suspension: an activity read on 3.0.0 (200) and an on-chain activity write on 3.0.1 (202)..coreand.migrationqueues now holds a background task (UIApplication.beginBackgroundTask) from when it is queued until it ends, so iOS lets it finish before suspending the app.BackgroundTime.during: the Blocktank info refresh, the seen-activity and closed-channel reads, the database wipe, bitkit-core's firstinitDb, and the USDT wallet's history, sync, refresh, restore, quotes, execution check and payment proof.BackgroundTimeends its task once, also when the time expires before the task's identifier is stored, and when it is released. The app installs theUIApplicationcalls at launch, so the notification extension, which compiles the same file, runs without background time.Out of Scope
WakeSeenStore'sflockin the app group, held only within one call.Design
N/A — no UI changes.
Preview
N/A
QA Notes
Setup
Physical iPhone with no debugger attached (a debugger keeps the app from being suspended), regtest build.
Journeys
N/A — no user-visible behaviour change.
Manual Tests
Automated Checks
BackgroundTimeTests.swift— the background task ends once, also on expiry before its identifier is stored and on release; without the app's hooks no task is ended;duringends its task also when the body throws; and only database queue work holds background timeEvidence
BackgroundTimeTestspassed on 6b6a3a3.SWIFT_ACTIVE_COMPILATION_CONDITIONS='DEBUG E2E_BUILD': succeeded on 9306d7a.Gaps
Models used
Claude Opus 5.5(reasoning:medium)Claude Opus 5.5(reasoning:medium),Claude Sonnet 5.5(reasoning:high)gemini-4-neon-high(reasoning:Not exposed)The pre-PR review run records only its model id.