diff --git a/acceleration/internal/api/forward_test.go b/acceleration/internal/api/forward_test.go index 1fac998f7a..85f47de04d 100644 --- a/acceleration/internal/api/forward_test.go +++ b/acceleration/internal/api/forward_test.go @@ -3,11 +3,16 @@ package api import ( + "bytes" + "context" "fmt" "log/slog" "net/http" "net/http/httptest" "net/url" + "runtime/pprof" + "strings" + "sync" "testing" "time" @@ -250,6 +255,86 @@ 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), 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") +} + +// 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), + 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), + }) + proxy.hung.Store(true) + proxy.stop() + proxy.down.Store(false) + reading, stop := context.WithCancel(s.T().Context()) + 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), 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() + 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() +} + +// 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(700 * 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 +451,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 8fdf4dd982..dbdac5d72f 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" @@ -633,6 +634,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. @@ -640,12 +644,30 @@ func (s *Server) writesElsewhere(ctx context.Context, agentID string, admits fun if s.directory == nil { return false } - 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) + ctx, cancel := context.WithTimeout(ctx, directoryTimeout) + defer cancel() + 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, 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 0dd1dd6994..eb202d0d72 100644 --- a/acceleration/internal/node/directory_test.go +++ b/acceleration/internal/node/directory_test.go @@ -208,6 +208,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", "")