Repository navigation
AI-3752: a number is held by one app per Stream app - #2412
martinmitrevski merged 9 commits into
Conversation
️✅ 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. 🦉 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. |
0e62420 to
df5375b
Compare
thesyncim
left a comment
There was a problem hiding this comment.
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
internal/phone/service.go,dialVendor(if theirs, err := s.placed(...); err != nil || theirs == pin): any error fromplacedis answered asErrNumberHeldElsewhere, whichlastingthen 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 inheldApart.migrations/global/20270310000000_*.sqlsorts 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 inusageIndexes(keep both). Please take the next free slot in the agreed order, or hold this until they have merged.- Rules no test holds: in
Transfer, 0 passed in place ofrequest.StreamApptodialVendoror toclearLinesFor;evictreaching the app withForAppin place ofForAppRemoving;unlinefailing on a Stream error;offTrunkignoring theDeleteTrunkerror undermust. 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
pinnedTotreats no pin and the deployment's id as one app,theirs == pinindialVendordoes not: a transfer in a call with no pin is let through where the same one pinned by id is refused.- Removing the
usageIndexesentry, or itsWHERE, 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?
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>
df5375b to
a89720c
Compare
|
Thanks. Rebased on main (both 1. 2. Migration slot (50710df): moved to global 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 ( Nit, Reconcile: no. The only check against the vendor is |
…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>
## 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>
Why
POST /v1/phone/trunks/{id}/numberslet any customer add any E.164 to its own SIP trunk, whoever else held it:InsertOnSIPTrunkonly looked for the caller's own row, andphone_numbers_trunk_held_idxis unique per(customer_id, e164)./v1/data/importwrote such a row too, with no check at all.One call from a number on a trunk lines it:
sharedLine→line→joinputs 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 inAppsSuitewith the Stream stand-in'sOneTrunkPerNumber(): after the squatter's one call (the line is made before the dial, so the call need not connect), the buyer'sAttachandCallboth failed withnumbers already used by another SIP trunk, and kept failing.Where the ticket differs from the code:
sip_trunkprovider's leg isStreamLegShared(siptrunk/siptrunk.go:171). The router's bridge dials the number's Stream trunk withx_stream_call_id, and the rule'slineCallTemplateis 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. Itsphone_numbercustom is read only byNumberRungInApp(attached numbers only, andAttachrefuses a trunk number), afterCallResourceshas already claimed a placed leg.NumberByCallInApp'sErrAmbiguousHookis narrower than stated. A call on a line made today carriesphone_numberand is resolved byNumberRungInApp. The fallback by E.164 only serves calls namedphone-<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:1315is a comment incall; the line is made atservice.go:1348(sharedLine).How it works
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.streamForis not side-effect free for a holder:Stored.Forcounts a use of the fallback and logs it under the holder's name (fellBack),Forwarded.identityasks the gateway's mint for a token that is about to run out and stores it, andClients.Forbinds a client and caches the answer.Stored.Placed(Clients.Placed,phone.Apps.Placed) makes the same decision asForwithout 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, asForanswers when the gateway will not mint another. Deployment mode'sForacts 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 asErrNoIdentity. Pins are compared throughpinnedTo(store.SameStreamApp), so no pin and the deployment's id name one app.unlinenotes). 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.sip_trunk) evicts, only other customers' livesip_trunkrows, only lines of that E.164, only in the app the buyer's line is about to be made in. It runs inAttach,call(shared line and per-call trunk alike) andTransfer, before anything is made at Stream and outside the buyer's own trunk-group lock.offTrunkgainedmust: 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_trunkrow was checked to be vouched for by a vendor:Buyrecords the E.164 the vendor'sBuyNumberanswered andSweepOrdersrecords one only afterHoldsNumberconfirms it; imports never write one (importableNumber), no update setsvendoror clearsreleased_at, and vendors run on the deployment's own credentials, so no customer brings its own account.BoughtElsewherenow 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.api/datamove.go:284,replicate.go:345returned without moving the cursor).applyChangestakes every number's lock in one statement, sorted (unnest, aslockTaskLimitsandlogRequestsdo), before its first change: one lock per change in change order let two batches deadlock (40P01).errNumberHeldElsewhereis oneAPIError: 409phone_number_held_elsewhere, "Another app holds this number, so it cannot be added to or called from your SIP trunk.", fromsipTrunkFailure(trunk add) andphoneFailure(call, transfer, throughcallFailure). It names no app, organization or trunk and carries nostore:text.transferPhoneCallnow declares 409. The call's refusal is no longerInvalid(...), whosemarkedwrapper hid the sentinel fromerrors.Is;lastingnames it instead, so a campaign does not retry it.phone_numbers_e164_held_idx (e164) WHERE released_at IS NULL, built concurrently in global migration20270301001400and listed inusageIndexes. 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,
Holdersis the readholdersalready ran, without the lock):Run on the local test Postgres (19.0), on a copy of the
phone_numbersschema 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 e164Plans after:
phone_numbers_e164_held_idxholders(every registration, imported number)BoughtElsewhere(every trunk call)TrunkLinesElsewhere(every bought attach or call)BoughtElsewhere's plan before is Postgres 18's skip scan; a server before 18 reads the wholephone_numbers_held_idxthere instead.Validation
AppsSuite/TestABuyerAttachesANumberAnotherCustomerLinedOnItsTrunkBeforeItWasBoughtAppsSuite/TestABuyerCallsFrom...,TestABuyerTransfersFrom...BeforeItWasBoughtAppsSuite/TestACallFromANumberOnATrunkTakesNoOtherCustomersLineAppsSuite/TestALineForTheNumberInAnotherAppIsLeftAloneAppsSuite/TestALineWhoseAppCannotBeReachedIsLeftAsItWas,TestALineStreamWillNotDeleteTheRuleOfIsLeftAsItWas,TestALineOnATrunkStreamWillNotTakeTheNumberOffIsLeftAsItWas,TestALineOnATrunkWithNoRowIsLeftAsItWasWhenStreamKeepsItsRuleunlinedo it)unlineas it was (mutant P7)AppsSuite/TestALineOnATrunkStreamNoLongerHasIsForgotten,TestALineOnATrunkWithNoRowIsDeletedAtStreamAppsSuite/TestTwoCustomersInAppsOfTheirOwnCanAddOneNumberToTheirTrunksAppsSuite/TestANumberBoughtInAnotherAppCanBeAddedToATrunkAndCalledFromAppsSuite/TestANumberACustomerInTheSameAppBoughtCannotBeAddedToATrunk,TestANumberOnTheTrunkOfACustomerInTheSameAppCannotBeAddedToAnotherTrunkAppsSuite/TestAHolderWhoseAppCannotBeReadIsTakenToShareTheApp,TestACustomerWhoseAppCannotBeReadIsTakenToShareTheHoldersApp,TestATrunkNumberABuyerWhoseAppCannotBeReadHoldsIsNotCalledFromAppsSuite/TestANumberAnotherCustomerBoughtIsNotLinedFromATrunkItWasAddedToFirstStoredSuite/TestAskingWhereAFallingBackCustomersWorkGoesCountsNoUseOfTheFallback,TestAskingWhereAnAppWithATokenAboutToExpireActsAsksTheGatewayNothing,TestAskingWhereAnAppWhoseTokenRanOutActsAnswersItsOwnAppAppsSuite/TestAskingWhereAHoldersLinesAreMadeCountsNoUseOfTheFallbackForItphone.Appsreads a holder's app throughForStoreSuite/TestANumberAHolderInAnotherAppHoldsCanBeAddedToATrunk,TestAHolderNotReadInAnotherAppRefusesTheNumberapartignored, or a holder the service did not clear let inStoreSuite/TestTheTrunkLinesElsewhereAreOtherCustomersLinesForTheNumberInTheAppStoreSuite/TestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPinStoreSuite+ShardedStoreSuite/TestAChangeToARecordingIsWrittenPastANumberLeftOutOfItsBatchDataMoveSuite/TestANumberAnotherCustomerHoldsHereIsLeftOutOfAnImportErrInvalidImport)DataMoveSuite/TestABatchOfChangesWritesEverythingButANumberAnotherCustomerHoldsHereDataMoveSuite/TestABatchOfChangesTakesItsNumbersLocksInOneOrderapi DataMoveSuite/TestAnImportedNumberOnItsOwnTrunkAnotherAppHoldsIsLeftOutAndNotCountedTestReplicateRepeatSuite/TestACopyLeavesOut...,TestAFollowLeavesOutANumberAnotherAppHoldsHereAndMovesItsCursorrouter replicatestops at it and never moves its cursor, or does not say how many it left outTestANumberAnotherAppHoldsIsOneConflictWhereverItIsRefused,SIPTrunksSuite/TestANumberAnotherAppHoldsIsAConflictThatNamesNoAppstore:textStoreSuite/TestPhoneNumberQueryBudgetsHolders,BoughtElsewhere,TrunkLinesElsewhereone query eachKept 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:TestABuyer...tests,TestALineOnATrunkStreamNoLongerHasIsForgotten,TestALineOnATrunkWithNoRowIsDeletedAtStreamAttach/call/TransferwithoutclearLinesForTestABuyerAttaches...(+2) /TestABuyerCallsFrom.../TestABuyerTransfersFrom...TestACallFromANumberOnATrunkTakesNoOtherCustomersLineunlinedoes)TestALineWhoseAppCannotBeReachedIsLeftAsItWasmustfalse:unline's behaviour)mustbranch ofoffTrunkignored...WithNoRowIsLeftAsItWas.../...WillNotDeleteTheRule.../...WillNotTakeTheNumberOff...TestALineOnATrunkStreamNoLongerHasIsForgottenheldApartclears nobody (held anywhere)...BoughtInAnotherApp...,...ABuyerWhoseAppCannotBeRead...heldApartclears everybodyTestAHolderWhoseAppCannotBeRead...TestAHolderWhoseAppCannotBeRead.../TestACustomerWhoseAppCannotBeRead......ABuyerWhoseAppCannotBeReadHoldsIsNotCalledFrom/...BoughtInAnotherAppCanBeAddedToATrunkAndCalledFrom/...IsNotLinedFromATrunkItWasAddedToFirst(+2)lasting...IsNotLinedFromATrunkItWasAddedToFirstPlacedcounts a fallback use / acts / refreshes the token /Clients.PlacedasksFor/Forstops actingTestAskingWhere...tests; S5 by four existingFortestsTestAskingWhereAnAppWhoseTokenRanOut...(+1)Foralso answers the own app for a token that ran out (!actingdropped)TestAnAppNoTokenWasForwardedForActsNowhereand four otherFortestsClients.Pin(For)TestAskingWhereAHoldersLinesAreMadeCountsNoUseOfTheFallbackForItInsertOnSIPTrunkignoresapart/ never refuses another holderTestANumberAHolderInAnotherAppHoldsCanBeAddedToATrunk/ both race tests,TestAHolderNotReadInAnotherAppRefusesTheNumber, the two refusal testsTrunkLinesElsewherewithout its vendor / customer / held / lined / app / number clauseTestTheTrunkLinesElsewhere...(each); the app clause alsoTestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPinTestATrunkLineInTheDeploymentsAppIsFoundByItsIdOrNoPin(+1)...IsLeftOutOfAnImport,TestABatchOfChangesWrites...,TestAChangeToARecording...(both suites)TestABatchOfChangesWrites...,TestAChangeToARecording...ShardedStoreSuite/TestAChangeToARecordingIsWrittenPastANumberLeftOutOfItsBatchTestABatchOfChangesTakesItsNumbersLocksInOneOrderholderscounts given-back rowsSIPTrunksSuite/TestANumberAnotherAppHolds.../ same /TestANumberAnotherAppHoldsIsOneConflictWhereverItIsRefused(500)api DataMoveSuite/TestAnImportedNumberOnItsOwnTrunkAnotherAppHoldsIsLeftOutAndNotCountedrouter replicatecopy / follow stops at itTestACopyLeavesOut.../TestAFollowLeavesOut...TestACopyLeavesOut.../TestAFollowLeavesOut.../TestAnImportedNumber...LeftOutAndNotCountedThe "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/storewhole (StoreSuite,ShardedStoreSuite,DataMoveSuite): everything passes but three chat-inbound tests inStoreSuiteand one inShardedStoreSuite, a clock race this branch does not cause (below).internal/phone/...whole (the package and its vendor,siptrunk,sipbridgeandoutcomepackages).internal/streamappwhole.internal/api:SIPTrunksSuite,PhoneSuite,CallsSuite,CallHooksSuite,AppHooksSuite,DataMoveSuite,TelephonyBillingSuite,AppModeNamedCallSuite,DeploymentNamedCallSuiteand the phone failure unit tests, 310 subtests.cmd/routerTestReplicate*.go vet -tags integration ./...andgofmtare clean;cmd/openapileaves the spec as committed;sdks/swift/generate.py --checkandsdks/ruby/script/generate --checkpass. 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 changedStoreSuitetests,DataMoveSuite(store and API),SIPTrunksSuiteandTestReplicateRepeatSuitepass, but for the clock race below;cmd/openapiand 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 movingnext_attempt_atback by exactly the wait,timePasses) and claim it at once by Postgres'snow(). On this machine the test Postgres container's clock drifts from the host's by tens of milliseconds: 400 reads ofclock_timestamp(), each started after a host timestampt0, came back 14–26 ms beforet0. With Postgres behind, the row is not due yet and the claim takes nothing. Evidence:TestAChatMessageIsNotClaimedBeforeItIsDue,TestARetriedChatMessageIsDueAtItsNextAttemptandTestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThirtyDaysfail 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 inShardedStoreSuite).TestARetriedChatMessageIsDueAtItsNextAttemptfailed alone, on origin/main and on this branch alike.TestACampaignPausedAtTheSourceBeforeTheLastCatchUpRingsNobodyTwiceHereandTestACampaignTheCopyPausedIsNamedAndResumesWhereTheCopyLeftOfffailed in wholeDataMoveSuiteruns of this branch merged with origin/main, and pass alone. They mark contacts due at Postgres'snow()and claim them withClaim(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 wholeDataMoveSuiterun, at the same 4–5 ms. Five price-list tests, which readPriceEntries.Active(ctx, time.Now()), failed once on the merge in the same window and not since.aNumber()is ininternal/phone.For the reviewer
DataImportis a model in every server SDK, and anumbers_left_outfield needs the .NET and PHP models regenerated, which this machine cannot run without Docker. Instead the answer'srowsandtablesleave the number out, the router logsnumbers_left_out=<n>with the import, androuter replicatelogs how many it left out, each asserted. Finishing it is one field onDataImport, set fromleftOut, thencmd/openapiand every SDK's generator.Clients.Placedasks any source but app mode'sFor. Deployment mode's acts on nothing.Static(tests and embedders) asks its fallback'sFor.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).transferPhoneCalldeclares 409;addTrunkNumberandimportDatadescribe 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.mainat ad39f1c;-race):internal/phone/...andinternal/streamappin full;internal/apiSIPTrunksSuite,PhoneSuite,PhoneDigitsSuite,DataMoveSuite,CallsSuite,CallHooksSuite,AppHooksSuite,TelephonyBillingSuite,AppModeNamedCallSuite,DeploymentNamedCallSuite,CallStatusSuite;internal/storenumber, trunk, pin, migrate and import tests;cmd/routerTestReplicate*. New tests, each failing with its mutant (applied alone with-overlay):dialVendortakes anyplacederror as held elsewhereTestACallFromATrunkNumberWhoseBuyersAppWasNotReadIsTriedAgain,…BuyersPolicyWasNotRead…heldAparttakes a failed read (caller's or a holder's) as sharingTestAddingANumberWhereTheCustomersAppWasNotReadIsTriedAgain,TestAddingANumberWhoseHoldersAppWasNotReadIsTriedAgainPlacedanswersErrNoIdentity, or the own app, for an unread policyStoredSuite/TestAPolicyReadErrorPlacesNobodyErrNoIdentityStoredSuite/TestAskingWhereAnAppThatMustActInItsOwnAndWhoseTokenRanOutActsAnswersItsOwnApptheirs == pin(no pin and the deployment's id taken as two apps)TestATransferInAnUnpinnedCallIsRefusedLikeOnePinnedToTheDeploymentsAppTransferpasses 0 todialVendor/ toclearLinesForTestATransferInAnAppTwoCustomersShareIsNotMadeFromATrunkNumberTheOtherBought/TestABuyerTransfersInAnAppItSharesFromANumberAnotherCustomerLinedThereevictreaches the app withForAppTestABuyerTakesDownALineWhoseCustomerHasSinceConnectedAnAppOfItsOwnunlinefails on a Stream errorTestAReleaseStreamWillNotDeleteTheRuleOfStillGivesTheNumberBackoffTrunkignoresDeleteTrunk's error undermustTestALineOnATrunkWithNoRowStreamWillNotDeleteIsLeftAsItWasusageIndexesentry, or itsWHERE, removedTestMigrateRebuildsTheHeldNumberIndexLeftInvalidImportRow's doc comment; the sentence moved to its own paragraph, and the merge is clean now (git merge-tree). Not run together.Not done
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.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 inStopInbound("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.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