Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/skills/go/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ A state change that is more than a column write gets a domain verb on the same r
moves between the sets in place: add it to the new set, copy, then drop it.
- Every migration run in a transaction starts with `SET LOCAL lock_timeout = '5s';`, so one
waiting behind a long query fails instead of holding every write queued behind it
(`TestEveryTransactionalMigrationAfterTheBaselineSetsALockTimeout`).
(`TestEveryTransactionalMigrationAfterTheInitialOneSetsALockTimeout`).
- The change log (`data_changes`, `data_change_capture`, `record_data_change()`) is in both
sets, written idempotently, because a row's change is recorded in the database it is
written to. A migration that changes it goes in both sets.
Expand Down
6 changes: 2 additions & 4 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1688,10 +1688,8 @@ Writes go to this shard's database. Reads of one call, session or recording look
shard, and lists merge every shard's rows, so a session carried on in another region is
still one session. Each database runs the migration set it holds: `migrations/global` on the
global one and `migrations/shard` on each shard's, both on the one database of a single node
(`schema/global.sql` and `schema/shard.sql` list what each set leaves). A database migrated
before the sets were split kept every table; once every router runs a release with two sets,
`router schema drop-strays` drops the empty ones of the other set. A socket for a session held in
another shard is proxied to the node holding it, since that shard's relay is not this
(`schema/global.sql` and `schema/shard.sql` list what each set leaves). A socket for a session
held in another shard is proxied to the node holding it, since that shard's relay is not this
one's. Empty shard settings fall back to the global ones, which is the single-node setup.

Percentiles merged from several shards' rollups are approximate: they are weighted by request
Expand Down
3 changes: 0 additions & 3 deletions acceleration/cmd/router/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,6 @@ const usage = `usage: router [--config path] [command]
replicate copy another deployment's data here and follow its changes
stream-apps look after the Stream apps customers registered in app mode
prices read and check the price list (router prices for its commands)
schema drop-strays drop the empty tables a shard or the shared database kept of the other's set; run once every router is on a release with two migration sets
usage replay write the usage rows a log says were lost, once each (--from path)
usage reship send this shard's shipped or refused rows to the usage service again (--since, --rejected)
usage storage record the last hour of every knowledge base's size, once each (hourly, one job per turbopuffer key)
Expand Down Expand Up @@ -277,8 +276,6 @@ func dispatchCommand(command string, args []string, settings config.Config, logg
return runStreamApps(args, settings, logger)
case "prices":
return runPrices(args, settings, logger)
case "schema":
return runSchema(args, settings, os.Stdout)
case "usage":
return runUsage(args, settings, os.Stdout)
case "help", "-h", "--help":
Expand Down
35 changes: 0 additions & 35 deletions acceleration/cmd/router/schema.go

This file was deleted.

2 changes: 1 addition & 1 deletion acceleration/internal/api/channels.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (s *Server) linkChannelNumber(ctx context.Context, request *linkChannelRequ

link, err := s.channels.Link(ctx, customerID, config.ID, request.Body.UserId)
if err != nil {
return nil, invalidRequest(err.Error())
return nil, err
}
return &channelLinkResponse{Body: ChannelLink{Code: link.Code, ExpiresAt: link.ExpiresAt}}, nil
}
Expand Down
79 changes: 79 additions & 0 deletions acceleration/internal/api/channels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,56 @@ func (s *ChannelsSuite) TestACodeAlreadySpentClaimsNothingMore() {
s.ErrorIs(err, store.ErrNoContact)
}

// A code texted to another agent's line of the app is answered as a code nobody was given, so a
// guess cannot tell a live code from a dead one, and is not spent: the number still claims it on
// the line of the agent it was minted for.
func (s *ChannelsSuite) TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOnItsOwn() {
ownNumber, otherNumber := s.number(), s.number()
own, other := s.connect(ownNumber), s.connect(otherNumber)
config := s.agentOn(ownNumber, store.ChannelIdentityLink)
otherConfig := s.agentOn(otherNumber, store.ChannelIdentityLink)
owner := s.utils.uuid()
writer := s.writer()
var minted ChannelLink
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: owner}, &minted))
s.Regexp(`^[0-9]{6}$`, minted.Code)

s.Require().Equal(http.StatusAccepted, s.deliver(other, writer, "msg-"+s.utils.uuid(), "no such code"))
unknown := s.reply(writer, 1)
s.Require().Equal(http.StatusAccepted, s.deliver(other, writer, "msg-"+s.utils.uuid(), minted.Code))
s.Equal(unknown, s.reply(writer, 2))
_, err := s.store.ContactMapEntries.GetByAddress(context.Background(), s.customerID(), otherConfig.Id, "whatsapp", "+"+writer)
s.Require().ErrorIs(err, store.ErrNoContact)

s.Require().Equal(http.StatusAccepted, s.deliver(own, writer, "msg-"+s.utils.uuid(), minted.Code))
s.Equal("This number is yours now. What can I do for you?", s.reply(writer, 3))
held, err := s.store.ContactMapEntries.GetByAddress(context.Background(), s.customerID(), config.Id, "whatsapp", "+"+writer)
s.Require().NoError(err)
s.Equal(owner, held.UserID)
}

// A guess that hits another agent's live code counts as a wrong one, as any other guess does.
func (s *ChannelsSuite) TestCodesOfAnotherAgentCountAsWrongCodes() {
ownNumber, otherNumber := s.number(), s.number()
s.connect(ownNumber)
other := s.connect(otherNumber)
config := s.agentOn(ownNumber, store.ChannelIdentityLink)
s.agentOn(otherNumber, store.ChannelIdentityLink)
guesser := s.writer()
var minted ChannelLink
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &minted))
for n := range 5 {
s.Require().Equal(http.StatusAccepted, s.deliver(other, guesser, "msg-"+s.utils.uuid(), minted.Code))
s.Contains(s.reply(guesser, n+1), "code")
}

s.Require().Equal(http.StatusAccepted, s.deliver(other, guesser, "msg-"+s.utils.uuid(), "no such code"))

s.Contains(s.reply(guesser, 6), "Too many codes")
}

// A code is six digits, so a number that may text guesses without end finds one.
func (s *ChannelsSuite) TestANumberThatTextsWrongCodesCannotClaimEvenTheRightOne() {
number := s.number()
Expand Down Expand Up @@ -727,6 +777,35 @@ func (s *ChannelsSuite) TestNumbersGuessingCodesOnOneLineTogetherCannotClaimOne(
s.ErrorIs(err, store.ErrNoContact)
}

// A code the router cannot write is its own failure: the caller is told so, not what the store said.
func (s *ChannelsSuite) TestACodeThatCannotBeWrittenIsA500WithoutTheStoresWords() {
number := s.number()
s.connect(number)
config := s.agentOn(number, store.ChannelIdentityLink)

s.failQueries(`INSERT INTO "channel_links"`)
status, payload := s.serverClient.call(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()})

s.Equal(http.StatusInternalServerError, status, string(payload))
s.Contains(string(payload), "something went wrong")
s.NotContains(string(payload), "channel link")
s.NotContains(string(payload), "store:")
}

// Two people linking on one agent before either texts get two codes.
func (s *ChannelsSuite) TestTwoPeopleLinkingOnOneAgentGetTwoCodes() {
number := s.number()
s.connect(number)
config := s.agentOn(number, store.ChannelIdentityLink)
var first, second ChannelLink
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &first))
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &second))
s.NotEqual(first.Code, second.Code)
}

func (s *ChannelsSuite) TestAnAgentIdentifyingBySomebodysNumberHasNothingToLink() {
number := s.number()
s.connect(number)
Expand Down
14 changes: 2 additions & 12 deletions acceleration/internal/channels/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,18 +190,13 @@ func (s *Service) Receive(ctx context.Context, token string, header http.Header,
// Link mints a code somebody signed in may text from their phone to claim it. It is how an
// agent that keeps something personal learns which end user a number belongs to.
func (s *Service) Link(ctx context.Context, customerID, configID, userID string) (store.ChannelLink, error) {
code, err := linkCode()
if err != nil {
return store.ChannelLink{}, err
}
link := store.ChannelLink{
Code: code,
CustomerID: customerID,
ConfigID: configID,
UserID: userID,
ExpiresAt: time.Now().UTC().Add(LinkValidFor),
}
if err := s.store.ChannelLinks.Insert(ctx, &link); err != nil {
if err := s.store.ChannelLinks.Insert(ctx, &link, linkCode); err != nil {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Should fix] R1.1 No test checks that this call site draws a fresh code. A mutant that replaces linkCode with func() (string, error) { return "123456", nil } passes all of TestChannelsSuite. Every test mints at most one live code per app, so a second person who links before the first texts gets a 500, and nothing catches it. Fix: add this test to ChannelsSuite in internal/api/channels_test.go. I ran it in a scratch copy: it fails under the mutant (the second POST is not a 200) and passes on head.

// Two people linking on one agent before either texts get two codes.
func (s *ChannelsSuite) TestTwoPeopleLinkingOnOneAgentGetTwoCodes() {
	number := s.number()
	s.connect(number)
	config := s.agentOn(number, store.ChannelIdentityLink)
	var first, second ChannelLink
	s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
		LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &first))
	s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/agents/channels/links",
		LinkChannelRequest{ConfigId: config.Id, UserId: s.utils.uuid()}, &second))
	s.NotEqual(first.Code, second.Code)
}

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8657283: TestTwoPeopleLinkingOnOneAgentGetTwoCodes (ChannelsSuite). With the constant-code mutant at the Insert call it fails; it passes on head.

return store.ChannelLink{}, err
}
return link, nil
Expand Down Expand Up @@ -545,7 +540,7 @@ func (s *Service) identify(ctx context.Context, config store.AgentConfig, accoun
answering(account.CustomerID, ""))
return store.ContactMapEntry{}, false
}
link, err := s.store.ChannelLinks.Claim(ctx, account.CustomerID, strings.TrimSpace(message.Text))
link, err := s.store.ChannelLinks.Claim(ctx, account.CustomerID, config.ID, strings.TrimSpace(message.Text))
if err != nil {
if errors.Is(err, store.ErrUnknownChannelLink) {
if err := s.store.ChannelLinkFailures.Record(ctx, account.ID, message.From, window, window.Add(-LinkValidFor)); err != nil {
Expand All @@ -557,11 +552,6 @@ func (s *Service) identify(ctx context.Context, config store.AgentConfig, accoun
answering(account.CustomerID, ""))
return store.ContactMapEntry{}, false
}
if link.ConfigID != config.ID {
s.say(ctx, line, provider, message, Reply{Text: "That code is for another agent."},
answering(account.CustomerID, ""))
return store.ContactMapEntry{}, false
}
identity.UserID = link.UserID
}
if err := s.store.ContactMapEntries.Upsert(ctx, &identity); err != nil {
Expand Down
82 changes: 0 additions & 82 deletions acceleration/internal/store/call_leg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ import (
"fmt"
"sync"
"time"

"github.com/pressly/goose/v3"
"github.com/pressly/goose/v3/database"

"github.com/GetStream/Vision-Agents/acceleration/internal/pricing"
)

func (s *StoreSuite) TestOnlyTheRefusedCallersLegIsRefused() {
Expand Down Expand Up @@ -348,83 +343,6 @@ func (s *ShardedStoreSuite) TestALegAnotherShardPlacedIsChangedThere() {
s.Equal("busy", found.Outcome)
}

// mergeVersion is the shard migration that merges phone_calls into call_legs.
const mergeVersion int64 = 20270116000001

// billed is the seconds each customer's ended legs were billed, by vendor, direction and
// country.
func billed(legs []CallLeg) map[string]int64 {
totals := map[string]int64{}
for _, leg := range legs {
totals[leg.CustomerID+"/"+leg.Vendor+"/"+leg.Direction+"/"+leg.Country] += leg.Used()[pricing.CallSeconds]
}
return totals
}

func (s *StoreSuite) TestMergingPlacedCallsIntoTheirLegsBillsTheSame() {
db, err := Open(s.emptyDatabase("merge_legs"))
s.Require().NoError(err)
defer db.Close()
s.Require().NoError(db.migrate(s.ctx, db.globalDSN, globalSet))
versions, err := database.NewStore(database.DialectPostgres, shardSet.table)
s.Require().NoError(err)
provider, err := goose.NewProvider("", db.shard.DB, shardSet.files, goose.WithStore(versions))
s.Require().NoError(err)
_, err = provider.UpTo(s.ctx, mergeVersion-1)
s.Require().NoError(err)

_, err = db.shard.ExecContext(s.ctx, `
INSERT INTO call_legs (customer_id, call_type, call_id, vendor, vendor_call_id, direction, local_number, remote_number,
country, dialed_at, started_at, ended_at, end_reason) VALUES
('acme', 'default', 'answered', 'telnyx', 'v-answered', 'outbound', '+15125550100', '+15125550199', 'US',
?0, ?0::timestamptz + interval '5 seconds', ?0::timestamptz + interval '66 seconds', 'ended'),
('acme', 'default', 'arrived', 'telnyx', NULL, 'inbound', '+15125550100', '+15125550142', 'US',
?0, ?0, ?0::timestamptz + interval '90.5 seconds', 'left'),
('acme', 'default', 'unanswered', 'twilio', 'v-unanswered', 'outbound', '+15125550100', '+442071838750', 'GB',
?0, NULL, ?0::timestamptz + interval '30 seconds', 'unanswered'),
('acme', 'default', 'by-numbers', 'twilio', NULL, 'outbound', '+15125550100', '+15125550177', 'US',
?0, ?0::timestamptz + interval '1 second', ?0::timestamptz + interval '2.25 seconds', 'left');
INSERT INTO phone_calls (token, customer_id, call_type, call_id, vendor, vendor_call_id, local_number, remote_number,
reports, placed_at, answered_at, ended_at, outcome) VALUES
('t-answered', 'acme', 'default', 'answered', 'telnyx', 'v-answered', '+15125550100', '+15125550199',
true, ?0, ?0::timestamptz + interval '5 seconds', ?0::timestamptz + interval '66 seconds', 'completed'),
('t-unanswered', 'acme', 'default', 'unanswered', 'twilio', 'v-unanswered', '+15125550100', '+442071838750',
true, ?0, NULL, ?0::timestamptz + interval '30 seconds', 'no_answer'),
('t-by-numbers', 'acme', 'default', 'by-numbers', 'twilio', NULL, '+15125550100', '+15125550177',
false, ?0, NULL, NULL, NULL),
('t-refused', 'acme', 'default', 'refused', 'telnyx', 'v-refused', '+15125550100', '+15125550188',
true, ?0, NULL, ?0::timestamptz + interval '3 seconds', 'busy')`, s.base)
s.Require().NoError(err)
var legs []CallLeg
s.Require().NoError(db.shard.NewSelect().Model(&legs).
Column("customer_id", "vendor", "direction", "country", "started_at", "ended_at").
Where("started_at IS NOT NULL").Scan(s.ctx))
before := billed(legs)

s.Require().NoError(db.Migrate(s.ctx))

ended, err := db.CallLegs.SelectEnded(s.ctx, s.base.Add(-time.Hour), s.base.Add(time.Hour), 100)
s.Require().NoError(err)
s.Equal(map[string]int64{"acme/telnyx/outbound/US": 61, "acme/telnyx/inbound/US": 91, "acme/twilio/outbound/US": 2}, before)
s.Equal(before, billed(ended), "the merge bills no leg more or less")

placed, err := db.CallLegs.SelectPlaced(s.ctx, "acme", []string{"answered", "unanswered", "by-numbers", "refused", "arrived"})
s.Require().NoError(err)
outcomes := map[string]string{}
for _, leg := range placed {
outcomes[leg.CallID] = leg.TokenHash + "/" + leg.Outcome
}
s.Equal(map[string]string{"answered": callTokenHash("t-answered") + "/completed", "unanswered": callTokenHash("t-unanswered") + "/no_answer",
"by-numbers": callTokenHash("t-by-numbers") + "/", "refused": callTokenHash("t-refused") + "/busy"}, outcomes)
var count int
s.Require().NoError(db.shard.QueryRowContext(s.ctx, "SELECT count(*) FROM call_legs").Scan(&count))
s.Equal(5, count, "a placed call with a leg is that leg; only the one without becomes a leg of its own")
refused, err := db.CallLegs.GetByToken(s.ctx, "t-refused")
s.Require().NoError(err)
s.False(refused.Connected())
s.NotNil(refused.EndedAt, "a call with no leg is no leg still ringing")
}

func (s *StoreSuite) TestCallLegQueryBudgets() {
shards := len(s.store.shards())
scope := AppScope{App: 7}
Expand Down
Loading
Loading