Repository navigation
[AI-3655] Keep scheduled-delivery timings per router in tests - #2293
Conversation
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>
kanat
left a comment
There was a problem hiding this comment.
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.gois 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 clocktime.Now.NewServeris the only non-test constructor. - An AST sweep of every test-file write to a package var under
acceleration/finds none left ininternal/api. The packages that still have such writes run not.Paralleltests. - No test was weakened and no timeout raised. The attempt assertions read what the worker was given, and
TestACallNobodyPicksUpIsNotAnsweredgained 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") |
There was a problem hiding this comment.
[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")There was a problem hiding this comment.
Fixed in 20d4aa3: TestAPeerIsGivenLongEnoughToRingAndHoldATasksCall now requires phoneWindow == 90s and callLimit == 10m each. With the two NewServer defaults swapped it fails (expected 1m30s, actual 10m0s).
There was a problem hiding this comment.
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.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
kanat
left a comment
There was a problem hiding this comment.
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:
TestAPeerIsGivenLongEnoughToRingAndHoldATasksCallfails (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 integrationon 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.
## 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>
## 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>
Why
TestTelnyxUnpaidSuitefailed now and then in CIintegration (api)on PRs that do not touch scheduled tasks (AI-3655):TestAThreadTaskWhoseMoneyCannotBeCheckedIsRetriedexpected 4 attempts and got 3 (scheduled_unpaid_test.go:170).TestAThreadTaskWhoseSessionEndsMidTurnSettlesexpected the rundeliveredand gotfailed(scheduled_unpaid_test.go:1133).Cause:
runSuiteruns every suite witht.Parallel()in one process (router_suite_test.go:152).ScheduledTasksSuiteandTelnyxUnpaidSuitesaved, 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.retryAtOnce: 2 waits, so the worker made 1+2 attemptslen(scheduling.DeliveryRetries)after the run settled. By then another suite had restored the default 3 waitsfailed, expecteddeliveredScheduledTasksSuite.TestAReplyNeverWrittenIsNoReplysets 1 sWhat 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 settlesfailedbefore the session ends.-racedoes not report this race. The suites share log and pool mutexes, and these give the race detector a happens-before edge (a-racerun 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.
scheduling.DeliveryRetriesScheduler.SetRetries, unexporteddeliveryRetriesscheduling.FinishRetries(new on main, same pattern)Scheduler.SetFinishRetries, unexportedfinishRetriesscheduledReplyWindowvarServer.replyWindow(the name stays as a const default)scheduledPhoneWindowvarServer.phoneWindowscheduledCallLimitvarServer.callLimitresumedAtvarServer.resumedAttime.NowscheduledPeerWindow()Server.scheduledPeerWindow()Tests:
retryAtOnce,retryLateandfinishAtOncesetRouterSuite.retriesorfinishRetries, and the workers the suites start (newScheduler) apply it. The window and clock overrides set the suite's owns.router, as tests already do forreplyPoll.Production does not change:
cmd/router/main.go:1677still callsscheduling.NewScheduler, which takes the same default waits, andNewServersets the same defaults (asserted inTestAPeerIsGivenLongEnoughToRingAndHoldATasksCall). No log line changes and no ClickHouse view is affected.Changes
internal/scheduling/scheduler.go:DeliveryRetriesandFinishRetriesbecome unexported, andSetRetriesandSetFinishRetriesare added besideSetActivity.internal/api: the four windows and the clock becomeServerfields, set inNewServer.len(s.retries).TestACallNobodyPicksUpIsNotAnswerednow 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
TestProbeOverrides, not committed): a parallel test saves, sets and restores the globals the wayScheduledTasksSuitedoes. Beside it,MidTurnSettlesfailed 3 of 3 runs withdelivery_failed/conversation is already open. The probe cannot build on head: the globals are gone.MidTurnSettlesalone on base: 10/10 pass, and 10/10 with-race -cpu 1. So it fails only beside another suite.TestTelnyxUnpaidSuite,TestScheduledTasksSuite,TestLinqChannelSuite,TestTelnyxChannelSuite,TestTelnyxSandboxSuite,TestWhatsAppChannelSuiteandinternal/scheduling(unit and integration) pass.NewServer, the peer window had its call limit dropped, andSetRetriesornewSchedulerwas made a no-op. Two survive: a no-opSetFinishRetriesand anewSchedulerthat ignoresfinishRetries.finishAtOnceonly 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.-count=50,-raceand-cpu 1over the suite (the done criteria of AI-3655).🤖 Generated with Claude Code