From 645bb531a1209f4f6e0e7ac2753efa41b20d72f4 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 15:26:18 +0000 Subject: [PATCH 1/4] fix(api): a message waits one second at most for the node directory --- acceleration/internal/api/forward_test.go | 46 +++++++++++++++++++- acceleration/internal/api/messagehooks.go | 5 +++ acceleration/internal/api/redisproxy_test.go | 22 +++++++++- acceleration/internal/node/directory_test.go | 11 +++++ 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 1fac998f7a..8e0377e57e 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -250,6 +250,45 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereWhenTh settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") } +// The same when Redis hangs rather than fails: the message is not held up by it. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTimeWhenTheDirectoryHangs() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + proxy, redis := newRedisProxy(s.T()) + unread, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), + func(options *Options) { options.Directory = s.directoryOver(redis, "here") }) + unread.Client().Timeout = 10 * time.Second + s.serverClient.on(unread).createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + proxy.hung.Store(true) + + started := time.Now() + s.Require().Equal(http.StatusOK, s.signedlyOn(unread, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Less(time.Since(started), 2*time.Second) + s.Require().Eventually(func() bool { return s.wasAsked(written) }, + settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") +} + +// A directory that is slow to answer is waited for: the other customer's session it names still +// keeps the one here from answering. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredByNeitherThoughTheDirectoryIsSlow() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() + proxy, redis := newRedisProxy(s.T()) + slow, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), + func(options *Options) { options.Directory = s.directoryOver(redis, "here") }) + s.directoryOver(redis, "elsewhere").Hold(s.T().Context(), "another-customer", 0, s.utils.uuid(), channel, "") + s.serverClient.on(slow).createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + proxy.lag.Store(int64(300 * time.Millisecond)) + + s.Require().Equal(http.StatusOK, s.signedlyOn(slow, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Never(func() bool { return s.wasAsked(written) }, time.Second, 10*time.Millisecond, + "the session where the message landed answered before the directory did") +} + // A channel stamped with its customer is answered in the hook's app: that customer's session // writing as the agent in another app is not where the message goes, and with nothing of theirs // running in this app, their worker here is handed it. @@ -366,8 +405,13 @@ func (s *RouterSuite) unreadableDirectory() *node.Directory { redis, err := redisready.NewClient(rueidis.ClientOption{InitAddress: []string{s.redisAddr}, DisableCache: true}) s.Require().NoError(err) redis.Close() + return s.directoryOver(redis, "unreadable") +} + +// directoryOver is a node's directory over a Redis connection of the test's own, at address. +func (s *RouterSuite) directoryOver(redis rueidis.Client, address string) *node.Directory { directory, err := node.NewDirectory(node.DirectoryOptions{ - Redis: redis, Address: "unreadable", Prefix: s.relayPrefix, Logger: slog.New(slog.DiscardHandler), + Redis: redis, Address: address, Prefix: s.relayPrefix, Logger: slog.New(slog.DiscardHandler), }) s.Require().NoError(err) s.T().Cleanup(directory.Close) diff --git a/acceleration/internal/api/messagehooks.go b/acceleration/internal/api/messagehooks.go index 81503fa2cd..09be2b67e1 100644 --- a/acceleration/internal/api/messagehooks.go +++ b/acceleration/internal/api/messagehooks.go @@ -603,6 +603,9 @@ func (s *Server) liveSessionOn(ctx context.Context, origin hookOrigin, event mes return found, running, nil } +// directoryTimeout bounds asking which nodes write as an agent: the message waits for the answer. +const directoryTimeout = time.Second + // writesElsewhere reports whether the directory says a session admits takes, by its customer and // Stream app, writes as an agent on any node. A directory that cannot be read says none does, as // forwardedMessage answers here when it cannot find the node answering. @@ -610,6 +613,8 @@ func (s *Server) writesElsewhere(ctx context.Context, agentID string, admits fun if s.directory == nil { return false } + ctx, cancel := context.WithTimeout(ctx, directoryTimeout) + defer cancel() nodes, err := s.directory.NodesByAgent(ctx, agentID, admits) if err != nil { s.logger.Warn("could not find out which nodes write as an agent", "agent", agentID, "error", err) diff --git a/acceleration/internal/api/redisproxy_test.go b/acceleration/internal/api/redisproxy_test.go index ecc7d1a062..e5d74f9e58 100644 --- a/acceleration/internal/api/redisproxy_test.go +++ b/acceleration/internal/api/redisproxy_test.go @@ -10,6 +10,7 @@ import ( "sync" "sync/atomic" "testing" + "time" "github.com/redis/rueidis" "github.com/stretchr/testify/require" @@ -21,7 +22,10 @@ import ( // redisProxy is the suites' Redis behind a TCP proxy a test can take down: down, every // connection through it is closed and new ones are refused, as a Redis that went away. type redisProxy struct { - down atomic.Bool + down atomic.Bool + // hung drops every answer, as a Redis that is paused; lag holds each back that long. + hung atomic.Bool + lag atomic.Int64 mu sync.Mutex conns []net.Conn } @@ -58,7 +62,7 @@ func newRedisProxy(t *testing.T) (*redisProxy, rueidis.Client) { p.conns = append(p.conns, conn, upstream) p.mu.Unlock() go func() { _, _ = io.Copy(upstream, conn); _ = upstream.Close() }() - go func() { _, _ = io.Copy(conn, upstream); _ = conn.Close() }() + go func() { _, _ = io.Copy(proxiedAnswers{conn, p}, upstream); _ = conn.Close() }() } }() options, err := rueidis.ParseURL("redis://" + listener.Addr().String() + "/" + strconv.Itoa(usagetest.RedisDB)) @@ -70,6 +74,20 @@ func newRedisProxy(t *testing.T) (*redisProxy, rueidis.Client) { return p, client } +// proxiedAnswers is a connection's answers from Redis, as hung and lag have them. +type proxiedAnswers struct { + net.Conn + proxy *redisProxy +} + +func (a proxiedAnswers) Write(answer []byte) (int, error) { + time.Sleep(time.Duration(a.proxy.lag.Load())) + if a.proxy.hung.Load() { + return len(answer), nil + } + return a.Conn.Write(answer) +} + // stop takes Redis away: every connection through the proxy is closed, and every one after, // until down is cleared. func (p *redisProxy) stop() { diff --git a/acceleration/internal/node/directory_test.go b/acceleration/internal/node/directory_test.go index 89650274d4..673379dc6b 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -207,6 +207,17 @@ func (s *DirectorySuite) TestAClaimOnAnAgentByItsCustomerAloneIsFoundNowhere() { s.Empty(writing) } +// A renewal says a claim on an agent in its session's app again, not in the deployment's. +func (s *DirectorySuite) TestARenewedClaimOnAnAgentIsInItsSessionsApp() { + directory := s.directoryAt("node-a:1") + directory.Hold(s.ctx, "acme", 7, "s1", "support", "") + s.Require().NoError(s.client.Do(s.ctx, s.client.B().Del().Key(s.prefix+":writing-as-in:support").Build()).Error()) + + directory.renewAll(s.ctx) + + s.Equal("node-a:1", s.writingAs(s.directoryAt("node-c:1"), "acme", 7, "support")) +} + // A router of the release before reads a claim on an agent by its customer alone. func (s *DirectorySuite) TestASessionWritingAsAnAgentIsFoundByItsCustomerAlone() { s.directoryAt("node-a:1").Hold(s.ctx, "acme", 7, "s1", "support", "") From 9ca2ab7b81df691eb124e6e7001316e2e5f63817 Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 16:28:02 +0000 Subject: [PATCH 2/4] fix(api): the node directory's limit holds while another caller dials Redis --- acceleration/internal/api/forward_test.go | 58 ++++++++++++++++++++++- acceleration/internal/api/messagehooks.go | 25 ++++++++-- 2 files changed, 78 insertions(+), 5 deletions(-) diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 8e0377e57e..c3e5725c64 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -3,11 +3,14 @@ package api import ( + "context" "fmt" "log/slog" "net/http" "net/http/httptest" "net/url" + "strings" + "sync" "testing" "time" @@ -270,6 +273,59 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTime settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") } +// The same while the node's renewals and its other reads of the directory, which have no limit, +// dial the connection the read waits for. +func (s *ForwardedSessionSuite) TestMessagesNamingNoCustomerAreAnsweredHereInTimeWhileOthersDialTheHungDirectory() { + channel := "chat-" + s.utils.uuid() + proxy, redis := newRedisProxy(s.T()) + directory := s.directoryOver(redis, "here") + unread, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), + func(options *Options) { options.Directory = directory }) + unread.Client().Timeout = 10 * time.Second + s.serverClient.on(unread).createSession(CreateSessionRequest{ + AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), + }) + // Held, so the directory has something to renew. + directory.Hold(s.T().Context(), "another-customer", 0, s.utils.uuid(), "", "") + proxy.hung.Store(true) + + reading, stop := context.WithCancel(s.T().Context()) + var others, messages sync.WaitGroup + others.Go(func() { + for reading.Err() == nil { + others.Go(func() { _, _ = directory.Node(reading, "another-customer", "no-session") }) + select { + case <-reading.Done(): + case <-time.After(3 * time.Second): + } + } + }) + target, err := url.Parse(unread.URL + "/v1/chat/hooks/stream") + s.Require().NoError(err) + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + for i := range 40 { + body := strings.Replace(writtenTo(channel, `{}`, "is anybody there?"), + "message-"+channel, fmt.Sprintf("message-%d-%s", i, channel), 1) + request := s.request(target.Path, body, sign(body, suiteStreamSecret)) + request.URL, request.Host = target, target.Host + messages.Go(func() { + started := time.Now() + response, err := unread.Client().Do(request) + took := time.Since(started) + if s.NoError(err) { + s.Equal(http.StatusOK, response.StatusCode) + s.NoError(response.Body.Close()) + } + s.Less(took, 2*time.Second, "message %d", i) + }) + <-ticker.C + } + messages.Wait() + stop() + others.Wait() +} + // A directory that is slow to answer is waited for: the other customer's session it names still // keeps the one here from answering. func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredByNeitherThoughTheDirectoryIsSlow() { @@ -281,7 +337,7 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredByNeitherT s.serverClient.on(slow).createSession(CreateSessionRequest{ AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), }) - proxy.lag.Store(int64(300 * time.Millisecond)) + proxy.lag.Store(int64(700 * time.Millisecond)) s.Require().Equal(http.StatusOK, s.signedlyOn(slow, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) diff --git a/acceleration/internal/api/messagehooks.go b/acceleration/internal/api/messagehooks.go index 65045273df..d9aa5e04df 100644 --- a/acceleration/internal/api/messagehooks.go +++ b/acceleration/internal/api/messagehooks.go @@ -15,6 +15,7 @@ import ( "github.com/GetStream/Vision-Agents/acceleration/internal/chatlog" "github.com/GetStream/Vision-Agents/acceleration/internal/conversation" "github.com/GetStream/Vision-Agents/acceleration/internal/dispatch" + "github.com/GetStream/Vision-Agents/acceleration/internal/goroutine" "github.com/GetStream/Vision-Agents/acceleration/internal/llm" "github.com/GetStream/Vision-Agents/acceleration/internal/node" "github.com/GetStream/Vision-Agents/acceleration/internal/routing" @@ -620,12 +621,28 @@ func (s *Server) writesElsewhere(ctx context.Context, agentID string, admits fun } ctx, cancel := context.WithTimeout(ctx, directoryTimeout) defer cancel() - nodes, err := s.directory.NodesByAgent(ctx, agentID, admits) - if err != nil { - s.logger.Warn("could not find out which nodes write as an agent", "agent", agentID, "error", err) + type read struct { + nodes map[string]string + err error + } + // rueidis waits past ctx for a connection another caller is dialing: the goroutine ends with + // that dial, which rueidis gives 5 s to connect and 5 s to greet Redis. + done := make(chan read, 1) + goroutine.Go(ctx, func() { + nodes, err := s.directory.NodesByAgent(ctx, agentID, admits) + done <- read{nodes, err} + }) + var answer read + select { + case answer = <-done: + case <-ctx.Done(): + answer.err = ctx.Err() + } + if answer.err != nil { + s.logger.Warn("could not find out which nodes write as an agent", "agent", agentID, "error", answer.err) return false } - return len(nodes) > 0 + return len(answer.nodes) > 0 } // storedOwnerOf is the customer the store says a channel in the hook's app is: its last call's, From 4885c279a0106f8127f80ea6469c10536c1c752c Mon Sep 17 00:00:00 2001 From: thesyncim Date: Wed, 25 Nov 2026 18:32:15 +0000 Subject: [PATCH 3/4] test(api): one message stands for a hung directory another read dials --- acceleration/internal/api/forward_test.go | 68 ++++++++++------------- 1 file changed, 29 insertions(+), 39 deletions(-) diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index c3e5725c64..4b8ecb9baf 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -3,12 +3,14 @@ package api import ( + "bytes" "context" "fmt" "log/slog" "net/http" "net/http/httptest" "net/url" + "runtime/pprof" "strings" "sync" "testing" @@ -273,10 +275,10 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTime settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") } -// The same while the node's renewals and its other reads of the directory, which have no limit, -// dial the connection the read waits for. -func (s *ForwardedSessionSuite) TestMessagesNamingNoCustomerAreAnsweredHereInTimeWhileOthersDialTheHungDirectory() { - channel := "chat-" + s.utils.uuid() +// The same while another read of the directory, which has no limit, dials the connection this one +// waits for, and what asked the directory ends with that dial. +func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTimeWhileAnotherReadDialsTheHungDirectory() { + channel, written := "chat-"+s.utils.uuid(), "is anybody there? "+s.utils.uuid() proxy, redis := newRedisProxy(s.T()) directory := s.directoryOver(redis, "here") unread, _, _ := s.otherNodeHolding(nil, s.sealer, slog.New(slog.DiscardHandler), @@ -285,44 +287,32 @@ func (s *ForwardedSessionSuite) TestMessagesNamingNoCustomerAreAnsweredHereInTim s.serverClient.on(unread).createSession(CreateSessionRequest{ AgentId: &channel, Llm: pointerTo("vision/vision-model"), Incognito: pointerTo(true), }) - // Held, so the directory has something to renew. - directory.Hold(s.T().Context(), "another-customer", 0, s.utils.uuid(), "", "") proxy.hung.Store(true) - + proxy.stop() + proxy.down.Store(false) reading, stop := context.WithCancel(s.T().Context()) - var others, messages sync.WaitGroup - others.Go(func() { - for reading.Err() == nil { - others.Go(func() { _, _ = directory.Node(reading, "another-customer", "no-session") }) - select { - case <-reading.Done(): - case <-time.After(3 * time.Second): - } - } - }) - target, err := url.Parse(unread.URL + "/v1/chat/hooks/stream") - s.Require().NoError(err) - ticker := time.NewTicker(500 * time.Millisecond) - defer ticker.Stop() - for i := range 40 { - body := strings.Replace(writtenTo(channel, `{}`, "is anybody there?"), - "message-"+channel, fmt.Sprintf("message-%d-%s", i, channel), 1) - request := s.request(target.Path, body, sign(body, suiteStreamSecret)) - request.URL, request.Host = target, target.Host - messages.Go(func() { - started := time.Now() - response, err := unread.Client().Do(request) - took := time.Since(started) - if s.NoError(err) { - s.Equal(http.StatusOK, response.StatusCode) - s.NoError(response.Body.Close()) - } - s.Less(took, 2*time.Second, "message %d", i) - }) - <-ticker.C - } - messages.Wait() + defer stop() + var others sync.WaitGroup + others.Go(func() { _, _ = directory.Node(reading, "another-customer", "no-session") }) + s.Require().Eventually(func() bool { + proxy.mu.Lock() + defer proxy.mu.Unlock() + return len(proxy.conns) > 0 + }, settleFor, time.Millisecond, "nothing dials the directory") + + started := time.Now() + s.Require().Equal(http.StatusOK, s.signedlyOn(unread, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) + + s.Less(time.Since(started), 2*time.Second) + s.Require().Eventually(func() bool { return s.wasAsked(written) }, + settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") stop() + proxy.stop() + s.Eventually(func() bool { + var running bytes.Buffer + s.NoError(pprof.Lookup("goroutine").WriteTo(&running, 2)) + return !strings.Contains(running.String(), "writesElsewhere.func") + }, settleFor, 10*time.Millisecond, "what asked the directory is still running") others.Wait() } From 0dcec5247c835dbeca1d01047c62306094b5118e Mon Sep 17 00:00:00 2001 From: thesyncim Date: Thu, 26 Nov 2026 08:50:32 +0000 Subject: [PATCH 4/4] test(api): the hung directory tests hold the message to 1.5 s --- acceleration/internal/api/forward_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 4b8ecb9baf..85f47de04d 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -270,7 +270,7 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTime started := time.Now() s.Require().Equal(http.StatusOK, s.signedlyOn(unread, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) - s.Less(time.Since(started), 2*time.Second) + s.Less(time.Since(started), 1500*time.Millisecond) s.Require().Eventually(func() bool { return s.wasAsked(written) }, settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") } @@ -303,7 +303,7 @@ func (s *ForwardedSessionSuite) TestAMessageNamingNoCustomerIsAnsweredHereInTime started := time.Now() s.Require().Equal(http.StatusOK, s.signedlyOn(unread, "/v1/chat/hooks/stream", writtenTo(channel, `{}`, written))) - s.Less(time.Since(started), 2*time.Second) + s.Less(time.Since(started), 1500*time.Millisecond) s.Require().Eventually(func() bool { return s.wasAsked(written) }, settleFor, 10*time.Millisecond, "the session where the message landed was asked nothing") stop()