Skip to content

AI-3514: record vendor work whose outcome was lost - #2284

Merged
martinmitrevski merged 12 commits into
mainfrom
martinmitrevski/ai-3514-work-done-at-a-vendor-and-not
Nov 23, 2026
Merged

martinmitrevski merged 12 commits into
mainfrom
martinmitrevski/ai-3514-work-done-at-a-vendor-and-not

Conversation

@martinmitrevski

@martinmitrevski martinmitrevski commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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

call leg      OpenLeg ── write ─┬─ ok ─────────────────────> billed when it ends
                                └─ fails ─> 2 more tries ─┬─ ok
                                                          └─ kept (max 1000)
                         leg sweep (10 min) <─────────────────┘
                           writes it; it takes the join and leave its phone had
                           meanwhile, and ends at the call's end if session_ended
                           reached this router first; billed
                         router stop, after the HTTP and session drains:
                           one last write; what is left, and any leg kept
                           after it, is logged at ERROR
                         a transfer leg is unique by (call, vendor call id), so
                           a write tried again after a lost commit writes nothing

buy number    order row ─> vendor BuyNumber ─┬─ ok ──> row + delete order (one tx)
release       order row ─> vendor Release ───┤  ok ──> released_at, then delete order
                                             ├─ 4xx, or refused before the vendor
                                             │  was asked ─> order forgotten
                                             └─ timeout, 5xx, other ─> order kept
                  │
                  └─ order left behind ─> phone sweep claims it (FOR UPDATE SKIP
                     LOCKED) once 10 min old, asks the vendor HoldsNumber(e164)
                       ├─ buy, held       -> row as of the order, first month billed once
                       ├─ release, gone   -> that vendor's row, bought before the
                       │                     order, released as of the order
                       ├─ anything else   -> order forgotten
                       └─ vendor can't say -> ERROR, claimed again in 1 h,
                                              behind the orders due before then

10DLC         set *_requested_at (only if unset) ─> vendor ─┬─ ok ─> id saved (3 tries,
                                                            │       else ERROR naming the id)
                                                            ├─ 4xx, or never sent ─> unset
                                                            └─ else ─> kept
              a later poll, request under 10 min old ─> left alone (may still be running)
                            request older:
                              campaign ─> listed under its brand by referenceId (the use case id)
                                            ├─ found ─> recorded and billed under its own id
                                            └─ none  ─> unset, asked for again next poll
                              brand    ─> use case to vendor_rejected ("contact support"), one
                                          ERROR; not asked for again until support records the
                                          brand id or clears the request

connector     refresh saves fail 3 times ─> renewal held in the resolver (max 1000)
refresh       next Resolve of that connection on this router saves it, then resolves

use case      check numbers ─> one tx: insert (ON CONFLICT on the
create        default index, tried once more) + assign the numbers

Changes

Item Change Result Test (failed before the fix)
Leg insert (legs.go) OpenLeg writes the row twice more, 100 ms then 200 ms apart, then keeps the leg for SweepLegs. At most 1000 per process. StopLegSweep, deferred in cmd/router after the drains and sessions.Shutdown, writes the kept legs once more; a leg still or newly unwritable after it is logged at ERROR The call is billed TestALegWhoseFirstWriteFailsIsBilled, TestALegThatCouldNotBeWrittenIsWrittenAndBilledByTheSweep, TestALegKeptWhenTheRouterStopsIsWrittenOnceMore, TestALegThatCannotBeWrittenAfterTheSweepStoppedIsLogged
Kept leg after its call ended (review) EndLegs tells the kept legs of the call when it ended; the sweep ends such a leg there once written (EndLegs again) Billed to the call's end, not open 4 h against the organization's concurrent calls TestALegWrittenAfterItsCallEndedEndsWithTheCall
Transfer leg retried (review) Shard migration 20270201000320: unique call_legs_transfer_idx on (call type, call id, app, vendor call id) for tokenless legs, so Open's ON CONFLICT DO NOTHING writes a retried transfer once. Built concurrently, after clearing the vendor id of older duplicates (only a test vendor's fixed id made them); listed in usageIndexes so a failed build is rebuilt. The phone tests' stub now gives each dial its own id No second ringing leg for one transfer TestATransferLegWrittenTwiceIsOneLeg
Buy and release (service.go) New phone_number_orders table: 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 after released_at is 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. SweepOrders claims due orders through the store's queue (attempts, next_attempt_at, FOR UPDATE SKIP LOCKED) and settles them through the optional phone.NumberFinder (Telnyx, Twilio) A number bought or given back whose answer was lost is recorded; a number the vendor still holds stays held; one router asks about an order at a time, and an unsettleable order no longer starves newer ones; a purchase no vendor was asked about leaves no order for the sweep to log every hour TestANumberBoughtWithoutItsRowIsRecordedByTheSweep, TestANumberGivenBackWithoutItsReleaseIsReleasedByTheSweep, TestAnOrderTheVendorDoesNotHoldIsForgottenWithoutANumber, TestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweep, TestANumberGivenBackWhoseAnswerWasAFailureIsReleasedByTheSweep, TestANumberTheVendorStillHoldsAfterAFailedReleaseStaysHeld, TestAnOrderAVendorCannotSettleIsKeptAndNotAskedAboutEverySweep, TestAClaimedOrderWaitsForItsLeaseBehindTheOrdersDueFirst, TestAPurchaseFromAVendorNotImplementedLeavesNoOrder, TestAPurchaseFromAVendorMissingASettingLeavesNoOrder, TestAPurchaseTheVendorCannotTakeAsAskedLeavesNoOrder
Refresh save (resolver.go) #2192 (AI-3504) retries the save 3 times. Now a renewal whose saves all failed with a retryable error is held in the resolver (one per connection, at most 1000) and saved on that connection's next Resolve on the same router, with its audit row No reconnect after a Postgres failure longer than the retries, on the router that renewed TestARefreshWhoseSavesAllFailedIsSavedOnTheNextUse
10DLC brand / campaign (dlc/service.go) brand_requested_at and campaign_requested_at are set by a conditional update before the vendor is asked. dlc.ErrNotCarriedOut (a Telnyx 4xx, or a request never written whole, seen through httptrace) unsets it, only if it is still that request. A request under 10 min old is left alone. An older campaign request is settled by dlc.CampaignFinder: Telnyx lists the brand's campaigns and finds the one whose referenceId (now the use case id, which Telnyx keeps unique) matches. An older brand request moves the use case to vendor_rejected with a note. Saves after a registration are tried 3 times; a last failure is logged at ERROR with the vendor's id Nothing is registered twice; a lost campaign is recovered; a lost brand frees the app's use case and goes to support TestABrandWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice, TestACampaignWhoseRegistrationWasNotAnsweredIsNotRegisteredTwice, TestABrandWhoseAnswerWasLostIsLeftToSupportAndFreesTheUseCase, TestACampaignWhoseAnswerWasLostIsFoundAtTheVendor, TestACampaignTheVendorNeverRegisteredIsAskedForAgain, TestABrandRegisteredWhoseIdCouldNotBeSavedIsLoggedWithIt, TestACampaignRegisteredWhoseSaveFailedIsFoundAtTheVendorLater, TestOnlyARequestThatNeverReachedTelnyxIsNotCarriedOut, TestACampaignIsFoundByTheUseCaseItWasRegisteredFor
Use case create (dlc/service.go) Create checks the numbers first, then UseCases.Insert writes the use case and assigns its numbers in one transaction A refused or failed assignment leaves no use case TestAUseCaseNamingANumberTheAppDoesNotHoldIsRefusedNamingIt, TestAUseCaseWhoseNumbersTheDatabaseFailsIsAnInternalError (new assertions: no use case left)
First use case race (store/use_case.go) Insert uses ON CONFLICT (customer_id) WHERE is_default DO NOTHING and tries once more The second create is the app's second use case, not a 500 TestACreateRacingTheAppsFirstUseCaseIsItsSecond

Migrations: global 20270201001100_phone_number_orders.sql (new table, with the queue's attempts and next_attempt_at), global 20270201001110_dlc_registration_requests.sql (two nullable columns), shard 20270201001120_call_legs_transfer_idx.sql (no transaction: one update of duplicate rows, then CREATE UNIQUE INDEX CONCURRENTLY). They were renumbered from …0300/…0310/…0320 so they sit above #2279 (20270201000500) and #2276 (20270201000700), which merge first; goose refuses a migration older than the newest one applied. schema/global.sql and schema/shard.sql are regenerated. No HTTP operation changed, so openapi.yaml and the SDKs are untouched.

Decisions to review

  • A lost 10DLC brand goes to support; a lost campaign is found. Telnyx's create-brand body takes no caller reference and its brand list filters only by display name and the like, so a brand whose answer was lost cannot be found for sure, and asking again can register and bill a second one. After 10 minutes the use case moves to vendor_rejected with 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 records vendor_brand_id or clears brand_requested_at. A campaign takes a referenceId that Telnyx keeps unique, so it is now sent and the campaign is found by it.
  • What counts as never sent. A request whose WroteRequest trace 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.
  • Which orders are forgotten at once. A 4xx, and a refusal before the vendor was asked (not implemented, not configured, invalid): no vendor returns one of those after its buy or release call. sip_trunk writes no order: the registry does not declare it, so Buy refuses it before the order, and Release skips 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 an Idempotency-Key) on a new connection and returns that dial's error. A VendorError with a 2xx status (an answer that could not be read) is kept too, since the vendor did the work.
  • Orders at vendors other than Telnyx and Twilio cannot be settled automatically: those providers have no HoldsNumber yet. Their order is logged at ERROR and claimed again an hour later, behind newer orders. Telnyx numbers listed as purchase-failed, port-failed, deleted or ported-out count as not held. A swept Telnyx number records no vendor_id: its listing does not name the number order a purchase records.
  • A number the sweep records is priced from the order's quote, because the vendor's buy answer was lost. Its first month is billed only if RecordedUsage shows the purchase did not bill it, with the number_rental origin.
  • Two routers registering one use case (AI-3659, the follow-up AI-3499: poll every use case a vendor holds, not the first page #2254 names): the conditional RequestBrand / RequestCampaign update lets only one router ask the vendor; the other finds the request and leaves it.
  • Kept legs and held renewals live in memory. Postgres is what failed, so there is no durable store for them. A kept leg learns its call's end only from a session_ended this router receives; one received by another router leaves it to MaxCallLength, 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 ./... and gofmt clean; go test ./internal/phone/... pass; go test ./internal/api/ -run '^(TestPhoneSuite|TestCallStatusSuite|TestSIPTrunksSuite|TestBookingSuite|TestDLCBookingSuite|TestAdmissionSuite|TestShadowAdmissionSuite|TestDataMoveSuite|TestSuspensionSuite)$' pass; TestEveryTableWithAUserIDIsForgottenOrKeptForAReason now passes ([AI-3661] Drop calls from the tables kept on forget #2299 fixed it on main). The three new tests failed on eb862236b, and each fails again with its own clause removed.

  • go test ./internal/phone/... ./internal/dlc/...: pass. internal/dlc is left out of CI (AI-2040), so it was run by hand.

  • go test ./internal/store/: everything this branch touches passes, TestTheSchemaFilesAreCurrent and the migration tests included. The full run fails TestEveryTableWithAUserIDIsForgottenOrKeptForAReason, which main's own Integration (router) run at 36e551845 fails too (keptUserTables names calls, which has no user_id). An earlier full run also failed 10 price-change tests and 2 data-move campaign tests that compare Postgres's now() 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 vet on the touched packages, gofmt: clean. go run ./cmd/openapi leaves openapi.yaml unchanged.

  • 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, EndLegs not telling the kept legs, StopLegSweep only logging, the young-request check removed, FindCampaign skipped, the save-failure log removed) and the test run: each failed, and passed again with the fix.

🤖 Generated with Claude Code

@martinmitrevski martinmitrevski left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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) and 20270201000310 (two nullable ADD COLUMNs, no rewrite) set lock_timeout first. Both versions are above everything on origin/main (global and shard both end at 20270127000400). schema/global.sql matches 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 NOTHING plus one retry is correct under READ COMMITTED. TestACreateRacingTheAppsFirstUseCaseIsItsSecond waits on the real lock through pg_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 update WHERE 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/openapi leaves openapi.yaml unchanged.

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.

Comment thread acceleration/internal/phone/service.go Resolved
Comment thread acceleration/internal/phone/legs.go Resolved
Comment thread acceleration/internal/phone/legs.go Resolved
Comment thread acceleration/internal/phone/legs.go Resolved
Comment thread acceleration/internal/phone/service.go Resolved
Comment thread acceleration/internal/dlc/service.go Resolved
Comment thread acceleration/internal/dlc/service.go Resolved
Comment thread acceleration/internal/dlc/service.go Resolved
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3514-work-done-at-a-vendor-and-not branch from d08b995 to eb86223 Compare November 23, 2026 21:21
@github-actions github-actions Bot added the docs label Nov 23, 2026
@martinmitrevski

Copy link
Copy Markdown
Collaborator Author

On the two items in the review body:

Item 3 (refresh save). Fixed in 92adb54, not accepted as a bounded retry.

When saveAgain's last error is one a retry may fix, the renewal is now held in the resolver next to its cache. It keeps the checkpoint's state and the state to save, one per connection, at most 1000. The next Resolve of that connection on the same router sees needs_reauthorization and does three things in order:

  1. saves the held renewal, but only while the row is still as the checkpoint left it, so a reconnect or revocation that came first wins;
  2. writes the refresh's audit row;
  3. resolves as usual.

There is no goroutine and nothing to flush.

Residual risk: only the router that renewed holds the renewal. A Resolve on another router still gets ErrNotConnected until this one is used again. A process that stops, or more than 1000 held renewals at once, loses it, and that connection needs a reconnect, as before.

Test: TestARefreshWhoseSavesAllFailedIsSavedOnTheNextUse. It fails without the change.

Description nit. Corrected. The body now says a release deletes its order in a second statement, after released_at is written. The rest of the body is updated for the review, the rebase on #2254 and the migration renumber (20270201001100, 20270201001110, shard 20270201001120).

@martinmitrevski martinmitrevski left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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 by TestANumberBoughtWhoseAnswerWasLostIsRecordedByTheSweep and ...GivenBackWhoseAnswerWasAFailure....
  • Transfer leg: call_legs_transfer_idx makes the retry idempotent. The shard migration deletes no rows: it clears vendor_call_id on 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 only Placed, 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 built CONCURRENTLY, and ensureUsageIndexes rebuilds it if the build fails.
  • Shutdown, and a leg written after its call ended: fixed by StopLegSweep after the drains and unopened.end.
  • Sweep starvation: fixed by Claim with SKIP LOCKED and 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 its referenceId, 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.

Comment thread acceleration/internal/phone/service.go Resolved
Comment thread acceleration/internal/dlc/service.go Resolved
martinmitrevski and others added 12 commits November 23, 2026 22:41
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>
@martinmitrevski
martinmitrevski force-pushed the martinmitrevski/ai-3514-work-done-at-a-vendor-and-not branch from eb86223 to 730f8c8 Compare November 23, 2026 21:48

@martinmitrevski martinmitrevski left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:
    • ErrNotImplemented comes from the registry's stub for a declared vendor with no implementation.
    • NotConfigured is raised only by bandwidth's site-id check.
    • Invalid is raised by vonage's country check and by the offer lookups that run before the order is sent (telnyx priceOf, didww offerFor, countryID, groupTypeID).
    • No vendor's do() maps an HTTP answer to any of the three.
    • marked has no Unwrap, so none of them can hide a VendorError either.
  • Both reasons for not taking my suggestions hold.
    • bird, bandwidth and didww return a VendorError carrying the 2xx status when an answer cannot be read (e.g. bird could 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.
  • I was wrong about sip_trunk: it is not declared in phone.yaml, so Registry.Open refuses it before an order is written. bics was the case a customer could actually trigger, and TestAPurchaseFromAVendorNotImplementedLeavesNoOrder covers 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).

@martinmitrevski
martinmitrevski marked this pull request as ready for review November 23, 2026 21:54
@martinmitrevski
martinmitrevski merged commit 18962cc into main Nov 23, 2026
15 checks passed
@martinmitrevski
martinmitrevski deleted the martinmitrevski/ai-3514-work-done-at-a-vendor-and-not branch November 23, 2026 22:32
Loschcode added a commit that referenced this pull request Nov 24, 2026
## 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant