Skip to content

Codex/fix whatsmeow lifecycle - #237

Open
jadercarvalhoPRM wants to merge 5 commits into
evolution-foundation:mainfrom
jadercarvalhoPRM:codex/fix-whatsmeow-lifecycle
Open

jadercarvalhoPRM wants to merge 5 commits into
evolution-foundation:mainfrom
jadercarvalhoPRM:codex/fix-whatsmeow-lifecycle

Conversation

@jadercarvalhoPRM

@jadercarvalhoPRM jadercarvalhoPRM commented Nov 4, 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

Harden WhatsApp client lifecycle and authentication handling while validating the fix through integration gates and publishing an attested release image.

Bug Fixes:

  • Stabilize WhatsApp client lifecycle management to prevent duplicate generations, stale QR publication, leaked handlers, and unsafe concurrent reconnect, stop, logout, and delete operations.
  • Keep WhatsMeow's native reconnect behavior active while validating that message sends use the current connected and logged-in client.
  • Reuse the shared authentication database store across client starts and recover cleanly from transient initialization failures.
  • Apply the dynamically fetched WhatsApp Web version consistently to the WhatsMeow handshake state to avoid client-outdated connection failures.
  • Prevent sensitive URLs, identifiers, recipient data, tokens, response bodies, QR payloads, and storage URLs from being written to logs.

Enhancements:

  • Centralize instance lifecycle ownership behind synchronized service APIs and generation-aware cancellation.
  • Update the runtime and dependency baseline to newer Go, WhatsMeow, and supporting library versions.

Build:

  • Pin and refresh the Go and Alpine container bases and remove redundant package index updates.

CI:

  • Add CI gates for Go tests, vetting, race detection, real WhatsApp QR integration, runtime dependency smoke tests, vulnerability scanning, multi-architecture image publication, SBOM/provenance generation, and sanitized evidence artifacts.

Deployment:

  • Publish lifecycle-fix images to GHCR with immutable/channel tags and preserve an explicit rollback image reference.

Tests:

  • Add coverage for authentication-store reuse and recovery, lifecycle route serialization, stale-generation protection, reconnect behavior, dynamic WhatsApp version application, connection readiness, and log redaction.

@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR fixes WhatsMeow lifecycle races and outdated-client failures by introducing serialized per-instance generation ownership, shared auth-store reuse, dynamic handshake version application, stronger session validation, and comprehensive regression/integration coverage; it also hardens logging and adds CI workflows for runtime, vulnerability, multi-architecture publication, and supply-chain verification.

Sequence diagram for serialized WhatsMeow instance lifecycle

sequenceDiagram
    participant API as InstanceService
    participant WM as WhatsmeowService
    participant Gen as lifecycleGeneration
    participant Client as WhatsmeowClient
    participant Repo as InstanceRepository

    API->>WM: StartInstance(instanceId)
    WM->>WM: lifecycleLock(instanceId)
    WM->>WM: newGeneration(instanceId)
    WM->>WM: startClient(clientData, generation)
    WM->>Client: Connect()
    WM->>WM: publishClient(instanceId, generation, client)
    WM->>Gen: generationStarted(instanceId, generation)

    API->>WM: StopInstance(instanceId, token, logout)
    WM->>Gen: beginStop()
    Gen-->>WM: ctx.Done()
    WM->>Client: Logout(context) 
    WM->>Client: Disconnect()
    WM->>Gen: finishGeneration(instanceId, generation, client, myClient)
    Gen->>Gen: workers.Wait()
    WM->>Repo: UpdateConnected(instanceId, false, reason)
Loading

File-Level Changes

Change Details Files
Centralize WhatsMeow client lifecycle ownership around per-instance generations and serialized lifecycle operations.
  • Replace direct shared-map access in service routes with lifecycle service accessors.
  • Add per-instance locks, generation contexts, stop acknowledgement, stale-generation checks, and native auto-reconnect handling.
  • Route connect, reconnect, disconnect, logout, delete, QR, and message operations through the lifecycle owner.
pkg/whatsmeow/service/whatsmeow.go
pkg/instance/service/instance_service.go
pkg/call/service/call_service.go
pkg/chat/service/chat_service.go
pkg/community/service/community_service.go
pkg/group/service/group_service.go
pkg/label/service/label_service.go
pkg/message/service/message_service.go
pkg/newsletter/service/newsletter_service.go
pkg/sendMessage/service/send_service.go
pkg/user/service/user_service.go
Make WhatsApp protocol versioning dynamic and compatible with the current WhatsMeow handshake state.
  • Fetch and apply the runtime WhatsApp Web version to both WhatsMeow global and device handshake version fields.
  • Serialize global version updates and preserve/restore state in tests.
  • Add an opt-in real WhatsApp QR integration gate that detects outdated-client failures.
pkg/whatsmeow/service/whatsmeow.go
pkg/whatsmeow/service/wa_version_test.go
pkg/whatsmeow/service/wa_version_integration_test.go
go.mod
go.sum
Reuse the process-owned authentication database pool instead of opening a new store for each client generation.
  • Cache and mutex-protect the auth SQL store container.
  • Use the existing PostgreSQL connection pool and retry initialization after transient failures.
  • Cover SQLite, PostgreSQL, concurrent starts, reuse, and recovery behavior with tests.
pkg/whatsmeow/service/whatsmeow.go
pkg/whatsmeow/service/auth_store_test.go
Prevent sensitive identifiers, URLs, tokens, QR payloads, and response bodies from entering logs.
  • Remove or redact identity, recipient, webhook URL/query, media URL, passkey, QR, and storage URL logging.
  • Stop printing poll and MinIO debug data.
  • Verify webhook secret redaction with a focused test and sanitize CI/runtime evidence.
pkg/events/webhook/webhook_producer.go
pkg/events/webhook/webhook_producer_test.go
pkg/group/service/group_service.go
pkg/message/service/message_service.go
pkg/middleware/jid_validation_middleware.go
pkg/newsletter/service/newsletter_service.go
pkg/poll/service/poll_service.go
pkg/sendMessage/service/send_service.go
pkg/storage/minio/media_storage.go
pkg/user/service/user_service.go
pkg/utils/utils.go
pkg/whatsmeow/service/whatsmeow.go
docker/ci/smoke-runtime.sh
Strengthen session validation and update compatibility with newer dependency APIs.
  • Require both connected and logged-in state before sending messages.
  • Update profile-status calls and refresh Go, WhatsMeow, messaging, image, and networking dependencies.
  • Add focused connection-state coverage.
pkg/sendMessage/service/send_service.go
pkg/sendMessage/service/connection_state_test.go
pkg/user/service/user_service.go
go.mod
go.sum
Add CI gates for protocol, runtime, image, security, and supply-chain verification.
  • Run Go tests, vet, race tests, build, and real WhatsApp QR verification.
  • Build and smoke-test an amd64 image with PostgreSQL, Redis, and API readiness checks.
  • Scan the image, publish multi-architecture GHCR artifacts, and attach provenance/SBOM metadata with rollback references.
.github/workflows/publish-auth-pool-ghcr.yml
Dockerfile
docker/ci/smoke-runtime.sh
evidence/fix-evolution-go-client-outdated/00-red-production.log
evidence/fix-evolution-go-client-outdated/01-red-test.log
evidence/fix-evolution-go-client-outdated/02-green-test.log
evidence/fix-evolution-go-client-outdated/03-green-real-whatsmeow-qr.log
Add concurrency and lifecycle regression coverage for shutdown ordering, stale workers, reconnect behavior, and route serialization.
  • Verify one lifecycle owner and no handler leaks under concurrent routes.
  • Exercise native reconnect behavior, race-safe cache access, generation identity, broadcast stop, and stale QR suppression.
  • Test immediate start/stop cycles and route-level lifecycle serialization.
pkg/whatsmeow/service/reconnect_contract_test.go
pkg/instance/service/lifecycle_routes_test.go

Possibly linked issues

  • #fix(whatsmeow): call store.SetWAVersion with dynamic webVersion to prevent 405 Client Outdated: The PR applies the fetched/configured version through store.SetWAVersion and updates handshake versions, directly addressing the 405 Client Outdated issue.
  • #unknown: The PR caches one auth sqlstore container and uses the process-owned authDB pool across client starts, preventing reconnects from creating leaked pools.
  • #unknown: The PR removes the Disconnected handler’s concurrent ReconnectClient calls and serializes lifecycle operations, addressing the issue’s race and panic trigger.

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 reviewed your changes and they look great!

Fixed security issues:

  • github.com/chai2010/webp (link)
  • github.com/jackc/pgx/v5 (link)
  • github.com/klauspost/compress (link)
  • github.com/rabbitmq/amqp091-go (link)
  • golang.org/x/crypto (link)
  • golang.org/x/image (link)
  • golang.org/x/net (link)
  • golang.org/x/text (link)

Sourcery assessment

Needs a human reviewer. A lifecycle bug in StopInstance or Logout could disconnect a WhatsApp device and invalidate its stored session, forcing the user to pair again. Reverting restores the previous lifecycle code but cannot restore sessions already invalidated.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

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