Repository navigation
AI-3514: record vendor work whose outcome was lost - #2284
martinmitrevski merged 12 commits into
Conversation
martinmitrevski
left a comment
There was a problem hiding this comment.
Reviewed #2284 at d08b995 (merge base 644103a, mergeable). CI: go and integration were skipped (draft), so no Go test has run in CI on this head; CodeQL go/python still pending.
Question (item 3, no diff line): resolver.go on main does retry the save (#2192), but only 3 saves, 100 ms then 200 ms apart (saveAgain, resolver.go:464-486). After that the rotated token is dropped and the connection needs a reconnect (TestARefreshWhoseSavesAllFailKeepsTheCheckpointAndIsLoggedOnce). The ticket asked to keep it in memory until it is stored. So a Postgres failure lasting more than about 300 ms still costs the person a reconnect: the gap this PR closes for legs with an in-memory queue. Either say in AI-3514 that the bounded retry is the accepted outcome, or keep the token the way the legs are kept.
Nit (description): 'deleted in the same transaction that writes the outcome' is true for a buy (PhoneNumberOrders.Bought). A release's order is deleted by a separate statement after unline commits (service.go:595). A leftover one settles harmlessly (the vendor no longer holds the number, and the row is already released), so only the description is wrong.
Verdict: request changes, for the Blocker at service.go:516. A vendor call that errors forgets its order, so the timeout/5xx case is never settled, even though the number may have been bought or released at the vendor.
Checked and sound:
- Migrations
20270201000300(new table) and20270201000310(two nullableADD COLUMNs, no rewrite) setlock_timeoutfirst. Both versions are above everything onorigin/main(global and shard both end at20270127000400).schema/global.sqlmatches them. - Telnyx 4xx ->
ErrVendorRefused, 5xx kept: right. A 4xx answer (validation, auth, rate limit) registers nothing. - Items 5 and 6: the numbers are checked, then the use case and its numbers are written in one transaction.
ON CONFLICT (customer_id) WHERE is_default DO NOTHINGplus one retry is correct under READ COMMITTED.TestACreateRacingTheAppsFirstUseCaseIsItsSecondwaits on the real lock throughpg_stat_activity. - Kept legs: bounded at 1000, owned by the process, each carrying its own tenant fields, with no goroutine or timer. The retry is idempotent for an inbound leg (
call_legs_inbound_idx) and for a placed one (token updateWHERE dialed_at IS NULL). - A swept number cannot be inserted twice (
phone_numbers_held_idx->ErrNumberRecorded) or billed twice (the month's usage id is vendor + e164 + purchased_at + month, the same on both paths). - No HTTP operation changed:
go run ./cmd/openapileavesopenapi.yamlunchanged.
Ran in the review worktree: go build ./..., go vet on the touched packages with and without -tags integration, and the unit tests in ./internal/phone/... ./internal/dlc/... ./internal/store/. All pass. Integration tests were not run: no finding depends on them.
d08b995 to
eb86223
Compare
|
On the two items in the review body: Item 3 (refresh save). Fixed in 92adb54, not accepted as a bounded retry. When
There is no goroutine and nothing to flush. Residual risk: only the router that renewed holds the renewal. A Test: Description nit. Corrected. The body now says a release deletes its order in a second statement, after |
martinmitrevski
left a comment
There was a problem hiding this comment.
Re-reviewed at eb86223 (base 89e9e0c; acceleration/ is unchanged from there to current main 82742b4). CI: go and integration were skipped (draft).
Every finding from the last review is addressed:
- Orders (the Blocker): an order is forgotten only on a 4xx
VendorError, so a timeout or 5xx is now left to the sweep. Covered byTestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweepand...GivenBackWhoseAnswerWasAFailure.... - Transfer leg:
call_legs_transfer_idxmakes the retry idempotent. The shard migration deletes no rows: it clearsvendor_call_idon the older of two legs that share call, app and vendor id. That column is not part of any usage id (legUsageID= customer, call, leg id, dialed_at), and onlyPlaced, the check for pressing digits, reads it. So no minutes are lost and the newest leg still authorizes digits. The UPDATE runs outside a transaction and locks only the rows it changes; the index is builtCONCURRENTLY, andensureUsageIndexesrebuilds it if the build fails. - Shutdown, and a leg written after its call ended: fixed by
StopLegSweepafter the drains andunopened.end. - Sweep starvation: fixed by
ClaimwithSKIP LOCKEDand a 1 h lease. - The release the vendor still holds: now tested.
- 10DLC: an unsent request is
ErrNotCarriedOut; a request under 10 min old is left alone; a campaign is found by itsreferenceId, which Telnyx's API reference requires to be unique across submitted campaigns, so a re-ask cannot register a second one. The id is logged when its save fails. - Item 3: a renewal is held in memory, keyed by
ConnectionRef(customer + connection), at most 1000. It is saved only while the row is still exactly as its checkpoint left it, so it cannot overwrite a reconnect or a newer save. - Nits: all fixed.
Nit (no diff line): a lost brand now frees the use case (vendor_rejected, editable and deletable) and tells the customer to contact support. Support's step, recording the brand id or clearing brand_requested_at, is still raw SQL on production; a staff command or a runbook entry would close that.
Verdict: approve: no Blocker. The Should fix at service.go:617 can land here or in a follow-up.
Ran in the review worktree: go build ./..., go vet ./... and go vet -tags integration ./... on every package (clean), plus the unit tests of phone/..., dlc/..., store, connectors/resolver and cmd/router (pass). The integration tests were not run: the test Postgres was not up, and no finding depends on them. I read each new test against a broken version of the code it covers (forget on every error, release on every release order, no lease, no last write at stop, no add refusal after stop, no unique index, no in-memory hold); each one would fail.
dlc.Service.Create inserted the use case, then checked and assigned its numbers in a second transaction, so a refused or failed assignment left a use case without them. The numbers are now checked first and assigned in the transaction that inserts the use case. Two creates at once for an app's first use case both found none, and the second insert hit dlc_use_cases_default_idx: a 500. The insert now uses ON CONFLICT on that index and is tried again once, when the app has a default and the new use case is its second. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the row of a call leg could not be written, OpenLeg logged that its minutes were not billed and moved on: the call was up and nobody was billed for it. OpenLeg now writes it twice more, 100 ms and 200 ms apart, and then keeps it, at most 1000 per process, for the leg sweep, which writes it with the join and leave its phone had meanwhile (as a leg written late already is) and bills it. A leg still kept when the sweep stops is logged at ERROR, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Buy asked the vendor and then inserted the number's row once: a failed insert left a number Stream paid for every month that no customer held. Release asked the vendor and then marked the row released once: a failed update left a number given back that kept being billed to the customer. Both now write a phone_number_orders row before the vendor is asked and delete it with the write that records the outcome. The phone sweeper settles orders older than 10 minutes by asking the vendor whether it holds the number (phone.NumberFinder, for Telnyx and Twilio): a number bought and held gets its row, as of the purchase, and its first month if the purchase did not bill it; a number given back and no longer held is released as of when it was. A vendor that cannot be asked leaves the order and an ERROR line for an operator. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A brand or campaign registration whose answer was lost (a timeout, a 5xx, or the row not written after it) left no id behind, so the next poll registered, and the vendor billed, a second one. Two routers polling at once could do the same. The router now records when it asked (business_profiles. brand_requested_at, dlc_use_cases.campaign_requested_at) with a conditional update before the vendor is asked, so only one caller asks. A 4xx from Telnyx (dlc.ErrVendorRefused) registered nothing and forgets the request; any other failure keeps it, and each poll then logs at ERROR for an operator instead of asking again. Telnyx takes no idempotency key on these calls, so there is no safe automatic retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A purchase or release whose vendor call timed out or answered a 5xx may have been carried out, so its order now stays for the sweep to settle by what the vendor holds; only a 4xx refusal forgets it at once. The sweep claims due orders with FOR UPDATE SKIP LOCKED and moves each one's next attempt an hour on, so one router asks about an order at a time and an order no vendor can settle no longer starves newer ones. A swept release only releases the row the order gave back (same vendor, bought before it), a Telnyx number found by the sweep records no other kind of vendor id, and a purchase whose order a sweep settled first says it was not recorded. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OpenLeg's retry and the leg sweep write a leg again after a write whose answer may have been lost. An inbound or placed leg has a key that makes that a no-op; a transfer leg had none, so a lost commit could leave a second ringing leg that a phone with an unknown number could be given, billing the transfer twice. call_legs_transfer_idx makes a tokenless leg unique by its call and the vendor's call id, so the insert's ON CONFLICT DO NOTHING writes nothing the second time. It is built concurrently after clearing the vendor id of older duplicates (only a test vendor's fixed id made them), and is rebuilt by usageIndexes if a build fails. The phone tests' stub vendor now gives each dial an id of its own, as vendors do. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The legs OpenLeg could not write were given up as soon as shutdown began, before the HTTP and session drains, and a leg kept after that was never written nor logged at ERROR. The router now calls StopLegSweep once the drains are over: it writes the kept legs a last time, and from then on a leg that cannot be written is logged at ERROR, not kept. A kept leg whose call ended (session_ended on this router) before the sweep wrote it is now ended at the call's end, rather than left open for MaxCallLength, counted against the organization's concurrent calls and then given away unbilled. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A request whose answer was lost blocked the app's 10DLC for good, even when the request never reached Telnyx, and an id the router held when a save failed was dropped unlogged. - A request never written whole (dial, DNS, TLS, context done first) is dlc.ErrNotCarriedOut, as a 4xx is, and its mark is cleared; only the mark of that request is cleared. - A request under 10 minutes old may still be running and is left alone, so it is no longer logged as lost. - A campaign is registered with the use case's id as its referenceId, which Telnyx keeps unique; an older request is settled by finding the campaign under its brand (CampaignFinder): found, it is recorded and billed under its own id; missing, it is asked for again. - Telnyx takes no reference on a brand, so an older brand request moves the use case to vendor_rejected with a note to contact support, which the app may edit or delete, and is not asked for again. - The save after a registration is tried 3 times on a context the caller cannot end; a last failure is logged at ERROR with the id. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A refresh whose 3 saves all failed dropped the renewed tokens, so a Postgres failure longer than ~300 ms cost the person a reconnect when the provider had rotated the refresh token. The resolver now holds such a renewal in memory, one per connection and at most 1000, when the last error is one a retry may fix. The next Resolve of that connection on the same router saves it, while the row is still as the checkpoint left it, writes the refresh's audit row, and resolves as usual. A reconnect or revocation that came first leaves it forgotten; a process that stops loses it, as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since #2254 a brand report refreshes only the use cases of the app that holds the brand, so a report naming no app's brand polls nothing. The 10DLC registration tests run a poll themselves instead. A poll refreshes every held use case in the shared test database, so the fake registry now answers and counts each app's registrations apart, telling apps by their profile's contact email. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#2279 (20270201000500) and #2276 (20270201000700) merge first, and goose refuses a migration older than the newest one applied, so this branch's migrations move above both: global 20270201001100 (phone_number_orders), global 20270201001110 (dlc registration requests) and shard 20270201001120 (call_legs_transfer_idx). Nothing else names the versions; the schema files are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A purchase or release refused before the vendor was asked (a vendor not implemented, one missing a setting, or an order it cannot take as asked) kept its order. No vendor can settle such an order, so the sweep logged it at ERROR every hour, and a customer could create one at will by buying from a declared vendor that is not implemented. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
eb86223 to
730f8c8
Compare
martinmitrevski
left a comment
There was a problem hiding this comment.
Re-reviewed at 730f8c8 (rebased on 2ea9511). The Should fix at service.go:617 is addressed, and I have no new findings.
- The three errors are raised only before any vendor request. In every vendor's buy and release path:
ErrNotImplementedcomes from the registry's stub for a declared vendor with no implementation.NotConfiguredis raised only by bandwidth's site-id check.Invalidis raised by vonage's country check and by the offer lookups that run before the order is sent (telnyxpriceOf, didwwofferFor,countryID,groupTypeID).- No vendor's
do()maps an HTTP answer to any of the three. markedhas noUnwrap, so none of them can hide aVendorErroreither.
- Both reasons for not taking my suggestions hold.
- bird, bandwidth and didww return a
VendorErrorcarrying the 2xx status when an answer cannot be read (e.g. birdcould not read the answer), so the inverted check would forget a real purchase. - bird's buy POST sends an
Idempotency-Key, which makes it replayable by Go's transport: the dial error of a retry can follow a first attempt that reached the server.
- bird, bandwidth and didww return a
- I was wrong about
sip_trunk: it is not declared inphone.yaml, soRegistry.Openrefuses it before an order is written.bicswas the case a customer could actually trigger, andTestAPurchaseFromAVendorNotImplementedLeavesNoOrdercovers it; on the previous head it fails with one order left. - The two Nits deferred to follow-ups are fine.
Ran in the review worktree: go build ./..., go vet ./... and go vet -tags integration ./... (clean), and go test ./internal/phone/... (pass). I did not run the integration tests.
Verdict: approve (posted as COMMENT, since this is my own PR).
## Why https://linear.app/stream/issue/AI-3517/leases-are-written-with-one-clock-and-judged-with-another A channel turn's lease and a queue claim's lease were written from the calling router's clock, then judged against another clock: Postgres's `now()` for a turn, or the next claiming router's clock for a queue. A router a few seconds behind could get a turn lease that had already expired, or have a queue row taken from it while its lease was still live. A claim cancelled while the router was stopping could also commit and lose its rows, which left them leased to nobody until the lease ran out. ## What changed - **`ChannelTurns.Take` (`channel_turn.go`)**: the caller now passes `ChannelTurn.Lease`, a duration, instead of `LeaseUntil`. The insert writes `lease_until = now() + make_interval(secs => lease)`, so the turn is written and judged on Postgres's clock. `takeTurn` no longer reads `time.Now()`. `Validate` requires `lease > 0` where it used to require `lease_until`. - **Queue claim clock (`queue.go` `claim`)**: a row is due at `next_attempt_at <= now()`, and the claim leases it until `now() + make_interval(secs => lease)`. `ChatInbounds`, `ChannelInbounds`, `ImageJobs` and `ConnectionEventSubscriptions` now take `Claim(ctx, limit, lease)`, the same shape `ScheduledTasks.Claim` already has. Their workers pass their lease instead of `now` and `now+lease`. `PhoneNumberOrders.Claim` came in from main with #2284 (AI-3514) and is converted the same way, as `Claim(ctx, lease, limit)`. Its metering tests now let orders settle on the database's clock as well as the suite's fake clock (`ordersSettle`). - **Claim on cancel (`queue.go`)**: - A caller whose context is already done claims nothing and returns the error before any SQL, so a stopping router does not spend an attempt of every due row. - Otherwise the claim runs on `context.WithoutCancel(ctx)`, so its rows always come back. - Its bound (`claimSettle`, 5 s) starts only when the caller's context ends, via `context.AfterFunc`, not when the claim starts. A bound from the start could land after the commit and lease rows to nobody in the same way. - If the caller stopped meanwhile, `unclaim` makes the rows due again, on a 5 s context of its own, guarded by the attempts value the claim wrote, and the claim returns the cancellation. The attempt the claim counted stays counted. `attempts` is the token `heldBy` fences writes with, so giving the number back would let the claim before it write the row again. - **Skipped: the `scheduled_task.go` clocks bullet.** That file is owned by #2229 (AI-3496, scheduled-task races) and #2177 (store review), which are both open and edit it. `ScheduledTasks.Claim` already leases from `databaseNow`. Overlap: #2230 edits `Prune` and #2244 edits `ConnectionEventSubscriptions.Insert` in some of the same files. Neither touches the `Claim` hunks. Still on the router's clock, and left as they are: - The due times that enqueue and `Retry` write (`NextAttemptAt: time.Now()`, backoffs). Clock skew there only moves when a row becomes due by a few seconds. It cannot hand a live lease to a second router. - The other leases are filed as [AI-3716](https://linear.app/stream/issue/AI-3716/more-leases-are-written-and-judged-on-the-routers-clock) rather than converted here: - `EventDeliveries.Claim` (`event_delivery.go`) - `ClaimSummaries` (`episode.go`) - the campaign contact leases (`campaign_contact.go`) - the campaign attempt leases (`campaign_attempt.go`) - `SimulationRuns.Renew` / `Abandon` (`simulation_run.go`) ## Tests - `TestAChannelTurnsLeaseLastsItsFullLengthOnTheDatabasesClock` reads `lease_until - now()` back from Postgres and checks it is the full minute. This test alone would also pass on the old code whenever host and Postgres agree. Skew is covered by construction instead: `Take` and `claim` no longer take a time at all. Their only inputs are a `time.Duration` (`ChannelTurn.Lease`, `lease`). The type system rules out a router time reaching either statement, so a golden check on the SQL is not needed. The repo's store tests also assert on results, not on SQL (`go-testing/store.md`). - `TestAClaimWhoseCallerHadStoppedTakesNothing`: a claim on an already-cancelled context returns `context.Canceled`, and the row's next claim counts attempt 1. - `TestTheHolderOfAChannelTurnExtendsItsLease` asserts the renewed lease the same way. - `TestAClaimCancelledAfterItWasSentLeavesNoRowLeased` uses a query hook to cancel the caller right after the claim's statement returns. The claim returns `context.Canceled`, and the row is claimable again at once. With the release disabled the test fails. It checks the contract; it does not reproduce the commit-then-read race on the wire. - The queue store tests used to pass a made-up `now`. They now move time forward with `timePasses(table, d)`, which shifts `next_attempt_at` back. "Not due yet" rows are due an hour after `time.Now()`. The two "another router finished it during my claim" tests now claim with a zero lease, so only the row's state keeps router A off it. - `TestEveryQueuesModelHasItsKeyAndAttempts` (unit) checks that each queue model exposes the key and `attempts` fields `unclaim` reads by reflection. - Rows the tests queue "now" (`queuedImageJob`, channelbridge's `queue`) are now due a little in the past. A claim judges them on Postgres's clock, and that clock ran a few ms behind this process's. It made two image job tests flaky locally. - `go test -tags integration ./internal/store` (whole `StoreSuite`), `./internal/channelbridge ./internal/chatinbound ./internal/imagejobs ./internal/mcpevents`, and `./internal/api -testify.m 'Turn|Thread|ChannelAnotherRouter|ChatChannel'`: all pass. `go vet ./...` and `gofmt` are clean. 🤖 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
Work the router does at a vendor was not always recorded here, so it went unbilled, was billed to the wrong side, or was paid for twice (https://linear.app/stream/issue/AI-3514). Each of the six items was checked against the code at ce41c39 before it was changed; one was already fixed on main, and is now closed further (held renewal, below). The self-review (#2284 (review)) is addressed in the five commits after
fix(dlc): ask the vendor once for a brand or campaign. The branch is rebased on main after #2254, whose brand report refreshes only its own app's use cases, so the 10DLC tests run a poll themselves, and the fake registry answers and counts each app's registrations apart, since a poll reaches every app's held use cases (test(dlc): …).How it works
Changes
legs.go)OpenLegwrites the row twice more, 100 ms then 200 ms apart, then keeps the leg forSweepLegs. At most 1000 per process.StopLegSweep, deferred incmd/routerafter the drains andsessions.Shutdown, writes the kept legs once more; a leg still or newly unwritable after it is logged at ERRORTestALegWhoseFirstWriteFailsIsBilled,TestALegThatCouldNotBeWrittenIsWrittenAndBilledByTheSweep,TestALegKeptWhenTheRouterStopsIsWrittenOnceMore,TestALegThatCannotBeWrittenAfterTheSweepStoppedIsLoggedEndLegstells the kept legs of the call when it ended; the sweep ends such a leg there once written (EndLegsagain)TestALegWrittenAfterItsCallEndedEndsWithTheCall20270201000320: uniquecall_legs_transfer_idxon (call type, call id, app, vendor call id) for tokenless legs, soOpen'sON CONFLICT DO NOTHINGwrites a retried transfer once. Built concurrently, after clearing the vendor id of older duplicates (only a test vendor's fixed id made them); listed inusageIndexesso a failed build is rebuilt. The phone tests' stub now gives each dial its own idTestATransferLegWrittenTwiceIsOneLegservice.go)phone_number_orderstable: an order row before the vendor is asked. A purchase deletes it in the transaction that writes the number's row; a release deletes it afterreleased_atis written. A vendor error forgets it when it is a 4xx*VendorError, or a refusal before the vendor was asked (ErrNotImplemented,ErrNotConfigured,ErrInvalid: a declared vendor not implemented, a missing setting such as Bandwidth's site id, an order it cannot take such as Vonage without a country); a timeout, a 5xx or any other error leaves it.SweepOrdersclaims due orders through the store'squeue(attempts,next_attempt_at,FOR UPDATE SKIP LOCKED) and settles them through the optionalphone.NumberFinder(Telnyx, Twilio)TestANumberBoughtWithoutItsRowIsRecordedByTheSweep,TestANumberGivenBackWithoutItsReleaseIsReleasedByTheSweep,TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber,TestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweep,TestANumberGivenBackWhoseAnswerWasAFailureIsReleasedByTheSweep,TestANumberTheVendorStillHoldsAfterAFailedReleaseStaysHeld,TestAnOrderAVendorCannotSettleIsKeptAndNotAskedAboutEverySweep,TestAClaimedOrderWaitsForItsLeaseBehindTheOrdersDueFirst,TestAPurchaseFromAVendorNotImplementedLeavesNoOrder,TestAPurchaseFromAVendorMissingASettingLeavesNoOrder,TestAPurchaseTheVendorCannotTakeAsAskedLeavesNoOrderresolver.go)Resolveon the same router, with its audit rowTestARefreshWhoseSavesAllFailedIsSavedOnTheNextUsedlc/service.go)brand_requested_atandcampaign_requested_atare set by a conditional update before the vendor is asked.dlc.ErrNotCarriedOut(a Telnyx 4xx, or a request never written whole, seen throughhttptrace) unsets it, only if it is still that request. A request under 10 min old is left alone. An older campaign request is settled bydlc.CampaignFinder: Telnyx lists the brand's campaigns and finds the one whosereferenceId(now the use case id, which Telnyx keeps unique) matches. An older brand request moves the use case tovendor_rejectedwith a note. Saves after a registration are tried 3 times; a last failure is logged at ERROR with the vendor's idTestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice,TestACampaignWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice,TestABrandWhoseAnswerWasLostIsLeftToSupportAndFreesTheUseCase,TestACampaignWhoseAnswerWasLostIsFoundAtTheVendor,TestACampaignTheVendorNeverRegisteredIsAskedForAgain,TestABrandRegisteredWhoseIdCouldNotBeSavedIsLoggedWithIt,TestACampaignRegisteredWhoseSaveFailedIsFoundAtTheVendorLater,TestOnlyARequestThatNeverReachedTelnyxIsNotCarriedOut,TestACampaignIsFoundByTheUseCaseItWasRegisteredFordlc/service.go)Createchecks the numbers first, thenUseCases.Insertwrites the use case and assigns its numbers in one transactionTestAUseCaseNamingANumberTheAppDoesNotHoldIsRefusedNamingIt,TestAUseCaseWhoseNumbersTheDatabaseFailsIsAnInternalError(new assertions: no use case left)store/use_case.go)ON CONFLICT (customer_id) WHERE is_default DO NOTHINGand tries once moreTestACreateRacingTheAppsFirstUseCaseIsItsSecondMigrations: global
20270201001100_phone_number_orders.sql(new table, with the queue'sattemptsandnext_attempt_at), global20270201001110_dlc_registration_requests.sql(two nullable columns), shard20270201001120_call_legs_transfer_idx.sql(no transaction: one update of duplicate rows, thenCREATE UNIQUE INDEX CONCURRENTLY). They were renumbered from…0300/…0310/…0320so they sit above #2279 (20270201000500) and #2276 (20270201000700), which merge first; goose refuses a migration older than the newest one applied.schema/global.sqlandschema/shard.sqlare regenerated. No HTTP operation changed, soopenapi.yamland the SDKs are untouched.Decisions to review
vendor_rejectedwith a note saying to contact support, so the app can edit or delete it, and one ERROR is logged. The brand is not asked for again until support recordsvendor_brand_idor clearsbrand_requested_at. A campaign takes areferenceIdthat Telnyx keeps unique, so it is now sent and the campaign is found by it.WroteRequesttrace never reported a complete write (dial, DNS or TLS failure, or a context done first) is treated like a 4xx. One that was written and then got no answer is kept as possibly registered.sip_trunkwrites no order: the registry does not declare it, soBuyrefuses it before the order, andReleaseskips the order for it. A dial or DNS failure is kept, not taken as proof: Go's transport retries a replayable request (Bird's POST carries anIdempotency-Key) on a new connection and returns that dial's error. AVendorErrorwith a 2xx status (an answer that could not be read) is kept too, since the vendor did the work.HoldsNumberyet. Their order is logged at ERROR and claimed again an hour later, behind newer orders. Telnyx numbers listed aspurchase-failed,port-failed,deletedorported-outcount as not held. A swept Telnyx number records novendor_id: its listing does not name the number order a purchase records.RecordedUsageshows the purchase did not bill it, with thenumber_rentalorigin.RequestBrand/RequestCampaignupdate lets only one router ask the vendor; the other finds the request and leaves it.session_endedthis router receives; one received by another router leaves it toMaxCallLength, as before. A held renewal is saved only by the router that holds it; a process that stops with one loses it, and its connection needs a reconnect, as before.Validation
All runs were local, on the branch rebased on main at
89e9e0c5c, against a test Postgres and Redis of this worktree's own, with-tags integration -p 1:Last round (orders no vendor was asked about), rebased on main at
2ea951108:go build ./...,go vet -tags integration ./...andgofmtclean;go test ./internal/phone/...pass;go test ./internal/api/ -run '^(TestPhoneSuite|TestCallStatusSuite|TestSIPTrunksSuite|TestBookingSuite|TestDLCBookingSuite|TestAdmissionSuite|TestShadowAdmissionSuite|TestDataMoveSuite|TestSuspensionSuite)$'pass;TestEveryTableWithAUserIDIsForgottenOrKeptForAReasonnow passes ([AI-3661] Drop calls from the tables kept on forget #2299 fixed it on main). The three new tests failed oneb862236b, and each fails again with its own clause removed.go test ./internal/phone/... ./internal/dlc/...: pass.internal/dlcis left out of CI (AI-2040), so it was run by hand.go test ./internal/store/: everything this branch touches passes,TestTheSchemaFilesAreCurrentand the migration tests included. The full run failsTestEveryTableWithAUserIDIsForgottenOrKeptForAReason, which main's ownIntegration (router)run at36e551845fails too (keptUserTablesnamescalls, which has nouser_id). An earlier full run also failed 10 price-change tests and 2 data-move campaign tests that compare Postgres'snow()with the Go clock; all passed when run alone.go test ./internal/api/ -run 'TestBookingSuite|TestDLCBookingSuite|TestDLCPollSuite|TestSuspensionSuite|TestPhoneSuite|TestCallStatusSuite|TestTelnyxSandboxSuite|TestAdmissionSuite|TestTelephonyBillingSuite|TestTelephonySandboxBillingSuite|TestDLCSuite|TestTelnyxChannelSuite': pass.go test ./internal/connectors/resolver/: pass.go test ./cmd/router/ -run 'TestRouterStartSuite/(TestAStartingRouterRetiresTheStatusURLs|TestAStartingRouterSweepsTheBridges|TestAStartingRouterEndsALegLeftRinging|TestAStartingRouterAsksTheVendorAfterItsCampaigns)': pass. The unit tests of the touched packages pass too.go build ./...,go vet -tags integration ./...(every package),go veton the touched packages,gofmt: clean.go run ./cmd/openapileavesopenapi.yamlunchanged.How each new test was shown to fail first: the fix it covers was undone in place (for example the order forgotten on every vendor error, the sweep releasing on every release order, a claim that leases nothing, the transfer index left out,
EndLegsnot telling the kept legs,StopLegSweeponly logging, the young-request check removed,FindCampaignskipped, the save-failure log removed) and the test run: each failed, and passed again with the fix.🤖 Generated with Claude Code