Skip to content

fix: run pubky work on its own service queue - #1798

Merged
jvsena42 merged 2 commits into
masterfrom
fix/pubky-own-queue
Nov 6, 2026
Merged

jvsena42 merged 2 commits into
masterfrom
fix/pubky-own-queue

Conversation

@jvsena42

@jvsena42 jvsena42 commented Nov 6, 2026 •

Copy link
Copy Markdown
Member

Fixes #1695

This PR moves Pubky and Paykit work off the shared core service queue so that a slow Paykit start can no longer freeze app launch.

Description

  • Adds a dedicated Pubky service queue and runs every Pubky service call on it. Before this, Paykit initialization (a blocking native constructor) could hold the core queue while the main thread waited on that same queue to create the core service during launch. That is the startup ANR reported from Play Console.
  • Paykit already orders its own work with its setup and operation locks, so it does not depend on the core queue for ordering. The core queue never held its thread across a suspended Paykit call anyway.
  • The two bitkit-core calls inside the Pubky service (auth URL parsing and Pubky Ring approval) move with it on purpose. One is a stateless parse and the other a network call of up to 30 s, so neither needs to wait behind or block core database work.

Out of Scope

  • CoreService init: construction still waits on the core queue from the main thread for its own database setup. Making it asynchronous would change when other callers see the database as ready. After this change, nothing except user-started Trezor operations runs on the core queue before CoreService exists.
  • iOS: no port needed. Paykit initialization there does not run on the core queue, and core service init calls initDb directly instead of waiting on a queue.

Design

N/A — no UI changes.

Preview

N/A

QA Notes

Setup

  • Dev (regtest) build of this branch on an emulator with an existing wallet.
  • Case 1 uses two temporary debug patches. Apply one with git apply on top of the branch, build with just build, and never commit it. Both start Pubky initialization from App.onCreate and block its thread for 15 s, the way the stuck native Paykit constructor did.
    • repro-fixed.diff keeps this PR's fix: Pubky init blocks pubky-queue.
    • repro-unfixed.diff also moves PubkyService.initialize() back to ServiceQueue.CORE, as on master: Pubky init blocks core-queue.
  • Reset between variants with git checkout -- app/src/main/java.
repro-fixed.diff
diff --git a/app/src/main/java/to/bitkit/App.kt b/app/src/main/java/to/bitkit/App.kt
index 0df1da560..4cca0a28e 100644
--- a/app/src/main/java/to/bitkit/App.kt
+++ b/app/src/main/java/to/bitkit/App.kt
@@ -39,6 +39,9 @@ internal open class App : Application(), Configuration.Provider {
     @Inject
     lateinit var pubkyAuthHandlerRegistrar: PubkyAuthHandlerRegistrar
 
+    @Inject
+    lateinit var reproPubkyService: to.bitkit.services.PubkyService
+
     @Inject
     lateinit var subscriptionClockOffsetSync: SubscriptionClockOffsetSync
 
@@ -65,6 +68,8 @@ internal open class App : Application(), Configuration.Provider {
         pubkyAuthHandlerRegistrar.start()
         subscriptionClockOffsetSync.start()
         observeAppForeground()
+        Thread { kotlinx.coroutines.runBlocking { reproPubkyService.initialize() } }.start()
+        Thread.sleep(500)
     }
 
     private fun observeAppForeground() {
diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt
index 413fb3c90..7b6c33c98 100644
--- a/app/src/main/java/to/bitkit/services/PubkyService.kt
+++ b/app/src/main/java/to/bitkit/services/PubkyService.kt
@@ -14,6 +14,7 @@ import kotlinx.coroutines.withTimeoutOrNull
 import to.bitkit.async.ServiceQueue
 import to.bitkit.ext.runSuspendCatching
 import to.bitkit.utils.AppError
+import to.bitkit.utils.Logger
 import javax.inject.Inject
 import javax.inject.Singleton
 import kotlin.time.Duration
@@ -30,6 +31,8 @@ class PubkyService @Inject constructor(
     }
 
     suspend fun initialize() = ServiceQueue.PUBKY.background {
+        Logger.warn("REPRO blocking '${Thread.currentThread().name}' for 15s", context = "REPRO")
+        Thread.sleep(15_000)
         paykitSdkService.initialize()
     }
repro-unfixed.diff
diff --git a/app/src/main/java/to/bitkit/App.kt b/app/src/main/java/to/bitkit/App.kt
index 0df1da560..4cca0a28e 100644
--- a/app/src/main/java/to/bitkit/App.kt
+++ b/app/src/main/java/to/bitkit/App.kt
@@ -39,6 +39,9 @@ internal open class App : Application(), Configuration.Provider {
     @Inject
     lateinit var pubkyAuthHandlerRegistrar: PubkyAuthHandlerRegistrar
 
+    @Inject
+    lateinit var reproPubkyService: to.bitkit.services.PubkyService
+
     @Inject
     lateinit var subscriptionClockOffsetSync: SubscriptionClockOffsetSync
 
@@ -65,6 +68,8 @@ internal open class App : Application(), Configuration.Provider {
         pubkyAuthHandlerRegistrar.start()
         subscriptionClockOffsetSync.start()
         observeAppForeground()
+        Thread { kotlinx.coroutines.runBlocking { reproPubkyService.initialize() } }.start()
+        Thread.sleep(500)
     }
 
     private fun observeAppForeground() {
diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt
index 413fb3c90..bc144e6de 100644
--- a/app/src/main/java/to/bitkit/services/PubkyService.kt
+++ b/app/src/main/java/to/bitkit/services/PubkyService.kt
@@ -14,6 +14,7 @@ import kotlinx.coroutines.withTimeoutOrNull
 import to.bitkit.async.ServiceQueue
 import to.bitkit.ext.runSuspendCatching
 import to.bitkit.utils.AppError
+import to.bitkit.utils.Logger
 import javax.inject.Inject
 import javax.inject.Singleton
 import kotlin.time.Duration
@@ -29,7 +30,9 @@ class PubkyService @Inject constructor(
         internal val AUTHORIZATION_TIMEOUT = 30.seconds
     }
 
-    suspend fun initialize() = ServiceQueue.PUBKY.background {
+    suspend fun initialize() = ServiceQueue.CORE.background {
+        Logger.warn("REPRO blocking '${Thread.currentThread().name}' for 15s", context = "REPRO")
+        Thread.sleep(15_000)
         paykitSdkService.initialize()
     }

Journeys

N/A — no user-visible behaviour change.

Manual Tests

  • 1. regression: With the repro patch, force-stop the app → cold launch → press a key within 5 s → Home loads with no ANR dialog, and the log shows REPRO blocking 'pubky-queue'. The unfixed variant shows the Application Not Responding dialog and REPRO blocking 'core-queue'. — injecting a blocking native constructor (code patch) not in Capabilities

Automated Checks

  • added PubkyServiceTest.kt — a Paykit initialization that blocks its thread no longer prevents the core queue from running work; fails without the fix
  • updated PubkyServiceTest.kt — relay approval tests run on the Pubky queue so their thread-local native mocks apply
  • updated PaykitSdkServiceTest.kt — shop import cancellation test drains the Pubky queue instead of the core queue

Evidence

  • 2fd479699, locally: just compile, just lint and just test passed. The new PubkyServiceTest.kt case failed with the PubkyService change reverted and passed with it.
  • Case 1 at 2fd479699 plus the repro patch, dev debug arm64 build on the Gate_Throwaway emulator (Android, existing regtest wallet):
    • Unfixed variant: the log shows REPRO blocking 'core-queue' for 15s, then ANR in to.bitkit.dev (to.bitkit.dev/to.bitkit.ui.MainActivity) with reason Input dispatching timed out, and the focused window is Application Not Responding: to.bitkit.dev.
    • Fixed variant: the log shows REPRO blocking 'pubky-queue' for 15s, no ANR is logged, MainActivity keeps focus, and Home shows TotalBalance, Send and Receive.

Gaps

  • Not reproduced on the reported device (Infinix SMART 10 HD, armeabi-v7a), and no deterministic production repro exists. Case 1 simulates the slow constructor with a patch.

Models used

  • Planning/scoping: claude-opus-5-5 (reasoning: Not exposed)
  • Implementation: claude-opus-5-5 (reasoning: Not exposed)
  • Review: claude-opus-5-5 (reasoning: Not exposed)
  • Review rounds: 1

Metadata note: the sessions report the model ID but expose no reasoning-effort setting in run metadata. The reviewer subagent self-reported low effort, but no run record confirms it.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@jvsena42 jvsena42 self-assigned this Nov 6, 2026
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from 2fd4796 (run).

Download bitkit-dev-debug universal APK (expires in 30 days).

@jvsena42
jvsena42 marked this pull request as ready for review November 6, 2026 14:26
@greptile-apps

greptile-apps Bot commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

Moves queued Pubky work from ServiceQueue.CORE to the new ServiceQueue.PUBKY, keeping slow Paykit startup off the core thread.

  • Pubky startup and service calls use their own queue.

jvsena42 explicitly leaves synchronous CoreService construction out of scope because changing it would change when callers see the database as ready.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A["PubkyService calls"] --> B["PUBKY queue"]
  B --> C["Paykit work and Pubky auth"]
  D["CoreService construction"] --> E["CORE queue"]
  E --> F["Core database setup"]
Loading

Reviews (1) · Last reviewed commit: "chore: rename changelog fragment" · Reviewed by Greptile

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

No findings. Moves every PubkyService call from ServiceQueue.CORE to a new single-thread ServiceQueue.PUBKY, so a stuck Paykit platform init can no longer hold the thread CoreService.init blocks the main thread on. Reviewed 2fd4796, full tier, static: per this repo's convention for unattended reviews the branch was not built here, so the build and tests are CI's.

What I checked, and 5 candidates I ruled out

Read in full: ServiceQueue.kt, PubkyService.kt, the setup and lock path of PaykitSdkService.kt (initialize, setupMutex, operationLock, completeSdkCall, handle), CoreService.init and the Paykit backfill on CORE, PubkyRepo.ensureServiceInitialized, the changed tests.

Ruled out

  • Lost ordering with core DB work: no PubkyService method touches the bitkit-core database. The two bitkit-core calls that moved are parsePubkyAuthUrl (stateless) and approvePubkyAuth, which bitkit-core runs on its own tokio runtime (ensure_runtime().spawn in src/lib.rs), so neither relied on CORE's thread. Paykit ordering comes from setupMutex and operationLock, not the queue.
  • CORE/PUBKY deadlock: the only ServiceQueue.*.blocking caller is CoreService.init, and the CORE work that reads Paykit state (backfillPaykitContacts through PrivatePaykitContactResolver) goes through ioDispatcher rather than PubkyService, so no thread waits on the other queue while holding its own.
  • cancellablePublicRead / importShopContacts cancellation: both swapped to PUBKY.queueContext.minusKey(Job) together, same semantics as before on the new thread.
  • Thread-local static mocks in other tests: PubkyAuthApprovalViewModelTest and PrivatePaykitRepoTest mock bitkit-core on their own thread and mock pubkyRepo/paykitSdkService rather than calling PubkyService; the two relay tests that do go through PubkyService were moved to PUBKY.
  • Enum ordinal shift from inserting PUBKY: nothing reads ServiceQueue ordinals or entries.

Test: paykit initialization does not hold the core queue blocks the mocked initialize() on a latch and asserts ServiceQueue.CORE.blocking still runs; with PubkyService on CORE that latch would hold the CORE thread and the 5 s await fails, so it covers the regression.

CI at review time: lint, detekt and build green; build-and-test, compose-ui / ui-tests and the e2e shards still running.

Merge confidence: 4/5, no findings, but the unit and e2e runs were still pending when this was posted and the branch was not built here.

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed (the review runner does not report a setting)

@ovi-reviewer ovi-reviewer Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: ✅ Approve

Findings: None.

QA for 2fd4796:

Check: Dev build ✅ The app builds at the reviewed head.

assembleDevDebug passed on the unmodified head.

Pubky queue isolation and cancellation ✅ The focused unit tests pass.

PubkyServiceTest.kt and PaykitSdkServiceTest.kt passed, including the blocked-initialization regression, public-read cancellation, relay timeout and cancellation, and deferred shop import cancellation.

Check: Cold launch regression report ✅ The author reports both controlled startup variants at this head.

Manual case 1 reuses the author's QA Evidence: the fixed variant reaches Home without an ANR while Pubky blocks for 15 seconds; the unfixed control triggers an input-dispatch ANR. I did not repeat this unchanged-head device case. The affected 32-bit physical device and the cause of the native constructor delay remain unverified.

Full review: ef8cffa..2fd4796, all five changed files. Other Pubky workflows were reviewed statically. The earlier static review also reports no findings.

iOS: no twin PR is needed; Paykit startup runs outside the core queue and core database initialization does not wait on that queue.


Reviewed by gpt-6.1-sol-high

@ovitrif ovitrif left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utAck

@jvsena42
jvsena42 merged commit ebe9bc0 into master Nov 6, 2026
40 checks passed
@jvsena42
jvsena42 deleted the fix/pubky-own-queue branch November 6, 2026 15:55
@piotr-iohk piotr-iohk mentioned this pull request Nov 12, 2026
3 tasks
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.

[Bug]: Startup ANR while CoreService blocks behind Paykit initialization

3 participants