grpcproc
Documentation

Tests and inspection

A service tested alone with fakes, the deployments tested whole with a node lost on purpose, and the running cluster inspected with grpcprocctl.

A service alone

A service is tested alone with fakes behind the addresses it calls: processes registered under the contracts' names on the node the placement points at, which with no placement is this one. di.Test gives a scope stopped when the test ends; the test composes the platform and the conversations module in it, overrides the limits with short ones, and spawns a model and a sandbox of its own.

internal/conversations/conversations_test.go
// The conversations alone. Their collaborators are addresses, so a test
// puts fakes behind them: processes registered under the names the
// contracts give, on the node the placement points at, which with none is
// this one, and a scheduler in the models group. What the model is asked
// comes out on a channel, for the test to read.
func service(t *testing.T, limits conversations.Limits, model func(*modelsv1.Generate) *modelsv1.Generated) (*grpcproc.Node, <-chan *modelsv1.Generate) {
	t.Helper()
	s := di.Test(t)
	platform.Compose(s, platform.Config{Node: "local", Listen: "127.0.0.1:0"}, slog.New(slog.DiscardHandler), conversations.Module)
	s.Value(limits).Override()
	if err := s.Start(t.Context()); err != nil {
		t.Fatal(err)
	}
	n := s.Get[*grpcproc.Node]()
	asked := make(chan *modelsv1.Generate, 8)
	scheduler := func(p *grpcproc.Process[*modelsv1.Generate]) error {
		for {
			m, err := p.Receive()
			if err != nil {
				return err
			}
			asked <- m.Body
			_ = m.Reply(model(m.Body), nil)
		}
	}
	a, err := n.Spawn(scheduler, grpcproc.WithName(modelsv1.SchedulerProcess))
	if err != nil {
		t.Fatal(err)
	}
	if err := s.Get[*groups.Scope]().Join(t.Context(), n, modelsv1.Group, a.PID()); err != nil {
		t.Fatal(err)
	}
	// A sandbox that takes every call and answers none.
	runner := func(p *grpcproc.Process[*toolsv1.Run]) error {
		for {
			if _, err := p.Receive(); err != nil {
				return err
			}
		}
	}
	if _, err := n.Spawn(runner, grpcproc.WithName(toolsv1.RunnerProcess)); err != nil {
		t.Fatal(err)
	}
	return n, asked
}

The fake model reports what it is asked on a channel, so a test reads what a conversation sent it. This one has the model ask for a tool the sandbox never answers, and checks that the model is asked again and told so:

internal/conversations/conversations_test.go
// A tool that does not answer in time is an answer: the model is asked
// again, and told.
func TestAToolWithNoAnswerIsToldToTheModel(t *testing.T) {
	limits := conversations.Limits{Idle: time.Minute, Generate: time.Second, Tool: 50 * time.Millisecond, Busy: time.Millisecond}
	n, asked := service(t, limits, func(g *modelsv1.Generate) *modelsv1.Generated {
		if last := g.History[len(g.History)-1]; last.Role == modelsv1.Role_ROLE_TOOL {
			return &modelsv1.Generated{Text: "It did not answer."}
		}
		return &modelsv1.Generated{Text: "One moment.", Tool: &toolsv1.Run{Name: "sleep", Args: "1h"}}
	})
	if _, err := conversationsv1.NewConversation("local", "1").Say(t.Context(), n, "wait an hour"); err != nil {
		t.Fatal(err)
	}
	next(t, asked)
	last := next(t, asked).History[2] // the user, the model, the tool
	if last.Role != modelsv1.Role_ROLE_TOOL || !strings.Contains(last.Text, "no answer from the sandbox") {
		t.Fatalf("the model was told %v", last)
	}
}

And this one waits for an idle conversation's process to end, speaks to it again, and checks that the new process shows the model what was said to the old one:

internal/conversations/conversations_test.go
// A conversation nobody speaks to ends its process, and the next thing said
// starts one that knows what was said before.
func TestAnIdleConversationEndsAndComesBack(t *testing.T) {
	limits := conversations.Limits{Idle: 50 * time.Millisecond, Generate: time.Second, Tool: time.Second, Busy: time.Millisecond}
	n, asked := service(t, limits, func(*modelsv1.Generate) *modelsv1.Generated {
		return &modelsv1.Generated{Text: "Noted."}
	})
	c := conversationsv1.NewConversation("local", "1")
	if said, err := c.Say(t.Context(), n, "one"); err != nil || said.Turn != 1 {
		t.Fatalf("%v %v", said, err)
	}
	next(t, asked)
	// A call of a type the conversation has no rpc for is answered ErrType,
	// as the node answered it when the mailbox held one type, and does not
	// keep the conversation from going idle.
	if _, err := n.CallTo[*conversationsv1.Said](t.Context(), c.ConversationAddr, &conversationsv1.Open{Id: "1"}); !errors.Is(err, grpcproc.ErrType) {
		t.Fatalf("a stranger's call: %v", err)
	}
	for range 500 {
		if _, running := n.Whereis(c.Name()); !running {
			break
		}
		time.Sleep(10 * time.Millisecond)
	}
	if _, running := n.Whereis(c.Name()); running {
		t.Fatal("the conversation is still running")
	}
	if said, err := c.Say(t.Context(), n, "two"); err != nil || said.Turn != 2 {
		t.Fatalf("%v %v", said, err)
	}
	if h := next(t, asked).History; len(h) != 3 || h[0].Text != "one" || h[1].Text != "Noted." || h[2].Text != "two" {
		t.Fatalf("the model was shown %v", h)
	}
}

The deployment whole

The deployments are tested whole. Each node is composed as its entry point composes it and told what a deployment would: its peers, where the services it does not run are, what it exports and whom it does not trust. The test binds the ports first, so it knows them, and hands each node its listener with an override, which di requires to be marked as one. gpu-1 gets a model that says two words and stalls.

Before it speaks, the test waits until the gateway's copy of the models group has both GPU nodes, so that the conversation asks gpu-1 first, as the group orders them. It then follows a conversation, says something, and waits for those two words. It pins what each node runs at that moment, stops gpu-1, and pins what the follower is sent from then on. Last, a process on the sandbox tries to speak to the conversation, and must be told there is none.

cluster_test.go
package guide

import (
	"context"
	"errors"
	"net"
	"net/http"
	"strings"
	"testing"
	"time"

	"golang.yandex/di"
	"google.golang.org/protobuf/proto"

	"github.com/floatdrop/grpcproc"
	"github.com/floatdrop/grpcproc/examples/guide/internal/models"
	"github.com/floatdrop/grpcproc/examples/guide/internal/platform"
	conversationsv1 "github.com/floatdrop/grpcproc/examples/guide/proto/conversations/v1"
	modelsv1 "github.com/floatdrop/grpcproc/examples/guide/proto/models/v1"
	toolsv1 "github.com/floatdrop/grpcproc/examples/guide/proto/tools/v1"
	"github.com/floatdrop/grpcproc/groups"
)

// stalling is a model that says two words and nothing more: a GPU node
// about to be lost.
type stalling struct{}

func (stalling) Generate(ctx context.Context, _ []*modelsv1.Turn, emit func(string) error) (*toolsv1.Run, error) {
	if err := emit("Let me think"); err != nil {
		return nil, err
	}
	<-ctx.Done()
	return nil, ctx.Err()
}

// The distributed deployment: a gateway, two GPU nodes and a sandbox, the
// same modules split between them, and the configuration a deployment would
// give each. gpu-1 is lost in the middle of an answer.
func TestCluster(t *testing.T) {
	stall := func(s *di.Scope) { s.Value[models.Model](stalling{}).Override() }
	nodes := []struct {
		name     string
		services []di.Module
		more     []di.Module
		ln       net.Listener
		app      *di.Scope
	}{
		{name: "gateway", services: gateway},
		{name: "gpu-1", services: gpu, more: []di.Module{stall}},
		{name: "gpu-2", services: gpu, more: []di.Module{fast}},
		{name: "sandbox", services: sandbox},
	}
	// Each node's port is bound first, so every node can be told the others'.
	peers := map[string]string{}
	for i := range nodes {
		ln, err := net.Listen("tcp", "127.0.0.1:0")
		if err != nil {
			t.Fatal(err)
		}
		nodes[i].ln, peers[nodes[i].name] = ln, ln.Addr().String()
	}
	apps := map[string]*di.Scope{}
	for i := range nodes {
		n := &nodes[i]
		cfg := platform.Config{Node: n.name, Listen: peers[n.name], Peers: peers}
		switch n.name {
		case "gateway":
			// Where the tools run, and whom not to trust. The models are
			// found in their group.
			cfg.Placement = map[string]string{toolsv1.Service: "sandbox"}
			cfg.Untrusted = []string{"sandbox"}
		case "sandbox":
			cfg.Export = []string{toolsv1.RunnerProcess}
		default:
			cfg.Export = []string{modelsv1.SchedulerProcess}
			cfg.Untrusted = []string{"sandbox"}
		}
		n.app = compose(cfg, n.services, n.more...)
		n.app.Value(n.ln).Override() // the port bound above
		start(t, n.app)
		apps[n.name] = n.app
	}
	front := apps["gateway"]
	awaitModels(t, front, 2)
	events := follow(t, front.Get[*grpcproc.Node](), "gateway", "1")

	if code, body := say(t, front, "1", "what is 6 * 7?"); code != http.StatusAccepted {
		t.Fatalf("%d %s", code, body)
	}
	// gpu-1 has begun the answer: what the nodes run now is the drawing the
	// guide shows, a generation in flight included.
	if said, token := <-events, <-events; said.GetSaid() == "" || token.GetToken() != "Let me think" {
		t.Fatalf("got %v, %v", said, token)
	}
	var trees []string
	for _, n := range nodes {
		trees = append(trees, tree(n.app.Get[*grpcproc.Node]()))
	}
	golden(t, "cluster.txt", strings.Join(trees, "\n"))

	// gpu-1 is lost. The conversation's call fails, and it asks gpu-2, which
	// starts the answer over; the tool runs in the sandbox.
	if err := apps["gpu-1"].Stop(t.Context()); err != nil {
		t.Fatal(err)
	}
	chat := "> what is 6 * 7?\nLet me think\n" + transcript(t, events, 1)
	// From then on gpu-2 is asked first: gpu-1 did not finish.
	if code, body := say(t, front, "1", "thanks"); code != http.StatusAccepted {
		t.Fatalf("%d %s", code, body)
	}
	chat += transcript(t, events, 1)
	golden(t, "failover.txt", chat)

	// The sandbox answers the gateway, and may ask nothing of it or of the
	// GPU nodes: to the sandbox, their processes do not exist.
	denied := make(chan error, 2)
	if _, err := apps["sandbox"].Get[*grpcproc.Node]().Spawn(func(p *grpcproc.Process[proto.Message]) error {
		_, err := conversationsv1.NewConversation("gateway", "1").Say(p.Context(), p, "let me in")
		denied <- err
		// Nor a GPU node's scheduler, which would publish where it is told.
		_, err = modelsv1.SchedulerAt("gpu-2").Generate(p.Context(), p, &modelsv1.Generate{})
		denied <- err
		return nil
	}); err != nil {
		t.Fatal(err)
	}
	for range 2 {
		if err := <-denied; !errors.Is(err, grpcproc.ErrNoProc) {
			t.Fatalf("the sandbox was answered %v", err)
		}
	}
}

// awaitModels waits until app's copy of the models group has n GPU nodes' schedulers.
func awaitModels(t *testing.T, app *di.Scope, n int) {
	t.Helper()
	scope := app.Get[*groups.Scope]()
	for deadline := time.Now().Add(10 * time.Second); len(scope.Members(modelsv1.Group)) != n; {
		if time.Now().After(deadline) {
			t.Fatalf("the models group has %v", scope.Members(modelsv1.Group))
		}
		time.Sleep(10 * time.Millisecond)
	}
}

Inspecting the running cluster

Every node serves the Inspector, and one asked about another node forwards the question there, so grpcprocctl pointed at one node can ask about any. nodes and dot --cluster list the nodes it is linked to, their links and processes, and who started whom; for the gateway, once a conversation has used a tool, that is all four. inspect shows what a process says about itself: a conversation its turns, a supervisor its children and restarts. The platform's Inspector is read-only, so exit and loglevel are refused.

shell
go install github.com/floatdrop/grpcproc/tools/cmd/grpcprocctl@latest
export GRPCPROC_ADDR=127.0.0.1:9101          # the gateway's Inspector
grpcprocctl --plaintext nodes                # the nodes it is linked to, and their links
grpcprocctl --plaintext ps --node gpu-1      # gpu-1's processes, asked there: a generation, perhaps
grpcprocctl --plaintext inspect conversation/1   # how many turns it has had
grpcprocctl --plaintext inspect root         # the gateway's root: its children, its restarts
grpcprocctl --plaintext dot --cluster | dot -Tsvg -o runtime.svg
kill %1 %2 %3 %4 %5                          # the four programs, and the curl that follows

Command line has the rest of what grpcprocctl does, and Web UI shows the same cluster in a browser.