diff --git a/acceleration/cmd/router/sandboxes_integration_test.go b/acceleration/cmd/router/sandboxes_integration_test.go index 50df1301d0..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, 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 54745502ef..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, 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 7581ff8924..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, 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 cf7e767d09..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, 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/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..65e4da7fe9 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,31 @@ func (s *RecordFlushSuite) TestAnotherCustomersCloseOfTheSameSessionIdLeavesItOp s.Empty(got.EndReason) } +func (s *RecordFlushSuite) TestACloseQueuedByTheRouterThatHeldASessionBeforeItWasReopenedLeavesItOpen() { + row := s.row() + 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 +481,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 +535,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 +666,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 +683,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") @@ -855,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/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 } 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..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, 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 6071e3888c..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", 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 23d66cfac8..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", 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 650654d8fe..48d101a4ff 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: 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"` // EndReason is why it ended (session.EndReason), empty while it runs and for one that @@ -309,6 +316,10 @@ 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"). + // 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. @@ -320,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)) @@ -327,6 +343,88 @@ 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 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. 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 +// 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")) + } + // 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 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). + Scan(ctx) + return rows, err + }) + if err != nil { + return stack.Wrap(fmt.Errorf("store: supersede session: %w", err)) + } + // 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 := 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", + 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)) + } + _, err = onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { + return db.NewUpdate().Model((*AgentSession)(nil)). + Set("superseded_at = GREATEST(superseded_at, ?)", opened). + 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 +} + // 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,10 +450,11 @@ 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 { - if customerID == "" || id == "" { - return stack.Wrap(errors.New("store: a customer and a session id are required")) +// 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 == "" || 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() @@ -369,6 +468,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 +588,35 @@ 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, 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")) } - session, err := whicheverShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (AgentSession, error) { - var session AgentSession - err := db.NewSelect().Model(&session). + 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). - Limit(1). Scan(ctx) - return session, err + // 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 len(sessions) > 0 { + return sessions[0], nil + } 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 + 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 @@ -706,7 +813,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 +946,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..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", 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", 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", 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", 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", 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) @@ -495,9 +495,50 @@ 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) 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 }) + 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", 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) @@ -1135,7 +1176,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 +1184,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) }}, @@ -1167,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, 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 }}, @@ -1198,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", 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 0938f82a7e..bd3b27fb12 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" ) @@ -80,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", 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)) @@ -91,12 +92,181 @@ 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", 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) + 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)) + + 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 { + 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]) + } + return listed +} + +func (s *ShardedStoreSuite) TestASessionCarriedOnInAnotherShardIsFoundAsItIsThereFromTheShardItLeft() { + 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.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", 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") + 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) 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") +} + +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 { + 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) 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)) + + 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() { 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", 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", 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) @@ -109,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) @@ -163,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) @@ -179,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)) @@ -200,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)) @@ -212,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) @@ -234,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) @@ -246,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})) } @@ -271,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) diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index b37bf068c2..801af3fa96 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", 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 c91283f67e..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", 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", 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", 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", 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", 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", 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) 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