From 0dc56a0735fc597c967d69a435d2997f2ce9b03e Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:16:26 +0200 Subject: [PATCH 01/12] fix: stop automatic profile deletion replay --- Bitkit/Managers/PubkyProfileManager.swift | 52 ---------------- Bitkit/Views/Profile/EditProfileView.swift | 29 +++------ BitkitTests/PubkyProfileManagerTests.swift | 59 ------------------- .../next/profile-delete-retry.fixed.md | 1 + .../delete-profile-uncertain-response.xml | 17 ++++++ 5 files changed, 25 insertions(+), 133 deletions(-) create mode 100644 changelog.d/next/profile-delete-retry.fixed.md create mode 100644 journeys/profile/delete-profile-uncertain-response.xml diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index d29dd6b1e0..5591d441a0 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -1597,14 +1597,6 @@ class PubkyProfileManager: ObservableObject { } } - func refreshSessionIfPossible(after error: Error) async -> Bool { - await Self.refreshSessionIfPossible( - after: error, - loadKeychainString: { try Keychain.loadString(key: $0) }, - signInWithSecretKey: { try await PubkyService.signIn(secretKeyHex: $0) } - ) - } - // MARK: - Cached Profile Metadata private static let cachedNameKey = "pubky_profile_name" @@ -1982,50 +1974,6 @@ class PubkyProfileManager: ObservableObject { return false } - nonisolated static func isSessionRefreshableError(_ error: Error) -> Bool { - let errorText = [ - (error as? AppError)?.debugMessage, - error.localizedDescription, - String(describing: error), - ] - .compactMap { $0?.lowercased() } - - return errorText.contains { - ($0.contains("authfailed") || $0.contains("authentication failed") || $0.contains("sessionnotactive")) - || ($0.contains("transport error") && $0.contains("/session")) - } - } - - nonisolated static func refreshSessionIfPossible( - after error: Error, - loadKeychainString: (KeychainEntryType) throws -> String? = { - try Keychain.loadString(key: $0) - }, - signInWithSecretKey: (String) async throws -> String, - publicKeyFromSecretKey: (String) throws -> String = { - try PubkyProfileManager.publicKeyFromSecretKey($0) - } - ) async -> Bool { - guard isSessionRefreshableError(error) else { - return false - } - - guard let secretKeyHex = activeSecretKeyHex(loadKeychainString: loadKeychainString) else { - Logger.warn("Cannot refresh pubky session without a secret key", context: "PubkyProfileManager") - return false - } - - do { - _ = try await signInWithSecretKey(secretKeyHex) - _ = try publicKeyFromSecretKey(secretKeyHex) - Logger.info("Refreshed pubky session from local secret key", context: "PubkyProfileManager") - return true - } catch { - Logger.warn("Failed to refresh pubky session: \(error)", context: "PubkyProfileManager") - return false - } - } - nonisolated static func resolveSessionInitialization( savedSessionSecret: String?, storedSecretKeyHex: String?, diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index 183393e119..e9dbe433eb 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -158,33 +158,18 @@ struct EditProfileView: View { defer { isDeleting = false } do { try await pubkyProfile.performProfileDeletion { - await deleteProfileWithSessionRetry(session: session) - } - } catch { - guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } - showDeleteFailureOptions = true - } - } - - private func deleteProfileWithSessionRetry(session: PubkyProfileManager.SignedInSession) async { - do { - try await performDeleteProfile(session: session) - } catch { - guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } - if pubkyProfile.currentSession == session, await pubkyProfile.refreshSessionIfPossible(after: error) { do { try await performDeleteProfile(session: session) - return } catch { - Logger.error("Failed to delete profile after session refresh: \(error)", context: "EditProfileView") + guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } + Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") + showDeleteFailureOptions = true } - } else { - Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") - } - - if !Task.isCancelled, pubkyProfile.publicKey == session.publicKey { - showDeleteFailureOptions = true } + } catch { + guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } + Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") + showDeleteFailureOptions = true } } diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index 8a021497b5..14f4dfe654 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -3459,65 +3459,6 @@ final class PubkyProfileManagerTests: XCTestCase { XCTAssertFalse(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) } - func testIsSessionRefreshableErrorRecognizesSessionTransportFailure() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - - XCTAssertTrue(PubkyProfileManager.isSessionRefreshableError(error)) - } - - func testRefreshSessionIfPossibleRefreshesSessionFromLocalSecret() async { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - let refreshed = await PubkyProfileManager.refreshSessionIfPossible( - after: error, - loadKeychainString: { key in - switch key { - case .pubkySecretKey: - return "local-secret" - default: - return nil - } - }, - signInWithSecretKey: { secretKey in - XCTAssertEqual(secretKey, "local-secret") - return "fresh-session" - }, - publicKeyFromSecretKey: { secretKey in - XCTAssertEqual(secretKey, "local-secret") - return "pubky_fresh" - } - ) - - XCTAssertTrue(refreshed) - } - - func testRefreshSessionIfPossibleReturnsFalseWithoutLocalSecret() async { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error: error sending request for url (https://example.com/session)")"# - ) - - let refreshed = await PubkyProfileManager.refreshSessionIfPossible( - after: error, - loadKeychainString: { _ in nil }, - signInWithSecretKey: { _ in - XCTFail("Expected refresh to stop when no local secret key exists") - return "fresh-session" - }, - publicKeyFromSecretKey: { _ in - XCTFail("No public key should be derived without a local secret") - return "pubky_unused" - } - ) - - XCTAssertFalse(refreshed) - } - // MARK: - Session backup state func testSnapshotSessionBackupStatePrefersLocalSeedOverSessionSecret() throws { diff --git a/changelog.d/next/profile-delete-retry.fixed.md b/changelog.d/next/profile-delete-retry.fixed.md new file mode 100644 index 0000000000..fb97b9ecd4 --- /dev/null +++ b/changelog.d/next/profile-delete-retry.fixed.md @@ -0,0 +1 @@ +Prevent uncertain profile deletion failures from automatically repeating contact cleanup and deletion. diff --git a/journeys/profile/delete-profile-uncertain-response.xml b/journeys/profile/delete-profile-uncertain-response.xml new file mode 100644 index 0000000000..fe825c36ff --- /dev/null +++ b/journeys/profile/delete-profile-uncertain-response.xml @@ -0,0 +1,17 @@ + + + Requires a disposable test identity and a controlled homeserver proxy; never use a personal profile. + Configure the proxy to accept one profile deletion but lose its acknowledgement, retaining a redacted + request counter. This is a fault-injection fixture requirement, not evidence that this journey has run. + Normal SDK recovery may retry an individual request only after a confirmed authentication rejection; + the app must not restart contact cleanup and profile deletion because a request has an uncertain outcome. + + + Open Edit Profile and confirm deletion + Drop the acknowledgement after the server accepts the profile deletion + Verify failure options are shown and no success notification or onboarding navigation occurs + Wait through the network timeout and verify the app starts no second contact cleanup, profile deletion or sign-in + Cancel the failure dialog and verify no mutation is retried + Restart the app without choosing Retry and verify it does not automatically repeat the deletion + + From 1b8a6db827d0967cac744dc6f41d38283ee755db Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 01:17:16 +0200 Subject: [PATCH 02/12] docs: associate deletion fix with PR 1122 --- changelog.d/next/{profile-delete-retry.fixed.md => 1122.fixed.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/next/{profile-delete-retry.fixed.md => 1122.fixed.md} (100%) diff --git a/changelog.d/next/profile-delete-retry.fixed.md b/changelog.d/next/1122.fixed.md similarity index 100% rename from changelog.d/next/profile-delete-retry.fixed.md rename to changelog.d/next/1122.fixed.md From f204e05eb41ed4f34e4e08f7138cc600b296d45e Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 02:33:24 +0100 Subject: [PATCH 03/12] fix: serialize backup observation lifecycle --- Bitkit/Services/BackupService.swift | 236 ++++++++++-------- BitkitTests/BackupServiceTests.swift | 167 +++++++++++++ changelog.d/next/1123.fixed.md | 1 + .../wallet-snapshot-consistency.md | 22 ++ 4 files changed, 320 insertions(+), 106 deletions(-) create mode 100644 changelog.d/next/1123.fixed.md diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 94fe0d95a4..982b003a65 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -113,9 +113,12 @@ class BackupService { @MainActor weak var usdtWallet: UsdtWalletManager? private var backupJobs: [BackupCategory: Task] = [:] private var runningBackupTasks: [BackupCategory: Task] = [:] - private var cancellables = Set() - private var periodicCheckTask: Task? - private var isObserving = false + @MainActor private var cancellables = Set() + @MainActor private var periodicCheckTask: Task? + @MainActor private var observationTask: Task? + @MainActor private var isObserving = false + private var schedulingGeneration: UInt64 = 0 + private var isStoppingBackups = false private var isRestoring = false private var isWiping = false private var lastNotificationTime: UInt64 = 0 @@ -200,18 +203,13 @@ class BackupService { } } + @MainActor func startObservingBackups() { - guard !shouldSkipBackup() else { return } - - Task { - let shouldStart = try? await ServiceQueue.background(.backup) { - guard !self.isObserving else { return false } - self.isObserving = true - return true - } - - guard shouldStart == true else { return } - + let previous = observationTask + observationTask = Task { + await previous?.value + guard !shouldSkipBackup(), !isObserving else { return } + isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") startBackupStatusObservers() startDataStoreListeners() @@ -219,25 +217,43 @@ class BackupService { } } + @MainActor func stopObservingBackups() async { - let shouldStop = try? await ServiceQueue.background(.backup) { - let wasObserving = self.isObserving - self.isObserving = false - - self.backupJobs.values.forEach { $0.cancel() } - self.backupJobs.removeAll() - self.runningBackupTasks.values.forEach { $0.cancel() } - self.runningBackupTasks.removeAll() - self.periodicCheckTask?.cancel() - self.periodicCheckTask = nil - return wasObserving + let previous = observationTask + let stopping = Task { + await previous?.value + isObserving = false + cancellables.removeAll() + periodicCheckTask?.cancel() + periodicCheckTask = nil + + let tasks = try? await ServiceQueue.background(.backup) { + self.stateQueue.sync { self.schedulingGeneration &+= 1 } + self.isStoppingBackups = true + let scheduled = Array(self.backupJobs.values) + let running = Array(self.runningBackupTasks.values) + scheduled.forEach { $0.cancel() } + running.forEach { $0.cancel() } + return (scheduled, running) + } + // Cleanup uses the backup queue too, so drain outside it before a replacement starts. + if let (scheduled, running) = tasks { + for task in scheduled { + await task.value + } + for task in running { + _ = await task.value + } + } + await walletBackupWriter.waitUntilIdle() + await usdtBackupWriter.waitUntilIdle() + try? await ServiceQueue.background(.backup) { + self.isStoppingBackups = false + } + Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") } - - await walletBackupWriter.waitUntilIdle() - await usdtBackupWriter.waitUntilIdle() - guard shouldStop == true else { return } - cancellables.removeAll() - Logger.debug("Stopped observing backup statuses and data store changes", context: "BackupService") + observationTask = stopping + await stopping.value } @discardableResult @@ -246,19 +262,32 @@ class BackupService { } private func triggerBackup(category: BackupCategory, isScheduled: Bool) async -> BackupOutcome { - let backupTask = try? await ServiceQueue.background(.backup) { [self] () -> Task? in - guard runningBackupTasks[category] == nil else { return nil } - let backupTask = Task { await self.runBackup(category: category, isScheduled: isScheduled) } - runningBackupTasks[category] = backupTask - return backupTask + while !Task.isCancelled { + let admission = try? await ServiceQueue.background(.backup) { [self] () -> (Task?, Bool) in + guard !isStoppingBackups else { return (nil, true) } + guard runningBackupTasks[category] == nil else { return (nil, false) } + let task = Task { await self.runBackup(category: category, isScheduled: isScheduled) } + runningBackupTasks[category] = task + return (task, false) + } + guard let (backupTask, isStopping) = admission else { return .failed } + if isStopping, !isScheduled { + await waitForObservationTransition() + continue + } + guard let backupTask else { return .busy } + return await withTaskCancellationHandler { + await backupTask.value + } onCancel: { + backupTask.cancel() + } } + return .failed + } - guard let backupTask else { return .busy } - return await withTaskCancellationHandler { - await backupTask.value - } onCancel: { - backupTask.cancel() - } + @MainActor + private func waitForObservationTransition() async { + await observationTask?.value } private func runBackup(category: BackupCategory, isScheduled: Bool) async -> BackupOutcome { @@ -618,6 +647,7 @@ class BackupService { // MARK: - Private Methods + @MainActor private func startBackupStatusObservers() { for category in BackupCategory.allCases { let categoryPublisher = backupStatusesPublisher @@ -635,8 +665,9 @@ class BackupService { .sink { [weak self] status in guard let self, !self.shouldSkipBackup(category: category) else { return } if status.isRequired && !status.running { + let generation = currentSchedulingGeneration Task { - await self.scheduleBackup(category: category) + await self.scheduleBackup(category: category, generation: generation) } } } @@ -646,27 +677,25 @@ class BackupService { Logger.debug("Started \(BackupCategory.allCases.count) backup status observers", context: "BackupService") } + @MainActor private func startDataStoreListeners() { - Task { @MainActor [weak self] in - guard let self else { return } - // SETTINGS - SettingsViewModel.shared.settingsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .settings) - } - .store(in: &cancellables) + // SETTINGS + SettingsViewModel.shared.settingsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .settings) + } + .store(in: &cancellables) - // WIDGETS - SettingsViewModel.shared.widgetsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .widgets) - } - .store(in: &cancellables) - } + // WIDGETS + SettingsViewModel.shared.widgetsPublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .widgets) + } + .store(in: &cancellables) // Record requirements synchronously; the scheduled upload already has a debounce. WalletBackupChangeTracker.localChanges @@ -714,16 +743,13 @@ class BackupService { .store(in: &cancellables) // APP STATE (UserDefaults changes, etc.) - Task { @MainActor [weak self] in - guard let self else { return } - SettingsViewModel.shared.appStatePublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) - .sink { [weak self] _ in - guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) - } - .store(in: &cancellables) - } + SettingsViewModel.shared.appStatePublisher + .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + guard let self, !self.shouldSkipBackup() else { return } + markBackupRequired(category: .metadata) + } + .store(in: &cancellables) // BLOCKTANK CoreService.shared.blocktank.stateChangedPublisher @@ -752,16 +778,13 @@ class BackupService { Logger.debug("Started data store listeners", context: "BackupService") } + @MainActor private func startPeriodicBackupFailureCheck() { - Task { - try? await ServiceQueue.background(.backup) { - self.periodicCheckTask = Task { - while !Task.isCancelled { - try? await Task.sleep(nanoseconds: UInt64(Self.backupFailureCheckInterval * 1_000_000_000)) - guard !Task.isCancelled else { break } - self.checkForFailedBackups() - } - } + periodicCheckTask = Task { + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: UInt64(Self.backupFailureCheckInterval * 1_000_000_000)) + guard !Task.isCancelled else { break } + checkForFailedBackups() } } } @@ -788,42 +811,42 @@ class BackupService { return BackupItemStatus( synced: status.synced, required: max(status.required, status.synced + 1, UInt64(Date().timeIntervalSince1970)), - running: schedule || status.running + running: status.running ) } guard schedule else { return } - Task { - let status = getBackupStatus(category: category) - if status.isRequired && !shouldSkipBackup(category: category) { - await scheduleBackup(category: category) - } else if !status.isRequired { + let generation = currentSchedulingGeneration + Task { await scheduleBackup(category: category, generation: generation) } + } + + private var currentSchedulingGeneration: UInt64 { + stateQueue.sync { schedulingGeneration } + } + + private func scheduleBackup(category: BackupCategory, generation: UInt64) async { + while !Task.isCancelled { + let waitingForStop = try? await ServiceQueue.background(.backup) { [self] in + guard generation == currentSchedulingGeneration else { return false } + guard !isStoppingBackups else { return true } + guard backupJobs[category] == nil, getBackupStatus(category: category).isRequired, + !shouldSkipBackup(category: category) else { return false } updateBackupStatus(category: category) { status in BackupItemStatus( synced: status.synced, required: status.required, - running: false + running: true ) } + backupJobs[category] = Task { await self.runScheduledBackup(category: category, generation: generation) } + return false } + guard waitingForStop == true else { return } + await waitForObservationTransition() } } - private func scheduleBackup(category: BackupCategory) async { - try? await ServiceQueue.background(.backup) { [self] in - guard backupJobs[category] == nil else { return } - updateBackupStatus(category: category) { status in - BackupItemStatus( - synced: status.synced, - required: status.required, - running: true - ) - } - backupJobs[category] = Task { await self.runScheduledBackup(category: category) } - } - } - - private func runScheduledBackup(category: BackupCategory) async { + private func runScheduledBackup(category: BackupCategory, generation: UInt64) async { var outcome = BackupOutcome.failed var retryDelay: UInt64 = 10_000_000_000 while !Task.isCancelled { @@ -845,14 +868,14 @@ class BackupService { break } } - _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } updateBackupStatus(category: category) { status in BackupItemStatus(synced: status.synced, required: status.required, running: false) } + _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } if outcome.canRetryPendingBackup, !Task.isCancelled, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { - await scheduleBackup(category: category) + await scheduleBackup(category: category, generation: generation) } } @@ -936,6 +959,7 @@ class BackupService { } func scheduleFullBackup() async { + let generation = currentSchedulingGeneration let currentTime = UInt64(Date().timeIntervalSince1970) for category in BackupCategory.allCases { updateBackupStatus(category: category) { status in @@ -951,7 +975,7 @@ class BackupService { for category in BackupCategory.allCases { let status = getBackupStatus(category: category) if status.isRequired && !status.running { - await scheduleBackup(category: category) + await scheduleBackup(category: category, generation: generation) } } } diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index a0cc74b0fc..efb5c25fe5 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -169,6 +169,149 @@ final class BackupServiceTests: XCTestCase { } } + func testStopDrainsCancelledWorkBeforeManualBackupAndRestart() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let started = expectation(description: "Scheduled delay started") + let cancelled = expectation(description: "Scheduled delay cancelled") + let uploadedEarly = expectation(description: "Manual upload must wait for cleanup") + uploadedEarly.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + let service = BackupService(defaults: defaults, backupData: { _ in Data("complete".utf8) }, uploadBackup: { key, data in + await recorder.recordUpload(key: key, data: data) + if await gate.isHeld { + uploadedEarly.fulfill() + } + }, waitForBackupDelay: { + try await withTaskCancellationHandler { + await gate.wait(started: started) + try Task.checkCancellation() + } onCancel: { cancelled.fulfill() } + }) + service.markBackupRequired(category: .wallet) + await fulfillment(of: [started], timeout: 2) + let stop = Task { + await service.stopObservingBackups() + await gate.recordStop() + } + await fulfillment(of: [cancelled], timeout: 2) + let deferred = expectation(description: "New USDT request survives the drain") + let deferredSubscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in deferred.fulfill() } + service.markBackupRequired(category: .usdt) + let manual = Task { await service.triggerBackup(category: .metadata) } + await fulfillment(of: [uploadedEarly], timeout: 0.1) + let stoppedBeforeDrain = await gate.didStop + XCTAssertFalse(stoppedBeforeDrain) + await gate.release() + await stop.value + let outcome = await manual.value + await fulfillment(of: [deferred], timeout: 2) + deferredSubscription.cancel() + XCTAssertEqual(outcome, .completed) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .wallet).running) + let uploads = await recorder.uploads + XCTAssertEqual(Set(uploads.map(\.key)), [BackupCategory.metadata.rawValue, BackupCategory.usdt.rawValue]) + XCTAssertEqual(uploads.count, 2) + await service.stopObservingBackups() + + let restarted = BackupService(defaults: defaults, backupData: { _ in Data("latest".utf8) }, + uploadBackup: { _, _ in }, waitForBackupDelay: {}) + let completed = expectation(description: "Restart uploads retained work") + let subscription = restarted.backupStatusesPublisher + .filter { $0[.wallet].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + restarted.startObservingBackups() + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await restarted.stopObservingBackups() + XCTAssertFalse(restarted.getBackupStatus(category: .wallet).isRequired) + } + + func testStopWaitsForFinalScheduledStatusWrite() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let delayStarted = expectation(description: "Scheduled backup entered delay") + let cleanupStarted = expectation(description: "Final status write entered") + let stoppedEarly = expectation(description: "Stop must wait for final status write") + stoppedEarly.isInverted = true + let delayGate = BackupDelayGate() + let cleanupGate = DispatchSemaphore(value: 0) + let stopGate = BackupDelayGate() + let service = BackupService(defaults: defaults, backupData: { _ in Data() }, + uploadBackup: { _, _ in XCTFail("Wiping must prevent upload") }, + waitForBackupDelay: { await delayGate.wait(started: delayStarted) }) + service.markBackupRequired(category: .wallet) + await fulfillment(of: [delayStarted], timeout: 2) + let subscription = service.backupStatusesPublisher + .filter { $0[.wallet]?.running == false } + .first().sink { _ in + cleanupStarted.fulfill() + cleanupGate.wait() + } + service.setWiping(true) + await delayGate.release() + await fulfillment(of: [cleanupStarted], timeout: 2) + let stop = Task { + await service.stopObservingBackups() + if await stopGate.isHeld { + stoppedEarly.fulfill() + } + } + await fulfillment(of: [stoppedEarly], timeout: 0.1) + await stopGate.release() + cleanupGate.signal() + await stop.value + subscription.cancel() + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .wallet).running) + } + + func testImmediateStartStopDoesNotObserveLaterWalletChanges() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let service = BackupService(defaults: defaults, backupData: { _ in Data("complete".utf8) }, + uploadBackup: { _, _ in }, waitForBackupDelay: {}) + for _ in 0 ..< 25 { + service.startObservingBackups() + await service.stopObservingBackups() + let stoppedStatus = service.getBackupStatus(category: .wallet) + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertEqual(service.getBackupStatus(category: .wallet), stoppedStatus) + } + } + + func testExplicitUsdtBackupRetriesWhileObserversRemainStopped() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "USDT retry acknowledged without node observation") + var captures = 0 + let service = BackupService(defaults: defaults, backupData: { _ in + captures += 1 + if captures == 1 { + throw PaykitError.SharedStateBusy(code: "shared_state_busy", context: "temporarily unavailable") + } + return Data("signed-recovery".utf8) + }, uploadBackup: { _, _ in }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { _ in }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .usdt) + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + XCTAssertEqual(captures, 2) + XCTAssertFalse(service.getBackupStatus(category: .usdt).isRequired) + } + func testTemporaryFailureRemainsPendingAcrossServiceRestart() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) @@ -453,3 +596,27 @@ private final class WalletBackupSdk: PaykitSdk, @unchecked Sendable { return "wallet-backup" } } + +private actor BackupDelayGate { + private(set) var isHeld = true + private(set) var didStop = false + private var continuation: CheckedContinuation? + + func wait(started: XCTestExpectation) async { + guard isHeld else { return } + await withCheckedContinuation { continuation in + self.continuation = continuation + started.fulfill() + } + } + + func recordStop() { + didStop = true + } + + func release() { + isHeld = false + continuation?.resume() + continuation = nil + } +} diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md new file mode 100644 index 0000000000..3cba6c7e79 --- /dev/null +++ b/changelog.d/next/1123.fixed.md @@ -0,0 +1 @@ +Fixed a crash when backup observation stops and ensured pending backups resume safely after restart. diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index 0c5e7acfb5..e79d4e3233 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -34,3 +34,25 @@ mutation. A genuine capture/upload failure must not enter an automatic retry loo Record the tested commit, gate locations, attempts and upload counts, and the restored state. Unit coverage does not establish a device pass or a maximum backup delay during sustained activity. + +## Backup observation shutdown + +The following controls require the same dedicated lifecycle/capture fixture; +these are not ordinary UI journey capabilities. No wallet reset is needed. + +1. Hold a scheduled backup in its cancellable debounce, stop observation, and + request a manual metadata backup while cancellation cleanup remains held. + Verify shutdown and the manual upload both wait for cleanup, including a final + status write held after the delay finishes. Release cleanup; + verify pending wallet work remains required and resumes on observation restart. +2. Request a new USDT recovery backup during cleanup and again after observation + is stopped. Verify both requests can finish without restarting Lightning, and + transient backup failures retain bounded automatic retry. +3. Repeatedly start and immediately stop observation. Change a wallet record only + after stop returns; verify the stopped observer does not schedule an upload or + mutate its saved backup status. Restart observation and verify a single set of + listeners resumes pending work. + +The iOS lifecycle unit tests exercise these component boundaries with injected +capture/upload and delay controls. They do not prove a full device fault journey. +Android's related job-ownership and reset paths require separate validation. From 538f45c7551dddfb96193e0107f9f2a3a01e7166 Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 04:28:06 +0100 Subject: [PATCH 04/12] fix: retain backup changes during observation restart --- Bitkit/Services/BackupService.swift | 65 +++++------ BitkitTests/BackupServiceTests.swift | 102 ++++++++++++++++++ .../wallet-snapshot-consistency.md | 7 +- 3 files changed, 143 insertions(+), 31 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 982b003a65..7903e1c8e7 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -206,13 +206,14 @@ class BackupService { @MainActor func startObservingBackups() { let previous = observationTask + let listeners = makeDataStoreListeners() observationTask = Task { await previous?.value guard !shouldSkipBackup(), !isObserving else { return } isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") + cancellables.formUnion(listeners) startBackupStatusObservers() - startDataStoreListeners() startPeriodicBackupFailureCheck() } } @@ -329,7 +330,7 @@ class BackupService { updateBackupStatus(category: category) { status in BackupItemStatus( synced: status.synced, - required: category == .wallet || category == .usdt ? status.required : status.synced, + required: status.required, running: false ) } @@ -678,87 +679,81 @@ class BackupService { } @MainActor - private func startDataStoreListeners() { + private func makeDataStoreListeners() -> Set { + var listeners = Set() // SETTINGS SettingsViewModel.shared.settingsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .settings) + markObservedBackupRequired(category: .settings) } - .store(in: &cancellables) + .store(in: &listeners) // WIDGETS SettingsViewModel.shared.widgetsPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .widgets) + markObservedBackupRequired(category: .widgets) } - .store(in: &cancellables) + .store(in: &listeners) // Record requirements synchronously; the scheduled upload already has a debounce. WalletBackupChangeTracker.localChanges .merge(with: PaykitSdkService.walletBackupDataChangedPublisher) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .wallet) + markObservedBackupRequired(category: .wallet) } - .store(in: &cancellables) + .store(in: &listeners) UsdtWalletManager.walletBackupDataChangedPublisher .merge(with: PaykitUsdtPaymentService.walletBackupDataChangedPublisher) .sink { [weak self] _ in guard let self, !self.isWipingOrRestoringUsdt() else { return } - markBackupRequired(category: .usdt) + markObservedBackupRequired(category: .usdt) } - .store(in: &cancellables) + .store(in: &listeners) // ACTIVITIES CoreService.shared.activity.activitiesChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .activity) + markObservedBackupRequired(category: .activity) } - .store(in: &cancellables) + .store(in: &listeners) // METADATA (from ActivityService) CoreService.shared.activity.metadataChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // METADATA (hardware wallet names). Scoped to the names alone: the known-device store is also // rewritten by every connect, and reconnect traffic must not re-upload the whole envelope. HwKnownDeviceStorage.namesChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // APP STATE (UserDefaults changes, etc.) SettingsViewModel.shared.appStatePublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .metadata) + markObservedBackupRequired(category: .metadata) } - .store(in: &cancellables) + .store(in: &listeners) // BLOCKTANK CoreService.shared.blocktank.stateChangedPublisher - .debounce(for: .milliseconds(500), scheduler: DispatchQueue.main) .sink { [weak self] _ in guard let self, !self.shouldSkipBackup() else { return } - markBackupRequired(category: .blocktank) + markObservedBackupRequired(category: .blocktank) } - .store(in: &cancellables) + .store(in: &listeners) // LIGHTNING SYNC STATUS LightningService.shared.syncStatusChangedPublisher @@ -773,9 +768,19 @@ class BackupService { ) } } - .store(in: &cancellables) + .store(in: &listeners) + + return listeners + } - Logger.debug("Started data store listeners", context: "BackupService") + private func markObservedBackupRequired(category: BackupCategory) { + // Persist notifications during restart without admitting uploads before cleanup finishes. + markBackupRequired(category: category, schedule: false) + Task { @MainActor in + await waitForObservationTransition() + guard isObserving else { return } + await scheduleBackup(category: category, generation: currentSchedulingGeneration) + } } @MainActor diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index efb5c25fe5..76ae93fabb 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -232,6 +232,108 @@ final class BackupServiceTests: XCTestCase { XCTAssertFalse(restarted.getBackupStatus(category: .wallet).isRequired) } + func testRestartRecordsWalletChangesWhilePreviousCleanupDrains() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let started = expectation(description: "Old scheduled work started") + let cancelled = expectation(description: "Old work entered cancellation cleanup") + let completed = expectation(description: "Restart uploads the change made during cleanup") + let early = expectation(description: "New upload must wait for old cleanup") + early.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + var state = Data("initial".utf8) + var delays = 0 + let service = BackupService(defaults: defaults, backupData: { _ in state }, uploadBackup: { key, data in + await recorder.recordUpload(key: key, data: data) + if data == Data("updated".utf8), await gate.isHeld { + early.fulfill() + } + }, waitForBackupDelay: { + delays += 1 + guard delays == 1 else { return } + try await withTaskCancellationHandler { + await gate.wait(started: started) + try Task.checkCancellation() + } onCancel: { cancelled.fulfill() } + }) + await service.triggerBackup(category: .wallet) + service.markBackupRequired(category: .settings) + await fulfillment(of: [started], timeout: 2) + let stop = Task { await service.stopObservingBackups() } + await fulfillment(of: [cancelled], timeout: 2) + + service.startObservingBackups() + state = Data("updated".utf8) + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + let beforeDrain = await recorder.uploads + XCTAssertEqual(beforeDrain.map(\.data), [Data("initial".utf8)]) + let subscription = service.backupStatusesPublisher + .filter { $0[.wallet].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + await fulfillment(of: [early], timeout: 0.1) + await gate.release() + await stop.value + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + let uploads = await recorder.uploads.filter { $0.key == BackupCategory.wallet.rawValue } + XCTAssertEqual(uploads.map(\.data), [Data("initial".utf8), Data("updated".utf8)]) + } + + func testCancelledUploadRetainsNewerSettingsAfterRestart() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let entered = expectation(description: "Settings upload entered") + let gate = BackupDelayGate() + let service = BackupService(defaults: defaults, backupData: { _ in Data("old".utf8) }, uploadBackup: { _, _ in + await gate.wait(started: entered) + try Task.checkCancellation() + }) + let upload = Task { await service.triggerBackup(category: .settings) } + await fulfillment(of: [entered], timeout: 2) + upload.cancel() + service.markBackupRequired(category: .settings, schedule: false) + await gate.release() + let outcome = await upload.value + XCTAssertEqual(outcome, .failed) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + await service.stopObservingBackups() + + let uploaded = expectation(description: "Restart uploads latest settings") + let restarted = BackupService(defaults: defaults, backupData: { _ in Data("latest".utf8) }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.settings.rawValue) + XCTAssertEqual(data, Data("latest".utf8)) + uploaded.fulfill() + }, waitForBackupDelay: {}) + restarted.startObservingBackups() + await fulfillment(of: [uploaded], timeout: 2) + await restarted.stopObservingBackups() + } + + func testImmediateStopRetainsReceivedSettingsChange() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = SettingsViewModel.shared.swipeBalanceToHide + defer { SettingsViewModel.shared.swipeBalanceToHide = original } + let service = BackupService(defaults: defaults, backupData: { _ in Data() }, uploadBackup: { _, _ in + XCTFail("Immediate stop must prevent upload") + }) + service.startObservingBackups() + let received = expectation(description: "Settings notification received") + let subscription = SettingsViewModel.shared.settingsPublisher.first().sink { _ in received.fulfill() } + SettingsViewModel.shared.swipeBalanceToHide = !original + await fulfillment(of: [received], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .settings).running) + } + func testStopWaitsForFinalScheduledStatusWrite() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) diff --git a/journeys/backup-restore/wallet-snapshot-consistency.md b/journeys/backup-restore/wallet-snapshot-consistency.md index e79d4e3233..767d93452d 100644 --- a/journeys/backup-restore/wallet-snapshot-consistency.md +++ b/journeys/backup-restore/wallet-snapshot-consistency.md @@ -45,13 +45,18 @@ these are not ordinary UI journey capabilities. No wallet reset is needed. Verify shutdown and the manual upload both wait for cleanup, including a final status write held after the delay finishes. Release cleanup; verify pending wallet work remains required and resumes on observation restart. + Change wallet/settings state after requesting restart while cleanup is held; + verify no new upload starts before the drain and the latest state uploads + afterward without another edit. Repeat with a canceled settings upload; its + cleanup must not clear a newer required marker. 2. Request a new USDT recovery backup during cleanup and again after observation is stopped. Verify both requests can finish without restarting Lightning, and transient backup failures retain bounded automatic retry. 3. Repeatedly start and immediately stop observation. Change a wallet record only after stop returns; verify the stopped observer does not schedule an upload or mutate its saved backup status. Restart observation and verify a single set of - listeners resumes pending work. + listeners resumes pending work. Also receive a settings-change notification + immediately before stop: its pending marker must survive the stopped listener. The iOS lifecycle unit tests exercise these component boundaries with injected capture/upload and delay controls. They do not prove a full device fault journey. From 1ad665f81364c08f52329767478cd29e75dd8a2f Mon Sep 17 00:00:00 2001 From: benk10 Date: Sun, 25 Oct 2026 05:29:53 +0100 Subject: [PATCH 05/12] test: wait for unobstructed USDT back navigation --- BitkitUITests/UsdtWalletUITests.swift | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/BitkitUITests/UsdtWalletUITests.swift b/BitkitUITests/UsdtWalletUITests.swift index 6dccbc5662..fd8cb46e6a 100644 --- a/BitkitUITests/UsdtWalletUITests.swift +++ b/BitkitUITests/UsdtWalletUITests.swift @@ -35,7 +35,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertFalse(app.staticTexts["Could not update USDT. Check your connection and try again."].exists) XCTAssertFalse(app.staticTexts["Older activity is still syncing. Your balance is up to date when the connection is available."].exists) capture(app, "USDT unknown wallet in German region") - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) app.buttons["Send"].tap() XCTAssertTrue(app.buttons["RecipientManual"].waitForExistence(timeout: 5)) app.buttons["RecipientManual"].tap() @@ -65,9 +65,9 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertTrue(network.isEnabled) network.tap() XCTAssertTrue(app.buttons["UsdtNetwork-Polygon"].waitForExistence(timeout: 5)) - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(app.buttons["UsdtReview"].waitForExistence(timeout: 5)) - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) let restoredRecipient = app.textViews["RecipientInput"] XCTAssertTrue(restoredRecipient.waitForExistence(timeout: 5)) XCTAssertEqual(restoredRecipient.value as? String, recipient) @@ -174,6 +174,16 @@ final class UsdtWalletUITests: XCTestCase { capture(app, "USDT saved activity offline after restart") } + @MainActor + private func tapBack(in app: XCUIApplication) throws { + let buttons = app.buttons.matching(identifier: "NavigationBack") + let available = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + buttons.allElementsBoundByIndex.contains(where: \.isHittable) + }, object: app) + XCTAssertEqual(XCTWaiter.wait(for: [available], timeout: 10), .completed, app.debugDescription) + try XCTUnwrap(buttons.allElementsBoundByIndex.first(where: \.isHittable)).tap() + } + @MainActor private func capture(_ app: XCUIApplication, _ name: String) { let attachment = XCTAttachment(screenshot: app.screenshot()) @@ -223,7 +233,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertFalse(amountlessUri.contains("uint256=")) app.buttons["SpecifyInvoiceButton"].tap() app.buttons["N5"].tap() - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(qr.waitForExistence(timeout: 5)) XCTAssertEqual(qr.label, amountlessUri) app.buttons["SpecifyInvoiceButton"].tap() @@ -234,7 +244,7 @@ final class UsdtWalletUITests: XCTestCase { XCTAssertTrue(committedUri.contains("uint256=3000000")) app.buttons["SpecifyInvoiceButton"].tap() app.buttons["N5"].tap() - try XCTUnwrap(app.buttons.matching(identifier: "NavigationBack").allElementsBoundByIndex.first(where: \.isHittable)).tap() + try tapBack(in: app) XCTAssertTrue(qr.waitForExistence(timeout: 5)) XCTAssertEqual(qr.label, committedUri) app.buttons["UsdtReceiveDetails"].tap() From ca10ace721cf718331a66e594607b226034e2370 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 01:04:59 +0200 Subject: [PATCH 06/12] test: retain navigation timeout evidence --- .../SendConfirmationLifecycleTests.swift | 37 ++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/BitkitTests/SendConfirmationLifecycleTests.swift b/BitkitTests/SendConfirmationLifecycleTests.swift index d36bb0f220..d033e469ad 100644 --- a/BitkitTests/SendConfirmationLifecycleTests.swift +++ b/BitkitTests/SendConfirmationLifecycleTests.swift @@ -581,7 +581,42 @@ private final class SendConfirmationTestNavigation { while visibleRoutes != [route], ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } - XCTAssertEqual(visibleRoutes, [route], file: file, line: line) + let observedRoutes = visibleRoutes + XCTAssertEqual(observedRoutes, [route], file: file, line: line) + guard observedRoutes != [route] else { return } + + XCTContext.runActivity(named: "Navigation appearance deadline") { activity in + let state = XCTAttachment(string: "expected=\(route) visible=\(observedRoutes) path=\(path)") + state.name = "navigation-state" + state.lifetime = .keepAlways + activity.add(state) + + func describe(_ view: UIView, depth: Int = 0) -> String { + let row = "\(String(repeating: " ", count: depth))\(type(of: view)) frame=\(view.frame) hidden=\(view.isHidden) firstResponder=\(view.isFirstResponder)\n" + return row + view.subviews.map { describe($0, depth: depth + 1) }.joined() + } + func describe(_ controller: UIViewController, depth: Int = 0) -> String { + let row = "\(String(repeating: " ", count: depth))\(type(of: controller)) appearing=\(controller.isBeingPresented) disappearing=\(controller.isBeingDismissed) transitioning=\(controller.transitionCoordinator != nil)\n" + let children = controller.children.map { describe($0, depth: depth + 1) }.joined() + let presented = controller.presentedViewController.map { describe($0, depth: depth + 1) } ?? "" + return row + children + presented + } + let windows = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.flatMap(\.windows) + for (index, window) in windows.enumerated() { + let controllers = window.rootViewController.map { describe($0) } ?? "No root view controller\n" + let hierarchy = XCTAttachment(string: "key=\(window.isKeyWindow)\n" + controllers + describe(window)) + hierarchy.name = "deadline-window-\(index)-hierarchy" + hierarchy.lifetime = .keepAlways + activity.add(hierarchy) + guard !window.isHidden, !window.bounds.isEmpty else { continue } + let screenshot = XCTAttachment(image: UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: false) + }) + screenshot.name = "deadline-window-\(index)" + screenshot.lifetime = .keepAlways + activity.add(screenshot) + } + } } } From 494c9492596100e198b0bdb91c712ebe5888d929 Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 21:51:49 +0200 Subject: [PATCH 07/12] fix: retry backup transport failures and coalesce status writes --- Bitkit/Services/BackupService.swift | 17 +++++- BitkitTests/BackupServiceTests.swift | 85 ++++++++++++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 102 insertions(+), 2 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 7903e1c8e7..03f1257119 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -357,11 +357,24 @@ class BackupService { case PaykitError.ConcurrentUpdate, PaykitError.SharedStateBusy, PaykitError.Transport, VssError.ConnectionError, VssError.NetworkError, VssError.StoreError, VssError.PutError: true + case let VssError.UnknownError(details): + isVssRequestSendFailure(details) default: false } } + private static func isVssRequestSendFailure(_ details: String) -> Bool { + let prefix = "error sending request for url (" + guard details.hasPrefix(prefix), details.hasSuffix(")"), + let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast())), + url.scheme == "http" || url.scheme == "https", + let host = url.host, !host.isEmpty, + url.path.hasSuffix("/putObjects") + else { return false } + return true + } + func persistWalletBackup() async throws { do { try await writeWalletBackup() @@ -989,7 +1002,9 @@ class BackupService { statusUpdateQueue.sync { var statuses = getAllBackupStatuses() let currentStatus = statuses[category] ?? BackupItemStatus() - statuses[category] = update(currentStatus) + let nextStatus = update(currentStatus) + guard statuses[category] != nextStatus else { return } + statuses[category] = nextStatus saveBackupStatuses(statuses) } } diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 76ae93fabb..a8b78a243c 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -1,10 +1,79 @@ @testable import Bitkit import Combine import Paykit +import VssRustClientFfi import XCTest @MainActor final class BackupServiceTests: XCTestCase { + func testReleasedVssConnectionErrorIsTemporaryWithoutBroadUnknownRetry() { + XCTAssertTrue(BackupService.isTemporaryBackupFailure( + VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)") + )) + XCTAssertTrue(BackupService.isTemporaryBackupFailure( + VssError.UnknownError(errorDetails: "error sending request for url (https://backup.example/vss/putObjects)") + )) + for details in ["invalid ciphertext", "permission denied", "HTTP status client error (401 Unauthorized)", + "error sending request for url (not a URL)", "prefix error sending request for url (https://example.com)", + "error sending request for url (https://example.com/getObject)", + "error sending request for url (file://example.com/putObjects)", + "error sending request for url (https:///putObjects)", + "error sending request for url (https://example.com/putObjects) suffix"] + { + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.UnknownError(errorDetails: details))) + } + XCTAssertFalse(BackupService.isTemporaryBackupFailure(URLError(.notConnectedToInternet))) + XCTAssertFalse(BackupService.isTemporaryBackupFailure(CancellationError())) + } + + func testReleasedVssConnectionFailureRetriesStoppedUsdtWithBoundedBackoff() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "Recovery upload acknowledged after connection resumes") + var attempts = 0 + var delays: [UInt64] = [] + let payload = Data("same-signed-recovery".utf8) + let service = BackupService(defaults: defaults, backupData: { _ in payload }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.usdt.rawValue) + XCTAssertEqual(data, payload) + attempts += 1 + if attempts <= 8 { + throw VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)") + } + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { delays.append($0) }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.usdt].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .usdt) + await fulfillment(of: [completed], timeout: 3) + subscription.cancel() + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 9) + XCTAssertEqual(delays, [10, 20, 40, 80, 160, 300, 300, 300].map { UInt64($0) * 1_000_000_000 }) + XCTAssertFalse(service.getBackupStatus(category: .usdt).isRequired) + } + + func testRepeatedPendingNotificationsDoNotRewriteUnchangedDurableStatus() throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(CountingBackupDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let required = UInt64(Date().timeIntervalSince1970) + 3600 + let pending = BackupItemStatus(synced: 0, required: required, running: false) + try defaults.set(JSONEncoder().encode([BackupCategory.wallet.rawValue: pending]), forKey: "backupStatuses") + let service = BackupService(defaults: defaults) + let writes = defaults.backupStatusWrites + for _ in 0 ..< 200 { + service.markBackupRequired(category: .wallet, schedule: false) + } + XCTAssertEqual(defaults.backupStatusWrites, writes) + XCTAssertEqual(service.getBackupStatus(category: .wallet), pending) + let restarted = BackupService(defaults: defaults) + XCTAssertEqual(restarted.getBackupStatus(category: .wallet), pending) + } + func testChangesDuringCaptureAndUploadRemainRequired() async throws { for changeDuringCapture in [true, false] { let suite = "BackupServiceTests.\(UUID().uuidString)" @@ -699,6 +768,22 @@ private final class WalletBackupSdk: PaykitSdk, @unchecked Sendable { } } +private final class CountingBackupDefaults: UserDefaults { + private let writeLock = NSLock() + private var writes = 0 + + var backupStatusWrites: Int { + writeLock.withLock { writes } + } + + override func set(_ value: Any?, forKey defaultName: String) { + if defaultName == "backupStatuses" { + writeLock.withLock { writes += 1 } + } + super.set(value, forKey: defaultName) + } +} + private actor BackupDelayGate { private(set) var isHeld = true private(set) var didStop = false diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 3cba6c7e79..94995fe117 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Fixed a crash when backup observation stops and ensured pending backups resume safely after restart. +Prevent crashes when backup observation stops and resume pending backups after restart or temporary connection failures without redundant status writes. From ff999a50e24326ad45fb033c61155b95c041d1be Mon Sep 17 00:00:00 2001 From: benk10 Date: Mon, 26 Oct 2026 23:11:18 +0200 Subject: [PATCH 08/12] fix: complete wallet initialization once --- .../Onboarding/InitializingWalletView.swift | 11 +++++++++ BitkitTests/InitializingWalletViewTests.swift | 23 +++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/Bitkit/Views/Onboarding/InitializingWalletView.swift b/Bitkit/Views/Onboarding/InitializingWalletView.swift index 63f1a22ea7..e56638cc01 100644 --- a/Bitkit/Views/Onboarding/InitializingWalletView.swift +++ b/Bitkit/Views/Onboarding/InitializingWalletView.swift @@ -10,11 +10,22 @@ struct InitializingWalletView: View { @Binding var nodeLifecycleState: NodeLifecycleState let onComplete: () -> Void + init( + nodeLifecycleState: Binding, + initialPercentage: Double = 0, + onComplete: @escaping () -> Void + ) { + _nodeLifecycleState = nodeLifecycleState + _percentage = State(initialValue: initialPercentage) + self.onComplete = onComplete + } + private var shouldFinish: Bool { nodeLifecycleState == .running } private func handleCompletion() { + guard shouldFinish, !shouldStopAnimation else { return } timer?.invalidate() shouldStopAnimation = true Haptics.stopHaptics() diff --git a/BitkitTests/InitializingWalletViewTests.swift b/BitkitTests/InitializingWalletViewTests.swift index 7e23a21190..a8eb9b0780 100644 --- a/BitkitTests/InitializingWalletViewTests.swift +++ b/BitkitTests/InitializingWalletViewTests.swift @@ -4,6 +4,29 @@ import XCTest @MainActor final class InitializingWalletViewTests: XCTestCase { + func testNormalizingCompletedProgressInvokesCompletionOnce() async { + var completionCount = 0 + let completion = expectation(description: "Wallet initialization completes once") + let window = UIWindow(frame: UIScreen.main.bounds) + window.rootViewController = UIHostingController(rootView: InitializingWalletView( + nodeLifecycleState: .constant(.running), initialPercentage: 98.75 + ) { + completionCount += 1 + if completionCount == 1 { + completion.fulfill() + } + }) + window.makeKeyAndVisible() + defer { + window.isHidden = true + window.rootViewController = nil + } + + await fulfillment(of: [completion], timeout: 3) + try? await Task.sleep(for: .milliseconds(200)) + XCTAssertEqual(completionCount, 1) + } + func testSlowRetryWaitsForRunningNodeBeforeCompleting() async { let state = InitializationTestState() var completionCount = 0 diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 94995fe117..0136537fdc 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Prevent crashes when backup observation stops and resume pending backups after restart or temporary connection failures without redundant status writes. +Preserve pending backups through observation changes and temporary connection failures, and complete wallet initialization only once after node startup. From bfc4a5e87b2694cf4906d1c6aa784e2fa1c3e78b Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 27 Oct 2026 19:52:39 +0200 Subject: [PATCH 09/12] fix: retain backup changes while stopped uploads drain --- Bitkit/Services/BackupService.swift | 10 ++-- BitkitTests/BackupServiceTests.swift | 69 ++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 03f1257119..873bb1a37f 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -113,7 +113,8 @@ class BackupService { @MainActor weak var usdtWallet: UsdtWalletManager? private var backupJobs: [BackupCategory: Task] = [:] private var runningBackupTasks: [BackupCategory: Task] = [:] - @MainActor private var cancellables = Set() + @MainActor private var dataStoreListeners = Set() + @MainActor private var statusListeners = Set() @MainActor private var periodicCheckTask: Task? @MainActor private var observationTask: Task? @MainActor private var isObserving = false @@ -212,7 +213,7 @@ class BackupService { guard !shouldSkipBackup(), !isObserving else { return } isObserving = true Logger.debug("Start observing backup statuses and data store changes", context: "BackupService") - cancellables.formUnion(listeners) + dataStoreListeners.formUnion(listeners) startBackupStatusObservers() startPeriodicBackupFailureCheck() } @@ -224,7 +225,7 @@ class BackupService { let stopping = Task { await previous?.value isObserving = false - cancellables.removeAll() + statusListeners.removeAll() periodicCheckTask?.cancel() periodicCheckTask = nil @@ -248,6 +249,7 @@ class BackupService { } await walletBackupWriter.waitUntilIdle() await usdtBackupWriter.waitUntilIdle() + dataStoreListeners.removeAll() try? await ServiceQueue.background(.backup) { self.isStoppingBackups = false } @@ -685,7 +687,7 @@ class BackupService { } } } - .store(in: &cancellables) + .store(in: &statusListeners) } Logger.debug("Started \(BackupCategory.allCases.count) backup status observers", context: "BackupService") diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index a8b78a243c..ec9ba4f2fd 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -352,6 +352,75 @@ final class BackupServiceTests: XCTestCase { XCTAssertEqual(uploads.map(\.data), [Data("initial".utf8), Data("updated".utf8)]) } + func testStopRetainsEditsUntilAcknowledgedUploadDrains() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let original = SettingsViewModel.shared.swipeBalanceToHide + defer { SettingsViewModel.shared.swipeBalanceToHide = original } + let entered = expectation(description: "Captured settings upload entered") + let cancelled = expectation(description: "Stop cancelled the held upload") + let unexpectedUpload = expectation(description: "Stopped observers cannot upload new data") + unexpectedUpload.isInverted = true + let gate = BackupDelayGate() + let recorder = BackupRecorder() + var data = Data("initial".utf8) + var holdUpload = false + var mayUploadLatest = false + let service = BackupService(defaults: defaults, backupData: { _ in data }, uploadBackup: { key, bytes in + await recorder.recordUpload(key: key, data: bytes) + if bytes == Data("latest".utf8), !mayUploadLatest { + unexpectedUpload.fulfill() + } + if holdUpload, key == BackupCategory.settings.rawValue { + holdUpload = false + await withTaskCancellationHandler { + await gate.wait(started: entered) + } onCancel: { cancelled.fulfill() } + } + }, waitForBackupDelay: {}) + await service.triggerBackup(category: .settings) + await service.triggerBackup(category: .wallet) + service.startObservingBackups() + holdUpload = true + data = Data("captured".utf8) + SettingsViewModel.shared.swipeBalanceToHide = !original + await fulfillment(of: [entered], timeout: 2) + let stop = Task { await service.stopObservingBackups() } + await fulfillment(of: [cancelled], timeout: 2) + + data = Data("latest".utf8) + SettingsViewModel.shared.swipeBalanceToHide = original + try Bitkit.WatchOnlyAccountStore.save([], defaults: defaults) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertTrue(service.getBackupStatus(category: .wallet).isRequired) + await gate.release() + await stop.value + for category in [BackupCategory.settings, .wallet] { + XCTAssertTrue(service.getBackupStatus(category: category).isRequired) + XCTAssertFalse(service.getBackupStatus(category: category).running) + } + await fulfillment(of: [unexpectedUpload], timeout: 0.1) + let stoppedUploads = await recorder.uploads + XCTAssertEqual(stoppedUploads.map(\.data), [Data("initial".utf8), Data("initial".utf8), Data("captured".utf8)]) + + mayUploadLatest = true + let completed = expectation(description: "Restart uploads both latest sources") + let subscription = service.backupStatusesPublisher + .filter { statuses in + [BackupCategory.settings, .wallet].allSatisfy { category in + statuses[category].map { !$0.isRequired && !$0.running } == true + } + }.first().sink { _ in completed.fulfill() } + service.startObservingBackups() + await fulfillment(of: [completed], timeout: 2) + subscription.cancel() + await service.stopObservingBackups() + let latest = await recorder.uploads.filter { $0.data == Data("latest".utf8) } + XCTAssertEqual(Set(latest.map(\.key)), [BackupCategory.settings.rawValue, BackupCategory.wallet.rawValue]) + XCTAssertEqual(latest.count, 2) + } + func testCancelledUploadRetainsNewerSettingsAfterRestart() async throws { let suite = "BackupServiceTests.\(UUID().uuidString)" let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) From 1dd6d2fb8974cffc674802180d5f8ef620a60959 Mon Sep 17 00:00:00 2001 From: benk10 Date: Fri, 30 Oct 2026 00:59:49 +0200 Subject: [PATCH 10/12] test: isolate identity publication return deadline --- BitkitTests/PaykitSdkClientConfigTests.swift | 31 ++++++++++++++++---- 1 file changed, 25 insertions(+), 6 deletions(-) diff --git a/BitkitTests/PaykitSdkClientConfigTests.swift b/BitkitTests/PaykitSdkClientConfigTests.swift index 6c919cff3b..88d2858a95 100644 --- a/BitkitTests/PaykitSdkClientConfigTests.swift +++ b/BitkitTests/PaykitSdkClientConfigTests.swift @@ -586,14 +586,22 @@ final class PaykitSdkClientConfigTests: XCTestCase { try Keychain.delete(key: .paykitKeyGeneration(publicKey: publicKey)) let republishStarted = expectation(description: "Republish started") let republishFinished = expectation(description: "Republish finished") + let republishFinishedBeforeGateOpened = expectation(description: "Republish finished before gate opened") + republishFinishedBeforeGateOpened.isInverted = true let activationReturned = expectation(description: "Activation returned") let gate = AsyncStream.makeStream() + defer { gate.continuation.finish() } let bootstrap = CacheActivationBootstrap(noPointer: .init()) bootstrap.republishOperation = { republishStarted.fulfill() + var gateOpened = false for await _ in gate.stream { + gateOpened = true break } + if !gateOpened { + republishFinishedBeforeGateOpened.fulfill() + } republishFinished.fulfill() return true } @@ -608,13 +616,24 @@ final class PaykitSdkClientConfigTests: XCTestCase { try await service.activateRegisteredIdentity(.init(result: result, walletGeneration: 0)) activationReturned.fulfill() } - // Shorter than the republish timeout, so an activation that awaited the publication would miss it. - await fulfillment(of: [activationReturned, republishStarted], timeout: 2) - XCTAssertEqual(bootstrap.republishedKeys, [result.publicKey]) + defer { activation.cancel() } + try await withTaskCancellationHandler { + let setup = await XCTWaiter.fulfillment(of: [republishStarted], timeout: 10) + XCTAssertEqual(setup, .completed, "Identity activation must reach the gated publication") + if setup == .completed { + // Measure the return after credential preparation, below the unchanged five-second publication cap. + await fulfillment(of: [activationReturned, republishFinishedBeforeGateOpened], timeout: 2) + XCTAssertEqual(bootstrap.republishedKeys, [result.publicKey]) + } - gate.continuation.yield() - await fulfillment(of: [republishFinished], timeout: 1) - try await activation.value + gate.continuation.yield() + gate.continuation.finish() + await fulfillment(of: [republishFinished], timeout: 1) + try await activation.value + } onCancel: { + gate.continuation.finish() + activation.cancel() + } } func testSessionImportDoesNotCreateRuntimeBeforeBootstrapSucceeds() async throws { From 4e6c06ed79d0b916529b293fc83cd98d8acb0d33 Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 14:31:19 -0500 Subject: [PATCH 11/12] fix: publish backup idle after scheduled admission cleanup --- Bitkit/Services/BackupService.swift | 8 +-- .../BackupForegroundRecoveryTests.swift | 50 +++++++++++++++++++ changelog.d/next/1123.fixed.md | 2 +- 3 files changed, 56 insertions(+), 4 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index 6949a8ca54..d810c600ac 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1054,10 +1054,12 @@ class BackupService { break } } - updateBackupStatus(category: category) { status in - BackupItemStatus(synced: status.synced, required: status.required, running: false) + _ = try? await ServiceQueue.background(.backup) { + self.backupJobs.removeValue(forKey: category) + self.updateBackupStatus(category: category) { status in + BackupItemStatus(synced: status.synced, required: status.required, running: false) + } } - _ = try? await ServiceQueue.background(.backup) { self.backupJobs.removeValue(forKey: category) } if outcome.canRetryPendingBackup, !Task.isCancelled, getBackupStatus(category: category).isRequired, !shouldSkipBackup(category: category) { diff --git a/BitkitTests/BackupForegroundRecoveryTests.swift b/BitkitTests/BackupForegroundRecoveryTests.swift index 6d3b8b8341..4989593d69 100644 --- a/BitkitTests/BackupForegroundRecoveryTests.swift +++ b/BitkitTests/BackupForegroundRecoveryTests.swift @@ -308,6 +308,56 @@ final class BackupForegroundRecoveryTests: XCTestCase { await service.stopObservingBackups() } + func testScheduledIdlePublicationWaitsForForegroundAdmissionCleanup() async throws { + let fixture = try Fixture(categories: [.settings]) + defer { fixture.removeDefaults() } + let uploads = UploadRecorder() + let delayStarted = expectation(description: "Initial scheduled backup is held") + let queueHeld = expectation(description: "Backup admission queue is held") + let prematureIdle = expectation(description: "Idle must not precede admission cleanup") + prematureIdle.isInverted = true + let settled = expectation(description: "Scheduled backup becomes available for foreground retry") + let (delay, releaseDelay) = AsyncStream.makeStream() + let releaseQueue = DispatchSemaphore(value: 0) + defer { + releaseDelay.finish() + releaseQueue.signal() + } + let service = fixture.service(uploadBackup: { key, _ in + await uploads.record(key) + }, waitForBackupDelay: { + delayStarted.fulfill() + for await _ in delay {} + throw CancellationError() + }) + await service.startObservingBackups()?.value + await fulfillment(of: [delayStarted], timeout: 2) + Bitkit.ServiceQueue.ServiceTypes.backup.queue.async { + queueHeld.fulfill() + XCTAssertEqual(releaseQueue.wait(timeout: .now() + 2), .success) + } + await fulfillment(of: [queueHeld], timeout: 2) + let earlySubscription = service.backupStatusesPublisher + .filter { $0[.settings]?.running == false } + .first().sink { _ in prematureIdle.fulfill() } + releaseDelay.finish() + await fulfillment(of: [prematureIdle], timeout: 0.2) + earlySubscription.cancel() + let settledSubscription = service.backupStatusesPublisher + .filter { $0[.settings]?.running == false } + .first().sink { _ in settled.fulfill() } + defer { settledSubscription.cancel() } + releaseQueue.signal() + await fulfillment(of: [settled], timeout: 2) + + await service.setAppActive(true)?.value + let recorded = await uploads.counts + XCTAssertEqual(recorded, [BackupCategory.settings.rawValue: 1]) + XCTAssertFalse(service.getBackupStatus(category: .settings).isRequired) + service.setAppActive(false) + await service.stopObservingBackups() + } + private func startAfterPendingJobsSettle(_ service: BackupService, categories: [BackupCategory]) async { let settled = categories.map { expectation(description: "Initial \($0.rawValue) scheduling settled") } let subscriptions = zip(categories, settled).map { category, completed in diff --git a/changelog.d/next/1123.fixed.md b/changelog.d/next/1123.fixed.md index 0136537fdc..ad9fb38d18 100644 --- a/changelog.d/next/1123.fixed.md +++ b/changelog.d/next/1123.fixed.md @@ -1 +1 @@ -Preserve pending backups through observation changes and temporary connection failures, and complete wallet initialization only once after node startup. +Preserve pending backups through observation changes and temporary connection failures, keep foreground retries available as scheduled backups finish, and complete wallet initialization only once after node startup. From 11fb65d780055a10081bd9d7e12fee61949d140d Mon Sep 17 00:00:00 2001 From: benk10 Date: Tue, 3 Nov 2026 17:38:38 -0500 Subject: [PATCH 12/12] fix: retry temporary backup authentication failures --- Bitkit/Services/BackupService.swift | 29 ++++++--- BitkitTests/BackupServiceTests.swift | 90 ++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 8 deletions(-) diff --git a/Bitkit/Services/BackupService.swift b/Bitkit/Services/BackupService.swift index d810c600ac..f6fc217b19 100644 --- a/Bitkit/Services/BackupService.swift +++ b/Bitkit/Services/BackupService.swift @@ -1,6 +1,7 @@ import BitkitCore import Combine import Foundation +import Network import Paykit import VssRustClientFfi @@ -499,23 +500,35 @@ class BackupService { case MetadataBackupError.walletTemporarilyUnavailable, PaykitError.ConcurrentUpdate, PaykitError.SharedStateBusy, PaykitError.Transport, VssError.ConnectionError, VssError.NetworkError, VssError.StoreError, VssError.PutError: - true + return true case let VssError.UnknownError(details): - isVssRequestSendFailure(details) + return isVssRequestSendFailure(details, pathSuffix: "/putObjects") + case let VssError.AuthError(details): + let prefix = "error performing external request: " + let requestFailure = details.hasPrefix(prefix) ? String(details.dropFirst(prefix.count)) : details + return isVssRequestSendFailure(requestFailure) default: - false + return false } } - private static func isVssRequestSendFailure(_ details: String) -> Bool { + private static func isVssRequestSendFailure(_ details: String, pathSuffix: String? = nil) -> Bool { let prefix = "error sending request for url (" + let invalidHostCharacters = CharacterSet.whitespacesAndNewlines.union(.controlCharacters) + .union(CharacterSet(charactersIn: "/%@?#\\")) guard details.hasPrefix(prefix), details.hasSuffix(")"), - let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast())), + let url = URLComponents(string: String(details.dropFirst(prefix.count).dropLast()), encodingInvalidCharacters: false), url.scheme == "http" || url.scheme == "https", - let host = url.host, !host.isEmpty, - url.path.hasSuffix("/putObjects") + let host = url.host, !host.isEmpty, host.rangeOfCharacter(from: invalidHostCharacters) == nil, + (0 ... 65535).contains(url.port ?? 0), + url.url != nil else { return false } - return true + if host.hasPrefix("[") { + guard host.hasSuffix("]"), IPv6Address(String(host.dropFirst().dropLast())) != nil else { return false } + } else if host.contains(":") || host.contains("[") || host.contains("]") { + return false + } + return pathSuffix.map { url.path.hasSuffix($0) } ?? true } func persistWalletBackup() async throws { diff --git a/BitkitTests/BackupServiceTests.swift b/BitkitTests/BackupServiceTests.swift index 58f1511ba9..fe70679a86 100644 --- a/BitkitTests/BackupServiceTests.swift +++ b/BitkitTests/BackupServiceTests.swift @@ -6,6 +6,96 @@ import XCTest @MainActor final class BackupServiceTests: XCTestCase { + func testReleasedVssAuthTransportIsTemporaryWithoutRetryingAuthorizationFailures() { + let requestFailure = "error sending request for url (https://backup.example/lnurl_auth/auth)" + for details in [requestFailure, "error performing external request: \(requestFailure)", + "error sending request for url (http://127.0.0.1:1/custom/callback)", + "error sending request for url (http://[::1]:8080/auth?value=a%20b)", + "error sending request for url (https://xn--bcher-kva.example/auth)"] + { + XCTAssertTrue(BackupService.isTemporaryBackupFailure(VssError.AuthError(errorDetails: details)), details) + } + for details in ["permission denied", "invalid JWT", "HTTP status client error (401 Unauthorized)", + "error decoding response body", "error performing external request: permission denied", + "error performing external request: error performing external request: \(requestFailure)", + "prefix \(requestFailure)", "\(requestFailure) suffix", + "error sending request for url (not a URL)", + "error sending request for url (file://example.com/auth)", + "error sending request for url (https:///auth)", + "error sending request for url (https://backup.example/auth) trailing)", + "error sending request for url (https://backup.example/auth path)", + "error sending request for url (https://%20/auth)", + "error sending request for url (https://auth%20example.com/auth)", + "error sending request for url (https://%2F/auth)", + "error sending request for url (https://%3A/auth)", + "error sending request for url (https://%40/auth)", + "error sending request for url (https://[abc]/auth)", + "error sending request for url (https://[:::]/auth)", + "error sending request for url (https://host:99999/auth)"] + { + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.AuthError(errorDetails: details)), details) + } + XCTAssertFalse(BackupService.isTemporaryBackupFailure(VssError.UnknownError(errorDetails: requestFailure))) + } + + func testReleasedVssAuthTransportRetriesScheduledSettingsWithoutObservation() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let completed = expectation(description: "Settings acknowledged after auth transport recovers") + var attempts = 0 + var delays: [UInt64] = [] + let payload = Data("settings-snapshot".utf8) + let service = BackupService(defaults: defaults, backupData: { _ in payload }, uploadBackup: { key, data in + XCTAssertEqual(key, BackupCategory.settings.rawValue) + XCTAssertEqual(data, payload) + attempts += 1 + if attempts == 1 { + throw VssError.AuthError(errorDetails: "error performing external request: error sending request for url (http://127.0.0.1:1/auth)") + } + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { delays.append($0) }) + await service.stopObservingBackups() + let subscription = service.backupStatusesPublisher + .filter { $0[.settings].map { !$0.isRequired && !$0.running } == true } + .first().sink { _ in completed.fulfill() } + service.markBackupRequired(category: .settings) + await fulfillment(of: [completed], timeout: 3) + subscription.cancel() + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 2) + XCTAssertEqual(delays, [10_000_000_000]) + XCTAssertFalse(service.getBackupStatus(category: .settings).isRequired) + } + + func testReleasedVssAuthorizationDenialStaysPendingWithoutAutomaticRetry() async throws { + let suite = "BackupServiceTests.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let attempted = expectation(description: "Authorization refused") + let retried = expectation(description: "Authorization refusal automatically retried") + retried.isInverted = true + var attempts = 0 + let service = BackupService(defaults: defaults, backupData: { _ in Data("settings-snapshot".utf8) }, uploadBackup: { _, _ in + attempts += 1 + if attempts == 1 { + attempted.fulfill() + } else { + retried.fulfill() + } + throw VssError.AuthError(errorDetails: "permission denied") + }, waitForBackupDelay: {}, waitForTemporaryFailureDelay: { _ in retried.fulfill() }) + await service.stopObservingBackups() + service.markBackupRequired(category: .settings) + await fulfillment(of: [attempted], timeout: 3) + await fulfillment(of: [retried], timeout: 0.2) + service.setWiping(true) + await service.stopObservingBackups() + XCTAssertEqual(attempts, 1) + XCTAssertTrue(service.getBackupStatus(category: .settings).isRequired) + XCTAssertFalse(service.getBackupStatus(category: .settings).running) + } + func testReleasedVssConnectionErrorIsTemporaryWithoutBroadUnknownRetry() { XCTAssertTrue(BackupService.isTemporaryBackupFailure( VssError.UnknownError(errorDetails: "error sending request for url (http://127.0.0.1:1/putObjects)")