Skip to content
2 changes: 1 addition & 1 deletion acceleration/cmd/router/sandboxes_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, ""))
}
}

Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/api/org_activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/phone/outcome_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 7 additions & 2 deletions acceleration/internal/session/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Comment thread
martinmitrevski marked this conversation as resolved.
Resolved
m.records.Opened(row, toolRows(created))
} else {
m.records.CarriedOn(row, toolRows(created))
}
created.startRecording()
}

Expand Down
40 changes: 33 additions & 7 deletions acceleration/internal/session/record_flush_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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()}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) },
}, {
Expand Down Expand Up @@ -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)
Expand All @@ -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")
Expand Down Expand Up @@ -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'
Expand Down
65 changes: 63 additions & 2 deletions acceleration/internal/session/recorded_create_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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) {
Expand All @@ -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
Expand Down Expand Up @@ -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 })
Expand All @@ -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 {
Expand All @@ -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 }

Expand Down
36 changes: 27 additions & 9 deletions acceleration/internal/session/records.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
}

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 {
Expand All @@ -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()
Expand Down Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion acceleration/internal/session/records_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {}

Expand Down Expand Up @@ -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{
Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/store/activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
}

Expand Down
2 changes: 1 addition & 1 deletion acceleration/internal/store/episode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading