Skip to content

fix(store): bound every serving statement on the server, and a cached read's wait on Redis - #2230

Merged
thesyncim merged 1 commit into
mainfrom
fix/ai-3494-statement-time-limits
Nov 23, 2026
Merged

thesyncim merged 1 commit into
mainfrom
fix/ai-3494-statement-time-limits

Conversation

@thesyncim

@thesyncim thesyncim commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Problem
The serving pool (connect) set no server-side limit. pgdriver gives up on a read after 10 s and drops the socket, but Postgres ran the statement to its end and committed it, and a transaction kept its locks until the backend next touched the socket. cached read Redis on the caller's context with no limit of its own, so with Redis unreachable every cached read, API key lookups included, waited out the caller's whole deadline. Users.record had the same wait.

Fix

  • The limits are set on the serving pool only (connect); the migration pool fix(store): make the migrations after the baseline safe on a live database #2208 added keeps none.
  • Every serving connection runs with statement_timeout 8 s (below the driver's 10 s), lock_timeout 3 s, idle_in_transaction_session_timeout 30 s and timezone UTC (sessionDefaults). A parameter the DSN sets itself wins. Days and hours are cut in UTC whatever the database's own zone is.
  • Work that legitimately takes longer raises the limits for its own transaction only (boundTransaction, set_config(..., true)):
    • ExportCustomer, every transaction it opens, global and shard: an hour, the export deadline the API gives one (exportWait);
    • LimitGrantUses.Reconcile: its lock held idle for 5 min while the shards are read;
    • StreamTrunks.InGroup: idle for 1 min across a Stream call (its client allows 30 s), and another router's wait on the group's lock ends at the statement limit rather than at 3 s.
  • Single statements that a backlog could push past the limit, and that would then roll back every time, now go in batches of 5000 rows: the activity and digest prunes, ChannelInbounds.Prune, ChatInbounds.Prune, ImageJobs.Prune, PruneDataChanges (lowest numbers first, so pruned_through holds) and Requests.RenameUser, whose rewrite of the recorded changes of the requests runs with each batch. Buckets.Rollup runs a bucket at a time. A SET LOCAL would not help these: the driver still gives up at 10 s. VendorCostGaps sets its own limit already.
  • Each Redis command of a cached read waits 250 ms (cacheWait) for its answer, through a hook on the store's shared Redis client. The hook bounds the commands sent on a cached read's context and every command sent with no deadline: rueidisaside's own (its client marker, the release of a load's lock) and any other send of the store's with no deadline. A command on a context with a deadline of its own keeps it: forget and each of its retries wait up to forgetWait (2 s), so a deletion Redis answers late still tells every replica. Then the row is read from Postgres. The load runs on the caller's context with no such bound, and so does rueidisaside's wait for a load another caller on the router is running, so the readers of a cold key share one load and a read after a write and its forget loads the new row. Users.record gives its Redis read and write the same 250 ms. A lower ConnWriteTimeout was not used: it would end every slow command on every connection of the client, whatever its context, and a hang would still cost more than 250 ms.
  • Behaviour that changes: a statement that took 8 to 10 s fails; a lock wait fails at 3 s rather than 10 s, except a wait on a trunk group or on a number's row (SetAgent, ClearAgent, Attach, Release, which a group holds across its Stream calls), which the 8 s statement limit ends; StartDataCapture waits at most 7 s, so it still answers ErrWritesOpen; a transaction idle for 30 s is ended; a rename or prune cut short leaves the batches already done, and the next run finishes it. A command on the shared Redis client sent with no deadline fails after 250 ms without an answer; the call-state writers (turns, events) set deadlines of their own, so they keep them. Each new connection costs four SET round trips, and a write to a number three more statements.
  • Not done: SetConnMaxIdleTime (5 min) is already on main, and a retry of a read on a connection error would wrap every read path.
  • Textual conflicts with fix(store): write a cached row in a detached transaction and forget what it returned #2209 in store.go and redis.go.

Tests
Each fails under the mutant of its rule; the first group also fails on main's code.

  • TestAStatementPastTheLimitIsEndedOnTheServer: pg_sleep(20) fails in about 8 s with 57014 and nothing is left running in pg_stat_activity.
  • TestAWaitOnAnotherSessionsLockIsEnded, TestAServingConnectionBoundsAnIdleTransaction, TestDaysAreCutInUTCWhateverTheDatabaseSays: a lock wait ends at 3 s, the idle limit is set, a day bucket is UTC under a UTC+14 database.
  • TestAConfigIsReadFromPostgresWhileRedisCannotBeReached: with Redis's port closed, AgentConfigs.Get answers from Postgres in under a second.
  • TestAReaderWhileRedisHangsAnswersFromPostgresWithinTheWait: with Redis hung, a cold read answers in under 400 ms.
  • TestReadersWaitingOnALoadWhoseWriteBackHangsAnswerWithinTheWait: four readers of a key whose write-back hangs all answer in under 2 s, not the 12 s the client takes to give up.
  • TestAFreshRoutersFirstReadAnswersWithinTheWaitWhenRedisHangsAfterAMiss: on a new client, Redis hangs right after the first miss, before rueidisaside sets its marker, and the read still answers in under 400 ms rather than 12 s.
  • TestAUserIsWrittenDownWhileRedisHangs: a sighting is written in under a second with Redis hung.
  • TestAWriteToANumberATrunkGroupHoldsWaitsForTheGroup, TestATrunkGroupRunsWithTheGroupsLimits: a write to a number a group holds for 4 s waits and succeeds, and the group runs with its own lock and idle limits.
  • TestACaptureStartGivenLongerThanTheStatementLimitGivesUpAsWritesOpen, TestAForgetWaitsOnARedisSlowerThanACachedReadWould, TestADSNsParameterWinsWhateverTheCaseItIsWrittenIn: a capture start answers ErrWritesOpen, a deletion Redis answers in 500 ms is told, and a DSN's TimeZone wins however it is spelt.
  • TestAReadAfterAWriteAndItsForgetGetsTheNewRow: a read that starts after a write's forget, while an older load is still running, answers the new row, and the old one is not cached.
  • TestReadersOfAColdRowShareOneReadOfPostgres: eight readers of a cold key with a 600 ms load cost one load.
  • TestAnotherRoutersTrunkGroupWaitsForTheOneHoldingIt: a second router joins a group held for 4 s.
  • TestALimitTheDSNSetsIsKeptOverTheDefault: a DSN's own limit wins, and the pool hands out no connection the server ended.
  • TestATrunkGroupLeavesItsConnectionWithTheServingLimits: on a one-connection pool, the limits are back to 8 s, 3 s and 30 s after a trunk group.
  • TestAnExportOutlastsTheIdleLimitOfAServingTransaction, TestAnExportStatementOutlastsTheServingStatementLimit, TestAReconcileKeepsItsLockWhileItWaitsOnAShard, TestATrunkGroupOutlastsTheIdleLimitOfAServingTransaction: each exempted piece of work runs past a limit that ends an ordinary transaction (shortened through the DSN).
  • TestABacklogOf…IsPrunedWhole (activity, written messages, chat messages, image jobs, changes) and TestRenamingAUserWithMoreRequestsThanOneStatementTakesRenamesThemAll: a backlog of more than one batch is deleted or renamed whole, a batch per statement, and the same user id under another app is left alone. TestAPruneCutShortAfterOneBatchHasDroppedTheLowestChangeAndSaidSo: a prune stopped after one batch dropped the lowest change and set pruned_through to it. TestRenamingAUserToTheirOwnIdRewritesNothing: a rename to the same id ends. TestBucketQueryBudgets: a three-bucket window is three pairs of statements.
  • TestARowSlowerToLoadThanRedisIsWaitedOnIsStillCached, TestARowLoadedAsRedisGoesIsTheAnswer: a slow load is answered and cached, and a row loaded as Redis goes is the answer without a second read.
  • TestEveryHotTableIsReadByIndex seeds through a DSN that lifts the statement limit and the read timeout for its 100,000-row inserts, and the 99,999-contact seed of the campaign cap test lifts the statement limit in its transaction. TestEveryHotTableIsReadByIndex/Requests.RenameUser now renames to another id, so the batched statement is explained. On Postgres 16 it reads requests_customer_spend_idx, as CountByUser does there; CI's Postgres 19 is what checks requests_customer_started_idx.

Part of AI-3494

@github-actions github-actions Bot added the docs label Nov 23, 2026
@thesyncim
thesyncim force-pushed the fix/ai-3494-statement-time-limits branch 3 times, most recently from 36be9be to 6592d62 Compare November 23, 2026 18:09
@thesyncim
thesyncim marked this pull request as ready for review November 23, 2026 18:09
@thesyncim
thesyncim requested a review from kanat November 23, 2026 18:10
@thesyncim
thesyncim force-pushed the fix/ai-3494-statement-time-limits branch from 6592d62 to 1a2fcf8 Compare November 23, 2026 18:36
@thesyncim
thesyncim force-pushed the fix/ai-3494-statement-time-limits branch from 1a2fcf8 to c8d58ff Compare November 23, 2026 19:11
@thesyncim thesyncim added the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
Loschcode added a commit that referenced this pull request Nov 23, 2026
## Why


https://linear.app/stream/issue/AI-3509/statistic-windows-drop-their-first-bucket-and-days-follow-the

Tag and turn statistics compared bucket start times with the window's
ends. A window from 10:30 to 12:30 dropped the 10:00 bucket and returned
the 12:00 bucket whole. Every `date_trunc` also ran without a zone, so a
day was the database session's day. That is right only while the
session's zone is UTC.

## What changed

- **Whole buckets**:
- `TagBuckets.Select` (rollup tables) filters with `wholeBuckets`, which
the rollups already use, and returns every bucket the window touches.
- `TurnBuckets.Select` filters its hourly rows with
`wholeBuckets(Hourly, ...)` at either granularity. A daily turn read is
the hours the window touches, grouped by UTC day. That matches how the
request and spend statistics keep their window, and the API's "from
inclusive, to exclusive". A daily window starting at midday does not
count that day's morning.
- **Fixed-length buckets in `wholeBuckets`**: its upper bound used to
add `interval '1 day'`. That is a calendar day in the session's zone, an
hour short or long across a DST change (in Denver, the day ending
2026-03-09 00:00Z ended at 03-08 23:00Z). It now adds `'24 hours'` or
`'1 hour'`.
- **UTC days, in SQL**: every `date_trunc` in `internal/store` now
passes `'UTC'` as its third argument. The places are:
  - `wholeBuckets`, both bounds
  - the provider and tag rollups
  - `Buckets.Select`
  - `Requests.Spend`
  - `TurnBuckets.Select`
  - every bucket in `CustomerActivity`

  `grep "date_trunc(" internal/store/*.go` finds none without a zone.
- **UTC on the connection (skipped here)**: setting `timezone = UTC` in
`connect` belongs to AI-3494 / #2230, which changes the same line. With
this PR's fixed-length intervals and named zones, the statistics no
longer depend on the session's zone, even before #2230 lands.
- **Bound on the turn statistics range (skipped: does not reproduce)**:
the ticket says to bound it "as the other statistics are". On `main`,
and at `ed5c656b9`, no statistics endpoint bounds its range. `getStats`,
`getTagStats`, `getSpend`, `getTagKeys`, `getActivity` and
`getAgentStats` all check only `to > from`. The only limit in
`internal/api` is the organization activity's 90 days. Turn statistics
are unpaginated and load every hourly bin in range, so a multi-year
hourly read is unbounded. That is filed as
[AI-3645](https://linear.app/stream/issue/AI-3645/turn-statistics-accept-any-date-range-and-load-every-hourly-bin-in-it).

## Overlap

- **#2258 (AI-3498)** rewrites `TagBuckets.Select` to read the raw
`requests` rows with an exact `[from, to)` window, as `Buckets.Select`
does. #2258 merges first, and this PR is then rebased onto it:
- `TagBuckets.Select` keeps #2258's exact raw-row window, not
`wholeBuckets`. Only its `date_trunc` gains `'UTC'`.
- `TestATagWindowInsideItsHoursReturnsEveryHourItTouches` is rewritten
for that window. It will neither call `Rollup` nor expect the 12:45 row.
- **#2230 (AI-3494)** owns `connect`. This PR does not touch it. The
time zone test sets its zone as a startup parameter of its own DSNs
(`?timezone=America/Denver`, which pgdriver passes on). #2230's session
defaults let a DSN parameter win, so the test keeps working once #2230
lands.

## Tests

`go test -tags integration -p 1 ./internal/store/` (StoreSuite and
ShardedStoreSuite):

- **`TestATurnWindowInsideItsHoursReturnsEveryHourItTouches` and
`TestATagWindowInsideItsHoursReturnsEveryHourItTouches`**: a window from
10:30 to 12:30 with rows at 10:45 and 12:45.
- **`TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt`.**
- **`TestADayIsAUTCDayWhateverTheDatabasesTimeZone`**: a router whose
connections are in `America/Denver`, with rows at 03:00 UTC (the evening
before, in Denver) and 10:00 UTC. Each of these gives one bucket at
00:00 UTC:
  - `Buckets.Select`
  - `Requests.Spend`
  - `TurnBuckets.Select`
  - `CustomerActivity` (sessions, messages, calls, people)
  - a daily `Rollup`
  - a `stats_tags_daily` read
- **`TestADailyRollupOnTheDayTheClocksChangeKeepsTheWholeUTCDay`**:
Denver, 2026-03-08, with a row at 23:30Z that is kept and a row the
midday before that is not touched.

I checked the tests by mutation. Taking `'UTC'` out of any one site, or
putting back `+ interval '1 day'` or the per-granularity turn filter,
fails at least one of these tests. That covers all 14 mutations.

Locally, against Postgres 16 (`va-test-pg`, postgres:16-alpine) and a
Redis of its own:

- The new tests fail on `main` and pass here. The exception is
`TestADailyTurnWindowStartingMidDayCountsOnlyTheHoursInIt`, which pins
behaviour `main` already has and which this PR's first commit had
broken.
- The whole `./internal/store` package passes in CI's `integration
(store)` job. On the local Postgres 16, five plan assertions in
`TestEveryHotTableIsReadByIndex` that this PR does not touch fail the
same way on an untouched `main` checkout.
- `go vet` and `gofmt` are clean.
- CI's `integration (api)` fails in `TestChannelsSuite` the same way on
`main` (ce41c39).

🤖 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>

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed c8d58ff85 merged onto main 3ec8be2ef (the merge is clean). CI on the head is all green. On the merged tree, the 64 new and changed tests pass, and the full store package fails only the known TestEveryHotTableIsReadByIndex subtests on PG16. Mutations: 38 checked, 7 survived (R1.2).

Findings with no line in the diff:

[Nit] R1.3 datamove.go:283: StartDataCapture sets lock_timeout to within (30 s), but the serving statement limit now ends that wait at 8 s with 57014. The export then answers 503 "changes cannot be recorded" instead of errWritesOpen. On main, the driver's 10 s cut it short too. Either map 57014 there to ErrWritesOpen, or bound the wait below the statement limit. Ticket.

[Nit] R1.5 PR body: "a call's turns and events included ... fail after 250 ms" is not right. Their writers set deadlines of their own (agent/turns.go:822, agent/decisions.go:202), and the hook leaves those alone. Turns and events always use the shared client (turn.go:102), not only when the shard has no Redis of its own.

[Question] R1.7 I could not check the time zone of the staging or production databases. If either is not UTC, day and hour cuts (rollups, CustomerActivity) move at deploy, and rows cut before the deploy stay in the old zone. SHOW timezone on each settles it before merge.

Checked and sound:

  • boundTransaction uses set_config(..., true) inside real transactions.
  • DSN parameters win (maps.Copy order, mutant killed).
  • The migration pool has its own connector without the limits.
  • cached and Users.record fall back to Postgres on a Redis error, as their mutants show.
  • I swept the lock and long-statement paths for exports, imports, data moves, prunes, campaigns, image jobs, rollups, the grant reconcile and #2229's scheduled tasks. Apart from the trunk group's row locks (R1.1), their lock holders are short DB-only transactions or try-locks.

Verdict: request changes, for R1.1: an API write to a number is now refused after 3 s while a trunk group holds the number, where main let it finish.

Comment thread acceleration/internal/store/request.go Resolved
Comment thread acceleration/internal/store/store.go Resolved
Comment thread acceleration/internal/store/redis.go Resolved

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Round 2, delta review of d5e5b17 (round 1 was c8d58ff). Verdict: GO. I built and tested the head merged onto current main.

Prior findings

  • R1.1 fixed. Store.writeNumbers (phone_number.go) gives the six number writers the trunk group waiter's lock limit. I re-ran my round-1 probe: a group holds the number for 4 s, ClearAgent waits 4 s and succeeds (round 1: 55P03 at 3 s). The new TestAWriteToANumberATrunkGroupHoldsWaitsForTheGroup passes in both store suites. I broke writeNumbers 9 ways and each fails the test: lock limit back to 3 s, the bound removed, statement limit 2 s, and each of the six call sites back to a plain transaction. None survives.
  • R1.2 to R1.8 are untouched by this commit and keep their round-1 status. R1.2 stays a follow-up that does not block.

Your questions

  • Writers left at 3 s: BackfillStreamPins is a CLI batch (runBackfillPins) the API never calls. The data move apply is served by the admin API, but it writes into a deployment that does not yet serve the customer. Neither contends with a trunk group in practice, so leaving them is right.
  • Budget rise (1 to 2+2, and 2+2 to 3+2): the extra statement is the set_config of boundTransaction, plus BEGIN/COMMIT for single-statement writes. A SET LOCAL needs a transaction, so I found no cheaper way short of a longer lock limit for every write. The cost is justified.
  • The merge of main (406fbe4) has no conflicts, and the PR's own lines are unchanged: the diff against its old head differs only in index lines and hunk offsets.

New finding (unchanged code, does not block)

  • [Nit] R2.1 acceleration/internal/store/sip_trunk.go:140, SIPTrunks.Delete. A trunk group holds its number rows FOR UPDATE across Stream calls. The foreign-key check on deleting a SIP trunk takes FOR KEY SHARE on that trunk's numbers, so it waits on the group too. With a group holding a number on the trunk for 4 s: on this head the delete fails after 3 s with 55P03 (a 500). On main it waits and answers ErrSIPTrunkInUse. The delete is refused either way, so only the answer changes, in a narrow race. Fix: run it under the same lock limit as writeNumbers, in this PR or a ticket.

Checks: go vet -tags integration ./... and gofmt clean. Store phone, use case, trunk and number tests (both suites), dlc, phone and the api phone, use case, DLC and campaign suites pass. CI on d5e5b17: all green except integration (store), which fails only TestEveryTableWithAUserIDIsForgottenOrKeptForAReason, which is tracked on main separately (it passed on my run merged onto current main).

@kanat kanat left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approving on the reviewer's GO in delta round 2. R1.1 is fixed: number-row writes wait under the trunk group's lock limit, and 9 mutants were killed. R1.2 and R2.1 (the SIPTrunks.Delete race answering 500 instead of in-use) are follow-ups. Before merge: R1.7 (is the database time zone UTC?), and a merge of main, which brings in #2299 and turns integration (store) green.

@thesyncim thesyncim removed the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
@thesyncim
thesyncim force-pushed the fix/ai-3494-statement-time-limits branch from d5e5b17 to c98118d Compare November 23, 2026 22:33
@thesyncim
thesyncim force-pushed the fix/ai-3494-statement-time-limits branch from c98118d to 783874c Compare November 23, 2026 22:34
@thesyncim

Copy link
Copy Markdown
Member Author

R1.3 is fixed here, since it is one line: StartDataCapture keeps its lock wait a second under the statement limit (captureLockWait, 7 s), so a capture start given 30 s gives up as ErrWritesOpen rather than a statement timeout. TestACaptureStartGivenLongerThanTheStatementLimitGivesUpAsWritesOpen fails without it. R1.5: the body no longer says turns and events fail after 250 ms; their writers set deadlines of their own, and the hook bounds only what has none (forget no longer among them). R1.7: agreed, this needs SHOW timezone on each hosted database before merge; if either is not UTC, the rollups and day cuts move at deploy. I am getting it checked and will confirm here before this merges.

@thesyncim
thesyncim requested a review from kanat November 23, 2026 23:24
@thesyncim thesyncim added the data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review label Nov 23, 2026
@thesyncim
thesyncim merged commit f8f1de8 into main Nov 23, 2026
13 checks passed
@thesyncim
thesyncim deleted the fix/ai-3494-statement-time-limits branch November 23, 2026 23:25
@thesyncim

Copy link
Copy Markdown
Member Author

This merged before the R1.7 check I said I would confirm here. The check is still owed before the next deploy: SHOW timezone on each hosted database. If either is not UTC, the rollups and day cuts move when this ships.

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

data-layer-review: ready Data layer review fix: passed automated review, merges cleanly, ready for a human review docs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants