Skip to content

fix(store): an import writes only numbers on the customer's own trunk - #2182

Merged
thesyncim merged 2 commits into
mainfrom
fix/ai-3476-imported-numbers-are-history
Nov 23, 2026
Merged

thesyncim merged 2 commits into
mainfrom
fix/ai-3476-imported-numbers-are-history

Conversation

@thesyncim

@thesyncim thesyncim commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Problem

importRow wrote any imported phone_numbers row, so a number bought at a vendor became a row held by the importing customer. The release and attach paths trust that row. The row also carried the source's line, trunk and use case. It was billed a second time as well: Rentals.Bill charged the months before its release here, although the source had already billed them. And a row, or a replayed delete, naming the id of a number bought here and still held could update or delete it.

Fix

  • importableNumber now skips any row whose vendor is not exactly sip_trunk, on import and on change replay, with no insert, no update and no error. Such a row has nothing this deployment can use, and its bills already move in requests. A customer that moves keeps a bought number by buying or porting it at the destination. SIP_TRUNK, sip_trunk and an empty vendor count as bought numbers.
  • A sip_trunk row is checked with PhoneNumber.Validate: E.164, a vendor, and a cost that is not negative. fix(store): validate imported rows and force what a request counts against #2181 leaves phone_numbers to this PR. The check for a number another customer holds, vendorKeys and ErrNumberHeldElsewhere only mattered for bought numbers, so they are removed. The released_at override from the first commit is removed too.
  • The conflict WHERE in importRow and the conditions in deleteRow now leave alone any row that was bought here and is still held, whatever id it names.
  • No imported number keeps its dlc_use_case_id.
  • fix(store): give an imported request a usage id of the importing deployment's #2189 relies on this PR for the rental case.

Tests

Each test below was run on this commit and passes, and was run with datamove.go and phone_number.go reset to the previous head, where it fails.

  • TestAnImportedNumberNotOnItsOwnTrunkIsNotStored covers telnyx, SIP_TRUNK, sip_trunk and an empty vendor, by import and by change. Before the fix, each was stored.
  • TestAMovedBoughtNumberDoesNotArrive: neither a held nor a released bought number arrives. Before the fix, both did.
  • TestANumberBoughtHereIsNotWrittenOverByARowWithItsID sends rows that reuse the id, as telnyx, as sip_trunk and as released. The number keeps its vendor, line and release state. Before the fix, it was overwritten.
  • TestAReplayedDeleteLeavesANumberBoughtHere: before the fix, the number was deleted.
  • TestAnImportedNumberWithANegativeCostIsRefused: before the fix, the row was accepted.
  • TestAMovedCustomersBoughtNumberIsNotBilledAgainHere (MeteringSuite) runs Rentals.Bill after an import. Before the fix, a month was billed.
  • TestAnImportedNumberIsNeverGivenBackAtTheVendor (AppsSuite): release and attach of the imported number find nothing.
  • The existing tests for number forms, other holders and replication now use sip_trunk numbers, and the API tests show a bought row is not stored and a malformed sip_trunk row is refused.

Fixes AI-3476

@thesyncim
thesyncim force-pushed the fix/ai-3476-imported-numbers-are-history branch from 616d8ea to 1ecc65e Compare November 23, 2026 11:04
@thesyncim
thesyncim force-pushed the fix/ai-3476-imported-numbers-are-history branch from 1ecc65e to c56fe3a Compare November 23, 2026 11:34
@thesyncim thesyncim changed the title fix(store): an imported bought number arrives given back fix(store): an import writes only numbers on the customer's own trunk Nov 23, 2026
@thesyncim
thesyncim marked this pull request as ready for review November 23, 2026 12:11
@thesyncim thesyncim added the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
thesyncim added a commit that referenced this pull request Nov 23, 2026
…ainst (#2181)

**Problem**
`Store.importRow` wrote each imported line through
`jsonb_populate_record` without running its model's `Validate`, so an
import could store rows the API refuses, such as a campaign's
concurrency above 50 or a sandbox over its CPU, memory or disk bounds.
It also carried `voice_samples` and `voice_bindings`, whose object keys
and provider voice ids point at this deployment's bucket and provider
account, not the importer's. An imported `requests` row kept the
`billable` flag and `organization_id` it was sent with.

**Fix**
- `importRow` reads each row as it would be written and refuses it with
its model's `Validate` error, for every table whose model has one. Phone
numbers are left out here: #2182 owns their import and adds their check.
- `voice_samples` and `voice_bindings` are no longer in `dataTables`. A
sample's audio is in this deployment's bucket and a binding's clone in
this deployment's provider account, so neither row means anything where
a customer moves, like a knowledge file. A moved voice arrives with its
id, name and description; the customer adds a recording and prepares it
again. An import or change that names either table is refused, as any
table an export does not carry already is. A global migration
(`20270123021810`) drops their change-feed triggers, as was done for
`call_bridges`; check the newest global migration on main before
merging.
- An imported request is stored with `billable = false`.
- An imported request is stored with the app's organization from the new
`AppOrganizations.OrganizationOf`: the one it was last seen under here,
else the one it is registered under in `apps`. `Holds` now uses it too.
An app this deployment neither saw nor registered gets an empty
organization, which nothing fills in later.

**Tests**
- `TestAnImportedCampaignAboveTheConcurrencyCapIsRefused` and
`TestAnImportedConfigOverTheSandboxLimitsIsRefused`: a row over the
API's caps is stored. Both failed before the fix.
- `TestAMovedVoiceArrivesWithoutItsSamplesOrBindings`: a move carries a
voice's sample and ready binding. Failed before the fix.
- `TestAnImportOfAVoiceSampleOrBindingIsRefused`: a whole sample or
binding line from an older export is written. Failed before the fix.
-
`TestAnImportedRequestIsNotBilledAndCountsAgainstTheAppsOwnOrganization`:
the sent flag and organization are kept. Failed before the fix.
-
`TestAnImportedRequestOfAnAppRegisteredButUnseenHereCountsAgainstItsOrganization`:
an app registered but not yet seen here gets an empty organization.
Failed before the fix.
- `TestChildRowsFollowTheirParent` and
`TestAChildRowCannotBeImportedOntoSomebodyElsesParent` now use campaign
contacts in place of voice samples.

Fixes AI-3478
A phone_numbers row imported, or replayed from the change feed, for a
number bought at a vendor now arrives released at the import time unless
it was released already, so it is billing history here: it cannot be
attached or given back at the vendor, and it does not stop the number
being bought here. A number on the customer's own SIP trunk still arrives
held. No imported number keeps its dlc_use_case_id.
An imported phone_numbers row, or one in a replayed change, is written only
when its vendor is exactly sip_trunk; any other row is skipped without an
error. A bought number stays in the vendor account of the deployment that
bought it and its bills move with the requests, so the destination neither
holds it nor bills its months again. A number bought here and still held is
never updated or deleted by an imported row or a replayed change. An
imported sip_trunk number is checked with PhoneNumber.Validate.
@thesyncim
thesyncim force-pushed the fix/ai-3476-imported-numbers-are-history branch from 37215b7 to af3eb71 Compare November 23, 2026 12:58
@thesyncim
thesyncim merged commit d4ce8d8 into main Nov 23, 2026
10 of 12 checks passed
@thesyncim
thesyncim deleted the fix/ai-3476-imported-numbers-are-history branch November 23, 2026 12:58

@kanat kanat left a comment

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.

Reviewed af3eb71b8 merged onto current main (d4ce8d886). Round 1 started on 37215b766. The rebase left this PR's own diff unchanged, file by file.

[Should fix] R1.2 acceleration/internal/store/datamove.go:870 is not in this diff. The importedModels comment from #2181 still says a phone number "is checked by importableNumber instead, which takes one given back in the form it was held in then". After this PR, importableNumber skips every bought row, given back or not, and checks every sip_trunk row, given back ones included, with Validate (E.164). Reword the comment to say that.

[Nit] R1.5 In unchanged code, acceleration/internal/phone/apps_integration_test.go:99: aNumber() picks from about 8M numbers, all under the shared vendor twilio, and phone_numbers_held_idx is global. The first attempt of integration (routers) on 37215b766 failed TestAppsSuite/TestDetachingLeavesALiveCallAlone in SetupTest with a duplicate key on that index; the rerun passed. Ticket: make the flake fix its own change.

CI on af3eb71b8: integration (api) fails to build internal/api/chat_channels_hosted_test.go (unknown field LLM, no CreateAgentConfig). integration (rest) fails TestResolverSuite/TestARefreshWhoseFirstSaveFailsIsSavedByTheNextAndStaysConnected. Both fail the same way on main's own run at d4ce8d886, so neither comes from this PR. Everything else passes.

Checked and sound:

  • The vendor skip, Validate, the conflict and delete guards, and the cleared use case: 13 mutations were run. Each is killed by a test, except the R1.1 widening and one equivalent mutant.
  • A move of a customer's own trunk numbers still works: the own-trunk move test and the copying tests pass, and so do the replication suites.
  • Release never reaches the vendor for a sip_trunk row, because seller is nil for it.
  • No migration, and rolling back only brings back the old import rule.

Verdict: request changes, for R1.1 and R1.2.

// 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.

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.

}
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.

thesyncim added a commit that referenced this pull request Nov 23, 2026
…oyment's (#2189)

**Problem**
Fixed charges (a number's rental month, 10DLC fees, knowledge storage
hours) get a usage id derived from a fixed key, and
`Requests.InsertMany` skips a row whose usage id already exists (`ON
CONFLICT (usage_id) DO NOTHING`). An imported `requests` row kept the
usage id it was sent with. A row sent with the id of a future charge
therefore made that charge look already recorded, and it was never
billed.

**Fix**
- `importRow` gives an imported request a usage id of its own,
`importedUsageID(customer, origin)`, where origin is the usage id the
row had where it was first recorded. No imported row can carry the id of
a charge this deployment has yet to make.
- The origin is kept in a new nullable column,
`requests.source_usage_id` (shard migration `20270119000000`). Importing
a row again, or a copy of it moved on from another deployment, writes
one row.
- A row taken back to where it was first recorded keeps its usage id
when this customer already holds it there, so a move there and back is
one row. An id the customer already holds names no charge still to come.
- `deleteRow` finds a delete in a change batch by the id made from the
one the key names, and never removes a request this deployment recorded
itself.
- A moved request no longer counts as this deployment's record of a
charge. The one charge this could bill twice, a bought number's month,
goes away with #2182 (merged).
- Merge order: the migration sits below the shard migrations of #2195
and #2208, so this merges first or is renumbered.

**Tests**
-
`TestAnImportedRequestNamingANumbersComingMonthDoesNotStopItBeingBilled`,
`TestAnImportedRequestIsGivenAUsageIDOfItsOwnAndIsNeverShipped`,
`TestAMovedRequestNeverOverwritesTheDestinationsRowWithItsID`: failed
before the fix.
- `TestARequestMovedBackIsOneRowWhereItWasRecorded`,
`TestARequestMovedOnFromACopyIsOneRowWhereverItLands`: a move back, or
on from a copy, is one row. Each failed on the previous head.
- `TestADeleteNamingARequestRecordedHereLeavesIt`,
`TestARequestImportedByTwoAppsIsHeldByEach`,
`TestADeleteNamingAMovedRequestInCapitalsFindsIt`: each fails under the
change it guards (delete by the raw usage id, a derivation ignoring the
app, no uuid normalisation).

Fixes AI-3477
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review docs project-info

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants