Harden Harness runtime, persistence and execution for Hand
This commit is contained in:
1 parent
09c30fe2d5
commit
0972eed3ea
164 files changed
+15851
-445
No files matched your search
@@ -0,0 +1,45 @@
|
||||
name: Qualify Harness
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main, 'codex/**']
|
||||
workflow_dispatch:
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
native:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest]
|
||||
runs-on: ${{ matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- name: Record candidate identity
|
||||
run: |
|
||||
mkdir evidence
|
||||
git rev-parse HEAD > evidence/commit.txt
|
||||
git status --porcelain > evidence/status.txt
|
||||
go version > evidence/toolchain.txt
|
||||
go env -json GOOS GOARCH GOVERSION > evidence/platform.json
|
||||
- name: Build and vet
|
||||
run: |
|
||||
go build ./... > evidence/build.txt 2>&1
|
||||
go vet ./... > evidence/vet.txt 2>&1
|
||||
- name: Uncached race and coverage suite
|
||||
run: go test -count=1 -timeout=10m -race -json -covermode=atomic -coverprofile=evidence/coverage.out ./... > evidence/tests.jsonl 2> evidence/tests.stderr
|
||||
- name: Reject skipped or incomplete qualification
|
||||
run: python3 scripts/check_test_events.py evidence/tests.jsonl > evidence/test-gate.json
|
||||
- name: Repeat lifecycle regressions
|
||||
run: go test -count=20 -race -timeout=10m -json ./process ./tools/bash ./runtime -run 'TestCancellationStopsShellDescendant|TestNormalExitStopsShellDescendant|TestArtifactCrossProcessReservation|TestRun_StreamingAbortMidKickoffPairsAllEntries' > evidence/critical-repeat.jsonl 2> evidence/critical-repeat.stderr
|
||||
- name: Reject skipped or incomplete lifecycle repetitions
|
||||
run: python3 scripts/check_test_events.py evidence/critical-repeat.jsonl > evidence/repeat-gate.json
|
||||
- name: Preserve raw results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: harness-${{ matrix.os }}-${{ github.sha }}
|
||||
path: evidence/
|
||||
@@ -404,3 +404,39 @@ for the changelog of each tagged version.
|
||||
## License
|
||||
|
||||
MIT — see [`LICENSE`](./LICENSE).
|
||||
|
||||
## Usage accounting
|
||||
|
||||
See [USAGE.md](USAGE.md) for request-level records, reported versus unknown usage,
|
||||
retry/compaction accounting and the cache-counter migration from v0.3.9.
|
||||
|
||||
### Managed subprocess lifecycle and output
|
||||
|
||||
The `process` package creates a private Unix process group for a command and
|
||||
kills that group on context cancellation. `process.Run` joins the command and
|
||||
removes descendants after normal exit too. Callers using `Start`/`Wait` directly
|
||||
must call `process.KillGroup` when their protocol closes. Bash and stdio MCP use
|
||||
this lifecycle; non-Unix platforms currently provide direct-child cleanup only.
|
||||
A child that deliberately starts a new session can escape a process group: this
|
||||
is lifecycle management, not isolation. Use a containment backend for isolation.
|
||||
|
||||
`process.Capture` drains output while retaining a bounded prefix. Bash retains
|
||||
at most 64 KiB per stdout/stderr stream and includes explicit truncation notices,
|
||||
observed byte counts, truncation flags, cancellation/timeout flags and an exit
|
||||
code when available in result metadata. Cancellation and timeout reasons remain
|
||||
visible even if stderr has content. Output exceeding the memory prefix is spooled into private 0600 artifacts. The
|
||||
metadata and inline notice identify their paths, captured bytes, disk truncation
|
||||
and any capture error. The default store is `harness-output-<uid>` under the OS
|
||||
temporary directory; callers may provide BashTool.OutputStore to choose a
|
||||
private directory. Treat output as potentially sensitive.
|
||||
|
||||
Each artifact is capped at 8 MiB and the store reserves at most 64 MiB across
|
||||
active and completed captures. Cooperating processes use advisory locks so
|
||||
active files cannot be evicted; completed files are evicted oldest first.
|
||||
Allocation also removes completed files older than 24 hours. Time-based cleanup
|
||||
is lazy, so files can remain until the next allocation; storage remains bounded.
|
||||
Artifacts are ephemeral and paths can expire after eviction. A full active quota
|
||||
or write failure is explicitly reported while output continues to drain.
|
||||
Artifact locking is supported on Unix; other platforms report unavailable disk
|
||||
capture and retain the bounded inline prefix. These locks do not defend against
|
||||
malicious programs running as the same user.
|
||||
@@ -0,0 +1,120 @@
|
||||
# Session JSONL format, version 1
|
||||
|
||||
New sessions begin with one `session_header` record. Its nonempty `id` is the
|
||||
session identity, `schemaVersion` is 1, and `timestamp` records creation time.
|
||||
The header has no parent. It is independent of agent/key names and survives
|
||||
renaming the file. Copying a file preserves identity; a product-level fork must
|
||||
assign a new identity explicitly rather than pretending the copy is a new session.
|
||||
|
||||
```json
|
||||
{"id":"ses_example","type":"session_header","schemaVersion":1,"timestamp":1788796800,"data":null}
|
||||
{"id":"e_example","type":"message","role":"user","timestamp":1788796801,"data":{"text":"Hello"}}
|
||||
```
|
||||
|
||||
The header must be the first nonblank record and cannot occur again. Unsupported
|
||||
header versions, a version field on a conversation record, and graph links to
|
||||
headers or selection controls are errors. No loader, recovery or migration path
|
||||
silently accepts an unsupported version. Entry IDs are unique within the log;
|
||||
parents precede children. Selection controls use `type: selection`, their target
|
||||
in `parentId`, and `data: {"version":1}`. They select a conversation node without
|
||||
becoming part of its history. Ordinary appends subsequently select the new node.
|
||||
|
||||
`Session.Entries` contains graph entries and selection controls, excluding the
|
||||
format header. `History` and `View` exclude both kinds of control record. A raw
|
||||
file export must retain the header; serialising `Entries` alone is not a complete
|
||||
identity-preserving session export. Store.List exposes the stored session ID and
|
||||
excludes the header from EntryCount.
|
||||
|
||||
Store.Create commits a complete synced header file without overwriting an
|
||||
existing key. First append to a new/empty file writes the header before the entry.
|
||||
Rewrite retains the same header. Use an exclusive session lease and Flush/Close
|
||||
according to their documented producer-joining contract. A failed append may
|
||||
leave an incomplete final record and must be treated as degraded persistence.
|
||||
|
||||
Legacy headerless files remain readable without implicit modification. Their
|
||||
historical format has no persisted session ID, so ordinary Load still assigns
|
||||
an ephemeral ID. Use MigrateLegacy before exposing durable session identity:
|
||||
it adds the version-1 header, corrects supported old compaction duplicate IDs,
|
||||
and retains a synced complete-original backup before atomic replacement. The
|
||||
report distinguishes format upgrade from duplicate-ID remapping. Repeating the
|
||||
migration on a valid version-1 file preserves its exact bytes and ID.
|
||||
|
||||
Recovery repairs only incomplete final JSON objects and retains its own backup.
|
||||
A future-version or structurally invalid complete record is never a recoverable
|
||||
tail. Truncated first-header recovery yields an empty log; without a complete
|
||||
header there was no recoverable durable identity. Unsupported versions require
|
||||
an explicit future migration implementation.
|
||||
|
||||
Payload-specific schemas, application session catalogues, attachment/export
|
||||
policies and cross-platform release qualification remain separate work. Unknown
|
||||
JSON fields are retained by the legacy converter; generic typed rewrites do not
|
||||
promise lossless preservation of arbitrary unknown fields.
|
||||
|
||||
## Application annotations
|
||||
|
||||
`annotation` records contain `data: {"version":1,"kind":"app.name","payload":{...}}`.
|
||||
They are durable application metadata, exposed by Entries and Annotations but
|
||||
excluded from History and View. They do not move the selected leaf, even in an
|
||||
empty session. Their optional parent attaches them to the current conversation
|
||||
node; conversation nodes cannot use annotations as parents or branch targets.
|
||||
Kinds contain ASCII letters, digits, dots, underscores or hyphens (1–128 bytes).
|
||||
The encoded annotation data is limited to 64 KiB. Unsupported annotation versions
|
||||
are rejected. Annotate flushes before committing the in-memory record; invalid
|
||||
input returns an error without degrading persistence. Stored metadata is retained
|
||||
by full graph rewrites and raw exports. Applications define payload schemas,
|
||||
request deduplication and inherited-versus-new accounting semantics for forks.
|
||||
|
||||
This extension is part of the unpublished session format candidate. The older
|
||||
5cc93a3 development snapshot does not implement annotation control semantics and
|
||||
must not be used to load files created by this candidate.
|
||||
|
||||
## Attachment references (unpublished development format)
|
||||
|
||||
New persistent message/tool-result images store `attachment: {sha256, size}`
|
||||
instead of base64 `data`. Blobs live in the agent session directory's private
|
||||
`.attachments` directory. Legacy inline data remains readable. Image MIME type
|
||||
and unknown payload fields remain in JSONL. AppendContext publishes and syncs
|
||||
blobs before the referring record; ResolveImages verifies and hydrates them for
|
||||
model replay. Missing/corrupt references are errors. In-memory sessions retain
|
||||
inline data. This extension requires the corresponding runtime; older loaders
|
||||
must not be used for image replay on these unpublished candidates.
|
||||
|
||||
CopyAttachments publishes only referenced blobs into a target store before its
|
||||
session JSONL is published. Portable JSONL copies must travel together with their
|
||||
sibling `.attachments` directory. Copying JSONL alone is insufficient when it
|
||||
contains references. Blob quotas do not evict existing session data.
|
||||
|
||||
MigrateLegacy also externalizes legacy inline images, including image records
|
||||
larger than the normal reader limit. Its migration-only record cap is 64 MiB,
|
||||
within the existing 128 MiB total import cap. Each blob must fit the attachment
|
||||
store's 32 MiB limit. Normalized output still passes the unchanged 10 MiB record
|
||||
reader and strict graph/duplicate-ID validation before replacement. The backup
|
||||
and reported source digest refer to the original unmodified bytes. The report's
|
||||
ExternalizedImages count describes transformed image occurrences. Repeated
|
||||
migration of reference-backed records leaves bytes and identity unchanged.
|
||||
Invalid image data and oversized non-image records remain errors. A failed
|
||||
conversion can leave unreferenced immutable blobs; it never rewrites the source.
|
||||
Combined recovery is available through the explicit MigrateRecovering API.
|
||||
|
||||
## Combined recovery and migration
|
||||
|
||||
MigrateLegacy remains strict about unfinished tails. MigrateRecovering may
|
||||
remove only a syntactically unfinished final JSON object, preserving a full
|
||||
original backup. It converts and validates the complete retained prefix under
|
||||
one lifetime writer lease, including oversized inline images and recognised
|
||||
historical compaction clones. Interior corruption, terminated malformed records
|
||||
and invalid retained graphs remain errors with no source replacement.
|
||||
TailRecovered and DiscardedTailBytes are set only after replacement; Migrated
|
||||
still indicates replacement when a later directory sync fails. The source hash
|
||||
covers the full original including the discarded tail. Restart is idempotent.
|
||||
|
||||
### Listing metadata
|
||||
|
||||
`Store.List` scans records up to the legacy image import record limit and checks
|
||||
scan/read errors. Each `SessionInfo.MetadataError` is empty only when that file's
|
||||
metadata scan completed. On failure the key stays discoverable for explicit
|
||||
recovery, but ID and entry count are cleared; timestamps use file modification
|
||||
time when available. Non-regular files are reported without opening them.
|
||||
Listing extracts syntactic metadata; it does not validate the session graph or
|
||||
replace leased loading/migration. Callers must not interpret a metadata error as
|
||||
an empty, valid session.
|
||||
@@ -0,0 +1,63 @@
|
||||
# Usage accounting
|
||||
|
||||
`llm.Usage.InputTokens` is total input, including cached input. Cache-read and
|
||||
cache-creation counters are subsets used for pricing and analysis. Do not add
|
||||
them to InputTokens when calculating context occupancy or total input. The
|
||||
Anthropic adapter normalizes its separate wire counters to this contract;
|
||||
OpenAI-style prompt-token totals already include all input.
|
||||
|
||||
This changes Anthropic InputTokens from its old uncached-only value. Consumers
|
||||
upgrading from v0.3.9 must remove their extra addition of cache counters. For
|
||||
example, 10 uncached + 42 cache creation + 17 cache read becomes InputTokens=69,
|
||||
not 10 and not 128 after adding cache twice.
|
||||
|
||||
`runtime.EventRequestUsage` carries one `llm.RequestUsage` per provider attempt:
|
||||
request ID, model, category (`generation`, `retry`, `compaction`), status,
|
||||
source (`reported` or `unavailable`) and optional usage. A nil usage value is
|
||||
unknown, including on potentially billable failures. It must never be priced
|
||||
as zero or replaced by the preceding request's usage. No estimated figure is
|
||||
labelled reported by this layer.
|
||||
|
||||
Use the newest applicable generation/retry record for the active model when
|
||||
showing context occupancy. Use the sum of records for consumption. Ten
|
||||
20,000-input requests consume 200,000 reported input tokens while the newest
|
||||
request occupies approximately 20,000 input tokens. An unavailable newest
|
||||
record makes current occupancy unknown; model/session changes also require
|
||||
resetting a consumer's gauge.
|
||||
|
||||
`EventDone.Usage` is a reported-only aggregate for the run, including observed
|
||||
retries and run-owned background and synchronous compaction. It is incomplete whenever any request
|
||||
record has unavailable usage. RunTurn returns the aggregate for that call,
|
||||
including refusal retries, rather than only the last attempt. Request records
|
||||
are available on error paths even when no EventDone is emitted.
|
||||
|
||||
Compaction returns its attempt records in `compaction.Result.Requests`.
|
||||
`Manager.OnUsage` optionally observes all compaction attempts, including
|
||||
background compaction. The observer must be concurrency-safe. Background work
|
||||
started with `MaybeCompactAsyncContext` retains the caller's cancellation and
|
||||
usage observer. Runtime joins its background producer and flushes the session
|
||||
before emitting EventDone or closing the event stream. Cancellation during
|
||||
that join produces EventAborted instead of a successful EventDone. This may
|
||||
add summarisation latency at the end of a run; consume the stream until it
|
||||
closes, including after cancellation.
|
||||
|
||||
The legacy `MaybeCompactAsync` API still creates detached work. Applications
|
||||
using it must own that producer separately and collect its session accounting.
|
||||
`JoinInFlight` cancels on caller cancellation and still waits for the producer
|
||||
to exit; prevent new launches while joining or releasing session ownership.
|
||||
Providers must honour cancellation for bounded shutdown. When combining event and
|
||||
callback streams, deduplicate by request ID.
|
||||
|
||||
`llm.WithUsageObserver` can be used by other adapters with `llm.ObserveChat`.
|
||||
Observers are invoked before the terminal event is forwarded; providers must
|
||||
honour cancellation and end their streams after EventDone/EventError.
|
||||
`RunTurn` preserves serial delivery of its TurnEmit callbacks. UsageLedger is
|
||||
intended for a bounded operation, not an unbounded global history. Persistence,
|
||||
price schedules and budget admission remain application responsibilities.
|
||||
|
||||
Context-owned compaction retains its completed result until `JoinInFlight` (or
|
||||
`ForgetSession`) consumes it. Always join, even when `HasInFlight` is false:
|
||||
that method reports active execution, not an unread result. Repeated launches
|
||||
return the existing handle until consumption, preventing an unread failure
|
||||
from being overwritten. `WaitForInFlight` observes without consuming. This
|
||||
retains at most one result per owned session; release it when ownership ends.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Session attachment storage
|
||||
|
||||
`Open(directory, quotaBytes)` opens a private (0700) content store. Its parent directory must already exist;
|
||||
the store directory and its parent publication are synced before use. Use
|
||||
`DefaultStoreBytes` for a 1 GiB quota. `Put(ctx, data)` publishes a synced 0600
|
||||
blob and returns a `Ref` containing its lowercase SHA-256 digest and exact byte
|
||||
length. `Read(ctx, ref)` verifies regular-file identity, size and digest. Blobs
|
||||
are limited to 32 MiB; MIME type belongs in the referring session record.
|
||||
|
||||
Publication uses a synced temporary file, exclusive hard link and directory
|
||||
sync. A cross-process lock serialises deduplication, quota admission and
|
||||
publication on Linux/macOS. Interrupted pending files are removed under that
|
||||
lock on a later new-content put. Existing published attachments are never
|
||||
evicted. A full store fails admission. Directory scanning is bounded to 8192
|
||||
entries, including control files; oversized stores require explicit maintenance.
|
||||
|
||||
References contain no caller-chosen filesystem path. File operations use
|
||||
`os.Root`; external symlinks cannot escape that root. The caller owns the
|
||||
configured private root and must not replace it with an untrusted directory.
|
||||
Do not close the store until its operations have joined. Cancellation interrupts
|
||||
lock waits and chunked I/O; the caller still owns its input byte slice until Put
|
||||
returns. Other platforms reject writer locking explicitly.
|
||||
|
||||
This package is the storage foundation. Session image references, runtime
|
||||
hydration, legacy inline-image conversion, fork copying and portable export
|
||||
packaging must be integrated before claiming attachment workflow completion.
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build !darwin && !linux
|
||||
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func lock(context.Context, *os.File) error {
|
||||
return errors.New("attachment writer locking unsupported on this platform")
|
||||
}
|
||||
func unlock(*os.File) {}
|
||||
@@ -0,0 +1,34 @@
|
||||
//go:build darwin || linux
|
||||
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"golang.org/x/sys/unix"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func lock(ctx context.Context, f *os.File) error {
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
err := unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, unix.EWOULDBLOCK) && !errors.Is(err, unix.EAGAIN) {
|
||||
return err
|
||||
}
|
||||
timer := time.NewTimer(10 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func unlock(f *os.File) { _ = unix.Flock(int(f.Fd()), unix.LOCK_UN) }
|
||||
@@ -0,0 +1,267 @@
|
||||
// Package attachment stores immutable session attachments by their content hash.
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const MaxBlobBytes int64 = 32 << 20
|
||||
const DefaultStoreBytes int64 = 1 << 30
|
||||
const maxEntries = 8192
|
||||
|
||||
// Ref has no path chosen by a caller. MIME type belongs to the referring entry.
|
||||
type Ref struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
Size int64 `json:"size"`
|
||||
}
|
||||
|
||||
func (r Ref) Validate() error {
|
||||
if len(r.SHA256) != 64 || r.Size < 0 || r.Size > MaxBlobBytes {
|
||||
return errors.New("invalid attachment reference")
|
||||
}
|
||||
for _, c := range r.SHA256 {
|
||||
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
||||
return errors.New("invalid attachment digest")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
root *os.Root
|
||||
limit int64
|
||||
}
|
||||
|
||||
// Open opens a private directory. Close after all operations join. A full store
|
||||
// rejects new content; existing session attachments are never evicted.
|
||||
func Open(dir string, limit int64) (*Store, error) {
|
||||
if limit <= 0 {
|
||||
return nil, errors.New("attachment quota must be positive")
|
||||
}
|
||||
if err := os.Mkdir(dir, 0700); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Lstat(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return nil, errors.New("attachment directory must be private (0700)")
|
||||
}
|
||||
root, err := os.OpenRoot(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A durable blob directory also needs its name synced in the parent before
|
||||
// any session record can refer to a blob inside it. The parent must exist.
|
||||
parent, err := os.Open(filepath.Dir(dir))
|
||||
if err != nil {
|
||||
root.Close()
|
||||
return nil, err
|
||||
}
|
||||
if err = errors.Join(parent.Sync(), parent.Close()); err != nil {
|
||||
root.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Store{root: root, limit: limit}, nil
|
||||
}
|
||||
func (s *Store) Close() error { return s.root.Close() }
|
||||
|
||||
func (s *Store) Put(ctx context.Context, data []byte) (Ref, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if int64(len(data)) > MaxBlobBytes {
|
||||
return Ref{}, errors.New("attachment exceeds blob limit")
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
ref := Ref{SHA256: hex.EncodeToString(digest[:]), Size: int64(len(data))}
|
||||
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer guard.Close()
|
||||
if err := lock(ctx, guard); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer unlock(guard)
|
||||
if _, err := s.root.Lstat(ref.SHA256); err == nil {
|
||||
if _, err := s.Read(ctx, ref); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
// Reestablish a durability fence when reusing a prior publication.
|
||||
f, err := s.root.Open(ref.SHA256)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
err = f.Sync()
|
||||
closeErr := f.Close()
|
||||
if err = errors.Join(err, closeErr, s.sync()); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
return ref, nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return Ref{}, err
|
||||
}
|
||||
used, err := s.usage(ctx)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if ref.Size > s.limit-used {
|
||||
return Ref{}, errors.New("attachment store quota exceeded")
|
||||
}
|
||||
name := ".pending-" + rand.Text()
|
||||
f, err := s.root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
defer s.root.Remove(name)
|
||||
for offset := 0; offset < len(data); {
|
||||
if err = ctx.Err(); err != nil {
|
||||
f.Close()
|
||||
return Ref{}, err
|
||||
}
|
||||
end := min(offset+64*1024, len(data))
|
||||
n, writeErr := f.Write(data[offset:end])
|
||||
offset += n
|
||||
if writeErr != nil {
|
||||
f.Close()
|
||||
return Ref{}, writeErr
|
||||
}
|
||||
if n == 0 {
|
||||
f.Close()
|
||||
return Ref{}, io.ErrShortWrite
|
||||
}
|
||||
}
|
||||
err = f.Sync()
|
||||
err = errors.Join(err, f.Close())
|
||||
if err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = s.root.Link(name, ref.SHA256); err != nil {
|
||||
return Ref{}, err
|
||||
}
|
||||
if err = s.sync(); err != nil {
|
||||
return Ref{}, fmt.Errorf("attachment published but directory sync failed: %w", err)
|
||||
}
|
||||
return ref, nil
|
||||
}
|
||||
|
||||
func (s *Store) Read(ctx context.Context, ref Ref) ([]byte, error) {
|
||||
if err := ref.Validate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := s.root.Lstat(ref.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() != ref.Size {
|
||||
return nil, errors.New("attachment is not a regular file of the declared size")
|
||||
}
|
||||
f, err := s.root.Open(ref.SHA256)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
actual, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !actual.Mode().IsRegular() || !os.SameFile(info, actual) || actual.Size() != ref.Size {
|
||||
return nil, errors.New("attachment changed while opening")
|
||||
}
|
||||
data := make([]byte, 0, int(ref.Size))
|
||||
buffer := make([]byte, 64*1024)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := f.Read(buffer)
|
||||
if int64(len(data)+n) > ref.Size {
|
||||
return nil, errors.New("attachment grew past declared size")
|
||||
}
|
||||
data = append(data, buffer[:n]...)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
digest := sha256.Sum256(data)
|
||||
if int64(len(data)) != ref.Size || hex.EncodeToString(digest[:]) != ref.SHA256 {
|
||||
return nil, errors.New("attachment integrity check failed")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (s *Store) sync() error {
|
||||
dir, err := s.root.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return errors.Join(dir.Sync(), dir.Close())
|
||||
}
|
||||
|
||||
// Called under the cross-process writer lock. Pending files are leftovers of
|
||||
// interrupted puts; published blobs are never removed by this cleanup.
|
||||
func (s *Store) usage(ctx context.Context) (int64, error) {
|
||||
dir, err := s.root.Open(".")
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer dir.Close()
|
||||
entries, err := dir.ReadDir(maxEntries + 1)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return 0, err
|
||||
}
|
||||
if len(entries) > maxEntries {
|
||||
return 0, errors.New("attachment directory entry limit exceeded")
|
||||
}
|
||||
var used int64
|
||||
for _, entry := range entries {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
name := entry.Name()
|
||||
if name == ".lock" {
|
||||
continue
|
||||
}
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return 0, errors.New("non-regular attachment store entry")
|
||||
}
|
||||
if strings.HasPrefix(name, ".pending-") {
|
||||
if err := s.root.Remove(name); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err := (Ref{SHA256: name, Size: info.Size()}).Validate(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if info.Size() > s.limit-used {
|
||||
return 0, errors.New("attachment store exceeds quota")
|
||||
}
|
||||
used += info.Size()
|
||||
}
|
||||
return used, nil
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func openTest(t *testing.T, dir string, quota int64) *Store {
|
||||
t.Helper()
|
||||
if err := os.Chmod(dir, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := Open(dir, quota)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestLargeAttachmentRoundTripAndDeduplication(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, DefaultStoreBytes)
|
||||
data := bytes.Repeat([]byte{0x42}, 12<<20)
|
||||
ref, err := s.Put(context.Background(), data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
duplicate, err := s.Put(context.Background(), data)
|
||||
if err != nil || duplicate != ref {
|
||||
t.Fatal(duplicate, err)
|
||||
}
|
||||
other := openTest(t, dir, DefaultStoreBytes)
|
||||
got, err := other.Read(context.Background(), ref)
|
||||
if err != nil || !bytes.Equal(got, data) {
|
||||
t.Fatal("reopened blob changed", err)
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 2 {
|
||||
t.Fatal("deduplication left extra files", entries)
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(dir, ref.SHA256))
|
||||
if err != nil || info.Mode().Perm() != 0600 {
|
||||
t.Fatal(info, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentIntegrityAndTraversal(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
ref, err := s.Put(context.Background(), []byte("original"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, ref.SHA256), []byte("modified"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err == nil {
|
||||
t.Fatal("tampering accepted")
|
||||
}
|
||||
if _, err := s.Put(context.Background(), []byte("original")); err == nil {
|
||||
t.Fatal("corrupt existing blob reused")
|
||||
}
|
||||
if _, err := s.Read(context.Background(), Ref{SHA256: "../outside", Size: 1}); err == nil {
|
||||
t.Fatal("path accepted as digest")
|
||||
}
|
||||
if err := os.Remove(filepath.Join(dir, ref.SHA256)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outside := filepath.Join(t.TempDir(), "secret")
|
||||
if err := os.WriteFile(outside, []byte("original"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(outside, filepath.Join(dir, ref.SHA256)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err == nil {
|
||||
t.Fatal("symlink accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentQuotaSerialisesIndependentStores(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
stores := []*Store{openTest(t, dir, 10), openTest(t, dir, 10)}
|
||||
var wg sync.WaitGroup
|
||||
errs := make([]error, 2)
|
||||
refs := make([]Ref, 2)
|
||||
for i := range stores {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
refs[i], errs[i] = stores[i].Put(context.Background(), bytes.Repeat([]byte{byte(i)}, 8))
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
success := 0
|
||||
for i, err := range errs {
|
||||
if err == nil {
|
||||
success++
|
||||
if _, err := stores[i].Read(context.Background(), refs[i]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if success != 1 {
|
||||
t.Fatalf("quota accepted %d independent writes: %v", success, errs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentCancellationAndPendingCleanup(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
guard, err := s.root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer guard.Close()
|
||||
if err := lock(context.Background(), guard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
|
||||
defer cancel()
|
||||
_, err = s.Put(ctx, []byte("cancelled"))
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unlock(guard)
|
||||
if err := os.WriteFile(filepath.Join(dir, ".pending-orphan"), []byte("unfinished"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, err := s.Put(context.Background(), []byte("complete"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, ".pending-orphan")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("orphan retained", err)
|
||||
}
|
||||
cancelled, stop := context.WithCancel(context.Background())
|
||||
stop()
|
||||
if _, err := s.Read(cancelled, ref); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Read(context.Background(), ref); err != nil {
|
||||
t.Fatal("cancellation damaged content", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAttachmentLimitsAndPrivateDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
s := openTest(t, dir, 100)
|
||||
if _, err := s.Put(context.Background(), make([]byte, MaxBlobBytes+1)); err == nil {
|
||||
t.Fatal("oversized blob accepted")
|
||||
}
|
||||
if _, err := s.Put(context.Background(), make([]byte, 101)); err == nil {
|
||||
t.Fatal("quota exceeded")
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name() != ".lock" {
|
||||
t.Fatal("failed put published file", entry.Name())
|
||||
}
|
||||
}
|
||||
if _, err := Open(t.TempDir(), 0); err == nil {
|
||||
t.Fatal("invalid quota accepted")
|
||||
}
|
||||
public := t.TempDir()
|
||||
if err := os.Chmod(public, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := Open(public, 100); err == nil {
|
||||
t.Fatal("public directory accepted")
|
||||
}
|
||||
}
|
||||
+349
@@ -0,0 +1,349 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
var ErrCostExhausted = fmt.Errorf("session cost budget: %w", ErrExhausted)
|
||||
|
||||
const costKind = "harness.budget.cost.v1"
|
||||
|
||||
type CostAttempt struct {
|
||||
ID string `json:"id"`
|
||||
Category llm.CallCategory `json:"category"`
|
||||
Model string `json:"model"`
|
||||
Quote PriceQuote `json:"quote"`
|
||||
ChargedNano int64 `json:"charged_nano"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
type CostState struct {
|
||||
Currency string `json:"currency"`
|
||||
LimitNano int64 `json:"limit_nano"`
|
||||
CommittedNano int64 `json:"committed_nano"`
|
||||
Strict bool `json:"strict"`
|
||||
Exhausted bool `json:"exhausted"`
|
||||
Unknown int `json:"unknown_attempts"`
|
||||
Attempts []CostAttempt `json:"attempts"`
|
||||
}
|
||||
type costEvent struct {
|
||||
Version int `json:"version"`
|
||||
Kind string `json:"kind"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
LimitNano int64 `json:"limit_nano,omitempty"`
|
||||
Strict bool `json:"strict,omitempty"`
|
||||
Attempt *CostAttempt `json:"attempt,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
ChargedNano int64 `json:"charged_nano,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
// CostLedger records session-wide attempt costs in nano-units of one currency.
|
||||
// Use an exclusively loaded disk Session for cross-process ownership. Unknown
|
||||
// advisory charges remain visible and prevent silently enabling strict mode.
|
||||
// Interrupted attempts retain their reservation and exact pricing snapshot.
|
||||
type CostLedger struct {
|
||||
session *session.Session
|
||||
kind string
|
||||
}
|
||||
|
||||
func OpenCostLedger(s *session.Session) (*CostLedger, error) {
|
||||
return openCostLedger(s, costKind)
|
||||
}
|
||||
|
||||
func openCostLedger(s *session.Session, kind string) (*CostLedger, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("cost budget requires a session")
|
||||
}
|
||||
l := &CostLedger{session: s, kind: kind}
|
||||
_, _, err := l.read()
|
||||
return l, err
|
||||
}
|
||||
func currencyValid(s string) bool {
|
||||
return len(s) == 3 && strings.IndexFunc(s, func(r rune) bool { return r < 'A' || r > 'Z' }) < 0
|
||||
}
|
||||
func (l *CostLedger) read() (CostState, int, error) {
|
||||
var state CostState
|
||||
records := l.session.Annotations(l.kind)
|
||||
if len(records) > maxRecords {
|
||||
return state, 0, errors.New("cost journal exceeds record limit")
|
||||
}
|
||||
index := map[string]int{}
|
||||
for _, record := range records {
|
||||
var e costEvent
|
||||
if err := decodeBudgetJSON(record.Payload, &e); err != nil {
|
||||
return state, 0, err
|
||||
}
|
||||
if e.Version != 1 {
|
||||
return state, 0, errors.New("invalid cost record")
|
||||
}
|
||||
switch e.Kind {
|
||||
case "decision":
|
||||
if !currencyValid(e.Currency) || (state.Currency != "" && state.Currency != e.Currency) || e.LimitNano <= state.CommittedNano || e.LimitNano > maxTokens || (e.Strict && state.Unknown > 0) {
|
||||
return state, 0, errors.New("invalid cost decision")
|
||||
}
|
||||
state.Currency = e.Currency
|
||||
state.LimitNano = e.LimitNano
|
||||
state.Strict = e.Strict
|
||||
state.Exhausted = false
|
||||
case "reserve":
|
||||
a := e.Attempt
|
||||
if a == nil || a.ID == "" || len(a.ID) > 128 || len(a.Model) > 1024 || a.Status != "reserved" || state.LimitNano == 0 || state.Exhausted {
|
||||
return state, 0, errors.New("invalid cost reservation")
|
||||
}
|
||||
if _, ok := index[a.ID]; ok {
|
||||
return state, 0, errors.New("duplicate cost attempt")
|
||||
}
|
||||
q := a.Quote
|
||||
if q.Nano < 0 || q.Nano > maxTokens || a.ChargedNano != q.Nano || (q.Currency != "" && q.Currency != state.Currency) || (!q.Known && (q.Nano != 0 || q.Reason == "" || state.Strict)) {
|
||||
return state, 0, errors.New("invalid reservation quote")
|
||||
}
|
||||
if q.Snapshot != nil {
|
||||
if err := q.Snapshot.Validate(); err != nil {
|
||||
return state, 0, err
|
||||
}
|
||||
}
|
||||
if q.Known && (q.Snapshot == nil || !q.Snapshot.AllChargesBounded || q.Currency != q.Snapshot.Currency || a.Model != q.Snapshot.Model) {
|
||||
return state, 0, errors.New("known quote lacks matching tariff")
|
||||
}
|
||||
if q.Nano > state.LimitNano-state.CommittedNano {
|
||||
return state, 0, errors.New("reservation exceeds balance")
|
||||
}
|
||||
index[a.ID] = len(state.Attempts)
|
||||
state.Attempts = append(state.Attempts, *a)
|
||||
state.CommittedNano += q.Nano
|
||||
if !q.Known {
|
||||
state.Unknown++
|
||||
}
|
||||
case "settle":
|
||||
i, ok := index[e.ID]
|
||||
if !ok || state.Attempts[i].Status != "reserved" {
|
||||
return state, 0, errors.New("invalid cost settlement")
|
||||
}
|
||||
a := &state.Attempts[i]
|
||||
if e.ChargedNano < 0 || e.ChargedNano > maxTokens {
|
||||
return state, 0, errors.New("invalid settled amount")
|
||||
}
|
||||
switch e.Status {
|
||||
case "not_dispatched":
|
||||
if e.ChargedNano != 0 {
|
||||
return state, 0, errors.New("undispatched charge is nonzero")
|
||||
}
|
||||
if !a.Quote.Known {
|
||||
state.Unknown--
|
||||
}
|
||||
case "reported":
|
||||
if !a.Quote.Known {
|
||||
return state, 0, errors.New("reported charge lacks tariff")
|
||||
}
|
||||
case "uncertain":
|
||||
if e.ChargedNano < a.Quote.Nano {
|
||||
return state, 0, errors.New("uncertain charge released reservation")
|
||||
}
|
||||
default:
|
||||
return state, 0, errors.New("invalid cost status")
|
||||
}
|
||||
state.CommittedNano -= a.ChargedNano
|
||||
if e.ChargedNano > maxTokens-state.CommittedNano {
|
||||
return state, 0, errors.New("cost total overflow")
|
||||
}
|
||||
state.CommittedNano += e.ChargedNano
|
||||
a.ChargedNano = e.ChargedNano
|
||||
a.Status = e.Status
|
||||
if state.CommittedNano >= state.LimitNano {
|
||||
state.Exhausted = true
|
||||
}
|
||||
case "exhausted":
|
||||
state.Exhausted = true
|
||||
default:
|
||||
return state, 0, errors.New("unknown cost event")
|
||||
}
|
||||
}
|
||||
return state, len(records), nil
|
||||
}
|
||||
func (l *CostLedger) State() (CostState, error) { s, _, err := l.read(); return s, err }
|
||||
func (l *CostLedger) append(e costEvent, n int) error {
|
||||
s, current, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current != n {
|
||||
return session.ErrAnnotationConflict
|
||||
}
|
||||
pending := 0
|
||||
for _, a := range s.Attempts {
|
||||
if a.Status == "reserved" {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
if e.Kind == "reserve" {
|
||||
pending++
|
||||
}
|
||||
if e.Kind == "settle" {
|
||||
pending--
|
||||
}
|
||||
if n+1+pending > maxRecords {
|
||||
return errors.New("cost journal lacks settlement capacity")
|
||||
}
|
||||
e.Version = 1
|
||||
raw, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.session.AnnotateIfCount(l.kind, raw, n)
|
||||
}
|
||||
|
||||
// Decide records an explicitly approved absolute ceiling. It does not authorize
|
||||
// spending by itself: callers must obtain the user's decision first. Currency
|
||||
// cannot change within a ledger and no charges are erased by a new decision.
|
||||
func (l *CostLedger) Decide(ctx context.Context, currency string, limit int64, strict bool) error {
|
||||
if !currencyValid(currency) || limit <= 0 || limit > maxTokens {
|
||||
return errors.New("invalid cost ceiling or currency")
|
||||
}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s, n, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Currency != "" && s.Currency != currency {
|
||||
return errors.New("cost ledger currency cannot change")
|
||||
}
|
||||
if limit <= s.CommittedNano {
|
||||
return errors.New("cost ceiling must exceed committed reservations and charges")
|
||||
}
|
||||
if strict && s.Unknown > 0 {
|
||||
return errors.New("unpriced prior attempts prevent a strict cost guarantee")
|
||||
}
|
||||
err = l.append(costEvent{Kind: "decision", Currency: currency, LimitNano: limit, Strict: strict}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// CostResolver must return the tariff for the actual provider route and a full
|
||||
// input estimate. A nil tariff means unknown. Callers must bind provider and
|
||||
// destination to their constructed client; model equality alone is not enough.
|
||||
type CostResolver func(llm.ChatRequest, llm.CallCategory) (*PriceSnapshot, int64, error)
|
||||
|
||||
func (l *CostLedger) Admission(resolve CostResolver) llm.CallAdmission {
|
||||
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
|
||||
if resolve == nil || id == "" || len(id) > 128 || len(req.Model) > 1024 {
|
||||
return nil, errors.New("invalid cost resolver or attempt")
|
||||
}
|
||||
price, input, err := resolve(req, category)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if price != nil {
|
||||
copy := *price
|
||||
price = ©
|
||||
if price.Provider != req.Route.Provider || price.Destination != req.Route.Destination {
|
||||
return nil, errors.New("price route differs from dispatched provider destination")
|
||||
}
|
||||
if price.Model != req.Model {
|
||||
return nil, errors.New("price model differs from dispatched model")
|
||||
}
|
||||
}
|
||||
var quote PriceQuote
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, n, err := l.read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if s.LimitNano == 0 || s.Exhausted {
|
||||
return nil, ErrCostExhausted
|
||||
}
|
||||
for _, a := range s.Attempts {
|
||||
if a.ID == id {
|
||||
return nil, errors.New("duplicate cost attempt")
|
||||
}
|
||||
}
|
||||
if price != nil && price.Currency != s.Currency {
|
||||
return nil, errors.New("tariff currency differs from budget")
|
||||
}
|
||||
quote, err = ReservePrice(price, input, int64(req.MaxTokens), time.Now(), s.Strict)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if quote.Nano > s.LimitNano-s.CommittedNano {
|
||||
err = l.append(costEvent{Kind: "exhausted"}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
return nil, errors.Join(ErrCostExhausted, err)
|
||||
}
|
||||
err = l.append(costEvent{Kind: "reserve", Attempt: &CostAttempt{ID: id, Model: req.Model, Category: category, Quote: quote, ChargedNano: quote.Nano, Status: "reserved"}}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
var once sync.Once
|
||||
var result error
|
||||
return func(r llm.RequestUsage) error { once.Do(func() { result = l.settle(id, quote, r) }); return result }, nil
|
||||
}
|
||||
}
|
||||
func (l *CostLedger) settle(id string, q PriceQuote, r llm.RequestUsage) error {
|
||||
if r.ID != id {
|
||||
return errors.New("cost settlement identity mismatch")
|
||||
}
|
||||
charge, status := q.Nano, "uncertain"
|
||||
if r.Status == "not_dispatched" {
|
||||
charge, status = 0, "not_dispatched"
|
||||
} else if q.Known && q.Snapshot != nil {
|
||||
actual, err := ReportedPrice(*q.Snapshot, r.Usage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if actual.Known {
|
||||
if r.Status == "completed" {
|
||||
charge, status = actual.Nano, "reported"
|
||||
} else {
|
||||
charge = max(charge, actual.Nano)
|
||||
}
|
||||
}
|
||||
}
|
||||
for {
|
||||
state, n, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if charge > maxTokens || charge > maxTokens-(state.CommittedNano-q.Nano) {
|
||||
return errors.New("settled cost exceeds representable ledger balance; reservation retained")
|
||||
}
|
||||
err = l.append(costEvent{Kind: "settle", ID: id, ChargedNano: charge, Status: status}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s, err := l.State()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if s.Exhausted {
|
||||
return ErrCostExhausted
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
func currentFixturePrice() PriceSnapshot {
|
||||
p := fixturePrice()
|
||||
p.EffectiveAt = time.Now().Add(-time.Hour)
|
||||
p.ExpiresAt = time.Now().Add(time.Hour)
|
||||
return p
|
||||
}
|
||||
func priceResolver(p *PriceSnapshot) CostResolver {
|
||||
return func(llm.ChatRequest, llm.CallCategory) (*PriceSnapshot, int64, error) { return p, 10, nil }
|
||||
}
|
||||
func TestCostLedgerRestartAndPricingProvenance(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "cost"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "cost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, _ := OpenCostLedger(s)
|
||||
if err = l.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := currentFixturePrice()
|
||||
_, err = l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallRetry, "interrupted")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = store.LoadExclusive("a", "cost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
l, err = OpenCostLedger(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := l.State()
|
||||
if err != nil || state.CommittedNano != 337507 || len(state.Attempts) != 1 || state.Attempts[0].Status != "reserved" {
|
||||
t.Fatalf("state %+v err %v", state, err)
|
||||
}
|
||||
if state.Attempts[0].Quote.Snapshot.Source != p.Source || state.Attempts[0].Category != llm.CallRetry {
|
||||
t.Fatal("provenance lost")
|
||||
}
|
||||
state.Attempts[0].Quote.Snapshot.Source = "caller mutation"
|
||||
state, _ = l.State()
|
||||
if state.Attempts[0].Quote.Snapshot.Source != p.Source {
|
||||
t.Fatal("mutable state shared")
|
||||
}
|
||||
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallCompaction, "summary")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = done(llm.RequestUsage{ID: "summary", Status: "completed", Usage: &llm.Usage{InputTokens: 10, OutputTokens: 5}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ = l.State()
|
||||
if state.CommittedNano != 442514 || state.Attempts[1].Status != "reported" {
|
||||
t.Fatalf("state %+v", state)
|
||||
}
|
||||
}
|
||||
func TestStrictCostBlocksUnknownAndAdvisoryPersistsUncertainty(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
|
||||
if err := l.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
observed := llm.WithCallAdmission(ctx, l.Admission(priceResolver(nil)))
|
||||
_, err := llm.ObserveChat(observed, llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
t.Fatal("strict unknown price dispatched")
|
||||
return nil, nil
|
||||
})
|
||||
if !errors.Is(err, ErrUnknownPrice) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = l.Decide(ctx, "USD", 1000000, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done, err := l.Admission(priceResolver(nil))(ctx, llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallGeneration, "unknown")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = done(llm.RequestUsage{ID: "unknown", Status: "completed", Usage: &llm.Usage{InputTokens: 10}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ := l.State()
|
||||
if state.Unknown != 1 || state.Attempts[0].Quote.Known || state.Attempts[0].Status != "uncertain" {
|
||||
t.Fatalf("state %+v", state)
|
||||
}
|
||||
if err = l.Decide(ctx, "USD", 2000000, true); err == nil {
|
||||
t.Fatal("unknown historic charge disappeared in strict mode")
|
||||
}
|
||||
if err = l.Decide(ctx, "EUR", 2000000, false); err == nil {
|
||||
t.Fatal("implicit currency conversion accepted")
|
||||
}
|
||||
}
|
||||
func TestCostConcurrentOwnersAndExplicitResume(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := session.NewSession("a", "cost")
|
||||
a, _ := OpenCostLedger(s)
|
||||
b, _ := OpenCostLedger(s)
|
||||
if err := a.Decide(ctx, "USD", 500000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := currentFixturePrice()
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, 2)
|
||||
for i, l := range []*CostLedger{a, b} {
|
||||
wg.Add(1)
|
||||
go func(i int, l *CostLedger) {
|
||||
defer wg.Done()
|
||||
_, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallRetry, string(rune('a'+i)))
|
||||
results <- err
|
||||
}(i, l)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
success := 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
success++
|
||||
} else if !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
state, _ := a.State()
|
||||
if success != 1 || state.CommittedNano != 337507 || !state.Exhausted {
|
||||
t.Fatalf("state %+v success %d", state, success)
|
||||
}
|
||||
if err := a.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ = a.State()
|
||||
if state.Exhausted || state.CommittedNano != 337507 {
|
||||
t.Fatal("resume erased charges")
|
||||
}
|
||||
}
|
||||
func TestCostFailedUsageRetainsReservationAndOverrunExhausts(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
|
||||
p := currentFixturePrice()
|
||||
if err := l.Decide(ctx, "USD", 500000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "partial")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = done(llm.RequestUsage{ID: "partial", Status: "cancelled", Usage: &llm.Usage{InputTokens: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ := l.State()
|
||||
if state.CommittedNano != 337507 {
|
||||
t.Fatal("partial usage released uncertain cost")
|
||||
}
|
||||
if err = l.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done, err = l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "overrun")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = done(llm.RequestUsage{ID: "overrun", Status: "completed", Usage: &llm.Usage{OutputTokens: 100}})
|
||||
if !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal("overrun did not stop admission")
|
||||
}
|
||||
state, _ = l.State()
|
||||
if state.CommittedNano != 1837514 || !state.Exhausted {
|
||||
t.Fatalf("state %+v", state)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCostOversizedSettlementPreservesReadableJournal(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
l, _ := OpenCostLedger(session.NewSession("a", "cost"))
|
||||
p := currentFixturePrice()
|
||||
p.OutputNanoPerMillion = 1000000000000000
|
||||
if err := l.Decide(ctx, "USD", 1000000000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done, err := l.Admission(priceResolver(&p))(ctx, llm.ChatRequest{Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, Model: p.Model, MaxTokens: 20}, llm.CallGeneration, "oversized")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, _ := l.State()
|
||||
if err = done(llm.RequestUsage{ID: "oversized", Status: "completed", Usage: &llm.Usage{OutputTokens: 2000000}}); err == nil {
|
||||
t.Fatal("oversized settlement accepted")
|
||||
}
|
||||
after, err := l.State()
|
||||
if err != nil || after.CommittedNano != before.CommittedNano || after.Attempts[0].Status != "reserved" {
|
||||
t.Fatalf("journal corrupted: %+v %v", after, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCostAdmissionRejectsSameModelAtDifferentDestination(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
l, _ := OpenCostLedger(session.NewSession("a", "route"))
|
||||
p := currentFixturePrice()
|
||||
if err := l.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, route := range []llm.CallRoute{{}, {Provider: p.Provider, Destination: "http://other.example/v1"}, {Provider: "other", Destination: p.Destination}} {
|
||||
request := llm.ChatRequest{Route: route, Model: p.Model, MaxTokens: 20}
|
||||
_, err := llm.ObserveChat(llm.WithCallAdmission(ctx, l.Admission(priceResolver(&p))), request, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
t.Fatal("mismatched tariff dispatched")
|
||||
return nil, nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("route mismatch accepted")
|
||||
}
|
||||
}
|
||||
state, err := l.State()
|
||||
if err != nil || len(state.Attempts) != 0 {
|
||||
t.Fatalf("mismatch reserved funds: %+v %v", state, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
var ErrTimeExhausted = fmt.Errorf("session time budget: %w", ErrExhausted)
|
||||
|
||||
const deadlineKind = "harness.budget.deadline.v1"
|
||||
|
||||
type DeadlineState struct {
|
||||
Version int `json:"version"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
Deadline time.Time `json:"deadline"`
|
||||
}
|
||||
|
||||
// DecideDeadline starts a new explicitly approved wall-clock allowance. Idle
|
||||
// time counts, and restarting does not reset the deadline. No prior cost/token
|
||||
// charges are changed. There is deliberately no implicit disable or renewal.
|
||||
func DecideDeadline(ctx context.Context, s *session.Session, allowance time.Duration) error {
|
||||
return decideDeadline(ctx, s, deadlineKind, allowance)
|
||||
}
|
||||
func decideDeadline(ctx context.Context, s *session.Session, kind string, allowance time.Duration) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if s == nil || allowance <= 0 || allowance > 30*24*time.Hour {
|
||||
return errors.New("time allowance must be positive and at most 30 days")
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
raw, err := json.Marshal(DeadlineState{Version: 1, DecidedAt: now, Deadline: now.Add(allowance)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.Annotate(kind, raw)
|
||||
}
|
||||
func ReadDeadline(s *session.Session) (DeadlineState, error) {
|
||||
return readDeadline(s, deadlineKind)
|
||||
}
|
||||
func readDeadline(s *session.Session, kind string) (DeadlineState, error) {
|
||||
var state DeadlineState
|
||||
if s == nil {
|
||||
return state, nil
|
||||
}
|
||||
records := s.Annotations(kind)
|
||||
if len(records) == 0 {
|
||||
return state, nil
|
||||
}
|
||||
if err := decodeBudgetJSON(records[len(records)-1].Payload, &state); err != nil {
|
||||
return state, err
|
||||
}
|
||||
if state.Version != 1 || state.DecidedAt.IsZero() || !state.Deadline.After(state.DecidedAt) || state.Deadline.Sub(state.DecidedAt) > 30*24*time.Hour {
|
||||
return state, errors.New("invalid session time budget record")
|
||||
}
|
||||
return state, nil
|
||||
}
|
||||
|
||||
// WithDeadline binds owned work to the stored session deadline. The caller must
|
||||
// cancel after all child work joins. Expired sessions fail before dispatch;
|
||||
// active work is cancelled with ErrTimeExhausted as its context cause.
|
||||
func WithDeadline(ctx context.Context, s *session.Session) (context.Context, context.CancelFunc, error) {
|
||||
return withDeadline(ctx, s, deadlineKind, ErrTimeExhausted)
|
||||
}
|
||||
func withDeadline(ctx context.Context, s *session.Session, kind string, cause error) (context.Context, context.CancelFunc, error) {
|
||||
noop := func() {}
|
||||
state, err := readDeadline(s, kind)
|
||||
if err != nil {
|
||||
return ctx, noop, err
|
||||
}
|
||||
if state.Version == 0 {
|
||||
return ctx, noop, nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ctx, noop, err
|
||||
}
|
||||
if !time.Now().Before(state.Deadline) {
|
||||
return ctx, noop, cause
|
||||
}
|
||||
child, cancel := context.WithDeadlineCause(ctx, state.Deadline, cause)
|
||||
return child, cancel, nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sausheong/harness/session"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDeadlineExpiresAcrossRestartAndExplicitResume(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "time"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "time")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = DecideDeadline(ctx, s, time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := WithDeadline(ctx, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
select {
|
||||
case <-bound.Done():
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("deadline did not cancel")
|
||||
}
|
||||
if !errors.Is(context.Cause(bound), ErrTimeExhausted) {
|
||||
t.Fatal(context.Cause(bound))
|
||||
}
|
||||
before, err := ReadDeadline(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = store.LoadExclusive("a", "time")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
after, err := ReadDeadline(s)
|
||||
if err != nil || !after.Deadline.Equal(before.Deadline) {
|
||||
t.Fatal("restart reset deadline")
|
||||
}
|
||||
_, cleanup, err := WithDeadline(ctx, s)
|
||||
cleanup()
|
||||
if !errors.Is(err, ErrTimeExhausted) {
|
||||
t.Fatal("expired restart accepted")
|
||||
}
|
||||
if err = DecideDeadline(ctx, s, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resumed, cleanup, err := WithDeadline(ctx, s)
|
||||
defer cleanup()
|
||||
if err != nil || resumed.Err() != nil {
|
||||
t.Fatal("explicit resume failed")
|
||||
}
|
||||
}
|
||||
func TestDeadlineValidationAndParentCancellation(t *testing.T) {
|
||||
s := session.NewSession("a", "time")
|
||||
ctx := context.Background()
|
||||
for _, d := range []time.Duration{0, -1, 31 * 24 * time.Hour} {
|
||||
if err := DecideDeadline(ctx, s, d); err == nil {
|
||||
t.Fatal("invalid allowance accepted")
|
||||
}
|
||||
}
|
||||
if err := DecideDeadline(ctx, s, time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent, cancel := context.WithCancel(ctx)
|
||||
bound, cleanup, err := WithDeadline(parent, s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cleanup()
|
||||
cancel()
|
||||
<-bound.Done()
|
||||
if !errors.Is(context.Cause(bound), context.Canceled) || errors.Is(context.Cause(bound), ErrTimeExhausted) {
|
||||
t.Fatal("user cancellation relabelled as budget exhaustion")
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"reflect"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// All version-1 budget schema names are lowercase. Validate the complete JSON
|
||||
// structure before typed decoding can accept aliases, duplicates or null scalar
|
||||
// values. The existing typed decoder still enforces the per-object field set.
|
||||
func decodeBudgetJSON(raw json.RawMessage, destination any) error {
|
||||
trimmed := bytes.TrimSpace(raw)
|
||||
if !utf8.Valid(raw) || len(trimmed) == 0 || trimmed[0] != '{' {
|
||||
return errors.New("budget record requires a UTF-8 object")
|
||||
}
|
||||
scanner := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := scanBudgetJSON(scanner, "", 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if scanner.Decode(new(any)) != io.EOF {
|
||||
return errors.New("trailing budget JSON")
|
||||
}
|
||||
if err := requireBudgetFields(raw, reflect.TypeOf(destination)); err != nil {
|
||||
return err
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
return d.Decode(destination)
|
||||
}
|
||||
|
||||
func scanBudgetJSON(d *json.Decoder, field string, depth int) error {
|
||||
if depth > 16 {
|
||||
return errors.New("budget JSON nesting exceeds schema limit")
|
||||
}
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token == nil && field != "snapshot" && field != "attempt" {
|
||||
return errors.New("budget scalar field cannot be null")
|
||||
}
|
||||
delimiter, compound := token.(json.Delim)
|
||||
if !compound {
|
||||
return nil
|
||||
}
|
||||
switch delimiter {
|
||||
case '{':
|
||||
seen := map[string]bool{}
|
||||
for d.More() {
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, ok := token.(string)
|
||||
if !ok || key != strings.ToLower(key) || seen[key] {
|
||||
return errors.New("duplicate or noncanonical budget field")
|
||||
}
|
||||
seen[key] = true
|
||||
if err := scanBudgetJSON(d, key, depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if token, err := d.Token(); err != nil || token != json.Delim('}') {
|
||||
return errors.New("invalid budget object")
|
||||
}
|
||||
case '[':
|
||||
for d.More() {
|
||||
if err := scanBudgetJSON(d, "", depth+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if token, err := d.Token(); err != nil || token != json.Delim(']') {
|
||||
return errors.New("invalid budget array")
|
||||
}
|
||||
default:
|
||||
return errors.New("unexpected budget delimiter")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// The on-disk contract matches the writer: fields without omitempty must be
|
||||
// present even when their value is zero. This keeps omitted settlement charges
|
||||
// or price counters from being silently manufactured by typed unmarshalling.
|
||||
func requireBudgetFields(raw json.RawMessage, typ reflect.Type) error {
|
||||
if typ == nil {
|
||||
return errors.New("budget destination type missing")
|
||||
}
|
||||
for typ.Kind() == reflect.Pointer {
|
||||
typ = typ.Elem()
|
||||
}
|
||||
if typ.Kind() != reflect.Struct || typ == reflect.TypeOf(time.Time{}) || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &fields); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < typ.NumField(); i++ {
|
||||
field := typ.Field(i)
|
||||
if field.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
tag := strings.Split(field.Tag.Get("json"), ",")
|
||||
name := tag[0]
|
||||
if name == "-" {
|
||||
continue
|
||||
}
|
||||
if name == "" {
|
||||
name = field.Name
|
||||
}
|
||||
optional := false
|
||||
for _, option := range tag[1:] {
|
||||
if option == "omitempty" {
|
||||
optional = true
|
||||
}
|
||||
}
|
||||
value, exists := fields[name]
|
||||
if !exists {
|
||||
if optional {
|
||||
continue
|
||||
}
|
||||
return errors.New("missing required budget field: " + name)
|
||||
}
|
||||
if err := requireBudgetFields(value, field.Type); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func FuzzBudgetRecordJSON(f *testing.F) {
|
||||
f.Add(byte(0), []byte(`{"version":1,"kind":"limit","tokens":100}`))
|
||||
f.Add(byte(0), []byte(`{"version":1,"kind":"settle","id":"one","status":"reported","tokens":0}`))
|
||||
f.Add(byte(0), []byte(`{"version":1,"kind":"limit","tokens":1,"to\u006bens":1000}`))
|
||||
f.Add(byte(1), []byte(`{"version":1,"kind":"decision","currency":"USD","limit_nano":100,"strict":true}`))
|
||||
f.Add(byte(2), []byte(`{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T01:00:00Z"}`))
|
||||
f.Add(byte(2), []byte(`{"version":1,"decided_at":"2026-09-09T00:00:00+00:00","deadline":"2026-09-09T01:00:00+00:00"}`))
|
||||
f.Fuzz(func(t *testing.T, kind byte, raw []byte) {
|
||||
if len(raw) > 128<<10 {
|
||||
return
|
||||
}
|
||||
var first, second any
|
||||
switch kind % 3 {
|
||||
case 0:
|
||||
first, second = new(tokenEvent), new(tokenEvent)
|
||||
case 1:
|
||||
first, second = new(costEvent), new(costEvent)
|
||||
default:
|
||||
first, second = new(DeadlineState), new(DeadlineState)
|
||||
}
|
||||
if err := decodeBudgetJSON(raw, first); err != nil {
|
||||
return
|
||||
}
|
||||
canonical, err := json.Marshal(first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := decodeBudgetJSON(canonical, second); err != nil {
|
||||
t.Fatalf("accepted record cannot round trip: %v", err)
|
||||
}
|
||||
// Compare persisted semantics, not time.Time's internal Location
|
||||
// pointer, which may normalise a zero offset to UTC on encoding.
|
||||
repeated, err := json.Marshal(second)
|
||||
if err != nil || !bytes.Equal(canonical, repeated) {
|
||||
t.Fatal("canonical round trip changed budget record", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
func TestBudgetJSONAmbiguityRefusesReopenedAdmission(t *testing.T) {
|
||||
cases := []struct{ name, kind, payload string }{
|
||||
{"token-duplicate", tokenKind, `{"version":1,"kind":"limit","tokens":1,"tokens":1000}`},
|
||||
{"token-escaped", tokenKind, `{"version":1,"kind":"limit","tokens":1,"to\u006bens":1000}`},
|
||||
{"token-alias", tokenKind, `{"version":1,"kind":"limit","tokens":1,"TOKENS":1000}`},
|
||||
{"cost-duplicate", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1,"limit_nano":1000}`},
|
||||
{"cost-alias", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1,"LIMIT_NANO":1000}`},
|
||||
{"cost-null-strict", costKind, `{"version":1,"kind":"decision","currency":"USD","limit_nano":1000,"strict":null}`},
|
||||
{"deadline-duplicate", deadlineKind, `{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T00:00:01Z","deadline":"2026-09-10T00:00:00Z"}`},
|
||||
{"deadline-alias", deadlineKind, `{"version":1,"decided_at":"2026-09-09T00:00:00Z","deadline":"2026-09-09T00:00:01Z","DEADLINE":"2026-09-10T00:00:00Z"}`},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
for _, run := range []bool{false, true} {
|
||||
name := tc.name
|
||||
if run {
|
||||
name += "-run"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
kind := tc.kind
|
||||
if run {
|
||||
var err error
|
||||
kind, err = runKind(kind, "logical")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
root := t.TempDir()
|
||||
store := session.NewStore(root)
|
||||
sess, err := store.LoadExclusive("hand", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sess.Annotate(kind, json.RawMessage(tc.payload)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "hand", "key.jsonl")
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("hand", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sess.Close()
|
||||
switch tc.kind {
|
||||
case tokenKind:
|
||||
ledger, err := openTokenLedger(sess, kind)
|
||||
if err == nil {
|
||||
t.Fatal("ambiguous token ceiling accepted")
|
||||
}
|
||||
if finish, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 1, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 2}, llm.CallGeneration, "attempt"); err == nil || finish != nil {
|
||||
t.Fatal("admitted corrupt token state")
|
||||
}
|
||||
case costKind:
|
||||
ledger, err := openCostLedger(sess, kind)
|
||||
if err == nil {
|
||||
t.Fatal("ambiguous cost ceiling accepted")
|
||||
}
|
||||
if err := ledger.Decide(context.Background(), "USD", 2000, false); err == nil {
|
||||
t.Fatal("appended over corrupt cost state")
|
||||
}
|
||||
case deadlineKind:
|
||||
if _, err := readDeadline(sess, kind); err == nil {
|
||||
t.Fatal("ambiguous deadline accepted")
|
||||
}
|
||||
}
|
||||
if err := sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatal("corrupt budget changed", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBudgetNestedQuoteIntegrity(t *testing.T) {
|
||||
price := currentFixturePrice()
|
||||
event := costEvent{Version: 1, Kind: "reserve", Attempt: &CostAttempt{ID: "one", Model: price.Model, Category: llm.CallGeneration, Quote: PriceQuote{Known: true, Nano: 1, Currency: "USD", Snapshot: &price}, ChargedNano: 1, Status: "reserved"}}
|
||||
raw, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range []string{"valid", "duplicate-price", "alias-price", "null-price", "duplicate-quote"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
payload := string(raw)
|
||||
switch name {
|
||||
case "duplicate-price":
|
||||
payload = strings.Replace(payload, `"fixed_nano":`, `"fixed_nano":999,"fixed_nano":`, 1)
|
||||
case "alias-price":
|
||||
payload = strings.Replace(payload, `"fixed_nano":`, `"FIXED_NANO":999,"fixed_nano":`, 1)
|
||||
case "null-price":
|
||||
payload = strings.Replace(payload, `"fixed_nano":`+strconv.FormatInt(price.FixedNano, 10), `"fixed_nano":null`, 1)
|
||||
case "duplicate-quote":
|
||||
payload = strings.Replace(payload, `"nano":1`, `"nano":999,"nano":1`, 1)
|
||||
}
|
||||
sess := session.NewSession("a", "nested")
|
||||
ledger, err := OpenCostLedger(sess)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ledger.Decide(context.Background(), "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sess.Annotate(costKind, json.RawMessage(payload)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := ledger.State()
|
||||
if name == "valid" {
|
||||
if err != nil || state.CommittedNano != 1 {
|
||||
t.Fatalf("valid nested record failed: %+v %v", state, err)
|
||||
}
|
||||
} else if err == nil {
|
||||
t.Fatal("ambiguous nested price accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMissingTokenSettlementChargeDoesNotReleaseReservation(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
store := session.NewStore(root)
|
||||
sess, err := store.LoadExclusive("a", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ledger, err := OpenTokenLedger(sess)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ledger.Decide(context.Background(), 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 10, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 10}, llm.CallGeneration, "one"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sess.Annotate(tokenKind, json.RawMessage(`{"version":1,"kind":"settle","id":"one","status":"reported"}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "a", "key.jsonl")
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("a", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sess.Close()
|
||||
ledger, err = OpenTokenLedger(sess)
|
||||
if err == nil {
|
||||
state, _ := ledger.State()
|
||||
t.Fatalf("missing charge released reserved tokens: %+v", state)
|
||||
}
|
||||
if finish, err := ledger.Admission(func(llm.ChatRequest) (int64, error) { return 1, nil })(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 1}, llm.CallGeneration, "next"); err == nil || finish != nil {
|
||||
t.Fatal("corrupt settlement admitted request")
|
||||
}
|
||||
if err := sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil || !bytes.Equal(before, after) {
|
||||
t.Fatal("corrupt journal changed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBudgetRequiredNestedFieldsAndExplicitZero(t *testing.T) {
|
||||
price := currentFixturePrice()
|
||||
event := costEvent{Version: 1, Kind: "reserve", Attempt: &CostAttempt{ID: "one", Model: price.Model, Category: llm.CallGeneration, Quote: PriceQuote{Known: true, Nano: 0, Currency: "USD", Snapshot: &price}, ChargedNano: 0, Status: "reserved"}}
|
||||
raw, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, path := range [][]string{
|
||||
{"attempt", "charged_nano"},
|
||||
{"attempt", "quote", "nano"},
|
||||
{"attempt", "quote", "known"},
|
||||
{"attempt", "quote", "snapshot", "fixed_nano"},
|
||||
{"attempt", "quote", "snapshot", "input_nano_per_million"},
|
||||
{"attempt", "quote", "snapshot", "all_charges_bounded"},
|
||||
} {
|
||||
t.Run(strings.Join(path, "/"), func(t *testing.T) {
|
||||
var object map[string]any
|
||||
if err := json.Unmarshal(raw, &object); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current := object
|
||||
for _, key := range path[:len(path)-1] {
|
||||
current = current[key].(map[string]any)
|
||||
}
|
||||
delete(current, path[len(path)-1])
|
||||
corrupted, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var decoded costEvent
|
||||
if err := decodeBudgetJSON(corrupted, &decoded); err == nil {
|
||||
t.Fatal("missing required pricing field accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
// Explicit zero is still meaningful; optional false/empty fields emitted
|
||||
// with omitempty remain compatible with the existing writer contract.
|
||||
for _, value := range []any{event, costEvent{Version: 1, Kind: "decision", Currency: "USD", LimitNano: 100}, tokenEvent{Version: 1, Kind: "settle", ID: "one", Status: "reported", Tokens: 0}} {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
switch value.(type) {
|
||||
case costEvent:
|
||||
var decoded costEvent
|
||||
if err := decodeBudgetJSON(encoded, &decoded); err != nil {
|
||||
t.Fatal("writer output rejected", err)
|
||||
}
|
||||
case tokenEvent:
|
||||
var decoded tokenEvent
|
||||
if err := decodeBudgetJSON(encoded, &decoded); err != nil {
|
||||
t.Fatal("explicit zero rejected", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
var ErrUnknownPrice = errors.New("request price is unknown or unbounded")
|
||||
|
||||
// PriceSnapshot is an immutable, caller-reviewed tariff for a specific route.
|
||||
// Rates are billionths of Currency per million tokens; FixedNano is charged
|
||||
// once per provider attempt. No implicit currency conversion is performed.
|
||||
// AllChargesBounded must be false when tool, reasoning, image, tiered-cache or
|
||||
// other provider charges are not fully represented by these counters/rates.
|
||||
// Input, cache creation and cache read counters must be disjoint subsets of
|
||||
// total input under the provider adapter's usage contract.
|
||||
type PriceSnapshot struct {
|
||||
Provider string `json:"provider"`
|
||||
Model string `json:"model"`
|
||||
Destination string `json:"destination"`
|
||||
Currency string `json:"currency"`
|
||||
Source string `json:"source"`
|
||||
Version string `json:"version"`
|
||||
EffectiveAt time.Time `json:"effective_at"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
InputNanoPerMillion int64 `json:"input_nano_per_million"`
|
||||
OutputNanoPerMillion int64 `json:"output_nano_per_million"`
|
||||
CacheWriteNanoPerMillion int64 `json:"cache_write_nano_per_million"`
|
||||
CacheReadNanoPerMillion int64 `json:"cache_read_nano_per_million"`
|
||||
FixedNano int64 `json:"fixed_nano"`
|
||||
AllChargesBounded bool `json:"all_charges_bounded"`
|
||||
}
|
||||
|
||||
func (p PriceSnapshot) Validate() error {
|
||||
for _, s := range []string{p.Provider, p.Model, p.Destination, p.Source, p.Version} {
|
||||
if strings.TrimSpace(s) == "" || len(s) > 2048 || !utf8.ValidString(s) || strings.ContainsAny(s, "\x00\r\n") {
|
||||
return errors.New("pricing requires bounded route, source and version metadata")
|
||||
}
|
||||
}
|
||||
if len(p.Currency) != 3 || strings.IndexFunc(p.Currency, func(r rune) bool { return r < 'A' || r > 'Z' }) >= 0 {
|
||||
return errors.New("pricing currency requires three uppercase letters")
|
||||
}
|
||||
if p.EffectiveAt.IsZero() || p.ExpiresAt.IsZero() || !p.ExpiresAt.After(p.EffectiveAt) {
|
||||
return errors.New("pricing requires an explicit validity interval")
|
||||
}
|
||||
for _, rate := range []int64{p.InputNanoPerMillion, p.OutputNanoPerMillion, p.CacheWriteNanoPerMillion, p.CacheReadNanoPerMillion, p.FixedNano} {
|
||||
if rate < 0 {
|
||||
return errors.New("negative price")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PriceQuote separates a known amount from unknown cost. Nano must never be
|
||||
// interpreted as a free request when Known is false. Snapshot is copied into
|
||||
// the quote for durable request accounting by the caller.
|
||||
type PriceQuote struct {
|
||||
Known bool `json:"known"`
|
||||
Nano int64 `json:"nano"`
|
||||
Currency string `json:"currency,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
Snapshot *PriceSnapshot `json:"snapshot,omitempty"`
|
||||
}
|
||||
|
||||
// ReservePrice prices an estimated input bound plus a finite output cap. The
|
||||
// maximum input/cache rate prevents optimistic cache-hit assumptions. Strict
|
||||
// mode refuses missing, expired or unbounded pricing. Advisory mode returns an
|
||||
// explicitly unknown quote. Invalid metadata/negative values always fail.
|
||||
func ReservePrice(p *PriceSnapshot, input, output int64, now time.Time, strict bool) (PriceQuote, error) {
|
||||
if input < 0 || output <= 0 {
|
||||
return PriceQuote{}, errors.New("reservation requires nonnegative input and a positive output cap")
|
||||
}
|
||||
unknown := func(reason string) (PriceQuote, error) {
|
||||
q := PriceQuote{Reason: reason}
|
||||
if p != nil {
|
||||
copy := *p
|
||||
q.Snapshot = ©
|
||||
q.Currency = p.Currency
|
||||
}
|
||||
if strict {
|
||||
return q, fmt.Errorf("%w: %s", ErrUnknownPrice, reason)
|
||||
}
|
||||
return q, nil
|
||||
}
|
||||
if p == nil {
|
||||
return unknown("no route price supplied")
|
||||
}
|
||||
if err := p.Validate(); err != nil {
|
||||
return PriceQuote{}, err
|
||||
}
|
||||
if now.IsZero() || now.Before(p.EffectiveAt) || !now.Before(p.ExpiresAt) {
|
||||
return unknown("price is outside its validity interval")
|
||||
}
|
||||
if !p.AllChargesBounded {
|
||||
return unknown("tariff does not bound all provider charges")
|
||||
}
|
||||
rate := max(p.InputNanoPerMillion, p.CacheWriteNanoPerMillion, p.CacheReadNanoPerMillion)
|
||||
amount, err := priceSum(p.FixedNano, [][2]int64{{input, rate}, {output, p.OutputNanoPerMillion}})
|
||||
if err != nil {
|
||||
return PriceQuote{}, err
|
||||
}
|
||||
copy := *p
|
||||
return PriceQuote{Known: true, Nano: amount, Currency: p.Currency, Snapshot: ©}, nil
|
||||
}
|
||||
|
||||
// ReportedPrice uses the admission-time snapshot, even if its validity interval
|
||||
// has since expired. Nil usage remains unknown. Cache tokens are subsets of
|
||||
// InputTokens, not extra input charges. Invalid/inconsistent counters fail so
|
||||
// callers retain their conservative reservation instead of undercharging.
|
||||
func ReportedPrice(p PriceSnapshot, u *llm.Usage) (PriceQuote, error) {
|
||||
if err := p.Validate(); err != nil {
|
||||
return PriceQuote{}, err
|
||||
}
|
||||
q := PriceQuote{Currency: p.Currency, Snapshot: &p}
|
||||
if u == nil {
|
||||
q.Reason = "provider usage unavailable"
|
||||
return q, nil
|
||||
}
|
||||
if !p.AllChargesBounded {
|
||||
q.Reason = "tariff does not bound all provider charges"
|
||||
return q, nil
|
||||
}
|
||||
input, output, write, read := int64(u.InputTokens), int64(u.OutputTokens), int64(u.CacheCreationInputTokens), int64(u.CacheReadInputTokens)
|
||||
if input < 0 || output < 0 || write < 0 || read < 0 || write > input || read > input-write {
|
||||
return q, errors.New("inconsistent provider token counters")
|
||||
}
|
||||
amount, err := priceSum(p.FixedNano, [][2]int64{{input - write - read, p.InputNanoPerMillion}, {write, p.CacheWriteNanoPerMillion}, {read, p.CacheReadNanoPerMillion}, {output, p.OutputNanoPerMillion}})
|
||||
if err != nil {
|
||||
return q, err
|
||||
}
|
||||
q.Known = true
|
||||
q.Nano = amount
|
||||
return q, nil
|
||||
}
|
||||
|
||||
// Integer accumulation rounds the final token charge up once to a nano-unit.
|
||||
// big.Int avoids multiplication overflow before checking the representable sum.
|
||||
func priceSum(fixed int64, terms [][2]int64) (int64, error) {
|
||||
total := new(big.Int)
|
||||
for _, term := range terms {
|
||||
if term[0] < 0 || term[1] < 0 || fixed < 0 {
|
||||
return 0, errors.New("negative pricing operand")
|
||||
}
|
||||
total.Add(total, new(big.Int).Mul(big.NewInt(term[0]), big.NewInt(term[1])))
|
||||
}
|
||||
total.Add(total, big.NewInt(999999))
|
||||
total.Quo(total, big.NewInt(1000000))
|
||||
total.Add(total, big.NewInt(fixed))
|
||||
if !total.IsInt64() {
|
||||
return 0, errors.New("request price exceeds representable amount")
|
||||
}
|
||||
return total.Int64(), nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fixturePrice() PriceSnapshot {
|
||||
return PriceSnapshot{Provider: "fixture", Model: "scripted", Destination: "http://127.0.0.1/v1", Currency: "USD", Source: "test fixture, not a market tariff", Version: "fixture-1", EffectiveAt: time.Unix(1000, 0), ExpiresAt: time.Unix(2000, 0), InputNanoPerMillion: 3000000000, OutputNanoPerMillion: 15000000000, CacheWriteNanoPerMillion: 3750000000, CacheReadNanoPerMillion: 300000000, FixedNano: 7, AllChargesBounded: true}
|
||||
}
|
||||
func TestPriceReservationAndCacheReconciliation(t *testing.T) {
|
||||
p := fixturePrice()
|
||||
q, err := ReservePrice(&p, 100, 20, time.Unix(1500, 0), true)
|
||||
if err != nil || !q.Known || q.Nano != 675007 || q.Currency != "USD" {
|
||||
t.Fatalf("quote %+v err %v", q, err)
|
||||
}
|
||||
actual, err := ReportedPrice(p, &llm.Usage{InputTokens: 100, OutputTokens: 20, CacheCreationInputTokens: 20, CacheReadInputTokens: 30})
|
||||
// 50 regular + 20 cache write + 30 cache read; no double-counted cache.
|
||||
if err != nil || actual.Nano != 534007 || !actual.Known {
|
||||
t.Fatalf("actual %+v err %v", actual, err)
|
||||
}
|
||||
p.Source = "changed"
|
||||
if q.Snapshot.Source == p.Source {
|
||||
t.Fatal("quote retained caller-owned snapshot")
|
||||
}
|
||||
}
|
||||
func TestUnknownPricesAreNotFree(t *testing.T) {
|
||||
for _, name := range []string{"missing", "expired", "future", "unbounded"} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
p := fixturePrice()
|
||||
ptr := &p
|
||||
now := time.Unix(1500, 0)
|
||||
switch name {
|
||||
case "missing":
|
||||
ptr = nil
|
||||
case "expired":
|
||||
now = p.ExpiresAt
|
||||
case "future":
|
||||
now = p.EffectiveAt.Add(-time.Second)
|
||||
case "unbounded":
|
||||
p.AllChargesBounded = false
|
||||
}
|
||||
advisory, err := ReservePrice(ptr, 1, 1, now, false)
|
||||
if err != nil || advisory.Known || advisory.Reason == "" {
|
||||
t.Fatalf("advisory %+v %v", advisory, err)
|
||||
}
|
||||
strict, err := ReservePrice(ptr, 1, 1, now, true)
|
||||
if !errors.Is(err, ErrUnknownPrice) || strict.Known {
|
||||
t.Fatalf("strict %+v %v", strict, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
p := fixturePrice()
|
||||
q, err := ReportedPrice(p, nil)
|
||||
if err != nil || q.Known || q.Reason == "" {
|
||||
t.Fatal("missing usage charged as free")
|
||||
}
|
||||
}
|
||||
func TestPricingRefusesInvalidCountersAndOverflow(t *testing.T) {
|
||||
p := fixturePrice()
|
||||
for _, u := range []llm.Usage{{InputTokens: -1}, {OutputTokens: -1}, {InputTokens: 10, CacheCreationInputTokens: 8, CacheReadInputTokens: 3}, {InputTokens: 10, CacheReadInputTokens: -1}} {
|
||||
if _, err := ReportedPrice(p, &u); err == nil {
|
||||
t.Fatalf("accepted %+v", u)
|
||||
}
|
||||
}
|
||||
p.OutputNanoPerMillion = math.MaxInt64
|
||||
if _, err := ReservePrice(&p, 0, math.MaxInt64, time.Unix(1500, 0), true); err == nil {
|
||||
t.Fatal("overflow accepted")
|
||||
}
|
||||
p = fixturePrice()
|
||||
p.InputNanoPerMillion = -1
|
||||
if _, err := ReservePrice(&p, 1, 1, time.Unix(1500, 0), false); err == nil {
|
||||
t.Fatal("advisory accepted negative tariff")
|
||||
}
|
||||
}
|
||||
func TestPriceRoundingAndExplicitZeroTariff(t *testing.T) {
|
||||
amount, err := priceSum(0, [][2]int64{{1, 1}, {1, 1}})
|
||||
if err != nil || amount != 1 {
|
||||
t.Fatalf("rounding %d %v", amount, err)
|
||||
}
|
||||
p := fixturePrice()
|
||||
p.InputNanoPerMillion = 0
|
||||
p.OutputNanoPerMillion = 0
|
||||
p.CacheReadNanoPerMillion = 0
|
||||
p.CacheWriteNanoPerMillion = 0
|
||||
p.FixedNano = 0
|
||||
q, err := ReservePrice(&p, 10, 10, time.Unix(1500, 0), true)
|
||||
if err != nil || !q.Known || q.Nano != 0 {
|
||||
t.Fatalf("explicit free tariff %+v %v", q, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
var ErrRunTimeExhausted = fmt.Errorf("run time budget: %w", ErrExhausted)
|
||||
|
||||
// Run IDs are stable logical-operation identities, not process-local counters.
|
||||
// Reusing an ID reopens its existing charges and deadline. A caller must bind
|
||||
// the same ID to retries, summaries, continuation and recovery of that run.
|
||||
func runKind(base, id string) (string, error) {
|
||||
if len(id) == 0 || len(id) > 64 || strings.IndexFunc(id, func(r rune) bool {
|
||||
return !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-')
|
||||
}) >= 0 {
|
||||
return "", errors.New("run budget ID must contain 1-64 ASCII letters, digits, underscores or hyphens")
|
||||
}
|
||||
return base + ".run." + id, nil
|
||||
}
|
||||
|
||||
// OpenRunTokenLedger opens a durable per-run ledger. Attach its admission guard
|
||||
// alongside the session guard; opening this ledger does not replace either
|
||||
// scope or grant a new allowance.
|
||||
func OpenRunTokenLedger(s *session.Session, id string) (*TokenLedger, error) {
|
||||
kind, err := runKind(tokenKind, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return openTokenLedger(s, kind)
|
||||
}
|
||||
func OpenRunCostLedger(s *session.Session, id string) (*CostLedger, error) {
|
||||
kind, err := runKind(costKind, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return openCostLedger(s, kind)
|
||||
}
|
||||
func DecideRunDeadline(ctx context.Context, s *session.Session, id string, allowance time.Duration) error {
|
||||
kind, err := runKind(deadlineKind, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return decideDeadline(ctx, s, kind, allowance)
|
||||
}
|
||||
func ReadRunDeadline(s *session.Session, id string) (DeadlineState, error) {
|
||||
kind, err := runKind(deadlineKind, id)
|
||||
if err != nil {
|
||||
return DeadlineState{}, err
|
||||
}
|
||||
return readDeadline(s, kind)
|
||||
}
|
||||
func WithRunDeadline(ctx context.Context, s *session.Session, id string) (context.Context, context.CancelFunc, error) {
|
||||
kind, err := runKind(deadlineKind, id)
|
||||
if err != nil {
|
||||
return ctx, func() {}, err
|
||||
}
|
||||
return withDeadline(ctx, s, kind, ErrRunTimeExhausted)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
func TestRunLedgersComposeWithSessionAndSurviveRestart(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "runs"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "runs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if s != nil {
|
||||
s.Close()
|
||||
}
|
||||
}()
|
||||
total, _ := OpenTokenLedger(s)
|
||||
run, _ := OpenRunTokenLedger(s, "job-1")
|
||||
if err = total.Decide(ctx, 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = run.Decide(ctx, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
guarded := llm.WithCallAdmission(llm.WithCallAdmission(ctx, total.Admission(estimate)), run.Admission(estimate))
|
||||
calls := 0
|
||||
provider := func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
calls++
|
||||
out := make(chan llm.ChatEvent, 1)
|
||||
out <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 8, OutputTokens: 2}}
|
||||
close(out)
|
||||
return out, nil
|
||||
}
|
||||
req := llm.ChatRequest{Model: "m", MaxTokens: 20}
|
||||
if _, err = llm.ObserveChat(guarded, req, llm.CallGeneration, provider); !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := total.State()
|
||||
if err != nil || state.Committed != 0 || calls != 0 {
|
||||
t.Fatalf("denied run charged session: %+v %v calls=%d", state, err, calls)
|
||||
}
|
||||
if err = run.Decide(ctx, 80); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, category := range []llm.CallCategory{llm.CallGeneration, llm.CallRetry, llm.CallCompaction} {
|
||||
events, e := llm.ObserveChat(guarded, req, category, provider)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for ev := range events {
|
||||
if ev.Error != nil {
|
||||
t.Fatal(ev.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s = nil
|
||||
s, err = store.LoadExclusive("a", "runs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total, _ = OpenTokenLedger(s)
|
||||
run, _ = OpenRunTokenLedger(s, "job-1")
|
||||
other, _ := OpenRunTokenLedger(s, "job-2")
|
||||
for _, l := range []*TokenLedger{total, run} {
|
||||
state, e := l.State()
|
||||
if e != nil || state.Committed != 30 {
|
||||
t.Fatalf("lost charge: %+v %v", state, e)
|
||||
}
|
||||
}
|
||||
untouched, e := other.State()
|
||||
if e != nil || untouched.Limit != 0 || untouched.Committed != 0 {
|
||||
t.Fatalf("scope collision: %+v %v", untouched, e)
|
||||
}
|
||||
}
|
||||
func TestRunCostAndDeadlinePersistWithoutSessionReset(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "run-cost"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "run-cost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() {
|
||||
if s != nil {
|
||||
s.Close()
|
||||
}
|
||||
}()
|
||||
run, _ := OpenRunCostLedger(s, "operation")
|
||||
if err = run.Decide(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := currentFixturePrice()
|
||||
req := llm.ChatRequest{Model: p.Model, Route: llm.CallRoute{Provider: p.Provider, Destination: p.Destination}, MaxTokens: 20}
|
||||
// An interrupted attempt remains reserved under the same run after reopen.
|
||||
if _, err = run.Admission(priceResolver(&p))(ctx, req, llm.CallRetry, "attempt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = DecideRunDeadline(ctx, s, "operation", time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := ReadRunDeadline(s, "operation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s = nil
|
||||
s, err = store.LoadExclusive("a", "run-cost")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ = OpenRunCostLedger(s, "operation")
|
||||
state, err := run.State()
|
||||
if err != nil || state.CommittedNano != 337507 || state.Attempts[0].Status != "reserved" {
|
||||
t.Fatalf("lost run cost: %+v %v", state, err)
|
||||
}
|
||||
after, err := ReadRunDeadline(s, "operation")
|
||||
if err != nil || !after.Deadline.Equal(before.Deadline) {
|
||||
t.Fatalf("deadline renewed: %+v %v", after, err)
|
||||
}
|
||||
sessionCost, _ := OpenCostLedger(s)
|
||||
total, err := sessionCost.State()
|
||||
if err != nil || total.CommittedNano != 0 || total.LimitNano != 0 {
|
||||
t.Fatalf("scope contaminated session: %+v %v", total, err)
|
||||
}
|
||||
sessionDeadline, err := ReadDeadline(s)
|
||||
if err != nil || sessionDeadline.Version != 0 {
|
||||
t.Fatal("run set session deadline")
|
||||
}
|
||||
parent, cancel := context.WithCancel(ctx)
|
||||
child, stop, err := WithRunDeadline(parent, s, "operation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stop()
|
||||
cancel()
|
||||
<-child.Done()
|
||||
if !errors.Is(context.Cause(child), context.Canceled) {
|
||||
t.Fatal("parent cancellation lost")
|
||||
}
|
||||
}
|
||||
func TestRunBudgetIDsRejectAmbiguousNamespaces(t *testing.T) {
|
||||
s := session.NewSession("a", "ids")
|
||||
for _, id := range []string{"", "x.y", "../session", "with space", "a/b", strings.Repeat("a", 65), "日本"} {
|
||||
if _, err := OpenRunTokenLedger(s, id); err == nil {
|
||||
t.Fatalf("accepted %q", id)
|
||||
}
|
||||
if _, err := OpenRunCostLedger(s, id); err == nil {
|
||||
t.Fatalf("accepted %q", id)
|
||||
}
|
||||
if err := DecideRunDeadline(context.Background(), s, id, time.Hour); err == nil {
|
||||
t.Fatalf("accepted %q", id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunDeadlineExpiryDoesNotRenewOnRebind(t *testing.T) {
|
||||
s := session.NewSession("a", "expiry")
|
||||
ctx := context.Background()
|
||||
if err := DecideRunDeadline(ctx, s, "run", 20*time.Millisecond); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
child, cancel, err := WithRunDeadline(ctx, s, "run")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
select {
|
||||
case <-child.Done():
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("run deadline did not expire")
|
||||
}
|
||||
if !errors.Is(context.Cause(child), ErrRunTimeExhausted) {
|
||||
t.Fatal(context.Cause(child))
|
||||
}
|
||||
if _, stop, err := WithRunDeadline(ctx, s, "run"); !errors.Is(err, ErrRunTimeExhausted) {
|
||||
stop()
|
||||
t.Fatal("expired run implicitly renewed", err)
|
||||
}
|
||||
if err := DecideRunDeadline(ctx, s, "run", time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, stop, err := WithRunDeadline(ctx, s, "run")
|
||||
defer stop()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// Package budget provides durable provider-attempt admission policies.
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
var ErrExhausted = errors.New("budget_exhausted")
|
||||
|
||||
const tokenKind = "harness.budget.tokens.v1"
|
||||
const maxRecords = 10000
|
||||
const maxTokens int64 = 1 << 50
|
||||
|
||||
type tokenEvent struct {
|
||||
Version int `json:"version"`
|
||||
Kind string `json:"kind"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Model string `json:"model,omitempty"`
|
||||
Category llm.CallCategory `json:"category,omitempty"`
|
||||
Tokens int64 `json:"tokens"`
|
||||
Status string `json:"status,omitempty"`
|
||||
}
|
||||
|
||||
type TokenAttempt struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
Category llm.CallCategory `json:"category"`
|
||||
Reserved int64 `json:"reserved"`
|
||||
Charged int64 `json:"charged"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type TokenState struct {
|
||||
Limit int64 `json:"limit"`
|
||||
Committed int64 `json:"committed"`
|
||||
Exhausted bool `json:"exhausted"`
|
||||
Attempts []TokenAttempt `json:"attempts"`
|
||||
}
|
||||
|
||||
// TokenLedger shares a session-wide limit across every attached operation and
|
||||
// branch. Use a disk session loaded exclusively for durability across processes.
|
||||
// Reopening never changes limits or releases interrupted reservations. Multiple
|
||||
// ledgers over the same Session coordinate through conditional durable appends.
|
||||
// This is token admission, not a financial billing cap.
|
||||
type TokenLedger struct {
|
||||
session *session.Session
|
||||
kind string
|
||||
}
|
||||
|
||||
func OpenTokenLedger(s *session.Session) (*TokenLedger, error) {
|
||||
return openTokenLedger(s, tokenKind)
|
||||
}
|
||||
|
||||
func openTokenLedger(s *session.Session, kind string) (*TokenLedger, error) {
|
||||
if s == nil {
|
||||
return nil, errors.New("budget requires a session")
|
||||
}
|
||||
l := &TokenLedger{session: s, kind: kind}
|
||||
_, _, err := l.read()
|
||||
return l, err
|
||||
}
|
||||
|
||||
func (l *TokenLedger) read() (TokenState, int, error) {
|
||||
var state TokenState
|
||||
records := l.session.Annotations(l.kind)
|
||||
if len(records) > maxRecords {
|
||||
return state, 0, errors.New("budget journal exceeds record limit")
|
||||
}
|
||||
index := map[string]int{}
|
||||
for _, record := range records {
|
||||
var e tokenEvent
|
||||
if err := decodeBudgetJSON(record.Payload, &e); err != nil {
|
||||
return state, 0, err
|
||||
}
|
||||
if e.Version != 1 || e.Tokens < 0 || e.Tokens > maxTokens {
|
||||
return state, 0, errors.New("invalid budget record")
|
||||
}
|
||||
switch e.Kind {
|
||||
case "limit":
|
||||
if e.Tokens <= state.Committed {
|
||||
return state, 0, errors.New("budget decision leaves no available capacity")
|
||||
}
|
||||
state.Limit = e.Tokens
|
||||
state.Exhausted = false
|
||||
case "reserve":
|
||||
if _, exists := index[e.ID]; exists || e.ID == "" || state.Limit == 0 || state.Exhausted || e.Tokens <= 0 || e.Tokens > state.Limit-state.Committed {
|
||||
return state, 0, errors.New("invalid budget reservation")
|
||||
}
|
||||
index[e.ID] = len(state.Attempts)
|
||||
state.Attempts = append(state.Attempts, TokenAttempt{ID: e.ID, Model: e.Model, Category: e.Category, Reserved: e.Tokens, Charged: e.Tokens, Status: "reserved"})
|
||||
state.Committed += e.Tokens
|
||||
case "settle":
|
||||
i, ok := index[e.ID]
|
||||
if !ok || state.Attempts[i].Status != "reserved" {
|
||||
return state, 0, errors.New("invalid budget settlement")
|
||||
}
|
||||
a := &state.Attempts[i]
|
||||
if e.Status != "reported" && e.Status != "unknown" && e.Status != "not_dispatched" {
|
||||
return state, 0, errors.New("invalid settlement status")
|
||||
}
|
||||
if (e.Status == "unknown" && e.Tokens < a.Reserved) || (e.Status == "not_dispatched" && e.Tokens != 0) {
|
||||
return state, 0, errors.New("invalid settlement charge")
|
||||
}
|
||||
state.Committed -= a.Charged
|
||||
if e.Tokens > maxTokens-state.Committed {
|
||||
return state, 0, errors.New("budget total overflow")
|
||||
}
|
||||
state.Committed += e.Tokens
|
||||
a.Charged = e.Tokens
|
||||
a.Status = e.Status
|
||||
if state.Committed >= state.Limit {
|
||||
state.Exhausted = true
|
||||
}
|
||||
case "exhausted":
|
||||
state.Exhausted = true
|
||||
default:
|
||||
return state, 0, errors.New("unknown budget event")
|
||||
}
|
||||
}
|
||||
return state, len(records), nil
|
||||
}
|
||||
|
||||
func (l *TokenLedger) append(e tokenEvent, revision int) error {
|
||||
state, current, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current != revision {
|
||||
return session.ErrAnnotationConflict
|
||||
}
|
||||
pending := 0
|
||||
for _, a := range state.Attempts {
|
||||
if a.Status == "reserved" {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
if e.Kind == "reserve" {
|
||||
pending++
|
||||
}
|
||||
if e.Kind == "settle" {
|
||||
pending--
|
||||
}
|
||||
if revision+1+pending > maxRecords {
|
||||
return errors.New("budget journal lacks settlement capacity")
|
||||
}
|
||||
if revision >= maxRecords {
|
||||
return errors.New("budget journal full")
|
||||
}
|
||||
e.Version = 1
|
||||
raw, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.session.AnnotateIfCount(l.kind, raw, revision)
|
||||
}
|
||||
func (l *TokenLedger) State() (TokenState, error) { s, _, err := l.read(); return s, err }
|
||||
|
||||
// Decide explicitly sets an absolute session token ceiling above all committed
|
||||
// and uncertain usage. It resumes a previously exhausted ledger without erasing
|
||||
// charges. Callers must obtain the user's budget decision before invoking it.
|
||||
func (l *TokenLedger) Decide(ctx context.Context, limit int64) error {
|
||||
if limit <= 0 || limit > maxTokens {
|
||||
return errors.New("invalid token ceiling")
|
||||
}
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
s, n, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if limit <= s.Committed {
|
||||
return errors.New("ceiling must exceed committed and reserved tokens")
|
||||
}
|
||||
err = l.append(tokenEvent{Kind: "limit", Tokens: limit}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Admission reserves inputEstimate(req)+MaxTokens before dispatch. The supplied
|
||||
// estimator must include system text, tool schemas, framing and multimodal
|
||||
// input; its provenance must be disclosed by the application. Estimation error
|
||||
// and provider output overruns can exceed the limit and latch exhaustion.
|
||||
func (l *TokenLedger) Admission(inputEstimate func(llm.ChatRequest) (int64, error)) llm.CallAdmission {
|
||||
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
|
||||
if inputEstimate == nil || id == "" || len(id) > 128 || len(req.Model) > 1024 || req.MaxTokens <= 0 {
|
||||
return nil, errors.New("bounded request and estimator required")
|
||||
}
|
||||
input, err := inputEstimate(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input < 0 || input > maxTokens-int64(req.MaxTokens) {
|
||||
return nil, errors.New("invalid token estimate")
|
||||
}
|
||||
reserved := input + int64(req.MaxTokens)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s, n, err := l.read()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, a := range s.Attempts {
|
||||
if a.ID == id {
|
||||
return nil, errors.New("duplicate budget attempt")
|
||||
}
|
||||
}
|
||||
if s.Limit == 0 || s.Exhausted {
|
||||
return nil, ErrExhausted
|
||||
}
|
||||
if reserved > s.Limit-s.Committed {
|
||||
err = l.append(tokenEvent{Kind: "exhausted"}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
return nil, errors.Join(ErrExhausted, err)
|
||||
}
|
||||
// Leave one record for each outstanding settlement. Journal exhaustion
|
||||
// must not admit a request whose terminal record cannot fit.
|
||||
pending := 0
|
||||
for _, a := range s.Attempts {
|
||||
if a.Status == "reserved" {
|
||||
pending++
|
||||
}
|
||||
}
|
||||
if n+pending+2 > maxRecords {
|
||||
return nil, errors.New("budget journal lacks settlement capacity")
|
||||
}
|
||||
err = l.append(tokenEvent{Kind: "reserve", ID: id, Model: req.Model, Category: category, Tokens: reserved}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
var once sync.Once
|
||||
var settledErr error
|
||||
return func(r llm.RequestUsage) error {
|
||||
once.Do(func() { settledErr = l.settle(id, reserved, r) })
|
||||
return settledErr
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
func (l *TokenLedger) settle(id string, reserved int64, r llm.RequestUsage) error {
|
||||
if r.ID != id {
|
||||
return errors.New("settlement identity mismatch")
|
||||
}
|
||||
charge, status := reserved, "unknown"
|
||||
if r.Status == "not_dispatched" {
|
||||
charge, status = 0, "not_dispatched"
|
||||
} else if r.Usage != nil {
|
||||
u := r.Usage
|
||||
if u.InputTokens < 0 || u.OutputTokens < 0 || int64(u.InputTokens) > maxTokens-int64(u.OutputTokens) {
|
||||
return errors.New("invalid reported tokens")
|
||||
}
|
||||
charge = int64(u.InputTokens) + int64(u.OutputTokens)
|
||||
if r.Status == "completed" {
|
||||
status = "reported"
|
||||
} else if charge < reserved {
|
||||
charge = reserved
|
||||
}
|
||||
}
|
||||
for {
|
||||
state, n, err := l.read()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if charge > maxTokens || charge > maxTokens-(state.Committed-reserved) {
|
||||
return errors.New("settled tokens exceed representable ledger balance; reservation retained")
|
||||
}
|
||||
err = l.append(tokenEvent{Kind: "settle", ID: id, Tokens: charge, Status: status}, n)
|
||||
if errors.Is(err, session.ErrAnnotationConflict) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("persist token settlement: %w", err)
|
||||
}
|
||||
state, err = l.State()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Exhausted {
|
||||
return ErrExhausted
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package budget
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
func estimate(llm.ChatRequest) (int64, error) { return 10, nil }
|
||||
func reserve(t *testing.T, l *TokenLedger, id string) func(llm.RequestUsage) error {
|
||||
t.Helper()
|
||||
done, err := l.Admission(estimate)(context.Background(), llm.ChatRequest{Model: "m", MaxTokens: 20}, llm.CallCompaction, id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return done
|
||||
}
|
||||
func TestTokenLedgerRestartRetainsUncertainAndRequiresDecision(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "s")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err := OpenTokenLedger(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = l.Decide(ctx, 50); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reserve(t, l, "interrupted")
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = store.LoadExclusive("a", "s")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
l, err = OpenTokenLedger(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := l.State()
|
||||
if err != nil || state.Committed != 30 || state.Attempts[0].Status != "reserved" {
|
||||
t.Fatalf("restart %+v %v", state, err)
|
||||
}
|
||||
_, err = l.Admission(estimate)(ctx, llm.ChatRequest{MaxTokens: 20}, llm.CallRetry, "next")
|
||||
if !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Even a smaller request cannot implicitly resume an exhausted decision.
|
||||
_, err = l.Admission(estimate)(ctx, llm.ChatRequest{MaxTokens: 1}, llm.CallRetry, "small")
|
||||
if !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal("exhaustion not latched")
|
||||
}
|
||||
if err = l.Decide(ctx, 80); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := reserve(t, l, "resumed")
|
||||
if err = done(llm.RequestUsage{ID: "resumed", Status: "completed", Usage: &llm.Usage{InputTokens: 8, OutputTokens: 2}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ = l.State()
|
||||
if state.Committed != 40 || state.Limit != 80 || state.Exhausted {
|
||||
t.Fatalf("state %+v", state)
|
||||
}
|
||||
s.Compact("summary", 0)
|
||||
if err = s.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, err = OpenTokenLedger(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, _ = l.State()
|
||||
if state.Committed != 40 {
|
||||
t.Fatal("compaction erased ledger")
|
||||
}
|
||||
}
|
||||
func TestTokenLedgerOwnersCannotDoubleReserve(t *testing.T) {
|
||||
s := session.NewSession("a", "s")
|
||||
first, _ := OpenTokenLedger(s)
|
||||
second, _ := OpenTokenLedger(s)
|
||||
if err := first.Decide(context.Background(), 30); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
results := make(chan error, 2)
|
||||
for i, l := range []*TokenLedger{first, second} {
|
||||
wg.Add(1)
|
||||
go func(i int, l *TokenLedger) {
|
||||
defer wg.Done()
|
||||
_, err := l.Admission(estimate)(context.Background(), llm.ChatRequest{MaxTokens: 20}, llm.CallGeneration, string(rune('a'+i)))
|
||||
results <- err
|
||||
}(i, l)
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
ok := 0
|
||||
for err := range results {
|
||||
if err == nil {
|
||||
ok++
|
||||
} else if !errors.Is(err, ErrExhausted) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
state, err := first.State()
|
||||
if err != nil || ok != 1 || state.Committed != 30 || len(state.Attempts) != 1 {
|
||||
t.Fatalf("state %+v success %d err %v", state, ok, err)
|
||||
}
|
||||
}
|
||||
func TestTokenLedgerSettlementUncertaintyAndOverrun(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, status string
|
||||
usage *llm.Usage
|
||||
want int64
|
||||
exhausted bool
|
||||
}{
|
||||
{"missing", "completed", nil, 30, false},
|
||||
{"partial", "cancelled", &llm.Usage{InputTokens: 1}, 30, false},
|
||||
{"not_sent", "not_dispatched", nil, 0, false},
|
||||
{"overrun", "completed", &llm.Usage{InputTokens: 80, OutputTokens: 40}, 120, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
l, _ := OpenTokenLedger(session.NewSession("a", "s"))
|
||||
if err := l.Decide(context.Background(), 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := reserve(t, l, "attempt")
|
||||
r := llm.RequestUsage{ID: "attempt", Status: tc.status, Usage: tc.usage}
|
||||
if err := done(r); (err != nil) != tc.exhausted || (err != nil && !errors.Is(err, ErrExhausted)) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := done(r); (err != nil) != tc.exhausted || (err != nil && !errors.Is(err, ErrExhausted)) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := l.State()
|
||||
if err != nil || state.Committed != tc.want || state.Exhausted != tc.exhausted {
|
||||
t.Fatalf("state %+v err %v", state, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestTokenLedgerPersistenceFailurePreventsDispatch(t *testing.T) {
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "s"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "s")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l, _ := OpenTokenLedger(s)
|
||||
if err = l.Decide(context.Background(), 100); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := llm.WithCallAdmission(context.Background(), l.Admission(estimate))
|
||||
_, err = llm.ObserveChat(ctx, llm.ChatRequest{MaxTokens: 20}, llm.CallGeneration, func(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
t.Fatal("failed reservation dispatched")
|
||||
return nil, nil
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("closed journal accepted reservation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type budgetProvider struct {
|
||||
fakeProvider
|
||||
requests []llm.ChatRequest
|
||||
}
|
||||
|
||||
func (p *budgetProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.requests = append(p.requests, req)
|
||||
return p.fakeProvider.ChatStream(ctx, req)
|
||||
}
|
||||
func TestSummariserOutputBudgetAndResponseBound(t *testing.T) {
|
||||
entries := []session.SessionEntry{session.UserMessageEntry("task")}
|
||||
for _, limit := range []int{0, 1, 2048, 32768, -1, 32769} {
|
||||
provider := &budgetProvider{fakeProvider: fakeProvider{text: "summary"}}
|
||||
s := &Summarizer{Provider: provider, MaxOutputTokens: limit}
|
||||
_, err := s.Summarize(context.Background(), entries, "")
|
||||
if limit < 0 || limit > 32768 {
|
||||
if err == nil || len(provider.requests) != 0 {
|
||||
t.Fatal("invalid budget dispatched")
|
||||
}
|
||||
continue
|
||||
}
|
||||
want := limit
|
||||
if want == 0 {
|
||||
want = 4096
|
||||
}
|
||||
if err != nil || len(provider.requests) != 1 || provider.requests[0].MaxTokens != want {
|
||||
t.Fatalf("budget %d: %v %+v", limit, err, provider.requests)
|
||||
}
|
||||
}
|
||||
provider := &budgetProvider{fakeProvider: fakeProvider{text: strings.Repeat("x", (256<<10)+1)}}
|
||||
s := &Summarizer{Provider: provider}
|
||||
out, err := s.Summarize(context.Background(), entries, "")
|
||||
if err == nil || out != "" || len(provider.requests) != 1 {
|
||||
t.Fatal("oversized summary accepted or retried")
|
||||
}
|
||||
}
|
||||
+121
-47
@@ -4,16 +4,15 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
// MaxConsecutiveFailures is the per-session circuit-breaker threshold.
|
||||
// After this many consecutive autocompact attempts that drop to the
|
||||
// placeholder stage (stage 3), MaybeCompact stops attempting compaction
|
||||
// After this many consecutive failed autocompact attempts, MaybeCompact stops attempting compaction
|
||||
// for the session and returns Skipped="circuit_breaker".
|
||||
//
|
||||
// The breaker resets on any genuine summarizer success (stage 1 or 2
|
||||
@@ -34,6 +33,8 @@ const (
|
||||
// false, Skipped names the reason ("too_short", "empty_summary",
|
||||
// "ollama_down", "model_missing", "timeout", "summarizer_error").
|
||||
type Result struct {
|
||||
Requests []llm.RequestUsage
|
||||
|
||||
Compacted bool
|
||||
Reason Reason
|
||||
Skipped string
|
||||
@@ -46,7 +47,23 @@ type Result struct {
|
||||
|
||||
// Manager orchestrates compaction for sessions. One Manager is shared across
|
||||
// the whole agent runtime; it tracks per-session mutexes internally.
|
||||
type CommitNotification struct {
|
||||
SessionID string
|
||||
Reason Reason
|
||||
TurnsCompacted int
|
||||
TokensBefore int
|
||||
TokensAfter int
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
// OnCommitted observes a successfully committed compaction after its lock is released.
|
||||
// Configure while idle; callbacks must honour their bounded context. Panics are contained.
|
||||
OnCommitted func(context.Context, CommitNotification)
|
||||
|
||||
// OnUsage receives compaction attempt records, including background work.
|
||||
// The callback must be concurrency-safe and must not mutate records.
|
||||
OnUsage func(llm.RequestUsage)
|
||||
|
||||
Summarizer *Summarizer
|
||||
PreserveTurns int // K; default 4 if zero
|
||||
Threshold float64 // fraction of context window that triggers preventive compaction (e.g. 0.6); 0 means use caller default
|
||||
@@ -65,13 +82,14 @@ type Manager struct {
|
||||
// mutexes so awaiting an in-flight compaction (WaitForInFlight)
|
||||
// never serializes on the per-session lock-map or failure-counter.
|
||||
inFlightMu sync.Mutex
|
||||
inFlight map[string]*inFlightCompaction // session.ID → in-flight handle
|
||||
inFlight map[string]*inFlightCompaction // stable session key → active or unconsumed handle
|
||||
}
|
||||
|
||||
// inFlightCompaction tracks a background compaction goroutine spawned
|
||||
// via MaybeCompactAsync. The done channel is closed when the goroutine
|
||||
// returns; result holds the outcome for any waiter that wants it.
|
||||
type inFlightCompaction struct {
|
||||
cancel context.CancelFunc
|
||||
done chan struct{}
|
||||
result Result
|
||||
err error
|
||||
@@ -90,11 +108,32 @@ type inFlightCompaction struct {
|
||||
// will block until the first completes. This is intentional — it prevents
|
||||
// two compactions from racing on session.Append — but callers triggering
|
||||
// manual compactions while a preventive one is in flight should expect a wait.
|
||||
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (Result, error) {
|
||||
func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reason Reason, instructions string) (result Result, resultErr error) {
|
||||
ledger := &llm.UsageLedger{}
|
||||
ctx = llm.WithUsageObserver(ctx, func(record llm.RequestUsage) {
|
||||
ledger.Record(record)
|
||||
if m != nil && m.OnUsage != nil {
|
||||
m.OnUsage(record)
|
||||
}
|
||||
})
|
||||
defer func() { result.Requests = ledger.Records() }()
|
||||
|
||||
if m == nil || m.Summarizer == nil {
|
||||
return Result{Reason: reason, Skipped: "no_summarizer"}, nil
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if resultErr == nil && result.Compacted && m.OnCommitted != nil {
|
||||
observerCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
slog.Warn("compaction observer panicked")
|
||||
}
|
||||
}()
|
||||
m.OnCommitted(observerCtx, CommitNotification{sess.ID, result.Reason, result.TurnsCompacted, result.TokensBefore, result.TokensAfter})
|
||||
}
|
||||
}()
|
||||
key := stableKey(sess)
|
||||
if fc := m.failureCount(key); fc >= MaxConsecutiveFailures {
|
||||
slog.Info("compaction skipped",
|
||||
@@ -124,27 +163,20 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
|
||||
|
||||
slog.Info("compaction triggered", "session_id", sess.ID, "reason", string(reason))
|
||||
|
||||
summary, err := m.Summarizer.Summarize(ctx, toCompact, instructions)
|
||||
combined, err := guidanceFor(ctx, instructions)
|
||||
if err != nil {
|
||||
return Result{Reason: reason, Skipped: "invalid_guidance"}, err
|
||||
}
|
||||
summary, err := m.Summarizer.Summarize(ctx, toCompact, combined)
|
||||
if err != nil {
|
||||
skipReason := classifySummarizerError(err)
|
||||
slog.Warn("compaction skipped", "session_id", sess.ID, "reason", string(reason), "skipped", skipReason, "detail", err.Error())
|
||||
// A hard error from Summarize means even stage 3 didn't run.
|
||||
// Count it as a failure for breaker accounting.
|
||||
// Leave both raw and effective history unchanged on summarizer failure.
|
||||
m.incrementFailure(key)
|
||||
return Result{Reason: reason, Skipped: skipReason}, nil
|
||||
}
|
||||
|
||||
// summarizeWithFallback's stage 3 returns a placeholder summary
|
||||
// (no error) when both stage 1 and stage 2 failed. We detect
|
||||
// placeholders by their stable marker phrase and treat them as
|
||||
// failures for breaker accounting; real (stage-1 or stage-2)
|
||||
// summaries reset the counter.
|
||||
isPlaceholder := strings.Contains(summary, "compaction failed and the summary could not be generated")
|
||||
if isPlaceholder {
|
||||
m.incrementFailure(key)
|
||||
} else {
|
||||
m.resetFailures(key)
|
||||
}
|
||||
|
||||
first := toCompact[0]
|
||||
last := toCompact[len(toCompact)-1]
|
||||
@@ -156,14 +188,8 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
|
||||
// compaction at the leaf and View() would terminate on it immediately,
|
||||
// silently dropping every preserved turn.
|
||||
entry.ParentID = toPreserve[0].ParentID
|
||||
sess.Append(entry)
|
||||
for i, e := range toPreserve {
|
||||
if i == 0 {
|
||||
e.ParentID = entry.ID
|
||||
}
|
||||
// Re-append with same ID — Session.Append's entryMap overwrite and
|
||||
// the loader's last-write-wins behaviour both make this safe.
|
||||
sess.Append(e)
|
||||
if err := sess.CommitCompaction(view[len(view)-1].ID, entry, toPreserve); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
|
||||
dur := time.Since(start).Milliseconds()
|
||||
@@ -197,6 +223,18 @@ func (m *Manager) MaybeCompact(ctx context.Context, sess *session.Session, reaso
|
||||
// enough for the three-stage fallback path) so that a returning
|
||||
// caller's cancellation can't kill the in-flight summary.
|
||||
func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan struct{} {
|
||||
return m.maybeCompactAsync(context.Background(), sess, reason, false)
|
||||
}
|
||||
|
||||
// MaybeCompactAsyncContext retains caller cancellation and usage observation.
|
||||
// Its completed result remains available until JoinInFlight or ForgetSession;
|
||||
// another launch for this session returns the existing handle until then.
|
||||
// Callers must join before releasing ownership, including on error paths.
|
||||
func (m *Manager) MaybeCompactAsyncContext(parent context.Context, sess *session.Session, reason Reason) <-chan struct{} {
|
||||
return m.maybeCompactAsync(parent, sess, reason, true)
|
||||
}
|
||||
|
||||
func (m *Manager) maybeCompactAsync(parent context.Context, sess *session.Session, reason Reason, retainResult bool) <-chan struct{} {
|
||||
if m == nil || m.Summarizer == nil || sess == nil {
|
||||
ch := make(chan struct{})
|
||||
close(ch)
|
||||
@@ -211,27 +249,26 @@ func (m *Manager) MaybeCompactAsync(sess *session.Session, reason Reason) <-chan
|
||||
if m.inFlight == nil {
|
||||
m.inFlight = make(map[string]*inFlightCompaction)
|
||||
}
|
||||
fl := &inFlightCompaction{done: make(chan struct{})}
|
||||
m.inFlight[key] = fl
|
||||
m.inFlightMu.Unlock()
|
||||
|
||||
timeout := m.Summarizer.Timeout
|
||||
if timeout == 0 {
|
||||
timeout = 60 * time.Second
|
||||
}
|
||||
go func() {
|
||||
defer close(fl.done)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*timeout)
|
||||
defer cancel()
|
||||
res, err := m.MaybeCompact(ctx, sess, reason, "")
|
||||
fl.result = res
|
||||
fl.err = err
|
||||
// Drop our entry from the map so a subsequent burst can fire a
|
||||
// fresh compaction (the next turn's WaitForInFlight will see no
|
||||
// entry and proceed straight to its own threshold check).
|
||||
m.inFlightMu.Lock()
|
||||
delete(m.inFlight, key)
|
||||
ctx, cancel := context.WithTimeout(parent, 2*timeout)
|
||||
fl := &inFlightCompaction{done: make(chan struct{}), cancel: cancel}
|
||||
m.inFlight[key] = fl
|
||||
m.inFlightMu.Unlock()
|
||||
|
||||
go func() {
|
||||
defer func() {
|
||||
cancel()
|
||||
m.inFlightMu.Lock()
|
||||
close(fl.done)
|
||||
if !retainResult && m.inFlight[key] == fl {
|
||||
delete(m.inFlight, key)
|
||||
}
|
||||
m.inFlightMu.Unlock()
|
||||
}()
|
||||
fl.result, fl.err = m.MaybeCompact(ctx, sess, reason, "")
|
||||
}()
|
||||
return fl.done
|
||||
}
|
||||
@@ -281,8 +318,16 @@ func (m *Manager) HasInFlight(sess *session.Session) bool {
|
||||
key := stableKey(sess)
|
||||
m.inFlightMu.Lock()
|
||||
defer m.inFlightMu.Unlock()
|
||||
_, ok := m.inFlight[key]
|
||||
return ok
|
||||
fl, ok := m.inFlight[key]
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
select {
|
||||
case <-fl.done:
|
||||
return false
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// ForgetSession removes the per-session lock, failure counter, and
|
||||
@@ -300,6 +345,9 @@ func (m *Manager) ForgetSession(sess *session.Session) {
|
||||
if m == nil || sess == nil {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
m.JoinInFlight(ctx, sess)
|
||||
key := stableKey(sess)
|
||||
m.mu.Lock()
|
||||
delete(m.locks, key)
|
||||
@@ -307,9 +355,7 @@ func (m *Manager) ForgetSession(sess *session.Session) {
|
||||
m.failMu.Lock()
|
||||
delete(m.failures, key)
|
||||
m.failMu.Unlock()
|
||||
// Drop any in-flight tracking entry too. The goroutine itself
|
||||
// already deletes its entry on completion; this covers the rare
|
||||
// case of a session being forgotten mid-compaction.
|
||||
// Clear tracking after joining; the owner must prevent concurrent launches.
|
||||
m.inFlightMu.Lock()
|
||||
delete(m.inFlight, key)
|
||||
m.inFlightMu.Unlock()
|
||||
@@ -389,3 +435,31 @@ func classifySummarizerError(err error) string {
|
||||
return "summarizer_error"
|
||||
}
|
||||
}
|
||||
|
||||
// JoinInFlight waits for and consumes the current background producer, returning its result
|
||||
// and error. Cancellation cancels that producer, then still waits for it to
|
||||
// finish; it never reports a join while session writes can continue. Callers
|
||||
// must prevent concurrent new launches while ending session ownership.
|
||||
func (m *Manager) JoinInFlight(ctx context.Context, sess *session.Session) (Result, bool, error) {
|
||||
if m == nil || sess == nil {
|
||||
return Result{}, false, nil
|
||||
}
|
||||
m.inFlightMu.Lock()
|
||||
fl, ok := m.inFlight[stableKey(sess)]
|
||||
m.inFlightMu.Unlock()
|
||||
if !ok {
|
||||
return Result{}, false, nil
|
||||
}
|
||||
select {
|
||||
case <-fl.done:
|
||||
case <-ctx.Done():
|
||||
fl.cancel()
|
||||
<-fl.done
|
||||
}
|
||||
m.inFlightMu.Lock()
|
||||
if m.inFlight[stableKey(sess)] == fl {
|
||||
delete(m.inFlight, stableKey(sess))
|
||||
}
|
||||
m.inFlightMu.Unlock()
|
||||
return fl.result, true, fl.err
|
||||
}
|
||||
@@ -93,12 +93,7 @@ func TestManagerRefusesShortSession(t *testing.T) {
|
||||
assert.Equal(t, "too_short", res.Skipped)
|
||||
}
|
||||
|
||||
func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
|
||||
// With the three-stage fallback chain, an empty model response no
|
||||
// longer surfaces ErrEmptySummary to the Manager — stage 3 emits a
|
||||
// placeholder summary so compaction "succeeds" with a stub. The
|
||||
// circuit breaker (Task 5) detects the stub by string match for
|
||||
// breaker accounting.
|
||||
func TestManagerSummarizerErrorSkipsWithoutSummary(t *testing.T) {
|
||||
mgr := &Manager{
|
||||
Summarizer: &Summarizer{
|
||||
Provider: &fakeProvider{text: ""},
|
||||
@@ -110,9 +105,9 @@ func TestManagerSummarizerErrorFallsBackToPlaceholder(t *testing.T) {
|
||||
sess := longSession()
|
||||
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, res.Compacted, "stage-3 placeholder counts as a successful compaction")
|
||||
assert.Contains(t, res.Summary, "compaction failed",
|
||||
"summary must contain the placeholder marker so Task 5's breaker can detect it")
|
||||
assert.False(t, res.Compacted)
|
||||
assert.Empty(t, res.Summary)
|
||||
assert.NotEmpty(t, res.Skipped)
|
||||
}
|
||||
|
||||
func TestManagerSerializesPerSession(t *testing.T) {
|
||||
@@ -342,24 +337,11 @@ func TestCircuitBreakerTripsAfterMaxFailures(t *testing.T) {
|
||||
}
|
||||
sess := longSession()
|
||||
|
||||
// First N-1 attempts run the summarizer; the alwaysFailingProvider
|
||||
// makes every call drop to stage 3 (placeholder). The breaker treats
|
||||
// hitting stage 3 as failure for circuit-breaker accounting.
|
||||
//
|
||||
// After each placeholder compaction, View() walks back to the new
|
||||
// compaction entry and Split sees only the preserved K turns — too
|
||||
// short to compact again. To keep the loop reaching the summarizer
|
||||
// (so the failure counter can increment) we add a new user/assistant
|
||||
// pair between iterations, simulating real conversation continuing
|
||||
// through repeated compaction failures.
|
||||
//
|
||||
// First MaxConsecutiveFailures calls: Compacted=true (placeholder)
|
||||
// — each increments the failure counter. The next call sees
|
||||
// counter >= MaxConsecutiveFailures and is blocked by the breaker.
|
||||
// Failed attempts leave history available and increment the breaker.
|
||||
for i := range MaxConsecutiveFailures {
|
||||
res, err := mgr.MaybeCompact(context.Background(), sess, ReasonPreventive, "")
|
||||
require.NoError(t, err, "iteration %d", i)
|
||||
assert.True(t, res.Compacted, "iteration %d should still attempt", i)
|
||||
assert.False(t, res.Compacted, "iteration %d must preserve history", i)
|
||||
// Add new turns so the next iteration has something to compact.
|
||||
sess.Append(session.UserMessageEntry("follow-up"))
|
||||
sess.Append(session.AssistantMessageEntry("more reply"))
|
||||
@@ -429,3 +411,81 @@ func longSessionWith(agentID, key string) *session.Session {
|
||||
}
|
||||
return sess
|
||||
}
|
||||
|
||||
func TestCommittedObserverSeesCommittedHistoryAndCannotChangeResult(t *testing.T) {
|
||||
for _, mode := range []string{"success", "panic", "skip", "failure"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
sess := longSession()
|
||||
defer sess.Close()
|
||||
mgr := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
|
||||
if mode == "skip" {
|
||||
mgr.Summarizer = nil
|
||||
}
|
||||
if mode == "failure" {
|
||||
mgr.Summarizer.Provider = &fakeProvider{err: errors.New("unavailable")}
|
||||
}
|
||||
calls := 0
|
||||
mgr.OnCommitted = func(ctx context.Context, event CommitNotification) {
|
||||
calls++
|
||||
if event.SessionID != sess.ID || event.TurnsCompacted == 0 || sess.View()[0].Type != session.EntryTypeCompaction {
|
||||
t.Fatal(event, sess.View())
|
||||
}
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || time.Until(deadline) > 2*time.Second {
|
||||
t.Fatal("observer not bounded")
|
||||
}
|
||||
lock := mgr.lockFor(stableKey(sess))
|
||||
if !lock.TryLock() {
|
||||
t.Fatal("observer called under compaction lock")
|
||||
}
|
||||
lock.Unlock()
|
||||
if mode == "panic" {
|
||||
panic("observer failure")
|
||||
}
|
||||
}
|
||||
result, err := mgr.MaybeCompact(context.Background(), sess, ReasonManual, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := mode == "success" || mode == "panic"
|
||||
if result.Compacted != expected || (calls == 1) != expected {
|
||||
t.Fatal(result, calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackgroundCompactionJoinsCommittedObserver(t *testing.T) {
|
||||
sess := longSession()
|
||||
defer sess.Close()
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: "summary"}, Model: "m", Timeout: time.Second}, PreserveTurns: 4}
|
||||
manager.OnCommitted = func(ctx context.Context, event CommitNotification) {
|
||||
close(entered)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
done := manager.MaybeCompactAsyncContext(ctx, sess, ReasonPreventive)
|
||||
select {
|
||||
case <-entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("observer never entered")
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
t.Fatal("background finished before observer joined")
|
||||
default:
|
||||
}
|
||||
if !manager.HasInFlight(sess) {
|
||||
t.Fatal("active observer not tracked")
|
||||
}
|
||||
close(release)
|
||||
result, joined, err := manager.JoinInFlight(ctx, sess)
|
||||
if err != nil || !joined || !result.Compacted || manager.HasInFlight(sess) {
|
||||
t.Fatal(result, joined, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type guidanceKey struct{}
|
||||
|
||||
// WithGuidance binds immutable caller guidance to synchronous and asynchronous
|
||||
// compaction derived from this context. It does not modify shared managers.
|
||||
func WithGuidance(ctx context.Context, guidance string) (context.Context, error) {
|
||||
if len(guidance) > 48<<10 || !utf8.ValidString(guidance) || strings.ContainsRune(guidance, 0) {
|
||||
return ctx, errors.New("compaction guidance exceeds 48 KiB or is invalid UTF-8")
|
||||
}
|
||||
return context.WithValue(ctx, guidanceKey{}, guidance), nil
|
||||
}
|
||||
func guidanceFor(ctx context.Context, focus string) (string, error) {
|
||||
guidance, _ := ctx.Value(guidanceKey{}).(string)
|
||||
if len(focus) > 16<<10 || !utf8.ValidString(focus) || strings.ContainsRune(focus, 0) {
|
||||
return "", errors.New("compaction focus exceeds 16 KiB or is invalid UTF-8")
|
||||
}
|
||||
if guidance == "" {
|
||||
return focus, nil
|
||||
}
|
||||
return guidance + "\n\nCurrent compaction focus:\n" + focus, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestJoinRetainsCompletedResultUntilConsumed(t *testing.T) {
|
||||
mgr := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary"}, PreserveTurns: 1}
|
||||
sess := longSession()
|
||||
done := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonManual)
|
||||
<-done
|
||||
require.False(t, mgr.HasInFlight(sess), "completed producer is not running")
|
||||
// Neither a legacy waiter nor another launch may erase an unconsumed result.
|
||||
res, found := mgr.WaitForInFlight(sess, time.Second)
|
||||
require.True(t, found)
|
||||
require.True(t, res.Compacted)
|
||||
require.Equal(t, done, mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive))
|
||||
res, found, err := mgr.JoinInFlight(context.Background(), sess)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.True(t, res.Compacted)
|
||||
require.Len(t, res.Requests, 1)
|
||||
_, found, err = mgr.JoinInFlight(context.Background(), sess)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
next := mgr.MaybeCompactAsyncContext(context.Background(), sess, ReasonPreventive)
|
||||
require.NotEqual(t, done, next)
|
||||
<-next
|
||||
_, found, err = mgr.JoinInFlight(context.Background(), sess)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/stretchr/testify/require"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFailedSummarisationPreservesEffectiveAndRawHistory(t *testing.T) {
|
||||
sess := longSession()
|
||||
before := sess.View()
|
||||
raw := sess.Entries()
|
||||
leaf := sess.LeafID()
|
||||
manager := &Manager{Summarizer: &Summarizer{Provider: &fakeProvider{text: ""}, Model: "test"}, PreserveTurns: 4}
|
||||
result, err := manager.MaybeCompact(context.Background(), sess, ReasonManual, "")
|
||||
require.NoError(t, err)
|
||||
require.False(t, result.Compacted)
|
||||
require.NotEmpty(t, result.Skipped)
|
||||
require.Equal(t, before, sess.View())
|
||||
require.Equal(t, raw, sess.Entries())
|
||||
require.Equal(t, leaf, sess.LeafID())
|
||||
}
|
||||
+32
-40
@@ -18,7 +18,10 @@ var ErrEmptySummary = errors.New("compaction: empty summary returned")
|
||||
// for compaction. The provider is expected to be the bundled Ollama in
|
||||
// production but any LLMProvider works (used for tests).
|
||||
type Summarizer struct {
|
||||
Route llm.CallRoute // identifies the independently selected provider client
|
||||
|
||||
Provider llm.LLMProvider
|
||||
MaxOutputTokens int // 0 defaults to 4096; otherwise 1-32768
|
||||
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
|
||||
Timeout time.Duration // per-call deadline; 0 → 60s
|
||||
}
|
||||
@@ -27,16 +30,9 @@ type Summarizer struct {
|
||||
// trimmed, formatted summary text. additionalInstructions is appended to
|
||||
// the prompt when non-empty (used by manual /compact <focus...>).
|
||||
//
|
||||
// The call wraps three fallback stages:
|
||||
// 1. Full transcript — preferred; preserves all detail.
|
||||
// 2. Small-only — drops oversized messages, keeps a note that they were
|
||||
// elided. Triggered when stage 1 returns a context-overflow error
|
||||
// or a stream error.
|
||||
// 3. Placeholder — a static stub indicating compaction failed; never
|
||||
// returns an error to the caller so the agent loop can continue.
|
||||
//
|
||||
// Each stage applies FormatCompactSummary to strip the analysis scratchpad
|
||||
// and unwrap the summary block.
|
||||
// A full transcript is attempted first. Overflow/stream failures may retry
|
||||
// with oversized messages explicitly elided. If neither attempt produces a
|
||||
// summary, return the error so the manager preserves effective history.
|
||||
func (s *Summarizer) Summarize(ctx context.Context, entries []session.SessionEntry, additionalInstructions string) (string, error) {
|
||||
return s.summarizeWithFallback(ctx, entries, additionalInstructions)
|
||||
}
|
||||
@@ -49,16 +45,8 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
|
||||
}
|
||||
stage1Err := err
|
||||
|
||||
// Context cancellation/deadline propagates up — the caller asked us to
|
||||
// stop, so don't burn an extra provider call on stage 2 or paper over
|
||||
// the cancel with a placeholder. This preserves the Manager's ability
|
||||
// to classify cancellation/timeout distinctly from "compaction is
|
||||
// genuinely broken; degrade gracefully".
|
||||
//
|
||||
// We also propagate a per-call deadline (Summarizer.Timeout firing while
|
||||
// the parent ctx is still alive) — otherwise a per-call timeout would
|
||||
// flow into stage 2/3, masking timeout as a placeholder. Manager
|
||||
// classifies the wrapped DeadlineExceeded as Skipped: "timeout".
|
||||
// Cancellation and per-call deadlines stop retries and retain their
|
||||
// classification for the manager.
|
||||
if ctxErr := ctx.Err(); ctxErr != nil || errors.Is(stage1Err, context.DeadlineExceeded) {
|
||||
return "", stage1Err
|
||||
}
|
||||
@@ -67,7 +55,7 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
|
||||
// buildSmallOnlyTranscript actually elides something — otherwise we'd
|
||||
// be re-sending the same transcript with the same prompt against the
|
||||
// same provider (predictable failure, wasted call). Fall through to
|
||||
// stage 3 in that case.
|
||||
// the final error in that case.
|
||||
if isOverflowError(stage1Err) || isStreamError(stage1Err) {
|
||||
small, droppedCount := buildSmallOnlyTranscript(entries)
|
||||
if droppedCount > 0 {
|
||||
@@ -79,9 +67,10 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 3: placeholder. Never returns an error — the agent loop must
|
||||
// be able to continue even if compaction is wholly broken.
|
||||
return placeholderSummary(len(entries)), nil
|
||||
if failure := errors.Join(stage1Err, err); failure != nil {
|
||||
return "", failure
|
||||
}
|
||||
return "", ErrEmptySummary
|
||||
}
|
||||
|
||||
// callOnce performs a single summarizer invocation against a pre-built
|
||||
@@ -94,6 +83,16 @@ func (s *Summarizer) summarizeWithFallback(ctx context.Context, entries []sessio
|
||||
// 5-minute TTL window hits cache_read for the prefix, dropping a few
|
||||
// seconds off TTFT.
|
||||
func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstructions string) (string, error) {
|
||||
maxTokens := s.MaxOutputTokens
|
||||
if maxTokens == 0 {
|
||||
maxTokens = 4096
|
||||
}
|
||||
if maxTokens < 1 || maxTokens > 32768 {
|
||||
return "", errors.New("summariser output token limit must be 1-32768")
|
||||
}
|
||||
if s.Provider == nil {
|
||||
return "", errors.New("summariser provider unavailable")
|
||||
}
|
||||
systemPrompt, userMessage := BuildPromptParts(transcript, additionalInstructions)
|
||||
timeout := s.Timeout
|
||||
if timeout == 0 {
|
||||
@@ -103,6 +102,7 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
||||
defer cancel()
|
||||
|
||||
req := llm.ChatRequest{
|
||||
Route: s.Route,
|
||||
Model: s.Model,
|
||||
Messages: []llm.Message{{Role: "user", Content: userMessage}},
|
||||
// One cache-marked system part: providers that support caching
|
||||
@@ -111,9 +111,9 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
||||
SystemPromptParts: []llm.SystemPromptPart{
|
||||
{Text: systemPrompt, Cache: true},
|
||||
},
|
||||
MaxTokens: 4096,
|
||||
MaxTokens: maxTokens,
|
||||
}
|
||||
stream, err := s.Provider.ChatStream(callCtx, req)
|
||||
stream, err := llm.ObserveChat(callCtx, req, llm.CallCompaction, s.Provider.ChatStream)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("compaction: chat stream: %w", err)
|
||||
}
|
||||
@@ -122,11 +122,17 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
|
||||
for ev := range stream {
|
||||
switch ev.Type {
|
||||
case llm.EventTextDelta:
|
||||
if len(ev.Text) > 256<<10-sb.Len() {
|
||||
return "", errors.New("summariser response exceeds 256 KiB")
|
||||
}
|
||||
sb.WriteString(ev.Text)
|
||||
case llm.EventError:
|
||||
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
|
||||
}
|
||||
}
|
||||
if err := callCtx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
out := strings.TrimSpace(sb.String())
|
||||
if out == "" {
|
||||
return "", ErrEmptySummary
|
||||
@@ -161,20 +167,6 @@ func buildSmallOnlyTranscript(entries []session.SessionEntry) (string, int) {
|
||||
return BuildTranscript(kept), dropped
|
||||
}
|
||||
|
||||
// placeholderSummary is the stage-3 fallback. It must be a valid summary
|
||||
// the model can pick up from — minimally describing what was elided so
|
||||
// the next turn doesn't act as if the conversation was empty. The
|
||||
// "compaction failed and the summary could not be generated" phrase is
|
||||
// stable: Task 5's circuit breaker detects placeholders by string match
|
||||
// on this fragment to count them as failures for breaker accounting.
|
||||
func placeholderSummary(entryCount int) string {
|
||||
return fmt.Sprintf(
|
||||
"Summary:\nConversation history (%d entries) — compaction failed and the summary could not be generated. "+
|
||||
"The conversation continues; refer to the recent preserved turns and ask the user for any context you need.",
|
||||
entryCount,
|
||||
)
|
||||
}
|
||||
|
||||
// isOverflowError reports whether err looks like a "your prompt is too big"
|
||||
// signal from any provider. Re-uses the overflow signature list rather
|
||||
// than depending on package-level state.
|
||||
|
||||
@@ -58,37 +58,26 @@ func TestSummarizerTrimsWhitespace(t *testing.T) {
|
||||
assert.Equal(t, "summary text", got)
|
||||
}
|
||||
|
||||
func TestSummarizerEmptyResponseFallsBackToPlaceholder(t *testing.T) {
|
||||
// An empty model response is no longer surfaced as ErrEmptySummary —
|
||||
// the three-stage fallback chain catches it: stage 1 returns
|
||||
// ErrEmptySummary internally, stage 2 is skipped (not an overflow or
|
||||
// stream error), stage 3 emits the placeholder. The underlying
|
||||
// ErrEmptySummary remains the failure mode that callOnce reports
|
||||
// inside the chain; the user-facing contract is "always returns a
|
||||
// usable summary string, never an error".
|
||||
func TestSummarizerEmptyResponseReturnsError(t *testing.T) {
|
||||
s := &Summarizer{
|
||||
Provider: &fakeProvider{text: " \n "},
|
||||
Model: "qwen2.5:3b-instruct",
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, got, "compaction failed")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestSummarizerProviderErrorFallsBackToPlaceholder(t *testing.T) {
|
||||
// A provider-level ChatStream error is wrapped as
|
||||
// "compaction: chat stream: <err>" — neither an overflow nor a
|
||||
// stream-event error, so stage 2 is skipped and we fall straight
|
||||
// through to the placeholder. The agent loop sees no error.
|
||||
func TestSummarizerProviderErrorReturnsError(t *testing.T) {
|
||||
s := &Summarizer{
|
||||
Provider: &fakeProvider{err: errors.New("ollama down")},
|
||||
Model: "qwen2.5:3b-instruct",
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
got, err := s.Summarize(context.Background(), []session.SessionEntry{session.UserMessageEntry("hi")}, "")
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, got, "compaction failed")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
// flakyProvider returns ChatStream errors a configured number of times,
|
||||
@@ -153,7 +142,7 @@ func TestSummarizeFallbackToSmallOnlyOnOverflow(t *testing.T) {
|
||||
"second-stage success must produce the summary")
|
||||
}
|
||||
|
||||
func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
|
||||
func TestSummarizeReturnsErrorWhenAllStagesFail(t *testing.T) {
|
||||
entries := []session.SessionEntry{session.UserMessageEntry("hi")}
|
||||
s := &Summarizer{
|
||||
Provider: &flakyProvider{failsRemaining: 99, successText: ""},
|
||||
@@ -161,12 +150,8 @@ func TestSummarizeFallbackToPlaceholderWhenAllStagesFail(t *testing.T) {
|
||||
Timeout: time.Second,
|
||||
}
|
||||
got, err := s.Summarize(context.Background(), entries, "")
|
||||
require.NoError(t, err,
|
||||
"placeholder stage must not surface the underlying error to caller")
|
||||
assert.Contains(t, got, "Conversation history",
|
||||
"placeholder must be a usable summary stub")
|
||||
assert.Contains(t, got, "compaction failed",
|
||||
"placeholder must indicate the failure so the next turn can adapt")
|
||||
require.Error(t, err)
|
||||
assert.Empty(t, got)
|
||||
}
|
||||
|
||||
func TestSummarizePerCallTimeoutPropagates(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package compaction
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type usageSummaryProvider struct{ llmtest.Base }
|
||||
|
||||
func (usageSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Summary of prior work."}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1200, OutputTokens: 20}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
func TestCompactionUsageRecordsAndBackgroundObserver(t *testing.T) {
|
||||
ledger := &llm.UsageLedger{}
|
||||
manager := &Manager{Summarizer: &Summarizer{Provider: usageSummaryProvider{}, Model: "summary-model"}, OnUsage: ledger.Record, PreserveTurns: 4}
|
||||
result, err := manager.MaybeCompact(context.Background(), longSession(), ReasonManual, "")
|
||||
require.NoError(t, err)
|
||||
require.True(t, result.Compacted)
|
||||
require.Len(t, result.Requests, 1)
|
||||
require.Equal(t, llm.CallCompaction, result.Requests[0].Category)
|
||||
require.Equal(t, "summary-model", result.Requests[0].Model)
|
||||
<-manager.MaybeCompactAsync(longSession(), ReasonPreventive)
|
||||
require.Len(t, ledger.Records(), 2)
|
||||
require.Equal(t, 2400, ledger.Total().InputTokens)
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
// Package execution provides explicit host and container command boundaries.
|
||||
// Admission belongs to the caller; choosing a backend never grants permission.
|
||||
package execution
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
type Request struct {
|
||||
CaptureLimit int // zero uses 64 KiB; bounded protocol callers may request up to 16 MiB
|
||||
OutputStore *process.ArtifactStore // caller-owned trusted capture store
|
||||
Argv []string
|
||||
Env map[string]string
|
||||
Stdin []byte
|
||||
}
|
||||
type Result struct {
|
||||
StdoutTruncated, StderrTruncated bool
|
||||
StdoutBytes, StderrBytes int64
|
||||
StdoutArtifact, StderrArtifact process.ArtifactInfo
|
||||
Stdout, Stderr string
|
||||
ExitCode int
|
||||
Truncated bool
|
||||
}
|
||||
type Backend interface {
|
||||
Run(context.Context, Request) (Result, error)
|
||||
Boundary() string
|
||||
}
|
||||
type Host struct{ Workspace string }
|
||||
|
||||
func (Host) Boundary() string { return "unrestricted host; commands can access host resources" }
|
||||
func (h Host) Run(ctx context.Context, r Request) (Result, error) {
|
||||
if err := validate(r); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
return runCaptured(ctx, r.OutputStore, r.CaptureLimit, h.Workspace, environment(r.Env), r.Stdin, r.Argv[0], r.Argv[1:]...)
|
||||
}
|
||||
|
||||
var imageID = regexp.MustCompile(`^sha256:[0-9a-f]{64}$`)
|
||||
var envName = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
|
||||
|
||||
type Container struct {
|
||||
Resources []ReadOnlyResource // explicit pinned files mounted read-only at /harness-resources
|
||||
WorkerSHA256 string // required when WorkerPath is configured
|
||||
WorkerPath string // optional trusted executable mounted read-only at /hand-worker
|
||||
Docker, Socket, Image, Workspace string
|
||||
Writable, Network bool
|
||||
}
|
||||
|
||||
func (c Container) Boundary() string {
|
||||
return fmt.Sprintf("container: workspace writable=%t; network=%t; other host paths unmounted", c.Writable, c.Network)
|
||||
}
|
||||
func validate(r Request) error {
|
||||
if r.CaptureLimit < 0 || r.CaptureLimit > 16<<20 {
|
||||
return errors.New("invalid capture limit")
|
||||
}
|
||||
if len(r.Argv) == 0 || r.Argv[0] == "" || len(r.Argv) > 1024 || len(r.Stdin) > 1<<20 {
|
||||
return errors.New("invalid or oversized execution request")
|
||||
}
|
||||
size := 0
|
||||
for _, a := range r.Argv {
|
||||
size += len(a)
|
||||
if strings.ContainsRune(a, 0) {
|
||||
return errors.New("NUL in argument")
|
||||
}
|
||||
}
|
||||
for k, v := range r.Env {
|
||||
size += len(k) + len(v)
|
||||
if !envName.MatchString(k) || strings.ContainsRune(v, 0) {
|
||||
return errors.New("invalid environment entry")
|
||||
}
|
||||
}
|
||||
if size > 1<<20 {
|
||||
return errors.New("execution arguments exceed 1 MiB")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func environment(values map[string]string) []string {
|
||||
env := []string{"PATH=/usr/local/bin:/usr/bin:/bin"}
|
||||
keys := make([]string, 0, len(values))
|
||||
for k := range values {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
env = append(env, k+"="+values[k])
|
||||
}
|
||||
return env
|
||||
}
|
||||
func run(ctx context.Context, dir string, env []string, input []byte, name string, args ...string) (Result, error) {
|
||||
return runCaptured(ctx, nil, 0, dir, env, input, name, args...)
|
||||
}
|
||||
func runCaptured(ctx context.Context, store *process.ArtifactStore, limit int, dir string, env []string, input []byte, name string, args ...string) (Result, error) {
|
||||
cmd := process.Command(ctx, name, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
cmd.Stdin = bytes.NewReader(input)
|
||||
type capture interface {
|
||||
Write([]byte) (int, error)
|
||||
Snapshot() (string, int64, bool)
|
||||
}
|
||||
if limit == 0 {
|
||||
limit = 64 << 10
|
||||
}
|
||||
var out, stderr capture = process.NewCapture(limit), process.NewCapture(limit)
|
||||
var diskOut, diskErr *process.OutputCapture
|
||||
if store != nil {
|
||||
diskOut, diskErr = store.Capture(limit), store.Capture(limit)
|
||||
out, stderr = diskOut, diskErr
|
||||
}
|
||||
cmd.Stdout = out
|
||||
cmd.Stderr = stderr
|
||||
err := process.Run(cmd)
|
||||
result := Result{ExitCode: -1}
|
||||
if diskOut != nil {
|
||||
diskOut.Close()
|
||||
diskErr.Close()
|
||||
result.StdoutArtifact = diskOut.Info()
|
||||
result.StderrArtifact = diskErr.Info()
|
||||
}
|
||||
a, ab, at := out.Snapshot()
|
||||
b, bb, bt := stderr.Snapshot()
|
||||
result.Stdout = a
|
||||
result.Stderr = b
|
||||
result.StdoutBytes = ab
|
||||
result.StderrBytes = bb
|
||||
result.Truncated = at || bt
|
||||
result.StdoutTruncated = at
|
||||
result.StderrTruncated = bt
|
||||
if cmd.ProcessState != nil {
|
||||
result.ExitCode = cmd.ProcessState.ExitCode()
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
|
||||
type containerCommand struct {
|
||||
docker string
|
||||
args []string
|
||||
cleanup func() error
|
||||
}
|
||||
|
||||
func (c Container) Run(ctx context.Context, r Request) (result Result, err error) {
|
||||
plan, err := c.prepare(ctx, r)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer func() { err = errors.Join(err, plan.cleanup()) }()
|
||||
return runCaptured(ctx, r.OutputStore, r.CaptureLimit, "", environment(nil), r.Stdin, plan.docker, plan.args...)
|
||||
}
|
||||
func (c Container) prepare(ctx context.Context, r Request) (plan *containerCommand, err error) {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = validate(r); err != nil {
|
||||
return
|
||||
}
|
||||
if !filepath.IsAbs(c.Docker) || !filepath.IsAbs(c.Socket) || !imageID.MatchString(c.Image) {
|
||||
return nil, errors.New("container requires absolute Docker executable/socket and immutable sha256 image ID")
|
||||
}
|
||||
info, e := os.Stat(c.Socket)
|
||||
if e != nil || info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("local container socket unavailable; no host fallback")
|
||||
}
|
||||
workspace, e := filepath.EvalSymlinks(c.Workspace)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
workspace, e = filepath.Abs(workspace)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
info, e = os.Stat(workspace)
|
||||
if e != nil || !info.IsDir() || strings.ContainsAny(workspace, ",\n\r") {
|
||||
return nil, errors.New("invalid workspace mount")
|
||||
}
|
||||
// A separate config directory prevents ambient Docker auth/context inheritance.
|
||||
config, e := os.MkdirTemp("", "harness-docker-config-")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer func() {
|
||||
if plan == nil {
|
||||
os.RemoveAll(config)
|
||||
}
|
||||
}()
|
||||
configCanonical, e := filepath.EvalSymlinks(config)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
relative, e := filepath.Rel(workspace, configCanonical)
|
||||
if e != nil || (relative != ".." && !strings.HasPrefix(relative, ".."+string(filepath.Separator)) && !filepath.IsAbs(relative)) {
|
||||
return nil, errors.New("container state must be outside the mounted workspace")
|
||||
}
|
||||
if strings.ContainsAny(configCanonical, ",\n\r") {
|
||||
return nil, errors.New("container state path cannot be mounted safely")
|
||||
}
|
||||
base := []string{"--config", config, "--host", "unix://" + c.Socket}
|
||||
inspectCtx, inspectCancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
inspected, inspectErr := run(inspectCtx, "", environment(nil), nil, c.Docker, append(append([]string{}, base...), "image", "inspect", "--format", `{{json (index .Config "Volumes")}}`, c.Image)...)
|
||||
inspectCancel()
|
||||
if inspectErr != nil {
|
||||
return nil, fmt.Errorf("inspect container image: %w: %s", inspectErr, inspected.Stderr)
|
||||
}
|
||||
if inspected.Truncated {
|
||||
return nil, errors.New("container image volume metadata exceeds limit")
|
||||
}
|
||||
if err = validateImageVolumes(inspected.Stdout); err != nil {
|
||||
return
|
||||
}
|
||||
name := "harness-exec-" + strings.ToLower(rand.Text())
|
||||
cleanup := func() error {
|
||||
defer os.RemoveAll(config)
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
res, e := run(cleanupCtx, "", environment(nil), nil, c.Docker, append(append([]string{}, base...), "rm", "--force", name)...)
|
||||
if e != nil {
|
||||
return fmt.Errorf("container cleanup failed for %s: %w: %s", name, e, res.Stderr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
network := "none"
|
||||
if c.Network {
|
||||
network = "bridge"
|
||||
}
|
||||
mount := "type=bind,src=" + workspace + ",dst=/workspace,bind-propagation=rprivate,bind-recursive=disabled"
|
||||
if !c.Writable {
|
||||
mount += ",readonly"
|
||||
}
|
||||
uid, gid := os.Getuid(), os.Getgid()
|
||||
if uid < 1 {
|
||||
uid, gid = 65534, 65534
|
||||
}
|
||||
args := append(append([]string{}, base...), "create", "--name", name, "--pull=never", "--read-only", "--cap-drop=ALL", "--security-opt=no-new-privileges", "--network", network, "--pids-limit=128", "--memory=512m", "--memory-swap=512m", "--cpus=2", "--init", "--no-healthcheck", "--log-driver=none", "--user", strconv.Itoa(uid)+":"+strconv.Itoa(gid), "--mount", mount, "--tmpfs", "/tmp:rw,nosuid,nodev,size=64m,mode=1777", "--workdir", "/workspace", "--interactive", "--entrypoint", r.Argv[0])
|
||||
if c.WorkerPath != "" {
|
||||
worker, e := snapshotWorker(ctx, c.WorkerPath, c.WorkerSHA256, config)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
args = append(args, "--mount", "type=bind,src="+worker+",dst=/hand-worker,readonly")
|
||||
}
|
||||
|
||||
if len(c.Resources) > 0 {
|
||||
resources, e := snapshotResources(ctx, c.Resources, config)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
args = append(args, "--mount", "type=bind,src="+resources+",dst=/harness-resources,readonly,bind-recursive=disabled")
|
||||
}
|
||||
|
||||
for _, entry := range environment(r.Env) {
|
||||
args = append(args, "--env", entry)
|
||||
}
|
||||
args = append(args, c.Image)
|
||||
args = append(args, r.Argv[1:]...)
|
||||
// Join creation independently of caller cancellation before removing its name.
|
||||
// A daemon/transport failure is surfaced and cannot be treated as clean exit.
|
||||
createCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
created, createErr := run(createCtx, "", environment(nil), nil, c.Docker, args...)
|
||||
cancel()
|
||||
if createErr != nil {
|
||||
return nil, errors.Join(fmt.Errorf("container create failed: %w: %s", createErr, created.Stderr), cleanup())
|
||||
}
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, errors.Join(err, cleanup())
|
||||
}
|
||||
return &containerCommand{docker: c.Docker, args: append(append([]string{}, base...), "start", "--attach", "--interactive", name), cleanup: cleanup}, nil
|
||||
}
|
||||
|
||||
// Image-declared volumes otherwise create implicit writable disk mounts even
|
||||
// with a read-only root filesystem. Require explicit workspace/scratch only.
|
||||
func validateImageVolumes(raw string) error {
|
||||
var volumes map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(raw), &volumes); err != nil {
|
||||
return errors.New("invalid container image volume metadata")
|
||||
}
|
||||
if len(volumes) != 0 {
|
||||
return errors.New("container image declares implicit volumes; use an image without VOLUME declarations")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHostExplicitEnvironmentAndExactArguments(t *testing.T) {
|
||||
t.Setenv("EXECUTION_TEST_SECRET", "must-not-inherit")
|
||||
h := Host{Workspace: t.TempDir()}
|
||||
result, err := h.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", `test -z "$EXECUTION_TEST_SECRET"; printf '%s' "$1"`, "sh", "a; echo injected"}})
|
||||
if err != nil || result.Stdout != "a; echo injected" {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
if !strings.Contains(h.Boundary(), "unrestricted host") {
|
||||
t.Fatal("host boundary hidden")
|
||||
}
|
||||
}
|
||||
func TestMissingContainerNeverExecutesHostCommand(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "must-not-exist")
|
||||
c := Container{Docker: "/missing/docker", Socket: "/missing/socket", Image: "sha256:" + strings.Repeat("a", 64), Workspace: t.TempDir()}
|
||||
if _, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "touch " + path}}); err == nil {
|
||||
t.Fatal("missing backend accepted")
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("host fallback ran")
|
||||
}
|
||||
}
|
||||
|
||||
// This is an opt-in real-container suite. Its skip never qualifies isolation.
|
||||
func TestNativeContainerBoundary(t *testing.T) {
|
||||
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native container fixture not configured")
|
||||
}
|
||||
workspace := t.TempDir()
|
||||
if err := os.Chmod(workspace, 0777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := filepath.Join(t.TempDir(), "outside")
|
||||
if err := os.WriteFile(secret, []byte("outside"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Symlink(secret, filepath.Join(workspace, "escape")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: workspace}
|
||||
script := `set -eu; command -v /sbin/ip >/dev/null; command -v nc >/dev/null; test -z "${EXECUTION_TEST_SECRET-}"; test "$EXPLICIT_VALUE" = allowed; test ! -e /var/run/docker.sock; test ! -e /workspace/escape; ! touch /workspace/denied; ! touch /etc/denied; printf scratch >/tmp/allowed; sh -c 'test ! -e /workspace/escape; ! touch /etc/child-denied'; test -z "$(/sbin/ip route)"; ! nc -z -w 1 192.0.2.1 80; printf bounded`
|
||||
t.Setenv("EXECUTION_TEST_SECRET", "must-not-inherit")
|
||||
result, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", script}, Env: map[string]string{"EXPLICIT_VALUE": "allowed"}})
|
||||
if err != nil || result.Stdout != "bounded" {
|
||||
t.Fatalf("boundary: %+v %v", result, err)
|
||||
}
|
||||
c.Writable = true
|
||||
result, err = c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "cat > /workspace/allowed"}, Stdin: []byte("explicit write")})
|
||||
if err != nil {
|
||||
t.Fatalf("write: %+v %v", result, err)
|
||||
}
|
||||
raw, err := os.ReadFile(filepath.Join(workspace, "allowed"))
|
||||
if err != nil || string(raw) != "explicit write" {
|
||||
t.Fatalf("write missing: %q %v", raw, err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
_, err = c.Run(ctx, Request{Argv: []string{"/bin/sh", "-c", "sleep 60 & wait"}})
|
||||
if err == nil || time.Since(start) > 6*time.Second {
|
||||
t.Fatalf("cancel not bounded: %v %s", err, time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageImplicitVolumesRejected(t *testing.T) {
|
||||
for _, raw := range []string{`{"/data":{}}`, `{"/tmp":{}}`, `[]`, `"unknown"`, `{} garbage`} {
|
||||
if err := validateImageVolumes(raw); err == nil {
|
||||
t.Fatalf("accepted implicit or malformed volumes: %s", raw)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{`null`, `{}`} {
|
||||
if err := validateImageVolumes(raw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestNativeImageVolumeRejection(t *testing.T) {
|
||||
image, socket := os.Getenv("HARNESS_TEST_VOLUME_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native volume image fixture not configured")
|
||||
}
|
||||
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir()}
|
||||
_, err := c.Run(context.Background(), Request{Argv: []string{"/bin/sh", "-c", "exit 99"}})
|
||||
if err == nil || !strings.Contains(err.Error(), "implicit volumes") {
|
||||
t.Fatalf("image volume declarations were not rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeCancellationStopsChildWrites(t *testing.T) {
|
||||
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native container fixture not configured")
|
||||
}
|
||||
workspace := t.TempDir()
|
||||
if err := os.Chmod(workspace, 0777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: workspace, Writable: true}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
done := make(chan error, 1)
|
||||
joined := false
|
||||
defer func() {
|
||||
cancel()
|
||||
if !joined {
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(6 * time.Second):
|
||||
t.Error("container invocation did not join during test cleanup")
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
_, err := c.Run(ctx, Request{Argv: []string{"/bin/sh", "-c", `sh -c 'while :; do printf tick >> /workspace/heartbeat; sleep 0.05; done' & wait`}})
|
||||
done <- err
|
||||
}()
|
||||
heartbeat := filepath.Join(workspace, "heartbeat")
|
||||
for {
|
||||
if b, err := os.ReadFile(heartbeat); err == nil && len(b) > 0 {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case err := <-done:
|
||||
joined = true
|
||||
t.Fatalf("container exited before child became active: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal("child did not become active before deadline")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
start := time.Now()
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
joined = true
|
||||
if err == nil {
|
||||
t.Fatal("cancelled invocation reported success")
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("container cleanup exceeded five seconds")
|
||||
}
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Fatal("child cleanup exceeded five seconds")
|
||||
}
|
||||
before, err := os.ReadFile(heartbeat)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
after, err := os.ReadFile(heartbeat)
|
||||
if err != nil || string(before) != string(after) {
|
||||
t.Fatalf("child continued writing after cancellation: before=%d after=%d err=%v", len(before), len(after), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
// Starter is optional: backends that cannot own interactive processes must fail
|
||||
// explicitly instead of routing those operations to the host.
|
||||
type Starter interface {
|
||||
Start(context.Context, Request) (*Handle, error)
|
||||
}
|
||||
|
||||
// Handle remains running until both the process and backend cleanup have joined.
|
||||
type Handle struct {
|
||||
*process.Handle
|
||||
done chan struct{}
|
||||
err error
|
||||
}
|
||||
|
||||
func ownedHandle(handle *process.Handle, cleanup func() error) *Handle {
|
||||
h := &Handle{Handle: handle, done: make(chan struct{})}
|
||||
go func() { defer close(h.done); h.err = errors.Join(handle.Wait(), cleanup()) }()
|
||||
return h
|
||||
}
|
||||
func (h *Handle) Wait() error { <-h.done; return h.err }
|
||||
func (h *Handle) Close() error { h.Cancel(); return h.Wait() }
|
||||
func (h *Handle) Snapshot() process.HandleSnapshot {
|
||||
s := h.Handle.Snapshot()
|
||||
select {
|
||||
case <-h.done:
|
||||
s.Running = false
|
||||
if h.err != nil {
|
||||
s.Error = h.err.Error()
|
||||
}
|
||||
default:
|
||||
s.Running = true
|
||||
}
|
||||
return s
|
||||
}
|
||||
func validateStart(r Request) error {
|
||||
if err := validate(r); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.OutputStore == nil {
|
||||
return errors.New("asynchronous execution requires an output store")
|
||||
}
|
||||
if len(r.Stdin) != 0 {
|
||||
return errors.New("asynchronous input must use the owned handle")
|
||||
}
|
||||
if r.CaptureLimit != 0 {
|
||||
return errors.New("asynchronous execution uses standard bounded captures")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (h Host) Start(ctx context.Context, r Request) (*Handle, error) {
|
||||
if err := validateStart(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, err := process.StartHandleWithEnv(ctx, r.OutputStore, environment(r.Env), h.Workspace, r.Argv[0], r.Argv[1:]...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ownedHandle(handle, func() error { return nil }), nil
|
||||
}
|
||||
func (c Container) Start(ctx context.Context, r Request) (*Handle, error) {
|
||||
if err := validateStart(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan, err := c.prepare(ctx, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
handle, err := process.StartHandleWithEnv(ctx, r.OutputStore, environment(nil), "", plan.docker, plan.args...)
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, plan.cleanup())
|
||||
}
|
||||
return ownedHandle(handle, plan.cleanup), nil
|
||||
}
|
||||
|
||||
func (h *Handle) Send(ctx context.Context, data []byte) error {
|
||||
err := h.Handle.Send(ctx, data)
|
||||
if ctx.Err() != nil {
|
||||
h.Cancel()
|
||||
<-h.done
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
func TestHandleCompletionIncludesBackendCleanup(t *testing.T) {
|
||||
store, err := process.NewArtifactStore(filepath.Join(t.TempDir(), "capture"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := process.StartHandle(context.Background(), store, t.TempDir(), "/bin/sh", "-c", "exit 0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
h := ownedHandle(raw, func() error { close(entered); <-release; return nil })
|
||||
<-entered
|
||||
if !h.Snapshot().Running {
|
||||
t.Fatal("terminal visible before cleanup")
|
||||
}
|
||||
close(release)
|
||||
if err = h.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.Snapshot().Running {
|
||||
t.Fatal("joined handle remains running")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ReadOnlyResource is an explicitly pinned file exposed under
|
||||
// /harness-resources/<Relative>. Only a verified private copy is mounted.
|
||||
type ReadOnlyResource struct {
|
||||
Path string
|
||||
Relative string
|
||||
SHA256 string
|
||||
Executable bool
|
||||
}
|
||||
|
||||
func snapshotResources(ctx context.Context, files []ReadOnlyResource, directory string) (string, error) {
|
||||
if len(files) == 0 || len(files) > 65 {
|
||||
return "", errors.New("resource bundle requires 1 to 65 files")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, f := range files {
|
||||
digest, err := hex.DecodeString(f.SHA256)
|
||||
if !filepath.IsAbs(f.Path) || !fs.ValidPath(f.Relative) || f.Relative == "." || strings.ContainsAny(f.Relative, "\\,:\r\n\x00") || err != nil || len(digest) != 32 || hex.EncodeToString(digest) != f.SHA256 {
|
||||
return "", errors.New("invalid pinned resource")
|
||||
}
|
||||
key := strings.ToLower(f.Relative)
|
||||
if seen[key] {
|
||||
return "", errors.New("duplicate resource path")
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
for key := range seen {
|
||||
for parent := filepath.ToSlash(filepath.Dir(key)); parent != "."; parent = filepath.ToSlash(filepath.Dir(parent)) {
|
||||
if seen[parent] {
|
||||
return "", errors.New("resource path overlaps a directory")
|
||||
}
|
||||
}
|
||||
}
|
||||
root, err := os.MkdirTemp(directory, "verified-resources-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
complete := false
|
||||
defer func() {
|
||||
if !complete {
|
||||
os.RemoveAll(root)
|
||||
}
|
||||
}()
|
||||
var total int64
|
||||
for _, f := range files {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
n, e := copyResource(ctx, f, filepath.Join(root, filepath.FromSlash(f.Relative)), 160<<20-total)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
total += n
|
||||
}
|
||||
// Files are immutable to the container UID and the entire bind mount is read-only.
|
||||
err = filepath.WalkDir(root, func(path string, d fs.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.IsDir() {
|
||||
return os.Chmod(path, 0755)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
complete = true
|
||||
return root, nil
|
||||
}
|
||||
func copyResource(ctx context.Context, f ReadOnlyResource, target string, remaining int64) (int64, error) {
|
||||
input, err := openWorkerSource(f.Path)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer input.Close()
|
||||
info, err := input.Stat()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > MaxWorkerBytes || info.Size() > remaining {
|
||||
return 0, errors.New("resource size or file type invalid")
|
||||
}
|
||||
if err = os.MkdirAll(filepath.Dir(target), 0700); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
output, err := os.OpenFile(target, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer output.Close()
|
||||
hash := sha256.New()
|
||||
buffer := make([]byte, 32<<10)
|
||||
reader := io.LimitReader(input, info.Size()+1)
|
||||
var total int64
|
||||
for {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
n, e := reader.Read(buffer)
|
||||
if n > 0 {
|
||||
total += int64(n)
|
||||
if total > info.Size() {
|
||||
return 0, errors.New("resource changed size")
|
||||
}
|
||||
if _, err = output.Write(buffer[:n]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
hash.Write(buffer[:n])
|
||||
}
|
||||
if e == io.EOF {
|
||||
break
|
||||
}
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
}
|
||||
if total != info.Size() || hex.EncodeToString(hash.Sum(nil)) != f.SHA256 {
|
||||
return 0, errors.New("resource digest mismatch")
|
||||
}
|
||||
mode := os.FileMode(0444)
|
||||
if f.Executable {
|
||||
mode = 0555
|
||||
}
|
||||
if err = output.Chmod(mode); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if err = output.Sync(); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return total, output.Close()
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPinnedResourceSnapshotIntegrity(t *testing.T) {
|
||||
source := filepath.Join(t.TempDir(), "asset")
|
||||
if err := os.WriteFile(source, []byte("reviewed"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pin := fmt.Sprintf("%x", sha256.Sum256([]byte("reviewed")))
|
||||
root := t.TempDir()
|
||||
files := []ReadOnlyResource{{Path: source, Relative: "package/asset.txt", SHA256: pin}}
|
||||
frozen, err := snapshotResources(context.Background(), files, root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(source, []byte("changed"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(frozen, "package/asset.txt"))
|
||||
if err != nil || string(b) != "reviewed" {
|
||||
t.Fatal(string(b), err)
|
||||
}
|
||||
if err = os.RemoveAll(frozen); err != nil {
|
||||
t.Fatal("snapshot not removable", err)
|
||||
}
|
||||
if _, err = snapshotResources(context.Background(), files, root); err == nil {
|
||||
t.Fatal("changed source accepted")
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("partial snapshot retained", entries, err)
|
||||
}
|
||||
for _, paths := range [][]string{{"../escape"}, {"a", "a/b"}, {"A", "a"}, {"bad,path"}} {
|
||||
var invalid []ReadOnlyResource
|
||||
for _, path := range paths {
|
||||
invalid = append(invalid, ReadOnlyResource{Path: source, Relative: path, SHA256: pin})
|
||||
}
|
||||
if _, err = snapshotResources(context.Background(), invalid, root); err == nil {
|
||||
t.Fatal("invalid layout accepted", paths)
|
||||
}
|
||||
}
|
||||
link := filepath.Join(t.TempDir(), "link")
|
||||
if err = os.Symlink(source, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files[0].Path = link
|
||||
if _, err = snapshotResources(context.Background(), files, root); err == nil {
|
||||
t.Fatal("symlink source accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/sausheong/harness/process"
|
||||
)
|
||||
|
||||
// StreamStarter opens a raw protocol stream inside the selected boundary.
|
||||
// Consumers must bound framing and drain both output streams. No capture or
|
||||
// implicit fallback is applied to protocol traffic.
|
||||
type StreamStarter interface {
|
||||
OpenStream(context.Context, Request) (*Stream, error)
|
||||
}
|
||||
|
||||
type Stream struct {
|
||||
Stdin io.WriteCloser
|
||||
Stdout io.ReadCloser
|
||||
Stderr io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
stop func()
|
||||
done chan struct{}
|
||||
err error
|
||||
closeOnce sync.Once
|
||||
}
|
||||
|
||||
// Wait joins the child and boundary cleanup. Readers remain usable until Close.
|
||||
func (s *Stream) Wait() error { <-s.done; return s.err }
|
||||
|
||||
// Close stops the child, joins boundary cleanup and releases all owned pipes.
|
||||
func (s *Stream) Close() error {
|
||||
s.closeOnce.Do(func() {
|
||||
s.cancel()
|
||||
s.stop()
|
||||
s.Stdin.Close()
|
||||
s.Wait()
|
||||
s.Stdout.Close()
|
||||
s.Stderr.Close()
|
||||
})
|
||||
return s.Wait()
|
||||
}
|
||||
|
||||
func validateStream(r Request) error {
|
||||
if err := validate(r); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(r.Stdin) != 0 || r.OutputStore != nil || r.CaptureLimit != 0 {
|
||||
return errors.New("protocol streams require pipe input and consumer-owned output bounds")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (h Host) OpenStream(ctx context.Context, r Request) (*Stream, error) {
|
||||
if err := validateStream(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return openStream(ctx, h.Workspace, environment(r.Env), r.Argv[0], r.Argv[1:], func() error { return nil })
|
||||
}
|
||||
func (c Container) OpenStream(ctx context.Context, r Request) (*Stream, error) {
|
||||
if err := validateStream(r); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan, err := c.prepare(ctx, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return openStream(ctx, "", environment(nil), plan.docker, plan.args, plan.cleanup)
|
||||
}
|
||||
func openStream(ctx context.Context, dir string, env []string, name string, args []string, cleanup func() error) (stream *Stream, err error) {
|
||||
owned, cancel := context.WithCancel(ctx)
|
||||
cmd := process.Command(owned, name, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
var pipes []*os.File
|
||||
retained := false
|
||||
defer func() {
|
||||
if !retained {
|
||||
cancel()
|
||||
for _, p := range pipes {
|
||||
p.Close()
|
||||
}
|
||||
err = errors.Join(err, cleanup())
|
||||
}
|
||||
}()
|
||||
input, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if !retained {
|
||||
input.Close()
|
||||
}
|
||||
}()
|
||||
output, outWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pipes = append(pipes, output, outWriter)
|
||||
diagnostic, errWriter, err := os.Pipe()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pipes = append(pipes, diagnostic, errWriter)
|
||||
cmd.Stdout = outWriter
|
||||
cmd.Stderr = errWriter
|
||||
if err = ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = cmd.Start(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outWriter.Close()
|
||||
errWriter.Close()
|
||||
s := &Stream{Stdin: input, Stdout: output, Stderr: diagnostic, cancel: cancel, stop: func() { process.KillGroup(cmd) }, done: make(chan struct{})}
|
||||
retained = true
|
||||
go func() {
|
||||
defer close(s.done)
|
||||
defer cancel()
|
||||
runErr := cmd.Wait()
|
||||
if owned.Err() != nil {
|
||||
runErr = nil
|
||||
}
|
||||
s.err = errors.Join(runErr, process.KillGroup(cmd), cleanup())
|
||||
}()
|
||||
return s, nil
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHostProtocolStreamRoundTrip(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
s, err := (Host{Workspace: t.TempDir()}).OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat; printf diagnostic >&2"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
errout := make(chan string, 1)
|
||||
go func() { b, _ := io.ReadAll(s.Stderr); errout <- string(b) }()
|
||||
if _, err = s.Stdin.Write([]byte("protocol\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Stdin.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := io.ReadAll(s.Stdout)
|
||||
if err != nil || string(b) != "protocol\n" {
|
||||
t.Fatal(string(b), err)
|
||||
}
|
||||
if err = s.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := <-errout; got != "diagnostic" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
func TestHostProtocolStreamCancellationAndValidation(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
s, err := (Host{Workspace: t.TempDir()}).OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "printf ready; sleep 20"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
b := make([]byte, 5)
|
||||
if _, err = io.ReadFull(s.Stdout, b); err != nil || string(b) != "ready" {
|
||||
t.Fatal(string(b), err)
|
||||
}
|
||||
start := time.Now()
|
||||
cancel()
|
||||
_ = s.Close()
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Fatal("stream cleanup exceeded deadline")
|
||||
}
|
||||
if _, err = (Host{}).OpenStream(context.Background(), Request{Argv: []string{"/bin/sh"}, Stdin: []byte("x")}); err == nil {
|
||||
t.Fatal("buffered input accepted")
|
||||
}
|
||||
_, err = (Container{}).OpenStream(context.Background(), Request{Argv: []string{"/bin/sh"}})
|
||||
if err == nil || !strings.Contains(err.Error(), "container requires") {
|
||||
t.Fatal("invalid container did not fail closed", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerProtocolStreamRoundTrip(t *testing.T) {
|
||||
image := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE")
|
||||
socket := os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native container fixture required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir()}
|
||||
s, err := c.OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat; printf isolated >&2"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
diagnostic := make(chan string, 1)
|
||||
go func() { b, _ := io.ReadAll(s.Stderr); diagnostic <- string(b) }()
|
||||
if _, err = s.Stdin.Write([]byte("container protocol\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Stdin.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, err := io.ReadAll(s.Stdout)
|
||||
if err != nil || string(b) != "container protocol\n" {
|
||||
t.Fatal(string(b), err)
|
||||
}
|
||||
if err = s.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := <-diagnostic; got != "isolated" {
|
||||
t.Fatal(got)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerProtocolPinnedResources(t *testing.T) {
|
||||
image, socket := os.Getenv("HARNESS_TEST_CONTAINER_IMAGE"), os.Getenv("HARNESS_TEST_CONTAINER_SOCKET")
|
||||
if image == "" || socket == "" {
|
||||
t.Skip("native container fixture required")
|
||||
}
|
||||
source := filepath.Join(t.TempDir(), "asset.txt")
|
||||
if err := os.WriteFile(source, []byte("pinned-content"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := Container{Docker: "/usr/local/bin/docker", Socket: socket, Image: image, Workspace: t.TempDir(), Resources: []ReadOnlyResource{{Path: source, Relative: "package/asset.txt", SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("pinned-content")))}}}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 40*time.Second)
|
||||
defer cancel()
|
||||
s, err := c.OpenStream(ctx, Request{Argv: []string{"/bin/sh", "-c", "cat /harness-resources/package/asset.txt; if printf changed > /harness-resources/package/asset.txt 2>/dev/null; then exit 7; fi"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
go io.Copy(io.Discard, s.Stderr)
|
||||
b, err := io.ReadAll(s.Stdout)
|
||||
if err != nil || string(b) != "pinned-content" {
|
||||
t.Fatal(string(b), err)
|
||||
}
|
||||
if err = s.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original, err := os.ReadFile(source)
|
||||
if err != nil || string(original) != "pinned-content" {
|
||||
t.Fatal(string(original), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const MaxWorkerBytes int64 = 128 << 20
|
||||
|
||||
// snapshotWorker freezes verified bytes in a private directory outside the
|
||||
// workspace. The daemon mounts this copy, never the mutable configured path.
|
||||
func snapshotWorker(ctx context.Context, source, expected, directory string) (string, error) {
|
||||
digest, err := hex.DecodeString(expected)
|
||||
if err != nil || len(digest) != sha256.Size {
|
||||
return "", errors.New("worker requires a SHA-256 digest")
|
||||
}
|
||||
canonical, err := filepath.EvalSymlinks(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
input, err := openWorkerSource(canonical)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer input.Close()
|
||||
info, err := input.Stat()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 || info.Size() > MaxWorkerBytes {
|
||||
return "", errors.New("worker must be a regular executable within 128 MiB")
|
||||
}
|
||||
destination := filepath.Join(directory, "verified-worker")
|
||||
output, err := os.OpenFile(destination, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0500)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
complete := false
|
||||
defer func() {
|
||||
output.Close()
|
||||
if !complete {
|
||||
os.Remove(destination)
|
||||
}
|
||||
}()
|
||||
hash := sha256.New()
|
||||
reader := io.LimitReader(input, MaxWorkerBytes+1)
|
||||
buffer := make([]byte, 32<<10)
|
||||
var total int64
|
||||
for {
|
||||
if err = ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
n, readErr := reader.Read(buffer)
|
||||
if n > 0 {
|
||||
total += int64(n)
|
||||
if total > MaxWorkerBytes {
|
||||
return "", errors.New("worker exceeds 128 MiB")
|
||||
}
|
||||
if _, err = output.Write(buffer[:n]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash.Write(buffer[:n])
|
||||
}
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
if readErr != nil {
|
||||
return "", readErr
|
||||
}
|
||||
}
|
||||
if hex.EncodeToString(hash.Sum(nil)) != expected {
|
||||
return "", errors.New("worker SHA-256 mismatch; refusing execution")
|
||||
}
|
||||
if err = output.Chmod(0555); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = output.Sync(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = output.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
complete = true
|
||||
return destination, nil
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package execution
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWorkerSnapshotPinsBytesAcrossSourceReplacement(t *testing.T) {
|
||||
source := filepath.Join(t.TempDir(), "worker")
|
||||
original := []byte("#!/bin/sh\nprintf original\n")
|
||||
if err := os.WriteFile(source, original, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash := sha256.Sum256(original)
|
||||
digest := hex.EncodeToString(hash[:])
|
||||
frozen, err := snapshotWorker(context.Background(), source, digest, t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = os.WriteFile(source, []byte("#!/bin/sh\nprintf replaced\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := os.ReadFile(frozen)
|
||||
if err != nil || string(raw) != string(original) {
|
||||
t.Fatal("snapshot changed with source")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
if _, err = snapshotWorker(context.Background(), source, digest, dir); err == nil {
|
||||
t.Fatal("changed worker accepted")
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("failed snapshot retained")
|
||||
}
|
||||
}
|
||||
func TestWorkerSnapshotRejectsCancellationAndInvalidDigest(t *testing.T) {
|
||||
source := filepath.Join(t.TempDir(), "worker")
|
||||
if err := os.WriteFile(source, []byte("worker"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := snapshotWorker(context.Background(), source, "invalid", t.TempDir()); err == nil {
|
||||
t.Fatal("invalid digest accepted")
|
||||
}
|
||||
hash := sha256.Sum256([]byte("worker"))
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := snapshotWorker(ctx, source, hex.EncodeToString(hash[:]), t.TempDir()); err != context.Canceled {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !unix
|
||||
|
||||
package execution
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func openWorkerSource(string) (*os.File, error) {
|
||||
return nil, errors.New("worker snapshot source validation is unavailable on this platform")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//go:build unix
|
||||
|
||||
package execution
|
||||
|
||||
import (
|
||||
"golang.org/x/sys/unix"
|
||||
"os"
|
||||
)
|
||||
|
||||
func openWorkerSource(path string) (*os.File, error) {
|
||||
fd, err := unix.Open(path, unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return os.NewFile(uintptr(fd), path), nil
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Read verifies a completed artifact within this store. It never follows paths
|
||||
// supplied by output prose. Missing/expired, active, corrupt or legacy unverified
|
||||
// artifacts fail explicitly. Truncated describes capture completeness separately
|
||||
// from integrity: the verified captured prefix may still be read.
|
||||
func (s *ArtifactStore) Read(ctx context.Context, info ArtifactInfo) ([]byte, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
digest, err := hex.DecodeString(info.SHA256)
|
||||
if err != nil || len(digest) != sha256.Size || info.Bytes < 0 || info.Bytes > ArtifactFileLimit || info.Error != "" {
|
||||
return nil, errors.New("artifact has no valid completed integrity record")
|
||||
}
|
||||
rel, err := filepath.Rel(s.dir, info.Path)
|
||||
if err != nil || filepath.Base(rel) != rel || !strings.HasPrefix(rel, "output-") || !strings.HasSuffix(rel, ".log") {
|
||||
return nil, errors.New("artifact is outside this store")
|
||||
}
|
||||
root, err := os.OpenRoot(s.dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer root.Close()
|
||||
before, err := root.Lstat(rel)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !before.Mode().IsRegular() {
|
||||
return nil, errors.New("artifact is not a regular file")
|
||||
}
|
||||
f, err := root.OpenFile(rel, artifactReadFlags(), 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
if err := lockArtifact(f, true); err != nil {
|
||||
return nil, fmt.Errorf("artifact is active or unavailable: %w", err)
|
||||
}
|
||||
stat, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !stat.Mode().IsRegular() || stat.Mode().Perm()&0077 != 0 || stat.Size() != info.Bytes {
|
||||
return nil, errors.New("artifact size or permissions changed")
|
||||
}
|
||||
data := make([]byte, 0, int(info.Bytes))
|
||||
buf := make([]byte, 32<<10)
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, readErr := f.Read(buf)
|
||||
if int64(len(data)+n) > info.Bytes {
|
||||
return nil, errors.New("artifact grew during read")
|
||||
}
|
||||
data = append(data, buf[:n]...)
|
||||
if readErr == io.EOF {
|
||||
break
|
||||
}
|
||||
if readErr != nil {
|
||||
return nil, readErr
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
actual := sha256.Sum256(data)
|
||||
if int64(len(data)) != info.Bytes || hex.EncodeToString(actual[:]) != strings.ToLower(info.SHA256) {
|
||||
return nil, errors.New("artifact integrity mismatch")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//go:build unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestArtifactReadVerifiedAndTampered(t *testing.T) {
|
||||
store := testStore(t)
|
||||
capture := store.Capture(4)
|
||||
data := bytes.Repeat([]byte("captured output\n"), 100)
|
||||
capture.Write(data)
|
||||
if _, err := store.Read(context.Background(), capture.Info()); err == nil {
|
||||
t.Fatal("active unfinalised capture accepted")
|
||||
}
|
||||
if err := capture.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
info := capture.Info()
|
||||
got, err := store.Read(context.Background(), info)
|
||||
if err != nil || !bytes.Equal(got, data) || len(info.SHA256) != 64 {
|
||||
t.Fatal("verified artifact unavailable", err)
|
||||
}
|
||||
tampered := bytes.Repeat([]byte("x"), len(data))
|
||||
if err := os.WriteFile(info.Path, tampered, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Read(context.Background(), info); err == nil {
|
||||
t.Fatal("same-size tampering accepted")
|
||||
}
|
||||
if err := os.Remove(info.Path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Read(context.Background(), info); !os.IsNotExist(err) {
|
||||
t.Fatal("missing artifact not reported", err)
|
||||
}
|
||||
}
|
||||
func TestArtifactReadScopeLockAndCancellation(t *testing.T) {
|
||||
store := testStore(t)
|
||||
capture := store.Capture(1)
|
||||
capture.Write([]byte("complete output"))
|
||||
capture.Close()
|
||||
info := capture.Info()
|
||||
outside := info
|
||||
outside.Path = filepath.Join(t.TempDir(), filepath.Base(info.Path))
|
||||
if _, err := store.Read(context.Background(), outside); err == nil {
|
||||
t.Fatal("outside path accepted")
|
||||
}
|
||||
link := filepath.Join(store.dir, "output-link.log")
|
||||
if err := os.Symlink(info.Path, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
alias := info
|
||||
alias.Path = link
|
||||
if _, err := store.Read(context.Background(), alias); err == nil {
|
||||
t.Fatal("symlink accepted")
|
||||
}
|
||||
file, err := os.OpenFile(info.Path, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lockArtifact(file, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Read(context.Background(), info); err == nil {
|
||||
t.Fatal("locked artifact accepted")
|
||||
}
|
||||
file.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err := store.Read(ctx, info); err != context.Canceled {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacy := info
|
||||
legacy.SHA256 = ""
|
||||
if _, err := store.Read(context.Background(), legacy); err == nil {
|
||||
t.Fatal("unverified legacy record accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const ArtifactFileLimit int64 = 8 << 20
|
||||
const ArtifactStoreLimit int64 = 64 << 20
|
||||
const ArtifactRetention = 24 * time.Hour
|
||||
|
||||
// ArtifactStore owns a private directory used only for command output. Each
|
||||
// active capture reserves one full file allowance. Advisory file locks protect
|
||||
// active files across cooperating processes; old completed files are evicted
|
||||
// oldest first. Retention is enforced when a new artifact is allocated.
|
||||
type ArtifactStore struct{ dir string }
|
||||
|
||||
func NewArtifactStore(dir string) (*ArtifactStore, error) {
|
||||
abs, err := filepath.Abs(dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.MkdirAll(abs, 0700); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info, err := os.Lstat(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.IsDir() || info.Mode().Perm()&0077 != 0 {
|
||||
return nil, errors.New("artifact directory must be a private directory (0700)")
|
||||
}
|
||||
return &ArtifactStore{dir: abs}, nil
|
||||
}
|
||||
|
||||
func (s *ArtifactStore) allocate() (*os.File, string, error) {
|
||||
root, err := os.OpenRoot(s.dir)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer root.Close()
|
||||
guard, err := root.OpenFile(".lock", os.O_CREATE|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
defer guard.Close()
|
||||
if err = lockArtifact(guard, false); err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
names, err := fs.ReadDir(root.FS(), ".")
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
type candidate struct {
|
||||
name string
|
||||
modified time.Time
|
||||
}
|
||||
var files []candidate
|
||||
for _, e := range names {
|
||||
if !strings.HasPrefix(e.Name(), "output-") {
|
||||
continue
|
||||
}
|
||||
info, err := e.Info()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > ArtifactFileLimit {
|
||||
return nil, "", errors.New("invalid output artifact in store")
|
||||
}
|
||||
files = append(files, candidate{e.Name(), info.ModTime()})
|
||||
}
|
||||
sort.Slice(files, func(i, j int) bool { return files[i].modified.Before(files[j].modified) })
|
||||
count := len(files)
|
||||
for _, f := range files {
|
||||
expired := time.Since(f.modified) > ArtifactRetention
|
||||
if !expired && int64(count+1)*ArtifactFileLimit <= ArtifactStoreLimit {
|
||||
continue
|
||||
}
|
||||
file, err := root.OpenFile(f.name, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
err = lockArtifact(file, true)
|
||||
if artifactBusy(err) {
|
||||
file.Close()
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, "", err
|
||||
}
|
||||
err = root.Remove(f.name)
|
||||
file.Close()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
count--
|
||||
}
|
||||
if int64(count+1)*ArtifactFileLimit > ArtifactStoreLimit {
|
||||
return nil, "", errors.New("output artifact quota occupied by active captures")
|
||||
}
|
||||
name := "output-" + rand.Text() + ".log"
|
||||
file, err := root.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if err = lockArtifact(file, false); err != nil {
|
||||
file.Close()
|
||||
root.Remove(name)
|
||||
return nil, "", err
|
||||
}
|
||||
return file, filepath.Join(s.dir, name), nil
|
||||
}
|
||||
|
||||
// OutputCapture drains every byte, retains a bounded memory prefix, and spills
|
||||
// output exceeding that prefix into an artifact with an independent disk cap.
|
||||
// Call Close after the subprocess joins, before consuming Info. Write errors
|
||||
// are recorded instead of stopping the drain and changing subprocess behaviour.
|
||||
type OutputCapture struct {
|
||||
mu sync.Mutex
|
||||
prefix *Capture
|
||||
store *ArtifactStore
|
||||
file *os.File
|
||||
info ArtifactInfo
|
||||
closed bool
|
||||
digest hash.Hash
|
||||
}
|
||||
|
||||
type ArtifactInfo struct {
|
||||
SHA256 string `json:"sha256,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (s *ArtifactStore) Capture(memoryLimit int) *OutputCapture {
|
||||
return &OutputCapture{store: s, prefix: NewCapture(memoryLimit), digest: sha256.New()}
|
||||
}
|
||||
|
||||
func (c *OutputCapture) Write(p []byte) (int, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.closed {
|
||||
return 0, os.ErrClosed
|
||||
}
|
||||
var before string
|
||||
if c.file == nil && c.info.Error == "" {
|
||||
_, retained, limit := c.prefix.stats()
|
||||
if len(p) > limit-retained {
|
||||
before, _, _ = c.prefix.Snapshot()
|
||||
}
|
||||
}
|
||||
c.prefix.Write(p)
|
||||
total, retained, _ := c.prefix.stats()
|
||||
truncated := total > int64(retained)
|
||||
if truncated && c.file == nil && c.info.Error == "" {
|
||||
f, path, err := c.store.allocate()
|
||||
if err != nil {
|
||||
c.info.Error = err.Error()
|
||||
} else {
|
||||
c.file = f
|
||||
c.info.Path = path
|
||||
c.writeDisk([]byte(before))
|
||||
}
|
||||
}
|
||||
if c.file != nil {
|
||||
c.writeDisk(p)
|
||||
}
|
||||
c.info.Truncated = truncated && (c.info.Bytes < total)
|
||||
return len(p), nil
|
||||
}
|
||||
func (c *OutputCapture) writeDisk(p []byte) {
|
||||
if c.info.Error != "" {
|
||||
return
|
||||
}
|
||||
keep := min(int64(len(p)), ArtifactFileLimit-c.info.Bytes)
|
||||
n, err := c.file.Write(p[:int(keep)])
|
||||
c.info.Bytes += int64(n)
|
||||
c.digest.Write(p[:n])
|
||||
if err == nil && int64(n) != keep {
|
||||
err = errors.New("short artifact write")
|
||||
}
|
||||
if err != nil {
|
||||
c.info.Error = fmt.Sprintf("capture output: %v", err)
|
||||
}
|
||||
}
|
||||
func (c *OutputCapture) Snapshot() (string, int64, bool) { return c.prefix.Snapshot() }
|
||||
func (c *OutputCapture) Info() ArtifactInfo { c.mu.Lock(); defer c.mu.Unlock(); return c.info }
|
||||
func (c *OutputCapture) Close() error {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.closed {
|
||||
return nil
|
||||
}
|
||||
c.closed = true
|
||||
if c.file == nil {
|
||||
return nil
|
||||
}
|
||||
err := errors.Join(c.file.Sync(), c.file.Close())
|
||||
c.info.SHA256 = fmt.Sprintf("%x", c.digest.Sum(nil))
|
||||
if err != nil {
|
||||
c.info.Error = err.Error()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//go:build !unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
func lockArtifact(_ *os.File, _ bool) error {
|
||||
return errors.New("output artifact locking is unsupported on this platform")
|
||||
}
|
||||
func artifactBusy(_ error) bool { return false }
|
||||
|
||||
func artifactReadFlags() int { return os.O_RDONLY }
|
||||
@@ -0,0 +1,182 @@
|
||||
//go:build unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testStore(t *testing.T) *ArtifactStore {
|
||||
t.Helper()
|
||||
dir := filepath.Join(t.TempDir(), "output")
|
||||
s, err := NewArtifactStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s
|
||||
}
|
||||
func TestArtifactSpillExactAndCap(t *testing.T) {
|
||||
s := testStore(t)
|
||||
c := s.Capture(7)
|
||||
for _, p := range []string{"abc", "def", "ghij", "klmnop"} {
|
||||
c.Write([]byte(p))
|
||||
}
|
||||
c.Close()
|
||||
info := c.Info()
|
||||
raw, err := os.ReadFile(info.Path)
|
||||
if err != nil || string(raw) != "abcdefghijklmnop" || info.Bytes != 16 || info.Truncated || info.Error != "" {
|
||||
t.Fatalf("%q %+v %v", raw, info, err)
|
||||
}
|
||||
stat, _ := os.Stat(info.Path)
|
||||
if stat.Mode().Perm() != 0600 {
|
||||
t.Fatal(stat.Mode())
|
||||
}
|
||||
capped := s.Capture(4)
|
||||
block := bytes.Repeat([]byte("z"), 1<<20)
|
||||
for range 10 {
|
||||
capped.Write(block)
|
||||
}
|
||||
capped.Close()
|
||||
info = capped.Info()
|
||||
stat, err = os.Stat(info.Path)
|
||||
if err != nil || stat.Size() != ArtifactFileLimit || info.Bytes != ArtifactFileLimit || !info.Truncated {
|
||||
t.Fatalf("%+v %v", info, err)
|
||||
}
|
||||
prefix, total, truncated := capped.Snapshot()
|
||||
if prefix != "zzzz" || total != 10<<20 || !truncated {
|
||||
t.Fatalf("%q %d %v", prefix, total, truncated)
|
||||
}
|
||||
}
|
||||
func TestArtifactQuotaProtectsActiveAndEvictsCompleted(t *testing.T) {
|
||||
s := testStore(t)
|
||||
var active []*OutputCapture
|
||||
for range 8 {
|
||||
c := s.Capture(1)
|
||||
c.Write([]byte("abc"))
|
||||
if c.Info().Error != "" {
|
||||
t.Fatal(c.Info())
|
||||
}
|
||||
active = append(active, c)
|
||||
defer c.Close()
|
||||
}
|
||||
// A separate store instance must obey the same active-file reservations.
|
||||
other, err := NewArtifactStore(s.dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
full := other.Capture(1)
|
||||
full.Write([]byte("abc"))
|
||||
full.Close()
|
||||
if full.Info().Error == "" || !full.Info().Truncated || full.Info().Path != "" {
|
||||
t.Fatal(full.Info())
|
||||
}
|
||||
old := active[0].Info().Path
|
||||
active[0].Close()
|
||||
next := other.Capture(1)
|
||||
next.Write([]byte("abc"))
|
||||
defer next.Close()
|
||||
if next.Info().Error != "" {
|
||||
t.Fatal(next.Info())
|
||||
}
|
||||
if _, err := os.Stat(old); !os.IsNotExist(err) {
|
||||
t.Fatalf("completed artifact not evicted: %v", err)
|
||||
}
|
||||
for _, c := range active[1:] {
|
||||
if _, err := os.Stat(c.Info().Path); err != nil {
|
||||
t.Fatal("active artifact evicted", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestArtifactRetentionAndPrivateDirectory(t *testing.T) {
|
||||
s := testStore(t)
|
||||
c := s.Capture(1)
|
||||
c.Write([]byte("abc"))
|
||||
c.Close()
|
||||
old := c.Info().Path
|
||||
expired := time.Now().Add(-ArtifactRetention - time.Hour)
|
||||
if err := os.Chtimes(old, expired, expired); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next := s.Capture(1)
|
||||
next.Write([]byte("abc"))
|
||||
next.Close()
|
||||
if _, err := os.Stat(old); !os.IsNotExist(err) {
|
||||
t.Fatalf("expired artifact remains: %v", err)
|
||||
}
|
||||
small := s.Capture(10)
|
||||
small.Write([]byte("abc"))
|
||||
small.Close()
|
||||
if small.Info().Path != "" || small.Info().Truncated {
|
||||
t.Fatal(small.Info())
|
||||
}
|
||||
if _, err := small.Write([]byte("x")); err == nil {
|
||||
t.Fatal("write after close succeeded")
|
||||
}
|
||||
if err := os.Chmod(s.dir, 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := NewArtifactStore(s.dir); err == nil {
|
||||
t.Fatal("public directory accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactCrossProcessReservation(t *testing.T) {
|
||||
if dir := os.Getenv("HARNESS_ARTIFACT_QUOTA_FIXTURE"); dir != "" {
|
||||
s, err := NewArtifactStore(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := s.Capture(1)
|
||||
c.Write([]byte("abc"))
|
||||
c.Close()
|
||||
if c.Info().Error == "" || c.Info().Path != "" {
|
||||
t.Fatal("child bypassed active reservations", c.Info())
|
||||
}
|
||||
return
|
||||
}
|
||||
s := testStore(t)
|
||||
for range 8 {
|
||||
c := s.Capture(1)
|
||||
c.Write([]byte("abc"))
|
||||
defer c.Close()
|
||||
if c.Info().Error != "" {
|
||||
t.Fatal(c.Info())
|
||||
}
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
cmd := Command(ctx, exe, "-test.run=^TestArtifactCrossProcessReservation$")
|
||||
cmd.Env = append(os.Environ(), "HARNESS_ARTIFACT_QUOTA_FIXTURE="+s.dir, "GORACE=atexit_sleep_ms=0")
|
||||
var output bytes.Buffer
|
||||
cmd.Stdout = &output
|
||||
cmd.Stderr = &output
|
||||
if err := Run(cmd); err != nil {
|
||||
t.Fatalf("child quota check: %v %s", err, output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactAllocationFailureStillDrains(t *testing.T) {
|
||||
s := testStore(t)
|
||||
if err := os.Mkdir(filepath.Join(s.dir, ".lock"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := s.Capture(2)
|
||||
n, err := c.Write([]byte("abcdef"))
|
||||
c.Close()
|
||||
if n != 6 || err != nil {
|
||||
t.Fatalf("drain: %d %v", n, err)
|
||||
}
|
||||
prefix, total, truncated := c.Snapshot()
|
||||
if prefix != "ab" || total != 6 || !truncated || c.Info().Error == "" || !c.Info().Truncated {
|
||||
t.Fatalf("%q %d %v %+v", prefix, total, truncated, c.Info())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
//go:build unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func lockArtifact(f *os.File, nonblocking bool) error {
|
||||
flags := syscall.LOCK_EX
|
||||
if nonblocking {
|
||||
flags |= syscall.LOCK_NB
|
||||
}
|
||||
return syscall.Flock(int(f.Fd()), flags)
|
||||
}
|
||||
func artifactBusy(err error) bool { return errors.Is(err, syscall.EWOULDBLOCK) }
|
||||
|
||||
func artifactReadFlags() int { return os.O_RDONLY | syscall.O_NONBLOCK | syscall.O_NOFOLLOW }
|
||||
@@ -0,0 +1,44 @@
|
||||
package process
|
||||
|
||||
import "sync"
|
||||
|
||||
// Capture retains a bounded prefix while draining all writes. It deliberately
|
||||
// does not embed a buffer: io.Copy must not bypass Write through ReaderFrom.
|
||||
// The zero value drains without retaining bytes.
|
||||
type Capture struct {
|
||||
mu sync.Mutex
|
||||
limit int
|
||||
data []byte
|
||||
total int64
|
||||
}
|
||||
|
||||
func NewCapture(limit int) *Capture {
|
||||
if limit < 0 {
|
||||
limit = 0
|
||||
}
|
||||
return &Capture{limit: limit}
|
||||
}
|
||||
|
||||
func (c *Capture) Write(p []byte) (int, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
n := len(p)
|
||||
c.total += int64(n)
|
||||
keep := min(n, c.limit-len(c.data))
|
||||
c.data = append(c.data, p[:keep]...)
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Snapshot returns an independent prefix, observed byte count and truncation.
|
||||
func (c *Capture) Snapshot() (string, int64, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return string(c.data), c.total, c.total > int64(len(c.data))
|
||||
}
|
||||
|
||||
// stats inspects accounting without allocating a copy of the retained bytes.
|
||||
func (c *Capture) stats() (total int64, retained, limit int) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.total, len(c.data), c.limit
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOutputCaptureFloodAllocationsPlateau(t *testing.T) {
|
||||
store, err := NewArtifactStore(filepath.Join(t.TempDir(), "output"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
capture := store.Capture(64 << 10)
|
||||
defer capture.Close()
|
||||
block := bytes.Repeat([]byte("x"), 32<<10)
|
||||
for i := 0; i < 300; i++ {
|
||||
if _, err = capture.Write(block); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if info := capture.Info(); info.Bytes != ArtifactFileLimit || !info.Truncated {
|
||||
t.Fatalf("disk not saturated: %+v", info)
|
||||
}
|
||||
allocations := testing.AllocsPerRun(100, func() {
|
||||
if _, err := capture.Write(block); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
})
|
||||
if allocations != 0 {
|
||||
t.Fatalf("saturated capture allocates per write: %f", allocations)
|
||||
}
|
||||
prefix, total, truncated := capture.Snapshot()
|
||||
if len(prefix) != 64<<10 || total <= 300*int64(len(block)) || !truncated {
|
||||
t.Fatal("capture accounting changed")
|
||||
}
|
||||
t.Logf("saturated_write_allocations=%f retained_prefix_bytes=%d backing_capacity_bytes=%d", allocations, len(prefix), cap(capture.prefix.data))
|
||||
if cap(capture.prefix.data) > 2*(64<<10)+8192 {
|
||||
t.Fatal("capture backing storage exceeded allowance")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCaptureCopyBound(t *testing.T) {
|
||||
c := NewCapture(17)
|
||||
n, err := io.Copy(c, strings.NewReader(strings.Repeat("x", 1<<20)))
|
||||
prefix, total, truncated := c.Snapshot()
|
||||
if err != nil || n != 1<<20 || total != n || prefix != strings.Repeat("x", 17) || !truncated {
|
||||
t.Fatalf("copy=%d err=%v prefix=%q total=%d truncated=%v", n, err, prefix, total, truncated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureConcurrentAndEmpty(t *testing.T) {
|
||||
var c Capture
|
||||
var wg sync.WaitGroup
|
||||
for range 10 {
|
||||
wg.Go(func() {
|
||||
for range 100 {
|
||||
_, _ = c.Write([]byte("abc"))
|
||||
c.Snapshot()
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
prefix, total, truncated := c.Snapshot()
|
||||
if prefix != "" || total != 3000 || !truncated {
|
||||
t.Fatalf("%q %d %v", prefix, total, truncated)
|
||||
}
|
||||
empty := NewCapture(10)
|
||||
_, total, truncated = empty.Snapshot()
|
||||
if total != 0 || truncated {
|
||||
t.Fatal("empty capture marked truncated")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Package process owns bounded subprocess shutdown. On Unix each command has
|
||||
// its own process group. This is lifecycle management, not a security sandbox.
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Command creates a command whose cancellation kills its owned process group.
|
||||
// Run joins it and removes descendants left after normal exit. Callers using
|
||||
// Start/Wait directly must call KillGroup when their protocol closes.
|
||||
func Command(ctx context.Context, name string, args ...string) *exec.Cmd {
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
configureGroup(cmd)
|
||||
cmd.Cancel = func() error { return KillGroup(cmd) }
|
||||
cmd.WaitDelay = 250 * time.Millisecond
|
||||
return cmd
|
||||
}
|
||||
func Run(cmd *exec.Cmd) error {
|
||||
err := cmd.Run()
|
||||
cleanupErr := KillGroup(cmd)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return cleanupErr
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build !unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
func configureGroup(cmd *exec.Cmd) {}
|
||||
|
||||
// Other platforms stop the direct child only. Process-tree guarantees apply
|
||||
// to the advertised Linux/macOS backends; isolation is a separate capability.
|
||||
func KillGroup(cmd *exec.Cmd) error {
|
||||
if cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
err := cmd.Process.Kill()
|
||||
if errors.Is(err, os.ErrProcessDone) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
//go:build unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
func configureGroup(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} }
|
||||
|
||||
// KillGroup only signals the group explicitly created for this command.
|
||||
func KillGroup(cmd *exec.Cmd) error {
|
||||
if cmd.Process == nil {
|
||||
return nil
|
||||
}
|
||||
var err error
|
||||
if cmd.SysProcAttr != nil && cmd.SysProcAttr.Setpgid {
|
||||
err = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
} else {
|
||||
err = cmd.Process.Kill()
|
||||
}
|
||||
if errors.Is(err, syscall.ESRCH) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"io"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
const HandleInputLimit = 64 << 10
|
||||
|
||||
type inputWrite struct {
|
||||
data []byte
|
||||
done chan error
|
||||
}
|
||||
|
||||
// Handle owns one deliberately asynchronous process group. It does not survive
|
||||
// its owner context or application shutdown; callers must Close or Wait.
|
||||
type Handle struct {
|
||||
ID string
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
command *exec.Cmd
|
||||
stdin io.WriteCloser
|
||||
stdout, stderr *OutputCapture
|
||||
input chan inputWrite
|
||||
inputDone, done chan struct{}
|
||||
err error
|
||||
}
|
||||
type HandleSnapshot struct {
|
||||
ID string
|
||||
Running bool
|
||||
ExitCode int
|
||||
Error string
|
||||
Stdout, Stderr string
|
||||
StdoutBytes, StderrBytes int64
|
||||
StdoutTruncated, StderrTruncated bool
|
||||
StdoutArtifact, StderrArtifact ArtifactInfo
|
||||
}
|
||||
|
||||
func StartHandle(parent context.Context, store *ArtifactStore, dir, name string, args ...string) (*Handle, error) {
|
||||
return startHandle(parent, store, nil, dir, name, args...)
|
||||
}
|
||||
|
||||
// StartHandleWithEnv uses only the supplied environment, without ambient inheritance.
|
||||
func StartHandleWithEnv(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
|
||||
return startHandle(parent, store, append([]string{}, env...), dir, name, args...)
|
||||
}
|
||||
func startHandle(parent context.Context, store *ArtifactStore, env []string, dir, name string, args ...string) (*Handle, error) {
|
||||
if store == nil {
|
||||
return nil, errors.New("background process requires an output store")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
cmd := Command(ctx, name, args...)
|
||||
cmd.Dir = dir
|
||||
cmd.Env = env
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
h := &Handle{ID: rand.Text(), ctx: ctx, cancel: cancel, command: cmd, stdin: stdin, stdout: store.Capture(64 << 10), stderr: store.Capture(64 << 10), input: make(chan inputWrite, 1), inputDone: make(chan struct{}), done: make(chan struct{})}
|
||||
cmd.Stdout = h.stdout
|
||||
cmd.Stderr = h.stderr
|
||||
if err := cmd.Start(); err != nil {
|
||||
cancel()
|
||||
stdin.Close()
|
||||
h.stdout.Close()
|
||||
h.stderr.Close()
|
||||
return nil, err
|
||||
}
|
||||
go h.writeInput()
|
||||
go func() {
|
||||
defer close(h.done)
|
||||
waitErr := cmd.Wait()
|
||||
cleanupErr := KillGroup(cmd)
|
||||
cancel()
|
||||
stdin.Close()
|
||||
<-h.inputDone
|
||||
h.err = errors.Join(waitErr, cleanupErr, h.stdout.Close(), h.stderr.Close())
|
||||
}()
|
||||
return h, nil
|
||||
}
|
||||
func (h *Handle) writeInput() {
|
||||
defer close(h.inputDone)
|
||||
for {
|
||||
select {
|
||||
case <-h.ctx.Done():
|
||||
return
|
||||
case request := <-h.input:
|
||||
if err := h.ctx.Err(); err != nil {
|
||||
request.done <- err
|
||||
continue
|
||||
}
|
||||
n, err := h.stdin.Write(request.data)
|
||||
if err == nil && n != len(request.data) {
|
||||
err = io.ErrShortWrite
|
||||
}
|
||||
request.done <- err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Send waits for a bounded input write. If its context is cancelled after
|
||||
// admission, the owned process is cancelled because a partial write cannot be
|
||||
// withdrawn safely. Successful return means the pipe accepted all bytes.
|
||||
func (h *Handle) Send(ctx context.Context, data []byte) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(data) > HandleInputLimit {
|
||||
return errors.New("process input exceeds 64 KiB")
|
||||
}
|
||||
request := inputWrite{data: append([]byte(nil), data...), done: make(chan error, 1)}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-h.done:
|
||||
return errors.New("process already stopped")
|
||||
case <-h.ctx.Done():
|
||||
return h.ctx.Err()
|
||||
case h.input <- request:
|
||||
}
|
||||
select {
|
||||
case err := <-request.done:
|
||||
return err
|
||||
case <-h.done:
|
||||
select {
|
||||
case err := <-request.done:
|
||||
return err
|
||||
default:
|
||||
return errors.New("process stopped before input delivery completed")
|
||||
}
|
||||
case <-ctx.Done():
|
||||
h.cancel()
|
||||
<-h.done
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
func (h *Handle) Cancel() { h.cancel() }
|
||||
func (h *Handle) Wait() error { <-h.done; return h.err }
|
||||
func (h *Handle) Close() error { h.cancel(); return h.Wait() }
|
||||
func (h *Handle) Snapshot() HandleSnapshot {
|
||||
s := HandleSnapshot{ID: h.ID, Running: true, ExitCode: -1}
|
||||
select {
|
||||
case <-h.done:
|
||||
s.Running = false
|
||||
if h.command.ProcessState != nil {
|
||||
s.ExitCode = h.command.ProcessState.ExitCode()
|
||||
}
|
||||
if h.err != nil {
|
||||
s.Error = h.err.Error()
|
||||
}
|
||||
default:
|
||||
}
|
||||
s.Stdout, s.StdoutBytes, s.StdoutTruncated = h.stdout.Snapshot()
|
||||
s.Stderr, s.StderrBytes, s.StderrTruncated = h.stderr.Snapshot()
|
||||
s.StdoutArtifact, s.StderrArtifact = h.stdout.Info(), h.stderr.Info()
|
||||
return s
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//go:build unix
|
||||
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestHandleSendReadWait(t *testing.T) {
|
||||
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "read line; printf 'received:%s' \"$line\"")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := h.Send(ctx, []byte("hello\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := h.Snapshot()
|
||||
if result.Running || result.ExitCode != 0 || result.Stdout != "received:hello" {
|
||||
t.Fatal(result)
|
||||
}
|
||||
if err := h.Send(ctx, []byte("late")); err == nil {
|
||||
t.Fatal("input accepted after exit")
|
||||
}
|
||||
}
|
||||
func TestHandleBoundedCaptureAndOwnerCancellation(t *testing.T) {
|
||||
store := testStore(t)
|
||||
h, err := StartHandle(context.Background(), store, t.TempDir(), "sh", "-c", "head -c 70000 /dev/zero")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Close()
|
||||
if err := h.Wait(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result := h.Snapshot()
|
||||
if len(result.Stdout) != 64<<10 || result.StdoutBytes != 70000 || !result.StdoutTruncated {
|
||||
t.Fatal("capture bound failed")
|
||||
}
|
||||
data, err := store.Read(context.Background(), result.StdoutArtifact)
|
||||
if err != nil || len(data) != 70000 {
|
||||
t.Fatal("full capture unavailable", err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
server, err := StartHandle(ctx, store, t.TempDir(), "sh", "-c", "sleep 30 & wait")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer server.Close()
|
||||
cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- server.Wait() }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("owned process did not stop")
|
||||
}
|
||||
if server.Snapshot().Running {
|
||||
t.Fatal("cancelled process still running")
|
||||
}
|
||||
}
|
||||
func TestHandleRejectsOversizedInput(t *testing.T) {
|
||||
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Close()
|
||||
if err := h.Send(context.Background(), []byte(strings.Repeat("x", HandleInputLimit+1))); err == nil {
|
||||
t.Fatal("oversized input accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleCancelledInputStopsAndJoinsProcess(t *testing.T) {
|
||||
h, err := StartHandle(context.Background(), testStore(t), t.TempDir(), "sh", "-c", "sleep 30")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer h.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
payload := []byte(strings.Repeat("x", HandleInputLimit))
|
||||
// A process that never reads eventually fills its pipe; delivery cancellation
|
||||
// must stop it rather than leave a queued or partially delivered write alive.
|
||||
for i := 0; i < 32; i++ {
|
||||
err = h.Send(ctx, payload)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != context.DeadlineExceeded {
|
||||
t.Fatal("blocked input did not observe deadline", err)
|
||||
}
|
||||
if h.Snapshot().Running {
|
||||
t.Fatal("cancelled input returned before process joined")
|
||||
}
|
||||
}
|
||||
@@ -354,7 +354,7 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventDone,
|
||||
Usage: &llm.Usage{
|
||||
InputTokens: int(inputTokens),
|
||||
InputTokens: int(inputTokens + cacheCreationTokens + cacheReadTokens),
|
||||
OutputTokens: int(event.Usage.OutputTokens),
|
||||
CacheCreationInputTokens: int(cacheCreationTokens),
|
||||
CacheReadInputTokens: int(cacheReadTokens),
|
||||
@@ -457,7 +457,7 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventDone,
|
||||
Usage: &llm.Usage{
|
||||
InputTokens: int(msg.Usage.InputTokens),
|
||||
InputTokens: int(msg.Usage.InputTokens + msg.Usage.CacheCreationInputTokens + msg.Usage.CacheReadInputTokens),
|
||||
OutputTokens: int(msg.Usage.OutputTokens),
|
||||
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
|
||||
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
|
||||
|
||||
@@ -424,7 +424,7 @@ data: {"type":"message_stop"}
|
||||
require.Equal(t, 42, done.Usage.CacheCreationInputTokens)
|
||||
require.Equal(t, 17, done.Usage.CacheReadInputTokens)
|
||||
require.Equal(t, 5, done.Usage.OutputTokens)
|
||||
require.Equal(t, 10, done.Usage.InputTokens)
|
||||
require.Equal(t, 69, done.Usage.InputTokens) // 10 uncached + 42 cache creation + 17 cache read
|
||||
}
|
||||
|
||||
// TestBuildMessageParamsIsPure protects the cache-prefix invariant
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Steering boundary contract
|
||||
|
||||
`WithSteering` installs a prompt source for `Runtime.Run`/`RunSync`. It is polled
|
||||
after a model response and between joined tools. Without a source, existing tool
|
||||
concurrency and streaming kickoff behaviour is unchanged. With a source, tools
|
||||
run serially and streaming kickoff is disabled, providing a boundary before
|
||||
each remaining proposed call.
|
||||
|
||||
A source returns nil when no correction is pending. Otherwise it returns a
|
||||
stable ID, nonempty UTF-8 text bounded to 8 MiB after JSON encoding, up to 16 images
|
||||
with at most 32 MiB of image bytes in total, and an optional acknowledgement
|
||||
callback. The source must retain that correction until acknowledgement, honour
|
||||
cancellation, and return promptly. IDs are at most 128 bytes. A delivered ID
|
||||
must never be reused with different text.
|
||||
|
||||
On delivery, remaining calls receive explicit skipped results, then the user
|
||||
correction is appended under its stable ID and flushed. Only then does Harness
|
||||
acknowledge the source. The next model turn sees that history. Source or
|
||||
persistence errors stop execution. An acknowledgement failure also stops the
|
||||
run; redelivery of the same ID/text acknowledges without appending a duplicate.
|
||||
|
||||
This API does not cancel an already executing tool or take over its approval.
|
||||
The host must manage queue ownership, freeze text while delivery is claimed,
|
||||
reconcile acknowledgement failures, and render pending/delivered state. A
|
||||
correction arriving during a pending approval waits for that tool's execution
|
||||
boundary; separate cancellation remains available. `RunTurn` does not currently
|
||||
use this API. Native platform and integrated Hand qualification remain pending.
|
||||
|
||||
Steering images use the session attachment store and are verified/hydrated for
|
||||
identity comparison on redelivery. `MatchesSteering` exposes that semantic
|
||||
comparison to hosts reconciling interrupted acknowledgements. Text and image
|
||||
bytes must remain immutable while a delivery is unresolved. These limits bound
|
||||
the data; hosts must still enforce their model image capabilities and file
|
||||
attachment policies before supplying a correction.
|
||||
@@ -0,0 +1,23 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"github.com/sausheong/harness/process"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
// Only typed, completed built-in capture metadata becomes an artifact reference.
|
||||
// MCP JSON maps or paths mentioned in tool output are never interpreted as files.
|
||||
func resultArtifacts(result tool.ToolResult) map[string]process.ArtifactInfo {
|
||||
var artifacts map[string]process.ArtifactInfo
|
||||
for _, stream := range []string{"stdout", "stderr"} {
|
||||
info, ok := result.Metadata[stream+"_artifact"].(process.ArtifactInfo)
|
||||
if !ok || info.Path == "" || len(info.Path) > 4096 || len(info.SHA256) != 64 || info.Bytes < 0 || info.Bytes > process.ArtifactFileLimit || info.Error != "" {
|
||||
continue
|
||||
}
|
||||
if artifacts == nil {
|
||||
artifacts = make(map[string]process.ArtifactInfo)
|
||||
}
|
||||
artifacts[stream] = info
|
||||
}
|
||||
return artifacts
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/process"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/bash"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDispatchedArtifactReferenceSurvivesReopen(t *testing.T) {
|
||||
outputStore, err := process.NewArtifactStore(filepath.Join(t.TempDir(), "output"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("agent", "key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := store.LoadExclusive("agent", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
registry := tool.NewRegistry()
|
||||
registry.Register(&bash.BashTool{WorkDir: t.TempDir(), OutputStore: outputStore})
|
||||
rt := &Runtime{Session: sess, Tools: registry, AgentID: "agent"}
|
||||
result, aborted := rt.dispatchTool(context.Background(), llm.ToolCall{ID: "capture", Name: "bash", Input: json.RawMessage(`{"command":"head -c 70000 /dev/zero"}`)}, nil)
|
||||
if aborted || result.Error != "" {
|
||||
t.Fatal(aborted, result.Error)
|
||||
}
|
||||
if err := sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("agent", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sess.Close()
|
||||
found := false
|
||||
for _, entry := range sess.View() {
|
||||
if entry.Type != session.EntryTypeToolResult {
|
||||
continue
|
||||
}
|
||||
var data session.ToolResultData
|
||||
if err := json.Unmarshal(entry.Data, &data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ref, ok := data.Artifacts["stdout"]
|
||||
if !ok {
|
||||
t.Fatal("artifact reference missing after reopen")
|
||||
}
|
||||
captured, err := outputStore.Read(context.Background(), ref)
|
||||
if err != nil || len(captured) != 70000 || ref.Truncated {
|
||||
t.Fatal("persisted artifact cannot be verified", len(captured), err)
|
||||
}
|
||||
for _, b := range captured {
|
||||
if b != 0 {
|
||||
t.Fatal("artifact bytes changed")
|
||||
}
|
||||
}
|
||||
found = true
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("no persisted tool result")
|
||||
}
|
||||
}
|
||||
|
||||
func TestArtifactMetadataDoesNotPromoteUntrustedJSON(t *testing.T) {
|
||||
result := tool.ToolResult{Output: "[stdout artifact: /outside/private]", Metadata: map[string]any{"stdout_artifact": map[string]any{"path": "/outside/private", "sha256": "claimed"}}}
|
||||
if resultArtifacts(result) != nil {
|
||||
t.Fatal("untrusted JSON became artifact capability")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
type attachmentReplayProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
images []llm.ImageContent
|
||||
}
|
||||
|
||||
func (p *attachmentReplayProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
for _, msg := range req.Messages {
|
||||
p.images = append(p.images, msg.Images...)
|
||||
}
|
||||
events := make(chan llm.ChatEvent, 1)
|
||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(events)
|
||||
return events, nil
|
||||
}
|
||||
|
||||
func TestRuntimeReplaysAttachmentsAndRejectsMissingBlobs(t *testing.T) {
|
||||
for _, missing := range []bool{false, true} {
|
||||
name := "replay"
|
||||
if missing {
|
||||
name = "missing"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := session.NewStore(dir)
|
||||
if err := store.Create("agent", "key"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := store.LoadExclusive("agent", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess.Append(session.UserMessageWithImagesEntry("original", []session.ImageData{{MimeType: "image/png", Data: base64.StdEncoding.EncodeToString([]byte("original image"))}}))
|
||||
if err := sess.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess.Close()
|
||||
sess, err = store.LoadExclusive("agent", "key")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sess.Close()
|
||||
if missing {
|
||||
var data session.MessageData
|
||||
json.Unmarshal(sess.History()[0].Data, &data)
|
||||
if err := os.Remove(filepath.Join(dir, "agent", ".attachments", data.Images[0].Reference.SHA256)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
provider := &attachmentReplayProvider{}
|
||||
rt := &Runtime{Session: sess, LLM: provider, Tools: usageNoopExecutor{}, Model: "model", MaxTurns: 1}
|
||||
_, err = rt.RunSync(context.Background(), "continue", nil)
|
||||
if missing {
|
||||
if err == nil || provider.calls != 0 {
|
||||
t.Fatal("missing image silently omitted", err, provider.calls)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || provider.calls != 1 || len(provider.images) != 1 || string(provider.images[0].Data) != "original image" {
|
||||
t.Fatal(provider, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+78
-25
@@ -70,9 +70,23 @@ type RuntimeInputs struct {
|
||||
// 2. Parsing the reasoning mode (default-to-off + warn on invalid)
|
||||
// 3. Resolving the per-agent KnowledgeGraph via deps.KGFn (nil-safe)
|
||||
//
|
||||
// Returns the constructed Runtime and a nil error today, but callers MUST
|
||||
// check the error: the return is reserved for future validation.
|
||||
// Use BuildRuntimeContext when construction must be cancellable.
|
||||
func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runtime, error) {
|
||||
return BuildRuntimeContext(context.Background(), deps, inputs, spec)
|
||||
}
|
||||
|
||||
// BuildRuntimeContext propagates cancellation through MCP initialization and
|
||||
// discovery. On failure, all established sessions are closed before returning;
|
||||
// the caller's registry receives no partially discovered tools. The context
|
||||
// bounds construction, not the lifetime of successfully connected sessions.
|
||||
func BuildRuntimeContext(ctx context.Context, deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (_ *Runtime, buildErr error) {
|
||||
if spec.MaxOutputTokens < 0 {
|
||||
return nil, fmt.Errorf("max output tokens cannot be negative")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
provider, modelName := llm.ParseProviderModel(spec.Model)
|
||||
reasoning, err := llm.ParseReasoningMode(spec.Reasoning)
|
||||
if err != nil {
|
||||
@@ -91,51 +105,73 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
// callers always pass *tool.Registry; test paths that don't won't
|
||||
// get load tools registered (which is fine for them).
|
||||
var mcpClients []*mcp.Client
|
||||
if reg, ok := inputs.Tools.(*tool.Registry); ok {
|
||||
var mcpStatus []MCPServerStatus
|
||||
names := make(map[string]bool)
|
||||
for _, srv := range spec.MCPServers {
|
||||
if srv.Name == "" || names[srv.Name] {
|
||||
return nil, fmt.Errorf("mcp server names must be nonempty and unique")
|
||||
}
|
||||
if srv.ConnectTimeout < 0 {
|
||||
return nil, fmt.Errorf("MCP connect timeout must not be negative")
|
||||
}
|
||||
names[srv.Name] = true
|
||||
}
|
||||
defer func() {
|
||||
if buildErr != nil {
|
||||
for _, c := range mcpClients {
|
||||
_ = c.Close()
|
||||
}
|
||||
}
|
||||
}()
|
||||
var rt *Runtime
|
||||
var stagedTools []tool.Tool
|
||||
if _, ok := inputs.Tools.(*tool.Registry); ok {
|
||||
if deps.Skills != nil {
|
||||
skills := deps.Skills
|
||||
reg.Register(&tool.LoadSkillTool{
|
||||
stagedTools = append(stagedTools, &tool.LoadSkillTool{
|
||||
Lookup: func(name string) (string, bool) {
|
||||
return skills.Get(name)
|
||||
if rt.Skills == nil {
|
||||
return "", false
|
||||
}
|
||||
return rt.Skills.Get(name)
|
||||
},
|
||||
})
|
||||
}
|
||||
if deps.Memory != nil {
|
||||
mem := deps.Memory
|
||||
reg.Register(&tool.LoadMemoryTool{
|
||||
stagedTools = append(stagedTools, &tool.LoadMemoryTool{
|
||||
Lookup: func(id string) (string, bool) {
|
||||
return mem.Get(id)
|
||||
},
|
||||
})
|
||||
}
|
||||
// Connect declared MCP servers and register their adapter tools.
|
||||
// On any failure, close everything connected so far before
|
||||
// returning — a partially-built Runtime would leak processes.
|
||||
for _, srv := range spec.MCPServers {
|
||||
cli, err := mcp.Connect(context.Background(), srv)
|
||||
var err error
|
||||
mcpClients, mcpStatus, err = connectMCPServers(ctx, spec.MCPServers)
|
||||
if err != nil {
|
||||
for _, c := range mcpClients {
|
||||
_ = c.Close()
|
||||
return nil, err
|
||||
}
|
||||
return nil, fmt.Errorf("mcp server %q: %w", srv.Name, err)
|
||||
}
|
||||
for _, t := range cli.Tools() {
|
||||
reg.Register(t)
|
||||
}
|
||||
mcpClients = append(mcpClients, cli)
|
||||
for _, cli := range mcpClients {
|
||||
stagedTools = append(stagedTools, cli.Tools()...)
|
||||
}
|
||||
|
||||
} else if len(spec.MCPServers) > 0 {
|
||||
return nil, fmt.Errorf("AgentSpec.MCPServers requires inputs.Tools to be *tool.Registry")
|
||||
}
|
||||
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if reg, ok := inputs.Tools.(*tool.Registry); ok {
|
||||
for _, t := range stagedTools {
|
||||
reg.Register(t)
|
||||
}
|
||||
}
|
||||
|
||||
// Pre-compute the static portion of the system prompt so the per-turn
|
||||
// hot loop never reads config or rebuilds the indices. The load tools
|
||||
// are registered above so toolNames includes them in the default
|
||||
// identity tool hints.
|
||||
skillsIndex := ""
|
||||
if deps.Skills != nil {
|
||||
skillsIndex = deps.Skills.FormatIndex()
|
||||
}
|
||||
skillsIndex, skillSources := skillIndexSnapshot(deps.Skills)
|
||||
promptSources := append([]ContextSource(nil), spec.SystemPromptSources...)
|
||||
memoryIndex := ""
|
||||
if deps.Memory != nil {
|
||||
memoryIndex = deps.Memory.FormatIndex()
|
||||
@@ -168,7 +204,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
|
||||
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
|
||||
|
||||
rt := &Runtime{
|
||||
rt = &Runtime{
|
||||
LLM: inputs.Provider,
|
||||
Tools: inputs.Tools,
|
||||
Session: inputs.Session,
|
||||
@@ -177,6 +213,7 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
Model: modelName,
|
||||
FallbackModel: fallbackModel,
|
||||
ContextWindow: spec.ContextWindow,
|
||||
MaxOutputTokens: spec.MaxOutputTokens,
|
||||
Provider: provider,
|
||||
Reasoning: reasoning,
|
||||
Workspace: spec.Workspace,
|
||||
@@ -190,8 +227,15 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
IngestSource: inputs.IngestSource,
|
||||
AgentLoop: loop,
|
||||
StaticSystemPrompt: staticPrompt,
|
||||
refreshToolPrompt: func(names []string) string {
|
||||
currentSkills, sources := skillIndexSnapshot(rt.Skills)
|
||||
skillSources = append([]ContextSource(nil), sources...)
|
||||
return BuildStaticSystemPrompt(spec.Workspace, spec.SystemPrompt, spec.ID, spec.Name, names, deps.ConfigSummary, currentSkills, memoryIndex, deps.MemoryFiles)
|
||||
},
|
||||
contextSources: func() []ContextSource { return append(append([]ContextSource(nil), promptSources...), skillSources...) },
|
||||
CalibratorStore: deps.CalibratorStore,
|
||||
mcpClients: mcpClients,
|
||||
mcpStatus: mcpStatus,
|
||||
}
|
||||
|
||||
// Seed the calibrator from prior (ratio, count) for this session so a
|
||||
@@ -227,6 +271,15 @@ func mergeLoopConfig(base, override LoopConfig) LoopConfig {
|
||||
if override.MaxToolResultLen > 0 {
|
||||
out.MaxToolResultLen = override.MaxToolResultLen
|
||||
}
|
||||
if override.Hooks.OnRunStart != nil {
|
||||
out.Hooks.OnRunStart = override.Hooks.OnRunStart
|
||||
}
|
||||
if override.Hooks.OnRunFinish != nil {
|
||||
out.Hooks.OnRunFinish = override.Hooks.OnRunFinish
|
||||
}
|
||||
if override.Hooks.TransformToolContext != nil {
|
||||
out.Hooks.TransformToolContext = override.Hooks.TransformToolContext
|
||||
}
|
||||
if override.Hooks.OnUserPromptSubmit != nil {
|
||||
out.Hooks.OnUserPromptSubmit = override.Hooks.OnUserPromptSubmit
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
sdk "github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
func TestConstructionServerFixture(t *testing.T) {
|
||||
marker := os.Getenv("HARNESS_TEST_MCP_SHUTDOWN_MARKER")
|
||||
if marker == "" {
|
||||
return
|
||||
}
|
||||
server := sdk.NewServer(&sdk.Implementation{Name: "construction-fixture", Version: "1"}, nil)
|
||||
server.AddTool(&sdk.Tool{Name: "echo", InputSchema: json.RawMessage(`{"type":"object"}`)}, func(context.Context, *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
|
||||
return &sdk.CallToolResult{}, nil
|
||||
})
|
||||
err := server.Run(context.Background(), &sdk.StdioTransport{})
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := os.WriteFile(marker, []byte("closed"), 0600); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func constructionServer(t *testing.T) (mcp.ServerConfig, string) {
|
||||
t.Helper()
|
||||
marker := filepath.Join(t.TempDir(), "closed")
|
||||
return mcp.ServerConfig{Name: "healthy", Command: os.Args[0], Args: []string{"-test.run=^TestConstructionServerFixture$"}, Env: map[string]string{"HARNESS_TEST_MCP_SHUTDOWN_MARKER": marker, "GORACE": "atexit_sleep_ms=0"}}, marker
|
||||
}
|
||||
|
||||
func TestBuildRuntimeContextCancellationClosesPartialConnections(t *testing.T) {
|
||||
healthy, marker := constructionServer(t)
|
||||
reg := tool.NewRegistry()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{healthy, {Name: "hung", Command: "sleep", Args: []string{"30"}}}})
|
||||
if rt != nil || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("build = %v, %v", rt, err)
|
||||
}
|
||||
if len(reg.Names()) != 0 {
|
||||
t.Fatalf("partial tools leaked into registry: %v", reg.Names())
|
||||
}
|
||||
if _, err := os.Stat(marker); err != nil {
|
||||
t.Fatalf("healthy connection not closed before return: %v", err)
|
||||
}
|
||||
if time.Since(start) > 3*time.Second {
|
||||
t.Fatal("construction shutdown exceeded bound")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRuntimeContextAlreadyCancelledDoesNotMutateRegistry(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
reg := tool.NewRegistry()
|
||||
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{})
|
||||
if rt != nil || !errors.Is(err, context.Canceled) || len(reg.Names()) != 0 {
|
||||
t.Fatalf("build = %v, %v, tools %v", rt, err, reg.Names())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildRuntimeContextDoesNotOwnSuccessfulSessionLifetime(t *testing.T) {
|
||||
healthy, marker := constructionServer(t)
|
||||
reg := tool.NewRegistry()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{healthy}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
cancel()
|
||||
pingCtx, pingCancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer pingCancel()
|
||||
if err := rt.mcpClients[0].Ping(pingCtx); err != nil {
|
||||
t.Fatalf("construction context killed established session: %v", err)
|
||||
}
|
||||
if len(reg.Names()) != 1 || reg.Names()[0] != "mcp__healthy__echo" {
|
||||
t.Fatalf("tools %v", reg.Names())
|
||||
}
|
||||
if err := rt.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := os.Stat(marker); err != nil {
|
||||
t.Fatal("runtime close did not join child")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOptionalMCPFailurePreservesHealthyCatalogue(t *testing.T) {
|
||||
healthy, _ := constructionServer(t)
|
||||
reg := tool.NewRegistry()
|
||||
rt, err := BuildRuntimeContext(context.Background(), RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{
|
||||
{Name: "optional", Optional: true, Command: "sleep", Args: []string{"30"}, ConnectTimeout: 50 * time.Millisecond}, healthy,
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
if names := reg.Names(); len(names) != 1 || names[0] != "mcp__healthy__echo" {
|
||||
t.Fatalf("catalogue %v", names)
|
||||
}
|
||||
status := rt.MCPStatus()
|
||||
if len(status) != 2 || status[0].State != "unavailable" || !status[0].Optional || status[1].State != "connected" || status[1].Tools != 1 {
|
||||
t.Fatalf("status %+v", status)
|
||||
}
|
||||
status[0].State = "mutated"
|
||||
if rt.MCPStatus()[0].State != "unavailable" {
|
||||
t.Fatal("mutable status escaped")
|
||||
}
|
||||
}
|
||||
func TestOptionalMCPDoesNotSwallowOwnerCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
|
||||
defer cancel()
|
||||
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{MCPServers: []mcp.ServerConfig{{Name: "optional", Optional: true, Command: "sleep", Args: []string{"30"}}}})
|
||||
if rt != nil || !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatalf("owner cancellation: %v %v", rt, err)
|
||||
}
|
||||
}
|
||||
func TestMCPDuplicateNamesRejectedBeforeConstruction(t *testing.T) {
|
||||
reg := tool.NewRegistry()
|
||||
rt, err := BuildRuntimeContext(context.Background(), RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{MCPServers: []mcp.ServerConfig{{Name: "same"}, {Name: "same"}}})
|
||||
if rt != nil || err == nil || len(reg.Names()) != 0 {
|
||||
t.Fatalf("duplicate names: %v %v", rt, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/session"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPinnedGuidanceReachesManualAndAsyncSummariser(t *testing.T) {
|
||||
sess := session.NewSession("hand", "focus")
|
||||
provider := &recordingProvider{reply: "<summary>usable summary</summary>"}
|
||||
r := &Runtime{Session: sess}
|
||||
pin := ContextPin{ID: "constraint", Kind: "constraint", Text: "PRESERVE EXACT CONSTRAINT"}
|
||||
if err := r.SetContextPins(context.Background(), []ContextPin{pin}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.SetContextState(context.Background(), 0, []ContextStateItem{{ID: "decision", Kind: "decision", Text: "PRESERVE EXACT DECISION"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, err := r.CompactionContext(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Provider: provider, Model: "fixture"}, PreserveTurns: 2}
|
||||
add := func() {
|
||||
for i := 0; i < 10; i++ {
|
||||
sess.Append(session.UserMessageEntry("task detail"))
|
||||
sess.Append(session.AssistantMessageEntry("decision and evidence"))
|
||||
}
|
||||
}
|
||||
add()
|
||||
result, err := manager.MaybeCompact(ctx, sess, compaction.ReasonManual, "FOCUS ON UNRESOLVED WORK")
|
||||
if err != nil || !result.Compacted {
|
||||
t.Fatalf("manual: %+v %v", result, err)
|
||||
}
|
||||
add()
|
||||
done := manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonPreventive)
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("async compaction did not join")
|
||||
}
|
||||
if len(provider.requests) != 2 {
|
||||
t.Fatalf("requests %d", len(provider.requests))
|
||||
}
|
||||
for _, request := range provider.requests {
|
||||
if !strings.Contains(request.Messages[0].Content, pin.Text) || !strings.Contains(request.Messages[0].Content, "PRESERVE EXACT DECISION") {
|
||||
t.Fatal("pin omitted from summariser request")
|
||||
}
|
||||
}
|
||||
if !strings.Contains(provider.requests[0].Messages[0].Content, "FOCUS ON UNRESOLVED WORK") {
|
||||
t.Fatal("manual focus omitted")
|
||||
}
|
||||
if strings.Contains(provider.requests[1].Messages[0].Content, "FOCUS ON UNRESOLVED WORK") {
|
||||
t.Fatal("one-off focus leaked into automatic compaction")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
type joinedSummaryProvider struct {
|
||||
llmtest.Base
|
||||
entered, cancelled, release chan struct{}
|
||||
beforeReturn func()
|
||||
}
|
||||
|
||||
func (p *joinedSummaryProvider) ChatStream(ctx context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
close(p.entered)
|
||||
select {
|
||||
case <-p.release:
|
||||
case <-ctx.Done():
|
||||
close(p.cancelled)
|
||||
<-p.release
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if p.beforeReturn != nil {
|
||||
p.beforeReturn()
|
||||
}
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Summary of original work and constraints."}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 70, OutputTokens: 7}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestRuntimeJoinsDeferredBackgroundCompactionAndUsage(t *testing.T) {
|
||||
for _, cancelRun := range []bool{false, true} {
|
||||
name := "complete"
|
||||
if cancelRun {
|
||||
name = "cancel"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
sess := session.NewSession("agent", "key")
|
||||
for i := 0; i < 8; i++ {
|
||||
sess.Append(session.UserMessageEntry("question"))
|
||||
sess.Append(session.AssistantMessageEntry("answer"))
|
||||
}
|
||||
summary := &joinedSummaryProvider{entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})}
|
||||
var releaseOnce sync.Once
|
||||
release := func() { releaseOnce.Do(func() { close(summary.release) }) }
|
||||
defer release()
|
||||
manager := &compaction.Manager{PreserveTurns: 1, Summarizer: &compaction.Summarizer{Provider: summary, Model: "summary", Timeout: time.Second}}
|
||||
rt := &Runtime{Tools: usageNoopExecutor{}, LLM: &requestUsageProvider{total: 1}, Session: sess, Model: "generation", ContextWindow: 1000000, MaxTurns: 1, Compaction: manager}
|
||||
rt.AgentLoop.Hooks.OnStop = func(ctx context.Context, _ string) {
|
||||
manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonManual)
|
||||
}
|
||||
ledger := &llm.UsageLedger{}
|
||||
ctx, cancel := context.WithCancel(llm.WithUsageObserver(context.Background(), ledger.Record))
|
||||
defer cancel()
|
||||
events, err := rt.Run(ctx, "go", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
joined := make(chan struct{})
|
||||
var observed []AgentEvent
|
||||
go func() {
|
||||
for event := range events {
|
||||
observed = append(observed, event)
|
||||
}
|
||||
close(joined)
|
||||
}()
|
||||
select {
|
||||
case <-summary.entered:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("background summary not started")
|
||||
}
|
||||
if cancelRun {
|
||||
cancel()
|
||||
select {
|
||||
case <-summary.cancelled:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("parent cancellation lost")
|
||||
}
|
||||
}
|
||||
select {
|
||||
case <-joined:
|
||||
t.Fatal("runtime stream closed before background joined")
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
select {
|
||||
case <-joined:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("runtime did not join background")
|
||||
}
|
||||
if manager.HasInFlight(sess) {
|
||||
t.Fatal("producer remains after runtime close")
|
||||
}
|
||||
var doneCount, abortedCount int
|
||||
for i, event := range observed {
|
||||
if event.Type == EventDone {
|
||||
doneCount++
|
||||
if i != len(observed)-1 || event.Usage == nil || event.Usage.InputTokens != 20070 {
|
||||
t.Fatalf("done must be last with final accounting: %+v", event)
|
||||
}
|
||||
}
|
||||
if event.Type == EventAborted {
|
||||
abortedCount++
|
||||
}
|
||||
if event.Type == EventError && !cancelRun {
|
||||
t.Fatalf("unexpected error: %v", event.Error)
|
||||
}
|
||||
}
|
||||
if cancelRun && (doneCount != 0 || abortedCount != 1) {
|
||||
t.Fatalf("cancel: done=%d aborted=%d", doneCount, abortedCount)
|
||||
}
|
||||
if !cancelRun && (doneCount != 1 || abortedCount != 0) {
|
||||
t.Fatalf("success: done=%d aborted=%d", doneCount, abortedCount)
|
||||
}
|
||||
records := ledger.Records()
|
||||
if len(records) != 2 || records[1].Category != llm.CallCompaction {
|
||||
t.Fatal("background observer context lost", records)
|
||||
}
|
||||
if cancelRun {
|
||||
if records[1].Status != "cancelled" {
|
||||
t.Fatal(records[1])
|
||||
}
|
||||
} else if records[1].Usage == nil || records[1].Usage.InputTokens != 70 {
|
||||
t.Fatal(records[1])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRuntimeReportsAlreadyFinishedCompactionError(t *testing.T) {
|
||||
sess := session.NewSession("agent", "key")
|
||||
for i := 0; i < 8; i++ {
|
||||
sess.Append(session.UserMessageEntry("question"))
|
||||
sess.Append(session.AssistantMessageEntry("answer"))
|
||||
}
|
||||
summary := &joinedSummaryProvider{entered: make(chan struct{}), cancelled: make(chan struct{}), release: make(chan struct{})}
|
||||
// A concurrent branch change makes the summary's source view stale. This is
|
||||
// a real CommitCompaction error, without making the session writer fail.
|
||||
summary.beforeReturn = func() { sess.Append(session.UserMessageEntry("new branch work")) }
|
||||
close(summary.release)
|
||||
manager := &compaction.Manager{PreserveTurns: 1, Summarizer: &compaction.Summarizer{Provider: summary, Model: "summary", Timeout: time.Second}}
|
||||
rt := &Runtime{Tools: usageNoopExecutor{}, LLM: &requestUsageProvider{total: 1}, Session: sess, Model: "generation", ContextWindow: 1000000, MaxTurns: 1, Compaction: manager}
|
||||
rt.AgentLoop.Hooks.OnStop = func(ctx context.Context, _ string) {
|
||||
<-manager.MaybeCompactAsyncContext(ctx, sess, compaction.ReasonManual)
|
||||
}
|
||||
events, err := rt.Run(context.Background(), "go", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var errorsSeen, doneSeen int
|
||||
for event := range events {
|
||||
if event.Type == EventError {
|
||||
if !errors.Is(event.Error, session.ErrSessionChanged) {
|
||||
t.Fatalf("expected stale-session error, got %v", event.Error)
|
||||
}
|
||||
errorsSeen++
|
||||
}
|
||||
if event.Type == EventDone {
|
||||
doneSeen++
|
||||
}
|
||||
}
|
||||
if errorsSeen != 1 || doneSeen != 0 {
|
||||
t.Fatalf("completed failed producer: errors=%d done=%d", errorsSeen, doneSeen)
|
||||
}
|
||||
if err := sess.Flush(); err != nil {
|
||||
t.Fatalf("error must originate in compaction, not persistence: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
)
|
||||
|
||||
// ContextContribution describes size, never the potentially sensitive body.
|
||||
type ContextContribution struct {
|
||||
Kind string `json:"kind"`
|
||||
Name string `json:"name"`
|
||||
Count int `json:"count"`
|
||||
EstimatedTokens int `json:"estimated_tokens"`
|
||||
}
|
||||
|
||||
// ContextSource describes a component already included in the installed prompt.
|
||||
// These estimates are subsets of the static category, not additional tokens.
|
||||
type ContextSource struct {
|
||||
Kind string `json:"kind"`
|
||||
Path string `json:"path"`
|
||||
EstimatedTokens int `json:"estimated_tokens"`
|
||||
}
|
||||
|
||||
type SkillIndexSnapshotter interface {
|
||||
IndexSnapshot() (string, []ContextSource)
|
||||
}
|
||||
|
||||
func skillIndexSnapshot(provider SkillProvider) (string, []ContextSource) {
|
||||
if provider == nil {
|
||||
return "", nil
|
||||
}
|
||||
if snapshotter, ok := provider.(SkillIndexSnapshotter); ok {
|
||||
return snapshotter.IndexSnapshot()
|
||||
}
|
||||
return provider.FormatIndex(), nil
|
||||
}
|
||||
|
||||
type ContextInspection struct {
|
||||
Sources []ContextSource `json:"sources,omitempty"`
|
||||
OmittedSources int `json:"omitted_sources,omitempty"`
|
||||
EstimateMethod string `json:"estimate_method"`
|
||||
EstimatedTokens int `json:"estimated_tokens"`
|
||||
Contributions []ContextContribution `json:"contributions"`
|
||||
Limitations []string `json:"limitations"`
|
||||
}
|
||||
|
||||
// InspectContext measures the installed static prompt, current effective history
|
||||
// and registered schemas while idle. It does not make provider calls or refresh
|
||||
// discovery. Dynamic retrieval and a future user message are not included.
|
||||
func (r *Runtime) InspectContext(ctx context.Context) (ContextInspection, error) {
|
||||
var out ContextInspection
|
||||
if !r.runMu.TryLock() {
|
||||
return out, fmt.Errorf("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return out, err
|
||||
}
|
||||
var messages []llm.Message
|
||||
if r.Session != nil {
|
||||
history, err := r.Session.ResolveImages(ctx, r.Session.View())
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
messages = assembleMessages(history)
|
||||
}
|
||||
var defs []llm.ToolDef
|
||||
if r.Tools != nil {
|
||||
defs = r.Tools.ToolDefs()
|
||||
}
|
||||
if r.contextSources != nil {
|
||||
sources := r.contextSources()
|
||||
if len(sources) > 128 {
|
||||
out.OmittedSources = len(sources) - 128
|
||||
sources = sources[:128]
|
||||
}
|
||||
out.Sources = append([]ContextSource(nil), sources...)
|
||||
}
|
||||
out.EstimateMethod = "UTF-8 bytes / 4 with message framing and fixed image allowance; not provider-reported usage"
|
||||
pinned, err := r.contextPinsPrompt()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
statePrompt, err := r.contextStatePrompt()
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.EstimatedTokens = tokens.Estimate(messages, r.StaticSystemPrompt+pinned+statePrompt, defs)
|
||||
out.Contributions = append(out.Contributions, ContextContribution{Kind: "static_prompt", Name: "Installed identity, guidance, skills and memory", Count: 1, EstimatedTokens: tokens.Estimate(nil, r.StaticSystemPrompt, nil)})
|
||||
var ordinary, results []llm.Message
|
||||
for _, m := range messages {
|
||||
if m.Role == "tool" {
|
||||
results = append(results, m)
|
||||
} else {
|
||||
ordinary = append(ordinary, m)
|
||||
}
|
||||
}
|
||||
out.Contributions = append(out.Contributions,
|
||||
ContextContribution{Kind: "messages", Name: "Effective conversation", Count: len(ordinary), EstimatedTokens: tokens.Estimate(ordinary, "", nil)},
|
||||
ContextContribution{Kind: "tool_results", Name: "Effective tool results", Count: len(results), EstimatedTokens: tokens.Estimate(results, "", nil)},
|
||||
ContextContribution{Kind: "tool_schemas", Name: "Registered tool schemas", Count: len(defs), EstimatedTokens: tokens.Estimate(nil, "", defs)})
|
||||
if pinned != "" {
|
||||
pins, _ := r.contextPins()
|
||||
out.Contributions = append(out.Contributions, ContextContribution{Kind: "pins", Name: "Pinned objectives and constraints", Count: len(pins), EstimatedTokens: tokens.Estimate(nil, pinned, nil)})
|
||||
}
|
||||
if statePrompt != "" {
|
||||
state, _ := r.contextState()
|
||||
out.Contributions = append(out.Contributions, ContextContribution{Kind: "task_state", Name: "Structured objectives, decisions, unresolved work and evidence references", Count: len(state.Items), EstimatedTokens: tokens.Estimate(nil, statePrompt, nil)})
|
||||
}
|
||||
out.Limitations = []string{"Source estimates are subsets of the static prompt category, not additional tokens.", "Excludes the next user message, per-request date/identity suffix and dynamic retrieval.", "Estimates include only effective history after compaction; raw archived history is not counted.", "Image estimates use a fixed allowance, not provider-specific tiles or resolution.", "Components round down individually; their sum can differ slightly from the total."}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInspectContextEstimatesWithoutChangingHistory(t *testing.T) {
|
||||
s := session.NewSession("test", "inspect")
|
||||
s.Append(session.UserMessageEntry("private content must not be returned"))
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(echoTool{})
|
||||
r := &Runtime{Session: s, Tools: reg, StaticSystemPrompt: strings.Repeat("a", 100)}
|
||||
got, err := r.InspectContext(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := tokens.Estimate([]llm.Message{{Role: "user", Content: "private content must not be returned"}}, r.StaticSystemPrompt, reg.ToolDefs())
|
||||
if got.EstimatedTokens != want || len(got.Contributions) != 4 {
|
||||
t.Fatalf("inspection: %+v want %d", got, want)
|
||||
}
|
||||
if got.Contributions[1].Count != 1 || got.Contributions[3].Count != 1 || !strings.Contains(got.EstimateMethod, "not provider-reported") {
|
||||
t.Fatalf("metadata: %+v", got)
|
||||
}
|
||||
if len(s.View()) != 1 {
|
||||
t.Fatal("inspection changed history")
|
||||
}
|
||||
r.runMu.Lock()
|
||||
_, err = r.InspectContext(context.Background())
|
||||
r.runMu.Unlock()
|
||||
if err == nil {
|
||||
t.Fatal("busy inspection accepted")
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if _, err = r.InspectContext(ctx); err == nil {
|
||||
t.Fatal("cancelled inspection accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const contextPinsKind = "harness.context_pins"
|
||||
|
||||
type ContextPin struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
type contextPinsRecord struct {
|
||||
Version int `json:"version"`
|
||||
Pins []ContextPin `json:"pins"`
|
||||
}
|
||||
|
||||
func validatePins(pins []ContextPin) error {
|
||||
if len(pins) > 16 {
|
||||
return errors.New("at most 16 context pins are allowed")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, pin := range pins {
|
||||
if pin.ID == "" || len(pin.ID) > 64 || strings.IndexFunc(pin.ID, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '_') }) >= 0 || seen[pin.ID] {
|
||||
return errors.New("pin IDs must be unique lowercase identifiers of 1-64 characters")
|
||||
}
|
||||
seen[pin.ID] = true
|
||||
if pin.Kind != "objective" && pin.Kind != "constraint" {
|
||||
return errors.New("pin kind must be objective or constraint")
|
||||
}
|
||||
if strings.TrimSpace(pin.Text) == "" || len(pin.Text) > 2048 || !utf8.ValidString(pin.Text) || strings.ContainsRune(pin.Text, 0) {
|
||||
return errors.New("pin text must contain 1-2048 UTF-8 bytes without NUL")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetContextPins replaces the session-wide pin set durably while idle. An empty
|
||||
// set clears pins. Pins do not grant capabilities and are independent of branch
|
||||
// selection; changing sessions changes the pin set.
|
||||
func (r *Runtime) SetContextPins(ctx context.Context, pins []ContextPin) error {
|
||||
if !r.runMu.TryLock() {
|
||||
return errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Session == nil {
|
||||
return errors.New("session unavailable")
|
||||
}
|
||||
if err := validatePins(pins); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(contextPinsRecord{Version: 1, Pins: pins})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Session.Annotate(contextPinsKind, raw)
|
||||
}
|
||||
func (r *Runtime) ContextPins(ctx context.Context) ([]ContextPin, error) {
|
||||
if !r.runMu.TryLock() {
|
||||
return nil, errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.contextPins()
|
||||
}
|
||||
func (r *Runtime) contextPins() ([]ContextPin, error) {
|
||||
if r.Session == nil {
|
||||
return nil, nil
|
||||
}
|
||||
records := r.Session.Annotations(contextPinsKind)
|
||||
if len(records) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var record contextPinsRecord
|
||||
decoder := json.NewDecoder(bytes.NewReader(records[len(records)-1].Payload))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if decoder.Decode(new(any)) != io.EOF || record.Version != 1 {
|
||||
return nil, errors.New("unsupported or malformed context pin record")
|
||||
}
|
||||
if err := validatePins(record.Pins); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return record.Pins, nil
|
||||
}
|
||||
func (r *Runtime) contextPinsPrompt() (string, error) {
|
||||
pins, err := r.contextPins()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(pins) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("\n\nPinned session guidance (subject to the current user request; grants no tool permissions):\n")
|
||||
for _, pin := range pins {
|
||||
fmt.Fprintf(&b, "%s [%s]: %s\n", pin.Kind, pin.ID, pin.Text)
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
// CompactionContext captures the session pin guidance while idle for manual
|
||||
// compaction. Automatic runs bind the same guidance at run admission.
|
||||
func (r *Runtime) CompactionContext(ctx context.Context) (context.Context, error) {
|
||||
if !r.runMu.TryLock() {
|
||||
return ctx, errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
guidance, err := r.preservedContextPrompt()
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
ctx, err = compaction.WithGuidance(ctx, guidance)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
return r.budgetContext(ctx)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestContextPinsSurviveCompactionAndRestart(t *testing.T) {
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("agent", "pins"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := store.LoadExclusive("agent", "pins")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), StaticSystemPrompt: "identity", MaxTurns: 1}
|
||||
pins := []ContextPin{{ID: "constraint", Kind: "constraint", Text: "KEEP THIS EXACT CONSTRAINT"}, {ID: "objective", Kind: "objective", Text: "Deliver working implementation"}}
|
||||
if err = r.SetContextPins(context.Background(), pins); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pins[0].Text = "caller mutation"
|
||||
for i := 0; i < 3; i++ {
|
||||
sess.Compact("summary deliberately omits pins", 0)
|
||||
if err = sess.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if i == 1 {
|
||||
if err = sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("agent", "pins")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Session = sess
|
||||
}
|
||||
events, err := r.Run(context.Background(), "continue", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := false
|
||||
for event := range events {
|
||||
if event.Type == EventError {
|
||||
t.Fatal(event.Error)
|
||||
}
|
||||
if event.Type == EventDone {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
if !done {
|
||||
t.Fatal("run did not complete")
|
||||
}
|
||||
}
|
||||
defer sess.Close()
|
||||
if len(provider.requests) != 3 {
|
||||
t.Fatal("missing requests")
|
||||
}
|
||||
for _, request := range provider.requests {
|
||||
prompt := llm.JoinSystemPromptParts(request.SystemPromptParts)
|
||||
if !strings.Contains(prompt, "KEEP THIS EXACT CONSTRAINT") || !strings.Contains(prompt, "Deliver working implementation") {
|
||||
t.Fatal("pins omitted after compaction")
|
||||
}
|
||||
}
|
||||
inspected, err := r.InspectContext(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if inspected.Contributions[len(inspected.Contributions)-1].Kind != "pins" {
|
||||
t.Fatal("pins not counted")
|
||||
}
|
||||
if err = r.SetContextPins(context.Background(), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := r.ContextPins(context.Background())
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatal("clear failed", err)
|
||||
}
|
||||
}
|
||||
func TestContextPinsValidationAndCorruptRecord(t *testing.T) {
|
||||
r := &Runtime{Session: session.NewSession("agent", "pins")}
|
||||
for _, pins := range [][]ContextPin{{{ID: "bad id", Kind: "constraint", Text: "x"}}, {{ID: "ok", Kind: "other", Text: "x"}}, {{ID: "ok", Kind: "objective", Text: strings.Repeat("x", 2049)}}} {
|
||||
if err := r.SetContextPins(context.Background(), pins); err == nil {
|
||||
t.Fatal("invalid pins accepted")
|
||||
}
|
||||
}
|
||||
if len(r.Session.Annotations(contextPinsKind)) != 0 {
|
||||
t.Fatal("invalid write persisted")
|
||||
}
|
||||
r.runMu.Lock()
|
||||
err := r.SetContextPins(context.Background(), nil)
|
||||
r.runMu.Unlock()
|
||||
if err == nil {
|
||||
t.Fatal("busy update accepted")
|
||||
}
|
||||
if err = r.Session.Annotate(contextPinsKind, json.RawMessage(`{"version":99,"pins":[]}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = r.ContextPins(context.Background()); err == nil {
|
||||
t.Fatal("unsupported record ignored")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
const contextStateKind = "harness.context_state"
|
||||
|
||||
// ContextStateItem records task facts independently of generated summaries.
|
||||
// Reference is an opaque evidence locator, never opened or treated as proof.
|
||||
type ContextStateItem struct {
|
||||
ID string `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Text string `json:"text"`
|
||||
Reference string `json:"reference,omitempty"`
|
||||
}
|
||||
|
||||
// ContextState is session-wide, including across branch selection. Revision is
|
||||
// required on replacement so a stale client cannot silently discard newer work.
|
||||
type ContextState struct {
|
||||
Revision int `json:"revision"`
|
||||
Items []ContextStateItem `json:"items"`
|
||||
}
|
||||
type contextStateRecord struct {
|
||||
Version int `json:"version"`
|
||||
Items []ContextStateItem `json:"items"`
|
||||
}
|
||||
|
||||
func encodeContextState(items []ContextStateItem) ([]byte, error) {
|
||||
if len(items) > 32 {
|
||||
return nil, errors.New("at most 32 structured context items are allowed")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, item := range items {
|
||||
if item.ID == "" || len(item.ID) > 64 || strings.IndexFunc(item.ID, func(r rune) bool { return !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-' || r == '_') }) >= 0 || seen[item.ID] {
|
||||
return nil, errors.New("context item IDs must be unique lowercase identifiers of 1-64 characters")
|
||||
}
|
||||
seen[item.ID] = true
|
||||
switch item.Kind {
|
||||
case "objective", "decision", "unresolved_work", "verification_reference":
|
||||
default:
|
||||
return nil, errors.New("unsupported structured context kind")
|
||||
}
|
||||
if strings.TrimSpace(item.Text) == "" || len(item.Text) > 2048 || !utf8.ValidString(item.Text) || strings.ContainsRune(item.Text, 0) {
|
||||
return nil, errors.New("context text must contain 1-2048 UTF-8 bytes without NUL")
|
||||
}
|
||||
if len(item.Reference) > 1024 || !utf8.ValidString(item.Reference) || strings.ContainsRune(item.Reference, 0) {
|
||||
return nil, errors.New("context reference must be at most 1024 UTF-8 bytes without NUL")
|
||||
}
|
||||
if item.Kind == "verification_reference" && strings.TrimSpace(item.Reference) == "" {
|
||||
return nil, errors.New("verification context requires an evidence reference")
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(contextStateRecord{Version: 1, Items: items})
|
||||
if len(raw) > 8192 {
|
||||
return nil, errors.New("structured context exceeds 8 KiB encoded limit")
|
||||
}
|
||||
return raw, err
|
||||
}
|
||||
func (r *Runtime) contextState() (ContextState, error) {
|
||||
var state ContextState
|
||||
if r.Session == nil {
|
||||
return state, errors.New("session unavailable")
|
||||
}
|
||||
records := r.Session.Annotations(contextStateKind)
|
||||
state.Revision = len(records)
|
||||
if len(records) == 0 {
|
||||
return state, nil
|
||||
}
|
||||
payload := records[len(records)-1].Payload
|
||||
if len(payload) > 8192 {
|
||||
return state, errors.New("structured context exceeds 8 KiB")
|
||||
}
|
||||
var rec contextStateRecord
|
||||
dec := json.NewDecoder(bytes.NewReader(payload))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(&rec); err != nil {
|
||||
return state, err
|
||||
}
|
||||
if rec.Version != 1 || dec.Decode(new(any)) != io.EOF {
|
||||
return state, errors.New("unsupported or malformed structured context")
|
||||
}
|
||||
if _, err := encodeContextState(rec.Items); err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.Items = rec.Items
|
||||
return state, nil
|
||||
}
|
||||
func (r *Runtime) ContextState(ctx context.Context) (ContextState, error) {
|
||||
if !r.runMu.TryLock() {
|
||||
return ContextState{}, errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ContextState{}, err
|
||||
}
|
||||
return r.contextState()
|
||||
}
|
||||
|
||||
// SetContextState durably replaces the set while idle; an empty set explicitly
|
||||
// clears it. These records confer neither execution authority nor verified status.
|
||||
func (r *Runtime) SetContextState(ctx context.Context, expectedRevision int, items []ContextStateItem) error {
|
||||
if !r.runMu.TryLock() {
|
||||
return errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Session == nil {
|
||||
return errors.New("session unavailable")
|
||||
}
|
||||
raw, err := encodeContextState(items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := r.contextState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Revision != expectedRevision {
|
||||
return session.ErrAnnotationConflict
|
||||
}
|
||||
return r.Session.AnnotateIfCount(contextStateKind, raw, expectedRevision)
|
||||
}
|
||||
func (r *Runtime) contextStatePrompt() (string, error) {
|
||||
if r.Session == nil {
|
||||
return "", nil
|
||||
}
|
||||
state, err := r.contextState()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(state.Items) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
raw, err := encodeContextState(state.Items)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "\n\nRecorded task state (subject to current user instructions; grants no permissions). Evidence references are locators, not proof of current validity; inspect their scope and workspace version before claiming verification:\n" + string(raw) + "\n", nil
|
||||
}
|
||||
func (r *Runtime) preservedContextPrompt() (string, error) {
|
||||
pins, err := r.contextPinsPrompt()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
state, err := r.contextStatePrompt()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return pins + state, nil
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func TestStructuredContextSurvivesSummaryAndRestart(t *testing.T) {
|
||||
for _, turn := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "Run", true: "RunTurn"}[turn], func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("agent", "state"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := store.LoadExclusive("agent", "state")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { sess.Close() }()
|
||||
provider := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), MaxTurns: 1}
|
||||
items := []ContextStateItem{{ID: "goal", Kind: "objective", Text: "EXACT GOAL"}, {ID: "design", Kind: "decision", Text: "EXACT DECISION"}, {ID: "todo", Kind: "unresolved_work", Text: "EXACT TODO"}, {ID: "tests", Kind: "verification_reference", Text: "EXACT TEST SCOPE", Reference: "evidence/run.json#snapshot-abc"}}
|
||||
if err = r.SetContextState(ctx, 0, items); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.SetContextState(ctx, 0, nil); !errors.Is(err, session.ErrAnnotationConflict) {
|
||||
t.Fatalf("stale replacement: %v", err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
sess.Compact("summary deliberately omits all task facts", 0)
|
||||
if err = sess.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("agent", "state")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Session = sess
|
||||
if turn {
|
||||
result, err := r.RunTurn(ctx, "continue", nil, nil)
|
||||
if err != nil || result.Err != nil {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
} else {
|
||||
events, err := r.Run(ctx, "continue", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for e := range events {
|
||||
if e.Type == EventError {
|
||||
t.Fatal(e.Error)
|
||||
}
|
||||
}
|
||||
}
|
||||
prompt := llm.JoinSystemPromptParts(provider.requests[len(provider.requests)-1].SystemPromptParts)
|
||||
for _, item := range items {
|
||||
if !strings.Contains(prompt, item.Text) || !strings.Contains(prompt, item.Reference) {
|
||||
t.Fatal("structured state lost", prompt)
|
||||
}
|
||||
}
|
||||
state, err := r.ContextState(ctx)
|
||||
if err != nil || state.Revision != 1 || !reflect.DeepEqual(state.Items, items) {
|
||||
t.Fatalf("%+v %v", state, err)
|
||||
}
|
||||
}
|
||||
view, err := r.InspectContext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if view.Contributions[len(view.Contributions)-1].Kind != "task_state" {
|
||||
t.Fatal("context estimate omits task state")
|
||||
}
|
||||
if err = r.SetContextState(ctx, 1, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := r.ContextState(ctx)
|
||||
if err != nil || state.Revision != 2 || len(state.Items) != 0 {
|
||||
t.Fatal(state, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestStructuredContextRejectsInvalidAndCorruptState(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: session.NewSession("a", "s"), LLM: p, Tools: tool.NewRegistry()}
|
||||
invalid := [][]ContextStateItem{
|
||||
{{ID: "a", Kind: "verification_reference", Text: "test"}},
|
||||
{{ID: "a", Kind: "unknown", Text: "test"}},
|
||||
{{ID: "a", Kind: "objective", Text: "x"}, {ID: "a", Kind: "decision", Text: "y"}},
|
||||
{{ID: "a", Kind: "objective", Text: strings.Repeat("x", 2049)}},
|
||||
}
|
||||
large := []ContextStateItem{}
|
||||
for _, id := range []string{"a", "b", "c", "d"} {
|
||||
large = append(large, ContextStateItem{ID: id, Kind: "objective", Text: strings.Repeat("x", 2048)})
|
||||
}
|
||||
invalid = append(invalid, large)
|
||||
for _, items := range invalid {
|
||||
if err := r.SetContextState(ctx, 0, items); err == nil {
|
||||
t.Fatal("invalid state accepted")
|
||||
}
|
||||
}
|
||||
if len(r.Session.Annotations(contextStateKind)) != 0 {
|
||||
t.Fatal("invalid records persisted")
|
||||
}
|
||||
cancelled, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
if err := r.SetContextState(cancelled, 0, nil); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Session.Annotate(contextStateKind, json.RawMessage(`{"version":2,"items":[]}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := r.RunTurn(ctx, "do not dispatch", nil, nil)
|
||||
if err == nil && result.Err == nil {
|
||||
t.Fatal("corrupt state accepted")
|
||||
}
|
||||
if len(p.requests) != 0 {
|
||||
t.Fatal("corrupt state dispatched provider")
|
||||
}
|
||||
if _, err = r.CompactionContext(ctx); err == nil {
|
||||
t.Fatal("corrupt state compacted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
)
|
||||
|
||||
const costPricesKind = "harness.budget.prices.v1"
|
||||
|
||||
type costPricesRecord struct {
|
||||
Version int `json:"version"`
|
||||
Prices []budget.PriceSnapshot `json:"prices"`
|
||||
}
|
||||
type costBudgetContextKey struct{ session *session.Session }
|
||||
|
||||
func validateCostPrices(prices []budget.PriceSnapshot) error {
|
||||
if len(prices) > 16 {
|
||||
return errors.New("at most 16 route prices are allowed")
|
||||
}
|
||||
type key struct{ provider, model, destination string }
|
||||
seen := map[key]bool{}
|
||||
for _, p := range prices {
|
||||
if err := p.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
k := key{p.Provider, p.Model, p.Destination}
|
||||
if seen[k] {
|
||||
return errors.New("duplicate route price")
|
||||
}
|
||||
seen[k] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetCostPrices durably replaces explicitly reviewed session route tariffs.
|
||||
// It does not change the budget ceiling or erase historical request snapshots.
|
||||
func (r *Runtime) SetCostPrices(ctx context.Context, prices []budget.PriceSnapshot) error {
|
||||
if !r.runMu.TryLock() {
|
||||
return errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Session == nil {
|
||||
return errors.New("session unavailable")
|
||||
}
|
||||
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
|
||||
return errors.New("compaction is running")
|
||||
}
|
||||
if err := validateCostPrices(prices); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(costPricesRecord{Version: 1, Prices: prices})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Session.Annotate(costPricesKind, raw)
|
||||
}
|
||||
func (r *Runtime) costPrices() ([]budget.PriceSnapshot, error) {
|
||||
if r.Session == nil {
|
||||
return nil, errors.New("session unavailable")
|
||||
}
|
||||
records := r.Session.Annotations(costPricesKind)
|
||||
if len(records) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var record costPricesRecord
|
||||
d := json.NewDecoder(bytes.NewReader(records[len(records)-1].Payload))
|
||||
d.DisallowUnknownFields()
|
||||
if err := d.Decode(&record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if d.Decode(new(any)) != io.EOF || record.Version != 1 {
|
||||
return nil, errors.New("invalid session price record")
|
||||
}
|
||||
return record.Prices, validateCostPrices(record.Prices)
|
||||
}
|
||||
func (r *Runtime) CostPrices(ctx context.Context) ([]budget.PriceSnapshot, error) {
|
||||
if !r.runMu.TryLock() {
|
||||
return nil, errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.costPrices()
|
||||
}
|
||||
func (r *Runtime) DecideCostBudget(ctx context.Context, currency string, limitNano int64, strict bool) error {
|
||||
if !r.runMu.TryLock() {
|
||||
return errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
|
||||
return errors.New("compaction is running")
|
||||
}
|
||||
l, err := budget.OpenCostLedger(r.Session)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.Decide(ctx, currency, limitNano, strict)
|
||||
}
|
||||
func (r *Runtime) CostBudget(ctx context.Context) (budget.CostState, error) {
|
||||
if !r.runMu.TryLock() {
|
||||
return budget.CostState{}, errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return budget.CostState{}, err
|
||||
}
|
||||
l, err := budget.OpenCostLedger(r.Session)
|
||||
if err != nil {
|
||||
return budget.CostState{}, err
|
||||
}
|
||||
return l.State()
|
||||
}
|
||||
func (r *Runtime) costBudgetContext(ctx context.Context) (context.Context, error) {
|
||||
if r.Session == nil {
|
||||
return ctx, nil
|
||||
}
|
||||
key := costBudgetContextKey{r.Session}
|
||||
if ctx.Value(key) != nil {
|
||||
return ctx, nil
|
||||
}
|
||||
l, err := budget.OpenCostLedger(r.Session)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
state, err := l.State()
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
if state.LimitNano == 0 {
|
||||
return ctx, nil
|
||||
}
|
||||
prices, err := r.costPrices()
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
guard := l.Admission(func(req llm.ChatRequest, _ llm.CallCategory) (*budget.PriceSnapshot, int64, error) {
|
||||
prompt := req.SystemPrompt
|
||||
if len(req.SystemPromptParts) > 0 {
|
||||
prompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
|
||||
}
|
||||
input := int64(tokens.Estimate(req.Messages, prompt, req.Tools))
|
||||
for _, p := range prices {
|
||||
if p.Provider == req.Route.Provider && p.Destination == req.Route.Destination && p.Model == req.Model {
|
||||
return &p, input, nil
|
||||
}
|
||||
}
|
||||
return nil, input, nil
|
||||
})
|
||||
return context.WithValue(llm.WithCallAdmission(ctx, guard), key, true), nil
|
||||
}
|
||||
func (r *Runtime) budgetContext(ctx context.Context) (context.Context, error) {
|
||||
if err := r.validateRunBinding(ctx); err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
ctx, err := r.tokenBudgetContext(ctx)
|
||||
if err != nil {
|
||||
return ctx, err
|
||||
}
|
||||
return r.costBudgetContext(ctx)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func runtimeFixturePrice(route llm.CallRoute, model string) budget.PriceSnapshot {
|
||||
return budget.PriceSnapshot{Provider: route.Provider, Destination: route.Destination, Model: model, Currency: "USD", Source: "local test tariff", Version: "1", EffectiveAt: time.Now().Add(-time.Hour), ExpiresAt: time.Now().Add(time.Hour), InputNanoPerMillion: 1000000, OutputNanoPerMillion: 1000000, AllChargesBounded: true}
|
||||
}
|
||||
func TestCostBudgetRuntimeAndIndependentSummary(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := &recordingProvider{reply: "<summary>done</summary>"}
|
||||
s := session.NewSession("a", "cost")
|
||||
main := llm.CallRoute{Provider: "local", Destination: "http://main.example/v1"}
|
||||
summary := llm.CallRoute{Provider: "local", Destination: "http://summary.example/v1"}
|
||||
r := &Runtime{Session: s, Route: main, Provider: "local", Model: "fixture", LLM: provider, Tools: tool.NewRegistry(), MaxTurns: 1}
|
||||
if err := r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
events, err := r.Run(ctx, "unpriced", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unknown := false
|
||||
for event := range events {
|
||||
if errors.Is(event.Error, budget.ErrUnknownPrice) {
|
||||
unknown = true
|
||||
}
|
||||
}
|
||||
if !unknown || len(provider.requests) != 0 {
|
||||
t.Fatal("unpriced runtime reached provider")
|
||||
}
|
||||
prices := []budget.PriceSnapshot{runtimeFixturePrice(main, "fixture"), runtimeFixturePrice(summary, "fixture")}
|
||||
if err = r.SetCostPrices(ctx, prices); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
prices[0].Source = "caller mutation"
|
||||
events, err = r.Run(ctx, "priced", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range events {
|
||||
}
|
||||
state, err := r.CostBudget(ctx)
|
||||
if err != nil || len(state.Attempts) != 1 || state.Attempts[0].Quote.Snapshot.Destination != main.Destination {
|
||||
t.Fatalf("state %+v err %v", state, err)
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
s.Append(session.UserMessageEntry("task"))
|
||||
s.Append(session.AssistantMessageEntry("evidence"))
|
||||
}
|
||||
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Route: summary, Provider: provider, Model: "fixture", MaxOutputTokens: 100}, PreserveTurns: 2}
|
||||
manual, err := r.CompactionContext(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := manager.MaybeCompact(manual, s, compaction.ReasonManual, "")
|
||||
if err != nil || !result.Compacted {
|
||||
t.Fatalf("compaction %+v %v", result, err)
|
||||
}
|
||||
state, err = r.CostBudget(ctx)
|
||||
if err != nil || len(state.Attempts) != 2 || state.Attempts[1].Category != llm.CallCompaction || state.Attempts[1].Quote.Snapshot.Destination != summary.Destination {
|
||||
t.Fatalf("state %+v err %v", state, err)
|
||||
}
|
||||
installed, err := r.CostPrices(ctx)
|
||||
if err != nil || installed[0].Source == "caller mutation" {
|
||||
t.Fatal("caller mutation changed durable prices")
|
||||
}
|
||||
}
|
||||
func TestRunTurnCannotBypassSessionBudgets(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
provider := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: session.NewSession("a", "turn"), LLM: provider, Tools: tool.NewRegistry(), Model: "fixture"}
|
||||
if err := r.DecideTokenBudget(ctx, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := r.RunTurn(ctx, "blocked", nil, nil)
|
||||
if !errors.Is(err, budget.ErrExhausted) && !errors.Is(result.Err, budget.ErrExhausted) {
|
||||
t.Fatalf("result %+v err %v", result, err)
|
||||
}
|
||||
if len(provider.requests) != 0 {
|
||||
t.Fatal("RunTurn bypassed token budget")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCostPricesRestartAndInvalidReplacement(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("a", "prices"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := store.LoadExclusive("a", "prices")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := &Runtime{Session: s}
|
||||
price := runtimeFixturePrice(llm.CallRoute{Provider: "local", Destination: "http://fixture.example/v1"}, "fixture")
|
||||
if err = r.SetCostPrices(ctx, []budget.PriceSnapshot{price}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = r.SetCostPrices(ctx, []budget.PriceSnapshot{price, price}); err == nil {
|
||||
t.Fatal("duplicate route accepted")
|
||||
}
|
||||
if err = r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = s.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err = store.LoadExclusive("a", "prices")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
r.Session = s
|
||||
prices, err := r.CostPrices(ctx)
|
||||
if err != nil || len(prices) != 1 || prices[0].Source != price.Source || prices[0].Destination != price.Destination {
|
||||
t.Fatalf("prices %+v err %v", prices, err)
|
||||
}
|
||||
state, err := r.CostBudget(ctx)
|
||||
if err != nil || state.LimitNano != 1000000 || !state.Strict {
|
||||
t.Fatalf("state %+v err %v", state, err)
|
||||
}
|
||||
r.runMu.Lock()
|
||||
err = r.SetCostPrices(ctx, nil)
|
||||
r.runMu.Unlock()
|
||||
if err == nil {
|
||||
t.Fatal("busy price replacement accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
var ErrMCPAttachBusy = errors.New("runtime is active; defer MCP attachment until idle")
|
||||
|
||||
// AttachMCP transfers ownership only on success. The caller retains ownership
|
||||
// on all errors, including busy, and may retry or close the client. Connection
|
||||
// happens outside the runtime, so local runs can continue during discovery.
|
||||
func (r *Runtime) AttachMCP(client *mcp.Client, optional bool) error {
|
||||
if client == nil {
|
||||
return errors.New("nil MCP client")
|
||||
}
|
||||
if !r.runMu.TryLock() {
|
||||
return ErrMCPAttachBusy
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
r.mcpMu.Lock()
|
||||
defer r.mcpMu.Unlock()
|
||||
if r.mcpClosed {
|
||||
return errors.New("runtime is closed")
|
||||
}
|
||||
reg, ok := r.Tools.(*tool.Registry)
|
||||
if !ok || r.refreshToolPrompt == nil {
|
||||
return errors.New("runtime does not support dynamic MCP attachment")
|
||||
}
|
||||
name := client.Name()
|
||||
for _, s := range r.mcpStatus {
|
||||
if s.Name == name && s.State == "connected" {
|
||||
return fmt.Errorf("MCP server %q already connected", name)
|
||||
}
|
||||
}
|
||||
if err := reg.RegisterUnique(client.Tools()); err != nil {
|
||||
return err
|
||||
}
|
||||
r.StaticSystemPrompt = r.refreshToolPrompt(reg.Names())
|
||||
r.mcpClients = append(r.mcpClients, client)
|
||||
status := MCPServerStatus{Name: name, Optional: optional, State: "connected", Tools: len(client.Tools())}
|
||||
for i, s := range r.mcpStatus {
|
||||
if s.Name == name {
|
||||
r.mcpStatus[i] = status
|
||||
return nil
|
||||
}
|
||||
}
|
||||
r.mcpStatus = append(r.mcpStatus, status)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
func TestMCPAttachAtIdleUpdatesCatalogueAndOwnsShutdown(t *testing.T) {
|
||||
config, marker := constructionServer(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
client, err := mcp.Connect(ctx, config)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer client.Close()
|
||||
reg := tool.NewRegistry()
|
||||
rt, err := BuildRuntime(RuntimeDeps{}, RuntimeInputs{Tools: reg}, AgentSpec{ID: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
rt.runMu.Lock()
|
||||
err = rt.AttachMCP(client, true)
|
||||
rt.runMu.Unlock()
|
||||
if !errors.Is(err, ErrMCPAttachBusy) || len(reg.Names()) != 0 {
|
||||
t.Fatalf("active attachment: %v", err)
|
||||
}
|
||||
if _, err = os.Stat(marker); !os.IsNotExist(err) {
|
||||
t.Fatal("rejected attachment closed caller's client")
|
||||
}
|
||||
if err = rt.AttachMCP(client, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reg.Names()) != 1 || rt.Tools.ToolDefs()[0].Name != "mcp__healthy__echo" || rt.StaticSystemPrompt != BuildStaticSystemPrompt("", "", "test", "", reg.Names(), "", "", "", "") {
|
||||
t.Fatal("tool catalogue and model context diverged")
|
||||
}
|
||||
if status := rt.MCPStatus(); len(status) != 1 || status[0].State != "connected" {
|
||||
t.Fatalf("status %+v", status)
|
||||
}
|
||||
if err = rt.AttachMCP(client, true); err == nil {
|
||||
t.Fatal("duplicate attachment accepted")
|
||||
}
|
||||
if err = rt.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = os.Stat(marker); err != nil {
|
||||
t.Fatal("attached client not joined on close")
|
||||
}
|
||||
if err = rt.AttachMCP(client, true); err == nil {
|
||||
t.Fatal("attachment after close")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
const MCPConnectConcurrency = 4
|
||||
|
||||
// connectMCPServers joins every worker before returning. Results retain config
|
||||
// order, independent of completion order; publication remains transactional in
|
||||
// BuildRuntimeContext. The caller owns and must close returned clients on error.
|
||||
func connectMCPServers(parent context.Context, servers []mcp.ServerConfig) ([]*mcp.Client, []MCPServerStatus, error) {
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
defer cancel()
|
||||
clients := make([]*mcp.Client, len(servers))
|
||||
status := make([]MCPServerStatus, len(servers))
|
||||
var firstErr error
|
||||
var fail sync.Once
|
||||
jobs := make(chan int)
|
||||
var workers sync.WaitGroup
|
||||
for w := 0; w < min(MCPConnectConcurrency, len(servers)); w++ {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
for i := range jobs {
|
||||
if ctx.Err() != nil {
|
||||
continue
|
||||
}
|
||||
srv := servers[i]
|
||||
serverCtx := ctx
|
||||
stop := func() {}
|
||||
timeout := srv.ConnectTimeout
|
||||
if timeout == 0 && srv.Optional {
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
if timeout > 0 {
|
||||
serverCtx, stop = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
cli, err := mcp.Connect(serverCtx, srv)
|
||||
stop()
|
||||
status[i] = MCPServerStatus{Name: srv.Name, Optional: srv.Optional, State: "unavailable"}
|
||||
if err != nil {
|
||||
if !srv.Optional {
|
||||
fail.Do(func() { firstErr = fmt.Errorf("mcp server %q: %w", srv.Name, err); cancel() })
|
||||
}
|
||||
continue
|
||||
}
|
||||
clients[i] = cli
|
||||
status[i].State = "connected"
|
||||
status[i].Tools = len(cli.Tools())
|
||||
}
|
||||
}()
|
||||
}
|
||||
dispatch:
|
||||
for i := range servers {
|
||||
select {
|
||||
case jobs <- i:
|
||||
case <-ctx.Done():
|
||||
break dispatch
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
workers.Wait()
|
||||
connected := make([]*mcp.Client, 0, len(clients))
|
||||
for _, cli := range clients {
|
||||
if cli != nil {
|
||||
connected = append(connected, cli)
|
||||
}
|
||||
}
|
||||
if parent.Err() != nil {
|
||||
return connected, nil, parent.Err()
|
||||
}
|
||||
if firstErr != nil {
|
||||
return connected, nil, firstErr
|
||||
}
|
||||
return connected, status, nil
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tools/mcp"
|
||||
)
|
||||
|
||||
type startupTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f startupTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func TestMCPConnectionsIndependentAndBounded(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
release := make(chan struct{})
|
||||
entered := make(chan struct{}, 32)
|
||||
var active, peak atomic.Int32
|
||||
client := &http.Client{Transport: startupTransport(func(r *http.Request) (*http.Response, error) {
|
||||
n := active.Add(1)
|
||||
defer active.Add(-1)
|
||||
for old := peak.Load(); n > old; old = peak.Load() {
|
||||
if peak.CompareAndSwap(old, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
select {
|
||||
case entered <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-release:
|
||||
case <-r.Context().Done():
|
||||
}
|
||||
return nil, errors.New("fixture unavailable")
|
||||
})}
|
||||
servers := make([]mcp.ServerConfig, 8)
|
||||
for i := range servers {
|
||||
servers[i] = mcp.ServerConfig{Name: fmt.Sprintf("server%d", i), Optional: true, URL: "http://fixture.invalid/mcp", HTTPClient: client}
|
||||
}
|
||||
type result struct {
|
||||
rt *Runtime
|
||||
err error
|
||||
}
|
||||
done := make(chan result, 1)
|
||||
go func() {
|
||||
rt, err := BuildRuntimeContext(ctx, RuntimeDeps{}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{MCPServers: servers})
|
||||
done <- result{rt, err}
|
||||
}()
|
||||
for i := 0; i < MCPConnectConcurrency; i++ {
|
||||
select {
|
||||
case <-entered:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("connections did not start independently")
|
||||
}
|
||||
}
|
||||
if n := active.Load(); n != MCPConnectConcurrency {
|
||||
t.Fatalf("active connections %d", n)
|
||||
}
|
||||
close(release)
|
||||
r := <-done
|
||||
if r.err != nil {
|
||||
t.Fatal(r.err)
|
||||
}
|
||||
defer r.rt.Close()
|
||||
if n := peak.Load(); n > MCPConnectConcurrency {
|
||||
t.Fatalf("concurrency exceeded: %d", n)
|
||||
}
|
||||
status := r.rt.MCPStatus()
|
||||
if len(status) != len(servers) {
|
||||
t.Fatalf("status count %d", len(status))
|
||||
}
|
||||
for i, s := range status {
|
||||
if s.Name != servers[i].Name || s.State != "unavailable" {
|
||||
t.Fatalf("status order %+v", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package runtime
|
||||
|
||||
func (r *Runtime) outputTokenLimit() int {
|
||||
if r.MaxOutputTokens > 0 {
|
||||
return r.MaxOutputTokens
|
||||
}
|
||||
return 8192
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type outputLimitProvider struct {
|
||||
llmtest.Base
|
||||
limits []int
|
||||
fallback bool
|
||||
}
|
||||
|
||||
func (p *outputLimitProvider) ChatStream(_ context.Context, r llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.limits = append(p.limits, r.MaxTokens)
|
||||
if p.fallback && len(p.limits) == 1 {
|
||||
return nil, errors.New("529 overloaded")
|
||||
}
|
||||
ch := make(chan llm.ChatEvent, 1)
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
func TestGenerationOutputLimitReachesRequestsAndFallback(t *testing.T) {
|
||||
for _, single := range []bool{false, true} {
|
||||
for _, limit := range []int{0, 123, 32768, -1} {
|
||||
p := &outputLimitProvider{fallback: true}
|
||||
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "b"), Model: "primary", FallbackModel: "fallback", MaxTurns: 1, MaxOutputTokens: limit}
|
||||
var err error
|
||||
if single {
|
||||
var result TurnResult
|
||||
result, err = r.RunTurn(context.Background(), "hello", nil, nil)
|
||||
if err == nil {
|
||||
err = result.Err
|
||||
}
|
||||
} else {
|
||||
var events <-chan AgentEvent
|
||||
events, err = r.Run(context.Background(), "hello", nil)
|
||||
if err == nil {
|
||||
for e := range events {
|
||||
if e.Error != nil {
|
||||
err = e.Error
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if limit < 0 {
|
||||
if err == nil || len(p.limits) != 0 {
|
||||
t.Fatal("negative limit dispatched", err, p.limits)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := limit
|
||||
if want == 0 {
|
||||
want = 8192
|
||||
}
|
||||
if len(p.limits) != 2 {
|
||||
t.Fatal("missing fallback", p.limits)
|
||||
}
|
||||
for _, got := range p.limits {
|
||||
if got != want {
|
||||
t.Fatalf("single=%v limit=%d got=%d", single, limit, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
type persistenceProvider struct {
|
||||
usageDoneProvider
|
||||
before func()
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *persistenceProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
if p.before != nil {
|
||||
p.before()
|
||||
}
|
||||
return p.usageDoneProvider.ChatStream(ctx, req)
|
||||
}
|
||||
|
||||
func TestPersistenceFailurePreventsSuccessfulRuntimeCompletion(t *testing.T) {
|
||||
for _, stage := range []string{"prompt", "answer"} {
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "store")
|
||||
sess := session.NewSession("agent", "key")
|
||||
sess.SetStore(session.NewStore(root))
|
||||
provider := &persistenceProvider{}
|
||||
if stage == "prompt" {
|
||||
if err := os.WriteFile(root, []byte("obstruction"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
provider.before = func() {
|
||||
path := filepath.Join(root, "agent", "key.jsonl")
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if err := os.Mkdir(path, 0700); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
rt := &Runtime{AgentID: "agent", Provider: "local", Model: "fixture", Session: sess, Tools: tool.NewRegistry(), LLM: provider, MaxTurns: 1}
|
||||
events, err := rt.Run(context.Background(), "work", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed, done := false, false
|
||||
for event := range events {
|
||||
if event.Type == EventError && event.Error != nil {
|
||||
failed = true
|
||||
}
|
||||
if event.Type == EventDone {
|
||||
done = true
|
||||
}
|
||||
}
|
||||
if !failed || done || sess.PersistenceError() == nil {
|
||||
t.Fatal("persistence failure became success", failed, done)
|
||||
}
|
||||
if stage == "prompt" && provider.calls != 0 {
|
||||
t.Fatal("unsaved prompt sent to provider")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSyncJoinsAfterError(t *testing.T) {
|
||||
entered, release := make(chan struct{}), make(chan struct{})
|
||||
rt := &Runtime{AgentID: "agent", Provider: "local", Model: "fixture", Session: session.NewSession("agent", "key"), Tools: tool.NewRegistry(), LLM: &mockLLMProvider{events: []llm.ChatEvent{{Type: llm.EventError, Error: errors.New("provider failed")}}}, MaxTurns: 1}
|
||||
rt.AgentLoop.Hooks.OnStop = func(context.Context, string) { close(entered); <-release }
|
||||
result := make(chan error, 1)
|
||||
go func() { _, err := rt.RunSync(context.Background(), "work", nil); result <- err }()
|
||||
<-entered
|
||||
select {
|
||||
case err := <-result:
|
||||
t.Fatal("RunSync returned before cleanup", err)
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
close(release)
|
||||
if err := <-result; err == nil {
|
||||
t.Fatal("failure lost while joining")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type requestUsageProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
total int
|
||||
failFirst bool
|
||||
missingLast bool
|
||||
}
|
||||
|
||||
func (p *requestUsageProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
if p.failFirst && p.calls == 1 {
|
||||
return nil, errors.New("529 overloaded")
|
||||
}
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
if p.calls < p.total {
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
|
||||
}
|
||||
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
|
||||
if p.missingLast && p.calls == p.total {
|
||||
usage = nil
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: usage}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
func TestRequestUsageSeparatesLatestFromCumulative(t *testing.T) {
|
||||
p := &requestUsageProvider{total: 10}
|
||||
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", MaxTurns: 10}
|
||||
events, err := r.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
var records []llm.RequestUsage
|
||||
var total *llm.Usage
|
||||
for e := range events {
|
||||
if e.Type == EventRequestUsage {
|
||||
records = append(records, *e.RequestUsage)
|
||||
}
|
||||
if e.Type == EventDone {
|
||||
total = e.Usage
|
||||
}
|
||||
}
|
||||
require.Len(t, records, 10)
|
||||
require.Equal(t, 20000, records[9].Usage.InputTokens)
|
||||
require.Equal(t, 200000, total.InputTokens)
|
||||
for _, r := range records {
|
||||
require.Equal(t, llm.CallGeneration, r.Category)
|
||||
require.Equal(t, "reported", r.Source)
|
||||
}
|
||||
}
|
||||
func TestRequestUsageRetainsUnknownFailedAttemptAndModelChange(t *testing.T) {
|
||||
p := &requestUsageProvider{total: 2, failFirst: true, missingLast: true}
|
||||
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", FallbackModel: "fallback", MaxTurns: 2}
|
||||
events, err := r.Run(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
var records []llm.RequestUsage
|
||||
for e := range events {
|
||||
if e.Type == EventRequestUsage {
|
||||
records = append(records, *e.RequestUsage)
|
||||
}
|
||||
}
|
||||
require.Len(t, records, 2)
|
||||
require.Equal(t, "failed", records[0].Status)
|
||||
require.Nil(t, records[0].Usage)
|
||||
require.Equal(t, "primary", records[0].Model)
|
||||
require.Equal(t, "fallback", records[1].Model)
|
||||
require.Equal(t, llm.CallRetry, records[1].Category)
|
||||
require.Equal(t, "unavailable", records[1].Source)
|
||||
}
|
||||
|
||||
type refusalUsageProvider struct {
|
||||
llmtest.Base
|
||||
calls int
|
||||
}
|
||||
|
||||
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.calls++
|
||||
ch := make(chan llm.ChatEvent, 1)
|
||||
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
|
||||
if p.calls == 1 {
|
||||
e.StopReason = llm.StopReasonRefusal
|
||||
e.Usage.InputTokens = 20000
|
||||
}
|
||||
ch <- e
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
func TestRunTurnUsageIncludesRefusedAttempt(t *testing.T) {
|
||||
p := &refusalUsageProvider{}
|
||||
r := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("a", "k"), Model: "primary", FallbackModel: "fallback"}
|
||||
var records []llm.RequestUsage
|
||||
result, err := r.RunTurn(context.Background(), "go", nil, func(e AgentEvent) {
|
||||
if e.RequestUsage != nil {
|
||||
records = append(records, *e.RequestUsage)
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, result.Err)
|
||||
require.Equal(t, 30000, result.Usage.InputTokens)
|
||||
require.Len(t, records, 2)
|
||||
require.Equal(t, llm.CallRetry, records[1].Category)
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
)
|
||||
|
||||
var ErrRunTokenExhausted = fmt.Errorf("run token budget: %w", budget.ErrExhausted)
|
||||
var ErrRunCostExhausted = fmt.Errorf("run cost budget: %w", budget.ErrExhausted)
|
||||
|
||||
type RunBudgetState struct {
|
||||
ID string `json:"id"`
|
||||
Tokens budget.TokenState `json:"tokens"`
|
||||
Cost budget.CostState `json:"cost"`
|
||||
Deadline budget.DeadlineState `json:"deadline"`
|
||||
}
|
||||
|
||||
type runBudgetKey struct{ session *session.Session }
|
||||
type runBudgetBinding struct {
|
||||
id string
|
||||
tokens, cost bool
|
||||
deadline time.Time
|
||||
}
|
||||
|
||||
func (r *Runtime) withIdleRunBudget(ctx context.Context, fn func() error) error {
|
||||
if !r.runMu.TryLock() {
|
||||
return errors.New("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.Session == nil {
|
||||
return errors.New("session unavailable")
|
||||
}
|
||||
if r.Compaction != nil && r.Compaction.HasInFlight(r.Session) {
|
||||
return errors.New("compaction is running")
|
||||
}
|
||||
return fn()
|
||||
}
|
||||
func (r *Runtime) DecideRunTokenBudget(ctx context.Context, id string, limit int64) error {
|
||||
return r.withIdleRunBudget(ctx, func() error {
|
||||
l, err := budget.OpenRunTokenLedger(r.Session, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.Decide(ctx, limit)
|
||||
})
|
||||
}
|
||||
func (r *Runtime) DecideRunCostBudget(ctx context.Context, id, currency string, limitNano int64, strict bool) error {
|
||||
return r.withIdleRunBudget(ctx, func() error {
|
||||
l, err := budget.OpenRunCostLedger(r.Session, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.Decide(ctx, currency, limitNano, strict)
|
||||
})
|
||||
}
|
||||
func (r *Runtime) DecideRunTimeBudget(ctx context.Context, id string, allowance time.Duration) error {
|
||||
return r.withIdleRunBudget(ctx, func() error { return budget.DecideRunDeadline(ctx, r.Session, id, allowance) })
|
||||
}
|
||||
func (r *Runtime) RunBudget(ctx context.Context, id string) (state RunBudgetState, err error) {
|
||||
err = r.withIdleRunBudget(ctx, func() error { var e error; state, e = r.runBudgetState(id); return e })
|
||||
return
|
||||
}
|
||||
func (r *Runtime) runBudgetState(id string) (RunBudgetState, error) {
|
||||
state := RunBudgetState{ID: id}
|
||||
token, err := budget.OpenRunTokenLedger(r.Session, id)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
cost, err := budget.OpenRunCostLedger(r.Session, id)
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.Tokens, err = token.State()
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.Cost, err = cost.State()
|
||||
if err != nil {
|
||||
return state, err
|
||||
}
|
||||
state.Deadline, err = budget.ReadRunDeadline(r.Session, id)
|
||||
return state, err
|
||||
}
|
||||
|
||||
// PrepareRunBudget binds an explicitly configured logical run to all provider
|
||||
// attempts, including retries and compaction, while retaining inherited guards.
|
||||
// Use the returned context for the whole logical run (including continuations).
|
||||
// Cancel only after every owned operation joins. Preparing/repreparing never
|
||||
// changes limits or renews the deadline; unconfigured IDs fail closed.
|
||||
func (r *Runtime) PrepareRunBudget(ctx context.Context, id string) (context.Context, context.CancelFunc, error) {
|
||||
bound := ctx
|
||||
cancel := func() {}
|
||||
err := r.withIdleRunBudget(ctx, func() error {
|
||||
key := runBudgetKey{r.Session}
|
||||
if prior, ok := ctx.Value(key).(runBudgetBinding); ok {
|
||||
if prior.id != id {
|
||||
return errors.New("cannot replace an inherited run budget")
|
||||
}
|
||||
return r.validateRunBinding(ctx)
|
||||
}
|
||||
state, err := r.runBudgetState(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Tokens.Limit == 0 && state.Cost.LimitNano == 0 && state.Deadline.Version == 0 {
|
||||
return errors.New("run budget has no explicit decision")
|
||||
}
|
||||
bound, err = r.budgetContext(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state.Tokens.Limit > 0 {
|
||||
l, e := budget.OpenRunTokenLedger(r.Session, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
bound = llm.WithCallAdmission(bound, runAdmission(l.Admission(runInputEstimate), ErrRunTokenExhausted))
|
||||
}
|
||||
if state.Cost.LimitNano > 0 {
|
||||
l, e := budget.OpenRunCostLedger(r.Session, id)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
prices, e := r.costPrices()
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
resolver := func(req llm.ChatRequest, _ llm.CallCategory) (*budget.PriceSnapshot, int64, error) {
|
||||
input, e := runInputEstimate(req)
|
||||
if e != nil {
|
||||
return nil, 0, e
|
||||
}
|
||||
for _, p := range prices {
|
||||
if p.Provider == req.Route.Provider && p.Destination == req.Route.Destination && p.Model == req.Model {
|
||||
return &p, input, nil
|
||||
}
|
||||
}
|
||||
return nil, input, nil
|
||||
}
|
||||
bound = llm.WithCallAdmission(bound, runAdmission(l.Admission(resolver), ErrRunCostExhausted))
|
||||
}
|
||||
withSession, sessionCancel, e := budget.WithDeadline(bound, r.Session)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
withRun, runCancel, e := budget.WithRunDeadline(withSession, r.Session, id)
|
||||
if e != nil {
|
||||
sessionCancel()
|
||||
return e
|
||||
}
|
||||
cancel = func() { runCancel(); sessionCancel() }
|
||||
bound = context.WithValue(withRun, key, runBudgetBinding{id: id, tokens: state.Tokens.Limit > 0, cost: state.Cost.LimitNano > 0, deadline: state.Deadline.Deadline})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return ctx, func() {}, err
|
||||
}
|
||||
return bound, cancel, nil
|
||||
}
|
||||
func runInputEstimate(req llm.ChatRequest) (int64, error) {
|
||||
prompt := req.SystemPrompt
|
||||
if len(req.SystemPromptParts) > 0 {
|
||||
prompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
|
||||
}
|
||||
return int64(tokens.Estimate(req.Messages, prompt, req.Tools)), nil
|
||||
}
|
||||
func runAdmission(guard llm.CallAdmission, cause error) llm.CallAdmission {
|
||||
classify := func(err error) error {
|
||||
if errors.Is(err, budget.ErrExhausted) {
|
||||
return errors.Join(cause, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return func(ctx context.Context, req llm.ChatRequest, category llm.CallCategory, id string) (func(llm.RequestUsage) error, error) {
|
||||
settle, err := guard(ctx, req, category, id)
|
||||
if err != nil {
|
||||
return nil, classify(err)
|
||||
}
|
||||
return func(usage llm.RequestUsage) error { return classify(settle(usage)) }, nil
|
||||
}
|
||||
}
|
||||
|
||||
// A newly enabled dimension or changed deadline needs a fresh binding from
|
||||
// the owner context. Existing ledger guards already reload changed ceilings.
|
||||
func (r *Runtime) validateRunBinding(ctx context.Context) error {
|
||||
binding, ok := ctx.Value(runBudgetKey{r.Session}).(runBudgetBinding)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
state, err := r.runBudgetState(binding.id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if binding.tokens != (state.Tokens.Limit > 0) || binding.cost != (state.Cost.LimitNano > 0) || !binding.deadline.Equal(state.Deadline.Deadline) {
|
||||
return errors.New("run budget decision changed; prepare a fresh context from its owner")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func TestRunBudgetBindingChargesRunTurnAndCompactionOnce(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &recordingProvider{reply: "<summary>done</summary>"}
|
||||
r := &Runtime{Session: session.NewSession("a", "run"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture", MaxTurns: 1}
|
||||
if err := r.DecideTokenBudget(ctx, 1000000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.DecideRunTokenBudget(ctx, "logical-run", 1000000); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := r.PrepareRunBudget(ctx, "logical-run")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
// Repreparing must not attach another reservation for the same scope.
|
||||
same, stop, err := r.PrepareRunBudget(bound, "logical-run")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer stop()
|
||||
if _, stop, e := r.PrepareRunBudget(bound, "replacement"); e == nil {
|
||||
stop()
|
||||
t.Fatal("inherited scope replaced")
|
||||
}
|
||||
events, err := r.Run(same, "first", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for ev := range events {
|
||||
if ev.Error != nil {
|
||||
t.Fatal(ev.Error)
|
||||
}
|
||||
}
|
||||
result, err := r.RunTurn(same, "second", nil, nil)
|
||||
if err != nil || result.Err != nil {
|
||||
t.Fatalf("turn %+v %v", result, err)
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
r.Session.Append(session.UserMessageEntry("task"))
|
||||
r.Session.Append(session.AssistantMessageEntry("evidence"))
|
||||
}
|
||||
manager := &compaction.Manager{Summarizer: &compaction.Summarizer{Provider: p, Model: "fixture", MaxOutputTokens: 100}, PreserveTurns: 2}
|
||||
manual, err := r.CompactionContext(same)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
compacted, err := manager.MaybeCompact(manual, r.Session, compaction.ReasonManual, "")
|
||||
if err != nil || !compacted.Compacted {
|
||||
t.Fatalf("summary %+v %v", compacted, err)
|
||||
}
|
||||
run, err := r.RunBudget(ctx, "logical-run")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total, err := r.TokenBudget(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(run.Tokens.Attempts) != 3 || len(total.Attempts) != 3 || run.Tokens.Committed != total.Committed || run.Tokens.Attempts[2].Category != llm.CallCompaction {
|
||||
t.Fatalf("run=%+v total=%+v", run, total)
|
||||
}
|
||||
}
|
||||
func TestRunBudgetBindingCannotBypassEitherScope(t *testing.T) {
|
||||
for _, small := range []string{"run", "session"} {
|
||||
t.Run(small, func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: session.NewSession("a", "blocked"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
|
||||
runLimit, sessionLimit := int64(100000), int64(100000)
|
||||
if small == "run" {
|
||||
runLimit = 1
|
||||
} else {
|
||||
sessionLimit = 1
|
||||
}
|
||||
if err := r.DecideTokenBudget(ctx, sessionLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.DecideRunTokenBudget(ctx, "job", runLimit); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
events, err := r.Run(bound, "blocked", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var terminal error
|
||||
for ev := range events {
|
||||
if ev.Error != nil {
|
||||
terminal = ev.Error
|
||||
}
|
||||
}
|
||||
if !errors.Is(terminal, budget.ErrExhausted) || len(p.requests) != 0 {
|
||||
t.Fatalf("admission failed: %v requests=%d", terminal, len(p.requests))
|
||||
}
|
||||
if small == "run" && !errors.Is(terminal, ErrRunTokenExhausted) {
|
||||
t.Fatal("run reason lost", terminal)
|
||||
}
|
||||
run, _ := r.RunBudget(ctx, "job")
|
||||
total, _ := r.TokenBudget(ctx)
|
||||
if run.Tokens.Committed != 0 || total.Committed != 0 {
|
||||
t.Fatal("undispatched work charged")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
func TestRunBudgetDeadlineCancelsOwnedProvider(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &deadlineProvider{started: make(chan struct{}), stopped: make(chan struct{})}
|
||||
r := &Runtime{Session: session.NewSession("a", "time"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
|
||||
if _, stop, err := r.PrepareRunBudget(ctx, "missing"); err == nil {
|
||||
stop()
|
||||
t.Fatal("unconfigured run allowed")
|
||||
}
|
||||
if err := r.DecideRunTimeBudget(ctx, "timed", time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := r.PrepareRunBudget(ctx, "timed")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
events, err := r.Run(bound, "wait", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := false
|
||||
for ev := range events {
|
||||
if errors.Is(ev.Error, budget.ErrRunTimeExhausted) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("run deadline cause lost")
|
||||
}
|
||||
select {
|
||||
case <-p.stopped:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("provider not stopped")
|
||||
}
|
||||
if _, stop, e := r.PrepareRunBudget(ctx, "timed"); !errors.Is(e, budget.ErrRunTimeExhausted) {
|
||||
stop()
|
||||
t.Fatal("expired deadline renewed", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBudgetStaleBindingCannotOmitNewDimension(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: session.NewSession("a", "stale"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture"}
|
||||
if err := r.DecideRunTimeBudget(ctx, "job", time.Hour); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
if err = r.DecideRunTokenBudget(ctx, "job", 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = r.Run(bound, "must not bypass", nil); err == nil {
|
||||
t.Fatal("stale binding bypassed new token limit")
|
||||
}
|
||||
if len(p.requests) != 0 {
|
||||
t.Fatal("stale binding dispatched")
|
||||
}
|
||||
}
|
||||
func TestRunCostBindingStrictAdmissionAndSharedCharges(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
p := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: session.NewSession("a", "money"), LLM: p, Tools: tool.NewRegistry(), Model: "fixture", MaxTurns: 1, Route: llm.CallRoute{Provider: "local", Destination: "fixture"}}
|
||||
if err := r.DecideCostBudget(ctx, "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.SetCostPrices(ctx, []budget.PriceSnapshot{runtimeFixturePrice(r.Route, r.Model)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.DecideRunCostBudget(ctx, "job", "USD", 1, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bound, cancel, err := r.PrepareRunBudget(ctx, "job")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cancel()
|
||||
events, err := r.Run(bound, "blocked", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var terminal error
|
||||
for ev := range events {
|
||||
if ev.Error != nil {
|
||||
terminal = ev.Error
|
||||
}
|
||||
}
|
||||
if !errors.Is(terminal, ErrRunCostExhausted) || len(p.requests) != 0 {
|
||||
t.Fatalf("run cost bypass: %v", terminal)
|
||||
}
|
||||
total, err := r.CostBudget(ctx)
|
||||
if err != nil || total.CommittedNano != 0 {
|
||||
t.Fatalf("denied attempt charged session: %+v %v", total, err)
|
||||
}
|
||||
if err = r.DecideRunCostBudget(ctx, "job", "USD", 1000000, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
events, err = r.Run(bound, "resumed", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for ev := range events {
|
||||
if ev.Error != nil {
|
||||
t.Fatal(ev.Error)
|
||||
}
|
||||
}
|
||||
state, err := r.RunBudget(ctx, "job")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
total, err = r.CostBudget(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state.Cost.CommittedNano <= 0 || state.Cost.CommittedNano != total.CommittedNano || len(p.requests) != 1 {
|
||||
t.Fatalf("charges run=%+v total=%+v", state.Cost, total)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (r *Runtime) startRunLifecycle(ctx context.Context) (err error) {
|
||||
if hook := r.AgentLoop.Hooks.OnRunStart; hook != nil {
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
err = recoveredPanicError("OnRunStart hook", recovered)
|
||||
}
|
||||
}()
|
||||
return hook(ctx)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (r *Runtime) finishRunLifecycle(parent context.Context, reason string) {
|
||||
if hook := r.AgentLoop.Hooks.OnRunFinish; hook != nil {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 2*time.Second)
|
||||
defer cancel()
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
_ = recoveredPanicError("OnRunFinish hook", recovered)
|
||||
}
|
||||
}()
|
||||
hook(ctx, reason)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunLifecycleStartFailureAndFinishCannotChangeOutcome(t *testing.T) {
|
||||
for _, mode := range []string{"run", "runturn"} {
|
||||
for _, deny := range []bool{false, true} {
|
||||
t.Run(mode+map[bool]string{true: "-deny", false: "-allow"}[deny], func(t *testing.T) {
|
||||
starts, finishes := 0, 0
|
||||
reason := ""
|
||||
blocked := errors.New("start denied")
|
||||
rt := hookFixture(t, LifecycleHooks{OnRunStart: func(context.Context) error {
|
||||
starts++
|
||||
if deny {
|
||||
return blocked
|
||||
}
|
||||
return nil
|
||||
}, OnRunFinish: func(ctx context.Context, outcome string) {
|
||||
finishes++
|
||||
reason = outcome
|
||||
if ctx.Err() != nil {
|
||||
t.Error("finish context already cancelled")
|
||||
}
|
||||
if _, ok := ctx.Deadline(); !ok {
|
||||
t.Error("finish unbounded")
|
||||
}
|
||||
panic("observer cannot rewrite outcome")
|
||||
}}, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
|
||||
defer rt.Close()
|
||||
defer rt.Session.Close()
|
||||
failed := false
|
||||
if mode == "run" {
|
||||
events, err := rt.Run(context.Background(), "hello", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for event := range events {
|
||||
if event.Error != nil {
|
||||
failed = true
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result, err := rt.RunTurn(context.Background(), "hello", nil, nil)
|
||||
failed = err != nil || result.Err != nil
|
||||
}
|
||||
if starts != 1 || finishes != 1 || failed != deny {
|
||||
t.Fatal(starts, finishes, failed, deny)
|
||||
}
|
||||
if deny {
|
||||
if reason != "error" || len(rt.Session.View()) != 0 {
|
||||
t.Fatal("denied start mutated history", reason, rt.Session.View())
|
||||
}
|
||||
} else if reason != "completed" {
|
||||
t.Fatal(reason)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
+247
-87
@@ -3,6 +3,7 @@ package runtime
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sort"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/compaction"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
@@ -31,10 +33,13 @@ const (
|
||||
EventCompactionStart
|
||||
EventCompactionDone
|
||||
EventCompactionSkipped
|
||||
EventRequestUsage
|
||||
)
|
||||
|
||||
// AgentEvent is a single streaming event from the agent.
|
||||
type AgentEvent struct {
|
||||
RequestUsage *llm.RequestUsage // one provider attempt, independent of cumulative Usage
|
||||
|
||||
Type EventType
|
||||
// AgentID is the emitter's agent identifier. Empty for top-level
|
||||
// (Parent==nil) runtimes; populated by Runtime.emit when forwarding a
|
||||
@@ -45,11 +50,14 @@ type AgentEvent struct {
|
||||
Result *tool.ToolResult
|
||||
Error error
|
||||
Compaction *compaction.Result // populated for EventCompaction* events
|
||||
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
|
||||
Usage *llm.Usage // reported-only cumulative consumption on EventRequestUsage/EventDone; see USAGE.md for unknown attempts and compaction
|
||||
}
|
||||
|
||||
// Runtime is the agent think-act loop.
|
||||
type Runtime struct {
|
||||
// Route identifies the client in LLM for admission; update atomically with it.
|
||||
Route llm.CallRoute
|
||||
|
||||
LLM llm.LLMProvider
|
||||
Tools tool.Executor
|
||||
Session *session.Session
|
||||
@@ -79,6 +87,8 @@ type Runtime struct {
|
||||
|
||||
// ContextWindow overrides the auto-detected window. 0 = auto-detect.
|
||||
ContextWindow int
|
||||
// MaxOutputTokens bounds each generation request. Zero retains the 8192 default.
|
||||
MaxOutputTokens int
|
||||
|
||||
// StaticSystemPrompt is the cacheable portion of the system prompt.
|
||||
// Built once at BuildRuntime time; reused verbatim every turn so the
|
||||
@@ -145,6 +155,11 @@ type Runtime struct {
|
||||
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
|
||||
// not used.
|
||||
mcpClients []*mcp.Client
|
||||
mcpMu sync.Mutex
|
||||
mcpClosed bool
|
||||
refreshToolPrompt func([]string) string
|
||||
contextSources func() []ContextSource
|
||||
mcpStatus []MCPServerStatus
|
||||
|
||||
// runMu enforces the Runtime contract that one session exchange runs at a
|
||||
// time. TryLock lets a second caller receive a normal error instead of
|
||||
@@ -159,6 +174,9 @@ type Runtime struct {
|
||||
// Returns the first Close error encountered, if any; remaining
|
||||
// clients are still closed.
|
||||
func (r *Runtime) Close() error {
|
||||
r.mcpMu.Lock()
|
||||
defer r.mcpMu.Unlock()
|
||||
r.mcpClosed = true
|
||||
var firstErr error
|
||||
for _, c := range r.mcpClients {
|
||||
if err := c.Close(); err != nil && firstErr == nil {
|
||||
@@ -187,7 +205,7 @@ func (r *Runtime) emit(ev AgentEvent) {
|
||||
// maybeKickoffAsyncCompaction conditionally fires Compaction.MaybeCompactAsync
|
||||
// when the just-finished turn left the session close enough to the trigger
|
||||
// threshold that the NEXT turn would compact synchronously.
|
||||
func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.SystemPromptPart, toolDefs []llm.ToolDef) {
|
||||
func (r *Runtime) maybeKickoffAsyncCompaction(ctx context.Context, msgs []llm.Message, parts []llm.SystemPromptPart, toolDefs []llm.ToolDef) {
|
||||
if r.Compaction == nil || r.Model == "" {
|
||||
return
|
||||
}
|
||||
@@ -209,7 +227,7 @@ func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.Sy
|
||||
if !preemptThresholdHit && !preemptCountHit {
|
||||
return
|
||||
}
|
||||
r.Compaction.MaybeCompactAsync(r.Session, compaction.ReasonPreventive)
|
||||
r.Compaction.MaybeCompactAsyncContext(ctx, r.Session, compaction.ReasonPreventive)
|
||||
}
|
||||
|
||||
// providerSupportsCaching returns true when the runtime's provider implements
|
||||
@@ -290,18 +308,75 @@ func isFileTool(name string) bool {
|
||||
|
||||
// Run executes the agent loop for a user message, returning a channel of events.
|
||||
func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageContent) (<-chan AgentEvent, error) {
|
||||
if r.MaxOutputTokens < 0 {
|
||||
return nil, fmt.Errorf("max output tokens cannot be negative")
|
||||
}
|
||||
if !r.runMu.TryLock() {
|
||||
return nil, fmt.Errorf("runtime is already running")
|
||||
}
|
||||
guidance, guidanceErr := r.preservedContextPrompt()
|
||||
if guidanceErr != nil {
|
||||
r.runMu.Unlock()
|
||||
return nil, guidanceErr
|
||||
}
|
||||
ctx, guidanceErr = compaction.WithGuidance(ctx, guidance)
|
||||
if guidanceErr != nil {
|
||||
r.runMu.Unlock()
|
||||
return nil, guidanceErr
|
||||
}
|
||||
ctx, guidanceErr = r.budgetContext(ctx)
|
||||
if guidanceErr != nil {
|
||||
r.runMu.Unlock()
|
||||
return nil, guidanceErr
|
||||
}
|
||||
ctx, deadlineCancel, deadlineErr := budget.WithDeadline(ctx, r.Session)
|
||||
if deadlineErr != nil {
|
||||
r.runMu.Unlock()
|
||||
return nil, deadlineErr
|
||||
}
|
||||
ctx, cancelRun := context.WithCancelCause(ctx)
|
||||
events := make(chan AgentEvent, 100)
|
||||
r.events = events
|
||||
ledger := &llm.UsageLedger{}
|
||||
ctx = llm.WithUsageObserver(ctx, func(record llm.RequestUsage) {
|
||||
ledger.Record(record)
|
||||
r.emit(AgentEvent{Type: EventRequestUsage, RequestUsage: &record, Usage: ledger.Total()})
|
||||
})
|
||||
tr := TraceFrom(ctx)
|
||||
tr.Mark("agent.run.start", "user_msg_len", len(userMsg), "images", len(images))
|
||||
|
||||
go func() {
|
||||
completed := false
|
||||
defer close(events)
|
||||
defer deadlineCancel()
|
||||
defer cancelRun(nil)
|
||||
defer r.runMu.Unlock()
|
||||
defer tr.Summary()
|
||||
// Registered before stop hooks so their deferred work runs before the
|
||||
// final producer join and persistence fence. Events stays open throughout.
|
||||
defer func() {
|
||||
result, joined, err := r.Compaction.JoinInFlight(ctx, r.Session)
|
||||
if joined {
|
||||
kind := EventCompactionSkipped
|
||||
if result.Compacted {
|
||||
kind = EventCompactionDone
|
||||
}
|
||||
r.emit(AgentEvent{Type: kind, Compaction: &result})
|
||||
}
|
||||
if r.Session != nil {
|
||||
err = errors.Join(err, r.Session.Flush())
|
||||
}
|
||||
if err != nil {
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
}
|
||||
if completed {
|
||||
if ctx.Err() != nil {
|
||||
r.emit(abortedEvent(ctx))
|
||||
} else if err == nil {
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: ledger.Total()})
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Flush the per-session calibrator once at Run end (all exit paths:
|
||||
// normal, error, abort) instead of writing to disk on every LLM
|
||||
@@ -320,6 +395,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
// so the natural fall-through (loop exhausted MaxTurns) records the
|
||||
// right reason without an explicit assignment at that exit.
|
||||
stopReason := "max_turns"
|
||||
defer func() { r.finishRunLifecycle(ctx, stopReason) }()
|
||||
if hook := r.AgentLoop.Hooks.OnStop; hook != nil {
|
||||
defer func() { callOnStopHook(ctx, hook, stopReason) }()
|
||||
}
|
||||
@@ -331,6 +407,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
}()
|
||||
|
||||
if err := r.startRunLifecycle(ctx); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
// OnUserPromptSubmit may rewrite prompt and/or images BEFORE the
|
||||
// session sees them. Returning err aborts Run with EventError.
|
||||
if hook := r.AgentLoop.Hooks.OnUserPromptSubmit; hook != nil {
|
||||
@@ -352,11 +434,17 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
Data: base64.StdEncoding.EncodeToString(img.Data),
|
||||
})
|
||||
}
|
||||
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
r.Session.AppendContext(ctx, session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
} else {
|
||||
r.Session.Append(session.UserMessageEntry(userMsg))
|
||||
}
|
||||
|
||||
if err := r.Session.PersistenceError(); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
if hook := r.AgentLoop.Hooks.OnSessionStart; hook != nil {
|
||||
hook(ctx, r.Session)
|
||||
}
|
||||
@@ -424,12 +512,16 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
"reason", d.Reason)
|
||||
}
|
||||
|
||||
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
|
||||
|
||||
for turn := 0; turn < maxTurns; turn++ {
|
||||
if err := r.Session.PersistenceError(); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
r.emit(abortedEvent(ctx))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -451,7 +543,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, dateLine, kgContext)
|
||||
pinned, pinErr := r.preservedContextPrompt()
|
||||
if pinErr != nil {
|
||||
r.emit(AgentEvent{Type: EventError, Error: fmt.Errorf("load context pins: %w", pinErr)})
|
||||
return
|
||||
}
|
||||
dynamicSuffix += pinned
|
||||
|
||||
// Tool execution from the previous round has joined here. Refresh
|
||||
// self-authored skills before assembling the next model request.
|
||||
if r.Skills != nil {
|
||||
r.refreshSkills()
|
||||
}
|
||||
staticText := r.StaticSystemPrompt
|
||||
parts := []llm.SystemPromptPart{
|
||||
{Text: staticText, Cache: true},
|
||||
@@ -460,7 +563,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
|
||||
}
|
||||
|
||||
history := r.Session.View()
|
||||
history, imageErr := r.Session.ResolveImages(ctx, r.Session.View())
|
||||
if imageErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: imageErr})
|
||||
return
|
||||
}
|
||||
msgs := assembleMessages(history)
|
||||
|
||||
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
|
||||
@@ -510,10 +618,11 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
|
||||
req := llm.ChatRequest{
|
||||
Route: r.Route,
|
||||
Model: r.Model,
|
||||
Messages: msgs,
|
||||
Tools: toolDefs,
|
||||
MaxTokens: 8192,
|
||||
MaxTokens: r.outputTokenLimit(),
|
||||
SystemPromptParts: parts,
|
||||
CacheLastMessage: r.providerSupportsCaching(),
|
||||
Reasoning: r.Reasoning,
|
||||
@@ -525,7 +634,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
prefillChars += len(m.Content)
|
||||
}
|
||||
tr.Mark("llm.request_sent", "turn", turn, "model", r.Model, "prefill_chars", prefillChars)
|
||||
stream, err := r.LLM.ChatStream(ctx, req)
|
||||
stream, err := r.observeChat(ctx, req, llm.CallGeneration, r.LLM.ChatStream)
|
||||
if err != nil {
|
||||
if compaction.IsContextOverflow(err) && r.Compaction != nil {
|
||||
r.emit(AgentEvent{Type: EventCompactionStart})
|
||||
@@ -537,7 +646,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
req.Messages = msgs
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
}
|
||||
@@ -550,7 +659,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
"err", err.Error())
|
||||
tr.Mark("llm.fallback", "turn", turn, "primary", req.Model, "fallback", r.FallbackModel)
|
||||
req.Model = r.FallbackModel
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||
}
|
||||
if err != nil {
|
||||
stopReason = "error"
|
||||
@@ -564,7 +673,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
var thinkingBlocks []session.ThinkingBlockData
|
||||
gotFirstToken := false
|
||||
|
||||
streamingOn := r.streamingToolsEnabled()
|
||||
streamingOn := r.streamingToolsEnabled() && steeringSource(ctx) == nil
|
||||
kickoffs := map[string]chan kickoffResult{}
|
||||
kickoffStopped := false
|
||||
|
||||
@@ -576,6 +685,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
var refusalCategory string
|
||||
streamLoop:
|
||||
for {
|
||||
toolIDs := make(map[string]bool)
|
||||
for event := range streamSource {
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
@@ -606,6 +716,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
continue
|
||||
}
|
||||
tc := *event.ToolCall
|
||||
if err := acceptToolCallID(toolIDs, tc.ID); err != nil {
|
||||
cancelRun(err)
|
||||
// Join usage settlement before the runtime event channel closes.
|
||||
for range streamSource {
|
||||
}
|
||||
break streamLoop
|
||||
}
|
||||
toolCalls = append(toolCalls, tc)
|
||||
if !streamingOn || kickoffStopped {
|
||||
continue
|
||||
@@ -626,9 +743,6 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
runUsage = addUsage(runUsage, event.Usage)
|
||||
}
|
||||
if event.Usage != nil && r.calibrator != nil {
|
||||
// Recompute the estimate on the CURRENT msgs (which may
|
||||
// have been reassembled by mid-turn compaction) so the
|
||||
@@ -641,6 +755,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
|
||||
case llm.EventError:
|
||||
// Once tools have started, replaying the provider call can
|
||||
// repeat external effects. Stop owned work and reconcile
|
||||
// its results below before returning the original cause.
|
||||
if len(kickoffs) > 0 || ctx.Err() != nil || errors.Is(event.Error, budget.ErrExhausted) {
|
||||
cancelRun(event.Error)
|
||||
if len(toolCalls) > 0 {
|
||||
break streamLoop
|
||||
}
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return
|
||||
}
|
||||
if !gotFirstToken && !preTokenRetried {
|
||||
if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok {
|
||||
preTokenRetried = true
|
||||
@@ -664,7 +790,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
kickoffs = map[string]chan kickoffResult{}
|
||||
gotFirstToken = false
|
||||
kickoffStopped = false
|
||||
nsStream, retryErr := ns.ChatNonStreaming(ctx, req)
|
||||
nsStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, ns.ChatNonStreaming)
|
||||
if retryErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
@@ -682,6 +808,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
if len(toolCalls) > 0 {
|
||||
// Reconcile started tools below before closing events;
|
||||
// cancellation must not discard their session pairs.
|
||||
break streamLoop
|
||||
}
|
||||
drainKickoffs(kickoffs)
|
||||
stopReason = "aborted"
|
||||
r.emit(abortedEvent(ctx))
|
||||
return
|
||||
}
|
||||
|
||||
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
|
||||
// stop_reason=refusal, usually no content. Without handling,
|
||||
// the turn ends as a silent empty success. Retry once on the
|
||||
@@ -708,7 +846,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
refused = false
|
||||
retriedRefusal = true
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||
if retryErr != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
@@ -752,83 +890,83 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
}
|
||||
}
|
||||
|
||||
if steered, err := r.applySteering(ctx, toolCalls); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
} else if steered {
|
||||
continue
|
||||
}
|
||||
|
||||
if ctx.Err() != nil && len(toolCalls) == 0 {
|
||||
stopReason = "aborted"
|
||||
r.emit(abortedEvent(ctx))
|
||||
return
|
||||
}
|
||||
if len(toolCalls) == 0 {
|
||||
if len(kickoffs) > 0 {
|
||||
drainKickoffs(kickoffs)
|
||||
}
|
||||
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
|
||||
if err := r.Session.Flush(); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
}
|
||||
stopReason = "completed"
|
||||
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
|
||||
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
|
||||
completed = true
|
||||
r.maybeKickoffAsyncCompaction(ctx, msgs, parts, toolDefs)
|
||||
return
|
||||
}
|
||||
|
||||
var pending []llm.ToolCall
|
||||
var reconcileErr error
|
||||
for _, tc := range toolCalls {
|
||||
if ch, ok := kickoffs[tc.ID]; ok {
|
||||
kp := <-ch
|
||||
r.Session.Append(session.ToolCallEntry(kp.tc.ID, kp.tc.Name, kp.tc.Input))
|
||||
if r.KG != nil {
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{
|
||||
Role: "assistant",
|
||||
Content: fmt.Sprintf("[tool: %s]\n%s", kp.tc.Name, string(kp.tc.Input)),
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
delete(kickoffs, tc.ID)
|
||||
reconcileErr = errors.Join(reconcileErr, r.persistKickoff(ctx, kp, kgThreadOrNil(r.KG, &thread)))
|
||||
} else {
|
||||
pending = append(pending, tc)
|
||||
}
|
||||
if kp.aborted {
|
||||
r.Session.Append(session.AbortedToolResultEntry(kp.tc.ID))
|
||||
if r.KG != nil {
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{Role: "user", Content: "[error] aborted by user"})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
for _, tc2 := range toolCalls {
|
||||
if tc2.ID == kp.tc.ID {
|
||||
continue
|
||||
}
|
||||
ch2, ok := kickoffs[tc2.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
kp2 := <-ch2
|
||||
r.Session.Append(session.ToolCallEntry(kp2.tc.ID, kp2.tc.Name, kp2.tc.Input))
|
||||
r.Session.Append(session.AbortedToolResultEntry(kp2.tc.ID))
|
||||
if r.KG != nil {
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{
|
||||
Role: "assistant",
|
||||
Content: fmt.Sprintf("[tool: %s]\n%s", kp2.tc.Name, string(kp2.tc.Input)),
|
||||
})
|
||||
thread = append(thread, Message{Role: "user", Content: "[error] aborted by user"})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
if ctx.Err() != nil || reconcileErr != nil {
|
||||
// Calls emitted by the provider but not started must remain
|
||||
// paired too. Never invoke their permission hooks or tools.
|
||||
for _, tc := range pending {
|
||||
kp := kickoffResult{tc: tc, aborted: true}
|
||||
reconcileErr = errors.Join(reconcileErr, r.persistKickoff(ctx, kp, kgThreadOrNil(r.KG, &thread)))
|
||||
}
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
if reconcileErr != nil {
|
||||
r.emit(AgentEvent{Type: EventError, Error: errors.Join(context.Cause(ctx), reconcileErr)})
|
||||
} else {
|
||||
r.emit(abortedEvent(ctx))
|
||||
}
|
||||
return
|
||||
}
|
||||
imgData := convertToolResultImages(kp.result.Images)
|
||||
r.Session.Append(session.ToolResultEntry(kp.tc.ID, kp.result.Output, kp.result.Error, imgData))
|
||||
if r.KG != nil {
|
||||
content := kp.result.Output
|
||||
if kp.result.Error != "" {
|
||||
content = "[error] " + kp.result.Error
|
||||
}
|
||||
r.kgMu.Lock()
|
||||
thread = append(thread, Message{Role: "user", Content: content})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
continue
|
||||
}
|
||||
pending = append(pending, tc)
|
||||
}
|
||||
|
||||
batches := partitionToolCalls(pending, r.Tools)
|
||||
for _, b := range batches {
|
||||
if steeringSource(ctx) != nil {
|
||||
batches = nil
|
||||
for _, tc := range pending {
|
||||
batches = append(batches, batch{calls: []llm.ToolCall{tc}})
|
||||
}
|
||||
}
|
||||
for i, b := range batches {
|
||||
// The first boundary was checked immediately after model output.
|
||||
if i > 0 {
|
||||
if steered, err := r.applySteering(ctx, pending[i:]); err != nil {
|
||||
stopReason = "error"
|
||||
r.emit(AgentEvent{Type: EventError, Error: err})
|
||||
return
|
||||
} else if steered {
|
||||
break
|
||||
}
|
||||
}
|
||||
if r.runBatch(ctx, b, kgThreadOrNil(r.KG, &thread), turn, tr) {
|
||||
stopReason = "aborted"
|
||||
r.emit(AgentEvent{Type: EventAborted})
|
||||
r.emit(abortedEvent(ctx))
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -863,7 +1001,7 @@ func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *
|
||||
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
|
||||
*msgs = newMsgs
|
||||
req.Messages = newMsgs
|
||||
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
|
||||
if s, e := r.observeChat(ctx, *req, llm.CallRetry, r.LLM.ChatStream); e == nil {
|
||||
return s, true
|
||||
}
|
||||
} else {
|
||||
@@ -874,7 +1012,7 @@ func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *
|
||||
slog.Info("llm fallback model engaged (stream error)",
|
||||
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
|
||||
req.Model = r.FallbackModel
|
||||
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
|
||||
if s, e := r.observeChat(ctx, *req, llm.CallRetry, r.LLM.ChatStream); e == nil {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
@@ -890,18 +1028,25 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
|
||||
}
|
||||
|
||||
var response strings.Builder
|
||||
var runErr error
|
||||
for event := range events {
|
||||
switch event.Type {
|
||||
case EventTextDelta:
|
||||
response.WriteString(event.Text)
|
||||
case EventAborted:
|
||||
return response.String(), context.Canceled
|
||||
if runErr == nil {
|
||||
runErr = context.Canceled
|
||||
}
|
||||
case EventError:
|
||||
return response.String(), event.Error
|
||||
if runErr == nil {
|
||||
runErr = event.Error
|
||||
if runErr == nil {
|
||||
runErr = fmt.Errorf("runtime emitted an error without details")
|
||||
}
|
||||
}
|
||||
|
||||
return response.String(), nil
|
||||
}
|
||||
}
|
||||
return response.String(), runErr
|
||||
}
|
||||
|
||||
// dispatchTool executes one tool call with strict tool_use ↔ tool_result
|
||||
@@ -953,7 +1098,7 @@ func (r *Runtime) dispatchTool(
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.appendAbortedResult(tc.ID, kgThread), true
|
||||
return r.appendAbortedResult(ctx, tc.ID, kgThread), true
|
||||
}
|
||||
|
||||
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
|
||||
@@ -962,11 +1107,11 @@ func (r *Runtime) dispatchTool(
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.appendAbortedResult(tc.ID, kgThread), true
|
||||
return r.appendAbortedResult(ctx, tc.ID, kgThread), true
|
||||
}
|
||||
|
||||
imgData := convertToolResultImages(result.Images)
|
||||
r.Session.Append(session.ToolResultEntry(tc.ID, result.Output, result.Error, imgData))
|
||||
r.Session.AppendContext(ctx, session.ToolResultWithArtifactsEntry(tc.ID, result.Output, result.Error, imgData, resultArtifacts(result)))
|
||||
if kgThread != nil {
|
||||
content := result.Output
|
||||
if result.Error != "" {
|
||||
@@ -1019,14 +1164,14 @@ func (r *Runtime) executeToolKickoff(ctx context.Context, tc llm.ToolCall) (resu
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return tool.ToolResult{Error: "aborted by user"}, true
|
||||
return tool.ToolResult{Error: toolAbortReason(ctx)}, true
|
||||
}
|
||||
result, err := callToolExecute(ctx, r.Tools, tc.Name, tc.Input)
|
||||
if err != nil {
|
||||
result = tool.ToolResult{Error: err.Error()}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return tool.ToolResult{Error: "aborted by user"}, true
|
||||
return tool.ToolResult{Error: toolAbortReason(ctx)}, true
|
||||
}
|
||||
if result.Error == "" && isFileTool(tc.Name) {
|
||||
r.recordFileTouch(extractPathFromInput(tc.Input))
|
||||
@@ -1051,16 +1196,16 @@ func (r *Runtime) appendDenialResult(toolCallID, reason string, kgThread *[]Mess
|
||||
}
|
||||
|
||||
// appendAbortedResult writes the synthetic abort entry.
|
||||
func (r *Runtime) appendAbortedResult(toolCallID string, kgThread *[]Message) tool.ToolResult {
|
||||
r.Session.Append(session.AbortedToolResultEntry(toolCallID))
|
||||
func (r *Runtime) appendAbortedResult(ctx context.Context, toolCallID string, kgThread *[]Message) tool.ToolResult {
|
||||
r.Session.Append(session.AbortedToolResultWithReasonEntry(toolCallID, toolAbortReason(ctx)))
|
||||
if kgThread != nil {
|
||||
r.kgMu.Lock()
|
||||
*kgThread = append(*kgThread, Message{
|
||||
Role: "user", Content: "[error] aborted by user",
|
||||
Role: "user", Content: "[error] " + toolAbortReason(ctx),
|
||||
})
|
||||
r.kgMu.Unlock()
|
||||
}
|
||||
return tool.ToolResult{Error: "aborted by user"}
|
||||
return tool.ToolResult{Error: toolAbortReason(ctx)}
|
||||
}
|
||||
|
||||
// convertToolResultImages adapts tool image attachments to session ImageData.
|
||||
@@ -1085,3 +1230,18 @@ func kgThreadOrNil(kg KnowledgeGraph, thread *[]Message) *[]Message {
|
||||
}
|
||||
return thread
|
||||
}
|
||||
|
||||
// MCPServerStatus is immutable construction evidence without credentials or raw
|
||||
// transport errors. Connected servers alone contribute tools to the catalogue.
|
||||
type MCPServerStatus struct {
|
||||
Name string
|
||||
Optional bool
|
||||
State string
|
||||
Tools int
|
||||
}
|
||||
|
||||
func (r *Runtime) MCPStatus() []MCPServerStatus {
|
||||
r.mcpMu.Lock()
|
||||
defer r.mcpMu.Unlock()
|
||||
return append([]MCPServerStatus(nil), r.mcpStatus...)
|
||||
}
|
||||
+88
-19
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/budget"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
@@ -19,7 +20,7 @@ type TurnResult struct {
|
||||
StopReason string // "continue" | "completed" | "error" | "aborted"
|
||||
Entries []session.SessionEntry // entries appended during THIS turn, in order
|
||||
Err error
|
||||
Usage *llm.Usage
|
||||
Usage *llm.Usage // reported aggregate for this call, including retries
|
||||
}
|
||||
|
||||
// TurnEmit is an optional live-streaming callback. Pass nil for headless
|
||||
@@ -40,10 +41,55 @@ type TurnEmit func(AgentEvent)
|
||||
// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on
|
||||
// the first round of an exchange (folding the hint into the system prompt) and
|
||||
// async knowledge-graph ingest on the completing round.
|
||||
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
|
||||
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (turnOutcome TurnResult, turnError error) {
|
||||
if r.MaxOutputTokens < 0 {
|
||||
return TurnResult{}, fmt.Errorf("max output tokens cannot be negative")
|
||||
}
|
||||
if !r.runMu.TryLock() {
|
||||
return TurnResult{}, fmt.Errorf("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
var budgetErr error
|
||||
ctx, budgetErr = r.budgetContext(ctx)
|
||||
if budgetErr != nil {
|
||||
return TurnResult{}, budgetErr
|
||||
}
|
||||
|
||||
ctx, deadlineCancel, deadlineErr := budget.WithDeadline(ctx, r.Session)
|
||||
if deadlineErr != nil {
|
||||
return TurnResult{}, deadlineErr
|
||||
}
|
||||
defer deadlineCancel()
|
||||
ctx, cancelTurn := context.WithCancel(ctx)
|
||||
defer cancelTurn()
|
||||
if emit == nil {
|
||||
emit = func(AgentEvent) {}
|
||||
}
|
||||
ledger := &llm.UsageLedger{}
|
||||
ctx = llm.WithUsageObserver(ctx, ledger.Record)
|
||||
emittedUsage := 0
|
||||
flushUsage := func() {
|
||||
records := ledger.Records()
|
||||
for ; emittedUsage < len(records); emittedUsage++ {
|
||||
record := records[emittedUsage]
|
||||
emit(AgentEvent{Type: EventRequestUsage, RequestUsage: &record, Usage: ledger.Total()})
|
||||
}
|
||||
}
|
||||
defer flushUsage()
|
||||
defer func() {
|
||||
reason := turnOutcome.StopReason
|
||||
if reason == "" {
|
||||
if ctx.Err() != nil {
|
||||
reason = "aborted"
|
||||
} else {
|
||||
reason = "error"
|
||||
}
|
||||
}
|
||||
r.finishRunLifecycle(ctx, reason)
|
||||
}()
|
||||
if err := r.startRunLifecycle(ctx); err != nil {
|
||||
return TurnResult{StopReason: "error", Err: err}, err
|
||||
}
|
||||
startLen := len(r.Session.Entries())
|
||||
|
||||
if userMsg != "" || len(images) > 0 {
|
||||
@@ -55,17 +101,23 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
Data: base64.StdEncoding.EncodeToString(img.Data),
|
||||
})
|
||||
}
|
||||
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
r.Session.AppendContext(ctx, session.UserMessageWithImagesEntry(userMsg, imgData))
|
||||
} else {
|
||||
r.Session.Append(session.UserMessageEntry(userMsg))
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.turnSlice(startLen, true, "aborted", nil, ctx.Err()), nil
|
||||
return r.turnSlice(startLen, true, "aborted", nil, context.Cause(ctx)), nil
|
||||
}
|
||||
|
||||
history := r.Session.View()
|
||||
if err := r.Session.PersistenceError(); err != nil {
|
||||
return r.turnSlice(startLen, true, "error", nil, err), nil
|
||||
}
|
||||
history, imageErr := r.Session.ResolveImages(ctx, r.Session.View())
|
||||
if imageErr != nil {
|
||||
return r.turnSlice(startLen, true, "error", nil, imageErr), nil
|
||||
}
|
||||
msgs := assembleMessages(history)
|
||||
toolDefs := r.Tools.ToolDefs()
|
||||
if r.Permission != nil {
|
||||
@@ -85,25 +137,31 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
}
|
||||
|
||||
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, "", kgHint)
|
||||
pinned, pinErr := r.preservedContextPrompt()
|
||||
if pinErr != nil {
|
||||
return r.turnSlice(startLen, true, "error", nil, fmt.Errorf("load context pins: %w", pinErr)), nil
|
||||
}
|
||||
dynamicSuffix += pinned
|
||||
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
|
||||
if dynamicSuffix != "" {
|
||||
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
|
||||
}
|
||||
req := llm.ChatRequest{
|
||||
Route: r.Route,
|
||||
Model: r.Model,
|
||||
Messages: msgs,
|
||||
Tools: toolDefs,
|
||||
MaxTokens: 8192,
|
||||
MaxTokens: r.outputTokenLimit(),
|
||||
SystemPromptParts: parts,
|
||||
CacheLastMessage: r.providerSupportsCaching(),
|
||||
Reasoning: r.Reasoning,
|
||||
}
|
||||
|
||||
stream, err := r.LLM.ChatStream(ctx, req)
|
||||
stream, err := r.observeChat(ctx, req, llm.CallGeneration, r.LLM.ChatStream)
|
||||
if err != nil {
|
||||
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
|
||||
req.Model = r.FallbackModel
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
stream, err = r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||
}
|
||||
if err != nil {
|
||||
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
|
||||
@@ -114,13 +172,16 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
|
||||
var textContent strings.Builder
|
||||
var toolCalls []llm.ToolCall
|
||||
var thinkingBlocks []session.ThinkingBlockData
|
||||
var lastUsage *llm.Usage
|
||||
retriedRefusal := false
|
||||
streamLoop:
|
||||
for {
|
||||
toolIDs := make(map[string]bool)
|
||||
var refused bool
|
||||
var refusalCategory string
|
||||
for event := range stream {
|
||||
if event.Type == llm.EventDone || event.Type == llm.EventError {
|
||||
flushUsage()
|
||||
}
|
||||
switch event.Type {
|
||||
case llm.EventTextDelta:
|
||||
textContent.WriteString(event.Text)
|
||||
@@ -136,20 +197,28 @@ streamLoop:
|
||||
}
|
||||
case llm.EventToolCallDone:
|
||||
if event.ToolCall != nil {
|
||||
if err := acceptToolCallID(toolIDs, event.ToolCall.ID); err != nil {
|
||||
cancelTurn()
|
||||
for range stream {
|
||||
}
|
||||
flushUsage()
|
||||
emit(AgentEvent{Type: EventError, Error: err})
|
||||
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
|
||||
}
|
||||
toolCalls = append(toolCalls, *event.ToolCall)
|
||||
}
|
||||
case llm.EventDone:
|
||||
refused = event.StopReason == llm.StopReasonRefusal
|
||||
refusalCategory = event.StopCategory
|
||||
if event.Usage != nil {
|
||||
lastUsage = event.Usage
|
||||
}
|
||||
case llm.EventError:
|
||||
emit(AgentEvent{Type: EventError, Error: event.Error})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
|
||||
return r.turnSlice(startLen, true, "error", ledger.Total(), event.Error), nil
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return r.turnSlice(startLen, true, "aborted", ledger.Total(), context.Cause(ctx)), nil
|
||||
}
|
||||
// Same refusal contract as Run: retry once on the fallback model,
|
||||
// else surface a visible explanation instead of empty silence.
|
||||
if refused {
|
||||
@@ -158,10 +227,10 @@ streamLoop:
|
||||
textContent.Reset()
|
||||
toolCalls = nil
|
||||
req.Model = r.FallbackModel
|
||||
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
|
||||
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
|
||||
if retryErr != nil {
|
||||
emit(AgentEvent{Type: EventError, Error: retryErr})
|
||||
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
|
||||
return r.turnSlice(startLen, true, "error", ledger.Total(), retryErr), nil
|
||||
}
|
||||
stream = retryStream
|
||||
continue streamLoop
|
||||
@@ -200,8 +269,8 @@ streamLoop:
|
||||
if r.KG != nil {
|
||||
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
|
||||
}
|
||||
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
|
||||
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
|
||||
emit(AgentEvent{Type: EventDone, Usage: ledger.Total()})
|
||||
return r.turnSlice(startLen, true, "completed", ledger.Total(), nil), nil
|
||||
}
|
||||
|
||||
// RunTurn dispatches tool calls serially by design: deterministic
|
||||
@@ -212,11 +281,11 @@ streamLoop:
|
||||
result, aborted := r.dispatchTool(ctx, tc, nil)
|
||||
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
|
||||
if aborted {
|
||||
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
|
||||
return r.turnSlice(startLen, true, "aborted", ledger.Total(), context.Cause(ctx)), nil
|
||||
}
|
||||
}
|
||||
|
||||
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
|
||||
return r.turnSlice(startLen, false, "continue", ledger.Total(), nil), nil
|
||||
}
|
||||
|
||||
// turnSlice builds a TurnResult from the entries appended since startLen.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
func TestRunTurnPinsAfterCompactionRestartAndCorruption(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := session.NewStore(t.TempDir())
|
||||
if err := store.Create("agent", "turn-pins"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err := store.LoadExclusive("agent", "turn-pins")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { sess.Close() }()
|
||||
provider := &recordingProvider{reply: "done"}
|
||||
r := &Runtime{Session: sess, LLM: provider, Tools: tool.NewRegistry(), StaticSystemPrompt: "identity"}
|
||||
if err = r.SetContextPins(ctx, []ContextPin{{ID: "objective", Kind: "objective", Text: "EXACT OBJECTIVE"}, {ID: "constraint", Kind: "constraint", Text: "EXACT CONSTRAINT"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
sess.Compact("summary omits all pins", 0)
|
||||
if err = sess.Flush(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = sess.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sess, err = store.LoadExclusive("agent", "turn-pins")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Session = sess
|
||||
result, err := r.RunTurn(ctx, "continue", nil, nil)
|
||||
if err != nil || result.Err != nil || result.StopReason != "completed" {
|
||||
t.Fatalf("%+v %v", result, err)
|
||||
}
|
||||
req := provider.requests[len(provider.requests)-1]
|
||||
prompt := llm.JoinSystemPromptParts(req.SystemPromptParts)
|
||||
for _, text := range []string{"EXACT OBJECTIVE", "EXACT CONSTRAINT"} {
|
||||
if strings.Count(prompt, text) != 1 {
|
||||
t.Fatalf("missing or duplicated pin: %s", prompt)
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = sess.Annotate(contextPinsKind, json.RawMessage(`{"version":99,"pins":[]}`)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before := len(provider.requests)
|
||||
result, err := r.RunTurn(ctx, "must not dispatch", nil, nil)
|
||||
if err == nil && result.Err == nil {
|
||||
t.Fatal("corrupt pins accepted")
|
||||
}
|
||||
if len(provider.requests) != before {
|
||||
t.Fatal("provider dispatched with corrupt pins")
|
||||
}
|
||||
}
|
||||
@@ -163,3 +163,24 @@ func TestRunTurn_PreCancelledContext(t *testing.T) {
|
||||
require.Error(t, res.Err)
|
||||
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
|
||||
}
|
||||
|
||||
func TestRunTurnExcludesConcurrentRuntimeOperations(t *testing.T) {
|
||||
rt := &Runtime{LLM: &scriptedStreamLLM{events: []scriptedStreamEvent{{typ: llm.EventTextDelta, text: "hello"}, {typ: llm.EventDone}}}, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"), AgentID: "a", Model: "test"}
|
||||
rt.runMu.Lock()
|
||||
_, err := rt.RunTurn(context.Background(), "rejected", nil, nil)
|
||||
rt.runMu.Unlock()
|
||||
require.Error(t, err)
|
||||
require.Empty(t, rt.Session.Entries())
|
||||
observed := false
|
||||
_, err = rt.RunTurn(context.Background(), "accepted", nil, func(AgentEvent) {
|
||||
observed = true
|
||||
if rt.runMu.TryLock() {
|
||||
rt.runMu.Unlock()
|
||||
t.Error("runtime lock released during RunTurn")
|
||||
}
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.True(t, observed)
|
||||
require.True(t, rt.runMu.TryLock(), "runtime lock not released after RunTurn")
|
||||
rt.runMu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tool/skills"
|
||||
"github.com/sausheong/harness/tool/skills/disk"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type authoringProvider struct {
|
||||
llmtest.Base
|
||||
prompts []string
|
||||
}
|
||||
|
||||
func (p *authoringProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
p.prompts = append(p.prompts, llm.JoinSystemPromptParts(req.SystemPromptParts))
|
||||
ch := make(chan llm.ChatEvent, 2)
|
||||
switch len(p.prompts) {
|
||||
case 1:
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "author", Name: "skill_manage", Input: json.RawMessage(`{"action":"create","name":"authored-skill","body":"---\ndescription: newly authored workflow\n---\nunique procedure body"}`)}}
|
||||
case 2:
|
||||
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "load", Name: "load_skill", Input: json.RawMessage(`{"name":"authored-skill"}`)}}
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
func TestSkillAuthoringRefreshesNextModelRequest(t *testing.T) {
|
||||
store := disk.NewStore(t.TempDir())
|
||||
reg := tool.NewRegistry()
|
||||
reg.Register(&skills.SkillTool{Store: store})
|
||||
provider := &authoringProvider{}
|
||||
rt, err := BuildRuntime(RuntimeDeps{Skills: store.AsSkillProvider()}, RuntimeInputs{Tools: reg, Session: session.NewSession("test", "skills")}, AgentSpec{ID: "test", SystemPrompt: "fixed identity", MaxTurns: 4})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
rt.LLM = provider
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
events, err := rt.Run(ctx, "create then load the workflow", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := false
|
||||
loaded := false
|
||||
for event := range events {
|
||||
if event.Type == EventError {
|
||||
t.Errorf("runtime error: %v", event.Error)
|
||||
}
|
||||
if event.Type == EventDone {
|
||||
done = true
|
||||
}
|
||||
if event.Type == EventToolResult && event.ToolCall != nil && event.ToolCall.Name == "load_skill" {
|
||||
encoded, _ := json.Marshal(event)
|
||||
loaded = strings.Contains(string(encoded), "unique procedure body")
|
||||
}
|
||||
}
|
||||
if !done || !loaded || len(provider.prompts) != 3 {
|
||||
t.Fatalf("done=%v loaded=%v requests=%d", done, loaded, len(provider.prompts))
|
||||
}
|
||||
if strings.Contains(provider.prompts[0], "newly authored workflow") {
|
||||
t.Fatal("skill existed before authoring")
|
||||
}
|
||||
for _, prompt := range provider.prompts[1:] {
|
||||
if !strings.Contains(prompt, "newly authored workflow") || !strings.Contains(prompt, "fixed identity") {
|
||||
t.Fatalf("next request omitted refreshed skill: %s", prompt)
|
||||
}
|
||||
}
|
||||
if _, ok, err := store.Get(ctx, "authored-skill"); err != nil || !ok {
|
||||
t.Fatalf("skill not persisted: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package runtime
|
||||
|
||||
import "fmt"
|
||||
|
||||
// RefreshSkills refreshes discovery while idle. Run also refreshes between
|
||||
// model requests, after preceding tool calls have joined. Providers must bound
|
||||
// filesystem work; callers cannot refresh concurrently with an active run.
|
||||
func (r *Runtime) RefreshSkills() error {
|
||||
if !r.runMu.TryLock() {
|
||||
return fmt.Errorf("runtime is already running")
|
||||
}
|
||||
defer r.runMu.Unlock()
|
||||
r.refreshSkills()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runtime) refreshSkills() {
|
||||
if r.refreshToolPrompt == nil {
|
||||
return
|
||||
}
|
||||
var names []string
|
||||
if r.Tools != nil {
|
||||
names = r.Tools.Names()
|
||||
}
|
||||
r.StaticSystemPrompt = r.refreshToolPrompt(names)
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/sausheong/harness/tool/skills"
|
||||
"github.com/sausheong/harness/tool/skills/disk"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRefreshSkillsDiscoversAuthoredAndRemovedSkills(t *testing.T) {
|
||||
store := disk.NewStore(t.TempDir())
|
||||
rt, err := BuildRuntime(RuntimeDeps{Skills: store.AsSkillProvider(), ConfigSummary: "configuration retained", MemoryFiles: "memory retained"}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{ID: "test", SystemPrompt: "identity retained"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
initial := rt.StaticSystemPrompt
|
||||
if _, err = store.Create(context.Background(), skills.Skill{Name: "new-skill", Description: "new description", Body: "procedure"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rt.runMu.Lock()
|
||||
err = rt.RefreshSkills()
|
||||
rt.runMu.Unlock()
|
||||
if err == nil || rt.StaticSystemPrompt != initial {
|
||||
t.Fatal("busy refresh mutated prompt")
|
||||
}
|
||||
if err = rt.RefreshSkills(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, want := range []string{"new-skill", "new description", "identity retained", "configuration retained", "memory retained"} {
|
||||
if !strings.Contains(rt.StaticSystemPrompt, want) {
|
||||
t.Fatalf("missing %s", want)
|
||||
}
|
||||
}
|
||||
if err = store.Remove(context.Background(), "new-skill"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = rt.RefreshSkills(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rt.StaticSystemPrompt != initial {
|
||||
t.Fatal("removed skill remains or unrelated context changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshSkillsUsesCurrentProviderForToolAndIndex(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
first := disk.NewStore(t.TempDir())
|
||||
second := disk.NewStore(t.TempDir())
|
||||
for _, entry := range []struct {
|
||||
store *disk.Store
|
||||
body string
|
||||
}{{first, "original"}, {second, "replacement"}} {
|
||||
if _, err := entry.store.Create(ctx, skills.Skill{Name: "selected", Description: entry.body, Body: entry.body}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
rt, err := BuildRuntime(RuntimeDeps{Skills: first.AsSkillProvider()}, RuntimeInputs{Tools: tool.NewRegistry()}, AgentSpec{ID: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rt.Close()
|
||||
rt.Skills = second.AsSkillProvider()
|
||||
if err = rt.RefreshSkills(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := rt.Tools.Execute(ctx, "load_skill", []byte(`{"name":"selected"}`))
|
||||
if err != nil || result.Error != "" || !strings.Contains(result.Output, "replacement") || strings.Contains(result.Output, "original") || !strings.Contains(rt.StaticSystemPrompt, "replacement") {
|
||||
t.Fatal(result, err, rt.StaticSystemPrompt)
|
||||
}
|
||||
rt.Skills = nil
|
||||
if err = rt.RefreshSkills(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err = rt.Tools.Execute(ctx, "load_skill", []byte(`{"name":"selected"}`))
|
||||
if err != nil || result.Error == "" || strings.Contains(rt.StaticSystemPrompt, "replacement") {
|
||||
t.Fatal("removed provider still used", result, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
)
|
||||
|
||||
type steeringContextKey struct{}
|
||||
|
||||
// SteeringMessage identifies one correction. Source retains it until Acknowledge
|
||||
// succeeds. ID must be stable across retry; Text must not change after delivery.
|
||||
type SteeringMessage struct {
|
||||
ID string
|
||||
Text string
|
||||
Images []llm.ImageContent
|
||||
Acknowledge func() error
|
||||
}
|
||||
type SteeringSource func(context.Context) (*SteeringMessage, error)
|
||||
|
||||
// WithSteering enables safe-boundary delivery for Run. Tool execution becomes
|
||||
// serial and streaming kickoff is disabled so no eligible later tool can race a
|
||||
// correction. Source is called after model output and between joined tools.
|
||||
// A nil message means no correction. Source must return promptly and honour ctx.
|
||||
func WithSteering(ctx context.Context, source SteeringSource) context.Context {
|
||||
return context.WithValue(ctx, steeringContextKey{}, source)
|
||||
}
|
||||
func steeringSource(ctx context.Context) SteeringSource {
|
||||
source, _ := ctx.Value(steeringContextKey{}).(SteeringSource)
|
||||
return source
|
||||
}
|
||||
|
||||
func (r *Runtime) applySteering(ctx context.Context, pending []llm.ToolCall) (bool, error) {
|
||||
source := steeringSource(ctx)
|
||||
if source == nil {
|
||||
return false, nil
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
message, err := source(ctx)
|
||||
if err != nil || message == nil {
|
||||
return false, err
|
||||
}
|
||||
if message.ID == "" || len(message.ID) > 128 || strings.ContainsAny(message.ID, "\r\n\x00") || !utf8.ValidString(message.ID) || !utf8.ValidString(message.Text) || strings.TrimSpace(message.Text) == "" || len(message.Text) > 8<<20 {
|
||||
return false, errors.New("invalid steering identity or text")
|
||||
}
|
||||
if len(message.Images) > 16 {
|
||||
return false, errors.New("too many steering images")
|
||||
}
|
||||
totalImageBytes := 0
|
||||
for _, img := range message.Images {
|
||||
if len(img.Data) > (32<<20)-totalImageBytes {
|
||||
return false, errors.New("steering images exceed 32 MiB")
|
||||
}
|
||||
totalImageBytes += len(img.Data)
|
||||
if img.MimeType == "" {
|
||||
return false, errors.New("steering image MIME type missing")
|
||||
}
|
||||
}
|
||||
entry := session.UserMessageEntry(message.Text)
|
||||
if len(entry.Data) > 8<<20 {
|
||||
return false, errors.New("encoded steering text exceeds 8 MiB")
|
||||
}
|
||||
if len(message.Images) > 0 {
|
||||
entry = session.UserMessageWithImagesEntry(message.Text, convertToolResultImages(message.Images))
|
||||
}
|
||||
entry.ID = "steering_" + message.ID
|
||||
for _, prior := range r.Session.Entries() {
|
||||
if prior.ID != entry.ID {
|
||||
continue
|
||||
}
|
||||
matches, err := MatchesSteering(ctx, r.Session, *message, prior)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !matches {
|
||||
return false, errors.New("conflicting delivered steering identity")
|
||||
}
|
||||
if err := r.Session.Flush(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if message.Acknowledge != nil {
|
||||
return false, message.Acknowledge()
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
// Reconcile every proposed call before injecting user input. Unexecuted tools
|
||||
// get explicit error results so provider histories never contain orphan calls.
|
||||
for _, tc := range pending {
|
||||
r.Session.AppendContext(ctx, session.ToolCallEntry(tc.ID, tc.Name, tc.Input))
|
||||
r.Session.AppendContext(ctx, session.ToolResultEntry(tc.ID, "", "skipped because user steering superseded this tool call", nil))
|
||||
}
|
||||
r.Session.AppendContext(ctx, entry)
|
||||
if err := r.Session.Flush(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if message.Acknowledge != nil {
|
||||
if err := message.Acknowledge(); err != nil {
|
||||
return true, err
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// MatchesSteering compares a delivered correction with its immutable source,
|
||||
// hydrating and verifying referenced image bytes before comparing semantics.
|
||||
// It is also used by hosts reconciling an interrupted acknowledgement.
|
||||
func MatchesSteering(ctx context.Context, sess *session.Session, message SteeringMessage, prior session.SessionEntry) (bool, error) {
|
||||
if prior.ID != "steering_"+message.ID || prior.Type != session.EntryTypeMessage || prior.Role != "user" {
|
||||
return false, nil
|
||||
}
|
||||
// Reject count/size/digest mismatches before hydration. A small forged JSONL
|
||||
// record can otherwise reference many large blobs and expand without bound.
|
||||
if len(message.Images) > 16 {
|
||||
return false, errors.New("too many steering images")
|
||||
}
|
||||
total := 0
|
||||
for _, img := range message.Images {
|
||||
if len(img.Data) > (32<<20)-total {
|
||||
return false, errors.New("steering images exceed 32 MiB")
|
||||
}
|
||||
total += len(img.Data)
|
||||
}
|
||||
var stored session.MessageData
|
||||
if err := json.Unmarshal(prior.Data, &stored); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if stored.Text != message.Text || len(stored.Images) != len(message.Images) {
|
||||
return false, nil
|
||||
}
|
||||
for i, img := range stored.Images {
|
||||
want := message.Images[i]
|
||||
if img.MimeType != want.MimeType {
|
||||
return false, nil
|
||||
}
|
||||
if img.Reference != nil {
|
||||
if img.Data != "" {
|
||||
return false, errors.New("ambiguous steering image representation")
|
||||
}
|
||||
if err := img.Reference.Validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
digest := sha256.Sum256(want.Data)
|
||||
if img.Reference.Size != int64(len(want.Data)) || img.Reference.SHA256 != hex.EncodeToString(digest[:]) {
|
||||
return false, nil
|
||||
}
|
||||
} else if img.Data != base64.StdEncoding.EncodeToString(want.Data) {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
entries, err := sess.ResolveImages(ctx, []session.SessionEntry{prior})
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
var actual session.MessageData
|
||||
if err := json.Unmarshal(entries[0].Data, &actual); err != nil {
|
||||
return false, err
|
||||
}
|
||||
expected := session.MessageData{Text: message.Text, Images: convertToolResultImages(message.Images)}
|
||||
return reflect.DeepEqual(actual, expected), nil
|
||||
}
|
||||
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user