Skip to content
6 changes: 5 additions & 1 deletion acceleration/internal/api/callhooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,11 @@ func (s *CallHooksSuite) TestAnArrivingCallToANumberWhoseAgentIsGoneIsRefused()
config := s.config("echo/local-model")
ctx := context.Background()
s.Require().NoError(s.store.PhoneNumbers.SetAgent(ctx, s.customerID(), s.e164, config))
s.Require().NoError(s.store.AgentConfigs.Delete(ctx, s.customerID(), config))
// A delete refuses a config a number answers with, so the row is marked deleted as a
// router from before that refusal left it.
_, err := s.store.GlobalDB().NewUpdate().Table("agent_configs").Set("deleted_at = now()").
Where("id = ?", config).Exec(ctx)
s.Require().NoError(err)
worker, release := s.dispatch.Register(s.customerID(), dispatch.Registration{Capacity: 1})
defer release()

Expand Down
14 changes: 7 additions & 7 deletions acceleration/internal/api/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -410,13 +410,6 @@ func (s *Server) deleteAgentConfig(ctx context.Context, request *deleteAgentConf
if err != nil {
return nil, unknownOr(err, store.ErrNoAgentConfig, errUnknownConfig)
}
answering, err := s.store.PhoneNumbers.AnsweredBy(ctx, customerID, request.Id)
if err != nil {
return nil, err
}
if len(answering) > 0 {
return nil, configAnswersNumbers(answering)
}
// Children are named by name, so one deleted would leave its parent calling whichever
// config takes the name next.
if parent, err := s.parentOf(ctx, customerID, existing.Name, existing.ID); err != nil {
Expand All @@ -425,6 +418,9 @@ func (s *Server) deleteAgentConfig(ctx context.Context, request *deleteAgentConf
return nil, conflict(fmt.Sprintf("%q hands work to this agent: take it out of %q's agents first", parent, parent))
}
if err := s.store.AgentConfigs.Delete(ctx, customerID, request.Id); err != nil {
if answering, ok := errors.AsType[*store.ConfigAnswersNumbersError](err); ok {
return nil, configAnswersNumbers(answering.Numbers)
}
return nil, unknownOr(err, store.ErrNoAgentConfig, errUnknownConfig)
}
// A deleted config's tasks have no agent left to run on: paused, they stop failing
Expand Down Expand Up @@ -692,6 +688,10 @@ func storeFailure(err error, taken APIError) error {
if owned, ok := errors.AsType[*store.ChannelConnectionTakenError](err); ok {
return channelConnectionTaken(owned)
}
// What channelsWarnings answers, for a config saved at the same time that passed it too.
if line, ok := errors.AsType[*store.ChannelLineTakenError](err); ok {
return invalidRequest("channels." + line.Kind + ": " + line.Number + " already answers as " + line.OwnerName)
}
switch {
case errors.Is(err, store.ErrNameTaken):
return taken
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/api/phone.go
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,8 @@ func (s *Server) setPhoneNumberAgent(ctx context.Context, request *setPhoneNumbe
return nil, errNumberNotAttached
}
if err != nil {
return nil, err
// Deleted since configFor read it.
return nil, unknownOr(err, store.ErrNoAgentConfig, errUnknownConfig)
}
held.ConfigID = config.ID
return &setPhoneNumberAgentResponse{Body: phoneNumber(held)}, nil
Expand Down
126 changes: 126 additions & 0 deletions acceleration/internal/channels/record_conversation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
//go:build integration

package channels

import (
"context"
"log/slog"
"os"
"testing"

"github.com/google/uuid"
"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/llmtest"
"github.com/GetStream/Vision-Agents/acceleration/internal/llmrouter"
"github.com/GetStream/Vision-Agents/acceleration/internal/routing"
"github.com/GetStream/Vision-Agents/acceleration/internal/session"
"github.com/GetStream/Vision-Agents/acceleration/internal/store"
"github.com/GetStream/Vision-Agents/acceleration/internal/streamapp"
"github.com/GetStream/Vision-Agents/acceleration/internal/testenv"
)

// RecordConversationSuite is a person's first message on a router that lost the race to record
// its conversation: the message goes on in the conversation recorded first.
type RecordConversationSuite struct {
suite.Suite
ctx context.Context
store *store.Store
manager *session.Manager
service *Service
}

func TestRecordConversationSuite(t *testing.T) { suite.Run(t, new(RecordConversationSuite)) }

func (s *RecordConversationSuite) SetupSuite() {
dsn := os.Getenv("ROUTER_POSTGRES_DSN")
if dsn == "" {
s.T().Skip("ROUTER_POSTGRES_DSN not set")
}
s.ctx = context.Background()
db, err := store.Open(testenv.Database(dsn, "channels_record"))
s.Require().NoError(err)
s.Require().NoError(db.Migrate(s.ctx))
s.T().Cleanup(func() { s.Require().NoError(db.Close()) })
s.store = db

logger := slog.New(slog.DiscardHandler)
config := routing.ModalityConfig{
Providers: []routing.ProviderConfig{{Provider: "stub", Model: "stub-model", Languages: []string{"en"}, Realtime: true}},
Aliases: map[string]routing.Alias{
"en-low-latency": {Languages: []string{"en"}, RequireRealtime: true},
"llm-flow": {Languages: []string{"en"}, RequireRealtime: true},
},
}
reasoning := llmrouter.NewRegistry()
reasoning.Register("stub", func(routing.Spec) (llmrouter.Provider, error) { return &llmtest.Thinker{Answer: "Sure."}, nil })
reasoner, err := llmrouter.New(llmrouter.Options{Config: config, Registry: reasoning, Logger: logger})
s.Require().NoError(err)
s.T().Cleanup(reasoner.Close)
chat := chattest.NewServer(s.T())
apps := streamapp.NewClients(streamapp.NewDeployment(streamapp.DeploymentOptions{
APIKey: "deploy-key", Secret: "deploy-secret", BaseURL: chat.URL, App: 4,
}), streamapp.ClientsOptions{})
manager, err := session.NewManager(session.ManagerOptions{
LLM: reasoner, Stream: apps, Conversations: persistent.NewForChats(persistent.StreamApps(apps)), Logger: logger,
Edge: func(context.Context, session.Spec, streamapp.Bound, *slog.Logger) (agent.Edge, error) {
return nil, nil
},
})
s.Require().NoError(err)
s.T().Cleanup(func() { _ = manager.Shutdown() })
s.manager = manager
s.service = &Service{store: db, sessions: manager, logger: logger}
}

// spec is a first message's session, kept in Chat for a person writing to customerID's agent.
func spec(customerID string) session.Spec {
return session.Spec{CustomerID: customerID, Text: true, PersistConversation: true, LLMTarget: "en-low-latency",
Caller: routing.Caller{UserID: "phone:+15550100", Verified: true}}
}

func (s *RecordConversationSuite) TestAFirstMessageGoesOnInTheConversationRecordedFirst() {
customerID, configID := "record-"+uuid.NewString(), uuid.NewString()
first, err := s.manager.Create(s.ctx, spec(customerID))
s.Require().NoError(err)
kept := first.Spec().ConversationID
_, err = s.manager.Close(first.ID(), session.OwnerOf(first.Spec()))
s.Require().NoError(err)
s.Require().NoError(s.store.ContactMapEntries.Upsert(s.ctx, &store.ContactMapEntry{
CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: "+15550100", UserID: "phone:+15550100", ConversationID: kept,
}))

orphan, err := s.manager.Create(s.ctx, spec(customerID))
s.Require().NoError(err)
s.Require().NotEqual(kept, orphan.Spec().ConversationID)
identity := store.ContactMapEntry{CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: "+15550100", UserID: "phone:+15550100"}

answering, err := s.service.recordConversation(s.ctx, orphan, spec(customerID), &identity, slog.New(slog.DiscardHandler))
s.Require().NoError(err)
s.T().Cleanup(func() { _, _ = s.manager.Close(answering.ID(), session.OwnerOf(answering.Spec())) })
s.Equal(kept, answering.Spec().ConversationID, "the message goes on in the conversation recorded first")
s.Equal(kept, identity.ConversationID)
s.False(s.manager.Running(customerID, orphan.ID()), "the session the lost race opened is closed")
}

// Opening the kept conversation can fail; the message is then answered where it was opened
// rather than dropped.
func (s *RecordConversationSuite) TestAFirstMessageIsAnsweredWhereItOpenedWhenTheKeptConversationCannotOpen() {
customerID, configID := "record-"+uuid.NewString(), uuid.NewString()
s.Require().NoError(s.store.ContactMapEntries.Upsert(s.ctx, &store.ContactMapEntry{
CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: "+15550100", UserID: "phone:+15550100",
ConversationID: "agent:never-made-" + uuid.NewString(),
}))
orphan, err := s.manager.Create(s.ctx, spec(customerID))
s.Require().NoError(err)
s.T().Cleanup(func() { _, _ = s.manager.Close(orphan.ID(), session.OwnerOf(orphan.Spec())) })
identity := store.ContactMapEntry{CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: "+15550100", UserID: "phone:+15550100"}

answering, err := s.service.recordConversation(s.ctx, orphan, spec(customerID), &identity, slog.New(slog.DiscardHandler))
s.Require().NoError(err)
s.Equal(orphan.ID(), answering.ID())
s.True(s.manager.Running(customerID, orphan.ID()))
}
44 changes: 34 additions & 10 deletions acceleration/internal/channels/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,9 @@ func (s *Service) answer(account store.ChannelAccount, line Account, provider Pr
spec.Custom["channel_from"] = message.From

created, err := s.sessions.Create(ctx, spec)
if err == nil && identity.ConversationID == "" {
created, err = s.recordConversation(ctx, created, spec, &identity, logger)
}
if err != nil {
logger.Error("could not open a conversation for a channel message", "channel", account.Kind,
"agent", config.Name, "error", err)
Expand All @@ -472,16 +475,6 @@ func (s *Service) answer(account store.ChannelAccount, line Account, provider Pr
events, detach := created.Watch()
defer detach()

// The conversation a session opened is the one the next message carries on, so it is
// recorded before the turn rather than after: a turn that fails halfway still leaves the
// person's history where they can see it.
if identity.ConversationID == "" {
identity.ConversationID = created.Spec().ConversationID
if err := s.store.ContactMapEntries.Upsert(ctx, &identity); err != nil {
logger.Error("could not record a channel conversation", "agent", config.Name, "error", err)
}
}

sending := make(chan struct{})
go func() {
defer close(sending)
Expand All @@ -495,6 +488,37 @@ func (s *Service) answer(account store.ChannelAccount, line Account, provider Pr
<-sending
}

// recordConversation records the conversation a person's first message opened, and returns
// the session the message goes on in. It is recorded before the turn rather than after: a turn
// that fails halfway still leaves the person's history where they can see it.
func (s *Service) recordConversation(ctx context.Context, created *session.Session, spec session.Spec,
identity *store.ContactMapEntry, logger *slog.Logger) (*session.Session, error) {
opened := created.Spec().ConversationID
identity.ConversationID = opened
if err := s.store.ContactMapEntries.Upsert(ctx, identity); err != nil {
logger.Error("could not record a channel conversation", "agent", spec.AgentName, "error", err)
return created, nil
}
if identity.ConversationID == opened {
return created, nil
}
// Another router opened one for this person's first message at the same time and recorded
// it first: this message goes on in that one, which is what continues. The one opened here
// is left empty, and closed only once the kept one is open: if that fails, the message is
// still answered here rather than dropped.
spec.ConversationID = identity.ConversationID
kept, err := s.sessions.Create(ctx, spec)
if err != nil {
logger.Error("could not open the conversation another router recorded first, answering in this one",
"agent", spec.AgentName, "kept", spec.ConversationID, "opened", opened, "error", err)
return created, nil
}
if _, err := s.sessions.Close(created.ID(), session.OwnerOf(created.Spec())); err != nil {
logger.Debug("could not close a channel conversation", "session", created.ID(), "error", err)
}
return kept, nil
}

// identify is who the number writing belongs to, and false when nobody is to be answered.
//
// Under phone, which is the default, each number is an end user of its own: anybody who
Expand Down
6 changes: 4 additions & 2 deletions acceleration/internal/phone/apps_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -567,15 +567,17 @@ func (s *AppsSuite) TestReattachingAfterRegistrationMovesTheTrunk() {
func (s *AppsSuite) TestReattachingInAnotherAppKeepsTheNumbersAgent() {
_, err := s.service.Attach(s.ctx, Attachment{CustomerID: s.customer, E164: s.e164})
s.Require().NoError(err)
s.Require().NoError(s.store.PhoneNumbers.SetAgent(s.ctx, s.customer, s.e164, "config-1"))
config := &store.AgentConfig{CustomerID: s.customer, Name: "answering"}
s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, config))
s.Require().NoError(s.store.PhoneNumbers.SetAgent(s.ctx, s.customer, s.e164, config.ID))
s.ownApp()

_, err = s.service.Attach(s.ctx, Attachment{CustomerID: s.customer, E164: s.e164})
s.Require().NoError(err)

held := s.number()
s.Equal(int64(4242), held.StreamAppPK)
s.Equal("config-1", held.ConfigID, "moving the number to another app took its agent away")
s.Equal(config.ID, held.ConfigID, "moving the number to another app took its agent away")
}

func (s *AppsSuite) TestDetachingKeepsTheNumberOnItsTrunk() {
Expand Down
26 changes: 25 additions & 1 deletion acceleration/internal/store/agent_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,9 @@ func (r *AgentConfigs) Insert(ctx context.Context, config *AgentConfig) error {
if err := refuseSecondChannelAgent(ctx, tx, config, nil, false); err != nil {
return err
}
if err := refuseSecondLineAgent(ctx, tx, config); err != nil {
return err
}
if _, err := tx.NewInsert().Model(config).Exec(ctx); err != nil {
switch constraint(err) {
case "agent_configs_name_idx":
Expand Down Expand Up @@ -458,6 +461,9 @@ func (r *AgentConfigs) save(ctx context.Context, config *AgentConfig, read, unmo
if err := refuseSecondChannelAgent(ctx, tx, config, stored.Connectors, stored.TestCopy()); err != nil {
return err
}
if err := refuseSecondLineAgent(ctx, tx, config); err != nil {
return err
}
_, err = tx.NewUpdate().Model(config).
Column(configColumns...).
Where("ac.id = ?", config.ID).
Expand Down Expand Up @@ -500,13 +506,28 @@ func (r *AgentConfigs) Delete(ctx context.Context, customerID, id string) error

var name string
err := r.store.detachedWrite(ctx, func(ctx context.Context, tx bun.Tx) error {
return tx.NewUpdate().Model((*AgentConfig)(nil)).
err := tx.NewUpdate().Model((*AgentConfig)(nil)).
Set("deleted_at = ?", time.Now().UTC()).
Where("id = ?", id).
Where("customer_id = ?", customerID).
Where("deleted_at IS NULL").
Returning("name").
Scan(ctx, &name)
if err != nil {
return err
}
// Read under the row's lock, which a number given this config waits on (liveConfig):
// no number can be pointed at it between this read and the commit.
answering, err := answeredBy(ctx, tx, customerID, id)
Comment thread
getstream-metis[bot] marked this conversation as resolved.
Resolved
if err != nil {
return err
}
if len(answering) > 0 {
// Refused and rolled back: the cached config is still the live one.
name = ""
return &ConfigAnswersNumbersError{Numbers: answering}
}
return nil
}, func() []string {
// Named once the write answered: a commit that fails can still have landed.
if name == "" {
Expand All @@ -517,6 +538,9 @@ func (r *AgentConfigs) Delete(ctx context.Context, customerID, id string) error
if errors.Is(err, sql.ErrNoRows) {
return unknownAgentConfig(id)
}
if _, answers := errors.AsType[*ConfigAnswersNumbersError](err); answers {
return stack.Wrap(err)
}
if err != nil {
return stack.Wrap(fmt.Errorf("store: delete agent config: %w", err))
}
Expand Down
3 changes: 2 additions & 1 deletion acceleration/internal/store/agent_config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,5 +359,6 @@ func (s *StoreSuite) TestAgentConfigQueryBudgets() {
s.Equal(1, s.countRedis(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) }))
return
}
s.Equal(3, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) }), "begin, the write and commit: a write of a cached row runs detached in a transaction of its own")
s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, "acme-app", config.ID)) }),
"begin, the write, the numbers it answers and commit: a write of a cached row runs detached in a transaction of its own")
}
Loading
Loading