Skip to content

AI-3752: a number is held by one app per Stream app - #2412

Merged
martinmitrevski merged 9 commits into
mainfrom
martinmitrevski/ai-3752-high-cross-tenant-phone-number
Nov 25, 2026
Merged

martinmitrevski merged 9 commits into
mainfrom
martinmitrevski/ai-3752-high-cross-tenant-phone-number

Conversation

@martinmitrevski

@martinmitrevski martinmitrevski commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

Why

POST /v1/phone/trunks/{id}/numbers let any customer add any E.164 to its own SIP trunk, whoever else held it: InsertOnSIPTrunk only looked for the caller's own row, and phone_numbers_trunk_held_idx is unique per (customer_id, e164). /v1/data/import wrote such a row too, with no check at all.

One call from a number on a trunk lines it: sharedLine → line → join puts the number on the customer's shared Stream trunk in its app, with a rule naming it. Stream lists a number on one trunk per app. In an app two customers share (the deployment's own, which every customer without an app of its own falls back to), the squatter's line made first leaves the real holder unable to attach the number or call from it. Reproduced in AppsSuite with the Stream stand-in's OneTrunkPerNumber(): after the squatter's one call (the line is made before the dial, so the call need not connect), the buyer's Attach and Call both failed with numbers already used by another SIP trunk, and kept failing.

Where the ticket differs from the code:

  • The rule is not removed (remediation 2). The sip_trunk provider's leg is StreamLegShared (siptrunk/siptrunk.go:171). The router's bridge dials the number's Stream trunk with x_stream_call_id, and the rule's lineCallTemplate is what lands that outbound leg in the session's call. Without a rule naming the number, no call through a customer's trunk reaches Stream; the per-call fallback makes a trunk and rule naming the number as well. Its phone_number custom is read only by NumberRungInApp (attached numbers only, and Attach refuses a trunk number), after CallResources has already claimed a placed leg.
  • NumberByCallInApp's ErrAmbiguousHook is narrower than stated. A call on a line made today carries phone_number and is resolved by NumberRungInApp. The fallback by E.164 only serves calls named phone-<e164> by rules made before that, and needs both customers' rows lined in one app. It is closed anyway, for rows already written.
  • service.go:1315 is a comment in call; the line is made at service.go:1348 (sharedLine).

How it works

add a number to a trunk (AddTrunkNumber)
  ├─ Holders(e164), no lock: who holds it now
  ├─ heldApart: Apps.Placed(caller) and Apps.Placed(each other holder)
  │     the app each one's lines are made in, read without acting for it
  │     both read and different  -> apart; settled unreadable
  │     (no identity, disconnected) -> shares the app; a failed read
  │     -> returned, the add is tried again
  └─ InsertOnSIPTrunk(number, apart)
        pg_advisory_xact_lock(e164), then the holders again
        ├─ the caller          -> ErrNumberHeld, 409 conflict, as before
        ├─ a holder not apart  -> 409 phone_number_held_elsewhere
        │   (one that came since the read is not apart)
        └─ none                -> insert; lock kept until commit

call or transfer from a trunk number, lined in app P (dialVendor)
  └─ another customer bought it and its lines are made in P
     (or its app is settled unreadable; a failed read is returned
     as ErrNotDialed, which a campaign retries)?
       ├─ yes -> 409 phone_number_held_elsewhere, lasting: no campaign retry
       └─ no  -> sharedLine -> line -> join, rule kept

attach, call or transfer from a bought number in app P (clearLinesFor)
  └─ TrunkLinesElsewhere(e164, P): other customers' live sip_trunk rows lined in P
     (the deployment's app is its id or no pin)
       └─ evict each, before the buyer's own line is made:
            reach its app            fails -> error, row untouched
            lock its trunk group, read it again (gone or moved -> nothing to do)
            offTrunk(must): rule, then the number off its trunk (or the trunk)
            any Stream failure -> error, transaction rolls back, row as it was
            Stream took it down -> forget the line

import or replayed change of a trunk number another customer holds here
  └─ left out (*NumbersLeftOutError); the rest of the import or batch is
     written; the API does not count it in rows, replicate logs how many and
     moves its cursor. A batch takes every number's lock up front, sorted.
  • Scope: the Stream app, not the deployment. In app mode each customer acts in a Stream app of its own (streamapp/stored.go), where its number cannot collide with anybody's. Refusing a number held anywhere let whoever registered B's public caller ID first give B a permanent 409, and the 201/409 answer was itself a probe that squatted. Now a number is refused only where it could block: when the other holder's lines are made in the same app as the caller's. In deployment mode every customer shares the deployment's app, so there the rule is what it was.
  • Reading another customer's app. streamFor is not side-effect free for a holder: Stored.For counts a use of the fallback and logs it under the holder's name (fellBack), Forwarded.identity asks the gateway's mint for a token that is about to run out and stores it, and Clients.For binds a client and caches the answer. Stored.Placed (Clients.Placed, phone.Apps.Placed) makes the same decision as For without any of that: it asks the gateway for nothing and counts no fallback use. A token about to run out counts as the app's own. So does one that has run out, when the customer may not fall back to the deployment's app (stream.fallback: refuse, the default): its work is then made in its own app or nowhere, so an app that stopped acting cannot hold a number against every other app. With the fallback on, a token that has run out reads as falling back to the deployment's app, as For answers when the gateway will not mint another. Deployment mode's For acts on nothing and is asked as it is. An app that cannot be read (disconnected, no identity) counts as shared: fail closed. A read that failed (a database error, a policy that could not be read) is not an answer: it is returned as it is, so the add or the call is tried again rather than refused for good. Read without acting, a customer whose policy requires an app of its own is placed in its own app like one with no fallback, and a policy that could not be read is returned as an error, not as ErrNoIdentity. Pins are compared through pinnedTo (store.SameStreamApp), so no pin and the deployment's id name one app.
  • Race. The apps are read before the lock, since reaching an app may read the database (a second pooled connection under the lock, as unline notes). The store reads the holders again under the lock and refuses any it was not told is apart, so of two registrations in one app the second still waits and is refused. Two registrations in different apps at the same instant can refuse the second once; asked again, it is let in.
  • Eviction. Only a bought number (vendor other than sip_trunk) evicts, only other customers' live sip_trunk rows, only lines of that E.164, only in the app the buyer's line is about to be made in. It runs in Attach, call (shared line and per-call trunk alike) and Transfer, before anything is made at Stream and outside the buyer's own trunk-group lock. offTrunk gained must: release and re-attach call it as before (best effort, a row always cleared), while eviction gets every Stream failure back and rolls the row back, so a line Stream would not let go stays found and is taken down by the next attach or call. A trunk Stream no longer has (404 on its update) lists the number nowhere and does not stop it. Before building it, every writer of a live non-sip_trunk row was checked to be vouched for by a vendor: Buy records the E.164 the vendor's BuyNumber answered and SweepOrders records one only after HoldsNumber confirms it; imports never write one (importableNumber), no update sets vendor or clears released_at, and vendors run on the deployment's own credentials, so no customer brings its own account.
  • Dial. BoughtElsewhere now answers the buyers, and a trunk call is refused only when a buyer's lines are made in the call's app. Together with eviction, the buyer's attach, call or transfer takes the number's line back, and the trunk's customer cannot line the number there again.
  • Imports stay deployment-wide. The store reads no Stream app, and a held number left out is counted, not fatal: the customer adds it again through the API afterwards, which applies the per-app rule. Refused instead, one number a third party controls stopped the whole move and every rerun (api/datamove.go:284, replicate.go:345 returned without moving the cursor).
  • Lock order. applyChanges takes every number's lock in one statement, sorted (unnest, as lockTaskLimits and logRequests do), before its first change: one lock per change in change order let two batches deadlock (40P01).
  • One answer. errNumberHeldElsewhere is one APIError: 409 phone_number_held_elsewhere, "Another app holds this number, so it cannot be added to or called from your SIP trunk.", from sipTrunkFailure (trunk add) and phoneFailure (call, transfer, through callFailure). It names no app, organization or trunk and carries no store: text. transferPhoneCall now declares 409. The call's refusal is no longer Invalid(...), whose marked wrapper hid the sentinel from errors.Is; lasting names it instead, so a campaign does not retry it.
  • Index. phone_numbers_e164_held_idx (e164) WHERE released_at IS NULL, built concurrently in global migration 20270301001400 and listed in usageIndexes. That is the next slot in the agreed order, so this PR lands after fix(store): spend limits, resets and grants keep whose they are #2396 (1100, 1110) and fix(store): renaming a user rewrites each recorded change once, with its batch #2348 (1300); whichever lands later takes a new number.

SQL changes

The three reads by E.164, as bun writes them (one is new, Holders is the read holders already ran, without the lock):

-- holders (InsertOnSIPTrunk under the lock, importableNumber, Holders)
SELECT "pn"."customer_id" FROM "phone_numbers" AS "pn" WHERE (e164 = $1) AND (released_at IS NULL);
-- BoughtElsewhere: every call or transfer from a trunk number
SELECT "pn"."customer_id" FROM "phone_numbers" AS "pn"
WHERE (e164 = $1) AND (vendor <> 'sip_trunk') AND (customer_id <> $2) AND (released_at IS NULL);
-- TrunkLinesElsewhere: every attach, call or transfer from a bought number
SELECT ... FROM "phone_numbers" AS "pn"
WHERE (e164 = $1) AND (vendor = 'sip_trunk') AND (customer_id <> $2) AND (released_at IS NULL)
  AND (stream_trunk_id IS NOT NULL) AND ((stream_app_pk = $3) OR (stream_app_pk IS NULL));

Run on the local test Postgres (19.0), on a copy of the phone_numbers schema with 300,000 rows: numbers held over time by 5,000 apps, 60% given back, 30% on apps' own trunks, the bought ones over 8 vendors, half of the held ones lined.

Plans before: EXPLAIN (ANALYZE, BUFFERS), 300k rows, no index led by e164
=== holders
 Bitmap Heap Scan on phone_numbers pn (actual time=3.479..11.104 rows=1.00 loops=1)
   Recheck Cond: (released_at IS NULL)
   Filter: (e164 = '+15120200000'::text)
   Rows Removed by Filter: 120000
   Heap Blocks: exact=2401
   Buffers: shared hit=2460 read=36
   ->  Bitmap Index Scan on phone_numbers_call_idx (actual time=1.639..1.639 rows=120001.00 loops=1)
 Execution Time: 11.137 ms

=== BoughtElsewhere
 Index Scan using phone_numbers_held_idx on phone_numbers pn (actual time=0.126..0.126 rows=0.00 loops=1)
   Index Cond: (e164 = '+15120200000'::text)
   Filter: (customer_id <> 'customer-1'::text)
   Index Searches: 17
   Buffers: shared hit=46 read=13
 Execution Time: 0.133 ms

=== TrunkLinesElsewhere
 Index Scan using phone_numbers_trunk_held_idx on phone_numbers pn (actual time=1.358..1.358 rows=0.00 loops=1)
   Index Cond: (e164 = '+15120200000'::text)
   Filter: ((stream_trunk_id IS NOT NULL) AND (customer_id <> 'customer-1'::text) AND ((stream_app_pk = 1) OR (stream_app_pk IS NULL)))
   Rows Removed by Filter: 1
   Index Searches: 1
   Buffers: shared hit=273
 Execution Time: 1.363 ms
Plans after: phone_numbers_e164_held_idx
=== holders
 Index Scan using phone_numbers_e164_held_idx on phone_numbers pn (actual time=0.022..0.023 rows=1.00 loops=1)
   Index Cond: (e164 = '+15120200000'::text)
   Index Searches: 1
   Buffers: shared hit=4
 Execution Time: 0.045 ms

=== BoughtElsewhere
 Index Scan using phone_numbers_e164_held_idx on phone_numbers pn (actual time=0.006..0.006 rows=0.00 loops=1)
   Index Cond: (e164 = '+15120200000'::text)
   Filter: ((vendor <> 'sip_trunk'::text) AND (customer_id <> 'customer-1'::text))
   Rows Removed by Filter: 1
   Index Searches: 1
   Buffers: shared hit=4
 Execution Time: 0.011 ms

=== TrunkLinesElsewhere
 Index Scan using phone_numbers_e164_held_idx on phone_numbers pn (actual time=0.005..0.005 rows=0.00 loops=1)
   Index Cond: (e164 = '+15120200000'::text)
   Filter: ((stream_trunk_id IS NOT NULL) AND (customer_id <> 'customer-1'::text) AND ((stream_app_pk = 1) OR (stream_app_pk IS NULL)) AND (vendor = 'sip_trunk'::text))
   Rows Removed by Filter: 1
   Index Searches: 1
   Buffers: shared hit=4
 Execution Time: 0.009 ms
Read Buffers before Buffers after Time before Time after
holders (every registration, imported number) 2,496 (every held row read) 4 11.1 ms 0.05 ms
BoughtElsewhere (every trunk call) 59 (skip scan over 17 vendors' ranges) 4 0.13 ms 0.01 ms
TrunkLinesElsewhere (every bought attach or call) 273 (whole trunk index) 4 1.36 ms 0.01 ms

BoughtElsewhere's plan before is Postgres 18's skip scan; a server before 18 reads the whole phone_numbers_held_idx there instead.

Validation

Test Defect it catches Fails before the fix
AppsSuite/TestABuyerAttachesANumberAnotherCustomerLinedOnItsTrunkBeforeItWasBought the reviewer's repro: a squatter's line made before the purchase refuses the buyer's attach and call for good yes (no eviction)
AppsSuite/TestABuyerCallsFrom..., TestABuyerTransfersFrom...BeforeItWasBought a call or transfer from the unattached bought number does not take the line back yes
AppsSuite/TestACallFromANumberOnATrunkTakesNoOtherCustomersLine a trunk holder evicts another trunk holder mutant
AppsSuite/TestALineForTheNumberInAnotherAppIsLeftAlone eviction reaches a line in another app mutant
AppsSuite/TestALineWhoseAppCannotBeReachedIsLeftAsItWas, TestALineStreamWillNotDeleteTheRuleOfIsLeftAsItWas, TestALineOnATrunkStreamWillNotTakeTheNumberOffIsLeftAsItWas, TestALineOnATrunkWithNoRowIsLeftAsItWasWhenStreamKeepsItsRule the row is forgotten while Stream still holds the line (the reviewer saw unline do it) yes for unline as it was (mutant P7)
AppsSuite/TestALineOnATrunkStreamNoLongerHasIsForgotten, TestALineOnATrunkWithNoRowIsDeletedAtStream a trunk Stream lost, or one with no row, stops the buyer for good mutant
AppsSuite/TestTwoCustomersInAppsOfTheirOwnCanAddOneNumberToTheirTrunks (b): two apps of their own refused one number yes
AppsSuite/TestANumberBoughtInAnotherAppCanBeAddedToATrunkAndCalledFrom a number bought in another app refuses the trunk, or its calls yes
AppsSuite/TestANumberACustomerInTheSameAppBoughtCannotBeAddedToATrunk, TestANumberOnTheTrunkOfACustomerInTheSameAppCannotBeAddedToAnotherTrunk (a): the shared app lets a squatter in mutant (P13)
AppsSuite/TestAHolderWhoseAppCannotBeReadIsTakenToShareTheApp, TestACustomerWhoseAppCannotBeReadIsTakenToShareTheHoldersApp, TestATrunkNumberABuyerWhoseAppCannotBeReadHoldsIsNotCalledFrom an unreadable app fails open mutant
AppsSuite/TestANumberAnotherCustomerBoughtIsNotLinedFromATrunkItWasAddedToFirst a trunk lines a number another bought in its app; the refusal is retried by a campaign yes
StoredSuite/TestAskingWhereAFallingBackCustomersWorkGoesCountsNoUseOfTheFallback, TestAskingWhereAnAppWithATokenAboutToExpireActsAsksTheGatewayNothing, TestAskingWhereAnAppWhoseTokenRanOutActsAnswersItsOwnApp reading another customer's app counts a fallback use or mints a token in its name; with no fallback, an app whose token ran out reads as sharing the deployment's app (an idle squatter would hold a number against every app) n/a (new method); the last fails on the commit before it
AppsSuite/TestAskingWhereAHoldersLinesAreMadeCountsNoUseOfTheFallbackForIt the router's phone.Apps reads a holder's app through For n/a (new method)
StoreSuite/TestANumberAHolderInAnotherAppHoldsCanBeAddedToATrunk, TestAHolderNotReadInAnotherAppRefusesTheNumber apart ignored, or a holder the service did not clear let in n/a (new parameter)
StoreSuite/TestTheTrunkLinesElsewhereAreOtherCustomersLinesForTheNumberInTheApp each clause of the eviction lookup (number, vendor, customer, held, lined, app) n/a (new method)
StoreSuite/TestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPin a line in the deployment's app pinned the other way is missed n/a
StoreSuite+ShardedStoreSuite/TestAChangeToARecordingIsWrittenPastANumberLeftOutOfItsBatch the shard's half of a batch is dropped after a left-out number n/a
DataMoveSuite/TestANumberAnotherCustomerHoldsHereIsLeftOutOfAnImport the held number stops the import (ErrInvalidImport) yes
DataMoveSuite/TestABatchOfChangesWritesEverythingButANumberAnotherCustomerHoldsHere the held number stops the batch yes
DataMoveSuite/TestABatchOfChangesTakesItsNumbersLocksInOneOrder locks taken in change order (deadlock) yes
api DataMoveSuite/TestAnImportedNumberOnItsOwnTrunkAnotherAppHoldsIsLeftOutAndNotCounted the API import stops at it, counts it as written, or does not log how many it left out yes
TestReplicateRepeatSuite/TestACopyLeavesOut..., TestAFollowLeavesOutANumberAnotherAppHoldsHereAndMovesItsCursor router replicate stops at it and never moves its cursor, or does not say how many it left out yes
TestANumberAnotherAppHoldsIsOneConflictWhereverItIsRefused, SIPTrunksSuite/TestANumberAnotherAppHoldsIsAConflictThatNamesNoApp three answers for one condition; store: text yes
StoreSuite/TestPhoneNumberQueryBudgets Holders, BoughtElsewhere, TrunkLinesElsewhere one query each budget added

Kept from the branch: the refusal, race and given-back store tests, TestOfAnImportAndAnAddOfOneNumberAtOnceTheSecondIsRefused, the hook fallback test, and the outbound-rule guard.

Mutants, each alone with go test -overlay, and what caught it:

Mutant Caught by
P1 no eviction at all (the branch before this commit) the three TestABuyer... tests, TestALineOnATrunkStreamNoLongerHasIsForgotten, TestALineOnATrunkWithNoRowIsDeletedAtStream
P2/P3/P4 Attach / call / Transfer without clearLinesFor TestABuyerAttaches... (+2) / TestABuyerCallsFrom... / TestABuyerTransfersFrom...
P5 a trunk number evicts too TestACallFromANumberOnATrunkTakesNoOtherCustomersLine
P6 eviction goes on with an unreachable app (as unline does) TestALineWhoseAppCannotBeReachedIsLeftAsItWas
P7 eviction best effort (must false: unline's behaviour) the three Stream-failure tests
P8 / P9 / P10 each must branch of offTrunk ignored ...WithNoRowIsLeftAsItWas... / ...WillNotDeleteTheRule... / ...WillNotTakeTheNumberOff...
P11 a trunk Stream lost fails the eviction TestALineOnATrunkStreamNoLongerHasIsForgotten
P12 heldApart clears nobody (held anywhere) (b), ...BoughtInAnotherApp..., ...ABuyerWhoseAppCannotBeRead...
P13 heldApart clears everybody (a) both, TestAHolderWhoseAppCannotBeRead...
P14 / P15 unreadable holder / caller counted apart TestAHolderWhoseAppCannotBeRead... / TestACustomerWhoseAppCannotBeRead...
P16 / P17 / P18 dial: unreadable buyer let through / any app refuses / never refuses ...ABuyerWhoseAppCannotBeReadHoldsIsNotCalledFrom / ...BoughtInAnotherAppCanBeAddedToATrunkAndCalledFrom / ...IsNotLinedFromATrunkItWasAddedToFirst (+2)
P19 the refusal not lasting ...IsNotLinedFromATrunkItWasAddedToFirst
S1–S5 Placed counts a fallback use / acts / refreshes the token / Clients.Placed asks For / For stops acting the TestAskingWhere... tests; S5 by four existing For tests
S6 a read mints for a token that ran out TestAskingWhereAnAppWhoseTokenRanOut... (+1)
S7 an acting For also answers the own app for a token that ran out (!acting dropped) TestAnAppNoTokenWasForwardedForActsNowhere and four other For tests
P20 the phone adapter reads through Clients.Pin (For) TestAskingWhereAHoldersLinesAreMadeCountsNoUseOfTheFallbackForIt
D1 / D2 InsertOnSIPTrunk ignores apart / never refuses another holder TestANumberAHolderInAnotherAppHoldsCanBeAddedToATrunk / both race tests, TestAHolderNotReadInAnotherAppRefusesTheNumber, the two refusal tests
D3a–f TrunkLinesElsewhere without its vendor / customer / held / lined / app / number clause TestTheTrunkLinesElsewhere... (each); the app clause also TestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPin
D4 / D5 the deployment's app only by no pin / only by its id TestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPin (+1)
D6 a held number refused, as the branch did ...IsLeftOutOfAnImport, TestABatchOfChangesWrites..., TestAChangeToARecording... (both suites)
D7 a batch stops at a left-out number TestABatchOfChangesWrites..., TestAChangeToARecording...
D8 the shard's half dropped after a left-out number ShardedStoreSuite/TestAChangeToARecordingIsWrittenPastANumberLeftOutOfItsBatch
D9 / D10 no locks up front / locks in change order TestABatchOfChangesTakesItsNumbersLocksInOneOrder
D11 holders counts given-back rows both "gave it back" tests
A1 / A2 / A3 trunk add unmapped (500) / store text as a conflict, as the branch did / call unmapped SIPTrunksSuite/TestANumberAnotherAppHolds... / same / TestANumberAnotherAppHoldsIsOneConflictWhereverItIsRefused (500)
A4 / A5 / A6 the API import stops at a left-out row / change, or counts it api DataMoveSuite/TestAnImportedNumberOnItsOwnTrunkAnotherAppHoldsIsLeftOutAndNotCounted
R1 / R2 router replicate copy / follow stops at it TestACopyLeavesOut... / TestAFollowLeavesOut...
R3 / R4 / A7 the copy / the follow / the API import does not count or say what it left out TestACopyLeavesOut... / TestAFollowLeavesOut... / TestAnImportedNumber...LeftOutAndNotCounted

The "fails before the fix" column: P1 is the branch before this commit, P12 its held-anywhere rule, D6 and A2 its import and answer; each fails the tests marked yes. "Mutant" rows guard a rule this commit adds.

Suites, with -race, on this branch: internal/store whole (StoreSuite, ShardedStoreSuite, DataMoveSuite): everything passes but three chat-inbound tests in StoreSuite and one in ShardedStoreSuite, a clock race this branch does not cause (below). internal/phone/... whole (the package and its vendor, siptrunk, sipbridge and outcome packages). internal/streamapp whole. internal/api: SIPTrunksSuite, PhoneSuite, CallsSuite, CallHooksSuite, AppHooksSuite, DataMoveSuite, TelephonyBillingSuite, AppModeNamedCallSuite, DeploymentNamedCallSuite and the phone failure unit tests, 310 subtests. cmd/router TestReplicate*. go vet -tags integration ./... and gofmt are clean; cmd/openapi leaves the spec as committed; sdks/swift/generate.py --check and sdks/ruby/script/generate --check pass. The Rust, .NET and PHP checks were not run: they generate schemas (none changed) and, for Rust, operation summaries (none changed). The branch merges cleanly with origin/main (8c4910e); on that merge, with -race, AppsSuite, the new and changed StoreSuite tests, DataMoveSuite (store and API), SIPTrunksSuite and TestReplicateRepeatSuite pass, but for the clock race below; cmd/openapi and the Go client regenerate unchanged there.

The chat and channel inbound-claim failures are not this branch's. Those tests write a row due at Go's time.Now() (directly, or by moving next_attempt_at back by exactly the wait, timePasses) and claim it at once by Postgres's now(). On this machine the test Postgres container's clock drifts from the host's by tens of milliseconds: 400 reads of clock_timestamp(), each started after a host timestamp t0, came back 14–26 ms before t0. With Postgres behind, the row is not due yet and the claim takes nothing. Evidence:

  • TestAChatMessageIsNotClaimedBeforeItIsDue, TestARetriedChatMessageIsDueAtItsNextAttempt and TestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThirtyDays fail run alone on origin/main (8c4910e), measured right after a 14–17 ms lag, the same three that failed in this branch's whole-package run (plus the first again in ShardedStoreSuite).
  • The whole package on origin/main passed twice earlier the same night.
  • Twenty minutes later the lag was down to about 1 ms: then only TestARetriedChatMessageIsDueAtItsNextAttempt failed alone, on origin/main and on this branch alike.
  • The other way round: TestACampaignPausedAtTheSourceBeforeTheLastCatchUpRingsNobodyTwiceHere and TestACampaignTheCopyPausedIsNamedAndResumesWhereTheCopyLeftOff failed in whole DataMoveSuite runs of this branch merged with origin/main, and pass alone. They mark contacts due at Postgres's now() and claim them with Claim(ctx, ..., time.Now(), ...). With the claim instrumented, the contacts' next_attempt_at, written before the Go time was taken, was 4.0–4.8 ms after it: Postgres ahead. Instrumented the same way, origin/main (8c4910e) failed both on its first whole DataMoveSuite run, at the same 4–5 ms. Five price-list tests, which read PriceEntries.Active(ctx, time.Now()), failed once on the merge in the same window and not since.
  • The branch touches no chat, channel, campaign or price code or test, and its aNumber() is in internal/phone.

For the reviewer

  • The left-out count is not a field of the import's answer (asked for: "count it in the result"). DataImport is a model in every server SDK, and a numbers_left_out field needs the .NET and PHP models regenerated, which this machine cannot run without Docker. Instead the answer's rows and tables leave the number out, the router logs numbers_left_out=<n> with the import, and router replicate logs how many it left out, each asserted. Finishing it is one field on DataImport, set from leftOut, then cmd/openapi and every SDK's generator.
  • A holder idle past its token's life reads as the deployment's. Without minting, a run-out token is taken as one the gateway will not replace, so a number such an app holds is refused to a trunk in the deployment's app, and a deployment-app trunk number it bought is not called from, until the app acts again.
  • Imports stay deployment-wide. A number held by an app in another Stream app is still left out of an import; the API takes it afterwards.
  • No retry for two registrations racing in different apps. The second is refused once (409); asked again, it is let in.
  • Clients.Placed asks any source but app mode's For. Deployment mode's acts on nothing. Static (tests and embedders) asks its fallback's For.
  • Behaviour change at deploy. A trunk number another app in the same Stream app bought stops dialling; the next attach, call or transfer by the buyer takes the trunk's line down. Rows: SELECT t.customer_id, t.e164 FROM phone_numbers t JOIN phone_numbers b ON b.e164 = t.e164 AND b.customer_id <> t.customer_id AND b.vendor <> 'sip_trunk' AND b.released_at IS NULL WHERE t.vendor = 'sip_trunk' AND t.released_at IS NULL; (which of them share an app is not in the database).
  • API. transferPhoneCall declares 409; addTrunkNumber and importData describe the new answers. Regenerated: api/openapi.yaml, the Go SDK, the JS types and the Python client. The other SDKs carry neither those descriptions nor statuses, and no hand-written SDK code wraps these operations, so no SDK note.
  • After review (rebased onto main at ad39f1c; -race): internal/phone/... and internal/streamapp in full; internal/api SIPTrunksSuite, PhoneSuite, PhoneDigitsSuite, DataMoveSuite, CallsSuite, CallHooksSuite, AppHooksSuite, TelephonyBillingSuite, AppModeNamedCallSuite, DeploymentNamedCallSuite, CallStatusSuite; internal/store number, trunk, pin, migrate and import tests; cmd/router TestReplicate*. New tests, each failing with its mutant (applied alone with -overlay):
Mutant Caught by
dialVendor takes any placed error as held elsewhere TestACallFromATrunkNumberWhoseBuyersAppWasNotReadIsTriedAgain, …BuyersPolicyWasNotRead…
heldApart takes a failed read (caller's or a holder's) as sharing TestAddingANumberWhereTheCustomersAppWasNotReadIsTriedAgain, TestAddingANumberWhoseHoldersAppWasNotReadIsTriedAgain
Placed answers ErrNoIdentity, or the own app, for an unread policy StoredSuite/TestAPolicyReadErrorPlacesNobody
a required-own-app customer whose token ran out answered ErrNoIdentity StoredSuite/TestAskingWhereAnAppThatMustActInItsOwnAndWhoseTokenRanOutActsAnswersItsOwnApp
theirs == pin (no pin and the deployment's id taken as two apps) TestATransferInAnUnpinnedCallIsRefusedLikeOnePinnedToTheDeploymentsApp
Transfer passes 0 to dialVendor / to clearLinesFor TestATransferInAnAppTwoCustomersShareIsNotMadeFromATrunkNumberTheOtherBought / TestABuyerTransfersInAnAppItSharesFromANumberAnotherCustomerLinedThere
evict reaches the app with ForApp TestABuyerTakesDownALineWhoseCustomerHasSinceConnectedAnAppOfItsOwn
unline fails on a Stream error TestAReleaseStreamWillNotDeleteTheRuleOfStillGivesTheNumberBack
offTrunk ignores DeleteTrunk's error under must TestALineOnATrunkWithNoRowStreamWillNotDeleteIsLeftAsItWas
the usageIndexes entry, or its WHERE, removed TestMigrateRebuildsTheHeldNumberIndexLeftInvalid

Not done

  • Trunk against trunk in one shared app is first come. Nothing proves whose a trunk number is: the first app to register it in a Stream app keeps it there, and the real owner registering second gets 409 and needs support. Only a vendor's sale takes a line back.
  • A customer's app can change. Registration reads where each customer's lines are made now. One that connects an app of its own, or loses its token and falls back to the deployment's, can meet a number registered while it was elsewhere; between two trunks the first line made wins at Stream. A buyer still takes its line back.
  • A per-call trunk is not taken back. One a call or transfer made for itself (a vendor that cannot name the call on its leg, a transfer into a call of another type, a number Stream routes some other way) is recorded on the call, not on the number, so eviction does not find it; it lasts until its call is released.
  • Duplicates already written are not healed. Find them with SELECT e164, array_agg(DISTINCT customer_id) FROM phone_numbers WHERE released_at IS NULL GROUP BY e164 HAVING count(DISTINCT customer_id) > 1;. Their calls do not all keep working: of two trunk rows in one shared app, whichever customer lines the number second has its line refused by Stream (numbers already used by another SIP trunk) until the first's is taken down; a trunk row beside a purchase in the same app is refused at dial, and the buyer's next attach or call takes its line down. The hook fallback no longer goes ambiguous over them.
  • A half-failed eviction keeps a dead rule id. If Stream deletes the squatter's rule and then refuses the trunk update, the squatter's row is rolled back with a rule id Stream no longer has. The next eviction or line tolerates the 404 and heals it; it matters only if the buyer releases the number before then.
  • A bought row the vendor no longer has is never reconciled. The only check against the vendor is SweepOrders, which settles purchase and release orders whose outcome was not recorded (HoldsNumber, Twilio and Telnyx only). A row whose purchase was recorded is never asked about again, so a number the vendor took back without a release here keeps refusing the trunk owner's calls in that app. On Twilio the holder's own release fails first in StopInbound ("not one of this account's numbers") and keeps no order; on Telnyx the release keeps its order and the sweep then releases the row.
  • Flake risk in the API suite. e164() draws from 10 million numbers on a kept database; a draw another app's earlier run left held in the deployment's app is now refused.

Fixes AI-3752

🤖 Generated with Claude Code

@gitguardian

gitguardian Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

️✅ There are no secrets present in this pull request anymore.

If these secrets were true positive and are still valid, we highly recommend you to revoke them.
While these secrets were previously flagged, we no longer have a reference to the
specific commits where they were detected. Once a secret has been leaked into a git
repository, you should consider it compromised, even if it was deleted immediately.
Find here more information about risks.


🦉 GitGuardian detects secrets in your source code to help developers and security teams secure the modern development process. You are seeing this because you or someone else with access to this repository has authorized GitGuardian to scan your pull request.

@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3752-high-cross-tenant-phone-number branch from 0e62420 to df5375b Compare November 25, 2026 08:04
@martinmitrevski
martinmitrevski marked this pull request as ready for review November 25, 2026 08:06

@thesyncim thesyncim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed at df5375b merged with main 0e5197a (full store package, phone, streamapp, api and cmd/router suites, 38 mutants, race probes). The holder rule holds under concurrent adds, imports and evictions. Please don't merge yet: two points, one of them blocking, are better discussed off the PR and will come to you directly. The rest:

Should fix

  1. internal/phone/service.go, dialVendor (if theirs, err := s.placed(...); err != nil || theirs == pin): any error from placed is answered as ErrNumberHeldElsewhere, which lasting then treats as final, so one failed database read ends a campaign contact. Only a settled answer (no identity, disconnected) should count as sharing; other errors should be returned as they are so the dial is retried. The same applies in heldApart.
  2. migrations/global/20270310000000_*.sql sorts above the global slots of open #2333, #2334, #2335, #2348 and #2396, and goose refuses those once a database has run this one. Main's newest global slot is now 20270301000900 (#2385), which also conflicts with this PR in usageIndexes (keep both). Please take the next free slot in the agreed order, or hold this until they have merged.
  3. Rules no test holds: in Transfer, 0 passed in place of request.StreamApp to dialVendor or to clearLinesFor; evict reaching the app with ForApp in place of ForAppRemoving; unline failing on a Stream error; offTrunk ignoring the DeleteTrunk error under must. Every transfer test here is in the deployment's app (pin 0). Could you add a transfer in an app two customers share, an eviction whose customer has since connected an app of its own, and a release that Stream fails a rule delete for?

Nits

  • pinnedTo treats no pin and the deployment's id as one app, theirs == pin in dialVendor does not: a transfer in a call with no pin is let through where the same one pinned by id is refused.
  • Removing the usageIndexes entry, or its WHERE, fails no test I ran.
  • The PR now conflicts with main.

Question: a bought row for a number the vendor no longer has, and never released here, refuses the trunk owner's calls for good. Is there a reconcile?

martinmitrevski and others added 9 commits November 25, 2026 11:38
Adding a number to a customer's own SIP trunk, by the API or by a data
import, is refused when another customer holds that number, bought or on
a trunk of its own. The check runs under an advisory lock keyed on the
number, kept until the insert commits, so two customers adding one number
at once cannot both land. The refusal is a 409 that names nobody.

A call or transfer from a trunk number another customer bought is refused
before anything is made at Stream, so a registration made before the
purchase cannot line the number in the buyer's app, where Stream lists a
number on one trunk only.

An arriving call named for a number no longer resolves to a number on a
customer's own trunk, which never answers a call.

The rule a trunk number's line carries is kept: it is what lands the
outbound leg in the session's call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A number another customer holds is refused on a trunk only where it could
block them: in the Stream app this customer's lines are made in, read for
the caller and each holder without acting for them (no token minted, no
fallback use counted). In app mode each customer acts in an app of its own,
so a number registered first elsewhere no longer refuses the real holder.
A call or transfer from a trunk number is refused only when another
customer whose lines are made in that app bought it.

Attaching, calling or transferring from a bought number first takes down
any other customer's trunk line for it in that app: a line made before the
purchase otherwise refused the buyer for good. The line is forgotten only
once Stream let it go; a Stream that cannot be reached or refuses leaves it
as it was and fails the buyer's request, to be tried again.

An import or a replayed change of a trunk number another customer holds
here is left out and counted, rather than stopping the whole move on it;
a batch takes its numbers' locks up front in one order. The refusal is one
409 phone_number_held_elsewhere wherever it is answered. Who holds a number
is read by a new index on e164.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
With no fallback, an app's work is made in its own app or nowhere, so a
token that has run out no longer reads as sharing every app. Otherwise a
squatter that went idle would again hold a number against other apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only a deployment with the fallback off places an app whose token ran out
in its own app; with the fallback on, the same answer can be a policy read
that failed, which stays closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The next free slot in the agreed order, above the open PRs' global
migrations, so goose does not refuse theirs once a database has run this one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…elsewhere

Only a settled answer about where a buyer's or holder's lines are made (no
identity, a disconnected app, no Stream) counts as sharing the app. Any other
failure is returned as it is, so one failed read neither refuses a trunk
number for good nor ends a campaign contact. Read without acting, a policy
that could not be read is now such a failure rather than ErrNoIdentity.
A call or transfer's pin is compared as pinnedTo reads it, so an unpinned
call in the deployment's app is refused like one pinned by its id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…eniency and the held-number index

A transfer in an app two customers share is refused and evicts in that app;
a line whose customer has since connected an app of its own is still taken
down; a release Stream refuses a rule delete for still gives the number back;
a trunk with no row Stream will not delete leaves the line as it was; and the
held-number index is rebuilt, with its WHERE, when a build left it invalid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts token ran out

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3752-high-cross-tenant-phone-number branch from df5375b to a89720c Compare November 25, 2026 11:23
@martinmitrevski

Copy link
Copy Markdown
Collaborator Author

Thanks. Rebased on main (both usageIndexes entries kept; importData's left-out count now lives in importLine). Noted on not merging yet.

1. dialVendor / heldApart (6426bfa): only a settled answer (no identity, disconnected, no Stream) counts as sharing; any other error from placed is returned as it is, in both. A failed read now fails the call as ErrNotDialed, which a campaign retries. Stored.Placed no longer turns a policy it could not read into ErrNoIdentity, which would have been settled; For is unchanged. Following from that (a89720c): read without acting, an app whose policy requires an app of its own is placed there when its token ran out, as with no fallback, rather than answered ErrNoIdentity.

2. Migration slot (50710df): moved to global 20270301001400, the next slot in the agreed order, so this lands after #2396 and #2348.

3. Tests (19ada91), each checked against its mutant: a transfer in an app two customers share (both the refusal and the eviction), an eviction whose customer has since connected its own app (ForAppRemoving), a release Stream refuses a rule delete for, a line on a trunk with no row that Stream will not delete (offTrunk under must), and TestMigrateRebuildsTheHeldNumberIndexLeftInvalid for the usageIndexes entry and its WHERE.

Nit, pinnedTo vs theirs == pin: fixed with the rest of 1, since it was the same line: dialVendor compares through pinnedTo (store.SameStreamApp), so a transfer in an unpinned call in the deployment's app is refused like one pinned by its id.

Reconcile: no. The only check against the vendor is SweepOrders, which settles purchase and release orders whose outcome was not recorded (HoldsNumber, Twilio and Telnyx only); a recorded purchase is never asked about again. Listed under "Not done" in the description.

@martinmitrevski
martinmitrevski merged commit b86e02f into main Nov 25, 2026
20 of 21 checks passed
@martinmitrevski
martinmitrevski deleted the martinmitrevski/ai-3752-high-cross-tenant-phone-number branch November 25, 2026 13:02
kanat added a commit that referenced this pull request Nov 25, 2026
…69-http-connectors

Conflicts:
- internal/api/configs.go: main moved the sensitive-connector rule into
  internal/connectors/sensitive (#2432); the feature's digest-aware grant check
  (grantSendsOut, #2324) moves there as sensitive.GrantSendsOut, used by
  bindingSendsOut, so ConfigComplaint and GraphComplaint both judge an http tool
  at the digest its grant pins.
- internal/api/connection_tools.go: listConnectionTools calls
  sensitive.GrantSendsOut; comment names both.
- internal/connectors/core/manifest.go, .claude/skills/connectors/SKILL.md:
  comments/doc keep both sides.
- internal/store/datamove.go: applyChanges keeps the feature's importableRow
  pass before the transaction and main's lockNumbers / NumbersLeftOutError
  (#2412); ImportRow drops main's `var err error` that redeclared the feature's err.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Loschcode added a commit that referenced this pull request Nov 27, 2026
## Why


https://linear.app/stream/issue/AI-3769/campaign-dialer-a-dial-that-can-never-succeed-ends-the-contact-instead

Since #2263 (AI-3508), a dial that fails before anything rings falls
into one of two kinds:
- a failure that may pass later, which is marked `phone.ErrNotDialed`;
- a failure no later dial can pass, the `lasting` set in
`internal/phone/service.go`.

The second kind was returned unmarked. `resultOf` then took it as a call
that may have rung (`Outcome: Unknown`). A double-dial campaign dialed
again at once, then used the attempt and scheduled the next one. Every
remaining attempt met the same failure.

Decision on the ticket (Laurent, 2026-11-24): end such a contact for
good.

## What changed

- **A lasting pre-ring failure ends the contact.**
- `phone.Service.Call` marks a lasting failure with a new
`phone.ErrCannotDial`, through `unsent(err)`. The wrapper keeps
`Unwrap`, so `errors.Is` on the inner kind (`store.ErrNoNumber`,
`ErrNoStream`, …) still holds for the API callers.
  - `resultOf` maps it to `Refused` with reason `cannot_dial`.
- `afterDial` settles that as `Failed` / `cannot_dial`, with no second
dial and no next attempt.
- This holds on dial 2 as well, even though dial 1 had rung the person:
a later attempt would only meet the same failure. On dial 2 the attempt
is counted as used.
- One exception: a router that dies between ending the dial and settling
the contact loses the reason, because the takeover reads only the stored
result. Then a dial-1 failure settles `failed` with no reason, and a
dial-2 failure gets one more attempt, which ends as `cannot_dial` at its
first dial.
- The dialer returns the error with the result, so the runner still logs
which credential, trunk or number is missing. Otherwise only the reason
code would be logged.
- The activity record counts such a dial refused under `cannot_dial`.
Before, it was counted under `dial_failed`.
- **A missing Stream identity is retried, not ended.**
- `streamapp.ErrNoIdentity` is in `lasting()` through
`streamapp.Settled`. But acting in app mode, streamapp also answers it
for two failures that may pass:
- the gateway could not mint a token to replace an expired forwarded
one;
- a database blip hid whether the customer may fall back to the
deployment's app.
- `Clients` also keeps the refusal for about 30s. So one blip would have
failed every contact a campaign dialed in that window.
- `unsent` therefore marks it `ErrNotDialed`: a 5-minute retry with the
12-try cap.
- Follow-up: AI-4302, so that streamapp returns those two failures
unmarked.
- **Kinds main added to `lasting()` since this branch was cut:**
- `store.ErrNumberHeldElsewhere` (#2412): another app holds the number.
This is lasting until that app lets the number go.
- `store.ErrCallTaken` (#2402): the named call is another customer's.
This is lasting for that call id. A campaign dials a fresh id each time,
so in practice it never meets it.
  - Both now end a campaign contact as `cannot_dial`.
- Caveat: the buyer check behind `ErrNumberHeldElsewhere` treats a buyer
whose app read answers `ErrNoIdentity` as holding the number. A
transient `ErrNoIdentity` there is still lasting. It needs a vendor to
have sold the same number to two customers, and it goes away with
AI-4302.
- **The retryable path is unchanged.**
- A failure that may pass is still `ErrNotDialed`, retried after 5
minutes, and uses the attempt after 12 tries.
- `TestADialThatKeepsFailingBeforeItRingsUsesTheAttemptInTheEnd` is
untouched and passes.
- **The campaign-wide pause is unchanged.**
- `pausing()` runs before the new case. A disconnected or moved Stream
app is in the lasting set (`streamapp.Settled`), and it still pauses the
campaign with the attempt kept.
  - A dlc refusal and an invalid number also keep their own results.
  - A test covers each of these with the new marker on the error.
- **Docs:** `.factory/features/campaigns.md` gains a `cannot_dial`
bullet, including the take-over exception.
- **No migration, no API change.**
  - `Refused` and the contact stage `failed` already exist.
- The contact `reason` is a free-text field: its API doc lists no
values, and `opted_out` is written the same way.
  - The attempt's `result` reads `refused`, which its doc already lists.
- `go run ./cmd/openapi` gives no diff, so no clients were regenerated.

## Tests

- `ServiceSuite.TestOnlyAFailureEveryLaterTryMeetsIsMarkedCannotDial` is
a unit table over `unsent`. It checks every lasting kind against
`ErrCannotDial` or `ErrNotDialed`. That covers `ErrNoIdentity` (bare,
and wrapping a mint 503) → retried, and `ErrSIPTrunksDisabled`,
`ErrNumberHeldElsewhere` and `ErrCallTaken` → cannot-dial.
- `TransitionSuite.TestAMissingStreamIdentityIsTriedAgain`: an
`ErrNoIdentity` marked never dialed is retried in 5 minutes without
using the attempt.
- `TransitionSuite`:
- `TestADialThatCanNeverBePlacedEndsTheContact`: each lasting kind ends
the contact on dial 1, attempt kept, and on dial 2, attempt used.
- `TestACampaignWideOrOwnFailureThatCanNeverBePlacedKeepsItsResult`:
Paused, Refused and InvalidNumber still win.
- `RunnerSuite.TestADialThatCanNeverBePlacedEndsTheContactAtOnce`
(integration):
- The real phone dialer runs on a router with no Stream credentials,
with double dial on.
  - It ticks, then ticks again after the attempt delay.
- Result: one dial and one attempt row, and the contact is `failed` /
`cannot_dial` with no next attempt.
- Its log names the missing credential, which fails if the dialer
swallows the error.
- `OutcomeSuite` (integration):
  - A number the app does not hold is `ErrCannotDial`.
  - A database blip and a vendor failure are not.

```
go test -race ./internal/phone/... ./internal/campaign/...                      ok
go test -tags integration -p 1 -race ./internal/phone/... ./internal/campaign/... ok
```

Results on the merged head `573de51f1`: both runs above pass for every
package.

Three reverts each make the new tests fail; the output is below:
- dropping the `ErrNoIdentity` exclusion in `unsent`, which fails the
unit table on both `ErrNoIdentity` rows;
- dropping the `ErrCannotDial` wrap in `Call`, with the sentinel kept;
- dropping the `resultOf` case.

Without the wrap in `Call`, the runner dials four times over two
attempts, the bug as it was:
```
--- FAIL: TestRunnerSuite/TestADialThatCanNeverBePlacedEndsTheContactAtOnce
    expected: "failed"       actual: "enrolled"
    expected: "cannot_dial"  actual: ""
    Expected nil, but got: time.Date(2026, time.March, 13, 11, 0, 0, 0, time.UTC)
    "[... 4 attempt rows: attempt 1 dial 1, 1/2, 2/2, 2/1, each call_outcome unknown]" should have 1 item(s), but has 4
```
Without the `ErrNoIdentity` exclusion:
```
--- FAIL: TestService/TestOnlyAFailureEveryLaterTryMeetsIsMarkedCannotDial
    Target error should be in err chain:      streamapp: no Stream app is configured for this customer
    Target error should not be in err chain:  streamapp: no Stream app is configured for this customer
    Target error should be in err chain:      streamapp: no Stream app is configured for this customer: gateway: mint: 503
```
Without the `resultOf` case:
```
--- FAIL: TestTransitionSuite/TestADialThatCanNeverBePlacedEndsTheContact
    expected: "refused"  actual: ""
    expected: "failed"   actual: "enrolled"
--- FAIL: TestRunnerSuite/TestADialThatCanNeverBePlacedEndsTheContactAtOnce
    expected: "failed"   actual: "enrolled"
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Laurent Schaffner <laurentschaffner@Laurents-MacBook-Pro-Stream.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants