Skip to content

fix: decouple wallet restore from profile refresh - #1686

Open
ben-kaufman wants to merge 170 commits into
masterfrom
fix/restore-identity-background
Open

ben-kaufman wants to merge 170 commits into
masterfrom
fix/restore-identity-background

Conversation

@ben-kaufman

@ben-kaufman ben-kaufman commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

November 14 · compose current master

Published c4d9939d on master e63b9d89, preserving the restore/background identity changes and incorporating the upstream swap-route cleanup dependency. The first hosted checkout 0c9cc62d has tree 1cc40637, matching the published result.

Original CI, Lint and E2E passed: 6,076 unit, 257 Compose and 39 E2E passes. Two opt-in unit cases, Settings08 and six migration jobs were skipped. All seven E2E shards passed their first attempt on suite 24c1c4f5; no workflow rerun. All six static reports have zero findings. All 36 live-base commits report valid signatures on GitHub.

Complete original diagnostics retain cursor/storage warnings, five metadata refusals followed by ordered same-process WALLET then METADATA success, two restore-wait timeouts, one legacy-list timeout and three on-chain sync deadlines followed by successful retries. RGS, fee/channel-close and native bootstrap diagnostics remain qualified. The external test harness also reports npm vulnerabilities. No new introduced finding was established; this does not establish complete-WALLET recovery, bounded native Reset, private authenticated cleanup or a runtime-clean app. Existing findings, prior failures and authored QA below remain unchanged.

November 12 · restore Spark balance updates after a finished exit

Published d28a1578 on 52bc2736 (validated tree b5b0fd34). Retained Done/Failed exit records now use the existing isExiting predicate in both derivation and the stopped/timeout fallback. Spark and active-transfer exit guards remain. The extended existing regression first reproduced the stale 119,865-sat total instead of 70,000, then passed with the correction.

Final local formatting, compile, full tests, lint and APK checks passed: 5,981 unit passes plus two explicit opt-in regtest skips; 133 focused passes. Complete Detekt/Android Lint reports have zero findings. All 35 live-base commits verify locally and on GitHub.

Original hosted CI, Lint and E2E passed on matching synthetic bd39ccf6: 5,981 unit passes plus two skips, 257 Compose passes and 39 first-attempt E2E passes. Settings08 and six migration jobs were skipped; no job/workflow rerun. Executed external suite: ce9c0e2b.

Complete diagnostics retain a real target-package Zygote abort during explicit suite reinstall (nine shard cases subsequently passed), 29 stale-element helper notices, fee disagreement followed by force-close/commitment broadcast, restore-wait guards, metadata refusals/later acknowledgements and widget cancellation. The exact abort initiator and actual-base runtime are not established. Hosted unit XML/Gradle Problems HTML were not uploaded; local reports remain separate evidence. These controls do not establish a funded finished-exit device journey, complete WALLET recovery, authenticated endpoint cleanup or native Reset Wallet. Earlier failures and authored QA remain below.

November 12 · refresh Spark balances after node startup times out

Published b2c3ea6e0 against 12d78484. The existing Spark fallback now handles NodeRunTimeoutError and preserves the current usable channel limit when the node becomes Running as the read finishes. The one-minute wait and cancellation handling are unchanged.

Local final formatting, compilation, full tests, lint and APK checks passed on tree b526c8b2: 5,579 unit tests, 111 focused WalletRepoTest cases and zero findings in six static reports. The new control first reproduced the stale total (119865 instead of 70000), then the recovered-channel limit (39900 instead of 55000). All 32 commits in the live-base range verify locally and on GitHub.

The original CI, Lint and E2E completed successfully on synthetic 8fbb0516, whose tree equals the local result. Hosted results: 5,579 units, 256 Compose tests, six clean static reports and 39 unique E2E cases eventually passed. Send's first @send_2 attempt stayed on Home after an acknowledged Send tap; the recipient/permission screen did not appear within 30 seconds. Its configured second attempt passed and skipped two already-passed cases. The cause of the first failure remains unproven. Settings08 remains disabled; all six migration jobs were skipped.

Runtime qualifications remain: Transfer passed while a 139/182-sat peer fee disagreement caused a force-close and commitment broadcast; three restore waits later completed in the same process; four METADATA acknowledgements and two widget-fetch cancellations were inspected. These results establish neither confirmed returned funds nor new private profile, complete-WALLET, native-reset or withdrawal-journal retirement acceptance. Earlier failures and exact-head results below remain historical. Later GitHub mergeability metadata returned dirty/null despite unchanged head/base; the completed checks retain their original recorded checkout identity.

November 12 · keep cached wallet data available during startup

At 89f3bc6b, cache hydration can publish cached balances and receiving details while a native balance read waits for node startup. Balance derivations remain serialized, final publication remains atomic, and the original wallet admission and owner checks remain in place. The local regression failed on ff9275d6 with the cached 50,000-sat balance still at zero; it passes with this fix and checks that a subsequent refresh remains current.

All five final local commands passed against master 6bb0ff55: formatting, compilation, 5,442 unit tests, lint and APK assembly. There were no test failures, skips or retries and no findings in six native static reports. The full WalletRepo class passed 110 cases. Two independent source reviews and the exact child-composition qualification found no outstanding defect.

The first original hosted CI run, Lint run and E2E run passed. Synthetic commit 66206d4e has the exact validated tree. Hosted results: 5,442 unit tests, 256 Compose tests, six static reports with zero findings and 39 enabled E2E cases passing on their first internal attempt. One Settings case remained disabled; all six migration jobs were skipped by their release-ref guards. The executed E2E suite was 0ca01e0a, whose restore helper changed since the preceding run; it is distinct from the selected reusable-workflow revision.

Complete available diagnostics retain the transfer peer-fee disagreement, force-close and commitment broadcast: the passing UI does not prove a cooperative close or confirmed returned funds. A stock restore wait hit its 30-second guard before later same-process restore success. Six guarded METADATA refusals received later same-process acknowledgements. Optional restore categories and no-session remote-cleanup warnings remain qualified. Unit XML and Gradle Problems HTML were not uploaded. Compose fixture results, stock E2E results and the controlled local startup regression do not establish authenticated/private recovery, native Reset Wallet or complete SDK WALLET acceptance.

All 30 commits in the live-base range verified locally and on GitHub. The earlier installed cold-start reproduction remains attributed to its original head; manual case 6 records the current-head fixture still needed. Earlier source, formatter and runtime failures remain below with their original inputs.

November 12 · keep Spark balances and payment results current

At ff9275d6, Spark balance changes update Home/Spending while LDK is stopped, preserving known Lightning and on-chain contributions. Cache hydration and retired wallet writes cannot overwrite newer balances. Pending, Success and Error payment screens retain their Close/Details actions when the remaining Spark balance falls below the paid invoice; the existing admission checks remain in place for payment entry.

Final formatting, compilation, full tests, lint and APK assembly passed on tree 413b4374 against master 6bb0ff55: 5,441 unit tests, zero failures/skips/retries and zero findings in six native static reports. The ten added balance, cache, cancellation and navigation controls passed alongside all 36 previous controls. Independent source reviews cover the affected production and child composition paths. All 29 live-base commits verify locally and on GitHub.

The first original CI, Lint and E2E runs passed on synthetic d6183ae4, with the same validated tree: 5,441 units, 256 Compose cases and 39 E2E passes. All seven E2E shards passed on internal attempt one, with no failed test execution; settings_08 remains intentionally disabled and six migration jobs were skipped. Complete available diagnostics and artifact provenance were inspected. The 48 helper notices are separate from testcase retries.

Runtime qualifications remain: Transfer recorded the peer's 139 versus 182 sat closing-fee disagreement, force-close and commitment broadcast; its passing UI assertions do not establish cooperative closure or confirmed returned funds. An initial native on-chain sync timeout later reached same-process sync completion and a successful explicit app retry. The 30-second restore wait guard was followed by a successful full restore, with WALLET/BLOCKTANK absent. Six guarded METADATA refusals had later same-process acknowledgements. A Zygote abort during test-package uninstall occurred before app initialization; the replacement process passed, without an established introduced app-code cause. Compiler/provider/JVM warnings and transient emulator connection notices remain recorded.

Current inputs are Core 0.8.0-rc14, Paykit 0.1.1-rc8, LDK 0.7.0-rc.80, VSS 0.5.26-rc2 and Spark 0.28.0; older pin lists below describe their original evidence. These checks do not include the unreleased owned SDK changes. Hosted stock fixtures do not reproduce the exact controlled stopped-node Spark journey, authenticated cleanup, terminal complete-WALLET recovery or bounded native Reset. Manual case 5 below records the remaining controlled app check. The earlier red balance regression and formatter/test-fixture failures remain preserved; passing controls do not erase them. Earlier evidence and authored QA notes follow.

November 12 · retain profile ownership with the current restore guards

At 2dc86ae0, the composition with master 6bb0ff55 retains the original sign-in throughout deferred profile refresh, migration and avatar writes. Wipe or replacement invalidates that work before it mutates storage or publishes profile state. The upstream invoice-history holds remain inside admitted recovery, after uploads drain and before category reads. Ordinary remote profile reads remain outside the identity-write lock.

Final formatting, compilation, full lint and APK assembly passed on tree 32497f24, with 5,431 unit tests, zero failures/skips/retries and zero introduced findings. All 36 affected controls passed, including the four identity controls and 32 added upstream cases. Two independent affected source reviews cover the composition. All 28 commits against the live base verify locally and on GitHub.

The first original CI, Lint and E2E runs passed on synthetic e1514446, whose tree equals the local validated tree: 5,431 unit tests, 256 Compose cases and 39 E2E passes. All seven E2E shards ran on attempt one with matching APK provenance and no testcase retry. settings_08 remains intentionally disabled; six migration jobs were skipped. Complete available diagnostics retain 37 helper/stale-element notices and inherited compiler, JVM and provider warnings.

The hosted transfer_2 case again recorded a peer closing-fee disagreement (139 versus 182 sat), followed by force-close and commitment broadcast. Its UI-success and connection-removal assertions passed; they do not establish cooperative closure or confirmed returned funds. The direct close path and LDK pin match base, without a base-runtime reproduction or an established introduced cause. Four guarded METADATA refusals had later same-process acknowledgements. Activity-tag cancellation remains unexplained. These stock checks do not establish authenticated profile cleanup, terminal complete-WALLET recovery, bounded native Reset or private SDK acceptance.

Earlier cd1d1290 validation remains scoped to tree 91ce475c and base 14e6d3dd: 389 focused and 5,399 full local tests, 27 verified commits, then 5,399 hosted units, 256 Compose cases and 39 E2E passes in the original run. Its 43 helper notices, force-close, three guarded metadata refusals and Legacy-account sync timeout remain recorded. The current run did not reproduce that exact Legacy timeout; it does not establish a fix for it. The three original stale-write failures and later passing controls retain their original revisions.

The deferred-refresh finding already has its verified fix reply. Existing human requests remain pending. Earlier evidence and authored QA notes continue below.

November 11 · resume Spark backups when restore ends

At cd0befc6, pending Spark backup state is reconsidered when the existing restore gate clears or expires. A second restore that interrupts the debounce also retains the pending work. Three repository controls reproduced these gaps before the correction; acknowledged generations still do not upload twice.

The first acdd99c3 hosted composition with master 831c4d2a exposed five obsolete Pubky test fixtures. They now use the upstream own-profile revision API; no production behavior or assertions were removed for that correction. The original five failures remain recorded. Final local format, compile, lint and APK assembly passed, with 5,396 full-suite and 255 focused tests on tree 79ef817e using Paykit rc7. Two independent affected reviews are clean; all 26 live-base commits were verified locally and on GitHub.

The first cd0befc6 hosted checks used synthetic d5d49a33, tree 2332eb13, against master 8e86d30d with the separate upstream rc8 pin. All 5,396 JVM tests, including the five former failures, and 256 Compose cases passed. Lint reported zero findings. Seven E2E shards passed 39 cases on internal attempt one using suite 53e8b45b; @settings_08 was disabled and six migration jobs were skipped by their branch rule. Complete diagnostics retain 45 stale-element/helper recovery lines, a caught optional permission-button timeout, two native sync timeouts followed by same-process successes, and a legacy-listing timeout before a successful full VSS restore. These are qualified results, not a claim of clean runtime or full recovery acceptance. CI · Lint · E2E

The external reviewer reported two controlled installed-app passes on the earlier acdd99c3: one upload after explicit restore completion and one after real ten-minute expiry. Those results belong to that tested revision and reviewer; their recordings/readbacks have not been independently qualified here. Interrupted debounce, storage-error timing and replacement during a native PUT remain distinct fixture gaps. The existing complete-WALLET and unbounded native-authentication findings remain open, including the recorded disposition. No SDK release/adoption or reset acceptance is implied.

The required child compositions are published separately at #1688 dc9a9813 and #1689 e0d25982; their first hosted checks are in progress.

November 11 · Spark backup notifications through identity retirement

At 710292aa, the additive composition with master 4f401bd3 preserves Spark startup, payment history and backup behavior alongside this PR’s original-wallet admission. A Spark notification is acknowledged only after its required status is stored. Cancellation before that write can replay after the original owner reopens; a storage error no longer stops later notifications. Three controls reproduced the two cancelled-write cases and the stopped collector before the fixes.

Final format, compile, full unit tests, lint and APK assembly passed on one frozen tree: 5,334 unit tests, 371 focused tests and zero static findings. Two independent scoped reviews found no unresolved issue. All 24 live-base commits verify locally and on GitHub.

First hosted checks passed 5,334 JVM tests, 256 Compose cases and 39 E2E cases. One Settings case and five migration jobs were explicitly skipped. All seven E2E shards passed their first internal attempt on suite 53e8b45b; 36 stale-element messages remain recorded. Four metadata guards each had a later acknowledgement in the same process. Full logs and ten diagnostic archives were inspected, including fixture database/startup, network, fee, channel-closing and dependency advisories. CI · Lint · E2E

These controls do not establish a new authenticated Spark recovery journey, terminal complete-WALLET recovery or native VSS reset acceptance. Existing open findings, SDK decisions and fixture limits remain. #1688’s direct-child projection is clean with the same feature patch; #1689’s conflicting composition is being validated separately.

November 9 · activity backups on 3e1fdb7d

An observed ACTIVITY backup skips an unchanged payload only after a successful write for the same wallet owner. A full-backup request received while that read is in progress still sends the activity data. An uncertain PUT clears the cached digest. Restore and reset detach the old cache. VSS admission and shutdown stay with the original coordinator.

The regression test paused an unchanged read and requested a full backup before releasing it. The initial composition sent only the seed upload. The corrected tree sent the requested second PUT. Local checks passed all 125 focused tests and 4,993 full-suite tests, with no skips or failures. The six lint and Detekt reports contained no findings. All 23 commits verified against master 596f46cd. The published VSS dependency stays at 0.5.26-rc1.

The first hosted run passed 4,993 JVM tests and 256 Compose tests. All seven E2E shards passed on their first workflow test attempt, with 39 cases passing and one explicitly disabled. Six migration jobs were skipped. Hosted lint and Detekt reported zero findings. The backup/wipe logs retained missing restored entries and a missing Pubky session during endpoint cleanup. Authenticated cleanup and complete WALLET recovery remain open. CI · E2E · Lint

November 6 validation at b5d5858d

This branch now includes the upstream send-flow tests and keeps the allowance-admission regression. All 600 cases from the two parents ran locally. The full local suite passed 4,967 tests, lint reported zero findings, and all 22 commits in the live-master range verified locally and on GitHub.

GitHub tested merge tree b1ad9c4e against master ebe9bc09. All 4,969 unit tests and 256 Compose cases passed. Six lint reports contained zero findings. The seven regtest E2E shards passed 39 cases on their first attempt. Settings address-type switching was disabled in the suite, and the release-branch migration jobs skipped. Hosted logs retain helper and runtime warnings. This run adds no authenticated Pubky/Paykit journey or terminal wallet-recovery result. CI · Lint · E2E

Current backup-status correction — November 4

Signed fix a2c58f2427635719b63263b9441b8d22a7b6c858 prevents cancelled backup cleanup from inheriting Running from a replacement reservation that never entered its original wallet. Each pending reservation now records actual native admission and is removed by exact identity. Retirement drains admitted cleanup; rejected queued work cannot leave a stale Running flag. Startup status cleanup uses the same distinction. This is a two-file correction with no new public API or persisted state.

Final formatting, compilation, 4,890 unit tests across 264 suites, lint and APK assembly passed with zero failures/errors/skips and zero static findings. All 1,797 frozen inputs match, complete diagnostics were inspected, and 1,947 sealed evidence files were verified. The single added regression covers retirement before and after the cancelled writer's status cleanup; it fails on the published predecessor and passes on this fix. Two affected independent source reviews are clean. All 21 live-master range commits verify locally and on GitHub.

Author J3: the frozen final ARM64 APK (317136cc1b1385d9776f5edba2c22d4a25a5dd56109045595d1ddaf19b70609e) was installed in place on the preserved unfunded API36 ARM emulator, and installed bytes were verified. Changing EUR to GBP in the actual app showed Settings Running during its five-second queue, then Latest Backup after the VSS acknowledgement. No Settings Retry was observed. The original wallet and fixtures were preserved. This runtime case is distinct from the controlled unit retirement race; no wallet reset or complete-WALLET acceptance is claimed.

The separate brief Transaction Log Failed Backup/Retry flash remains documented. Capture limitations and native/runtime diagnostics remain in the audit. The first CLI emulator launch exited after reporting boot; the single foreground SDK recovery ran the case. The emulator later accepted shutdown but exited134 after saving its snapshot. These observations are preserved and are not described as warning-free execution.

Current-head hosted CI, Lint and E2E all passed on attempt 1: 4,890 units, 256 Compose cases and 39 E2E passes, zero failures, one explicitly disabled Settings skip, and zero findings in six static reports. Six release-gated migration jobs were skipped. The synthetic checkout tree exactly matches a2c58f24; complete logs, nested diagnostics and all 1,531 sealed evidence files were inspected and verified. APK identity is bound by producer/consumer artifact ID and digest; hosted APK bytes were not independently downloaded. Three RNBackupClient list-file timeouts and one ActivityRepo cancellation are newly observed runtime categories with unchanged base emitters; their cause remains unproven. Earlier cursor/native/bootstrap warnings and the temporary nonterminal GitHub status discrepancy are retained. This does not establish terminal complete-WALLET or new authenticated J1/J2 acceptance. Evidence: work/validation/hosted-android1686-a2c5-20261104/inspection/report.md. On predecessor b93444c3, the sole authorized Settings infrastructure retry completed with 13 passes and one explicit skip; the final unique E2E result was 39 passes/one skip, alongside 4,889 units, 256 Compose passes and zero lint findings. The original Docker port collision, runtime diagnostics and six skipped migration jobs remain preserved; that result is not transferred to this new head.

Evidence: work/validation/android1686-admitted-status-final-audit-20261104/, work/validation/android1686-admitted-status-app-audit-20261104/ and work/validation/android1686-admitted-status-20261104/publication.json. Existing QA IDs, remaining authenticated cases and terminal complete-WALLET limitations below remain unchanged.

Additional external review: 5773366561 reports 10 passing cases and one failure at this exact a2c58f2 head on an unfunded API35 fixture. It confirms queued/cancelled Settings status and recovery gates, while reproducing the existing terminal-identity complete-WALLET failure: identity_error leaves new ordinary-wallet work pending and preserves remote bytes/version. The reviewer distinguishes pristine app runs from Debug fault controls and decoder checks from nonempty USDT import. Raw install/proxy/readback artifacts were not independently inspected by the author. This is attributed external evidence, not another author-run campaign or human approval; the existing HIGH remains open.

Queued backup status — November 4

b93444c35 fixes 4467512070: a scheduled backup now shows Running during debounce and payment wait instead of falsely displaying Failed/Retry. Status cleanup stays inside the original wallet admission, preserves another active/pending backup, and checks startup cleanup against current state inside the persisted update. This does not change backup contents or relax complete-WALLET refusal.

Final required compile, full tests, lint, formatting and DevDebug APK assembly passed on 1,797 matching inputs: 4,889 tests /264 suites, zero failures/errors/skips, and eight fresh static reports with zero findings. Two independent affected concurrency reviews are clean. The negative control retained three expected failures on the original production code; the intermediate compile/format failures remain recorded. Complete logs and structured diagnostics retain the verified existing cursor/JVM/deprecation/native-strip notices. All 20 commits against live master 44bf50ec verify locally and on GitHub (verified=true, reason=valid); new-head hosted CI is pending complete inspection.

Author-run J3 used a new unfunded API36 ARM64 emulator, the installed APK SHA256 6646ff3bfcc7bc27dbb59e4e5c71d94b439c6c0a753f8594be520a481f7196e6, and ordinary staging VSS/Electrum. Changing local currency showed Settings Running without Retry, then Latest Backup after the real SETTINGS put acknowledgement. Continuous video and complete diagnostics are retained; the first delayed still capture missed the interval and is not counted as a pass. Media offsets are not wall-clock measurements. No profile, recovery phrase, wallet reset or funds were used. This finite result does not complete J1/J2 or the terminal complete-WALLET finding. The complete recording also retains two brief Transaction Log Failed/Retry frames between ordinary updates and scheduling, with no ACTIVITY upload failure logged. The required-before-running state is representable in live master 44bf50ec too; the exact runtime interleaving is inferred, not reproduced on that base. This separate pre-scheduling presentation gap remains, so no all-category/no-flash claim is made.

Evidence: work/validation/android1686-backup-status-final-audit-20261104/report.md and work/validation/android1686-backup-status-app-audit-20261104/report.md. Earlier results below remain tied to their stated revisions.

VSS operation ownership — November 4

Signed 4056d2c00 keeps app and standalone LDK backup work with its original wallet generation. Identity replacement closes both client admissions, cancels and drains setup/native calls and their caller tails, shuts down the old slots, then holds admission closed through credential changes. Each client derives its store ID from the same captured mnemonic/passphrase as its signer. Setup and ordinary calls retain their existing concurrency and readiness behavior.

Backup payload capture, retries, status callbacks, routing repairs and detached node restarts retain the original owner. A canceled identity transition can rearm observer setup and pending backups; stale scheduling cannot replace a newer generation's debounce token. Explicit first-WALLET scheduling still works before node observation starts. Shutdown failure leaves admission closed. The released SDK and server protocol are unchanged.

Required final just compile, full just test and just lint passed on the same 1,796 frozen inputs: 4,887 tests /264 suites, zero failures/errors/skips, with fresh Detekt and Android Lint SARIF/XML showing zero findings. Final formatting is clean; a subsequent local flag rename has exact reverse-hash equivalence and was checked by final lint. Complete logs, test reports, embedded Gradle diagnostics and all earlier failures were inspected. Four existing cursor-close traces and three JVM notices remain recorded against actual-base sources; no introduced compiler/static finding remains. Two independent affected concurrency/security source reviews are clean. All 19 commits against live master 44bf50ec verify locally and on GitHub. Evidence: work/validation/android-vss-owner-diagnostics-20261104/report.md.

At 4056d2c0036e5a4e51698e26b3d1615825dd77f5, hosted CI attempt 2 passed after the one authorized Compose retry. Compose executed 256 tests across 60 classes, zero failures and zero skips; XML, all HTML case identities, raw instrumentation and both binary UTP result files agree. The required build aggregate passed. Existing exact-tree evidence remains 4,887 unit passes, zero Detekt/Android Lint findings, and 39 general E2E passes, zero failures, one source-declared skip. Migration jobs were release-gated skips. The checkout was synthetic merge 3c8fc2745652d6eb1f624ff537ec35cbe0702faa with the same tree 32b8d4633b0f12fc1b9ee7d94007824c766addbd as the published head, against master 44bf50ecabefe4e91d41fedbcbbb14fb132bbebc.

The authorized Compose retry is now fully audited: Compose job, aggregate, and test artifact. All 256 cases passed with no skips. The original attempt's No service published for: input startup failure remains preserved as a before-tests infrastructure failure. Complete logs and all 356 artifact members were inspected; check annotations contain only runner-image notices. Repeated fixture Core/database/Paykit bootstrap errors and Android resource warnings remain visible, and the non-uploaded Gradle problems HTML limits deprecation attribution. This does not establish running-node persistence quiescence, deployed migration or complete-WALLET recovery. No retry authority remains. Owner verification matched all 447 new evidence hashes and reused the sealed 475-file original audit. Evidence: work/validation/android1686-authorized-compose-retry-20261104/inspection/report.md. Existing authenticated QA and terminal complete-WALLET gaps remain open.

Current composition — November 3

Signed additive merge 43e0f3fe04705d397a81f493cf8e57239a0be73e incorporates live master 44bf50ecabefe4e91d41fedbcbbb14fb132bbebc. Both restore branches preserve deferred identity initialization while forwarding master’s failed optional backup categories to the completion screen. Existing required-restore, correction and cancellation gates remain in place. No published history was rewritten.

Final just format, just compile, just test and just lint passed on the same 1,794 inputs: 4,873 unit tests across 263 suites, zero failures or skips; Detekt and Android Lint report zero findings. Complete logs, XML, SARIF, HTML and embedded Gradle reports were audited, and the affected independent source review is clean. All 18 live-base commits are locally and GitHub signature-verified.

Two test-fixture repairs were necessary after composition: supply master’s new ledger-state Boolean in the mocked allowance executor, and use a plain Application in the mocked view-model suite. An earlier run stalled with 64 IO workers blocked by production auth registrars started by that test fixture. Its complete thread dump, 695 passing results, one interrupted case and stopped-worker failure are retained. The final run used a different test order; it is not a same-order starvation reproduction or a production dispatcher fix. The initial formatting finding and pre-execution sandbox failure are also retained. Existing Gradle deprecation and JVM/cursor diagnostics remain disclosed in the audit.

All current-head hosted runs are complete and inspected: 4,873 unit tests, 256 Compose tests and 39 external E2E cases passed; Detekt and Android Lint have zero findings. The seven E2E shards passed their first whole-shard attempts; one Settings case, six migration jobs and all 14 retry steps were explicitly skipped. Synthetic merge 79371a24 has exactly the published tree. Complete logs, nested XML/HTML/protobuf/logcats and 10 digest/CRC-verified report archives were audited; the owner verified all 520 evidence hashes.

Compose retains Core storage-initialization diagnostics in its Hilt fixture. General E2E retains RN backup-list/restore timeouts and a METADATA safety refusal; relevant source blocks match actual master, without a base runtime or historical-cause claim. Two multi-address tap-helper retries are distinct from whole-shard attempts. These passing suites do not establish full authenticated backup/recovery. Hosted evidence: work/validation/hosted-android1686-43e-20261103/inspection/report.md. The older hosted and runtime results below remain tied to their original revisions. No new authenticated J1, funded-payment or terminal complete-WALLET acceptance is claimed. Evidence: work/validation/android1686-master44bf-final-diagnostics-20261103/inspection/report.md; publication and exact signature receipts: work/validation/android1686-master44bf-publication-20261103.

Previous-head hosted results — November 2

All hosted jobs for b6751e22956653c4f2a80112143880b47298e30d are now inspected: 4,825 unit tests pass, all six static reports have zero findings, and 39 distinct E2E cases eventually pass with one deliberately disabled Settings case. The exact synthetic checkout tree matches this published head; the external suite is 611509ee.

The LNURL/transfer shard first failed two activity-card assertions and then passed its one automatic shard retry. Both failed executions and the exit-1 annotation remain recorded. Failure screenshots show the expected values in the second card; the guest clock differs from the host/deposit dates on the failed attempt. This supports a clock/order investigation, but the cause is not established. No manual CI rerun occurred. Six skipped migration jobs are not passes.

Complete logs, structured results, nested runtime streams, checksum/CRC-verified archives and failure images were inspected; the owner verified all 438 terminal evidence payloads. Runtime backup, TLS, sync and cancellation diagnostics remain disclosed. The earlier 181d664c routing failure is not waived or claimed repaired. Existing authenticated acceptance and terminal complete-WALLET gaps below remain open. Evidence: work/validation/hosted-android1686-b675-20261102/E2E-TERMINAL-REPORT.md.

Routing-test diagnostics — November 1

Signed b6751e22956653c4f2a80112143880b47298e30d adds failure-only resolved-activity and component-state diagnostics to the existing routing test. Assertions, query flags, deadlines and production behavior are preserved. It reuses the exact independently reviewed diagnostic file already present in #1688. The earlier 181d664c hosted failure below remains unresolved; this is not a causal repair or a waived check.

The final composed candidate passed required compile, 4,825 tests / 260 suites, formatting and static checks with zero findings. All 1,778 frozen files match. Complete logs, XML/HTML/SARIF and lint partial/model outputs were inspected: Detekt reports are fresh; aggregate Android lint reports were UP-TO-DATE, with fresh changed-unit analysis also inspected. Four retained CloseGuard events are not claimed fixed. The exact-file/API applicability review is clean. All 17 live-base commits verify locally and on GitHub. Current-head hosted results are recorded above. Evidence: work/validation/android1686-manifest-diagnostics-20261101/final-diagnostic-audit/REPORT.md.

Previous-head hosted unit failure — November 1, 23:24 UTC

CI run 41360316580 failed on exact head 181d664c38a40df156cad4388168b5ab2df132c4: 4,824 tests passed and one failed, with zero skips. PubkyAuthManifestTest.kt failed its first default-disabled route assertion for pubkyring://signup?hs=homeserver; both structural manifest checks and the new allowance off/on regression passed. The failure output omits the resolved activity and component override, so the cause is unresolved. Source equality with the actual parent does not establish a pre-existing runtime failure or infrastructure cause.

The completed lint job has zero findings across all six reports. Five complete logs, all unit HTML and both digest/CRC-verified report archives were inspected; 400 sealed payloads were independently hash-verified. Seven E2E shards were pending at this snapshot, and six migration jobs skipped. No unchanged CI rerun was made. The diagnostic descendant is being inspected before selecting a repair; this failed required check is not waived. Evidence: work/validation/hosted-android1686-181d-20261101-current-a/REPORT.md.

Allowance off/on recovery — November 1

Signed 181d664c38a40df156cad4388168b5ab2df132c4 fixes the lost activation reported in 4437596764. Turning allowances off still revokes queued work immediately. A pause revision now makes the latest enabled contact/settings state distinct, so turning them back on during held admission schedules a fresh activation for the current identity. Old queued acceptance remains revoked; identity, deletion and live-settings checks are retained.

The actual AppViewModel collector and real allowance repository reproduced the failure before the fix and pass afterward, using mocked SDK/executor resources. Final required compile, 4,825 tests /260 suites, formatting and six complete static reports passed with zero failures/skips/findings. All 1,778 frozen files match. Full logs and structured diagnostics were inspected; four CloseGuard warnings and earlier failed attempts remain recorded. Two independent concurrency reviews are clean. All 16 live-master range commits verify locally and on GitHub (verified=true, reason=valid).

The existing allowance-off journey now describes the Android delayed-contact-loading variant. The author has not run that held-boundary authenticated app case; component evidence is not a device pass. Current-head hosted CI is pending complete inspection. The separate terminal complete-WALLET finding remains open. Evidence: work/validation/android1686-allowance-resume-final-audit/REPORT.md and work/validation/android1686-allowance-resume-publication/.

Hosted validation update — November 1, 22:16 UTC

Exact-head hosted checks are complete: 4,824 unit tests pass, six static reports have zero findings, and 39 distinct end-to-end cases pass on their first executions. settings_08 remains an explicit disabled skip; skipped migration jobs are not passes. Complete logs and seven checksum/CRC-verified end-to-end archives were inspected. Nonfatal runtime diagnostics remain recorded, without a blanket clean-runtime claim. Terminal complete-WALLET availability and the existing authenticated acceptance gaps remain open.

Setup-pending and activation follow-up — November 1

Signed 1b1426fbebeccd616c29311fa5bf652089727a84 stops reconnect recovery from repeatedly fetching a deliberately absent profile while local profile setup is still pending. Once setup completes, missing restored profiles remain eligible for recovery. The actual repository regression failed before repair (six unexpected resolver calls over three reconnects) and passes afterward. This head also includes the reviewed shared allowance fixes: revocable contact/dispatcher activation and rejection before SDK backup mutation tracking.

Final required compile, full unit tests, lint and formatting passed: 4,824 tests, zero failures/skips and six static reports with zero findings. All 1,778 frozen inputs match; the combined source review preserves the independent shared concurrency reviews. Complete diagnostics retain four structured CloseGuard warnings and all earlier test-fixture failures/sandbox refusal. The complete 15-commit actual-live-base range verifies locally and on GitHub. New-head hosted CI is pending; no new authenticated app acceptance is claimed. The existing terminal identity/complete-WALLET HIGH remains unresolved and is not repaired by these changes.

Description

Ordinary wallet restore finishes after required wallet and USDT recovery; optional Pubky activation and profile enrichment continue afterward. Scheduled setup preserves an identity already activated by metadata restoration, coalesces requests for the same revision, and rejects obsolete results.

The reconnect follow-up in 9ac9746ae retries a missing own profile from existing reconnect, resume and maintenance calls. It captures the original sign-in, returns without waiting for profile networking, avoids re-importing an active session, and reuses the existing profile-write and overlapping-load guards. A successful load stops these retries. The previous “Your Name” placeholder finding is addressed without adding contact refresh or payment work.

Complete WALLET and METADATA capture still rejects unavailable or unreadable identity data instead of replacing a complete backup with an incomplete snapshot. Terminal identity failure can still leave newer ordinary WALLET state pending; the existing HIGH availability finding remains open.

Twin: synonymdev/bitkit-ios#1121. Parent #1685 and fee follow-up #1701 merged externally; this PR now targets master.

Out of Scope

  • journeys/allowances/allowances-turned-off.xml: clarify the delayed-contact variant's executable or manual steps in #1766, milestone 3.1.0. This nonblocking LOW review finding is deferred under the repository review policy. The existing seven actions do not exercise that extra boundary.

Current validation — November 1

Head 78269d8a1cae1ac127be93a96fba16f7d68d1019, tree 325f57e2e6f20211b805816026fa98463d1f74ad, targets live master 1337f121cd2694718fb58e1c4f022d73104cccc1 directly. The SDK admission callback still rejects work queued before allowance deactivation. Review 4433972339 additionally found ordinary contact sync replacing the activation for the same enabled identity. The correction now retains that activation; pause, deactivation and identity changes still invalidate it. Restore, spending and complete-backup guards are unchanged.

Final required format, compile, full tests and lint pass: 4,817 tests / 260 suites, zero failures/errors/skips/retries and zero fresh Detekt/Android Lint findings. All 1,778 frozen inputs match. Complete logs, nested output, XML/HTML/SARIF were audited; the owner verified 1,651 final artifacts. Three JVM notices and four cursor-close warnings remain, with retained actual-base/earlier-run comparisons. Two shared independent concurrency reviews and one affected integration review are clean; source/test blobs exactly match the validated #1684 correction. Controlled manual and automatic regressions failed before the correction and passed afterward; these are component tests, not a new authenticated app pass.

All 14 live-base commits are locally and GitHub true/valid. The first immediate post-push REST snapshot was stale; live-head reconciliation followed by one read-only verification completed successfully, without repeating the push. New-head hosted checks await complete inspection. Evidence: work/validation/android1686-stable-activation-20261101/ and work/validation/android1686-stable-activation-final-a/inspection/structured-report.json.

The previous 7b795fdc hosted CI, lint and E2E are fully audited on the exact published tree: 4,815 units, zero static findings, 39 first-attempt E2E passes and one disabled Settings case. Passing multi-address logs still contain native sync deadlines and WalletOperationTimeout; their causes remain unproven. All 462 sealed evidence files verified. These results certify only that prior head.

Retained evidence and unresolved findings

The terminal complete-WALLET availability defect remains open. Review5724858087 reproduces it at predecessor 71fa609c; the complete report and unpushed Debug-control appendix were read. Its raw runtime artifacts were not independently audited and its controlled APK is not claimed identical to the published APK. No nil/stale SDK fallback, partial backup or closure is implied by this allowance repair.

At predecessor 71fa609c, CI passed 4,814 units, lint had zero findings, and E2E reached 39 unique eventual passes with one disabled settings case. Multi-address attempt1 failed a 30-second ReceivedTransaction wait; attempt2 passed and skipped two already-completed cases. Complete logs, all attempts, artifacts and the exact synthetic tree were audited. The failure cause remains unproven; migration skips are not passes. Earlier missing-invoice, UI-timeout and setup failures retain their original receipts; no unchanged CI retry or causal-fix claim is made.

Design / Preview

The Spark correction retains the existing Home/Spending and Send result layouts; it updates displayed balances and prevents an unrelated node-wait overlay from covering the payment result.

Existing layout is unchanged. The status correction uses the mapped Back up wallet › Data Backups screen in docs/screens-map.md; an exact Figma frame URL is not recorded, so no node link is invented. Own-profile recovery still uses existing Home/profile presentation.

QA Notes

Setup

For J3, use a separate unfunded dev wallet in a DevDebug build (./gradlew assembleDevDebug, then install the matching ABI APK). Keep default staging VSS/Electrum available, English selected, and Debug developer mode enabled for adb shell am start -a android.intent.action.VIEW -d bitkit://screen/backup-settings to.bitkit.dev. Start at Home. A device-local recording captures the brief debounce interval when host command latency is too high; it changes no product timing. No reset, profile, seed access or funding is needed.

Use the committed Debug dependencies: Core 0.8.0-rc11, Paykit 0.1.1-rc6, VSS 0.5.26-rc2, LDK 0.7.0-rc.79 and Breez Spark 0.28.0. These published pins come from master; they do not include the private #267/#36 corrections or LDK #132. J1 needs a disposable test-network wallet with a complete VSS backup and saved identity. Keep metadata credential replacement and required imports available; delay only final activation or optional enrichment after required recovery. Preserve existing wallets and use no live funds.

For the current correction, Case 5 needs a separate disposable Spark regtest wallet, synthetic funds, a test recipient, and a controlled way to stop only LDK while Spark remains connected. Native balance readback and the selected operation's acknowledgement must be observable. The standard journey capability table does not provide this controlled Spark setup. Keep the published dependency pins; no private SDK, wallet reset or live funds are part of this case.

For manual case 6, use an isolated disposable development wallet with known cached balances and receiving data, a controlled native-startup hold, and independently releasable cache loading. These controls are unavailable in the standard journey fixture. Display amounts are fixture data; no payment or wallet reset is needed.

Manual Tests

  • 1. With two disposable linked identities and a pending allowance proposal, hold the receiver immediately before SDK acceptance admission. Tap Accept, synchronize a changed contact-key set while the same identity remains enabled, then release: the proposal accepts once. Repeat after disabling/re-enabling before release: the old queued attempt must be rejected. The standard journey environment lacks the controlled SDK-admission hold; deterministic repository coverage passes, but a fresh author-run authenticated app execution remains unperformed. The earlier before-fix runtime reproduction is attributed to its reviewed revision.

  • 2. Hold an allowance activation during contact synchronization, switch Enable Allowances off and back on, then release: the current enabled identity activates once without restarting the app; the old queued acceptance stays revoked. The author’s controlled collector/repository test passes, but the authenticated app timing gate is not available in the standard fixture.

  • 3. In an isolated unfunded Spark fixture, hold the backup-required status write before persistence, then fail an identity change without replacing credentials. After admission reopens, the pending readiness or exit-generation signal must still upload once. Also fail one status write with a storage error and verify that a later generation uploads without restarting observation. This requires controlled status-persistence and owner-transition faults unavailable in the standard journey environment; the three component regressions pass, but an authenticated app execution of these boundaries has not been performed.

  • 4. With an isolated unfunded Spark/VSS fixture, retain a backup-required generation during restore, then clear the restore gate or allow its real timeout to expire. Verify one acknowledged upload without another Spark event. Repeat with a second restore interrupting the debounce and verify the pending upload resumes once. Three local repository controls pass; the external reviewer reported the clear/expiry portions on acdd99c3. The interrupted-debounce installed-app case still needs the controlled fixture; no author-run authenticated pass is claimed.

  • 5. With LDK stopped and Spark ready, record the native Spark balance and the Home/Spending total. Complete a small Spark send to the test recipient, then a second send, and finally withdraw the remaining Spark balance using the fixture's authorized native operation. After each send, verify the payment result and its Close/Details actions remain visible without a Connecting to Network overlay, including when the remaining Spark balance is below the paid invoice amount. After each acknowledged balance change, verify Home/Spending reflects the current shown Spark amount while preserving any known LDK contribution and the on-chain balance. Check the zero-Spark result and reopen the cached screen. When Spark retains a displayed balance after a failed read, verify that display is not offered as spendable funds. Record the app revision, fixture configuration, native before/after amounts and acknowledgements. This is a prepared manual case, not an author-run app pass; local repository/observer controls and the earlier external reproduction remain separately attributed.

  • 6. Cold-start the controlled wallet with native node startup held. Allow cached data to load while a balance refresh waits for the node. Verify Home shows the known cached balance and the already-validated cached address/invoice becomes available before releasing native startup. Release the node hold and verify a fresh balance replaces the cached value; a later refresh must remain current if another earlier refresh was delayed. Keep any receiving address that still needs reservation validation unavailable. Record app/build identity, holds and release order, and cached versus fresh readbacks. The repository regression covers cache publication and refresh ordering; a new author-run installed-app execution needs the controlled fixture. The external failed cold-start reproduction remains attributed to ff9275d6.

Journeys

  • J3 — new scheduled-backup-status.xml: change a local currency and observe queued Running, followed by Latest Backup after acknowledgement. Android-only scheduling regression; author-run result is recorded above.

  • J2 — allowances/allowances-turned-off.xml: the seven executable actions cover ordinary off/on behavior and restoration of the Active row. The description-only delayed contact-loading variant is not exercised by those actions; its executable/manual documentation is deferred to #1766. That held-boundary case remains unexecuted as an author-run app journey.

  • J1 — restore-during-identity-outage.xml: optional activation outage after required restore, complete-backup protection, screen exit, missing-profile reconnect, stale enrichment after identity removal/replacement, restart, and required-recovery failures retaining spending/address gates.

The new reconnect action expects wallet maintenance to continue while a real profile read is held, then Home to recover after release without manual Profile navigation. The final candidate has repository-level tests with mocked native/service resources; this is not a complete authenticated app journey. The author's isolated complete-app fault controls for J1 are not yet provisioned.

External review 5688838161 reports real SDK/VSS cases and reproduces both findings at predecessor 89e2702e. Its raw nonvisual artifacts have not been independently verified by the author, and it is not acceptance evidence for the new head. The matching iOS reconnect follow-up is published in #1121 at 0b77f099; its iOS evidence does not establish Android acceptance.

Automated Checks

  • updated WalletRepoTest.kt — keeps known balance contributions and original-wallet ownership through stopped-node Spark changes, cache hydration and retirement.
  • updated SendSheetNavigationTest.kt — keeps payment results visible after the remaining balance falls below the paid invoice, and restores the wait when returning to Confirm.
  • updated BackupRepoTest.kt — retains Spark readiness and generation notifications across owner retirement, and keeps observing after a status-write failure.
  • updated LightningRepoTest.kt — supplies the existing coordinator to the upstream startup and cross-rail fixtures.

Evidence and remaining gaps

PubkyRepoTest covers the new retry and retained coalescing, cancellation, sign-in and profile-write guards. Existing WalletViewModelTest and BackupRepoTest cover required recovery admission and complete-backup refusal. Full-suite success does not establish process-kill, authenticated service faults or funded payments.

The terminal full-WALLET availability finding remains unresolved on both platforms. No stale SDK fallback, partial backup, independent-only writer, legacy migration activation, payment replay or authorization bypass is introduced. Full-wallet redesign and contact CAS are separate work, not substitutes for this PR's acceptance.

Models used

  • Planning/scoping: gpt-6-astra (reasoning: xhigh).
  • Implementation: gpt-6-astra (reasoning: xhigh).
  • Review: gpt-6-astra (reasoning: xhigh), gpt-6.1-sol (reasoning: high).

Actual execution metadata and historical review scopes are retained.

@ovitrif ovitrif added this to the 3.1.0 milestone Oct 24, 2026
@ovitrif

ovitrif commented Oct 24, 2026

Copy link
Copy Markdown
Collaborator

Triage: 3.1.0. It keeps the shipped wallet restore from waiting on profile refresh, and 3.1.0 is due 28 Oct.

@greptile-apps

greptile-apps Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable issues were found.

Summary

Wallet restore now schedules optional identity activation and profile reads without waiting for them.

  • Wallet restore finishes while Pubky identity refresh runs in the background.
  • Backups stop before upload when saved identity data is incomplete.

No actionable issues found. Review covered source and tests; tests were not run.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Required wallet and USDT recovery] --> B{Succeeded?}
    B -->|No| C[Keep restore blocked]
    B -->|Yes| D[Schedule identity work]
    D --> E[Complete wallet restore]
    D --> F{Identity revision still current?}
    F -->|No| G[Skip obsolete work]
    F -->|Yes| H[Activate identity and load profile]
    I[Build backup] --> J{Identity data complete?}
    J -->|No| K[Keep previous remote backup]
    J -->|Yes| L[Upload backup]
Loading

Reviews (1) · Last reviewed commit: "fix: decouple wallet restore from profil..." · 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 Pubky identity activation after a wallet restore off the restore screen's critical path (scheduleInitializationAfterRestore, coalesced per stored-identity revision), and makes WALLET and METADATA backups fail rather than upload a payload with the identity part silently missing. Reviewed ac2a7c6, full tier, stacked on #1685 (fix/pending-wallet-restore-admission), reviewed as the delta against that base.

What I checked, and 6 candidates I ruled out

Read in full: PubkyRepo.kt (initialization, restore, adoption, sign-out and backup-state regions), BackupRepo.kt (scheduling, triggerBackup, markBackupFailed, wallet and metadata snapshots, full restore), WalletViewModel.kt restore paths, PrivatePaykitRepo.backupSnapshot, PaykitSdkService (currentPublicKey, session provider, clearSessionAccess), and paykit-rs v0.1.1-rc1 identity_status / initialize.
Call sites traced: scheduleInitializationAfterRestore (both WalletViewModel restore paths), hasIdentityForBackup (only captureWalletBackupDataBytes), initialize() (still only the init block, unchanged semantics with expectedRevision = null).
CI: lint, detekt and build-local green. build is red on one test, PubkyAuthManifestTest > signup and authorization links resolve only through their enabled aliases, at its first assertion (line 77, every alias still at its default). The diff touches neither that test nor the manifest; the base head 837aa1c passed build, and the same test failed the same way in two of the last eight failed ci runs on unrelated branches (fix/update-terms-of-use, feat/usdt-design-followup-20261015). All seven new tests in PubkyRepoTest, BackupRepoTest passed in that run. The e2e shards were still running when I read the checks.
Not built here: this review is reasoned from the code and CI; CI is the gate.

Ruled out

  • Scheduled activation lost when the revision moves: the revision only moves through startSignIn (non-restoring) or a non-preserving clearAuthenticatedState, both of which are a newer identity's own path, so dropping the stale job is the intent. restoreSessionBackupState bumps it inside the restore, before the schedule reads it.
  • Something after Completed needing the identity: the public key is already set inside the required boundary (restoreSessionBackupState LocalSeed startSignIn), and the payment-request activate at BackupRepo.kt:1058 runs during the restore, unchanged.
  • Coalescing reusing a finished job: takeIf { !it.second.isCompleted }, and the completion handler clears the slot only when it still holds the same job.
  • Uncaught failure in the background job: initializeSession catches its own failures, checkAdoptedSource returns a Result, and appScope carries a SupervisorJob plus a logging handler.
  • WALLET backup blocked for good while a saved session exists: with a stored session currentPublicKey() reads the bound identity state through identity_status, so state is null only when the SDK has no identity, which is the case the check means to hold; an unreadable keychain fails the backup (covered by wallet backup cannot treat unreadable identity as absent).
  • METADATA getOrThrow turning a benign miss into a failure: both snapshots return null for absence inside runSuspendCatching, so only a read error now fails, which is what the two new tests pin.

Merge confidence: 3/5, the build job is red on PubkyAuthManifestTest, which I traced to a flake outside this diff; a green re-run would move it to 4/5 (J1 is still unrun).

Reviewer model: claude-opus-5-5
Reasoning effort: Not exposed

@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Regtest APK

Built from bc6b171 (run).

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

@jvsena42 jvsena42 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Code scan: one LOW inline, reproduced with a failing unit test.

Checked and clean:

  • No cross-identity leak on wipe and restore: the mutex, the revision and the isCurrent(signIn) guards hold.
  • Identity isn't lost for good: the retry paths cover a failed background refresh. The WALLET backup that can stay blocked is the open P1 thread.
  • No payment path starts before the identity exists: the key is set inside the required restore.
  • Twin synonymdev/bitkit-ios#1121 keeps the header signed-out until the background activation lands, so it has no flip.

Performance-relevant (the purpose is a faster restore). wallet/restore-during-identity-outage.xml needs fault controls that aren't provisioned, so the gate uses a proxy. It restores a regtest wallet whose backup carries a pubky session, then:

  • times Full restore success → Completed, head vs master, with the homeserver reachable and with it blocked;
  • checks that the header shows the identity and that profile and contacts arrive afterwards;
  • counts Restored paykit session for per restore (expected 1);
  • runs Settings → Backup for WALLET once the identity is active.

Device gate (partial): ac2a7c6 — not run yet; pending that proxy run. Device results will follow in a separate review.

@ovitrif

ovitrif commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator

All four children are now merged into this branch: #1688, #1689, #1690 and #1693. 3c2682a brings it up to date with master:

  • Master is merged in (b5c6b3b). It resolves 18 conflicting files, mostly where this stack's admission and receipt gates meet master's Spark, wake and RBF changes.
  • In WipeWalletUseCase, the profile-removal drain now wraps withIdentityChange. Removal therefore finishes before backup reset, and reset still runs before the VSS clients suspend.
  • The tests follow master's current APIs. Lightning max-send now expects master's combined channel and Spark amount (MoveToSparkMath.maxSendSats).

This PR is on hold. It will not merge until all of these are settled:

  • HIGH, terminal identity blocks ordinary WALLET backups (finding): not fixed here. The guard stays, because without it an identity-free WALLET would overwrite the last complete Paykit backup. Letting ordinary changes upload without the identity needs the restore contract @ben-kaufman described here: wallet and version binding, a reader older apps can select, and protection against stale writers. Carrying the remote Paykit section forward would pair stale payment state with newer wallet data on restore.
  • MEDIUM, Reset waits on held native authentication (thread): waits on fix: bound LNURL authentication before VSS requests vss-rust-client-ffi#36. An app-side timeout would have to reopen admission while the retired client's native poll is still running.
  • Retry refresh for a failed profile delete (thread): still open, for the reasons in that thread.
  • No device run has been reported on this head.

The unit suite and just lint pass on 3c2682a.

@ovitrif
ovitrif requested a review from a team November 26, 2026 02:45

@piotr-iohk piotr-iohk 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.

QA review

Scope: full PR at 3c2682a, re-reviewed after the comparison base changed from e63b9d89 to 1ffad41 with target-branch changes touching reviewed files.

3 actionable findings — resolve or provide an evidence-backed rebuttal.

Validation and coverage: GitHub Actions checks on 3c2682a completed for build, build-and-test, compose-ui / ui-tests, lint, detekt, and the 7 local E2E shards. Unit and Compose UI tests cover VssClientCoordinator, backup observation shutdown, WalletConnectionRecovery, ProfileRemovalStore, ProfileRemovalCoordinator, WalletResetRecoveryScreen, and profile removal ViewModels, but LightningRepoTest.kt's pending wallet wipe rejects native startup test does not assert that sparkRepo.start is skipped (leaving F1 unguarded). Product rule BITKIT-001 (concurrent wallet/Pubky installations unsupported) and BITKIT-002 (pre-2.6.0 profile compatibility unsupported) were applied; no findings depend on those exclusions.

iOS twin comparison: Compared shared flows against synonymdev/bitkit-ios#1121 at 6975667. Both platforms align on decoupling wallet restore from optional profile refresh, guarding WALLET backups against writing null paykitSdkBackupState when a stored identity is unresolved (PrivatePaykitService+Backup.swift mirrors Android's hasIdentityForBackup guard and carries the same terminal-identity availability gap), suspending VSS clients across local wipe, and refusing automatic retry of uncertain profile deletions. Intentional platform differences are documented in the updated journeys/ specs: Android adds the restricted WalletResetRecoveryScreen / MigrationRecoveryScreen routes, explicit ProfileRemovalCoordinator review/local-disconnect recovery, and backup/scheduled-backup-status.xml.

Recommended before device testing

  • Address F1 so LightningRepo.start() does not start Spark when profileRemovalStore.requireWalletAvailable() rejects startup, and extend LightningRepoTest.kt to assert verify(sparkRepo, never()).start(any()).
  • Confirm whether F2 (terminal or update-required Pubky identity blocking all WALLET backups until manual profile disconnect) is being resolved here or tracked as a follow-up before shipping.
  • Collapse the five changelog.d/next/*.fixed.md fragments (F4) into one fragment for #1686.

Suggested additional test cases

  • Android — Spark stays stopped during pending wallet reset: On a disposable dev wallet with Spark enabled, interrupt a wallet reset after profile_removal.json records WALLET_WIPE so WalletResetRecoveryScreen is active, then trigger a background/detached LightningRepo.start() (e.g. foreground service start or restartNode). Expected: both LDK startup and SparkRepo.start() are refused with ProfileRemovalPending, and no Spark connection or activity sync writes occur.
  • Android — Terminal Pubky identity vs ordinary WALLET backup: On a disposable dev wallet with an expired/revoked grant-only PAYKIT_SESSION (no local PUBKY_SECRET_KEY) and a completed wallet restore, create a new watch-only account or on-chain transfer and trigger a backup. Expected: verify whether non-Paykit WALLET backup recovery is unblocked or the user receives actionable guidance to disconnect the unrecoverable profile rather than generic repeated backup failure warnings.

Device testing: not performed in this review (code-only assessment; fault-injection journeys under journeys/ remain unexecuted here).

Earlier findings reconciled at this revision: 4 still present, 1 verified fixed, 1 duplicate.

Findings

  • [MEDIUM] Move Spark startup after pending wallet-wipe admission check in LightningRepo.start — inline at app/src/main/java/to/bitkit/repositories/LightningRepo.kt:422.
  • [MEDIUM] Preserve complete WALLET backup availability when a stored Pubky identity is terminally unavailable — now at app/src/main/java/to/bitkit/repositories/BackupRepo.kt:1440. Same issue as the earlier review.
  • [LOW] Use runSuspendCatching around receipt.commit in on-chain receive and confirmation handlers — inline at app/src/main/java/to/bitkit/services/CoreService.kt:1649.
  • [LOW] Consolidate the five changelog fragments into a single fragment for PR #1686 — inline at changelog.d/next/1688.fixed.md:1.

Existing concerns

  • [MEDIUM] Bound native authentication before draining VSS during reset — Reset still waits indefinitely on a held LNURL-auth response before it can shut down the standalone VSS clients or delete local credentials. GitHub review thread #1686 (comment) (PRRT_kwDOMPAnV861DLWS) remains unresolved, and the author confirmed at #1686 (comment) that it stays open on 3c2682a pending vss-rust-client-ffi#36. WipeWalletUseCase.kt:85-120 sets wiping true before entering withIdentityChange, runs keychain.wipe() only inside that block (line 148), and clears wiping only in finally (lines 118-120). VssClientCoordinator.kt:136-139 cancels admitted jobs and awaits pending.joinAll() inside NonCancellable before vssShutdownClient/vssShutdownLdkClient. gradle/libs.versions.toml:98 still pins com.synonym:vss-client-android 0.5.26-rc2 (tag v0.5.26-rc2 peels to cf5b5cdfb8aaa79c06953fc57e98d96236c57d25), where execute_async! runs Runtime::block_on for vss_get/vss_ldk_get and bundled vss-client-ng 0.4.0 builds its LNURL-auth client with no timeout before the 10-second VSS request timeout. ResetAndRestoreScreen.kt:76, 81, 114, and 122 disable Back and keep Reset loading while isWiping stays true. synonymdev/vss-rust-client-ffi#36 remains OPEN and unmerged. Same mechanism as synonymdev/bitkit-ios#1121 (comment); no material new evidence beyond the prior reports, and no device test was run here.
  • [LOW] Allowance journey describes a delayed-contact check its actions do not perform — The journey description still instructs the runner to repeat the off/on sequence while contact loading is delayed, while the action list still executes only a single off/request/on sequence with no delayed contact load. GitHub thread #1686 (comment) (PRRT_kwDOMPAnV86yliGN) is marked resolved because the author deferred the change as out of scope to #1766, which remains OPEN. Because this PR's own diff introduces the mismatched description against 1ffad41, the mismatch remains open here and is already tracked in #1766.
  • [MEDIUM] Backups required during restore stay unscheduled after restore — A non-SPARK_EXIT backup category marked required while restore is in progress is still not scheduled once restore finishes. shouldBackup(category) is false while restoring, so the status observer drops that emission and distinctUntilChanged does not re-emit when only restoreInProgress transitions to false. At 3c2682a, BackupRepo.startBackupStatusObservers (lines 494-502) combines restoreInProgress only for BackupCategory.SPARK_EXIT; line 497 leaves WALLET, METADATA, and every other category on the status flow alone. WALLET and METADATA marked via PrivatePaykitAddressReservationRepo.markPublicAddressBackupRequired (lines 122, 510-519) therefore remain unscheduled until a later status mutation or observer restart, and BackupRepo.getMetadataBackupDataBytes (lines 1354-1358) refuses a METADATA replacement while WALLET.isRequired is true and quarantined public addresses exist. This non-Spark observer gap already existed at base 1ffad41 (BackupRepo.kt:342-360, where no category combined restoreInProgress) and is neither introduced nor widened by this PR; it remains open rather than tracked_separately because a focused GitHub issue search found no open same-repository tracking issue. Already reported in #1686 (comment); that comment's device run and test patch were not repeated here.
  • [MEDIUM] Retry cannot refresh an expired session for a failed pubky profile delete — The expired-session profile-delete retry concern remains open. The integration update on this PR carries forward the original discussion after #1689 merged into this branch. At the reviewed revision, the delete still calls the service directly without session renewal.

Reviewer model: gemini-4-neon
Reasoning effort: high

Comment thread changelog.d/next/1688.fixed.md Resolved
@piotr-iohk

Copy link
Copy Markdown
Collaborator

@ben-kaufman please resolve conflicts.

@jvsena42

Copy link
Copy Markdown
Member

@ben-kaufman this conflicts with master; please rebase. I'll review it again once it merges cleanly.

…y-background

Conflicts:
- LightningRepo: master's config-change guards and whileStartPending sit
  inside this branch's vssClients.withWallet wrappers, with the wallet
  admission check, receipt cancellation and batched VSS deletes kept.
- CoreService: the Lightning write stays in this branch's receipt commit;
  master's retried move-part drop runs after a non-success write.
- WalletRepo: master's invoice payment hash is set inside this branch's
  wallet-owned cache load.
- Strings, imports, journeys and tests keep both sides; master's new move
  tests pass their payments as a provider, as the sync now takes.

Verified: testDevDebugUnitTest on the merged tree; detekt passes with the next commit
LightningRepo.start launched Spark and registered the caller's event
handler before the lifecycle lock checked the pending wallet reset, so a
retained or unreadable reset marker still let Spark connect and sync into
that wallet. Both now wait for wallet admission, and the lock's refusal
checks move into startRefusal.

Verified: testDevDebugUnitTest (extended pending-wipe test fails on the previous LightningRepo, passes here) and just lint
The on-chain receive and confirmation handlers wrapped their receipt work
in runCatching, so a wallet change that cancelled them was logged as an
error. They now use runSuspendCatching, as the replacement handler does.

Verified: testDevDebugUnitTest and just lint
Verified: none (changelog text only)
Checking admission before the lock left a window in which a reset that
began meanwhile still let Spark start; Spark and the caller's handler now
start right after the lock's refusal checks pass.

Verified: testDevDebugUnitTest and just lint
A wallet reset retires pending backups on Android, so the fragment no
longer says they survive it.

Verified: none (changelog text only)
@ovitrif

ovitrif commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Merged master into this PR in 077de6d to clear the conflicts, then pushed the review fixes (head 5c7df26).

  • Conflicts in LightningRepo, CoreService, WalletRepo, PubkyRepo, EditProfileScreen/EditProfileViewModel, the profile journey and 15 string files: master's changes are kept and this PR's edits are replayed on top (master's vssClients.withWallet wrapping, the new suspend move-part provider in the tests, strings as a union of both sides).
  • processBolt11 keeps master's receipt flow and drops a retried move part again when the payment has not succeeded.
  • testDevDebugUnitTest and just lint pass on the head.

This PR stays on hold until these are settled:

@ovitrif
ovitrif requested review from a team and piotr-iohk November 29, 2026 19:01
@ovitrif

ovitrif commented Nov 29, 2026

Copy link
Copy Markdown
Collaborator

Moved to 3.3.0: the HIGH terminal identity finding needs a restore contract change, and the VSS auth wait needs synonymdev/vss-rust-client-ffi#36, then a vss-client release and pin bumps in both apps. Neither can land before the 3.2.0 release, and 3.2.0 RC1 is already cut without this PR.

@ovitrif ovitrif modified the milestones: 3.2.0, 3.3.0 Nov 29, 2026

@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: ⛔️ Request changes — the terminal WALLET availability failure and stalled-authentication Reset failure remain. No new delta defect found.

Findings:

QA for 5c7df26:

Built the pristine head and ran the affected JVM classes. Device cases use an isolated, unfunded Android 16/API 36 development wallet, staging Pubky/VSS, and unpublished Debug controls for faults and readback. Installed APK hashes were checked; all eleven native libraries match the pristine APK. Videos play at 2×. Hidden-state claims are established by the stated app/native readbacks and logs.

Show a queued Settings backup until acknowledgement ✅ Changing USD to GBP showed Settings Running during debounce, then Latest Backup: now without Settings Retry, with the real VSS acknowledgement checked in app logs.

Installed head plus Debug-only tools; no scheduler or native code changes.

j3-backup-status-2x.2x.mp4

Keep Spark stopped while wallet reset needs recovery ✅ Retained WALLET_WIPE and unreadable markers both refused startup with ProfileRemovalPending, zero Spark starts, disconnected Spark, stopped LDK and no new event handler; recovery stayed restricted across restart.

Debug controls stage only durable marker state and count real SparkRepo.start entries; production admission is unchanged. Readback and logs establish hidden-state assertions.

pending-reset-2x.2x.mp4

Back up ordinary changes after terminal identity failure ❌ A new ordinary watch-only reservation stayed pending with real remote WALLET bytes/version unchanged after terminal identity failure; restoring original credentials allowed complete upload.

Existing HIGH reproduced with a controlled invalid saved session and no recovery secret. Real SDK/VSS capture and repair are checked in Debug readback/logs.

terminal-wallet-2x.2x.mp4

Finish Reset while native authentication is held ❌ Reset retained credentials and closed admission at 195.9 seconds after confirmation; releasing the real native auth response allowed cancellation, credential erasure and onboarding 7.2 seconds later.

Existing MEDIUM reproduced on VSS 0.5.26-rc3. Only a forwarding proxy held the real authentication response; no Kotlin held-poll or fake native result. Timing/state checked in app/proxy logs.

The recorder joined two consecutive portions; elapsed times come from the app/proxy readbacks.

stalled-native-auth-2x.2x.mp4

Complete an interrupted Reset after credentials were erased ✅ An injected local finalization failure after credential erasure kept restricted recovery across restart; a fresh Reset Wallet confirmation completed cleanup and reached onboarding.

Debug fault is injected only after wipeLocal succeeds and before completing its durable marker. WipeIncomplete/cause, missing credentials and cold UI route were checked in logs/readback; no SDK result was faked.

reset-erased-retry-2x.2x.mp4

Check: affected regressions and review fixes ✅ The pristine build and affected JVM classes passed.

Ran assembleDevDebug and the complete LightningRepoTest, BackupRepoTest, PubkyRepoTest, WipeWalletUseCaseTest, ActivityServiceTest, ActivityServiceLightningMessageTest and ActivityServiceMoveToSparkTest classes before adding controls. The on-chain receive/confirmation paths now propagate cancellation through runSuspendCatching; the consolidated PR has one changelog fragment. Full-suite, lint and Compose instrumentation were not repeated.

Check: retained journey evidence ✅ Earlier passes retain their original revisions and limits.

These are attributed executions, not a fresh uninterrupted J1 or a rerun of every manual case at 5c7df26. The existing expired-session profile-deletion Retry concern remains open. The deferred journey-documentation issue synonymdev/bitkit-android#1766 is not reopened.

Not driven: real Ring application UI and an actual unilateral Spark exit; they require external application/protocol or funded exit scenarios beyond the changed paths. Earlier contract-based Ring and controlled exit-record results retain their stated limits.

Scope: contiguous 3c2682a..5c7df26, merge composition and open findings. Receipt cancellation and changelog changes received source/component checks; no separate device cancellation injection was run. LDK rc83/VSS rc3 add the fixed LNURL-auth signing domain; staging native setup and VSS calls ran with these pins.

Twin: synonymdev/bitkit-ios#1121 fix: decouple wallet restore from profile refresh, checked at 75da1b2, also schedules optional identity initialization after required restore and retains the same complete-WALLET identity guard. Android preserves an already-active restored session; iOS clears authenticated presentation before scheduling initialization. No iOS device run is claimed here.

Unpublished Debug controls and deciding readbacks

Not pushed. The controls stage only disposable identity/recovery state, count actual Spark start entries, inject a one-shot local finalization failure, and read actual SDK/VSS results. The forwarding proxy holds the genuine standalone LDK authentication response. The first build served backup-status, pending-reset and terminal-identity cases; the final build adds only the post-erasure finalization fault. All native libraries remain pristine.

diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 6532aa144..0c551c48e 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -41,6 +41,7 @@ class DevToolsProvider : ContentProvider() {
 
     override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
         check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+        if (method.startsWith("qa1686")) return kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) { Qa1686.run(requireNotNull(context), method, arg) } // test hook
         return runCatching {
             val command = requireNotNull(DevCommand.parse(method, arg)) { "Unknown command: '$method'" }
             ServiceQueue.LDK.blocking { command.execute(deps) }
diff --git a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
index 259d689d6..52ec715f3 100644
--- a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
+++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
@@ -57,7 +57,7 @@ class VssBackupClientLdk @Inject constructor(
                         storeId = vssDeriveStoreId(Env.vssStoreIdPrefix, mnemonic, passphrase),
                         mnemonic = mnemonic,
                         passphrase = passphrase,
-                        lnurlAuthServerUrl = Env.lnurlAuthServerUrl,
+                        lnurlAuthServerUrl = if (to.bitkit.BuildConfig.DEBUG && java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-auth-override").exists()) "http://127.0.0.1:23469/lnurl_auth/auth" else Env.lnurlAuthServerUrl, // test hook
                         keyDomain = Env.lnurlAuthKeyDomain,
                     )
                     Logger.info("VSS LDK client setup for wallet[$walletIndex]", context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
index 81ffbfec7..49686515f 100644
--- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
@@ -297,6 +297,7 @@ class SparkRepo @Inject constructor(
     val walletWiped: SharedFlow<Int> = _walletWiped.asSharedFlow()
 
     suspend fun start(walletIndex: Int): Result<Unit> = withContext(bgDispatcher) {
+        if (to.bitkit.BuildConfig.DEBUG) { val f=java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-spark-start-count"); if (f.exists()) f.writeText((f.readText().toInt()+1).toString()) } // test hook
         if (!sparkService.isSupported) return@withContext Result.success(Unit)
         this@SparkRepo.walletIndex = walletIndex
         // A retry reads as connecting until it fails again.
diff --git a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
index 1702de847..530412bef 100644
--- a/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
+++ b/app/src/main/java/to/bitkit/usecases/WipeWalletUseCase.kt
@@ -102,6 +102,10 @@ class WipeWalletUseCase @Inject constructor(
                                     profileRemovalStore.begin(attemptId)
                                     if (pending.scope != ProfileRemovalScope.WALLET_WIPE) cleanupRemote()
                                     wipeLocal(walletIndex, pause) { credentialsMayBeErased = true }.getOrThrow()
+                                    if (to.bitkit.BuildConfig.DEBUG) { // test hook
+                                        val fault=java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-fail-finalize") // test hook
+                                        if(fault.exists()) { fault.delete(); throw java.io.IOException("QA finalization fault after credential erase") } // test hook
+                                    } // test hook
                                     profileRemovalStore.complete(attemptId)
                                     resetWalletState()
                                     onSuccess()
diff --git a/app/src/debug/java/to/bitkit/dev/Qa1686.kt b/app/src/debug/java/to/bitkit/dev/Qa1686.kt
new file mode 100644
index 000000000..c1fd3bcae
--- /dev/null
+++ b/app/src/debug/java/to/bitkit/dev/Qa1686.kt
@@ -0,0 +1,175 @@
+package to.bitkit.dev // test hook
+
+import android.content.Context // test hook
+import android.content.ClipData // test hook
+import android.content.ClipboardManager // test hook
+import android.os.Bundle // test hook
+import dagger.hilt.EntryPoint // test hook
+import dagger.hilt.InstallIn // test hook
+import dagger.hilt.android.EntryPointAccessors // test hook
+import dagger.hilt.components.SingletonComponent // test hook
+import kotlinx.coroutines.Dispatchers // test hook
+import kotlinx.coroutines.flow.first // test hook
+import kotlinx.coroutines.withContext // test hook
+import to.bitkit.data.CacheStore // test hook
+import to.bitkit.data.backup.VssBackupClient // test hook
+import to.bitkit.data.keychain.Keychain // test hook
+import to.bitkit.models.BackupCategory // test hook
+import to.bitkit.repositories.BackupRepo // test hook
+import to.bitkit.repositories.PubkyRepo // test hook
+import to.bitkit.repositories.WalletRepo // test hook
+import to.bitkit.repositories.LightningRepo // test hook
+import to.bitkit.services.PubkyService // test hook
+import to.bitkit.di.json // test hook
+import to.bitkit.models.WalletBackupV1 // test hook
+import to.bitkit.utils.Logger // test hook
+import java.io.File // test hook
+import kotlinx.coroutines.*
+import to.bitkit.models.*
+import to.bitkit.repositories.*
+import to.bitkit.services.*
+import kotlin.time.Clock
+
+object Qa1686 { // test hook
+    private var replacementPhrase: String? = null
+    private val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)
+    @EntryPoint @InstallIn(SingletonComponent::class) // test hook
+    interface Dependencies { // test hook
+        fun removal(): to.bitkit.data.ProfileRemovalStore
+        fun sparkExit(): SparkExitRepo
+        fun spark(): SparkRepo
+        fun sparkService(): SparkService
+        fun recovery(): to.bitkit.data.WalletConnectionRecovery
+        fun vssClients(): to.bitkit.data.backup.VssClientCoordinator
+        fun vssLdk(): to.bitkit.data.backup.VssBackupClientLdk
+        fun sdk(): to.bitkit.services.PaykitSdkService
+        fun allowanceExecutor(): to.bitkit.repositories.PaykitAllowanceExecutor
+        fun privatePaykit(): to.bitkit.repositories.PrivatePaykitRepo
+        fun allowances(): to.bitkit.repositories.PaykitAllowanceRepo
+        fun allowanceStore(): to.bitkit.repositories.PaykitAllowanceStore
+        fun keychain(): Keychain // test hook
+        fun backupRepo(): BackupRepo // test hook
+        fun pubkyRepo(): PubkyRepo // test hook
+        fun pubkyService(): PubkyService // test hook
+        fun vss(): VssBackupClient // test hook
+        fun cache(): CacheStore // test hook
+        fun wallet(): WalletRepo // test hook
+        fun accounts(): to.bitkit.data.WatchOnlyAccountStore
+        fun settings(): to.bitkit.data.SettingsStore
+        fun nodeService(): LightningService
+        fun lightning(): LightningRepo // test hook
+    } // test hook
+    suspend fun run(context: Context, method: String, arg: String?): Bundle { // test hook
+        val d = EntryPointAccessors.fromApplication(context, Dependencies::class.java) // test hook
+        fun file(name: String) = File(context.filesDir, "qa1686-$name")
+        val result = kotlin.runCatching { // test hook
+            when (method) {
+                "qa1686PendingSetup" -> {
+                    d.backupRepo().stopObservingBackups()
+                    d.lightning().stop().getOrThrow()
+                    d.sparkService().disconnect()
+                    check(!d.sparkService().isConnected)
+                    val attempt = java.util.UUID.randomUUID().toString()
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) {
+                        d.removal().begin(attempt)
+                    }
+                    file("spark-start-count").writeText("0")
+                    "pending=${d.removal().walletResetRecovery.first()}; sparkConnected=${d.sparkService().isConnected}"
+                }
+                "qa1686PendingStart" -> {
+                    val handlers = d.lightning().javaClass.getDeclaredField("_eventHandlers").apply { isAccessible=true }
+                    val before = (handlers.get(d.lightning()) as Collection<*>).size
+                    val result = d.lightning().start(eventHandler = {})
+                    delay(1500)
+                    val after = (handlers.get(d.lightning()) as Collection<*>).size
+                    val starts = file("spark-start-count").readText().toInt()
+                    check(result.exceptionOrNull() is to.bitkit.data.ProfileRemovalPending)
+                    check(starts == 0 && before == after && !d.sparkService().isConnected)
+                    "refused=${result.exceptionOrNull()?.javaClass?.simpleName}; sparkStarts=$starts; connected=${d.sparkService().isConnected}; handlersBefore=$before; handlersAfter=$after; node=${d.lightning().lightningState.value.nodeLifecycleState}"
+                }
+                "qa1686PendingUnreadable" -> {
+                    val attempt=requireNotNull(d.removal().pendingAttempt())
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) { d.removal().complete(attempt) }
+                    val dir=File(context.filesDir,"datastore")
+                    val f=File(dir,"profile_removal.json")
+                    check(f.exists())
+                    "CLEAR: restart required before staging unreadable datastore on disk"
+                }
+                "qa1686PendingClear" -> {
+                    val attempt=requireNotNull(d.removal().pendingAttempt())
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) { d.removal().complete(attempt) }
+                    "cleared disposable reset marker"
+                }
+                "qa1686Dev" -> { d.settings().update { it.copy(isDevModeEnabled = true) }; "enabled developer mode" }
+                "qa1686NativeAuth" -> {
+                    d.backupRepo().stopObservingBackups()
+                    d.vssClients().withSuspendedClients {}
+                    file("auth-override").writeText("hold")
+                    d.vssLdk().setup().getOrThrow()
+                    file("native-result").delete()
+                    scope.launch {
+                        try {
+                            val result = d.vssLdk().getObject("qa1686-held-auth")
+                            file("native-result").writeText("returned success=${result.isSuccess}; error=${result.exceptionOrNull()?.javaClass?.simpleName}")
+                        } catch(e: Exception) { file("native-result").writeText("cancelled=${e.javaClass.simpleName}") }
+                    }
+                    "scheduled actual standalone LDK lookup against held auth response"
+                }
+                "qa1686NativeState" -> "credentialsPresent=${d.keychain().exists(Keychain.Key.BIP39_MNEMONIC.name)}; wiping=${d.backupRepo().isWiping.value}; admissionOpen=${runCatching { d.vssClients().captureOwner() }.isSuccess}; result=${file("native-result").takeIf { it.exists() }?.readText()}"
+                "qa1686Backup" -> {
+                    for (c in listOf(BackupCategory.WALLET, BackupCategory.METADATA, BackupCategory.SETTINGS)) d.backupRepo().triggerBackup(c).getOrThrow()
+                    val wallet = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val metadata = requireNotNull(d.vss().getObject("METADATA").getOrThrow())
+                    val pending = d.cache().backupStatuses.first().filterKeys { it in listOf(BackupCategory.WALLET, BackupCategory.METADATA) }.any { it.value.isRequired }
+                    check(!pending)
+                    "backup synchronized; sdk=${json.decodeFromString<WalletBackupV1>(wallet.value.decodeToString()).paykitSdkBackupState != null}; metadataBytes=${metadata.value.size}"
+                }
+                "qa1686Terminal" -> {
+                    d.backupRepo().stopObservingBackups()
+                    val secret = requireNotNull(d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name))
+                    File(context.filesDir, "qa1686-original-secret").writeText(secret)
+                    val session = requireNotNull(d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name))
+                    File(context.filesDir, "qa1686-original-session").writeText(session)
+                    d.pubkyService().forgetSessionAccess()
+                    d.keychain().delete(Keychain.Key.PUBKY_SECRET_KEY.name)
+                    d.keychain().upsertString(Keychain.Key.PAYKIT_SESSION.name, "qa1686-invalid-session")
+                    d.pubkyRepo().initialize().getOrThrow()
+                    check(d.pubkyRepo().publicKey.value == null)
+                    val before = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val reserved = d.accounts().reserveAccountIndex(0, "qa1686-terminal-ordinary")
+                    check(d.accounts().backupSnapshot().allocationState.highestAccountIndexByWallet["0"] == reserved)
+                    val failed = d.backupRepo().triggerBackup(BackupCategory.WALLET)
+                    val after = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val same = before.value.contentEquals(after.value) && before.version == after.version
+                    val pending = d.cache().backupStatuses.first()[BackupCategory.WALLET]?.isRequired == true
+                    check(failed.isFailure && same && pending)
+                    "terminal=true; ordinary watch-only index=$reserved reserved; failed=true; remote unchanged=true; pending=true; error=${failed.exceptionOrNull()?.javaClass?.simpleName}"
+                }
+                "qa1686RepairIdentity" -> {
+                    d.keychain().upsertString(Keychain.Key.PUBKY_SECRET_KEY.name, File(context.filesDir, "qa1686-original-secret").readText())
+                    d.keychain().upsertString(Keychain.Key.PAYKIT_SESSION.name, File(context.filesDir, "qa1686-original-session").readText())
+                    d.pubkyRepo().initialize().getOrThrow()
+                    d.backupRepo().triggerBackup(BackupCategory.WALLET).getOrThrow()
+                    "recovered original identity and complete WALLET upload"
+                }
+                "qa1686Recover" -> { // test hook
+                    val secret = d.pubkyService().deriveSecretKey(requireNotNull(d.keychain().loadString(Keychain.Key.BIP39_MNEMONIC.name))) // test hook
+                    d.keychain().upsertString(Keychain.Key.PUBKY_SECRET_KEY.name, secret) // test hook
+                    d.pubkyService().initialize() // test hook
+                    d.pubkyRepo().restoreSessionBackupState(to.bitkit.models.PubkySessionBackupV1(kind = to.bitkit.models.PubkySessionBackupKind.LocalSeed)).getOrThrow() // test hook
+                    d.pubkyRepo().scheduleInitializationAfterRestore() // test hook
+                    d.backupRepo().triggerBackup(BackupCategory.WALLET).getOrThrow() // test hook
+                    d.backupRepo().startObservingBackups() // test hook
+                    "recovered identity and fresh complete backup" // test hook
+                } // test hook
+                "qa1686CreateProfile" -> {
+                    d.pubkyRepo().createIdentity("QA restore", "", emptyList(), emptyList(), null).getOrThrow()
+                    "created disposable profile"
+                }
+                else -> "source=${d.keychain().exists(Keychain.Key.SHARED_PUBKY_SOURCE.name)}, savedSecret=${!d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name).isNullOrBlank()}, savedSession=${!d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name).isNullOrBlank()}, sdk=${d.pubkyService().currentPublicKey() != null}, identity=${d.pubkyRepo().publicKey.value != null}, profile=${d.pubkyRepo().profile.value?.name}, contacts=${d.pubkyRepo().contacts.value.size}, pendingRestore=${d.backupRepo().hasPendingWalletRestore()}, node=${d.lightning().lightningState.value.nodeLifecycleState}" // test hook
+            } // test hook
+        }.fold({ it }, { "ERROR: ${it.javaClass.simpleName}: ${it.message}" }) // test hook
+        Logger.info("QA1686 $method: $result", context="TestHook") // test hook
+        return Bundle().apply { putString("result", result) } // test hook
+    } // test hook
+} // test hook

The authentication forwarding proxy:

from http.server import ThreadingHTTPServer,BaseHTTPRequestHandler
import urllib.request,time,pathlib,threading
root=pathlib.Path(__file__).parent
end=time.monotonic()+900
class Handler(BaseHTTPRequestHandler):
 def log_message(self,*args): pass
 def do_GET(self):
  with open(root/'auth-events.log','a') as f:f.write(f'{time.time():.3f} native auth request received\n')
  while (root/'hold-auth').exists() and time.monotonic()<end: time.sleep(.1)
  try:
   with urllib.request.urlopen('https://bitkit.stag0.blocktank.to'+self.path, timeout=30) as r:
    data=r.read();self.send_response(r.status);self.send_header('Content-Type',r.headers.get('Content-Type','application/json'));self.end_headers();self.wfile.write(data)
   with open(root/'auth-events.log','a') as f:f.write(f'{time.time():.3f} forwarded response delivered\n')
  except Exception as e:
   self.send_response(502);self.end_headers()
   with open(root/'auth-events.log','a') as f:f.write(f'{time.time():.3f} forward error {type(e).__name__}\n')
server=ThreadingHTTPServer(('127.0.0.1',23469),Handler)
threading.Timer(900,server.shutdown).start()
server.serve_forever()
Retained WALLET_WIPE: ProfileRemovalPending; Spark starts=0; connected=false; handlers 0 -> 0; LDK Stopped.
Unreadable marker after restart: same refusal, zero starts and unchanged handlers.
Terminal identity: ordinary watch-only index 1 reserved; capture failed; remote bytes/version unchanged; WALLET required.
Original credential repair: complete WALLET upload succeeds.
Held authentication: credentials present, wiping=true, admission closed at 195.9 s after Reset confirmation.
Response released at 214.3 s; 7.2 s later credentials absent, wiping=false, admission open; native lookup cancelled.
Injected finalization IOException: WipeIncomplete after credentials erased; durable recovery route survives restart.
Fresh cold Reset confirmation: credentials absent, admission open, onboarding reached.


Reviewed by gpt-6.1-sol-high

@piotr-iohk piotr-iohk 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.

QA review

Scope: full PR at 5c7df26f, re-reviewed after the comparison base changed from 1ffad418 to 6d968301 and the new base touches the backup, restore, and profile files.

1 actionable finding — resolve or provide an evidence-backed rebuttal.

No actionable code findings. Wallet restore still finishes required wallet and USDT recovery before optional Pubky activation. A full WALLET upload still fails closed while a saved identity cannot be exported, and that pending backup is kept. That matches journeys/wallet/restore-during-identity-outage.xml. VSS work stays on the captured wallet, profile removal does not replay remote deletion from the durable marker, and an interrupted wallet reset stays on the recovery route. Spark balance updates while Lightning is stopped are isolated so a wallet-owner cancellation does not stop later updates. The payment result routes do not show the connecting overlay.

Compared with twin bitkit-ios#1121 at 75da1b24 for the shared restore and connection-recovery journeys only. Both descriptions already record that iOS restores required backup state before starting a rebuilt node, while Android can need a running node during restoration.

Device testing: not performed in this review. J1 and manual cases 1–6 still need the controlled fault fixtures described in the PR QA notes.

Earlier findings reconciled at this revision: 4 still present, 3 verified fixed, 1 not substantiated.

Findings

  • [MEDIUM] Bound native authentication before draining VSS during reset — inline at app/src/main/java/to/bitkit/data/backup/VssClientCoordinator.kt:138. Still present from the earlier review.

Existing concerns

  • [LOW] Allowance journey describes a delayed-contact check its actions do not perform — The journey description still tells the runner to repeat the off/on sequence while contact loading is delayed, and the action list still does not do that. The GitHub thread #1686 (comment) is marked resolved; the author reply says it is out of scope and tracked in #1766. That resolution leaves the mismatched sentence in this PR's diff against 6d96830. #1766 is open.
  • [MEDIUM] Backups required during restore stay unscheduled after restore — A non-SPARK_EXIT backup marked required while restore is in progress is still not scheduled when restore ends. shouldBackup is false while restoring, the status observer drops that emission, and distinctUntilChanged does not emit again when only the restore flag changes. At this head, startBackupStatusObservers combines restoreInProgress only for SPARK_EXIT; every other category stays on the status flow. This non-Spark gap already exists at 6d96830, where no category combined restoreInProgress. This PR adds the Spark-only resume and does not introduce or widen the other categories. A focused issue search found no open same-repository issue for this observer gap, so it is not tracked_separately. The existing report is #1686 (comment). That comment's device run was not repeated here.
  • [MEDIUM] Retry cannot refresh an expired session for a failed pubky profile delete — A failed pubky profile delete still cannot refresh an expired session on retry. The thread #1689 (comment) is unresolved; its anchor is outdated. deleteProfile calls pubkyService.deletePubkyProfile directly. refreshSessionIfPossibleLocked is private and is used by withPubkyAppScopeLocked, which this delete path does not call. ProfileRemovalCoordinator.reviewAgain re-reads the profile and remove calls the same deleteProfile. PaykitSdkService.completeSdkCall does not refresh a session after PaykitException.Identity. An expired session therefore fails the delete again on Retry.

Reviewer model: grok-4.7
Reasoning effort: xhigh

try {
withContext(NonCancellable) {
pending.forEach { it.cancel(CancellationException("VSS wallet retired")) }
pending.joinAll()

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.

[MEDIUM] Bound native authentication before draining VSS during reset

When a standalone VSS request needs a fresh JWT and the LNURL-auth server holds its response, starting Reset and Restore would wait indefinitely here. The pinned VSS execute_async! bridge runs Runtime::block_on inside the synchronous UniFFI poll. Its vss-client-ng 0.4.0 authentication client has no timeout; the VSS request deadline starts only afterward. Cancelling the Kotlin job cannot finish that blocked poll, so this NonCancellable join never reaches shutdown or credential deletion. ResetAndRestoreScreen keeps Reset loading and disables Back while isWiping remains true; admission also stays closed. Bound native authentication while retaining drain-before-retirement, for example by adopting a release containing VSS #36, and add a stalled-auth reset regression. Evidence: pinned source analysis, checksum-verified dependency sources, and a focused Kotlin test using the real coordinator with a held synchronous-poll surrogate. No actual-native or device reproduction was performed. This adds Android-specific cancellation evidence to the shared iOS concern.

Still present at 5c7df26 (first reported at b5d5858): Reset still waits on a held LNURL-auth response before it can shut the standalone VSS clients down or delete credentials. The thread #1686 (comment) is unresolved and its anchor is current. WipeWalletUseCase.kt:85-120 sets wiping before withIdentityChange and clears it only in finally after that call returns. The coordinator join at VssClientCoordinator.kt:136-139 is NonCancellable and reaches shutdown only after every admitted job returns. VssBackupClientLdk.kt:55-61 and VssBackupClient.kt:72-73 pass keyDomain into the rc3 client, whose key-domain provider has no request timeout, and execute_async still runs Runtime::block_on. Cancelling the Kotlin job therefore leaves that blocked poll running. ResetAndRestoreScreen.kt:76, :81, :114, and :122 keep Back disabled and Reset loading while isWiping stays true. The reviewer reports, at this head, that Reset still retained credentials and closed admission 195.9 seconds after confirmation until the held response was released; that run was not repeated here. This is the same mechanism as synonymdev/bitkit-ios#1121 (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.

Reproduced at ae66286 with real standalone native authentication: Reset retained credentials and closed admission at 196.0 seconds after confirmation. Releasing the held response at 214.4 seconds permitted native cancellation and completion 25.5 seconds later. VSS 0.5.26-rc3 still lacks the native deadline fix; this remains open.

@piotr-iohk

Copy link
Copy Markdown
Collaborator

@ben-kaufman please resolve conflicts.

…y-background

Keeps this PR's start ordering in LightningRepo.startNode (Spark and the
caller's handler join only after the lock's refusal checks) and adds
master's dropStoppedNode() and detached connectMovedPeers().

Verified: testDevDebugUnitTest and just lint
@ovitrif

ovitrif commented Nov 30, 2026

Copy link
Copy Markdown
Collaborator

Merged master into this PR in ae66286 to clear the new conflict. The only conflict was LightningRepo.startNode: this PR's start ordering stays (Spark and the caller's handler join only after the lock's refusal checks), and master's dropStoppedNode() and detached connectMovedPeers() are added. testDevDebugUnitTest and just lint pass on the merge.

@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: ⛔️ Request changes — the existing terminal WALLET and held-authentication Reset failures remain. No new delta defect found.

Findings:

QA for ae66286:

Built the pristine head and ran the affected JVM regressions. Device cases use an isolated, unfunded Android 16/API 36 development wallet, real staging SDK/VSS services, and unpublished Debug controls for fault placement and readback.

Installed APK hashes were verified; the controlled APKs retain pristine native libraries. Videos play at 2×. Hidden-state claims below use the stated app/native readbacks and logs.

Replace a native node that has stopped ✅ Production startup replaced a real stopped native node with a distinct running instance and retained its handler count (native readback).

An unpublished Debug hook called the actual native Node.stop(), then production LightningRepo.start. Native-object identity/status and handler-count readbacks established that a distinct running node replaced the stopped one. No Rust panic was injected.

stopped-node-restart-2x.2x.mp4

Back up ordinary changes after terminal identity failure ❌ After terminal identity failure, a new ordinary reservation stayed pending with the remote WALLET unchanged until the original credentials were restored (SDK/VSS readback).

With a synchronized complete backup, a Debug control removed the local identity recovery secret and installed an invalid saved session. A new ordinary watch-only reservation remained pending while real remote WALLET bytes/version remained unchanged. Restoring the original credentials allowed a complete WALLET upload; native/app readbacks and acknowledgements establish these hidden states.

terminal-wallet-2x.2x.mp4

Keep Spark stopped while wallet reset needs recovery ✅ Retained and unreadable reset markers refused startup before Spark/handler admission, with restricted recovery after restart (app readback).

Debug controls staged a retained WALLET_WIPE marker and, separately, an unreadable marker across process restart. Production admission refused both before real Spark startup or caller-handler registration; readbacks established zero starts, disconnected Spark and stopped LDK. The recording shows the restricted recovery route.

pending-reset-2x.2x.mp4

Finish Reset while native authentication is held ❌ Reset remained blocked at 196.0 seconds and completed 25.5 seconds after the held authentication response was released (app/proxy readback).

A forwarding proxy held a real standalone LDK authentication response. App readbacks retained credentials, wiping=true and closed admission at 196.0 seconds after Reset confirmation. Release at 214.4 seconds allowed the old native call to cancel and Reset to finish 25.5 seconds later. The recording shows the wait; app/proxy logs establish state and timing.

stalled-native-auth-2x.2x.mp4

Retry profile deletion after the current grant expires ❌ Delete and Review stayed unavailable after genuine grant expiry with original credentials unchanged, yielding Transport/HTTP 401 rather than Identity (readback and retained exception).

The fixture signed a genuine four-minute grant with the disposable identity’s existing root, preserving its client/capabilities, and imported it through the normal native API. A Debug hold at the first Pubky-delete boundary waited for that signed expiry; it fabricated no service error or SDK result. Review returned to the same failure dialog without preparing a fresh confirmation. The native cause was PaykitException.Transport from acquiring the Pubky write lock (HTTP 401); this does not reproduce the earlier Identity-specific claim. Keychain readback retained the original root/session bytes, and the native Pubky-delete attempt count stayed at one after Review. The continuation resumes at the retained failure dialog; the debugger only inspected the already-retained exception. The original Identity-specific Retry concern remains source-only.

expired-profile-delete-retry-2x.2x.mp4

expired-profile-delete-retry-continuation-2x.2x.mp4

Check: build and affected regressions ✅ The pristine head builds and its targeted backup, identity, wallet and native-lifecycle regressions pass.

Ran assembleDevDebug and :app:testDevDebugUnitTest for BackupRepoTest, PubkyRepoTest, WalletRepoTest, LightningRepoTest and LightningServiceTest, with no failures or skips. Full-suite, lint and Compose instrumentation were not repeated.

Retained earlier case evidence Prior executions keep their original heads and fault-control limits.

Not driven: an actual Rust panic (the real native stop exercised the replacement branch), external Ring application UI, an actual unilateral Spark exit, and a native failed-balance-read fault. Master-only NFC, QuickPay/contact recreation, peer-move networking and force-close accounting changes received source review; these device cases exercise the restore/reset integration.

Coverage: contiguous delta 5c7df26..ae66286 plus outstanding findings and historical case reconciliation; the complete PR description and discussion were read. The deferred allowance-documentation issue and the separately reported base observer bug retain their existing disposition.

Twin: synonymdev/bitkit-ios#1121 at 75da1b2 matches the required-wallet/USDT-before-optional-identity contract and guarded missing-profile recovery. Startup order differs: iOS restores before starting its rebuilt node; Android can need a running node during restoration. No iOS device run is claimed here.


Reviewed by gpt-6.1-sol-high

@piotr-iohk

Copy link
Copy Markdown
Collaborator

@ben-kaufman please resolve conflicts.

…y-background

Master removed move to Spark and the Boltz savings swap. This PR's edits
to that code go with it: the retried move-part drops, the self-payment
replacement and the fee refresh in processBolt11, the swap stream in
WalletViewModel, the move tests and their metadata backup tests. Lightning
max send uses master's larger-of-channels-or-Spark cap everywhere,
including this PR's channel-change and recovery paths.

Verified: testDevDebugUnitTest and just lint
@ovitrif

ovitrif commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

Merged master into this PR in bc6b171 to clear the conflicts from master's removal of move to Spark and the Boltz savings swap.

  • This PR's edits to the removed code go with it: the retried move-part drops, the self-payment replacement and fee refresh in processBolt11, the swap stream in WalletViewModel, ActivityServiceMoveToSparkTest and the move-to-Spark metadata backup tests.
  • Lightning max send now uses master's cap (the larger of the channels' outbound limit and Spark's sendable balance) on this PR's channel-change and recovery paths too.
  • processBolt11 keeps this PR's receipt commit, the succeeded-row guard and the pending Spark-retry guard.
  • testDevDebugUnitTest and just lint pass on the merge.

@piotr-iohk piotr-iohk 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.

QA review

Scope: full PR at bc6b171d0954, re-reviewed after the comparison base changed and no completed baseline could be inherited.

No new actionable code findings.

No actionable code findings. Required wallet and USDT restore still finish before optional Pubky activation; a saved identity that cannot be exported fails the WALLET upload and leaves the previous remote record in place; profile removal stays bound to its attempt and does not replay on restart; a pending wallet wipe replaces the root UI, while a pending profile cleanup is shown on Profile (profile__cleanup_pending) and blocks session restore. A native VSS shutdown failure leaves backup admission closed until the process restarts; VssClientCoordinatorTest locks that in.

Compared with bitkit-ios#1121 at 3af88fff3ab2, only the shared restore, backup-admission, and profile-removal contracts. restore-during-identity-outage.xml matches. Connection recovery still rebuilds the Android node before required restore resumes, which that journey describes as the platform order. iOS reopens VSS admission if shutdown throws; this Android revision does not.

Device testing: not performed in this review. The author journeys that need a homeserver or VSS fault fixture were not executed. New English strings are present in every values-* catalog.

Earlier findings reconciled at this revision: 4 still present.

Existing concerns

  • [MEDIUM] Bound native authentication before draining VSS during reset — Reset still waits on a held LNURL-auth response before it can shut the standalone VSS clients down or delete credentials. GitHub review thread #1686 (comment) is unresolved and its anchor is current at VssClientCoordinator.kt:138. The later copy #1686 (comment) is also unresolved on that same line. WipeWalletUseCase.kt:83-92 sets wiping inside isStillNeeded before withIdentityChange, and the finally at lines 115-118 clears it only after that call returns. The coordinator join at lines 136-139 is NonCancellable and reaches vssShutdownClient and vssShutdownLdkClient only after every admitted job returns. Both b0a01b1 and this head pin com.synonym:vss-client-android 0.5.26-rc3 at gradle/libs.versions.toml:98. Tag v0.5.26-rc3 peels to 3baf76dda37126d313f85ed2298abd65f6ef62b2, whose execute_async macro at src/lib.rs:32-41 still runs Runtime::block_on, used by vss_get at line 209 and vss_ldk_get at line 477. Its key-domain provider at src/lnurl_auth.rs:147 builds reqwest::Client::builder().build() with no timeout, and fetch_jwt_token at lines 162-191 awaits the challenge and signed callback with no deadline. VssBackupClient.kt:73 and VssBackupClientLdk.kt:61 pass that key domain, and the LDK get at VssBackupClientLdk.kt:79 is admitted through withClient. Cancelling the Kotlin job therefore leaves that blocked poll running. ResetAndRestoreScreen.kt:76, :81, :114, and :122 keep Back disabled and Reset loading while isWiping stays true. synonymdev/vss-rust-client-ffi#36 is still open, mergedAt null, head 1a5b788ceabac22739a9c9deabef67fea071b644. This is the same mechanism as synonymdev/bitkit-ios#1121 (comment). The device reproductions reported at 5c7df26 and ae66286 were not repeated here.
  • [LOW] Allowance journey describes a delayed-contact check its actions do not perform — The journey description still tells the runner to repeat the off/on sequence while contact loading is delayed, and the action list still does one off, one request, and one on. The GitHub thread #1686 (comment) is marked resolved; the author reply says it is out of scope and tracked in #1766. That resolution leaves the mismatched sentence in this PR's diff against b0a01b1. #1766 is open, titled "docs: clarify delayed-contact coverage in the allowance toggle journey".
  • [MEDIUM] Backups required during restore stay unscheduled after restore — A non-SPARK_EXIT backup marked required while restore is in progress is still not scheduled when restore ends. shouldBackup is false while restoring, the status observer drops that emission, and distinctUntilChanged does not emit again when only the restore flag changes. At this head, startBackupStatusObservers combines restoreInProgress only for SPARK_EXIT; every other category stays on the status flow. This non-Spark gap already exists at b0a01b1, where no category combined restoreInProgress. This PR adds the Spark-only resume and does not introduce or widen the other categories. Focused issue searches returned no open same-repository issue for this observer gap, so it is not tracked_separately. The existing report is #1686 (comment). That comment's device run was not repeated here.
  • [MEDIUM] Retry cannot refresh an expired session for a failed pubky profile delete — A failed pubky profile delete still cannot refresh an expired session on retry. The thread #1689 (comment) is unresolved and its anchor is outdated. deleteProfile calls pubkyService.deletePubkyProfile directly. refreshSessionIfPossibleLocked is private and its only call is inside withPubkyAppScopeLocked, which this delete path does not call. ProfileRemovalCoordinator.reviewAgain prepares a new deletion and remove calls the same deleteProfile. PaykitSdkService.completeSdkCall does not refresh a session after PaykitException.Identity; invalidatePaykitKeyIfNeeded only clears the cached key. An expired session therefore fails the delete again on Retry.

Reviewer model: grok-4.7
Reasoning effort: xhigh

@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: ⛔️ Request changes — the existing terminal-WALLET and held-authentication Reset failures remain. No new delta defect found.

Findings:

QA for bc6b171:

Built and installed the pristine head, then drove an isolated, unfunded Android 16/API 36 development wallet against staging SDK/VSS services. Unpublished Debug controls place faults and expose readbacks; their native libraries match the pristine APK. Videos play at 2×. Hidden-state claims use the stated app/native/proxy readbacks.

Replace a native node that has stopped ✅ A real stopped native node was replaced by a distinct running node with event-handler count unchanged.

A Debug hook called real native Node.stop(), then production LightningRepo.start. Native-object identity/status and handler-count readbacks established replacement; the replacement delivered real SyncCompleted events to the app. No Rust panic was injected. The equivalent rc84 control at ae66286 also replaced the stopped node and retained handlers; no functional difference was observed in this empty-wallet fixture. Startup speed was not benchmarked.

stopped-node-restart-2x.2x.mp4

Keep a stale Spark balance out of spendable funds ✅ After a real native DNS sync error, production refresh retained a staged 5,000-sat display while native balance, Spark sendable and the settled wallet send limit were zero.

Manual 5’s remaining native-error boundary: device networking was disabled for a real Spark sync. The SDK call returned normally while emitting a native Network/DNS sync error and retaining GetInfo.lastSyncError. A prior 5,000-sat display was fixture data in an empty native wallet; production refresh retained it as keptBalanceSats, with native balance and Spark sendable zero. The wallet limit settled to zero after observer propagation; no native result was injected and no funds were sent.

native-spark-stale-read-2x.2x.mp4

Back up ordinary changes after terminal identity failure ❌ A new ordinary watch-only reservation remained pending and remote WALLET bytes/version stayed unchanged until the original identity credentials were restored.

A synchronized SDK-bearing complete backup existed before the fault. The Debug control removed the disposable local identity recovery secret and installed an invalid saved session, then reserved a new ordinary watch-only index. Real VSS readbacks compared WALLET bytes and version before/after; original-credential recovery then allowed the upload.

terminal-wallet-2x.2x.mp4

Finish Reset while native authentication is held ❌ Reset retained credentials and closed admission at 196.1 seconds after confirmation; it completed 26.1 seconds after releasing authentication (app/proxy readback).

A forwarding proxy held a genuine standalone LDK authentication response while the actual Settings Reset action ran. App/proxy logs establish the timing, credential retention and closed admission. Release permitted native cancellation and Reset completion.

stalled-native-auth-2x.2x.mp4

Retry profile deletion after the current grant expires ❌ After genuine grant expiry, Delete failed and repeated Review returned to the same failure without a fresh confirmation; original credentials and the single native delete-attempt count were unchanged (readback).

A genuine four-minute grant was signed with the disposable identity’s existing root and imported through the normal native API, preserving client/capabilities. A Debug hold delayed the first Pubky delete until actual expiry; it fabricated no SDK error. Current keychain exports and native-call counters establish credential retention and whether Review retried. This repeats the expiry-availability failure. The retained native exception category was not independently inspected in this run; the earlier Transport/HTTP 401 result remains attributed to the ae66286 execution. It does not establish the narrower Identity-specific Retry claim.

expired-profile-delete-retry-final-2x.2x.mp4

Check: pristine build and affected regressions ✅ The pristine head builds and the affected backup, identity, balance and native-lifecycle regressions pass.

Ran assembleDevDebug and testDevDebugUnitTest for BackupRepoTest, PubkyRepoTest, WalletRepoTest, LightningRepoTest and LightningServiceTest, with no failures or skips. Full-suite, lint and Compose instrumentation were not repeated.

Retained earlier case evidence These executions retain their original heads and control limits; the merge leaves their tested boundaries unchanged.

These are attributed constituent results, not a fresh uninterrupted J1 run or a new funded campaign. The deferred allowance-documentation issue and the separately reported base observer bug retain their disposition.

Not driven: an actual Rust panic, external Ring application UI or an actual unilateral Spark exit. The latter is not required by the retained Done/Failed display-state fixture. The upstream nearby fix, Boltz/Move-to-Spark removals, QuickPay and force-close changes received source review; these device cases exercise restore/reset integration and the stated Spark guard.

Coverage: contiguous delta ae66286..bc6b171 plus outstanding findings. The complete PR description, comments, reviews and inline discussion were read. Removed functionality’s tests were inspected with its removal; no new test skip or workflow weakening was added.

Twin: synonymdev/bitkit-ios#1121 at 3af88ff matches required wallet/USDT recovery before optional profile work and the complete-backup guard. iOS restores before starting its rebuilt node; Android can require a running node during restoration. Dependency difference: Android uses LDK rc85, iOS remains rc84; both use standalone VSS rc3. No iOS device execution is claimed.

Unpublished Debug controls

Fault placement and readback only; not pushed. The native authentication proxy holds then forwards a genuine response and has a finite shutdown. The expiry helper signs a real short-lived credential using only this disposable identity. No SDK result is substituted.

diff --git a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
index 289131a72..bee9048f5 100644
--- a/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
+++ b/app/src/debug/java/to/bitkit/dev/DevToolsProvider.kt
@@ -43,6 +43,7 @@ class DevToolsProvider : ContentProvider() {
 
     override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
         check(Binder.getCallingUid() == SHELL_UID) { "Only ADB shell callers are allowed" }
+        if (method.startsWith("qa1686")) return kotlinx.coroutines.runBlocking(kotlinx.coroutines.Dispatchers.IO) { Qa1686.run(requireNotNull(context), method, arg) } // test hook
         return runCatching {
             // Needs no node, so it does not wait behind LDK work.
             if (method == OverrideNfc.METHOD) return@runCatching OverrideNfc.execute(arg)
diff --git a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
index 259d689d6..52ec715f3 100644
--- a/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
+++ b/app/src/main/java/to/bitkit/data/backup/VssBackupClientLdk.kt
@@ -57,7 +57,7 @@ class VssBackupClientLdk @Inject constructor(
                         storeId = vssDeriveStoreId(Env.vssStoreIdPrefix, mnemonic, passphrase),
                         mnemonic = mnemonic,
                         passphrase = passphrase,
-                        lnurlAuthServerUrl = Env.lnurlAuthServerUrl,
+                        lnurlAuthServerUrl = if (to.bitkit.BuildConfig.DEBUG && java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-auth-override").exists()) "http://127.0.0.1:23469/lnurl_auth/auth" else Env.lnurlAuthServerUrl, // test hook
                         keyDomain = Env.lnurlAuthKeyDomain,
                     )
                     Logger.info("VSS LDK client setup for wallet[$walletIndex]", context = TAG)
diff --git a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
index 1f3272fc0..019239188 100644
--- a/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
+++ b/app/src/main/java/to/bitkit/repositories/SparkRepo.kt
@@ -297,6 +297,7 @@ class SparkRepo @Inject constructor(
     val walletWiped: SharedFlow<Int> = _walletWiped.asSharedFlow()
 
     suspend fun start(walletIndex: Int): Result<Unit> = withContext(bgDispatcher) {
+        if (to.bitkit.BuildConfig.DEBUG) { val f=java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-spark-start-count"); if (f.exists()) f.writeText((f.readText().toInt()+1).toString()) } // test hook
         if (!sparkService.isSupported) return@withContext Result.success(Unit)
         this@SparkRepo.walletIndex = walletIndex
         // A retry reads as connecting until it fails again.
diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt
index 7a86b78f8..61fcf87a8 100644
--- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt
+++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt
@@ -894,6 +894,7 @@ class PaykitSdkService @Inject constructor(
                     onAcknowledged()
                 } else {
                     completeSdkCall {
+                        if (to.bitkit.BuildConfig.DEBUG) { val f=java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-paykit-delete-attempts"); if(f.exists()) f.writeText((f.readText().toInt()+1).toString()) } // test hook
                         handle.deletePaykitProfile(snapshot.profileRevision)
                         onAcknowledged()
                         notifyBackupStateChanged()
@@ -949,6 +950,17 @@ class PaykitSdkService @Inject constructor(
             requireProfileIdentity(currentIdentity(), expectedIdentity)
             requireNoActiveSubscriptions(handle())
             completeSdkCall {
+                if (to.bitkit.BuildConfig.DEBUG) { // test hook
+                    val deadlineFile = java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-expiry-deadline") // test hook
+                    if (deadlineFile.exists()) { // test hook
+                        val deadline = deadlineFile.readText().trim().toLong() // test hook
+                        deadlineFile.delete() // test hook
+                        Logger.info("QA1686 entered Pubky delete before genuine grant expiry", context = TAG) // test hook
+                        while (to.bitkit.ext.nowMillis() < deadline * 1000 + 2000) kotlinx.coroutines.delay(500) // test hook
+                        Logger.info("QA1686 dispatched Pubky delete after genuine grant expiry", context = TAG) // test hook
+                    } // test hook
+                } // test hook
+                if (to.bitkit.BuildConfig.DEBUG) { val f=java.io.File("/data/user/0/to.bitkit.dev/files/qa1686-pubky-delete-attempts"); if(f.exists()) f.writeText((f.readText().toInt()+1).toString()) } // test hook
                 handle().deletePubkyProfile(expectedRevision)
                 onAcknowledged()
             }
diff --git a/app/src/debug/java/to/bitkit/dev/Qa1686.kt b/app/src/debug/java/to/bitkit/dev/Qa1686.kt
new file mode 100644
index 000000000..24820a024
--- /dev/null
+++ b/app/src/debug/java/to/bitkit/dev/Qa1686.kt
@@ -0,0 +1,239 @@
+package to.bitkit.dev // test hook
+
+import android.content.Context // test hook
+import android.content.ClipData // test hook
+import android.content.ClipboardManager // test hook
+import android.os.Bundle // test hook
+import dagger.hilt.EntryPoint // test hook
+import dagger.hilt.InstallIn // test hook
+import dagger.hilt.android.EntryPointAccessors // test hook
+import dagger.hilt.components.SingletonComponent // test hook
+import kotlinx.coroutines.Dispatchers // test hook
+import kotlinx.coroutines.flow.first // test hook
+import kotlinx.coroutines.withContext // test hook
+import to.bitkit.data.CacheStore // test hook
+import to.bitkit.data.backup.VssBackupClient // test hook
+import to.bitkit.data.keychain.Keychain // test hook
+import to.bitkit.models.BackupCategory // test hook
+import to.bitkit.repositories.BackupRepo // test hook
+import to.bitkit.repositories.PubkyRepo // test hook
+import to.bitkit.repositories.WalletRepo // test hook
+import to.bitkit.repositories.LightningRepo // test hook
+import to.bitkit.services.PubkyService // test hook
+import to.bitkit.di.json // test hook
+import to.bitkit.models.WalletBackupV1 // test hook
+import to.bitkit.utils.Logger // test hook
+import java.io.File // test hook
+import kotlinx.coroutines.*
+import to.bitkit.models.*
+import to.bitkit.repositories.*
+import to.bitkit.services.*
+import kotlin.time.Clock
+
+object Qa1686 { // test hook
+    private var replacementPhrase: String? = null
+    private val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.SupervisorJob() + Dispatchers.IO)
+    @EntryPoint @InstallIn(SingletonComponent::class) // test hook
+    interface Dependencies { // test hook
+        fun removal(): to.bitkit.data.ProfileRemovalStore
+        fun sparkExit(): SparkExitRepo
+        fun spark(): SparkRepo
+        fun sparkService(): SparkService
+        fun recovery(): to.bitkit.data.WalletConnectionRecovery
+        fun vssClients(): to.bitkit.data.backup.VssClientCoordinator
+        fun vssLdk(): to.bitkit.data.backup.VssBackupClientLdk
+        fun sdk(): to.bitkit.services.PaykitSdkService
+        fun allowanceExecutor(): to.bitkit.repositories.PaykitAllowanceExecutor
+        fun privatePaykit(): to.bitkit.repositories.PrivatePaykitRepo
+        fun allowances(): to.bitkit.repositories.PaykitAllowanceRepo
+        fun allowanceStore(): to.bitkit.repositories.PaykitAllowanceStore
+        fun keychain(): Keychain // test hook
+        fun backupRepo(): BackupRepo // test hook
+        fun pubkyRepo(): PubkyRepo // test hook
+        fun pubkyService(): PubkyService // test hook
+        fun vss(): VssBackupClient // test hook
+        fun cache(): CacheStore // test hook
+        fun wallet(): WalletRepo // test hook
+        fun accounts(): to.bitkit.data.WatchOnlyAccountStore
+        fun settings(): to.bitkit.data.SettingsStore
+        fun nodeService(): LightningService
+        fun lightning(): LightningRepo // test hook
+    } // test hook
+    suspend fun run(context: Context, method: String, arg: String?): Bundle { // test hook
+        val d = EntryPointAccessors.fromApplication(context, Dependencies::class.java) // test hook
+        fun file(name: String) = File(context.filesDir, "qa1686-$name")
+        val result = kotlin.runCatching { // test hook
+            when (method) {
+                "qa1686SparkStage" -> {
+                    d.backupRepo().stopObservingBackups()
+                    check(d.sparkService().isConnected)
+                    val native = d.sparkService().getInfo()
+                    check(native.balanceSats == 0uL)
+                    d.lightning().stop().getOrThrow()
+                    val f = d.spark().javaClass.getDeclaredField("_state").apply { isAccessible = true }
+                    @Suppress("UNCHECKED_CAST")
+                    val state = f.get(d.spark()) as kotlinx.coroutines.flow.MutableStateFlow<SparkState>
+                    state.value = state.value.copy(balanceSats = 5000uL, keptBalanceSats = null, isReady = true, hasReadState = true)
+                    "stagedPriorDisplay=5000; nativeBalance=${native.balanceSats}; connected=${d.sparkService().isConnected}; node=${d.lightning().lightningState.value.nodeLifecycleState}"
+                }
+                "qa1686SparkSync" -> {
+                    file("spark-sync-result").delete()
+                    scope.launch {
+                        val result=runCatching { d.sparkService().syncWallet() }
+                        file("spark-sync-result").writeText("success=${result.isSuccess}; error=${result.exceptionOrNull()?.javaClass?.simpleName}")
+                    }
+                    "started real native Spark sync; no return value injected"
+                }
+                "qa1686SparkRead" -> {
+                    val info=d.sparkService().getInfo()
+                    val refresh=d.spark().refreshState()
+                    val state=d.spark().state.value
+                    "nativeBalance=${info.balanceSats}; nativeSyncError=${info.lastSyncError != null}; lastSync=${info.lastSyncedAt}; sync=${file("spark-sync-result").takeIf { it.exists() }?.readText()}; refresh=${refresh.isSuccess}; balance=${state.balanceSats}; kept=${state.keptBalanceSats}; shown=${state.shownBalanceSats}; sendable=${state.sendableSats}; walletMax=${d.wallet().balanceState.value.maxSendLightningSats}"
+                }
+                "qa1686ExpiryExport" -> {
+                    d.backupRepo().stopObservingBackups()
+                    val root = requireNotNull(d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name))
+                    val session = requireNotNull(d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name))
+                    file("ttl-root").writeText(root)
+                    file("ttl-original-session").writeText(session)
+                    "exported disposable signer/session to app-private fixture files; rootPresent=true; sessionPresent=true"
+                }
+                "qa1686ExpiryImport" -> {
+                    val root = requireNotNull(d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name))
+                    val identity = requireNotNull(d.pubkyRepo().publicKey.value)
+                    d.pubkyService().importSession(file("ttl-session").readText())
+                    check(root == d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name))
+                    check(identity == d.pubkyRepo().publicKey.value)
+                    check(d.pubkyService().currentPublicKey() != null)
+                    file("pubky-delete-attempts").writeText("0")
+                    file("paykit-delete-attempts").writeText("0")
+                    "imported genuine short-lived signed grant; originalRootUnchanged=true; currentRepositoryIdentityUnchanged=true; sdkIdentityPresent=true; expiresAt=${file("expiry-deadline").readText()}"
+                }
+                "qa1686ExpiryState" -> {
+                    val root = d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name)
+                    val current = d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name)
+                    "rootUnchanged=${root == file("ttl-root").readText()}; savedSessionUnchanged=${current == file("ttl-session").readText()}; repositoryIdentityPresent=${d.pubkyRepo().publicKey.value != null}; sdkIdentityPresent=${d.pubkyService().currentPublicKey() != null}; profilePresent=${d.pubkyRepo().profile.value != null}; paykitDeletes=${file("paykit-delete-attempts").takeIf { it.exists() }?.readText()}; pubkyDeletes=${file("pubky-delete-attempts").takeIf { it.exists() }?.readText()}"
+                }
+                "qa1686RestartStopped" -> {
+                    d.backupRepo().stopObservingBackups()
+                    val before = requireNotNull(d.nodeService().node)
+                    check(before.status().isRunning)
+                    withContext(Dispatchers.IO) { before.stop() }
+                    check(d.nodeService().hasStoppedNode)
+                    val beforeHandlers = d.lightning().javaClass.getDeclaredField("_eventHandlers").apply { isAccessible=true }
+                    val handlerCount = (beforeHandlers.get(d.lightning()) as Collection<*>).size
+                    d.lightning().start(shouldRetry = false).getOrThrow()
+                    val after = requireNotNull(d.nodeService().node)
+                    check(after !== before && after.status().isRunning && !d.nodeService().hasStoppedNode)
+                    check((beforeHandlers.get(d.lightning()) as Collection<*>).size == handlerCount)
+                    "oldNativeStopped=true; replacement=true; nativeRunning=${after.status().isRunning}; lifecycle=${d.lightning().lightningState.value.nodeLifecycleState}; handlersUnchanged=true"
+                }
+                "qa1686PendingSetup" -> {
+                    d.backupRepo().stopObservingBackups()
+                    d.lightning().stop().getOrThrow()
+                    d.sparkService().disconnect()
+                    check(!d.sparkService().isConnected)
+                    val attempt = java.util.UUID.randomUUID().toString()
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) {
+                        d.removal().begin(attempt)
+                    }
+                    file("spark-start-count").writeText("0")
+                    "pending=${d.removal().walletResetRecovery.first()}; sparkConnected=${d.sparkService().isConnected}"
+                }
+                "qa1686PendingStart" -> {
+                    val handlers = d.lightning().javaClass.getDeclaredField("_eventHandlers").apply { isAccessible=true }
+                    val before = (handlers.get(d.lightning()) as Collection<*>).size
+                    val result = d.lightning().start(eventHandler = {})
+                    delay(1500)
+                    val after = (handlers.get(d.lightning()) as Collection<*>).size
+                    val starts = file("spark-start-count").readText().toInt()
+                    check(result.exceptionOrNull() is to.bitkit.data.ProfileRemovalPending)
+                    check(starts == 0 && before == after && !d.sparkService().isConnected)
+                    "refused=${result.exceptionOrNull()?.javaClass?.simpleName}; sparkStarts=$starts; connected=${d.sparkService().isConnected}; handlersBefore=$before; handlersAfter=$after; node=${d.lightning().lightningState.value.nodeLifecycleState}"
+                }
+                "qa1686PendingUnreadable" -> {
+                    val attempt=requireNotNull(d.removal().pendingAttempt())
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) { d.removal().complete(attempt) }
+                    val dir=File(context.filesDir,"datastore")
+                    val f=File(dir,"profile_removal.json")
+                    check(f.exists())
+                    "CLEAR: restart required before staging unreadable datastore on disk"
+                }
+                "qa1686PendingClear" -> {
+                    val attempt=requireNotNull(d.removal().pendingAttempt())
+                    d.removal().withAccess(attempt, to.bitkit.data.ProfileRemovalScope.WALLET_WIPE) { d.removal().complete(attempt) }
+                    "cleared disposable reset marker"
+                }
+                "qa1686Dev" -> { d.settings().update { it.copy(isDevModeEnabled = true) }; "enabled developer mode" }
+                "qa1686NativeAuth" -> {
+                    d.backupRepo().stopObservingBackups()
+                    d.vssClients().withSuspendedClients {}
+                    file("auth-override").writeText("hold")
+                    d.vssLdk().setup().getOrThrow()
+                    file("native-result").delete()
+                    scope.launch {
+                        try {
+                            val result = d.vssLdk().getObject("qa1686-held-auth")
+                            file("native-result").writeText("returned success=${result.isSuccess}; error=${result.exceptionOrNull()?.javaClass?.simpleName}")
+                        } catch(e: Exception) { file("native-result").writeText("cancelled=${e.javaClass.simpleName}") }
+                    }
+                    "scheduled actual standalone LDK lookup against held auth response"
+                }
+                "qa1686NativeState" -> "credentialsPresent=${d.keychain().exists(Keychain.Key.BIP39_MNEMONIC.name)}; wiping=${d.backupRepo().isWiping.value}; admissionOpen=${runCatching { d.vssClients().captureOwner() }.isSuccess}; result=${file("native-result").takeIf { it.exists() }?.readText()}"
+                "qa1686Backup" -> {
+                    for (c in listOf(BackupCategory.WALLET, BackupCategory.METADATA, BackupCategory.SETTINGS)) d.backupRepo().triggerBackup(c).getOrThrow()
+                    val wallet = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val metadata = requireNotNull(d.vss().getObject("METADATA").getOrThrow())
+                    val pending = d.cache().backupStatuses.first().filterKeys { it in listOf(BackupCategory.WALLET, BackupCategory.METADATA) }.any { it.value.isRequired }
+                    check(!pending)
+                    "backup synchronized; sdk=${json.decodeFromString<WalletBackupV1>(wallet.value.decodeToString()).paykitSdkBackupState != null}; metadataBytes=${metadata.value.size}"
+                }
+                "qa1686Terminal" -> {
+                    d.backupRepo().stopObservingBackups()
+                    val secret = requireNotNull(d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name))
+                    File(context.filesDir, "qa1686-original-secret").writeText(secret)
+                    val session = requireNotNull(d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name))
+                    File(context.filesDir, "qa1686-original-session").writeText(session)
+                    d.pubkyService().forgetSessionAccess()
+                    d.keychain().delete(Keychain.Key.PUBKY_SECRET_KEY.name)
+                    d.keychain().upsertString(Keychain.Key.PAYKIT_SESSION.name, "qa1686-invalid-session")
+                    d.pubkyRepo().initialize().getOrThrow()
+                    check(d.pubkyRepo().publicKey.value == null)
+                    val before = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val reserved = d.accounts().reserveAccountIndex(0, "qa1686-terminal-ordinary")
+                    check(d.accounts().backupSnapshot().allocationState.highestAccountIndexByWallet["0"] == reserved)
+                    val failed = d.backupRepo().triggerBackup(BackupCategory.WALLET)
+                    val after = requireNotNull(d.vss().getObject("WALLET").getOrThrow())
+                    val same = before.value.contentEquals(after.value) && before.version == after.version
+                    val pending = d.cache().backupStatuses.first()[BackupCategory.WALLET]?.isRequired == true
+                    check(failed.isFailure && same && pending)
+                    "terminal=true; ordinary watch-only index=$reserved reserved; failed=true; remote unchanged=true; pending=true; error=${failed.exceptionOrNull()?.javaClass?.simpleName}"
+                }
+                "qa1686RepairIdentity" -> {
+                    d.keychain().upsertString(Keychain.Key.PUBKY_SECRET_KEY.name, File(context.filesDir, "qa1686-original-secret").readText())
+                    d.keychain().upsertString(Keychain.Key.PAYKIT_SESSION.name, File(context.filesDir, "qa1686-original-session").readText())
+                    d.pubkyRepo().initialize().getOrThrow()
+                    d.backupRepo().triggerBackup(BackupCategory.WALLET).getOrThrow()
+                    "recovered original identity and complete WALLET upload"
+                }
+                "qa1686Recover" -> { // test hook
+                    val secret = d.pubkyService().deriveSecretKey(requireNotNull(d.keychain().loadString(Keychain.Key.BIP39_MNEMONIC.name))) // test hook
+                    d.keychain().upsertString(Keychain.Key.PUBKY_SECRET_KEY.name, secret) // test hook
+                    d.pubkyService().initialize() // test hook
+                    d.pubkyRepo().restoreSessionBackupState(to.bitkit.models.PubkySessionBackupV1(kind = to.bitkit.models.PubkySessionBackupKind.LocalSeed)).getOrThrow() // test hook
+                    d.pubkyRepo().scheduleInitializationAfterRestore() // test hook
+                    d.backupRepo().triggerBackup(BackupCategory.WALLET).getOrThrow() // test hook
+                    d.backupRepo().startObservingBackups() // test hook
+                    "recovered identity and fresh complete backup" // test hook
+                } // test hook
+                "qa1686CreateProfile" -> {
+                    d.pubkyRepo().createIdentity("QA restore", "", emptyList(), emptyList(), null).getOrThrow()
+                    "created disposable profile"
+                }
+                else -> "source=${d.keychain().exists(Keychain.Key.SHARED_PUBKY_SOURCE.name)}, savedSecret=${!d.keychain().loadString(Keychain.Key.PUBKY_SECRET_KEY.name).isNullOrBlank()}, savedSession=${!d.keychain().loadString(Keychain.Key.PAYKIT_SESSION.name).isNullOrBlank()}, sdk=${d.pubkyService().currentPublicKey() != null}, identity=${d.pubkyRepo().publicKey.value != null}, profile=${d.pubkyRepo().profile.value?.name}, contacts=${d.pubkyRepo().contacts.value.size}, pendingRestore=${d.backupRepo().hasPendingWalletRestore()}, node=${d.lightning().lightningState.value.nodeLifecycleState}" // test hook
+            } // test hook
+        }.fold({ it }, { "ERROR: ${it.javaClass.simpleName}: ${it.message}" }) // test hook
+        Logger.info("QA1686 $method: $result", context="TestHook") // test hook
+        return Bundle().apply { putString("result", result) } // test hook
+    } // test hook
+} // test hook
Real Node.stop -> production start: oldNativeStopped=true; replacement=true; nativeRunning=true; handlersUnchanged=true
Real Spark error/readback: nativeBalance=0; nativeSyncError=true; kept=5000; shown=5000; sendable=0; settled walletMax=0
Terminal identity: ordinary watch-only index=1 reserved; remote unchanged=true; pending=true
Repair: recovered original identity and complete WALLET upload
Held auth: credentials retained and admission closed at196.1s; release214.7s; completion26.1s later
Grant: genuine root-signed TTL240s; native Pubky-delete hold entered before expiry and dispatched after expiry
After delete and after Review: rootUnchanged=true; savedSessionUnchanged=true; paykitDeletes=0; pubkyDeletes=1

Reviewed by gpt-6.1-sol-high

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.

5 participants