Repository navigation
AI-3515: list a carried-on session once, guard late closes - #2279
martinmitrevski merged 7 commits into
Conversation
martinmitrevski
left a comment
There was a problem hiding this comment.
Reviewed #2279 at e4c7b31. CI on this head: GitGuardian and labeler passed, CodeQL Analyze still pending; the integration suites have not run in CI (draft).
Merge conflict: GitHub reports CONFLICTING. acceleration/internal/session/records.go conflicts with #2203 (7e3bbbaa4), which wraps every recorder write in attempt (retry for up to 10 s). Once rebased, Supersede runs inside attempt, so it has to be safe to run twice (see the comment on Supersede). The carried-on write also belongs in TestEveryWriteCutOffByADroppedConnectionIsStored.
Verdict: request changes. Two of these must land before merge: the unguarded conflict update in Upsert, which lets a late write from an earlier owner bring back both ticket bugs, and Get failing whenever any peer shard is down. The Supersede retry issue comes with the rebase. The missing wiring test and the Nit can follow.
Checked and sound:
- Migration
20270201000500: it adds nullable columns with no default, so it only changes the catalog and does not rewrite the table. It uses the same 5 slock_timeoutas20270127000200. The down migration drops only the two marker columns. Close: a row withopened_atNULL (every row from before the deploy) still closes. The only production caller passes the run'sOpenedAt, truncated to microseconds, which is the same value the row holds.- A→B→A: the
Upsertin A clears A's mark.Supersedemarks B's row, which opened earlier, and copies its fields back. Pin, unpin, review score,Describe,ChooseConnectionandClaimGuestwrite to every shard, so the two rows agree. - Session delete removes the row on every shard (
onEveryShard).BranchMessages.DeleteUserand the forget paths select by user across all rows, superseded ones included. A sharded deployment refuses to be an export source (errShardedSource), so no export carries two rows with one id. Getcallers run once per request or per call end, never per turn or frame, and none of them loops.go run ./cmd/openapileavesopenapi.yamlunchanged. No Huma operation changed.- Known gap beside the listed counts:
CustomerTurns(store.go:544) sumsCOUNT(DISTINCT session_id)over the shards, so it also counts a carried-on session once per shard. This was already true onmain.
Runs (from acceleration/, -tags integration -p 1, a database of this review's own): the PR's new store tests in TestStoreSuite and TestShardedStoreSuite all pass. I also ran four throwaway probes, then removed them; each one failed, confirming the findings inline.
e4c7b31 to
b694a46
Compare
martinmitrevski
left a comment
There was a problem hiding this comment.
Re-reviewed at b694a464a, against my review of e4c7b31. The branch merges cleanly into current main (git merge-tree, no conflict); GitHub shows it as MERGEABLE. CodeQL, GitGuardian and labeler passed; the integration jobs were skipped.
All five findings are addressed:
- Late
Upsert(dfb4fde35): fixed. A late same-shard write now changes nothing, so the earlier router's close leaves the live run open. A late write in the shard the session left keeps its superseded mark. A late insert is superseded by the newer run in another shard. Getwith a peer down (0a015cc00): fixed.Getreads its own shard first and reads the other shards only when its own row is superseded or missing. The trade-off, a stale row returned while the shard the session moved to is down, is limited to reads: a reopen still fails in that state, becauseActiveLeafreads every shard.Supersedesafe to retry (969dc3004): fixed. It now reads every earlier row, copies from them, and marks them last. Each write only moves one way, so running it twice ends the same.- Wiring test (
b694a464a): fixed. I inverted theReopenedcheck inCreateand the new test failed on both assertions. - Zero
opened(ffdc85512): fixed;Closenow refuses it. The refusal is not a transient error, soattemptdoes not retry it.
Rebase onto #2203: Close and Supersede now go through attempt. A retried Close is safe because of its closed_at IS NULL and opened_at guards; a retried Supersede is safe for the reasons in item 3.
Runs (-tags integration -p 1, a database of this review's own):
- Every new and changed store test passes, as do
TestAChatReopenedInAnotherShardIsListedByTheRowItRunsInand theRecordFlushSuiteretry tests. - My four earlier probes now pass. Two new probes also pass: a late insert followed by a retried
Supersede, and A→B→A with retries (one listed row; running and pinned from both shards).
Notes, not blocking:
- An unpin that lands between
Supersede's read and its copy is still re-pinned byCOALESCE. - The new
Upsertguard compares router clocks. A carry-on by a router whose clock is behind by more than the previous run's length is now ignored completely, where before it only weakened the close guard.
Verdict: the findings are addressed, and I have no new ones.
b694a46 to
e08b01a
Compare
#2279 (20270201000500) and #2276 (20270201000700) merge first, and goose refuses a migration older than the newest one applied, so this branch's migrations move above both: global 20270201001100 (phone_number_orders), global 20270201001110 (dlc registration requests) and shard 20270201001120 (call_legs_transfer_idx). Nothing else names the versions; the schema files are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A text session carried on in another shard gets a row there as well, which the shard's turns need. Lists showed it twice across pages, the new row lacked the pin, review score and last-answer time, and Get read the stale row of the shard it left. The row now records when its router opened it (opened_at). Carrying a session on supersedes its rows opened before, in every shard, and copies their pin, review score, last answer, modality and remembers onto the new one. Select, Search and Latest skip superseded rows; Get reads every shard and returns the one not superseded. Sessions.Close takes when the closing router opened the session and closes only a row not opened since, so a close queued by the router that held it no longer closes the run another router carried on. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Supersede marked the earlier rows and copied only what that mark returned. A call that failed after the mark committed in one shard (another shard down, a dropped connection, the copy failing) left nothing to copy for the retry the recorder now makes: the new row lost the pin, the review score, the last answer and remembers, and with remembers lost, deleting the session left that run's memories in the memory store. It now reads the earlier rows, superseded or not, copies from them, and marks them last, keeping the first mark. Run twice, it ends the same. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Upsert set opened_at and cleared superseded_at whatever the row held. A router's write of its own reopen, held up behind a slow write, could land after another router carried the session on. In the same shard it moved opened_at back, so its queued close then closed the live run; in the shard the session left it cleared the superseded mark, so the session was listed twice. The conflict update now changes nothing for a write opened before the run the row holds (a write with no opened_at, from a router before this release, still passes). superseded_at is when the run that superseded the row opened, and a write opened before it keeps the mark. Supersede marks this shard's own row when another shard holds a run opened since, for a late write that inserted the row. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Get read every shard at once and failed when any one failed, so one shard's outage broke reading, reopening and the phone call's session check on every shard, the last answering 409 for the caller's own session. It also sent every read to every shard. Get reads this shard's row first and answers with it unless it is superseded or missing; only then are the other shards read, as before this branch. While the shard a session was carried on in is down, its superseded row here answers, as it was when it left. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A zero opened matched only rows written before opened_at was kept, so a caller that left it out closed nothing and was told nothing, while Supersede refuses a zero time. The only caller passes the run's OpenedAt, which is always set, and a row from before the column is matched by its NULL whatever time is passed, so Close now refuses a zero time too. The tests pass when their rows opened. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only the branch in Create that queues CarriedOn for a reopened session makes Supersede run, and no test went through it: inverting it, or queueing Opened in both cases, passed the suite. The new test closes a chat on a router of one shard, pins it, reopens it through Create on a router of the other, and reads both: the row it runs in has the pin, and read from the shard it left it is running. Refs AI-3515 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#2258 added shard tests that call Sessions.Close without the time the closing router opened the session, and a second carriedOn helper. Both merged cleanly as text but did not compile: pass each row's open time and name #2258's helper carriedOnAt. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e08b01a to
8431575
Compare
#2279 (20270201000500) and #2276 (20270201000700) merge first, and goose refuses a migration older than the newest one applied, so this branch's migrations move above both: global 20270201001100 (phone_number_orders), global 20270201001110 (dlc registration requests) and shard 20270201001120 (call_legs_transfer_idx). Nothing else names the versions; the schema files are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#2279 and this branch both guard the session save's ON CONFLICT update: this one to leave another customer's row alone, #2279 to let a late write of an earlier run change nothing. Keep both conditions. When nothing is written, look whether the row is the customer's own: a late write of its own run is no error; another customer's id is ErrIDTaken. Also pass the open time to the one Close call of this branch's tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
How it works
A session carried on in another shard still gets a row there, since that shard's turns need one. The older row is now marked superseded, and every list skips it in SQL.
superseded_atis when the run that superseded the row opened. A write opened before it keeps the mark.A close only closes the run it belongs to, and a late write of an earlier run changes nothing:
sequenceDiagram participant R1 as Router 1 participant R2 as Router 2 participant PG as Postgres Note over R1: reopens the session at t1, its writes held up behind a slow one R2->>PG: carry on: Upsert, opened_at t2 R1->>PG: Upsert, opened_at t1 Note over PG: t1 < t2: the conflict update changes nothing R1->>PG: Close, opened t1: WHERE opened_at <= t1 Note over PG: no row matches, the session stays open R2->>PG: Close, opened t2 Note over PG: closedWhy
https://linear.app/stream/issue/AI-3515
Both items are real on
main(ce41c39):reopenedFromRow,internal/api/sessions.go:739). On a router of another shard, the recorder upserts a new row there, without the pin, review score or last-answer time of the first.Getread this shard first (whicheverShard,internal/store/shards.go:130) and so answered the stale row from the shard the session left.pageOfSessions(internal/store/session.go:677) dropped the older row only within one page. A cursor put the two rows on different pages, so the list showed the session twice (["chat", "other", "chat"]in the new test run on main's behaviour). A filter onstateorreview_scorecould match only the old row (a session running in B listed as closed), andLatest(org activity) listed both.Manager.Closereleases the session in the directory (internal/session/manager.go:1700) before the closer stamps and queues the close (:1702). Another router can carry it on in between. The queuedSessions.Close(internal/store/session.go:356) then matched the reopened row by id andclosed_at IS NULL, and closed the live session.Since #2203 the recorder retries every write, and one failing write can hold its queue for up to 10 s. So a router's write of its own reopen can also land after another router carried the session on. The guards below hold for that too.
Why not one row. Continuing on the shard that holds the row, or moving the row, was the first choice, but neither fits the code:
agent_responses,agent_branch_messagesandagent_session_toolshave a foreign key to that shard'sagent_sessions(migrations/shard/20270110000000_baseline.sql:787-799). The shard writing the turns must hold a row.So the per-shard rows stay as they are. The superseded marker gives each session one listed row in SQL. This is a root fix, not more read-side merging: every page, filter and
Latestsees one row.Changes
20270201000500: nullableopened_at,superseded_atonagent_sessionsADD COLUMN, 5 s lock timeoutTestTheSchemaFilesAreCurrent, schema regeneratedsessionRowstampsOpenedAtwith when this router opened the session;Upsertwrites itTestTheRowOfASessionCarriedOnIsOpenedWhenThisRouterOpenedItUpsert's conflict update hasWHEREthe write'sopened_atis not before the row's (a write with noopened_atpasses)TestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpenUpsertkeeps asuperseded_atlater than the write'sopened_atTestALateReopenWrittenInTheShardASessionLeftKeepsItListedOnceSessions.Close(…, opened, at, …)addsopened_at IS NULL OR opened_at <= opened, and refuses a zeroopened; the recorder and the session's closer pass the run'sOpenedAtTestACloseFromTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen,TestACloseQueuedByTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen,TestACloseThatDoesNotSayWhenItsRunOpenedIsRefusedSessions.Supersede, queued by the recorder after a carried-on row'sUpsert(CarriedOn), through #2203's retry like every recorder writeremembers, somayRememberstill forgets on deleteTestASessionCarriedOnInAnotherShardKeepsWhatItsRowHereSaid,TestAChatReopenedInAnotherShardIsListedByTheRowItRunsIn(throughManager.Create)Supersedereads every row first, copies, and marks last withGREATEST; every write only moves one wayTestASupersedeTriedAgainAfterAShardFailedTakesWhatTheEarlierRowSaidSupersedeonly marks rows opened before; finding a run opened after its own, it marks its own row insteadTestALateRowFromARouterThatHeldASessionEarlierLeavesItListedOnceByTheRunOpenedSincenarrowSessions(Select, Search) andLatestfiltersuperseded_at IS NULLTestASessionCarriedOnInAnotherShardIsListedOnceOnEveryPageWithItsPinGetreads this shard's row, and the other shards only when that row is superseded or missingTestASessionCarriedOnInAnotherShardIsFoundAsItIsThereFromTheShardItLeft,TestASessionHereIsFoundWhileAnotherShardIsDown,TestASessionCarriedOnInAShardThatIsDownIsFoundAsItLeftHereSQL
New statements, only when a session is carried on: one
SELECTper shard by primary key, then oneUPDATEof this shard's row by primary key and oneUPDATE … SET superseded_atper shard by primary key when an earlier row was found (or oneUPDATEof this shard's row when a later run was).Plans were taken with
EXPLAIN (ANALYZE, BUFFERS)on the store suite's seeded database (100,000agent_sessionsrows over 200 customers), local Postgres, warm cache, third run of each:agent_sessions_pkey, no conflict filterConflict Filteronopened_at, shared hit=69agent_sessions_last_message_idx, shared hit=29Filter: (superseded_at IS NULL), shared hit=29callagent_sessions_customer_idx, shared hit=16agent_sessions_pkey, shared hit=63agent_sessions_pkey, shared hit=4agent_sessions_pkey, shared hit=63agent_sessions_pkey, shared hit=8agent_sessions_pkeyNo plan or buffer count of an existing statement changed.
Getreads one shard for a live session, as on main;TestSessionQueryBudgetsholds it to one query. A carry-on makes one more primary-keySELECTandUPDATEper shard.Plan before: Select, default order
Plan after: Select, default order
Plan before / after: Latest
Plan before / after: Close, and Supersede's three statements
Plan after: Upsert
Not changed
Endingsand the activity counts (CustomerActivity,CustomerConcurrencyPeak) still count a carried-on session once per shard. They are counts, not lists. Worth a follow-up ticket if those numbers matter.opened_atnor touchsuperseded_at. While a multi-shard deployment rolls, a session carried back onto an old router keeps its superseded mark, and is listed by its other shard's row until a new router opens it again. A write with noopened_atpasses the new guard, so an old router's late write or close stays unguarded until every router runs this release.Supersedereaches the shard the session left, that shard's row is still listed andGetthere answers it, as on main. The recorder writes it right after the row, retried for up to 10 s; aSupersedethat gives up (a shard down for longer) is logged and leaves the session listed twice until it is carried on again.Getfrom the shard it left answers its superseded row, as it was when it left, rather than failing. Reopening it there, or the phone call's session check, still sees the caller's own session.Supersede's read and its copy is undone by the copy'sCOALESCE: a window of one statement, at a carry-on.agent_session_tools, which only the session tools endpoint reads back.Validation
Every new test was run against the code with its fix taken back out. Each failed for the reason it names:
ShardedStoreSuitetests above["chat","other","chat"], no pin, stateclosed, no last answer, live row closed["chat","other","chat"]closed,end_reasonleftLastResponseAtnilopenedTestACloseQueuedBy…(RecordFlushSuite)TestACloseQueuedBy…(RecordFlushSuite)OpenedAtfromcreatedTestTheRowOfASessionCarriedOnIsOpenedWhenThisRouterOpenedItTestASupersedeTriedAgainAfterAShardFailedTakesWhatTheEarlierRowSaidremembersfalseWHERETestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpenopened_atback at t1, titlelatesuperseded_atCASE (cleared instead)TestALateReopenWrittenInTheShardASessionLeftKeepsItListedOnce["chat","other","chat"]TestALateRowFromARouter…ListedOnceByTheRunOpenedSince["chat","other","chat"]TestASessionHereIsFoundWhileAnotherShardIsDown,TestASessionCarriedOnInAShardThatIsDownIsFoundAsItLeftHereopenedTestACloseThatDoesNotSayWhenItsRunOpenedIsRefusedCreatequeueingOpenedfor a reopen, or the condition invertedTestAChatReopenedInAnotherShardIsListedByTheRowItRunsIn(RecordedCreateSuite)Run locally, from
acceleration/, against a database and Redis of this branch's own:Rebased onto
mainat 49e60f1; no migration newer than20270201000500there.go build ./...,go vet(with and without-tags integration) oninternal/store,internal/session,internal/api,internal/phone/...,cmd/router, andgofmt -l: cleango test -tags integration -p 1 ./internal/session/ -count=1: ok (196 s)go test -tags integration -p 1 ./internal/store/ -count=1:ShardedStoreSuiteand every session, shard, query-budget andSessions.*index test pass. What fails is not this branch's: seven price-change tests inStoreSuiteand two campaign tests inDataMoveSuitefail the same way onmain(49e60f1), and the index test's seeding ofrequestshit the driver's read timeout on the shared test server under other runs' load (it passed in an earlier run of this branch)go test -tags integration -p 1 ./internal/api/ -run 'TestAppModeNamedCallSuite|TestCallStatusSuite|TestDeploymentNamedCallSuite|TestOrganizationActivitySuite|TestPhoneSuite|TestResumeHistorySuite|TestSessionCreateSuite|TestSessionDeleteSuite|TestSessionDeleteWithoutMemorySuite|TestSessionEndSuite|TestSessionListSuite|TestSessionReopenSettingsSuite|TestSessionVerbsSuite|TestSessionVoiceSuite|TestResponseBranchesSuite|TestScheduledTasksSuite': ok, 16 suites (one earlier run failedTestPhoneSuiteat the suite level with no test named; it passed five times alone and in the next full run)go test -tags integration -p 1 ./internal/phone/ ./internal/phone/outcome/ ./cmd/router/ -run 'TestOutcomeSuite|TestKeeperSuite|TestUsageCommandsSuite': okThe other packages' integration suites run in CI once the PR is marked ready.
🤖 Generated with Claude Code