grpcproc
Documentation

Models and tools

The model on GPU nodes, a process per generation that streams its tokens, failover when a node is lost, and tools run a process per call on a sandbox node.

The scheduler

A GPU node runs one scheduler, an actor: a struct holding its dependencies, with a method per kind of message. It embeds actor.CallsOnly, so a plain send to it is logged and dropped, and HandleCall takes the requests to generate.

A GPU holds so many generations at once: Slots. With none free, the scheduler answers busy at once, and the caller asks another node. Otherwise it starts a process for the generation with SpawnMonitor, keeps the call under the monitor's Ref, and returns actor.ErrNoReply: the call stays open, and the scheduler is free for the next request. It never generates anything itself, so it always answers. As it starts, Init joins it to the models process group, which is where the conversations find it.

a call handed to a process of its own
conversation/1on the gatewayits topicon the gatewaynode gpu-1modelsscheduler · 2 slotsgenerationholds the callgenerationof another callSpawnMonitor, the call handed overa third call:busy, at onceCall GenerateGeneratedPublish each token
internal/models/models.go
// scheduler is the actor. It answers a request with no slot free at once,
// and hands every other to a process started for it, which answers the call
// when the model is done. So the scheduler is never busy generating, and a
// generation that fails takes down nothing else.
type scheduler struct {
	actor.CallsOnly[proto.Message]
	model Model
	slots Slots
	scope *groups.Scope
	// running is the calls being answered, by the monitor of the process
	// that answers each.
	running map[grpcproc.Ref]grpcproc.Msg[proto.Message]
}

// Init joins the scheduler to the models group, where the conversations
// find it: it is in it until it exits, and a restart joins again.
func (s *scheduler) Init(p *grpcproc.Process[proto.Message]) error {
	return s.scope.Join(p.Context(), p, modelsv1.Group, p.PID())
}

// HandleCall hands a call to the Scheduler service's method for it: Generate.
func (s *scheduler) HandleCall(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message]) (proto.Message, error) {
	return modelsv1.HandleSchedulerCall(s, p, m)
}

func (s *scheduler) Generate(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message], req *modelsv1.Generate) (*modelsv1.Generated, error) {
	if len(s.running) >= int(s.slots) {
		return &modelsv1.Generated{Busy: true}, nil
	}
	// Monitored from before it runs, and linked to the scheduler, which
	// takes its generations with it if it ends.
	_, ref, err := p.SpawnMonitor(func(g *grpcproc.Process[proto.Message]) error {
		return generate(g, s.model, m, req)
	}, grpcproc.WithLabel("generation"), grpcproc.LinkParent())
	if err != nil {
		return nil, err
	}
	s.running[ref] = m
	return nil, actor.ErrNoReply // the generation answers
}

// HandleDown frees the slot of a generation that ended. One that ended
// without answering, by an error or a panic, has its call answered here.
func (s *scheduler) HandleDown(_ *grpcproc.Process[proto.Message], d grpcproc.Down) error {
	m := s.running[d.Ref]
	delete(s.running, d.Ref)
	if d.Reason != grpcproc.ReasonNormal {
		_ = m.Reply(nil, fmt.Errorf("models: the generation failed: %s", d.Reason))
	}
	return nil
}

The slot is freed by the Down, however the generation ended: done, failed, or panicked. One that ended without answering has its call answered here, with the reason. The generation is linked to the scheduler with LinkParent, so a scheduler that exits takes its generations with it, and its supervisor starts a scheduler with every slot free and nothing running behind its back.

A process per generation

The call was made to the scheduler and is answered by the generation: a call is answered by whoever holds its message, and the caller does not see the difference. The message brings the caller's deadline with it: m.Context gives a context that ends at that deadline, so the model does not run past it. Only the deadline travels: a caller that goes away sooner is not heard of.

internal/models/models.go
// generate is the process of one generation. The call it answers was made
// to the scheduler, which handed it over: a call is answered by whoever
// holds its message. Its tokens go straight to the topic the request names,
// and its answer after them on the same link, so a subscriber has every
// token before whoever called has the answer.
func generate(p *grpcproc.Process[proto.Message], model Model, m grpcproc.Msg[proto.Message], req *modelsv1.Generate) error {
	// The caller's deadline is the generation's, and so is an exit.
	ctx, cancel := m.Context(p.Context())
	defer cancel()
	topic := pubsub.Named[*conversationsv1.Event](req.TopicNode, req.Topic)
	var text string
	tool, err := model.Generate(ctx, req.History, func(token string) error {
		text += token
		return topic.Publish(ctx, p, &conversationsv1.Event{
			Turn: req.Turn, Attempt: req.Attempt, Kind: &conversationsv1.Event_Token{Token: token},
		})
	})
	if err != nil {
		return err // its exit reason, which HandleDown passes on
	}
	return m.Reply(&modelsv1.Generated{Text: text, Tool: tool}, nil)
}

Each token is published to the topic the request names, from the GPU node straight to the conversation's node. The answer follows the tokens on the same link, and a link delivers in order: every token is with the topic before the conversation has the answer, so the conversation's done is published after the last of them.

The model is an interface the container serves. The tutorial's is a script that asks for the calculator when it sees a sum and otherwise says back what it was told, a word at a time; a real one is a client of an inference server.

internal/models/models.go
// Model says the assistant's next turn of a conversation: it gives emit
// each token as it has it, and returns the tool it wants called before it
// goes on, if any. It is called from several processes at once. The guide's
// is a script, so that what it says can be pinned by a test; a real one is a
// client of an inference server, which the container builds the same way.
type Model interface {
	Generate(ctx context.Context, history []*modelsv1.Turn, emit func(token string) error) (*toolsv1.Run, error)
}

A node that is lost

A conversation finds the nodes that run a model in the models group, and asks them in order: those it knew, as it left them, then any that joined since. What it does next depends on what it is told, and the three cases are three different answers:

  • busy: nothing was generated. The next node is asked, and with every node busy the conversation waits a moment and asks again.
  • A LinkError with Unsent set: the node could not be reached, and the request never left. The next node is asked.
  • Any other error: the node was lost with the request, or its generation failed. It may have published tokens, so before another node is asked, the subscribers are told the answer starts over.
internal/conversations/conversations.go
// generate has a model answer, on the first node that takes the request. A
// node that is busy says so, and one that cannot be reached never had the
// request: the next is asked. One that is lost with the request, or fails
// it, may have published tokens: if another node is asked, the subscribers
// are first told the answer starts over. A node that failed goes to the back
// of the conversation's list, so the next answer is asked of one that did
// not. With every node busy, it waits for a slot, for as long as a model is
// given to answer.
func (c *conversation) generate(p *grpcproc.Process[proto.Message]) (*modelsv1.Generated, error) {
	waited := time.Now().Add(c.limits.Generate)
	lost := "" // the node that took the request and did not finish
	for {
		var errs []error
		c.models = c.nodes()
		busy := len(c.models) == 0 // none is known yet: as if every one were busy
		for _, node := range slices.Clone(c.models) {
			if p.Context().Err() != nil { // the conversation is told to exit
				return nil, p.Context().Err()
			}
			// A try has a number larger than the one before it; the time
			// makes it larger than those of the process before this one too.
			c.attempt = max(c.attempt+1, uint64(time.Now().UnixNano()))
			if lost != "" {
				_ = c.publish(p, &conversationsv1.Event{Attempt: c.attempt, Kind: &conversationsv1.Event_Retrying{Retrying: lost + " did not finish"}})
				lost = ""
			}
			// A message of its own for each try: a local send passes the
			// pointer, and the try before may still be reading its own.
			req := &modelsv1.Generate{
				History: c.turns, TopicNode: c.node, Topic: conversationsv1.ConversationEventsTopic(c.id),
				Turn: c.turn, Attempt: c.attempt,
			}
			ctx, cancel := context.WithTimeout(p.Context(), c.limits.Generate)
			out, err := modelsv1.SchedulerAt(node).Generate(ctx, p, req)
			cancel()
			switch {
			case err != nil:
				errs = append(errs, fmt.Errorf("%s: %w", node, err))
				c.models = append(slices.DeleteFunc(c.models, func(n string) bool { return n == node }), node)
				// It may have taken the request and published tokens, unless
				// the error says the request never left.
				if link, ok := errors.AsType[*grpcproc.LinkError](err); !ok || !link.Unsent {
					lost = node
				}
			case out.Busy:
				errs = append(errs, fmt.Errorf("%s: busy", node))
				busy = true
			default:
				return out, nil
			}
		}
		switch {
		case len(errs) == 0 && time.Now().After(waited):
			return nil, errors.New("no node runs a model")
		case len(errs) > 0 && (!busy || time.Now().After(waited)):
			return nil, fmt.Errorf("no model answered: %w", errors.Join(errs...))
		}
		select {
		case <-p.Context().Done():
			return nil, p.Context().Err()
		case <-time.After(c.limits.Busy):
		}
	}
}

A node that lost its link to the gateway, and not its power, goes on generating until the deadline and may publish again once it redials. So every request carries an attempt, larger than the one before, every token carries its request's, and the event that says an answer starts over carries the new one: the web front drops the tokens of an attempt older than the latest it has heard of.

A call to a node that goes down does not wait for its deadline. The call fails when the link to that node breaks, which is what makes failing over quick. In this test gpu-1 is stopped after its first token. A node that failed goes to the back of the conversation's list, so what comes after is asked of gpu-2 first:

gpu-1 is lost in the middle of an answer
followersbrowsersconversationand its topicgpu-1a generationgpu-2a generationCall GeneratePublish tokentokenthe node is lostthe link breaks: the call failsretrying: the answer starts overCall GeneratePublish every token, from the firsttokensGenerated
testdata/failover.txt
> what is 6 * 7?
Let me think
  [starting over] gpu-1 did not finish
Let me calculate that.
  [tool] calc 6 * 7
  [ran] 42
The answer is 42.
  [turn 1 done]
> thanks
You said: thanks
  [turn 2 done]

Tools, a process per call

What a tool does is decided by what a model wrote, so tools run on a node of their own. The runner is the scheduler's pattern again, a process per call, the call handed to it, the runner free at once, from actor.Workers, which also bounds how many run, sixteen across every tool. Each worker is labelled with its tool, so the Inspector shows which tool is running or stuck. Here the isolation is the point. A tool that panics ends its own process, which answers the call with the panic first, and nothing else on the node notices. The calculator divides by zero when asked to.

internal/tools/tools.go
// runner is the actor. It hands each call to a worker, a process started
// for it, and is free again at once; the worker's answer is the call's. A
// tool that failed is part of the answer, since the model is told of it,
// and so is one that panicked: the worker answers with the panic.
type runner struct {
	actor.CallsOnly[proto.Message]
	tools   Tools
	workers *actor.Workers
}

// HandleCall hands a call to the Runner service's method for it: Run.
func (r *runner) HandleCall(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message]) (proto.Message, error) {
	return toolsv1.HandleRunnerCall(r, p, m)
}

func (r *runner) Run(p *grpcproc.Process[proto.Message], m grpcproc.Msg[proto.Message], run *toolsv1.Run) (*toolsv1.Ran, error) {
	tool, ok := r.tools[run.Name]
	if !ok {
		return &toolsv1.Ran{Failed: "no tool named " + run.Name}, nil
	}
	return nil, r.workers.Label("tool:"+run.Name).ReplyLater(p, m, func(ctx context.Context, _ *grpcproc.Process[proto.Message]) (*toolsv1.Ran, error) {
		// The caller's deadline is the tool's. A goroutine cannot be
		// killed: a tool that does not watch ctx runs on after it, in its
		// worker's place.
		out, err := tool(ctx, run.Args)
		if err != nil {
			return &toolsv1.Ran{Failed: err.Error()}, nil
		}
		return &toolsv1.Ran{Output: out}, nil
	})
}

// running is how many tools the runner runs at once; a call beyond them is
// answered actor.ErrWorkersBusy.
const running = 16

The conversation calls with a deadline, Limits.Tool, and the tool's context ends with it. A tool that runs out of time is an answer too: the tool says its deadline passed, or the conversation's call ends first, and either way the model is told the tool failed and says so. A goroutine cannot be killed, so a tool that ignores its context runs on after its caller has gone, in one of the runner's sixteen places; with all of them held, every call is answered busy. A real sandbox runs tools in something that can be killed, a subprocess or a container, started from this process.

The sandbox answers the gateway and may ask nothing of it, or of the GPU nodes. The platform has how.