Harden Harness runtime, persistence and execution for Hand
This commit is contained in:
1 parent
09c30fe2d5
commit
0972eed3ea
164 files changed
+15912
-506
No files matched your search
@@ -0,0 +1,57 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// CallAdmission reserves capacity before an individual provider attempt. A
|
||||
// successful reservation returns a non-nil settlement callback, called exactly
|
||||
// once before terminal delivery. Missing usage is unknown, never zero cost.
|
||||
// Implementations must be concurrency safe and must not mutate the request.
|
||||
// Settlement must retain uncertain in-flight charges after cancellation.
|
||||
// A denial must leave no reservation behind. A settlement error must leave
|
||||
// conservative durable state; it turns the attempt into a visible error.
|
||||
type CallAdmission func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error)
|
||||
|
||||
type callAdmissionKey struct{}
|
||||
|
||||
// WithCallAdmission adds a guard; nested callers cannot remove earlier guards.
|
||||
// Guards run in installation order. If a later guard denies admission, earlier
|
||||
// reservations settle as not_dispatched, with no provider call made.
|
||||
func WithCallAdmission(ctx context.Context, guard CallAdmission) context.Context {
|
||||
previous, _ := ctx.Value(callAdmissionKey{}).([]CallAdmission)
|
||||
guards := append([]CallAdmission(nil), previous...)
|
||||
if guard != nil {
|
||||
guards = append(guards, guard)
|
||||
}
|
||||
return context.WithValue(ctx, callAdmissionKey{}, guards)
|
||||
}
|
||||
|
||||
func admitCall(ctx context.Context, req ChatRequest, record RequestUsage, guards []CallAdmission) (func(RequestUsage) error, error) {
|
||||
var settlements []func(RequestUsage) error
|
||||
settle := func(result RequestUsage) error {
|
||||
var failures []error
|
||||
for i := len(settlements) - 1; i >= 0; i-- {
|
||||
detached := result
|
||||
if result.Usage != nil {
|
||||
u := *result.Usage
|
||||
detached.Usage = &u
|
||||
}
|
||||
failures = append(failures, settlements[i](detached))
|
||||
}
|
||||
return errors.Join(failures...)
|
||||
}
|
||||
for _, guard := range guards {
|
||||
finish, err := guard(ctx, req, record.Category, record.ID)
|
||||
if err == nil && finish == nil {
|
||||
err = errors.New("admission guard returned no settlement callback")
|
||||
}
|
||||
if err != nil {
|
||||
record.Status = "not_dispatched"
|
||||
return nil, errors.Join(err, settle(record))
|
||||
}
|
||||
settlements = append(settlements, finish)
|
||||
}
|
||||
return settle, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAdmissionDenialUnwindsWithoutDispatch(t *testing.T) {
|
||||
denied := errors.New("budget exhausted")
|
||||
var records []RequestUsage
|
||||
ctx := WithCallAdmission(context.Background(), func(_ context.Context, _ ChatRequest, category CallCategory, id string) (func(RequestUsage) error, error) {
|
||||
if category != CallRetry || id == "" {
|
||||
t.Fatal("missing attempt identity")
|
||||
}
|
||||
return func(r RequestUsage) error { records = append(records, r); return nil }, nil
|
||||
})
|
||||
ctx = WithCallAdmission(ctx, func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
|
||||
return nil, denied
|
||||
})
|
||||
_, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallRetry, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
|
||||
t.Fatal("denied provider dispatched")
|
||||
return nil, nil
|
||||
})
|
||||
if !errors.Is(err, denied) || len(records) != 1 || records[0].Status != "not_dispatched" || records[0].Usage != nil {
|
||||
t.Fatalf("err %v records %+v", err, records)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdmissionSettlementPrecedesTerminalAndFailureIsVisible(t *testing.T) {
|
||||
failure := errors.New("ledger persistence failed")
|
||||
for _, category := range []CallCategory{CallGeneration, CallRetry, CallCompaction} {
|
||||
t.Run(string(category), func(t *testing.T) {
|
||||
settled := false
|
||||
ctx := WithCallAdmission(context.Background(), func(_ context.Context, _ ChatRequest, actual CallCategory, id string) (func(RequestUsage) error, error) {
|
||||
if actual != category {
|
||||
t.Fatal("wrong category")
|
||||
}
|
||||
return func(r RequestUsage) error {
|
||||
if r.ID != id || r.Usage == nil || r.Usage.OutputTokens != 7 || r.Status != "completed" {
|
||||
t.Errorf("record %+v", r)
|
||||
}
|
||||
settled = true
|
||||
return failure
|
||||
}, nil
|
||||
})
|
||||
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, category, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
|
||||
ch := make(chan ChatEvent, 1)
|
||||
ch <- ChatEvent{Type: EventDone, Usage: &Usage{OutputTokens: 7}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
count := 0
|
||||
for event := range ch {
|
||||
count++
|
||||
if !settled || event.Type != EventError || !errors.Is(event.Error, failure) {
|
||||
t.Fatalf("event %+v settled %v", event, settled)
|
||||
}
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatal("wrong terminal count")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdmissionConcurrentReservations(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
reserved, settlements := 0, 0
|
||||
guard := func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if reserved == 1 {
|
||||
return nil, errors.New("budget exhausted")
|
||||
}
|
||||
reserved++
|
||||
return func(r RequestUsage) error { mu.Lock(); defer mu.Unlock(); reserved--; settlements++; return nil }, nil
|
||||
}
|
||||
ctx := WithCallAdmission(context.Background(), guard)
|
||||
source := make(chan ChatEvent)
|
||||
first, err := ObserveChat(ctx, ChatRequest{}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) { return source, nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := ObserveChat(ctx, ChatRequest{}, CallCompaction, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
|
||||
t.Error("oversubscribed provider dispatched")
|
||||
return nil, nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("oversubscription accepted")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
source <- ChatEvent{Type: EventDone}
|
||||
close(source)
|
||||
for range first {
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if reserved != 0 || settlements != 1 {
|
||||
t.Fatalf("reserved %d settlements %d", reserved, settlements)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdmissionCancellationSettlesUnknownOnce(t *testing.T) {
|
||||
settled := make(chan RequestUsage, 2)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
ctx = WithCallAdmission(ctx, func(context.Context, ChatRequest, CallCategory, string) (func(RequestUsage) error, error) {
|
||||
return func(r RequestUsage) error { settled <- r; return nil }, nil
|
||||
})
|
||||
ch, err := ObserveChat(ctx, ChatRequest{}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) { return make(chan ChatEvent), nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cancel()
|
||||
for range ch {
|
||||
}
|
||||
r := <-settled
|
||||
if r.Status != "cancelled" || r.Usage != nil {
|
||||
t.Fatalf("record %+v", r)
|
||||
}
|
||||
select {
|
||||
case <-settled:
|
||||
t.Fatal("double settlement")
|
||||
default:
|
||||
}
|
||||
}
|
||||
@@ -152,7 +152,17 @@ func ParseReasoningMode(s string) (ReasoningMode, error) {
|
||||
}
|
||||
|
||||
// ChatRequest is the input to a streaming chat call.
|
||||
// CallRoute identifies the constructed provider client for local admission and
|
||||
// accounting. It is not sent to the provider. Destination must distinguish
|
||||
// custom endpoints from explicitly named provider defaults.
|
||||
type CallRoute struct {
|
||||
Provider string `json:"provider"`
|
||||
Destination string `json:"destination"`
|
||||
}
|
||||
|
||||
type ChatRequest struct {
|
||||
Route CallRoute `json:"-"`
|
||||
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
@@ -181,6 +191,8 @@ type ChatRequest struct {
|
||||
}
|
||||
|
||||
// Usage tracks token usage.
|
||||
// InputTokens is total input including cached input. Cache counters are
|
||||
// subsets used for pricing/analysis and must not be added again for context.
|
||||
type Usage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type CallCategory string
|
||||
|
||||
const (
|
||||
CallGeneration CallCategory = "generation"
|
||||
CallRetry CallCategory = "retry"
|
||||
CallCompaction CallCategory = "compaction"
|
||||
)
|
||||
|
||||
// RequestUsage represents one attempted provider call. Nil Usage explicitly
|
||||
// means unavailable, including potentially billable failures; it is not zero.
|
||||
// InputTokens includes cached input. Cache fields are subsets, not additions.
|
||||
type RequestUsage struct {
|
||||
ID string `json:"request_id"`
|
||||
Model string `json:"model"`
|
||||
Category CallCategory `json:"category"`
|
||||
Status string `json:"status"`
|
||||
Source string `json:"source"`
|
||||
Usage *Usage `json:"usage"`
|
||||
}
|
||||
|
||||
type usageObserverKey struct{}
|
||||
|
||||
// WithUsageObserver chains observers. Callbacks can run concurrently and must
|
||||
// not mutate their record. Each callback completes before its terminal event
|
||||
// is forwarded to the consumer.
|
||||
func WithUsageObserver(ctx context.Context, observer func(RequestUsage)) context.Context {
|
||||
previous, _ := ctx.Value(usageObserverKey{}).(func(RequestUsage))
|
||||
return context.WithValue(ctx, usageObserverKey{}, func(record RequestUsage) {
|
||||
if previous != nil {
|
||||
previous(record)
|
||||
}
|
||||
if observer != nil {
|
||||
observer(record)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ObserveChat observes streaming and non-streaming adapters using one contract.
|
||||
// Providers must terminate after EventDone/EventError and honour cancellation.
|
||||
func ObserveChat(ctx context.Context, req ChatRequest, category CallCategory, call func(context.Context, ChatRequest) (<-chan ChatEvent, error)) (<-chan ChatEvent, error) {
|
||||
observer, _ := ctx.Value(usageObserverKey{}).(func(RequestUsage))
|
||||
guards, _ := ctx.Value(callAdmissionKey{}).([]CallAdmission)
|
||||
if observer == nil && len(guards) == 0 {
|
||||
return call(ctx, req)
|
||||
}
|
||||
record := RequestUsage{ID: rand.Text(), Model: req.Model, Category: category, Source: "unavailable"}
|
||||
settle, err := admitCall(ctx, req, record, guards)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("provider admission: %w", err)
|
||||
}
|
||||
publish := func(status string, usage *Usage) error {
|
||||
record.Status = status
|
||||
if usage != nil {
|
||||
copy := *usage
|
||||
record.Usage = ©
|
||||
record.Source = "reported"
|
||||
}
|
||||
err := settle(record)
|
||||
if observer != nil {
|
||||
observer(record)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, errors.Join(err, context.Cause(ctx), publish("not_dispatched", nil))
|
||||
}
|
||||
source, err := call(ctx, req)
|
||||
if err != nil {
|
||||
status := "failed"
|
||||
if ctx.Err() != nil {
|
||||
status = "cancelled"
|
||||
}
|
||||
return nil, errors.Join(err, context.Cause(ctx), publish(status, nil))
|
||||
}
|
||||
if source == nil {
|
||||
return nil, errors.Join(fmt.Errorf("provider returned a nil event stream"), publish("failed", nil))
|
||||
}
|
||||
out := make(chan ChatEvent)
|
||||
go func() {
|
||||
defer close(out)
|
||||
var usage *Usage
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
publish("cancelled", usage)
|
||||
return
|
||||
case event, ok := <-source:
|
||||
if !ok {
|
||||
settlementErr := publish("failed", usage)
|
||||
select {
|
||||
case out <- ChatEvent{Type: EventError, Error: errors.Join(fmt.Errorf("provider stream closed without terminal event"), settlementErr, context.Cause(ctx))}:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return
|
||||
}
|
||||
if event.Usage != nil {
|
||||
copy := *event.Usage
|
||||
usage = ©
|
||||
}
|
||||
if event.Type == EventError && ctx.Err() != nil {
|
||||
event.Error = errors.Join(event.Error, context.Cause(ctx))
|
||||
}
|
||||
terminal := event.Type == EventDone || event.Type == EventError
|
||||
if terminal {
|
||||
status := "completed"
|
||||
if event.Type == EventError {
|
||||
status = "failed"
|
||||
}
|
||||
if err := publish(status, usage); err != nil {
|
||||
event.Type = EventError
|
||||
event.Error = errors.Join(event.Error, fmt.Errorf("provider settlement: %w", err))
|
||||
}
|
||||
}
|
||||
select {
|
||||
case out <- event:
|
||||
case <-ctx.Done():
|
||||
if !terminal {
|
||||
publish("cancelled", usage)
|
||||
}
|
||||
return
|
||||
}
|
||||
if terminal {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UsageLedger keeps immutable request records and a reported-only total.
|
||||
// Unknown requests remain visible through Records rather than being priced as
|
||||
// free. Create a ledger per bounded operation, not a process-global history.
|
||||
type UsageLedger struct {
|
||||
mu sync.Mutex
|
||||
records []RequestUsage
|
||||
total *Usage
|
||||
}
|
||||
|
||||
func (l *UsageLedger) Record(record RequestUsage) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if record.Usage != nil {
|
||||
u := *record.Usage
|
||||
record.Usage = &u
|
||||
if l.total == nil {
|
||||
l.total = &Usage{}
|
||||
}
|
||||
l.total.InputTokens += u.InputTokens
|
||||
l.total.OutputTokens += u.OutputTokens
|
||||
l.total.CacheCreationInputTokens += u.CacheCreationInputTokens
|
||||
l.total.CacheReadInputTokens += u.CacheReadInputTokens
|
||||
}
|
||||
l.records = append(l.records, record)
|
||||
}
|
||||
func (l *UsageLedger) Total() *Usage {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.total == nil {
|
||||
return nil
|
||||
}
|
||||
u := *l.total
|
||||
return &u
|
||||
}
|
||||
func (l *UsageLedger) Records() []RequestUsage {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
out := append([]RequestUsage(nil), l.records...)
|
||||
for i := range out {
|
||||
if out[i].Usage != nil {
|
||||
u := *out[i].Usage
|
||||
out[i].Usage = &u
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUsageObserverFailedRequestCanCarryReportedUsage(t *testing.T) {
|
||||
ledger := &UsageLedger{}
|
||||
ctx := WithUsageObserver(context.Background(), ledger.Record)
|
||||
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallRetry, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
|
||||
ch := make(chan ChatEvent, 1)
|
||||
ch <- ChatEvent{Type: EventError, Error: errors.New("failed"), Usage: &Usage{InputTokens: 42}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range ch {
|
||||
}
|
||||
records := ledger.Records()
|
||||
if len(records) != 1 || records[0].Status != "failed" || records[0].Source != "reported" || ledger.Total().InputTokens != 42 {
|
||||
t.Fatalf("records %+v total %+v", records, ledger.Total())
|
||||
}
|
||||
records[0].Usage.InputTokens = 100
|
||||
if ledger.Total().InputTokens != 42 {
|
||||
t.Fatal("records alias total")
|
||||
}
|
||||
}
|
||||
func TestUsageObserverReportsMissingTerminal(t *testing.T) {
|
||||
ledger := &UsageLedger{}
|
||||
ctx := WithUsageObserver(context.Background(), ledger.Record)
|
||||
ch, err := ObserveChat(ctx, ChatRequest{Model: "m"}, CallGeneration, func(context.Context, ChatRequest) (<-chan ChatEvent, error) {
|
||||
ch := make(chan ChatEvent)
|
||||
close(ch)
|
||||
return ch, nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var event ChatEvent
|
||||
for e := range ch {
|
||||
event = e
|
||||
}
|
||||
if event.Type != EventError || len(ledger.Records()) != 1 || ledger.Total() != nil {
|
||||
t.Fatal("missing terminal treated as success")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user