Repository navigation
[AI-3479] Link codes per app, deleted once claimed - #2240
Conversation
channel_links is keyed on (customer_id, code), so one app holding a code no longer fails another app's link. Claim deletes the code, and only for the agent it was minted for: a code texted to another agent's line of the app is answered as such and stays to claim. Insert draws again when the app already holds the code, and deletes every app's codes past their time in the same statement. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A different reply told a guesser the code was live. Claim now treats it as no code, so identify records the failure and gives the unknown-code reply. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Every Link error was a 400 carrying the store's text. Nothing the caller sent can fail it: the body is validated before. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… per set Each set's history up to its last migration (global 20270124093000, shard 20270126000000) becomes 20270110000000_initial.sql, keeping the version of the baseline every deployed database recorded, so none runs it. The router refuses a database that ran part of the squashed history or the single history from before the split, instead of claiming migrations it never ran. router schema drop-strays goes: it read the history for the tables to drop. migrations/squash/cleanup.sql rewrites a deployed database's tracking to the initial migration alone, after checking its schema against a fingerprint of a new one, and drops the empty stray tables of the other set.
kanat
left a comment
There was a problem hiding this comment.
Round-1 review at 9731111 (current main 284349e already merged in). CI: draft, so go and integration are skipped; they run at gh pr ready.
The touched suites pass: store Code|ChannelLink|Draw|LinkThat|Claim|TestTheSchemaFilesAreCurrent (sharded too), api TestChannelsSuite, ./internal/channels, go vet with -tags integration, and the generated-files check. 17 mutants: 16 killed, 1 survived (R1.1).
Checked and sound:
- Rollback. The previous release (284349e) migrates and runs on a DB migrated by this head. Its Insert of a code two other apps hold succeeds. Its Claim returns only its own app's row and nothing for another app. A row it marks used is not claimed by this head. This head redraws past a used, live code.
- The prune and the insert in one statement on an expired row with the same key give
INSERT 0 0and delete the row, so the next draw writes. - A blank
user_idis still a 400validation_failedafter R0.2 (answerFailuremapsstore.ValidationError). - The migration slot is newer than main and #2208.
channel_linksis not a data-move table.- R0.1 and R0.2 are mutation-checked.
Verdict: request changes, for R1.1 (Should fix).
| ExpiresAt: time.Now().UTC().Add(LinkValidFor), | ||
| } | ||
| if err := s.store.ChannelLinks.Insert(ctx, &link); err != nil { | ||
| if err := s.store.ChannelLinks.Insert(ctx, &link, linkCode); err != nil { |
There was a problem hiding this comment.
[Should fix] R1.1 No test checks that this call site draws a fresh code. A mutant that replaces linkCode with func() (string, error) { return "123456", nil } passes all of TestChannelsSuite. Every test mints at most one live code per app, so a second person who links before the first texts gets a 500, and nothing catches it. Fix: add this test to ChannelsSuite in internal/api/channels_test.go. I ran it in a scratch copy: it fails under the mutant (the second POST is not a 200) and passes on head.
// Two people linking on one agent before either texts get two codes.
func (s *ChannelsSuite) TestTwoPeopleLinkingOnOneAgentGetTwoCodes() {
number := s.number()
s.connect(number)
config := s.agentOn(number, store.ChannelIdentityLink)
var first, second ChannelLink
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &first))
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &second))
s.NotEqual(first.Code, second.Code)
}There was a problem hiding this comment.
Fixed in 8657283: TestTwoPeopleLinkingOnOneAgentGetTwoCodes (ChannelsSuite). With the constant-code mutant at the Insert call it fails; it passes on head.
| -- release still running writes and claims as before. A code is minted for one person linking one | ||
| -- phone, so the table is small and the key is rebuilt under the table's lock, as | ||
| -- 20270124000000_hash_call_tokens rebuilt call_bridges'. | ||
| ALTER TABLE channel_links |
There was a problem hiding this comment.
[Nit] R1.2 The comment says this follows 20270124000000_hash_call_tokens. That migration sets SET LOCAL lock_timeout = '5s'; before its PK swap, and this one does not. Without it, the ACCESS EXCLUSIVE lock waits behind any running query on channel_links, and every later Claim and Insert queues behind the ALTER. With the timeout, the migration fails and the next start retries. Fix: add the same line to Up and Down. The repo is mixed on this (20270115000400_stream_app_pk has none), so it is a Nit for a ticket.
There was a problem hiding this comment.
Fixed in 5d36bef: SET LOCAL lock_timeout = '5s' in Up and Down. TestEveryTransactionalMigrationAfterTheBaselineSetsALockTimeout covers Up and fails without it.
kanat
left a comment
There was a problem hiding this comment.
[security R1] GO: no security findings in this diff.
Checked against the repo security skill (go.md, rules 4, 5, 7, 9):
- A claim is scoped to the app and to the agent of the line the code was texted to, and a code of another agent is answered and counted like an unknown one. Mutation checks: removing either filter, the used/expiry filters, the conflict retry or the failure count each makes a test fail.
- One code claimed from many numbers at once is spent once, and links minted at once never share a code (concurrency checks run locally).
- The link endpoint stays server-side only and now answers a store failure as a 500 that does not carry the store message.
- Rollback: the previous build passes its link and channel suites on the migrated table.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
#2208 edited migrations the squash replaces and added 20270127*. The edits are dropped: every deployed database ran those files as they were, which is what the initial migration holds. Its 20270127 files stay as the first migrations after the initial one; they were written for a database that ran the original 20270114, which the initial one is. Its tests of states no database reaches after the squash (the expand-only 20270114, 20270116000001's leg matching, the Downs of 20270112*, adoption) are dropped; the rest run on the initial migration. checkHistory takes a version by its latest row, as its adoptLegacy did. cleanup.sql now accepts a database that ran this release's migrations after the initial one and keeps their rows; generate.sh rewrites what it knows of the migration files, fingerprints included.
Once the cleanup has removed the squashed history, a database rolled back from a release with a newer migration holds a version with no file and no squashed one, which checkHistory took for a partial history. Only a version inside the squashed history counts as one.
The squash replaces the migration history with one initial migration per set (#2247). 20270128000000_channel_links_per_customer stays after it and now sets a lock timeout first, as every transactional migration after the initial one does. cleanup.sql is regenerated with it among the global migrations after the initial one.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
The squash replaces the migration history with one initial migration per set (#2247), so a migration this branch adds has to come after it and after main's 20270127*: 20270120000000_log_session_and_attempt_campaign_idx is now 20270128000100 (#2240 adds 20270128000000). migrate.go takes the squash side: main has had the migration pool of its own since #2208, and adoptLegacy, which this branch made one transaction, is gone with the history it adopted. TestMergingPlacedCallsIntoTheirLegsBillsTheSame migrates to the middle of the squashed history and goes with it. APIKeys.Lookup takes main's, which returns a failed lookup as an error rather than as an unknown key. cleanup.sql is regenerated with the renumbered migration.
…fix/ai-3479-link-codes
kanat
left a comment
There was a problem hiding this comment.
Delta review 2 of 16b7840 (merged onto current main, clean): GO. No Blocker or Should fix is open.
Prior findings
- R1.1 fixed:
TestTwoPeopleLinkingOnOneAgentGetTwoCodesfails whenLinkpasses a constant code generator (the second link answers 500) and passes on head. - R1.2 fixed:
SET LOCAL lock_timeout = '5s'is the first statement of Up and Down. Removing it from Up failsTestEveryTransactionalMigrationAfterTheInitialOneSetsALockTimeout.
Migration on top of the squash (#2247's own content not reviewed)
- A database with the squashed history recorded and a live
channel_linksrow: Migrate runs only20270128000000, the key becomes(customer_id, code), the row stays. - An empty database: the initial migration, then ours, same key.
- Down to
20270127000400with two apps holding one code: one row dropped, the key is(code)again; Up again works. schema/global.sqldiffers from main only at thechannel_links_pkeyline, andTestTheSchemaFilesAreCurrentpasses.
Suites on the merged tree: vet (both tags) and gofmt clean; store, channels and TestChannelsSuite pass. TestEveryHotTableIsReadByIndex fails on my loaded shared test server with the same subtests on main, so it is not this PR.
Nits (not blocking)
- The migration has
SET LOCAL lock_timeouttwice in Up and in Down (inline). TestEveryTransactionalMigrationAfterTheInitialOneSetsALockTimeoutreads Up only, so Down's timeout is not pinned. The test belongs to #2247, so I leave it.
| -- +goose Up | ||
| SET LOCAL lock_timeout = '5s'; | ||
|
|
||
| SET LOCAL lock_timeout = '5s'; |
There was a problem hiding this comment.
Nit: the same SET LOCAL lock_timeout is here twice (lines 2 and 4), and again in Down: the merge applied the lock-timeout fix from both sides. Harmless, but drop one copy of each.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
## Why `integration (store)` is red on every PR (AI-3661, first seen in run 45261924288): `TestStoreSuite/TestEveryTableWithAUserIDIsForgottenOrKeptForAReason` and its sharded twin fail at `forget_user_test.go:368`. In `s.Equal(found, listed)`, "expected" is the schema and "actual" is the list. The list names `calls`, and the schema no longer has `calls.user_id`: ``` #2208 (c8e12d6) keeps the expand-only calls.user_id for the release before #2232 (3f7bee5) adds "calls" to keptUserTables ("kept for that release, and dropped in a later one") #2240 (457cca4) carries the #2247 squash: a new database no longer gets calls.config_id / user_id ("which no deployed database has and no code reads", #2247 body) -> keptUserTables still names calls -> meta-test fails on main ``` ## Change | File | Before | After | | --- | --- | --- | | `internal/store/forget.go` | `keptUserTables` lists `calls` | entry removed (the column is gone, so there is nothing to forget or keep) | There is no forget step for `calls`. The `Call` model (`internal/store/call.go`) maps no `user_id`. The meta-test is unchanged. ## Tests - Base 9effc9b: both meta-test runs fail with the CI diff (`calls` only in the list). - Head: both pass, plain and sharded. - Mutation: put back base `forget.go` (with the `calls` entry) → both fail. - Local only: `TestEveryHotTableIsReadByIndex` also fails on base `forget.go`. The local test Postgres is 16.15; CI runs `postgres:19-alpine` and passed it in run 45261924288. This PR does not touch it. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…gent deleted under a number (#2268) ## 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 (#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](https://linear.app/stream/issue/AI-3662/a-data-move-import-can-point-a-number-at-a-deleted-agent-config). - `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). #2247 (squash migrations) was checked, and nothing here adds a migration. **Overlap:** - #2209 (merged since) moved `AgentConfigs.Delete` onto `detachedWrite`. `main` is merged into this branch, and the numbers check now runs inside that transaction. - #2240 edits `identify` in `channels/service.go`, in a separate hunk from this PR's. - #2248's `api/channels.go` hunks are not touched here. ## 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 #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](https://claude.com/claude-code) --------- Co-authored-by: Laurent Schaffner <laurentschaffner@Laurents-MacBook-Pro-Stream.local> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Why
A link code ties a phone number to an app's user (AI-3479).
channel_linkswas keyed oncodealone, rows were never deleted, and a taken code was not drawn again: every app drew from one space of six-digit codes, so codes held by one app made other apps' links fail, more often as codes piled up. A code texted to another agent's line of the same app was also spent before its agent was checked. Codes stay at six digits and live 15 minutes (LinkValidFor, unchanged).How it works
PRIMARY KEY (code)PRIMARY KEY (customer_id, code)TestTwoAppsHoldOneCodeAtOnceUPDATE SET used_atDELETE ... RETURNING, row goneTestACodeIsSpentOnceTestACodeTheAppHoldsIsDrawnAgain,TestADrawThatIsAlwaysTakenGivesUpTestWritingACodeDeletesTheCodesPastTheirTime,TestACodeIsIssuedAgainAfterItWasClaimedOrLapsedTestACodeForAnotherAgentIsNotSpent,TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOnItsOwn,TestCodesOfAnotherAgentCountAsWrongCodesChanges
migrations/global/20270128000000_channel_links_per_customer.sql: swaps the primary key in oneALTER TABLE, under the table's lock, as20270124000000_hash_call_tokensdid forcall_bridges. The new key refuses nothing the old one let through, so an older release still running keeps working. Down keeps one app's row per duplicated code and restoresPRIMARY KEY (code).internal/store/channel_link.go:Inserttakes the draw function.Claimtakes the agent config id.used_atstays; Claim still skips a row an older release marked used, so a mixed rollout cannot claim a code twice.internal/channels/service.go:LinkpasseslinkCode;identifyhas no separate reply for another agent's code: it is an unknown code, so a guess cannot tell a live code from a dead one.internal/api/channels.go: an error ofLinkis returned as is, so it answers 500 "something went wrong" and not a 400 with the store's text (TestACodeThatCannotBeWrittenIsA500WithoutTheStoresWords).Claim's delete and the other-agent check filter on the whole primary key (
Index Scan using channel_links_pkey,Index Cond: customer_id, codewithenable_seqscan=offon a test database of 2 rows). The prune in Insert scans the table, which holds only codes still in time once the first Insert after deploy has run. That first run scans every code minted so far; the prod row count is unverified.Validation
go test -tags integration ./internal/store -run 'TestStoreSuite|TestShardedStoreSuite' -testify.m 'Code|ChannelLink|Draw|LinkThat|Claim|TestTheSchemaFilesAreCurrent',./internal/api -run TestChannelsSuite,./internal/channels: pass on the branch merged with main 284349e.go vet ./...andgo vet -tags integration ./...,gofmt -l: clean.TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOnItsOwnfails: the code texted to the wrong line was spent, so its own line answered "Send me the code ...".PRIMARY KEY (code); Up restored(customer_id, code)and took the second app's row.🤖 Generated with Claude Code