Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(realtime): bounded replay window for ShardedStreamRelay on restart (#4875)
MeloMeie3e3e7e23ff6
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 242565cbde..f4d4a55143 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -67,6 +67,7 @@ func shardedRelayConfigFromEnv() realtime.ShardedStreamRelayConfig {cfg.StreamMaxLen = envPositiveInt64("REALTIME_RELAY_STREAM_MAXLEN", cfg.StreamMaxLen)cfg.ReadCount = envPositiveInt64("REALTIME_RELAY_XREAD_COUNT", cfg.ReadCount)cfg.ReadBlock = envDuration("REALTIME_RELAY_XREAD_BLOCK", cfg.ReadBlock)+ cfg.ReplayGrace = envDuration("REALTIME_RELAY_REPLAY_GRACE", cfg.ReplayGrace)return cfg}diff --git a/server/go.mod b/server/go.modindex 9010fe5eb8..997d8f8d75 100644--- a/server/go.mod+++ b/server/go.mod@@ -10,6 +10,7 @@ require (github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.41.5github.com/go-chi/chi/v5 v5.2.5github.com/go-chi/cors v1.2.2+ github.com/go-redis/redismock/v9 v9.2.0github.com/go-resty/resty/v2 v2.17.2github.com/golang-jwt/jwt/v5 v5.3.1github.com/google/uuid v1.6.0diff --git a/server/go.sum b/server/go.sumindex cbef7161ac..2d40a2ebc5 100644--- a/server/go.sum+++ b/server/go.sum@@ -53,10 +53,14 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97cgithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=+github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=+github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=+github.com/go-redis/redismock/v9 v9.2.0 h1:ZrMYQeKPECZPjOj5u9eyOjg8Nnb0BS9lkVIZ6IpsKLw=+github.com/go-redis/redismock/v9 v9.2.0/go.mod h1:18KHfGDK4Y6c2R0H38EUGWAdc7ZQS9gfYxc94k7rWT0=github.com/go-resty/resty/v2 v2.17.2 h1:FQW5oHYcIlkCNrMD2lloGScxcHJ0gkjshV3qcQAyHQk=github.com/go-resty/resty/v2 v2.17.2/go.mod h1:kCKZ3wWmwJaNc7S29BRtUhJwy7iqmn+2mLtQrOyQlVA=github.com/go-test/deep v1.1.1 h1:0r/53hagsehfO4bzD2Pgr/+RgHqhmf+k1Bpse2cTu1U=@@ -95,8 +99,14 @@ github.com/mattn/go-shellwords v1.0.13 h1:DC0OMEpGjm6LfNFU4ckYcvbQKyp2vE8atyFGXNgithub.com/mattn/go-shellwords v1.0.13/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=+github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=+github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=github.com/oklog/ulid/v2 v2.1.1 h1:suPZ4ARWLOJLegGFiZZ1dFAkqzhMjL3J1TzI+5wHz8s=github.com/oklog/ulid/v2 v2.1.1/go.mod h1:rcEKHmBBKfef9DhnvX7y1HZBYxjXb0cP5ExxNsTT1QQ=+github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=+github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=+github.com/onsi/gomega v1.25.0 h1:Vw7br2PCDYijJHSfBOWhov+8cAnUf8MfMaIOV323l6Y=+github.com/onsi/gomega v1.25.0/go.mod h1:r+zV744Re+DiYCIPRlYOTxn0YkOLcAnW8k1xXdMPGhM=github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM=github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=@@ -154,6 +164,8 @@ google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=+gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=diff --git a/server/internal/realtime/sharded_stream_relay.go b/server/internal/realtime/sharded_stream_relay.goindex 04c3da722c..89c5c47be7 100644--- a/server/internal/realtime/sharded_stream_relay.go+++ b/server/internal/realtime/sharded_stream_relay.go@@ -18,6 +18,7 @@ const (defaultShardedRelayStreamMaxLen = 100000defaultShardedRelayReadCount = 128defaultShardedRelayReadBlock = 5 * time.Second+ defaultShardedRelayReplayGrace = 5 * time.Minute)// ShardedStreamKey returns the Redis Stream key used by a fixed relay shard.@@ -31,6 +32,11 @@ type ShardedStreamRelayConfig struct {StreamMaxLen int64ReadCount int64ReadBlock time.Duration+ // ReplayGrace is the lookback window on startup: the shard reader starts+ // consuming from (now - ReplayGrace) rather than "$" so that any events+ // published while this pod was down are replayed. Events are bounded by+ // the stream's MAXLEN, and downstream consumers must be idempotent.+ ReplayGrace time.Duration}// DefaultShardedStreamRelayConfig returns production-safe defaults: a small@@ -42,6 +48,7 @@ func DefaultShardedStreamRelayConfig() ShardedStreamRelayConfig {StreamMaxLen: defaultShardedRelayStreamMaxLen,ReadCount: defaultShardedRelayReadCount,ReadBlock: defaultShardedRelayReadBlock,+ ReplayGrace: defaultShardedRelayReplayGrace,}}@@ -59,6 +66,9 @@ func (c ShardedStreamRelayConfig) withDefaults() ShardedStreamRelayConfig {if c.ReadBlock <= 0 {c.ReadBlock = def.ReadBlock}+ if c.ReplayGrace <= 0 {+ c.ReplayGrace = def.ReplayGrace+ }return c}@@ -193,45 +203,70 @@ func (r *ShardedStreamRelay) shardFor(scopeType, scopeID string) int {return int(h.Sum32() % uint32(r.config.Shards))}+// replayStartID returns a Redis stream ID anchored to (now - ReplayGrace) so+// that a freshly started shard reader replays only the recent grace window+// rather than the entire retained stream. The "-0" suffix matches any+// sequence number at that millisecond.+func (r *ShardedStreamRelay) replayStartID() string {+ ms := time.Now().Add(-r.config.ReplayGrace).UnixMilli()+ if ms < 0 {+ ms = 0+ }+ return fmt.Sprintf("%d-0", ms)+}+func (r *ShardedStreamRelay) readShard(ctx context.Context, shard int) {stream := ShardedStreamKey(shard)- lastID := "$"+ // Start from a bounded lookback window, not "$", so that events+ // published while this pod was down are replayed. The grace window is+ // short enough that replay volume stays manageable, and downstream+ // consumers (daemon wakeups, client reconnects) are idempotent.+ lastID := r.replayStartID()for {if ctx.Err() != nil || r.isStopping() {return}-- readCtx, cancel := context.WithTimeout(ctx, r.config.ReadBlock+time.Second)- res, err := r.readRDB.XRead(readCtx, &redis.XReadArgs{- Streams: []string{stream, lastID},- Count: r.config.ReadCount,- Block: r.config.ReadBlock,- }).Result()- cancel()-- if errors.Is(err, redis.Nil) || (err != nil && (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled))) {- continue+ if !r.readShardOnce(ctx, shard, stream, &lastID) {+ return}- if err != nil {- M.RedisXReadErrors.Add(1)- M.SetRedisLastError(err.Error())- slog.Warn("realtime/sharded-redis: XREAD failed", "error", err, "shard", shard, "stream", stream)- select {- case <-ctx.Done():- return- case <-time.After(time.Second):- }- continue+ }+}++// readShardOnce performs a single XREAD iteration for one shard. It returns+// true when the caller should continue reading, false when the context is+// done and the loop should exit. lastID is advanced past any messages read.+func (r *ShardedStreamRelay) readShardOnce(ctx context.Context, shard int, stream string, lastID *string) bool {+ readCtx, cancel := context.WithTimeout(ctx, r.config.ReadBlock+time.Second)+ res, err := r.readRDB.XRead(readCtx, &redis.XReadArgs{+ Streams: []string{stream, *lastID},+ Count: r.config.ReadCount,+ Block: r.config.ReadBlock,+ }).Result()+ cancel()++ if errors.Is(err, redis.Nil) || (err != nil && (errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled))) {+ return true+ }+ if err != nil {+ M.RedisXReadErrors.Add(1)+ M.SetRedisLastError(err.Error())+ slog.Warn("realtime/sharded-redis: XREAD failed", "error", err, "shard", shard, "stream", stream)+ select {+ case <-ctx.Done():+ return false+ case <-time.After(time.Second):}+ return true+ }- for _, s := range res {- for _, msg := range s.Messages {- lastID = msg.ID- M.RedisXReadTotal.Add(1)- r.deliverMessage(msg)- }+ for _, s := range res {+ for _, msg := range s.Messages {+ *lastID = msg.ID+ M.RedisXReadTotal.Add(1)+ r.deliverMessage(msg)}}+ return true}func (r *ShardedStreamRelay) deliverMessage(msg redis.XMessage) {diff --git a/server/internal/realtime/sharded_stream_relay_test.go b/server/internal/realtime/sharded_stream_relay_test.goindex 65fb17e4a1..1781557df0 100644--- a/server/internal/realtime/sharded_stream_relay_test.go+++ b/server/internal/realtime/sharded_stream_relay_test.go@@ -1,10 +1,13 @@package realtimeimport (+ "context""encoding/json"+ "fmt""testing""time"+ redismock "github.com/go-redis/redismock/v9""github.com/redis/go-redis/v9")@@ -23,6 +26,9 @@ func TestShardedStreamRelayConfigDefaults(t *testing.T) {if relay.config.ReadBlock != defaultShardedRelayReadBlock {t.Fatalf("expected default read block %s, got %s", defaultShardedRelayReadBlock, relay.config.ReadBlock)}+ if relay.config.ReplayGrace != defaultShardedRelayReplayGrace {+ t.Fatalf("expected default replay grace %s, got %s", defaultShardedRelayReplayGrace, relay.config.ReplayGrace)+ }}func TestShardedStreamRelayShardForScopeIsStableAndBounded(t *testing.T) {@@ -71,3 +77,92 @@ func TestShardedStreamRelayDeliverMessageUsesEnvelopeScope(t *testing.T) {case <-time.After(20 * time.Millisecond):}}++func TestShardedStreamRelayReplayStartIDIsBounded(t *testing.T) {+ grace := 5 * time.Minute+ relay := NewShardedStreamRelay(NewHub(), nil, nil, ShardedStreamRelayConfig{+ ReplayGrace: grace,+ })++ before := time.Now().Add(-grace).UnixMilli()+ id := relay.replayStartID()+ after := time.Now().Add(-grace).UnixMilli()++ // The ID should be in the format "<millis>-0".+ var ms int64+ var seq int+ n, _ := fmt.Sscanf(id, "%d-%d", &ms, &seq)+ if n != 2 {+ t.Fatalf("replayStartID() = %q, want format <millis>-0", id)+ }+ if seq != 0 {+ t.Fatalf("replayStartID() sequence = %d, want 0", seq)+ }+ // The timestamp should be within [before, after] (inclusive).+ if ms < before || ms > after {+ t.Fatalf("replayStartID() timestamp %d outside expected window [%d, %d]", ms, before, after)+ }+}++func TestShardedStreamRelayReadShardOnceReplaysRetainedMessages(t *testing.T) {+ hub := NewHub()+ client := attachRealtimeTestClient(hub, ScopeTask, "task-replay")+ rdb, mock := redismock.NewClientMock()+ t.Cleanup(func() { _ = rdb.Close() })++ grace := 5 * time.Minute+ relay := NewShardedStreamRelay(hub, rdb, rdb, ShardedStreamRelayConfig{+ Shards: 1,+ ReadCount: 2,+ ReadBlock: time.Millisecond,+ ReplayGrace: grace,+ })+ stream := ShardedStreamKey(0)++ // The initial cursor must be a bounded time-window, not "$".+ lastID := relay.replayStartID()+ if lastID == "$" {+ t.Fatal("replayStartID() returned \"$\", want a bounded time-window cursor")+ }++ // Expect an XREAD starting from the bounded cursor (not "$").+ mock.ExpectXRead(&redis.XReadArgs{+ Streams: []string{stream, lastID},+ Count: relay.config.ReadCount,+ Block: relay.config.ReadBlock,+ }).SetVal([]redis.XStream{{+ Stream: stream,+ Messages: []redis.XMessage{{+ ID: "1710000000000-0",+ Values: envelopeRedisValues(envelope{+ EventID: "event-replayed",+ Scope: ScopeTask,+ ScopeID: "task-replay",+ PayloadJSON: `{"type":"task:updated"}`,+ }),+ }},+ }})++ if !relay.readShardOnce(context.Background(), 0, stream, &lastID) {+ t.Fatal("expected shard reader to continue after a successful replay read")+ }+ if lastID != "1710000000000-0" {+ t.Fatalf("expected last ID to advance to %q, got %q", "1710000000000-0", lastID)+ }++ select {+ case raw := <-client.send:+ var frame map[string]any+ if err := json.Unmarshal(raw, &frame); err != nil {+ t.Fatalf("delivered frame is not JSON: %v", err)+ }+ if frame["event_id"] != "event-replayed" {+ t.Fatalf("expected replayed event_id %q, got %v", "event-replayed", frame["event_id"])+ }+ case <-time.After(time.Second):+ t.Fatal("expected retained stream message to be delivered on replay")+ }+ if err := mock.ExpectationsWereMet(); err != nil {+ t.Fatal(err)+ }+}