Skip to content

fix: recover app-state sync errors safely - #144

Open
joldmarfilho wants to merge 1 commit into
evolution-foundation:mainfrom
joldmarfilho:fix-recover-app-state-sync
Open

fix: recover app-state sync errors safely#144
joldmarfilho wants to merge 1 commit into
evolution-foundation:mainfrom
joldmarfilho:fix-recover-app-state-sync

Conversation

@joldmarfilho

@joldmarfilho joldmarfilho commented Jul 29, 2026

Copy link
Copy Markdown

Description

Related Issue

Closes #(issue_number)

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement

Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced

Screenshots (if applicable)

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have tested my changes thoroughly
  • Any dependent changes have been merged and published

Additional Notes

Summary by Sourcery

Handle WhatsApp app-state sync errors with controlled recovery and add cooldown-based deduplication for recovery attempts.

Bug Fixes:

  • Recover from app-state incremental sync failures by retrying once as a full sync, then requesting a recovery snapshot from the primary device instead of triggering fatal unlinking.
  • Prevent repeated app-state recovery attempts within a cooldown window to avoid redundant full syncs and recovery requests.

Tests:

  • Add unit test to ensure app-state recovery reservations are deduplicated per collection and per stage.

@sourcery-ai

sourcery-ai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Reviewer's Guide

Implements a controlled, rate-limited app-state recovery flow for WhatsApp app-state sync errors, including a two-stage retry (full sync then recovery request), logging, and tests ensuring per-collection cooldown behavior.

Sequence diagram for controlled app-state sync error recovery

sequenceDiagram
    actor UserDevice
    participant MyClient
    participant Logger
    participant WAClient
    participant PrimaryDevice

    UserDevice->>MyClient: myEventHandler(AppStateSyncError)
    MyClient->>MyClient: handleAppStateSyncError(evt)
    MyClient->>MyClient: reserveAppStateRecovery(evt.Name, evt.FullSync)
    alt [cooldown active]
        MyClient->>Logger: GetLogger(userID)
        Logger-->>MyClient: LogInfo
        MyClient-->>UserDevice: [return]
    else [allowed]
        MyClient->>Logger: GetLogger(userID)
        alt [incremental sync failed]
            Logger-->>MyClient: LogWarn
            MyClient->>WAClient: FetchAppState(ctx, evt.Name, true, false)
        else [full sync failed]
            Logger-->>MyClient: LogWarn
            MyClient->>WAClient: SendPeerMessage(ctx, whatsmeow.BuildAppStateRecoveryRequest(evt.Name))
            WAClient-->>Logger: LogInfo
        end
    end
Loading

File-Level Changes

Change Details Files
Introduce rate-limited reservation mechanism for app-state full sync and recovery requests to avoid repeated recovery flows per collection.
  • Add appStateRecoveryMu and appStateRecovery fields to MyClient to track recovery attempts per appstate collection.
  • Implement reserveAppStateRecovery to record timestamps for full sync and recovery requests with a 15-minute cooldown per stage.
  • Use separate timestamps for full sync and recovery request stages so each can run once per cooldown window per collection.
pkg/whatsmeow/service/whatsmeow.go
Handle AppStateSyncError events by orchestrating incremental, full, and recovery syncs with structured logging and timeouts.
  • Add handleAppStateSyncError to guard against nil events, apply reservation logic, and run recovery flows in a background goroutine with a 30-second timeout.
  • Implement logic: on incremental failure, trigger a controlled full sync; on full sync failure, send an app-state recovery request message instead of fatal recovery.
  • Add detailed log messages for deduplicated attempts, full sync failures, recovery requests, and successful request dispatch.
pkg/whatsmeow/service/whatsmeow.go
Wire new app-state recovery handling into event loop and improve observability of recovery completions.
  • Extend myEventHandler to handle events.AppStateSyncError by delegating to handleAppStateSyncError.
  • Enhance handling of events.AppStateSyncComplete to log successful recovery completions (evt.Recovery) with collection name and version.
pkg/whatsmeow/service/whatsmeow.go
Add unit test to ensure app-state recovery reservation deduplicates attempts per stage and per collection.
  • Create appstate_recovery_test.go under whatsmeow_service package to test reserveAppStateRecovery.
  • Verify that duplicate full sync and duplicate recovery requests are suppressed within cooldown, stages are independent, and different collections do not share cooldown state.
pkg/whatsmeow/service/appstate_recovery_test.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai 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.

Hey - I've left some high level feedback:

  • Consider clearing or pruning entries in appStateRecovery (e.g., on AppStateSyncComplete for a given collection) to avoid unnecessary cooldown after successful recovery and to keep the map from growing over the lifetime of the client.
  • In handleAppStateSyncError, the recovery goroutine uses a fresh background context; consider deriving the context from the client or event lifecycle so that recovery attempts are automatically cancelled when the client is shutting down or the session is no longer valid.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider clearing or pruning entries in `appStateRecovery` (e.g., on `AppStateSyncComplete` for a given collection) to avoid unnecessary cooldown after successful recovery and to keep the map from growing over the lifetime of the client.
- In `handleAppStateSyncError`, the recovery goroutine uses a fresh background context; consider deriving the context from the client or event lifecycle so that recovery attempts are automatically cancelled when the client is shutting down or the session is no longer valid.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

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.

1 participant