Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .claude/skills/go/store.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<family>:{<customer>}:...`
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`,
Expand All @@ -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

Expand Down
5 changes: 2 additions & 3 deletions acceleration/internal/store/activity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
20 changes: 20 additions & 0 deletions acceleration/internal/store/activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
36 changes: 28 additions & 8 deletions acceleration/internal/store/bucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions acceleration/internal/store/bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions acceleration/internal/store/budget_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }

Expand Down
4 changes: 4 additions & 0 deletions acceleration/internal/store/campaign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 3 additions & 6 deletions acceleration/internal/store/channel_inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
7 changes: 7 additions & 0 deletions acceleration/internal/store/channel_inbound_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
9 changes: 3 additions & 6 deletions acceleration/internal/store/chat_inbound.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
7 changes: 7 additions & 0 deletions acceleration/internal/store/chat_inbound_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
50 changes: 40 additions & 10 deletions acceleration/internal/store/datamove.go
Original file line number Diff line number Diff line change
Expand Up @@ -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, `
Expand All @@ -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.
Expand Down Expand Up @@ -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.
//
Expand All @@ -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")
Expand All @@ -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,
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -2082,24 +2100,36 @@ 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
FROM (SELECT customer_id, MAX(seq) AS seq FROM pruned GROUP BY customer_id) AS p
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
Expand Down
Loading
Loading