Skip to content

fix(sync): do not stop the sync service for idleness while the app is open - #1719

Merged
HashEngineering merged 5 commits into
feat/kotlin-sdk-phase-1from
fix/no-idle-stop-while-app-open
Nov 24, 2026
Merged

HashEngineering merged 5 commits into
feat/kotlin-sdk-phase-1from
fix/no-idle-stop-while-app-open

Conversation

@HashEngineering

@HashEngineering HashEngineering commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

The sync service stops itself after a few quiet minutes (no transactions, blocks, headers or masternode list updates). That rule never looked at whether the app is on screen. It is the same rule as in 11.9.2, where a stop had no visible effect because the balance came from the wallet held in memory.

Since the cutover the service also runs the SDK engine behind the balance. A stop with the app open makes the wallet read as not synced: the header shows "Syncing balance" and the wallet-event tap ends, until something restarts the service. Only a screen resume (home, lock screen, send), the periodic 15-minute alarm or a manual rescan does that; nothing restarts it while the user stays on one screen.

12.0.1-beta field log: the user opened the app at 17:58:45 and unlocked at 17:58:56; the tick at 17:59:00 stopped the service on three quiet samples taken while the app was in the background. It came back at 18:00:10, when the user left and reopened the app.

Requirement

  • The service must not stop for idleness while the app is open.
  • In the background the idle rule is unchanged.

Change

  • shouldStopForIdle takes appOpen and returns false while it is true.
  • The tick handler reads AppForegroundMonitor and returns before the stop (and before the "bind blocked — stopping" log line) when the counters are idle and the app is open.

Commits 2 and 3 added a grace period after leaving the app; commit 4 removes it. The net change is the foreground check only.

Behaviour to note

  • The service and its notification stay up for as long as the app is open. The six-hour limit on this service type is handled as before.
  • "Open" means at least one activity is started. Screen off counts as background; the app's own lock screen counts as open.
  • Not changed: if the user leaves after a quiet spell, the service can stop on the next tick, and a quick return finds the engine restarting ("Syncing balance" for a few seconds; about 4 s in the field log).

Tests

SyncActivityIdleDetectorTest: one new case (idle counters with the app open do not stop the service; the same history in the background does). Existing cases updated for the new parameter.

Ran ./gradlew :wallet:test_testNet3DebugUnitTest --tests "de.schildbach.wallet.service.SyncActivityIdleDetectorTest": passes.

Known limits

  • Not run on a device or emulator.
  • The branch in the tick handler is not unit-tested; only the pure rule is.
  • The full wallet unit suite and ktlintFormat were not run.

Related: #1718 fixes the wrong balance shown during these stops. This PR removes the stop itself while the app is open. The two merge cleanly with each other and with #1714.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • The app’s background service stays running when sync activity is idle while the app is open. When the app moves to the background and sync activity remains idle, the service can stop as before, preserving expected idle behavior. This prevents the service from stopping while the app is in active use and allows it to stop when the app is no longer in the foreground.

HashEngineering and others added 4 commits November 19, 2026 11:44
… open

The idle rule stops the service after a few quiet minutes and never
looked at whether the app is on screen. Since the cutover the service
also runs the SDK engine behind the balance, so such a stop puts the
header on "Syncing balance" and ends the wallet-event tap until a screen
change, a reopen or the periodic alarm restarts the service
(12.0.1-beta field log: stopped four seconds after the user unlocked).

The idle verdict now also requires the app not to be open. While it is
open the quiet samples are dropped, as for an engine start, so leaving
the app does not stop the service on the very next tick. In the
background the rule is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… app

While the app is open only an already-idle history was dropped, so every
other tick left one quiet sample behind. Leaving the app just before the
next tick then stopped the service on that tick. A lone quiet sample is
now dropped too; a history with recent activity is still kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Dropping quiet samples only in some cases while the app is open still
let them count: with older activity in the history they were kept, and
leaving the app as that activity aged out stopped the service on the
next tick. The history is now emptied on every tick taken with the app
open, so the quiet window is made of background samples only. This
replaces the helper added in the previous commit.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The idle stop is skipped while the app is open; nothing else changes.
The history is no longer emptied on those ticks, so the first tick after
the user leaves can stop an idle service as before. This removes the
grace period the two previous commits tried to add, which is not needed
for the fix and cost the keep-alive that recent activity gives.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The idle-stop policy now considers whether the app is open. When the app is open and sync activity is idle, the service tick does not stop the service. Tests cover this behavior and existing replay and active-counter behavior.

Changes: Foreground-Aware Idle Stop

Layer / File(s) Summary
Idle-stop policy and tests
wallet/src/de/schildbach/wallet/service/SyncActivityIdleDetector.kt, wallet/test/de/schildbach/wallet/service/SyncActivityIdleDetectorTest.kt
shouldStopForIdle now requires the app to be closed, replay to be inactive, and sync history to be idle before it returns true. Tests cover app-open and background cases, replay, and active counters.
Service tick integration
wallet/src/de/schildbach/wallet/service/BlockchainServiceImpl.kt, wallet/test/de/schildbach/wallet/service/ServiceSelfStopTest.kt
The service tick returns without stopping when sync activity is idle and the app is open. The call to shouldStopForIdle now includes app-open state. A service test checks that ticks do not stop the service while the app is open and stop it after the app backgrounds.

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Possibly related issues

  • dashpay/dash-wallet#1731: The issue describes a pending-start retry case that can stop the service while idle. This change covers app-open state but does not address the pending-start retry condition.

Suggested reviewers: thepastaclaw

Merge Risk: Minimal · up to 9e3d1

The sync service now stays up while the app is open instead of stopping for idleness, which should remove the stuck "Syncing balance" state. It still stops in the background under the existing idle rule. The tests cover the changed behavior and no merge-blocking risk is apparent.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the sync service no longer stops for idleness while the app is open. The raw summary, objectives, and file changes all match this. The title follows the conventional f…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: the sync service no longer stops for idleness while the app is open. The raw summary, objectives, and file changes all match this. The title follows the conventional fix(scope) form and is specific. It does not cover the background-behavior test or the QA runs, which is expected.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 07b63c6 and 9e3d171.

Files selected for processing: 1

  • wallet/test/de/schildbach/wallet/service/ServiceSelfStopTest.kt

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

@thepastaclaw

thepastaclaw commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

✅ Final review complete — no blockers (commit 9e3d171) · triage: low · Phase 2 only (queue backlog)

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

Final validation — Phase 1 + Phase 2

The minute tick preserves the existing idle history and skips idle shutdown while a wallet activity is visible. No blocking defect was found; the remaining gap is a regression test that drives the real tick across foreground and background transitions. The build and check jobs passed, and the automated review check is pending.

🟡 1 suggestion(s)

Approved: nothing here blocks the merge. The non-blocking findings are optional: fix them forward, in this PR or a follow-up, without waiting for another review round.

Review provenance

Source: reviewer 1: glm-5.3-flash (agent: phase1-reviewer, role: general); reviewer 2: gpt-6.2-sol (agent: phase2-reviewer, role: general); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The diff adds a small, tested foreground guard to the idle-stop decision while preserving the existing background rule.
  • Phase 1 reviewers: glm-5.3-flash — general (completed, effort high); agent phase1-reviewer
  • Phase 1 model: glm-5.3-flash — zai quota: 5h 96% left, weekly 59% left; passed over gemini-3.8-flash-high (antigravity quota lookup failed)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review (PastaClaw). How to work through them:
- Verify each finding against the code; fix only what is real, as narrowly as the finding.
- If a finding is wrong, decline it on its thread in one or two sentences; the bot answers once and stops.
- To defer one, link a tracking issue on its thread (or reply asking the bot to file one).
- Suggestions don't block the merge, but most are worth fixing in this PR; judge each on its merits.
- Keep the PR's scope; don't grow it to satisfy hardening suggestions.
- Carried items were raised in an earlier round: read the thread first, and don't re-fix what you already fixed, declined or deferred there. Disputed and deferred items are already handled and are not listed.

In `wallet/src/de/schildbach/wallet/service/BlockchainServiceImpl.kt`:
- [SUGGESTION] wallet/src/de/schildbach/wallet/service/BlockchainServiceImpl.kt:2620-2633: Test foreground transitions through the idle-stop tick
  The lifecycle test verifies that activity callbacks update AppForegroundMonitor, the detector test passes appOpen directly, and ServiceSelfStopTest calls onIdleVerdict directly. None exercises how the minute tick reads the monitor, records the sample, and decides whether to request a stop. Drive the real tick across activity start and stop: reach the idle threshold while visible and assert that no stop is requested, then stop the last activity and assert that the first quiet background tick requests a stop. Set up the history so that the final tick reaches the threshold only if foreground samples were retained; otherwise the test would miss an early return that skips recording them.

Comment on lines +2620 to 2633
val appOpen = !AppForegroundMonitor.isInBackground
if (isSyncIdle(activityHistory) && appOpen) {
log.info("idle counters, but the app is open — keeping the service alive")
return
}
if (isSyncIdle(activityHistory) && bindBlocked) {
log.info(
"idling detected with the SDK bind blocked ({}) — stopping the service; the " +
"unlock receiver / app foreground restart it",
sdkBindRetryService.blocker.value
)
}
if (shouldStopForIdle(activityHistory, replaying)) {
if (shouldStopForIdle(activityHistory, replaying, appOpen)) {
onIdleVerdict()

@thepastaclaw thepastaclaw Nov 19, 2026 •

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.

✅ Resolved at 9e3d171b; see the replies below.

🟡 Suggestion: Test foreground transitions through the idle-stop tick

The lifecycle test verifies that activity callbacks update AppForegroundMonitor, the detector test passes appOpen directly, and ServiceSelfStopTest calls onIdleVerdict directly. None exercises how the minute tick reads the monitor, records the sample, and decides whether to request a stop. Drive the real tick across activity start and stop: reach the idle threshold while visible and assert that no stop is requested, then stop the last activity and assert that the first quiet background tick requests a stop. Set up the history so that the final tick reaches the threshold only if foreground samples were retained; otherwise the test would miss an early return that skips recording them.

source: glm-5.3-flash (phase1-reviewer: general); gpt-6.2-sol (phase2-reviewer: general)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 9e3d171: ServiceSelfStopTest now drives the real tickReceiver on the SDK path with a quiet engine. With the app open it reaches the idle threshold (two zero samples) and no stop is requested; after the app goes to the background the first quiet tick requests the stop. One background sample alone is below the threshold, so that tick stops only if the samples taken while the app was open were kept. Checked by mutation: clearing the history in the app-open branch, and ignoring app-open, each fail the test. The foreground edge is driven through AppForegroundMonitor directly; the activity callbacks stay covered by the lifecycle test.

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.

Resolved (re-reviewed at 9e3d171b): Your test drives the real receiver through two quiet foreground samples without requesting a stop, then checks that the first quiet background tick requests one. One background sample alone cannot reach the idle threshold, so this verifies that foreground history is retained; the existing lifecycle test covers how activity callbacks update the monitor.

@HashEngineering

Copy link
Copy Markdown
Collaborator Author

QA ✅ PASS — run 50, build 12000301 (12.0.3-qa01)

Passes in both directions, which is the half that matters for review: the PR must add a hold without disabling the idle rule. Commit under test: 07b63c6c.

Getting the device into the state at all

An idle verdict needs both windows satisfied — 9 minutes with no transactions and 2 minutes with no blocks, headers or mnlistdiff. Online that essentially never happens, because testnet produces a block roughly every 2.5 minutes. A first attempt with the app open and online for 12 minutes never went idle and therefore proved nothing; it is recorded as discarded rather than as a result.

The method that works: isolate the device (svc wifi disable / svc data disable) and keep the app in the foreground (svc power stayon true).

App open + idle → service kept

Device isolated at 19:29:28 with the app foregrounded. The per-minute history went all-zero (0/0/0/0, 0/0/0/0, …), i.e. the idle rule was satisfied, and the service was deliberately kept — in the app's own words:

19:38:00 BlockchainServiceImpl: idle counters, but the app is open — keeping the service alive
19:39:00 BlockchainServiceImpl: idle counters, but the app is open — keeping the service alive
19:40:00 BlockchainServiceImpl: idle counters, but the app is open — keeping the service alive

dumpsys activity services showed 1 ServiceRecord throughout.

App backgrounded + idle → service stops

The same device, counters already met, app backgrounded at 19:41:07. By 19:44:27 dumpsys activity services reported 0 ServiceRecords. The service stopped, as it should.

So:

state service
app open + idle counters met kept — and says so in the log
app backgrounded + idle counters met stopped

The idle rule is intact; the PR only adds the "app is open" hold.

Build provenance

Build: qa/integration-12.0.3 @ 883e49e4 = feat/kotlin-sdk-phase-1 @ 83a56f72 — the v12.0.2 tag, the commit that shipped to Google Play — plus ten PRs merged in this order: #1686 #1712 #1719 #1548 #1694 #1697 #1713 #1721 #1717 #1718. All ten merged clean. No branch was rebased or updated, by request, so this is each PR as its author left it. The order was settled by trial-merging rather than by GitHub's mergeable flag.

The SDK pin does not move — int36, the same pin 12.0.2 shipped with, and checked rather than assumed: libdash_sdk_jni.so was unpacked from this APK and from the shipped 12.0.2 and compared byte for byte (60,350,088 B, sha256 950faef8a1a6fe2d…, identical). Everything reported above is therefore an app change, not an engine one.

APK: versionCode 12000301, 328,718,680 B, sha256 f5684c4e4ec8f80a5642d2cb2074e17970d1156f7af6034b3b3409e87c2a8ce7, project release key. _testNet3 only — no mainnet or prod arm was built, by request.

Run: QA run 50, testnet, 2026-11-19. Five Android 16 devices plus one at API 29. Unit tests on the merged tree: 5,007 passing, 0 failures.

@HashEngineering

Copy link
Copy Markdown
Collaborator Author

QA run 52 — carried forward unchanged, plus upgrade and unit-test coverage

This PR is in builds 12000303 and 12000304 at commit 07b63c6cd — byte-identical to the commit run 50 tested, which I verified rather than assumed. Its run 50 results therefore stand as they are, and run 52 did not re-run them.

What run 52 adds for this PR specifically:

  • Three in-place upgrades (12000302 → 12000303 → 12000304) with this PR present: balances, unspent and total outputs, shielded notes, identities and contact requests byte-identical before and after each one.
  • Unit tests on 12000304: 4,779 tests across 330 classes, 0 failures, 0 errors, 1 skipped. 12000303 never had them run; that gap is now closed.
  • No crash, ANR, fatal exception or low-memory kill on any device across the run.

No new finding against this PR.

How this was tested

Builds. 12000303 = feat/kotlin-sdk-phase-1 @ 83a56f723 (the v12.0.2 tag) + Kotlin SDK int42 + dashj-platform 5.1.0-dev.3-20261123.212721-1, with #1686, #1712, #1719, #1548, #1694, #1697, #1713, #1721, #1717, #1718 and #1730 merged at their then-current heads.
12000304 = the same, plus #1736, and with #1725/#1721/#1718/#1714 taken from qa/spv-restart-with-1721-1718 @ 9244f3324 instead of merged separately. APK sha256 96422c3acd8dab7939ab12402d407a5500326f454564aae5b877e6c9e7e2c253.

Devices. Android 16 (API 36) emulators, testnet, release-signed builds. Platform protocol 14.

Unit tests on 12000304: 4,779 tests across 330 classes, 0 failures, 0 errors, 1 skipped.

Both SDK native libraries are byte-identical in size across the two builds, so differences between them come from the PRs and not from the SDK underneath.

Full report: https://github.com/HashEngineering/dash-wallet-qa-report — run 52.

The idle threshold is reached while the app is open and no stop is
requested; the first quiet tick after the last activity stops requests one,
which it can only do if the samples taken while the app was open were kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

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

Re-review — Final validation — Phase 2 only (queue backlog)

New on this head: This revision adds a regression test that drives the production minute-tick receiver on the SDK path. It verifies that no idle stop is requested while the app is open and that the first quiet background tick can request a stop using the retained samples. The check and build checks passed, CodeRabbit completed, and PastaClaw review was pending; no tests were run locally.

🔴 0 blocking | 🟡 0 suggestion(s) | 💬 0 nitpick(s)

Review provenance

Source: reviewer 1: gpt-6.2-sol (agent: phase2-reviewer, role: general); final verifier: gpt-6.2-sol (agent: sol-verifier, role: final-verifier)

  • Triage: low by gpt-6.2-sol (effort low) — The diff adds a localized foreground check to the idle-stop decision and tests that the existing background behavior is preserved.
  • Phase 1 reviewers: not run (skipped for throughput: 13 PRs queued, above the 10 limit)
  • Fresh verifier: gpt-6.2-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.2-sol — general (completed, effort medium); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify the current code and confirm that no unresolved issues remain.

No unresolved findings remain from the prior review on this head.

Comment on lines +2620 to 2633
val appOpen = !AppForegroundMonitor.isInBackground
if (isSyncIdle(activityHistory) && appOpen) {
log.info("idle counters, but the app is open — keeping the service alive")
return
}
if (isSyncIdle(activityHistory) && bindBlocked) {
log.info(
"idling detected with the SDK bind blocked ({}) — stopping the service; the " +
"unlock receiver / app foreground restart it",
sdkBindRetryService.blocker.value
)
}
if (shouldStopForIdle(activityHistory, replaying)) {
if (shouldStopForIdle(activityHistory, replaying, appOpen)) {
onIdleVerdict()

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.

Resolved (re-reviewed at 9e3d171b): Your test drives the real receiver through two quiet foreground samples without requesting a stop, then checks that the first quiet background tick requests one. One background sample alone cannot reach the idle threshold, so this verifies that foreground history is retained; the existing lifecycle test covers how activity callbacks update the monitor.

@HashEngineering
HashEngineering merged commit 092a1b0 into feat/kotlin-sdk-phase-1 Nov 24, 2026
4 checks passed
HashEngineering added a commit that referenced this pull request Nov 24, 2026
…x/send-after-first-sync

Brings in the squash of #1714 (1a30905), with its last fix to the
invoice screen's observers, and the base's #1719 and #1730.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
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