Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5d4632ffe3 | ||
|
|
a1c4d5d78c | ||
|
|
cc756425e8 | ||
|
|
0972eed3ea | ||
|
|
09c30fe2d5 | ||
|
|
50b791d3b6 | ||
|
|
3b5aadb31f | ||
|
|
897643db18 | ||
|
|
0ccfdb2a24 | ||
|
|
f624e4c7bd | ||
|
|
0ba1b4dbcc | ||
|
|
986c233d39 | ||
|
|
8e92125fb6 | ||
|
|
eb4fa67976 | ||
|
|
445614757b | ||
|
|
c7846eeab9 | ||
|
|
0300af6717 | ||
|
|
152d8b972e | ||
|
|
d3c74e5681 | ||
|
|
d1c63cac56 | ||
|
|
ef3a1d4927 | ||
|
|
2f97b1cf78 | ||
|
|
69f58903eb | ||
|
|
1ec0f9cac3 | ||
|
|
2630d88245 | ||
|
|
a797d446f8 | ||
|
|
ac724d18e1 | ||
|
|
7f0c3fd23d | ||
|
|
a5f21d3a2c | ||
|
|
34435736c5 | ||
|
|
3da8fe8ed3 | ||
|
|
9292731d79 | ||
|
|
04f02c56d6 | ||
|
|
3eb9596ee6 | ||
|
|
275636ed20 | ||
|
|
754721bc30 | ||
|
|
22f4329f44 | ||
|
|
8c9bc2963d | ||
|
|
1752cbf2fb | ||
|
|
e133f97e1e | ||
|
|
373e44b9c7 | ||
|
|
d0cd0989a9 | ||
|
|
385cd26e4b | ||
|
|
79a69e5dce | ||
|
|
e40733145f | ||
|
|
b85ffeac69 | ||
|
|
d6db565d7c | ||
|
|
fb5103fb87 | ||
|
|
01b55a1446 | ||
|
|
7d85074509 | ||
|
|
d7777f7c89 | ||
|
|
1e00916a82 | ||
|
|
083122a81f | ||
|
|
5d5dcd1902 | ||
|
|
34ebfc5e95 | ||
|
|
e1fd4dc689 | ||
|
|
25b2e9163f | ||
|
|
c710ea5a94 | ||
|
|
671c10e89a | ||
|
|
1da0584530 | ||
|
|
7151562d99 | ||
|
|
86ad622144 | ||
|
|
7052a66e38 | ||
|
|
de23ad986a | ||
|
|
27fecf4588 | ||
|
|
87f77c76ba | ||
|
|
7ae944f0eb | ||
|
|
c4750347e6 | ||
|
|
7fa3e75ad1 | ||
|
|
d5e8abf492 | ||
|
|
3064a0da14 | ||
|
|
cf47b2fca8 | ||
|
|
6f0040f606 | ||
|
|
0341628068 | ||
|
|
5d6326981e | ||
|
|
b7cbfc584c | ||
|
|
8f8d75cd06 | ||
|
|
fe71e7b36d | ||
|
|
f35070594f | ||
|
|
67178e018a | ||
|
|
ecdf97ca79 | ||
|
|
b7f4cfcf4a | ||
|
|
35896d215a | ||
|
|
1c6a05c0d8 | ||
|
|
e5c9b5dbb5 |
No files matched your search
@@ -0,0 +1,76 @@
|
||||
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-15-intel]
|
||||
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: Start Docker on hosted macOS
|
||||
if: runner.os == 'macOS'
|
||||
run: |
|
||||
brew install colima docker
|
||||
colima start --runtime docker --cpu 2 --memory 4
|
||||
docker info
|
||||
mkdir -p "$HOME/harness-test-tmp"
|
||||
echo "TMPDIR=$HOME/harness-test-tmp" >> "$GITHUB_ENV"
|
||||
- name: Prepare required Docker fixtures
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker_bin="$(command -v docker)"
|
||||
if [ ! -x /usr/local/bin/docker ]; then
|
||||
sudo ln -s "$docker_bin" /usr/local/bin/docker
|
||||
fi
|
||||
docker version > evidence/docker-version.txt
|
||||
endpoint="$(docker context inspect --format '{{.Endpoints.docker.Host}}')"
|
||||
case "$endpoint" in
|
||||
unix://*) socket="${endpoint#unix://}" ;;
|
||||
*) echo 'Qualification requires a local Unix Docker socket' >&2; exit 1 ;;
|
||||
esac
|
||||
docker pull alpine:3.22 > evidence/alpine-pull.txt
|
||||
docker pull debian:bookworm-slim > evidence/debian-pull.txt
|
||||
image="$(docker image inspect --format '{{.Id}}' alpine:3.22)"
|
||||
bash_image="$(docker image inspect --format '{{.Id}}' debian:bookworm-slim)"
|
||||
python3 scripts/prepare_container_fixtures.py --docker /usr/local/bin/docker \
|
||||
--socket "$socket" --image "$image" --bash-image "$bash_image" \
|
||||
--output "$RUNNER_TEMP/harness-fixtures"
|
||||
cp "$RUNNER_TEMP/harness-fixtures/fixtures.json" evidence/fixtures.json
|
||||
cat "$RUNNER_TEMP/harness-fixtures/fixtures.env" >> "$GITHUB_ENV"
|
||||
- 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/
|
||||
@@ -4,6 +4,7 @@
|
||||
!/developer.md
|
||||
!/examples/*/kb/
|
||||
!/examples/*/kb/*.md
|
||||
/docs/
|
||||
|
||||
# Other prose/document formats
|
||||
*.txt
|
||||
@@ -42,3 +43,6 @@ support-agent-audit.jsonl
|
||||
# Env
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# Keep native qualification setup with its runner.
|
||||
!scripts/QUALIFICATION.md
|
||||
@@ -5,7 +5,7 @@ streaming agent loop, tool registry, session storage, compaction, and
|
||||
token budgeting needed to run a multi-provider agent in production. BYO
|
||||
concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
|
||||
|
||||
> **Status: v0.1.0.** First tagged release. The `runtime` API
|
||||
> **Status: v0.3.9.** Latest tagged release. The `runtime` API
|
||||
> surface may still shift in the v0.x line — pin your version.
|
||||
|
||||
## Why Harness
|
||||
@@ -87,8 +87,8 @@ a lot. The package is optimized for the use cases above, not these.
|
||||
hardened in 1.25. Older toolchains will fail at `go build`.
|
||||
- **An LLM API key**, depending on which provider(s) you wire in:
|
||||
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
|
||||
Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind`
|
||||
at an Ollama endpoint — no key required.
|
||||
LiteLLM/OpenRouter key for those aggregators. For local models
|
||||
(Ollama, LM Studio, etc.), `local.NewLocalProvider` needs no key at all.
|
||||
- **Optional: an MCP server** for `tools/mcp` integrations (any
|
||||
binary that speaks the Model Context Protocol — `npx
|
||||
@modelcontextprotocol/server-filesystem`, etc.).
|
||||
@@ -119,9 +119,11 @@ github.com/sausheong/harness/
|
||||
│ # MemoryProvider/SkillProvider/KnowledgeGraph interfaces
|
||||
├── providers/
|
||||
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
|
||||
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
|
||||
│ ├── openai/ # OpenAI / OpenAI-compatible
|
||||
│ ├── gemini/ # Google Gemini via google.golang.org/genai
|
||||
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
|
||||
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
|
||||
│ ├── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
|
||||
│ └── local/ # Local model server — Ollama, LM Studio, etc. (OpenAI-compatible, no API key)
|
||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||
├── file/ # read_file (with vision), write_file, edit_file
|
||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||
@@ -229,6 +231,9 @@ them via `LoopConfig`:
|
||||
|
||||
`LoopConfig` field values win over env vars when set. Set the field
|
||||
to its zero value (or omit it) to fall back to env, then to defaults.
|
||||
`RuntimeDeps.AgentLoop` supplies shared process defaults;
|
||||
non-zero fields and non-nil hooks in `AgentSpec.Loop` override those
|
||||
defaults for that agent.
|
||||
|
||||
Everything else (provider API keys, model selection, workspace path,
|
||||
skill paths, etc.) is your config's responsibility — harness reads
|
||||
@@ -251,7 +256,7 @@ caller — you own the binary, you own the UI, you own the channel.
|
||||
| 3 | **Tool registry & schemas** | `tool.Registry`; `ToolDefs()` is sorted by name so the request prefix is stable across turns (cache hit) |
|
||||
| 4 | **Tool execution & permissions** | `tool.PermissionChecker` (`Check` + `FilterToolDefs`); concurrency-safe partitioning via `Tool.IsConcurrencySafe` + `LoopConfig.MaxToolConcurrency` (default 10) |
|
||||
| 5 | **Context & compaction** | `compaction.Manager` — summarize-and-splice at a clean user-message boundary; tool-result pruning at request time |
|
||||
| 6 | **System prompt assembly** | `llm.SystemPromptPart` — splits the static cacheable prefix from the per-turn dynamic suffix; provider-side `cache_control` placement is automatic |
|
||||
| 6 | **System prompt assembly** | `llm.SystemPromptPart` — splits the static cacheable prefix (`Runtime.StaticSystemPrompt`, built once) from the per-turn dynamic suffix (date line, KG hint, and `Runtime.DynamicIdentityHint` for any caller-mutable fact — e.g. the active model name after a live switch — that needs fresher recency than the cached prefix gives it); provider-side `cache_control` placement is automatic |
|
||||
| 7 | **Sub-agents / delegation** | `runtime.SubagentResolver` interface + `MaxAgentDepth=3` cap; subagents run as in-process goroutines with their own `Runtime` |
|
||||
| 8 | **Hooks** | `runtime.LifecycleHooks` (on `LoopConfig.Hooks`): `OnUserPromptSubmit`, `OnSessionStart`, `BeforeToolUse`, `AfterToolUse`, `OnStop`. Go callbacks — type-safe, in-process, nil-friendly |
|
||||
| 9 | **MCP** | `tools/mcp` package: `mcp.Connect(ctx, ServerConfig)` adapts an external MCP server's tools as `tool.Tool`s. Declare `AgentSpec.MCPServers` for auto-wiring; `Runtime.Close()` releases sessions |
|
||||
@@ -310,9 +315,11 @@ Deliberately not in scope (numbers from the same conceptual list):
|
||||
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
|
||||
auto-refresh comes for free. Call `Runtime.Close()` to release
|
||||
sessions.
|
||||
- **Four providers, one interface.** Anthropic, OpenAI (and
|
||||
OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in.
|
||||
Adding a fifth is implementing `llm.Provider` (~300 LOC).
|
||||
- **Six providers, one interface.** Anthropic, OpenAI, Gemini, LiteLLM,
|
||||
OpenRouter, and local (Ollama, LM Studio, etc.) ship built-in — LiteLLM,
|
||||
OpenRouter, and local cost none of that ~300 LOC each, since all three
|
||||
are thin constructors over the existing OpenAI-compatible path. Adding
|
||||
a genuinely new wire format is implementing `llm.Provider` (~300 LOC).
|
||||
|
||||
See [`developer.md`](./developer.md) for a step-by-step guide to
|
||||
building agents on top of Harness, including diagrams of the
|
||||
@@ -373,12 +380,12 @@ a real failure.
|
||||
|
||||
## Status
|
||||
|
||||
`v0.1.0` is the first tagged release. The v0.x line follows Go
|
||||
`v0.3.9` is the latest tagged release. The v0.x line follows Go
|
||||
module semver: minor bumps may break API, patch bumps are bug-fix
|
||||
only. Pin your dependency:
|
||||
|
||||
```bash
|
||||
go get github.com/sausheong/harness@v0.1.0
|
||||
go get github.com/sausheong/harness@v0.3.9
|
||||
```
|
||||
|
||||
Likely sources of v0.x churn before a v1.0.0:
|
||||
@@ -397,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")
|
||||
}
|
||||
}
|
||||
+122
-48
@@ -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)
|
||||
}
|
||||
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
|
||||
}
|
||||
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 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)
|
||||
m.inFlightMu.Unlock()
|
||||
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())
|
||||
}
|
||||
+35
-43
@@ -18,25 +18,21 @@ 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 {
|
||||
Provider llm.LLMProvider
|
||||
Model string // bare model id, e.g. "qwen2.5:3b-instruct"
|
||||
Timeout time.Duration // per-call deadline; 0 → 60s
|
||||
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
|
||||
}
|
||||
|
||||
// Summarize sends entries through the configured provider and returns the
|
||||
// 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)
|
||||
}
|
||||
+6
-3
@@ -59,7 +59,8 @@ required pieces are inside `inputs`; everything in `deps` is optional;
|
||||
The four mandatory pieces:
|
||||
|
||||
* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming
|
||||
chat client (Anthropic / OpenAI / Gemini / Qwen, or your own).
|
||||
chat client (Anthropic / OpenAI / Gemini / LiteLLM / OpenRouter /
|
||||
local (Ollama, LM Studio, etc.), or your own).
|
||||
* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM
|
||||
may invoke. Each tool implements `tool.Tool`.
|
||||
* **`session.Session`** (in `RuntimeInputs.Session`) — append-only
|
||||
@@ -387,9 +388,11 @@ Each provider has its own constructor. All return an `llm.LLMProvider`.
|
||||
|--------------|--------------------------------------------------------|-------------------------------------|
|
||||
| Anthropic | `anthropic.NewAnthropicProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI | `openai.NewOpenAIProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "local"\|"openai-compatible")` | for local Ollama, etc. |
|
||||
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
|
||||
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
|
||||
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
|
||||
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
|
||||
| Local | `local.NewLocalProvider(baseURL)` | `baseURL == ""` → `http://localhost:11434/v1` (Ollama's default; override for LM Studio, llama.cpp, vLLM, etc.); no API key |
|
||||
|
||||
The provider you pass on `RuntimeInputs.Provider` only needs to match the
|
||||
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
|
||||
|
||||
@@ -82,6 +82,8 @@ func main() {
|
||||
}
|
||||
defer rt.Close() // no-op here (no MCP), but idiomatic
|
||||
|
||||
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
|
||||
|
||||
// 5. REPL loop.
|
||||
in := bufio.NewScanner(os.Stdin)
|
||||
fmt.Println("harness demo — type a message, blank line to exit")
|
||||
@@ -115,5 +117,4 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
|
||||
}
|
||||
@@ -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:
|
||||
}
|
||||
}
|
||||
+13
-2
@@ -34,8 +34,8 @@ const stripCacheMax = 256
|
||||
// ApplyStripList runs StripFields over each tool's Parameters with the
|
||||
// given field-strip list, preserving input order and accumulating
|
||||
// diagnostics across all tools. The per-provider NormalizeToolSchema
|
||||
// methods (OpenAI, Qwen, Gemini) are thin wrappers over this helper —
|
||||
// only the strip list differs. Anthropic doesn't use this (identity).
|
||||
// methods (OpenAI, Gemini) are thin wrappers over this helper — only the
|
||||
// strip list differs. Anthropic doesn't use this (identity).
|
||||
//
|
||||
// Memoized: identical inputs return cached output without re-walking
|
||||
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
|
||||
@@ -93,6 +93,11 @@ func stripCacheKey(tools []ToolDef, fields []string) string {
|
||||
h.Write([]byte(t.Name))
|
||||
h.Write([]byte("\x02"))
|
||||
h.Write(t.Parameters)
|
||||
if t.CacheControl != nil {
|
||||
h.Write([]byte(t.CacheControl.Type))
|
||||
h.Write([]byte("\x04"))
|
||||
h.Write([]byte(t.CacheControl.TTL))
|
||||
}
|
||||
h.Write([]byte("\x03"))
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
@@ -104,6 +109,12 @@ func cloneToolDefs(in []ToolDef) []ToolDef {
|
||||
}
|
||||
out := make([]ToolDef, len(in))
|
||||
copy(out, in)
|
||||
for i := range out {
|
||||
if in[i].CacheControl != nil {
|
||||
cache := *in[i].CacheControl
|
||||
out[i].CacheControl = &cache
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
@@ -118,3 +118,16 @@ func TestStripFieldsMalformedSchema(t *testing.T) {
|
||||
assert.Equal(t, bad, out)
|
||||
assert.Empty(t, diags)
|
||||
}
|
||||
|
||||
func TestStripCacheKeyIncludesCacheControl(t *testing.T) {
|
||||
base := ToolDef{Name: "lookup", Parameters: json.RawMessage(`{"type":"object"}`)}
|
||||
fiveMinutes := base
|
||||
fiveMinutes.CacheControl = &CacheControl{Type: "ephemeral", TTL: "5m"}
|
||||
oneHour := base
|
||||
oneHour.CacheControl = &CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
assert.NotEqual(t, stripCacheKey([]ToolDef{fiveMinutes}, nil), stripCacheKey([]ToolDef{oneHour}, nil))
|
||||
|
||||
cloned := cloneToolDefs([]ToolDef{oneHour})
|
||||
cloned[0].CacheControl.TTL = "5m"
|
||||
assert.Equal(t, "1h", oneHour.CacheControl.TTL, "cached normalization results must not alias cache metadata")
|
||||
}
|
||||
+126
-26
@@ -17,6 +17,9 @@ const (
|
||||
EventToolCallDone
|
||||
EventDone
|
||||
EventError
|
||||
// EventThinkingBlock is emitted when the model returns an extended-thinking
|
||||
// block. The runtime must echo these back in subsequent turns verbatim.
|
||||
EventThinkingBlock
|
||||
)
|
||||
|
||||
// ImageContent holds image data for multimodal messages.
|
||||
@@ -26,13 +29,26 @@ type ImageContent struct {
|
||||
}
|
||||
|
||||
// Message represents a conversation message.
|
||||
// ThinkingBlock holds an opaque thinking/reasoning block returned by models
|
||||
// that support extended thinking (e.g. Anthropic with thinking enabled,
|
||||
// DeepSeek-v4-pro). The Signature field is the provider-supplied integrity
|
||||
// token that must be echoed back verbatim in subsequent turns.
|
||||
type ThinkingBlock struct {
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
|
||||
IsError bool `json:"is_error,omitempty"` // for tool results
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
|
||||
IsError bool `json:"is_error,omitempty"` // for tool results
|
||||
ThinkingBlocks []ThinkingBlock `json:"thinking_blocks,omitempty"` // echoed back for thinking-mode models
|
||||
// CacheControl requests a cache breakpoint on the final cacheable block of
|
||||
// this logical message. Nil means no explicit breakpoint.
|
||||
CacheControl *CacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
// ToolCall represents a tool invocation requested by the LLM.
|
||||
@@ -44,9 +60,17 @@ type ToolCall struct {
|
||||
|
||||
// ToolDef defines a tool for the LLM.
|
||||
type ToolDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"` // JSON Schema
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"` // JSON Schema
|
||||
CacheControl *CacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
// CacheControl is provider-neutral prompt-cache metadata. Type is currently
|
||||
// "ephemeral"; TTL is empty/"5m" or "1h".
|
||||
type CacheControl struct {
|
||||
Type string `json:"type"`
|
||||
TTL string `json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
// Diagnostic describes a single normalization or clamping event emitted
|
||||
@@ -66,14 +90,15 @@ type SystemPromptPart struct {
|
||||
Text string
|
||||
// Cache requests that the prefix up to and including this part be cached.
|
||||
// Anthropic-only; ignored elsewhere.
|
||||
Cache bool
|
||||
Cache bool
|
||||
CacheControl *CacheControl
|
||||
}
|
||||
|
||||
// ReasoningMode is the unified reasoning/thinking knob across providers.
|
||||
// Zero value (ReasoningOff) means no extended reasoning — safe default
|
||||
// for existing call sites that don't set the field. Each provider maps
|
||||
// this to its native config (Anthropic thinking budget, OpenAI
|
||||
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
|
||||
// reasoning_effort, Gemini ThinkingConfig).
|
||||
type ReasoningMode string
|
||||
|
||||
const (
|
||||
@@ -83,6 +108,31 @@ const (
|
||||
ReasoningHigh ReasoningMode = "high"
|
||||
)
|
||||
|
||||
// NativeReasoningConfig preserves an inbound provider reasoning request when
|
||||
// Harness is used as a protocol proxy. A nil config means the client omitted
|
||||
// the provider's reasoning controls; this is deliberately different from an
|
||||
// explicit disabled config because some models think by default.
|
||||
//
|
||||
// Type is "adaptive", "enabled", or "disabled". BudgetTokens applies to
|
||||
// enabled thinking and Effort is one of "low", "medium", "high", or "max".
|
||||
// Providers that cannot represent the requested semantics must reject the
|
||||
// request instead of silently changing it.
|
||||
type NativeReasoningConfig struct {
|
||||
Type string
|
||||
BudgetTokens int64
|
||||
Effort string
|
||||
Display string
|
||||
// OutputFormat is the provider-native structured-output format object.
|
||||
// It is kept as JSON so a protocol proxy can preserve schemas without
|
||||
// forcing provider-specific types into the portable llm package.
|
||||
OutputFormat json.RawMessage
|
||||
}
|
||||
|
||||
// Enabled reports whether the client explicitly requested reasoning.
|
||||
func (c *NativeReasoningConfig) Enabled() bool {
|
||||
return c != nil && (c.Type == "adaptive" || c.Type == "enabled")
|
||||
}
|
||||
|
||||
// ParseReasoningMode parses a config string into a ReasoningMode.
|
||||
// Accepts "" or "off" for ReasoningOff; "low", "medium", "high" for
|
||||
// the named levels. Case-sensitive. Returns an error for unknown values.
|
||||
@@ -102,13 +152,26 @@ 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 {
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
MaxTokens int
|
||||
Temperature float64
|
||||
SystemPrompt string
|
||||
Route CallRoute `json:"-"`
|
||||
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
MaxTokens int
|
||||
Temperature float64
|
||||
// TemperatureSet distinguishes an omitted sampling parameter from an
|
||||
// explicit zero, which is material when proxying an existing API request.
|
||||
TemperatureSet bool
|
||||
SystemPrompt string
|
||||
// SystemPromptParts, when non-empty, replaces SystemPrompt. Providers
|
||||
// that support caching emit one block per part, attaching cache markers
|
||||
// per Cache flag. Providers that don't support caching concatenate
|
||||
@@ -117,10 +180,19 @@ type ChatRequest struct {
|
||||
// CacheLastMessage requests that the final block of the final user
|
||||
// message also be cache-marked. Anthropic-only; ignored elsewhere.
|
||||
CacheLastMessage bool
|
||||
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
|
||||
// CacheControl enables provider-level automatic prompt caching.
|
||||
CacheControl *CacheControl
|
||||
// SessionID is routing metadata only and is not sent to providers.
|
||||
SessionID string
|
||||
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
|
||||
// NativeReasoning takes precedence over the portable Reasoning knob and
|
||||
// preserves exact inbound proxy semantics, including omitted vs disabled.
|
||||
NativeReasoning *NativeReasoningConfig
|
||||
}
|
||||
|
||||
// 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"`
|
||||
@@ -130,13 +202,29 @@ type Usage struct {
|
||||
|
||||
// ChatEvent is a single streaming event from the LLM.
|
||||
type ChatEvent struct {
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
Usage *Usage
|
||||
Error error
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
ThinkingBlock *ThinkingBlock // populated on EventThinkingBlock
|
||||
Usage *Usage
|
||||
Error error
|
||||
// StopReason carries the provider's terminal stop reason on EventDone
|
||||
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
|
||||
// the provider doesn't report one. StopReasonRefusal is the value the
|
||||
// runtime branches on: Claude Fable 5 safety classifiers decline a
|
||||
// request with HTTP 200 + stop_reason=refusal and empty content —
|
||||
// without surfacing it the turn looks like a silent empty success.
|
||||
StopReason string
|
||||
// StopCategory is the refusal policy category from stop_details
|
||||
// ("cyber", "bio", "reasoning_extraction"); informational only and
|
||||
// may be empty even on a refusal.
|
||||
StopCategory string
|
||||
}
|
||||
|
||||
// StopReasonRefusal is the StopReason value for safety-classifier and
|
||||
// model-initiated refusals (Claude Fable 5+).
|
||||
const StopReasonRefusal = "refusal"
|
||||
|
||||
// ModelInfo describes an available model.
|
||||
type ModelInfo struct {
|
||||
ID string
|
||||
@@ -171,6 +259,18 @@ type NonStreamingProvider interface {
|
||||
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
|
||||
}
|
||||
|
||||
// PromptCachingProvider is an optional capability interface: providers
|
||||
// that implement Anthropic-style explicit prompt caching (cache_control
|
||||
// breakpoints, CacheLastMessage) declare it here. The runtime gates
|
||||
// caching on this capability rather than on the provider's configured
|
||||
// NAME — a user-named provider block ("platformai", "bedrock", any
|
||||
// relay) wrapping an Anthropic-shaped API must still get caching;
|
||||
// matching the name string alone silently disabled it for every
|
||||
// renamed provider.
|
||||
type PromptCachingProvider interface {
|
||||
SupportsPromptCaching() bool
|
||||
}
|
||||
|
||||
// ParseProviderModel splits "provider/model" into (provider, model).
|
||||
// If no slash is present, returns ("", name) and the caller should use a default.
|
||||
func ParseProviderModel(name string) (provider, model string) {
|
||||
@@ -207,10 +307,10 @@ func JoinSystemPromptParts(parts []SystemPromptPart) string {
|
||||
// ProviderOptions holds connection details for creating an LLM provider.
|
||||
// Kept here so consumers can pass a single struct around even though the
|
||||
// concrete provider constructors live in subpackages
|
||||
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
|
||||
// New() takes the relevant fields directly.
|
||||
// (harness/providers/{anthropic,openai,gemini,litellm,openrouter}). Each
|
||||
// subpackage's New() takes the relevant fields directly.
|
||||
type ProviderOptions struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
|
||||
}
|
||||
+26
-6
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
// IsRetryableModelError reports whether err is a transient capacity
|
||||
@@ -14,14 +15,17 @@ import (
|
||||
//
|
||||
// - Anthropic 429 (rate limit) and 529 (overloaded)
|
||||
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
|
||||
// - Gemini 429 (quota/RESOURCE_EXHAUSTED) and 5xx (overloaded/unavailable),
|
||||
// recognized via a typed genai.APIError path (Gemini's error string
|
||||
// "Error 429, ... Status: RESOURCE_EXHAUSTED" does not match the
|
||||
// bounded substring forms, so the typed path is required).
|
||||
//
|
||||
// Anything else (including 4xx auth/validation errors) returns false:
|
||||
// retrying with a different model wouldn't fix the underlying problem.
|
||||
//
|
||||
// Errors from local providers (Ollama, etc.) and Gemini are NOT
|
||||
// classified as retryable here; their failure modes are different
|
||||
// and a model swap rarely helps. Add cases as new providers
|
||||
// accumulate retry experience.
|
||||
// Errors from local providers (Ollama, etc.) are NOT classified as
|
||||
// retryable here; their failure modes are different and a model swap
|
||||
// rarely helps. Add cases as new providers accumulate retry experience.
|
||||
func IsRetryableModelError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
@@ -47,13 +51,29 @@ func IsRetryableModelError(err error) bool {
|
||||
return openaiReqErr.HTTPStatusCode == 429 ||
|
||||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
|
||||
}
|
||||
// genai.APIError.Error() is a value receiver, so the error interface is
|
||||
// satisfied by the value; errors.As targets the value type.
|
||||
var genaiErr genai.APIError
|
||||
if errors.As(err, &genaiErr) {
|
||||
return genaiErr.Code == 429 ||
|
||||
(genaiErr.Code >= 500 && genaiErr.Code < 600)
|
||||
}
|
||||
|
||||
// Last-ditch: substring match on common SDK error wrappers that
|
||||
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
|
||||
// only reached when no typed match found above.
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
|
||||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
// Bounded forms so a bare "429"/"529" inside a request id or unrelated
|
||||
// digits doesn't trigger a retry. Word matches stay as-is (specific).
|
||||
for _, sig := range []string{
|
||||
"status 429", "code: 429", "code:429", " 429 ", "429 too many requests",
|
||||
"status 529", "code: 529", "code:529", " 529 ", "529 overloaded",
|
||||
} {
|
||||
if strings.Contains(msg, sig) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@@ -8,8 +8,26 @@ import (
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/genai"
|
||||
)
|
||||
|
||||
func TestIsRetryable_Gemini429(t *testing.T) {
|
||||
// Mirror genai.APIError's real shape.
|
||||
err := genai.APIError{Code: 429, Message: "Resource has been exhausted (e.g. check quota).", Status: "RESOURCE_EXHAUSTED"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini503(t *testing.T) {
|
||||
err := genai.APIError{Code: 503, Message: "The model is overloaded.", Status: "UNAVAILABLE"}
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryable_Gemini400NotRetryable(t *testing.T) {
|
||||
err := genai.APIError{Code: 400, Message: "Invalid argument", Status: "INVALID_ARGUMENT"}
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
@@ -89,3 +107,13 @@ func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
|
||||
err := errors.New("some other failure")
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_DigitsInRequestIDNotRetryable(t *testing.T) {
|
||||
err := errors.New("request failed: req_abc429def something went wrong")
|
||||
require.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestRetry_RealStatus429Retryable(t *testing.T) {
|
||||
err := errors.New("openai: error, status 429 too many requests")
|
||||
require.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
@@ -28,6 +29,11 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
|
||||
return &AnthropicProvider{client: client}
|
||||
}
|
||||
|
||||
// SupportsPromptCaching implements llm.PromptCachingProvider: the
|
||||
// Anthropic Messages API honours cache_control breakpoints regardless
|
||||
// of what the provider block is named in user config.
|
||||
func (p *AnthropicProvider) SupportsPromptCaching() bool { return true }
|
||||
|
||||
func (p *AnthropicProvider) Models() []llm.ModelInfo {
|
||||
return []llm.ModelInfo{
|
||||
{ID: "claude-sonnet-4-5-20250514", Name: "Claude Sonnet 4.5", Provider: "anthropic"},
|
||||
@@ -55,16 +61,18 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
props = schema.Properties
|
||||
required = schema.Required
|
||||
}
|
||||
tools = append(tools, anthropic.ToolUnionParam{
|
||||
OfTool: &anthropic.ToolParam{
|
||||
Name: t.Name,
|
||||
Description: anthropic.String(t.Description),
|
||||
InputSchema: anthropic.ToolInputSchemaParam{
|
||||
Properties: props,
|
||||
Required: required,
|
||||
},
|
||||
tool := anthropic.ToolParam{
|
||||
Name: t.Name,
|
||||
Description: anthropic.String(t.Description),
|
||||
InputSchema: anthropic.ToolInputSchemaParam{
|
||||
Properties: props,
|
||||
Required: required,
|
||||
},
|
||||
})
|
||||
}
|
||||
if cacheRequested(t.CacheControl) {
|
||||
tool.CacheControl = anthropicCacheControl(t.CacheControl)
|
||||
}
|
||||
tools = append(tools, anthropic.ToolUnionParam{OfTool: &tool})
|
||||
}
|
||||
|
||||
maxTokens := int64(req.MaxTokens)
|
||||
@@ -81,16 +89,94 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
|
||||
MaxTokens: maxTokens,
|
||||
Messages: msgs,
|
||||
}
|
||||
if cacheRequested(req.CacheControl) {
|
||||
params.CacheControl = anthropicCacheControl(req.CacheControl)
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
params.Tools = tools
|
||||
}
|
||||
if sys := buildAnthropicSystem(req); len(sys) > 0 {
|
||||
params.System = sys
|
||||
}
|
||||
if req.Temperature > 0 {
|
||||
if req.TemperatureSet {
|
||||
// Protocol-proxy requests must preserve even an explicit zero. Let the
|
||||
// upstream API reject an incompatible client combination unchanged.
|
||||
params.Temperature = anthropic.Float(req.Temperature)
|
||||
} else if req.Temperature > 0 && !anthropicAdaptiveThinkingOnly(model) {
|
||||
// Portable Harness callers retain the provider's compatibility guard:
|
||||
// adaptive-only models reject sampling parameters while thinking.
|
||||
params.Temperature = anthropic.Float(req.Temperature)
|
||||
}
|
||||
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
|
||||
if native := req.NativeReasoning; native != nil {
|
||||
// Proxy mode preserves exactly what the client requested. Do not infer a
|
||||
// model default, silently remove sampling controls, or enlarge max_tokens:
|
||||
// the upstream should accept or reject the same semantics as a direct call.
|
||||
switch native.Type {
|
||||
case "adaptive":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{
|
||||
Display: anthropic.ThinkingConfigAdaptiveDisplay(native.Display),
|
||||
},
|
||||
}
|
||||
case "enabled":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfEnabled: &anthropic.ThinkingConfigEnabledParam{
|
||||
BudgetTokens: native.BudgetTokens,
|
||||
Display: anthropic.ThinkingConfigEnabledDisplay(native.Display),
|
||||
},
|
||||
}
|
||||
case "disabled":
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
|
||||
}
|
||||
}
|
||||
if native.Effort != "" {
|
||||
params.OutputConfig = anthropic.OutputConfigParam{
|
||||
Effort: anthropic.OutputConfigEffort(native.Effort),
|
||||
}
|
||||
}
|
||||
if len(native.OutputFormat) > 0 {
|
||||
var format anthropic.JSONOutputFormatParam
|
||||
if err := json.Unmarshal(native.OutputFormat, &format); err == nil {
|
||||
params.OutputConfig.Format = format
|
||||
} else {
|
||||
// Decoders are expected to validate this before constructing the
|
||||
// request. Keep this defensive diagnostic for direct Harness callers.
|
||||
slog.Error("invalid native Anthropic output format", "err", err)
|
||||
}
|
||||
}
|
||||
} else if anthropicAdaptiveThinkingOnly(model) {
|
||||
// Fable 5 / Mythos 5 / Opus 4.7+ / Opus 5 / Sonnet 5 reject the
|
||||
// legacy enabled+budget_tokens config (400 "thinking.type.enabled
|
||||
// is not supported"). They take {type:"adaptive"} plus
|
||||
// output_config.effort; sampling params are also removed.
|
||||
if req.Reasoning != llm.ReasoningOff {
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
|
||||
}
|
||||
params.OutputConfig = anthropic.OutputConfigParam{
|
||||
Effort: anthropicEffort(req.Reasoning),
|
||||
}
|
||||
slog.Info("anthropic adaptive thinking",
|
||||
"model", model,
|
||||
"effort", string(anthropicEffort(req.Reasoning)))
|
||||
} else if anthropicThinksByDefault(model) {
|
||||
// Opus 5 and Sonnet 5 think by default when the thinking
|
||||
// param is omitted entirely (unlike Opus 4.7/4.8, Fable 5,
|
||||
// and Mythos, where omitting it means no thinking) — so
|
||||
// expressing "reasoning off" here requires an explicit
|
||||
// {type:"disabled"}. Accepted at effort high or below;
|
||||
// our ReasoningMode never asks for more than high.
|
||||
params.Thinking = anthropic.ThinkingConfigParamUnion{
|
||||
OfDisabled: &anthropic.ThinkingConfigDisabledParam{},
|
||||
}
|
||||
}
|
||||
// Else (Fable 5 / Mythos / Opus 4.7/4.8, reasoning off): omit
|
||||
// thinking entirely. Fable 5 and Mythos reject an explicit
|
||||
// {type:"disabled"} at any effort; Opus 4.7/4.8 already default
|
||||
// to no thinking when the param is omitted, so there's nothing
|
||||
// to disable.
|
||||
} else if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
|
||||
required := cfg.BudgetTokens + 4096
|
||||
if maxTokens < required {
|
||||
maxTokens = required
|
||||
@@ -141,12 +227,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
type pendingTC struct {
|
||||
id string
|
||||
name string
|
||||
inputJSON string // built from input_json_delta events
|
||||
startInput string // captured from content_block_start (proxy fallback)
|
||||
inputJSON strings.Builder // built from input_json_delta events
|
||||
startInput string // captured from content_block_start (proxy fallback)
|
||||
}
|
||||
var pendingTools []pendingTC
|
||||
var currentBlockType string
|
||||
var inputTokens, cacheCreationTokens, cacheReadTokens int64
|
||||
var pendingThinking strings.Builder
|
||||
var pendingThinkingSignature string
|
||||
|
||||
for stream.Next() {
|
||||
event := stream.Current()
|
||||
@@ -163,6 +251,10 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
switch cb.Type {
|
||||
case "text":
|
||||
currentBlockType = "text"
|
||||
case "thinking":
|
||||
currentBlockType = "thinking"
|
||||
pendingThinking.Reset()
|
||||
pendingThinkingSignature = ""
|
||||
case "tool_use":
|
||||
currentBlockType = "tool_use"
|
||||
pending := pendingTC{
|
||||
@@ -195,20 +287,38 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
Type: llm.EventTextDelta,
|
||||
Text: delta.Text,
|
||||
}
|
||||
case "thinking_delta":
|
||||
pendingThinking.WriteString(delta.Thinking)
|
||||
case "signature_delta":
|
||||
pendingThinkingSignature += delta.Signature
|
||||
case "input_json_delta":
|
||||
if len(pendingTools) > 0 {
|
||||
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
|
||||
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
|
||||
}
|
||||
}
|
||||
|
||||
case "content_block_stop":
|
||||
if currentBlockType == "thinking" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventThinkingBlock,
|
||||
ThinkingBlock: &llm.ThinkingBlock{
|
||||
Thinking: pendingThinking.String(),
|
||||
Signature: pendingThinkingSignature,
|
||||
},
|
||||
}
|
||||
pendingThinking.Reset()
|
||||
pendingThinkingSignature = ""
|
||||
}
|
||||
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
|
||||
tc := pendingTools[len(pendingTools)-1]
|
||||
// Index in place rather than copying the element: the
|
||||
// pendingTC holds a strings.Builder, which must not be
|
||||
// copied after first write (vet copylock).
|
||||
tc := &pendingTools[len(pendingTools)-1]
|
||||
// Prefer streamed deltas (canonical Anthropic). Fall
|
||||
// back to start-time input (proxy emitting full input
|
||||
// upfront). Default to "{}" so MCP servers receive a
|
||||
// valid empty-args envelope rather than null/empty.
|
||||
inp := tc.inputJSON
|
||||
inp := tc.inputJSON.String()
|
||||
if inp == "" {
|
||||
inp = tc.startInput
|
||||
}
|
||||
@@ -227,7 +337,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
currentBlockType = ""
|
||||
|
||||
case "message_delta":
|
||||
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
|
||||
stopReason := string(event.Delta.StopReason)
|
||||
stopCategory := string(event.Delta.StopDetails.Category)
|
||||
if stopReason == llm.StopReasonRefusal {
|
||||
slog.Warn("anthropic refusal stop reason",
|
||||
"category", stopCategory,
|
||||
"output_tokens", event.Usage.OutputTokens)
|
||||
}
|
||||
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
|
||||
slog.Info("anthropic stream usage",
|
||||
"input_tokens", inputTokens,
|
||||
"output_tokens", event.Usage.OutputTokens,
|
||||
@@ -237,11 +354,13 @@ 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),
|
||||
},
|
||||
StopReason: stopReason,
|
||||
StopCategory: stopCategory,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,7 +368,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
// Final event — nothing extra to emit
|
||||
|
||||
case "error":
|
||||
slog.Error("anthropic stream error", "event", event.Type)
|
||||
// The SDK surfaces error detail via stream.Err() (handled after
|
||||
// the loop); this in-band branch must not be a silent no-op —
|
||||
// emit an EventError so the runtime treats it as a failure.
|
||||
slog.Error("anthropic stream error event", "event", event.Type)
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventError,
|
||||
Error: fmt.Errorf("anthropic stream error event"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,8 +397,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
|
||||
// mid-flight; the partial output of the failed stream is discarded so
|
||||
// the prompt cache prefix on the next turn stays byte-identical.
|
||||
//
|
||||
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
|
||||
// matches the streaming path which also doesn't emit thinking deltas.
|
||||
// Thinking blocks are surfaced as EventThinkingBlock events so the runtime
|
||||
// can store and echo them back in subsequent turns.
|
||||
// Tool-use input is converted to JSON via the SDK's RawJSON field.
|
||||
func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
params := p.buildMessageParams(req)
|
||||
@@ -286,6 +412,16 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
|
||||
defer close(events)
|
||||
for _, block := range msg.Content {
|
||||
switch block.Type {
|
||||
case "thinking":
|
||||
if block.Thinking != "" || block.Signature != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventThinkingBlock,
|
||||
ThinkingBlock: &llm.ThinkingBlock{
|
||||
Thinking: block.Thinking,
|
||||
Signature: block.Signature,
|
||||
},
|
||||
}
|
||||
}
|
||||
case "text":
|
||||
if block.Text != "" {
|
||||
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: block.Text}
|
||||
@@ -321,11 +457,13 @@ 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),
|
||||
},
|
||||
StopReason: string(msg.StopReason),
|
||||
StopCategory: string(msg.StopDetails.Category),
|
||||
}
|
||||
}()
|
||||
return events, nil
|
||||
@@ -374,6 +512,64 @@ func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.Reasoning
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicAdaptiveThinkingOnly reports whether the model accepts ONLY
|
||||
// adaptive thinking: Claude Fable 5, Claude Mythos 5, Opus 4.7+, Opus 5,
|
||||
// and Sonnet 5. On these the legacy {type:"enabled", budget_tokens:N}
|
||||
// config and sampling params (temperature/top_p/top_k) return HTTP 400.
|
||||
// Matched by substring so gateway model-group names
|
||||
// (claude-fable-5-global) and Bedrock-style IDs
|
||||
// (us.anthropic.claude-opus-4-8-v1) are covered.
|
||||
func anthropicAdaptiveThinkingOnly(model string) bool {
|
||||
adaptiveOnly := []string{
|
||||
"claude-fable-5",
|
||||
"claude-mythos-5",
|
||||
"claude-mythos-preview",
|
||||
"claude-opus-4-7",
|
||||
"claude-opus-4-8",
|
||||
"claude-opus-4-9", // future-proof within the 4.x line
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, marker := range adaptiveOnly {
|
||||
if strings.Contains(model, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// anthropicThinksByDefault reports whether the model runs adaptive
|
||||
// thinking when the thinking param is omitted entirely — true for Opus 5
|
||||
// and Sonnet 5 only. Fable 5, Mythos, and Opus 4.7/4.8 do NOT think by
|
||||
// default (omitting thinking means no thinking on those), so expressing
|
||||
// "reasoning off" there is a no-op omission; on Opus 5 / Sonnet 5 it
|
||||
// requires an explicit {type:"disabled"} or the model thinks anyway.
|
||||
func anthropicThinksByDefault(model string) bool {
|
||||
thinksByDefault := []string{
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, marker := range thinksByDefault {
|
||||
if strings.Contains(model, marker) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
|
||||
// for adaptive-thinking-only models.
|
||||
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
|
||||
switch mode {
|
||||
case llm.ReasoningLow:
|
||||
return anthropic.OutputConfigEffortLow
|
||||
case llm.ReasoningMedium:
|
||||
return anthropic.OutputConfigEffortMedium
|
||||
default:
|
||||
return anthropic.OutputConfigEffortHigh
|
||||
}
|
||||
}
|
||||
|
||||
// anthropicSupportsThinking returns true for Claude models that accept
|
||||
// extended thinking. Conservative — unknown IDs default to true so we
|
||||
// let the API decide rather than silently drop a knob the user set.
|
||||
@@ -414,7 +610,11 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
i-- // un-consume; outer loop will re-process
|
||||
break
|
||||
}
|
||||
blocks = append(blocks, buildToolResultBlock(cur))
|
||||
block := buildToolResultBlock(cur)
|
||||
if cacheRequested(cur.CacheControl) {
|
||||
setCacheControlOnBlock(&block, cur.CacheControl)
|
||||
}
|
||||
blocks = append(blocks, block)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
|
||||
} else if len(m.Images) > 0 {
|
||||
@@ -426,12 +626,29 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
if m.Content != "" {
|
||||
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
|
||||
}
|
||||
if cacheRequested(m.CacheControl) && len(blocks) > 0 {
|
||||
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
|
||||
} else {
|
||||
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
|
||||
block := anthropic.NewTextBlock(m.Content)
|
||||
if cacheRequested(m.CacheControl) {
|
||||
setCacheControlOnBlock(&block, m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewUserMessage(block))
|
||||
}
|
||||
case "assistant":
|
||||
var blocks []anthropic.ContentBlockParamUnion
|
||||
// Thinking blocks must come first, before text and tool_use.
|
||||
for _, tb := range m.ThinkingBlocks {
|
||||
blocks = append(blocks, anthropic.ContentBlockParamUnion{
|
||||
OfThinking: &anthropic.ThinkingBlockParam{
|
||||
Type: "thinking",
|
||||
Thinking: tb.Thinking,
|
||||
Signature: tb.Signature,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
|
||||
}
|
||||
@@ -443,6 +660,9 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, input, tc.Name))
|
||||
}
|
||||
if len(blocks) > 0 {
|
||||
if cacheRequested(m.CacheControl) {
|
||||
setCacheControlOnBlock(&blocks[len(blocks)-1], m.CacheControl)
|
||||
}
|
||||
msgs = append(msgs, anthropic.NewAssistantMessage(blocks...))
|
||||
}
|
||||
}
|
||||
@@ -453,7 +673,7 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
if cacheLast && len(msgs) > 0 {
|
||||
tail := &msgs[len(msgs)-1]
|
||||
if len(tail.Content) > 0 {
|
||||
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
|
||||
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1], nil)
|
||||
}
|
||||
}
|
||||
return msgs
|
||||
@@ -465,8 +685,8 @@ func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.Messag
|
||||
// so we mutate the variant struct directly. Variants other than text /
|
||||
// tool_result / image / tool_use are out of scope; the runtime never
|
||||
// produces them as the tail of a user message.
|
||||
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
|
||||
cc := anthropic.NewCacheControlEphemeralParam()
|
||||
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion, cache *llm.CacheControl) {
|
||||
cc := anthropicCacheControl(cache)
|
||||
switch {
|
||||
case block.OfText != nil:
|
||||
block.OfText.CacheControl = cc
|
||||
@@ -528,8 +748,8 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
|
||||
continue
|
||||
}
|
||||
b := anthropic.TextBlockParam{Text: p.Text}
|
||||
if p.Cache {
|
||||
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
|
||||
if p.Cache || cacheRequested(p.CacheControl) {
|
||||
b.CacheControl = anthropicCacheControl(p.CacheControl)
|
||||
}
|
||||
blocks = append(blocks, b)
|
||||
}
|
||||
@@ -543,3 +763,15 @@ func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func cacheRequested(cache *llm.CacheControl) bool {
|
||||
return cache != nil && (cache.Type == "" || cache.Type == "ephemeral")
|
||||
}
|
||||
|
||||
func anthropicCacheControl(cache *llm.CacheControl) anthropic.CacheControlEphemeralParam {
|
||||
cc := anthropic.NewCacheControlEphemeralParam()
|
||||
if cache != nil && cache.TTL != "" {
|
||||
cc.TTL = anthropic.CacheControlEphemeralTTL(cache.TTL)
|
||||
}
|
||||
return cc
|
||||
}
|
||||
@@ -6,12 +6,13 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// helper: extract tool_use IDs (in order) from an assistant MessageParam.
|
||||
@@ -234,6 +235,65 @@ func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
|
||||
require.Empty(t, string(got[1].CacheControl.Type), "second block must not be cache-marked")
|
||||
}
|
||||
|
||||
func TestAnthropicCacheControlPreservesTTLAtEveryWireLocation(t *testing.T) {
|
||||
cache1h := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-test",
|
||||
MaxTokens: 10,
|
||||
CacheControl: cache1h,
|
||||
SystemPromptParts: []llm.SystemPromptPart{
|
||||
{Text: "stable system", CacheControl: cache1h},
|
||||
},
|
||||
Tools: []llm.ToolDef{{
|
||||
Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache1h,
|
||||
}},
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache1h}},
|
||||
})
|
||||
|
||||
require.Equal(t, "ephemeral", string(params.CacheControl.Type))
|
||||
require.Equal(t, "1h", string(params.CacheControl.TTL))
|
||||
require.Len(t, params.System, 1)
|
||||
require.Equal(t, "1h", string(params.System[0].CacheControl.TTL))
|
||||
require.Len(t, params.Tools, 1)
|
||||
require.NotNil(t, params.Tools[0].OfTool)
|
||||
require.Equal(t, "1h", string(params.Tools[0].OfTool.CacheControl.TTL))
|
||||
require.Len(t, params.Messages, 1)
|
||||
messageCache := params.Messages[0].Content[0].GetCacheControl()
|
||||
require.NotNil(t, messageCache)
|
||||
require.Equal(t, "1h", string(messageCache.TTL))
|
||||
}
|
||||
|
||||
func TestAnthropicCacheControlAppearsOnActualHTTPRequest(t *testing.T) {
|
||||
bodyCh := make(chan map[string]any, 1)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
|
||||
bodyCh <- body
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_1\",\"type\":\"message\",\"role\":\"assistant\",\"content\":[],\"model\":\"claude-test\",\"usage\":{\"input_tokens\":1,\"output_tokens\":0}}}\n\nevent: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":1}}\n\nevent: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cache := &llm.CacheControl{Type: "ephemeral", TTL: "1h"}
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
events, err := p.ChatStream(context.Background(), llm.ChatRequest{
|
||||
Model: "claude-test", MaxTokens: 10, CacheControl: cache,
|
||||
SystemPromptParts: []llm.SystemPromptPart{{Text: "system", CacheControl: cache}},
|
||||
Tools: []llm.ToolDef{{Name: "lookup", Parameters: json.RawMessage(`{"type":"object","properties":{}}`), CacheControl: cache}},
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello", CacheControl: cache}},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
for range events {
|
||||
}
|
||||
body := <-bodyCh
|
||||
require.Equal(t, "1h", body["cache_control"].(map[string]any)["ttl"])
|
||||
require.Equal(t, "1h", body["system"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
require.Equal(t, "1h", body["tools"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
message := body["messages"].([]any)[0].(map[string]any)
|
||||
require.Equal(t, "1h", message["content"].([]any)[0].(map[string]any)["cache_control"].(map[string]any)["ttl"])
|
||||
}
|
||||
|
||||
func TestAnthropicSystemPromptStringFallback(t *testing.T) {
|
||||
got := buildAnthropicSystem(llm.ChatRequest{SystemPrompt: "legacy"})
|
||||
require.Len(t, got, 1)
|
||||
@@ -364,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
|
||||
@@ -521,3 +581,281 @@ data: {"type":"message_stop"}
|
||||
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
|
||||
"argument-less tool call must serialize as {} so MCP transport accepts it")
|
||||
}
|
||||
|
||||
// --- Adaptive-thinking model mapping ---------------------------------
|
||||
//
|
||||
// Claude Fable 5, Claude Mythos 5, Opus 4.7/4.8, Opus 5, and Sonnet 5
|
||||
// reject the legacy thinking config: `thinking: {type:"enabled",
|
||||
// budget_tokens:N}` returns HTTP 400 ("thinking.type.enabled is not
|
||||
// supported for this model"). They also removed sampling params —
|
||||
// sending `temperature` is a 400. For these models the provider must
|
||||
// emit `thinking: {type:"adaptive"}` plus `output_config.effort`, and
|
||||
// drop temperature.
|
||||
//
|
||||
// Opus 5 and Sonnet 5 additionally think BY DEFAULT when the thinking
|
||||
// param is omitted — unlike Fable 5/Mythos/Opus 4.7/4.8, where omitting
|
||||
// it means no thinking. So "reasoning off" on Opus 5/Sonnet 5 must send
|
||||
// an explicit {type:"disabled"} rather than omit the param.
|
||||
|
||||
func wireJSON(t *testing.T, p *AnthropicProvider, req llm.ChatRequest) string {
|
||||
t.Helper()
|
||||
params := p.buildMessageParams(req)
|
||||
b, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
models := []string{
|
||||
"claude-fable-5",
|
||||
"claude-fable-5-global", // LiteLLM / gateway model-group names
|
||||
"claude-mythos-5",
|
||||
"claude-opus-4-7",
|
||||
"claude-opus-4-8",
|
||||
"us.anthropic.claude-opus-4-8-v1", // Bedrock-style ID
|
||||
"claude-opus-5",
|
||||
"claude-sonnet-5",
|
||||
}
|
||||
for _, model := range models {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Reasoning: llm.ReasoningHigh,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`,
|
||||
"adaptive-only models must send thinking.type=adaptive")
|
||||
assert.NotContains(t, got, `"budget_tokens"`,
|
||||
"budget_tokens is rejected with 400 on adaptive-only models")
|
||||
assert.Contains(t, got, `"output_config":{"effort":"high"}`,
|
||||
"reasoning mode maps to output_config.effort on adaptive-only models")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_EffortMapping(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
cases := []struct {
|
||||
mode llm.ReasoningMode
|
||||
effort string
|
||||
}{
|
||||
{llm.ReasoningLow, "low"},
|
||||
{llm.ReasoningMedium, "medium"},
|
||||
{llm.ReasoningHigh, "high"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(string(c.mode), func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-opus-4-8",
|
||||
Reasoning: c.mode,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"output_config":{"effort":"`+c.effort+`"}`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-fable-5",
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.NotContains(t, got, `"thinking"`,
|
||||
"reasoning off must omit the thinking param entirely — Fable 5 "+
|
||||
"rejects an explicit {type:disabled} with 400")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
}
|
||||
|
||||
func TestNativeReasoningConfigPreservesInboundProxySemantics(t *testing.T) {
|
||||
p := &AnthropicProvider{}
|
||||
tests := []struct {
|
||||
name string
|
||||
config *llm.NativeReasoningConfig
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "adaptive effort max",
|
||||
config: &llm.NativeReasoningConfig{Type: "adaptive", Effort: "max"},
|
||||
want: []string{`"thinking":{"type":"adaptive"}`, `"output_config":{"effort":"max"}`},
|
||||
},
|
||||
{
|
||||
name: "enabled exact budget",
|
||||
config: &llm.NativeReasoningConfig{Type: "enabled", BudgetTokens: 3072},
|
||||
want: []string{`"thinking":{"budget_tokens":3072,"type":"enabled"}`},
|
||||
},
|
||||
{
|
||||
name: "explicit disabled",
|
||||
config: &llm.NativeReasoningConfig{Type: "disabled"},
|
||||
want: []string{`"thinking":{"type":"disabled"}`},
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-opus-4-8-global", MaxTokens: 2048,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello"}},
|
||||
NativeReasoning: test.config,
|
||||
})
|
||||
raw, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
for _, want := range test.want {
|
||||
assert.Contains(t, string(raw), want)
|
||||
}
|
||||
assert.Contains(t, string(raw), `"max_tokens":2048`, "proxy mode must not enlarge max_tokens")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNativeProxyPreservesExplicitZeroTemperature(t *testing.T) {
|
||||
p := &AnthropicProvider{}
|
||||
params := p.buildMessageParams(llm.ChatRequest{
|
||||
Model: "claude-opus-4-8-global", MaxTokens: 32, Temperature: 0, TemperatureSet: true,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hello"}},
|
||||
})
|
||||
raw, err := json.Marshal(params)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(raw), `"temperature":0`)
|
||||
}
|
||||
|
||||
func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
for _, model := range []string{
|
||||
"claude-fable-5", "claude-opus-4-7", "claude-opus-4-8",
|
||||
"claude-opus-5", "claude-sonnet-5",
|
||||
} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Temperature: 0.7,
|
||||
Reasoning: llm.ReasoningMedium,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.NotContains(t, got, `"temperature"`,
|
||||
"sampling params are removed on these models — sending temperature is a 400")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled reproduces
|
||||
// the bug this test guards against: Opus 5 and Sonnet 5 think adaptively
|
||||
// when `thinking` is omitted (unlike every other adaptive-only model),
|
||||
// so simply omitting the param to express "reasoning off" leaves
|
||||
// thinking on. The provider must send an explicit {type:"disabled"}.
|
||||
func TestOpus5AndSonnet5_ThinkByDefault_ReasoningOffSendsDisabled(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
for _, model := range []string{"claude-opus-5", "claude-sonnet-5"} {
|
||||
t.Run(model, func(t *testing.T) {
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: model,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"thinking":{"type":"disabled"}`,
|
||||
"Opus 5/Sonnet 5 think by default when thinking is omitted; "+
|
||||
"reasoning off must send an explicit disabled config")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
|
||||
p := NewAnthropicProvider("test-key", "")
|
||||
got := wireJSON(t, p, llm.ChatRequest{
|
||||
Model: "claude-sonnet-4-5",
|
||||
Reasoning: llm.ReasoningHigh,
|
||||
Messages: []llm.Message{{Role: "user", Content: "hi"}},
|
||||
})
|
||||
assert.Contains(t, got, `"budget_tokens":16384`,
|
||||
"pre-4.7 models keep the enabled+budget_tokens config")
|
||||
assert.NotContains(t, got, `"output_config"`)
|
||||
}
|
||||
|
||||
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
|
||||
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
|
||||
// stop_reason=refusal + stop_details.category, and NO content blocks.
|
||||
// The parser previously dropped stop_reason entirely, so the runtime
|
||||
// saw an empty-but-successful turn and the user saw a silent nothing.
|
||||
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done, "stream must emit EventDone")
|
||||
assert.Equal(t, "refusal", done.StopReason)
|
||||
assert.Equal(t, "bio", done.StopCategory)
|
||||
}
|
||||
|
||||
// Normal end_turn streams must carry the stop reason too (and no category).
|
||||
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
|
||||
const sseBody = `event: message_start
|
||||
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
event: content_block_delta
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
|
||||
|
||||
event: content_block_stop
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
event: message_delta
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
|
||||
|
||||
event: message_stop
|
||||
data: {"type":"message_stop"}
|
||||
|
||||
`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(sseBody))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewAnthropicProvider("test-key", srv.URL)
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
|
||||
require.NoError(t, err)
|
||||
|
||||
var done *llm.ChatEvent
|
||||
for ev := range stream {
|
||||
if ev.Type == llm.EventDone {
|
||||
ev := ev
|
||||
done = &ev
|
||||
}
|
||||
}
|
||||
require.NotNil(t, done)
|
||||
assert.Equal(t, "end_turn", done.StopReason)
|
||||
assert.Empty(t, done.StopCategory)
|
||||
}
|
||||
|
||||
func TestAnthropicInputAccumulation(t *testing.T) {
|
||||
var b strings.Builder
|
||||
for _, part := range []string{`{"a"`, `:1`, `}`} {
|
||||
b.WriteString(part)
|
||||
}
|
||||
require.Equal(t, `{"a":1}`, b.String())
|
||||
}
|
||||
+54
-10
@@ -2,10 +2,15 @@ package gemini
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"google.golang.org/genai"
|
||||
"github.com/sausheong/harness/llm"
|
||||
@@ -182,6 +187,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
go func() {
|
||||
defer close(events)
|
||||
|
||||
var lastUsage *llm.Usage
|
||||
|
||||
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
|
||||
if err != nil {
|
||||
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
||||
@@ -189,13 +196,9 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
}
|
||||
|
||||
if resp.UsageMetadata != nil {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventDone,
|
||||
Usage: &llm.Usage{
|
||||
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
|
||||
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
|
||||
},
|
||||
}
|
||||
lastUsage = updateUsage(lastUsage,
|
||||
int(resp.UsageMetadata.PromptTokenCount),
|
||||
int(resp.UsageMetadata.CandidatesTokenCount))
|
||||
}
|
||||
|
||||
for _, cand := range resp.Candidates {
|
||||
@@ -215,9 +218,25 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
if err != nil {
|
||||
argsJSON = []byte("{}")
|
||||
}
|
||||
// Gemini's FunctionCall.ID is optional and is
|
||||
// frequently empty (single, non-parallel calls
|
||||
// commonly omit it). Falling back to fc.Name is
|
||||
// wrong on two counts: it isn't a valid
|
||||
// provider-neutral tool-call ID shape, and it
|
||||
// isn't unique — two calls to the same tool in
|
||||
// one turn, or the same tool called again later
|
||||
// in the conversation (routine for a coding
|
||||
// agent re-reading files), collide on the same
|
||||
// ID. When that history is later replayed to
|
||||
// Anthropic on a routing switch, duplicate
|
||||
// tool_use ids across the conversation are
|
||||
// rejected with a 400. Mint a synthetic
|
||||
// toolu_-shaped ID instead, matching Anthropic's
|
||||
// own ID shape so a later replay to Anthropic
|
||||
// looks like any other tool_use id.
|
||||
id := fc.ID
|
||||
if id == "" {
|
||||
id = fc.Name
|
||||
id = syntheticToolCallID()
|
||||
}
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallStart,
|
||||
@@ -240,12 +259,37 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
}
|
||||
|
||||
// Ensure a Done event is always sent
|
||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
|
||||
}()
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
|
||||
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
|
||||
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
|
||||
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
|
||||
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
|
||||
}
|
||||
|
||||
// syntheticToolCallID mints a unique, Anthropic-shaped tool-call ID
|
||||
// ("toolu_" + 16 hex chars) for Gemini function calls that arrive with
|
||||
// no ID of their own. Uniqueness (not just shape) is the point: a
|
||||
// name-based fallback collides whenever the same tool is called more
|
||||
// than once in a conversation, which produces duplicate tool_use ids if
|
||||
// that history is later replayed to Anthropic. Falls back to a
|
||||
// time+PID-derived suffix if crypto/rand is unavailable — still unique
|
||||
// within one process lifetime, which is all a single conversation needs.
|
||||
func syntheticToolCallID() string {
|
||||
b := make([]byte, 8)
|
||||
if _, err := rand.Read(b); err == nil {
|
||||
return "toolu_" + hex.EncodeToString(b)
|
||||
}
|
||||
mix := uint64(time.Now().UnixNano()) ^ uint64(os.Getpid())
|
||||
binary.BigEndian.PutUint64(b, mix)
|
||||
return "toolu_" + hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
|
||||
// subset" rejects. This is the broadest strip set across the four
|
||||
// providers — most of the cross-provider portability gap shows up here.
|
||||
@@ -295,7 +339,7 @@ func geminiSupportsThinking(model string) bool {
|
||||
}
|
||||
|
||||
// geminiResolveSystemPrompt returns the effective system prompt string,
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI
|
||||
// resolution path but the per-provider helper avoids importing the
|
||||
// genai SDK in test code.
|
||||
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package gemini
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -24,3 +25,31 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
|
||||
got := geminiResolveSystemPrompt(llm.ChatRequest{})
|
||||
require.Equal(t, "", got)
|
||||
}
|
||||
|
||||
func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
|
||||
var last *llm.Usage
|
||||
last = updateUsage(last, 10, 5)
|
||||
last = updateUsage(last, 20, 9) // final cumulative
|
||||
require.NotNil(t, last)
|
||||
require.Equal(t, 20, last.InputTokens)
|
||||
require.Equal(t, 9, last.OutputTokens)
|
||||
}
|
||||
|
||||
// TestSyntheticToolCallID_UniqueAndAnthropicShaped guards against the bug
|
||||
// where an empty Gemini FunctionCall.ID fell back to the function name.
|
||||
// That fallback isn't a valid provider-neutral tool-call ID shape, and
|
||||
// worse, it isn't unique: two calls to the same tool (parallel calls, or
|
||||
// the same tool called again later in a conversation — routine for a
|
||||
// coding agent re-reading files) collided on one ID. When that history
|
||||
// was later replayed to Anthropic on a routing switch, the duplicate
|
||||
// tool_use ids were rejected with a 400.
|
||||
func TestSyntheticToolCallID_UniqueAndAnthropicShaped(t *testing.T) {
|
||||
seen := make(map[string]bool)
|
||||
for range 100 {
|
||||
id := syntheticToolCallID()
|
||||
require.True(t, strings.HasPrefix(id, "toolu_"),
|
||||
"synthetic ID must be shaped like an Anthropic tool_use id so a later replay to Anthropic is accepted")
|
||||
require.False(t, seen[id], "synthetic IDs must be unique across calls in the same process")
|
||||
seen[id] = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Package litellm provides an llm.LLMProvider for a self-hosted LiteLLM
|
||||
// proxy. LiteLLM speaks the OpenAI chat-completions wire format and
|
||||
// itself routes to dozens of underlying vendors, so this package adds no
|
||||
// new request/stream-translation code of its own — it's a thin
|
||||
// constructor around harness's existing OpenAI-compatible support.
|
||||
package litellm
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// NewLiteLLMProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, a self-hosted LiteLLM proxy endpoint. Unlike OpenRouter,
|
||||
// LiteLLM has no public default endpoint — callers must supply a
|
||||
// non-empty baseURL (cmd/hand's buildProvider, for example, rejects an
|
||||
// empty one with a clear error before ever reaching here).
|
||||
// kind="openai-compatible" suppresses reasoning_effort, since not every
|
||||
// model LiteLLM routes a request to is guaranteed to support it.
|
||||
func NewLiteLLMProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package litellm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// TestNewLiteLLMProvider_HitsGivenBaseURL confirms the provider actually
|
||||
// targets the baseURL it was constructed with, and that a streamed
|
||||
// response comes back through it — not re-testing OpenAI wire-format
|
||||
// translation itself (already covered by providers/openai's own tests),
|
||||
// just that this thin constructor wires the base URL through correctly.
|
||||
func TestNewLiteLLMProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewLiteLLMProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// Package local provides an llm.LLMProvider for a locally-served model —
|
||||
// Ollama, LM Studio, llama.cpp's server, vLLM, or anything else exposing
|
||||
// an OpenAI-compatible endpoint on the caller's own machine or network.
|
||||
// Like providers/litellm and providers/openrouter, this adds no new
|
||||
// request/stream-translation code of its own — it's a thin constructor
|
||||
// around harness's existing OpenAI-compatible support.
|
||||
package local
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// DefaultBaseURL is used when NewLocalProvider is called with an empty
|
||||
// baseURL. It's Ollama's endpoint specifically — the most common local
|
||||
// server — but any other one works the same way via an explicit baseURL.
|
||||
const DefaultBaseURL = "http://localhost:11434/v1"
|
||||
|
||||
// NewLocalProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, or DefaultBaseURL when baseURL is empty. No API key is
|
||||
// needed — local servers generally don't authenticate requests.
|
||||
// kind="local" suppresses reasoning_effort, since locally-served models
|
||||
// don't uniformly support it, and keeps retryable-error classification
|
||||
// from treating a down local server the way it would a hosted API
|
||||
// outage (see llm/retry.go).
|
||||
func NewLocalProvider(baseURL string) *openai.OpenAIProvider {
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultBaseURL
|
||||
}
|
||||
return openai.NewOpenAIProviderWithKind("", baseURL, "local")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package local
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestDefaultBaseURL(t *testing.T) {
|
||||
require.Equal(t, "http://localhost:11434/v1", DefaultBaseURL)
|
||||
}
|
||||
|
||||
// TestNewLocalProvider_HitsGivenBaseURL confirms a custom baseURL
|
||||
// overrides the default and is actually what the provider talks to.
|
||||
func TestNewLocalProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewLocalProvider(srv.URL + "/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
|
||||
// TestNewLocalProvider_EmptyBaseURLDoesNotPanic confirms the empty ->
|
||||
// DefaultBaseURL fallback path constructs a usable provider (the actual
|
||||
// outbound host isn't inspectable from outside the openai package —
|
||||
// OpenAIProvider's client config is unexported — so this checks the
|
||||
// fallback doesn't panic or return nil, and DefaultBaseURL's own value
|
||||
// is asserted separately above).
|
||||
func TestNewLocalProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
|
||||
p := NewLocalProvider("")
|
||||
require.NotNil(t, p)
|
||||
}
|
||||
+38
-19
@@ -271,11 +271,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
defer stream.Close()
|
||||
|
||||
// Track tool calls being built up across deltas
|
||||
type pendingTC struct {
|
||||
id string
|
||||
name string
|
||||
argsJSON string
|
||||
}
|
||||
toolCalls := make(map[int]*pendingTC)
|
||||
|
||||
var lastUsage *llm.Usage
|
||||
@@ -337,25 +332,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
}
|
||||
}
|
||||
if tc.Function.Arguments != "" {
|
||||
pending.argsJSON += tc.Function.Arguments
|
||||
pending.args.WriteString(tc.Function.Arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// Finish reason
|
||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||
// Emit completed tool calls
|
||||
for _, tc := range toolCalls {
|
||||
if tc.name != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallDone,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: tc.id,
|
||||
Name: tc.name,
|
||||
Input: json.RawMessage(tc.argsJSON),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
emitToolCalls(events, toolCalls)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -366,6 +349,42 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// pendingTC accumulates a single streamed tool call across deltas. The
|
||||
// streamed tool-call index is the map key in toolCalls; the id, name, and
|
||||
// arguments arrive in separate chunks.
|
||||
type pendingTC struct {
|
||||
id string
|
||||
name string
|
||||
args strings.Builder
|
||||
}
|
||||
|
||||
// emitToolCalls sends EventToolCallDone for each completed tool call in
|
||||
// ascending index order. The map key is the streamed tool-call index;
|
||||
// iterating in order keeps the assistant message's tool_use block order
|
||||
// deterministic across turns so the prompt cache stays warm.
|
||||
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
|
||||
maxIdx := -1
|
||||
for idx := range toolCalls {
|
||||
if idx > maxIdx {
|
||||
maxIdx = idx
|
||||
}
|
||||
}
|
||||
for idx := 0; idx <= maxIdx; idx++ {
|
||||
tc, ok := toolCalls[idx]
|
||||
if !ok || tc.name == "" {
|
||||
continue
|
||||
}
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallDone,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: tc.id,
|
||||
Name: tc.name,
|
||||
Input: json.RawMessage(tc.args.String()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
|
||||
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
|
||||
var openaiUnsupportedFields = []string{"$ref", "definitions"}
|
||||
|
||||
@@ -73,3 +73,22 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
|
||||
require.GreaterOrEqual(t, len(captured.Messages), 1)
|
||||
require.Equal(t, "new", captured.Messages[0].Content)
|
||||
}
|
||||
|
||||
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
||||
mk := func(id, name string) *pendingTC {
|
||||
p := &pendingTC{id: id, name: name}
|
||||
p.args.WriteString("{}")
|
||||
return p
|
||||
}
|
||||
toolCalls := map[int]*pendingTC{2: mk("c", "third"), 0: mk("a", "first"), 1: mk("b", "second")}
|
||||
ch := make(chan llm.ChatEvent, 10)
|
||||
emitToolCalls(ch, toolCalls)
|
||||
close(ch)
|
||||
var ids []string
|
||||
for ev := range ch {
|
||||
if ev.Type == llm.EventToolCallDone {
|
||||
ids = append(ids, ev.ToolCall.ID)
|
||||
}
|
||||
}
|
||||
require.Equal(t, []string{"a", "b", "c"}, ids, "tool calls must emit in index order")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package openrouter provides an llm.LLMProvider for OpenRouter, an
|
||||
// aggregator that fronts hundreds of underlying models behind one
|
||||
// OpenAI-compatible endpoint. Like providers/litellm, this adds no new
|
||||
// request/stream-translation code of its own — it's a thin constructor
|
||||
// around harness's existing OpenAI-compatible support.
|
||||
package openrouter
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// DefaultBaseURL is OpenRouter's public API endpoint, used when
|
||||
// NewOpenRouterProvider is called with an empty baseURL.
|
||||
const DefaultBaseURL = "https://openrouter.ai/api/v1"
|
||||
|
||||
// NewOpenRouterProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, or DefaultBaseURL when baseURL is empty. kind="openai-compatible"
|
||||
// suppresses reasoning_effort, since OpenRouter's underlying models don't
|
||||
// uniformly support it.
|
||||
func NewOpenRouterProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultBaseURL
|
||||
}
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package openrouter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestDefaultBaseURL(t *testing.T) {
|
||||
require.Equal(t, "https://openrouter.ai/api/v1", DefaultBaseURL)
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_HitsGivenBaseURL confirms a custom baseURL
|
||||
// overrides the default and is actually what the provider talks to.
|
||||
func TestNewOpenRouterProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewOpenRouterProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic confirms the empty
|
||||
// -> DefaultBaseURL fallback path constructs a usable provider (the
|
||||
// actual outbound host isn't inspectable from outside the openai
|
||||
// package — OpenAIProvider's client config is unexported — so this
|
||||
// checks the fallback doesn't panic or return nil, and DefaultBaseURL's
|
||||
// own value is asserted separately above).
|
||||
func TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
|
||||
p := NewOpenRouterProvider("test-key", "")
|
||||
require.NotNil(t, p)
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
package qwen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
|
||||
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
|
||||
type QwenProvider struct {
|
||||
client *openai.Client
|
||||
}
|
||||
|
||||
// NewQwenProvider creates a new Qwen LLM provider.
|
||||
// The Qwen API is OpenAI-compatible, so we use the go-openai client
|
||||
// with Qwen's base URL.
|
||||
func NewQwenProvider(apiKey, baseURL string) *QwenProvider {
|
||||
cfg := openai.DefaultConfig(apiKey)
|
||||
if baseURL != "" {
|
||||
cfg.BaseURL = baseURL
|
||||
} else {
|
||||
// Default to Qwen's official API endpoint
|
||||
cfg.BaseURL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
|
||||
}
|
||||
client := openai.NewClientWithConfig(cfg)
|
||||
return &QwenProvider{client: client}
|
||||
}
|
||||
|
||||
func (p *QwenProvider) Models() []llm.ModelInfo {
|
||||
return []llm.ModelInfo{
|
||||
{ID: "qwen-plus", Name: "Qwen Plus", Provider: "qwen"},
|
||||
{ID: "qwen-turbo", Name: "Qwen Turbo", Provider: "qwen"},
|
||||
{ID: "qwen-max", Name: "Qwen Max", Provider: "qwen"},
|
||||
{ID: "qwen-coder-plus", Name: "Qwen Coder Plus", Provider: "qwen"},
|
||||
{ID: "qwen-vl-plus", Name: "Qwen VL Plus", Provider: "qwen"},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
// Build messages
|
||||
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
|
||||
|
||||
if sysPrompt := qwenResolveSystemPrompt(req); sysPrompt != "" {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleSystem,
|
||||
Content: sysPrompt,
|
||||
})
|
||||
}
|
||||
|
||||
for _, m := range req.Messages {
|
||||
switch m.Role {
|
||||
case "user":
|
||||
if m.ToolCallID != "" {
|
||||
if len(m.Images) > 0 {
|
||||
// Tool result with images: use multi-content parts
|
||||
var parts []openai.ChatMessagePart
|
||||
for _, img := range m.Images {
|
||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeImageURL,
|
||||
ImageURL: &openai.ChatMessageImageURL{
|
||||
URL: dataURI,
|
||||
Detail: openai.ImageURLDetailAuto,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeText,
|
||||
Text: m.Content,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleTool,
|
||||
MultiContent: parts,
|
||||
ToolCallID: m.ToolCallID,
|
||||
})
|
||||
} else {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleTool,
|
||||
Content: m.Content,
|
||||
ToolCallID: m.ToolCallID,
|
||||
})
|
||||
}
|
||||
} else if len(m.Images) > 0 {
|
||||
var parts []openai.ChatMessagePart
|
||||
for _, img := range m.Images {
|
||||
encoded := base64.StdEncoding.EncodeToString(img.Data)
|
||||
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeImageURL,
|
||||
ImageURL: &openai.ChatMessageImageURL{
|
||||
URL: dataURI,
|
||||
Detail: openai.ImageURLDetailAuto,
|
||||
},
|
||||
})
|
||||
}
|
||||
if m.Content != "" {
|
||||
parts = append(parts, openai.ChatMessagePart{
|
||||
Type: openai.ChatMessagePartTypeText,
|
||||
Text: m.Content,
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
MultiContent: parts,
|
||||
})
|
||||
} else {
|
||||
msgs = append(msgs, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
Content: m.Content,
|
||||
})
|
||||
}
|
||||
case "assistant":
|
||||
msg := openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleAssistant,
|
||||
Content: m.Content,
|
||||
}
|
||||
for _, tc := range m.ToolCalls {
|
||||
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
|
||||
ID: tc.ID,
|
||||
Type: openai.ToolTypeFunction,
|
||||
Function: openai.FunctionCall{
|
||||
Name: tc.Name,
|
||||
Arguments: string(tc.Input),
|
||||
},
|
||||
})
|
||||
}
|
||||
msgs = append(msgs, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// Build tools
|
||||
var tools []openai.Tool
|
||||
for _, t := range req.Tools {
|
||||
var params any
|
||||
if err := json.Unmarshal(t.Parameters, ¶ms); err != nil {
|
||||
params = map[string]any{"type": "object", "properties": map[string]any{}}
|
||||
}
|
||||
|
||||
tools = append(tools, openai.Tool{
|
||||
Type: openai.ToolTypeFunction,
|
||||
Function: &openai.FunctionDefinition{
|
||||
Name: t.Name,
|
||||
Description: t.Description,
|
||||
Parameters: params,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
model := req.Model
|
||||
if model == "" {
|
||||
model = "qwen-plus"
|
||||
}
|
||||
|
||||
maxTokens := req.MaxTokens
|
||||
if maxTokens == 0 {
|
||||
maxTokens = 4096
|
||||
}
|
||||
|
||||
openaiReq := openai.ChatCompletionRequest{
|
||||
Model: model,
|
||||
Messages: msgs,
|
||||
MaxTokens: maxTokens,
|
||||
Stream: true,
|
||||
}
|
||||
|
||||
if len(tools) > 0 {
|
||||
openaiReq.Tools = tools
|
||||
}
|
||||
|
||||
if req.Temperature > 0 {
|
||||
openaiReq.Temperature = float32(req.Temperature)
|
||||
}
|
||||
|
||||
if enabled, diag, ok := p.BuildEnableThinking(model, req.Reasoning); ok {
|
||||
// TODO: Qwen DashScope expects a custom top-level "enable_thinking"
|
||||
// JSON field that go-openai v1.41 does not expose via any
|
||||
// ExtraBody/RawJSON mechanism. Wiring it requires either upgrading
|
||||
// to a go-openai version with custom-field support or adding a
|
||||
// custom HTTP roundtripper. Tracked as a Phase 2 follow-up.
|
||||
_ = enabled
|
||||
_ = diag
|
||||
slog.Info("qwen thinking requested",
|
||||
"model", model,
|
||||
"requested", string(req.Reasoning),
|
||||
"clamped_to_bool", true,
|
||||
"reason", diag.Reason,
|
||||
"sdk_limitation", "enable_thinking not yet wired to wire format")
|
||||
} else if req.Reasoning != llm.ReasoningOff {
|
||||
slog.Info("reasoning ignored",
|
||||
"provider", "qwen",
|
||||
"model", model,
|
||||
"requested", string(req.Reasoning),
|
||||
"reason", "model does not support thinking")
|
||||
}
|
||||
|
||||
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
events := make(chan llm.ChatEvent, 100)
|
||||
|
||||
go func() {
|
||||
defer close(events)
|
||||
defer stream.Close()
|
||||
|
||||
// Track tool calls being built up across deltas
|
||||
type pendingTC struct {
|
||||
id string
|
||||
name string
|
||||
argsJSON string
|
||||
}
|
||||
toolCalls := make(map[int]*pendingTC)
|
||||
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
|
||||
return
|
||||
}
|
||||
|
||||
for _, choice := range resp.Choices {
|
||||
delta := choice.Delta
|
||||
|
||||
// Text content
|
||||
if delta.Content != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventTextDelta,
|
||||
Text: delta.Content,
|
||||
}
|
||||
}
|
||||
|
||||
// Tool calls
|
||||
for _, tc := range delta.ToolCalls {
|
||||
idx := 0
|
||||
if tc.Index != nil {
|
||||
idx = *tc.Index
|
||||
}
|
||||
pending, exists := toolCalls[idx]
|
||||
if !exists {
|
||||
pending = &pendingTC{}
|
||||
toolCalls[idx] = pending
|
||||
}
|
||||
|
||||
if tc.ID != "" {
|
||||
pending.id = tc.ID
|
||||
}
|
||||
if tc.Function.Name != "" {
|
||||
pending.name = tc.Function.Name
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallStart,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: pending.id,
|
||||
Name: pending.name,
|
||||
},
|
||||
}
|
||||
}
|
||||
if tc.Function.Arguments != "" {
|
||||
pending.argsJSON += tc.Function.Arguments
|
||||
}
|
||||
}
|
||||
|
||||
// Finish reason
|
||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||
// Emit completed tool calls
|
||||
for _, tc := range toolCalls {
|
||||
if tc.name != "" {
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallDone,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: tc.id,
|
||||
Name: tc.name,
|
||||
Input: json.RawMessage(tc.argsJSON),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
events <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// NormalizeToolSchema strips $ref and definitions from each tool's
|
||||
// JSON Schema. Qwen DashScope tracks the OpenAI function-calling
|
||||
// shape, so the same restricted JSON Schema subset applies (and the
|
||||
// same openaiUnsupportedFields list is reused).
|
||||
func (p *QwenProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
|
||||
return llm.ApplyStripList(tools, []string{"$ref", "definitions"})
|
||||
}
|
||||
|
||||
// BuildEnableThinking maps a llm.ReasoningMode to Qwen's enable_thinking
|
||||
// boolean. Returns (false, empty diag, false) when off or the model
|
||||
// doesn't support thinking. For any non-off mode on a supported model,
|
||||
// returns (true, clamped diag, true) — the boolean toggle loses the
|
||||
// requested low/medium/high granularity, so the diag always fires.
|
||||
func (p *QwenProvider) BuildEnableThinking(model string, mode llm.ReasoningMode) (bool, llm.Diagnostic, bool) {
|
||||
if mode == llm.ReasoningOff {
|
||||
return false, llm.Diagnostic{}, false
|
||||
}
|
||||
if !qwenSupportsThinking(model) {
|
||||
return false, llm.Diagnostic{}, false
|
||||
}
|
||||
return true, llm.Diagnostic{
|
||||
Action: "clamped",
|
||||
Reason: "qwen reasoning is boolean; granularity ignored",
|
||||
}, true
|
||||
}
|
||||
|
||||
// qwenSupportsThinking returns true for Qwen models that support the
|
||||
// enable_thinking parameter. Conservative — unknown IDs default to
|
||||
// false (only QwQ and Qwen3 family models accept this field).
|
||||
func qwenSupportsThinking(model string) bool {
|
||||
prefixes := []string{"qwen-qwq", "qwen3"}
|
||||
for _, prefix := range prefixes {
|
||||
if strings.HasPrefix(model, prefix) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// qwenResolveSystemPrompt returns the effective system prompt string,
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI/Gemini
|
||||
// resolution helpers.
|
||||
func qwenResolveSystemPrompt(req llm.ChatRequest) string {
|
||||
if len(req.SystemPromptParts) > 0 {
|
||||
return llm.JoinSystemPromptParts(req.SystemPromptParts)
|
||||
}
|
||||
return req.SystemPrompt
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package qwen
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestQwenResolveSystemPromptPrefersParts(t *testing.T) {
|
||||
got := qwenResolveSystemPrompt(llm.ChatRequest{
|
||||
SystemPrompt: "legacy",
|
||||
SystemPromptParts: []llm.SystemPromptPart{{Text: "new-a"}, {Text: "new-b"}},
|
||||
})
|
||||
require.Equal(t, "new-a\nnew-b", got)
|
||||
}
|
||||
|
||||
func TestQwenResolveSystemPromptFallback(t *testing.T) {
|
||||
got := qwenResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "legacy"})
|
||||
require.Equal(t, "legacy", got)
|
||||
}
|
||||
|
||||
func TestQwenResolveSystemPromptEmpty(t *testing.T) {
|
||||
got := qwenResolveSystemPrompt(llm.ChatRequest{})
|
||||
require.Equal(t, "", got)
|
||||
}
|
||||
@@ -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.
|
||||
+63
-7
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
|
||||
}
|
||||
|
||||
// Empty spillConfig → legacy in-place truncation path.
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// User message should be unchanged
|
||||
assert.Equal(t, "hello", msgs[0].Content)
|
||||
@@ -261,7 +261,7 @@ func TestPruneToolResultsShort(t *testing.T) {
|
||||
{Role: "user", Content: "short output", ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
assert.Equal(t, "short output", msgs[0].Content)
|
||||
}
|
||||
@@ -279,7 +279,7 @@ func TestPruneToolResultsNewlineBoundary(t *testing.T) {
|
||||
{Role: "user", Content: content, ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// Should be truncated and contain the truncation marker
|
||||
truncated := msgs[0].Content
|
||||
@@ -298,7 +298,7 @@ func TestPruneToolResultsSpillsToDisk(t *testing.T) {
|
||||
{Role: "user", Content: original, ToolCallID: "tc_42"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"}, nil)
|
||||
|
||||
// Message rewritten to head + spill marker pointing at the file.
|
||||
got := msgs[0].Content
|
||||
@@ -324,14 +324,14 @@ func TestPruneToolResultsIdempotentAfterSpill(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("b", 20000), ToolCallID: "tc_99"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
afterFirst := msgs[0].Content
|
||||
require.Contains(t, afterFirst, spillMarker)
|
||||
|
||||
// Second call: marker is present, so the message must be untouched.
|
||||
// Mutating it (e.g. spilling again or appending another marker)
|
||||
// would silently grow the prefill across turns and burn cache.
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
assert.Equal(t, afterFirst, msgs[0].Content)
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("c", 20000), ToolCallID: "tc_fail"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"}, nil)
|
||||
|
||||
got := msgs[0].Content
|
||||
assert.Less(t, len(got), 20000, "fallback must still bound the message")
|
||||
@@ -357,6 +357,31 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
assert.NotContains(t, got, spillMarker, "spilled marker must not appear when write failed")
|
||||
}
|
||||
|
||||
func TestPruneToolResultsSpillsOncePerID(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
cfg := spillConfig{Workspace: workspace, SessionKey: "sess_once"}
|
||||
spilled := map[string]bool{}
|
||||
|
||||
big := strings.Repeat("x", 50000)
|
||||
mk := func() []llm.Message {
|
||||
return []llm.Message{{ToolCallID: "call_big", Content: big}}
|
||||
}
|
||||
|
||||
m1 := mk()
|
||||
pruneToolResults(m1, 10000, cfg, spilled)
|
||||
require.Contains(t, m1[0].Content, spillMarker)
|
||||
spillPath := filepath.Join(workspace, ".harness", "spill", "sess_once", "call_big.txt")
|
||||
require.FileExists(t, spillPath)
|
||||
require.True(t, spilled["call_big"], "ID recorded as spilled")
|
||||
|
||||
require.NoError(t, os.Remove(spillPath))
|
||||
|
||||
m2 := mk()
|
||||
pruneToolResults(m2, 10000, cfg, spilled)
|
||||
require.Contains(t, m2[0].Content, spillMarker, "message still rewritten to the marker")
|
||||
require.NoFileExists(t, spillPath, "turn 2 must NOT re-write the spill file (idempotent via spilled set)")
|
||||
}
|
||||
|
||||
// --- Runtime tests ---
|
||||
|
||||
func TestRuntimeRun(t *testing.T) {
|
||||
@@ -871,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run
|
||||
// as a non-nil error (context.Canceled) rather than returning (partialText,
|
||||
// nil). Cron/sync callers must be able to distinguish a completed run from a
|
||||
// cancelled one. Reuses the same abort scaffolding as
|
||||
// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth).
|
||||
func TestRunSync_ReturnsErrorOnAbort(t *testing.T) {
|
||||
threeToolCalls := []llm.ToolCall{
|
||||
{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
{ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)},
|
||||
}
|
||||
llmFake := &threeToolCallLLM{toolCalls: threeToolCalls}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
count := 0
|
||||
exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count}
|
||||
|
||||
r := &Runtime{
|
||||
LLM: llmFake,
|
||||
Tools: exec,
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "test-model",
|
||||
MaxTurns: 5,
|
||||
}
|
||||
|
||||
_, err := r.RunSync(ctx, "go", nil)
|
||||
require.Error(t, err)
|
||||
require.ErrorIs(t, err, context.Canceled)
|
||||
}
|
||||
|
||||
// threeToolCallLLM emits the configured tool_calls as one assistant turn,
|
||||
// then EventDone. On the next call (after tool results, if the runtime
|
||||
// loops back), emits only EventDone with no tool_calls so Run terminates.
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+121
-30
@@ -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)
|
||||
if err != nil {
|
||||
for _, c := range mcpClients {
|
||||
_ = c.Close()
|
||||
}
|
||||
return nil, fmt.Errorf("mcp server %q: %w", srv.Name, err)
|
||||
}
|
||||
for _, t := range cli.Tools() {
|
||||
reg.Register(t)
|
||||
}
|
||||
mcpClients = append(mcpClients, cli)
|
||||
var err error
|
||||
mcpClients, mcpStatus, err = connectMCPServers(ctx, spec.MCPServers)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
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()
|
||||
@@ -166,7 +202,9 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
}
|
||||
}
|
||||
|
||||
rt := &Runtime{
|
||||
loop := mergeLoopConfig(deps.AgentLoop, spec.Loop)
|
||||
|
||||
rt = &Runtime{
|
||||
LLM: inputs.Provider,
|
||||
Tools: inputs.Tools,
|
||||
Session: inputs.Session,
|
||||
@@ -175,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,
|
||||
@@ -186,10 +225,17 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
Permission: deps.Permission,
|
||||
Compaction: inputs.Compaction,
|
||||
IngestSource: inputs.IngestSource,
|
||||
AgentLoop: deps.AgentLoop,
|
||||
AgentLoop: loop,
|
||||
StaticSystemPrompt: staticPrompt,
|
||||
CalibratorStore: deps.CalibratorStore,
|
||||
mcpClients: mcpClients,
|
||||
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
|
||||
@@ -206,3 +252,48 @@ func BuildRuntime(deps RuntimeDeps, inputs RuntimeInputs, spec AgentSpec) (*Runt
|
||||
|
||||
return rt, nil
|
||||
}
|
||||
|
||||
// mergeLoopConfig applies the per-agent non-zero settings over the shared
|
||||
// defaults. LoopConfig intentionally uses zero values as "inherit/default",
|
||||
// so this preserves existing RuntimeDeps.AgentLoop behavior while making the
|
||||
// documented AgentSpec.Loop override effective.
|
||||
func mergeLoopConfig(base, override LoopConfig) LoopConfig {
|
||||
out := base
|
||||
if override.MaxToolConcurrency > 0 {
|
||||
out.MaxToolConcurrency = override.MaxToolConcurrency
|
||||
}
|
||||
if override.MaxAgentDepth > 0 {
|
||||
out.MaxAgentDepth = override.MaxAgentDepth
|
||||
}
|
||||
if override.StreamingTools {
|
||||
out.StreamingTools = true
|
||||
}
|
||||
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
|
||||
}
|
||||
if override.Hooks.OnSessionStart != nil {
|
||||
out.Hooks.OnSessionStart = override.Hooks.OnSessionStart
|
||||
}
|
||||
if override.Hooks.BeforeToolUse != nil {
|
||||
out.Hooks.BeforeToolUse = override.Hooks.BeforeToolUse
|
||||
}
|
||||
if override.Hooks.AfterToolUse != nil {
|
||||
out.Hooks.AfterToolUse = override.Hooks.AfterToolUse
|
||||
}
|
||||
if override.Hooks.OnStop != nil {
|
||||
out.Hooks.OnStop = override.Hooks.OnStop
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/tool"
|
||||
@@ -38,6 +39,39 @@ func TestBuildRuntimeMinimalSpecSafe(t *testing.T) {
|
||||
require.NotEmpty(t, rt.StaticSystemPrompt)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeMergesSpecLoopOverSharedDefaults(t *testing.T) {
|
||||
baseCalled := false
|
||||
specCalled := false
|
||||
baseStop := func(context.Context, string) { baseCalled = true }
|
||||
specStop := func(context.Context, string) { specCalled = true }
|
||||
rt, err := BuildRuntime(
|
||||
RuntimeDeps{AgentLoop: LoopConfig{
|
||||
MaxToolConcurrency: 3,
|
||||
MaxAgentDepth: 2,
|
||||
MaxToolResultLen: 8000,
|
||||
Hooks: LifecycleHooks{OnStop: baseStop},
|
||||
}},
|
||||
RuntimeInputs{},
|
||||
AgentSpec{
|
||||
ID: "a", Name: "A", Model: "anthropic/claude-sonnet-4-5",
|
||||
Loop: LoopConfig{
|
||||
MaxToolConcurrency: 7,
|
||||
StreamingTools: true,
|
||||
Hooks: LifecycleHooks{OnStop: specStop},
|
||||
},
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 7, rt.AgentLoop.MaxToolConcurrency)
|
||||
assert.Equal(t, 2, rt.AgentLoop.MaxAgentDepth, "zero spec fields inherit shared defaults")
|
||||
assert.Equal(t, 8000, rt.AgentLoop.MaxToolResultLen)
|
||||
assert.True(t, rt.AgentLoop.StreamingTools)
|
||||
require.NotNil(t, rt.AgentLoop.Hooks.OnStop)
|
||||
rt.AgentLoop.Hooks.OnStop(context.Background(), "completed")
|
||||
assert.False(t, baseCalled)
|
||||
assert.True(t, specCalled)
|
||||
}
|
||||
|
||||
func TestBuildRuntimeUsesCallerProvidedMemoryFiles(t *testing.T) {
|
||||
// Caller composes memoryFiles however they want — typical patterns
|
||||
// include walking AGENTS.md from workspace + $HOME, building from a
|
||||
|
||||
@@ -443,8 +443,8 @@ func TestRuntimeDynamicSuffixIncludesDate(t *testing.T) {
|
||||
// this proves the date is stable across turns of a single Run.
|
||||
func TestRuntimeDateLineComputedOncePerRun(t *testing.T) {
|
||||
dl := "Today's date is 2026-05-01."
|
||||
a := buildDynamicSystemPromptSuffix(dl, "")
|
||||
b := buildDynamicSystemPromptSuffix(dl, "")
|
||||
a := buildDynamicSystemPromptSuffix("", dl, "")
|
||||
b := buildDynamicSystemPromptSuffix("", dl, "")
|
||||
require.Equal(t, a, b)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tokens"
|
||||
"github.com/sausheong/harness/tool"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// usageDoneProvider emits a usage-bearing EventDone so the agent loop can
|
||||
// populate (and persist) the per-session token calibrator.
|
||||
type usageDoneProvider struct {
|
||||
llmtest.Base
|
||||
}
|
||||
|
||||
func (p *usageDoneProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "answer"}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1000, OutputTokens: 10}}
|
||||
close(ch)
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// TestCalibratorPersistsByEndOfRun guards that the per-session calibrator is
|
||||
// persisted to the CalibratorStore by the time Run completes. After the P8
|
||||
// debounce change the Save moves from per-round to a single deferred flush at
|
||||
// Run end; this test asserts the observable end state (persisted) is unchanged.
|
||||
func TestCalibratorPersistsByEndOfRun(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
store := tokens.NewCalibratorStore(dir)
|
||||
rt := &Runtime{
|
||||
LLM: &usageDoneProvider{},
|
||||
Tools: tool.NewRegistry(),
|
||||
Session: session.NewSession("a", "k"),
|
||||
AgentID: "a",
|
||||
Model: "claude-sonnet-4-5",
|
||||
// Compaction must be non-nil for the runtime to lazily create the
|
||||
// per-session calibrator (the calibrator-creation path is gated on
|
||||
// it). MessageCap/threshold left at defaults so no compaction fires
|
||||
// during this short run.
|
||||
Compaction: newCompactionMgr(),
|
||||
Provider: "anthropic",
|
||||
MaxTurns: 2,
|
||||
Workspace: t.TempDir(),
|
||||
CalibratorStore: store,
|
||||
}
|
||||
_, err := rt.RunSync(context.Background(), "go", nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
ratio, count := tokens.NewCalibratorStore(dir).Load("a", "k")
|
||||
require.Greater(t, count, 0, "calibrator must be persisted by end of Run")
|
||||
require.Greater(t, ratio, 0.0)
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// maxToolResultLen returns the per-result truncation cap (chars) for tool
|
||||
// results in the in-context message history. Precedence:
|
||||
// 1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins.
|
||||
// 2. HARNESS_MAX_TOOL_RESULT_LEN env var (>0) — env fallback.
|
||||
// 3. defaultMaxToolResultLen (4000).
|
||||
//
|
||||
// Tool results longer than this are truncated (or spilled to disk via
|
||||
// spillConfig when supplied). 4000 is conservative; engineering-style
|
||||
// agents that read source files and run tests typically want 16000-25000.
|
||||
func (r *Runtime) maxToolResultLen() int {
|
||||
if r.AgentLoop.MaxToolResultLen > 0 {
|
||||
return r.AgentLoop.MaxToolResultLen
|
||||
}
|
||||
if v := os.Getenv("HARNESS_MAX_TOOL_RESULT_LEN"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
return n
|
||||
}
|
||||
}
|
||||
return defaultMaxToolResultLen
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestMaxToolResultLen_Precedence locks in the config > env > default
|
||||
// precedence so a regression here doesn't silently swap one source for
|
||||
// another.
|
||||
func TestMaxToolResultLen_Precedence(t *testing.T) {
|
||||
t.Run("default when nothing set", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("env overrides default", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != 12345 {
|
||||
t.Fatalf("want 12345, got %d", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("config overrides env", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
|
||||
r := &Runtime{AgentLoop: LoopConfig{MaxToolResultLen: 25000}}
|
||||
if got := r.maxToolResultLen(); got != 25000 {
|
||||
t.Fatalf("want 25000, got %d", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero env is ignored", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "0")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("garbage env is ignored", func(t *testing.T) {
|
||||
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "not-a-number")
|
||||
r := &Runtime{}
|
||||
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
|
||||
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package runtime
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
anthropicprovider "github.com/sausheong/harness/providers/anthropic"
|
||||
)
|
||||
|
||||
// cachingCapableFake implements llm.LLMProvider plus the
|
||||
// llm.PromptCachingProvider capability.
|
||||
type cachingCapableFake struct {
|
||||
llmtest.Stub
|
||||
}
|
||||
|
||||
func (*cachingCapableFake) SupportsPromptCaching() bool { return true }
|
||||
|
||||
// TestProviderSupportsCaching_CapabilityInterfaceWins: an Anthropic-shaped
|
||||
// provider registered under a custom name (platformai, bedrock, any relay)
|
||||
// must still get prompt caching. Gating on the config block's NAME meant
|
||||
// every turn on a renamed provider re-processed the full history uncached.
|
||||
func TestProviderSupportsCaching_CapabilityInterfaceWins(t *testing.T) {
|
||||
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
|
||||
assert.True(t, r.providerSupportsCaching(),
|
||||
"capability interface must win over the provider name")
|
||||
}
|
||||
|
||||
func TestProviderSupportsCaching_NameFallbackStillWorks(t *testing.T) {
|
||||
r := &Runtime{Provider: "anthropic", LLM: &llmtest.Stub{}}
|
||||
assert.True(t, r.providerSupportsCaching(),
|
||||
"legacy name-based gate kept for providers without the capability interface")
|
||||
}
|
||||
|
||||
func TestProviderSupportsCaching_NonCachingProviderFalse(t *testing.T) {
|
||||
r := &Runtime{Provider: "local", LLM: &llmtest.Stub{}}
|
||||
assert.False(t, r.providerSupportsCaching())
|
||||
}
|
||||
|
||||
// TestAnthropicProviderDeclaresPromptCaching pins the wiring end-to-end:
|
||||
// the real Anthropic provider must implement the capability interface.
|
||||
func TestAnthropicProviderDeclaresPromptCaching(t *testing.T) {
|
||||
p := anthropicprovider.NewAnthropicProvider("k", "")
|
||||
pc, ok := any(p).(llm.PromptCachingProvider)
|
||||
assert.True(t, ok, "AnthropicProvider must implement llm.PromptCachingProvider")
|
||||
if ok {
|
||||
assert.True(t, pc.SupportsPromptCaching())
|
||||
}
|
||||
}
|
||||
|
||||
// Mid-loop compaction was gated on the same name list; an Anthropic-shaped
|
||||
// provider under a custom name must support it too.
|
||||
func TestProviderSupportsMidLoopCompaction_CapabilityInterfaceWins(t *testing.T) {
|
||||
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
|
||||
assert.True(t, r.providerSupportsMidLoopCompaction())
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+43
-23
@@ -11,9 +11,15 @@ import (
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/session"
|
||||
"github.com/sausheong/harness/tool"
|
||||
)
|
||||
|
||||
const maxToolResultLen = 4000 // truncate tool results longer than this
|
||||
// defaultMaxToolResultLen is the fallback cap used when LoopConfig.MaxToolResultLen
|
||||
// is unset and the HARNESS_MAX_TOOL_RESULT_LEN env var is unset/invalid. Tool
|
||||
// results longer than this get truncated (or spilled to disk + truncated-with-
|
||||
// marker when spillConfig is supplied). 4000 chars (~1000 tokens) is conservative
|
||||
// so behaviour is unchanged for callers that don't opt into a larger budget.
|
||||
const defaultMaxToolResultLen = 4000
|
||||
|
||||
// detectImageMIME returns the actual MIME type based on magic bytes.
|
||||
// Falls back to the provided hint if the format is unrecognized.
|
||||
@@ -136,18 +142,23 @@ func BuildStaticSystemPrompt(
|
||||
}
|
||||
|
||||
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
|
||||
// — the date line and the cortex hint — into a single string the runtime
|
||||
// sends as the second (un-cached) SystemPromptPart. The date line, when
|
||||
// non-empty, appears at the top so the model anchors on "today" before
|
||||
// the per-turn content. Returns "" when all inputs are empty/nil.
|
||||
// — the identity hint, date line, and cortex hint — into a single string
|
||||
// the runtime sends as the second (un-cached) SystemPromptPart. identityHint
|
||||
// leads (see Runtime.DynamicIdentityHint: it needs to outweigh the model's
|
||||
// own prior in-conversation statements, so it gets the most prominent
|
||||
// position), then the date line so the model anchors on "today" before the
|
||||
// per-turn content. Returns "" when all inputs are empty/nil.
|
||||
//
|
||||
// As of sub-project 5, skill bodies and memory entries are no longer
|
||||
// auto-injected here. Their indices live in the cached static prompt
|
||||
// and the agent loads bodies on demand via the load_skill / load_memory
|
||||
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
|
||||
// speculative memory bodies from every prefill.
|
||||
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
|
||||
func buildDynamicSystemPromptSuffix(identityHint, dateLine, cortexContext string) string {
|
||||
var sb strings.Builder
|
||||
if identityHint != "" {
|
||||
sb.WriteString(identityHint)
|
||||
}
|
||||
if dateLine != "" {
|
||||
sb.WriteString(dateLine)
|
||||
}
|
||||
@@ -162,17 +173,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
|
||||
// corresponding tool_result in the next user message. Orphaned tool calls
|
||||
// (e.g. from interrupted sessions) get synthetic error results injected.
|
||||
func assembleMessages(history []session.SessionEntry) []llm.Message {
|
||||
// First pass: collect tool result IDs so we can detect orphaned tool calls.
|
||||
resultIDs := make(map[string]bool)
|
||||
for _, entry := range history {
|
||||
if entry.Type == session.EntryTypeToolResult {
|
||||
var tr session.ToolResultData
|
||||
if err := json.Unmarshal(entry.Data, &tr); err == nil {
|
||||
resultIDs[tr.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var msgs []llm.Message
|
||||
|
||||
for _, entry := range history {
|
||||
@@ -213,13 +213,19 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
|
||||
if err := json.Unmarshal(entry.Data, &md); err != nil {
|
||||
continue
|
||||
}
|
||||
// Before appending a new message, check if the last assistant
|
||||
// message has orphaned tool calls that need synthetic results.
|
||||
msgs = injectMissingToolResults(msgs)
|
||||
msg := llm.Message{
|
||||
Role: entry.Role,
|
||||
Content: md.Text,
|
||||
}
|
||||
// Restore thinking blocks for assistant messages (must be echoed back).
|
||||
if entry.Role == "assistant" {
|
||||
for _, tb := range md.ThinkingBlocks {
|
||||
msg.ThinkingBlocks = append(msg.ThinkingBlocks, llm.ThinkingBlock{
|
||||
Thinking: tb.Thinking,
|
||||
Signature: tb.Signature,
|
||||
})
|
||||
}
|
||||
}
|
||||
// Convert session images to LLM image content
|
||||
if entry.Role == "user" {
|
||||
for _, img := range md.Images {
|
||||
@@ -428,7 +434,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
|
||||
return "", fmt.Errorf("spill mkdir: %w", err)
|
||||
}
|
||||
path := filepath.Join(dir, toolCallID+".txt")
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
if err := tool.WriteFileAtomic(path, []byte(content), 0o600); err != nil {
|
||||
return "", fmt.Errorf("spill write: %w", err)
|
||||
}
|
||||
return path, nil
|
||||
@@ -455,7 +461,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
|
||||
// nearest newline boundary — most tool outputs (file reads, command
|
||||
// output) are front-loaded with the most relevant info, so the head
|
||||
// preview is usually enough on its own.
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig, spilled map[string]bool) {
|
||||
for i := range msgs {
|
||||
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
|
||||
continue
|
||||
@@ -475,11 +481,25 @@ func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
// Try spill first if configured. On any failure, fall through to
|
||||
// legacy truncation so the prefill stays bounded either way.
|
||||
if cfg.Workspace != "" && cfg.SessionKey != "" {
|
||||
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
|
||||
id := msgs[i].ToolCallID
|
||||
// Spill content is immutable per ToolCallID and lands at a
|
||||
// deterministic path. If this Run already spilled this ID,
|
||||
// skip the (multi-MB) disk re-write and just rebuild the
|
||||
// in-memory marker pointing at the same path.
|
||||
if spilled != nil && spilled[id] {
|
||||
path := filepath.Join(cfg.Workspace, ".harness", "spill", cfg.SessionKey, id+".txt")
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, path)
|
||||
continue
|
||||
}
|
||||
if writtenPath, err := spillToolResult(cfg, id, msgs[i].Content); err == nil {
|
||||
if spilled != nil {
|
||||
spilled[id] = true
|
||||
}
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, writtenPath)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
Loaded 100 of 227 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user