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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,10 @@ Only a built-in connector takes the OAuth client the deployment keeps in its env

`POST /v1/data/import` and change replays run each row's own validation before writing it, so an import is refused with a 400 naming the field where the API would refuse the same row: a campaign's concurrency above 50 or a config's sandbox over its CPU, memory or disk bounds, among the rest. A moved voice arrives with its id, name and description and without its samples or bindings, whose audio and clone stay with the deployment that made them: add a recording and prepare it again. An import that names `voice_samples` or `voice_bindings` is refused. An imported request is never billable here and counts against the importing app's organization: the one it was last seen under here, else the one it is registered under, else none.

### Only a number on the customer's own trunk moves in an import

`/v1/data/import`, and a change applied after it, writes a `phone_numbers` row only when its vendor is exactly `sip_trunk`; any other row is skipped without an error. A number bought at a vendor stays in the vendor account of the deployment that bought it, and its bills already move with the requests, so the destination neither holds it nor bills its months again. A customer that moves keeps a bought number by buying or porting it at the destination. A number bought here and still held is never updated or deleted by an imported row or a replayed change, whatever id it names. An imported `sip_trunk` number is held to the API's rules (E.164, a vendor, a cost that is not negative), and no imported number keeps its `dlc_use_case_id`, which names a use case of the source.

### A customer can no longer list or speak in another customer's cloned voice

Clones made through `/v1/agents/voices` sit in the deployment's shared provider account, which lists them all as its own. A voice id that another customer's voice was prepared as is now refused, whether it is the session's voice or the `voice_id` of TTS overwrites. The voice library lists only the caller's own clones besides the provider's published voices, previews another customer's clone as not found, and no longer suggests one as the closest voice.
Expand Down
8 changes: 5 additions & 3 deletions acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2780,9 +2780,11 @@ exported. A moved deployment mints its own keys and re-authorizes its plugin con
Voice recordings live in the bucket rather than in Postgres, so their rows move and copying
the bucket is the operator's.

A phone number still held moves only in E.164 form (`+15551234567`) and only while no other
app here holds it; one given back moves as written. A moved number arrives detached: its
trunk, route and call stay behind, so it is attached again where it arrives.
Only a phone number on the app's own SIP trunk (vendor `sip_trunk`) moves, in E.164 form
(`+15551234567`), and it arrives detached: its trunk, route, call and 10DLC use case stay
behind, so it is attached again where it arrives. A number bought at a vendor does not move,
held or given back; its bills move with the requests. The app keeps it by buying or porting
it where it moves to.

Changes are captured by a trigger per table writing into `data_changes`, gated on a row in
`data_change_capture`: with nobody moving, the hot path costs one index probe. Exporting
Expand Down
2 changes: 1 addition & 1 deletion acceleration/cmd/router/replicate_ids_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func (s *ReplicateIDsSuite) held(id int64) bool {
// copiedNumber is a number of acme's as an export carries it, under the source's id, which
// also makes its digits, so no two copied numbers are one.
func copiedNumber(id int64) json.RawMessage {
return json.RawMessage(fmt.Sprintf(`{"id":%d,"e164":"+1555%07d","vendor":"telnyx","country":"US","customer_id":"acme",`+
return json.RawMessage(fmt.Sprintf(`{"id":%d,"e164":"+1555%07d","vendor":"sip_trunk","country":"US","customer_id":"acme",`+
`"capabilities":["voice"],"monthly_cost_micros":0,"tags":{},"purchased_at":"2026-10-30T00:00:00Z"}`, id, id))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ func (s *ReplicateRepeatSuite) copiedBefore() {

// recorded records a number of acme's at the source, its digits the number given.
func (s *ReplicateRepeatSuite) recorded(digits int) {
number := &store.PhoneNumber{E164: e164(digits), Vendor: "telnyx", Country: "US", CustomerID: "acme"}
number := &store.PhoneNumber{E164: e164(digits), Vendor: "sip_trunk", Country: "US", CustomerID: "acme"}
s.Require().NoError(s.source.PhoneNumbers.Insert(s.ctx, number))
}

Expand Down
45 changes: 21 additions & 24 deletions acceleration/internal/api/datamove_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,50 +299,47 @@ func (s *DataMoveSuite) TestChangesAreAppliedToAnAppThatHoldsData() {
s.Equal("edited at the source", s.instructionsOf(agent.Id))
}

func (s *DataMoveSuite) TestAnImportCannotClaimAnotherAppsNumberInAnotherForm() {
func (s *DataMoveSuite) TestAnImportedBoughtNumberIsNotStored() {
ctx := context.Background()
other, e164 := s.utils.uuid(), s.utils.number()
s.Require().NoError(s.store.PhoneNumbers.Insert(ctx, &store.PhoneNumber{
E164: e164, Vendor: "plivo", Country: "US", CustomerID: other,
}))

// Plivo reads the number without its plus as the other app's.
variant := strings.TrimPrefix(e164, "+")
row, err := json.Marshal(map[string]any{
"id": rand.Int64N(1 << 50), "e164": variant, "vendor": "plivo", "country": "US",
"capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other,
"tags": map[string]string{}, "purchased_at": time.Now().UTC(),
})
s.Require().NoError(err)
status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import",
ndjson([]dataLine{{Table: "phone_numbers", Row: row}}))
s.Equal(http.StatusBadRequest, status)
s.Contains(failure, "E.164")
// The other app's number, as written and as Plivo reads it.
var lines []dataLine
for _, variant := range []string{e164, strings.TrimPrefix(e164, "+")} {
row, err := json.Marshal(map[string]any{
"id": rand.Int64N(1 << 50), "e164": variant, "vendor": "plivo", "country": "US",
"capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other,
"tags": map[string]string{}, "purchased_at": time.Now().UTC(),
})
s.Require().NoError(err)
lines = append(lines, dataLine{Table: "phone_numbers", Row: row})
}
s.Require().Equal(http.StatusOK, s.serverClient.do(http.MethodPost, "/v1/data/import", ndjson(lines), nil))

status, _ = s.serverClient.call(http.MethodDelete, "/v1/phone/numbers/"+variant, nil)
status, _ := s.serverClient.call(http.MethodDelete, "/v1/phone/numbers/"+e164, nil)
s.Equal(http.StatusNotFound, status)
imported, err := s.store.PhoneNumbers.Select(ctx, s.customerID(), store.PhoneNumberFilter{IncludeReleased: true})
s.Require().NoError(err)
s.Empty(imported)
held, err := s.store.PhoneNumbers.Select(ctx, other, store.PhoneNumberFilter{})
s.Require().NoError(err)
s.Len(held, 1, "the number stays with the app that holds it")
}

func (s *DataMoveSuite) TestARefusedNumberDoesNotSayWhoHoldsIt() {
other, e164 := s.utils.uuid(), s.utils.number()
s.Require().NoError(s.store.PhoneNumbers.Insert(context.Background(), &store.PhoneNumber{
E164: e164, Vendor: "plivo", Country: "US", CustomerID: other,
}))

func (s *DataMoveSuite) TestAnImportedNumberOnItsOwnTrunkInAnotherFormIsRefused() {
row, err := json.Marshal(map[string]any{
"id": rand.Int64N(1 << 50), "e164": e164, "vendor": "bandwidth", "country": "US",
"capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": other,
"id": rand.Int64N(1 << 50), "e164": strings.TrimPrefix(s.utils.number(), "+"), "vendor": "sip_trunk",
"country": "US", "capabilities": []string{"voice"}, "monthly_cost_micros": 0,
"tags": map[string]string{}, "purchased_at": time.Now().UTC(),
})
s.Require().NoError(err)
status, failure := s.serverClient.failure(http.MethodPost, "/v1/data/import",
ndjson([]dataLine{{Table: "phone_numbers", Row: row}}))
s.Equal(http.StatusBadRequest, status)
s.Contains(failure, "this number cannot be imported")
s.NotContains(failure, "app")
s.Contains(failure, "E.164")
}

func (s *DataMoveSuite) TestSomethingThatIsNotAnExportIsRefused() {
Expand Down
35 changes: 29 additions & 6 deletions acceleration/internal/phone/apps_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,16 @@ func (s *AppsSuite) vendorOnAnAllowlist() onAnAllowlist {
// numberOn registers a stub for the vendor next to the suite's own and gives the suite's
// customer a number on it.
func (s *AppsSuite) numberOn(vendor string) string {
other := s.vendorBeside(vendor)
e164 := aNumber()
s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{
E164: e164, Vendor: other.vendor, Country: "US", CustomerID: s.customer, PurchasedAt: time.Now().UTC(),
}))
return e164
}

// vendorBeside registers a stub for the vendor next to the suite's own.
func (s *AppsSuite) vendorBeside(vendor string) *stub {
other := &stub{vendor: vendor}
registry := NewRegistry(s.config())
registry.Register(s.vendor.vendor, func() (Provider, error) { return s.vendor, nil })
Expand All @@ -144,12 +154,7 @@ func (s *AppsSuite) numberOn(vendor string) string {
service, err := NewService(ServiceOptions{Registry: registry, Store: s.store, Apps: s.apps})
s.Require().NoError(err)
s.service = service

e164 := aNumber()
s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &store.PhoneNumber{
E164: e164, Vendor: other.vendor, Country: "US", CustomerID: s.customer, PurchasedAt: time.Now().UTC(),
}))
return e164
return other
}

// planStub is a vendor that fetches its call plan when the call is answered, and renders
Expand Down Expand Up @@ -311,6 +316,24 @@ func (s *AppsSuite) TestReleasingANumberDeletesItsTrunkAndRouteInItsApp() {
s.Empty(s.own.Rules())
}

func (s *AppsSuite) TestAnImportedNumberIsNeverGivenBackAtTheVendor() {
telnyx := s.vendorBeside("telnyx")
e164 := aNumber()
row, err := json.Marshal(map[string]any{
"id": rand.Int64N(1 << 50), "e164": e164, "vendor": telnyx.vendor, "country": "US",
"capabilities": []string{"voice"}, "monthly_cost_micros": 0, "customer_id": s.customer,
"tags": map[string]string{}, "purchased_at": time.Now().UTC(),
})
s.Require().NoError(err)
s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "phone_numbers", row))

s.ErrorIs(s.service.Release(s.ctx, s.customer, e164), store.ErrNoNumber)
s.Empty(telnyx.released, "the vendor is not asked to give it back")
_, err = s.service.Attach(s.ctx, Attachment{CustomerID: s.customer, E164: e164})
s.ErrorIs(err, store.ErrNoNumber, "nor are its calls pointed at an agent")
s.Empty(s.deployment.Trunks())
}

func (s *AppsSuite) TestReleasingStopsTheVendorSendingCallsFirst() {
s.ownApp()
s.sealed()
Expand Down
22 changes: 22 additions & 0 deletions acceleration/internal/phone/metering_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ package phone

import (
"context"
"encoding/json"
"errors"
"log/slog"
"math/rand/v2"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -835,6 +837,26 @@ func (s *MeteringSuite) TestAMonthThatBeganBeforeFromIsNeverBilled() {
"the month that began ten days ago began before the job was switched on")
}

func (s *MeteringSuite) TestAMovedCustomersBoughtNumberIsNotBilledAgainHere() {
s.Require().NoError(s.store.PhoneNumbers.Release(s.ctx, s.customer, s.e164, s.clock.now()))
now := time.Now().UTC().Truncate(time.Second)
// The month that began three days ago is the source's to bill, which held the number then.
row, err := json.Marshal(map[string]any{
"id": rand.Int64N(1 << 50), "e164": aNumber(), "vendor": s.vendor.vendor, "country": "US",
"capabilities": []string{"voice"}, "monthly_cost_micros": 1_000_000, "customer_id": s.customer,
"tags": map[string]string{}, "purchased_at": now.AddDate(0, -1, -3),
})
s.Require().NoError(err)
s.Require().NoError(s.store.ImportRow(s.ctx, s.customer, "phone_numbers", row))
rentals := Rentals{Store: s.store, Recorder: s.recorder, Logger: slog.New(slog.DiscardHandler)}

_, err = rentals.Bill(s.ctx, now.AddDate(0, 0, -30), time.Now().UTC())
s.Require().NoError(err)

s.Never(func() bool { return len(s.rows(ModelNumber)) > 0 }, time.Second, 50*time.Millisecond,
"the destination bills no month of a number it does not hold")
}

// row waits for the customer's one row of a model and reads it.
func (s *MeteringSuite) row(model string) store.Request {
return s.rowsWhen(model, 1)[0]
Expand Down
88 changes: 34 additions & 54 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
return err
}
if table == "phone_numbers" {
if err := importableNumber(ctx, db, customerID, row); err != nil {
if importable, err := importableNumber(ctx, db, customerID, row); err != nil || !importable {
return err
}
}
Expand Down Expand Up @@ -838,6 +838,10 @@ func (s *Store) importRow(ctx context.Context, db bun.IDB, customerID, table str
if table == "connector_connections" {
conflict += fmt.Sprintf(" AND %s.status <> '%s' AND %s.credentials_kek_version = 0", spec.name, ConnectionConnected, spec.name)
}
// A number bought here and still held is this deployment's, whatever row names its id.
if table == "phone_numbers" {
conflict += " AND NOT " + boughtHere("phone_numbers")
}

// Every writer of a log draws its id under its customer's lock (AgentLogs.Insert), so ids
// commit in order and a reader resuming after one misses none. The row is read through the
Expand Down Expand Up @@ -1376,64 +1380,36 @@ func moveRoom(ctx context.Context, tx bun.Tx, customerID string, marked []Schedu
return limits, held, nil
}

// digitsKey is a number as most vendors read the one they are given, as SQL over a text
// value: its digits. Plivo, DIDWW, Vonage and Bird drop the plus; Twilio, Telnyx and Sinch
// read it as written, which its digits only widen.
const digitsKey = `regexp_replace(%s, '[^0-9]', '', 'g')`

// vendorKeys is a number as a vendor that reads it another way does. Bandwidth also drops
// the 1 of an 11-digit number (bandwidth.digits), so +15551234567 and +5551234567 are one
// number there.
var vendorKeys = map[string]string{
"bandwidth": `regexp_replace(regexp_replace(%s, '[^0-9]', '', 'g'), '^1([0-9]{10})$', '\1')`,
}

// importableNumber refuses an imported number the customer would hold in a form other than
// E.164, or that another customer holds. Every bought number is held in the deployment's one
// account at its vendor, and releasing it there is what holding it here allows, so a number
// two customers held would be one either of them could give back. The unique index on what
// is held compares the text as written, so it sees neither another form of a number nor the
// same number at another vendor. A number given back is only its bill's history and imports
// as written; one on the customer's own trunk is in no account here.
//
// Two imports of one number into two customers at the same moment can both pass this.
func importableNumber(ctx context.Context, db bun.IDB, customerID string, row json.RawMessage) error {
// importableNumber says whether an imported number is written here, and refuses one the API
// would not store. Only a number on the customer's own trunk moves. A bought one is held in
// the vendor account of the deployment that bought it, with that one's line, trunk and use
// case, and its bills move in its requests: written here it would be billed again (Rentals)
// and given back at this deployment's vendor account. So it is not written, and the customer
// keeps it by buying or porting it here.
func importableNumber(ctx context.Context, db bun.IDB, customerID string, row json.RawMessage) (bool, error) {
// Read the way the insert reads it, by exact column name: a JSON decoder also matches a
// key in another case, which the insert then leaves out.
var e164, vendor sql.NullString
var released bool
var cost sql.NullInt64
if err := db.QueryRowContext(ctx,
"SELECT e164, vendor, released_at IS NOT NULL FROM jsonb_populate_record(NULL::phone_numbers, ?::jsonb)",
string(row)).Scan(&e164, &vendor, &released); err != nil {
return fmt.Errorf("store: read an imported number: %w", err)
}
if released {
return nil
"SELECT e164, vendor, monthly_cost_micros FROM jsonb_populate_record(NULL::phone_numbers, ?::jsonb)",
string(row)).Scan(&e164, &vendor, &cost); err != nil {
return false, fmt.Errorf("store: read an imported number: %w", err)
}
if !IsE164(e164.String) {
return stack.Wrap(fmt.Errorf("%w: %q", ErrNotE164, e164.String))
if vendor.String != sipTrunkVendor {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Question] R1.4 This stops new bought rows from arriving. A bought number imported before this change, since import shipped, is still held under the importer. Service.Release would still give it back at the vendor, and Rentals.Bill still bills it. The PR does not clean these up. To settle it: count held non-sip_trunk rows in staging and prod that this deployment never bought (no purchase of its own). If there are any, they need a one-off release here only, with no vendor call. That is a data step for the owner, not code in this PR.

return false, nil
}
if vendor.String == "sip_trunk" {
return nil
number := PhoneNumber{CustomerID: customerID, E164: e164.String, Vendor: vendor.String, MonthlyCostMicros: cost.Int64}
if err := number.Validate(); err != nil {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Nit] R1.3 An imported sip_trunk row is checked only by PhoneNumber.Validate. InsertOnSIPTrunk holds the same row to two more rules: it must name one of the customer's own trunks, and the customer must not already hold the number, bought or on a trunk (ErrNumberHeld). A probe stored a held sip_trunk row with no sip_trunk_id. It also stored a second held row next to a number the same customer bought here, so GetByE164 picks one of two rows. The base did the same: sip_trunk rows returned before any check. So this goes to a ticket, not this PR. A held row needs a trunk; one given back has none, because the release clears it.

return false, stack.Wrap(err)
}
// Compared as the vendor it would be given back at reads a number, so a number held in
// another form, before every write checked the form, is found as well.
key, found := vendorKeys[vendor.String]
if !found {
key = digitsKey
}
var held bool
if err := db.QueryRowContext(ctx, fmt.Sprintf(`
SELECT EXISTS (SELECT 1 FROM phone_numbers
WHERE customer_id <> ? AND released_at IS NULL AND vendor <> 'sip_trunk' AND %s = %s)`,
fmt.Sprintf(key, "e164"), fmt.Sprintf(key, "?::text")),
customerID, e164.String).Scan(&held); err != nil {
return fmt.Errorf("store: who holds an imported number: %w", err)
}
if held {
return stack.Wrap(fmt.Errorf("%w: %s", ErrNumberHeldElsewhere, e164.String))
}
return nil
return true, nil
}

// boughtHere is the condition that a number, as the given relation names it, was bought here
// and is still held: no import writes one (importableNumber), so none may update or delete it.
func boughtHere(relation string) string {
return fmt.Sprintf("(%[1]s.released_at IS NULL AND %[1]s.vendor <> '%[2]s')", relation, sipTrunkVendor)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Should fix] R1.1 boughtHere protects only a number bought here that is still held. A row given back here is that number's billing history, and two paths still reach it. An imported sip_trunk row that names its id passes the conflict guard and turns it into a live trunk number: vendor sip_trunk, released_at cleared. A replayed delete that names its id removes it. Rentals.Bill skips sip_trunk rows (internal/phone/rental.go, the number.Vendor == SIPTrunkVendor skip), so a month that began before the release and was not billed yet is never billed. This is the "history row turned live" case the change sets out to close.

How I checked: two probe tests in DataMoveSuite, on this head merged onto current main. Each buys a number here, attaches it, then releases it:

  1. Then ImportRow with a sip_trunk row that uses the same id and the customer's own trunk. Expected: the row keeps vendor telnyx and stays released. On head it becomes sip_trunk and held.
  2. Then ApplyChanges with a ChangeDelete keyed on its id. Expected: the row stays. On head it is deleted.

Fix: an import no longer writes a row with any other vendor, so every non-sip_trunk row here was bought here, held or given back. Drop the released_at IS NULL term:

return fmt.Sprintf("(%[1]s.vendor <> '%[2]s')", relation, sipTrunkVendor)

With that change both probes pass and the whole store DataMoveSuite still passes. Please add the two probes above as tests, and update the comment and the CHANGELOG/README line ("bought here and still held") to match.

}

// importableDefinition refuses an imported definition the API would not have stored, and gives the row the manifest as
Expand Down Expand Up @@ -1497,10 +1473,11 @@ func (t dataTable) identity() string {
}
// Nor does an attached number arrive with where its calls go: the trunk, route and call it was attached to are named by whatever
// the importer wrote, and a hook that finds one call under two customers' numbers answers
// it for neither (ErrAmbiguousHook). It arrives needing to be attached again.
// it for neither (ErrAmbiguousHook). It arrives needing to be attached again. Nor with its
// use case, which names one of the source's.
if t.name == "phone_numbers" {
return "jsonb_build_object('customer_id', ?::text, 'stream_trunk_id', NULL, 'stream_route_id', NULL," +
" 'stream_call_id', NULL, 'stream_call_type', NULL, 'attached_at', NULL)"
" 'stream_call_id', NULL, 'stream_call_type', NULL, 'attached_at', NULL, 'dlc_use_case_id', NULL)"
}
// A request was billed by the deployment that recorded it, so this one never ships it, and
// what that one's usage service answered for it is not this one's: a reship of the rows
Expand Down Expand Up @@ -1774,6 +1751,9 @@ func (s *Store) deleteRow(ctx context.Context, db bun.IDB, customerID string, ch
conditions = append(conditions, spec.filter)
}
}
if spec.name == "phone_numbers" {
conditions = append(conditions, "NOT "+boughtHere("t"))
}
args = append(args, customerID)

query := fmt.Sprintf("DELETE FROM %s AS t WHERE %s", spec.name, strings.Join(conditions, " AND "))
Expand Down
Loading
Loading