feat(daemon): run a Kit profile's task in its Kit container on the egress path
This commit is contained in:
17 files changed
+734
-42
No files matched your search
+30
-14
@@ -158,6 +158,8 @@ type Daemon struct {
|
||||
// set -- acquireTaskContainer parks the task rather than fall back to
|
||||
// forwarding the daemon's own administrative token.
|
||||
StateStoreGrants StateStoreGrantIssuer
|
||||
// KitLauncher starts tasks whose agent profile is a Kit. Nil parks them.
|
||||
KitLauncher KitLauncher
|
||||
// TaskRunReadyTimeout bounds how long runViaAgent retries an initial
|
||||
// taskrun request that fails with nats.ErrNoResponders, giving a
|
||||
// freshly spawned archie-agent container time to connect to NATS, set
|
||||
@@ -1261,6 +1263,12 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if profile.IsKit() {
|
||||
d.runKitTask(ctx, task, repo, workDir, profile)
|
||||
d.teardownStorage(ctx, task, repo, workDir)
|
||||
d.cleanupTerminalTaskWorktree(ctx, task, trees)
|
||||
return
|
||||
}
|
||||
ctr, revokeStateStoreGrant, ok := d.acquireTaskContainer(ctx, task, repo, workDir, profile.Image)
|
||||
if !ok {
|
||||
return
|
||||
@@ -1278,12 +1286,17 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
// task is always served by its own forge client and worktree manager.
|
||||
limitCtx, stopLimit := withTaskTimeLimit(ctx, d.configFor(task).Budgets.TaskWallClock.Std())
|
||||
runCtx, stopWatch := withContainerExit(limitCtx, ctr.Exited())
|
||||
d.runViaAgent(runCtx, task, repo, profile)
|
||||
d.runViaAgent(runCtx, task, repo, profile, nil)
|
||||
stopWatch()
|
||||
stopLimit()
|
||||
|
||||
// Teardown storage after workflow completes. The Docker backend is a
|
||||
// no-op; future backends (temp volumes, NFS leases) use this hook.
|
||||
d.teardownStorage(ctx, task, repo, workDir)
|
||||
d.cleanupTerminalTaskWorktree(ctx, task, trees)
|
||||
}
|
||||
|
||||
// teardownStorage runs after the workflow completes. The Docker backend is
|
||||
// a no-op; future backends (temp volumes, NFS leases) use this hook.
|
||||
func (d *Daemon) teardownStorage(ctx context.Context, task *workflow.Task, repo config.Repo, workDir string) {
|
||||
if d.Storage != nil {
|
||||
_ = d.Storage.Teardown(ctx, storage.TaskRef{
|
||||
WorktreeDir: workDir,
|
||||
@@ -1293,8 +1306,6 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) {
|
||||
Repo: task.Repo,
|
||||
})
|
||||
}
|
||||
|
||||
d.cleanupTerminalTaskWorktree(ctx, task, trees)
|
||||
}
|
||||
|
||||
// prepareWorkspace makes the directory the container binds as its
|
||||
@@ -1427,14 +1438,7 @@ func (d *Daemon) acquireTaskContainer(
|
||||
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
|
||||
}
|
||||
|
||||
// Write task.json -- the container's boot-time brief.
|
||||
if err := container.WriteTaskJSON(workDir, container.TaskPayload{
|
||||
ID: task.ID, Owner: task.Owner, Repo: task.Repo,
|
||||
Number: task.IssueNumber, Title: task.Title, Body: task.Body,
|
||||
Labels: strings.Split(task.Labels, ","),
|
||||
Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan,
|
||||
Inputs: task.Inputs,
|
||||
}); err != nil {
|
||||
if err := writeTaskBrief(workDir, task); err != nil {
|
||||
park("task.json write failed", err)
|
||||
return nil, nil, false
|
||||
}
|
||||
@@ -1496,6 +1500,17 @@ func (d *Daemon) acquireTaskContainer(
|
||||
return ctr, revokeStateStoreGrant, true
|
||||
}
|
||||
|
||||
// writeTaskBrief writes task.json, the container's boot-time brief.
|
||||
func writeTaskBrief(workDir string, task *workflow.Task) error {
|
||||
return container.WriteTaskJSON(workDir, container.TaskPayload{
|
||||
ID: task.ID, Owner: task.Owner, Repo: task.Repo,
|
||||
Number: task.IssueNumber, Title: task.Title, Body: task.Body,
|
||||
Labels: strings.Split(task.Labels, ","),
|
||||
Workflow: task.Workflow, Branch: task.Branch, Plan: task.Plan,
|
||||
Inputs: task.Inputs,
|
||||
})
|
||||
}
|
||||
|
||||
// parkCapabilityUnavailable parks a task whose daemon-side capability is
|
||||
// missing (container pool or task transport): both are environmental, so
|
||||
// the park class is transient and the KindParked event carries the class
|
||||
@@ -1588,7 +1603,7 @@ func (d *Daemon) recordPark(ctx context.Context, taskID int64, reason string) {
|
||||
// itself when nothing else could have: the request never reached (or was
|
||||
// never answered by) an archie-agent, or archie-agent failed before its
|
||||
// own workflow.Run got a chance to record an outcome.
|
||||
func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo config.Repo, profile config.AgentProfile) {
|
||||
func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo config.Repo, profile config.AgentProfile, harness *agentexec.HarnessSpec) {
|
||||
grant, revoke, ok := d.publicationGrant(ctx, task)
|
||||
if !ok {
|
||||
return
|
||||
@@ -1608,6 +1623,7 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf
|
||||
LabelWorkflows: d.LabelWorkflows,
|
||||
WorkflowDefinition: task.WorkflowDefinitionYAML,
|
||||
Tools: profile.Tools,
|
||||
Harness: harness,
|
||||
}
|
||||
data, err := json.Marshal(req)
|
||||
if err != nil {
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
natssrv "github.com/nats-io/nats-server/v2/test"
|
||||
natsio "github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
@@ -27,6 +28,8 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
agentnats "github.com/samcharles93/archie-core/internal/infrastructure/agenttransport/nats"
|
||||
arnats "github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
"github.com/samcharles93/archie-core/internal/secret"
|
||||
@@ -2330,7 +2333,7 @@ func TestRunViaAgentCarriesTheWorkflowProfile(t *testing.T) {
|
||||
if !ok || profile.Image != "agent-net:1" {
|
||||
t.Fatalf("pinTaskProfile() = %+v, %v; want the net profile", profile, ok)
|
||||
}
|
||||
d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, profile)
|
||||
d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, profile, nil)
|
||||
select {
|
||||
case req := <-received:
|
||||
if len(req.Tools) != 1 || req.Tools[0] != "whois" {
|
||||
@@ -2378,7 +2381,7 @@ func TestRunViaAgentParksWhenTheContainerExits(t *testing.T) {
|
||||
defer stop()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
d.runViaAgent(runCtx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, config.AgentProfile{})
|
||||
d.runViaAgent(runCtx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, config.AgentProfile{}, nil)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
@@ -2422,7 +2425,7 @@ func TestRunViaAgentParksWhenTheTaskTimeLimitPasses(t *testing.T) {
|
||||
defer stop()
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
d.runViaAgent(runCtx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, config.AgentProfile{})
|
||||
d.runViaAgent(runCtx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, config.AgentProfile{}, nil)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
@@ -2436,3 +2439,85 @@ func TestRunViaAgentParksWhenTheTaskTimeLimitPasses(t *testing.T) {
|
||||
t.Fatalf("task = %+v, %v; want parked naming the time limit", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeKitLauncher struct {
|
||||
got kitrun.Request
|
||||
released bool
|
||||
removed []kit.Volume
|
||||
}
|
||||
|
||||
func (f *fakeKitLauncher) Launch(_ context.Context, req kitrun.Request) (*kitrun.Run, error) {
|
||||
f.got = req
|
||||
return &kitrun.Run{
|
||||
Container: &container.Container{},
|
||||
Harness: agentexec.HarnessSpec{Adapter: agentexec.AdapterClaudeCode, Launch: []string{"claude"}},
|
||||
Volumes: []kit.Volume{{Name: "v", Path: "/home/agent/.claude"}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *fakeKitLauncher) Release(context.Context, *kitrun.Run) error {
|
||||
f.released = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeKitLauncher) RemoveVolumes(_ context.Context, v []kit.Volume) error {
|
||||
f.removed = append(f.removed, v...)
|
||||
return nil
|
||||
}
|
||||
|
||||
// A Kit profile starts the task through the Kit launcher, hands the worker
|
||||
// the Kit's harness, keeps model provider keys out of the container, and
|
||||
// removes the execution's volumes once the task is no longer retryable.
|
||||
func TestKitProfileRunsTheTaskOnItsHarness(t *testing.T) {
|
||||
d, s, busClient := daemonWithNATS(t)
|
||||
launcher := &fakeKitLauncher{}
|
||||
d.KitLauncher = launcher
|
||||
d.ConnectedNATS.URL = "nats://172.17.0.1:4222"
|
||||
t.Setenv("KIT_TEST_PROVIDER_KEY", "sk-real")
|
||||
cfg := d.Cfg.Get()
|
||||
cfg.Providers = map[string]config.Provider{"p": {APIKeyEnv: "KIT_TEST_PROVIDER_KEY"}}
|
||||
d.Cfg.Set(cfg)
|
||||
ctx := context.Background()
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 31, "t", "b", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim: (%v, %v)", task, err)
|
||||
}
|
||||
received := make(chan taskrun.Request, 1)
|
||||
sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) {
|
||||
var req taskrun.Request
|
||||
_ = json.Unmarshal(msg.Data, &req)
|
||||
received <- req
|
||||
data, _ := json.Marshal(taskrun.Response{Status: workflow.StatusPROpen})
|
||||
_ = msg.Respond(data)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("subscribe: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sub.Unsubscribe() })
|
||||
|
||||
profile := config.AgentProfile{Kit: []string{"kit@sha256:ab"}, Adapter: agentexec.AdapterClaudeCode}
|
||||
d.runKitTask(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}, t.TempDir(), profile)
|
||||
|
||||
select {
|
||||
case req := <-received:
|
||||
if req.Harness == nil || req.Harness.Adapter != agentexec.AdapterClaudeCode {
|
||||
t.Fatalf("request harness = %+v, want the Kit's", req.Harness)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("archied did not publish a taskrun request")
|
||||
}
|
||||
if !slices.Equal(launcher.got.Kit, profile.Kit) || launcher.got.Adapter != profile.Adapter {
|
||||
t.Fatalf("launch request %+v, want the profile's kits and adapter", launcher.got)
|
||||
}
|
||||
for _, e := range launcher.got.WorkerEnv {
|
||||
if strings.Contains(e, "sk-real") {
|
||||
t.Fatalf("worker env carries a model provider key: %q", e)
|
||||
}
|
||||
}
|
||||
if !launcher.released || len(launcher.removed) != 1 {
|
||||
t.Fatalf("released %v, removed %v; want the run released and its volumes removed", launcher.released, launcher.removed)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kit"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/kitrun"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// KitLauncher starts and ends the container of a task whose agent profile
|
||||
// is a Kit.
|
||||
type KitLauncher interface {
|
||||
Launch(ctx context.Context, req kitrun.Request) (*kitrun.Run, error)
|
||||
Release(ctx context.Context, run *kitrun.Run) error
|
||||
RemoveVolumes(ctx context.Context, volumes []kit.Volume) error
|
||||
}
|
||||
|
||||
// runKitTask runs a task in its Kit's container, every agent stage on the
|
||||
// Kit's harness. The worker reaches NATS and the State Store only through
|
||||
// the egress relay, and its environment carries no model provider key.
|
||||
func (d *Daemon) runKitTask(ctx context.Context, task *workflow.Task, repo config.Repo, workDir string, profile config.AgentProfile) {
|
||||
park := func(reason string, err error) {
|
||||
d.Log.Error(reason, "task", task.ID, "err", err)
|
||||
d.parkRunningTask(ctx, task.ID, reason+": "+err.Error(), taskstate.ParkTransient)
|
||||
}
|
||||
if d.KitLauncher == nil {
|
||||
park("kit profile", fmt.Errorf("kit harness runs are unavailable on this daemon"))
|
||||
return
|
||||
}
|
||||
if err := writeTaskBrief(workDir, task); err != nil {
|
||||
park("task.json write failed", err)
|
||||
return
|
||||
}
|
||||
stateStoreToken, revokeStateStoreGrant, err := d.stateStoreGrantToken(task)
|
||||
if err != nil {
|
||||
park("state store grant failed", err)
|
||||
return
|
||||
}
|
||||
defer revokeStateStoreGrant()
|
||||
env, err := kitrun.WorkerEnv(kitrun.Endpoints{
|
||||
NATS: d.ConnectedNATS.URL, NATSToken: d.ConnectedNATS.Token,
|
||||
StateStore: d.ConnectedStateStore.URL, StateStoreToken: stateStoreToken,
|
||||
}, os.Getuid(), os.Getgid())
|
||||
if err != nil {
|
||||
park("kit worker environment", err)
|
||||
return
|
||||
}
|
||||
run, err := d.KitLauncher.Launch(ctx, kitrun.Request{
|
||||
Execution: fmt.Sprintf("task-%d", task.ID),
|
||||
Kit: profile.Kit,
|
||||
Adapter: profile.Adapter,
|
||||
WorkDir: workDir,
|
||||
WorkerEnv: env,
|
||||
})
|
||||
if err != nil {
|
||||
park("kit launch failed", err)
|
||||
return
|
||||
}
|
||||
|
||||
limitCtx, stopLimit := withTaskTimeLimit(ctx, d.configFor(task).Budgets.TaskWallClock.Std())
|
||||
runCtx, stopWatch := withContainerExit(limitCtx, run.Container.Exited())
|
||||
d.runViaAgent(runCtx, task, repo, profile, &run.Harness)
|
||||
stopWatch()
|
||||
stopLimit()
|
||||
|
||||
if err := d.KitLauncher.Release(ctx, run); err != nil {
|
||||
d.Log.Warn("kit release failed", "task", task.ID, "err", err)
|
||||
}
|
||||
d.removeEndedKitVolumes(ctx, task.ID, run.Volumes)
|
||||
}
|
||||
|
||||
// removeEndedKitVolumes removes the execution's Kit volumes unless the task
|
||||
// parked: a retry of a parked task is the same execution and resumes from
|
||||
// them.
|
||||
func (d *Daemon) removeEndedKitVolumes(ctx context.Context, taskID int64, volumes []kit.Volume) {
|
||||
if len(volumes) == 0 || d.Store == nil {
|
||||
return
|
||||
}
|
||||
lookupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
latest, err := d.Store.TaskByID(lookupCtx, taskID)
|
||||
if err != nil || latest == nil || latest.Status == workflow.StatusParked {
|
||||
return
|
||||
}
|
||||
if err := d.KitLauncher.RemoveVolumes(lookupCtx, volumes); err != nil {
|
||||
d.Log.Warn("kit volume removal failed", "task", taskID, "err", err)
|
||||
}
|
||||
}
|
||||
@@ -42,5 +42,5 @@ func runPinnedViaAgent(ctx context.Context, d *Daemon, task *workflow.Task, repo
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
d.runViaAgent(ctx, task, repo, profile)
|
||||
d.runViaAgent(ctx, task, repo, profile, nil)
|
||||
}
|
||||
Reference in new issue
Block a user