From 834978d8f2359b7b487eb6cbb80bb97ef875d558 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 19:42:42 +0100 Subject: [PATCH 1/6] fix(store): keep a number's first conversation and a line's one agent A contact row that has a conversation keeps it, and a router that opened a second one for the same first message carries on in the kept one. A config naming a channel line another live config names is refused under a lock on the line. Deleting a config reads the numbers it answers under its row lock, which a number being given the config waits on. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/configs.go | 14 +-- acceleration/internal/api/phone.go | 3 +- acceleration/internal/channels/service.go | 32 ++++-- acceleration/internal/store/agent_config.go | 38 +++++-- acceleration/internal/store/channel_owner.go | 51 +++++++++ .../internal/store/channel_owner_test.go | 51 +++++++++ .../internal/store/config_delete_test.go | 106 ++++++++++++++++++ .../internal/store/contact_map_entry.go | 9 +- .../internal/store/contact_map_entry_test.go | 43 +++++++ acceleration/internal/store/phone_number.go | 55 +++++++-- 10 files changed, 367 insertions(+), 35 deletions(-) create mode 100644 acceleration/internal/store/config_delete_test.go diff --git a/acceleration/internal/api/configs.go b/acceleration/internal/api/configs.go index 43f9c233a8..69156b0c0c 100644 --- a/acceleration/internal/api/configs.go +++ b/acceleration/internal/api/configs.go @@ -403,13 +403,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 { @@ -418,6 +411,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 @@ -655,6 +651,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 diff --git a/acceleration/internal/api/phone.go b/acceleration/internal/api/phone.go index d981116f39..1695ac7795 100644 --- a/acceleration/internal/api/phone.go +++ b/acceleration/internal/api/phone.go @@ -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 diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index 4f274fbdaa..066868df5d 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -467,6 +467,28 @@ func (s *Service) answer(account store.ChannelAccount, line Account, provider Pr "agent", config.Name, "error", err) return } + // 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 == "" { + 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", config.Name, "error", err) + } else if identity.ConversationID != opened { + // 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. + 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) + } + spec.ConversationID = identity.ConversationID + if created, err = s.sessions.Create(ctx, spec); err != nil { + logger.Error("could not open a conversation for a channel message", "channel", account.Kind, + "agent", config.Name, "error", err) + return + } + } + } // The session ends with the message it answered, which is what saves the conversation: // the next message reopens it by its id rather than starting over. defer func() { @@ -477,16 +499,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) diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 9acdf2d490..59b19cc887 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -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": @@ -420,6 +423,9 @@ func (r *AgentConfigs) Update(ctx context.Context, config *AgentConfig) error { if err := refuseSecondChannelAgent(ctx, tx, config, stored.Connectors, stored.TestCopy()); err != nil { return err } + if err := refuseSecondLineAgent(ctx, tx, config); err != nil { + return err + } // The name the row had is read in the same statement, locked, so the one forgotten is // the one a concurrent rename did not already replace. was := tx.NewSelect().Model((*AgentConfig)(nil)).Column("name"). @@ -467,16 +473,34 @@ func (r *AgentConfigs) Delete(ctx context.Context, customerID, id string) error } var name string - err := r.store.global.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) + err := r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + 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) + if err != nil { + return err + } + if len(answering) > 0 { + return &ConfigAnswersNumbersError{Numbers: answering} + } + return nil + }) 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)) } diff --git a/acceleration/internal/store/channel_owner.go b/acceleration/internal/store/channel_owner.go index 114d110c96..c4d63f9d07 100644 --- a/acceleration/internal/store/channel_owner.go +++ b/acceleration/internal/store/channel_owner.go @@ -5,6 +5,7 @@ import ( "database/sql" "errors" "fmt" + "maps" "slices" "github.com/uptrace/bun" @@ -223,6 +224,56 @@ func (s *Store) AgentConfigsBindingConnection(ctx context.Context, customerID, c return configs, nil } +// ChannelLineTakenError is a write of a live config naming a channel line, such as an SMS +// number, another live config already names (refuseSecondLineAgent). +type ChannelLineTakenError struct { + Kind string + Number string + // OwnerID and OwnerName are the live config already on the line. + OwnerID string + OwnerName string +} + +func (e *ChannelLineTakenError) Error() string { + return fmt.Sprintf("store: the %s line %s is named by agent config %s already", e.Kind, e.Number, e.OwnerID) +} + +// channelLineLockSeed is the second argument to hashtextextended for the lock a channel line's +// agent is decided under, apart from channelOwnerLockSeed's connections. +const channelLineLockSeed = 3512 + +// refuseSecondLineAgent refuses a write of a config naming a channel line another live config +// names, matched as ConfigOnChannel matches it: two agents on one number would both answer +// every message. The API checks this before the write too, but two configs saved at once both +// pass that check, so the decision is taken again here under a transaction-scoped lock on the +// customer and line, in kind order, as refuseSecondChannelAgent takes its. +func refuseSecondLineAgent(ctx context.Context, tx bun.Tx, config *AgentConfig) error { + named := config.Channels.Lines.Lines() + for _, kind := range slices.Sorted(maps.Keys(named)) { + number := named[kind] + if err := lockUntilCommit(ctx, tx, config.CustomerID+"/"+kind+"/"+number, channelLineLockSeed); err != nil { + return fmt.Errorf("store: lock channel line: %w", err) + } + var owner AgentConfig + err := tx.NewSelect().Model(&owner).Column("id", "name"). + Where("customer_id = ?", config.CustomerID). + Where("id != ?", config.ID). + Where("channels_lines -> ? ->> 'number' = ?", kind, number). + Where("deleted_at IS NULL"). + Order("created_at", "id"). + Limit(1). + Scan(ctx) + if errors.Is(err, sql.ErrNoRows) { + continue + } + if err != nil { + return fmt.Errorf("store: channel line owner: %w", err) + } + return &ChannelLineTakenError{Kind: kind, Number: number, OwnerID: owner.ID, OwnerName: owner.Name} + } + return nil +} + // ConfigOnChannel is the agent reachable on a number, and false when none is. // // It answers both questions there are about a line: which agent a message to it is for, and diff --git a/acceleration/internal/store/channel_owner_test.go b/acceleration/internal/store/channel_owner_test.go index 035260dd1a..0ada8f318f 100644 --- a/acceleration/internal/store/channel_owner_test.go +++ b/acceleration/internal/store/channel_owner_test.go @@ -4,6 +4,7 @@ package store import ( "errors" + "sync" "time" ) @@ -215,3 +216,53 @@ func (s *StoreSuite) TestATestCopyIsNotAmongTheConfigsThatBindAConnection() { s.Require().Len(configs, 1) s.Equal(live, configs[0].ID) } + +// smsAgent is a config of customerID answering on the SMS number e164. +func smsAgent(customerID, e164 string) *AgentConfig { + return &AgentConfig{ + CustomerID: customerID, Name: "texted-" + newID(), + Channels: AgentAnswersIn{Lines: AgentChannels{SMS: &ChannelLine{Number: e164}, Identity: ChannelIdentityPhone}}, + } +} + +func (s *StoreSuite) TestASecondConfigNamingAnSMSNumberIsRefusedAndTheFirstStillSaves() { + customerID, e164 := newID(), "+1555"+newID()[:7] + first := smsAgent(customerID, e164) + s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, first)) + + err := s.store.AgentConfigs.Insert(s.ctx, smsAgent(customerID, e164)) + taken, ok := errors.AsType[*ChannelLineTakenError](err) + s.Require().True(ok, "%v", err) + s.Equal(first.ID, taken.OwnerID) + s.Equal("sms", taken.Kind) + + first.Instructions = "Answer texts." + s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, first), "the config on the line keeps it") + s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, smsAgent(newID(), e164)), "another customer's number is theirs") +} + +// Two configs saved at once each pass the API's check before the write: one of them is the +// line's agent, and the other is refused. +func (s *StoreSuite) TestTwoConfigsSavedAtOnceNamingOneSMSNumberLeaveOneOnIt() { + customerID, e164 := newID(), "+1555"+newID()[:7] + saved := make([]error, 2) + var wg sync.WaitGroup + for i := range saved { + wg.Go(func() { saved[i] = s.store.AgentConfigs.Insert(s.ctx, smsAgent(customerID, e164)) }) + } + wg.Wait() + + refused := 0 + for _, err := range saved { + if _, ok := errors.AsType[*ChannelLineTakenError](err); ok { + refused++ + } else { + s.Require().NoError(err) + } + } + s.Equal(1, refused) + on, err := s.store.GlobalDB().NewSelect().Model((*AgentConfig)(nil)). + Where("customer_id = ?", customerID).Where("deleted_at IS NULL").Count(s.ctx) + s.Require().NoError(err) + s.Equal(1, on) +} diff --git a/acceleration/internal/store/config_delete_test.go b/acceleration/internal/store/config_delete_test.go new file mode 100644 index 0000000000..e113ed5068 --- /dev/null +++ b/acceleration/internal/store/config_delete_test.go @@ -0,0 +1,106 @@ +//go:build integration + +package store + +import ( + "context" + "errors" + "fmt" + "math/rand/v2" + "time" +) + +// heldNumber is a number customerID holds, attached to a trunk, with no agent yet. +func (s *StoreSuite) heldNumber(customerID string) string { + e164 := fmt.Sprintf("+1512%07d", rand.IntN(10_000_000)) + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: e164, Vendor: "twilio", Country: "US", CustomerID: customerID, PurchasedAt: s.base, + })) + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, customerID, e164, NumberAttachment{TrunkID: "trunk-1", CallType: "default"})) + return e164 +} + +// liveAgent is a config of customerID. +func (s *StoreSuite) liveAgent(customerID string) *AgentConfig { + config := &AgentConfig{CustomerID: customerID, Name: "answering-" + newID()} + s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, config)) + return config +} + +func (s *StoreSuite) TestAConfigANumberAnswersWithIsNotDeleted() { + customerID := newID() + config := s.liveAgent(customerID) + e164 := s.heldNumber(customerID) + s.Require().NoError(s.store.PhoneNumbers.SetAgent(s.ctx, customerID, e164, config.ID)) + + err := s.store.AgentConfigs.Delete(s.ctx, customerID, config.ID) + answering, ok := errors.AsType[*ConfigAnswersNumbersError](err) + s.Require().True(ok, "%v", err) + s.Equal([]string{e164}, answering.Numbers) + _, err = s.store.AgentConfigs.Get(s.ctx, customerID, config.ID) + s.NoError(err, "the config is still there") +} + +func (s *StoreSuite) TestANumberIsNotGivenAConfigDeletedSinceItWasRead() { + customerID := newID() + config := s.liveAgent(customerID) + e164 := s.heldNumber(customerID) + s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, customerID, config.ID)) + + err := s.store.PhoneNumbers.SetAgent(s.ctx, customerID, e164, config.ID) + s.ErrorIs(err, ErrNoAgentConfig) + number, err := s.store.PhoneNumbers.GetByE164(s.ctx, customerID, e164) + s.Require().NoError(err) + s.Empty(number.ConfigID) +} + +// Attaching again keeps the agent a number had, unless its config was deleted meanwhile. +func (s *StoreSuite) TestANumberAttachedAgainDropsAnAgentDeletedMeanwhile() { + customerID := newID() + config := s.liveAgent(customerID) + e164 := s.heldNumber(customerID) + s.Require().NoError(s.store.AgentConfigs.Delete(s.ctx, customerID, config.ID)) + + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, customerID, e164, + NumberAttachment{TrunkID: "trunk-2", CallType: "default", ConfigID: config.ID})) + number, err := s.store.PhoneNumbers.GetByE164(s.ctx, customerID, e164) + s.Require().NoError(err) + s.Empty(number.ConfigID) + + kept := s.liveAgent(customerID) + s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, customerID, e164, + NumberAttachment{TrunkID: "trunk-3", CallType: "default", ConfigID: kept.ID})) + number, err = s.store.PhoneNumbers.GetByE164(s.ctx, customerID, e164) + s.Require().NoError(err) + s.Equal(kept.ID, number.ConfigID, "a live agent is kept") +} + +// A delete that starts while a number is being given the config waits for it, and then sees +// the number rather than leaving it answering with a deleted agent. +func (s *StoreSuite) TestADeleteWaitsForANumberBeingGivenTheConfig() { + customerID := newID() + config := s.liveAgent(customerID) + e164 := s.heldNumber(customerID) + + tx, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + var live []string + s.Require().NoError(liveConfig(tx, customerID, config.ID).Scan(s.ctx, &live)) + s.Require().Len(live, 1) + _, err = tx.NewUpdate().Model((*PhoneNumber)(nil)).Set("config_id = ?", config.ID). + Where("customer_id = ?", customerID).Where("e164 = ?", e164).Exec(s.ctx) + s.Require().NoError(err) + + deleted := make(chan error, 1) + go func() { deleted <- s.store.AgentConfigs.Delete(context.WithoutCancel(s.ctx), customerID, config.ID) }() + select { + case err := <-deleted: + s.Failf("the delete did not wait for the number", "it returned %v", err) + case <-time.After(300 * time.Millisecond): + } + s.Require().NoError(tx.Commit()) + + err = <-deleted + _, ok := errors.AsType[*ConfigAnswersNumbersError](err) + s.True(ok, "%v", err) +} diff --git a/acceleration/internal/store/contact_map_entry.go b/acceleration/internal/store/contact_map_entry.go index 30b76fbea3..c0e8635675 100644 --- a/acceleration/internal/store/contact_map_entry.go +++ b/acceleration/internal/store/contact_map_entry.go @@ -175,8 +175,10 @@ func (r *ContactMapEntries) GetByUser(ctx context.Context, customerID, configID, return entry, nil } -// Upsert records who a channel line's sender is, or moves their conversation on and where a -// reply reaches them. +// Upsert records who a channel line's sender is, their conversation and where a reply reaches +// them, and reads the row back into entry. A row that has a conversation keeps it: two first +// messages from one number on two routers each open one, and the second is handed the first +// to carry on in. func (r *ContactMapEntries) Upsert(ctx context.Context, entry *ContactMapEntry) error { if err := entry.Validate(); err != nil { return stack.Wrap(err) @@ -190,9 +192,10 @@ func (r *ContactMapEntries) Upsert(ctx context.Context, entry *ContactMapEntry) _, err := r.store.global.NewInsert().Model(entry). On("CONFLICT (customer_id, config_id, kind, address) DO UPDATE"). Set("user_id = EXCLUDED.user_id"). - Set("conversation_id = EXCLUDED.conversation_id"). + Set("conversation_id = COALESCE(NULLIF(?TableAlias.conversation_id, ''), EXCLUDED.conversation_id)"). Set("thread = EXCLUDED.thread"). Set("updated_at = EXCLUDED.updated_at"). + Returning("*"). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: save contact: %w", err)) diff --git a/acceleration/internal/store/contact_map_entry_test.go b/acceleration/internal/store/contact_map_entry_test.go index 2a688c027b..c48c9e7d80 100644 --- a/acceleration/internal/store/contact_map_entry_test.go +++ b/acceleration/internal/store/contact_map_entry_test.go @@ -186,6 +186,49 @@ func (s *StoreSuite) TestWhoANumberIsCanBeRecordedAndItsConversationMovedOn() { s.Equal("phone:"+address, held.UserID) } +// Two routers answering a number's first messages at once each open a conversation: the one +// recorded first is kept, and each is handed it. +func (s *StoreSuite) TestTwoConcurrentFirstMessagesFromOneNumberEndInOneConversation() { + customerID, configID := newID(), newID() + address := "+1347" + newID()[:7] + kept := make([]string, 2) + var wg sync.WaitGroup + for i := range kept { + wg.Go(func() { + identity := ContactMapEntry{CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: address, UserID: "phone:" + address} + s.NoError(s.store.ContactMapEntries.Upsert(s.ctx, &identity)) + identity.ConversationID = "agent:omni-" + newID() + s.NoError(s.store.ContactMapEntries.Upsert(s.ctx, &identity)) + kept[i] = identity.ConversationID + }) + } + wg.Wait() + + held, err := s.store.ContactMapEntries.GetByAddress(s.ctx, customerID, configID, "sms", address) + s.Require().NoError(err) + s.Equal(held.ConversationID, kept[0]) + s.Equal(held.ConversationID, kept[1]) +} + +// A router that saw no row for a number writes one with no conversation: one another router +// recorded meanwhile is not wiped, and is handed back. +func (s *StoreSuite) TestAFirstSightingOfANumberKeepsTheConversationRecordedMeanwhile() { + customerID, configID := newID(), newID() + address := "+1347" + newID()[:7] + recorded := ContactMapEntry{CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: address, + UserID: "phone:" + address, ConversationID: "agent:omni-first"} + s.Require().NoError(s.store.ContactMapEntries.Upsert(s.ctx, &recorded)) + + late := ContactMapEntry{CustomerID: customerID, ConfigID: configID, Kind: "sms", Address: address, UserID: "phone:" + address} + s.Require().NoError(s.store.ContactMapEntries.Upsert(s.ctx, &late)) + s.Equal("agent:omni-first", late.ConversationID) + s.Equal(recorded.ID, late.ID) + + held, err := s.store.ContactMapEntries.GetByAddress(s.ctx, customerID, configID, "sms", address) + s.Require().NoError(err) + s.Equal("agent:omni-first", held.ConversationID) +} + // The same person writing to two agents is two conversations. func (s *StoreSuite) TestANumberIsIdentifiedPerAgent() { customerID, address := newID(), "+1347"+newID()[:7] diff --git a/acceleration/internal/store/phone_number.go b/acceleration/internal/store/phone_number.go index 5897f7230a..09051788ff 100644 --- a/acceleration/internal/store/phone_number.go +++ b/acceleration/internal/store/phone_number.go @@ -226,7 +226,8 @@ func attachNumber(ctx context.Context, db bun.IDB, customerID, e164 string, atta } update := db.NewUpdate().Model((*PhoneNumber)(nil)) if attached.ConfigID != "" { - update.Set("config_id = ?", attached.ConfigID) + // The agent the number had, unless its config was deleted since it was read. + update.Set("config_id = (?)", liveConfig(db, customerID, attached.ConfigID)) } result, err := update. Set("stream_trunk_id = ?", attached.TrunkID). @@ -326,14 +327,15 @@ func (r *PhoneNumbers) SetAgent(ctx context.Context, customerID, e164, configID if customerID == "" || e164 == "" || configID == "" { return stack.Wrap(errors.New("store: a customer, a number and a config are required")) } - // Only an attached number has an agent, and a detach can land between the caller's - // read and this write. + // Only an attached number has an agent, and only a live config is one, and a detach or + // the config's delete can land between the caller's read and this write. result, err := r.store.global.NewUpdate().Model((*PhoneNumber)(nil)). Set("config_id = ?", configID). Where("customer_id = ?", customerID). Where("e164 = ?", e164). Where("released_at IS NULL"). Where("attached_at IS NOT NULL"). + Where("EXISTS (?)", liveConfig(r.store.global, customerID, configID)). Exec(ctx) if err != nil { return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) @@ -342,10 +344,34 @@ func (r *PhoneNumbers) SetAgent(ctx context.Context, customerID, e164, configID if err != nil { return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) } - if affected == 0 { - return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds attached", e164, customerID)}) + if affected > 0 { + return nil } - return nil + // The number or the config is not there: the caller is told which. + live, err := r.store.global.NewSelect().Model((*AgentConfig)(nil)). + Where("id = ?", configID). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + Exists(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) + } + if !live { + return unknownAgentConfig(configID) + } + return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds attached", e164, customerID)}) +} + +// liveConfig selects the id of a customer's config while it is live, share-locking its row +// until the transaction ends. AgentConfigs.Delete holds that row while it reads the numbers the +// config answers, so a number is pointed at a config either before that read sees it, or after +// the delete, when the config is no longer there to point at. +func liveConfig(db bun.IDB, customerID, configID string) *bun.SelectQuery { + return db.NewSelect().Model((*AgentConfig)(nil)).Column("id"). + Where("id = ?", configID). + Where("customer_id = ?", customerID). + Where("deleted_at IS NULL"). + For("SHARE") } // ClearAgent sends a number's calls back to dispatch. A number with no agent is left as it @@ -378,8 +404,23 @@ func (r *PhoneNumbers) AnsweredBy(ctx context.Context, customerID, configID stri if customerID == "" || configID == "" { return nil, stack.Wrap(errors.New("store: a customer and a config are required")) } + return answeredBy(ctx, r.store.global, customerID, configID) +} + +// ConfigAnswersNumbersError is a config that cannot be deleted while numbers answer with it. +type ConfigAnswersNumbersError struct { + // Numbers are the numbers it answers, sorted. + Numbers []string +} + +func (e *ConfigAnswersNumbersError) Error() string { + return fmt.Sprintf("store: the agent config answers %d numbers", len(e.Numbers)) +} + +// answeredBy is AnsweredBy read in db. +func answeredBy(ctx context.Context, db bun.IDB, customerID, configID string) ([]string, error) { var numbers []string - err := r.store.global.NewSelect().Model((*PhoneNumber)(nil)). + err := db.NewSelect().Model((*PhoneNumber)(nil)). Column("e164"). Where("customer_id = ?", customerID). Where("config_id = ?", configID). From 12c222151d80b234a89f28562d3ff4f675434067 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:02:15 +0100 Subject: [PATCH 2/6] fix(channels): one log line for a channel session that could not open The reopen of the kept conversation moves into recordConversation, so a failed open on either attempt is logged where it always was. Two test fixtures that set up a number answering with a deleted or missing config now build that state directly. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/callhooks_test.go | 6 ++- acceleration/internal/channels/service.go | 48 ++++++++++--------- .../internal/phone/apps_integration_test.go | 6 ++- 3 files changed, 35 insertions(+), 25 deletions(-) diff --git a/acceleration/internal/api/callhooks_test.go b/acceleration/internal/api/callhooks_test.go index bf14fbef3f..c816792d5e 100644 --- a/acceleration/internal/api/callhooks_test.go +++ b/acceleration/internal/api/callhooks_test.go @@ -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() diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index 066868df5d..d78b39e764 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -462,33 +462,14 @@ 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) return } - // 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 == "" { - 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", config.Name, "error", err) - } else if identity.ConversationID != opened { - // 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. - 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) - } - spec.ConversationID = identity.ConversationID - if created, err = s.sessions.Create(ctx, spec); err != nil { - logger.Error("could not open a conversation for a channel message", "channel", account.Kind, - "agent", config.Name, "error", err) - return - } - } - } // The session ends with the message it answered, which is what saves the conversation: // the next message reopens it by its id rather than starting over. defer func() { @@ -512,6 +493,29 @@ 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. + 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) + } + spec.ConversationID = identity.ConversationID + return s.sessions.Create(ctx, spec) +} + // 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 diff --git a/acceleration/internal/phone/apps_integration_test.go b/acceleration/internal/phone/apps_integration_test.go index 94753b63c6..2c9b867f8c 100644 --- a/acceleration/internal/phone/apps_integration_test.go +++ b/acceleration/internal/phone/apps_integration_test.go @@ -547,7 +547,9 @@ 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}) @@ -555,7 +557,7 @@ func (s *AppsSuite) TestReattachingInAnotherAppKeepsTheNumbersAgent() { 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() { From e62d86d504c51dec96f109dbe91e05810eb3cca2 Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 20:20:44 +0100 Subject: [PATCH 3/6] ci: run the checks again Co-Authored-By: Claude Opus 5.5 From ef1b852da0a9edca3fffc5a1849cced82f675c6e Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 21:10:51 +0100 Subject: [PATCH 4/6] fix(store): a config keeps an SMS line it named before the line rule Also counts the delete's numbers read in the query budget. Co-Authored-By: Claude Opus 5.5 --- .../internal/store/agent_config_test.go | 3 ++- acceleration/internal/store/channel_owner.go | 16 +++++++++++++++- .../internal/store/channel_owner_test.go | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/store/agent_config_test.go b/acceleration/internal/store/agent_config_test.go index dc15b89a10..d8c6416d03 100644 --- a/acceleration/internal/store/agent_config_test.go +++ b/acceleration/internal/store/agent_config_test.go @@ -300,5 +300,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") } diff --git a/acceleration/internal/store/channel_owner.go b/acceleration/internal/store/channel_owner.go index c4d63f9d07..700eac7529 100644 --- a/acceleration/internal/store/channel_owner.go +++ b/acceleration/internal/store/channel_owner.go @@ -254,8 +254,22 @@ func refuseSecondLineAgent(ctx context.Context, tx bun.Tx, config *AgentConfig) if err := lockUntilCommit(ctx, tx, config.CustomerID+"/"+kind+"/"+number, channelLineLockSeed); err != nil { return fmt.Errorf("store: lock channel line: %w", err) } + // A line the stored config named already is not a new claim, so a config that shared a + // line before this rule can still be saved, as refuseSecondChannelAgent keeps a binding. + kept, err := tx.NewSelect().Model((*AgentConfig)(nil)). + Where("id = ?", config.ID). + Where("customer_id = ?", config.CustomerID). + Where("deleted_at IS NULL"). + Where("channels_lines -> ? ->> 'number' = ?", kind, number). + Exists(ctx) + if err != nil { + return fmt.Errorf("store: channel line owner: %w", err) + } + if kept { + continue + } var owner AgentConfig - err := tx.NewSelect().Model(&owner).Column("id", "name"). + err = tx.NewSelect().Model(&owner).Column("id", "name"). Where("customer_id = ?", config.CustomerID). Where("id != ?", config.ID). Where("channels_lines -> ? ->> 'number' = ?", kind, number). diff --git a/acceleration/internal/store/channel_owner_test.go b/acceleration/internal/store/channel_owner_test.go index 0ada8f318f..966d06c307 100644 --- a/acceleration/internal/store/channel_owner_test.go +++ b/acceleration/internal/store/channel_owner_test.go @@ -241,6 +241,24 @@ func (s *StoreSuite) TestASecondConfigNamingAnSMSNumberIsRefusedAndTheFirstStill s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, smsAgent(newID(), e164)), "another customer's number is theirs") } +// Two configs that shared a line before the rule can each still be saved while they keep it. +func (s *StoreSuite) TestAConfigThatSharedAnSMSNumberBeforeTheRuleStillSaves() { + customerID, e164 := newID(), "+1555"+newID()[:7] + first := smsAgent(customerID, e164) + s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, first)) + second := smsAgent(customerID, "+1555"+newID()[:7]) + s.Require().NoError(s.store.AgentConfigs.Insert(s.ctx, second)) + // Put on the first's number as a router from before the rule could. + _, err := s.store.GlobalDB().NewUpdate().Table("agent_configs"). + Set("channels_lines = jsonb_build_object('sms', jsonb_build_object('number', ?::text))", e164). + Where("id = ?", second.ID).Exec(s.ctx) + s.Require().NoError(err) + second.Channels.Lines.SMS.Number = e164 + + second.Instructions = "Answer texts." + s.Require().NoError(s.store.AgentConfigs.Update(s.ctx, second)) +} + // Two configs saved at once each pass the API's check before the write: one of them is the // line's agent, and the other is refused. func (s *StoreSuite) TestTwoConfigsSavedAtOnceNamingOneSMSNumberLeaveOneOnIt() { From f171e3036a5885aadc93d8c14bd6fd7ddf2090df Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Mon, 23 Nov 2026 21:47:58 +0100 Subject: [PATCH 5/6] fix(channels): open the kept conversation before closing the one a lost race opened If the kept conversation cannot open, the message is answered in the one already open rather than dropped. Adds a test that a save waits on the line's lock, and leaves the cache alone when a delete is refused. Co-Authored-By: Claude Opus 5.5 --- .../channels/record_conversation_test.go | 126 ++++++++++++++++++ acceleration/internal/channels/service.go | 14 +- acceleration/internal/store/agent_config.go | 2 + .../internal/store/channel_owner_test.go | 28 ++++ .../internal/store/config_delete_test.go | 3 +- 5 files changed, 169 insertions(+), 4 deletions(-) create mode 100644 acceleration/internal/channels/record_conversation_test.go diff --git a/acceleration/internal/channels/record_conversation_test.go b/acceleration/internal/channels/record_conversation_test.go new file mode 100644 index 0000000000..0224020f67 --- /dev/null +++ b/acceleration/internal/channels/record_conversation_test.go @@ -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(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(orphan.ID())) +} diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index d78b39e764..31b90c0b5e 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -508,12 +508,20 @@ func (s *Service) recordConversation(ctx context.Context, created *session.Sessi 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. + // 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, "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) } - spec.ConversationID = identity.ConversationID - return s.sessions.Create(ctx, spec) + return kept, nil } // identify is who the number writing belongs to, and false when nobody is to be answered. diff --git a/acceleration/internal/store/agent_config.go b/acceleration/internal/store/agent_config.go index 1311250eb8..06c3616557 100644 --- a/acceleration/internal/store/agent_config.go +++ b/acceleration/internal/store/agent_config.go @@ -498,6 +498,8 @@ func (r *AgentConfigs) Delete(ctx context.Context, customerID, id string) error 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 diff --git a/acceleration/internal/store/channel_owner_test.go b/acceleration/internal/store/channel_owner_test.go index 966d06c307..81c6245682 100644 --- a/acceleration/internal/store/channel_owner_test.go +++ b/acceleration/internal/store/channel_owner_test.go @@ -284,3 +284,31 @@ func (s *StoreSuite) TestTwoConfigsSavedAtOnceNamingOneSMSNumberLeaveOneOnIt() { s.Require().NoError(err) s.Equal(1, on) } + +// A config naming a line waits for another save of the line to finish, and then sees it, +// rather than both reading the line as free. +func (s *StoreSuite) TestASaveNamingAnSMSNumberWaitsForAnotherSaveOfIt() { + customerID, e164 := newID(), "+1555"+newID()[:7] + tx, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + _, err = tx.ExecContext(s.ctx, "SELECT pg_advisory_xact_lock(hashtextextended(?, ?))", customerID+"/sms/"+e164, channelLineLockSeed) + s.Require().NoError(err) + holder := smsAgent(customerID, e164) + holder.ID, holder.CreatedAt, holder.UpdatedAt = newID(), time.Now().UTC(), time.Now().UTC() + normalizeConfig(holder) + _, err = tx.NewInsert().Model(holder).Exec(s.ctx) + s.Require().NoError(err) + + saved := make(chan error, 1) + go func() { saved <- s.store.AgentConfigs.Insert(s.ctx, smsAgent(customerID, e164)) }() + select { + case err := <-saved: + s.Require().NoError(tx.Rollback()) + s.FailNowf("the save did not wait for the line", "it returned %v", err) + case <-time.After(300 * time.Millisecond): + } + s.Require().NoError(tx.Commit()) + + _, taken := errors.AsType[*ChannelLineTakenError](<-saved) + s.True(taken, "the save that waited sees the config that held the line") +} diff --git a/acceleration/internal/store/config_delete_test.go b/acceleration/internal/store/config_delete_test.go index e113ed5068..d18b941e9d 100644 --- a/acceleration/internal/store/config_delete_test.go +++ b/acceleration/internal/store/config_delete_test.go @@ -95,7 +95,8 @@ func (s *StoreSuite) TestADeleteWaitsForANumberBeingGivenTheConfig() { go func() { deleted <- s.store.AgentConfigs.Delete(context.WithoutCancel(s.ctx), customerID, config.ID) }() select { case err := <-deleted: - s.Failf("the delete did not wait for the number", "it returned %v", err) + s.Require().NoError(tx.Rollback()) + s.FailNowf("the delete did not wait for the number", "it returned %v", err) case <-time.After(300 * time.Millisecond): } s.Require().NoError(tx.Commit()) From 0cb28ee75d08c0f8baeecc593f4517c50f6de0ef Mon Sep 17 00:00:00 2001 From: Laurent Schaffner Date: Tue, 24 Nov 2026 01:19:10 +0100 Subject: [PATCH 6/6] fix(channels): name both conversations when a message stays in the one it opened Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/channels/service.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index 31b90c0b5e..2dcd3bbfac 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -515,7 +515,7 @@ func (s *Service) recordConversation(ctx context.Context, created *session.Sessi 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, "error", err) + "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 {