From 553da80f8001fe604a830b32bebad02f7b5fc538 Mon Sep 17 00:00:00 2001 From: Tanmay Deep Sharma Date: Thu, 7 May 2026 12:19:13 +0700 Subject: [PATCH] fix(voice): retry ContactInbox lookup on inbound call race A concurrent WhatsApp message webhook for the same wa_id could win the (inbox_id, source_id) insert; the call path then re-raised RecordNotUnique and the outer rescue mislabeled it as a duplicate provider_call_id, silently dropping the connect. Handle the race inside ensure_contact_inbox! and drop the now-redundant outer rescue so unrelated unique violations surface instead of being swallowed. Co-Authored-By: Claude Opus 4.7 (1M context) --- enterprise/app/services/voice/inbound_call_builder.rb | 4 ++++ enterprise/app/services/whatsapp/incoming_call_service.rb | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/enterprise/app/services/voice/inbound_call_builder.rb b/enterprise/app/services/voice/inbound_call_builder.rb index f3388d4f5..7b8b0e684 100644 --- a/enterprise/app/services/voice/inbound_call_builder.rb +++ b/enterprise/app/services/voice/inbound_call_builder.rb @@ -46,12 +46,16 @@ class Voice::InboundCallBuilder # Always look up by (inbox, source_id) first — that pair has a UNIQUE index, so # creating with a colliding source_id under a different contact would raise # RecordNotUnique. Reuse the existing ContactInbox (and its contact) when found. + # A concurrent message webhook for the same wa_id can win the (inbox_id, source_id) + # race; rescue and re-find so the call path doesn't drop the connect. def ensure_contact_inbox! sid = source_id_for_provider existing = inbox.contact_inboxes.find_by(source_id: sid) return existing if existing ContactInbox.create!(contact: ensure_contact!, inbox: inbox, source_id: sid) + rescue ActiveRecord::RecordNotUnique + inbox.contact_inboxes.find_by!(source_id: sid) end def ensure_contact! diff --git a/enterprise/app/services/whatsapp/incoming_call_service.rb b/enterprise/app/services/whatsapp/incoming_call_service.rb index 1bead1013..3abf0f4be 100644 --- a/enterprise/app/services/whatsapp/incoming_call_service.rb +++ b/enterprise/app/services/whatsapp/incoming_call_service.rb @@ -23,8 +23,6 @@ class Whatsapp::IncomingCallService return accept_outbound_call(call, payload) if call.outgoing? Rails.logger.info "[WHATSAPP CALL] Duplicate inbound connect for #{payload[:id]}; ignoring" - rescue ActiveRecord::RecordNotUnique - Rails.logger.warn "[WHATSAPP CALL] Duplicate provider_call_id received: #{payload[:id]}" end def create_inbound_call(payload)