Skip to content

[AI-3655] Keep scheduled-delivery timings per router in tests - #2293

Merged
kanat merged 5 commits into
mainfrom
kanat/ai-3655-unpaid-suite-flake
Nov 24, 2026
Merged

kanat merged 5 commits into
mainfrom
kanat/ai-3655-unpaid-suite-flake

Conversation

@kanat

@kanat kanat commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Why

TestTelnyxUnpaidSuite failed now and then in CI integration (api) on PRs that do not touch scheduled tasks (AI-3655):

Cause: runSuite runs every suite with t.Parallel() in one process (router_suite_test.go:152). ScheduledTasksSuite and TelnyxUnpaidSuite saved, set and restored package vars that every router and every worker read. When the save and restore of two suites interleave, one suite's worker or router runs on the other suite's value.

Failure Value the test set Value the code read Evidence
3 attempts, expected 4 retryAtOnce: 2 waits, so the worker made 1+2 attempts the assertion read len(scheduling.DeliveryRetries) after the run settled. By then another suite had restored the default 3 waits CI job log of #2229
run failed, expected delivered default 3 min reply window ScheduledTasksSuite.TestAReplyNeverWrittenIsNoReply sets 1 s CI log: attempt 1's held turn is cancelled after 5 s, and attempt 2 runs no turn. Local base probe: 3 of 3 runs fail

What happens on the second failure with a 1 s window: attempt 1 stops reading the reply after 1 s, while the kept session is still closing (its turn gets a 5 s grace). The two 1 ms retries then fail with conversation is already open, and the run settles failed before the session ends.

TelnyxUnpaidSuite            process-wide var          ScheduledTasksSuite
  kept = 3 min ------------> scheduledReplyWindow <---- kept = 3 min, set 1 s
  ...                                          (1 s) <- restored later
  MidTurnSettles reads 1 s
  -> attempt 1 gives up at 1 s, retries hit "conversation is already open"

-race does not report this race. The suites share log and pool mutexes, and these give the race detector a happens-before edge (a -race run of both suites on base was clean).

#2229 does not touch any of these vars, and its own CI run failed on this flake, so it does not fix it.

How it works

Each value now belongs to one worker or one router. A test sets the value on its own worker or router, so no other suite sees the change.

Before (process-wide) After (per instance) Default
scheduling.DeliveryRetries Scheduler.SetRetries, unexported deliveryRetries 30 s, 2 min, 10 min
scheduling.FinishRetries (new on main, same pattern) Scheduler.SetFinishRetries, unexported finishRetries 1 s, 2 s, 4 s
scheduledReplyWindow var Server.replyWindow (the name stays as a const default) 3 min
scheduledPhoneWindow var Server.phoneWindow 90 s
scheduledCallLimit var Server.callLimit 10 min
resumedAt var Server.resumedAt time.Now
scheduledPeerWindow() Server.scheduledPeerWindow() 21 min 30 s

Tests: retryAtOnce, retryLate and finishAtOnce set RouterSuite.retries or finishRetries, and the workers the suites start (newScheduler) apply it. The window and clock overrides set the suite's own s.router, as tests already do for replyPoll.

Production does not change: cmd/router/main.go:1677 still calls scheduling.NewScheduler, which takes the same default waits, and NewServer sets the same defaults (asserted in TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall). No log line changes and no ClickHouse view is affected.

Changes

  • internal/scheduling/scheduler.go: DeliveryRetries and FinishRetries become unexported, and SetRetries and SetFinishRetries are added beside SetActivity.
  • internal/api: the four windows and the clock become Server fields, set in NewServer.
  • Tests: every override goes to the suite's own router or worker. The 4 attempt assertions read len(s.retries). TestACallNobodyPicksUpIsNotAnswered now also checks that the ring ended well before the default 90 s. Before, a ring on the default window still passed, only 90 s later.

Validation

  • Base probe (TestProbeOverrides, not committed): a parallel test saves, sets and restores the globals the way ScheduledTasksSuite does. Beside it, MidTurnSettles failed 3 of 3 runs with delivery_failed / conversation is already open. The probe cannot build on head: the globals are gone.
  • MidTurnSettles alone on base: 10/10 pass, and 10/10 with -race -cpu 1. So it fails only beside another suite.
  • Head: TestTelnyxUnpaidSuite, TestScheduledTasksSuite, TestLinqChannelSuite, TestTelnyxChannelSuite, TestTelnyxSandboxSuite, TestWhatsAppChannelSuite and internal/scheduling (unit and integration) pass.
  • Mutations: 12 of 14 are killed. Each changed read was moved back to the default const, each default dropped from NewServer, the peer window had its call limit dropped, and SetRetries or newScheduler was made a no-op. Two survive: a no-op SetFinishRetries and a newScheduler that ignores finishRetries. finishAtOnce only shortens the 1-4 s finish waits, and its two tests pass at the defaults too, only slower. I added no timing bound for them: a bound that tight would flake on a loaded runner.
  • Not yet run: -count=50, -race and -cpu 1 over the suite (the done criteria of AI-3655).

🤖 Generated with Claude Code

kanat and others added 3 commits November 23, 2026 21:45
Suites run in parallel in one process (runSuite), and ScheduledTasksSuite
and TelnyxUnpaidSuite saved, set and restored package vars every router
and worker reads: scheduling.DeliveryRetries, scheduledReplyWindow,
scheduledPhoneWindow, scheduledCallLimit and resumedAt. Their restores
interleaved, so one suite's worker or router ran on the other's values:
an unpaid thread task counted 3 attempts against a default of 4, and a
thread task whose session ends mid-turn gave up at another suite's 1 s
reply window while the session was still closing.

Each now belongs to one Scheduler (SetRetries) or one Server (replyWindow,
phoneWindow, callLimit, resumedAt), defaulting to the same values, and a
test sets its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
FinishRetries, new on main, is the same process-wide value a suite set
and restored while other suites' workers read it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the docs label Nov 23, 2026

@kanat kanat 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.

Round-1 review at 829b630 (on main 9effc9b). CI: draft, so go and integration are skipped; CI runs at gh pr ready.

Checked and sound:

  • Production wiring is unchanged. cmd/router/main.go is not in the diff. The defaults are the base values: retries 30 s, 2 min and 10 min; finish retries 1 s, 2 s and 4 s; reply window 3 min, ring 90 s, call limit 10 min; resume clock time.Now. NewServer is the only non-test constructor.
  • An AST sweep of every test-file write to a package var under acceleration/ finds none left in internal/api. The packages that still have such writes run no t.Parallel tests.
  • No test was weakened and no timeout raised. The attempt assertions read what the worker was given, and TestACallNobodyPicksUpIsNotAnswered gained a bound.
  • The author's probe fails on base 2 of 2 times. Head passes the touched suites, and the two suites side by side passed 2 of 2 times.

R1.2 Nit (ticket): SetFinishRetries and the finishRetries path in newScheduler are not covered by any test (M13, M14). I rule this acceptable here: the setter only makes the tests faster, and every outcome is the same at the default waits. A deterministic test for it: give finishAtOnce 1 wait and use failFinishes(2). The run then stays running, while with the default 3 waits it settles.

Verdict: request changes, for R1.1.

require.Equal(t, 21*time.Minute+30*time.Second, server.scheduledPeerWindow())
require.Greater(t, server.scheduledPeerWindow(), server.phoneWindow+server.callLimit+time.Minute,
"a call answered at the last ring and held to its limit is not cut by the asker")
require.Equal(t, 3*time.Minute, server.replyWindow, "a router reads a channel's answer for 3 min")

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.

[Should fix] R1.1 The control test checks replyWindow and the sum phoneWindow + scheduledWindow + callLimit, but not the ring and the call limit on their own. A mutant of NewServer that swaps them (phoneWindow: scheduledCallLimit, callLimit: scheduledPhoneWindow) keeps the sum at 21 min 30 s and passes this test. In production, that mutant rings for 10 min and hangs up after 90 s. No integration test covers the two defaults either, because every phone test shortens both.

Fix: add these two lines here (I checked them in a scratch copy: they pass on head and fail under the mutant with expected: 1m30s, actual: 10m0s).

require.Equal(t, 90*time.Second, server.phoneWindow, "a router waits out a ring for 90 s")
require.Equal(t, 10*time.Minute, server.callLimit, "a call a task placed lasts 10 min at most")

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.

Fixed in 20d4aa3: TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall now requires phoneWindow == 90s and callLimit == 10m each. With the two NewServer defaults swapped it fails (expected 1m30s, actual 10m0s).

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.

R1.2 (no thread of its own) fixed in 0ea3798: TestScheduledTasksSuite/TestAFinishIsNotWrittenAgainPastTheWaitsItIsGiven (1 wait, 2 refusals leaves the run running) and TestAFinishIsWrittenAgainOncePerWaitItIsGiven (3 waits settle it). SetFinishRetries as a no-op and newScheduler dropping the finishRetries branch both fail the first.

kanat and others added 2 commits November 23, 2026 23:01
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@kanat
kanat marked this pull request as ready for review November 23, 2026 22:14
@kanat
kanat marked this pull request as draft November 23, 2026 23:28

@kanat kanat 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.

Delta review, round 2 — GO (head 0ea3798, previous reviewed 829b630; test files only)

Prior findings

  • R1.1 (Should fix), control pins phoneWindow and callLimit each: fixed. Mutation RM1 (NewServer swaps phoneWindow and callLimit, server.go:618-619) on the merged tree: TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall fails (expected 1m30s, actual 10m0s). Unmutated: passes.
  • R1.2 (Nit), SetFinishRetries and the newScheduler finishRetries branch untested: fixed on evidence. The two new TestAFinish* tests read correctly against scheduler.go:638. M13 and M14 failed on the fixer's head run. I could not re-run them: Docker is down on this machine, so the shared test Postgres is unreachable.

New findings

  • None.

Checks

  • Merged onto origin/main f8f1de8 (clean auto-merge; aborted, nothing committed).
  • gofmt clean; go vet -tags integration on internal/api and internal/scheduling passes.
  • CI on 0ea3798: go, integration (api), (router), (store), (rest), (routers), (agent) all pass.

Unverified

  • M13 and M14 re-run here, and -count=10 -cpu 1 / -race runs of the new tests. Pending Docker; the merged tree was not run against a database by this round.

@kanat
kanat marked this pull request as ready for review November 23, 2026 23:51
@kanat
kanat merged commit 6892e8b into main Nov 24, 2026
27 of 28 checks passed
@kanat
kanat deleted the kanat/ai-3655-unpaid-suite-flake branch November 24, 2026 00:29
thesyncim pushed a commit that referenced this pull request Nov 24, 2026
## Why

The `api` group of Integration (router) does not compile on main since
dc88f2f ([run
45350145644](https://github.com/GetStream/Agents/actions/runs/45350145644)):

```
internal/api/scheduled_unpaid_test.go:1200:2: cannot assign to scheduledPhoneWindow (neither addressable nor a map index expression)
```

[#2277](#2277) set the
package-level `scheduledPhoneWindow` and `scheduledCallLimit` in
`TelnyxUnpaidSuite.callOn`.
[#2293](#2293), merged before
it, made them constants and moved the values a test changes onto the
router. Each passed CI on its own. Until this lands, every PR whose CI
runs the `api` group fails.

## Changes

- `callOn` sets `s.router.phoneWindow` and `s.router.callLimit` and
restores them in its cleanup, as `scheduled_phone_test.go:136-138` does.
Test-only.

## Validation

- `go vet -tags integration ./internal/api`: compiles.
- `go test -tags integration ./internal/api -run TestTelnyxUnpaidSuite
-count=1`: ok (99.7 s), including the three tests that go through
`callOn`.

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
kanat added a commit that referenced this pull request Nov 25, 2026
## Why

A Slack app configuration token rotates: `Server.configToken` calls
`Rotate`, and Slack then treats the refresh token it just got as spent.
The new pair was saved with one `Upsert`. When that one save failed (a
dropped connection, a short database outage), the new pair was gone and
the stored one was dead, so the customer had to send a new
`config_refresh_token`. Same pattern as the credential refresh fixed in
#2192, found in its sibling sweep (AI-3504).

## How it works

```
configToken
├─ Rotate (Slack spends the old refresh token)
└─ saveConfigToken
   ├─ Upsert           ok -> done
   ├─ failed, store.Unwritable? -> stop (a retry fails the same way)
   ├─ wait 100 ms, Upsert again
   ├─ wait 200 ms, Upsert again
   └─ still failing -> one error log (customer, connector, attempts; no token), error returned as before
```

- Bound: 3 saves, 300 ms of pauses, each save at most the store's 2 s
(`credentialDetachedTimeout`), so under 6.3 s, inside the provider app
lock the caller already holds.
- The save is an upsert, so one whose answer was lost and landed is safe
to repeat.
- Reused: `store.Unwritable` (the rule behind the resolver's
`retryable`). Not reused: the resolver's `saveAttempts`, `saveAgain` and
`wait` are unexported and tied to its credential store, and the 10DLC
service repeats the same numbers; a shared helper would need a package
of its own, so the three constants stay local with the reason in the
comment.
- API answers are unchanged: a failed save is the same 500 as before.

## Changes

- `connector_provider_apps.go`: `saveConfigToken` with its two
constants; `configToken` logs the last failure.
- Tests: `RouterSuite.failFirstQueries` (fail only the first n queries
that name a value, on the suite's existing query-hook seam); four tests
in `ConnectorProviderAppsSuite`:
`TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation`,
`TestARotatedConfigTokenWhoseEverySaveFailsIsLoggedOnceWithoutItsWordsAndAnsweredAsAnyFailure`,
`TestARotatedConfigTokenThatPostgresRefusesIsNotSavedAgain`,
`TestARotatedConfigTokenWhoseSaveLosesItsConnectionIsSavedByTheNextAndUsedWithoutAnotherRotation`.
- Second commit, unrelated to AI-3550: `TelnyxUnpaidSuite.callOn`
assigned the package-level `scheduledPhoneWindow` and
`scheduledCallLimit`, which #2293 made constants, so the api package's
integration tests did not compile on `main` (`go vet -tags integration
./internal/api` at dc88f2f). It sets them on the router as the other
scheduled tests do. The same change is #2341 (AI-3712); whichever merges
first, the other's copy merges clean.

## Validation

| Defect | Test | Mutant that fails it |
|---|---|---|
| One failed save loses the pair |
`TestARotatedConfigTokenWhoseFirstSaveFailsIsSavedByTheNextAndUsedWithoutAnotherRotation`:
the next call uses the stored pair, no second rotation | no retry;
`seam-always-fails` |
| Retries without end, or without waiting |
`...WhoseEverySaveFailsIsLoggedOnce...`: 3 attempts, at least 300 ms,
500 | unbounded; 2 attempts; no pause; constant pause |
| A row Postgres refuses is saved again |
`...ThatPostgresRefusesIsNotSavedAgain` (customer id past the index
limit, SQLSTATE 54000): `attempts=1` | retry on `Unwritable` |
| A token or its words in the log, no customer or connector in it | the
all-fail test reads the one error line | token, refresh token, stored
refresh in the line; no customer; no connector; warn level; no log |
| The failure swallowed | all-fail test: status 500 | return nil |
| A dropped connection (SQLSTATE 57P01) is not retried |
`...WhoseSaveLosesItsConnectionIsSavedByTheNext...`: the next call uses
the stored pair | retry only on context deadline; never retry a
Postgres-reported error |
| A refused row's log names the sent token |
`...ThatPostgresRefusesIsNotSavedAgain`: the log line holds no sent
token | log `sent` |
| The every-save-fails log line has extra or missing fields |
`...WhoseEverySaveFailsIsLoggedOnce...`: the line has exactly time,
level, msg, customer, connector, attempts, error | sealed pair as an
extra field |
| The first-save test passes without a failed save |
`...WhoseFirstSaveFailsIs...`: the seam fails exactly one save (two
saves ran) | seam off by one |
| The all-fail call waits on every save |
`...WhoseEverySaveFailsIsLogged...`: the call ends under 2 s | 1 s sleep
after every save |

- Tests run against real Postgres and the suite's fake Slack; the
failing save is the suite's per-suite query hook, no DDL and no store
mock.
- Run: `go test -tags integration ./internal/api -run
TestConnectorProviderAppsSuite` passes, and the suites that use
`failQueries` (authorizations, agent teams, channels, data move,
knowledge urls, 10DLC, guests) pass on the tests that call it. The full
integration run is CI's.
- `go vet -tags integration ./internal/api`, `gofmt -l`, `go build
./...` are clean.
- Not checked: Slack's real behavior on a spent refresh token (the fake
takes the strict reading, as its comment says); whether
`credentialDetachedTimeout` is the real worst case on a stalled network.
The 3 x 100/200 ms bound is a choice, not measured, as in the resolver.

## Review rounds

Round 1: main review NO-GO (no test of a dropped connection; two time
and count gaps), security review GO with one log-field test gap. Round
2: all fixed in tests only; delta review GO, 24 mutants, none survived.
Round 3: one comment word.

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

---------

Co-authored-by: Claude Sonnet 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