Skip to content

AI-3512: keep a number's first conversation, one agent per line, no agent deleted under a number - #2268

Merged
Loschcode merged 8 commits into
mainfrom
laurentschaffner/ai-3512-inbound-messages-can-land-in-the
Nov 24, 2026
Merged

Loschcode merged 8 commits into
mainfrom
laurentschaffner/ai-3512-inbound-messages-can-land-in-the

Conversation

@Loschcode

@Loschcode Loschcode commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Why

https://linear.app/stream/issue/AI-3512/inbound-messages-can-land-in-the-wrong-conversation-or-on-the-wrong

Concurrent writes could leave a number's first message in a conversation that nothing continues, put two agents on one SMS line, or leave a number answering with a deleted agent.

What changed

  • Contact map conversation (ContactMapEntries.Upsert): a row that already has a conversation keeps it (COALESCE(NULLIF(stored, ''), new)), and the row is read back into the caller's entry (RETURNING *, the shape Map already uses). In channels/service.go (recordConversation), a router whose session opened a different conversation for the same first message first opens the kept conversation, then closes its own session, all before the turn. The message and its answer therefore land where the next message continues. If the kept conversation cannot open, the message is answered in the session already open rather than dropped. A lost race leaves behind an empty conversation (a Chat channel) and a session closed without a turn. The same rule also stops identify's first-sighting write, which carries no conversation, from wiping one that another router had just recorded.
  • AppConnectionByAccount newest connection: skipped, already fixed. 73dc7bf ([AI-3503] Inbound app message goes to the bound connection #2185, AI-3503) orders the matches by "a live config binds it", then connected, then newest. A pending or unbound second connection no longer takes the workspace's messages.
  • Two configs naming one SMS number: AgentConfigs.Insert and Update now run refuseSecondLineAgent in their transaction. The rule covers every channel line kind (sms, whatsapp and imessage), not only SMS. It takes a transaction-scoped advisory lock per customer and line, in kind order, and repeats ConfigOnChannel's match. A line the stored config already named is skipped, so configs that shared a line before this rule stay editable. The second of two concurrent saves gets a *ChannelLineTakenError. storeFailure answers that error with the same 400 that channelsWarnings gives, on create, update, patch and sync. This needs no migration. A unique expression index would need one, and it would fail to build on any deployment that already has a duplicate, so the lock was the safer choice.
  • Config delete vs. a number given the config:
    • AgentConfigs.Delete now runs in a transaction. It sets deleted_at, which locks the row, then reads the numbers the config answers. When there are any, it returns *ConfigAnswersNumbersError and rolls back. The handler's separate pre-check is gone, and it maps that error to the same 409 as before.
    • The two API writers of phone_numbers.config_id take FOR SHARE on the live config row (liveConfig), so they wait on a delete in progress and then re-check deleted_at. A refused delete leaves the cached config alone. The data-move import writes config_id a third way, without this guard; that is filed as AI-3662.
      • SetAgent keeps one statement (EXISTS (... FOR SHARE)). When the config is gone it answers ErrNoAgentConfig, which the handler sends as a 404.
      • Re-attaching a number keeps its agent only while that config is live, and otherwise clears it.
  • No migration is needed, and no OpenAPI drift (go run ./cmd/openapi is clean). chore(store): squash migrations into one per set #2247 (squash migrations) was checked, and nothing here adds a migration.

Overlap:

Tests

  • store (StoreSuite and ShardedStoreSuite):
    • TestTwoConcurrentFirstMessagesFromOneNumberEndInOneConversation
    • TestAFirstSightingOfANumberKeepsTheConversationRecordedMeanwhile
    • TestASecondConfigNamingAnSMSNumberIsRefusedAndTheFirstStillSaves
    • TestTwoConfigsSavedAtOnceNamingOneSMSNumberLeaveOneOnIt
    • TestAConfigThatSharedAnSMSNumberBeforeTheRuleStillSaves
    • TestASaveNamingAnSMSNumberWaitsForAnotherSaveOfIt: the line's advisory lock is held in an open transaction. The save blocks until that commits, then is refused.
    • TestAConfigANumberAnswersWithIsNotDeleted
    • TestANumberIsNotGivenAConfigDeletedSinceItWasRead
    • TestANumberAttachedAgainDropsAnAgentDeletedMeanwhile
    • TestADeleteWaitsForANumberBeingGivenTheConfig: the number is pointed at the config in an open transaction. The delete blocks until that transaction commits, then refuses.
  • The ticket's second test, a connected and a pending connection, is covered by [AI-3503] Inbound app message goes to the bound connection #2185's tests.
  • Mutation check: removing each guard (the COALESCE, the line check, the delete's numbers read, the SetAgent EXISTS, the attach subquery) fails its test.
  • channels, in RecordConversationSuite:
    • TestAFirstMessageGoesOnInTheConversationRecordedFirst: the message is on the kept conversation, and the session opened by the lost race is gone from the manager.
    • TestAFirstMessageIsAnsweredWhereItOpenedWhenTheKeptConversationCannotOpen
  • TestConfigsSuite, TestPhoneSuite, TestSyncSuite and internal/channels pass. TestChannelsSuite has three failures that also fail without this change, on a branch from the same main: TestARedeliveryRacingAStopThatFailsRecordsIt, TestAStartTheStoreRefusedIsObeyedWhenDeliveredAgain and TestAStopTheStoreRefusedIsObeyedWhenDeliveredAgain. Each expects error text that the body no longer carries.
  • Two existing fixtures depended on the old behaviour and now build their state directly:
    • TestAnArrivingCallToANumberWhoseAgentIsGoneIsRefused used Delete on a config a number answered with, which is now refused. It marks the row deleted, as an older router left it.
    • TestReattachingInAnotherAppKeepsTheNumbersAgent gave a number the agent config-1, which does not exist. It now inserts a real config.
  • TestCallHooksSuite, internal/phone and TestDataMoveSuite (its number and agent tests) pass.
  • go vet and gofmt are clean.

🤖 Generated with Claude Code

A contact row that has a conversation keeps it, and a router that opened
a second one for the same first message carries on in the kept one. A
config naming a channel line another live config names is refused under
a lock on the line. Deleting a config reads the numbers it answers under
its row lock, which a number being given the config waits on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Laurent Schaffner and others added 3 commits November 23, 2026 20:02
The reopen of the kept conversation moves into recordConversation, so a
failed open on either attempt is logged where it always was. Two test
fixtures that set up a number answering with a deleted or missing config
now build that state directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…land-in-the

The config delete's numbers check moves into #2209's detachedWrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it.

How it works

  • Findings come as inline comments, each starting with [Must Fix], [Should Fix], nit: or consider:.
  • Push fixes whenever you're ready. Once the branch has been quiet for 10 minutes I review the new head and resolve the threads it fixes. To skip the wait, comment /jeffery review.
  • If you disagree or have a question, reply in the thread. I'll answer there, and resolve it if you're right.
  • I approve once every must-fix and should-fix is closed and nobody has requested changes. CI isn't part of that; branch protection still holds the merge until it's green. From round 3 on, open should-fix findings stop blocking.
  • I don't approve release/* branches or changes to protected paths, and I'll say so when that applies.
  • If a must-fix is still open after round 8, I stop and hand the PR to a human. Draft PRs wait until they're marked ready.

Commands (each as a whole comment)

Command What it does
/jeffery review Review the current head now
/jeffery rereview Start over at round 1 on the current head and withdraw my approval. This redoes the whole review and costs as much as the first one, so use it only when you don't trust the earlier rounds. If nothing changed since my last round I say so instead; add force to redo it anyway
/jeffery pause / /jeffery resume Stop or restart automatic reviews on this PR
/jeffery status What I last reviewed, and why I have or haven't approved
/jeffery help This list

/review-agent or a mention of me works in place of /jeffery.

@getstream-metis getstream-metis 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.

Round 1 on cfd7e8c94395 · 🆕 2 new

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

@getstream-metis getstream-metis 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.

✅ Approved cfd7e8c94395 after 1 round

Left open, your call:

Also counts the delete's numbers read in the query budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Loschcode

Copy link
Copy Markdown
Contributor Author

Round 1: both points are fixed in ef1b852 (the delete's query budget, and lines a config named before the rule are kept). The replies are in the threads.

@getstream-metis
getstream-metis Bot dismissed their stale review November 23, 2026 20:12

Withdrawing approval until ef1b852 is reviewed.

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

@getstream-metis getstream-metis 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.

✅ Approved ef1b852da0a9 after 2 rounds · 2 fixed

…st race opened

If the kept conversation cannot open, the message is answered in the one
already open rather than dropped. Adds a test that a save waits on the
line's lock, and leaves the cache alone when a delete is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@getstream-metis
getstream-metis Bot dismissed their stale review November 23, 2026 20:49

Withdrawing approval until f171e30 is reviewed.

@getstream-metis getstream-metis 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.

Round 3 on f171e3036a58 · 🆕 1 new

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

@getstream-metis getstream-metis 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.

✅ Approved f171e3036a58 after 3 rounds · 2 fixed

Left open, your call:

…e it opened

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@getstream-metis
getstream-metis Bot dismissed their stale review November 24, 2026 01:09

Withdrawing approval until 0cb28ee is reviewed.

kept, err := s.sessions.Create(ctx, spec)
if err != nil {
logger.Error("could not open the conversation another router recorded first, answering in this one",
"agent", spec.AgentName, "kept", spec.ConversationID, "opened", opened, "error", err)
getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 24, 2026

@getstream-metis getstream-metis 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.

✅ Approved 0cb28ee75d08 after 4 rounds · 3 fixed

…land-in-the

SetAgent's live-config guard moves into main's numberWrite transaction, and
the line check into the shared save.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@getstream-metis
getstream-metis Bot dismissed their stale review November 24, 2026 09:01

Withdrawing approval until 8b70f4e is reviewed.

// every message. The API checks this before the write too, but two configs saved at once both
// pass that check, so the decision is taken again here under a transaction-scoped lock on the
// customer and line, in kind order, as refuseSecondChannelAgent takes its.
func refuseSecondLineAgent(ctx context.Context, tx bun.Tx, config *AgentConfig) error {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: Do dashboard test copies (the draft_of tag) carry the live config's channels lines? If they do, saving a copy is refused as a second agent on the line, because this check has no test-copy exemption while refuseSecondChannelAgent does.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test copies are made by the dashboard, outside this repo, so I can't say from here whether a copy carries the live config's channels lines. Either way this PR doesn't change the outcome. The API's own check runs before any save: channelsWarnings → ConfigOnChannel, on create, update, patch and sync. It has no test-copy exemption, so on main a copy naming the live config's line is already refused, with the same 400. The store check repeats that rule under a lock, so only the concurrent case changes. Exempting test copies from both checks would be a product decision, outside this ticket. Copies answer no channel message, so it may well be wanted. I've left it as is.

@getstream-metis getstream-metis 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.

✅ Approved 8b70f4e2097b after 5 rounds · 3 fixed

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

/jeffery review

Nothing changed since round 5 on 8b70f4e2097b; comment /jeffery rereview force to redo the full review anyway.

@Loschcode
Loschcode merged commit ed60906 into main Nov 24, 2026
9 of 13 checks passed
@Loschcode
Loschcode deleted the laurentschaffner/ai-3512-inbound-messages-can-land-in-the branch November 24, 2026 09:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants