Skip to content

chore(store): squash migrations into one per set - #2247

Draft
tbarbugli wants to merge 5 commits into
mainfrom
tommaso/squash-migrations
Draft

tbarbugli wants to merge 5 commits into
mainfrom
tommaso/squash-migrations

Conversation

@tbarbugli

@tbarbugli tbarbugli commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

How it works

Each set's history becomes one file that keeps the baseline's version, 20270110000000, which every deployed database already recorded. goose ignores recorded versions that have no file, so a deployed database starts as it is and runs only what comes after the initial migration: today, the 20270127… migrations #2208 added.

migrations/global: 24 files -> 20270110000000_initial.sql (2105 lines), then 20270127000400
migrations/shard:  11 files -> 20270110000000_initial.sql  (831 lines), then 20270127000000…000400

Store.Migrate, each set
├─ no tracking table
│  ├─ the set's tables there (ran the pre-split history)  -> refused
│  └─ empty database                     -> runs the initial migration
└─ tracking table
   ├─ only versions that have a file      -> as before
   ├─ versions with no file, the squash head among them
   │    (every deployed database today)   -> starts as it is
   ├─ versions with no file inside the squashed history, no squash head
   │    (ran part of the history)         -> refused
   └─ versions with no file after the squashed history
        (a later release's, rolled back)  -> starts as it is

After every router of a deployment runs this release, migrations/squash/cleanup.sql rewrites each of its databases, in one transaction under the router's migrate lock:

cleanup.sql -v set=global|shard|both   (dry run unless -v apply=1)
├─ 1. tracking state, per set (latest row per version):
│     squashed history whole (or already cleaned) and the migrations after it none or all
│     -> "before" or "after"; abort on anything else, or on a version it does not know
├─ 2. fingerprint the set's catalogue  -> abort unless it is a new database's in that state
├─ 3. delete the squashed versions but 20270110000000   ("fake apply"; later rows kept)
├─ 4. drop goose_db_version (pre-split tracking)
├─ 5. apply=1: recreate limits_level_check as written
└─ 6. drop_strays=1: drop the other set's empty tables

What it knows of the migration files (the versions after the initial one, each set's tables, sequences and functions, the six fingerprints) sits in a generated block that migrations/squash/generate.sh rewrites: it builds a new database of each kind before and after those migrations in a throwaway postgres:18-alpine container and fingerprints them with cleanup.sql itself. Rerun it whenever a migration lands before this release ships; #2240 and #2177 already carry theirs.

Why

The history kept migrations that only made sense for one transition (adoption from the single history, folding tables, backfills), plus tests that loaded rows mid-history to check them. Every database deployed now ran all of it, so one file per set says what the schema is, and new migrations start from there.

Changes

  • migrations/{global,shard}/20270110000000_initial.sql: pg_dump -s of a database migrated through the whole history. The change-log objects both sets keep come first, written to be idempotent, because a single-database deployment runs both files. Primary key, unique and index statements are in the order the history created them: the planner breaks equal-cost ties by index age, and alphabetical order flipped Calls.Select running from calls_customer_agent_idx to calls_customer_idx (TestEveryHotTableIsReadByIndex caught it).
  • Merges main with #2208. Its edits to squashed files (the lock timeouts, the expand-only 20270114) 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. On it the backfill finds nothing to do, calls_customer_agent_idx/calls_customer_campaign_idx are built concurrently (calls_campaign_idx dropped), and calls_session_id_fkey is already valid. A new database no longer gets the expand-only columns agent_sessions.call_id/call_type and calls.config_id/user_id, which no deployed database has and no code reads.
  • internal/store/migrate.go: checkHistory replaces adoptLegacy. It counts a version by its latest row, and only a version inside the squashed history counts against a database, so a rollback from a later release starts. DropStrays, createdTables and router schema drop-strays are removed: they read the history to know which tables to drop, and cleanup.sql does that job once.
  • Removed the tests of squashed migrations' data rewrites (notices, phone_calls merge, trunk bridges, deliveries seen, connector side tables, legacy adoption), and fix(store): make the migrations after the baseline safe on a live database #2208's tests of states no database reaches after the squash (TestEverySessionKeepsItsCallThroughTheBatchedBackfill, TestTheReleaseBeforeStillWritesAndReadsASessionsCall, TestTheSessionKeyIsAddedUnchecked, the two TestALegTwoPlacedCallsMatch…, TestTheFirstSharedMigrationsStepBackAndForward). Its lock-timeout test becomes TestEveryTransactionalMigrationAfterTheInitialOneSetsALockTimeout. Added TestADatabaseThatRanTheSquashedHistoryStartsAsItIs, TestADatabaseThatRanPartOfTheSquashedHistoryIsRefused, TestADatabaseFromBeforeTheSplitIsRefused, TestARolledBackVersionWithNoFileIsNotRefused, TestADatabaseALaterReleaseMigratedStartsAfterTheCleanup, and a fixture test for setTables' drop and rename handling.
  • migrations/squash/cleanup.sql, generate.sh and run.sh: the one-off tracking rewrite, the generator of what it knows of the migration files, and a runner that executes it from a short-lived psql pod reading the DSN from accelerate-secrets. Delete both once every database has run them.

Rollout

  1. Release and deploy as usual, staging first. Only the migrations after the initial one run (two concurrent index builds on calls, the rest no-ops), so no downtime is needed.
  2. For each database, run a dry run, then apply once every router using it is on this release. The cleanup accepts a database before or after the release's migrations ran, so a dry run before the deploy says whether it will apply:
Database Command
staging (one database) run.sh us-east1 accelerate-staging ROUTER_POSTGRES_DSN both
prod shared run.sh us-east4 accelerate-prod ROUTER_POSTGRES_DSN global
prod us-east4 / us-west1 / europe-west4 run.sh <region> accelerate-prod ROUTER_POSTGRES_SHARD_DSN shard

Add --apply to commit and --drop-strays to drop the other set's empty tables. A stray holding rows is left and named.

Once a database is cleaned, a release from before this one must not start on it: it would see its history as unapplied and run it again. To undo the cleanup, insert the squashed versions back into the tracking table.

Validation

Check Result
pg_dump -s of a new database vs one migrated through the whole history (global, shard, both on one database) identical, except the COMMENT ON SCHEMA public IS '' the old baseline wrote, which no live database has
Index creation order, new vs whole history identical, except data_change_starts_pkey (the only index of a one-row table)
Live schemas (staging, prod shared, prod us-east4/us-west1/europe-west4), dumped today, vs new every object of each set identical; live has only the router's runtime data_changes_recorded triggers, goose_db_version, and the other set's stray tables
limits_level_check on prod shared same check, but stored with the OR chain nested, which Postgres 18 flattens when it parses any new constraint; cleanup.sql recreates it flat
cleanup.sql fingerprint on the five live schemas restored locally matches
cleanup.sql on databases set up like prod (whole history, strays, one stray with rows, goose_db_version, runtime triggers), before and after this release's router boots on them: dry run, apply, apply again, then router boot state read right both times, fingerprints match, tracking keeps 0, 20270110000000 and the 20270127… rows, the stray with rows is left, the second run is a no-op, the router boots and runs nothing
Same with #2240's and #2177's branches merged with this one, then this release booted on the result their migrations apply, the cleanup matches, and the rollback to this release starts
go run ./cmd/schema no diff
go test -tags integration ./internal/store/... ./internal/api/, go test ./..., go vet -tags integration ./... pass

Notes

  • Open PRs with migrations, both merged with this branch: #2240 keeps 20270128000000 and now sets a lock timeout; #2177's 20270120000000 sat inside the squashed history and is now 20270128000100. Whichever lands second regenerates cleanup.sql (generate.sh), and if the first has deployed by then, the second's version has to be above it.
  • A branch fast-deployed to staging records its migrations there. The cleanup refuses such versions, so rerun the staging dry run just before applying.
  • The benchmark database (accelerate-benchmark, router v0.6.277) predates the split, and this release refuses it. Recreate it, or run v0.6.372 on it first and then the cleanup.
  • A local database that stopped partway through the history is refused with a message; drop it and let the router recreate it.

… 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.
#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.
tbarbugli added a commit that referenced this pull request Nov 23, 2026
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.
tbarbugli added a commit that referenced this pull request Nov 23, 2026
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.
kanat added a commit that referenced this pull request Nov 23, 2026
> **Merge order:** this branch carries #2247 (the migration squash),
merged in by its author. Merge #2247 first; this PR's own diff is then 7
files.

## Why

A link code ties a phone number to an app's user (AI-3479).
`channel_links` was keyed on `code` alone, 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

```
POST /v1/agents/channels/links -> Service.Link -> ChannelLinks.Insert(link, linkCode)
  loop, at most 4 draws
  ├─ draw a code
  ├─ WITH expired AS (DELETE every app's codes past their time)
  │  INSERT ... ON CONFLICT DO NOTHING
  ├─ 1 row written -> done
  └─ 0 rows (the app holds the code) -> draw again

inbound message -> Service.identify -> ChannelLinks.Claim(app, agent, text)
  DELETE ... WHERE app, code, agent, unused, not expired RETURNING *
  ├─ row      -> number claimed, "This number is yours now."
  └─ no row   -> ErrUnknownChannelLink: failure counted, "Send me the code ..."
               (an unknown code, a spent one and another agent's live one answer alike;
                another agent's code is not spent)
```

| Change | Before | After | Test |
|---|---|---|---|
| Key | `PRIMARY KEY (code)` | `PRIMARY KEY (customer_id, code)` |
`TestTwoAppsHoldOneCodeAtOnce` |
| Claim | `UPDATE SET used_at` | `DELETE ... RETURNING`, row gone |
`TestACodeIsSpentOnce` |
| Code taken by the app | insert error, link fails | drawn again, 4
draws at most | `TestACodeTheAppHoldsIsDrawnAgain`,
`TestADrawThatIsAlwaysTakenGivesUp` |
| Codes past their time | kept forever | deleted by the next Insert, any
app | `TestWritingACodeDeletesTheCodesPastTheirTime`,
`TestACodeIsIssuedAgainAfterItWasClaimedOrLapsed` |
| Code texted to another agent's line | spent, then refused | answered
as an unknown code and counted as a failure; still claims on its own
line | `TestACodeForAnotherAgentIsNotSpent`,
`TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOnItsOwn`,
`TestCodesOfAnotherAgentCountAsWrongCodes` |

## Changes

- `migrations/global/20270128000000_channel_links_per_customer.sql`:
swaps the primary key in one `ALTER TABLE`, under the table's lock, as
`20270124000000_hash_call_tokens` did for `call_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
restores `PRIMARY KEY (code)`.
- `internal/store/channel_link.go`: `Insert` takes the draw function.
`Claim` takes the agent config id. `used_at` stays; Claim still skips a
row an older release marked used, so a mixed rollout cannot claim a code
twice.
- `internal/channels/service.go`: `Link` passes `linkCode`; `identify`
has 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 of `Link` is returned as is, so
it answers 500 "something went wrong" and not a 400 with the store's
text (`TestACodeThatCannotBeWrittenIsA500WithoutTheStoresWords`).
- No API change: the request and response stay the same, so no client is
regenerated.

Claim's delete and the other-agent check filter on the whole primary key
(`Index Scan using channel_links_pkey`, `Index Cond: customer_id, code`
with `enable_seqscan=off` on 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 ./...` and `go vet -tags integration ./...`, `gofmt -l`:
clean.
- On base 108539d,
`TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOnItsOwn` fails:
the code texted to the wrong line was spent, so its own line answered
"Send me the code ...".
- Migration Up and Down run by hand in one rolled-back transaction: Down
kept one of two apps' rows for a shared code and restored `PRIMARY KEY
(code)`; Up restored `(customer_id, code)` and took the second app's
row.
- 22 mutants (every changed condition, filter, bound and branch in the
store and the service), all killed. The script is in the ledger.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Tommaso Barbugli <tbarbugli@gmail.com>
martinmitrevski pushed a commit that referenced this pull request Nov 23, 2026
## 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>
Loschcode added a commit that referenced this pull request Nov 24, 2026
…call legs (#2270)

## Why


https://linear.app/stream/issue/AI-3511/small-wrong-results-spend-other-cancelling-a-price-already-in-force

Five small wrong results from the data layer review. Each one reproduced
on current `main`, and each is fixed in its own commit.

## What changed

- **Spend "other"** (`store/request.go`, `store/shard_merge.go`,
`api/server.go`).
- The remainder row now carries a new optional field, `other: true`, and
keeps `value: "other"`.
- A cost label whose value is `other` is now a row of its own, without
the flag, instead of being merged into the remainder.
- The field is `omitempty` and optional in the spec, so a client reading
an older router still parses its rows. An old client that picks the
remainder by `value == "other"` will now see two rows with that value
when a label really is `other`. Before, it saw them summed into one.
- Regenerated `openapi.yaml` and the Go, Python, JS, .NET, PHP, Ruby and
Rust SDKs. Swift's generator is not available locally, but the Swift
client has no `SpendBucket`, and its CI check passes.
  - Added an SDK note under `.claude/skills/sdk/notes/`.
- The Volt dashboard still keys on `value == "other"`. Follow-up:
[AI-3653](https://linear.app/stream/issue/AI-3653).
- **Cancelling a price already in force** (`store/price_change.go`).
- `Cancel` now checks `EffectiveAt` against `clock_timestamp()`, read
once the price list's lock is held, and writes the same time as
`cancelled_at`.
- The `price_changes` trigger that backs this up still uses `now()`, so
it has the same gap. The new test shows the trigger lets such a cancel
through when the Go check does. Fixing the trigger needs a migration,
which I left out while #2247 squashes them. Follow-up:
[AI-3654](https://linear.app/stream/issue/AI-3654), which also covers
`Insert` and `syncPrices`, both still stamped from `now()` after the
same lock wait.
- **Activity counted twice** (`store/activity.go`,
`activity/activity.go`).
- A write whose COMMIT was sent and got no answer is now
`store.ErrActivityUnsure`, and the recorder drops and logs it instead of
keeping its deltas. A dropped write holds nothing back, so `write`
reports true and a full record is not left waiting for the next tick.
- Commit failures that did not land are still retried. database/sql
answers a context that ended before the commit with `ErrTxDone` or the
context's error, without sending COMMIT; pgdriver sends COMMIT on
`context.Background()`, so neither comes from a COMMIT on the wire. An
error the server answered (`pgdriver.Error`) is a commit it refused.
- The trade-off: an ambiguous commit now undercounts, by at most one
write's rows, instead of double-counting.
- A write that fails before its commit wrote nothing and is still
written again (`TestAFailedWriteIsWrittenByTheNextOne`).
- I chose this over a batch id because a batch id needs a new table, so
a migration.
- **59 or 61 seconds** (`store/call_leg.go`, `joinTaken`).
- An inbound leg opens started at the call's arrival. A join delivered
after the leg already kept that start (`Connect` uses `COALESCE`).
- A join made after the arrival but delivered before it moved the start
to the join, so the same call billed a second less.
- The kept join now starts only a leg that has not started yet. Outbound
legs open unstarted, so they are unchanged.
- **Prices drift and BYOK** (`store/request.go`, `vendorCosts`).
- BYOK rows are left out of the drift query. They are priced with no
cost at the vendor's rates, so each one read as 100% under.
- Rows written before the `byok` column existed read `false` and stay
in. The default 168 h window ages them out.

## Tests

- `api` `TestALabelValuedOtherIsKeptApartFromTheRest`: a spend query
grouped by a tag with a value `other` returns it apart from the
remainder.
- `store` `TestACancelThatWaitedPastTheChangesTimeIsRefused`: a cancel
whose transaction starts before the change's time and waits on the lock
past it is refused. The change's time is read off the database's clock.
With `now()` it fails: the cancel goes through.
- `activity`, three tests:
- `TestAWriteWhoseCommitAnswerWasLostIsNotWrittenAgain`: a TCP proxy
passes COMMIT on and then cuts the client's connection, so the commit
lands and its answer is lost. The row is counted once. Without the drop
it is counted twice.
- `TestAWriteWhoseContextEndedBeforeItsCommitIsWrittenAgain`: a query
hook ends the context after the upsert. Commit returns without sending
COMMIT, nothing is written, and the error is not `ErrActivityUnsure`, so
it is retried.
- `TestACommitTheDatabaseRefusedIsNotUnsure`: a deferred constraint
fails the commit with an answer from the server, which is not
`ErrActivityUnsure`.
- Treating every commit error as unsure fails the last two. Never
treating one as unsure fails the first.
- `phone`
`TestACallerIsBilledFromTheArrivalWhicheverEventIsDeliveredFirst`:
before the fix it billed 59 s in one order and 60 s in the other. It now
bills 60 s both ways.
- `cmd/router` `TestDriftLeavesOutWorkOnTheCustomersOwnKey`: fails
without the filter (2 rows, `drift`).
- These pass, in both store suites where they apply: `go test -tags
integration` on `internal/store` (price, call leg, activity,
`TestEveryHotTableIsReadByIndex`, `TestRequestQueryBudgets`),
`internal/phone`, `internal/activity`, the spend tests of `internal/api`
`TestServerSuite`, and the drift tests of `cmd/router`
`TestPriceSyncSuite`. `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>
Loschcode added a commit that referenced this pull request Nov 24, 2026
…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>
Loschcode added a commit that referenced this pull request Nov 27, 2026
## Why


https://linear.app/stream/issue/AI-3202/a-reopened-fork-loses-its-parents-turns

A fork's channel starts empty, so its parent's turns reach the model
only through `spec.Recall`, which is set when the fork is created. A
fork that ended and is carried on from its row (`reopenedFromRow`) got
no recall, so the parent's turns were lost on every reopen. This
affected a fork at a `response_id` and a whole fork alike.

The row only had `forked_from`, and that is not enough to rebuild the
recall. A whole fork, a fork at a response, and a fork with `messages:
false` all look the same there.

## What changed

- **Migrations**:
- `migrations/shard/20270301001930_session_fork_point.sql` adds a
nullable `agent_sessions.fork_point jsonb`. It is expand-only and uses
the 5s lock timeout.
- The column holds `{"messages": true, "response_id": "…"}` or
`{"messages": false}`.
- NULL means a session that is not a fork, or a fork made before this
change, which is reopened as today.
- I chose jsonb over a text column because a text column would need a
sentinel string mixed in with response ids to say "none".
- `migrations/global/20270301009100_session_index_fork_point.sql` adds
the same column to `session_index`, and `fork_point` is added to
`indexedSessions`. The session lists read every model column from the
shared copy.
- **Version slots:** shard `20270301001930` is above main's `…001920`.
Global `20270301009100` is above main's `…008300` and above every open
PR's global migration (#2678 `…008400`, #2633 `…009000`). #2247, the
squash, touches both sets.
- **Fork create** (`forkSession` → `forkPoint`) records where the fork's
history stops:
  - At a response, it is that response.
- For a whole fork, it is the parent's last response at the moment of
the fork, read after flushing a running parent's records. The parent's
later turns are therefore never the fork's.
- **Reopen** (`forkRecall`) rebuilds the recall from the parent's
recorded turns on the path to the cut (`Responses.ExchangesAt`),
whatever was rewound or regenerated since:
- `ExchangesAt` reads the session's responses once, walks
`parent_response_id` up from the cut (`responseTree.pathTo`), then loads
the answers. That is two queries.
- Rows from before branches name no parent. Through those, the path
carries on by creation time, keeping those still in the conversation at
that point.
- It runs on both reopen paths: from the row, and from the spec a fork
ended on in this process (`carryOn`).
- **The reopen never fails because of the parent:**
- If the parent was deleted, or the response at the cut no longer
exists, the fork goes on without the parent's turns. This is logged at
info, and it also replaces what an in-process fork was opened with, so
deleted data is not handed to a model again.
- If the read fails, the row path goes on without the parent's turns,
and the in-process path keeps what it was opened with. The warn is
throttled to once a minute per app (`quota.Throttle`).
- A reopened session whose recall still reads a channel (only the
in-process snapshot after a failed re-read) logs a throttled warn and
goes on, instead of refusing. A fresh fork that cannot read its parent
is still refused.
- The datamove `bareColumns` gains `fork_point`, and the `forked_from`
comment now says it is read with the customer.

## Tests

`internal/api/fork_reopen_test.go` (`ForkReopenSuite`) uses the
`recites` model, so each answer is the exact history the model was
given. Most cases run on both reopen paths: "stopped" (from the row) and
"ended here" (in process).

- **At a response, and whole fork.** The history after the reopen must
start with the history before it. Both fail on main on the row path.
- **Whole fork after the parent says more.** The reopened fork does not
see the parent's later turns. It fails on the previous head on both
paths.
- **Parent regenerates the fork point.** The reopened fork keeps the
parent's turn as it was. It fails on the previous head on both paths.
- **Fork point deleted.** The fork goes on without the parent's turns.
On the in-process path, the test fails if the `ErrUnknownResponse`
branch is removed.
- **Other cases:**
  - parent deleted (both paths);
  - `messages: false`;
  - a pre-deploy fork with NULL;
  - a whole fork of a parent without a channel;
  - a fork of a fork;
- a fork made by a backend for another user than the parent's (at a
response: a whole fork of a channel they can't read is refused at
create).
- **Stored fork point:** one test for each kind of fork.
- **Store:** `ExchangesAt` follows the path through a regenerate,
carries on through pre-branch rows, refuses an unknown or another
customer's response, and stays within its query budget of 2.

The fork, reopen, branch, document, connector, reopen-settings,
resume-history and ownership suites pass locally. The schema files were
regenerated.

## Not in this PR

- A whole fork of a fork is made from a live read of its parent's
channel, which holds only the parent's own turns, so the grandparent's
turns are missing even at create. The `forkSpec` comment that the
parent's channel "already holds both" is wrong. This predates this PR.
- Tool history across a fork is still lost, because `store.ReplyItems`
is scoped to the conversation id.

🤖 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>

This branch has not been deployed

No deployments
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.

1 participant