Repository navigation
AI-3512: keep a number's first conversation, one agent per line, no agent deleted under a number - #2268
Conversation
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>
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>
|
/jeffery review |
|
Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it. How it works
Commands (each as a whole comment)
|
There was a problem hiding this comment.
✅ Approved cfd7e8c94395 after 1 round
Left open, your call:
- consider: Delete query-budget test expects 3 queries, now 4 (
acceleration/internal/store/agent_config.go:496) - consider: Configs already sharing an SMS line can no longer be saved (
acceleration/internal/store/channel_owner.go:250)
Also counts the delete's numbers read in the query budget. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
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. |
Withdrawing approval until ef1b852 is reviewed.
…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>
Withdrawing approval until f171e30 is reviewed.
There was a problem hiding this comment.
✅ Approved f171e3036a58 after 3 rounds · 2 fixed
Left open, your call:
- consider: Fallback log omits the two conversation IDs it splits (
acceleration/internal/channels/service.go:518)
…e it opened Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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) |
…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>
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
/jeffery review |
Nothing changed since round 5 on |
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
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 shapeMapalready uses). Inchannels/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 stopsidentify's first-sighting write, which carries no conversation, from wiping one that another router had just recorded.AppConnectionByAccountnewest 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", thenconnected, then newest. A pending or unbound second connection no longer takes the workspace's messages.AgentConfigs.InsertandUpdatenow runrefuseSecondLineAgentin their transaction. The rule covers every channel line kind (sms,whatsappandimessage), not only SMS. It takes a transaction-scoped advisory lock per customer and line, in kind order, and repeatsConfigOnChannel'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.storeFailureanswers that error with the same 400 thatchannelsWarningsgives, 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.AgentConfigs.Deletenow runs in a transaction. It setsdeleted_at, which locks the row, then reads the numbers the config answers. When there are any, it returns*ConfigAnswersNumbersErrorand rolls back. The handler's separate pre-check is gone, and it maps that error to the same 409 as before.phone_numbers.config_idtakeFOR SHAREon the live config row (liveConfig), so they wait on a delete in progress and then re-checkdeleted_at. A refused delete leaves the cached config alone. The data-move import writesconfig_ida third way, without this guard; that is filed as AI-3662.SetAgentkeeps one statement (EXISTS (... FOR SHARE)). When the config is gone it answersErrNoAgentConfig, which the handler sends as a 404.go run ./cmd/openapiis clean). chore(store): squash migrations into one per set #2247 (squash migrations) was checked, and nothing here adds a migration.Overlap:
AgentConfigs.DeleteontodetachedWrite.mainis merged into this branch, and the numbers check now runs inside that transaction.identifyinchannels/service.go, in a separate hunk from this PR's.api/channels.gohunks are not touched here.Tests
store(StoreSuiteandShardedStoreSuite):TestTwoConcurrentFirstMessagesFromOneNumberEndInOneConversationTestAFirstSightingOfANumberKeepsTheConversationRecordedMeanwhileTestASecondConfigNamingAnSMSNumberIsRefusedAndTheFirstStillSavesTestTwoConfigsSavedAtOnceNamingOneSMSNumberLeaveOneOnItTestAConfigThatSharedAnSMSNumberBeforeTheRuleStillSavesTestASaveNamingAnSMSNumberWaitsForAnotherSaveOfIt: the line's advisory lock is held in an open transaction. The save blocks until that commits, then is refused.TestAConfigANumberAnswersWithIsNotDeletedTestANumberIsNotGivenAConfigDeletedSinceItWasReadTestANumberAttachedAgainDropsAnAgentDeletedMeanwhileTestADeleteWaitsForANumberBeingGivenTheConfig: the number is pointed at the config in an open transaction. The delete blocks until that transaction commits, then refuses.SetAgentEXISTS, the attach subquery) fails its test.channels, inRecordConversationSuite:TestAFirstMessageGoesOnInTheConversationRecordedFirst: the message is on the kept conversation, and the session opened by the lost race is gone from the manager.TestAFirstMessageIsAnsweredWhereItOpenedWhenTheKeptConversationCannotOpenTestConfigsSuite,TestPhoneSuite,TestSyncSuiteandinternal/channelspass.TestChannelsSuitehas three failures that also fail without this change, on a branch from the samemain:TestARedeliveryRacingAStopThatFailsRecordsIt,TestAStartTheStoreRefusedIsObeyedWhenDeliveredAgainandTestAStopTheStoreRefusedIsObeyedWhenDeliveredAgain. Each expects error text that the body no longer carries.TestAnArrivingCallToANumberWhoseAgentIsGoneIsRefusedusedDeleteon a config a number answered with, which is now refused. It marks the row deleted, as an older router left it.TestReattachingInAnotherAppKeepsTheNumbersAgentgave a number the agentconfig-1, which does not exist. It now inserts a real config.TestCallHooksSuite,internal/phoneandTestDataMoveSuite(its number and agent tests) pass.go vetandgofmtare clean.🤖 Generated with Claude Code