From 783874c9ace57c552d9b06bf35d5651eda3f3d22 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Mon, 23 Nov 2026 22:31:04 +0000 Subject: [PATCH] fix(store): bound every serving statement on the server, and a cached read's wait on Redis --- .claude/skills/go/store.md | 12 + acceleration/internal/store/activity.go | 5 +- acceleration/internal/store/activity_test.go | 20 + acceleration/internal/store/bucket.go | 36 +- acceleration/internal/store/bucket_test.go | 5 + acceleration/internal/store/budget_test.go | 34 ++ acceleration/internal/store/campaign_test.go | 4 + .../internal/store/channel_inbound.go | 9 +- .../internal/store/channel_inbound_test.go | 7 + acceleration/internal/store/chat_inbound.go | 9 +- .../internal/store/chat_inbound_test.go | 7 + acceleration/internal/store/datamove.go | 50 ++- acceleration/internal/store/datamove_test.go | 103 ++++++ acceleration/internal/store/image_job.go | 10 +- acceleration/internal/store/image_job_test.go | 7 + .../internal/store/limit_grant_use.go | 8 + .../internal/store/limit_grant_use_test.go | 35 +- acceleration/internal/store/phone_number.go | 99 +++-- .../internal/store/phone_number_test.go | 10 +- acceleration/internal/store/redis.go | 96 ++++- acceleration/internal/store/redis_test.go | 341 ++++++++++++++++++ acceleration/internal/store/request.go | 38 +- acceleration/internal/store/request_test.go | 46 +++ acceleration/internal/store/store.go | 64 +++- .../internal/store/store_explain_test.go | 13 +- acceleration/internal/store/store_test.go | 125 +++++++ .../internal/store/store_unit_test.go | 14 + acceleration/internal/store/stream_trunk.go | 11 + .../internal/store/stream_trunk_test.go | 97 ++++- acceleration/internal/store/user.go | 11 +- 30 files changed, 1220 insertions(+), 106 deletions(-) diff --git a/.claude/skills/go/store.md b/.claude/skills/go/store.md index 0e4baf1d7d..4c45c13ccb 100644 --- a/.claude/skills/go/store.md +++ b/.claude/skills/go/store.md @@ -70,6 +70,11 @@ A state change that is more than a column write gets a domain verb on the same r It takes the store's `rueidis.Client`. - Any method touching more than one key sends one round trip: `DoMulti`, a `MULTI`, or a Lua script. A loop issuing one command per item is a bug. +- Each Redis command of a cached read (`cachedFor`) waits `cacheWait` (250ms) for its answer, + and so does any command on the shared client sent with no deadline, rueidisaside's own + among them (`cacheReadBound`); then the row is read + from Postgres. A Redis that is down slows a request and does not stop it. The load itself + runs on the caller's context, and the readers of a cold key on one router share it. - Every key has a TTL or a named owner that deletes it. Name keys `:{}:...` so a customer's keys share a cluster slot when a script needs several. - Rate limiters, admission counters and pub/sub stay in their own packages (`policy`, @@ -93,6 +98,13 @@ A state change that is more than a column write gets a domain verb on the same r `nextDue` says when to look again, and every write after the claim goes through `heldBy`, so a claim whose lease ran out cannot overwrite the next one. `image_jobs.go` is the example. Do not write the claim by hand. +- Every serving connection runs with `statement_timeout` 8s, `lock_timeout` 3s, + `idle_in_transaction_session_timeout` 30s and `timezone` UTC (`sessionDefaults` in + `store.go`); a parameter the DSN names wins. Work that legitimately takes longer raises the + limits for its own transaction with `boundTransaction` (the export, the grant reconcile, + a trunk group), or a `SET LOCAL` of its own (`VendorCostGaps`). A prune or rename over + many rows goes `writeBatch` rows per statement (`deleteInBatches`), and a rollup a bucket at + a time: the driver gives up after 10 s, so no statement may outgrow that. ## Naming diff --git a/acceleration/internal/store/activity.go b/acceleration/internal/store/activity.go index 79f864ab99..ec8a8688e0 100644 --- a/acceleration/internal/store/activity.go +++ b/acceleration/internal/store/activity.go @@ -475,10 +475,9 @@ func (r *Activities) Prune(ctx context.Context, now time.Time) (int, error) { // day, and returns how many it deleted. func pruneDays(ctx context.Context, db bun.IDB, table string, now time.Time) (int, error) { before := now.UTC().AddDate(0, 0, -ActivityKeepDays).Format(time.DateOnly) - result, err := db.NewDelete().TableExpr(table).Where("day < ?::date", before).Exec(ctx) + deleted, err := deleteInBatches(ctx, db, table, "day < ?::date", before) if err != nil { - return 0, stack.Wrap(fmt.Errorf("store: prune %s: %w", table, err)) + return int(deleted), stack.Wrap(fmt.Errorf("store: prune %s: %w", table, err)) } - deleted, _ := result.RowsAffected() return int(deleted), nil } diff --git a/acceleration/internal/store/activity_test.go b/acceleration/internal/store/activity_test.go index bb5ae10d5f..e45c4e672c 100644 --- a/acceleration/internal/store/activity_test.go +++ b/acceleration/internal/store/activity_test.go @@ -499,3 +499,23 @@ func (s *ShardedStoreSuite) TestSessionsAreReadFromEveryShard() { s.Equal("there-new", latest[0].ID) s.Equal("here-new", latest[1].ID) } + +func (s *StoreSuite) TestABacklogOfActivityDaysPastTheirKeepIsPrunedWhole() { + s.inSmallBatches() + now := s.base + var deltas []ActivityDelta + for days := range 3 { + deltas = append(deltas, s.day("acme", "agent_setup", AuditSourceCLI, now.AddDate(0, 0, -ActivityKeepDays-1-days), 1, 0)) + } + deltas = append(deltas, s.day("acme", "agent_setup", AuditSourceCLI, now, 1, 0)) + s.Require().NoError(s.store.Activities.Add(s.ctx, deltas)) + + var pruned int + var err error + deletes := s.statementsLike("DELETE FROM customer_activity", func() { pruned, err = s.store.Activities.Prune(s.ctx, now) }) + + s.Require().NoError(err) + s.Equal(3, pruned) + s.Equal(1, s.activityRows("acme"), "today's row is kept") + s.Equal(4, deletes, "a row per statement, then the one that finds none") +} diff --git a/acceleration/internal/store/bucket.go b/acceleration/internal/store/bucket.go index 243ae0aec2..1c9c7ac3e0 100644 --- a/acceleration/internal/store/bucket.go +++ b/acceleration/internal/store/bucket.go @@ -65,6 +65,15 @@ func (g Granularity) truncateUnit() string { return "hour" } +// next is the start of the bucket after the one at holds, in UTC as the rollups cut them. +func (g Granularity) next(at time.Time) time.Time { + if g == Daily { + year, month, day := at.UTC().Date() + return time.Date(year, month, day+1, 0, 0, 0, 0, time.UTC) + } + return at.UTC().Truncate(time.Hour).Add(time.Hour) +} + // Valid reports whether the granularity is one this store knows. func (g Granularity) Valid() bool { return g == Hourly || g == Daily @@ -99,15 +108,26 @@ func (r *Buckets) Rollup(ctx context.Context, granularity Granularity, from, to return 0, stack.Wrap(fmt.Errorf("store: rollup window must be non-empty, got %s to %s", from, to)) } - providers, err := r.rollup(ctx, granularity, from, to) - if err != nil { - return 0, err - } - tags, err := r.store.TagBuckets.rollup(ctx, granularity, from, to) - if err != nil { - return 0, err + // A bucket at a time, each in statements of its own: a wide window in one statement reads + // every request in it and runs out of the statement limit, rolling back all of it. + var written int64 + for start := from; start.Before(to); { + end := granularity.next(start) + if end.After(to) { + end = to + } + providers, err := r.rollup(ctx, granularity, start, end) + if err != nil { + return written, err + } + tags, err := r.store.TagBuckets.rollup(ctx, granularity, start, end) + if err != nil { + return written, err + } + written += providers + tags + start = end } - return providers + tags, nil + return written, nil } // wholeBuckets is a rollup's WHERE on column: the whole buckets [from, to) touches, taking diff --git a/acceleration/internal/store/bucket_test.go b/acceleration/internal/store/bucket_test.go index e2159bbb05..e8bfa4246f 100644 --- a/acceleration/internal/store/bucket_test.go +++ b/acceleration/internal/store/bucket_test.go @@ -522,6 +522,11 @@ func (s *StoreSuite) TestBucketQueryBudgets() { _, err := s.store.Buckets.Rollup(s.ctx, Hourly, s.base, s.base.Add(time.Hour)) s.Require().NoError(err) })) + // A wider window is the same two a bucket at a time, so no statement covers all of it. + s.Equal(6, s.countQueries(func() { + _, err := s.store.Buckets.Rollup(s.ctx, Hourly, s.base.Add(30*time.Minute), s.base.Add(3*time.Hour)) + s.Require().NoError(err) + })) s.Equal(len(s.store.shards()), s.countQueries(func() { buckets, err := s.store.Buckets.Select(s.ctx, "acme", BucketFilter{Modality: "stt", Granularity: Hourly, From: s.base, To: s.base.Add(time.Hour)}) s.Require().NoError(err) diff --git a/acceleration/internal/store/budget_test.go b/acceleration/internal/store/budget_test.go index 8560748176..a2989f1bc1 100644 --- a/acceleration/internal/store/budget_test.go +++ b/acceleration/internal/store/budget_test.go @@ -68,6 +68,40 @@ func (s *StoreSuite) countEveryQuery() { } } +// statementsOf counts the statements starting with prefix sent while it is active. +type statementsOf struct { + prefix string + active atomic.Bool + sent atomic.Int64 +} + +func (c *statementsOf) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { + return ctx +} + +func (c *statementsOf) AfterQuery(_ context.Context, event *bun.QueryEvent) { + if c.active.Load() && strings.HasPrefix(event.Query, c.prefix) { + c.sent.Add(1) + } +} + +// statementsLike is how many statements starting with prefix run sends, on every database the +// store holds: how many batches a batched write took. +func (s *StoreSuite) statementsLike(prefix string, run func()) int { + counter := &statementsOf{prefix: prefix} + databases := append([]*bun.DB{s.store.global}, s.store.peers...) + if s.store.Sharded() { + databases = append(databases, s.store.shard) + } + for _, db := range databases { + db.AddQueryHook(counter) + } + counter.active.Store(true) + run() + counter.active.Store(false) + return int(counter.sent.Load()) +} + // roundTrips counts what the store sends Redis: a command, or a pipeline of them, is one. type roundTrips struct{ sent atomic.Int64 } diff --git a/acceleration/internal/store/campaign_test.go b/acceleration/internal/store/campaign_test.go index f24e0a0234..9d38c8c924 100644 --- a/acceleration/internal/store/campaign_test.go +++ b/acceleration/internal/store/campaign_test.go @@ -285,6 +285,10 @@ func (s *StoreSuite) TestACampaignHoldsAtMostAHundredThousandContacts() { if _, err := tx.ExecContext(ctx, "SET LOCAL session_replication_role = replica"); err != nil { return err } + // Setup, not the store's own work: it may run past the serving statement limit. + if _, err := tx.ExecContext(ctx, "SET LOCAL statement_timeout = 0"); err != nil { + return err + } _, err := tx.ExecContext(ctx, `INSERT INTO campaign_contacts (id, campaign_id, to_number) SELECT 'c' || n, ?, '+1' || n FROM generate_series(1, 99999) AS n`, campaign.ID) return err diff --git a/acceleration/internal/store/channel_inbound.go b/acceleration/internal/store/channel_inbound.go index c7b52bbd52..4c2426bbcb 100644 --- a/acceleration/internal/store/channel_inbound.go +++ b/acceleration/internal/store/channel_inbound.go @@ -438,13 +438,10 @@ func updateClaimedChannelInbound(ctx context.Context, claimed ChannelInbound, up // Prune deletes the rows of written messages finished a day before now, and of // given-up ones 30 days before, and returns how many it deleted. func (r *ChannelInbounds) Prune(ctx context.Context, now time.Time) (int, error) { - result, err := r.store.global.NewDelete().Model((*ChannelInbound)(nil)). - Where("(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", - ChannelInboundDone, now.Add(-channelInboundDoneKeep).UTC(), ChannelInboundFailed, now.Add(-channelInboundFailedKeep).UTC()). - Exec(ctx) + pruned, err := deleteInBatches(ctx, r.store.global, "channel_thread_inbound", "(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", + ChannelInboundDone, now.Add(-channelInboundDoneKeep).UTC(), ChannelInboundFailed, now.Add(-channelInboundFailedKeep).UTC()) if err != nil { - return 0, stack.Wrap(fmt.Errorf("store: prune channel inbound: %w", err)) + return int(pruned), stack.Wrap(fmt.Errorf("store: prune channel inbound: %w", err)) } - pruned, _ := result.RowsAffected() return int(pruned), nil } diff --git a/acceleration/internal/store/channel_inbound_test.go b/acceleration/internal/store/channel_inbound_test.go index 179cf6c8c0..ee2e9bff68 100644 --- a/acceleration/internal/store/channel_inbound_test.go +++ b/acceleration/internal/store/channel_inbound_test.go @@ -833,3 +833,10 @@ func (s *StoreSuite) TestChannelInboundQueryBudgets() { s.Equal(2, pruned) }), "Prune") } + +// PruningKeepsAWrittenMessageADayAndAGivenUpOneThirtyDays, with a backlog of more than one statement's worth. +func (s *StoreSuite) TestABacklogOfWrittenMessagesIsPrunedWhole() { + s.inSmallBatches() + deletes := s.statementsLike("DELETE FROM channel_thread_inbound", s.TestPruningKeepsAWrittenMessageADayAndAGivenUpOneThirtyDays) + s.Equal(3, deletes, "a row per statement, then the one that finds none") +} diff --git a/acceleration/internal/store/chat_inbound.go b/acceleration/internal/store/chat_inbound.go index 8933fa7a46..2b32bb39ed 100644 --- a/acceleration/internal/store/chat_inbound.go +++ b/acceleration/internal/store/chat_inbound.go @@ -274,13 +274,10 @@ func (r *ChatInbounds) ReleaseAnswer(ctx context.Context, streamApp int64, messa // Prune deletes the rows of answered messages finished a day before now, and of // given-up ones 30 days before, and returns how many it deleted. func (r *ChatInbounds) Prune(ctx context.Context, now time.Time) (int, error) { - result, err := r.store.global.NewDelete().Model((*ChatInbound)(nil)). - Where("(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", - ChatInboundDone, now.Add(-chatInboundDoneKeep).UTC(), ChatInboundFailed, now.Add(-chatInboundFailedKeep).UTC()). - Exec(ctx) + pruned, err := deleteInBatches(ctx, r.store.global, "chat_inbound", "(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", + ChatInboundDone, now.Add(-chatInboundDoneKeep).UTC(), ChatInboundFailed, now.Add(-chatInboundFailedKeep).UTC()) if err != nil { - return 0, stack.Wrap(fmt.Errorf("store: prune chat inbound: %w", err)) + return int(pruned), stack.Wrap(fmt.Errorf("store: prune chat inbound: %w", err)) } - pruned, _ := result.RowsAffected() return int(pruned), nil } diff --git a/acceleration/internal/store/chat_inbound_test.go b/acceleration/internal/store/chat_inbound_test.go index d8a5e14911..9ed4c5d3ef 100644 --- a/acceleration/internal/store/chat_inbound_test.go +++ b/acceleration/internal/store/chat_inbound_test.go @@ -804,3 +804,10 @@ func (s *StoreSuite) TestChatInboundQueryBudgets() { s.Equal(2, pruned) }), "Prune") } + +// PruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThirtyDays, with a backlog of more than one statement's worth. +func (s *StoreSuite) TestABacklogOfAnsweredChatMessagesIsPrunedWhole() { + s.inSmallBatches() + deletes := s.statementsLike("DELETE FROM chat_inbound", s.TestPruningKeepsAnAnsweredChatMessageADayAndAGivenUpOneThirtyDays) + s.Equal(3, deletes, "a row per statement, then the one that finds none") +} diff --git a/acceleration/internal/store/datamove.go b/acceleration/internal/store/datamove.go index dbae7d9890..15f28fa534 100644 --- a/acceleration/internal/store/datamove.go +++ b/acceleration/internal/store/datamove.go @@ -321,9 +321,10 @@ func (s *Store) StartDataCapture(ctx context.Context, customerID string, retenti return errors.New("store: a customer id is required") } err := s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { - // A lock_timeout of 0 waits for ever. + // A lock_timeout of 0 waits for ever. The wait stays under the statement limit, which + // would otherwise end it first and answer a statement timeout instead of ErrWritesOpen. if _, err := tx.ExecContext(ctx, "SELECT set_config('lock_timeout', ?, true)", - fmt.Sprintf("%dms", max(within.Milliseconds(), 1))); err != nil { + fmt.Sprintf("%dms", max(min(within, captureLockWait).Milliseconds(), 1))); err != nil { return err } if _, err := tx.ExecContext(ctx, ` @@ -350,6 +351,10 @@ ON CONFLICT (customer_id) DO UPDATE SET expires_at = EXCLUDED.expires_at, return nil } +// captureLockWait is the longest StartDataCapture waits on a write open before it, a second +// under the statement limit. +const captureLockWait = statementTimeout - time.Second + // captureLapseMargin is how close to expiring a capture may be and still count as lapsed when // it is renewed. It is well above a renewal's usual length (milliseconds) and far below any // retention. @@ -409,6 +414,9 @@ WHERE locktype = 'transactionid' AND transactionid::text = ANY(?)`, return nil } +// exportLimit is how long an export's statements may run and its transactions sit idle. +const exportLimit = time.Hour + // ExportCustomer writes every row belonging to a customer and returns the cursor their // changes carry on from. // @@ -429,6 +437,10 @@ WHERE locktype = 'transactionid' AND transactionid::text = ANY(?)`, // an object bucket rather than in Postgres. The rows naming them come across, and copying // the bucket is a copy between two object stores that neither deployment should be in the // middle of. +// +// Its transactions run past the serving limits, to exportLimit: a table of a large customer +// streams for longer than a statement may take, and each transaction sits idle while the +// others, or a slow reader of the rows, are served. func (s *Store) ExportCustomer(ctx context.Context, customerID string, write func(table string, row json.RawMessage) error) (int64, error) { if customerID == "" { return 0, errors.New("store: a customer id is required") @@ -445,6 +457,9 @@ func (s *Store) ExportCustomer(ctx context.Context, customerID string, write fun return 0, fmt.Errorf("store: export: %w", err) } defer tx.Rollback() //nolint:errcheck // read-only, and the error on the way out says nothing + if err := boundTransaction(ctx, tx, exportLimit, lockTimeout, exportLimit); err != nil { + return 0, fmt.Errorf("store: export: %w", err) + } // Never below where the recording last started again: Changes refuses a cursor from before // it. A transaction holding a number at or below it had written its row before that start, @@ -479,6 +494,9 @@ func (s *Store) ExportCustomer(ctx context.Context, customerID string, write fun return 0, fmt.Errorf("store: export: shard: %w", err) } defer shardTx.Rollback() //nolint:errcheck // read-only, and the error on the way out says nothing + if err := boundTransaction(ctx, shardTx, exportLimit, lockTimeout, exportLimit); err != nil { + return 0, fmt.Errorf("store: export: shard: %w", err) + } shards = append(shards, shardTx) } for _, table := range dataTables { @@ -2082,12 +2100,20 @@ func (s *Store) PruneDataChanges(ctx context.Context, retention time.Duration) ( // prunes, and of two prunes at once the one that dropped the lower numbers can commit last, so // pruned_through only goes up. A WITH statement that changes rows runs once and to the end // whether or not the query reads it (https://www.postgresql.org/docs/current/queries-with.html). + // + // The lowest numbers go first, writeBatch of them per statement, so a backlog is pruned in + // statements that each finish inside the statement limit, and pruned_through still says + // how far the pruning got. var removed int64 - err = s.global.QueryRowContext(ctx, ` + for { + var batch int64 + err = s.global.QueryRowContext(ctx, ` WITH pruned AS ( - DELETE FROM data_changes - WHERE at < now() - make_interval(secs => ?) - AND seq <= LEAST(?, (SELECT MIN(seq) - 1 FROM data_changes WHERE at >= now() - make_interval(secs => ?))) + DELETE FROM data_changes WHERE seq IN ( + SELECT seq FROM data_changes + WHERE at < now() - make_interval(secs => ?) + AND seq <= LEAST(?, (SELECT MIN(seq) - 1 FROM data_changes WHERE at >= now() - make_interval(secs => ?))) + ORDER BY seq LIMIT ?) RETURNING customer_id, seq ), noted AS ( UPDATE data_change_capture AS c SET pruned_through = p.seq @@ -2095,11 +2121,15 @@ WITH pruned AS ( WHERE c.customer_id = p.customer_id AND c.pruned_through < p.seq ) SELECT count(*) FROM pruned`, - retention.Seconds(), mark, retention.Seconds()).Scan(&removed) - if err != nil { - return 0, fmt.Errorf("store: prune data changes: %w", err) + retention.Seconds(), mark, retention.Seconds(), writeBatch).Scan(&batch) + if err != nil { + return removed, fmt.Errorf("store: prune data changes: %w", err) + } + removed += batch + if batch < int64(writeBatch) { + return removed, nil + } } - return removed, nil } // watchDataChanges attaches the recording trigger to every table an export carries, in one diff --git a/acceleration/internal/store/datamove_test.go b/acceleration/internal/store/datamove_test.go index 7c62f3ed7e..51334204ea 100644 --- a/acceleration/internal/store/datamove_test.go +++ b/acceleration/internal/store/datamove_test.go @@ -4815,3 +4815,106 @@ func (s *DataMoveSuite) TestAConfigFromAnOlderReleaseKeepsItsRenamedSettings() { s.Equal(config.EpisodeCards, moved.EpisodeCards) s.Equal(config.Channels, moved.Channels) } + +func (s *StoreSuite) TestAnExportOutlastsTheIdleLimitOfAServingTransaction() { + limited := s.limitedStore() + s.boundConfig("app") + + rows := 0 + _, err := limited.ExportCustomer(s.ctx, "app", func(string, json.RawMessage) error { + if rows == 0 { + // A reader slower than the limit leaves every transaction of the export idle. + time.Sleep(3 * shortLimit) + } + rows++ + return nil + }) + + s.Require().NoError(err) + s.Positive(rows) +} + +func (s *StoreSuite) TestAnExportStatementOutlastsTheServingStatementLimit() { + limited := s.limitedStore() + s.boundConfig("app") + holder, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer holder.Rollback() //nolint:errcheck // only ever holds the lock + _, err = holder.ExecContext(s.ctx, "LOCK TABLE skills IN ACCESS EXCLUSIVE MODE") + s.Require().NoError(err) + release := time.AfterFunc(3*shortLimit, func() { _ = holder.Rollback() }) + defer release.Stop() + + _, err = limited.ExportCustomer(s.ctx, "app", func(string, json.RawMessage) error { return nil }) + + s.Require().NoError(err, "the read of skills waited on the lock past the serving limit") +} + +func (s *DataMoveSuite) TestABacklogOfChangesIsPrunedWhole() { + kept := writeBatch + writeBatch = 1 + s.T().Cleanup(func() { writeBatch = kept }) + s.TestPruningDropsWhatNobodyCanResumeFrom() +} + +// cutAfterFirstPrune cancels its context once a statement pruning data_changes has run. +type cutAfterFirstPrune struct{ cancel context.CancelFunc } + +func (c cutAfterFirstPrune) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context { + return ctx +} + +func (c cutAfterFirstPrune) AfterQuery(_ context.Context, event *bun.QueryEvent) { + if strings.Contains(event.Query, "DELETE FROM data_changes") { + c.cancel() + } +} + +func (s *DataMoveSuite) TestAPruneCutShortAfterOneBatchHasDroppedTheLowestChangeAndSaidSo() { + kept := writeBatch + writeBatch = 1 + s.T().Cleanup(func() { writeBatch = kept }) + s.capture("acme") + for _, name := range []string{"one", "two", "three"} { + s.seedAgentConfig(s.source, "acme", name) + } + s.age() + var seqs []int64 + s.Require().NoError(s.source.GlobalDB().NewRaw("SELECT seq FROM data_changes WHERE customer_id = 'acme' ORDER BY seq").Scan(s.ctx, &seqs)) + s.Require().Len(seqs, 3) + // The lowest is rewritten, so it is the last row a read in no order meets. + _, err := s.source.GlobalDB().ExecContext(s.ctx, "UPDATE data_changes SET at = at WHERE seq = ?", seqs[0]) + s.Require().NoError(err) + var database string + s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx, "SELECT current_database()").Scan(&database)) + parsed, err := url.Parse(os.Getenv(DSNEnvVar)) + s.Require().NoError(err) + parsed.Path = "/" + database + pruning, err := Open(parsed.String()) + s.Require().NoError(err) + defer pruning.Close() + ctx, cancel := context.WithCancel(s.ctx) + defer cancel() + pruning.GlobalDB().AddQueryHook(cutAfterFirstPrune{cancel: cancel}) + + _, err = pruning.PruneDataChanges(ctx, 7*24*time.Hour) + + s.Require().ErrorIs(err, context.Canceled) + var left []int64 + s.Require().NoError(s.source.GlobalDB().NewRaw("SELECT seq FROM data_changes WHERE customer_id = 'acme' ORDER BY seq").Scan(s.ctx, &left)) + s.Equal(seqs[1:], left, "the lowest went first") + var through int64 + s.Require().NoError(s.source.GlobalDB().QueryRowContext(s.ctx, + "SELECT pruned_through FROM data_change_capture WHERE customer_id = 'acme'").Scan(&through)) + s.Equal(seqs[0], through) +} + +func (s *DataMoveSuite) TestACaptureStartGivenLongerThanTheStatementLimitGivesUpAsWritesOpen() { + before := s.beginAt(sql.LevelRepeatableRead) + defer before.Rollback() //nolint:errcheck // only holds the starts + s.writeIn(before, "acme", "looked before the start") + + err := s.source.StartDataCapture(s.ctx, "acme", time.Hour, 30*time.Second) + + s.ErrorIs(err, ErrWritesOpen, "not a statement the statement limit ended: %v", err) +} diff --git a/acceleration/internal/store/image_job.go b/acceleration/internal/store/image_job.go index 628b2e7780..51d8be5c9e 100644 --- a/acceleration/internal/store/image_job.go +++ b/acceleration/internal/store/image_job.go @@ -248,12 +248,10 @@ func (r *ImageJobs) update(ctx context.Context, job ImageJob, doing string, // Prune deletes the jobs past their keep as of now, and returns how many. func (r *ImageJobs) Prune(ctx context.Context, now time.Time) (int64, error) { - result, err := r.store.global.NewDelete().Model((*ImageJob)(nil)). - Where("(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", - ImageJobDone, now.Add(-imageJobDoneKeep).UTC(), ImageJobFailed, now.Add(-imageJobFailedKeep).UTC()). - Exec(ctx) + pruned, err := deleteInBatches(ctx, r.store.global, "image_jobs", "(state = ? AND finished_at < ?) OR (state = ? AND finished_at < ?)", + ImageJobDone, now.Add(-imageJobDoneKeep).UTC(), ImageJobFailed, now.Add(-imageJobFailedKeep).UTC()) if err != nil { - return 0, stack.Wrap(fmt.Errorf("store: prune image jobs: %w", err)) + return pruned, stack.Wrap(fmt.Errorf("store: prune image jobs: %w", err)) } - return result.RowsAffected() + return pruned, nil } diff --git a/acceleration/internal/store/image_job_test.go b/acceleration/internal/store/image_job_test.go index 6c6d6b98be..899894ab36 100644 --- a/acceleration/internal/store/image_job_test.go +++ b/acceleration/internal/store/image_job_test.go @@ -169,3 +169,10 @@ func (s *StoreSuite) TestImageJobQueryBudgets() { s.Equal(int64(1), pruned) }), "Prune") } + +// PostedImageJobsAreDeletedAfterADayAndFailedOnesAfter30Days, with a backlog of more than one statement's worth. +func (s *StoreSuite) TestABacklogOfFinishedImageJobsIsPrunedWhole() { + s.inSmallBatches() + deletes := s.statementsLike("DELETE FROM image_jobs", s.TestPostedImageJobsAreDeletedAfterADayAndFailedOnesAfter30Days) + s.Equal(3, deletes, "a row per statement, then the one that finds none") +} diff --git a/acceleration/internal/store/limit_grant_use.go b/acceleration/internal/store/limit_grant_use.go index 18a313685a..b9dca40e5d 100644 --- a/acceleration/internal/store/limit_grant_use.go +++ b/acceleration/internal/store/limit_grant_use.go @@ -239,6 +239,9 @@ const ( // grantReconcilePage is how many rows one read of a shard takes; where the reconcile got // is kept after each, so one cut short goes on from there. grantReconcilePage = 2_000 + // grantReconcileHold is how long a reconcile holds its lock with nothing to say to the + // shared database, longer than the pass the policy service gives a reconcile. + grantReconcileHold = 5 * time.Minute ) // ErrReconcileBusy is LimitGrantUses.Reconcile finding another router reconciling. @@ -260,6 +263,11 @@ func (r *LimitGrantUses) Reconcile(ctx context.Context) (int, error) { return 0, stack.Wrap(fmt.Errorf("store: reconcile grant uses: %w", err)) } defer tx.Rollback() //nolint:errcheck // it writes nothing; ending it lets go of the lock + // The transaction holds the lock and sits idle while the shards are read, for longer than + // the serving limit would let it before ending the session and letting the lock go. + if err := boundTransaction(ctx, tx, statementTimeout, lockTimeout, grantReconcileHold); err != nil { + return 0, stack.Wrap(fmt.Errorf("store: reconcile grant uses: %w", err)) + } var locked bool if err := tx.QueryRowContext(ctx, "SELECT pg_try_advisory_xact_lock(hashtextextended('limit_grant_reconciles', 0))").Scan(&locked); err != nil { return 0, stack.Wrap(fmt.Errorf("store: reconcile grant uses: lock: %w", err)) diff --git a/acceleration/internal/store/limit_grant_use_test.go b/acceleration/internal/store/limit_grant_use_test.go index f9306e81e1..b418e7e9af 100644 --- a/acceleration/internal/store/limit_grant_use_test.go +++ b/acceleration/internal/store/limit_grant_use_test.go @@ -346,10 +346,41 @@ func (s *StoreSuite) TestLimitGrantUseQueryBudgets() { shards := len(s.store.shards()) reconcile := 0 if s.store.Sharded() { - reconcile = 3 + 3*shards + reconcile = 4 + 3*shards } s.Equal(reconcile, s.countQueries(func() { _, err := s.store.LimitGrantUses.Reconcile(s.ctx) s.Require().NoError(err) - }), "begin, the lock, and for each shard where it got, one page and where it gets to, then the end") + }), "begin, its limits, the lock, and for each shard where it got, one page and where it gets to, then the end") +} + +func (s *ShardedStoreSuite) TestAReconcileKeepsItsLockWhileItWaitsOnAShard() { + // Only the shared database's connections are held to the short limit: the reconcile's lock + // is there, and its wait is on the shard. + reconciling, err := OpenShards(Options{DSN: s.limitedDSN(s.dsn), ShardDSN: s.shardDSN}) + s.Require().NoError(err) + defer reconciling.Close() + holder, err := s.store.ShardDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer holder.Rollback() //nolint:errcheck // only ever holds the lock + _, err = holder.ExecContext(s.ctx, "LOCK TABLE requests IN ACCESS EXCLUSIVE MODE") + s.Require().NoError(err) + + reconciled := make(chan error, 1) + go func() { + _, err := reconciling.LimitGrantUses.Reconcile(s.ctx) + reconciled <- err + }() + s.Require().Eventually(func() bool { + var waiting int + s.Require().NoError(s.store.ShardDB().QueryRowContext(s.ctx, + "SELECT count(*) FROM pg_locks WHERE NOT granted AND relation = 'requests'::regclass").Scan(&waiting)) + return waiting > 0 + }, 2*time.Second, 10*time.Millisecond, "the reconcile waits on the shard") + time.Sleep(3 * shortLimit) + + _, err = s.other.LimitGrantUses.Reconcile(s.ctx) + s.Require().ErrorIs(err, ErrReconcileBusy, "the first reconcile still holds its lock") + s.Require().NoError(holder.Rollback()) + s.NoError(<-reconciled) } diff --git a/acceleration/internal/store/phone_number.go b/acceleration/internal/store/phone_number.go index 9b9f47d4b0..cd61c66fc6 100644 --- a/acceleration/internal/store/phone_number.go +++ b/acceleration/internal/store/phone_number.go @@ -209,7 +209,9 @@ func (r *PhoneNumbers) Release(ctx context.Context, customerID, e164 string, at if customerID == "" || e164 == "" { return stack.Wrap(errors.New("store: a customer and a number are required")) } - return releaseNumber(ctx, r.store.global, customerID, e164, at) + return r.store.numberWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return releaseNumber(ctx, tx, customerID, e164, at) + }) } // Attach records which SIP trunk calls to a number arrive on and which Stream call they @@ -221,7 +223,22 @@ func (r *PhoneNumbers) Attach(ctx context.Context, customerID, e164 string, atta if customerID == "" || e164 == "" { return stack.Wrap(errors.New("store: a customer and a number are required")) } - return attachNumber(ctx, r.store.global, customerID, e164, attached) + return r.store.numberWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + return attachNumber(ctx, tx, customerID, e164, attached) + }) +} + +// numberWrite runs write, a write to a number's row from outside its trunk group, in a +// transaction that waits on the row as long as a trunk group waits on the group: the group +// holds the row (TrunkGroupTx.Number) across its calls to Stream, which outlast the serving +// lock limit. The statement limit still ends the wait. +func (s *Store) numberWrite(ctx context.Context, write func(context.Context, bun.Tx) error) error { + return s.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + if err := boundTransaction(ctx, tx, statementTimeout, trunkGroupIdle, idleInTransactionTimeout); err != nil { + return stack.Wrap(fmt.Errorf("store: number write: %w", err)) + } + return write(ctx, tx) + }) } // attachNumber records in db that a number is attached. @@ -331,26 +348,28 @@ func (r *PhoneNumbers) SetAgent(ctx context.Context, customerID, e164, configID if customerID == "" || e164 == "" || configID == "" { return stack.Wrap(errors.New("store: a customer, a number and a config are required")) } - // Only an attached number has an agent, and a detach can land between the caller's - // read and this write. - result, err := r.store.global.NewUpdate().Model((*PhoneNumber)(nil)). - Set("config_id = ?", configID). - Where("customer_id = ?", customerID). - Where("e164 = ?", e164). - Where("released_at IS NULL"). - Where("attached_at IS NOT NULL"). - Exec(ctx) - if err != nil { - return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) - } - affected, err := result.RowsAffected() - if err != nil { - return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) - } - if affected == 0 { - return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds attached", e164, customerID)}) - } - return nil + return r.store.numberWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + // Only an attached number has an agent, and a detach can land between the caller's + // read and this write. + result, err := tx.NewUpdate().Model((*PhoneNumber)(nil)). + Set("config_id = ?", configID). + Where("customer_id = ?", customerID). + Where("e164 = ?", e164). + Where("released_at IS NULL"). + Where("attached_at IS NOT NULL"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) + } + affected, err := result.RowsAffected() + if err != nil { + return stack.Wrap(fmt.Errorf("store: set number agent: %w", err)) + } + if affected == 0 { + return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds attached", e164, customerID)}) + } + return nil + }) } // ClearAgent sends a number's calls back to dispatch. A number with no agent is left as it @@ -359,23 +378,25 @@ func (r *PhoneNumbers) ClearAgent(ctx context.Context, customerID, e164 string) if customerID == "" || e164 == "" { return stack.Wrap(errors.New("store: a customer and a number are required")) } - result, err := r.store.global.NewUpdate().Model((*PhoneNumber)(nil)). - Set("config_id = NULL"). - Where("customer_id = ?", customerID). - Where("e164 = ?", e164). - Where("released_at IS NULL"). - Exec(ctx) - if err != nil { - return stack.Wrap(fmt.Errorf("store: clear number agent: %w", err)) - } - affected, err := result.RowsAffected() - if err != nil { - return stack.Wrap(fmt.Errorf("store: clear number agent: %w", err)) - } - if affected == 0 { - return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds", e164, customerID)}) - } - return nil + return r.store.numberWrite(ctx, func(ctx context.Context, tx bun.Tx) error { + result, err := tx.NewUpdate().Model((*PhoneNumber)(nil)). + Set("config_id = NULL"). + Where("customer_id = ?", customerID). + Where("e164 = ?", e164). + Where("released_at IS NULL"). + Exec(ctx) + if err != nil { + return stack.Wrap(fmt.Errorf("store: clear number agent: %w", err)) + } + affected, err := result.RowsAffected() + if err != nil { + return stack.Wrap(fmt.Errorf("store: clear number agent: %w", err)) + } + if affected == 0 { + return stack.Wrap(numberNotHeld{fmt.Sprintf("store: %s is not a number %s holds", e164, customerID)}) + } + return nil + }) } // AnsweredBy returns the numbers a config answers, sorted. diff --git a/acceleration/internal/store/phone_number_test.go b/acceleration/internal/store/phone_number_test.go index 9e9fe7032c..931233a2e0 100644 --- a/acceleration/internal/store/phone_number_test.go +++ b/acceleration/internal/store/phone_number_test.go @@ -231,7 +231,9 @@ func (s *StoreSuite) TestPhoneNumberQueryBudgets() { s.Equal(3, s.countQueries(func() { s.Require().NoError(s.trunkNumber("acme", trunk.ID, "+15125550198")) }), "InsertOnSIPTrunk reads the trunk and the number before it inserts") - s.Equal(1, s.countQueries(func() { + // A write to a number is a transaction, BEGIN to COMMIT, that waits on the row as long as a + // trunk group may hold it. + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.PhoneNumbers.Attach(s.ctx, "acme", "+15125550199", NumberAttachment{TrunkID: "trunk-1", CallType: "default"})) }), "Attach") s.Equal(1, s.countQueries(func() { @@ -243,7 +245,7 @@ func (s *StoreSuite) TestPhoneNumberQueryBudgets() { _, err := s.store.PhoneNumbers.GetByE164(s.ctx, "acme", "+15125550100") s.Require().NoError(err) }), "GetByE164") - s.Equal(1, s.countQueries(func() { + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.PhoneNumbers.SetAgent(s.ctx, "acme", "+15125550199", config)) }), "SetAgent") s.Equal(1, s.countQueries(func() { @@ -251,7 +253,7 @@ func (s *StoreSuite) TestPhoneNumberQueryBudgets() { s.Require().NoError(err) s.Len(numbers, 6) }), "AnsweredBy") - s.Equal(1, s.countQueries(func() { + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.PhoneNumbers.ClearAgent(s.ctx, "acme", "+15125550199")) }), "ClearAgent") s.Equal(1, s.countQueries(func() { @@ -259,7 +261,7 @@ func (s *StoreSuite) TestPhoneNumberQueryBudgets() { s.Require().NoError(err) s.Len(held, 7) }), "HeldSince") - s.Equal(1, s.countQueries(func() { + s.Equal(4, s.countQueries(func() { s.Require().NoError(s.store.PhoneNumbers.Release(s.ctx, "acme", "+15125550199", s.base.Add(time.Hour))) }), "Release") } diff --git a/acceleration/internal/store/redis.go b/acceleration/internal/store/redis.go index 14e039fa61..a192c6a8a6 100644 --- a/acceleration/internal/store/redis.go +++ b/acceleration/internal/store/redis.go @@ -24,6 +24,16 @@ var tracer = tracing.Tracer("store") // deletion that did not land. const cacheTTL = time.Hour +// forgetWait is how long the deletion of cached rows, or one try at it again, waits on Redis. +// It is longer than cacheWait: a deletion that is answered late still tells every replica, +// where a read that waits that long is better answered from Postgres. +const forgetWait = 2 * time.Second + +// cacheWait is how long a read of the cache waits on one answer from Redis before going to +// Postgres instead. +// Redis answers in a millisecond or two; one that takes this long is down or cut off. +const cacheWait = 250 * time.Millisecond + // keyCacheTTL is how long a key's owner is cached. It is short because a key revoked where // the deletion does not reach, in the database alone or when Redis drops the DEL, has to // stop authenticating within a minute rather than an hour. @@ -77,7 +87,11 @@ func (s *Store) openRedis(options Options) error { aside(messages) s.Users.invalidate(messages) } - return build(option) + client, err := build(option) + if err != nil { + return nil, err + } + return rueidishook.WithHook(client, cacheReadBound{}), nil } cache, err := rueidisaside.NewClient(rueidisaside.ClientOption{ClientOption: options.Redis.option(), ClientBuilder: shared}) if err != nil { @@ -132,6 +146,11 @@ func cached[T any](ctx context.Context, s *Store, name string, load func(context } // cachedFor is cached with a TTL of the caller's own. +// +// Each Redis command of the read waits on Redis's answer for cacheWait (cacheReadBound), so a +// Redis that cannot be reached costs that and not the caller's whole deadline. load runs on +// the caller's context, unbounded by that wait, and so does rueidisaside's wait for a load +// another caller of this router is running: the readers of a cold key share one load. func cachedFor[T any](ctx context.Context, s *Store, name string, ttl time.Duration, load func(context.Context) (T, error)) (T, error) { var value T if s.cache == nil { @@ -142,18 +161,24 @@ func cachedFor[T any](ctx context.Context, s *Store, name string, ttl time.Durat defer span.End() var refused error - encoded, err := s.cache.Get(ctx, ttl, name, func(ctx context.Context, _ string) (string, error) { - loaded, err := load(ctx) - if err != nil { + var loaded T + var hasLoaded bool + encoded, err := s.cache.Get(context.WithValue(ctx, cacheReadKey{}, true), ttl, name, func(ctx context.Context, _ string) (string, error) { + var err error + if loaded, err = load(ctx); err != nil { refused = err return "", err } + hasLoaded = true raw, err := json.Marshal(loaded) return string(raw), err }) switch { case refused != nil: return value, stack.Wrap(refused) + case err != nil && hasLoaded: + slog.Default().Error("could not cache a row in redis", "key", name, "error", err) + return loaded, nil case err != nil: slog.Default().Error("could not read a cached row from redis, reading postgres", "key", name, "error", err) return load(ctx) @@ -165,6 +190,60 @@ func cachedFor[T any](ctx context.Context, s *Store, name string, ttl time.Durat return value, nil } +// cacheReadKey marks the context of a cached read, whose Redis commands cacheReadBound bounds. +type cacheReadKey struct{} + +// cacheReadBound gives cacheWait to be answered to each command sent on a cached read's +// context, and to each one sent on a context with no deadline. The second are rueidisaside's +// own, its client marker and the release of a load's lock, which a cached read and the +// readers waiting on its load wait for, and the store's sends that outlive a request (forget). +// A command on a context with a deadline of its own keeps it. A stream is read after the call +// returns, so it is left alone. +type cacheReadBound struct{} + +func boundCacheRead(ctx context.Context) (context.Context, context.CancelFunc) { + if _, deadline := ctx.Deadline(); deadline && ctx.Value(cacheReadKey{}) == nil { + return ctx, func() {} + } + return context.WithTimeout(ctx, cacheWait) +} + +func (cacheReadBound) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResult { + ctx, cancel := boundCacheRead(ctx) + defer cancel() + return client.Do(ctx, cmd) +} + +func (cacheReadBound) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) []rueidis.RedisResult { + ctx, cancel := boundCacheRead(ctx) + defer cancel() + return client.DoMulti(ctx, multi...) +} + +func (cacheReadBound) DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) rueidis.RedisResult { + ctx, cancel := boundCacheRead(ctx) + defer cancel() + return client.DoCache(ctx, cmd, ttl) +} + +func (cacheReadBound) DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) []rueidis.RedisResult { + ctx, cancel := boundCacheRead(ctx) + defer cancel() + return client.DoMultiCache(ctx, multi...) +} + +func (cacheReadBound) Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(rueidis.PubSubMessage)) error { + return client.Receive(ctx, subscribe, fn) +} + +func (cacheReadBound) DoStream(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { + return client.DoStream(ctx, cmd) +} + +func (cacheReadBound) DoMultiStream(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { + return client.DoMultiStream(ctx, multi...) +} + // found is a row looked up together with whether there was one, so that a row nobody holds // can be cached as well. type found[T any] struct { @@ -187,7 +266,10 @@ func (s *Store) forget(ctx context.Context, names ...string) bool { if s.cache == nil || len(names) == 0 { return false } - ctx = context.WithoutCancel(ctx) + // A deadline of its own, so cacheReadBound leaves the deletion its forgetWait rather than + // a cached read's wait. + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), forgetWait) + defer cancel() client := s.cache.Client() // Each key is deleted on its own: a Redis Cluster refuses one DEL whose keys sit in // different hash slots, and the keys one write changes usually do. @@ -256,11 +338,13 @@ func (s *Store) forgetLater(names []string, err error) { commands = append(commands, client.B().Del().Key(name).Build()) } var missed []string - for i, reply := range client.DoMulti(s.closing, commands...) { + attempt, cancel := context.WithTimeout(s.closing, forgetWait) + for i, reply := range client.DoMulti(attempt, commands...) { if failed := reply.Error(); failed != nil && !errors.Is(failed, rueidis.Nil) { missed, err = append(missed, names[i]), failed } } + cancel() if names = missed; len(names) == 0 { return } diff --git a/acceleration/internal/store/redis_test.go b/acceleration/internal/store/redis_test.go index 4d094e39ac..2b9470505f 100644 --- a/acceleration/internal/store/redis_test.go +++ b/acceleration/internal/store/redis_test.go @@ -19,6 +19,8 @@ import ( "sync/atomic" "time" + "github.com/redis/rueidis" + "github.com/redis/rueidis/rueidishook" "github.com/uptrace/bun" ) @@ -828,3 +830,342 @@ func (s *StoreSuite) TestEveryCachedWriteARequestGaveUpOnLeavesNoStaleCopy() { s.Run(name, site) } } + +// redisLine is the suite's Redis reached through a proxy a test can break: cut closes every +// connection and the port, as a Redis that went away does, and freeze stops answering on the +// connections already open, as a Redis that hangs does. +type redisLine struct { + cut, freeze func() + // slow holds back every answer from Redis by a while, as a Redis that is slow but up does. + slow func(time.Duration) +} + +// storeOnRedisLine is another router's store on the suite's databases, whose Redis is reached +// through a redisLine. Skipped without Redis. +func (s *StoreSuite) storeOnRedisLine() (*Store, redisLine) { + return s.storeOnRedisLineHooked(nil) +} + +// storeOnRedisLineHooked is storeOnRedisLine with hook seeing every command, given the line. +func (s *StoreSuite) storeOnRedisLineHooked(hook func(redisLine) rueidishook.Hook) (*Store, redisLine) { + upstream := s.redis() + if upstream.Address == "" { + s.T().Skipf("%s not set", redisAddressVar) + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + s.Require().NoError(err) + var mu sync.Mutex + var clients, servers []net.Conn + closed := false + // delay holds back each answer from Redis by this many nanoseconds. + var delay atomic.Int64 + go func() { + for { + client, err := listener.Accept() + if err != nil { + return + } + server, err := net.Dial("tcp", upstream.Address) + mu.Lock() + if err != nil || closed { + mu.Unlock() + _ = client.Close() + if server != nil { + _ = server.Close() + } + continue + } + clients, servers = append(clients, client), append(servers, server) + mu.Unlock() + go func() { _, _ = io.Copy(server, client) }() + go func() { + buffer := make([]byte, 32<<10) + for { + n, err := server.Read(buffer) + if n > 0 { + time.Sleep(time.Duration(delay.Load())) + if _, err := client.Write(buffer[:n]); err != nil { + return + } + } + if err != nil { + return + } + } + }() + } + }() + freeze := func() { + mu.Lock() + defer mu.Unlock() + closed = true + for _, server := range servers { + _ = server.Close() + } + } + cut := sync.OnceFunc(func() { + freeze() + mu.Lock() + defer mu.Unlock() + _ = listener.Close() + for _, client := range clients { + _ = client.Close() + } + }) + + line := redisLine{cut: cut, freeze: freeze, slow: func(by time.Duration) { delay.Store(int64(by)) }} + options := Options{DSN: s.dsn, ShardDSN: s.shardDSN, Redis: Redis{Address: listener.Addr().String()}} + if hook != nil { + options.redisHook = hook(line) + } + store, err := OpenShards(options) + s.Require().NoError(err) + // Cut first: closing a store on a frozen Redis waits for the client to give up on it. + s.T().Cleanup(func() { + cut() + s.NoError(store.Close()) + }) + return store, line +} + +func (s *StoreSuite) TestAConfigIsReadFromPostgresWhileRedisCannotBeReached() { + created := s.boundConfig("app") + cutOff, line := s.storeOnRedisLine() + line.cut() + + ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + defer cancel() + started := time.Now() + found, err := cutOff.AgentConfigs.Get(ctx, "app", created.ID) + + s.Require().NoError(err) + s.Equal(created.Name, found.Name) + s.Less(time.Since(started), time.Second, "the read waited on Redis rather than going to Postgres") +} + +func (s *StoreSuite) TestARowSlowerToLoadThanRedisIsWaitedOnIsStillCached() { + if s.store.cache == nil { + s.T().Skipf("%s not set", redisAddressVar) + } + name := cacheKey("slow", newID()) + + loaded, err := cached(s.ctx, s.store, name, func(ctx context.Context) (string, error) { + _, err := s.store.GlobalDB().ExecContext(ctx, "SELECT pg_sleep(?)", (2 * cacheWait).Seconds()) + return "loaded", err + }) + s.Require().NoError(err, "a read of Postgres is not held to Redis's wait") + s.Equal("loaded", loaded) + + again, err := cached(s.ctx, s.store, name, func(context.Context) (string, error) { + return "", errors.New("read from postgres again") + }) + s.Require().NoError(err) + s.Equal("loaded", again, "the row was cached") +} + +func (s *StoreSuite) TestARowLoadedAsRedisGoesIsTheAnswer() { + cutOff, line := s.storeOnRedisLine() + loads := 0 + + ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + defer cancel() + found, err := cached(ctx, cutOff, cacheKey("lost", newID()), func(context.Context) (string, error) { + loads++ + line.cut() + return fmt.Sprintf("load %d", loads), nil + }) + + s.Require().NoError(err) + s.Equal("load 1", found, "the row Postgres answered with, not a second read of it") +} + +func (s *StoreSuite) TestAUserIsWrittenDownWhileRedisHangs() { + hung, line := s.storeOnRedisLine() + line.freeze() + app := s.freshApp() + + ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + defer cancel() + started := time.Now() + s.Require().NoError(hung.Users.Seen(ctx, app, "jlahey", UserKindAuthenticated)) + + s.Less(time.Since(started), time.Second, "the sighting waited on Redis") + _, found := s.userRow(app, "jlahey") + s.True(found) +} + +func (s *StoreSuite) TestReadersOfAColdRowShareOneReadOfPostgres() { + if s.store.cache == nil { + s.T().Skipf("%s not set", redisAddressVar) + } + name := cacheKey("cold", newID()) + var loads atomic.Int32 + answers := make(chan string, 8) + var readers sync.WaitGroup + for range 8 { + readers.Go(func() { + found, err := cached(s.ctx, s.store, name, func(ctx context.Context) (string, error) { + loads.Add(1) + _, err := s.store.GlobalDB().ExecContext(ctx, "SELECT pg_sleep(0.6)") + return "loaded", err + }) + s.NoError(err) + answers <- found + }) + } + readers.Wait() + close(answers) + + for found := range answers { + s.Equal("loaded", found) + } + s.EqualValues(1, loads.Load(), "one read of Postgres for every reader of the row") +} + +func (s *StoreSuite) TestAReadAfterAWriteAndItsForgetGetsTheNewRow() { + if s.store.cache == nil { + s.T().Skipf("%s not set", redisAddressVar) + } + name := cacheKey("rewritten", newID()) + loading, release := make(chan struct{}), make(chan struct{}) + older := make(chan string, 1) + go func() { + found, err := cached(s.ctx, s.store, name, func(context.Context) (string, error) { + close(loading) + <-release + return "old", nil + }) + s.NoError(err) + older <- found + }() + <-loading + // The write lands and forgets the key while the older read is still loading the row. + s.store.forget(s.ctx, name) + newer := make(chan string, 1) + go func() { + found, err := cached(s.ctx, s.store, name, func(context.Context) (string, error) { return "new", nil }) + s.NoError(err) + newer <- found + }() + // Long enough for the newer read to be waiting on the older one's load, which nothing + // outside the client can see. + time.Sleep(100 * time.Millisecond) + close(release) + + s.Equal("old", <-older, "the older read began before the write") + s.Equal("new", <-newer) + again, err := cached(s.ctx, s.store, name, func(context.Context) (string, error) { + return "", errors.New("read from postgres again") + }) + s.Require().NoError(err) + s.Equal("new", again, "the older read's row was not cached over the newer") +} + +func (s *StoreSuite) TestAReaderWhileRedisHangsAnswersFromPostgresWithinTheWait() { + hung, line := s.storeOnRedisLine() + line.freeze() + + ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + defer cancel() + started := time.Now() + found, err := cached(ctx, hung, cacheKey("hung", newID()), func(context.Context) (string, error) { return "loaded", nil }) + + s.Require().NoError(err) + s.Equal("loaded", found) + s.Less(time.Since(started), 400*time.Millisecond) +} + +func (s *StoreSuite) TestReadersWaitingOnALoadWhoseWriteBackHangsAnswerWithinTheWait() { + hung, line := s.storeOnRedisLine() + name := cacheKey("hung-write-back", newID()) + var freeze sync.Once + answers := make(chan string, 4) + var readers sync.WaitGroup + ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) + defer cancel() + started := time.Now() + for range 4 { + readers.Go(func() { + found, err := cached(ctx, hung, name, func(context.Context) (string, error) { + // Redis hangs while the row is loaded, before it is written back. + freeze.Do(line.freeze) + return "loaded", nil + }) + s.NoError(err) + answers <- found + }) + } + readers.Wait() + close(answers) + + for found := range answers { + s.Equal("loaded", found) + } + s.Less(time.Since(started), 2*time.Second, "the readers waited on Redis rather than its wait") +} + +// freezeOnMiss freezes the line once Redis has answered a cached read that it holds no row. +type freezeOnMiss struct{ line redisLine } + +func (f freezeOnMiss) Do(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResult { + return client.Do(ctx, cmd) +} + +func (f freezeOnMiss) DoMulti(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) []rueidis.RedisResult { + return client.DoMulti(ctx, multi...) +} + +func (f freezeOnMiss) DoCache(client rueidis.Client, ctx context.Context, cmd rueidis.Cacheable, ttl time.Duration) rueidis.RedisResult { + result := client.DoCache(ctx, cmd, ttl) + if rueidis.IsRedisNil(result.Error()) { + f.line.freeze() + } + return result +} + +func (f freezeOnMiss) DoMultiCache(client rueidis.Client, ctx context.Context, multi ...rueidis.CacheableTTL) []rueidis.RedisResult { + return client.DoMultiCache(ctx, multi...) +} + +func (f freezeOnMiss) Receive(client rueidis.Client, ctx context.Context, subscribe rueidis.Completed, fn func(rueidis.PubSubMessage)) error { + return client.Receive(ctx, subscribe, fn) +} + +func (f freezeOnMiss) DoStream(client rueidis.Client, ctx context.Context, cmd rueidis.Completed) rueidis.RedisResultStream { + return client.DoStream(ctx, cmd) +} + +func (f freezeOnMiss) DoMultiStream(client rueidis.Client, ctx context.Context, multi ...rueidis.Completed) rueidis.MultiRedisResultStream { + return client.DoMultiStream(ctx, multi...) +} + +// A fresh client's first load sets the marker that says it is alive before it takes the +// row's lock, on a context of the client's own. +func (s *StoreSuite) TestAFreshRoutersFirstReadAnswersWithinTheWaitWhenRedisHangsAfterAMiss() { + fresh, _ := s.storeOnRedisLineHooked(func(line redisLine) rueidishook.Hook { return freezeOnMiss{line: line} }) + + ctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) + defer cancel() + started := time.Now() + found, err := cached(ctx, fresh, cacheKey("fresh", newID()), func(context.Context) (string, error) { return "loaded", nil }) + + s.Require().NoError(err) + s.Equal("loaded", found) + s.Less(time.Since(started), 400*time.Millisecond) +} + +func (s *StoreSuite) TestAForgetWaitsOnARedisSlowerThanACachedReadWould() { + slowed, line := s.storeOnRedisLine() + name := cacheKey("slow-forget", newID()) + client := slowed.cache.Client() + s.Require().NoError(client.Do(s.ctx, client.B().Set().Key(name).Value("old").Build()).Error()) + line.slow(2 * cacheWait) + + told := slowed.forget(s.ctx, name) + + s.True(told, "the deletion was answered late, not given up on") + line.slow(0) + held, err := client.Do(s.ctx, client.B().Exists().Key(name).Build()).AsInt64() + s.Require().NoError(err) + s.Zero(held) +} diff --git a/acceleration/internal/store/request.go b/acceleration/internal/store/request.go index a14345de1a..5bb12f6256 100644 --- a/acceleration/internal/store/request.go +++ b/acceleration/internal/store/request.go @@ -715,19 +715,41 @@ func (r *Requests) CountByUser(ctx context.Context, appID, userID string) (int64 return total, nil } -// RenameUser replaces an app's end user id with replacement on every shard's requests, and in -// the changes recorded of their requests in the same statement (renamedChanges), and answers -// how many rows it rewrote. A request recorded after the statement keeps its change as it is. +// RenameUser replaces an app's end user id with replacement on every shard's requests, +// writeBatch of them per statement, and in the changes recorded of their requests in each of +// those statements (renamedChanges), and answers how many rows it rewrote. A request recorded +// after the last statement keeps its change as it is. func (r *Requests) RenameUser(ctx context.Context, appID, userID, replacement string) (int64, error) { - renamed, err := onEveryShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (sql.Result, error) { - // A data-modifying WITH runs to the end whether or not the statement reads it. - changes := renamedChanges(db, appID, "requests", userID, replacement) - return db.NewUpdate().With("changes", changes).Model((*Request)(nil)).Set("user_id = ?", replacement). - Where("customer_id = ?", appID).Where("user_id = ?", userID).Exec(ctx) + if replacement == userID { + // Nothing to rewrite, and every batch would match the rows it just wrote. + return 0, nil + } + counts, err := everyShard(ctx, r.store, func(ctx context.Context, db bun.IDB) (int64, error) { + var renamed int64 + for { + // A data-modifying WITH runs to the end whether or not the statement reads it. + changes := renamedChanges(db, appID, "requests", userID, replacement) + batch := db.NewSelect().Model((*Request)(nil)).Column("id"). + Where("customer_id = ?", appID).Where("user_id = ?", userID).Limit(writeBatch) + result, err := db.NewUpdate().With("changes", changes).Model((*Request)(nil)).Set("user_id = ?", replacement). + Where("id IN (?)", batch).Exec(ctx) + if err != nil { + return renamed, err + } + n, err := result.RowsAffected() + renamed += n + if err != nil || n < int64(writeBatch) { + return renamed, err + } + } }) if err != nil { return 0, stack.Wrap(fmt.Errorf("store: rename user requests: %w", err)) } + var renamed int64 + for _, count := range counts { + renamed += count + } return renamed, nil } diff --git a/acceleration/internal/store/request_test.go b/acceleration/internal/store/request_test.go index 7c4f4da995..9bbb8d6387 100644 --- a/acceleration/internal/store/request_test.go +++ b/acceleration/internal/store/request_test.go @@ -3,6 +3,7 @@ package store import ( + "context" "crypto/rand" "encoding/hex" "fmt" @@ -683,3 +684,48 @@ func (s *StoreSuite) TestRequestQueryBudgets() { s.Require().NoError(err) }), "VendorCostGaps") } + +func (s *StoreSuite) TestRenamingAUserWithMoreRequestsThanOneStatementTakesRenamesThemAll() { + s.inSmallBatches() + for i := range 3 { + s.Require().NoError(s.store.Requests.Insert(s.ctx, &Request{ + Modality: "stt", CustomerID: "acme", UserID: "jlahey", Provider: "deepgram", Model: "flux-general-en", + StartedAt: s.base.Add(time.Duration(i) * time.Minute), Success: true, + })) + } + + s.Require().NoError(s.store.Requests.Insert(s.ctx, &Request{ + Modality: "stt", CustomerID: "other-app", UserID: "jlahey", Provider: "deepgram", Model: "flux-general-en", StartedAt: s.base, Success: true, + })) + + var renamed int64 + var err error + updates := s.statementsLike(`WITH "changes" AS (UPDATE`, func() { renamed, err = s.store.Requests.RenameUser(s.ctx, "acme", "jlahey", "forgotten") }) + + s.Require().NoError(err) + s.EqualValues(3, renamed) + s.Equal(4+len(s.store.shards())-1, updates, "a row per statement, then the one that finds none, and one on each shard holding none") + theirs, err := s.store.Requests.CountByUser(s.ctx, "other-app", "jlahey") + s.Require().NoError(err) + s.EqualValues(1, theirs, "the same id under another app is another person") + left, err := s.store.Requests.CountByUser(s.ctx, "acme", "jlahey") + s.Require().NoError(err) + s.Zero(left) + moved, err := s.store.Requests.CountByUser(s.ctx, "acme", "forgotten") + s.Require().NoError(err) + s.EqualValues(3, moved) +} + +func (s *StoreSuite) TestRenamingAUserToTheirOwnIdRewritesNothing() { + s.inSmallBatches() + s.Require().NoError(s.store.Requests.Insert(s.ctx, &Request{ + Modality: "stt", CustomerID: "acme", UserID: "jlahey", Provider: "deepgram", Model: "flux-general-en", StartedAt: s.base, Success: true, + })) + ctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + defer cancel() + + renamed, err := s.store.Requests.RenameUser(ctx, "acme", "jlahey", "jlahey") + + s.Require().NoError(err) + s.Zero(renamed) +} diff --git a/acceleration/internal/store/store.go b/acceleration/internal/store/store.go index 6efb0f3e61..ba3a023674 100644 --- a/acceleration/internal/store/store.go +++ b/acceleration/internal/store/store.go @@ -124,6 +124,68 @@ func Open(dsn string) (*Store, error) { return OpenShards(Options{DSN: dsn}) } +// The server's own limits on what a serving connection runs. pgdriver gives up on a read +// after 10 s and drops the socket, but the server runs the statement to its end and commits +// it, so a write the caller was told failed would still land. statementTimeout ends the +// statement on the server first, and stays below the driver's read timeout for that. +// lockTimeout bounds a wait on another session's lock, and idleInTransactionTimeout how long +// a transaction whose router went quiet keeps its locks. Work that legitimately takes longer +// raises them for its own transaction (boundTransaction). +const ( + statementTimeout = 8 * time.Second + lockTimeout = 3 * time.Second + idleInTransactionTimeout = 30 * time.Second +) + +// sessionDefaults sets the limits above, and UTC as the time zone days and hours are cut in, +// on every connection, leaving any of them the DSN sets itself. +func sessionDefaults(conf *pgdriver.Config) { + defaults := map[string]any{ + "statement_timeout": fmt.Sprintf("%dms", statementTimeout.Milliseconds()), + "lock_timeout": fmt.Sprintf("%dms", lockTimeout.Milliseconds()), + "idle_in_transaction_session_timeout": fmt.Sprintf("%dms", idleInTransactionTimeout.Milliseconds()), + "timezone": "UTC", + } + // Postgres reads a parameter's name in any case, so a DSN's TimeZone is timezone here. + for name, value := range conf.ConnParams { + defaults[strings.ToLower(name)] = value + } + conf.ConnParams = defaults +} + +// boundTransaction gives the rest of tx statement, lock and idle limits of its own, for work +// known to take longer than the serving defaults allow. +func boundTransaction(ctx context.Context, tx bun.Tx, statement, lock, idle time.Duration) error { + _, err := tx.ExecContext(ctx, "SELECT set_config('statement_timeout', ?, true), set_config('lock_timeout', ?, true), "+ + "set_config('idle_in_transaction_session_timeout', ?, true)", + fmt.Sprintf("%dms", statement.Milliseconds()), fmt.Sprintf("%dms", lock.Milliseconds()), fmt.Sprintf("%dms", idle.Milliseconds())) + return err +} + +// writeBatch is how many rows one statement of a prune or a rename touches. A backlog is +// worked through in statements of this many, each well inside the statement limit: one +// statement over all of it would run out of time and roll back, every time, while the backlog +// grew. +var writeBatch = 5000 + +// deleteInBatches deletes the rows of table that where matches, writeBatch of them per +// statement, and returns how many it deleted. +func deleteInBatches(ctx context.Context, db bun.IDB, table, where string, args ...any) (int64, error) { + var deleted int64 + for { + batch := db.NewSelect().TableExpr(table).Column("ctid").Where(where, args...).Limit(writeBatch) + result, err := db.NewDelete().TableExpr(table).Where("ctid IN (?)", batch).Exec(ctx) + if err != nil { + return deleted, err + } + n, err := result.RowsAffected() + deleted += n + if err != nil || n < int64(writeBatch) { + return deleted, err + } + } +} + // connect opens a pool of at most conns connections. func connect(dsn string, conns int) (_ *bun.DB, err error) { // pgdriver panics on a DSN it cannot parse, and the panic holds the whole DSN, password @@ -133,7 +195,7 @@ func connect(dsn string, conns int) (_ *bun.DB, err error) { err = stack.Wrap(errors.New("store: the database DSN does not parse")) } }() - sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn))) + sqldb := sql.OpenDB(pgdriver.NewConnector(pgdriver.WithDSN(dsn), sessionDefaults)) // database/sql keeps two idle connections by default, so every burst of writes past two // dials Postgres and shakes hands over TLS again, and under load those handshakes are // what times out. The pool is kept instead, and bounded so that two pods, each running diff --git a/acceleration/internal/store/store_explain_test.go b/acceleration/internal/store/store_explain_test.go index 801af3fa96..15715b8445 100644 --- a/acceleration/internal/store/store_explain_test.go +++ b/acceleration/internal/store/store_explain_test.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "net/url" "regexp" "strings" "sync" @@ -40,7 +41,15 @@ func (s *StoreSuite) seededDatabase() string { return s.seededDSN } dsn := s.emptyDatabase("store_explain") - store, err := Open(dsn) + // Seeding is setup, not the store's own work: its inserts of seedRows may run past the + // serving statement limit and the driver's read timeout, which the DSN lifts for it. + parsed, err := url.Parse(dsn) + s.Require().NoError(err) + query := parsed.Query() + query.Set("statement_timeout", "0") + query.Set("read_timeout", "2m") + parsed.RawQuery = query.Encode() + store, err := Open(parsed.String()) s.Require().NoError(err) defer store.Close() s.Require().NoError(store.Migrate(s.ctx)) @@ -262,7 +271,7 @@ func (s *StoreSuite) TestEveryHotTableIsReadByIndex() { return err }}, {name: "Requests.RenameUser", index: "requests_customer_started_idx", run: func(ctx context.Context, store *Store) error { - _, err := store.Requests.RenameUser(ctx, "customer-7", "user-207", "user-207") + _, err := store.Requests.RenameUser(ctx, "customer-7", "user-207", "user-207-renamed") return err }}, {name: "Requests.Spend", index: "requests_customer_spend_idx", run: func(ctx context.Context, store *Store) error { diff --git a/acceleration/internal/store/store_test.go b/acceleration/internal/store/store_test.go index 5e5bcc3622..122ffa6c79 100644 --- a/acceleration/internal/store/store_test.go +++ b/acceleration/internal/store/store_test.go @@ -5,6 +5,9 @@ package store import ( "context" "database/sql" + "errors" + "fmt" + "net/url" "os" "strings" "sync" @@ -14,6 +17,7 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/suite" "github.com/uptrace/bun" + "github.com/uptrace/bun/driver/pgdriver" "github.com/GetStream/Vision-Agents/acceleration/internal/testenv" ) @@ -614,3 +618,124 @@ func (s *StoreSuite) TestARouterWaitingToMigrateDoesNotHoldUpTheOneMigrating() { s.FailNow("the waiting router never migrated once the lock was free") } } + +// shortLimit is the statement and idle limit of a limitedStore's connections. +const shortLimit = 300 * time.Millisecond + +// limitedDSN is dsn with a statement and idle limit of shortLimit on every connection, as a +// DSN may set them, so a test can show what outlasts the serving limits without waiting for +// them. +func (s *StoreSuite) limitedDSN(dsn string) string { + parsed, err := url.Parse(dsn) + s.Require().NoError(err) + query := parsed.Query() + limit := fmt.Sprintf("%dms", shortLimit.Milliseconds()) + query.Set("statement_timeout", limit) + query.Set("idle_in_transaction_session_timeout", limit) + parsed.RawQuery = query.Encode() + return parsed.String() +} + +// limitedStore is another router's store on the suite's databases, every connection of it +// held to shortLimit. +func (s *StoreSuite) limitedStore() *Store { + store, err := OpenShards(Options{DSN: s.limitedDSN(s.dsn), ShardDSN: s.limitedDSN(s.shardDSN)}) + s.Require().NoError(err) + s.T().Cleanup(func() { s.NoError(store.Close()) }) + return store +} + +// postgresCode is the SQLSTATE Postgres answered err with, empty for an error of another kind. +func postgresCode(err error) string { + var refused pgdriver.Error + if errors.As(err, &refused) { + return refused.Field('C') + } + return "" +} + +func (s *StoreSuite) TestAStatementPastTheLimitIsEndedOnTheServer() { + started := time.Now() + _, err := s.store.GlobalDB().ExecContext(s.ctx, "SELECT pg_sleep(20)") + took := time.Since(started) + + s.Equal("57014", postgresCode(err), "the server cancelled it, not the driver: %v", err) + s.InDelta(8, took.Seconds(), 1) + var running int + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, ` +SELECT count(*) FROM pg_stat_activity +WHERE datname = current_database() AND state = 'active' AND query LIKE '%pg_sleep(20)%' AND pid <> pg_backend_pid()`).Scan(&running)) + s.Zero(running, "nothing is left running on the server") +} + +func (s *StoreSuite) TestAWaitOnAnotherSessionsLockIsEnded() { + config := s.boundConfig("app") + holder, err := s.store.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer holder.Rollback() //nolint:errcheck // only ever holds the lock + _, err = holder.ExecContext(s.ctx, "SELECT 1 FROM agent_configs WHERE id = ? FOR UPDATE", config.ID) + s.Require().NoError(err) + + started := time.Now() + _, err = s.store.GlobalDB().ExecContext(s.ctx, "UPDATE agent_configs SET name = name WHERE id = ?", config.ID) + + s.Equal("55P03", postgresCode(err), "the wait was ended as a lock timeout: %v", err) + s.InDelta(3, time.Since(started).Seconds(), 1) +} + +func (s *StoreSuite) TestAServingConnectionBoundsAnIdleTransaction() { + var limit string + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SHOW idle_in_transaction_session_timeout").Scan(&limit)) + s.Equal("30s", limit) +} + +func (s *StoreSuite) TestDaysAreCutInUTCWhateverTheDatabaseSays() { + var database string + s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx, "SELECT current_database()").Scan(&database)) + _, err := s.store.GlobalDB().ExecContext(s.ctx, "ALTER DATABASE ? SET timezone = 'Pacific/Kiritimati'", bun.Ident(database)) + s.Require().NoError(err) + s.T().Cleanup(func() { + _, err := s.store.GlobalDB().ExecContext(s.ctx, "ALTER DATABASE ? RESET timezone", bun.Ident(database)) + s.NoError(err) + }) + fresh, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN}) + s.Require().NoError(err) + defer fresh.Close() + // One in the morning in UTC is the afternoon of the same day at UTC+14, whose day began + // the evening before in UTC. + morning := time.Date(2026, 3, 1, 1, 0, 0, 0, time.UTC) + s.opened("one", "acme", morning, nil) + + buckets, err := fresh.CustomerActivity(s.ctx, "acme", ActivityDaily, morning.Add(-48*time.Hour), morning.Add(48*time.Hour)) + + s.Require().NoError(err) + s.Require().Len(buckets, 1) + s.Equal(time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), buckets[0].Bucket.UTC()) +} + +func (s *StoreSuite) TestALimitTheDSNSetsIsKeptOverTheDefault() { + limited := s.limitedStore() + tx, err := limited.GlobalDB().BeginTx(s.ctx, nil) + s.Require().NoError(err) + defer tx.Rollback() //nolint:errcheck // ended by the server + _, err = tx.ExecContext(s.ctx, "SELECT 1") + s.Require().NoError(err) + + time.Sleep(3 * shortLimit) + _, err = tx.ExecContext(s.ctx, "SELECT 1") + + s.Error(err, "the transaction was ended at the DSN's idle limit, not the default's") + _ = tx.Rollback() + for range 3 { + _, err := limited.GlobalDB().ExecContext(s.ctx, "SELECT 1") + s.Require().NoError(err, "the pool hands out no connection the server ended") + } +} + +// inSmallBatches makes every batched prune and rename take one row per statement for the +// test, so a backlog of a few rows is more than one statement's worth. +func (s *StoreSuite) inSmallBatches() { + kept := writeBatch + writeBatch = 1 + s.T().Cleanup(func() { writeBatch = kept }) +} diff --git a/acceleration/internal/store/store_unit_test.go b/acceleration/internal/store/store_unit_test.go index 8bf4bf17a4..418f10811b 100644 --- a/acceleration/internal/store/store_unit_test.go +++ b/acceleration/internal/store/store_unit_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/stretchr/testify/require" + "github.com/uptrace/bun/driver/pgdriver" ) // The error goes to the logs, past their redaction, so it must not carry the DSN's password. @@ -13,3 +14,16 @@ func TestADSNThatDoesNotParseIsRefusedWithoutItsPassword(t *testing.T) { require.Error(t, err) require.NotContains(t, err.Error(), "s3cret") } + +func TestADSNsParameterWinsWhateverTheCaseItIsWrittenIn(t *testing.T) { + conf := pgdriver.Config{ConnParams: map[string]any{"TimeZone": "Europe/Lisbon", "Statement_Timeout": "1s"}} + + sessionDefaults(&conf) + + require.Equal(t, map[string]any{ + "statement_timeout": "1s", + "lock_timeout": "3000ms", + "idle_in_transaction_session_timeout": "30000ms", + "timezone": "Europe/Lisbon", + }, conf.ConnParams) +} diff --git a/acceleration/internal/store/stream_trunk.go b/acceleration/internal/store/stream_trunk.go index e4254c9200..0f1c0628a0 100644 --- a/acceleration/internal/store/stream_trunk.go +++ b/acceleration/internal/store/stream_trunk.go @@ -78,6 +78,10 @@ type TrunkGroupTx struct { // the same text. const trunkGroupLockSeed = 0 +// trunkGroupIdle is how long a trunk group's transaction may sit idle: longer than one call +// to Stream's API, which its client gives up on after 30 s. +const trunkGroupIdle = time.Minute + // Get returns one of a customer's Stream trunks by Stream's id. func (r *StreamTrunks) Get(ctx context.Context, customerID, id string) (StreamTrunk, error) { var trunk StreamTrunk @@ -102,6 +106,13 @@ func (r *StreamTrunks) InGroup(ctx context.Context, group TrunkGroup, fn func(ct } key := "stream_trunks:" + group.CustomerID + ":" + strconv.FormatInt(group.StreamAppPK, 10) + ":" + group.Vendor return r.store.global.RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error { + // fn calls Stream between its statements, each call allowed as long as the serving + // idle limit, so the transaction gets an idle limit that outlasts one. Another router + // joining the group waits on the lock while those calls run: its wait is ended by the + // statement limit rather than the serving lock limit, which is shorter than one call. + if err := boundTransaction(ctx, tx, statementTimeout, trunkGroupIdle, trunkGroupIdle); err != nil { + return stack.Wrap(fmt.Errorf("store: trunk group: %w", err)) + } if err := lockUntilCommit(ctx, tx, key, trunkGroupLockSeed); err != nil { return stack.Wrap(fmt.Errorf("store: lock trunk group: %w", err)) } diff --git a/acceleration/internal/store/stream_trunk_test.go b/acceleration/internal/store/stream_trunk_test.go index df418cf7b7..a23c380910 100644 --- a/acceleration/internal/store/stream_trunk_test.go +++ b/acceleration/internal/store/stream_trunk_test.go @@ -397,9 +397,10 @@ func (s *StoreSuite) TestStreamTrunkQueryBudgets() { _, err := s.store.StreamTrunks.Get(s.ctx, "acme", "trunk-0") s.Require().NoError(err) }), "Get") - // InGroup is a transaction, BEGIN to COMMIT, that takes the group's lock first. + // InGroup is a transaction, BEGIN to COMMIT, that sets its idle limit and takes the group's + // lock first. in := func(name string, budget int, fn func(tx *TrunkGroupTx) error) { - s.Equal(3+budget, s.countQueries(func() { + s.Equal(4+budget, s.countQueries(func() { s.Require().NoError(s.store.StreamTrunks.InGroup(s.ctx, group, func(_ context.Context, tx *TrunkGroupTx) error { return fn(tx) })) @@ -430,3 +431,95 @@ func (s *StoreSuite) TestStreamTrunkQueryBudgets() { in("DeleteTrunk", 1, func(tx *TrunkGroupTx) error { return tx.DeleteTrunk("trunk-3") }) in("ReleaseNumber", 1, func(tx *TrunkGroupTx) error { return tx.ReleaseNumber("+15125550199", s.base) }) } + +func (s *StoreSuite) TestATrunkGroupOutlastsTheIdleLimitOfAServingTransaction() { + limited := s.limitedStore() + group := TrunkGroup{CustomerID: "acme", StreamAppPK: 7, Vendor: "twilio"} + + err := limited.StreamTrunks.InGroup(s.ctx, group, func(_ context.Context, tx *TrunkGroupTx) error { + if _, err := tx.Trunks(); err != nil { + return err + } + // A call to Stream slower than the limit, between two of the group's statements. + time.Sleep(3 * shortLimit) + return tx.SaveTrunk(StreamTrunk{ID: "trunk-1", BridgeURI: "sip:trunk-1@sip.example.test"}) + }) + + s.Require().NoError(err) + s.Equal([]string{"trunk-1"}, s.trunkIDs(group)) +} + +func (s *StoreSuite) TestAnotherRoutersTrunkGroupWaitsForTheOneHoldingIt() { + group := TrunkGroup{CustomerID: "acme", StreamAppPK: 7, Vendor: "twilio"} + other, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN}) + s.Require().NoError(err) + defer other.Close() + holding := make(chan struct{}) + held := make(chan error, 1) + go func() { + held <- s.store.StreamTrunks.InGroup(s.ctx, group, func(context.Context, *TrunkGroupTx) error { + close(holding) + // Longer than the serving lock limit, as a call to Stream can take. + time.Sleep(4 * time.Second) + return nil + }) + }() + <-holding + + err = other.StreamTrunks.InGroup(s.ctx, group, func(_ context.Context, tx *TrunkGroupTx) error { + return tx.SaveTrunk(StreamTrunk{ID: "trunk-1", BridgeURI: "sip:trunk-1@sip.example.test"}) + }) + + s.Require().NoError(err, "the second router waited for the group") + s.Require().NoError(<-held) + s.Equal([]string{"trunk-1"}, s.trunkIDs(group)) +} + +func (s *StoreSuite) TestATrunkGroupLeavesItsConnectionWithTheServingLimits() { + single, err := OpenShards(Options{DSN: s.dsn, ShardDSN: s.shardDSN}) + s.Require().NoError(err) + defer single.Close() + single.GlobalDB().SetMaxOpenConns(1) + s.Require().NoError(single.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", Vendor: "twilio"}, + func(context.Context, *TrunkGroupTx) error { return nil })) + + var statement, lock, idle string + s.Require().NoError(single.GlobalDB().QueryRowContext(s.ctx, + "SELECT current_setting('statement_timeout'), current_setting('lock_timeout'), current_setting('idle_in_transaction_session_timeout')"). + Scan(&statement, &lock, &idle)) + s.Equal([]string{"8s", "3s", "30s"}, []string{statement, lock, idle}, "the group's own limits ended with its transaction") +} + +func (s *StoreSuite) TestAWriteToANumberATrunkGroupHoldsWaitsForTheGroup() { + group := TrunkGroup{CustomerID: "acme", Vendor: "twilio"} + s.Require().NoError(s.store.PhoneNumbers.Insert(s.ctx, &PhoneNumber{ + E164: "+15125551234", Vendor: group.Vendor, Country: "US", CustomerID: group.CustomerID, PurchasedAt: s.base, + })) + holding := make(chan struct{}) + held := make(chan error, 1) + go func() { + held <- s.store.StreamTrunks.InGroup(s.ctx, group, func(_ context.Context, tx *TrunkGroupTx) error { + if _, err := tx.Number("+15125551234"); err != nil { + return err + } + close(holding) + // Longer than the serving lock limit, as a call to Stream can take. + time.Sleep(4 * time.Second) + return nil + }) + }() + <-holding + + err := s.store.PhoneNumbers.ClearAgent(s.ctx, "acme", "+15125551234") + + s.Require().NoError(err, "the write waited for the group") + s.Require().NoError(<-held) +} + +func (s *StoreSuite) TestATrunkGroupRunsWithTheGroupsLimits() { + var lock, idle string + s.Require().NoError(s.store.StreamTrunks.InGroup(s.ctx, TrunkGroup{CustomerID: "acme", Vendor: "twilio"}, func(ctx context.Context, tx *TrunkGroupTx) error { + return tx.tx.QueryRowContext(ctx, "SELECT current_setting('lock_timeout'), current_setting('idle_in_transaction_session_timeout')").Scan(&lock, &idle) + })) + s.Equal([]string{"1min", "1min"}, []string{lock, idle}) +} diff --git a/acceleration/internal/store/user.go b/acceleration/internal/store/user.go index 2d1add9e1a..41e968a528 100644 --- a/acceleration/internal/store/user.go +++ b/acceleration/internal/store/user.go @@ -116,8 +116,10 @@ func (r *Users) record(ctx context.Context, customerID, userID, sighting string) // Read through the client-side cache, which is what puts the key under Redis's // tracking: a later claim deleting it drops this entry on every replica holding // one. A Redis that cannot be reached is a slow deployment and not a broken one, - // so the answer there is the same as a miss. - found, err := redis.DoCache(ctx, redis.B().Get().Key(name).Cache(), userTTL).ToString() + // so the answer there is the same as a miss, within cacheWait. + read, cancel := context.WithTimeout(ctx, cacheWait) + found, err := redis.DoCache(read, redis.B().Get().Key(name).Cache(), userTTL).ToString() + cancel() switch { case err == nil && found != "" && settles(found, sighting): r.seen.Keep(customerID, userID, found, time.Time{}) @@ -143,7 +145,10 @@ func (r *Users) record(ctx context.Context, customerID, userID, sighting string) if redis != nil { set := redis.B().Set().Key(name).Value(sighting).Ex(userTTL).Build() - if err := redis.Do(ctx, set).Error(); err != nil { + write, cancel := context.WithTimeout(ctx, cacheWait) + err := redis.Do(write, set).Error() + cancel() + if err != nil { slog.Default().Error("could not cache a user in redis", "customer", customerID, "user", userID, "error", err) }