Skip to content

fix(messages): prevent duplicate inbox messages from channel echoes - #893

Merged
viethung0o0 merged 1 commit into
mainfrom
fix/instagram-echo-duplicate-messages
Aug 4, 2026
Merged

fix(messages): prevent duplicate inbox messages from channel echoes#893
viethung0o0 merged 1 commit into
mainfrom
fix/instagram-echo-duplicate-messages

Conversation

@viethung0o0

Copy link
Copy Markdown
Contributor

Problem

When the bot replies on Instagram/Messenger, the outbound message is saved once (the Send API returns the mid, stored as sourceId). The channel then echoes that same message back a few seconds later (is_echo: true, same mid). In production this echo was saved a second time, so a single reply appeared twice in the inbox.

The echo dedup already keys on sourceId, but the guard read used the incoming row's own createdAt as its lower bound. Because findBySourceId filters createdAt >= sinceTime, the earlier row (saved ~1.4s before) fell outside the window and was never found, so a duplicate row was inserted.

Fix

Widen the dedup guard read to look back a bounded window (1 day) so it can see the message saved moments earlier, reusing the existing getSafeSinceTime helper. Applied to every dedup lookup in both createOrUpdate and createOrUpdateWithAttachments.

  • Channel-agnostic — fixes the same class of duplicate for Instagram, Messenger, and echo redelivery.
  • No schema change / no migration.
  • Shard fan-out is unchanged in normal operation (shards do not auto-rotate; a 1-day window resolves to the same active shard), and the lookup stays a LIMIT 1 on a highly selective sourceId.

Test plan

  • pnpm --filter @chatbotx.io/database test — 377 passing, incl. 2 new regression tests (createOrUpdate and createOrUpdateWithAttachments) reproducing the send→echo duplicate
  • pnpm --filter @chatbotx.io/database check-types
  • pnpm lint
  • pnpm check:circular — no new circular dependency
  • Manual: reply from the bot on an Instagram-connected inbox and confirm the reply appears exactly once after the echo webhook arrives

@github-actions github-actions Bot added the bug Something isn't working as expected label Aug 4, 2026
@viethung0o0
viethung0o0 marked this pull request as ready for review August 4, 2026 10:06
@viethung0o0
viethung0o0 merged commit e930a2e into main Aug 4, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working as expected

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants