From 625812ac907a90f9a3afafec4bb521b7e7cd25dd Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:00:08 +0100 Subject: [PATCH 1/8] fix(channels): link codes are per app and deleted once claimed channel_links is keyed on (customer_id, code), so one app holding a code no longer fails another app's link. Claim deletes the code, and only for the agent it was minted for: a code texted to another agent's line of the app is answered as such and stays to claim. Insert draws again when the app already holds the code, and deletes every app's codes past their time in the same statement. Co-Authored-By: Claude Opus 5.5 --- acceleration/internal/api/channels_test.go | 26 ++ acceleration/internal/channels/service.go | 19 +- acceleration/internal/store/channel_link.go | 110 +++++--- .../internal/store/channel_link_test.go | 236 ++++++++++++++++-- ...70128000000_channel_links_per_customer.sql | 20 ++ acceleration/schema/global.sql | 2 +- 6 files changed, 343 insertions(+), 70 deletions(-) create mode 100644 acceleration/migrations/global/20270128000000_channel_links_per_customer.sql diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index af1960b070..48dd65811a 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -428,6 +428,32 @@ func (s *ChannelsSuite) TestACodeAlreadySpentClaimsNothingMore() { s.ErrorIs(err, store.ErrNoContact) } +// A code texted to another agent's line of the app is answered as such and 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(), minted.Code)) + s.Equal("That code is for another agent.", s.reply(writer, 1)) + _, 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, 2)) + held, err := s.store.ContactMapEntries.GetByAddress(context.Background(), s.customerID(), config.Id, "whatsapp", "+"+writer) + s.Require().NoError(err) + s.Equal(owner, held.UserID) +} + // A code is six digits, so a number that may text guesses without end finds one. func (s *ChannelsSuite) TestANumberThatTextsWrongCodesCannotClaimEvenTheRightOne() { number := s.number() diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index d9fa877a48..f0a53d2122 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -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 { return store.ChannelLink{}, err } return link, nil @@ -522,7 +517,12 @@ 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 errors.Is(err, store.ErrChannelLinkElsewhere) { + s.say(ctx, line, provider, message, Reply{Text: "That code is for another agent."}, + answering(account.CustomerID, "")) + return store.ContactMapEntry{}, false + } 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 { @@ -534,11 +534,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 { diff --git a/acceleration/internal/store/channel_link.go b/acceleration/internal/store/channel_link.go index b6326f6777..8f16ba838d 100644 --- a/acceleration/internal/store/channel_link.go +++ b/acceleration/internal/store/channel_link.go @@ -11,17 +11,19 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/stack" ) -// ChannelLink is a code that ties the number texting it to an end user. +// ChannelLink is a code that ties the number texting it to an end user. A code is unique within +// its app, which is where it is claimed. type ChannelLink struct { bun.BaseModel `bun:"table:channel_links,alias:cl"` - Code string `bun:"code,pk"` - CustomerID string `bun:"customer_id,notnull"` - ConfigID string `bun:"config_id,notnull"` - UserID string `bun:"user_id,notnull"` - CreatedAt time.Time `bun:"created_at,notnull"` - ExpiresAt time.Time `bun:"expires_at,notnull"` - UsedAt *time.Time `bun:"used_at"` + CustomerID string `bun:"customer_id,pk"` + Code string `bun:"code,pk"` + ConfigID string `bun:"config_id,notnull"` + UserID string `bun:"user_id,notnull"` + CreatedAt time.Time `bun:"created_at,notnull"` + ExpiresAt time.Time `bun:"expires_at,notnull"` + // UsedAt is set only by a release older than the one that deletes a code it claims. + UsedAt *time.Time `bun:"used_at"` } // Validate refuses a code that ties a number to no one. @@ -38,51 +40,95 @@ func (l *ChannelLink) Validate() error { // ErrUnknownChannelLink is a code nobody was given, one already spent, or one past its time. var ErrUnknownChannelLink = errors.New("store: there is no such code") +// ErrChannelLinkElsewhere is a code of the app that was given for another of its agents. It +// is not spent, so it still claims the number on that agent's line. +var ErrChannelLinkElsewhere = errors.New("store: the code is for another agent") + +// channelLinkDraws is how many codes Insert draws before it gives up. A draw is taken only when +// the app already holds the code drawn, which for six digits and ten thousand codes held at +// once is one draw in a hundred: four in a row taken means the draw is broken, and looping on +// it would never end. +const channelLinkDraws = 4 + // ChannelLinks are the codes somebody may text to claim their number, in the shared database. type ChannelLinks struct { store *Store } -// Insert stores a code somebody may text to claim their number. -func (r *ChannelLinks) Insert(ctx context.Context, link *ChannelLink) error { - if err := link.Validate(); err != nil { - return stack.Wrap(err) - } - link.CreatedAt = time.Now().UTC() - if _, err := r.store.global.NewInsert().Model(link).Exec(ctx); err != nil { - return stack.Wrap(fmt.Errorf("store: save channel link: %w", err)) +// Insert stores a code somebody may text to claim their number, drawn by draw: a code the app +// already holds is drawn again, so two people linking at once never get one code. Codes past +// their time, of any app, are deleted in the same statement, so the table holds only the codes +// that may still be claimed. +func (r *ChannelLinks) Insert(ctx context.Context, link *ChannelLink, draw func() (string, error)) error { + for range channelLinkDraws { + code, err := draw() + if err != nil { + return err + } + link.Code = code + if err := link.Validate(); err != nil { + return stack.Wrap(err) + } + link.CreatedAt = time.Now().UTC() + expired := r.store.global.NewDelete().Model((*ChannelLink)(nil)). + Where("expires_at <= ?", link.CreatedAt) + result, err := r.store.global.NewInsert().With("expired", expired).Model(link). + On("CONFLICT DO NOTHING"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: save channel link: %w", err)) + } + // A conflict is no error to the driver: no row written is what says the code is taken. + written, err := result.RowsAffected() + if err != nil { + return stack.Wrap(fmt.Errorf("store: save channel link: %w", err)) + } + if written == 1 { + return nil + } } - return nil + return stack.Wrap(fmt.Errorf("store: save channel link: %d codes drawn were all taken", channelLinkDraws)) } -// Claim spends a code. A code already spent or past its time is no code at all, so a number -// cannot be claimed twice over by somebody who saw the message go by. -func (r *ChannelLinks) Claim(ctx context.Context, customerID, code string) (ChannelLink, error) { - if customerID == "" || code == "" { +// Claim spends a code by deleting it. A code already spent or past its time is no code at all, +// so a number cannot be claimed twice over by somebody who saw the message go by. A code of +// another of the app's agents is ErrChannelLinkElsewhere and stays, so texting it to the wrong +// line does not spend it. +func (r *ChannelLinks) Claim(ctx context.Context, customerID, configID, code string) (ChannelLink, error) { + if customerID == "" || configID == "" || code == "" { return ChannelLink{}, stack.Wrap(ErrUnknownChannelLink) } now := time.Now().UTC() - var link ChannelLink - result, err := r.store.global.NewUpdate().Model(&link). - Set("used_at = ?", now). - Where("code = ?", code). + var claimed []ChannelLink + // A code an older release marked used is spent already, so it is not claimed again. + err := r.store.global.NewDelete().Model(&claimed). Where("customer_id = ?", customerID). + Where("code = ?", code). + Where("config_id = ?", configID). Where("used_at IS NULL"). Where("expires_at > ?", now). Returning("*"). - Exec(ctx) + Scan(ctx) if err != nil { return ChannelLink{}, stack.Wrap(fmt.Errorf("store: claim channel link: %w", err)) } - // An update that matched nothing is not an error to the driver, so the count is what - // says the code was already spent, has run out, or was never anybody's. - affected, err := result.RowsAffected() + if len(claimed) == 1 { + return claimed[0], nil + } + + // The delete takes a code of this agent, so a code of the app still to claim is another agent's. + elsewhere, err := r.store.global.NewSelect().Model((*ChannelLink)(nil)). + Where("customer_id = ?", customerID). + Where("code = ?", code). + Where("used_at IS NULL"). + Where("expires_at > ?", now). + Exists(ctx) if err != nil { return ChannelLink{}, stack.Wrap(fmt.Errorf("store: claim channel link: %w", err)) } - if affected == 0 { - return ChannelLink{}, stack.Wrap(ErrUnknownChannelLink) + if elsewhere { + return ChannelLink{}, stack.Wrap(ErrChannelLinkElsewhere) } - return link, nil + return ChannelLink{}, stack.Wrap(ErrUnknownChannelLink) } diff --git a/acceleration/internal/store/channel_link_test.go b/acceleration/internal/store/channel_link_test.go index 8c3b360aea..bbaa76dc24 100644 --- a/acceleration/internal/store/channel_link_test.go +++ b/acceleration/internal/store/channel_link_test.go @@ -2,56 +2,242 @@ package store -import "time" +import ( + "errors" + "time" +) -// A code somebody saw go by must not claim a second number. -func (s *StoreSuite) TestACodeIsSpentOnce() { - customerID := newID() - link := ChannelLink{ - Code: newID()[:6], CustomerID: customerID, ConfigID: newID(), - UserID: "on-call-engineer", ExpiresAt: time.Now().UTC().Add(time.Minute), +// minted is a code of one app, for one of its agents, that may still be claimed. +func minted(customerID, configID, userID string) ChannelLink { + return ChannelLink{ + Code: newID()[:8], CustomerID: customerID, ConfigID: configID, + UserID: userID, ExpiresAt: time.Now().UTC().Add(time.Minute), } - s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link)) +} + +// draws hands out codes in turn, the last one again once they run out, and counts the draws. +func draws(codes ...string) (func() (string, error), *int) { + drawn := 0 + return func() (string, error) { + code := codes[min(drawn, len(codes)-1)] + drawn++ + return code, nil + }, &drawn +} - claimed, err := s.store.ChannelLinks.Claim(s.ctx, customerID, link.Code) +// insertCode stores the link under the code it already has. +func (s *StoreSuite) insertCode(link *ChannelLink) { + draw, _ := draws(link.Code) + s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, link, draw)) +} + +// lapseCode writes a code past its time as it was before a later write deleted it. +func (s *StoreSuite) lapseCode(link *ChannelLink) { + link.CreatedAt = time.Now().UTC().Add(-time.Hour) + link.ExpiresAt = time.Now().UTC().Add(-time.Minute) + _, err := s.store.global.NewInsert().Model(link).Exec(s.ctx) + s.Require().NoError(err) +} + +// codesHeld is how many rows the app holds under the code. +func (s *StoreSuite) codesHeld(customerID, code string) int { + count, err := s.store.global.NewSelect().Model((*ChannelLink)(nil)). + Where("customer_id = ? AND code = ?", customerID, code).Count(s.ctx) + s.Require().NoError(err) + return count +} + +// A code somebody saw go by must not claim a second number, and the row it was is gone. +func (s *StoreSuite) TestACodeIsSpentOnce() { + link := minted(newID(), newID(), "on-call-engineer") + s.insertCode(&link) + + claimed, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) s.Require().NoError(err) s.Equal("on-call-engineer", claimed.UserID) + s.Equal(link.ConfigID, claimed.ConfigID) + s.Zero(s.codesHeld(link.CustomerID, link.Code), "a claimed code is deleted, not kept as used") - _, err = s.store.ChannelLinks.Claim(s.ctx, customerID, link.Code) + _, err = s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) s.ErrorIs(err, ErrUnknownChannelLink) } func (s *StoreSuite) TestACodePastItsTimeIsNoCodeAtAll() { - customerID := newID() - link := ChannelLink{ - Code: newID()[:6], CustomerID: customerID, ConfigID: newID(), - UserID: "on-call-engineer", ExpiresAt: time.Now().UTC().Add(-time.Minute), - } - s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link)) + link := minted(newID(), newID(), "on-call-engineer") + s.lapseCode(&link) - _, err := s.store.ChannelLinks.Claim(s.ctx, customerID, link.Code) + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) s.ErrorIs(err, ErrUnknownChannelLink) } func (s *StoreSuite) TestAnotherAppsCodeCannotBeSpentHere() { - link := ChannelLink{ - Code: newID()[:6], CustomerID: newID(), ConfigID: newID(), - UserID: "on-call-engineer", ExpiresAt: time.Now().UTC().Add(time.Minute), + link := minted(newID(), newID(), "on-call-engineer") + s.insertCode(&link) + + _, err := s.store.ChannelLinks.Claim(s.ctx, newID(), link.ConfigID, link.Code) + + s.ErrorIs(err, ErrUnknownChannelLink) + s.Equal(1, s.codesHeld(link.CustomerID, link.Code), "the code is still its own app's") +} + +// Codes are drawn per app, so one app holding a code does not keep another from holding it. +func (s *StoreSuite) TestTwoAppsHoldOneCodeAtOnce() { + first := minted(newID(), newID(), "first-app-user") + second := minted(newID(), newID(), "second-app-user") + second.Code = first.Code + s.insertCode(&first) + s.insertCode(&second) + + claimed, err := s.store.ChannelLinks.Claim(s.ctx, second.CustomerID, second.ConfigID, second.Code) + s.Require().NoError(err) + s.Equal("second-app-user", claimed.UserID) + claimed, err = s.store.ChannelLinks.Claim(s.ctx, first.CustomerID, first.ConfigID, first.Code) + s.Require().NoError(err) + s.Equal("first-app-user", claimed.UserID) +} + +// Texting a code to another agent's line of the app says so and leaves the code to claim. +func (s *StoreSuite) TestACodeForAnotherAgentIsNotSpent() { + link := minted(newID(), newID(), "on-call-engineer") + s.insertCode(&link) + + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, newID(), link.Code) + s.ErrorIs(err, ErrChannelLinkElsewhere) + + claimed, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) + s.Require().NoError(err) + s.Equal("on-call-engineer", claimed.UserID) +} + +// Another agent's code that could not be claimed there either is no code at all, not one to +// send to the other line. +func (s *StoreSuite) TestAnotherAgentsSpentOrLapsedCodeIsNoCode() { + used := minted(newID(), newID(), "on-call-engineer") + at := time.Now().UTC() + used.UsedAt = &at + s.insertCode(&used) + lapsed := minted(newID(), newID(), "on-call-engineer") + s.lapseCode(&lapsed) + + for name, link := range map[string]ChannelLink{"past its time": lapsed, "marked used by an older release": used} { + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, newID(), link.Code) + s.ErrorIs(err, ErrUnknownChannelLink, name) + _, err = s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) + s.ErrorIs(err, ErrUnknownChannelLink, name) } - s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link)) +} - _, err := s.store.ChannelLinks.Claim(s.ctx, newID(), link.Code) +func (s *StoreSuite) TestAClaimNamingNoAgentClaimsNothing() { + link := minted(newID(), newID(), "on-call-engineer") + s.insertCode(&link) + + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, "", link.Code) s.ErrorIs(err, ErrUnknownChannelLink) + s.Equal(1, s.codesHeld(link.CustomerID, link.Code)) +} + +// A code the app holds is drawn again, so two people linking never get one code. +func (s *StoreSuite) TestACodeTheAppHoldsIsDrawnAgain() { + held := minted(newID(), newID(), "first-user") + s.insertCode(&held) + link := minted(held.CustomerID, held.ConfigID, "second-user") + fresh := link.Code + draw, drawn := draws(held.Code, fresh) + + s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link, draw)) + + s.Equal(fresh, link.Code) + s.Equal(2, *drawn) + claimed, err := s.store.ChannelLinks.Claim(s.ctx, held.CustomerID, held.ConfigID, held.Code) + s.Require().NoError(err) + s.Equal("first-user", claimed.UserID, "the code held is not overwritten") + claimed, err = s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, fresh) + s.Require().NoError(err) + s.Equal("second-user", claimed.UserID) +} + +// A draw that only ever gives a taken code ends, so linking fails rather than hangs. +func (s *StoreSuite) TestADrawThatIsAlwaysTakenGivesUp() { + held := minted(newID(), newID(), "first-user") + s.insertCode(&held) + link := minted(held.CustomerID, held.ConfigID, "second-user") + draw, drawn := draws(held.Code) + + err := s.store.ChannelLinks.Insert(s.ctx, &link, draw) + + s.Error(err) + s.Equal(channelLinkDraws, *drawn) + s.Equal(4, channelLinkDraws) + s.Equal(1, s.codesHeld(held.CustomerID, held.Code)) +} + +// A code that cannot be drawn, or a link that ties a number to no one, writes nothing. +func (s *StoreSuite) TestALinkThatCannotBeWrittenWritesNothing() { + broken := errors.New("no randomness") + link := minted(newID(), newID(), "on-call-engineer") + err := s.store.ChannelLinks.Insert(s.ctx, &link, func() (string, error) { return "", broken }) + s.ErrorIs(err, broken) + + nobody := minted(newID(), newID(), "") + draw, _ := draws(nobody.Code) + var invalid *ValidationError + s.ErrorAs(s.store.ChannelLinks.Insert(s.ctx, &nobody, draw), &invalid) + s.Equal("user_id", invalid.Field) + s.Zero(s.codesHeld(nobody.CustomerID, nobody.Code)) +} + +// A code claimed or past its time is free to be drawn again. +func (s *StoreSuite) TestACodeIsIssuedAgainAfterItWasClaimedOrLapsed() { + claimed := minted(newID(), newID(), "first-user") + s.insertCode(&claimed) + _, err := s.store.ChannelLinks.Claim(s.ctx, claimed.CustomerID, claimed.ConfigID, claimed.Code) + s.Require().NoError(err) + lapsed := minted(newID(), newID(), "first-user") + + for name, old := range map[string]ChannelLink{"claimed": claimed, "past its time": lapsed} { + if name == "past its time" { + s.lapseCode(&lapsed) + old = lapsed + } + again := minted(old.CustomerID, old.ConfigID, "second-user") + again.Code = old.Code + s.insertCode(&again) + + link, err := s.store.ChannelLinks.Claim(s.ctx, old.CustomerID, old.ConfigID, old.Code) + s.Require().NoError(err, name) + s.Equal("second-user", link.UserID, name) + } +} + +// Writing a code deletes every app's codes past their time, so the table keeps no more than +// the codes that may still be claimed. +func (s *StoreSuite) TestWritingACodeDeletesTheCodesPastTheirTime() { + live := minted(newID(), newID(), "first-user") + s.insertCode(&live) + lapsed := minted(newID(), newID(), "first-user") + s.lapseCode(&lapsed) + s.Require().Equal(1, s.codesHeld(lapsed.CustomerID, lapsed.Code)) + + other := minted(newID(), newID(), "second-user") + s.insertCode(&other) + + s.Zero(s.codesHeld(lapsed.CustomerID, lapsed.Code), "another app's code past its time") + s.Equal(1, s.codesHeld(live.CustomerID, live.Code), "a code still to claim stays") } func (s *StoreSuite) TestChannelLinkQueryBudgets() { - link := ChannelLink{Code: newID()[:6], CustomerID: newID(), ConfigID: newID(), UserID: "user-one", ExpiresAt: time.Now().Add(time.Minute)} + link := minted(newID(), newID(), "user-one") + draw, _ := draws(link.Code) - s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link)) }), "Insert") + s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link, draw)) }), "Insert") + s.Equal(2, s.countQueries(func() { + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, newID(), link.Code) + s.Require().ErrorIs(err, ErrChannelLinkElsewhere) + }), "Claim of another agent's code") s.Equal(1, s.countQueries(func() { - _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.Code) + _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) s.Require().NoError(err) }), "Claim") } diff --git a/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql new file mode 100644 index 0000000000..fdb858b8b4 --- /dev/null +++ b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql @@ -0,0 +1,20 @@ +-- +goose Up + +-- A link code is claimed on the app's own lines, so it needs to be unique only within the app: +-- keyed on the code alone, every app drew from one space of codes, and a code one app held +-- failed another app's link. The new key refuses nothing the old one let through, so an older +-- release still running writes and claims as before. A code is minted for one person linking one +-- phone, so the table is small and the key is rebuilt under the table's lock, as +-- 20270124000000_hash_call_tokens rebuilt call_bridges'. +ALTER TABLE channel_links + DROP CONSTRAINT channel_links_pkey, + ADD CONSTRAINT channel_links_pkey PRIMARY KEY (customer_id, code); + +-- +goose Down + +-- Two apps may hold one code now: all but one app's are dropped, and those links fail. +DELETE FROM channel_links held USING channel_links kept + WHERE held.code = kept.code AND held.customer_id > kept.customer_id; +ALTER TABLE channel_links + DROP CONSTRAINT channel_links_pkey, + ADD CONSTRAINT channel_links_pkey PRIMARY KEY (code); diff --git a/acceleration/schema/global.sql b/acceleration/schema/global.sql index 98f731af05..69bf163a58 100644 --- a/acceleration/schema/global.sql +++ b/acceleration/schema/global.sql @@ -288,7 +288,7 @@ TABLE channel_links expires_at timestamp with time zone NOT NULL used_at timestamp with time zone user_id text NOT NULL - CONSTRAINT channel_links_pkey PRIMARY KEY (code) + CONSTRAINT channel_links_pkey PRIMARY KEY (customer_id, code) TABLE channel_thread_inbound attempts integer NOT NULL DEFAULT 0 From 98d66fb90eb2ad4cb89669ad778e736b1211d13d Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:10:03 +0100 Subject: [PATCH 2/8] AI-3479: answer another agent's code as an unknown one, and count it A different reply told a guesser the code was live. Claim now treats it as no code, so identify records the failure and gives the unknown-code reply. Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/channels_test.go | 32 ++++++++++++++++--- acceleration/internal/channels/service.go | 5 --- acceleration/internal/store/channel_link.go | 21 ++---------- .../internal/store/channel_link_test.go | 11 +++---- 4 files changed, 35 insertions(+), 34 deletions(-) diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index 48dd65811a..8374f5fdd9 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -428,8 +428,9 @@ func (s *ChannelsSuite) TestACodeAlreadySpentClaimsNothingMore() { s.ErrorIs(err, store.ErrNoContact) } -// A code texted to another agent's line of the app is answered as such and not spent: the -// number still claims it on the line of the agent it was minted for. +// 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) @@ -442,18 +443,41 @@ func (s *ChannelsSuite) TestACodeTextedToAnotherAgentsLineStillClaimsTheNumberOn 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("That code is for another agent.", s.reply(writer, 1)) + 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, 2)) + 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() diff --git a/acceleration/internal/channels/service.go b/acceleration/internal/channels/service.go index f0a53d2122..0adba9ae85 100644 --- a/acceleration/internal/channels/service.go +++ b/acceleration/internal/channels/service.go @@ -518,11 +518,6 @@ func (s *Service) identify(ctx context.Context, config store.AgentConfig, accoun return store.ContactMapEntry{}, false } link, err := s.store.ChannelLinks.Claim(ctx, account.CustomerID, config.ID, strings.TrimSpace(message.Text)) - if errors.Is(err, store.ErrChannelLinkElsewhere) { - s.say(ctx, line, provider, message, Reply{Text: "That code is for another agent."}, - answering(account.CustomerID, "")) - return store.ContactMapEntry{}, false - } 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 { diff --git a/acceleration/internal/store/channel_link.go b/acceleration/internal/store/channel_link.go index 8f16ba838d..ea50f11791 100644 --- a/acceleration/internal/store/channel_link.go +++ b/acceleration/internal/store/channel_link.go @@ -40,10 +40,6 @@ func (l *ChannelLink) Validate() error { // ErrUnknownChannelLink is a code nobody was given, one already spent, or one past its time. var ErrUnknownChannelLink = errors.New("store: there is no such code") -// ErrChannelLinkElsewhere is a code of the app that was given for another of its agents. It -// is not spent, so it still claims the number on that agent's line. -var ErrChannelLinkElsewhere = errors.New("store: the code is for another agent") - // channelLinkDraws is how many codes Insert draws before it gives up. A draw is taken only when // the app already holds the code drawn, which for six digits and ten thousand codes held at // once is one draw in a hundred: four in a row taken means the draw is broken, and looping on @@ -92,8 +88,8 @@ func (r *ChannelLinks) Insert(ctx context.Context, link *ChannelLink, draw func( // Claim spends a code by deleting it. A code already spent or past its time is no code at all, // so a number cannot be claimed twice over by somebody who saw the message go by. A code of -// another of the app's agents is ErrChannelLinkElsewhere and stays, so texting it to the wrong -// line does not spend it. +// another of the app's agents is no code here either, and stays, so texting it to the wrong +// line does not spend it and does not tell the sender it is a live one. func (r *ChannelLinks) Claim(ctx context.Context, customerID, configID, code string) (ChannelLink, error) { if customerID == "" || configID == "" || code == "" { return ChannelLink{}, stack.Wrap(ErrUnknownChannelLink) @@ -117,18 +113,5 @@ func (r *ChannelLinks) Claim(ctx context.Context, customerID, configID, code str return claimed[0], nil } - // The delete takes a code of this agent, so a code of the app still to claim is another agent's. - elsewhere, err := r.store.global.NewSelect().Model((*ChannelLink)(nil)). - Where("customer_id = ?", customerID). - Where("code = ?", code). - Where("used_at IS NULL"). - Where("expires_at > ?", now). - Exists(ctx) - if err != nil { - return ChannelLink{}, stack.Wrap(fmt.Errorf("store: claim channel link: %w", err)) - } - if elsewhere { - return ChannelLink{}, stack.Wrap(ErrChannelLinkElsewhere) - } return ChannelLink{}, stack.Wrap(ErrUnknownChannelLink) } diff --git a/acceleration/internal/store/channel_link_test.go b/acceleration/internal/store/channel_link_test.go index bbaa76dc24..07b2979160 100644 --- a/acceleration/internal/store/channel_link_test.go +++ b/acceleration/internal/store/channel_link_test.go @@ -97,21 +97,20 @@ func (s *StoreSuite) TestTwoAppsHoldOneCodeAtOnce() { s.Equal("first-app-user", claimed.UserID) } -// Texting a code to another agent's line of the app says so and leaves the code to claim. +// Texting a code to another agent's line of the app is texting no code, and leaves the code to claim. func (s *StoreSuite) TestACodeForAnotherAgentIsNotSpent() { link := minted(newID(), newID(), "on-call-engineer") s.insertCode(&link) _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, newID(), link.Code) - s.ErrorIs(err, ErrChannelLinkElsewhere) + s.ErrorIs(err, ErrUnknownChannelLink) claimed, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) s.Require().NoError(err) s.Equal("on-call-engineer", claimed.UserID) } -// Another agent's code that could not be claimed there either is no code at all, not one to -// send to the other line. +// Another agent's code that could not be claimed there either is no code at all. func (s *StoreSuite) TestAnotherAgentsSpentOrLapsedCodeIsNoCode() { used := minted(newID(), newID(), "on-call-engineer") at := time.Now().UTC() @@ -232,9 +231,9 @@ func (s *StoreSuite) TestChannelLinkQueryBudgets() { draw, _ := draws(link.Code) s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.ChannelLinks.Insert(s.ctx, &link, draw)) }), "Insert") - s.Equal(2, s.countQueries(func() { + s.Equal(1, s.countQueries(func() { _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, newID(), link.Code) - s.Require().ErrorIs(err, ErrChannelLinkElsewhere) + s.Require().ErrorIs(err, ErrUnknownChannelLink) }), "Claim of another agent's code") s.Equal(1, s.countQueries(func() { _, err := s.store.ChannelLinks.Claim(s.ctx, link.CustomerID, link.ConfigID, link.Code) From 9731111190dfe275eb1c24e5c6654cabd67a241a Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 18:13:37 +0100 Subject: [PATCH 3/8] AI-3479: answer a code the router cannot write as a 500 Every Link error was a 400 carrying the store's text. Nothing the caller sent can fail it: the body is validated before. Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/channels.go | 2 +- acceleration/internal/api/channels_test.go | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/acceleration/internal/api/channels.go b/acceleration/internal/api/channels.go index b22b8fef1b..92c0aeef08 100644 --- a/acceleration/internal/api/channels.go +++ b/acceleration/internal/api/channels.go @@ -172,7 +172,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 } diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index 8374f5fdd9..d990d83bea 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -525,6 +525,22 @@ 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:") +} + func (s *ChannelsSuite) TestAnAgentIdentifyingBySomebodysNumberHasNothingToLink() { number := s.number() s.connect(number) From b8ad6b085787c151f70100525834282407cca8cd Mon Sep 17 00:00:00 2001 From: Tommaso Barbugli Date: Mon, 23 Nov 2026 18:37:27 +0100 Subject: [PATCH 4/8] chore(store): squash the migration history into one initial migration per set Each set's history up to its last migration (global 20270124093000, shard 20270126000000) becomes 20270110000000_initial.sql, keeping the version of the baseline every deployed database recorded, so none runs it. The router refuses a database that ran part of the squashed history or the single history from before the split, instead of claiming migrations it never ran. router schema drop-strays goes: it read the history for the tables to drop. migrations/squash/cleanup.sql rewrites a deployed database's tracking to the initial migration alone, after checking its schema against a fingerprint of a new one, and drops the empty stray tables of the other set. --- acceleration/README.md | 6 +- acceleration/cmd/router/main.go | 3 - acceleration/cmd/router/schema.go | 35 -- acceleration/internal/store/call_leg_test.go | 82 --- .../internal/store/delivery_seen_test.go | 27 - acceleration/internal/store/migrate.go | 150 ++--- acceleration/internal/store/migrate_test.go | 163 +----- .../internal/store/migrate_unit_test.go | 40 +- acceleration/internal/store/notice_test.go | 59 -- .../internal/store/stream_trunk_test.go | 72 --- ...aseline.sql => 20270110000000_initial.sql} | 545 +++++++----------- .../global/20270111000000_notices.sql | 93 --- .../20270112000000_knowledge_urls_due_idx.sql | 6 - .../20270112000100_drop_plugin_tables.sql | 18 - .../20270112000200_simulation_run_lease.sql | 17 - .../20270112000300_agent_config_groups.sql | 34 -- ...113000000_connector_side_tables_folded.sql | 121 ---- .../global/20270113000001_deliveries_seen.sql | 51 -- ...connection_event_subscription_attempts.sql | 12 - ...5000100_contact_map_channel_identities.sql | 45 -- ...0115000200_channel_threads_fold_people.sql | 33 -- .../20270115000300_episodes_fold_activity.sql | 31 - .../global/20270115000400_stream_app_pk.sql | 11 - .../global/20270115000500_channel_turns.sql | 31 - ...16000000_campaign_contacts_lease_until.sql | 6 - .../20270116000002_stream_trunk_bridges.sql | 46 -- ...20270116000003_use_case_campaign_index.sql | 6 - ...270117000300_scheduled_tasks_leased_by.sql | 8 - ...70117000400_record_data_change_secrets.sql | 186 ------ .../20270119000000_image_jobs_queued_idx.sql | 20 - .../20270122000000_channel_link_failures.sql | 15 - ...0122000100_voice_bindings_external_idx.sql | 8 - .../20270123021810_voice_data_not_moved.sql | 10 - .../20270124093000_activity_digests.sql | 15 - acceleration/migrations/migrations.go | 2 + ...aseline.sql => 20270110000000_initial.sql} | 212 ++++--- ...0270114000000_calls_belong_to_sessions.sql | 95 --- .../20270116000001_merge_phone_calls.sql | 92 --- ...116000004_call_resources_created_index.sql | 6 - .../20270117000100_drop_agent_request_log.sql | 28 - ...70117000400_record_data_change_secrets.sql | 190 ------ ...0270118000000_call_legs_unanswered_idx.sql | 11 - ...270118000100_calls_session_started_idx.sql | 15 - .../shard/20270124000000_hash_call_tokens.sql | 47 -- ...0270124000100_call_legs_token_hash_idx.sql | 13 - ...0270126000000_requests_source_usage_id.sql | 8 - acceleration/migrations/squash/cleanup.sql | 309 ++++++++++ acceleration/migrations/squash/run.sh | 80 +++ 48 files changed, 792 insertions(+), 2321 deletions(-) delete mode 100644 acceleration/cmd/router/schema.go rename acceleration/migrations/global/{20270110000000_baseline.sql => 20270110000000_initial.sql} (85%) delete mode 100644 acceleration/migrations/global/20270111000000_notices.sql delete mode 100644 acceleration/migrations/global/20270112000000_knowledge_urls_due_idx.sql delete mode 100644 acceleration/migrations/global/20270112000100_drop_plugin_tables.sql delete mode 100644 acceleration/migrations/global/20270112000200_simulation_run_lease.sql delete mode 100644 acceleration/migrations/global/20270112000300_agent_config_groups.sql delete mode 100644 acceleration/migrations/global/20270113000000_connector_side_tables_folded.sql delete mode 100644 acceleration/migrations/global/20270113000001_deliveries_seen.sql delete mode 100644 acceleration/migrations/global/20270113000002_connection_event_subscription_attempts.sql delete mode 100644 acceleration/migrations/global/20270115000100_contact_map_channel_identities.sql delete mode 100644 acceleration/migrations/global/20270115000200_channel_threads_fold_people.sql delete mode 100644 acceleration/migrations/global/20270115000300_episodes_fold_activity.sql delete mode 100644 acceleration/migrations/global/20270115000400_stream_app_pk.sql delete mode 100644 acceleration/migrations/global/20270115000500_channel_turns.sql delete mode 100644 acceleration/migrations/global/20270116000000_campaign_contacts_lease_until.sql delete mode 100644 acceleration/migrations/global/20270116000002_stream_trunk_bridges.sql delete mode 100644 acceleration/migrations/global/20270116000003_use_case_campaign_index.sql delete mode 100644 acceleration/migrations/global/20270117000300_scheduled_tasks_leased_by.sql delete mode 100644 acceleration/migrations/global/20270117000400_record_data_change_secrets.sql delete mode 100644 acceleration/migrations/global/20270119000000_image_jobs_queued_idx.sql delete mode 100644 acceleration/migrations/global/20270122000000_channel_link_failures.sql delete mode 100644 acceleration/migrations/global/20270122000100_voice_bindings_external_idx.sql delete mode 100644 acceleration/migrations/global/20270123021810_voice_data_not_moved.sql delete mode 100644 acceleration/migrations/global/20270124093000_activity_digests.sql rename acceleration/migrations/shard/{20270110000000_baseline.sql => 20270110000000_initial.sql} (86%) delete mode 100644 acceleration/migrations/shard/20270114000000_calls_belong_to_sessions.sql delete mode 100644 acceleration/migrations/shard/20270116000001_merge_phone_calls.sql delete mode 100644 acceleration/migrations/shard/20270116000004_call_resources_created_index.sql delete mode 100644 acceleration/migrations/shard/20270117000100_drop_agent_request_log.sql delete mode 100644 acceleration/migrations/shard/20270117000400_record_data_change_secrets.sql delete mode 100644 acceleration/migrations/shard/20270118000000_call_legs_unanswered_idx.sql delete mode 100644 acceleration/migrations/shard/20270118000100_calls_session_started_idx.sql delete mode 100644 acceleration/migrations/shard/20270124000000_hash_call_tokens.sql delete mode 100644 acceleration/migrations/shard/20270124000100_call_legs_token_hash_idx.sql delete mode 100644 acceleration/migrations/shard/20270126000000_requests_source_usage_id.sql create mode 100644 acceleration/migrations/squash/cleanup.sql create mode 100755 acceleration/migrations/squash/run.sh diff --git a/acceleration/README.md b/acceleration/README.md index eaa4c628c1..0010e3c937 100644 --- a/acceleration/README.md +++ b/acceleration/README.md @@ -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 diff --git a/acceleration/cmd/router/main.go b/acceleration/cmd/router/main.go index 299bb7c335..6a5ac25aa1 100644 --- a/acceleration/cmd/router/main.go +++ b/acceleration/cmd/router/main.go @@ -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) @@ -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": diff --git a/acceleration/cmd/router/schema.go b/acceleration/cmd/router/schema.go deleted file mode 100644 index b19c57de3d..0000000000 --- a/acceleration/cmd/router/schema.go +++ /dev/null @@ -1,35 +0,0 @@ -package main - -import ( - "context" - "errors" - "fmt" - "io" - "strings" - - "github.com/GetStream/Vision-Agents/acceleration/internal/config" -) - -const schemaUsage = `usage: router schema drop-strays - - drop-strays drop the empty tables each database kept of the other migration set from - before the split, and list the ones holding rows, which it leaves` - -func runSchema(args []string, settings config.Config, out io.Writer) error { - if len(args) == 0 || args[0] != "drop-strays" { - return errors.New(schemaUsage) - } - ctx := context.Background() - pgStore, err := openStore(ctx, settings) - if err != nil { - return err - } - defer pgStore.Close() - dropped, left, err := pgStore.DropStrays(ctx) - if err != nil { - return err - } - _, err = fmt.Fprintf(out, "dropped %d tables: %s\nleft %d holding rows: %s\n", - len(dropped), strings.Join(dropped, ", "), len(left), strings.Join(left, ", ")) - return err -} diff --git a/acceleration/internal/store/call_leg_test.go b/acceleration/internal/store/call_leg_test.go index 4bcc1a60e1..a33e350c9b 100644 --- a/acceleration/internal/store/call_leg_test.go +++ b/acceleration/internal/store/call_leg_test.go @@ -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() { @@ -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.global, 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} diff --git a/acceleration/internal/store/delivery_seen_test.go b/acceleration/internal/store/delivery_seen_test.go index 66097adc05..884861094f 100644 --- a/acceleration/internal/store/delivery_seen_test.go +++ b/acceleration/internal/store/delivery_seen_test.go @@ -56,33 +56,6 @@ func (s *StoreSuite) TestADeliveryOfADayAgoIsForgottenAndFirstAgain() { s.False(recent) } -func (s *StoreSuite) TestMergingTheDeliveryTablesKeepsWhatWasSeen() { - merged := s.migratedTo("seen", 20270113000001-1) - defer merged.Close() - seen := time.Now().UTC() - _, err := merged.global.ExecContext(s.ctx, ` -INSERT INTO hook_deliveries (key, seen_at) VALUES ('hook-key', ?); -INSERT INTO connection_event_subscriptions (id, customer_id, connection_id, config_id, binding, event, key, token, secret_sealed, kek_version, status, created_at, updated_at) -VALUES ('sub', 'app', 'conn', 'config', 'acme', 'issue', 'k', 'token', '\x00', 1, 'active', ?, ?); -INSERT INTO connection_event_deliveries (subscription_id, event_id, received_at) VALUES ('sub', 'evt', ?); -`, seen, seen, seen, seen) - s.Require().NoError(err) - - s.Require().NoError(merged.Migrate(s.ctx)) - - for _, delivery := range []struct{ scope, key string }{ - {DeliveryScopeHook, "hook-key"}, - {DeliveryScopeConnectionEvent, ConnectionEventKey("sub", "evt")}, - } { - first, err := merged.DeliveriesSeen.First(s.ctx, delivery.scope, delivery.key) - s.Require().NoError(err) - s.False(first, delivery.key) - } - fresh, err := merged.DeliveriesSeen.First(s.ctx, DeliveryScopeConnectionEvent, ConnectionEventKey("sub", "other")) - s.Require().NoError(err) - s.True(fresh) -} - func (s *StoreSuite) TestDeliverySeenQueryBudgets() { s.store.DeliveriesSeen.pruned.Store(0) s.Equal(2, s.countQueries(func() { diff --git a/acceleration/internal/store/migrate.go b/acceleration/internal/store/migrate.go index 6b888daafe..fa305c6dc5 100644 --- a/acceleration/internal/store/migrate.go +++ b/acceleration/internal/store/migrate.go @@ -6,7 +6,6 @@ import ( "database/sql/driver" "fmt" "io/fs" - "log/slog" "regexp" "slices" "strings" @@ -29,20 +28,14 @@ type migrationSet struct { // marker is a table of this set that every database which ran the single history before // the split holds, so such a database is told from a new one. marker string + // squashed is the last version of the history squashed into the set's initial migration, + // whose schema is the one that history left. + squashed int64 } var ( - globalSet = migrationSet{name: "global", files: migrations.Global, table: "goose_global_version", marker: "agent_configs"} - shardSet = migrationSet{name: "shard", files: migrations.Shard, table: "goose_shard_version", marker: "requests"} -) - -const ( - // legacyHead is the last version of the single history every database ran before the - // split. A database that applied it is marked as having applied the baseline of each set - // rather than running it. - legacyHead int64 = 20270103090000 - // baseline is the version of each set's first migration, the schema at legacyHead. - baseline int64 = 20270110000000 + globalSet = migrationSet{name: "global", files: migrations.Global, table: "goose_global_version", marker: "agent_configs", squashed: 20270124093000} + shardSet = migrationSet{name: "shard", files: migrations.Shard, table: "goose_shard_version", marker: "requests", squashed: 20270126000000} ) // Migrate applies every pending migration: the shared set to the shared database and the @@ -94,117 +87,65 @@ func (s *Store) migrate(ctx context.Context, db *bun.DB, set migrationSet) error if err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } - if err := adoptLegacy(ctx, conn, versions, set); err != nil { - return err - } // A provider of its own rather than goose's globals: the two sets record their versions // in tables of their own, and the ledger migrates in the same process. provider, err := goose.NewProvider("", db.DB, set.files, goose.WithStore(versions)) if err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } + if err := checkHistory(ctx, conn, provider, set); err != nil { + return err + } if _, err := provider.Up(ctx); err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } return ensureUsageIndexes(ctx, conn, set) } -// adoptLegacy marks a database that ran the single history before the split as having -// applied the set's baseline, which is the schema that history left. One that stopped short -// of its last version cannot be adopted: the baseline would claim migrations it never ran. -func adoptLegacy(ctx context.Context, conn *sql.Conn, versions database.Store, set migrationSet) error { +// checkHistory refuses a database whose history the set's migrations no longer hold, which +// the initial migration would otherwise be wrong about: one that ran the single history from +// before the split, on which it would fail to create tables already there, and one that ran +// part of the history squashed into it, whose missing migrations it would claim as applied. +// One that ran the whole history holds the initial migration's schema and starts as it is. +func checkHistory(ctx context.Context, conn *sql.Conn, provider *goose.Provider, set migrationSet) error { var recorded, legacy bool err := conn.QueryRowContext(ctx, "SELECT to_regclass($1) IS NOT NULL, to_regclass($2) IS NOT NULL", set.table, set.marker).Scan(&recorded, &legacy) if err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } - if recorded || !legacy { + if !recorded { + if legacy { + return fmt.Errorf("store: migrate %s: the database ran the migrations from before they were split; recreate it, or start a release from before the history was squashed first", set.name) + } return nil } - var head bool - err = conn.QueryRowContext(ctx, `SELECT to_regclass('goose_db_version') IS NOT NULL AND EXISTS ( - SELECT 1 FROM goose_db_version WHERE version_id = $1 AND is_applied)`, legacyHead).Scan(&head) + known := map[int64]bool{0: true} + for _, source := range provider.ListSources() { + known[source.Version] = true + } + rows, err := conn.QueryContext(ctx, "SELECT version_id FROM "+set.table+" WHERE is_applied") if err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } - if !head { - return fmt.Errorf("store: migrate %s: the database has not applied migration %d; start a release from before the migrations were split first", set.name, legacyHead) - } - if err := versions.CreateVersionTable(ctx, conn); err != nil { - return fmt.Errorf("store: migrate %s: %w", set.name, err) + defer rows.Close() + var unknown, squashed bool + for rows.Next() { + var version int64 + if err := rows.Scan(&version); err != nil { + return fmt.Errorf("store: migrate %s: %w", set.name, err) + } + unknown = unknown || !known[version] + squashed = squashed || version == set.squashed } - if err := versions.Insert(ctx, conn, database.InsertRequest{Version: 0}); err != nil { + if err := rows.Err(); err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } - if err := versions.Insert(ctx, conn, database.InsertRequest{Version: baseline}); err != nil { - return fmt.Errorf("store: migrate %s: %w", set.name, err) + if unknown && !squashed { + return fmt.Errorf("store: migrate %s: the database has not applied migration %d, the last of the history squashed into the initial one; recreate it, or start a release from before the history was squashed first", set.name, set.squashed) } - slog.Default().Info("adopted a database that ran the single migration history", "set", set.name) return nil } -// DropStrays drops the tables of the other set that each database kept from before the split, -// when every database carried every table: the shared set's on this shard, and the shard -// set's on the shared database unless it is some shard's own too. It returns the tables it -// dropped and those it left. A deployment of one database has none. -// -// It is not part of Migrate: a router of the release before the split, still serving during a -// rollout, reads those tables. Run it once every router is on a release with two sets. -func (s *Store) DropStrays(ctx context.Context) (dropped, left []string, err error) { - if !s.Sharded() { - return nil, nil, nil - } - if dropped, left, err = dropStrays(ctx, s.shard, globalSet); err != nil || s.globalIsShard { - return dropped, left, err - } - more, kept, err := dropStrays(ctx, s.global, shardSet) - return append(dropped, more...), append(left, kept...), err -} - -// dropStrays drops the empty tables of the other set that db holds. Only an empty one is -// dropped: rows in one are a state nobody should lose to a command, so it is left for a -// person. A stray another stray points at is dropped on a later pass, once the one pointing -// is gone. -func dropStrays(ctx context.Context, db *bun.DB, other migrationSet) (dropped, left []string, err error) { - tables, err := createdTables(other) - if err != nil { - return nil, nil, err - } - var strays []string - for _, table := range tables { - var present, empty bool - if err := db.QueryRowContext(ctx, "SELECT to_regclass(?) IS NOT NULL", table).Scan(&present); err != nil { - return nil, nil, fmt.Errorf("store: strays: %w", err) - } - if !present { - continue - } - if err := db.NewRaw("SELECT NOT EXISTS (SELECT 1 FROM ?)", bun.Ident(table)).Scan(ctx, &empty); err != nil { - return nil, nil, fmt.Errorf("store: strays: %w", err) - } - if !empty { - left = append(left, table) - continue - } - strays = append(strays, table) - } - for len(strays) > 0 { - var kept []string - for _, table := range strays { - if _, err := db.ExecContext(ctx, "DROP TABLE ?", bun.Ident(table)); err != nil { - kept = append(kept, table) - continue - } - dropped = append(dropped, table) - } - if len(kept) == len(strays) { - return dropped, append(left, kept...), nil - } - strays = kept - } - return dropped, left, nil -} - // migrateLockFirst and migrateLockMost are the pause between two tries at the migrate lock: // the first, doubled after each miss up to the most, which bounds how long a router idles // after the one migrating is done. @@ -343,19 +284,6 @@ var tableChange = regexp.MustCompile(`(?i)(CREATE TABLE (?:IF NOT EXISTS )?|DROP // setTables are the tables the set's migrations leave, read from their Up SQL in order. A // table is created by one set alone, except the change log both keep. func setTables(set migrationSet) ([]string, error) { - return migratedTables(set, false) -} - -// createdTables are the tables the set's migrations ever create, a later one dropping or -// renaming them included, which a database of the other set may still hold from before the -// split. -func createdTables(set migrationSet) ([]string, error) { - return migratedTables(set, true) -} - -// migratedTables reads the set's tables from its migrations' Up SQL in order. ever keeps the -// tables a later migration drops, and the old name of one it renames. -func migratedTables(set migrationSet, ever bool) ([]string, error) { files, err := fs.Glob(set.files, "*.sql") if err != nil { return nil, err @@ -377,14 +305,10 @@ func migratedTables(set migrationSet, ever bool) ([]string, error) { tables = append(tables, table) } case strings.HasPrefix(verb, "DROP"): - if !ever { - tables = slices.DeleteFunc(tables, func(held string) bool { return held == table }) - } + tables = slices.DeleteFunc(tables, func(held string) bool { return held == table }) case renamed != "": - if i := slices.Index(tables, table); i >= 0 && !ever { + if i := slices.Index(tables, table); i >= 0 { tables[i] = renamed - } else if i >= 0 && !slices.Contains(tables, renamed) { - tables = append(tables, renamed) } } } diff --git a/acceleration/internal/store/migrate_test.go b/acceleration/internal/store/migrate_test.go index 5f4aa6c836..76abea89ce 100644 --- a/acceleration/internal/store/migrate_test.go +++ b/acceleration/internal/store/migrate_test.go @@ -7,13 +7,8 @@ import ( "database/sql" "os" "path/filepath" - "time" - "github.com/pressly/goose/v3" - "github.com/pressly/goose/v3/database" "github.com/uptrace/bun" - - "github.com/GetStream/Vision-Agents/acceleration/internal/connectors/core" ) func (s *ShardedStoreSuite) TestTheSchemaFilesAreCurrent() { @@ -35,39 +30,6 @@ func (s *ShardedStoreSuite) TestEachDatabaseHoldsOnlyItsOwnSet() { s.False(requests, "the shared database keeps no requests") } -// A shard that ran the single history kept every table. The empty ones of the shared set are -// dropped; one holding rows is left for a person. -func (s *ShardedStoreSuite) TestAShardDropsTheEmptyTablesOfTheSharedSet() { - global, shard := s.emptyDatabase("strays_global"), s.emptyDatabase("strays_shard") - everything, err := Open(shard) - s.Require().NoError(err) - s.Require().NoError(everything.Migrate(s.ctx)) - _, err = everything.global.ExecContext(s.ctx, "INSERT INTO skills (id, customer_id, name, description, instructions) VALUES ('kept', 'app', 'kept', '', '')") - s.Require().NoError(err) - s.Require().NoError(everything.Close()) - - split, err := OpenShards(Options{DSN: global, ShardDSN: shard}) - s.Require().NoError(err) - defer split.Close() - s.Require().NoError(split.Migrate(s.ctx)) - var before bool - s.Require().NoError(split.shard.QueryRowContext(s.ctx, "SELECT to_regclass('agent_configs') IS NOT NULL").Scan(&before)) - s.True(before, "migrating drops nothing a router of the previous release may still read") - - dropped, left, err := split.DropStrays(s.ctx) - s.Require().NoError(err) - s.Contains(dropped, "agent_configs") - s.Equal([]string{"skills"}, left) - - var configs, skills, requests bool - s.Require().NoError(split.shard.QueryRowContext(s.ctx, - "SELECT to_regclass('agent_configs') IS NOT NULL, to_regclass('skills') IS NOT NULL, to_regclass('requests') IS NOT NULL"). - Scan(&configs, &skills, &requests)) - s.False(configs, "an empty table of the shared set is dropped") - s.True(skills, "a table of the shared set holding rows is kept") - s.True(requests, "the shard's own tables stay") -} - // record_data_change locks the one data_change_starts row on a repeatable read write, on either // set, so a new database of each starts with it. func (s *ShardedStoreSuite) TestARepeatableReadWriteOnANewDatabaseIsRecorded() { @@ -89,113 +51,44 @@ func (s *ShardedStoreSuite) TestARepeatableReadWriteOnANewDatabaseIsRecorded() { s.NoError(err, "a repeatable read write on a new shard") } -// legacy turns the suite's database back into one that ran the single history up to version: -// the baseline's schema, recorded in the single history's table. -func (s *StoreSuite) legacy(dsn string, version int64) *Store { - legacy, err := Open(dsn) - s.Require().NoError(err) - s.upTo(legacy, globalSet, baseline) - s.upTo(legacy, shardSet, baseline) - _, err = legacy.global.ExecContext(s.ctx, `DROP TABLE goose_global_version, goose_shard_version; - CREATE TABLE goose_db_version (id serial PRIMARY KEY, version_id bigint NOT NULL, is_applied boolean NOT NULL, tstamp timestamp DEFAULT now()); - INSERT INTO goose_db_version (version_id, is_applied) VALUES (0, true), (?, true)`, version) - s.Require().NoError(err) - return legacy -} - -func (s *StoreSuite) TestADatabaseThatRanTheSingleHistoryIsAdopted() { - legacy := s.legacy(s.emptyDatabase("adopted"), legacyHead) - defer legacy.Close() - - s.Require().NoError(legacy.Migrate(s.ctx)) - - for _, table := range []string{"goose_global_version", "goose_shard_version"} { - var applied bool - s.Require().NoError(legacy.global.QueryRowContext(s.ctx, - "SELECT EXISTS (SELECT 1 FROM "+table+" WHERE version_id = ? AND is_applied)", baseline).Scan(&applied)) - s.True(applied, table) +// ranHistory is a database of the suite's own that recorded, besides each set's initial +// migration, the version given of the history squashed into it. +func (s *StoreSuite) ranHistory(name string, global, shard int64) *Store { + db, err := Open(s.emptyDatabase(name)) + s.Require().NoError(err) + s.Require().NoError(db.Migrate(s.ctx)) + for _, ran := range []struct { + set migrationSet + version int64 + }{{globalSet, global}, {shardSet, shard}} { + _, err := db.global.ExecContext(s.ctx, "INSERT INTO ? (version_id, is_applied) VALUES (?, true)", bun.Ident(ran.set.table), ran.version) + s.Require().NoError(err) } + return db } -func (s *StoreSuite) TestADatabaseShortOfTheSingleHistorysLastMigrationIsRefused() { - legacy := s.legacy(s.emptyDatabase("behind"), legacyHead-1) - defer legacy.Close() +// Every database deployed before the squash ran the whole history, so it holds the initial +// migration's schema and starts as it is. +func (s *StoreSuite) TestADatabaseThatRanTheSquashedHistoryStartsAsItIs() { + db := s.ranHistory("squashed", globalSet.squashed, shardSet.squashed) + defer db.Close() - s.ErrorContains(legacy.Migrate(s.ctx), "has not applied migration 20270103090000") + s.Require().NoError(db.Migrate(s.ctx)) } -// migratedTo opens an empty database of the suite's own with the shared set applied up to -// version, so a test can write the rows a later migration rewrites. -func (s *StoreSuite) migratedTo(name string, version int64) *Store { - opened, err := Open(s.emptyDatabase(name)) - s.Require().NoError(err) - s.upTo(opened, globalSet, version) - return opened -} +func (s *StoreSuite) TestADatabaseThatRanPartOfTheSquashedHistoryIsRefused() { + db := s.ranHistory("behind", globalSet.squashed-1, shardSet.squashed) + defer db.Close() -// upTo applies set's migrations to the store's one database up to version. -func (s *StoreSuite) upTo(opened *Store, set migrationSet, version int64) { - versions, err := database.NewStore(database.DialectPostgres, set.table) - s.Require().NoError(err) - provider, err := goose.NewProvider("", opened.global.DB, set.files, goose.WithStore(versions)) - s.Require().NoError(err) - _, err = provider.UpTo(s.ctx, version) - s.Require().NoError(err) + s.ErrorContains(db.Migrate(s.ctx), "has not applied migration 20270124093000") } -func (s *StoreSuite) TestFoldingTheConnectorSideTablesKeepsTheirRows() { - folded := s.migratedTo("folded", 20270113000000-1) - defer folded.Close() - checked := time.Date(2026, 3, 1, 10, 0, 0, 123456000, time.UTC) - expires := checked.Add(time.Hour) - _, err := folded.global.ExecContext(s.ctx, ` -INSERT INTO connector_connections (id, customer_id, connector_id, definition_revision, owner_type, auth_scheme, status) -VALUES ('with', 'app', 'acme', 1, 'app', 'test_key', 'connected'), ('without', 'app', 'acme', 1, 'app', 'test_key', 'pending'); -INSERT INTO connector_connection_clients (connection_id, registration, client_id, updated_at) VALUES ('with', 'dcr', 'issued', ?); -INSERT INTO connector_connection_validations (connection_id, revision, status, code, error, checked_at) -VALUES ('with', 3, 'failed', '503', 'Service Unavailable', ?); -INSERT INTO connector_audit (id, customer_id, connection_id, connector_id, owner_type, action, created_at) -VALUES ('granted', 'app', 'with', 'acme', 'app', 'grant_created', ?), ('called', 'app', 'with', 'acme', 'app', 'proxy_call', ?); -INSERT INTO connector_audit_credentials (audit_id, access_fingerprint, refresh_fingerprint, previous_refresh_fingerprint, rotated, access_expires_at) -VALUES ('granted', 'a1', 'r2', 'r1', true, ?); -INSERT INTO connector_invocations (id, customer_id, connection_id, connector_id, config_id, binding, tool, started_at, latency_ms) -VALUES ('shaped', 'app', 'with', 'acme', 'config', 'acme', 'search', ?, 5), ('unshaped', 'app', 'with', 'acme', 'config', 'acme', 'search', ?, 5); -INSERT INTO connector_invocation_arguments (invocation_id, shape) VALUES ('shaped', '[{"name": "q", "type": "string", "length": 4}]'); -`, checked, checked, checked, checked.Add(-time.Second), expires, checked, checked.Add(-time.Second)) - s.Require().NoError(err) - - s.Require().NoError(folded.Migrate(s.ctx)) - - with, err := folded.ConnectorConnections.Get(s.ctx, "app", "with") - s.Require().NoError(err) - s.Equal(ConnectorConnectionClient{Registration: core.ClientDCR, ClientID: "issued", UpdatedAt: checked}, with.Client) - s.Equal(ConnectorConnectionValidation{Revision: 3, Status: "failed", Code: "503", Error: "Service Unavailable", CheckedAt: checked}, with.Validation) - without, err := folded.ConnectorConnections.Get(s.ctx, "app", "without") - s.Require().NoError(err) - s.Zero(without.Client) - s.Zero(without.Validation) - - events, err := folded.ConnectorAuditEvents.Select(s.ctx, "app", AuditFilter{ConnectionID: "with"}) +func (s *StoreSuite) TestADatabaseFromBeforeTheSplitIsRefused() { + db, err := Open(s.emptyDatabase("unsplit")) s.Require().NoError(err) - s.Require().Len(events, 2) - s.Equal(&ConnectorAuditCredential{AccessFingerprint: "a1", RefreshFingerprint: "r2", PreviousRefreshFingerprint: "r1", - Rotated: true, AccessExpiresAt: expires}, normalized(events[0].Credential)) - s.Nil(events[1].Credential, "a row without a credential has none") - - invocations, err := folded.ConnectorInvocations.Select(s.ctx, "app", InvocationFilter{ConnectionID: "with"}) + defer db.Close() + _, err = db.global.ExecContext(s.ctx, "CREATE TABLE agent_configs (id text PRIMARY KEY)") s.Require().NoError(err) - s.Require().Len(invocations, 2) - length := 4 - s.Equal([]ArgumentShape{{Name: "q", Type: "string", Length: &length}}, invocations[0].Arguments) - s.Nil(invocations[1].Arguments, "a call whose arguments were not an object has no shape") -} -// normalized is credential with its times in UTC, as they were written. -func normalized(credential *ConnectorAuditCredential) *ConnectorAuditCredential { - if credential == nil { - return nil - } - out := *credential - out.AccessExpiresAt, out.RefreshExpiresAt = out.AccessExpiresAt.UTC(), out.RefreshExpiresAt.UTC() - return &out + s.ErrorContains(db.Migrate(s.ctx), "ran the migrations from before they were split") } diff --git a/acceleration/internal/store/migrate_unit_test.go b/acceleration/internal/store/migrate_unit_test.go index c07ed9954d..2cd7991e05 100644 --- a/acceleration/internal/store/migrate_unit_test.go +++ b/acceleration/internal/store/migrate_unit_test.go @@ -3,6 +3,7 @@ package store import ( "slices" "testing" + "testing/fstest" "github.com/stretchr/testify/require" ) @@ -20,29 +21,6 @@ func TestEveryTableBelongsToOneSet(t *testing.T) { } } -// A table a later migration drops is not one the set leaves, so nothing describes or moves it. -func TestADroppedTableIsNotInItsSet(t *testing.T) { - global, err := setTables(globalSet) - require.NoError(t, err) - - require.Contains(t, global, "connector_connections") - require.NotContains(t, global, "connector_connection_clients") -} - -// A table a later migration drops is no longer the set's, but a database of the other set may -// still hold it from before the split, so it stays a stray to drop there. -func TestADroppedTableLeavesItsSetButStaysAStray(t *testing.T) { - global, err := setTables(globalSet) - require.NoError(t, err) - created, err := createdTables(globalSet) - require.NoError(t, err) - for _, table := range retiredTables { - require.NotContains(t, global, table) - require.Contains(t, created, table) - } - require.Contains(t, global, "agent_configs") -} - // An export reads and writes each table in the database it lives in. func TestEveryExportedTableIsOnTheSideItsSetSays(t *testing.T) { shard, err := setTables(shardSet) @@ -52,10 +30,16 @@ func TestEveryExportedTableIsOnTheSideItsSetSays(t *testing.T) { } } -// A table a later migration drops is no longer the set's, though the baseline created it. -func TestADroppedTableIsNoLongerTheSets(t *testing.T) { - shard, err := setTables(shardSet) +// A table a later migration drops or renames is not one the set leaves under its old name, so +// nothing describes or moves it. +func TestATableALaterMigrationDropsOrRenamesIsNotTheSets(t *testing.T) { + set := migrationSet{files: fstest.MapFS{ + "1_initial.sql": {Data: []byte("-- +goose Up\nCREATE TABLE kept (id int);\nCREATE TABLE dropped (id int);\nCREATE TABLE renamed (id int);\n" + + "-- +goose Down\nCREATE TABLE downed (id int);\n")}, + "2_change.sql": {Data: []byte("-- +goose Up\nDROP TABLE dropped;\nALTER TABLE renamed RENAME TO moved;\n")}, + }} + + tables, err := setTables(set) require.NoError(t, err) - require.NotContains(t, shard, "phone_calls") - require.Contains(t, shard, "call_legs") + require.Equal(t, []string{"kept", "moved"}, tables) } diff --git a/acceleration/internal/store/notice_test.go b/acceleration/internal/store/notice_test.go index 649197d76b..1f112e9765 100644 --- a/acceleration/internal/store/notice_test.go +++ b/acceleration/internal/store/notice_test.go @@ -7,13 +7,8 @@ import ( "time" "github.com/google/uuid" - "github.com/pressly/goose/v3" - "github.com/pressly/goose/v3/database" ) -// noticesVersion is the migration that keeps every kind of notice in one table. -const noticesVersion = 20270111000000 - func (s *StoreSuite) limitNotice(organization string) LimitNotice { return LimitNotice{ OrganizationID: organization, Kind: LimitNoCredit, AppID: "app-1", Tier: "free", @@ -186,57 +181,3 @@ func (s *StoreSuite) TestNoticeQueryBudgets() { s.Equal(1, s.countQueries(func() { s.Len(keysOf(s.claimed(), organization), 1) })) s.Equal(1, s.countQueries(func() { s.Require().NoError(s.store.Notices.MarkPosted(s.ctx, limit)) })) } - -// The migration that made the notices one table carries every row of the three it replaced, -// in its kind's own shape, and its Down puts them back. -func (s *StoreSuite) TestTheNoticesOfTheThreeOldTablesAreCarriedIntoOne() { - db, err := Open(s.emptyDatabase("notices_migration")) - s.Require().NoError(err) - defer db.Close() - s.Require().NoError(db.Migrate(s.ctx)) - versions, err := database.NewStore(database.DialectPostgres, globalSet.table) - s.Require().NoError(err) - provider, err := goose.NewProvider("", db.global.DB, globalSet.files, goose.WithStore(versions)) - s.Require().NoError(err) - _, err = provider.DownTo(s.ctx, noticesVersion-1) - s.Require().NoError(err) - _, err = db.global.ExecContext(s.ctx, ` - INSERT INTO limit_notices (organization_id, kind, app_id, tier, enforced, message, claimed_at, posted_at) - VALUES ('org-a', 'spend_limit', 'app-1', 'free', true, 'over', now() - interval '2 hours', NULL), - ('org-a', 'no_credit', '', '', false, 'posted', now(), now()); - INSERT INTO balance_notices (organization_id, kind, granted_micros, balance_micros, threshold_micros) - VALUES ('org-a', 'balance_low', 10, 4, 5); - INSERT INTO cost_anomaly_notices (organization_id, day, spent_micros, baseline_micros, claimed_at) - VALUES ('org-a', '2026-03-10', 500, 100, now() - interval '2 hours')`) - s.Require().NoError(err) - - _, err = provider.Up(s.ctx) - s.Require().NoError(err) - - var rows []Notice - s.Require().NoError(db.global.NewSelect().Model(&rows).Order("kind").Scan(s.ctx)) - s.Require().Len(rows, 4) - balance, anomaly, limit, posted := rows[0], rows[1], rows[3], rows[2] - s.Equal("10", balance.DedupeKey) - s.JSONEq(`{"balance_micros": 4, "threshold_micros": 5}`, string(balance.Payload)) - s.NotNil(balance.PostedAt, "a balance warning was queued as it was written") - read, err := anomaly.CostAnomaly() - s.Require().NoError(err) - s.Equal(CostAnomaly{OrganizationID: "org-a", Day: time.Date(2026, 3, 10, 0, 0, 0, 0, time.UTC), SpentMicros: 500, BaselineMicros: 100}, read) - over, err := limit.LimitNotice() - s.Require().NoError(err) - s.Equal(LimitNotice{OrganizationID: "org-a", Kind: LimitSpendLimit, AppID: "app-1", Tier: "free", Enforced: true, Message: "over"}, over) - s.NotNil(posted.PostedAt) - claimed, err := db.Notices.Claim(s.ctx, time.Hour, 10) - s.Require().NoError(err) - s.ElementsMatch([]string{"cost_anomaly/2026-03-10", "spend_limit/"}, keysOf(claimed, "org-a"), "the unposted are claimed as before") - - _, err = provider.DownTo(s.ctx, noticesVersion-1) - s.Require().NoError(err) - var limits, balances, anomalies int - s.Require().NoError(db.global.QueryRowContext(s.ctx, `SELECT - (SELECT count(*) FROM limit_notices WHERE app_id = 'app-1' AND enforced AND message = 'over'), - (SELECT count(*) FROM balance_notices WHERE granted_micros = 10 AND balance_micros = 4), - (SELECT count(*) FROM cost_anomaly_notices WHERE day = '2026-03-10' AND spent_micros = 500)`).Scan(&limits, &balances, &anomalies)) - s.Equal([]int{1, 1, 1}, []int{limits, balances, anomalies}, "and the Down puts each back") -} diff --git a/acceleration/internal/store/stream_trunk_test.go b/acceleration/internal/store/stream_trunk_test.go index 5a1dc82582..df418cf7b7 100644 --- a/acceleration/internal/store/stream_trunk_test.go +++ b/acceleration/internal/store/stream_trunk_test.go @@ -7,9 +7,6 @@ import ( "fmt" "sync" "time" - - "github.com/pressly/goose/v3" - "github.com/pressly/goose/v3/database" ) // trunkIDs are the ids of the trunks one group sees. @@ -373,75 +370,6 @@ func (s *StoreSuite) TestAStreamTrunkIsReadByIdForItsOwnCustomerOnly() { s.ErrorIs(err, ErrNoStreamTrunk) } -// bridgesVersion is the global migration that moves numbers' bridges onto their trunks. -const bridgesVersion int64 = 20270116000002 - -func (s *StoreSuite) TestMovingBridgesOntoTrunksKeepsEveryNumbersTrunk() { - db, err := Open(s.emptyDatabase("trunk_bridges")) - s.Require().NoError(err) - defer db.Close() - versions, err := database.NewStore(database.DialectPostgres, globalSet.table) - s.Require().NoError(err) - provider, err := goose.NewProvider("", db.global.DB, globalSet.files, goose.WithStore(versions)) - s.Require().NoError(err) - _, err = provider.UpTo(s.ctx, bridgesVersion-1) - s.Require().NoError(err) - - _, err = db.global.ExecContext(s.ctx, ` -INSERT INTO stream_trunks (id, customer_id, vendor, numbers, bridge_uri, bridge_username, bridge_password_sealed, - bridge_password_kek_version) VALUES - ('trunk-shared', 'acme', 'telnyx', '{+15125550101,+15125550102}', 'sip:trunk-shared@bridge.test', 'shared-user', - 'trunk sealed', 1); -INSERT INTO phone_numbers (e164, vendor, country, customer_id, purchased_at, stream_trunk_id, bridge_uri, bridge_username, - bridge_password_sealed, bridge_password_kek_version, attached_at, released_at) VALUES - ('+15125550101', 'telnyx', 'US', 'acme', ?0, 'trunk-shared', 'sip:+15125550101@bridge.test', 'shared-user', - 'number sealed', 1, ?0, NULL), - ('+15125550102', 'telnyx', 'US', 'acme', ?0, 'trunk-shared', NULL, NULL, NULL, NULL, NULL, NULL), - ('+15125550103', 'telnyx', 'US', 'acme', ?0, 'trunk-own', 'sip:+15125550103@own.test', 'own-user', - 'own sealed', 2, ?0, NULL), - ('+15125550104', 'telnyx', 'US', 'acme', ?0, 'trunk-unkept', 'sip:+15125550104@own.test', 'unkept-user', - NULL, NULL, ?0, NULL), - ('+15125550105', 'telnyx', 'US', 'acme', ?0, 'trunk-gone', 'sip:+15125550105@own.test', 'gone-user', - 'gone sealed', 2, NULL, ?0), - ('+15125550106', 'telnyx', 'US', 'acme', ?0, 'trunk-bare', NULL, NULL, NULL, NULL, ?0, NULL)`, s.base) - s.Require().NoError(err) - - s.Require().NoError(db.Migrate(s.ctx)) - - trunks := map[string]StreamTrunk{} - s.Require().NoError(db.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", Vendor: "telnyx"}, - func(_ context.Context, tx *TrunkGroupTx) error { - read, err := tx.Trunks() - for _, trunk := range read { - trunk.CreatedAt = time.Time{} - trunks[trunk.ID] = trunk - } - return err - })) - s.Equal(map[string]StreamTrunk{ - "trunk-shared": {ID: "trunk-shared", CustomerID: "acme", Vendor: "telnyx", Numbers: []string{"+15125550101", "+15125550102"}, - BridgeURI: "sip:trunk-shared@bridge.test", BridgeUsername: "shared-user", - BridgePasswordSealed: []byte("trunk sealed"), BridgePasswordKEKVersion: 1}, - "trunk-own": {ID: "trunk-own", CustomerID: "acme", Vendor: "telnyx", Numbers: []string{"+15125550103"}, - BridgeURI: "sip:+15125550103@own.test", BridgeUsername: "own-user", - BridgePasswordSealed: []byte("own sealed"), BridgePasswordKEKVersion: 2, Own: true}, - "trunk-unkept": {ID: "trunk-unkept", CustomerID: "acme", Vendor: "telnyx", Numbers: []string{"+15125550104"}, - BridgeURI: "sip:+15125550104@own.test", BridgeUsername: "unkept-user", BridgePasswordSealed: []byte{}, Own: true}, - }, trunks, "a shared trunk keeps its password; a number's own becomes a trunk; a released number's does not") - - shared, err := db.PhoneNumbers.AttachedBridge(s.ctx, "telnyx", "+15125550101") - s.Require().NoError(err) - s.Equal([]byte("trunk sealed"), shared.PasswordSealed, "the trunk's password, sealed to the trunk") - own, err := db.PhoneNumbers.AttachedBridge(s.ctx, "telnyx", "+15125550103") - s.Require().NoError(err) - s.Equal(AttachedBridge{CustomerID: "acme", TrunkID: "trunk-own", Own: true, URI: "sip:+15125550103@own.test", - Username: "own-user", PasswordSealed: []byte("own sealed"), KEKVersion: 2}, own) - for _, unkept := range []string{"+15125550104", "+15125550106"} { - _, err = db.PhoneNumbers.AttachedBridge(s.ctx, "telnyx", unkept) - s.ErrorIs(err, ErrNoStoredBridge, unkept) - } -} - func (s *StoreSuite) TestAnOwnTrunkMadeWithoutAKeyIsSavedWithNoPassword() { group := TrunkGroup{CustomerID: "acme", Vendor: "twilio"} s.Require().NoError(s.store.StreamTrunks.InGroup(s.ctx, group, func(_ context.Context, tx *TrunkGroupTx) error { diff --git a/acceleration/migrations/global/20270110000000_baseline.sql b/acceleration/migrations/global/20270110000000_initial.sql similarity index 85% rename from acceleration/migrations/global/20270110000000_baseline.sql rename to acceleration/migrations/global/20270110000000_initial.sql index 06014c44bb..28b15cefd9 100644 --- a/acceleration/migrations/global/20270110000000_baseline.sql +++ b/acceleration/migrations/global/20270110000000_initial.sql @@ -1,8 +1,11 @@ -- +goose Up --- The shared tables as they stood at 20270103090000, the last version of the single migration --- history every database ran. A database that ran it is marked as having applied this baseline --- (store.adoptLegacy); a new one runs it. Every shard reads them from the one shared database. +-- The shared tables: tenants, configs, connectors, numbers, limits. Every shard reads them from the +-- one shared database. This is the whole history up to 20270124093000, squashed; a database that ran +-- that history records this version as applied and runs nothing here. + +-- The change log, kept by both sets: a deployment of one database runs both initial migrations on +-- it, so each of these is a no-op the second time. -- +goose StatementBegin CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger @@ -50,16 +53,21 @@ BEGIN RETURN NULL; END IF; - FOREACH column_name IN ARRAY TG_ARGV[3:] LOOP + -- TG_ARGV[3] is the table's secret columns as an array literal (store.isSecret, attached by + -- Store.watchDataChanges), and TG_ARGV[4:] the columns naming the row. A trigger attached + -- before the list was passed would record the secrets, so it records nothing and fails. + IF coalesce(left(TG_ARGV[3], 1), '') <> '{' THEN + RAISE EXCEPTION 'record_data_change: % was attached without its secret columns', TG_TABLE_NAME; + END IF; + + FOREACH column_name IN ARRAY TG_ARGV[4:] LOOP identity := identity || jsonb_build_object(column_name, subject -> column_name); END LOOP; -- Credentials are left behind. A secret this deployment sealed is worth nothing to -- the one reading it, and an access token a customer's user granted to this -- deployment is not something to hand out because somebody asked for their data. - subject := subject - 'secret_sealed' - 'access_token' - 'refresh_token' - - 'oauth_state' - 'code_verifier' - 'credentials_sealed' - 'password_sealed' - - 'bridge_password_sealed' - 'refresh_secret_hash'; + subject := subject - TG_ARGV[3]::text[]; -- A change is numbered when it is written and seen when its transaction commits, so no -- committed row tells a reader which lower number a transaction still running holds. @@ -93,15 +101,21 @@ $_$; -- +goose StatementEnd CREATE TABLE IF NOT EXISTS data_change_capture ( - customer_id text PRIMARY KEY, + customer_id text NOT NULL, started_at timestamp with time zone DEFAULT now() NOT NULL, expires_at timestamp with time zone NOT NULL, recorded_since bigint DEFAULT 0 NOT NULL, pruned_through bigint DEFAULT 0 NOT NULL ); +CREATE TABLE IF NOT EXISTS data_change_starts ( + one boolean DEFAULT true NOT NULL, + started bigint DEFAULT 0 NOT NULL, + CONSTRAINT data_change_starts_one_check CHECK (one) +); + CREATE TABLE IF NOT EXISTS data_changes ( - seq bigserial PRIMARY KEY, + seq bigint NOT NULL, customer_id text NOT NULL, table_name text NOT NULL, op text NOT NULL, @@ -111,14 +125,57 @@ CREATE TABLE IF NOT EXISTS data_changes ( at timestamp with time zone DEFAULT now() NOT NULL ); +CREATE SEQUENCE IF NOT EXISTS data_changes_seq_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; + +ALTER SEQUENCE data_changes_seq_seq OWNED BY data_changes.seq; + +ALTER TABLE ONLY data_changes ALTER COLUMN seq SET DEFAULT nextval('data_changes_seq_seq'::regclass); + +-- +goose StatementBegin +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_change_capture_pkey' AND conrelid = 'data_change_capture'::regclass) THEN + ALTER TABLE ONLY data_change_capture + ADD CONSTRAINT data_change_capture_pkey PRIMARY KEY (customer_id); + END IF; +END $$; +-- +goose StatementEnd + +-- +goose StatementBegin +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_change_starts_pkey' AND conrelid = 'data_change_starts'::regclass) THEN + ALTER TABLE ONLY data_change_starts + ADD CONSTRAINT data_change_starts_pkey PRIMARY KEY (one); + END IF; +END $$; +-- +goose StatementEnd + +-- +goose StatementBegin +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_changes_pkey' AND conrelid = 'data_changes'::regclass) THEN + ALTER TABLE ONLY data_changes + ADD CONSTRAINT data_changes_pkey PRIMARY KEY (seq); + END IF; +END $$; +-- +goose StatementEnd + CREATE INDEX IF NOT EXISTS data_changes_at_idx ON data_changes USING btree (at); CREATE INDEX IF NOT EXISTS data_changes_customer_idx ON data_changes USING btree (customer_id, seq); -COMMENT ON SCHEMA public IS ''; +INSERT INTO data_change_starts DEFAULT VALUES ON CONFLICT DO NOTHING; + +-- The set's own objects. -- +goose StatementBegin -CREATE OR REPLACE FUNCTION price_changes_guard() RETURNS trigger +CREATE FUNCTION price_changes_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN @@ -138,7 +195,7 @@ END $$; -- +goose StatementEnd -- +goose StatementBegin -CREATE OR REPLACE FUNCTION price_entries_guard() RETURNS trigger +CREATE FUNCTION price_entries_guard() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN @@ -150,6 +207,12 @@ BEGIN END $$; -- +goose StatementEnd +CREATE TABLE activity_digests ( + day date NOT NULL, + claimed_at timestamp with time zone DEFAULT now() NOT NULL, + posted_at timestamp with time zone +); + CREATE TABLE agent_configs ( id text NOT NULL, customer_id text NOT NULL, @@ -171,8 +234,7 @@ CREATE TABLE agent_configs ( sync_hash text DEFAULT ''::text NOT NULL, search text DEFAULT ''::text NOT NULL, mode text DEFAULT 'voice'::text NOT NULL, - plugins jsonb DEFAULT '[]'::jsonb NOT NULL, - sandbox text DEFAULT ''::text NOT NULL, + sandbox_provider text DEFAULT ''::text CONSTRAINT agent_configs_sandbox_not_null NOT NULL, video_source text DEFAULT ''::text NOT NULL, video_max_frames integer DEFAULT 1 NOT NULL, sts text DEFAULT ''::text NOT NULL, @@ -183,24 +245,20 @@ CREATE TABLE agent_configs ( dispatch_text boolean DEFAULT false NOT NULL, connectors jsonb DEFAULT '[]'::jsonb NOT NULL, sandbox_options jsonb DEFAULT '{}'::jsonb NOT NULL, - plugin_events jsonb DEFAULT '[]'::jsonb NOT NULL, - mcp_servers jsonb DEFAULT '[]'::jsonb NOT NULL, - channels jsonb DEFAULT '{}'::jsonb NOT NULL, - episode_cards boolean DEFAULT false NOT NULL, - progressive_tools boolean DEFAULT false NOT NULL, + channels_lines jsonb DEFAULT '{}'::jsonb CONSTRAINT agent_configs_channels_not_null NOT NULL, + episode_cards_on boolean DEFAULT false CONSTRAINT agent_configs_episode_cards_not_null NOT NULL, greeting_mode text DEFAULT 'exact'::text NOT NULL, left_out_connectors jsonb DEFAULT '[]'::jsonb NOT NULL, role text DEFAULT ''::text NOT NULL, scheduling jsonb DEFAULT '{}'::jsonb NOT NULL, review_instructions text DEFAULT ''::text NOT NULL, - tool_output_retention text DEFAULT ''::text NOT NULL, resume_history jsonb DEFAULT '{}'::jsonb NOT NULL, region text DEFAULT 'us'::text NOT NULL, calls jsonb DEFAULT '{}'::jsonb NOT NULL, episode_cards_record boolean DEFAULT false NOT NULL, floor_control jsonb, llm_fallbacks jsonb, - chat_channels jsonb DEFAULT '[]'::jsonb NOT NULL, + channels_chat jsonb DEFAULT '[]'::jsonb CONSTRAINT agent_configs_chat_channels_not_null NOT NULL, agents jsonb, image text DEFAULT ''::text NOT NULL, ui_instructions text DEFAULT ''::text NOT NULL, @@ -234,63 +292,6 @@ CREATE SEQUENCE agent_logs_id_seq ALTER SEQUENCE agent_logs_id_seq OWNED BY agent_logs.id; -CREATE TABLE agent_plugin_clients ( - customer_id text NOT NULL, - config_id text NOT NULL, - plugin_id text NOT NULL, - client_id text NOT NULL, - secret_sealed bytea, - kek_version integer DEFAULT 0 NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL -); - -CREATE TABLE agent_plugin_connections ( - id text NOT NULL, - customer_id text NOT NULL, - config_id text NOT NULL, - plugin_id text NOT NULL, - instance_url text DEFAULT ''::text NOT NULL, - access_token text DEFAULT ''::text NOT NULL, - refresh_token text DEFAULT ''::text NOT NULL, - expires_at timestamp with time zone, - status text DEFAULT 'pending'::text NOT NULL, - oauth_state text DEFAULT ''::text NOT NULL, - code_verifier text DEFAULT ''::text NOT NULL, - client_id text DEFAULT ''::text NOT NULL, - token_endpoint text DEFAULT ''::text NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL, - updated_at timestamp with time zone DEFAULT now() NOT NULL, - deleted_at timestamp with time zone, - user_id text DEFAULT ''::text NOT NULL -); - -CREATE TABLE agent_plugin_event_deliveries ( - subscription_id text NOT NULL, - event_id text NOT NULL, - received_at timestamp with time zone NOT NULL -); - -CREATE TABLE agent_plugin_event_subscriptions ( - id text NOT NULL, - customer_id text NOT NULL, - config_id text NOT NULL, - plugin_id text NOT NULL, - user_id text DEFAULT ''::text NOT NULL, - event text NOT NULL, - arguments jsonb DEFAULT '{}'::jsonb NOT NULL, - key text NOT NULL, - token text NOT NULL, - secret text NOT NULL, - remote_id text DEFAULT ''::text NOT NULL, - refresh_before timestamp with time zone, - status text NOT NULL, - error text DEFAULT ''::text NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - deleted_at timestamp with time zone -); - CREATE TABLE api_keys ( id text NOT NULL, app_id text NOT NULL, @@ -337,16 +338,6 @@ CREATE TABLE audit_log ( created_at timestamp with time zone NOT NULL ); -CREATE TABLE balance_notices ( - organization_id text NOT NULL, - kind text NOT NULL, - granted_micros bigint NOT NULL, - balance_micros bigint NOT NULL, - threshold_micros bigint NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL, - CONSTRAINT balance_notices_kind_check CHECK ((kind = ANY (ARRAY['balance_low'::text, 'balance_exhausted'::text]))) -); - CREATE TABLE business_profiles ( customer_id text NOT NULL, legal_business_name text DEFAULT ''::text NOT NULL, @@ -412,7 +403,7 @@ CREATE TABLE campaign_contacts ( step_id text DEFAULT ''::text NOT NULL, next_attempt_at timestamp with time zone, leased_by text DEFAULT ''::text NOT NULL, - leased_until timestamp with time zone, + lease_until timestamp with time zone, outcome text DEFAULT ''::text NOT NULL, converted boolean DEFAULT false NOT NULL ); @@ -474,17 +465,11 @@ CREATE TABLE channel_deliveries ( from_address text DEFAULT ''::text NOT NULL ); -CREATE TABLE channel_identities ( - id text NOT NULL, - customer_id text NOT NULL, - config_id text NOT NULL, - kind text NOT NULL, - address text NOT NULL, - user_id text NOT NULL, - conversation_id text DEFAULT ''::text NOT NULL, - created_at timestamp with time zone NOT NULL, - updated_at timestamp with time zone NOT NULL, - thread text DEFAULT ''::text NOT NULL +CREATE TABLE channel_link_failures ( + account_id text NOT NULL, + from_address text NOT NULL, + window_start timestamp with time zone NOT NULL, + failures integer NOT NULL ); CREATE TABLE channel_links ( @@ -543,16 +528,6 @@ CREATE TABLE channel_thread_messages ( CONSTRAINT channel_thread_messages_kind_check CHECK ((kind = ANY (ARRAY['inbound'::text, 'turn'::text, 'reply'::text]))) ); -CREATE TABLE channel_thread_people ( - channel_id text NOT NULL, - chat_person text NOT NULL -); - -CREATE TABLE channel_thread_starters ( - channel_id text NOT NULL, - starter text NOT NULL -); - CREATE TABLE channel_thread_waiting ( customer_id text NOT NULL, connector_id text NOT NULL, @@ -575,21 +550,21 @@ CREATE TABLE channel_threads ( thread_parts jsonb DEFAULT '{}'::jsonb NOT NULL, stream_app_pk bigint, last_inbound_at timestamp with time zone NOT NULL, - turn_holder text, - turn_until timestamp with time zone, - created_at timestamp with time zone DEFAULT now() NOT NULL + created_at timestamp with time zone DEFAULT now() NOT NULL, + chat_person text DEFAULT ''::text NOT NULL, + starter text DEFAULT ''::text NOT NULL ); -CREATE TABLE chat_channel_turns ( - stream_app_pk bigint NOT NULL, - cid text NOT NULL, - turn_holder text NOT NULL, - turn_until timestamp with time zone NOT NULL +CREATE TABLE channel_turns ( + stream_app_pk bigint CONSTRAINT chat_channel_turns_stream_app_pk_not_null NOT NULL, + cid text CONSTRAINT chat_channel_turns_cid_not_null NOT NULL, + leased_by text CONSTRAINT chat_channel_turns_turn_holder_not_null NOT NULL, + lease_until timestamp with time zone CONSTRAINT chat_channel_turns_turn_until_not_null NOT NULL ); CREATE TABLE chat_inbound ( seq bigint NOT NULL, - stream_app bigint NOT NULL, + stream_app_pk bigint CONSTRAINT chat_inbound_stream_app_not_null NOT NULL, message_id text NOT NULL, customer_id text DEFAULT ''::text NOT NULL, deployment boolean NOT NULL, @@ -613,12 +588,6 @@ ALTER TABLE chat_inbound ALTER COLUMN seq ADD GENERATED ALWAYS AS IDENTITY ( CACHE 1 ); -CREATE TABLE connection_event_deliveries ( - subscription_id text NOT NULL, - event_id text NOT NULL, - received_at timestamp with time zone NOT NULL -); - CREATE TABLE connection_event_subscriptions ( id text NOT NULL, customer_id text NOT NULL, @@ -639,6 +608,8 @@ CREATE TABLE connection_event_subscriptions ( failures integer DEFAULT 0 NOT NULL, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL, + attempts integer DEFAULT 0 NOT NULL, + CONSTRAINT connection_event_subscriptions_attempts_check CHECK ((attempts >= 0)), CONSTRAINT connection_event_subscriptions_kek_version_check CHECK ((kek_version >= 1)), CONSTRAINT connection_event_subscriptions_secret_sealed_check CHECK ((secret_sealed <> '\x'::bytea)), CONSTRAINT connection_event_subscriptions_status_check CHECK ((status = ANY (ARRAY['pending'::text, 'active'::text, 'failed'::text]))) @@ -660,18 +631,8 @@ CREATE TABLE connector_audit ( latency_ms integer, target text DEFAULT ''::text NOT NULL, created_at timestamp with time zone NOT NULL, - tools jsonb -); - -CREATE TABLE connector_audit_credentials ( - audit_id text NOT NULL, - access_fingerprint text DEFAULT ''::text NOT NULL, - previous_access_fingerprint text DEFAULT ''::text CONSTRAINT connector_audit_credentials_previous_access_fingerprin_not_null NOT NULL, - refresh_fingerprint text DEFAULT ''::text NOT NULL, - previous_refresh_fingerprint text DEFAULT ''::text CONSTRAINT connector_audit_credentials_previous_refresh_fingerpri_not_null NOT NULL, - rotated boolean DEFAULT false NOT NULL, - access_expires_at timestamp with time zone, - refresh_expires_at timestamp with time zone + tools jsonb, + credential jsonb ); CREATE TABLE connector_authorization_attempts ( @@ -712,22 +673,6 @@ CREATE TABLE connector_config_tokens ( CONSTRAINT connector_config_tokens_tokens_sealed_check CHECK ((tokens_sealed <> '\x'::bytea)) ); -CREATE TABLE connector_connection_clients ( - connection_id text NOT NULL, - registration text NOT NULL, - client_id text NOT NULL, - updated_at timestamp with time zone NOT NULL -); - -CREATE TABLE connector_connection_validations ( - connection_id text NOT NULL, - revision integer NOT NULL, - status text NOT NULL, - code text DEFAULT ''::text NOT NULL, - error text DEFAULT ''::text NOT NULL, - checked_at timestamp with time zone NOT NULL -); - CREATE TABLE connector_connections ( id text NOT NULL, customer_id text NOT NULL, @@ -756,6 +701,14 @@ CREATE TABLE connector_connections ( deleted_at timestamp with time zone, provider_unit_id text, connected_at timestamp with time zone, + client_registration text DEFAULT ''::text NOT NULL, + client_id text DEFAULT ''::text NOT NULL, + client_updated_at timestamp with time zone, + validation_revision integer DEFAULT 0 NOT NULL, + validation_status text DEFAULT ''::text NOT NULL, + validation_code text DEFAULT ''::text NOT NULL, + validation_error text DEFAULT ''::text NOT NULL, + validation_checked_at timestamp with time zone, CONSTRAINT connector_connections_definition_revision_check CHECK ((definition_revision >= 1)), CONSTRAINT connector_connections_owner CHECK ((((owner_type = 'app'::text) AND (owner_id = ''::text)) OR ((owner_type = 'user'::text) AND (owner_id <> ''::text)))), CONSTRAINT connector_connections_revision_check CHECK ((revision >= 1)) @@ -803,11 +756,6 @@ CREATE TABLE connector_event_destinations ( CONSTRAINT connector_event_destinations_secret_sealed_check CHECK ((secret_sealed <> '\x'::bytea)) ); -CREATE TABLE connector_invocation_arguments ( - invocation_id text NOT NULL, - shape jsonb NOT NULL -); - CREATE TABLE connector_invocations ( id text NOT NULL, customer_id text NOT NULL, @@ -822,6 +770,7 @@ CREATE TABLE connector_invocations ( error_type text DEFAULT ''::text NOT NULL, provider_status integer, error_message text DEFAULT ''::text NOT NULL, + arguments jsonb, CONSTRAINT connector_invocations_error_type_check CHECK ((error_type = ANY (ARRAY[''::text, 'customer_auth'::text, 'external_server'::text, 'client_timeout'::text, 'outcome_unknown'::text, 'denied'::text]))), CONSTRAINT connector_invocations_latency_ms_check CHECK ((latency_ms >= 0)) ); @@ -857,7 +806,7 @@ CREATE TABLE connector_tool_pins ( CREATE TABLE contact_map ( id text NOT NULL, customer_id text NOT NULL, - agent_config_id text NOT NULL, + config_id text CONSTRAINT contact_map_agent_config_id_not_null NOT NULL, kind text NOT NULL, address text NOT NULL, conversation_id text NOT NULL, @@ -865,19 +814,10 @@ CREATE TABLE contact_map ( stream_app_pk bigint, created_at timestamp with time zone NOT NULL, updated_at timestamp with time zone NOT NULL, + thread text DEFAULT ''::text NOT NULL, CONSTRAINT contact_map_address_check CHECK ((address <> ''::text)) ); -CREATE TABLE cost_anomaly_notices ( - organization_id text NOT NULL, - day date NOT NULL, - spent_micros bigint NOT NULL, - baseline_micros bigint NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL, - claimed_at timestamp with time zone DEFAULT now() NOT NULL, - posted_at timestamp with time zone -); - CREATE TABLE custom_models ( id text NOT NULL, customer_id text NOT NULL, @@ -910,12 +850,6 @@ CREATE TABLE customer_activity ( last_at timestamp with time zone NOT NULL ); -CREATE TABLE data_change_starts ( - one boolean DEFAULT true NOT NULL, - started bigint DEFAULT 0 NOT NULL, - CONSTRAINT data_change_starts_one_check CHECK (one) -); - CREATE TABLE data_move_cursors ( customer_id text NOT NULL, source text NOT NULL, @@ -923,6 +857,13 @@ CREATE TABLE data_move_cursors ( read_at timestamp with time zone NOT NULL ); +CREATE TABLE deliveries_seen ( + scope text NOT NULL, + key text NOT NULL, + seen_at timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT deliveries_seen_key_check CHECK ((key <> ''::text)) +); + CREATE TABLE dlc_review_logs ( id text NOT NULL, use_case_id text NOT NULL, @@ -965,12 +906,6 @@ CREATE TABLE dlc_use_cases ( approved_at timestamp with time zone ); -CREATE TABLE episode_activity ( - episode_id text NOT NULL, - last_message_at timestamp with time zone, - summary_lease_until timestamp with time zone -); - CREATE TABLE episodes ( id text NOT NULL, customer_id text NOT NULL, @@ -985,19 +920,17 @@ CREATE TABLE episodes ( ended_at timestamp with time zone, stream_app_pk bigint, created_at timestamp with time zone DEFAULT now() NOT NULL, + last_message_at timestamp with time zone, + lease_until timestamp with time zone, + leased_by text, CONSTRAINT episodes_check CHECK (((source = 'call'::text) = (session_id IS NOT NULL))), CONSTRAINT episodes_status_check CHECK ((status = ANY (ARRAY['in_progress'::text, 'ended'::text, 'summarized'::text, 'summary_failed'::text]))) ); -CREATE TABLE hook_deliveries ( - key text NOT NULL, - seen_at timestamp with time zone DEFAULT now() NOT NULL -); - CREATE TABLE image_jobs ( id text NOT NULL, customer_id text NOT NULL, - stream_app bigint DEFAULT 0 NOT NULL, + stream_app_pk bigint DEFAULT 0 CONSTRAINT image_jobs_stream_app_not_null NOT NULL, cid text NOT NULL, agent_user text NOT NULL, session_id text NOT NULL, @@ -1122,19 +1055,6 @@ CREATE SEQUENCE limit_grants_id_seq ALTER SEQUENCE limit_grants_id_seq OWNED BY limit_grants.id; -CREATE TABLE limit_notices ( - organization_id text NOT NULL, - kind text NOT NULL, - app_id text DEFAULT ''::text NOT NULL, - tier text DEFAULT ''::text NOT NULL, - enforced boolean NOT NULL, - message text NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL, - claimed_at timestamp with time zone DEFAULT now() NOT NULL, - posted_at timestamp with time zone, - CONSTRAINT limit_notices_kind_check CHECK ((kind = ANY (ARRAY['no_credit'::text, 'spend_hard_limit'::text, 'spend_limit'::text]))) -); - CREATE TABLE limits ( id bigint NOT NULL, subject text NOT NULL, @@ -1152,7 +1072,7 @@ CREATE TABLE limits ( updated_at timestamp with time zone DEFAULT now() NOT NULL, CONSTRAINT limits_ids_check CHECK ((((app_id <> ''::text) = (level = ANY (ARRAY['app'::text, 'api_key'::text, 'user'::text]))) AND ((api_key <> ''::text) = (level = 'api_key'::text)) AND ((user_id <> ''::text) = (level = 'user'::text)) AND ((category <> ''::text) = (subject = ANY (ARRAY['category'::text, 'app_category'::text]))))), CONSTRAINT limits_interval_check CHECK (("interval" = ANY (ARRAY['daily'::text, 'weekly'::text, 'biweekly'::text, 'monthly'::text]))), - CONSTRAINT limits_level_check CHECK ((((((((((((subject = 'organization'::text) AND (level = 'organization'::text)) OR ((subject = 'app'::text) AND (level = 'app'::text))) OR ((subject = 'api_key'::text) AND (level = 'organization'::text))) OR ((subject = 'api_key'::text) AND (level = 'app'::text))) OR ((subject = 'api_key'::text) AND (level = 'api_key'::text))) OR ((subject = 'user'::text) AND (level = 'organization'::text))) OR ((subject = 'user'::text) AND (level = 'app'::text))) OR ((subject = 'user'::text) AND (level = 'user'::text))) OR ((subject = 'category'::text) AND (level = 'organization'::text))) OR ((subject = 'app_category'::text) AND (level = 'app'::text)))), + CONSTRAINT limits_level_check CHECK ((((subject = 'organization'::text) AND (level = 'organization'::text)) OR ((subject = 'app'::text) AND (level = 'app'::text)) OR ((subject = 'api_key'::text) AND (level = 'organization'::text)) OR ((subject = 'api_key'::text) AND (level = 'app'::text)) OR ((subject = 'api_key'::text) AND (level = 'api_key'::text)) OR ((subject = 'user'::text) AND (level = 'organization'::text)) OR ((subject = 'user'::text) AND (level = 'app'::text)) OR ((subject = 'user'::text) AND (level = 'user'::text)) OR ((subject = 'category'::text) AND (level = 'organization'::text)) OR ((subject = 'app_category'::text) AND (level = 'app'::text)))), CONSTRAINT limits_limit_micros_check CHECK ((limit_micros >= 0)), CONSTRAINT limits_organization_id_check CHECK ((organization_id <> ''::text)) ); @@ -1166,6 +1086,19 @@ CREATE SEQUENCE limits_id_seq ALTER SEQUENCE limits_id_seq OWNED BY limits.id; +CREATE TABLE notices ( + organization_id text NOT NULL, + kind text NOT NULL, + dedupe_key text DEFAULT ''::text NOT NULL, + payload jsonb DEFAULT '{}'::jsonb NOT NULL, + created_at timestamp with time zone DEFAULT now() NOT NULL, + claimed_at timestamp with time zone DEFAULT now() NOT NULL, + posted_at timestamp with time zone, + CONSTRAINT notices_kind_check CHECK ((kind = ANY (ARRAY['no_credit'::text, 'spend_hard_limit'::text, 'spend_limit'::text, 'balance_low'::text, 'balance_exhausted'::text, 'cost_anomaly'::text]))), + CONSTRAINT notices_organization_id_check CHECK ((organization_id <> ''::text)), + CONSTRAINT notices_payload_check CHECK ((jsonb_typeof(payload) = 'object'::text)) +); + CREATE TABLE opt_outs ( id text NOT NULL, customer_id text NOT NULL, @@ -1208,10 +1141,6 @@ CREATE TABLE phone_numbers ( stream_app_pk bigint, stream_route_id text, sip_trunk_id text, - bridge_uri text, - bridge_username text, - bridge_password_sealed bytea, - bridge_password_kek_version integer, attached_at timestamp with time zone, config_id text ); @@ -1351,7 +1280,7 @@ CREATE TABLE scheduled_tasks ( custom jsonb DEFAULT '{}'::jsonb NOT NULL, quiet_hours jsonb, lease_until timestamp with time zone, - claim_id text DEFAULT ''::text NOT NULL, + leased_by text DEFAULT ''::text CONSTRAINT scheduled_tasks_claim_id_not_null NOT NULL, consecutive_failures integer DEFAULT 0 NOT NULL, created_by text DEFAULT 'api'::text NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -1396,7 +1325,7 @@ CREATE TABLE simulation_runs ( error text, started_at timestamp with time zone DEFAULT now() NOT NULL, finished_at timestamp with time zone, - held_until timestamp with time zone, + lease_until timestamp with time zone, stop_requested boolean DEFAULT false NOT NULL ); @@ -1475,12 +1404,12 @@ CREATE TABLE stream_trunks ( customer_id text NOT NULL, stream_app_pk bigint, vendor text NOT NULL, - numbers text[] NOT NULL, bridge_uri text NOT NULL, bridge_username text NOT NULL, bridge_password_sealed bytea NOT NULL, bridge_password_kek_version integer NOT NULL, - created_at timestamp with time zone DEFAULT now() NOT NULL + created_at timestamp with time zone DEFAULT now() NOT NULL, + own boolean DEFAULT false NOT NULL ); CREATE TABLE telephony_suspensions ( @@ -1597,23 +1526,35 @@ ALTER TABLE ONLY price_list_entries ALTER COLUMN id SET DEFAULT nextval('price_e ALTER TABLE ONLY usage_resets ALTER COLUMN id SET DEFAULT nextval('usage_resets_id_seq'::regclass); -ALTER TABLE ONLY agent_configs - ADD CONSTRAINT agent_configs_pkey PRIMARY KEY (id); +ALTER TABLE audit_log + ADD CONSTRAINT audit_log_action_check CHECK ((action = ANY (ARRAY['created'::text, 'updated'::text, 'deleted'::text, 'synced'::text, 'cancelled'::text]))) NOT VALID; -ALTER TABLE ONLY agent_logs - ADD CONSTRAINT agent_logs_pkey PRIMARY KEY (id); +ALTER TABLE audit_log + ADD CONSTRAINT audit_log_resource_type_check CHECK ((resource_type = ANY (ARRAY['agent_config'::text, 'skill'::text, 'knowledge'::text, 'knowledge_url'::text, 'router_config'::text, 'plugin'::text, 'policy'::text, 'price_list'::text, 'end_user'::text, 'limit'::text, 'provider_key'::text]))) NOT VALID; + +ALTER TABLE audit_log + ADD CONSTRAINT audit_log_source_check CHECK ((source = ANY (ARRAY['dashboard'::text, 'cli'::text, 'sdk'::text, 'api'::text, 'manage'::text]))) NOT VALID; + +ALTER TABLE connector_audit + ADD CONSTRAINT connector_audit_action_check CHECK ((action = ANY (ARRAY['grant_created'::text, 'grant_refreshed'::text, 'grant_revoked'::text, 'proxy_call'::text, 'token_export'::text, 'tool_reapproved'::text]))) NOT VALID; -ALTER TABLE ONLY agent_plugin_clients - ADD CONSTRAINT agent_plugin_clients_pkey PRIMARY KEY (customer_id, config_id, plugin_id); +ALTER TABLE contact_map + ADD CONSTRAINT contact_map_kind_check CHECK ((kind = ANY (ARRAY['phone'::text, 'slack'::text, 'stream_user'::text, 'whatsapp'::text, 'sms'::text, 'imessage'::text]))) NOT VALID; -ALTER TABLE ONLY agent_plugin_connections - ADD CONSTRAINT agent_plugin_connections_pkey PRIMARY KEY (id); +ALTER TABLE episodes + ADD CONSTRAINT episodes_source_check CHECK ((source = ANY (ARRAY['call'::text, 'sms'::text, 'whatsapp'::text, 'slack'::text, 'imessage'::text, 'chat'::text]))) NOT VALID; -ALTER TABLE ONLY agent_plugin_event_deliveries - ADD CONSTRAINT agent_plugin_event_deliveries_pkey PRIMARY KEY (subscription_id, event_id); +ALTER TABLE knowledge_documents + ADD CONSTRAINT knowledge_documents_state_check CHECK ((state = ANY (ARRAY['pending'::text, 'indexed'::text, 'failed'::text]))) NOT VALID; -ALTER TABLE ONLY agent_plugin_event_subscriptions - ADD CONSTRAINT agent_plugin_event_subscriptions_pkey PRIMARY KEY (id); +ALTER TABLE policies + ADD CONSTRAINT policies_scope_check CHECK ((scope = ANY (ARRAY['organization'::text, 'app'::text, 'user'::text]))) NOT VALID; + +ALTER TABLE ONLY agent_configs + ADD CONSTRAINT agent_configs_pkey PRIMARY KEY (id); + +ALTER TABLE ONLY agent_logs + ADD CONSTRAINT agent_logs_pkey PRIMARY KEY (id); ALTER TABLE ONLY api_keys ADD CONSTRAINT api_keys_pkey PRIMARY KEY (id); @@ -1624,21 +1565,9 @@ ALTER TABLE ONLY app_organizations ALTER TABLE ONLY apps ADD CONSTRAINT apps_pkey PRIMARY KEY (id); -ALTER TABLE audit_log - ADD CONSTRAINT audit_log_action_check CHECK ((action = ANY (ARRAY['created'::text, 'updated'::text, 'deleted'::text, 'synced'::text, 'cancelled'::text]))) NOT VALID; - ALTER TABLE ONLY audit_log ADD CONSTRAINT audit_log_pkey PRIMARY KEY (id); -ALTER TABLE audit_log - ADD CONSTRAINT audit_log_resource_type_check CHECK ((resource_type = ANY (ARRAY['agent_config'::text, 'skill'::text, 'knowledge'::text, 'knowledge_url'::text, 'router_config'::text, 'plugin'::text, 'policy'::text, 'price_list'::text, 'end_user'::text, 'limit'::text, 'provider_key'::text]))) NOT VALID; - -ALTER TABLE audit_log - ADD CONSTRAINT audit_log_source_check CHECK ((source = ANY (ARRAY['dashboard'::text, 'cli'::text, 'sdk'::text, 'api'::text, 'manage'::text]))) NOT VALID; - -ALTER TABLE ONLY balance_notices - ADD CONSTRAINT balance_notices_pkey PRIMARY KEY (organization_id, kind, granted_micros); - ALTER TABLE ONLY business_profiles ADD CONSTRAINT business_profiles_pkey PRIMARY KEY (customer_id); @@ -1657,9 +1586,6 @@ ALTER TABLE ONLY channel_accounts ALTER TABLE ONLY channel_deliveries ADD CONSTRAINT channel_deliveries_pkey PRIMARY KEY (account_id, message_id); -ALTER TABLE ONLY channel_identities - ADD CONSTRAINT channel_identities_pkey PRIMARY KEY (id); - ALTER TABLE ONLY channel_links ADD CONSTRAINT channel_links_pkey PRIMARY KEY (code); @@ -1675,39 +1601,24 @@ ALTER TABLE ONLY channel_thread_members ALTER TABLE ONLY channel_thread_messages ADD CONSTRAINT channel_thread_messages_pkey PRIMARY KEY (channel_id, kind, message_id); -ALTER TABLE ONLY channel_thread_people - ADD CONSTRAINT channel_thread_people_pkey PRIMARY KEY (channel_id); - -ALTER TABLE ONLY channel_thread_starters - ADD CONSTRAINT channel_thread_starters_pkey PRIMARY KEY (channel_id); - ALTER TABLE ONLY channel_thread_waiting ADD CONSTRAINT channel_thread_waiting_pkey PRIMARY KEY (customer_id, connector_id, provider_unit_id, thread_key, provider_message_id); ALTER TABLE ONLY channel_threads ADD CONSTRAINT channel_threads_pkey PRIMARY KEY (channel_id); -ALTER TABLE ONLY chat_channel_turns - ADD CONSTRAINT chat_channel_turns_pkey PRIMARY KEY (stream_app_pk, cid); +ALTER TABLE ONLY channel_turns + ADD CONSTRAINT channel_turns_pkey PRIMARY KEY (stream_app_pk, cid); ALTER TABLE ONLY chat_inbound ADD CONSTRAINT chat_inbound_pkey PRIMARY KEY (seq); ALTER TABLE ONLY chat_inbound - ADD CONSTRAINT chat_inbound_stream_app_message_id_key UNIQUE (stream_app, message_id); - -ALTER TABLE ONLY connection_event_deliveries - ADD CONSTRAINT connection_event_deliveries_pkey PRIMARY KEY (subscription_id, event_id); + ADD CONSTRAINT chat_inbound_stream_app_pk_message_id_key UNIQUE (stream_app_pk, message_id); ALTER TABLE ONLY connection_event_subscriptions ADD CONSTRAINT connection_event_subscriptions_pkey PRIMARY KEY (id); -ALTER TABLE connector_audit - ADD CONSTRAINT connector_audit_action_check CHECK ((action = ANY (ARRAY['grant_created'::text, 'grant_refreshed'::text, 'grant_revoked'::text, 'proxy_call'::text, 'token_export'::text, 'tool_reapproved'::text]))) NOT VALID; - -ALTER TABLE ONLY connector_audit_credentials - ADD CONSTRAINT connector_audit_credentials_pkey PRIMARY KEY (audit_id); - ALTER TABLE ONLY connector_audit ADD CONSTRAINT connector_audit_pkey PRIMARY KEY (id); @@ -1723,12 +1634,6 @@ ALTER TABLE ONLY connector_broken_revisions ALTER TABLE ONLY connector_config_tokens ADD CONSTRAINT connector_config_tokens_pkey PRIMARY KEY (customer_id, connector_id); -ALTER TABLE ONLY connector_connection_clients - ADD CONSTRAINT connector_connection_clients_pkey PRIMARY KEY (connection_id); - -ALTER TABLE ONLY connector_connection_validations - ADD CONSTRAINT connector_connection_validations_pkey PRIMARY KEY (connection_id); - ALTER TABLE ONLY connector_connections ADD CONSTRAINT connector_connections_pkey PRIMARY KEY (id); @@ -1741,9 +1646,6 @@ ALTER TABLE ONLY connector_event_deliveries ALTER TABLE ONLY connector_event_destinations ADD CONSTRAINT connector_event_destinations_pkey PRIMARY KEY (id); -ALTER TABLE ONLY connector_invocation_arguments - ADD CONSTRAINT connector_invocation_arguments_pkey PRIMARY KEY (invocation_id); - ALTER TABLE ONLY connector_invocations ADD CONSTRAINT connector_invocations_pkey PRIMARY KEY (id); @@ -1753,26 +1655,15 @@ ALTER TABLE ONLY connector_oauth_clients ALTER TABLE ONLY connector_tool_pins ADD CONSTRAINT connector_tool_pins_pkey PRIMARY KEY (connection_id, tool_name); -ALTER TABLE contact_map - ADD CONSTRAINT contact_map_kind_check CHECK ((kind = ANY (ARRAY['phone'::text, 'slack'::text, 'stream_user'::text]))) NOT VALID; - ALTER TABLE ONLY contact_map ADD CONSTRAINT contact_map_pkey PRIMARY KEY (id); -ALTER TABLE ONLY cost_anomaly_notices - ADD CONSTRAINT cost_anomaly_notices_pkey PRIMARY KEY (organization_id, day); - ALTER TABLE ONLY custom_models ADD CONSTRAINT custom_models_pkey PRIMARY KEY (id); ALTER TABLE ONLY customer_activity ADD CONSTRAINT customer_activity_pkey PRIMARY KEY (app_id, area, client, day); -ALTER TABLE ONLY data_change_starts - ADD CONSTRAINT data_change_starts_pkey PRIMARY KEY (one); - -INSERT INTO data_change_starts DEFAULT VALUES; - ALTER TABLE ONLY data_move_cursors ADD CONSTRAINT data_move_cursors_pkey PRIMARY KEY (customer_id, source); @@ -1782,18 +1673,9 @@ ALTER TABLE ONLY dlc_review_logs ALTER TABLE ONLY dlc_use_cases ADD CONSTRAINT dlc_use_cases_pkey PRIMARY KEY (id); -ALTER TABLE ONLY episode_activity - ADD CONSTRAINT episode_activity_pkey PRIMARY KEY (episode_id); - ALTER TABLE ONLY episodes ADD CONSTRAINT episodes_pkey PRIMARY KEY (id); -ALTER TABLE episodes - ADD CONSTRAINT episodes_source_check CHECK ((source = ANY (ARRAY['call'::text, 'sms'::text, 'whatsapp'::text, 'slack'::text, 'imessage'::text, 'chat'::text]))) NOT VALID; - -ALTER TABLE ONLY hook_deliveries - ADD CONSTRAINT hook_deliveries_pkey PRIMARY KEY (key); - ALTER TABLE ONLY image_jobs ADD CONSTRAINT image_jobs_pkey PRIMARY KEY (id); @@ -1803,9 +1685,6 @@ ALTER TABLE ONLY image_jobs ALTER TABLE ONLY knowledge_documents ADD CONSTRAINT knowledge_documents_pkey PRIMARY KEY (id); -ALTER TABLE knowledge_documents - ADD CONSTRAINT knowledge_documents_state_check CHECK ((state = ANY (ARRAY['pending'::text, 'indexed'::text, 'failed'::text]))) NOT VALID; - ALTER TABLE ONLY knowledge_namespaces ADD CONSTRAINT knowledge_namespaces_pkey PRIMARY KEY (customer_id, namespace); @@ -1821,9 +1700,6 @@ ALTER TABLE ONLY limit_grant_uses ALTER TABLE ONLY limit_grants ADD CONSTRAINT limit_grants_pkey PRIMARY KEY (id); -ALTER TABLE ONLY limit_notices - ADD CONSTRAINT limit_notices_pkey PRIMARY KEY (organization_id, kind); - ALTER TABLE ONLY limits ADD CONSTRAINT limits_pkey PRIMARY KEY (id); @@ -1842,9 +1718,6 @@ ALTER TABLE ONLY phone_numbers ALTER TABLE ONLY policies ADD CONSTRAINT policies_pkey PRIMARY KEY (scope, scope_id); -ALTER TABLE policies - ADD CONSTRAINT policies_scope_check CHECK ((scope = ANY (ARRAY['organization'::text, 'app'::text, 'user'::text]))) NOT VALID; - ALTER TABLE ONLY price_changes ADD CONSTRAINT price_changes_idempotency_key_key UNIQUE (idempotency_key); @@ -1934,16 +1807,6 @@ CREATE INDEX agent_logs_error_order ON agent_logs USING btree (customer_id, seve CREATE UNIQUE INDEX agent_logs_source_idx ON agent_logs USING btree (customer_id, source_id) WHERE (source_id IS NOT NULL); -CREATE INDEX agent_plugin_connections_config_idx ON agent_plugin_connections USING btree (customer_id, config_id) WHERE (deleted_at IS NULL); - -CREATE UNIQUE INDEX agent_plugin_connections_one_idx ON agent_plugin_connections USING btree (config_id, plugin_id, user_id) WHERE (deleted_at IS NULL); - -CREATE UNIQUE INDEX agent_plugin_connections_state_idx ON agent_plugin_connections USING btree (oauth_state) WHERE ((deleted_at IS NULL) AND (oauth_state <> ''::text)); - -CREATE UNIQUE INDEX agent_plugin_event_subscriptions_one_idx ON agent_plugin_event_subscriptions USING btree (config_id, plugin_id, user_id, key) WHERE (deleted_at IS NULL); - -CREATE UNIQUE INDEX agent_plugin_event_subscriptions_token_idx ON agent_plugin_event_subscriptions USING btree (token); - CREATE INDEX api_keys_app_idx ON api_keys USING btree (app_id, created_at DESC); CREATE INDEX app_organizations_organization_idx ON app_organizations USING btree (organization_id); @@ -1964,7 +1827,7 @@ CREATE INDEX campaign_contacts_campaign_idx ON campaign_contacts USING btree (ca CREATE INDEX campaign_contacts_due_idx ON campaign_contacts USING btree (campaign_id, stage, next_attempt_at); -CREATE INDEX campaign_contacts_lease_idx ON campaign_contacts USING btree (leased_until) WHERE (stage = 'in_progress'::text); +CREATE INDEX campaign_contacts_lease_idx ON campaign_contacts USING btree (lease_until) WHERE (stage = 'in_progress'::text); CREATE UNIQUE INDEX campaign_contacts_number_idx ON campaign_contacts USING btree (campaign_id, to_number) WHERE (reason IS DISTINCT FROM 'duplicate'::text); @@ -1978,8 +1841,6 @@ CREATE UNIQUE INDEX channel_accounts_token_idx ON channel_accounts USING btree ( CREATE INDEX channel_deliveries_from_idx ON channel_deliveries USING btree (account_id, from_address, received_at DESC); -CREATE UNIQUE INDEX channel_identities_address_idx ON channel_identities USING btree (customer_id, config_id, kind, address); - CREATE INDEX channel_thread_inbound_finished ON channel_thread_inbound USING btree (finished_at) WHERE (state <> 'queued'::text); CREATE INDEX channel_thread_inbound_queued ON channel_thread_inbound USING btree (channel_id, seq) WHERE (state = 'queued'::text); @@ -2016,14 +1877,12 @@ CREATE INDEX connector_invocations_connection_idx ON connector_invocations USING CREATE UNIQUE INDEX connector_oauth_clients_provider_app ON connector_oauth_clients USING btree (connector_id, provider_app_id) WHERE (provider_app_id <> ''::text); -CREATE UNIQUE INDEX contact_map_address ON contact_map USING btree (customer_id, agent_config_id, kind, address); +CREATE UNIQUE INDEX contact_map_address ON contact_map USING btree (customer_id, config_id, kind, address); -CREATE INDEX contact_map_conversation ON contact_map USING btree (customer_id, agent_config_id, conversation_id); +CREATE INDEX contact_map_conversation ON contact_map USING btree (customer_id, config_id, conversation_id); CREATE INDEX contact_map_retired ON contact_map USING btree (customer_id, regexp_replace(address, '^retired:[^:]*:'::text, ''::text)) WHERE (address ~~ 'retired:%'::text); -CREATE INDEX cost_anomaly_notices_unposted ON cost_anomaly_notices USING btree (claimed_at) WHERE (posted_at IS NULL); - CREATE INDEX custom_models_customer_idx ON custom_models USING btree (customer_id, created_at DESC, id DESC); CREATE UNIQUE INDEX custom_models_name_idx ON custom_models USING btree (customer_id, name); @@ -2038,8 +1897,6 @@ CREATE UNIQUE INDEX dlc_use_cases_default_idx ON dlc_use_cases USING btree (cust CREATE INDEX dlc_use_cases_status_idx ON dlc_use_cases USING btree (status, updated_at, id); -CREATE INDEX episode_activity_summary_lease ON episode_activity USING btree (summary_lease_until) WHERE (summary_lease_until IS NOT NULL); - CREATE UNIQUE INDEX episodes_call_session ON episodes USING btree (session_id); CREATE INDEX episodes_contact ON episodes USING btree (contact_id, started_at DESC); @@ -2050,10 +1907,6 @@ CREATE UNIQUE INDEX episodes_open_thread ON episodes USING btree (customer_id, t CREATE INDEX episodes_thread ON episodes USING btree (customer_id, thread_channel, started_at); -CREATE INDEX hook_deliveries_seen_at ON hook_deliveries USING btree (seen_at); - -CREATE INDEX image_jobs_due ON image_jobs USING btree (next_attempt_at) WHERE (state = 'queued'::text); - CREATE UNIQUE INDEX knowledge_documents_source_idx ON knowledge_documents USING btree (customer_id, namespace, source); CREATE INDEX knowledge_urls_namespace_idx ON knowledge_urls USING btree (customer_id, namespace) WHERE (deleted_at IS NULL); @@ -2064,8 +1917,6 @@ CREATE INDEX limit_grant_uses_usage_idx ON limit_grant_uses USING btree (usage_i CREATE INDEX limit_grants_live_idx ON limit_grants USING btree (organization_id) WHERE (revoked_at IS NULL); -CREATE INDEX limit_notices_unposted ON limit_notices USING btree (claimed_at) WHERE (posted_at IS NULL); - CREATE UNIQUE INDEX limits_one_per_level ON limits USING btree (organization_id, subject, level, "interval", app_id, api_key, user_id, category); CREATE INDEX opt_outs_customer_idx ON opt_outs USING btree (customer_id, created_at DESC, id DESC); @@ -2116,7 +1967,7 @@ CREATE INDEX simulation_cases_run_idx ON simulation_cases USING btree (run_id, v CREATE INDEX simulation_runs_customer_idx ON simulation_runs USING btree (customer_id, started_at DESC); -CREATE INDEX simulation_runs_held_idx ON simulation_runs USING btree (held_until) WHERE (state = 'running'::text); +CREATE INDEX simulation_runs_lease_idx ON simulation_runs USING btree (lease_until) WHERE (state = 'running'::text); CREATE INDEX simulation_runs_simulation_idx ON simulation_runs USING btree (simulation_id, started_at DESC); @@ -2144,6 +1995,38 @@ CREATE INDEX voices_customer_idx ON voices USING btree (customer_id, created_at CREATE UNIQUE INDEX voices_name_idx ON voices USING btree (customer_id, name) WHERE (deleted_at IS NULL); +ALTER TABLE ONLY notices + ADD CONSTRAINT notices_pkey PRIMARY KEY (organization_id, kind, dedupe_key); + +CREATE INDEX notices_unposted ON notices USING btree (claimed_at) WHERE (posted_at IS NULL); + +CREATE INDEX knowledge_urls_due_idx ON knowledge_urls USING btree (updated_at) WHERE ((deleted_at IS NULL) AND (refresh_hours > 0) AND (state <> 'pending'::text)); + +ALTER TABLE ONLY deliveries_seen + ADD CONSTRAINT deliveries_seen_pkey PRIMARY KEY (scope, key); + +CREATE INDEX deliveries_seen_seen_at ON deliveries_seen USING btree (seen_at); + +CREATE INDEX episodes_lease ON episodes USING btree (lease_until) WHERE (lease_until IS NOT NULL); + +CREATE INDEX phone_numbers_trunk_idx ON phone_numbers USING btree (customer_id, stream_trunk_id) WHERE (released_at IS NULL); + +CREATE INDEX dlc_use_cases_vendor_campaign_idx ON dlc_use_cases USING btree (vendor, vendor_campaign_id) WHERE (vendor_campaign_id <> ''::text); + +CREATE INDEX image_jobs_undecided ON image_jobs USING btree (next_attempt_at, id) WHERE ((state = 'queued'::text) AND (message = ''::text)); + +CREATE INDEX image_jobs_decided ON image_jobs USING btree (next_attempt_at, id) WHERE ((state = 'queued'::text) AND (message <> ''::text)); + +ALTER TABLE ONLY channel_link_failures + ADD CONSTRAINT channel_link_failures_pkey PRIMARY KEY (account_id, from_address, window_start); + +CREATE INDEX channel_link_failures_window_idx ON channel_link_failures USING btree (window_start); + +CREATE INDEX voice_bindings_external_idx ON voice_bindings USING btree (provider, external_id); + +ALTER TABLE ONLY activity_digests + ADD CONSTRAINT activity_digests_pkey PRIMARY KEY (day); + CREATE TRIGGER price_changes_guard BEFORE DELETE OR UPDATE ON price_changes FOR EACH ROW EXECUTE FUNCTION price_changes_guard(); CREATE TRIGGER price_entries_guard BEFORE INSERT OR DELETE OR UPDATE ON price_list_entries FOR EACH ROW EXECUTE FUNCTION price_entries_guard(); @@ -2172,33 +2055,12 @@ ALTER TABLE ONLY channel_thread_members ALTER TABLE ONLY channel_thread_messages ADD CONSTRAINT channel_thread_messages_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES channel_threads(channel_id); -ALTER TABLE ONLY channel_thread_people - ADD CONSTRAINT channel_thread_people_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES channel_threads(channel_id) ON DELETE CASCADE; - -ALTER TABLE ONLY channel_thread_starters - ADD CONSTRAINT channel_thread_starters_channel_id_fkey FOREIGN KEY (channel_id) REFERENCES channel_threads(channel_id) ON DELETE CASCADE; - -ALTER TABLE ONLY connection_event_deliveries - ADD CONSTRAINT connection_event_deliveries_subscription_id_fkey FOREIGN KEY (subscription_id) REFERENCES connection_event_subscriptions(id) ON DELETE CASCADE; - -ALTER TABLE ONLY connector_audit_credentials - ADD CONSTRAINT connector_audit_credentials_audit_id_fkey FOREIGN KEY (audit_id) REFERENCES connector_audit(id) ON DELETE CASCADE; - ALTER TABLE ONLY connector_authorization_attempts ADD CONSTRAINT connector_authorization_attempts_connection_id_fkey FOREIGN KEY (connection_id) REFERENCES connector_connections(id); -ALTER TABLE ONLY connector_connection_clients - ADD CONSTRAINT connector_connection_clients_connection_id_fkey FOREIGN KEY (connection_id) REFERENCES connector_connections(id) ON DELETE CASCADE; - -ALTER TABLE ONLY connector_connection_validations - ADD CONSTRAINT connector_connection_validations_connection_id_fkey FOREIGN KEY (connection_id) REFERENCES connector_connections(id) ON DELETE CASCADE; - ALTER TABLE ONLY connector_event_deliveries ADD CONSTRAINT connector_event_deliveries_destination_id_fkey FOREIGN KEY (destination_id) REFERENCES connector_event_destinations(id) ON DELETE CASCADE; -ALTER TABLE ONLY connector_invocation_arguments - ADD CONSTRAINT connector_invocation_arguments_invocation_id_fkey FOREIGN KEY (invocation_id) REFERENCES connector_invocations(id) ON DELETE CASCADE; - ALTER TABLE ONLY connector_invocations ADD CONSTRAINT connector_invocations_connection_id_fkey FOREIGN KEY (connection_id) REFERENCES connector_connections(id) ON DELETE CASCADE; @@ -2208,9 +2070,6 @@ ALTER TABLE ONLY connector_tool_pins ALTER TABLE ONLY dlc_review_logs ADD CONSTRAINT dlc_review_logs_use_case_id_fkey FOREIGN KEY (use_case_id) REFERENCES dlc_use_cases(id) ON DELETE CASCADE; -ALTER TABLE ONLY episode_activity - ADD CONSTRAINT episode_activity_episode_id_fkey FOREIGN KEY (episode_id) REFERENCES episodes(id) ON DELETE CASCADE; - ALTER TABLE ONLY episodes ADD CONSTRAINT episodes_contact_id_fkey FOREIGN KEY (contact_id) REFERENCES contact_map(id); @@ -2242,5 +2101,5 @@ ALTER TABLE ONLY voice_samples ADD CONSTRAINT voice_samples_voice_id_fkey FOREIGN KEY (voice_id) REFERENCES voices(id) ON DELETE CASCADE; -- +goose Down --- A baseline is not undone. +-- The initial migration is not undone. SELECT 1; diff --git a/acceleration/migrations/global/20270111000000_notices.sql b/acceleration/migrations/global/20270111000000_notices.sql deleted file mode 100644 index ed94a9ae26..0000000000 --- a/acceleration/migrations/global/20270111000000_notices.sql +++ /dev/null @@ -1,93 +0,0 @@ --- +goose Up - --- One table for every notice an organization is sent once (store.Notice): the first router to --- write an organization's row of a kind and key is the one that sends it. dedupe_key is what --- makes a kind's notice due again: nothing for a money limit, which is noticed once ever, the --- credit granted for a balance warning, the UTC day for a cost anomaly. payload is the kind's --- own fields. A notice queued as webhook deliveries is posted as it is written. -CREATE TABLE notices ( - organization_id TEXT NOT NULL CHECK (organization_id <> ''), - kind TEXT NOT NULL CHECK (kind IN ( - 'no_credit', 'spend_hard_limit', 'spend_limit', 'balance_low', 'balance_exhausted', 'cost_anomaly')), - dedupe_key TEXT NOT NULL DEFAULT '', - payload JSONB NOT NULL DEFAULT '{}' CHECK (jsonb_typeof(payload) = 'object'), - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), - posted_at TIMESTAMPTZ, - PRIMARY KEY (organization_id, kind, dedupe_key) -); - -CREATE INDEX notices_unposted ON notices (claimed_at) WHERE posted_at IS NULL; - -INSERT INTO notices (organization_id, kind, dedupe_key, payload, created_at, claimed_at, posted_at) -SELECT organization_id, kind, '', - jsonb_build_object('app_id', app_id, 'tier', tier, 'enforced', enforced, 'message', message), - created_at, claimed_at, posted_at -FROM limit_notices -UNION ALL -SELECT organization_id, kind, granted_micros::text, - jsonb_build_object('balance_micros', balance_micros, 'threshold_micros', threshold_micros), - created_at, created_at, created_at -FROM balance_notices -UNION ALL -SELECT organization_id, 'cost_anomaly', to_char(day, 'YYYY-MM-DD'), - jsonb_build_object('spent_micros', spent_micros, 'baseline_micros', baseline_micros), - created_at, claimed_at, posted_at -FROM cost_anomaly_notices; - -DROP TABLE limit_notices, balance_notices, cost_anomaly_notices; - --- +goose Down -CREATE TABLE limit_notices ( - organization_id TEXT NOT NULL, - kind TEXT NOT NULL CHECK (kind = ANY (ARRAY['no_credit', 'spend_hard_limit', 'spend_limit'])), - app_id TEXT NOT NULL DEFAULT '', - tier TEXT NOT NULL DEFAULT '', - enforced BOOLEAN NOT NULL, - message TEXT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), - posted_at TIMESTAMPTZ, - PRIMARY KEY (organization_id, kind) -); -CREATE INDEX limit_notices_unposted ON limit_notices (claimed_at) WHERE posted_at IS NULL; - -CREATE TABLE balance_notices ( - organization_id TEXT NOT NULL, - kind TEXT NOT NULL CHECK (kind = ANY (ARRAY['balance_low', 'balance_exhausted'])), - granted_micros BIGINT NOT NULL, - balance_micros BIGINT NOT NULL, - threshold_micros BIGINT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - PRIMARY KEY (organization_id, kind, granted_micros) -); - -CREATE TABLE cost_anomaly_notices ( - organization_id TEXT NOT NULL, - day DATE NOT NULL, - spent_micros BIGINT NOT NULL, - baseline_micros BIGINT NOT NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), - posted_at TIMESTAMPTZ, - PRIMARY KEY (organization_id, day) -); -CREATE INDEX cost_anomaly_notices_unposted ON cost_anomaly_notices (claimed_at) WHERE posted_at IS NULL; - -INSERT INTO limit_notices (organization_id, kind, app_id, tier, enforced, message, created_at, claimed_at, posted_at) -SELECT organization_id, kind, COALESCE(payload->>'app_id', ''), COALESCE(payload->>'tier', ''), - COALESCE((payload->>'enforced')::boolean, false), COALESCE(payload->>'message', ''), - created_at, claimed_at, posted_at -FROM notices WHERE kind IN ('no_credit', 'spend_hard_limit', 'spend_limit'); - -INSERT INTO balance_notices (organization_id, kind, granted_micros, balance_micros, threshold_micros, created_at) -SELECT organization_id, kind, dedupe_key::bigint, (payload->>'balance_micros')::bigint, (payload->>'threshold_micros')::bigint, - created_at -FROM notices WHERE kind IN ('balance_low', 'balance_exhausted'); - -INSERT INTO cost_anomaly_notices (organization_id, day, spent_micros, baseline_micros, created_at, claimed_at, posted_at) -SELECT organization_id, dedupe_key::date, (payload->>'spent_micros')::bigint, (payload->>'baseline_micros')::bigint, - created_at, claimed_at, posted_at -FROM notices WHERE kind = 'cost_anomaly'; - -DROP TABLE notices; diff --git a/acceleration/migrations/global/20270112000000_knowledge_urls_due_idx.sql b/acceleration/migrations/global/20270112000000_knowledge_urls_due_idx.sql deleted file mode 100644 index 3ee5c0edb6..0000000000 --- a/acceleration/migrations/global/20270112000000_knowledge_urls_due_idx.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up - --- KnowledgeURLs.SelectDue reads every customer's pages oldest first; without this it reads --- the whole table. -CREATE INDEX IF NOT EXISTS knowledge_urls_due_idx ON knowledge_urls (updated_at) - WHERE deleted_at IS NULL AND refresh_hours > 0 AND state <> 'pending'; diff --git a/acceleration/migrations/global/20270112000100_drop_plugin_tables.sql b/acceleration/migrations/global/20270112000100_drop_plugin_tables.sql deleted file mode 100644 index a408838d6f..0000000000 --- a/acceleration/migrations/global/20270112000100_drop_plugin_tables.sql +++ /dev/null @@ -1,18 +0,0 @@ --- +goose Up - --- Plugins were replaced by connectors. No release reads these tables, or the config columns --- that named plugins, plugin events and MCP servers: the model never mapped the columns and an --- insert left them at their default. An import from an older release skips the tables' rows --- (store.retiredTables). The lock waits at most 5 s behind a running query, past which the --- migration fails and the router's next start tries again. -SET LOCAL lock_timeout = '5s'; - -DROP TABLE IF EXISTS agent_plugin_event_deliveries; -DROP TABLE IF EXISTS agent_plugin_event_subscriptions; -DROP TABLE IF EXISTS agent_plugin_connections; -DROP TABLE IF EXISTS agent_plugin_clients; - -ALTER TABLE agent_configs - DROP COLUMN IF EXISTS plugins, - DROP COLUMN IF EXISTS plugin_events, - DROP COLUMN IF EXISTS mcp_servers; diff --git a/acceleration/migrations/global/20270112000200_simulation_run_lease.sql b/acceleration/migrations/global/20270112000200_simulation_run_lease.sql deleted file mode 100644 index f992cf92c8..0000000000 --- a/acceleration/migrations/global/20270112000200_simulation_run_lease.sql +++ /dev/null @@ -1,17 +0,0 @@ --- +goose Up - --- A run's router holds it until lease_until, as a queue row is held, so the column is named --- as the queue's is. A router of the release before reads held_until and fails until it is --- replaced; a run it was having is written off by the next one's Abandon. An import from an --- older release carries held_until over (store.renameImported). Run again on a database that --- has it already, as an adopted one does, it changes nothing. --- +goose StatementBegin -DO $$ -BEGIN - IF EXISTS (SELECT 1 FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = 'simulation_runs' AND column_name = 'held_until') THEN - ALTER TABLE simulation_runs RENAME COLUMN held_until TO lease_until; - END IF; -END $$; --- +goose StatementEnd -ALTER INDEX IF EXISTS simulation_runs_held_idx RENAME TO simulation_runs_lease_idx; diff --git a/acceleration/migrations/global/20270112000300_agent_config_groups.sql b/acceleration/migrations/global/20270112000300_agent_config_groups.sql deleted file mode 100644 index fc3839de91..0000000000 --- a/acceleration/migrations/global/20270112000300_agent_config_groups.sql +++ /dev/null @@ -1,34 +0,0 @@ --- +goose Up - --- agent_configs names its columns as AgentConfig groups them: each group's columns share its --- name as their prefix (sandbox_, video_, dispatch_, episode_cards_, channels_), and the model --- columns keep their own names. A router of the release before reads the old names and fails --- until it is replaced. An import from an older release carries the old names over --- (store.renameImported). Run again on a database that has them already, as an adopted one --- does, it changes nothing. The lock waits at most 5 s behind a running query, past which the --- migration fails and the router's next start tries again. -SET LOCAL lock_timeout = '5s'; - --- +goose StatementBegin -DO $$ -DECLARE - renamed TEXT[][] := ARRAY[ - ARRAY['sandbox', 'sandbox_provider'], - ARRAY['episode_cards', 'episode_cards_on'], - ARRAY['channels', 'channels_lines'], - ARRAY['chat_channels', 'channels_chat']]; - pair TEXT[]; -BEGIN - FOREACH pair SLICE 1 IN ARRAY renamed LOOP - IF EXISTS (SELECT 1 FROM information_schema.columns - WHERE table_schema = current_schema() AND table_name = 'agent_configs' AND column_name = pair[1]) THEN - EXECUTE format('ALTER TABLE agent_configs RENAME COLUMN %I TO %I', pair[1], pair[2]); - END IF; - END LOOP; -END $$; --- +goose StatementEnd - --- Tool groups and connector bindings replaced these, and this release reads neither. -ALTER TABLE agent_configs - DROP COLUMN IF EXISTS progressive_tools, - DROP COLUMN IF EXISTS tool_output_retention; diff --git a/acceleration/migrations/global/20270113000000_connector_side_tables_folded.sql b/acceleration/migrations/global/20270113000000_connector_side_tables_folded.sql deleted file mode 100644 index ec9431ebb5..0000000000 --- a/acceleration/migrations/global/20270113000000_connector_side_tables_folded.sql +++ /dev/null @@ -1,121 +0,0 @@ --- +goose Up - --- Each of these tables held one row per row of its parent, read with the parent every time it --- was read. As columns they cost no second read or write. The client and the last validation --- are still read without unsealing the credentials, and the audit credential and the argument --- shapes are a few names and fingerprints, not a payload worth keeping apart. - -ALTER TABLE connector_connections - ADD COLUMN client_registration text NOT NULL DEFAULT '', - ADD COLUMN client_id text NOT NULL DEFAULT '', - ADD COLUMN client_updated_at timestamp with time zone, - ADD COLUMN validation_revision integer NOT NULL DEFAULT 0, - ADD COLUMN validation_status text NOT NULL DEFAULT '', - ADD COLUMN validation_code text NOT NULL DEFAULT '', - ADD COLUMN validation_error text NOT NULL DEFAULT '', - ADD COLUMN validation_checked_at timestamp with time zone; - -ALTER TABLE connector_audit ADD COLUMN credential jsonb; - -ALTER TABLE connector_invocations ADD COLUMN arguments jsonb; - -UPDATE connector_connections AS cc -SET client_registration = ccc.registration, client_id = ccc.client_id, client_updated_at = ccc.updated_at -FROM connector_connection_clients AS ccc -WHERE ccc.connection_id = cc.id; - -UPDATE connector_connections AS cc -SET validation_revision = ccv.revision, validation_status = ccv.status, validation_code = ccv.code, - validation_error = ccv.error, validation_checked_at = ccv.checked_at -FROM connector_connection_validations AS ccv -WHERE ccv.connection_id = cc.id; - --- The keys are store.ConnectorAuditCredential's; an expiry the provider did not give is left out. -UPDATE connector_audit AS ca -SET credential = jsonb_strip_nulls(jsonb_build_object( - 'access_fingerprint', cac.access_fingerprint, - 'previous_access_fingerprint', cac.previous_access_fingerprint, - 'refresh_fingerprint', cac.refresh_fingerprint, - 'previous_refresh_fingerprint', cac.previous_refresh_fingerprint, - 'rotated', cac.rotated, - 'access_expires_at', cac.access_expires_at, - 'refresh_expires_at', cac.refresh_expires_at)) -FROM connector_audit_credentials AS cac -WHERE cac.audit_id = ca.id; - -UPDATE connector_invocations AS ci -SET arguments = cia.shape -FROM connector_invocation_arguments AS cia -WHERE cia.invocation_id = ci.id; - -DROP TABLE connector_connection_clients; -DROP TABLE connector_connection_validations; -DROP TABLE connector_audit_credentials; -DROP TABLE connector_invocation_arguments; - --- +goose Down - -CREATE TABLE connector_connection_clients ( - connection_id text PRIMARY KEY REFERENCES connector_connections(id) ON DELETE CASCADE, - registration text NOT NULL, - client_id text NOT NULL, - updated_at timestamp with time zone NOT NULL -); - -CREATE TABLE connector_connection_validations ( - connection_id text PRIMARY KEY REFERENCES connector_connections(id) ON DELETE CASCADE, - revision integer NOT NULL, - status text NOT NULL, - code text NOT NULL DEFAULT '', - error text NOT NULL DEFAULT '', - checked_at timestamp with time zone NOT NULL -); - -CREATE TABLE connector_audit_credentials ( - audit_id text PRIMARY KEY REFERENCES connector_audit(id) ON DELETE CASCADE, - access_fingerprint text NOT NULL DEFAULT '', - previous_access_fingerprint text NOT NULL DEFAULT '', - refresh_fingerprint text NOT NULL DEFAULT '', - previous_refresh_fingerprint text NOT NULL DEFAULT '', - rotated boolean NOT NULL DEFAULT false, - access_expires_at timestamp with time zone, - refresh_expires_at timestamp with time zone -); - -CREATE TABLE connector_invocation_arguments ( - invocation_id text PRIMARY KEY REFERENCES connector_invocations(id) ON DELETE CASCADE, - shape jsonb NOT NULL -); - -INSERT INTO connector_connection_clients (connection_id, registration, client_id, updated_at) -SELECT id, client_registration, client_id, client_updated_at FROM connector_connections -WHERE client_updated_at IS NOT NULL; - -INSERT INTO connector_connection_validations (connection_id, revision, status, code, error, checked_at) -SELECT id, validation_revision, validation_status, validation_code, validation_error, validation_checked_at -FROM connector_connections WHERE validation_checked_at IS NOT NULL; - -INSERT INTO connector_audit_credentials (audit_id, access_fingerprint, previous_access_fingerprint, - refresh_fingerprint, previous_refresh_fingerprint, rotated, access_expires_at, refresh_expires_at) -SELECT id, coalesce(credential ->> 'access_fingerprint', ''), coalesce(credential ->> 'previous_access_fingerprint', ''), - coalesce(credential ->> 'refresh_fingerprint', ''), coalesce(credential ->> 'previous_refresh_fingerprint', ''), - coalesce((credential ->> 'rotated')::boolean, false), (credential ->> 'access_expires_at')::timestamptz, - (credential ->> 'refresh_expires_at')::timestamptz -FROM connector_audit WHERE credential IS NOT NULL; - -INSERT INTO connector_invocation_arguments (invocation_id, shape) -SELECT id, arguments FROM connector_invocations WHERE arguments IS NOT NULL; - -ALTER TABLE connector_connections - DROP COLUMN client_registration, - DROP COLUMN client_id, - DROP COLUMN client_updated_at, - DROP COLUMN validation_revision, - DROP COLUMN validation_status, - DROP COLUMN validation_code, - DROP COLUMN validation_error, - DROP COLUMN validation_checked_at; - -ALTER TABLE connector_audit DROP COLUMN credential; - -ALTER TABLE connector_invocations DROP COLUMN arguments; diff --git a/acceleration/migrations/global/20270113000001_deliveries_seen.sql b/acceleration/migrations/global/20270113000001_deliveries_seen.sql deleted file mode 100644 index 58558abdf2..0000000000 --- a/acceleration/migrations/global/20270113000001_deliveries_seen.sql +++ /dev/null @@ -1,51 +0,0 @@ --- +goose Up - --- hook_deliveries and connection_event_deliveries only made a second insert of one delivery --- fail. One table does that for both, a scope apart, and one pruner forgets both after a day. - -CREATE TABLE deliveries_seen ( - scope text NOT NULL, - key text NOT NULL, - seen_at timestamp with time zone NOT NULL DEFAULT now(), - PRIMARY KEY (scope, key), - CONSTRAINT deliveries_seen_key_check CHECK (key <> '') -); - -CREATE INDEX deliveries_seen_seen_at ON deliveries_seen (seen_at); - --- A subscription id is hex, so the first slash of a connection event's key ends it --- (store.ConnectionEventKey). -INSERT INTO deliveries_seen (scope, key, seen_at) -SELECT 'hook', key, seen_at FROM hook_deliveries -UNION ALL -SELECT 'connection_event', subscription_id || '/' || event_id, received_at FROM connection_event_deliveries; - -DROP TABLE hook_deliveries; -DROP TABLE connection_event_deliveries; - --- +goose Down - -CREATE TABLE hook_deliveries ( - key text PRIMARY KEY, - seen_at timestamp with time zone NOT NULL DEFAULT now() -); - -CREATE INDEX hook_deliveries_seen_at ON hook_deliveries (seen_at); - -CREATE TABLE connection_event_deliveries ( - subscription_id text NOT NULL REFERENCES connection_event_subscriptions(id) ON DELETE CASCADE, - event_id text NOT NULL, - received_at timestamp with time zone NOT NULL, - PRIMARY KEY (subscription_id, event_id) -); - -INSERT INTO hook_deliveries (key, seen_at) -SELECT key, seen_at FROM deliveries_seen WHERE scope = 'hook'; - -INSERT INTO connection_event_deliveries (subscription_id, event_id, received_at) -SELECT split_part(seen.key, '/', 1), substr(seen.key, strpos(seen.key, '/') + 1), seen.seen_at -FROM deliveries_seen AS seen -JOIN connection_event_subscriptions AS subscription ON subscription.id = split_part(seen.key, '/', 1) -WHERE seen.scope = 'connection_event'; - -DROP TABLE deliveries_seen; diff --git a/acceleration/migrations/global/20270113000002_connection_event_subscription_attempts.sql b/acceleration/migrations/global/20270113000002_connection_event_subscription_attempts.sql deleted file mode 100644 index 30b7e477d8..0000000000 --- a/acceleration/migrations/global/20270113000002_connection_event_subscription_attempts.sql +++ /dev/null @@ -1,12 +0,0 @@ --- +goose Up - --- A claim counts its attempt here, and a worker's write names the count it claimed, so a --- worker whose lease ran out does not overwrite the one that took the subscription after it. --- failures stays the streak of the server's refusals, which the retry wait grows with. -ALTER TABLE connection_event_subscriptions - ADD COLUMN attempts integer NOT NULL DEFAULT 0, - ADD CONSTRAINT connection_event_subscriptions_attempts_check CHECK (attempts >= 0); - --- +goose Down - -ALTER TABLE connection_event_subscriptions DROP COLUMN attempts; diff --git a/acceleration/migrations/global/20270115000100_contact_map_channel_identities.sql b/acceleration/migrations/global/20270115000100_contact_map_channel_identities.sql deleted file mode 100644 index 25238c2e6d..0000000000 --- a/acceleration/migrations/global/20270115000100_contact_map_channel_identities.sql +++ /dev/null @@ -1,45 +0,0 @@ --- +goose Up - --- channel_identities and contact_map both said who an address is to one agent of a customer. --- The channel lines' rows (kind whatsapp, sms or imessage) move into contact_map with thread, --- where a reply reaches the person; their conversation_id stays the conversation the next --- message carries on. Their kinds are their own, so the phone rows of episode cards and links --- never share a row with them. -ALTER TABLE contact_map RENAME COLUMN agent_config_id TO config_id; -ALTER TABLE contact_map ADD COLUMN thread TEXT NOT NULL DEFAULT ''; -ALTER TABLE contact_map DROP CONSTRAINT contact_map_kind_check; -ALTER TABLE contact_map ADD CONSTRAINT contact_map_kind_check - CHECK (kind IN ('phone', 'slack', 'stream_user', 'whatsapp', 'sms', 'imessage')) NOT VALID; - -INSERT INTO contact_map (id, customer_id, config_id, kind, address, conversation_id, user_id, thread, created_at, updated_at) -SELECT id, customer_id, config_id, kind, address, conversation_id, user_id, thread, created_at, updated_at -FROM channel_identities -ON CONFLICT DO NOTHING; - -DROP TABLE channel_identities; - --- +goose Down -CREATE TABLE channel_identities ( - id TEXT PRIMARY KEY, - customer_id TEXT NOT NULL, - config_id TEXT NOT NULL, - kind TEXT NOT NULL, - address TEXT NOT NULL, - thread TEXT NOT NULL DEFAULT '', - user_id TEXT NOT NULL, - conversation_id TEXT NOT NULL DEFAULT '', - created_at TIMESTAMPTZ NOT NULL, - updated_at TIMESTAMPTZ NOT NULL -); -CREATE UNIQUE INDEX channel_identities_address_idx ON channel_identities (customer_id, config_id, kind, address); - -INSERT INTO channel_identities (id, customer_id, config_id, kind, address, thread, user_id, conversation_id, created_at, updated_at) -SELECT id, customer_id, config_id, kind, address, thread, COALESCE(user_id, ''), conversation_id, created_at, updated_at -FROM contact_map -WHERE kind IN ('whatsapp', 'sms', 'imessage'); - -DELETE FROM contact_map WHERE kind IN ('whatsapp', 'sms', 'imessage'); -ALTER TABLE contact_map DROP CONSTRAINT contact_map_kind_check; -ALTER TABLE contact_map ADD CONSTRAINT contact_map_kind_check CHECK (kind IN ('phone', 'slack', 'stream_user')) NOT VALID; -ALTER TABLE contact_map DROP COLUMN thread; -ALTER TABLE contact_map RENAME COLUMN config_id TO agent_config_id; diff --git a/acceleration/migrations/global/20270115000200_channel_threads_fold_people.sql b/acceleration/migrations/global/20270115000200_channel_threads_fold_people.sql deleted file mode 100644 index 24ca7759d2..0000000000 --- a/acceleration/migrations/global/20270115000200_channel_threads_fold_people.sql +++ /dev/null @@ -1,33 +0,0 @@ --- +goose Up - --- channel_thread_people and channel_thread_starters were split from channel_threads only so a --- rollback could still read it; the store reads with unknown columns discarded, so they are --- columns of the thread again. Empty is none recorded. -ALTER TABLE channel_threads - ADD COLUMN chat_person TEXT NOT NULL DEFAULT '', - ADD COLUMN starter TEXT NOT NULL DEFAULT ''; - -UPDATE channel_threads AS ct -SET chat_person = COALESCE(ctp.chat_person, ''), starter = COALESCE(cts.starter, '') -FROM channel_threads AS t -LEFT JOIN channel_thread_people AS ctp ON ctp.channel_id = t.channel_id -LEFT JOIN channel_thread_starters AS cts ON cts.channel_id = t.channel_id -WHERE t.channel_id = ct.channel_id AND (ctp.channel_id IS NOT NULL OR cts.channel_id IS NOT NULL); - -DROP TABLE channel_thread_people; -DROP TABLE channel_thread_starters; - --- +goose Down -CREATE TABLE channel_thread_people ( - channel_id TEXT PRIMARY KEY REFERENCES channel_threads (channel_id) ON DELETE CASCADE, - chat_person TEXT NOT NULL -); -CREATE TABLE channel_thread_starters ( - channel_id TEXT PRIMARY KEY REFERENCES channel_threads (channel_id) ON DELETE CASCADE, - starter TEXT NOT NULL -); -INSERT INTO channel_thread_people (channel_id, chat_person) -SELECT channel_id, chat_person FROM channel_threads WHERE chat_person <> ''; -INSERT INTO channel_thread_starters (channel_id, starter) -SELECT channel_id, starter FROM channel_threads WHERE starter <> ''; -ALTER TABLE channel_threads DROP COLUMN chat_person, DROP COLUMN starter; diff --git a/acceleration/migrations/global/20270115000300_episodes_fold_activity.sql b/acceleration/migrations/global/20270115000300_episodes_fold_activity.sql deleted file mode 100644 index a3954e6194..0000000000 --- a/acceleration/migrations/global/20270115000300_episodes_fold_activity.sql +++ /dev/null @@ -1,31 +0,0 @@ --- +goose Up - --- episode_activity was split from episodes only so a rollback could still read it; the store --- reads with unknown columns discarded, so its columns are the episode's again. The summary --- lease is lease_until, held by leased_by, the router that closed or took the episode. -ALTER TABLE episodes - ADD COLUMN last_message_at TIMESTAMPTZ, - ADD COLUMN lease_until TIMESTAMPTZ, - ADD COLUMN leased_by TEXT; - -UPDATE episodes AS ep -SET last_message_at = act.last_message_at, lease_until = act.summary_lease_until -FROM episode_activity AS act -WHERE act.episode_id = ep.id; - --- The leases a claim takes once they run out (Episodes.ClaimSummaries). -CREATE INDEX episodes_lease ON episodes (lease_until) WHERE lease_until IS NOT NULL; - -DROP TABLE episode_activity; - --- +goose Down -CREATE TABLE episode_activity ( - episode_id TEXT PRIMARY KEY REFERENCES episodes (id) ON DELETE CASCADE, - last_message_at TIMESTAMPTZ, - summary_lease_until TIMESTAMPTZ -); -CREATE INDEX episode_activity_summary_lease ON episode_activity (summary_lease_until) WHERE summary_lease_until IS NOT NULL; -INSERT INTO episode_activity (episode_id, last_message_at, summary_lease_until) -SELECT id, last_message_at, lease_until FROM episodes WHERE last_message_at IS NOT NULL OR lease_until IS NOT NULL; -DROP INDEX episodes_lease; -ALTER TABLE episodes DROP COLUMN last_message_at, DROP COLUMN lease_until, DROP COLUMN leased_by; diff --git a/acceleration/migrations/global/20270115000400_stream_app_pk.sql b/acceleration/migrations/global/20270115000400_stream_app_pk.sql deleted file mode 100644 index 05a5819393..0000000000 --- a/acceleration/migrations/global/20270115000400_stream_app_pk.sql +++ /dev/null @@ -1,11 +0,0 @@ --- +goose Up - --- stream_app_pk names a Stream app pinned to a row, as every other table names it. -ALTER TABLE chat_inbound RENAME COLUMN stream_app TO stream_app_pk; -ALTER TABLE chat_inbound RENAME CONSTRAINT chat_inbound_stream_app_message_id_key TO chat_inbound_stream_app_pk_message_id_key; -ALTER TABLE image_jobs RENAME COLUMN stream_app TO stream_app_pk; - --- +goose Down -ALTER TABLE image_jobs RENAME COLUMN stream_app_pk TO stream_app; -ALTER TABLE chat_inbound RENAME CONSTRAINT chat_inbound_stream_app_pk_message_id_key TO chat_inbound_stream_app_message_id_key; -ALTER TABLE chat_inbound RENAME COLUMN stream_app_pk TO stream_app; diff --git a/acceleration/migrations/global/20270115000500_channel_turns.sql b/acceleration/migrations/global/20270115000500_channel_turns.sql deleted file mode 100644 index a65581c752..0000000000 --- a/acceleration/migrations/global/20270115000500_channel_turns.sql +++ /dev/null @@ -1,31 +0,0 @@ --- +goose Up - --- A channel's running turn is one lease, whether the channel is an app chat's or a thread --- channel the channel bridge writes into: chat_channel_turns becomes channel_turns, and the --- thread channels' leases on channel_threads move into it under their cid. A cid is unique --- only within its Stream app, so the app stays in the key; 0 is the deployment's own. -ALTER TABLE chat_channel_turns RENAME TO channel_turns; -ALTER TABLE channel_turns RENAME CONSTRAINT chat_channel_turns_pkey TO channel_turns_pkey; -ALTER TABLE channel_turns RENAME COLUMN turn_holder TO leased_by; -ALTER TABLE channel_turns RENAME COLUMN turn_until TO lease_until; - -INSERT INTO channel_turns (stream_app_pk, cid, leased_by, lease_until) -SELECT COALESCE(stream_app_pk, 0), 'agent:' || channel_id, turn_holder, turn_until -FROM channel_threads -WHERE turn_holder IS NOT NULL AND turn_until IS NOT NULL -ON CONFLICT DO NOTHING; - -ALTER TABLE channel_threads DROP COLUMN turn_holder, DROP COLUMN turn_until; - --- +goose Down -ALTER TABLE channel_threads ADD COLUMN turn_holder TEXT, ADD COLUMN turn_until TIMESTAMPTZ; -UPDATE channel_threads AS ct -SET turn_holder = t.leased_by, turn_until = t.lease_until -FROM channel_turns AS t -WHERE t.stream_app_pk = COALESCE(ct.stream_app_pk, 0) AND t.cid = 'agent:' || ct.channel_id; -DELETE FROM channel_turns AS t USING channel_threads AS ct -WHERE t.stream_app_pk = COALESCE(ct.stream_app_pk, 0) AND t.cid = 'agent:' || ct.channel_id; -ALTER TABLE channel_turns RENAME COLUMN lease_until TO turn_until; -ALTER TABLE channel_turns RENAME COLUMN leased_by TO turn_holder; -ALTER TABLE channel_turns RENAME CONSTRAINT channel_turns_pkey TO chat_channel_turns_pkey; -ALTER TABLE channel_turns RENAME TO chat_channel_turns; diff --git a/acceleration/migrations/global/20270116000000_campaign_contacts_lease_until.sql b/acceleration/migrations/global/20270116000000_campaign_contacts_lease_until.sql deleted file mode 100644 index 3782699d26..0000000000 --- a/acceleration/migrations/global/20270116000000_campaign_contacts_lease_until.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- The name every queue gives the end of a lease (store.queue). -ALTER TABLE campaign_contacts RENAME COLUMN leased_until TO lease_until; - --- +goose Down -ALTER TABLE campaign_contacts RENAME COLUMN lease_until TO leased_until; diff --git a/acceleration/migrations/global/20270116000002_stream_trunk_bridges.sql b/acceleration/migrations/global/20270116000002_stream_trunk_bridges.sql deleted file mode 100644 index ae67fa40b1..0000000000 --- a/acceleration/migrations/global/20270116000002_stream_trunk_bridges.sql +++ /dev/null @@ -1,46 +0,0 @@ --- +goose Up --- A trunk made for one number, before trunks were shared or without a key to seal a shared --- one's password, is a row too: its password stays sealed to the number it was made for, and a --- line adopts it into its group. -ALTER TABLE stream_trunks ADD COLUMN own boolean NOT NULL DEFAULT false, DROP COLUMN numbers; - -INSERT INTO stream_trunks (id, customer_id, stream_app_pk, vendor, bridge_uri, bridge_username, - bridge_password_sealed, bridge_password_kek_version, created_at, own) -SELECT DISTINCT ON (pn.stream_trunk_id) pn.stream_trunk_id, pn.customer_id, pn.stream_app_pk, pn.vendor, pn.bridge_uri, - COALESCE(pn.bridge_username, ''), COALESCE(pn.bridge_password_sealed, ''::bytea), - COALESCE(pn.bridge_password_kek_version, 0), COALESCE(pn.attached_at, pn.purchased_at), true -FROM phone_numbers pn -WHERE pn.released_at IS NULL AND pn.stream_trunk_id IS NOT NULL AND pn.bridge_uri IS NOT NULL - AND NOT EXISTS (SELECT 1 FROM stream_trunks st WHERE st.id = pn.stream_trunk_id) -ORDER BY pn.stream_trunk_id, pn.id DESC; - --- A trunk's numbers are the numbers held on it. -CREATE INDEX phone_numbers_trunk_idx ON phone_numbers (customer_id, stream_trunk_id) WHERE released_at IS NULL; - -ALTER TABLE phone_numbers - DROP COLUMN bridge_uri, - DROP COLUMN bridge_username, - DROP COLUMN bridge_password_sealed, - DROP COLUMN bridge_password_kek_version; - --- +goose Down -ALTER TABLE phone_numbers - ADD COLUMN bridge_uri text, - ADD COLUMN bridge_username text, - ADD COLUMN bridge_password_sealed bytea, - ADD COLUMN bridge_password_kek_version integer; -ALTER TABLE stream_trunks ADD COLUMN numbers text[] NOT NULL DEFAULT '{}'; -UPDATE stream_trunks st SET numbers = ARRAY( - SELECT pn.e164 FROM phone_numbers pn - WHERE pn.customer_id = st.customer_id AND pn.stream_trunk_id = st.id AND pn.released_at IS NULL ORDER BY pn.id); -ALTER TABLE stream_trunks ALTER COLUMN numbers DROP DEFAULT; --- An own trunk's password was sealed to its number, so it goes back there; a shared one's was --- sealed to the trunk and cannot, so its numbers keep only the address. -UPDATE phone_numbers pn SET bridge_uri = st.bridge_uri, bridge_username = st.bridge_username, - bridge_password_sealed = CASE WHEN st.own AND st.bridge_password_sealed <> ''::bytea THEN st.bridge_password_sealed END, - bridge_password_kek_version = CASE WHEN st.own AND st.bridge_password_sealed <> ''::bytea THEN st.bridge_password_kek_version END -FROM stream_trunks st -WHERE st.id = pn.stream_trunk_id AND st.customer_id = pn.customer_id AND pn.released_at IS NULL; -DELETE FROM stream_trunks WHERE own; -DROP INDEX phone_numbers_trunk_idx; -ALTER TABLE stream_trunks DROP COLUMN own; diff --git a/acceleration/migrations/global/20270116000003_use_case_campaign_index.sql b/acceleration/migrations/global/20270116000003_use_case_campaign_index.sql deleted file mode 100644 index 91167ab1e6..0000000000 --- a/acceleration/migrations/global/20270116000003_use_case_campaign_index.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- A vendor's campaign webhook finds its use case by the vendor's id for it (UseCases.GetByCampaign). -CREATE INDEX dlc_use_cases_vendor_campaign_idx ON dlc_use_cases (vendor, vendor_campaign_id) WHERE vendor_campaign_id <> ''; - --- +goose Down -DROP INDEX dlc_use_cases_vendor_campaign_idx; diff --git a/acceleration/migrations/global/20270117000300_scheduled_tasks_leased_by.sql b/acceleration/migrations/global/20270117000300_scheduled_tasks_leased_by.sql deleted file mode 100644 index 6a84b31eeb..0000000000 --- a/acceleration/migrations/global/20270117000300_scheduled_tasks_leased_by.sql +++ /dev/null @@ -1,8 +0,0 @@ --- +goose Up - --- The column holds which worker's lease the task is under, not a claim of its own. -ALTER TABLE scheduled_tasks RENAME COLUMN claim_id TO leased_by; - --- +goose Down - -ALTER TABLE scheduled_tasks RENAME COLUMN leased_by TO claim_id; diff --git a/acceleration/migrations/global/20270117000400_record_data_change_secrets.sql b/acceleration/migrations/global/20270117000400_record_data_change_secrets.sql deleted file mode 100644 index 5e557a38e6..0000000000 --- a/acceleration/migrations/global/20270117000400_record_data_change_secrets.sql +++ /dev/null @@ -1,186 +0,0 @@ --- +goose Up - --- The secret columns a change leaves out are passed by the trigger (Store.watchDataChanges) from --- the one Go list (isSecret) rather than kept here as a second copy. --- +goose StatementBegin -CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger - LANGUAGE plpgsql - AS $_$ -DECLARE - subject JSONB; - owner TEXT; - identity JSONB := '{}'::JSONB; - column_name TEXT; - handed_out BIGINT; -BEGIN - IF TG_OP = 'DELETE' THEN - subject := to_jsonb(OLD); - ELSE - subject := to_jsonb(NEW); - END IF; - - -- TG_ARGV[0] is the column holding the customer id, or 'parent' when the row belongs - -- to a customer through another table: TG_ARGV[1] is then the column referencing it - -- and TG_ARGV[2] the table it references. - IF TG_ARGV[0] = 'parent' THEN - EXECUTE format('SELECT customer_id FROM %I WHERE id = $1', TG_ARGV[2]) - INTO owner USING subject ->> TG_ARGV[1]; - ELSE - owner := subject ->> TG_ARGV[0]; - END IF; - - IF owner IS NULL OR owner = '' THEN - RETURN NULL; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM data_change_capture - WHERE customer_id = owner AND expires_at > now() - ) THEN - -- At these two levels every query reads the snapshot of the transaction's first, so a - -- capture started since is not seen here, and the transaction may hold no id yet for - -- Store.WaitForOpenWrites to wait on. Every start updates the one row of - -- data_change_starts. Locking it fails the transaction with a serialization failure if - -- a start committed after its snapshot, and makes a start that comes later wait until it - -- ends (https://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ). - IF current_setting('transaction_isolation') IN ('repeatable read', 'serializable') THEN - PERFORM 1 FROM data_change_starts FOR SHARE; - END IF; - RETURN NULL; - END IF; - - -- TG_ARGV[3] is the table's secret columns as an array literal (store.isSecret, attached by - -- Store.watchDataChanges), and TG_ARGV[4:] the columns naming the row. A trigger attached - -- before the list was passed would record the secrets, so it records nothing and fails. - IF coalesce(left(TG_ARGV[3], 1), '') <> '{' THEN - RAISE EXCEPTION 'record_data_change: % was attached without its secret columns', TG_TABLE_NAME; - END IF; - - FOREACH column_name IN ARRAY TG_ARGV[4:] LOOP - identity := identity || jsonb_build_object(column_name, subject -> column_name); - END LOOP; - - -- Credentials are left behind. A secret this deployment sealed is worth nothing to - -- the one reading it, and an access token a customer's user granted to this - -- deployment is not something to hand out because somebody asked for their data. - subject := subject - TG_ARGV[3]::text[]; - - -- A change is numbered when it is written and seen when its transaction commits, so no - -- committed row tells a reader which lower number a transaction still running holds. - -- Before its first change, a transaction takes a shared advisory lock keyed by the - -- highest number handed out so far, below every number it will be given, and holds it - -- until it ends. pg_locks shows a lock as soon as it is taken, and Postgres releases it - -- only once the commit is visible (CommitTransaction in src/backend/access/transam/xact.c: - -- "this must be done _before_ releasing locks we hold"). Store.changeWatermark reads - -- these locks. The key - -- is the number's two halves in the two-integer key space; the other two-integer locks - -- here start at 839 << 32, a number no feed reaches. The setting, local to the - -- transaction, takes it once rather than once per row. - IF coalesce(current_setting('data_changes.bounded', true), '') = '' THEN - SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END - INTO handed_out FROM data_changes_seq_seq; - PERFORM pg_advisory_xact_lock_shared((handed_out >> 32)::int, ((handed_out << 32) >> 32)::int); - PERFORM set_config('data_changes.bounded', 'on', true); - END IF; - - INSERT INTO data_changes (customer_id, table_name, op, key, payload) - VALUES ( - owner, - TG_TABLE_NAME, - lower(TG_OP), - identity, - CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE subject END - ); - RETURN NULL; -END; -$_$; --- +goose StatementEnd - --- +goose Down - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger - LANGUAGE plpgsql - AS $_$ -DECLARE - subject JSONB; - owner TEXT; - identity JSONB := '{}'::JSONB; - column_name TEXT; - handed_out BIGINT; -BEGIN - IF TG_OP = 'DELETE' THEN - subject := to_jsonb(OLD); - ELSE - subject := to_jsonb(NEW); - END IF; - - -- TG_ARGV[0] is the column holding the customer id, or 'parent' when the row belongs - -- to a customer through another table: TG_ARGV[1] is then the column referencing it - -- and TG_ARGV[2] the table it references. - IF TG_ARGV[0] = 'parent' THEN - EXECUTE format('SELECT customer_id FROM %I WHERE id = $1', TG_ARGV[2]) - INTO owner USING subject ->> TG_ARGV[1]; - ELSE - owner := subject ->> TG_ARGV[0]; - END IF; - - IF owner IS NULL OR owner = '' THEN - RETURN NULL; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM data_change_capture - WHERE customer_id = owner AND expires_at > now() - ) THEN - -- At these two levels every query reads the snapshot of the transaction's first, so a - -- capture started since is not seen here, and the transaction may hold no id yet for - -- Store.WaitForOpenWrites to wait on. Every start updates the one row of - -- data_change_starts. Locking it fails the transaction with a serialization failure if - -- a start committed after its snapshot, and makes a start that comes later wait until it - -- ends (https://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ). - IF current_setting('transaction_isolation') IN ('repeatable read', 'serializable') THEN - PERFORM 1 FROM data_change_starts FOR SHARE; - END IF; - RETURN NULL; - END IF; - - FOREACH column_name IN ARRAY TG_ARGV[3:] LOOP - identity := identity || jsonb_build_object(column_name, subject -> column_name); - END LOOP; - - -- Credentials are left behind. A secret this deployment sealed is worth nothing to - -- the one reading it, and an access token a customer's user granted to this - -- deployment is not something to hand out because somebody asked for their data. - subject := subject - 'secret_sealed' - 'access_token' - 'refresh_token' - - 'oauth_state' - 'code_verifier' - 'credentials_sealed' - 'password_sealed' - - 'bridge_password_sealed' - 'refresh_secret_hash'; - - -- A change is numbered when it is written and seen when its transaction commits, so no - -- committed row tells a reader which lower number a transaction still running holds. - -- Before its first change, a transaction takes a shared advisory lock keyed by the - -- highest number handed out so far, below every number it will be given, and holds it - -- until it ends. pg_locks shows a lock as soon as it is taken, and Postgres releases it - -- only once the commit is visible (CommitTransaction in src/backend/access/transam/xact.c: - -- "this must be done _before_ releasing locks we hold"). Store.changeWatermark reads - -- these locks. The key - -- is the number's two halves in the two-integer key space; the other two-integer locks - -- here start at 839 << 32, a number no feed reaches. The setting, local to the - -- transaction, takes it once rather than once per row. - IF coalesce(current_setting('data_changes.bounded', true), '') = '' THEN - SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END - INTO handed_out FROM data_changes_seq_seq; - PERFORM pg_advisory_xact_lock_shared((handed_out >> 32)::int, ((handed_out << 32) >> 32)::int); - PERFORM set_config('data_changes.bounded', 'on', true); - END IF; - - INSERT INTO data_changes (customer_id, table_name, op, key, payload) - VALUES ( - owner, - TG_TABLE_NAME, - lower(TG_OP), - identity, - CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE subject END - ); - RETURN NULL; -END; -$_$; --- +goose StatementEnd diff --git a/acceleration/migrations/global/20270119000000_image_jobs_queued_idx.sql b/acceleration/migrations/global/20270119000000_image_jobs_queued_idx.sql deleted file mode 100644 index 0f3f15d946..0000000000 --- a/acceleration/migrations/global/20270119000000_image_jobs_queued_idx.sql +++ /dev/null @@ -1,20 +0,0 @@ --- +goose NO TRANSACTION --- +goose Up - --- The queued jobs of each kind a claim takes, still to be drawn or decided, in the order it --- takes them (next_attempt_at, id). On image_jobs_due the message a claim filters on was read --- off each row, so the planner, guessing few rows pass, bitmap-scanned and sorted every due --- entry: every dead one too, which a bitmap scan never marks to skip, so each claim read more. --- Built without stopping the writes of jobs; a build that fails is built again in Go --- (store.usageIndexes). -CREATE INDEX CONCURRENTLY IF NOT EXISTS image_jobs_undecided - ON image_jobs (next_attempt_at, id) WHERE state = 'queued' AND message = ''; -CREATE INDEX CONCURRENTLY IF NOT EXISTS image_jobs_decided - ON image_jobs (next_attempt_at, id) WHERE state = 'queued' AND message <> ''; -DROP INDEX CONCURRENTLY IF EXISTS image_jobs_due; - --- +goose Down -CREATE INDEX CONCURRENTLY IF NOT EXISTS image_jobs_due - ON image_jobs (next_attempt_at) WHERE state = 'queued'; -DROP INDEX CONCURRENTLY IF EXISTS image_jobs_decided; -DROP INDEX CONCURRENTLY IF EXISTS image_jobs_undecided; diff --git a/acceleration/migrations/global/20270122000000_channel_link_failures.sql b/acceleration/migrations/global/20270122000000_channel_link_failures.sql deleted file mode 100644 index 3f5454d0d5..0000000000 --- a/acceleration/migrations/global/20270122000000_channel_link_failures.sql +++ /dev/null @@ -1,15 +0,0 @@ --- +goose Up - --- The messages each number texted a line that claimed no link code, per window, so a code --- cannot be guessed by texting one after another. -CREATE TABLE IF NOT EXISTS channel_link_failures ( - account_id text NOT NULL, - from_address text NOT NULL, - window_start timestamptz NOT NULL, - failures integer NOT NULL, - CONSTRAINT channel_link_failures_pkey PRIMARY KEY (account_id, from_address, window_start) -); -CREATE INDEX IF NOT EXISTS channel_link_failures_window_idx ON channel_link_failures (window_start); - --- +goose Down -DROP TABLE IF EXISTS channel_link_failures; diff --git a/acceleration/migrations/global/20270122000100_voice_bindings_external_idx.sql b/acceleration/migrations/global/20270122000100_voice_bindings_external_idx.sql deleted file mode 100644 index fc0a6515f5..0000000000 --- a/acceleration/migrations/global/20270122000100_voice_bindings_external_idx.sql +++ /dev/null @@ -1,8 +0,0 @@ --- +goose Up - --- Whose a provider's voice id is, which a voice passed straight through to a provider is --- looked up by on every stream that opens, so one customer cannot speak in another's clone. -CREATE INDEX IF NOT EXISTS voice_bindings_external_idx ON voice_bindings (provider, external_id); - --- +goose Down -DROP INDEX IF EXISTS voice_bindings_external_idx; diff --git a/acceleration/migrations/global/20270123021810_voice_data_not_moved.sql b/acceleration/migrations/global/20270123021810_voice_data_not_moved.sql deleted file mode 100644 index 73d7b89140..0000000000 --- a/acceleration/migrations/global/20270123021810_voice_data_not_moved.sql +++ /dev/null @@ -1,10 +0,0 @@ --- +goose Up - --- A voice's samples and bindings are no longer carried by a move (store.dataTables): the audio --- is in this deployment's bucket and the clone in this deployment's account at the provider. -DROP TRIGGER IF EXISTS data_changes_recorded ON voice_samples; -DROP TRIGGER IF EXISTS data_changes_recorded ON voice_bindings; - --- +goose Down - --- Nothing: the router puts the trigger back on every table a move carries when it starts. diff --git a/acceleration/migrations/global/20270124093000_activity_digests.sql b/acceleration/migrations/global/20270124093000_activity_digests.sql deleted file mode 100644 index 1c2e450064..0000000000 --- a/acceleration/migrations/global/20270124093000_activity_digests.sql +++ /dev/null @@ -1,15 +0,0 @@ --- +goose Up - --- One row per UTC day whose activity digest was posted to the operator's channel, so the --- deployment posts each day's once whatever its routers and restarts. internal/limitnotice --- writes the row before it posts and posts only if its write made the row: posted_at stays --- empty until the post succeeds, and a row claimed long enough ago and never posted is --- claimed again, as notices are. -CREATE TABLE IF NOT EXISTS activity_digests ( - day DATE PRIMARY KEY, - claimed_at TIMESTAMPTZ NOT NULL DEFAULT now(), - posted_at TIMESTAMPTZ -); - --- +goose Down -DROP TABLE activity_digests; diff --git a/acceleration/migrations/migrations.go b/acceleration/migrations/migrations.go index b1c547f4eb..1d33ab3026 100644 --- a/acceleration/migrations/migrations.go +++ b/acceleration/migrations/migrations.go @@ -4,6 +4,8 @@ // connectors, numbers, limits. shard is each shard's own: sessions, responses, calls, call // legs, requests and their rollups. A deployment of one database runs both on it. Each set // records its versions in a table of its own, so a version is unique within its set only. +// Each starts with one initial migration, the history before it squashed into the schema it +// left. package migrations import ( diff --git a/acceleration/migrations/shard/20270110000000_baseline.sql b/acceleration/migrations/shard/20270110000000_initial.sql similarity index 86% rename from acceleration/migrations/shard/20270110000000_baseline.sql rename to acceleration/migrations/shard/20270110000000_initial.sql index f74eb90b13..f539e61f27 100644 --- a/acceleration/migrations/shard/20270110000000_baseline.sql +++ b/acceleration/migrations/shard/20270110000000_initial.sql @@ -1,8 +1,11 @@ -- +goose Up --- The shard tables as they stood at 20270103090000, the last version of the single migration --- history every database ran. A database that ran it is marked as having applied this baseline --- (store.adoptLegacy); a new one runs it. Each shard keeps its own; a deployment of one database keeps both sets in it. +-- A shard's own tables: sessions, responses, calls, call legs, requests and their rollups. This is +-- the whole history up to 20270126000000, squashed; a database that ran that history records this +-- version as applied and runs nothing here. + +-- The change log, kept by both sets: a deployment of one database runs both initial migrations on +-- it, so each of these is a no-op the second time. -- +goose StatementBegin CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger @@ -50,16 +53,21 @@ BEGIN RETURN NULL; END IF; - FOREACH column_name IN ARRAY TG_ARGV[3:] LOOP + -- TG_ARGV[3] is the table's secret columns as an array literal (store.isSecret, attached by + -- Store.watchDataChanges), and TG_ARGV[4:] the columns naming the row. A trigger attached + -- before the list was passed would record the secrets, so it records nothing and fails. + IF coalesce(left(TG_ARGV[3], 1), '') <> '{' THEN + RAISE EXCEPTION 'record_data_change: % was attached without its secret columns', TG_TABLE_NAME; + END IF; + + FOREACH column_name IN ARRAY TG_ARGV[4:] LOOP identity := identity || jsonb_build_object(column_name, subject -> column_name); END LOOP; -- Credentials are left behind. A secret this deployment sealed is worth nothing to -- the one reading it, and an access token a customer's user granted to this -- deployment is not something to hand out because somebody asked for their data. - subject := subject - 'secret_sealed' - 'access_token' - 'refresh_token' - - 'oauth_state' - 'code_verifier' - 'credentials_sealed' - 'password_sealed' - - 'bridge_password_sealed' - 'refresh_secret_hash'; + subject := subject - TG_ARGV[3]::text[]; -- A change is numbered when it is written and seen when its transaction commits, so no -- committed row tells a reader which lower number a transaction still running holds. @@ -93,15 +101,21 @@ $_$; -- +goose StatementEnd CREATE TABLE IF NOT EXISTS data_change_capture ( - customer_id text PRIMARY KEY, + customer_id text NOT NULL, started_at timestamp with time zone DEFAULT now() NOT NULL, expires_at timestamp with time zone NOT NULL, recorded_since bigint DEFAULT 0 NOT NULL, pruned_through bigint DEFAULT 0 NOT NULL ); +CREATE TABLE IF NOT EXISTS data_change_starts ( + one boolean DEFAULT true NOT NULL, + started bigint DEFAULT 0 NOT NULL, + CONSTRAINT data_change_starts_one_check CHECK (one) +); + CREATE TABLE IF NOT EXISTS data_changes ( - seq bigserial PRIMARY KEY, + seq bigint NOT NULL, customer_id text NOT NULL, table_name text NOT NULL, op text NOT NULL, @@ -111,36 +125,55 @@ CREATE TABLE IF NOT EXISTS data_changes ( at timestamp with time zone DEFAULT now() NOT NULL ); -CREATE INDEX IF NOT EXISTS data_changes_at_idx ON data_changes USING btree (at); +CREATE SEQUENCE IF NOT EXISTS data_changes_seq_seq + START WITH 1 + INCREMENT BY 1 + NO MINVALUE + NO MAXVALUE + CACHE 1; -CREATE INDEX IF NOT EXISTS data_changes_customer_idx ON data_changes USING btree (customer_id, seq); +ALTER SEQUENCE data_changes_seq_seq OWNED BY data_changes.seq; -CREATE TABLE IF NOT EXISTS data_change_starts ( - one boolean DEFAULT true NOT NULL PRIMARY KEY, - started bigint DEFAULT 0 NOT NULL, - CONSTRAINT data_change_starts_one_check CHECK (one) -); +ALTER TABLE ONLY data_changes ALTER COLUMN seq SET DEFAULT nextval('data_changes_seq_seq'::regclass); -INSERT INTO data_change_starts DEFAULT VALUES ON CONFLICT DO NOTHING; +-- +goose StatementBegin +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_change_capture_pkey' AND conrelid = 'data_change_capture'::regclass) THEN + ALTER TABLE ONLY data_change_capture + ADD CONSTRAINT data_change_capture_pkey PRIMARY KEY (customer_id); + END IF; +END $$; +-- +goose StatementEnd -- +goose StatementBegin -CREATE OR REPLACE FUNCTION log_agent_request() RETURNS trigger - LANGUAGE plpgsql - AS $$ -DECLARE cfg TEXT; sid TEXT; +DO $$ BEGIN - IF NEW.agent_id IS NULL OR NEW.agent_id = '' THEN RETURN NEW; END IF; - IF current_setting('router.request_logged', true) = 'on' THEN RETURN NEW; END IF; - PERFORM pg_advisory_xact_lock(hashtextextended(NEW.customer_id, 731)); - SELECT config_id,id INTO cfg,sid FROM calls WHERE customer_id=NEW.customer_id AND agent_id=NEW.agent_id AND (NEW.call_id IS NULL OR call_id=NEW.call_id) AND started_at <= NEW.started_at ORDER BY started_at DESC LIMIT 1; - INSERT INTO agent_logs(customer_id,config_id,agent_id,session_id,source,severity,event_type,message,occurred_at,details) - VALUES(NEW.customer_id,coalesce(cfg,''),NEW.agent_id,coalesce(sid,''),'system',CASE WHEN NEW.success OR NEW.error_code = 'cancelled' THEN 'info' ELSE 'error' END, - 'provider_request',NEW.modality || ' request ' || CASE WHEN NEW.error_code = 'cancelled' THEN 'cancelled' WHEN NEW.success THEN 'completed' ELSE 'failed' END,NEW.started_at, - jsonb_build_object('provider',NEW.provider,'model',NEW.model,'request_id',NEW.id::text,'duration_ms',NEW.latency_ms,'input_tokens',NEW.input_tokens,'output_tokens',NEW.output_tokens,'cost_micros',NEW.cost_micros,'error_code',NEW.error_code,'error_message',NEW.error_message)); - RETURN NEW; + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_change_starts_pkey' AND conrelid = 'data_change_starts'::regclass) THEN + ALTER TABLE ONLY data_change_starts + ADD CONSTRAINT data_change_starts_pkey PRIMARY KEY (one); + END IF; +END $$; +-- +goose StatementEnd + +-- +goose StatementBegin +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'data_changes_pkey' AND conrelid = 'data_changes'::regclass) THEN + ALTER TABLE ONLY data_changes + ADD CONSTRAINT data_changes_pkey PRIMARY KEY (seq); + END IF; END $$; -- +goose StatementEnd +CREATE INDEX IF NOT EXISTS data_changes_at_idx ON data_changes USING btree (at); + +CREATE INDEX IF NOT EXISTS data_changes_customer_idx ON data_changes USING btree (customer_id, seq); + +INSERT INTO data_change_starts DEFAULT VALUES ON CONFLICT DO NOTHING; + +-- The set's own objects. + CREATE TABLE agent_branch_messages ( session_id text NOT NULL, original_message_id text NOT NULL, @@ -215,8 +248,6 @@ CREATE TABLE agent_sessions ( project text DEFAULT ''::text NOT NULL, custom jsonb DEFAULT '{}'::jsonb NOT NULL, model_overwrites jsonb DEFAULT '{}'::jsonb NOT NULL, - call_id text, - call_type text, forked_from text, state text NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, @@ -243,7 +274,7 @@ CREATE TABLE agent_sessions ( ); CREATE TABLE call_bridges ( - token text NOT NULL, + token text, customer_id text NOT NULL, vendor text NOT NULL, trunk_uri text NOT NULL, @@ -252,7 +283,10 @@ CREATE TABLE call_bridges ( initial_digits text, call_id text NOT NULL, created_at timestamp with time zone DEFAULT now() NOT NULL, - expires_at timestamp with time zone NOT NULL + expires_at timestamp with time zone NOT NULL, + token_hash text, + trunk_password_sealed bytea, + trunk_password_kek_version integer ); CREATE TABLE call_legs ( @@ -275,12 +309,24 @@ CREATE TABLE call_legs ( country text DEFAULT ''::text NOT NULL, agent_id text DEFAULT ''::text NOT NULL, tags jsonb DEFAULT '{}'::jsonb NOT NULL, - dialed_at timestamp with time zone NOT NULL, + dialed_at timestamp with time zone, started_at timestamp with time zone, ended_at timestamp with time zone, end_reason text DEFAULT ''::text NOT NULL, vendor_call_id text, - CONSTRAINT call_legs_direction_check CHECK ((direction = ANY (ARRAY['inbound'::text, 'outbound'::text]))) + token text, + reports boolean DEFAULT false NOT NULL, + placed_at timestamp with time zone, + answered_at timestamp with time zone, + outcome_ended_at timestamp with time zone, + outcome text, + vendor_status text, + decided_at timestamp with time zone, + token_hash text, + CONSTRAINT call_legs_dialed_check CHECK (((dialed_at IS NOT NULL) OR (placed_at IS NOT NULL))), + CONSTRAINT call_legs_direction_check CHECK ((direction = ANY (ARRAY['inbound'::text, 'outbound'::text]))), + CONSTRAINT call_legs_outcome_check CHECK ((outcome = ANY (ARRAY['completed'::text, 'busy'::text, 'no_answer'::text, 'failed'::text, 'canceled'::text, 'unknown'::text]))), + CONSTRAINT call_legs_placed_check CHECK (((placed_at IS NOT NULL) OR ((token IS NULL) AND (outcome IS NULL)))) ); CREATE SEQUENCE call_legs_id_seq @@ -340,7 +386,6 @@ CREATE TABLE calls ( customer_id text NOT NULL, call_id text NOT NULL, agent_id text NOT NULL, - config_id text, campaign_id text, contact_id text, from_number text, @@ -360,10 +405,11 @@ CREATE TABLE calls ( skills jsonb, sts text DEFAULT ''::text NOT NULL, voice text DEFAULT ''::text NOT NULL, - user_id text DEFAULT ''::text NOT NULL, stream_app_pk bigint, conversation_id text, - agent_user_id text + agent_user_id text, + session_id text, + call_type text DEFAULT ''::text NOT NULL ); CREATE TABLE conversation_documents ( @@ -380,36 +426,6 @@ CREATE TABLE conversation_documents ( created_at timestamp with time zone DEFAULT now() NOT NULL ); -CREATE TABLE phone_calls ( - id bigint NOT NULL, - token text, - customer_id text NOT NULL, - stream_app_pk bigint, - call_type text NOT NULL, - call_id text NOT NULL, - vendor text NOT NULL, - local_number text NOT NULL, - remote_number text NOT NULL, - reports boolean NOT NULL, - vendor_call_id text, - placed_at timestamp with time zone NOT NULL, - answered_at timestamp with time zone, - ended_at timestamp with time zone, - outcome text, - vendor_status text, - decided_at timestamp with time zone, - CONSTRAINT phone_calls_outcome_check CHECK ((outcome = ANY (ARRAY['completed'::text, 'busy'::text, 'no_answer'::text, 'failed'::text, 'canceled'::text, 'unknown'::text]))) -); - -CREATE SEQUENCE phone_calls_id_seq - START WITH 1 - INCREMENT BY 1 - NO MINVALUE - NO MAXVALUE - CACHE 1; - -ALTER SEQUENCE phone_calls_id_seq OWNED BY phone_calls.id; - CREATE TABLE recordings ( id text NOT NULL, customer_id text NOT NULL, @@ -480,7 +496,8 @@ CREATE TABLE requests ( limit_grants bigint[] DEFAULT '{}'::bigint[] NOT NULL, sku text DEFAULT ''::text NOT NULL, region text DEFAULT ''::text NOT NULL, - byok boolean DEFAULT false NOT NULL + byok boolean DEFAULT false NOT NULL, + source_usage_id uuid ); CREATE TABLE stats_daily ( @@ -596,10 +613,11 @@ ALTER TABLE ONLY call_participants ALTER COLUMN id SET DEFAULT nextval('call_par ALTER TABLE ONLY call_resources ALTER COLUMN id SET DEFAULT nextval('call_resources_id_seq'::regclass); -ALTER TABLE ONLY phone_calls ALTER COLUMN id SET DEFAULT nextval('phone_calls_id_seq'::regclass); - ALTER TABLE ONLY requests ALTER COLUMN id SET DEFAULT nextval('stt_requests_id_seq'::regclass); +ALTER TABLE requests + ADD CONSTRAINT requests_usage_id_present CHECK ((usage_id IS NOT NULL)) NOT VALID; + ALTER TABLE ONLY agent_branch_messages ADD CONSTRAINT agent_branch_messages_pkey PRIMARY KEY (session_id, original_message_id); @@ -618,9 +636,6 @@ ALTER TABLE ONLY agent_session_tools ALTER TABLE ONLY agent_sessions ADD CONSTRAINT agent_sessions_pkey PRIMARY KEY (id); -ALTER TABLE ONLY call_bridges - ADD CONSTRAINT call_bridges_pkey PRIMARY KEY (token); - ALTER TABLE ONLY call_legs ADD CONSTRAINT call_legs_pkey PRIMARY KEY (id); @@ -636,18 +651,9 @@ ALTER TABLE ONLY calls ALTER TABLE ONLY conversation_documents ADD CONSTRAINT conversation_documents_pkey PRIMARY KEY (id); -ALTER TABLE ONLY phone_calls - ADD CONSTRAINT phone_calls_pkey PRIMARY KEY (id); - -ALTER TABLE ONLY phone_calls - ADD CONSTRAINT phone_calls_token_key UNIQUE (token); - ALTER TABLE ONLY recordings ADD CONSTRAINT recordings_pkey PRIMARY KEY (id); -ALTER TABLE requests - ADD CONSTRAINT requests_usage_id_present CHECK ((usage_id IS NOT NULL)) NOT VALID; - ALTER TABLE ONLY stats_daily ADD CONSTRAINT stats_daily_pkey PRIMARY KEY (modality, customer_id, provider, model, bucket); @@ -743,8 +749,6 @@ CREATE INDEX call_resources_call_idx ON call_resources USING btree (call_type, c CREATE INDEX calls_agent_idx ON calls USING btree (agent_id, started_at DESC); -CREATE INDEX calls_campaign_idx ON calls USING btree (campaign_id, started_at DESC) WHERE (campaign_id IS NOT NULL); - CREATE INDEX calls_customer_idx ON calls USING btree (customer_id, started_at DESC); CREATE INDEX calls_tags_idx ON calls USING gin (tags); @@ -753,10 +757,6 @@ CREATE INDEX conversation_documents_conversation_idx ON conversation_documents U CREATE INDEX conversation_documents_session_idx ON conversation_documents USING btree (customer_id, session_id, created_at); -CREATE INDEX phone_calls_customer_call_idx ON phone_calls USING btree (customer_id, call_id, id DESC); - -CREATE INDEX phone_calls_placed_idx ON phone_calls USING btree (placed_at) WHERE (token IS NOT NULL); - CREATE INDEX recordings_customer_idx ON recordings USING btree (customer_id, created_at DESC); CREATE INDEX requests_agent_started_idx ON requests USING btree (agent_id, started_at DESC) WHERE (agent_id IS NOT NULL); @@ -781,7 +781,32 @@ CREATE UNIQUE INDEX requests_usage_id_idx ON requests USING btree (usage_id); CREATE INDEX requests_user_spend_idx ON requests USING btree (customer_id, user_id, started_at) INCLUDE (cost_micros) WHERE (billable AND (user_id <> ''::text)); -CREATE TRIGGER agent_request_log AFTER INSERT ON requests FOR EACH ROW EXECUTE FUNCTION log_agent_request(); +CREATE INDEX calls_customer_agent_idx ON calls USING btree (customer_id, agent_id, started_at DESC); + +CREATE INDEX calls_campaign_idx ON calls USING btree (customer_id, campaign_id, started_at DESC) WHERE (campaign_id IS NOT NULL); + +ALTER TABLE ONLY call_legs + ADD CONSTRAINT call_legs_token_key UNIQUE (token); + +CREATE INDEX call_legs_placed_call_idx ON call_legs USING btree (customer_id, call_id, id DESC) WHERE (placed_at IS NOT NULL); + +CREATE INDEX call_legs_token_placed_idx ON call_legs USING btree (placed_at) WHERE (token IS NOT NULL); + +CREATE INDEX call_resources_created_idx ON call_resources USING btree (created_at); + +CREATE INDEX call_legs_unanswered_idx ON call_legs USING btree (call_type, call_id) WHERE ((direction = 'outbound'::text) AND (end_reason = 'unanswered'::text)); + +CREATE INDEX calls_session_started_idx ON calls USING btree (session_id, started_at DESC) WHERE (session_id IS NOT NULL); + +ALTER TABLE ONLY call_bridges + ADD CONSTRAINT call_bridges_token_key UNIQUE (token); + +ALTER TABLE ONLY call_bridges + ADD CONSTRAINT call_bridges_token_hash_key UNIQUE (token_hash); + +CREATE UNIQUE INDEX call_legs_token_hash_key ON call_legs USING btree (token_hash); + +CREATE INDEX call_legs_token_hash_placed_idx ON call_legs USING btree (placed_at) WHERE (token_hash IS NOT NULL); ALTER TABLE ONLY agent_branch_messages ADD CONSTRAINT agent_branch_messages_session_id_fkey FOREIGN KEY (session_id) REFERENCES agent_sessions(id) ON DELETE CASCADE; @@ -798,6 +823,9 @@ ALTER TABLE ONLY agent_responses ALTER TABLE ONLY agent_session_tools ADD CONSTRAINT agent_session_tools_session_id_fkey FOREIGN KEY (session_id) REFERENCES agent_sessions(id) ON DELETE CASCADE; +ALTER TABLE ONLY calls + ADD CONSTRAINT calls_session_id_fkey FOREIGN KEY (session_id) REFERENCES agent_sessions(id) ON DELETE SET NULL; + -- +goose Down --- A baseline is not undone. +-- The initial migration is not undone. SELECT 1; diff --git a/acceleration/migrations/shard/20270114000000_calls_belong_to_sessions.sql b/acceleration/migrations/shard/20270114000000_calls_belong_to_sessions.sql deleted file mode 100644 index 51bdafbff3..0000000000 --- a/acceleration/migrations/shard/20270114000000_calls_belong_to_sessions.sql +++ /dev/null @@ -1,95 +0,0 @@ --- +goose Up -ALTER TABLE calls - ADD COLUMN session_id text REFERENCES agent_sessions (id) ON DELETE SET NULL, - ADD COLUMN call_type text DEFAULT ''::text NOT NULL; - --- Every session held its one call under its own id, text sessions included, so each keeps --- that call: the existing row gains the session and its Stream call, and a session whose row --- was never written gets one. -INSERT INTO calls (id, session_id, customer_id, stream_app_pk, call_id, call_type, conversation_id, agent_id, direction, started_at, ended_at) -SELECT s.id, s.id, s.customer_id, s.stream_app_pk, COALESCE(s.call_id, ''), COALESCE(s.call_type, ''), s.conversation_id, - s.agent_id, 'inbound', s.created_at, s.closed_at -FROM agent_sessions AS s -ON CONFLICT (id) DO UPDATE SET - session_id = EXCLUDED.session_id, - call_type = EXCLUDED.call_type, - conversation_id = COALESCE(calls.conversation_id, EXCLUDED.conversation_id), - call_id = CASE WHEN calls.call_id = '' THEN EXCLUDED.call_id ELSE calls.call_id END; - -CREATE INDEX calls_session_idx ON calls USING btree (customer_id, session_id, started_at DESC) WHERE (session_id IS NOT NULL); - -CREATE INDEX calls_customer_agent_idx ON calls USING btree (customer_id, agent_id, started_at DESC); - -DROP INDEX calls_campaign_idx; - -CREATE INDEX calls_campaign_idx ON calls USING btree (customer_id, campaign_id, started_at DESC) WHERE (campaign_id IS NOT NULL); - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION log_agent_request() RETURNS trigger - LANGUAGE plpgsql - AS $$ -DECLARE cfg TEXT; sid TEXT; -BEGIN - IF NEW.agent_id IS NULL OR NEW.agent_id = '' THEN RETURN NEW; END IF; - IF current_setting('router.request_logged', true) = 'on' THEN RETURN NEW; END IF; - PERFORM pg_advisory_xact_lock(hashtextextended(NEW.customer_id, 731)); - SELECT s.config_id,c.session_id INTO cfg,sid FROM calls AS c LEFT JOIN agent_sessions AS s ON s.id = c.session_id WHERE c.customer_id=NEW.customer_id AND c.agent_id=NEW.agent_id AND (NEW.call_id IS NULL OR c.call_id=NEW.call_id) AND c.started_at <= NEW.started_at ORDER BY c.started_at DESC LIMIT 1; - INSERT INTO agent_logs(customer_id,config_id,agent_id,session_id,source,severity,event_type,message,occurred_at,details) - VALUES(NEW.customer_id,coalesce(cfg,''),NEW.agent_id,coalesce(sid,''),'system',CASE WHEN NEW.success OR NEW.error_code = 'cancelled' THEN 'info' ELSE 'error' END, - 'provider_request',NEW.modality || ' request ' || CASE WHEN NEW.error_code = 'cancelled' THEN 'cancelled' WHEN NEW.success THEN 'completed' ELSE 'failed' END,NEW.started_at, - jsonb_build_object('provider',NEW.provider,'model',NEW.model,'request_id',NEW.id::text,'duration_ms',NEW.latency_ms,'input_tokens',NEW.input_tokens,'output_tokens',NEW.output_tokens,'cost_micros',NEW.cost_micros,'error_code',NEW.error_code,'error_message',NEW.error_message)); - RETURN NEW; -END $$; --- +goose StatementEnd - -ALTER TABLE calls - DROP COLUMN user_id, - DROP COLUMN config_id; - -ALTER TABLE agent_sessions - DROP COLUMN call_id, - DROP COLUMN call_type; - --- +goose Down -ALTER TABLE agent_sessions - ADD COLUMN call_id text, - ADD COLUMN call_type text; - -ALTER TABLE calls - ADD COLUMN user_id text DEFAULT ''::text NOT NULL, - ADD COLUMN config_id text; - -UPDATE agent_sessions AS s SET call_id = NULLIF(c.call_id, ''), call_type = NULLIF(c.call_type, '') -FROM (SELECT DISTINCT ON (session_id) session_id, call_id, call_type FROM calls - WHERE session_id IS NOT NULL ORDER BY session_id, started_at DESC) AS c -WHERE c.session_id = s.id; - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION log_agent_request() RETURNS trigger - LANGUAGE plpgsql - AS $$ -DECLARE cfg TEXT; sid TEXT; -BEGIN - IF NEW.agent_id IS NULL OR NEW.agent_id = '' THEN RETURN NEW; END IF; - IF current_setting('router.request_logged', true) = 'on' THEN RETURN NEW; END IF; - PERFORM pg_advisory_xact_lock(hashtextextended(NEW.customer_id, 731)); - SELECT config_id,id INTO cfg,sid FROM calls WHERE customer_id=NEW.customer_id AND agent_id=NEW.agent_id AND (NEW.call_id IS NULL OR call_id=NEW.call_id) AND started_at <= NEW.started_at ORDER BY started_at DESC LIMIT 1; - INSERT INTO agent_logs(customer_id,config_id,agent_id,session_id,source,severity,event_type,message,occurred_at,details) - VALUES(NEW.customer_id,coalesce(cfg,''),NEW.agent_id,coalesce(sid,''),'system',CASE WHEN NEW.success OR NEW.error_code = 'cancelled' THEN 'info' ELSE 'error' END, - 'provider_request',NEW.modality || ' request ' || CASE WHEN NEW.error_code = 'cancelled' THEN 'cancelled' WHEN NEW.success THEN 'completed' ELSE 'failed' END,NEW.started_at, - jsonb_build_object('provider',NEW.provider,'model',NEW.model,'request_id',NEW.id::text,'duration_ms',NEW.latency_ms,'input_tokens',NEW.input_tokens,'output_tokens',NEW.output_tokens,'cost_micros',NEW.cost_micros,'error_code',NEW.error_code,'error_message',NEW.error_message)); - RETURN NEW; -END $$; --- +goose StatementEnd - -DROP INDEX calls_campaign_idx; - -CREATE INDEX calls_campaign_idx ON calls USING btree (campaign_id, started_at DESC) WHERE (campaign_id IS NOT NULL); - -DROP INDEX calls_customer_agent_idx; - -DROP INDEX calls_session_idx; - -ALTER TABLE calls - DROP COLUMN call_type, - DROP COLUMN session_id; diff --git a/acceleration/migrations/shard/20270116000001_merge_phone_calls.sql b/acceleration/migrations/shard/20270116000001_merge_phone_calls.sql deleted file mode 100644 index 44e79e01cd..0000000000 --- a/acceleration/migrations/shard/20270116000001_merge_phone_calls.sql +++ /dev/null @@ -1,92 +0,0 @@ --- +goose Up --- A placed call is its outbound leg: kept from before the dial, with its status token, until its --- outcome is decided. dialed_at is NULL until the vendor takes the dial. -ALTER TABLE call_legs - ALTER COLUMN dialed_at DROP NOT NULL, - ADD COLUMN token text, - ADD COLUMN reports boolean NOT NULL DEFAULT false, - ADD COLUMN placed_at timestamp with time zone, - ADD COLUMN answered_at timestamp with time zone, - ADD COLUMN outcome_ended_at timestamp with time zone, - ADD COLUMN outcome text, - ADD COLUMN vendor_status text, - ADD COLUMN decided_at timestamp with time zone, - ADD CONSTRAINT call_legs_token_key UNIQUE (token), - ADD CONSTRAINT call_legs_outcome_check - CHECK (outcome = ANY (ARRAY['completed', 'busy', 'no_answer', 'failed', 'canceled', 'unknown'])), - ADD CONSTRAINT call_legs_placed_check CHECK (placed_at IS NOT NULL OR (token IS NULL AND outcome IS NULL)), - ADD CONSTRAINT call_legs_dialed_check CHECK (dialed_at IS NOT NULL OR placed_at IS NOT NULL); - -CREATE INDEX call_legs_placed_call_idx ON call_legs (customer_id, call_id, id DESC) WHERE placed_at IS NOT NULL; -CREATE INDEX call_legs_token_placed_idx ON call_legs (placed_at) WHERE token IS NOT NULL; - --- Each placed call goes onto the outbound leg it opened, the one with its vendor id first, then --- the one dialled nearest it; a call no leg is left for becomes an ended leg of its own, which --- was never answered and is billed nothing. -WITH candidates AS ( - SELECT DISTINCT ON (pc.id) pc.id AS pc_id, cl.id AS cl_id - FROM phone_calls pc - JOIN call_legs cl ON cl.direction = 'outbound' - AND cl.customer_id = pc.customer_id AND cl.call_type = pc.call_type AND cl.call_id = pc.call_id - AND COALESCE(cl.stream_app_pk, 0) = COALESCE(pc.stream_app_pk, 0) - AND cl.local_number = pc.local_number AND cl.remote_number = pc.remote_number - AND (pc.vendor_call_id IS NULL OR cl.vendor_call_id IS NULL OR cl.vendor_call_id = pc.vendor_call_id) - ORDER BY pc.id, (cl.vendor_call_id IS NOT DISTINCT FROM pc.vendor_call_id) DESC, - abs(extract(epoch FROM cl.dialed_at - pc.placed_at)), cl.id -), matched AS ( - SELECT DISTINCT ON (cl_id) pc_id, cl_id FROM candidates ORDER BY cl_id, pc_id DESC -), merged AS ( - UPDATE call_legs cl SET - token = pc.token, reports = pc.reports, placed_at = pc.placed_at, answered_at = pc.answered_at, - outcome_ended_at = pc.ended_at, outcome = pc.outcome, vendor_status = pc.vendor_status, - decided_at = pc.decided_at, vendor_call_id = COALESCE(cl.vendor_call_id, pc.vendor_call_id) - FROM matched m JOIN phone_calls pc ON pc.id = m.pc_id - WHERE cl.id = m.cl_id -) -INSERT INTO call_legs (customer_id, stream_app_pk, call_type, call_id, vendor, vendor_call_id, direction, - local_number, remote_number, dialed_at, ended_at, token, reports, placed_at, answered_at, - outcome_ended_at, outcome, vendor_status, decided_at) -SELECT pc.customer_id, pc.stream_app_pk, pc.call_type, pc.call_id, pc.vendor, pc.vendor_call_id, 'outbound', - pc.local_number, pc.remote_number, pc.placed_at, COALESCE(pc.ended_at, pc.placed_at), pc.token, pc.reports, - pc.placed_at, pc.answered_at, pc.ended_at, pc.outcome, pc.vendor_status, pc.decided_at -FROM phone_calls pc -WHERE pc.id NOT IN (SELECT pc_id FROM matched); - -DROP TABLE phone_calls; - --- +goose Down -CREATE TABLE phone_calls ( - id bigserial PRIMARY KEY, - token text UNIQUE, - customer_id text NOT NULL, - stream_app_pk bigint, - call_type text NOT NULL, - call_id text NOT NULL, - vendor text NOT NULL, - local_number text NOT NULL, - remote_number text NOT NULL, - reports boolean NOT NULL, - vendor_call_id text, - placed_at timestamp with time zone NOT NULL, - answered_at timestamp with time zone, - ended_at timestamp with time zone, - outcome text CHECK (outcome = ANY (ARRAY['completed', 'busy', 'no_answer', 'failed', 'canceled', 'unknown'])), - vendor_status text, - decided_at timestamp with time zone -); -CREATE INDEX phone_calls_customer_call_idx ON phone_calls (customer_id, call_id, id DESC); -CREATE INDEX phone_calls_placed_idx ON phone_calls (placed_at) WHERE token IS NOT NULL; -INSERT INTO phone_calls (token, customer_id, stream_app_pk, call_type, call_id, vendor, local_number, remote_number, - reports, vendor_call_id, placed_at, answered_at, ended_at, outcome, vendor_status, decided_at) -SELECT token, customer_id, stream_app_pk, call_type, call_id, vendor, local_number, remote_number, - reports, vendor_call_id, placed_at, answered_at, outcome_ended_at, outcome, vendor_status, decided_at -FROM call_legs WHERE placed_at IS NOT NULL ORDER BY id; -DELETE FROM call_legs WHERE dialed_at IS NULL; -ALTER TABLE call_legs - DROP CONSTRAINT call_legs_dialed_check, - DROP CONSTRAINT call_legs_placed_check, - DROP CONSTRAINT call_legs_outcome_check, - DROP CONSTRAINT call_legs_token_key, - DROP COLUMN token, DROP COLUMN reports, DROP COLUMN placed_at, DROP COLUMN answered_at, - DROP COLUMN outcome_ended_at, DROP COLUMN outcome, DROP COLUMN vendor_status, DROP COLUMN decided_at, - ALTER COLUMN dialed_at SET NOT NULL; diff --git a/acceleration/migrations/shard/20270116000004_call_resources_created_index.sql b/acceleration/migrations/shard/20270116000004_call_resources_created_index.sql deleted file mode 100644 index 493cf22618..0000000000 --- a/acceleration/migrations/shard/20270116000004_call_resources_created_index.sql +++ /dev/null @@ -1,6 +0,0 @@ --- +goose Up --- The sweeper reads the rows of calls whose end hook never arrived by age (CallResources.SelectStale). -CREATE INDEX call_resources_created_idx ON call_resources (created_at); - --- +goose Down -DROP INDEX call_resources_created_idx; diff --git a/acceleration/migrations/shard/20270117000100_drop_agent_request_log.sql b/acceleration/migrations/shard/20270117000100_drop_agent_request_log.sql deleted file mode 100644 index 9e42b6d6ae..0000000000 --- a/acceleration/migrations/shard/20270117000100_drop_agent_request_log.sql +++ /dev/null @@ -1,28 +0,0 @@ --- +goose Up - --- A request's provider_request log row is written by the router (Requests.InsertMany), with --- one database or many, rather than by a trigger that only ran with one. -DROP TRIGGER IF EXISTS agent_request_log ON requests; -DROP FUNCTION IF EXISTS log_agent_request(); - --- +goose Down - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION log_agent_request() RETURNS trigger - LANGUAGE plpgsql - AS $$ -DECLARE cfg TEXT; sid TEXT; -BEGIN - IF NEW.agent_id IS NULL OR NEW.agent_id = '' THEN RETURN NEW; END IF; - IF current_setting('router.request_logged', true) = 'on' THEN RETURN NEW; END IF; - PERFORM pg_advisory_xact_lock(hashtextextended(NEW.customer_id, 731)); - SELECT s.config_id,c.session_id INTO cfg,sid FROM calls AS c LEFT JOIN agent_sessions AS s ON s.id=c.session_id WHERE c.customer_id=NEW.customer_id AND c.agent_id=NEW.agent_id AND (NEW.call_id IS NULL OR c.call_id=NEW.call_id) AND c.started_at <= NEW.started_at ORDER BY c.started_at DESC LIMIT 1; - INSERT INTO agent_logs(customer_id,config_id,agent_id,session_id,source,severity,event_type,message,occurred_at,details) - VALUES(NEW.customer_id,coalesce(cfg,''),NEW.agent_id,coalesce(sid,''),'system',CASE WHEN NEW.success OR NEW.error_code = 'cancelled' THEN 'info' ELSE 'error' END, - 'provider_request',NEW.modality || ' request ' || CASE WHEN NEW.error_code = 'cancelled' THEN 'cancelled' WHEN NEW.success THEN 'completed' ELSE 'failed' END,NEW.started_at, - jsonb_build_object('provider',NEW.provider,'model',NEW.model,'request_id',NEW.id::text,'duration_ms',NEW.latency_ms,'input_tokens',NEW.input_tokens,'output_tokens',NEW.output_tokens,'cost_micros',NEW.cost_micros,'error_code',NEW.error_code,'error_message',NEW.error_message)); - RETURN NEW; -END $$; --- +goose StatementEnd - -CREATE TRIGGER agent_request_log AFTER INSERT ON requests FOR EACH ROW EXECUTE FUNCTION log_agent_request(); diff --git a/acceleration/migrations/shard/20270117000400_record_data_change_secrets.sql b/acceleration/migrations/shard/20270117000400_record_data_change_secrets.sql deleted file mode 100644 index e342787679..0000000000 --- a/acceleration/migrations/shard/20270117000400_record_data_change_secrets.sql +++ /dev/null @@ -1,190 +0,0 @@ --- +goose Up - --- The secret columns a change leaves out are passed by the trigger (Store.watchDataChanges) from --- the one Go list (isSecret) rather than kept here as a second copy. --- +goose StatementBegin -CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger - LANGUAGE plpgsql - AS $_$ -DECLARE - subject JSONB; - owner TEXT; - identity JSONB := '{}'::JSONB; - column_name TEXT; - handed_out BIGINT; -BEGIN - IF TG_OP = 'DELETE' THEN - subject := to_jsonb(OLD); - ELSE - subject := to_jsonb(NEW); - END IF; - - -- TG_ARGV[0] is the column holding the customer id, or 'parent' when the row belongs - -- to a customer through another table: TG_ARGV[1] is then the column referencing it - -- and TG_ARGV[2] the table it references. - IF TG_ARGV[0] = 'parent' THEN - EXECUTE format('SELECT customer_id FROM %I WHERE id = $1', TG_ARGV[2]) - INTO owner USING subject ->> TG_ARGV[1]; - ELSE - owner := subject ->> TG_ARGV[0]; - END IF; - - IF owner IS NULL OR owner = '' THEN - RETURN NULL; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM data_change_capture - WHERE customer_id = owner AND expires_at > now() - ) THEN - -- At these two levels every query reads the snapshot of the transaction's first, so a - -- capture started since is not seen here, and the transaction may hold no id yet for - -- Store.WaitForOpenWrites to wait on. Every start updates the one row of - -- data_change_starts. Locking it fails the transaction with a serialization failure if - -- a start committed after its snapshot, and makes a start that comes later wait until it - -- ends (https://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ). - IF current_setting('transaction_isolation') IN ('repeatable read', 'serializable') THEN - PERFORM 1 FROM data_change_starts FOR SHARE; - END IF; - RETURN NULL; - END IF; - - -- TG_ARGV[3] is the table's secret columns as an array literal (store.isSecret, attached by - -- Store.watchDataChanges), and TG_ARGV[4:] the columns naming the row. A trigger attached - -- before the list was passed would record the secrets, so it records nothing and fails. - IF coalesce(left(TG_ARGV[3], 1), '') <> '{' THEN - RAISE EXCEPTION 'record_data_change: % was attached without its secret columns', TG_TABLE_NAME; - END IF; - - FOREACH column_name IN ARRAY TG_ARGV[4:] LOOP - identity := identity || jsonb_build_object(column_name, subject -> column_name); - END LOOP; - - -- Credentials are left behind. A secret this deployment sealed is worth nothing to - -- the one reading it, and an access token a customer's user granted to this - -- deployment is not something to hand out because somebody asked for their data. - subject := subject - TG_ARGV[3]::text[]; - - -- A change is numbered when it is written and seen when its transaction commits, so no - -- committed row tells a reader which lower number a transaction still running holds. - -- Before its first change, a transaction takes a shared advisory lock keyed by the - -- highest number handed out so far, below every number it will be given, and holds it - -- until it ends. pg_locks shows a lock as soon as it is taken, and Postgres releases it - -- only once the commit is visible (CommitTransaction in src/backend/access/transam/xact.c: - -- "this must be done _before_ releasing locks we hold"). Store.changeWatermark reads - -- these locks. The key - -- is the number's two halves in the two-integer key space; the other two-integer locks - -- here start at 839 << 32, a number no feed reaches. The setting, local to the - -- transaction, takes it once rather than once per row. - IF coalesce(current_setting('data_changes.bounded', true), '') = '' THEN - SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END - INTO handed_out FROM data_changes_seq_seq; - PERFORM pg_advisory_xact_lock_shared((handed_out >> 32)::int, ((handed_out << 32) >> 32)::int); - PERFORM set_config('data_changes.bounded', 'on', true); - END IF; - - INSERT INTO data_changes (customer_id, table_name, op, key, payload) - VALUES ( - owner, - TG_TABLE_NAME, - lower(TG_OP), - identity, - CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE subject END - ); - RETURN NULL; -END; -$_$; --- +goose StatementEnd - --- A call bridge is no longer carried by a move (store.dataTables): its key is the token that --- authenticates the fetch. -DROP TRIGGER IF EXISTS data_changes_recorded ON call_bridges; - --- +goose Down - --- +goose StatementBegin -CREATE OR REPLACE FUNCTION record_data_change() RETURNS trigger - LANGUAGE plpgsql - AS $_$ -DECLARE - subject JSONB; - owner TEXT; - identity JSONB := '{}'::JSONB; - column_name TEXT; - handed_out BIGINT; -BEGIN - IF TG_OP = 'DELETE' THEN - subject := to_jsonb(OLD); - ELSE - subject := to_jsonb(NEW); - END IF; - - -- TG_ARGV[0] is the column holding the customer id, or 'parent' when the row belongs - -- to a customer through another table: TG_ARGV[1] is then the column referencing it - -- and TG_ARGV[2] the table it references. - IF TG_ARGV[0] = 'parent' THEN - EXECUTE format('SELECT customer_id FROM %I WHERE id = $1', TG_ARGV[2]) - INTO owner USING subject ->> TG_ARGV[1]; - ELSE - owner := subject ->> TG_ARGV[0]; - END IF; - - IF owner IS NULL OR owner = '' THEN - RETURN NULL; - END IF; - IF NOT EXISTS ( - SELECT 1 FROM data_change_capture - WHERE customer_id = owner AND expires_at > now() - ) THEN - -- At these two levels every query reads the snapshot of the transaction's first, so a - -- capture started since is not seen here, and the transaction may hold no id yet for - -- Store.WaitForOpenWrites to wait on. Every start updates the one row of - -- data_change_starts. Locking it fails the transaction with a serialization failure if - -- a start committed after its snapshot, and makes a start that comes later wait until it - -- ends (https://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ). - IF current_setting('transaction_isolation') IN ('repeatable read', 'serializable') THEN - PERFORM 1 FROM data_change_starts FOR SHARE; - END IF; - RETURN NULL; - END IF; - - FOREACH column_name IN ARRAY TG_ARGV[3:] LOOP - identity := identity || jsonb_build_object(column_name, subject -> column_name); - END LOOP; - - -- Credentials are left behind. A secret this deployment sealed is worth nothing to - -- the one reading it, and an access token a customer's user granted to this - -- deployment is not something to hand out because somebody asked for their data. - subject := subject - 'secret_sealed' - 'access_token' - 'refresh_token' - - 'oauth_state' - 'code_verifier' - 'credentials_sealed' - 'password_sealed' - - 'bridge_password_sealed' - 'refresh_secret_hash'; - - -- A change is numbered when it is written and seen when its transaction commits, so no - -- committed row tells a reader which lower number a transaction still running holds. - -- Before its first change, a transaction takes a shared advisory lock keyed by the - -- highest number handed out so far, below every number it will be given, and holds it - -- until it ends. pg_locks shows a lock as soon as it is taken, and Postgres releases it - -- only once the commit is visible (CommitTransaction in src/backend/access/transam/xact.c: - -- "this must be done _before_ releasing locks we hold"). Store.changeWatermark reads - -- these locks. The key - -- is the number's two halves in the two-integer key space; the other two-integer locks - -- here start at 839 << 32, a number no feed reaches. The setting, local to the - -- transaction, takes it once rather than once per row. - IF coalesce(current_setting('data_changes.bounded', true), '') = '' THEN - SELECT CASE WHEN is_called THEN last_value ELSE last_value - 1 END - INTO handed_out FROM data_changes_seq_seq; - PERFORM pg_advisory_xact_lock_shared((handed_out >> 32)::int, ((handed_out << 32) >> 32)::int); - PERFORM set_config('data_changes.bounded', 'on', true); - END IF; - - INSERT INTO data_changes (customer_id, table_name, op, key, payload) - VALUES ( - owner, - TG_TABLE_NAME, - lower(TG_OP), - identity, - CASE WHEN TG_OP = 'DELETE' THEN NULL ELSE subject END - ); - RETURN NULL; -END; -$_$; --- +goose StatementEnd diff --git a/acceleration/migrations/shard/20270118000000_call_legs_unanswered_idx.sql b/acceleration/migrations/shard/20270118000000_call_legs_unanswered_idx.sql deleted file mode 100644 index f8f33e8c70..0000000000 --- a/acceleration/migrations/shard/20270118000000_call_legs_unanswered_idx.sql +++ /dev/null @@ -1,11 +0,0 @@ --- +goose NO TRANSACTION --- +goose Up - --- The outbound legs that ended unanswered, which a join delivered again after its call ended --- revives (CallLegs.Connect). Built without stopping the writes of legs; a build that fails is --- built again in Go (store.usageIndexes). -CREATE INDEX CONCURRENTLY IF NOT EXISTS call_legs_unanswered_idx - ON call_legs (call_type, call_id) WHERE direction = 'outbound' AND end_reason = 'unanswered'; - --- +goose Down -DROP INDEX CONCURRENTLY IF EXISTS call_legs_unanswered_idx; diff --git a/acceleration/migrations/shard/20270118000100_calls_session_started_idx.sql b/acceleration/migrations/shard/20270118000100_calls_session_started_idx.sql deleted file mode 100644 index a9df49ad92..0000000000 --- a/acceleration/migrations/shard/20270118000100_calls_session_started_idx.sql +++ /dev/null @@ -1,15 +0,0 @@ --- +goose NO TRANSACTION --- +goose Up - --- A session's calls, led by session_id: deleting a session sets session_id to NULL on its --- calls (calls_session_id_fkey), by session_id alone, which skip-scanned every customer of --- calls_session_idx. Built without stopping the writes of calls; a build that fails is built --- again in Go (store.usageIndexes). -CREATE INDEX CONCURRENTLY IF NOT EXISTS calls_session_started_idx - ON calls (session_id, started_at DESC) WHERE session_id IS NOT NULL; -DROP INDEX CONCURRENTLY IF EXISTS calls_session_idx; - --- +goose Down -CREATE INDEX CONCURRENTLY IF NOT EXISTS calls_session_idx - ON calls (customer_id, session_id, started_at DESC) WHERE session_id IS NOT NULL; -DROP INDEX CONCURRENTLY IF EXISTS calls_session_started_idx; diff --git a/acceleration/migrations/shard/20270124000000_hash_call_tokens.sql b/acceleration/migrations/shard/20270124000000_hash_call_tokens.sql deleted file mode 100644 index d462aca414..0000000000 --- a/acceleration/migrations/shard/20270124000000_hash_call_tokens.sql +++ /dev/null @@ -1,47 +0,0 @@ --- +goose Up - --- A call leg's token and a call bridge's are kept as the hex SHA-256 of the token, in --- token_hash, and a bridge's trunk password sealed (phone.Service.park), so the tables hold --- neither the bearer value a vendor presents nor the password. Only columns are added: token --- and trunk_password stay, nullable, for the release before, which still reads and writes them --- while it runs beside this one, and this release writes neither. A later migration drops them --- once no router of the release before can run against the database. --- --- The legs whose token is still set (a status url not yet retired, phone.SweepStatusTokens) --- are hashed in place and their token cleared, so this release finds the status posts of calls --- in flight and the release before misses them. A bridge parked before is left to the release --- that parked it, and is deleted by the phone sweep once it expires. The lock waits at most 5 s --- behind a running query, past which the migration fails and the router's next start tries --- again. -SET LOCAL lock_timeout = '5s'; - -ALTER TABLE call_legs ADD COLUMN token_hash text; -UPDATE call_legs SET token_hash = encode(sha256(convert_to(token, 'UTF8')), 'hex'), token = NULL -WHERE token IS NOT NULL; - -ALTER TABLE call_bridges - DROP CONSTRAINT call_bridges_pkey, - ALTER COLUMN token DROP NOT NULL, - ADD CONSTRAINT call_bridges_token_key UNIQUE (token), - ADD COLUMN token_hash text, - ADD CONSTRAINT call_bridges_token_hash_key UNIQUE (token_hash), - ADD COLUMN trunk_password_sealed BYTEA, - ADD COLUMN trunk_password_kek_version INTEGER; - --- +goose Down - --- A hash gives no token back: the status urls of the calls this release placed are refused from --- here on, and the bridges it parked are deleted. -SET LOCAL lock_timeout = '5s'; - -ALTER TABLE call_legs DROP COLUMN token_hash; - -DELETE FROM call_bridges WHERE token IS NULL; -ALTER TABLE call_bridges - DROP CONSTRAINT call_bridges_token_hash_key, - DROP COLUMN token_hash, - DROP COLUMN trunk_password_sealed, - DROP COLUMN trunk_password_kek_version, - DROP CONSTRAINT call_bridges_token_key, - ALTER COLUMN token SET NOT NULL, - ADD CONSTRAINT call_bridges_pkey PRIMARY KEY (token); diff --git a/acceleration/migrations/shard/20270124000100_call_legs_token_hash_idx.sql b/acceleration/migrations/shard/20270124000100_call_legs_token_hash_idx.sql deleted file mode 100644 index c1cf7e0563..0000000000 --- a/acceleration/migrations/shard/20270124000100_call_legs_token_hash_idx.sql +++ /dev/null @@ -1,13 +0,0 @@ --- +goose NO TRANSACTION --- +goose Up - --- The placed leg a status post is about, found by its token's hash (CallLegs.GetByToken), and --- the legs whose status url is still open, which phone.SweepStatusTokens retires. Built without --- stopping the writes of legs; a build that fails is built again in Go (store.usageIndexes). -CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS call_legs_token_hash_key ON call_legs (token_hash); -CREATE INDEX CONCURRENTLY IF NOT EXISTS call_legs_token_hash_placed_idx - ON call_legs (placed_at) WHERE token_hash IS NOT NULL; - --- +goose Down -DROP INDEX CONCURRENTLY IF EXISTS call_legs_token_hash_placed_idx; -DROP INDEX CONCURRENTLY IF EXISTS call_legs_token_hash_key; diff --git a/acceleration/migrations/shard/20270126000000_requests_source_usage_id.sql b/acceleration/migrations/shard/20270126000000_requests_source_usage_id.sql deleted file mode 100644 index 37340481fb..0000000000 --- a/acceleration/migrations/shard/20270126000000_requests_source_usage_id.sql +++ /dev/null @@ -1,8 +0,0 @@ --- +goose Up - --- The usage id a request had where it was first recorded, kept by an import, which gives the row --- a usage id of this deployment's: a row taken back where it was recorded is then known there. -ALTER TABLE requests ADD COLUMN IF NOT EXISTS source_usage_id uuid; - --- +goose Down -ALTER TABLE requests DROP COLUMN IF EXISTS source_usage_id; diff --git a/acceleration/migrations/squash/cleanup.sql b/acceleration/migrations/squash/cleanup.sql new file mode 100644 index 0000000000..3edeaf3c3d --- /dev/null +++ b/acceleration/migrations/squash/cleanup.sql @@ -0,0 +1,309 @@ +-- Squash cleanup: rewrites a database's migration tracking from the history squashed into each +-- set's initial migration (20270110000000_initial.sql) to that initial migration alone, the +-- "fake apply". Run it once on every database, after every router using it runs a release with +-- the squashed migrations: a release from before would run the history again on the rewritten +-- tracking. There is no going back to such a release once it has run. +-- +-- psql "$DSN" -v set=global|shard|both [-v apply=1] [-v drop_strays=1] [-v show=1] -f cleanup.sql +-- +-- set is the migration sets the database holds: global for the shared database, shard for a +-- region's own, both for a deployment of one database. Without apply=1 every step runs and is +-- rolled back. In one transaction, under the router's migrate lock, it: +-- +-- 1. refuses a database whose schema is not exactly the initial migrations', by a fingerprint +-- of its catalogue taken from a database the initial migrations made (show=1 prints the +-- lines fingerprinted, to diff against that database's); +-- 2. refuses a tracking table that does not record exactly the squashed history: one short +-- of it, or holding a version of a branch's own; +-- 3. leaves each tracking table recording the initial migration only; +-- 4. drops goose_db_version, which tracked the single history from before the split; +-- 5. with apply=1, recreates limits_level_check as the initial migration writes it: a +-- database made before Postgres 18 keeps the nesting of its OR chain, which a new one +-- flattens, though they check the same; +-- 6. with drop_strays=1, drops the empty tables of the other set a database kept from before +-- the split, and the functions only they used. One holding rows is left for a person. +-- +-- A database it already cleaned is checked and left as it is. + +\set ON_ERROR_STOP on +\set QUIET on + +\if :{?set} +\else + \echo 'usage: psql "$DSN" -v set=global|shard|both [-v apply=1] [-v drop_strays=1] [-v show=1] -f cleanup.sql' + SELECT 1/0 AS set_is_required; +\endif +\if :{?apply} +\else + \set apply 0 +\endif +\if :{?drop_strays} +\else + \set drop_strays 0 +\endif +\if :{?show} +\else + \set show 0 +\endif + +\set initial 20270110000000 + +\set global_versions '{20270110000000,20270111000000,20270112000000,20270112000100,20270112000200,20270112000300,20270113000000,20270113000001,20270113000002,20270115000100,20270115000200,20270115000300,20270115000400,20270115000500,20270116000000,20270116000002,20270116000003,20270117000300,20270117000400,20270119000000,20270122000000,20270122000100,20270123021810,20270124093000}' +\set shard_versions '{20270110000000,20270114000000,20270116000001,20270116000004,20270117000100,20270117000400,20270118000000,20270118000100,20270124000000,20270124000100,20270126000000}' + +\set global_tables '{activity_digests,agent_configs,agent_logs,api_keys,app_organizations,apps,audit_log,business_profiles,campaign_attempts,campaign_contacts,campaigns,channel_accounts,channel_deliveries,channel_link_failures,channel_links,channel_thread_inbound,channel_thread_members,channel_thread_messages,channel_thread_waiting,channel_threads,channel_turns,chat_inbound,connection_event_subscriptions,connector_audit,connector_authorization_attempts,connector_broken_revisions,connector_config_tokens,connector_connections,connector_definitions,connector_event_deliveries,connector_event_destinations,connector_invocations,connector_oauth_clients,connector_tool_pins,contact_map,custom_models,customer_activity,data_change_capture,data_change_starts,data_changes,data_move_cursors,deliveries_seen,dlc_review_logs,dlc_use_cases,episodes,image_jobs,knowledge_documents,knowledge_namespaces,knowledge_urls,limit_grant_reconciles,limit_grant_uses,limit_grants,limits,notices,opt_outs,organization_tiers,organizations,phone_numbers,policies,price_changes,price_list_entries,provider_keys,router_configs,sandbox_recipients,scheduled_task_runs,scheduled_tasks,simulation_cases,simulation_runs,simulations,sip_trunks,skills,stream_app_tokens,stream_fallback_uses,stream_trunks,telephony_suspensions,usage_resets,user_phone_history,user_phones,users,voice_bindings,voice_samples,voices}' +\set global_sequences '{agent_logs_id_seq,campaign_contacts_seq_seq,channel_thread_inbound_seq_seq,chat_inbound_seq_seq,data_changes_seq_seq,limit_grants_id_seq,limits_id_seq,phone_numbers_id_seq,price_entries_id_seq,usage_resets_id_seq}' +\set global_functions '{price_changes_guard,price_entries_guard,record_data_change}' + +\set shard_tables '{agent_branch_messages,agent_branch_switches,agent_response_items,agent_responses,agent_session_tools,agent_sessions,call_bridges,call_legs,call_participants,call_resources,calls,conversation_documents,data_change_capture,data_change_starts,data_changes,recordings,requests,stats_daily,stats_hourly,stats_tags_daily,stats_tags_hourly,turn_latency_hourly,turn_stats_hourly}' +\set shard_sequences '{call_legs_id_seq,call_participants_id_seq,call_resources_id_seq,data_changes_seq_seq,stt_requests_id_seq}' +\set shard_functions '{record_data_change}' + +-- The fingerprint of each kind of database the initial migrations make, on Postgres 18. +\set global_fingerprint '33b23c834d6849661a29da3c6fd22682' +\set shard_fingerprint 'fffce33c2a9db8243625ebe3e3e6644a' +\set both_fingerprint 'e7edc5427addf775bf3a35331b0b0f09' + +\set limits_level_check 'CHECK ((((subject = ''organization''::text) AND (level = ''organization''::text)) OR ((subject = ''app''::text) AND (level = ''app''::text)) OR ((subject = ''api_key''::text) AND (level = ''organization''::text)) OR ((subject = ''api_key''::text) AND (level = ''app''::text)) OR ((subject = ''api_key''::text) AND (level = ''api_key''::text)) OR ((subject = ''user''::text) AND (level = ''organization''::text)) OR ((subject = ''user''::text) AND (level = ''app''::text)) OR ((subject = ''user''::text) AND (level = ''user''::text)) OR ((subject = ''category''::text) AND (level = ''organization''::text)) OR ((subject = ''app_category''::text) AND (level = ''app''::text))))' + +BEGIN; +-- A router waiting on a lock this holds waits with it; this waits on nobody for long. +SET LOCAL lock_timeout = '5s'; +SET LOCAL statement_timeout = '5min'; + +CREATE TEMP TABLE squash_sets ON COMMIT DROP AS +SELECT name, 'goose_' || name || '_version' AS tracker, versions::bigint[] AS versions +FROM (VALUES ('global', :'global_versions'), ('shard', :'shard_versions')) AS sets (name, versions) +WHERE :'set' IN (name, 'both'); + +CREATE TEMP TABLE squash_plan ON COMMIT DROP AS +SELECT + ARRAY(SELECT DISTINCT unnest(CASE WHEN :'set' IN ('global', 'both') THEN :'global_tables'::text[] END + || CASE WHEN :'set' IN ('shard', 'both') THEN :'shard_tables'::text[] END)) AS tables, + ARRAY(SELECT DISTINCT unnest(CASE WHEN :'set' IN ('global', 'both') THEN :'global_sequences'::text[] END + || CASE WHEN :'set' IN ('shard', 'both') THEN :'shard_sequences'::text[] END)) AS sequences, + ARRAY(SELECT DISTINCT unnest(CASE WHEN :'set' IN ('global', 'both') THEN :'global_functions'::text[] END + || CASE WHEN :'set' IN ('shard', 'both') THEN :'shard_functions'::text[] END)) AS functions, + CASE :'set' WHEN 'global' THEN :'global_fingerprint' WHEN 'shard' THEN :'shard_fingerprint' WHEN 'both' THEN :'both_fingerprint' END + AS fingerprint, + :apply::int = 1 AS apply, + :drop_strays::int = 1 AS drop_strays, + :'limits_level_check'::text AS limits_level_check; + +DO $$ +BEGIN + IF (SELECT fingerprint IS NULL FROM squash_plan) THEN + RAISE EXCEPTION 'set must be global, shard or both'; + END IF; +END $$; + +DO $$ +BEGIN + PERFORM pg_advisory_xact_lock(hashtextextended('router.migrate', 0)); +END $$; + +-- 5. Before the fingerprint, so that it is taken of what the initial migration writes. +DO $$ +DECLARE + plan squash_plan; + held text; +BEGIN + SELECT * INTO plan FROM squash_plan; + SELECT pg_get_constraintdef(oid) INTO held FROM pg_constraint + WHERE conname = 'limits_level_check' AND conrelid = to_regclass('public.limits'); + IF NOT plan.apply OR held IS NULL OR held = plan.limits_level_check THEN + RETURN; + END IF; + EXECUTE 'ALTER TABLE limits DROP CONSTRAINT limits_level_check, ADD CONSTRAINT limits_level_check ' || plan.limits_level_check; + RAISE NOTICE 'recreated limits_level_check as the initial migration writes it'; +END $$; + +-- 1. What the set's objects are, each as one line. Neither owners nor the data_changes_recorded +-- triggers the router attaches as it starts are the migrations'. A CHECK is compared without +-- its parentheses, which only the nesting of an OR chain made before Postgres 18 differs in. +CREATE TEMP TABLE squash_described ON COMMIT DROP AS +WITH plan AS (SELECT * FROM squash_plan), +tables AS ( + SELECT c.oid, c.relname, c.relkind, c.relpersistence, c.reloptions + FROM pg_class c, plan + WHERE c.relnamespace = 'public'::regnamespace AND c.relkind IN ('r', 'p') AND c.relname = ANY (plan.tables) +) +SELECT format('table %s %s %s %s', relname, relkind, relpersistence, coalesce(array_to_string(reloptions, ','), '')) AS line +FROM tables +UNION ALL +SELECT format('missing %s', expected) +FROM plan, unnest(plan.tables || plan.sequences) AS expected +WHERE to_regclass('public.' || expected) IS NULL +UNION ALL +SELECT format('column %s %s %s %s %s %s %s %s %s', t.relname, + row_number() OVER (PARTITION BY t.oid ORDER BY a.attnum), a.attname, format_type(a.atttypid, a.atttypmod), + a.attnotnull, a.attidentity, a.attgenerated, a.attcollation::regcollation, coalesce(pg_get_expr(d.adbin, d.adrelid), '')) +FROM tables t +JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum > 0 AND NOT a.attisdropped +LEFT JOIN pg_attrdef d ON d.adrelid = t.oid AND d.adnum = a.attnum +UNION ALL +SELECT format('constraint %s %s %s %s %s %s', t.relname, co.conname, co.contype, co.convalidated, co.condeferrable, + CASE co.contype WHEN 'c' THEN translate(pg_get_constraintdef(co.oid), '()', '') ELSE pg_get_constraintdef(co.oid) END) +FROM tables t +JOIN pg_constraint co ON co.conrelid = t.oid +UNION ALL +SELECT format('index %s %s', pg_get_indexdef(i.indexrelid), i.indisvalid) +FROM tables t +JOIN pg_index i ON i.indrelid = t.oid +UNION ALL +SELECT format('trigger %s %s', pg_get_triggerdef(tg.oid), tg.tgenabled) +FROM tables t +JOIN pg_trigger tg ON tg.tgrelid = t.oid AND NOT tg.tgisinternal AND tg.tgname <> 'data_changes_recorded' +UNION ALL +SELECT format('function %s %s', p.proname, md5(pg_get_functiondef(p.oid))) +FROM pg_proc p, plan +WHERE p.pronamespace = 'public'::regnamespace AND p.proname = ANY (plan.functions) +UNION ALL +SELECT format('sequence %s %s %s %s %s %s %s %s %s', c.relname, format_type(s.seqtypid, NULL), s.seqstart, s.seqincrement, + s.seqmin, s.seqmax, s.seqcache, s.seqcycle, coalesce(owner.name, '')) +FROM pg_sequence s +JOIN pg_class c ON c.oid = s.seqrelid +CROSS JOIN plan +LEFT JOIN LATERAL ( + SELECT r.relname || '.' || a.attname AS name + FROM pg_depend dep + JOIN pg_class r ON r.oid = dep.refobjid + JOIN pg_attribute a ON a.attrelid = r.oid AND a.attnum = dep.refobjsubid + WHERE dep.classid = 'pg_class'::regclass AND dep.objid = c.oid AND dep.deptype = 'a' +) owner ON true +WHERE c.relnamespace = 'public'::regnamespace AND c.relname = ANY (plan.sequences); + +\if :show +SELECT line FROM squash_described ORDER BY line; +\endif + +DO $$ +DECLARE + expected text := (SELECT fingerprint FROM squash_plan); + held text := (SELECT md5(string_agg(line, E'\n' ORDER BY line)) FROM squash_described); +BEGIN + IF held <> expected THEN + RAISE EXCEPTION 'the schema is not the initial migrations'': fingerprint % where % was expected; rerun with -v show=1 and diff the lines against a database the initial migrations made', held, expected; + END IF; + RAISE NOTICE 'the schema is the initial migrations'' (%)', held; +END $$; + +-- 2 and 3. +DO $$ +DECLARE + plan squash_plan; + s squash_sets; + recorded bigint[]; + missing bigint[]; + extra bigint[]; +BEGIN + SELECT * INTO plan FROM squash_plan; + FOR s IN SELECT * FROM squash_sets ORDER BY name LOOP + IF to_regclass('public.' || s.tracker) IS NULL THEN + RAISE EXCEPTION '% does not exist: this database never ran the % set', s.tracker, s.name; + END IF; + EXECUTE format('SELECT coalesce(array_agg(DISTINCT version_id ORDER BY version_id), ''{}'') FROM %I WHERE is_applied AND version_id <> 0', s.tracker) + INTO recorded; + IF recorded = ARRAY[20270110000000::bigint] THEN + RAISE NOTICE '% already records the initial migration alone', s.tracker; + CONTINUE; + END IF; + missing := ARRAY(SELECT unnest(s.versions) EXCEPT SELECT unnest(recorded) ORDER BY 1); + extra := ARRAY(SELECT unnest(recorded) EXCEPT SELECT unnest(s.versions) ORDER BY 1); + IF missing <> '{}' THEN + RAISE EXCEPTION '% has not applied %, of the history squashed into the initial migration', s.tracker, missing; + END IF; + IF extra <> '{}' THEN + RAISE EXCEPTION '% records %, which the squashed history does not hold: a branch migrated this database', s.tracker, extra; + END IF; + EXECUTE format('DELETE FROM %I WHERE version_id <> 0', s.tracker); + EXECUTE format('INSERT INTO %I (version_id, is_applied) VALUES (20270110000000, true)', s.tracker); + RAISE NOTICE '% recorded % versions; it now records the initial migration alone', s.tracker, cardinality(recorded); + END LOOP; +END $$; + +-- 4. The ledger keeps its own versions in a goose_db_version too, numbered from 1, in a database +-- of its own; one holding such a version is not the router's to drop. +DO $$ +BEGIN + IF to_regclass('public.goose_db_version') IS NULL THEN + RETURN; + END IF; + IF EXISTS (SELECT 1 FROM goose_db_version WHERE version_id BETWEEN 1 AND 20000000000000) THEN + RAISE NOTICE 'left goose_db_version: it holds versions that are not the router''s'; + RETURN; + END IF; + DROP TABLE goose_db_version; + RAISE NOTICE 'dropped goose_db_version, the single history''s tracking from before the split'; +END $$; + +-- 6. A stray another stray points at is dropped on a later pass, once the one pointing is gone. +DO $$ +DECLARE + plan squash_plan; + strays text[]; + kept text[]; + stray text; + empty boolean; + dropped int := 0; +BEGIN + SELECT * INTO plan FROM squash_plan; + IF NOT plan.drop_strays THEN + RETURN; + END IF; + strays := ARRAY( + SELECT relname FROM pg_class + WHERE relnamespace = 'public'::regnamespace AND relkind IN ('r', 'p') + AND relname <> ALL (plan.tables) AND relname NOT LIKE 'goose\_%' + ORDER BY relname); + LOOP + kept := '{}'; + FOREACH stray IN ARRAY strays LOOP + EXECUTE format('SELECT NOT EXISTS (SELECT 1 FROM %I)', stray) INTO empty; + IF NOT empty THEN + RAISE NOTICE 'left stray %: it holds rows', stray; + CONTINUE; + END IF; + BEGIN + EXECUTE format('DROP TABLE %I', stray); + dropped := dropped + 1; + EXCEPTION WHEN dependent_objects_still_exist THEN + kept := kept || stray; + END; + END LOOP; + EXIT WHEN kept = '{}' OR cardinality(kept) = cardinality(strays); + strays := kept; + END LOOP; + IF kept <> '{}' THEN + RAISE NOTICE 'left strays %: a table holding rows points at them', kept; + END IF; + FOR stray IN + SELECT c.relname FROM pg_class c + WHERE c.relnamespace = 'public'::regnamespace AND c.relkind = 'S' + AND c.relname <> ALL (plan.sequences) AND c.relname NOT LIKE 'goose\_%' + AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass AND d.objid = c.oid AND d.deptype IN ('a', 'i')) + LOOP + EXECUTE format('DROP SEQUENCE %I', stray); + RAISE NOTICE 'dropped stray sequence %', stray; + END LOOP; + FOR stray IN + SELECT p.oid::regprocedure::text FROM pg_proc p + WHERE p.pronamespace = 'public'::regnamespace AND p.proname <> ALL (plan.functions) + LOOP + BEGIN + EXECUTE format('DROP FUNCTION %s', stray); + RAISE NOTICE 'dropped stray function %', stray; + EXCEPTION WHEN dependent_objects_still_exist THEN + RAISE NOTICE 'left stray function %: a trigger left with its table uses it', stray; + END; + END LOOP; + RAISE NOTICE 'dropped % empty stray tables', dropped; +END $$; + +\if :apply +COMMIT; +\echo 'committed' +\else +ROLLBACK; +\echo 'dry run: rolled back; rerun with -v apply=1 to commit' +\endif diff --git a/acceleration/migrations/squash/run.sh b/acceleration/migrations/squash/run.sh new file mode 100755 index 0000000000..7d6b4d56cd --- /dev/null +++ b/acceleration/migrations/squash/run.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# Runs cleanup.sql on one router database from a short-lived psql pod in the router's namespace, +# with the DSN read from accelerate-secrets, then deletes the pod. A dry run unless --apply. +# +# run.sh [--apply] [--drop-strays] [--show] +# +# Each database, once every router using it runs a release with the squashed migrations: +# +# run.sh us-east1 accelerate-staging ROUTER_POSTGRES_DSN both staging, one database +# run.sh us-east4 accelerate-prod ROUTER_POSTGRES_DSN global the shared database +# run.sh us-east4 accelerate-prod ROUTER_POSTGRES_SHARD_DSN shard each region's own +# run.sh us-west1 accelerate-prod ROUTER_POSTGRES_SHARD_DSN shard +# run.sh europe-west4 accelerate-prod ROUTER_POSTGRES_SHARD_DSN shard +set -euo pipefail + +if [[ $# -lt 4 ]]; then + sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//' + exit 2 +fi +region=$1 namespace=$2 key=$3 set=$4 +shift 4 +flags="" +for flag in "$@"; do + case $flag in + --apply) flags+=" -v apply=1" ;; + --drop-strays) flags+=" -v drop_strays=1" ;; + --show) flags+=" -v show=1" ;; + *) echo "unknown flag $flag" >&2; exit 2 ;; + esac +done +case $set in global | shard | both) ;; *) echo "set must be global, shard or both" >&2; exit 2 ;; esac + +context="gke_stream-gcp-2026-v2_${region}_${region}-acceleration" +pod="squash-cleanup-$(date +%s)" +script=$(base64 < "$(dirname "$0")/cleanup.sql" | tr -d '\n') + +kubectl --context "$context" -n "$namespace" apply -f - >/dev/null < /tmp/cleanup.sql && psql "\$DSN" -X -v set=${set}${flags} -f /tmp/cleanup.sql + securityContext: + allowPrivilegeEscalation: false + capabilities: {drop: [ALL]} + resources: + requests: {cpu: 100m, memory: 128Mi} + limits: {memory: 128Mi} + env: + - name: SCRIPT + value: "${script}" + - name: DSN + valueFrom: + secretKeyRef: {name: accelerate-secrets, key: ${key}} +EOF + +trap 'kubectl --context "$context" -n "$namespace" delete pod "$pod" --wait=false >/dev/null 2>&1 || true' EXIT +phase=Pending +for _ in $(seq 1 150); do + phase=$(kubectl --context "$context" -n "$namespace" get pod "$pod" -o jsonpath='{.status.phase}') + [[ $phase == Succeeded || $phase == Failed ]] && break + sleep 2 +done +echo "== $region $namespace $key ($set):$flags" +kubectl --context "$context" -n "$namespace" logs "$pod" +[[ $phase == Succeeded ]] From 86572834d5a2e236feaf63efc3958ba9ad5ffad3 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 19:04:00 +0100 Subject: [PATCH 5/8] AI-3479: test that Link draws a fresh code per call Co-Authored-By: Claude Sonnet 5.5 --- acceleration/internal/api/channels_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/acceleration/internal/api/channels_test.go b/acceleration/internal/api/channels_test.go index 11cb23fc56..ac6495ccda 100644 --- a/acceleration/internal/api/channels_test.go +++ b/acceleration/internal/api/channels_test.go @@ -756,6 +756,19 @@ func (s *ChannelsSuite) TestACodeThatCannotBeWrittenIsA500WithoutTheStoresWords( 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) From f729893302dcb64d21f1a5e4f434e4abf7d8cb0c Mon Sep 17 00:00:00 2001 From: Tommaso Barbugli Date: Mon, 23 Nov 2026 19:55:08 +0100 Subject: [PATCH 6/8] fix(store): start on a database a later release migrated Once the cleanup has removed the squashed history, a database rolled back from a release with a newer migration holds a version with no file and no squashed one, which checkHistory took for a partial history. Only a version inside the squashed history counts as one. --- acceleration/internal/store/migrate.go | 6 ++++-- acceleration/internal/store/migrate_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/store/migrate.go b/acceleration/internal/store/migrate.go index 1a8d7dfcb1..54fb1eb4e8 100644 --- a/acceleration/internal/store/migrate.go +++ b/acceleration/internal/store/migrate.go @@ -111,7 +111,9 @@ func (s *Store) migrate(ctx context.Context, dsn string, set migrationSet) error // the initial migration would otherwise be wrong about: one that ran the single history from // before the split, on which it would fail to create tables already there, and one that ran // part of the history squashed into it, whose missing migrations it would claim as applied. -// One that ran the whole history holds the initial migration's schema and starts as it is. +// One that ran the whole history holds the initial migration's schema and starts as it is, and +// so does one cleaned of it once deployed, which holds no version of it. A version after the +// squashed history with no file is a later release's, from before a rollback to this one. func checkHistory(ctx context.Context, conn *sql.Conn, provider *goose.Provider, set migrationSet) error { var recorded, legacy bool err := conn.QueryRowContext(ctx, "SELECT to_regclass($1) IS NOT NULL, to_regclass($2) IS NOT NULL", set.table, set.marker).Scan(&recorded, &legacy) @@ -142,7 +144,7 @@ func checkHistory(ctx context.Context, conn *sql.Conn, provider *goose.Provider, if err := rows.Scan(&version); err != nil { return fmt.Errorf("store: migrate %s: %w", set.name, err) } - unknown = unknown || !known[version] + unknown = unknown || (!known[version] && version < set.squashed) squashed = squashed || version == set.squashed } if err := rows.Err(); err != nil { diff --git a/acceleration/internal/store/migrate_test.go b/acceleration/internal/store/migrate_test.go index c9a6f48f07..4744afa97f 100644 --- a/acceleration/internal/store/migrate_test.go +++ b/acceleration/internal/store/migrate_test.go @@ -110,6 +110,22 @@ func (s *StoreSuite) TestARolledBackVersionWithNoFileIsNotRefused() { s.Require().NoError(db.Migrate(s.ctx)) } +// A database a later release migrated holds versions this one has no file for, after the +// squashed history and before any of it is recorded once the cleanup has run: rolling back to +// this release starts on it. +func (s *StoreSuite) TestADatabaseALaterReleaseMigratedStartsAfterTheCleanup() { + db, err := Open(s.emptyDatabase("later_release")) + s.Require().NoError(err) + defer db.Close() + s.Require().NoError(db.Migrate(s.ctx)) + for _, set := range []migrationSet{globalSet, shardSet} { + _, err = db.global.ExecContext(s.ctx, "INSERT INTO ? (version_id, is_applied) VALUES (29991231000000, true)", bun.Ident(set.table)) + s.Require().NoError(err) + } + + s.Require().NoError(db.Migrate(s.ctx)) +} + // shardTo opens an empty database of the suite's own with the shared set applied and the shard // set up to version, the order Migrate runs them in. func (s *StoreSuite) shardTo(name string, version int64) *Store { From 5d36bef3e8643f418b086dbc451d8b7d8021ec83 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:09:11 +0100 Subject: [PATCH 7/8] AI-3479: set a lock timeout before the channel_links key swap Co-Authored-By: Claude Sonnet 5.5 --- .../global/20270128000000_channel_links_per_customer.sql | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql index fdb858b8b4..8a92e66fc0 100644 --- a/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql +++ b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql @@ -1,5 +1,7 @@ -- +goose Up +SET LOCAL lock_timeout = '5s'; + -- A link code is claimed on the app's own lines, so it needs to be unique only within the app: -- keyed on the code alone, every app drew from one space of codes, and a code one app held -- failed another app's link. The new key refuses nothing the old one let through, so an older @@ -12,6 +14,8 @@ ALTER TABLE channel_links -- +goose Down +SET LOCAL lock_timeout = '5s'; + -- Two apps may hold one code now: all but one app's are dropped, and those links fail. DELETE FROM channel_links held USING channel_links kept WHERE held.code = kept.code AND held.customer_id > kept.customer_id; From fe90e4e55ae66cdb5bc1ff7abe86af740159c494 Mon Sep 17 00:00:00 2001 From: Kanat Date: Mon, 23 Nov 2026 20:45:29 +0100 Subject: [PATCH 8/8] AI-3479: one lock_timeout per migration section Co-Authored-By: Claude Opus 5.5 --- .../global/20270128000000_channel_links_per_customer.sql | 4 ---- 1 file changed, 4 deletions(-) diff --git a/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql index d77e618016..6c7bfed446 100644 --- a/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql +++ b/acceleration/migrations/global/20270128000000_channel_links_per_customer.sql @@ -1,8 +1,6 @@ -- +goose Up SET LOCAL lock_timeout = '5s'; -SET LOCAL lock_timeout = '5s'; - -- A link code is claimed on the app's own lines, so it needs to be unique only within the app: -- keyed on the code alone, every app drew from one space of codes, and a code one app held -- failed another app's link. The new key refuses nothing the old one let through, so an older @@ -16,8 +14,6 @@ ALTER TABLE channel_links -- +goose Down SET LOCAL lock_timeout = '5s'; -SET LOCAL lock_timeout = '5s'; - -- Two apps may hold one code now: all but one app's are dropped, and those links fail. DELETE FROM channel_links held USING channel_links kept WHERE held.code = kept.code AND held.customer_id > kept.customer_id;