8000 feat(agentcore): define executor backend and worker contracts (#92) · felinics/twilight@35f6e16 · GitHub
[go: up one dir, main page]

Skip to content

Commit 35f6e16

Browse files
authored
feat(agentcore): define executor backend and worker contracts (#92)
* agentcore: add execution worker contracts * refactor(executor): keep worker notices with the worker * fix(executor): avoid unsafe test store conversions
1 parent d5ce602 commit 35f6e16

10 files changed

Lines changed: 1833 additions & 0 deletions

File tree

‎agentcore/executor/backend.go‎

Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
package executor
2+
3+
import (
4+
"context"
5+
"encoding/json"
6+
"fmt"
7+
8+
"github.com/felinics/twilight/agentcore/executor/notice"
9+
executionstore "github.com/felinics/twilight/agentcore/executor/store"
10+
"github.com/felinics/twilight/agentcore/run"
11+
"github.com/felinics/twilight/agentcore/run/effect"
12+
)
13+
14+
// ExecutionRef is the Executor's physical binding of the current attempt for
15+
// one effect: the provider (backend) it was handed to and that backend's
16+
// opaque handle (RUN-EXE-9). It lives in the Execution Record and in the
17+
// Backend contract; Agent Core addresses executions by AssignmentKey only.
18+
type ExecutionRef = executionstore.ExecutionRef
19+
20+
// ErrUnknownProvider reports a record whose ExecutionRef names a provider
21+
// this Worker has no Backend for (RUN-EXE-10). It is a definitive answer for
22+
// Outcome reads (effect.ErrOutcomeUnavailable): this process cannot reach the
23+
// execution and retrying will not change that.
24+
var ErrUnknownProvider = fmt.Errorf("executor: unknown execution provider: %w", effect.ErrOutcomeUnavailable)
25+
26+
// ExecutionBackend performs one provider's effects. It is addressed by Ref:
27+
// the Worker persists the Ref Prepare returns before Start, and every later
28+
// lifecycle operation names that Ref. A backend keeps no table keyed by
29+
// AssignmentKey.
30+
type ExecutionBackend interface {
31+
// Validate checks that this Backend can serve the Assignment; it produces
32+
// no external effect (RUN-EXE-5).
33+
Validate(ctx context.Context, a effect.Assignment) (*run.ToolFailure, error)
34+
// Prepare derives the Ref of the Assignment without starting the effect
35+
// and without allocating anything outside the Backend: it runs before
36+
// the acceptance is written, and an Abort may win that write (RUN-EXE-16),
37+
// in which case the Ref is simply never used. It is a pure function of
38+
// the AssignmentKey (a repeated Prepare returns the same Ref), so a
39+
// process that dies between Prepare and the record write recovers the
40+
// same binding. Anything that reserves or creates an external resource
41+
// belongs in Start, which runs only for an accepted execution.
42+
Prepare(ctx context.Context, a effect.Assignment) (ref string, err error)
43+
// Start begins the execution Ref names. A definite rejection is an
44+
// ordinary error; a request that may have crossed the effect boundary is
45+
// effect.ErrDispatchUnknown. Start of a Ref that already started is a
46+
// no-op.
47+
Start(ctx context.Context, ref string, a effect.Assignment) error
48+
// Restart allocates the Ref of a new physical execution of the same
49+
// Assignment after the Backend reported the previous one missing: the
50+
// next attempt for the effect (RUN-EXE-9). Unlike Prepare it is not
51+
// required to return the same Ref; a Backend whose physical execution is
52+
// the durable object itself (a child Session) returns the same Ref.
53+
// Whether a tool may be restarted at all is decided before the call,
54+
// by the Worker, from the Assignment's Replay policy (RUN-EXE-9).
55+
Restart(ctx context.Context, previous string, a effect.Assignment) (ref string, err error)
56+
// Attach reports what the Backend finds for Ref. Missing is a proof: the
57+
// execution Ref names does not exist and will not start, so the Worker
58+
// may replay or settle it. A Backend that cannot confirm either way
59+
// answers orphaned, never missing; the Worker then keeps the lease and
60+
// asks again (RUN-EXE-3). Active and terminal are observations of a
61+
// live or finished execution. A Ref the Backend cannot interpret is an
62+
// error, not an observation.
63+
Attach(ctx context.Context, ref string) (effect.Attachment, error)
64+
Status(ctx context.Context, ref string) (effect.ExecutionStatus, error)
65+
// Outcome is a read: the terminal Outcome of Ref once it has one,
66+
// effect.ErrOutcomeNotReady while it has none, effect.ErrExecutionNotFound
67+
// for a Ref the Backend does not know. It never blocks on the execution;
68+
// a Backend that can say when to read implements notice.Source, and the
69+
// Worker waits on that stream (RUN-EXE-17).
70+
Outcome(ctx context.Context, ref string) (effect.Outcome, error)
71+
Cancel(ctx context.Context, ref string) error
72+
}
73+
74+
// Route hands the Assignments Match accepts to one provider's Backend. The
75+
// Worker evaluates routes once, at Dispatch, and persists the chosen
76+
// provider in the record (RUN-EXE-10); a nil Match accepts every Assignment.
77+
type Route struct {
78+
Provider string
79+
Match func(effect.Assignment) bool
80+
Backend ExecutionBackend
81+
}
82+
83+
// Default is the Route that accepts every Assignment: the last route of a
84+
// Worker's table.
85+
func Default(provider string, b ExecutionBackend) Route { return Route{Provider: provider, Backend: b} }
86+
87+
// MatchModel is the Route predicate of model calls.
88+
func MatchModel(a effect.Assignment) bool { _, ok := a.Model(); return ok } //nolint:gocritic // hugeParam: Route.Match takes the Assignment by value
89+
90+
// MatchTool is the Route predicate of tool calls declared with placement
91+
// (RUN-LOP-9): a Worker routes by the declaration, never by whether a target
92+
// is present.
93+
func MatchTool(placement run.ToolPlacement) func(effect.Assignment) bool {
94+
return func(a effect.Assignment) bool { //nolint:gocritic // hugeParam: Route.Match takes the Assignment by value
95+
t, ok := a.Tool()
96+
return ok && t.Placement == placement
97+
}
98+
}
99+
100+
// PortBackend adapts an effect.ExecutionPort -- an executor addressed by
101+
// AssignmentKey, such as the remote HTTP client -- to the ExecutionBackend
102+
// contract, so a Worker can route between it and colocated backends. The Ref
103+
// is the key itself, encoded, so Prepare is deterministic and the adapter
104+
// holds no state. New backends implement ExecutionBackend directly.
105+
func PortBackend(p effect.ExecutionPort) ExecutionBackend { return portBackend{p} }
106+
107+
type portBackend struct{ port effect.ExecutionPort }
108+
109+
func (b portBackend) Validate(ctx context.Context, a effect.Assignment) (*run.ToolFailure, error) {
110+
return b.port.Validate(ctx, a)
111+
}
112+
113+
// Progress relays the frames of the port behind this backend when it offers
114+
// them (RUN-EXE-12); a port without progress ends the stream at once.
115+
func (b portBackend) Progress(ctx context.Context, key effect.AssignmentKey, after uint64, fn func(effect.ProgressFrame) bool) error {
116+
if p, ok := b.port.(effect.ProgressPort); ok {
117+
return p.Progress(ctx, key, after, fn)
118+
}
119+
return nil
120+
}
121+
122+
func (b portBackend) Prepare(_ context.Context, a effect.Assignment) (string, error) {
123+
raw, err := json.Marshal(a.Key())
124+
if err != nil {
125+
return "", err
126+
}
127+
return string(raw), nil
128+
}
129+
130+
func (b portBackend) key(ref string) (effect.AssignmentKey, error) {
131+
var key effect.AssignmentKey
132+
if err := json.Unmarshal([]byte(ref), &key); err != nil {
133+
return effect.AssignmentKey{}, fmt.Errorf("executor: ref is not an assignment key: %w", err)
134+
}
135+
return key, nil
136+
}
137+
138+
func (b portBackend) Start(ctx context.Context, _ string, a effect.Assignment) error {
139+
return b.port.Dispatch(ctx, a)
140+
}
141+
142+
// Restart of a Port-shaped executor re-dispatches the same key: the Ref is
143+
// the key, so it does not change.
144+
func (b portBackend) Restart(_ context.Context, previous string, _ effect.Assignment) (string, error) {
145+
return previous, nil
146+
}
147+
148+
// Attach forwards to the Port by key. A Ref that is not a key is an error:
149+
// the adapter cannot prove anything about an execution it cannot name.
150+
func (b portBackend) Attach(ctx context.Context, ref string) (effect.Attachment, error) {
151+
key, err := b.key(ref)
152+
if err != nil {
153+
return effect.Attachment{}, err
154+
}
155+
return b.port.Attach(ctx, key)
156+
}
157+
158+
func (b portBackend) Status(ctx context.Context, ref string) (effect.ExecutionStatus, error) {
159+
key, err := b.key(ref)
160+
if err != nil {
161+
return effect.ExecutionNotFound, err
162+
}
163+
return b.port.GetStatus(ctx, key)
164+
}
165+
166+
func (b portBackend) Outcome(ctx context.Context, ref string) (effect.Outcome, error) {
167+
key, err := b.key(ref)
168+
if err != nil {
169+
return effect.Outcome{}, err
170+
}
171+
return b.port.GetOutcome(ctx, key)
172+
}
173+
174+
// Settled relays the port's settlement stream as Ref notices, the Ref being
175+
// the encoded key Prepare derived, so a Worker in front of a remote executor
176+
// waits on the remote's notices instead of polling it (RUN-EXE-17). A port
177+
// without SettlementPort has no stream: Settled returns at once and the
178+
// Worker falls back to reading at intervals.
179+
func (b portBackend) Settled(ctx context.Context, epoch string, after uint64, fn func(notice.Ref) bool) error {
180+
settlements, ok := b.port.(effect.SettlementPort)
181+
if !ok {
182+
return nil
183+
}
184+
return settlements.Settlements(ctx, epoch, after, func(s effect.Settlement) bool {
185+
if s.Key == (effect.AssignmentKey{}) {
186+
// The stream's announcement of its epoch and head has no subject.
187+
return fn(notice.Ref{Epoch: s.Epoch, Sequence: s.Sequence})
188+
}
189+
raw, err := json.Marshal(s.Key)
190+
if err != nil {
191+
return true
192+
}
193+
return fn(notice.Ref{Ref: string(raw), Epoch: s.Epoch, Sequence: s.Sequence})
194+
})
195+
}
196+
197+
func (b portBackend) Cancel(ctx context.Context, ref string) error {
198+
key, err := b.key(ref)
199+
if err != nil {
200+
return err
201+
}
202+
return b.port.Cancel(ctx, key)
203+
}

0 commit comments

Comments
 (0)
0