From 5c9251598bef1f6c2229280526eb21059a82e993 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:07:48 +0100 Subject: [PATCH 1/7] fix(store): list a carried-on session once and guard late closes 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 --- .../cmd/router/sandboxes_integration_test.go | 2 +- .../internal/api/org_activity_test.go | 2 +- .../phone/outcome/keeper_integration_test.go | 2 +- .../phone/outcome_integration_test.go | 2 +- acceleration/internal/session/manager.go | 9 +- .../internal/session/record_flush_test.go | 38 +++++-- acceleration/internal/session/records.go | 36 +++++-- acceleration/internal/session/records_test.go | 17 ++- acceleration/internal/store/activity_test.go | 2 +- acceleration/internal/store/episode_test.go | 2 +- acceleration/internal/store/response_test.go | 2 +- acceleration/internal/store/session.go | 101 +++++++++++++++--- acceleration/internal/store/session_test.go | 39 +++++-- acceleration/internal/store/shards_test.go | 96 ++++++++++++++++- .../internal/store/store_explain_test.go | 5 +- acceleration/internal/store/usage_test.go | 12 +-- ...1000500_sessions_opened_and_superseded.sql | 11 ++ acceleration/schema/shard.sql | 2 + 18 files changed, 321 insertions(+), 59 deletions(-) create mode 100644 acceleration/migrations/shard/20270201000500_sessions_opened_and_superseded.sql diff --git a/acceleration/cmd/router/sandboxes_integration_test.go b/acceleration/cmd/router/sandboxes_integration_test.go index 50df1301d0..9009f8a782 100644 --- a/acceleration/cmd/router/sandboxes_integration_test.go +++ b/acceleration/cmd/router/sandboxes_integration_test.go @@ -97,7 +97,7 @@ func (s *UsageCommandsSuite) meteredBy(deployment, id, app, session string, at t func (s *UsageCommandsSuite) session(id, app string, closed time.Time) { s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ID: id, CustomerID: app})) if !closed.IsZero() { - s.Require().NoError(s.store.Sessions.Close(s.ctx, app, id, closed, "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, app, id, time.Time{}, closed, "")) } } diff --git a/acceleration/internal/api/org_activity_test.go b/acceleration/internal/api/org_activity_test.go index 54745502ef..20bedff3ed 100644 --- a/acceleration/internal/api/org_activity_test.go +++ b/acceleration/internal/api/org_activity_test.go @@ -469,7 +469,7 @@ func (s *OrganizationActivitySuite) openedAs(agent, appID string, at time.Time, ID: id, CustomerID: appID, AgentName: agent, Modality: store.ModalityVoice, CreatedAt: at, })) if !running { - s.Require().NoError(s.store.Sessions.Close(context.Background(), appID, id, at.Add(time.Minute), reason)) + s.Require().NoError(s.store.Sessions.Close(context.Background(), appID, id, time.Time{}, at.Add(time.Minute), reason)) } return id } diff --git a/acceleration/internal/phone/outcome/keeper_integration_test.go b/acceleration/internal/phone/outcome/keeper_integration_test.go index 7581ff8924..53e2bb44eb 100644 --- a/acceleration/internal/phone/outcome/keeper_integration_test.go +++ b/acceleration/internal/phone/outcome/keeper_integration_test.go @@ -126,7 +126,7 @@ func (s *KeeperSuite) sessionClosed(at time.Time, reason string) { s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ ID: s.call.CallID, CustomerID: s.call.CustomerID, })) - s.Require().NoError(s.store.Sessions.Close(s.ctx, s.call.CustomerID, s.call.CallID, at, reason)) + s.Require().NoError(s.store.Sessions.Close(s.ctx, s.call.CustomerID, s.call.CallID, time.Time{}, at, reason)) } func (s *KeeperSuite) placed() string { diff --git a/acceleration/internal/phone/outcome_integration_test.go b/acceleration/internal/phone/outcome_integration_test.go index cf7e767d09..b69e80952a 100644 --- a/acceleration/internal/phone/outcome_integration_test.go +++ b/acceleration/internal/phone/outcome_integration_test.go @@ -901,7 +901,7 @@ func (s *OutcomeSuite) TestAnArrivingCallItsAgentLeftOnTheLineIsCountedDropped() s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ ID: callID, CustomerID: s.customer, })) - s.Require().NoError(s.store.Sessions.Close(s.ctx, s.customer, callID, s.clock.now(), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, s.customer, callID, time.Time{}, s.clock.now(), "")) s.clock.advance(time.Minute) s.ended(defaultCallType, callID) diff --git a/acceleration/internal/session/manager.go b/acceleration/internal/session/manager.go index b201465833..3af263dd02 100644 --- a/acceleration/internal/session/manager.go +++ b/acceleration/internal/session/manager.go @@ -1045,10 +1045,15 @@ func (m *Manager) Create(ctx context.Context, spec Spec) (_ *Session, failure er // session behind, and once search has started, so its tool is among the ones stored. // The turns held until now, the greeting's among them, are written after it. if created.records != nil { + row := sessionRow(created) created.closers = append(created.closers, func() { - m.records.Closed(spec.CustomerID, created.id, time.Now().UTC(), created.kept()) + m.records.Closed(spec.CustomerID, created.id, row.OpenedAt, time.Now().UTC(), created.kept()) }) - m.records.Opened(sessionRow(created), toolRows(created)) + if spec.Reopened.IsZero() { + m.records.Opened(row, toolRows(created)) + } else { + m.records.CarriedOn(row, toolRows(created)) + } created.startRecording() } diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index 945ef43222..6256527762 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -329,7 +329,7 @@ func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOp row := s.row() s.records.Opened(row, nil) - s.records.Closed("other-"+s.customer, row.ID, time.Now().UTC(), TimeoutHangup) + s.records.Closed("other-"+s.customer, row.ID, row.OpenedAt, time.Now().UTC(), TimeoutHangup) s.Require().NoError(s.records.Flush(s.bounded())) got, err := s.store.Sessions.Get(s.ctx, s.customer, row.ID) @@ -339,6 +339,32 @@ func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOp s.Empty(got.EndReason) } +func (s *RecordFlushSuite) TestACloseQueuedByTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen() { + row := s.row() + row.OpenedAt = row.CreatedAt.Truncate(time.Microsecond) + s.records.Opened(row, nil) + s.Require().NoError(s.records.Flush(s.bounded())) + // Another router carries the session on while the close of this one is still queued. + reopening := newSessionRecorder(s.store, slog.New(slog.DiscardHandler)) + s.T().Cleanup(reopening.Close) + reopened := row + reopened.OpenedAt = row.OpenedAt.Add(time.Minute) + reopening.CarriedOn(reopened, nil) + s.Require().NoError(reopening.Flush(s.bounded())) + + s.records.Closed(s.customer, row.ID, row.OpenedAt, time.Now().UTC(), TimeoutHangup) + s.Require().NoError(s.records.Flush(s.bounded())) + got, err := s.store.Sessions.Get(s.ctx, s.customer, row.ID) + s.Require().NoError(err) + s.Nil(got.ClosedAt, "the run that carried it on has not ended") + + reopening.Closed(s.customer, row.ID, reopened.OpenedAt, time.Now().UTC(), TimeoutHangup) + s.Require().NoError(reopening.Flush(s.bounded())) + got, err = s.store.Sessions.Get(s.ctx, s.customer, row.ID) + s.Require().NoError(err) + s.NotNil(got.ClosedAt, "the router running it closes it") +} + func (s *RecordFlushSuite) TestTheItemsOfATurnWhoseIdIsAnotherCustomersAreNotWritten() { other := "other-" + s.customer theirs := store.AgentSession{ID: rand.Text(), CustomerID: other, State: store.SessionRunning, CreatedAt: time.Now().UTC()} @@ -456,9 +482,9 @@ func (s *RecordFlushSuite) TestEndsThatCannotBeStoredAreCountedOnceTheRetriesRun callsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)) start := time.Now() - records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) + records.Closed(s.customer, rand.Text(), time.Now().UTC(), time.Now().UTC(), TimeoutHangup) // Refused before it reaches the database, which says nothing about whether it is back. - records.Closed("", rand.Text(), time.Now().UTC(), TimeoutHangup) + records.Closed("", rand.Text(), time.Now().UTC(), time.Now().UTC(), TimeoutHangup) (&callRecorder{records: records}).Ended(s.customer, rand.Text(), time.Now().UTC()) // Bounded well past one retry budget, so a slow runner is not read as a hang. ctx, cancel := context.WithTimeout(s.ctx, 3*recordRetryFor) @@ -510,7 +536,7 @@ func (s *RecordFlushSuite) TestEveryWriteCutOffByADroppedConnectionIsStored() { }, { name: "a session ending", queue: func(r *sessionRecorder, rows cutRows) { - r.Closed(s.customer, rows.session.ID, time.Now().UTC(), TimeoutHangup) + r.Closed(s.customer, rows.session.ID, rows.session.OpenedAt, time.Now().UTC(), TimeoutHangup) }, check: func(rows cutRows) { s.NotNil(s.sessionOf(rows.session.ID).ClosedAt) }, }, { @@ -641,7 +667,7 @@ func (s *RecordFlushSuite) TestAnEndQueuedWhileTheDatabaseIsBrieflyDownAfterAnOu // A blip: down when the end is first tried, up again for its retry. proxy.setDown(true) refused := proxy.refused.Load() - records.Closed(s.customer, row.ID, time.Now().UTC(), TimeoutHangup) + records.Closed(s.customer, row.ID, row.OpenedAt, time.Now().UTC(), TimeoutHangup) s.Require().Eventually(func() bool { return proxy.refused.Load() > refused }, settleFor, time.Millisecond, "the end was never tried while the database was down") proxy.setDown(false) @@ -658,7 +684,7 @@ func (s *RecordFlushSuite) TestEndsAFullQueueDropsAreCounted() { sessionsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostSessionEnd)) callsLost := testutil.ToFloat64(recordsLost.WithLabelValues(lostCallEnd)) - s.records.Closed(s.customer, rand.Text(), time.Now().UTC(), TimeoutHangup) + s.records.Closed(s.customer, rand.Text(), time.Now().UTC(), time.Now().UTC(), TimeoutHangup) (&callRecorder{records: s.records}).Ended(s.customer, rand.Text(), time.Now().UTC()) s.Equal(int64(2), s.records.Dropped(), "the queue was not full") diff --git a/acceleration/internal/session/records.go b/acceleration/internal/session/records.go index d33a29e0bf..680d3bb94b 100644 --- a/acceleration/internal/session/records.go +++ b/acceleration/internal/session/records.go @@ -76,13 +76,16 @@ type recordWrite struct { // customerID is whose session the write is to: an id alone may be another customer's. customerID string // session is a session that opened or was renamed, nil otherwise, and tools what its - // model is offered. - session *store.AgentSession - tools []store.ToolDefinition + // model is offered. carriedOn says it was carried on from a row it had. + session *store.AgentSession + tools []store.ToolDefinition + carriedOn bool // offered is the session whose model is now offered tools. offered string - // closed is the session that ended, closedAt when and endReason why. + // closed is the session that ended, opened when the router closing it opened it, closedAt + // when it ended and endReason why. closed string + opened time.Time closedAt time.Time endReason string // response is a turn that began, nil otherwise. @@ -146,7 +149,8 @@ type recorder interface { type sessionRecords interface { recorder Opened(row store.AgentSession, tools []store.ToolDefinition) - Closed(customerID, id string, at time.Time, reason EndReason) + CarriedOn(row store.AgentSession, tools []store.ToolDefinition) + Closed(customerID, id string, opened, at time.Time, reason EndReason) Close() } @@ -202,14 +206,20 @@ func (r *sessionRecorder) Opened(row store.AgentSession, tools []store.ToolDefin r.queueWrite(recordWrite{session: &row, tools: tools}) } +// CarriedOn queues the row of a session carried on from a row it had, maybe in another shard, +// which it supersedes once written. +func (r *sessionRecorder) CarriedOn(row store.AgentSession, tools []store.ToolDefinition) { + r.queueWrite(recordWrite{session: &row, tools: tools, carriedOn: true}) +} + // Offered queues what a session's model is now offered. func (r *sessionRecorder) Offered(customerID, id string, tools []store.ToolDefinition) { r.queueWrite(recordWrite{customerID: customerID, offered: id, tools: tools}) } -// Closed queues the time a session ended. -func (r *sessionRecorder) Closed(customerID, id string, at time.Time, reason EndReason) { - r.queueWrite(recordWrite{customerID: customerID, closed: id, closedAt: at, endReason: string(reason)}) +// Closed queues the time a session this router opened at opened ended. +func (r *sessionRecorder) Closed(customerID, id string, opened, at time.Time, reason EndReason) { + r.queueWrite(recordWrite{customerID: customerID, closed: id, opened: opened, closedAt: at, endReason: string(reason)}) } // described is what a session was renamed to. @@ -434,6 +444,13 @@ func (r *sessionRecorder) write(write recordWrite) { r.logger.Error("could not record the session starting", "error", err) return } + if write.carriedOn { + if err := r.attempt(func(ctx context.Context) error { + return r.store.Sessions.Supersede(ctx, write.session.CustomerID, write.session.ID, write.session.OpenedAt) + }); err != nil { + r.logger.Error("could not supersede the rows of a session carried on", "session", write.session.ID, "error", err) + } + } if err := r.attempt(func(ctx context.Context) error { return r.store.SessionTools.Upsert(ctx, write.session.CustomerID, write.session.ID, write.tools) }); err != nil { @@ -447,7 +464,7 @@ func (r *sessionRecorder) write(write recordWrite) { } case write.closed != "": if err := r.attempt(func(ctx context.Context) error { - return r.store.Sessions.Close(ctx, write.customerID, write.closed, write.closedAt, write.endReason) + return r.store.Sessions.Close(ctx, write.customerID, write.closed, write.opened, write.closedAt, write.endReason) }); err != nil { // The row stays open, read as live and counted in every concurrency peak. recordsLost.WithLabelValues(lostSessionEnd).Inc() @@ -625,6 +642,7 @@ func sessionRow(created *Session) store.AgentSession { State: store.SessionRunning, Modality: created.Modality(), CreatedAt: created.created.UTC(), + OpenedAt: created.began.UTC().Truncate(time.Microsecond), } // Whose the session is comes from the credential rather than from the spec's UserID, // which is who the agent joined the call as. Recording the agent's own id as the owner diff --git a/acceleration/internal/session/records_test.go b/acceleration/internal/session/records_test.go index 00a2dc939d..2d66b89387 100644 --- a/acceleration/internal/session/records_test.go +++ b/acceleration/internal/session/records_test.go @@ -76,7 +76,9 @@ func (r *heldRecorder) Flush(context.Context) error { return nil } func (r *heldRecorder) Opened(store.AgentSession, []store.ToolDefinition) {} -func (r *heldRecorder) Closed(string, string, time.Time, EndReason) {} +func (r *heldRecorder) CarriedOn(store.AgentSession, []store.ToolDefinition) {} + +func (r *heldRecorder) Closed(string, string, time.Time, time.Time, EndReason) {} func (r *heldRecorder) Close() {} @@ -474,6 +476,19 @@ func (s *RecordSuite) TestTheRowSaysWhoseSessionItIsRatherThanWhoTheAgentJoinedA s.Equal(store.SessionRunning, row.State) } +func (s *RecordSuite) TestTheRowOfASessionCarriedOnIsOpenedWhenThisRouterOpenedIt() { + first := time.Date(2026, 3, 1, 10, 0, 0, 0, time.UTC) + began := first.Add(time.Hour).Add(1500 * time.Nanosecond) + carried := &Session{id: "session-1", created: first, began: began, + spec: Spec{CustomerID: "acme", Reopened: first}} + + row := sessionRow(carried) + + s.Equal(first, row.CreatedAt, "created when it first opened") + s.Equal(began.Truncate(time.Microsecond), row.OpenedAt, + "opened by this router now, so the close of the run before leaves it open") +} + func (s *RecordSuite) TestMatchesLiveAnswersTheSameFiltersAsTheStore() { created := time.Now() live := &Session{ diff --git a/acceleration/internal/store/activity_test.go b/acceleration/internal/store/activity_test.go index af0521c22f..f247fdf5ba 100644 --- a/acceleration/internal/store/activity_test.go +++ b/acceleration/internal/store/activity_test.go @@ -372,7 +372,7 @@ func (s *StoreSuite) began(into *Store, id, appID string, at, closed time.Time, ID: id, CustomerID: appID, AgentName: "agent-" + id, Modality: ModalityVoice, CreatedAt: at, })) if !closed.IsZero() { - s.Require().NoError(into.Sessions.Close(s.ctx, appID, id, closed, reason)) + s.Require().NoError(into.Sessions.Close(s.ctx, appID, id, time.Time{}, closed, reason)) } } diff --git a/acceleration/internal/store/episode_test.go b/acceleration/internal/store/episode_test.go index 6071e3888c..9a2fb644b0 100644 --- a/acceleration/internal/store/episode_test.go +++ b/acceleration/internal/store/episode_test.go @@ -749,7 +749,7 @@ func (s *StoreSuite) TestACardsLinesEndAtTheFirstThingThatEndsIt() { s.called(bob, "agent:phone-1", "session-bob", 30) closed := s.called(ann, "agent:phone-2", "session-closed", 40) s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &AgentSession{ID: "session-closed", CustomerID: "acme-app"})) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme-app", "session-closed", s.base.Add(45*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme-app", "session-closed", time.Time{}, s.base.Add(45*time.Minute), "")) ended := s.episodeIn(ann, "agent:thread-ended", 50) _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE episodes SET status = 'ended', ended_at = ? WHERE id = ?", s.base.Add(55*time.Minute), ended.ID) s.Require().NoError(err) diff --git a/acceleration/internal/store/response_test.go b/acceleration/internal/store/response_test.go index 23d66cfac8..c1133c2eed 100644 --- a/acceleration/internal/store/response_test.go +++ b/acceleration/internal/store/response_test.go @@ -431,7 +431,7 @@ func (s *StoreSuite) TestTheSameCustomerWritingARowAgainUnderItsIdIsNotAnError() func (s *StoreSuite) TestAnOwnerScopedWriteWithoutACustomerIsRefused() { at := s.base.Add(time.Hour) writes := map[string]func() error{ - "Sessions.Close": func() error { return s.store.Sessions.Close(s.ctx, "", "one", at, "hangup") }, + "Sessions.Close": func() error { return s.store.Sessions.Close(s.ctx, "", "one", time.Time{}, at, "hangup") }, "Sessions.SetToolTimeout": func() error { return s.store.Sessions.SetToolTimeout(s.ctx, "", "one", "user", 5_000) }, "Sessions.SawVideo": func() error { return s.store.Sessions.SawVideo(s.ctx, "", "one") }, "Sessions.Voiced": func() error { return s.store.Sessions.Voiced(s.ctx, "", "one") }, diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index 650654d8fe..c7ea10dbcb 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -140,6 +140,13 @@ type AgentSession struct { Modality string `bun:"modality,notnull"` CreatedAt time.Time `bun:"created_at,notnull"` UpdatedAt time.Time `bun:"updated_at,notnull"` + // OpenedAt is when the router running the session opened it, first or carried on since. + // Zero, stored as NULL, on a row from before it was kept. + OpenedAt time.Time `bun:"opened_at,nullzero"` + // SupersededAt is when the session was carried on in another shard, whose row says what it + // is from then on (Sessions.Supersede). A list leaves this row out. Nil for a row nothing + // superseded. + SupersededAt *time.Time `bun:"superseded_at"` // ClosedAt is nil while the session is still running. ClosedAt *time.Time `bun:"closed_at"` // EndReason is why it ended (session.EndReason), empty while it runs and for one that @@ -309,6 +316,8 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { Set("closed_at = NULL"). Set("end_reason = ''"). Set("updated_at = EXCLUDED.updated_at"). + Set("opened_at = EXCLUDED.opened_at"). + Set("superseded_at = NULL"). // A reopened session's tool settings are kept for the kind of caller that opened it (the // row's caller_kind, which a reopen does not change): an end user's device carrying on // its backend's conversation neither clears the backend's tools nor sets its timeout. @@ -327,6 +336,56 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { return nil } +// Supersede makes the row Upsert just wrote in this shard, of a session carried on there that +// this router opened at opened, the row the session is listed and found by. Its rows opened +// before, in any shard, are marked superseded, and this one takes from the newest of them +// what its own run has not seen: when it was pinned, its review score, when it last answered, +// the modality it reached and whether it remembered. This shard's own row is not among them: +// it opened at opened, not before. +// +// Only a row opened before is superseded, so a late write from a router that held the session +// earlier never hides the row of the one holding it now. +func (r *Sessions) Supersede(ctx context.Context, customerID, id string, opened time.Time) error { + if customerID == "" || id == "" || opened.IsZero() { + return stack.Wrap(errors.New("store: a customer, a session id and when it opened are required")) + } + lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { + var earlier []AgentSession + _, err := db.NewUpdate().Model((*AgentSession)(nil)). + Set("superseded_at = ?", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("superseded_at IS NULL"). + Where("opened_at IS NULL OR opened_at < ?", opened). + Returning("modality, last_response_at, pinned_at, review_score, remembers, updated_at"). + Exec(ctx, &earlier) + return earlier, err + }) + if err != nil { + return stack.Wrap(fmt.Errorf("store: supersede session: %w", err)) + } + newest := merged(lists, func(a, b AgentSession) int { return b.UpdatedAt.Compare(a.UpdatedAt) }, 1) + if len(newest) == 0 { + return nil + } + from := newest[0] + _, err = r.store.shard.NewUpdate().Model((*AgentSession)(nil)). + // Modality only moves up, and so does remembering: once true it stays true. + Set("modality = CASE WHEN ?0 IN (modality, ?2) THEN ?0 WHEN ?1 IN (modality, ?2) THEN ?1 ELSE modality END", + ModalityVideo, ModalityVoice, from.Modality). + Set("remembers = remembers OR ?", from.Remembers). + Set("last_response_at = GREATEST(last_response_at, ?)", from.LastResponseAt). + Set("pinned_at = COALESCE(pinned_at, ?)", from.PinnedAt). + Set("review_score = COALESCE(review_score, ?)", from.ReviewScore). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: supersede session: take its earlier row's: %w", err)) + } + return nil +} + // SetToolTimeout records the tool_timeout_ms a running session was given since it opened, by // a caller of kind. Only the kind that opened it changes the row, as on Upsert. Zero is the // default. @@ -352,8 +411,9 @@ func (r *Sessions) SetToolTimeout(ctx context.Context, customerID, id, kind stri // Close records that a session ended, and why: empty when nothing said. One that already // ended keeps the first time and reason: a session is left once, and a second close is the -// same leaving reported again. -func (r *Sessions) Close(ctx context.Context, customerID, id string, at time.Time, reason string) error { +// same leaving reported again. opened is when the router closing it opened it: a row another +// router opened again since, carrying the session on, is that router's to close. +func (r *Sessions) Close(ctx context.Context, customerID, id string, opened, at time.Time, reason string) error { if customerID == "" || id == "" { return stack.Wrap(errors.New("store: a customer and a session id are required")) } @@ -369,6 +429,7 @@ func (r *Sessions) Close(ctx context.Context, customerID, id string, at time.Tim Where("id = ?", id). Where("customer_id = ?", customerID). Where("closed_at IS NULL"). + Where("opened_at IS NULL OR opened_at <= ?", opened). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: close session: %w", err)) @@ -488,28 +549,39 @@ func (r *Sessions) Exists(ctx context.Context, id string) (bool, error) { return exists, nil } -// Get returns one session a customer ran. +// Get returns one session a customer ran. A session carried on in another shard has a row in +// each, so every shard is read for the row that says what it is now: the one not superseded, +// and of two not superseded, which a peer that could not be reached leaves, the one written +// last. func (r *Sessions) Get(ctx context.Context, customerID, id string) (AgentSession, error) { if customerID == "" || id == "" { return AgentSession{}, stack.Wrap(errors.New("store: a customer and a session id are required")) } - session, err := whicheverShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (AgentSession, error) { - var session AgentSession - err := db.NewSelect().Model(&session). + lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { + var sessions []AgentSession + err := db.NewSelect().Model(&sessions). Where("id = ?", id). Where("customer_id = ?", customerID). - Limit(1). Scan(ctx) - return session, err + return sessions, err }) - if errors.Is(err, sql.ErrNoRows) { - return AgentSession{}, unknownStoredSession(id) - } if err != nil { return AgentSession{}, stack.Wrap(fmt.Errorf("store: stored session: %w", err)) } - return session, nil + superseded := func(session AgentSession) int { + if session.SupersededAt != nil { + return 1 + } + return 0 + } + current := merged(lists, func(a, b AgentSession) int { + return cmp.Or(cmp.Compare(superseded(a), superseded(b)), b.UpdatedAt.Compare(a.UpdatedAt)) + }, 1) + if len(current) == 0 { + return AgentSession{}, unknownStoredSession(id) + } + return current[0], nil } // ConversationPin is the Stream app a customer's conversation was kept in, read off the @@ -706,7 +778,8 @@ func pageOfSessions(lists [][]AgentSession, filter SessionFilter) []AgentSession // honoured by query and forgotten by search is one a caller uses to read somebody else's // conversations. func narrowSessions(query *bun.SelectQuery, filter SessionFilter) *bun.SelectQuery { - query = query.Limit(SessionLimit(filter.Limit) + 1) + // A session carried on in another shard is listed by that shard's row alone. + query = query.Limit(SessionLimit(filter.Limit) + 1).Where("superseded_at IS NULL") if filter.UserID != "" { query = query.Where("user_id = ?", filter.UserID) @@ -838,7 +911,7 @@ FROM unnest(?::text[]) AS app(id) CROSS JOIN LATERAL ( SELECT id, customer_id, agent_name, modality, created_at, closed_at, end_reason FROM agent_sessions - WHERE customer_id = app.id AND created_at >= ? + WHERE customer_id = app.id AND created_at >= ? AND superseded_at IS NULL ORDER BY created_at DESC, id DESC LIMIT ? ) AS asn` diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index 06c7b7623b..ee8c59f73d 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -463,8 +463,8 @@ func (s *StoreSuite) TestSearchHonoursTheSameFiltersAsQuery() { func (s *StoreSuite) TestClosingASessionKeepsTheFirstTime() { s.opened("one", "app", s.base, nil) first := s.base.Add(time.Hour) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", first, "")) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", first.Add(time.Hour), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, first, "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, first.Add(time.Hour), "")) found, err := s.store.Sessions.Get(s.ctx, "app", "one") s.Require().NoError(err) @@ -475,8 +475,8 @@ func (s *StoreSuite) TestClosingASessionKeepsTheFirstTime() { func (s *StoreSuite) TestClosingASessionKeepsTheFirstReason() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base.Add(time.Hour), "transferred")) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base.Add(2*time.Hour), "hangup")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "transferred")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(2*time.Hour), "hangup")) found, err := s.store.Sessions.Get(s.ctx, "app", "one") s.Require().NoError(err) @@ -485,7 +485,7 @@ func (s *StoreSuite) TestClosingASessionKeepsTheFirstReason() { func (s *StoreSuite) TestAReopenedSessionHasNotEnded() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base.Add(time.Hour), "agent_hangup")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "agent_hangup")) s.opened("one", "app", s.base.Add(2*time.Hour), nil) @@ -495,9 +495,27 @@ func (s *StoreSuite) TestAReopenedSessionHasNotEnded() { s.Empty(found.EndReason, "a reopened session shows why its last run ended") } +func (s *StoreSuite) TestACloseFromTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen() { + first, again := s.base, s.base.Add(time.Hour) + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = first }) + // Another router carries it on before the close of the first is written. + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = again }) + + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", first, first.Add(time.Minute), "left")) + found, err := s.store.Sessions.Get(s.ctx, "app", "one") + s.Require().NoError(err) + s.Nil(found.ClosedAt, "the run that carried it on has not ended") + s.Equal(SessionRunning, found.State) + + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", again, again.Add(time.Minute), "left")) + found, err = s.store.Sessions.Get(s.ctx, "app", "one") + s.Require().NoError(err) + s.NotNil(found.ClosedAt, "the router running it closes it") +} + func (s *StoreSuite) TestDescribingASessionLongAfterItEnded() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base.Add(time.Hour), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "")) err := s.store.Sessions.Describe(s.ctx, "app", "one", "Named later", "by a person", map[string]any{"pinned": true}) s.Require().NoError(err) @@ -1135,7 +1153,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { s.opened(fmt.Sprintf("seeded-%02d", i), "app", at.Add(time.Duration(i)*time.Second), nil) } row := &AgentSession{ID: "budgeted", CustomerID: "app", AgentID: "agent", ConversationID: "conversation", - State: SessionRunning, CreatedAt: at.Add(time.Minute)} + State: SessionRunning, CreatedAt: at.Add(time.Minute), OpenedAt: at.Add(time.Minute)} tools := []ToolDefinition{{Name: "lookup", Description: "Looks it up."}} pages := func(listed []AgentSession, err error) error { s.Len(listed, 11, "a page and the row that says there is another") @@ -1143,6 +1161,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { } s.withinQueryBudgets([]queryBudget{ {"Upsert", 1, 0, func() error { return s.store.Sessions.Upsert(s.ctx, row) }}, + {"Supersede", 0, 1, func() error { return s.store.Sessions.Supersede(s.ctx, "app", row.ID, row.OpenedAt) }}, {"SetToolTimeout", 1, 0, func() error { return s.store.Sessions.SetToolTimeout(s.ctx, row.CustomerID, row.ID, "http", 900) }}, {"SawVideo", 1, 0, func() error { return s.store.Sessions.SawVideo(s.ctx, row.CustomerID, row.ID) }}, {"Voiced", 1, 0, func() error { return s.store.Sessions.Voiced(s.ctx, row.CustomerID, row.ID) }}, @@ -1151,7 +1170,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { return s.store.Sessions.ChooseConnection(s.ctx, "app", row.ID, "crm", "connection") }}, {"Exists", 1, 0, func() error { _, err := s.store.Sessions.Exists(s.ctx, row.ID); return err }}, - {"Get", 1, 0, func() error { _, err := s.store.Sessions.Get(s.ctx, "app", row.ID); return err }}, + {"Get", 0, 1, func() error { _, err := s.store.Sessions.Get(s.ctx, "app", row.ID); return err }}, {"ConversationPin", 0, 1, func() error { _, _, err := s.store.Sessions.ConversationPin(s.ctx, "app", "conversation") return err @@ -1167,7 +1186,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { }}, {"Ends", 1, 0, func() error { _, err := s.store.Sessions.Ends(s.ctx, []string{row.ID, "seeded-01"}, at); return err }}, {"Close", 1, 0, func() error { - return s.store.Sessions.Close(s.ctx, row.CustomerID, row.ID, at.Add(2*time.Minute), "hangup") + return s.store.Sessions.Close(s.ctx, row.CustomerID, row.ID, time.Time{}, at.Add(2*time.Minute), "hangup") }}, {"SessionTools.Upsert", 1, 0, func() error { return s.store.SessionTools.Upsert(s.ctx, row.CustomerID, row.ID, tools) }}, {"SessionTools.Get", 1, 0, func() error { _, err := s.store.SessionTools.Get(s.ctx, row.ID); return err }}, @@ -1198,7 +1217,7 @@ func (s *StoreSuite) TestAnotherCustomersWriteToASessionIdChangesNothing() { writes := map[string]func() error{ "SetToolTimeout": func() error { return s.store.Sessions.SetToolTimeout(s.ctx, "somebody-else", "one", "user", 5_000) }, "Close": func() error { - return s.store.Sessions.Close(s.ctx, "somebody-else", "one", s.base.Add(time.Hour), "hangup") + return s.store.Sessions.Close(s.ctx, "somebody-else", "one", time.Time{}, s.base.Add(time.Hour), "hangup") }, "SawVideo": func() error { return s.store.Sessions.SawVideo(s.ctx, "somebody-else", "one") }, "Voiced": func() error { return s.store.Sessions.Voiced(s.ctx, "somebody-else", "one") }, diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 0938f82a7e..650251995f 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -80,7 +80,7 @@ func (s *ShardedStoreSuite) TestARequestItsCallerCancelledIsLoggedAsNoError() { func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnce() { s.opened("chat", "app", s.base, func(session *AgentSession) { session.Title = "before" }) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base.Add(time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(time.Minute), "")) carried := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", Title: "after", CreatedAt: s.base} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) @@ -91,12 +91,102 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnce() { s.Equal(SessionRunning, sessions[0].State) } +// carriedOn writes what a router of the other shard writes of session id of "app" when it +// carries the session on there, having opened it at opened. +func (s *ShardedStoreSuite) carriedOn(id string, opened time.Time) { + carried := &AgentSession{ID: id, CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", + CreatedAt: s.base, OpenedAt: opened, Remembers: new(false)} + s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) + s.Require().NoError(s.other.Sessions.Supersede(s.ctx, "app", id, opened)) +} + +// answered records a turn of session id of "app" ending at, in into's shard. +func (s *ShardedStoreSuite) answered(into *Store, id string, at time.Time) { + response := id + "-" + at.Format(time.RFC3339) + s.Require().NoError(into.Responses.Insert(s.ctx, &AgentResponse{ID: response, SessionID: id, CustomerID: "app", CreatedAt: at})) + s.Require().NoError(into.Responses.Finish(s.ctx, "app", response, ResponseCompleted, "", at)) +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnceOnEveryPageWithItsPin() { + s.opened("chat", "app", s.base, nil) + _, err := s.store.Sessions.Pin(s.ctx, "app", "chat", true, s.base) + s.Require().NoError(err) + s.answered(s.store, "chat", s.base.Add(10*time.Minute)) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(11*time.Minute), "")) + // Answered between chat's last answer here and its first there, so on pages of one session + // each of chat's two rows falls on a page of its own. + s.opened("other", "app", s.base.Add(15*time.Minute), nil) + s.answered(s.store, "other", s.base.Add(20*time.Minute)) + s.carriedOn("chat", s.base.Add(25*time.Minute)) + s.answered(s.other, "chat", s.base.Add(30*time.Minute)) + + var listed []AgentSession + filter := SessionFilter{Limit: 1} + for range 5 { + page, err := s.store.Sessions.Select(s.ctx, "app", filter) + s.Require().NoError(err) + s.Require().NotEmpty(page) + listed = append(listed, page[0]) + if len(page) == 1 { + break + } + filter.Cursor = after(page[0]) + } + s.Equal([]string{"chat", "other"}, sessionIDs(listed), "once, by the row it runs in") + s.NotNil(listed[0].PinnedAt, "pinned before it was carried on") + s.Equal(SessionRunning, listed[0].State) +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsFoundAsItIsThereFromTheShardItLeft() { + s.opened("chat", "app", s.base, nil) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(time.Minute), "left")) + s.carriedOn("chat", s.base.Add(time.Hour)) + + found, err := s.store.Sessions.Get(s.ctx, "app", "chat") + s.Require().NoError(err) + s.Equal(SessionRunning, found.State, "the row it runs in, not the one it left closed here") + s.Nil(found.ClosedAt) + s.Empty(found.EndReason) +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardKeepsWhatItsRowHereSaid() { + s.opened("chat", "app", s.base, func(session *AgentSession) { + session.Modality = ModalityVoice + session.Remembers = new(true) + }) + s.answered(s.store, "chat", s.base.Add(10*time.Minute)) + s.changed("chat", "review_score = ?", 4) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(11*time.Minute), "")) + s.carriedOn("chat", s.base.Add(time.Hour)) + + found, err := s.other.Sessions.Get(s.ctx, "app", "chat") + s.Require().NoError(err) + s.Equal(SessionRunning, found.State) + s.Require().NotNil(found.LastResponseAt, "it sorts by its last answer, not by when it began") + s.True(found.LastResponseAt.Equal(s.base.Add(10 * time.Minute))) + s.Require().NotNil(found.ReviewScore) + s.Equal(4, *found.ReviewScore) + s.Equal(ModalityVoice, found.Modality, "a session spoken in stays a voice one") + s.Require().NotNil(found.Remembers) + s.True(*found.Remembers, "deleting it still forgets what it taught the memory store") +} + +func (s *ShardedStoreSuite) TestALateRowFromARouterThatHeldASessionEarlierHidesNoRowOpenedSince() { + s.opened("chat", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base.Add(2 * time.Hour) }) + // The other shard's write of a run before the one here, landing after it. + s.carriedOn("chat", s.base.Add(time.Hour)) + + var here AgentSession + s.Require().NoError(s.store.shard.NewSelect().Model(&here).Where("id = ?", "chat").Scan(s.ctx)) + s.Nil(here.SupersededAt, "the run opened here since is still listed") +} + func (s *ShardedStoreSuite) TestSessionsOpenInTwoShardsAtOnceAreOnePeak() { s.opened("here", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "here", s.base.Add(10*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "here", time.Time{}, s.base.Add(10*time.Minute), "")) there := &AgentSession{ID: "there", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", CreatedAt: s.base.Add(5 * time.Minute)} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, there)) - s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "there", s.base.Add(20*time.Minute), "")) + s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "there", time.Time{}, s.base.Add(20*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "app", s.base.Add(-time.Hour), s.base.Add(time.Hour)) s.Require().NoError(err) diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index b37bf068c2..619dcbc0fd 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -458,11 +458,14 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return store.Sessions.Upsert(ctx, &AgentSession{ID: "seeded-session-7", CustomerID: "customer-7", AgentName: "agent 7", UserID: "user-7", CallerKind: "user", CreatedAt: s.base}) }}, + {name: "Sessions.Supersede", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { + return store.Sessions.Supersede(ctx, "customer-8", "seeded-session-8", s.base) + }}, {name: "Sessions.SetToolTimeout", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { return store.Sessions.SetToolTimeout(ctx, "customer-7", "seeded-session-7", "search", 1000) }}, {name: "Sessions.Close", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { - return store.Sessions.Close(ctx, "customer-100", "seeded-session-100", s.base, "left") + return store.Sessions.Close(ctx, "customer-100", "seeded-session-100", time.Time{}, s.base, "left") }}, {name: "Sessions.SawVideo", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { return store.Sessions.SawVideo(ctx, "customer-7", "seeded-session-7") diff --git a/acceleration/internal/store/usage_test.go b/acceleration/internal/store/usage_test.go index c91283f67e..1c0e90836b 100644 --- a/acceleration/internal/store/usage_test.go +++ b/acceleration/internal/store/usage_test.go @@ -154,13 +154,13 @@ func (s *StoreSuite) ranTool(session *AgentSession, tool string, at time.Time, t func (s *StoreSuite) TestThePeakIsTheMostSessionsOpenAtOnce() { s.opened("first", "acme", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "first", s.base.Add(10*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "first", time.Time{}, s.base.Add(10*time.Minute), "")) s.opened("second", "acme", s.base.Add(2*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "second", s.base.Add(5*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "second", time.Time{}, s.base.Add(5*time.Minute), "")) s.opened("third", "acme", s.base.Add(3*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "third", s.base.Add(4*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "third", time.Time{}, s.base.Add(4*time.Minute), "")) s.opened("later", "acme", s.base.Add(20*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "later", s.base.Add(21*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "later", time.Time{}, s.base.Add(21*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "acme", s.base, s.base.Add(24*time.Hour)) s.Require().NoError(err) @@ -171,9 +171,9 @@ func (s *StoreSuite) TestThePeakIsTheMostSessionsOpenAtOnce() { func (s *StoreSuite) TestASessionThatClosedAsAnotherOpenedDidNotOverlapIt() { s.opened("before", "acme", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "before", s.base.Add(time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "before", time.Time{}, s.base.Add(time.Minute), "")) s.opened("after", "acme", s.base.Add(time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "after", s.base.Add(2*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "after", time.Time{}, s.base.Add(2*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "acme", s.base, s.base.Add(24*time.Hour)) s.Require().NoError(err) diff --git a/acceleration/migrations/shard/20270201000500_sessions_opened_and_superseded.sql b/acceleration/migrations/shard/20270201000500_sessions_opened_and_superseded.sql new file mode 100644 index 0000000000..2280630745 --- /dev/null +++ b/acceleration/migrations/shard/20270201000500_sessions_opened_and_superseded.sql @@ -0,0 +1,11 @@ +-- +goose Up +SET LOCAL lock_timeout = '5s'; + +-- When a router last opened the session, which a close from a router that held it before leaves +-- alone, and when another shard carried it on, which keeps this row out of lists from then on. +ALTER TABLE agent_sessions + ADD COLUMN IF NOT EXISTS opened_at timestamptz, + ADD COLUMN IF NOT EXISTS superseded_at timestamptz; + +-- +goose Down +ALTER TABLE agent_sessions DROP COLUMN IF EXISTS superseded_at, DROP COLUMN IF EXISTS opened_at; diff --git a/acceleration/schema/shard.sql b/acceleration/schema/shard.sql index 8817cf453f..85aa431a2f 100644 --- a/acceleration/schema/shard.sql +++ b/acceleration/schema/shard.sql @@ -94,6 +94,7 @@ TABLE agent_sessions modality text NOT NULL DEFAULT 'voice'::text model_overwrites jsonb NOT NULL DEFAULT '{}'::jsonb no_ui boolean + opened_at timestamp with time zone pinned_at timestamp with time zone project text NOT NULL DEFAULT ''::text remembers boolean @@ -103,6 +104,7 @@ TABLE agent_sessions searchable tsvector DEFAULT (((setweight(to_tsvector('english'::regconfig, COALESCE(title, ''::text)), 'A'::"char") || setweight(to_tsvector('english'::regconfig, COALESCE(description, ''::text)), 'B'::"char")) || setweight(to_tsvector('english'::regconfig, COALESCE(project, ''::text)), 'C'::"char")) || setweight(to_tsvector('english'::regconfig, COALESCE(agent_name, ''::text)), 'D'::"char")) state text NOT NULL stream_app_pk bigint + superseded_at timestamp with time zone team text NOT NULL DEFAULT ''::text title text NOT NULL DEFAULT ''::text tool_timeout_ms integer From d610629159fe0f1e7bfbc512d935414d0227a77f Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:46:28 +0100 Subject: [PATCH 2/7] fix(store): make Supersede safe to try again 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 --- acceleration/internal/store/session.go | 23 +++++++++++--- acceleration/internal/store/shards_test.go | 36 ++++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index c7ea10dbcb..b3fb2437ad 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -345,20 +345,22 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { // // Only a row opened before is superseded, so a late write from a router that held the session // earlier never hides the row of the one holding it now. +// +// The rows are read, superseded already or not, before any is marked, and every write only +// moves one way. A call that failed partway, which the recorder retries, ends as one that did +// not. func (r *Sessions) Supersede(ctx context.Context, customerID, id string, opened time.Time) error { if customerID == "" || id == "" || opened.IsZero() { return stack.Wrap(errors.New("store: a customer, a session id and when it opened are required")) } lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { var earlier []AgentSession - _, err := db.NewUpdate().Model((*AgentSession)(nil)). - Set("superseded_at = ?", time.Now().UTC()). + err := db.NewSelect().Model(&earlier). + Column("modality", "last_response_at", "pinned_at", "review_score", "remembers", "updated_at"). Where("id = ?", id). Where("customer_id = ?", customerID). - Where("superseded_at IS NULL"). Where("opened_at IS NULL OR opened_at < ?", opened). - Returning("modality, last_response_at, pinned_at, review_score, remembers, updated_at"). - Exec(ctx, &earlier) + Scan(ctx) return earlier, err }) if err != nil { @@ -383,6 +385,17 @@ func (r *Sessions) Supersede(ctx context.Context, customerID, id string, opened if err != nil { return stack.Wrap(fmt.Errorf("store: supersede session: take its earlier row's: %w", err)) } + _, err = onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { + return db.NewUpdate().Model((*AgentSession)(nil)). + Set("superseded_at = COALESCE(superseded_at, ?)", time.Now().UTC()). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("opened_at IS NULL OR opened_at < ?", opened). + Exec(ctx) + }) + if err != nil { + return stack.Wrap(fmt.Errorf("store: supersede session: mark its earlier rows: %w", err)) + } return nil } diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 650251995f..9bf95cd73a 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -4,6 +4,7 @@ package store import ( "encoding/json" + "fmt" "time" ) @@ -171,6 +172,41 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardKeepsWhatItsRowHe s.True(*found.Remembers, "deleting it still forgets what it taught the memory store") } +func (s *ShardedStoreSuite) TestASupersedeTriedAgainAfterAShardFailedTakesWhatTheEarlierRowSaid() { + s.opened("chat", "app", s.base, func(session *AgentSession) { session.Remembers = new(true) }) + _, err := s.store.Sessions.Pin(s.ctx, "app", "chat", true, s.base) + s.Require().NoError(err) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(time.Minute), "")) + opened := s.base.Add(time.Hour) + carried := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", + CreatedAt: s.base, OpenedAt: opened, Remembers: new(false)} + s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) + + // The first try also reads a shard that is down, and fails once the shard holding the + // earlier row has answered. The recorder tries again. + s.Require().Error(s.withAShardDown(s.other.shardDSN, s.shardDSN).Sessions.Supersede(s.ctx, "app", "chat", opened)) + s.Require().NoError(s.other.Sessions.Supersede(s.ctx, "app", "chat", opened)) + + found, err := s.other.Sessions.Get(s.ctx, "app", "chat") + s.Require().NoError(err) + s.NotNil(found.PinnedAt, "pinned before it was carried on") + s.Require().NotNil(found.Remembers) + s.True(*found.Remembers, "deleting it still forgets what its first run taught the memory store") +} + +// withAShardDown is a router of the shard own that reads the shards up and one more, which is +// down: nothing listens on port 1. +func (s *ShardedStoreSuite) withAShardDown(own string, up ...string) *Store { + shards := map[string]string{"own": own, "down": "postgres://postgres:postgres@127.0.0.1:1/down?sslmode=disable"} + for i, dsn := range up { + shards[fmt.Sprintf("up-%d", i)] = dsn + } + router, err := OpenShards(Options{DSN: s.dsn, ShardDSN: own, Shards: shards}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(router.Close()) }) + return router +} + func (s *ShardedStoreSuite) TestALateRowFromARouterThatHeldASessionEarlierHidesNoRowOpenedSince() { s.opened("chat", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base.Add(2 * time.Hour) }) // The other shard's write of a run before the one here, landing after it. From 6f74846a4210fad00583af0431a485b4d365ab5a Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:50:07 +0100 Subject: [PATCH 3/7] fix(store): keep a late write of an earlier run off the live row 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 --- acceleration/internal/store/session.go | 56 +++++++++++++++------ acceleration/internal/store/session_test.go | 15 ++++++ acceleration/internal/store/shards_test.go | 40 ++++++++++++--- 3 files changed, 89 insertions(+), 22 deletions(-) diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index b3fb2437ad..3cd50e7394 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -143,9 +143,9 @@ type AgentSession struct { // OpenedAt is when the router running the session opened it, first or carried on since. // Zero, stored as NULL, on a row from before it was kept. OpenedAt time.Time `bun:"opened_at,nullzero"` - // SupersededAt is when the session was carried on in another shard, whose row says what it - // is from then on (Sessions.Supersede). A list leaves this row out. Nil for a row nothing - // superseded. + // SupersededAt is when the session was carried on in another shard: when the router that + // carried it on opened it. That shard's row says what it is from then on + // (Sessions.Supersede), and a list leaves this row out. Nil for a row nothing superseded. SupersededAt *time.Time `bun:"superseded_at"` // ClosedAt is nil while the session is still running. ClosedAt *time.Time `bun:"closed_at"` @@ -317,7 +317,9 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { Set("end_reason = ''"). Set("updated_at = EXCLUDED.updated_at"). Set("opened_at = EXCLUDED.opened_at"). - Set("superseded_at = NULL"). + // Superseded by a run opened after this write's, the row stays superseded: the write is + // a late one, of a run that ended. + Set("superseded_at = CASE WHEN ?TableAlias.superseded_at > EXCLUDED.opened_at THEN ?TableAlias.superseded_at END"). // A reopened session's tool settings are kept for the kind of caller that opened it (the // row's caller_kind, which a reopen does not change): an end user's device carrying on // its backend's conversation neither clears the backend's tools nor sets its timeout. @@ -329,6 +331,11 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { // remembered before is still in the store, so once true it stays true. Not known // stays not known: NULL OR false is NULL. Set("remembers = ?TableAlias.remembers OR EXCLUDED.remembers"). + // A write of a run opened before the one the row holds is late, from a router that held + // the session earlier, and changes nothing: the close that router queued next would + // otherwise close the run opened since. A write with no time is a router's from before + // opened_at was kept. + Where("EXCLUDED.opened_at IS NULL OR ?TableAlias.opened_at IS NULL OR ?TableAlias.opened_at <= EXCLUDED.opened_at"). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: save session: %w", err)) @@ -338,13 +345,14 @@ func (r *Sessions) Upsert(ctx context.Context, session *AgentSession) error { // Supersede makes the row Upsert just wrote in this shard, of a session carried on there that // this router opened at opened, the row the session is listed and found by. Its rows opened -// before, in any shard, are marked superseded, and this one takes from the newest of them +// before, in any shard, are marked superseded, and this one takes from the one opened last // what its own run has not seen: when it was pinned, its review score, when it last answered, // the modality it reached and whether it remembered. This shard's own row is not among them: // it opened at opened, not before. // // Only a row opened before is superseded, so a late write from a router that held the session -// earlier never hides the row of the one holding it now. +// earlier never hides the row of the one holding it now. Such a write's own row is superseded +// instead, by the run opened since. // // The rows are read, superseded already or not, before any is marked, and every write only // moves one way. A call that failed partway, which the recorder retries, ends as one that did @@ -353,24 +361,42 @@ func (r *Sessions) Supersede(ctx context.Context, customerID, id string, opened if customerID == "" || id == "" || opened.IsZero() { return stack.Wrap(errors.New("store: a customer, a session id and when it opened are required")) } + // As Postgres keeps it, so this router's own row compares as opened at opened. + opened = opened.Truncate(time.Microsecond) lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { - var earlier []AgentSession - err := db.NewSelect().Model(&earlier). - Column("modality", "last_response_at", "pinned_at", "review_score", "remembers", "updated_at"). + var rows []AgentSession + err := db.NewSelect().Model(&rows). + Column("opened_at", "modality", "last_response_at", "pinned_at", "review_score", "remembers", "updated_at"). Where("id = ?", id). Where("customer_id = ?", customerID). - Where("opened_at IS NULL OR opened_at < ?", opened). Scan(ctx) - return earlier, err + return rows, err }) if err != nil { return stack.Wrap(fmt.Errorf("store: supersede session: %w", err)) } - newest := merged(lists, func(a, b AgentSession) int { return b.UpdatedAt.Compare(a.UpdatedAt) }, 1) - if len(newest) == 0 { + // The run opened last first. A row from before opened_at was kept reads as opened first. + rows := merged(lists, func(a, b AgentSession) int { + return cmp.Or(b.OpenedAt.Compare(a.OpenedAt), b.UpdatedAt.Compare(a.UpdatedAt)) + }, 0) + if len(rows) > 0 && rows[0].OpenedAt.After(opened) { + since := rows[0].OpenedAt + _, err := r.store.shard.NewUpdate().Model((*AgentSession)(nil)). + Set("superseded_at = GREATEST(superseded_at, ?)", since). + Where("id = ?", id). + Where("customer_id = ?", customerID). + Where("opened_at IS NULL OR opened_at < ?", since). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: supersede session: by a run opened since: %w", err)) + } + return nil + } + earlier := slices.IndexFunc(rows, func(row AgentSession) bool { return row.OpenedAt.Before(opened) }) + if earlier < 0 { return nil } - from := newest[0] + from := rows[earlier] _, err = r.store.shard.NewUpdate().Model((*AgentSession)(nil)). // Modality only moves up, and so does remembering: once true it stays true. Set("modality = CASE WHEN ?0 IN (modality, ?2) THEN ?0 WHEN ?1 IN (modality, ?2) THEN ?1 ELSE modality END", @@ -387,7 +413,7 @@ func (r *Sessions) Supersede(ctx context.Context, customerID, id string, opened } _, err = onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { return db.NewUpdate().Model((*AgentSession)(nil)). - Set("superseded_at = COALESCE(superseded_at, ?)", time.Now().UTC()). + Set("superseded_at = GREATEST(superseded_at, ?)", opened). Where("id = ?", id). Where("customer_id = ?", customerID). Where("opened_at IS NULL OR opened_at < ?", opened). diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index ee8c59f73d..28aaf1874a 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -513,6 +513,21 @@ func (s *StoreSuite) TestACloseFromTheRouterThatHeldASessionBeforeItWasReopenedL s.NotNil(found.ClosedAt, "the router running it closes it") } +func (s *StoreSuite) TestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpen() { + late, again := s.base.Add(time.Hour), s.base.Add(2*time.Hour) + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base }) + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = again }) + // The router that reopened it before then, its writes held up behind a slow one. + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt, session.Title = late, "late" }) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", late, late.Add(time.Minute), "left")) + + found, err := s.store.Sessions.Get(s.ctx, "app", "one") + s.Require().NoError(err) + s.Nil(found.ClosedAt, "the run carried on since has not ended") + s.True(found.OpenedAt.Equal(again), "the row went back to the run before") + s.Empty(found.Title) +} + func (s *StoreSuite) TestDescribingASessionLongAfterItEnded() { s.opened("one", "app", s.base, nil) s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "")) diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 9bf95cd73a..8088b96a5c 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -121,6 +121,32 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnceOnEve s.carriedOn("chat", s.base.Add(25*time.Minute)) s.answered(s.other, "chat", s.base.Add(30*time.Minute)) + listed := s.pagesOfOne() + s.Equal([]string{"chat", "other"}, sessionIDs(listed), "once, by the row it runs in") + s.NotNil(listed[0].PinnedAt, "pinned before it was carried on") + s.Equal(SessionRunning, listed[0].State) +} + +func (s *ShardedStoreSuite) TestALateReopenWrittenInTheShardASessionLeftKeepsItListedOnce() { + s.opened("chat", "app", s.base, nil) + s.answered(s.store, "chat", s.base.Add(10*time.Minute)) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(11*time.Minute), "")) + s.opened("other", "app", s.base.Add(15*time.Minute), nil) + s.answered(s.store, "other", s.base.Add(20*time.Minute)) + s.carriedOn("chat", s.base.Add(25*time.Minute)) + s.answered(s.other, "chat", s.base.Add(30*time.Minute)) + + // A router of this shard reopened it before it was carried on there, and the row of that + // reopen lands only now. Its supersede comes next, and may fail. + late := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", + CreatedAt: s.base, OpenedAt: s.base.Add(12 * time.Minute)} + s.Require().NoError(s.store.Sessions.Upsert(s.ctx, late)) + + s.Equal([]string{"chat", "other"}, sessionIDs(s.pagesOfOne()), "listed by the row it runs in alone") +} + +// pagesOfOne lists the sessions of "app" one to a page, following each page's cursor. +func (s *ShardedStoreSuite) pagesOfOne() []AgentSession { var listed []AgentSession filter := SessionFilter{Limit: 1} for range 5 { @@ -133,9 +159,7 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnceOnEve } filter.Cursor = after(page[0]) } - s.Equal([]string{"chat", "other"}, sessionIDs(listed), "once, by the row it runs in") - s.NotNil(listed[0].PinnedAt, "pinned before it was carried on") - s.Equal(SessionRunning, listed[0].State) + return listed } func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsFoundAsItIsThereFromTheShardItLeft() { @@ -207,14 +231,16 @@ func (s *ShardedStoreSuite) withAShardDown(own string, up ...string) *Store { return router } -func (s *ShardedStoreSuite) TestALateRowFromARouterThatHeldASessionEarlierHidesNoRowOpenedSince() { +func (s *ShardedStoreSuite) TestALateRowFromARouterThatHeldASessionEarlierLeavesItListedOnceByTheRunOpenedSince() { s.opened("chat", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base.Add(2 * time.Hour) }) + s.answered(s.store, "chat", s.base.Add(3*time.Hour)) + s.opened("other", "app", s.base.Add(time.Minute), nil) // The other shard's write of a run before the one here, landing after it. s.carriedOn("chat", s.base.Add(time.Hour)) - var here AgentSession - s.Require().NoError(s.store.shard.NewSelect().Model(&here).Where("id = ?", "chat").Scan(s.ctx)) - s.Nil(here.SupersededAt, "the run opened here since is still listed") + listed := s.pagesOfOne() + s.Equal([]string{"chat", "other"}, sessionIDs(listed), "listed by the row of the run opened since alone") + s.Equal(SessionRunning, listed[0].State) } func (s *ShardedStoreSuite) TestSessionsOpenInTwoShardsAtOnceAreOnePeak() { From af4338c56bcca2cfcf76312d82a7a8de80f9e040 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:51:51 +0100 Subject: [PATCH 4/7] fix(store): read a session from its own shard first 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 --- acceleration/internal/store/session.go | 30 +++++++++------------ acceleration/internal/store/session_test.go | 2 +- acceleration/internal/store/shards_test.go | 18 +++++++++++++ 3 files changed, 32 insertions(+), 18 deletions(-) diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index 3cd50e7394..72cbca5899 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -589,38 +589,34 @@ func (r *Sessions) Exists(ctx context.Context, id string) (bool, error) { } // Get returns one session a customer ran. A session carried on in another shard has a row in -// each, so every shard is read for the row that says what it is now: the one not superseded, -// and of two not superseded, which a peer that could not be reached leaves, the one written -// last. +// each, and the one not superseded says what it is now. The row in this shard answers unless it +// is superseded or missing; only then are the other shards read, so a shard that is down fails +// no read of a session it does not hold. While the shard a session was carried on in is down, +// its superseded row here answers, as it was when the session left. func (r *Sessions) Get(ctx context.Context, customerID, id string) (AgentSession, error) { if customerID == "" || id == "" { return AgentSession{}, stack.Wrap(errors.New("store: a customer and a session id are required")) } - lists, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { + sessions, err := whicheverShard(ctx, r.store, func(ctx context.Context, db bun.IDB) ([]AgentSession, error) { var sessions []AgentSession err := db.NewSelect().Model(&sessions). Where("id = ?", id). Where("customer_id = ?", customerID). Scan(ctx) + // Read past a superseded row, to the shard the session was carried on in. + if err == nil && (len(sessions) == 0 || sessions[0].SupersededAt != nil) { + err = sql.ErrNoRows + } return sessions, err }) - if err != nil { - return AgentSession{}, stack.Wrap(fmt.Errorf("store: stored session: %w", err)) + if len(sessions) > 0 { + return sessions[0], nil } - superseded := func(session AgentSession) int { - if session.SupersededAt != nil { - return 1 - } - return 0 - } - current := merged(lists, func(a, b AgentSession) int { - return cmp.Or(cmp.Compare(superseded(a), superseded(b)), b.UpdatedAt.Compare(a.UpdatedAt)) - }, 1) - if len(current) == 0 { + if errors.Is(err, sql.ErrNoRows) { return AgentSession{}, unknownStoredSession(id) } - return current[0], nil + return AgentSession{}, stack.Wrap(fmt.Errorf("store: stored session: %w", err)) } // ConversationPin is the Stream app a customer's conversation was kept in, read off the diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index 28aaf1874a..eef11a983f 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -1185,7 +1185,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { return s.store.Sessions.ChooseConnection(s.ctx, "app", row.ID, "crm", "connection") }}, {"Exists", 1, 0, func() error { _, err := s.store.Sessions.Exists(s.ctx, row.ID); return err }}, - {"Get", 0, 1, func() error { _, err := s.store.Sessions.Get(s.ctx, "app", row.ID); return err }}, + {"Get", 1, 0, func() error { _, err := s.store.Sessions.Get(s.ctx, "app", row.ID); return err }}, {"ConversationPin", 0, 1, func() error { _, _, err := s.store.Sessions.ConversationPin(s.ctx, "app", "conversation") return err diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 8088b96a5c..1e3721b754 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -218,6 +218,24 @@ func (s *ShardedStoreSuite) TestASupersedeTriedAgainAfterAShardFailedTakesWhatTh s.True(*found.Remembers, "deleting it still forgets what its first run taught the memory store") } +func (s *ShardedStoreSuite) TestASessionHereIsFoundWhileAnotherShardIsDown() { + s.opened("chat", "app", s.base, nil) + + found, err := s.withAShardDown(s.shardDSN, s.other.shardDSN).Sessions.Get(s.ctx, "app", "chat") + s.Require().NoError(err, "a shard that does not hold the session failed its read") + s.Equal("chat", found.ID) +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnInAShardThatIsDownIsFoundAsItLeftHere() { + s.opened("chat", "app", s.base, nil) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(time.Minute), "left")) + s.carriedOn("chat", s.base.Add(time.Hour)) + + found, err := s.withAShardDown(s.shardDSN).Sessions.Get(s.ctx, "app", "chat") + s.Require().NoError(err, "a session of the caller's own read as nobody's") + s.Equal(SessionClosed, found.State, "as it was when it left here") +} + // withAShardDown is a router of the shard own that reads the shards up and one more, which is // down: nothing listens on port 1. func (s *ShardedStoreSuite) withAShardDown(own string, up ...string) *Store { From 318fb5eeaa080c02884245ba275984b3e6d8bc70 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:55:15 +0100 Subject: [PATCH 5/7] fix(store): refuse a session close that does not say when it opened 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 --- .../cmd/router/sandboxes_integration_test.go | 2 +- .../internal/api/org_activity_test.go | 2 +- .../phone/outcome/keeper_integration_test.go | 2 +- .../phone/outcome_integration_test.go | 2 +- .../internal/session/record_flush_test.go | 4 ++-- acceleration/internal/store/activity_test.go | 2 +- acceleration/internal/store/episode_test.go | 2 +- acceleration/internal/store/response_test.go | 2 +- acceleration/internal/store/session.go | 4 ++-- acceleration/internal/store/session_test.go | 24 ++++++++++++------- acceleration/internal/store/shards_test.go | 12 +++++----- .../internal/store/store_explain_test.go | 2 +- acceleration/internal/store/usage_test.go | 12 +++++----- 13 files changed, 40 insertions(+), 32 deletions(-) diff --git a/acceleration/cmd/router/sandboxes_integration_test.go b/acceleration/cmd/router/sandboxes_integration_test.go index 9009f8a782..de54bd6930 100644 --- a/acceleration/cmd/router/sandboxes_integration_test.go +++ b/acceleration/cmd/router/sandboxes_integration_test.go @@ -97,7 +97,7 @@ func (s *UsageCommandsSuite) meteredBy(deployment, id, app, session string, at t func (s *UsageCommandsSuite) session(id, app string, closed time.Time) { s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ID: id, CustomerID: app})) if !closed.IsZero() { - s.Require().NoError(s.store.Sessions.Close(s.ctx, app, id, time.Time{}, closed, "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, app, id, closed, closed, "")) } } diff --git a/acceleration/internal/api/org_activity_test.go b/acceleration/internal/api/org_activity_test.go index 20bedff3ed..75308f3fce 100644 --- a/acceleration/internal/api/org_activity_test.go +++ b/acceleration/internal/api/org_activity_test.go @@ -469,7 +469,7 @@ func (s *OrganizationActivitySuite) openedAs(agent, appID string, at time.Time, ID: id, CustomerID: appID, AgentName: agent, Modality: store.ModalityVoice, CreatedAt: at, })) if !running { - s.Require().NoError(s.store.Sessions.Close(context.Background(), appID, id, time.Time{}, at.Add(time.Minute), reason)) + s.Require().NoError(s.store.Sessions.Close(context.Background(), appID, id, at, at.Add(time.Minute), reason)) } return id } diff --git a/acceleration/internal/phone/outcome/keeper_integration_test.go b/acceleration/internal/phone/outcome/keeper_integration_test.go index 53e2bb44eb..77a43c1481 100644 --- a/acceleration/internal/phone/outcome/keeper_integration_test.go +++ b/acceleration/internal/phone/outcome/keeper_integration_test.go @@ -126,7 +126,7 @@ func (s *KeeperSuite) sessionClosed(at time.Time, reason string) { s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ ID: s.call.CallID, CustomerID: s.call.CustomerID, })) - s.Require().NoError(s.store.Sessions.Close(s.ctx, s.call.CustomerID, s.call.CallID, time.Time{}, at, reason)) + s.Require().NoError(s.store.Sessions.Close(s.ctx, s.call.CustomerID, s.call.CallID, at, at, reason)) } func (s *KeeperSuite) placed() string { diff --git a/acceleration/internal/phone/outcome_integration_test.go b/acceleration/internal/phone/outcome_integration_test.go index b69e80952a..26b9f61c75 100644 --- a/acceleration/internal/phone/outcome_integration_test.go +++ b/acceleration/internal/phone/outcome_integration_test.go @@ -901,7 +901,7 @@ func (s *OutcomeSuite) TestAnArrivingCallItsAgentLeftOnTheLineIsCountedDropped() s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &store.AgentSession{ ID: callID, CustomerID: s.customer, })) - s.Require().NoError(s.store.Sessions.Close(s.ctx, s.customer, callID, time.Time{}, s.clock.now(), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, s.customer, callID, s.clock.now(), s.clock.now(), "")) s.clock.advance(time.Minute) s.ended(defaultCallType, callID) diff --git a/acceleration/internal/session/record_flush_test.go b/acceleration/internal/session/record_flush_test.go index 6256527762..65e4da7fe9 100644 --- a/acceleration/internal/session/record_flush_test.go +++ b/acceleration/internal/session/record_flush_test.go @@ -341,7 +341,6 @@ func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOp func (s *RecordFlushSuite) TestACloseQueuedByTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen() { row := s.row() - row.OpenedAt = row.CreatedAt.Truncate(time.Microsecond) s.records.Opened(row, nil) s.Require().NoError(s.records.Flush(s.bounded())) // Another router carries the session on while the close of this one is still queued. @@ -881,7 +880,8 @@ func (s *RecordFlushSuite) bounded() context.Context { } func (s *RecordFlushSuite) row() store.AgentSession { - return store.AgentSession{ID: rand.Text(), CustomerID: s.customer, State: store.SessionRunning, CreatedAt: time.Now().UTC()} + now := time.Now().UTC().Truncate(time.Microsecond) + return store.AgentSession{ID: rand.Text(), CustomerID: s.customer, State: store.SessionRunning, CreatedAt: now, OpenedAt: now} } // stored says whether the session's row is in Postgres. It is called from the callers' diff --git a/acceleration/internal/store/activity_test.go b/acceleration/internal/store/activity_test.go index f247fdf5ba..bb5ae10d5f 100644 --- a/acceleration/internal/store/activity_test.go +++ b/acceleration/internal/store/activity_test.go @@ -372,7 +372,7 @@ func (s *StoreSuite) began(into *Store, id, appID string, at, closed time.Time, ID: id, CustomerID: appID, AgentName: "agent-" + id, Modality: ModalityVoice, CreatedAt: at, })) if !closed.IsZero() { - s.Require().NoError(into.Sessions.Close(s.ctx, appID, id, time.Time{}, closed, reason)) + s.Require().NoError(into.Sessions.Close(s.ctx, appID, id, at, closed, reason)) } } diff --git a/acceleration/internal/store/episode_test.go b/acceleration/internal/store/episode_test.go index 9a2fb644b0..fb3d44c720 100644 --- a/acceleration/internal/store/episode_test.go +++ b/acceleration/internal/store/episode_test.go @@ -749,7 +749,7 @@ func (s *StoreSuite) TestACardsLinesEndAtTheFirstThingThatEndsIt() { s.called(bob, "agent:phone-1", "session-bob", 30) closed := s.called(ann, "agent:phone-2", "session-closed", 40) s.Require().NoError(s.store.Sessions.Upsert(s.ctx, &AgentSession{ID: "session-closed", CustomerID: "acme-app"})) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme-app", "session-closed", time.Time{}, s.base.Add(45*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme-app", "session-closed", s.base.Add(40*time.Minute), s.base.Add(45*time.Minute), "")) ended := s.episodeIn(ann, "agent:thread-ended", 50) _, err := s.store.GlobalDB().ExecContext(s.ctx, "UPDATE episodes SET status = 'ended', ended_at = ? WHERE id = ?", s.base.Add(55*time.Minute), ended.ID) s.Require().NoError(err) diff --git a/acceleration/internal/store/response_test.go b/acceleration/internal/store/response_test.go index c1133c2eed..d37de50d24 100644 --- a/acceleration/internal/store/response_test.go +++ b/acceleration/internal/store/response_test.go @@ -431,7 +431,7 @@ func (s *StoreSuite) TestTheSameCustomerWritingARowAgainUnderItsIdIsNotAnError() func (s *StoreSuite) TestAnOwnerScopedWriteWithoutACustomerIsRefused() { at := s.base.Add(time.Hour) writes := map[string]func() error{ - "Sessions.Close": func() error { return s.store.Sessions.Close(s.ctx, "", "one", time.Time{}, at, "hangup") }, + "Sessions.Close": func() error { return s.store.Sessions.Close(s.ctx, "", "one", s.base, at, "hangup") }, "Sessions.SetToolTimeout": func() error { return s.store.Sessions.SetToolTimeout(s.ctx, "", "one", "user", 5_000) }, "Sessions.SawVideo": func() error { return s.store.Sessions.SawVideo(s.ctx, "", "one") }, "Sessions.Voiced": func() error { return s.store.Sessions.Voiced(s.ctx, "", "one") }, diff --git a/acceleration/internal/store/session.go b/acceleration/internal/store/session.go index 72cbca5899..48d101a4ff 100644 --- a/acceleration/internal/store/session.go +++ b/acceleration/internal/store/session.go @@ -453,8 +453,8 @@ func (r *Sessions) SetToolTimeout(ctx context.Context, customerID, id, kind stri // same leaving reported again. opened is when the router closing it opened it: a row another // router opened again since, carrying the session on, is that router's to close. func (r *Sessions) Close(ctx context.Context, customerID, id string, opened, at time.Time, reason string) error { - if customerID == "" || id == "" { - return stack.Wrap(errors.New("store: a customer and a session id are required")) + if customerID == "" || id == "" || opened.IsZero() { + return stack.Wrap(errors.New("store: a customer, a session id and when it opened are required")) } if at.IsZero() { at = time.Now().UTC() diff --git a/acceleration/internal/store/session_test.go b/acceleration/internal/store/session_test.go index eef11a983f..fd58358759 100644 --- a/acceleration/internal/store/session_test.go +++ b/acceleration/internal/store/session_test.go @@ -463,8 +463,8 @@ func (s *StoreSuite) TestSearchHonoursTheSameFiltersAsQuery() { func (s *StoreSuite) TestClosingASessionKeepsTheFirstTime() { s.opened("one", "app", s.base, nil) first := s.base.Add(time.Hour) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, first, "")) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, first.Add(time.Hour), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, first, "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, first.Add(time.Hour), "")) found, err := s.store.Sessions.Get(s.ctx, "app", "one") s.Require().NoError(err) @@ -475,8 +475,8 @@ func (s *StoreSuite) TestClosingASessionKeepsTheFirstTime() { func (s *StoreSuite) TestClosingASessionKeepsTheFirstReason() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "transferred")) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(2*time.Hour), "hangup")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, s.base.Add(time.Hour), "transferred")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, s.base.Add(2*time.Hour), "hangup")) found, err := s.store.Sessions.Get(s.ctx, "app", "one") s.Require().NoError(err) @@ -485,7 +485,7 @@ func (s *StoreSuite) TestClosingASessionKeepsTheFirstReason() { func (s *StoreSuite) TestAReopenedSessionHasNotEnded() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "agent_hangup")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, s.base.Add(time.Hour), "agent_hangup")) s.opened("one", "app", s.base.Add(2*time.Hour), nil) @@ -513,6 +513,14 @@ func (s *StoreSuite) TestACloseFromTheRouterThatHeldASessionBeforeItWasReopenedL s.NotNil(found.ClosedAt, "the router running it closes it") } +func (s *StoreSuite) TestACloseThatDoesNotSayWhenItsRunOpenedIsRefused() { + s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base }) + + err := s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "left") + + s.Error(err, "it would close no row opened since opened_at was kept, and say nothing") +} + func (s *StoreSuite) TestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpen() { late, again := s.base.Add(time.Hour), s.base.Add(2*time.Hour) s.opened("one", "app", s.base, func(session *AgentSession) { session.OpenedAt = s.base }) @@ -530,7 +538,7 @@ func (s *StoreSuite) TestALateReopenAndItsCloseLeaveTheRunOpenedSinceOpen() { func (s *StoreSuite) TestDescribingASessionLongAfterItEnded() { s.opened("one", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", time.Time{}, s.base.Add(time.Hour), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "one", s.base, s.base.Add(time.Hour), "")) err := s.store.Sessions.Describe(s.ctx, "app", "one", "Named later", "by a person", map[string]any{"pinned": true}) s.Require().NoError(err) @@ -1201,7 +1209,7 @@ func (s *StoreSuite) TestSessionQueryBudgets() { }}, {"Ends", 1, 0, func() error { _, err := s.store.Sessions.Ends(s.ctx, []string{row.ID, "seeded-01"}, at); return err }}, {"Close", 1, 0, func() error { - return s.store.Sessions.Close(s.ctx, row.CustomerID, row.ID, time.Time{}, at.Add(2*time.Minute), "hangup") + return s.store.Sessions.Close(s.ctx, row.CustomerID, row.ID, row.OpenedAt, at.Add(2*time.Minute), "hangup") }}, {"SessionTools.Upsert", 1, 0, func() error { return s.store.SessionTools.Upsert(s.ctx, row.CustomerID, row.ID, tools) }}, {"SessionTools.Get", 1, 0, func() error { _, err := s.store.SessionTools.Get(s.ctx, row.ID); return err }}, @@ -1232,7 +1240,7 @@ func (s *StoreSuite) TestAnotherCustomersWriteToASessionIdChangesNothing() { writes := map[string]func() error{ "SetToolTimeout": func() error { return s.store.Sessions.SetToolTimeout(s.ctx, "somebody-else", "one", "user", 5_000) }, "Close": func() error { - return s.store.Sessions.Close(s.ctx, "somebody-else", "one", time.Time{}, s.base.Add(time.Hour), "hangup") + return s.store.Sessions.Close(s.ctx, "somebody-else", "one", s.base, s.base.Add(time.Hour), "hangup") }, "SawVideo": func() error { return s.store.Sessions.SawVideo(s.ctx, "somebody-else", "one") }, "Voiced": func() error { return s.store.Sessions.Voiced(s.ctx, "somebody-else", "one") }, diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index 1e3721b754..a1e6832681 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -81,7 +81,7 @@ func (s *ShardedStoreSuite) TestARequestItsCallerCancelledIsLoggedAsNoError() { func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnce() { s.opened("chat", "app", s.base, func(session *AgentSession) { session.Title = "before" }) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(time.Minute), "")) carried := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", Title: "after", CreatedAt: s.base} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) @@ -113,7 +113,7 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsListedOnceOnEve _, err := s.store.Sessions.Pin(s.ctx, "app", "chat", true, s.base) s.Require().NoError(err) s.answered(s.store, "chat", s.base.Add(10*time.Minute)) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(11*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(11*time.Minute), "")) // Answered between chat's last answer here and its first there, so on pages of one session // each of chat's two rows falls on a page of its own. s.opened("other", "app", s.base.Add(15*time.Minute), nil) @@ -164,7 +164,7 @@ func (s *ShardedStoreSuite) pagesOfOne() []AgentSession { func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsFoundAsItIsThereFromTheShardItLeft() { s.opened("chat", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(time.Minute), "left")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(time.Minute), "left")) s.carriedOn("chat", s.base.Add(time.Hour)) found, err := s.store.Sessions.Get(s.ctx, "app", "chat") @@ -181,7 +181,7 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardKeepsWhatItsRowHe }) s.answered(s.store, "chat", s.base.Add(10*time.Minute)) s.changed("chat", "review_score = ?", 4) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", time.Time{}, s.base.Add(11*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(11*time.Minute), "")) s.carriedOn("chat", s.base.Add(time.Hour)) found, err := s.other.Sessions.Get(s.ctx, "app", "chat") @@ -263,10 +263,10 @@ func (s *ShardedStoreSuite) TestALateRowFromARouterThatHeldASessionEarlierLeaves func (s *ShardedStoreSuite) TestSessionsOpenInTwoShardsAtOnceAreOnePeak() { s.opened("here", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "here", time.Time{}, s.base.Add(10*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "here", s.base, s.base.Add(10*time.Minute), "")) there := &AgentSession{ID: "there", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", CreatedAt: s.base.Add(5 * time.Minute)} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, there)) - s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "there", time.Time{}, s.base.Add(20*time.Minute), "")) + s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "there", s.base.Add(5*time.Minute), s.base.Add(20*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "app", s.base.Add(-time.Hour), s.base.Add(time.Hour)) s.Require().NoError(err) diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index 619dcbc0fd..801af3fa96 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -465,7 +465,7 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return store.Sessions.SetToolTimeout(ctx, "customer-7", "seeded-session-7", "search", 1000) }}, {name: "Sessions.Close", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { - return store.Sessions.Close(ctx, "customer-100", "seeded-session-100", time.Time{}, s.base, "left") + return store.Sessions.Close(ctx, "customer-100", "seeded-session-100", s.base, s.base, "left") }}, {name: "Sessions.SawVideo", index: "agent_sessions_pkey", run: func(ctx context.Context, store *Store) error { return store.Sessions.SawVideo(ctx, "customer-7", "seeded-session-7") diff --git a/acceleration/internal/store/usage_test.go b/acceleration/internal/store/usage_test.go index 1c0e90836b..5e1b14b052 100644 --- a/acceleration/internal/store/usage_test.go +++ b/acceleration/internal/store/usage_test.go @@ -154,13 +154,13 @@ func (s *StoreSuite) ranTool(session *AgentSession, tool string, at time.Time, t func (s *StoreSuite) TestThePeakIsTheMostSessionsOpenAtOnce() { s.opened("first", "acme", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "first", time.Time{}, s.base.Add(10*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "first", s.base, s.base.Add(10*time.Minute), "")) s.opened("second", "acme", s.base.Add(2*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "second", time.Time{}, s.base.Add(5*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "second", s.base.Add(2*time.Minute), s.base.Add(5*time.Minute), "")) s.opened("third", "acme", s.base.Add(3*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "third", time.Time{}, s.base.Add(4*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "third", s.base.Add(3*time.Minute), s.base.Add(4*time.Minute), "")) s.opened("later", "acme", s.base.Add(20*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "later", time.Time{}, s.base.Add(21*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "later", s.base.Add(20*time.Minute), s.base.Add(21*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "acme", s.base, s.base.Add(24*time.Hour)) s.Require().NoError(err) @@ -171,9 +171,9 @@ func (s *StoreSuite) TestThePeakIsTheMostSessionsOpenAtOnce() { func (s *StoreSuite) TestASessionThatClosedAsAnotherOpenedDidNotOverlapIt() { s.opened("before", "acme", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "before", time.Time{}, s.base.Add(time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "before", s.base, s.base.Add(time.Minute), "")) s.opened("after", "acme", s.base.Add(time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "after", time.Time{}, s.base.Add(2*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "acme", "after", s.base.Add(time.Minute), s.base.Add(2*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "acme", s.base, s.base.Add(24*time.Hour)) s.Require().NoError(err) From dda5d33cfa65f04ed9cd4e0addfdc3aab02860d6 Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 20:57:38 +0100 Subject: [PATCH 6/7] test(session): reopen a chat in another shard through Create 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 --- .../internal/session/recorded_create_test.go | 65 ++++++++++++++++++- 1 file changed, 63 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/session/recorded_create_test.go b/acceleration/internal/session/recorded_create_test.go index 71ae1e9c91..4b4b000951 100644 --- a/acceleration/internal/session/recorded_create_test.go +++ b/acceleration/internal/session/recorded_create_test.go @@ -12,12 +12,15 @@ import ( "testing" "time" + getstream "github.com/GetStream/getstream-go/v5" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" "github.com/GetStream/Vision-Agents/acceleration/internal/agent" + persistent "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" + "github.com/GetStream/Vision-Agents/acceleration/internal/conversation/chattest" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" "github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" @@ -38,6 +41,8 @@ type RecordedCreateSuite struct { ctx context.Context store *store.Store customer string + // dsn is the suite's database, which store keeps every table in. + dsn string } func TestRecordedCreateSuite(t *testing.T) { @@ -50,7 +55,8 @@ func (s *RecordedCreateSuite) SetupSuite() { s.T().Skip("ROUTER_POSTGRES_DSN is not set") } s.ctx = context.Background() - db, err := store.Open(testenv.Database(dsn, "recorded_create")) + s.dsn = testenv.Database(dsn, "recorded_create") + db, err := store.Open(s.dsn) s.Require().NoError(err) s.Require().NoError(db.Migrate(s.ctx)) s.store = db @@ -252,6 +258,12 @@ func (s *RecordedCreateSuite) spec(spec Spec) Spec { // manager is a session manager over the suite's Postgres, joining every call on edge and // speaking with voice. A nil finder leaves the deployment without search. func (s *RecordedCreateSuite) manager(edge agent.Edge, voice tts.TTS, finder search.Provider) *Manager { + return s.managerOn(s.store, nil, edge, voice, finder) +} + +// managerOn is manager over on, keeping conversations in conversations unless it is nil. +func (s *RecordedCreateSuite) managerOn(on *store.Store, conversations *persistent.Service, edge agent.Edge, voice tts.TTS, + finder search.Provider) *Manager { logger := slog.New(slog.DiscardHandler) transcription := sttrouter.NewRegistry() transcription.Register("stub", func(routing.Spec) (stt.STT, error) { return &stubSTT{emitter: stt.NewEmitter(64)}, nil }) @@ -270,7 +282,7 @@ func (s *RecordedCreateSuite) manager(edge agent.Edge, voice tts.TTS, finder sea s.T().Cleanup(speaker.Close) options := ManagerOptions{ - LLM: reasoner, STT: transcriber, TTS: speaker, Store: s.store, Logger: logger, + LLM: reasoner, STT: transcriber, TTS: speaker, Store: on, Conversations: conversations, Logger: logger, Edge: func(context.Context, Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) { return edge, nil }, } if finder != nil { @@ -285,6 +297,55 @@ func (s *RecordedCreateSuite) manager(edge agent.Edge, voice tts.TTS, finder sea return m } +func (s *RecordedCreateSuite) TestAChatReopenedInAnotherShardIsListedByTheRowItRunsIn() { + here, there := s.twoShards() + chat := chattest.Client(s.T()) + held := s.chatting(there, chat) + first, err := held.Create(s.ctx, Spec{CustomerID: s.customer, Text: true, PersistConversation: true, + LLMTarget: "en-low-latency", Caller: routing.Caller{UserID: "employee-1"}}) + s.Require().NoError(err) + s.Require().NoError(first.Close()) + s.Require().NoError(held.records.Flush(s.ctx)) + _, err = there.Sessions.Pin(s.ctx, s.customer, first.ID(), true, time.Now().UTC()) + s.Require().NoError(err) + + carrying := s.chatting(here, chat) + reopened, err := carrying.Create(s.ctx, Spec{ID: first.ID(), CustomerID: s.customer, Text: true, PersistConversation: true, + ConversationID: first.Spec().ConversationID, Reopened: first.CreatedAt(), LLMTarget: "en-low-latency", + Caller: routing.Caller{UserID: "employee-1"}}) + s.Require().NoError(err) + s.T().Cleanup(func() { _ = reopened.Close() }) + s.Require().NoError(carrying.records.Flush(s.ctx)) + + running, err := here.Sessions.Get(s.ctx, s.customer, first.ID()) + s.Require().NoError(err) + s.NotNil(running.PinnedAt, "the row it runs in lost the pin it had before") + left, err := there.Sessions.Get(s.ctx, s.customer, first.ID()) + s.Require().NoError(err) + s.Equal(store.SessionRunning, left.State, "read where it left, it is listed by its closed row there") +} + +// twoShards are the stores of a router of each of two shards, over the suite's database. +func (s *RecordedCreateSuite) twoShards() (here, there *store.Store) { + dsn := os.Getenv("ROUTER_POSTGRES_DSN") + a, b := testenv.Database(dsn, "recorded_shard_a"), testenv.Database(dsn, "recorded_shard_b") + open := func(own string) *store.Store { + router, err := store.OpenShards(store.Options{DSN: s.dsn, ShardDSN: own, Shards: map[string]string{"a": a, "b": b}}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.Require().NoError(router.Close()) }) + s.Require().NoError(router.Migrate(s.ctx)) + return router + } + return open(a), open(b) +} + +// chatting is a session manager over on that keeps its conversations in chat. +func (s *RecordedCreateSuite) chatting(on *store.Store, chat *getstream.Stream) *Manager { + conversations := persistent.NewForChat(chat) + s.T().Cleanup(conversations.Close) + return s.managerOn(on, conversations, newQuietEdge(), &stubTTS{emitter: tts.NewEmitter(64)}, nil) +} + // refusingEdge is a call that will not have the agent. type refusingEdge struct{ *quietEdge } From 8431575f8aa344b90e522be5da7a00d5759bb1ab Mon Sep 17 00:00:00 2001 From: Martin Mitrevski Date: Mon, 23 Nov 2026 22:18:49 +0100 Subject: [PATCH 7/7] test(store): fit main's shard tests to Close taking the open time #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 --- acceleration/internal/store/shards_test.go | 24 +++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/acceleration/internal/store/shards_test.go b/acceleration/internal/store/shards_test.go index a1e6832681..bd3b27fb12 100644 --- a/acceleration/internal/store/shards_test.go +++ b/acceleration/internal/store/shards_test.go @@ -279,8 +279,8 @@ func (s *ShardedStoreSuite) TestASessionOpenInTwoShardsAtOnceIsOneInThePeak() { s.opened("chat", "app", s.base, nil) carried := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", CreatedAt: s.base} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) - s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "chat", s.base.Add(20*time.Minute), "")) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base.Add(30*time.Minute), "")) + s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(20*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(30*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "app", s.base.Add(-time.Hour), s.base.Add(time.Hour)) s.Require().NoError(err) @@ -333,7 +333,7 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsOneSessionOfIts func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsOneSessionOfItsActivity() { session := s.opened("chat", "app", s.base, nil) s.turned(session, "chat-1", s.base, nil) - s.carriedOn("chat", s.base.Add(time.Minute)) + s.carriedOnAt("chat", s.base.Add(time.Minute)) s.turnedThere("chat", "chat-2", "chat-1", s.base.Add(time.Minute), nil) s.opened("another", "app", s.base.Add(time.Minute), nil) @@ -349,7 +349,7 @@ func (s *ShardedStoreSuite) TestASessionCarriedOnIsCountedOnTheDayItBeganWhateve dayOne, dayTwo := s.base, s.base.Add(24*time.Hour) session := s.opened("chat", "app", dayOne, nil) s.turned(session, "chat-1", dayOne, nil) - s.carriedOn("chat", dayTwo) + s.carriedOnAt("chat", dayTwo) s.turnedThere("chat", "chat-2", "chat-1", dayTwo, nil) second, err := s.store.CustomerActivity(s.ctx, "app", ActivityDaily, dayTwo, dayTwo.Add(24*time.Hour)) @@ -370,7 +370,7 @@ func (s *ShardedStoreSuite) TestADayHoldingOnlyACarriedOnRowIsNotListed() { dayOne, dayTwo := s.base, s.base.Add(24*time.Hour) session := s.opened("chat", "app", dayOne, nil) s.turned(session, "chat-1", dayOne, nil) - s.carriedOn("chat", dayTwo) + s.carriedOnAt("chat", dayTwo) s.turnedThere("chat", "chat-2", "chat-1", dayTwo.Add(24*time.Hour), nil) buckets, err := s.store.CustomerActivity(s.ctx, "app", ActivityDaily, dayTwo, dayTwo.Add(24*time.Hour)) @@ -382,7 +382,7 @@ func (s *ShardedStoreSuite) TestATurnRewoundInTheOtherShardIsNotCountedBeforeATo session := s.opened("chat", "app", s.base, nil) s.turned(session, "chat-1", s.base, nil) s.turned(session, "chat-2", s.base.Add(time.Minute), answeredAfter("chat-1")) - s.carriedOn("chat", s.base.Add(2*time.Minute)) + s.carriedOnAt("chat", s.base.Add(2*time.Minute)) rewound := s.base.Add(3 * time.Minute) s.turnedThere("chat", "chat-gone", "chat-2", s.base.Add(2*time.Minute), &rewound) s.turnedThere("chat", "chat-3", "chat-2", s.base.Add(3*time.Minute), nil) @@ -404,7 +404,7 @@ func (s *ShardedStoreSuite) TestTurnsAtTheSameInstantInTwoShardsAreOrderedById() s.turned(session, "x", at, answeredAfter("chat-1")) s.turned(session, "z", at, answeredAfter("x")) s.calledTool(session, "z", "refund", at, map[string]any{"call_id": "c1"}, map[string]any{"call_id": "c1"}) - s.carriedOn("chat", at) + s.carriedOnAt("chat", at) s.turnedThere("chat", "w", "chat-1", at, nil) s.turnedThere("chat", "y", "w", at, nil) s.calledToolThere("chat", "y", "refund", at) @@ -416,8 +416,8 @@ func (s *ShardedStoreSuite) TestTurnsAtTheSameInstantInTwoShardsAreOrderedById() s.InDelta(3.0, *tools[0].AvgTurnsBeforeUse, 0.001) } -// carriedOn writes the row a session carried on in the other shard has there. -func (s *ShardedStoreSuite) carriedOn(id string, at time.Time) { +// carriedOnAt writes the row a session carried on in the other shard has there. +func (s *ShardedStoreSuite) carriedOnAt(id string, at time.Time) { s.Require().NoError(s.other.Sessions.Upsert(s.ctx, &AgentSession{ID: id, CustomerID: "app", AgentName: "docs", ConfigID: "cfg-docs", UserID: "jlahey", CallerKind: "user", CreatedAt: at})) } @@ -441,12 +441,12 @@ func (s *ShardedStoreSuite) calledToolThere(sessionID, responseID, tool string, func (s *ShardedStoreSuite) TestASessionAwayFromOneShardWhileAnotherRanIsNotOpenThroughTheGap() { s.opened("chat", "app", s.base, nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base.Add(10*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "chat", s.base, s.base.Add(10*time.Minute), "")) carried := &AgentSession{ID: "chat", CustomerID: "app", AgentName: "docs", UserID: "jlahey", CallerKind: "user", CreatedAt: s.base.Add(20 * time.Minute)} s.Require().NoError(s.other.Sessions.Upsert(s.ctx, carried)) - s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "chat", s.base.Add(30*time.Minute), "")) + s.Require().NoError(s.other.Sessions.Close(s.ctx, "app", "chat", s.base.Add(20*time.Minute), s.base.Add(30*time.Minute), "")) s.opened("between", "app", s.base.Add(12*time.Minute), nil) - s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "between", s.base.Add(18*time.Minute), "")) + s.Require().NoError(s.store.Sessions.Close(s.ctx, "app", "between", s.base.Add(12*time.Minute), s.base.Add(18*time.Minute), "")) peak, err := s.store.CustomerConcurrencyPeak(s.ctx, "app", s.base.Add(-time.Hour), s.base.Add(time.Hour)) s.Require().NoError(err)