Skip to content

AI-3508: campaign dialer stops ringing again on an unread outcome, and caps delay_minutes - #2263

Merged
Loschcode merged 10 commits into
mainfrom
laurentschaffner/ai-3508-campaign-dialer-rings-again-when-it
Nov 24, 2026
Merged

Loschcode merged 10 commits into
mainfrom
laurentschaffner/ai-3508-campaign-dialer-rings-again-when-it

Conversation

@Loschcode

@Loschcode Loschcode commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Why

https://linear.app/stream/issue/AI-3508/campaign-dialer-rings-again-when-it-cannot-read-how-a-call-ended-and

The campaign dialer had four problems. It rang a person a second time when it could not read how their call ended. It used up attempts on dials that never rang. It let delay_minutes overflow. And a router that finished late could undo the work of the router that took its contact over.

What changed

  • A failed outcome read no longer rings again (bullet 1, fixed).
    • Before: phoneDialer.Dial read the outcome itself. On a failed read it answered unknown, and a double dial takes unknown as "dial again at once".
    • Now: Dial leaves the outcome empty and Runner.ring reads it.
    • A failed read is retried twice, after 200 ms and 1 s. If all three reads fail, ring returns before End: the dial stays unended and the contact stays leased. The router that takes it over reads the outcome again in recover and never dials.
    • A take-over tick stops at the first outcome it cannot read, so a shard that does not answer cannot hold up claiming. The other contacts taken over in that tick keep the lease taken there.
  • A dial that failed before anything rang keeps its attempt, up to a cap (bullet 2, fixed).
    • phone.Call marks a failure from before the vendor was asked with phone.ErrNotDialed, unless a second try would hit it again. Such failures are not marked and use the attempt as before:
      • ErrInvalid, store.ErrNoNumber, store.ErrNoSIPTrunk
      • ErrNoStream, ErrNoSealerToCall, ErrNotConfigured, ErrSIPTrunksDisabled
      • the streamapp.Settled set
      • a vendor that cannot be built, and a password the router cannot open or seal
    • A marked failure, or a config read that failed, ends as a new result, dial_failed, and is retried 5 minutes later without using the attempt.
    • No list can be complete, so the 12th dial_failed of one attempt (about an hour) uses the attempt anyway. The count reads existing campaign_attempts rows, so no migration is needed.
    • A disconnected or moved Stream app pauses the campaign (stream_app_disconnected / stream_app_moved).
  • delay_minutes is capped at 30 days (bullet 3, fixed).
    • Step.validate refuses a delay over 43,200 minutes, so the API answers 400. The field's doc now says so; I regenerated openapi.yaml and the Python and JS clients.
    • Delays already stored keep their length at run time and are clamped only where a Duration would overflow (about 292 years). A stored delay of 31 days or more is not shortened.
  • Late end and settle (bullet 4, fixed).
    • CampaignAttempts.End only ends a dial whose ended_at IS NULL, so the first writer wins.
    • Settle carries LeaseUntil, the value the claim or take-over returned, and settles only under that same lease. Every runner path sets it. A nil value keeps the owner-only check, which leaves the direct store test calls and AI-3393: auto-enroll campaigns, edit one contact #2127 untouched.

Overlap: #2177 and #2127 edit nearby store files, but not settleContact, End or the dialer.

Follow-ups

  • AI-3665: a double dial can outlast the 20-minute lease, and a take-over loses the voicemail result and vendor call id.

Tests

  • delay_minutes and stored delays:
    • TestCampaignsSuite/TestADelayOverThirtyDaysIsRefused: delay_minutes: 200000000 gets a 400.
    • TestSequenceSuite/TestADelayIsAtMostThirtyDays: 43,200 is accepted and 43,201 refused.
    • TestTransitionSuite/TestAStoredDelayPastTheCapIsKeptAndOnePastADurationDoesNotWrap: a stored 31-day delay keeps its length, and 200,000,000 minutes lands about 292 years ahead.
  • Outcome reads (runner):
    • TestADialWhoseOutcomeCannotBeReadIsNotDialedAgainUntilItIsRead: all three reads fail. One dial, the contact still leased, the dial unended. After the take-over: settled from busy, still one dial.
    • TestAnOutcomeReadThatFailsOnceIsReadAgainAtOnce: the contact settles in the same tick. With no retries it fails.
  • Pre-dial failures:
    • Runner: TestADialThatKeepsFailingBeforeItRingsUsesTheAttemptInTheEnd. Eleven failures keep the attempt, and the twelfth uses it, with one dial per tick. With the cap disabled it fails.
    • Transition: TestADialThatFailedBeforeAnythingRangIsTriedAgainWithoutUsingTheAttempt, TestARefusalBeforeAnythingRangIsStillARefusal and TestADisconnectedOrMovedStreamAppPausesTheCampaign.
    • Phone: TestService/TestOnlyAFailureThatMayPassIsMarkedNeverDialed, plus TestOutcomeSuite/TestACallThatFailedBeforeItWasSentWasNeverDialed, TestACallFromANumberNotHeldIsNotMarkedNeverDialed and TestACallTheVendorFailedMayHaveRung.
  • Store: TestADialEndsOnce and TestASettleUnderALeaseTakenOverSinceSettlesNothing both fail with the store change reverted.
  • Passing locally:
    • go test -race -tags integration ./internal/campaign/
    • go test -tags integration ./internal/phone/
    • the campaign subset of TestStoreSuite
    • TestCampaignsSuite
    • go vet ./... and gofmt
  • Not tested: the take-over tick stopping at an unreadable outcome has no test of its own.

🤖 Generated with Claude Code

Laurent Schaffner and others added 4 commits November 23, 2026 19:27
A delay in minutes is made a time.Duration, which overflows above about 153
million minutes: the next attempt landed decades in the past and the rest
rang back to back. Step validation now refuses a delay over 43,200 minutes,
so the API answers 400.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Ending a dial checked nothing, so a router whose call outlived its lease
wrote over what the router that took the contact over had read. A dial now
ends once. Settling checked only the owner's name, which is one process: a
contact taken over, settled and claimed again by that same process took the
first claim's settle. A settle now names the lease its claim returned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The phone dialer read how a call ended and answered unknown when the read
failed, which a double dial takes as "dial again at once": the person who
just hung up was rung a second time because of a database blip. The runner
now reads the outcome itself after the dial, and a failed read leaves the
dial unended and the contact leased. The router that takes it over reads the
outcome again and settles from it without dialing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A config read that failed, or a phone.Call that failed before the vendor was
asked to dial, was taken as a call that may have rung: it used one of the
contact's attempts, and a double dial rang again at once. phone.Call now
marks a failure from before the vendor was asked with ErrNotDialed, keeping
its text and kind, and the campaign defers such a dial five minutes without
using the attempt.

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

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

Thanks for asking Jeffery for review. I'll stay on this PR until I can approve it.

How it works

  • Findings come as inline comments, each starting with [Must Fix], [Should Fix], nit: or consider:.
  • Push fixes whenever you're ready. Once the branch has been quiet for 10 minutes I review the new head and resolve the threads it fixes. To skip the wait, comment /jeffery review.
  • If you disagree or have a question, reply in the thread. I'll answer there, and resolve it if you're right.
  • I approve once every must-fix and should-fix is closed and nobody has requested changes. CI isn't part of that; branch protection still holds the merge until it's green. From round 3 on, open should-fix findings stop blocking.
  • I don't approve release/* branches or changes to protected paths, and I'll say so when that applies.
  • If a must-fix is still open after round 8, I stop and hand the PR to a human. Draft PRs wait until they're marked ready.

Commands (each as a whole comment)

Command What it does
/jeffery review Review the current head now
/jeffery rereview Start over at round 1 on the current head and withdraw my approval. This redoes the whole review and costs as much as the first one, so use it only when you don't trust the earlier rounds. If nothing changed since my last round I say so instead; add force to redo it anyway
/jeffery pause / /jeffery resume Stop or restart automatic reviews on this PR
/jeffery status What I last reviewed, and why I have or haven't approved
/jeffery help This list

/review-agent or a mention of me works in place of /jeffery.

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Round 1 on 403c688400a5 · 🆕 1 new
Still open: 1 should-fix. Full list on the checks tab.

A failure placing the call again would meet again - an invalid request, a
number the app does not hold, missing Stream credentials or sealing key -
was deferred every five minutes for ever. It is no longer marked
ErrNotDialed, so a campaign uses the attempt on it as before.

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

Copy link
Copy Markdown
Contributor Author

Round 1, addressed in e375fc4:

  • Permanent pre-dial failures retry every 5 minutes forever (fixed). phone.Call no longer marks failures that a second try would hit again: ErrInvalid (which includes errCustomKept), store.ErrNoNumber (the from-number was released), ErrNoStream and ErrNoSealerToCall. Those use the attempt as before. Only the remaining failures are deferred, such as a DB or Stream API blip. New test: TestACallFromANumberNotHeldIsNotMarkedNeverDialed. The not-dialed test now fails a phone_numbers read instead of using a number the app does not hold.
  • I did not add a per-contact cap on a transient failure that keeps happening. That would need a counter stored on the contact, and a busy-line deferral already retries with no cap.

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Round 2 on e375fc4f5593 · 🆕 1 new
Still open: 2 should-fix. Full list on the checks tab.

Comment thread acceleration/internal/phone/service.go Resolved
… failures

ErrNotConfigured and ErrSIPTrunksDisabled come from the deployment's setup,
so a second try meets them again; marked not dialed, a campaign deferred
every contact every five minutes for ever.

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

Copy link
Copy Markdown
Contributor Author

Round 2, addressed in 5d6b30f:

  • Deployment-permanent pre-dial errors still retry forever (fixed). ErrNotConfigured and ErrSIPTrunksDisabled are now treated as lasting, so they use the attempt instead of being deferred. Covered by a new unit test, TestService/TestOnlyAFailureThatMayPassIsMarkedNeverDialed.
  • Round 1's finding. The original 'every pre-send error deferred' finding is fixed by lasting, together with this addition.

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved 5d6b30f7460f after 3 rounds · 2 fixed

Laurent Schaffner and others added 2 commits November 23, 2026 22:04
…e again at once

A pre-dial failure that never passes retried every five minutes for ever,
and a list of lasting failures cannot be complete. Such a dial now ends as
dial_failed, and the twelfth of one attempt uses the attempt. The lasting
list also takes the Stream app's settled errors, a missing SIP trunk, a
password the router cannot open or seal, and a vendor that cannot be built;
a disconnected or moved Stream app pauses the campaign.

An outcome read is tried again twice before the contact is left leased, and
a take-over tick stops at the first outcome it cannot read, so a shard that
does not answer does not hold up claiming. A stored delay past what a
Duration holds is clamped there, so one stored before the cap does not wrap
into the past, and one of 31 days and up keeps its length.

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

Regenerated openapi.yaml and the Python and JavaScript clients from the
doc strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@getstream-metis
getstream-metis Bot dismissed their stale review November 23, 2026 21:05

Withdrawing approval until d306281 is reviewed.

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Round 4 on d306281be66f · 🆕 1 new

// app, or the deployment's own setup (credentials, keys, a public URL, SIP trunks). Such a
// failure is not marked ErrNotDialed, so a campaign does not try it for ever.
func lasting(err error) bool {
return errors.Is(err, ErrInvalid) || errors.Is(err, store.ErrNoNumber) || errors.Is(err, store.ErrNoSIPTrunk) ||

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

consider: Lasting failures still double-dial and count as placed
A failure in lasting (now including ErrNoSIPTrunk, ErrNoIdentity, ErrReadOnly, ErrDeploymentAppMismatch and vendor-build errors) falls through resultOf to an empty Result, so a double-dial campaign dials a second time and placedDial counts the row as a placed call. Giving these a non-placed Result, such as Refused with a code, would skip the doomed second dial and keep the analytics honest.

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 23, 2026

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved d306281be66f after 4 rounds · 2 fixed

Left open, your call:

…508-campaign-dialer-rings-again-when-it

# Conflicts:
#	acceleration/internal/store/campaign_contact_test.go
@getstream-metis
getstream-metis Bot dismissed their stale review November 24, 2026 05:19

Withdrawing approval until 0ea2b9b is reviewed.

getstream-metis[bot]
getstream-metis Bot previously approved these changes Nov 24, 2026

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved 0ea2b9b8e3ad after 5 rounds · 2 fixed

Left open, your call:

The Go client is regenerated with go generate. The .NET, PHP and Rust
generators are not installed here, so their three changed doc strings were
written as each generator writes them; CI's --check verifies them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@getstream-metis
getstream-metis Bot dismissed their stale review November 24, 2026 08:43

Withdrawing approval until 3fac504 is reviewed.

@getstream-metis getstream-metis Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

✅ Approved 3fac5045cb68 after 6 rounds · 2 fixed

Left open, your call:

@Loschcode

Copy link
Copy Markdown
Contributor Author

/jeffery review

@getstream-metis

Copy link
Copy Markdown

/jeffery review

Nothing changed since round 6 on 3fac5045cb68; comment /jeffery rereview force to redo the full review anyway.

@Loschcode

Copy link
Copy Markdown
Contributor Author

Round 6 consider, left as is: Lasting failures still double-dial and count as placed. This is how those failures behaved before this PR: they use the attempt, and a double dial dials a second time. Mapping them to Refused would also fail the contact for good, not just use one attempt, so I've left that to Laurent rather than change it here. Noted in the report.

@Loschcode
Loschcode merged commit e1cb5e4 into main Nov 24, 2026
15 of 20 checks passed
@Loschcode
Loschcode deleted the laurentschaffner/ai-3508-campaign-dialer-rings-again-when-it branch November 24, 2026 09:11
Loschcode added a commit that referenced this pull request Nov 27, 2026
## Why


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

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

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

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

## What changed

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

## Tests

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

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

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

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

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

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

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant