From 454944524eb0cc06d324eb19daddad91f9810889 Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 07:24:42 -0400 Subject: [PATCH 1/7] feat(#6936): estimate USD cost from tokens on cancelled runs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When a run is cancelled, Claude Code never emits its terminal result event (which carries total_cost_usd), so TotalCostUSD stays zero in telemetry. This adds a client-side pricing table that estimates cost from captured token counts and the model's published per-MTok rates. The estimation runs per-iteration before aggregation, so the estimated cost flows into the agent span, root span, metrics.json, and status comment — all four telemetry sinks. On successful runs where the authoritative cost is already present, the estimation is a no-op. lookupRates handles provider prefixes (anthropic-vertex/...) and iteratively strips trailing date/experiment suffixes to match model IDs against the rate table. Co-Authored-By: Claude Opus 4.6 --- internal/cli/pricing.go | 105 ++++++++++++++++++++ internal/cli/pricing_test.go | 185 +++++++++++++++++++++++++++++++++++ internal/cli/run.go | 15 ++- 3 files changed, 300 insertions(+), 5 deletions(-) create mode 100644 internal/cli/pricing.go create mode 100644 internal/cli/pricing_test.go diff --git a/internal/cli/pricing.go b/internal/cli/pricing.go new file mode 100644 index 0000000000..bee7f520ba --- /dev/null +++ b/internal/cli/pricing.go @@ -0,0 +1,105 @@ +package cli + +import ( + "strings" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" +) + +// modelRates holds per-million-token prices (USD) for an Anthropic model. +type modelRates struct { + Input float64 + Output float64 + CacheWrite float64 + CacheRead float64 +} + +// knownModelRates maps model-ID prefixes to their published rates. +// Source: https://docs.anthropic.com/en/docs/about-claude/pricing +var knownModelRates = map[string]modelRates{ + "claude-fable-5-1": {10, 50, 12.50, 0.25}, + "claude-mythos-5-1": {10, 50, 12.50, 0.25}, + "claude-fable-5": {10, 50, 12.50, 1}, + "claude-mythos-5": {10, 50, 12.50, 1}, + "claude-opus-5": {5, 25, 6.25, 0.50}, + "claude-opus-4-8": {5, 25, 6.25, 0.50}, + "claude-opus-4-7": {5, 25, 6.25, 0.50}, + "claude-opus-4-6": {5, 25, 6.25, 0.50}, + "claude-opus-4-5": {5, 25, 6.25, 0.50}, + "claude-sonnet-5": {2, 10, 2.50, 0.20}, + "claude-sonnet-4-6": {3, 15, 3.75, 0.30}, + "claude-sonnet-4-5": {3, 15, 3.75, 0.30}, + "claude-haiku-4-5": {1, 5, 1.25, 0.10}, + "claude-haiku-3-5": {0.80, 4, 1, 0.08}, +} + +// lookupRates resolves a model ID to its pricing rates. It handles +// provider prefixes ("anthropic-vertex/claude-opus-4-6") and trailing +// date suffixes ("claude-haiku-4-5-20251001"). +func lookupRates(model string) (modelRates, bool) { + if _, after, ok := strings.Cut(model, "/"); ok { + model = after + } + if r, ok := knownModelRates[model]; ok { + return r, true + } + for s := model; ; { + i := strings.LastIndex(s, "-") + if i <= 0 { + break + } + s = s[:i] + if r, ok := knownModelRates[s]; ok { + return r, true + } + } + return modelRates{}, false +} + +func estimateCostFromTokens(model string, input, output, reasoning, cacheWrite, cacheRead int) float64 { + rates, ok := lookupRates(model) + if !ok { + return 0 + } + return (float64(input)*rates.Input + + float64(output+reasoning)*rates.Output + + float64(cacheWrite)*rates.CacheWrite + + float64(cacheRead)*rates.CacheRead) / 1_000_000 +} + +// estimateRunMetricsCost fills in TotalCostUSD on per-iteration RunMetrics +// when it is zero but tokens are present. +func estimateRunMetricsCost(m *agentruntime.RunMetrics) { + if m.TotalCostUSD > 0 { + return + } + totalTokens := m.InputTokens + m.OutputTokens + + m.CacheCreationInputTokens + m.CacheReadInputTokens + if totalTokens == 0 { + return + } + + if len(m.PerModelUsage) > 0 { + var total float64 + for spec, u := range m.PerModelUsage { + if u.CostUSD > 0 { + total += u.CostUSD + continue + } + est := estimateCostFromTokens(spec, + u.InputTokens, u.OutputTokens, 0, + u.CacheCreationInputTokens, u.CacheReadInputTokens) + if est > 0 { + u.CostUSD = est + m.PerModelUsage[spec] = u + total += est + } + } + m.TotalCostUSD = total + return + } + + m.TotalCostUSD = estimateCostFromTokens(m.Model, + m.InputTokens, m.OutputTokens, m.ReasoningTokens, + m.CacheCreationInputTokens, m.CacheReadInputTokens) +} diff --git a/internal/cli/pricing_test.go b/internal/cli/pricing_test.go new file mode 100644 index 0000000000..fd711773ed --- /dev/null +++ b/internal/cli/pricing_test.go @@ -0,0 +1,185 @@ +package cli + +import ( + "math" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" +) + +func almostEqual(a, b, tol float64) bool { + return math.Abs(a-b) < tol +} + +func TestLookupRates_ExactMatch(t *testing.T) { + r, ok := lookupRates("claude-sonnet-5") + if !ok { + t.Fatal("expected match for claude-sonnet-5") + } + if r.Input != 2 || r.Output != 10 { + t.Errorf("got Input=%v Output=%v, want 2/10", r.Input, r.Output) + } +} + +func TestLookupRates_DateSuffix(t *testing.T) { + r, ok := lookupRates("claude-haiku-4-5-20251001") + if !ok { + t.Fatal("expected match for claude-haiku-4-5-20251001") + } + if r.Input != 1 || r.Output != 5 { + t.Errorf("got Input=%v Output=%v, want 1/5", r.Input, r.Output) + } +} + +func TestLookupRates_ProviderPrefix(t *testing.T) { + r, ok := lookupRates("anthropic-vertex/claude-opus-4-6") + if !ok { + t.Fatal("expected match for anthropic-vertex/claude-opus-4-6") + } + if r.Input != 5 || r.Output != 25 { + t.Errorf("got Input=%v Output=%v, want 5/25", r.Input, r.Output) + } +} + +func TestLookupRates_ProviderPrefixWithDate(t *testing.T) { + r, ok := lookupRates("anthropic/claude-sonnet-4-5-20241022") + if !ok { + t.Fatal("expected match for anthropic/claude-sonnet-4-5-20241022") + } + if r.Input != 3 || r.Output != 15 { + t.Errorf("got Input=%v Output=%v, want 3/15", r.Input, r.Output) + } +} + +func TestLookupRates_CompoundSuffix(t *testing.T) { + r, ok := lookupRates("claude-opus-4-6-exp-20250826") + if !ok { + t.Fatal("expected match for claude-opus-4-6-exp-20250826") + } + if r.Input != 5 { + t.Errorf("got Input=%v, want 5", r.Input) + } +} + +func TestLookupRates_Unknown(t *testing.T) { + _, ok := lookupRates("gpt-4o") + if ok { + t.Fatal("expected no match for gpt-4o") + } +} + +func TestLookupRates_Empty(t *testing.T) { + _, ok := lookupRates("") + if ok { + t.Fatal("expected no match for empty string") + } +} + +func TestEstimateCostFromTokens(t *testing.T) { + cost := estimateCostFromTokens("claude-sonnet-5", 10000, 5000, 0, 0, 0) + if !almostEqual(cost, 0.07, 0.0001) { + t.Errorf("got %v, want 0.07", cost) + } +} + +func TestEstimateCostFromTokens_WithCache(t *testing.T) { + cost := estimateCostFromTokens("claude-opus-5", 5000, 2000, 0, 10000, 20000) + if !almostEqual(cost, 0.1475, 0.0001) { + t.Errorf("got %v, want 0.1475", cost) + } +} + +func TestEstimateCostFromTokens_WithReasoning(t *testing.T) { + cost := estimateCostFromTokens("claude-sonnet-5", 1000, 500, 2000, 0, 0) + if !almostEqual(cost, 0.027, 0.0001) { + t.Errorf("got %v, want 0.027", cost) + } +} + +func TestEstimateCostFromTokens_UnknownModel(t *testing.T) { + cost := estimateCostFromTokens("unknown-model", 10000, 5000, 0, 0, 0) + if cost != 0 { + t.Errorf("expected 0 for unknown model, got %v", cost) + } +} + +func TestEstimateRunMetricsCost(t *testing.T) { + m := &agentruntime.RunMetrics{ + Model: "claude-opus-4-6", + InputTokens: 20000, + OutputTokens: 8000, + CacheCreationInputTokens: 5000, + CacheReadInputTokens: 50000, + } + estimateRunMetricsCost(m) + if !almostEqual(m.TotalCostUSD, 0.35625, 0.001) { + t.Errorf("got %v, want 0.35625", m.TotalCostUSD) + } +} + +func TestEstimateRunMetricsCost_PerModelUsage(t *testing.T) { + m := &agentruntime.RunMetrics{ + InputTokens: 15000, + OutputTokens: 8000, + PerModelUsage: map[string]agentruntime.ModelUsage{ + "anthropic-vertex/claude-sonnet-5": { + InputTokens: 10000, + OutputTokens: 5000, + }, + "anthropic-vertex/claude-haiku-4-5": { + InputTokens: 5000, + OutputTokens: 3000, + }, + }, + } + estimateRunMetricsCost(m) + // sonnet: (10000*2 + 5000*10) / 1e6 = 0.07 + // haiku: (5000*1 + 3000*5) / 1e6 = 0.02 + if !almostEqual(m.TotalCostUSD, 0.09, 0.001) { + t.Errorf("got %v, want 0.09", m.TotalCostUSD) + } + if !almostEqual(m.PerModelUsage["anthropic-vertex/claude-sonnet-5"].CostUSD, 0.07, 0.001) { + t.Errorf("sonnet cost = %v, want 0.07", m.PerModelUsage["anthropic-vertex/claude-sonnet-5"].CostUSD) + } + if !almostEqual(m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"].CostUSD, 0.02, 0.001) { + t.Errorf("haiku cost = %v, want 0.02", m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"].CostUSD) + } +} + +func TestEstimateRunMetricsCost_PerModelUsage_MixedCosts(t *testing.T) { + m := &agentruntime.RunMetrics{ + InputTokens: 15000, + OutputTokens: 8000, + PerModelUsage: map[string]agentruntime.ModelUsage{ + "anthropic/claude-sonnet-5": { + InputTokens: 10000, + OutputTokens: 5000, + CostUSD: 0.07, + }, + "anthropic/claude-haiku-4-5": { + InputTokens: 5000, + OutputTokens: 3000, + }, + }, + } + estimateRunMetricsCost(m) + if !almostEqual(m.TotalCostUSD, 0.09, 0.001) { + t.Errorf("got %v, want 0.09", m.TotalCostUSD) + } + if m.PerModelUsage["anthropic/claude-sonnet-5"].CostUSD != 0.07 { + t.Error("existing CostUSD was overwritten") + } +} + +func TestEstimateRunMetricsCost_Noop_WhenCostPresent(t *testing.T) { + m := &agentruntime.RunMetrics{ + TotalCostUSD: 0.50, + Model: "claude-sonnet-5", + InputTokens: 10000, + OutputTokens: 5000, + } + estimateRunMetricsCost(m) + if m.TotalCostUSD != 0.50 { + t.Errorf("cost changed from 0.50 to %v", m.TotalCostUSD) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index 8eaafc2757..5a006761fb 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2268,6 +2268,11 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } } + // Estimate USD cost from tokens when the authoritative cost is + // missing (zero) — e.g. cancelled runs that never receive the + // result event. On successful runs this is a no-op. + estimateRunMetricsCost(&metrics) + // Accumulate behavioral metrics across iterations. aggregateRunMetrics(&aggMetrics, &metrics, iteration) @@ -3711,11 +3716,11 @@ func transcriptErrorMessage(te agentruntime.TranscriptError) string { // artifact upload step (if: always()) captures the partial usage data // (#6936). // -// NOTE: TotalCostUSD will be zero in the persisted metrics because dollar -// cost is only available from the terminal ResultEvent, which a cancelled -// run never emits. Token counts (input, output, cache_read, cache_creation) -// are captured via the deferred TokensEvent and will be non-zero. See #6936 -// for background. +// NOTE: TotalCostUSD is estimated from token counts and the published +// rate table when the authoritative cost is missing (cancelled runs never +// emit the terminal ResultEvent). The estimate uses 5-minute cache-write +// rates and is zero if the model is unrecognized. See estimateRunMetricsCost +// and #6936 for background. // // cancelled is false when ctx is still live, in which case the caller's // normal control flow continues unchanged; the other return values are From 43f5e6e5908656c01a1ce83be1bc2e220ce6a5d0 Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 10:29:56 -0400 Subject: [PATCH 2/7] feat: replace static pricing table with historical rate cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the hardcoded Anthropic pricing table with a self-calibrating rate cache that derives effective $/token rates from successful runs. Rates are stored in .fullsend-cache/pricing-rates.json and updated via exponential moving average. This handles any model (Anthropic, OpenAI, etc.) without going stale when prices change. Fixes from review: - Restrict suffix-stripping to date suffixes and known tags (exp, preview, etc.) to prevent false matches like gpt-4o-mini → gpt-4o - Exclude ReasoningTokens from rate denominator since the deferred TokensEvent on cancelled runs does not capture them - Surface saveRateCache errors via printer.StepWarn instead of silently discarding - Update cost data contract docs and run.md field description Co-Authored-By: Claude Opus 4.6 --- docs/cli/run.md | 2 +- .../infrastructure/distributed-tracing.md | 14 +- internal/cli/pricing.go | 229 +++++++++--- internal/cli/pricing_test.go | 336 +++++++++++++----- internal/cli/run.go | 22 +- 5 files changed, 437 insertions(+), 166 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 96500184cf..708c084ecb 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -94,7 +94,7 @@ Each run produces artifacts in the output directory: | `requested_model` | Model the harness/agent requested | | `override_source` | Where `requested_model` came from (`--model flag`, `FULLSEND_MODEL`, `FULLSEND_PI_MODEL`, `FULLSEND_CODEX_MODEL`, ` agents.`, `harness`, `default`), suffixed `, remapped by models.aliases` when a per-repo alias override applied to it | | `runtime_source` | Where `requested_runtime` came from (`--runtime flag`, `FULLSEND_RUNTIME`, the config file path — suffixed ` agents.` when the agent's entry decided — or `default (config not found)`) | -| `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | +| `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations). On cancelled runs where the runtime never reports cost, fullsend estimates from cached per-model rates derived from prior successful runs. See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | | `num_turns` | Number of conversation turns | | `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) | | `per_model_usage` | Per-model-spec breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled). See below | diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index 5d407f1e30..a2526c17de 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -249,11 +249,15 @@ example, two iterations at `$0.414` and `$0.415` round individually to `$0.83` — or, with different fractional values, the aggregate may round differently than the sum of parts. -### No pricing-table fallback - -If a runtime does not report cost (returns zero or the field is absent), -fullsend records zero. There is no fallback cost calculation from token -counts. A missing runtime cost propagates as `$0.00` on all surfaces. +### Estimated cost on cancelled runs + +When a run completes normally, the runtime reports an authoritative cost +via the terminal `ResultEvent`. When a run is cancelled before that event, +fullsend estimates cost from cached per-model rates derived from prior +successful runs. The rates are stored in `.fullsend-cache/pricing-rates.json` +and update automatically via an exponential moving average. When no cached +rate exists for a model (e.g. first run in a fresh CI environment), the +cost remains `$0.00`. ### Distinction from backend-derived cost estimates diff --git a/internal/cli/pricing.go b/internal/cli/pricing.go index bee7f520ba..c75ab16adb 100644 --- a/internal/cli/pricing.go +++ b/internal/cli/pricing.go @@ -1,105 +1,220 @@ package cli import ( + "encoding/json" + "os" + "path/filepath" "strings" + "time" agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" ) -// modelRates holds per-million-token prices (USD) for an Anthropic model. -type modelRates struct { - Input float64 - Output float64 - CacheWrite float64 - CacheRead float64 +// cachedRate stores a model's blended per-token USD rate derived from +// successful runs. The exponential moving average smooths out runs with +// unusual cache-hit ratios. +type cachedRate struct { + RatePerToken float64 `json:"rate_per_token"` + SampleCount int `json:"sample_count"` + UpdatedAt time.Time `json:"updated_at"` } -// knownModelRates maps model-ID prefixes to their published rates. -// Source: https://docs.anthropic.com/en/docs/about-claude/pricing -var knownModelRates = map[string]modelRates{ - "claude-fable-5-1": {10, 50, 12.50, 0.25}, - "claude-mythos-5-1": {10, 50, 12.50, 0.25}, - "claude-fable-5": {10, 50, 12.50, 1}, - "claude-mythos-5": {10, 50, 12.50, 1}, - "claude-opus-5": {5, 25, 6.25, 0.50}, - "claude-opus-4-8": {5, 25, 6.25, 0.50}, - "claude-opus-4-7": {5, 25, 6.25, 0.50}, - "claude-opus-4-6": {5, 25, 6.25, 0.50}, - "claude-opus-4-5": {5, 25, 6.25, 0.50}, - "claude-sonnet-5": {2, 10, 2.50, 0.20}, - "claude-sonnet-4-6": {3, 15, 3.75, 0.30}, - "claude-sonnet-4-5": {3, 15, 3.75, 0.30}, - "claude-haiku-4-5": {1, 5, 1.25, 0.10}, - "claude-haiku-3-5": {0.80, 4, 1, 0.08}, +// rateCache is the on-disk format for pricing-rates.json. +type rateCache struct { + Rates map[string]cachedRate `json:"rates"` } -// lookupRates resolves a model ID to its pricing rates. It handles -// provider prefixes ("anthropic-vertex/claude-opus-4-6") and trailing -// date suffixes ("claude-haiku-4-5-20251001"). -func lookupRates(model string) (modelRates, bool) { +func rateCachePath(fullsendDir string) string { + return filepath.Join(fullsendDir, ".fullsend-cache", "pricing-rates.json") +} + +// normalizeModelKey strips the provider prefix from a model spec for use +// as a cache key. "anthropic-vertex/claude-opus-4-6" → "claude-opus-4-6". +func normalizeModelKey(model string) string { if _, after, ok := strings.Cut(model, "/"); ok { - model = after + return after } - if r, ok := knownModelRates[model]; ok { + return model +} + +func loadRateCache(fullsendDir string) rateCache { + data, err := os.ReadFile(rateCachePath(fullsendDir)) + if err != nil { + return rateCache{Rates: make(map[string]cachedRate)} + } + var rc rateCache + if err := json.Unmarshal(data, &rc); err != nil || rc.Rates == nil { + return rateCache{Rates: make(map[string]cachedRate)} + } + return rc +} + +func saveRateCache(fullsendDir string, rc rateCache) error { + p := rateCachePath(fullsendDir) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + data, err := json.MarshalIndent(rc, "", " ") + if err != nil { + return err + } + tmp := p + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, p) +} + +// isStrippableSuffix reports whether a trailing dash-delimited segment is +// safe to strip during model-name fallback. Only date suffixes (all digits, +// 6+ chars like "20260301") and known non-identity tags are strippable. +// This prevents false matches like gpt-4o-mini → gpt-4o. +func isStrippableSuffix(s string) bool { + if len(s) >= 6 { + allDigits := true + for _, c := range s { + if c < '0' || c > '9' { + allDigits = false + break + } + } + if allDigits { + return true + } + } + switch s { + case "exp", "preview", "latest", "beta": + return true + } + return false +} + +// lookupCachedRate resolves a model to its cached rate. Tries exact match +// first (after provider-prefix strip), then strips trailing date suffixes +// and known non-identity tags like "exp" or "preview". +func lookupCachedRate(rc rateCache, model string) (cachedRate, bool) { + key := normalizeModelKey(model) + if r, ok := rc.Rates[key]; ok { return r, true } - for s := model; ; { + for s := key; ; { i := strings.LastIndex(s, "-") if i <= 0 { break } + suffix := s[i+1:] + if !isStrippableSuffix(suffix) { + break + } s = s[:i] - if r, ok := knownModelRates[s]; ok { + if r, ok := rc.Rates[s]; ok { return r, true } } - return modelRates{}, false + return cachedRate{}, false } -func estimateCostFromTokens(model string, input, output, reasoning, cacheWrite, cacheRead int) float64 { - rates, ok := lookupRates(model) - if !ok { - return 0 +func sumTokens(input, output, reasoning, cacheWrite, cacheRead int) int { + return input + output + reasoning + cacheWrite + cacheRead +} + +const emaAlpha = 0.3 + +func updateRate(existing cachedRate, exists bool, newRate float64) cachedRate { + rate := newRate + count := 1 + if exists { + rate = emaAlpha*newRate + (1-emaAlpha)*existing.RatePerToken + count = existing.SampleCount + 1 + } + return cachedRate{ + RatePerToken: rate, + SampleCount: count, + UpdatedAt: time.Now(), } - return (float64(input)*rates.Input + - float64(output+reasoning)*rates.Output + - float64(cacheWrite)*rates.CacheWrite + - float64(cacheRead)*rates.CacheRead) / 1_000_000 +} + +// recordModelRates writes blended per-model rates from a successful run +// to the on-disk cache. No-op when TotalCostUSD is zero. Returns an error +// if the cache file cannot be written. +func recordModelRates(fullsendDir string, m *agentruntime.RunMetrics) error { + if m.TotalCostUSD <= 0 || fullsendDir == "" { + return nil + } + + rc := loadRateCache(fullsendDir) + + if len(m.PerModelUsage) > 0 { + for spec, u := range m.PerModelUsage { + total := sumTokens(u.InputTokens, u.OutputTokens, 0, + u.CacheCreationInputTokens, u.CacheReadInputTokens) + if total == 0 || u.CostUSD <= 0 { + continue + } + key := normalizeModelKey(spec) + existing, exists := rc.Rates[key] + rc.Rates[key] = updateRate(existing, exists, u.CostUSD/float64(total)) + } + } else { + // Exclude ReasoningTokens: the deferred TokensEvent on cancelled + // runs does not capture them, so the rate denominator must match + // the token types available during estimation. + total := sumTokens(m.InputTokens, m.OutputTokens, 0, + m.CacheCreationInputTokens, m.CacheReadInputTokens) + if total == 0 { + return nil + } + key := normalizeModelKey(m.Model) + existing, exists := rc.Rates[key] + rc.Rates[key] = updateRate(existing, exists, m.TotalCostUSD/float64(total)) + } + + return saveRateCache(fullsendDir, rc) } // estimateRunMetricsCost fills in TotalCostUSD on per-iteration RunMetrics -// when it is zero but tokens are present. -func estimateRunMetricsCost(m *agentruntime.RunMetrics) { +// when it is zero but tokens are present, using cached rates from prior +// successful runs. No-op when cost is already present or when no cached +// rate exists for the model. +func estimateRunMetricsCost(fullsendDir string, m *agentruntime.RunMetrics) { if m.TotalCostUSD > 0 { return } - totalTokens := m.InputTokens + m.OutputTokens + - m.CacheCreationInputTokens + m.CacheReadInputTokens - if totalTokens == 0 { + total := sumTokens(m.InputTokens, m.OutputTokens, m.ReasoningTokens, + m.CacheCreationInputTokens, m.CacheReadInputTokens) + if total == 0 || fullsendDir == "" { return } + rc := loadRateCache(fullsendDir) + if len(m.PerModelUsage) > 0 { - var total float64 + var costSum float64 for spec, u := range m.PerModelUsage { if u.CostUSD > 0 { - total += u.CostUSD + costSum += u.CostUSD continue } - est := estimateCostFromTokens(spec, - u.InputTokens, u.OutputTokens, 0, + tokens := sumTokens(u.InputTokens, u.OutputTokens, 0, u.CacheCreationInputTokens, u.CacheReadInputTokens) - if est > 0 { - u.CostUSD = est - m.PerModelUsage[spec] = u - total += est + if tokens == 0 { + continue } + rate, ok := lookupCachedRate(rc, spec) + if !ok { + continue + } + u.CostUSD = rate.RatePerToken * float64(tokens) + m.PerModelUsage[spec] = u + costSum += u.CostUSD } - m.TotalCostUSD = total + m.TotalCostUSD = costSum return } - m.TotalCostUSD = estimateCostFromTokens(m.Model, - m.InputTokens, m.OutputTokens, m.ReasoningTokens, - m.CacheCreationInputTokens, m.CacheReadInputTokens) + rate, ok := lookupCachedRate(rc, m.Model) + if !ok { + return + } + m.TotalCostUSD = rate.RatePerToken * float64(total) } diff --git a/internal/cli/pricing_test.go b/internal/cli/pricing_test.go index fd711773ed..0dc45191c5 100644 --- a/internal/cli/pricing_test.go +++ b/internal/cli/pricing_test.go @@ -2,6 +2,8 @@ package cli import ( "math" + "os" + "path/filepath" "testing" agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" @@ -11,113 +13,148 @@ func almostEqual(a, b, tol float64) bool { return math.Abs(a-b) < tol } -func TestLookupRates_ExactMatch(t *testing.T) { - r, ok := lookupRates("claude-sonnet-5") - if !ok { - t.Fatal("expected match for claude-sonnet-5") +func seedCache(t *testing.T, dir string, model string, cost float64, input, output, cacheWrite, cacheRead int) { + t.Helper() + m := &agentruntime.RunMetrics{ + TotalCostUSD: cost, + Model: model, + InputTokens: input, + OutputTokens: output, + CacheCreationInputTokens: cacheWrite, + CacheReadInputTokens: cacheRead, } - if r.Input != 2 || r.Output != 10 { - t.Errorf("got Input=%v Output=%v, want 2/10", r.Input, r.Output) + if err := recordModelRates(dir, m); err != nil { + t.Fatalf("seedCache: %v", err) } } -func TestLookupRates_DateSuffix(t *testing.T) { - r, ok := lookupRates("claude-haiku-4-5-20251001") - if !ok { - t.Fatal("expected match for claude-haiku-4-5-20251001") +func TestRecordAndEstimate_SingleModel(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "claude-opus-4-6", 0.50, 10000, 5000, 2000, 8000) + + m := &agentruntime.RunMetrics{ + Model: "claude-opus-4-6", + InputTokens: 20000, + OutputTokens: 10000, + CacheCreationInputTokens: 4000, + CacheReadInputTokens: 16000, } - if r.Input != 1 || r.Output != 5 { - t.Errorf("got Input=%v Output=%v, want 1/5", r.Input, r.Output) + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD <= 0 { + t.Fatal("expected non-zero estimated cost") + } + // rate = 0.50 / 25000 = 0.00002; cost = 0.00002 * 50000 = 1.00 + if !almostEqual(m.TotalCostUSD, 1.0, 0.001) { + t.Errorf("got %v, want ~1.0", m.TotalCostUSD) } } -func TestLookupRates_ProviderPrefix(t *testing.T) { - r, ok := lookupRates("anthropic-vertex/claude-opus-4-6") - if !ok { - t.Fatal("expected match for anthropic-vertex/claude-opus-4-6") +func TestRecordAndEstimate_ProviderPrefix(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "anthropic-vertex/claude-opus-4-6", 0.25, 5000, 2500, 1000, 4000) + + m := &agentruntime.RunMetrics{ + Model: "anthropic-vertex/claude-opus-4-6", + InputTokens: 5000, + OutputTokens: 2500, } - if r.Input != 5 || r.Output != 25 { - t.Errorf("got Input=%v Output=%v, want 5/25", r.Input, r.Output) + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD <= 0 { + t.Fatal("expected non-zero cost") } } -func TestLookupRates_ProviderPrefixWithDate(t *testing.T) { - r, ok := lookupRates("anthropic/claude-sonnet-4-5-20241022") - if !ok { - t.Fatal("expected match for anthropic/claude-sonnet-4-5-20241022") +func TestRecordAndEstimate_DateSuffixFallback(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "claude-haiku-4-5", 0.10, 10000, 5000, 0, 0) + + m := &agentruntime.RunMetrics{ + Model: "claude-haiku-4-5-20260301", + InputTokens: 10000, + OutputTokens: 5000, } - if r.Input != 3 || r.Output != 15 { - t.Errorf("got Input=%v Output=%v, want 3/15", r.Input, r.Output) + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD <= 0 { + t.Fatal("expected fallback to match claude-haiku-4-5") } } -func TestLookupRates_CompoundSuffix(t *testing.T) { - r, ok := lookupRates("claude-opus-4-6-exp-20250826") - if !ok { - t.Fatal("expected match for claude-opus-4-6-exp-20250826") +func TestEstimate_NoCache(t *testing.T) { + dir := t.TempDir() + m := &agentruntime.RunMetrics{ + Model: "gpt-4o", + InputTokens: 10000, + OutputTokens: 5000, } - if r.Input != 5 { - t.Errorf("got Input=%v, want 5", r.Input) + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD != 0 { + t.Errorf("expected 0 with no cache, got %v", m.TotalCostUSD) } } -func TestLookupRates_Unknown(t *testing.T) { - _, ok := lookupRates("gpt-4o") - if ok { - t.Fatal("expected no match for gpt-4o") +func TestEstimate_Noop_WhenCostPresent(t *testing.T) { + dir := t.TempDir() + m := &agentruntime.RunMetrics{ + TotalCostUSD: 0.50, + Model: "claude-opus-4-6", + InputTokens: 10000, + OutputTokens: 5000, } -} - -func TestLookupRates_Empty(t *testing.T) { - _, ok := lookupRates("") - if ok { - t.Fatal("expected no match for empty string") + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD != 0.50 { + t.Errorf("cost changed from 0.50 to %v", m.TotalCostUSD) } } -func TestEstimateCostFromTokens(t *testing.T) { - cost := estimateCostFromTokens("claude-sonnet-5", 10000, 5000, 0, 0, 0) - if !almostEqual(cost, 0.07, 0.0001) { - t.Errorf("got %v, want 0.07", cost) +func TestEstimate_Noop_EmptyDir(t *testing.T) { + m := &agentruntime.RunMetrics{ + Model: "claude-opus-4-6", + InputTokens: 10000, + OutputTokens: 5000, } -} - -func TestEstimateCostFromTokens_WithCache(t *testing.T) { - cost := estimateCostFromTokens("claude-opus-5", 5000, 2000, 0, 10000, 20000) - if !almostEqual(cost, 0.1475, 0.0001) { - t.Errorf("got %v, want 0.1475", cost) + estimateRunMetricsCost("", m) + if m.TotalCostUSD != 0 { + t.Errorf("expected 0 with empty dir, got %v", m.TotalCostUSD) } } -func TestEstimateCostFromTokens_WithReasoning(t *testing.T) { - cost := estimateCostFromTokens("claude-sonnet-5", 1000, 500, 2000, 0, 0) - if !almostEqual(cost, 0.027, 0.0001) { - t.Errorf("got %v, want 0.027", cost) +func TestRecord_Noop_ZeroCost(t *testing.T) { + dir := t.TempDir() + if err := recordModelRates(dir, &agentruntime.RunMetrics{ + Model: "claude-opus-4-6", + InputTokens: 10000, + OutputTokens: 5000, + }); err != nil { + t.Fatal(err) } -} - -func TestEstimateCostFromTokens_UnknownModel(t *testing.T) { - cost := estimateCostFromTokens("unknown-model", 10000, 5000, 0, 0, 0) - if cost != 0 { - t.Errorf("expected 0 for unknown model, got %v", cost) + _, err := os.ReadFile(rateCachePath(dir)) + if err == nil { + t.Fatal("expected no cache file when cost is zero") } } -func TestEstimateRunMetricsCost(t *testing.T) { - m := &agentruntime.RunMetrics{ - Model: "claude-opus-4-6", - InputTokens: 20000, - OutputTokens: 8000, - CacheCreationInputTokens: 5000, - CacheReadInputTokens: 50000, - } - estimateRunMetricsCost(m) - if !almostEqual(m.TotalCostUSD, 0.35625, 0.001) { - t.Errorf("got %v, want 0.35625", m.TotalCostUSD) +func TestRecordAndEstimate_PerModelUsage(t *testing.T) { + dir := t.TempDir() + if err := recordModelRates(dir, &agentruntime.RunMetrics{ + TotalCostUSD: 0.15, + InputTokens: 15000, + OutputTokens: 8000, + PerModelUsage: map[string]agentruntime.ModelUsage{ + "anthropic-vertex/claude-sonnet-5": { + InputTokens: 10000, + OutputTokens: 5000, + CostUSD: 0.10, + }, + "anthropic-vertex/claude-haiku-4-5": { + InputTokens: 5000, + OutputTokens: 3000, + CostUSD: 0.05, + }, + }, + }); err != nil { + t.Fatal(err) } -} -func TestEstimateRunMetricsCost_PerModelUsage(t *testing.T) { m := &agentruntime.RunMetrics{ InputTokens: 15000, OutputTokens: 8000, @@ -132,21 +169,22 @@ func TestEstimateRunMetricsCost_PerModelUsage(t *testing.T) { }, }, } - estimateRunMetricsCost(m) - // sonnet: (10000*2 + 5000*10) / 1e6 = 0.07 - // haiku: (5000*1 + 3000*5) / 1e6 = 0.02 - if !almostEqual(m.TotalCostUSD, 0.09, 0.001) { - t.Errorf("got %v, want 0.09", m.TotalCostUSD) - } - if !almostEqual(m.PerModelUsage["anthropic-vertex/claude-sonnet-5"].CostUSD, 0.07, 0.001) { - t.Errorf("sonnet cost = %v, want 0.07", m.PerModelUsage["anthropic-vertex/claude-sonnet-5"].CostUSD) + estimateRunMetricsCost(dir, m) + + if m.TotalCostUSD <= 0 { + t.Fatal("expected non-zero total cost") } - if !almostEqual(m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"].CostUSD, 0.02, 0.001) { - t.Errorf("haiku cost = %v, want 0.02", m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"].CostUSD) + sonnet := m.PerModelUsage["anthropic-vertex/claude-sonnet-5"] + haiku := m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"] + if sonnet.CostUSD <= 0 || haiku.CostUSD <= 0 { + t.Errorf("per-model costs not filled: sonnet=%v haiku=%v", sonnet.CostUSD, haiku.CostUSD) } } -func TestEstimateRunMetricsCost_PerModelUsage_MixedCosts(t *testing.T) { +func TestRecordAndEstimate_PerModelUsage_MixedCosts(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "claude-haiku-4-5", 0.05, 5000, 3000, 0, 0) + m := &agentruntime.RunMetrics{ InputTokens: 15000, OutputTokens: 8000, @@ -162,24 +200,134 @@ func TestEstimateRunMetricsCost_PerModelUsage_MixedCosts(t *testing.T) { }, }, } - estimateRunMetricsCost(m) - if !almostEqual(m.TotalCostUSD, 0.09, 0.001) { - t.Errorf("got %v, want 0.09", m.TotalCostUSD) - } + estimateRunMetricsCost(dir, m) + if m.PerModelUsage["anthropic/claude-sonnet-5"].CostUSD != 0.07 { t.Error("existing CostUSD was overwritten") } + if m.PerModelUsage["anthropic/claude-haiku-4-5"].CostUSD <= 0 { + t.Error("haiku cost should be estimated from cache") + } + if m.TotalCostUSD <= 0.07 { + t.Error("total should include both models") + } } -func TestEstimateRunMetricsCost_Noop_WhenCostPresent(t *testing.T) { +func TestEMA_SmoothsRates(t *testing.T) { + dir := t.TempDir() + // First sample: rate = 0.10 / 10000 = 0.00001 + seedCache(t, dir, "claude-opus-4-6", 0.10, 5000, 5000, 0, 0) + // Second sample: rate = 0.20 / 10000 = 0.00002 + // EMA: 0.3 * 0.00002 + 0.7 * 0.00001 = 0.000013 + seedCache(t, dir, "claude-opus-4-6", 0.20, 5000, 5000, 0, 0) + + rc := loadRateCache(dir) + rate, ok := rc.Rates["claude-opus-4-6"] + if !ok { + t.Fatal("expected cached rate") + } + if !almostEqual(rate.RatePerToken, 0.000013, 0.0000001) { + t.Errorf("EMA rate = %v, want ~0.000013", rate.RatePerToken) + } + if rate.SampleCount != 2 { + t.Errorf("sample count = %d, want 2", rate.SampleCount) + } +} + +func TestNormalizeModelKey(t *testing.T) { + tests := []struct { + input string + want string + }{ + {"claude-opus-4-6", "claude-opus-4-6"}, + {"anthropic-vertex/claude-opus-4-6", "claude-opus-4-6"}, + {"anthropic/claude-sonnet-5", "claude-sonnet-5"}, + {"gpt-4o", "gpt-4o"}, + {"openai/gpt-4o", "gpt-4o"}, + } + for _, tt := range tests { + got := normalizeModelKey(tt.input) + if got != tt.want { + t.Errorf("normalizeModelKey(%q) = %q, want %q", tt.input, got, tt.want) + } + } +} + +func TestLookupCachedRate_ExactThenSuffix(t *testing.T) { + rc := rateCache{Rates: map[string]cachedRate{ + "claude-opus-4-6": {RatePerToken: 0.00002, SampleCount: 3}, + "gpt-4o": {RatePerToken: 0.00001, SampleCount: 2}, + }} + + if _, ok := lookupCachedRate(rc, "claude-opus-4-6"); !ok { + t.Error("exact match failed") + } + if _, ok := lookupCachedRate(rc, "anthropic-vertex/claude-opus-4-6"); !ok { + t.Error("provider-prefix match failed") + } + if _, ok := lookupCachedRate(rc, "claude-opus-4-6-20260301"); !ok { + t.Error("date-suffix fallback failed") + } + if _, ok := lookupCachedRate(rc, "anthropic/claude-opus-4-6-exp-20260301"); !ok { + t.Error("compound suffix fallback failed") + } + if _, ok := lookupCachedRate(rc, "uncached-model"); ok { + t.Error("expected no match for uncached model") + } +} + +func TestLookupCachedRate_NoFalseMatchAcrossModels(t *testing.T) { + rc := rateCache{Rates: map[string]cachedRate{ + "gpt-4o": {RatePerToken: 0.00001, SampleCount: 2}, + }} + + if _, ok := lookupCachedRate(rc, "gpt-4o-mini"); ok { + t.Error("gpt-4o-mini must NOT match gpt-4o (different model, ~30x price difference)") + } + if _, ok := lookupCachedRate(rc, "gpt-4o-mini-20260301"); ok { + t.Error("gpt-4o-mini-20260301 must NOT match gpt-4o") + } + if _, ok := lookupCachedRate(rc, "gpt-4o"); !ok { + t.Error("exact match for gpt-4o should still work") + } + if _, ok := lookupCachedRate(rc, "gpt-4o-20260301"); !ok { + t.Error("date-suffix fallback for gpt-4o should work") + } +} + +func TestCacheFileAtomicity(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "claude-opus-4-6", 0.50, 10000, 5000, 0, 0) + + p := rateCachePath(dir) + if _, err := os.Stat(p); err != nil { + t.Fatalf("cache file missing: %v", err) + } + tmp := p + ".tmp" + if _, err := os.Stat(tmp); err == nil { + t.Error("tmp file should not persist after atomic write") + } + + cacheDir := filepath.Dir(p) + if _, err := os.Stat(cacheDir); err != nil { + t.Fatalf("cache dir missing: %v", err) + } +} + +func TestRecordAndEstimate_OpenAIModel(t *testing.T) { + dir := t.TempDir() + seedCache(t, dir, "openai/gpt-4o", 0.30, 20000, 10000, 0, 0) + m := &agentruntime.RunMetrics{ - TotalCostUSD: 0.50, - Model: "claude-sonnet-5", + Model: "openai/gpt-4o", InputTokens: 10000, OutputTokens: 5000, } - estimateRunMetricsCost(m) - if m.TotalCostUSD != 0.50 { - t.Errorf("cost changed from 0.50 to %v", m.TotalCostUSD) + estimateRunMetricsCost(dir, m) + if m.TotalCostUSD <= 0 { + t.Fatal("expected non-zero cost for cached OpenAI model") + } + if !almostEqual(m.TotalCostUSD, 0.15, 0.001) { + t.Errorf("got %v, want ~0.15", m.TotalCostUSD) } } diff --git a/internal/cli/run.go b/internal/cli/run.go index 5a006761fb..0adccc478d 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2268,10 +2268,14 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } } - // Estimate USD cost from tokens when the authoritative cost is - // missing (zero) — e.g. cancelled runs that never receive the - // result event. On successful runs this is a no-op. - estimateRunMetricsCost(&metrics) + // Record per-model rates from successful runs for future cost + // estimation; estimate USD cost from cached rates when the + // authoritative cost is missing (cancelled runs). Each call + // is a no-op when its precondition doesn't hold. + if err := recordModelRates(absFullsendDir, &metrics); err != nil { + printer.StepWarn(fmt.Sprintf("pricing rate cache: %v", err)) + } + estimateRunMetricsCost(absFullsendDir, &metrics) // Accumulate behavioral metrics across iterations. aggregateRunMetrics(&aggMetrics, &metrics, iteration) @@ -3716,11 +3720,11 @@ func transcriptErrorMessage(te agentruntime.TranscriptError) string { // artifact upload step (if: always()) captures the partial usage data // (#6936). // -// NOTE: TotalCostUSD is estimated from token counts and the published -// rate table when the authoritative cost is missing (cancelled runs never -// emit the terminal ResultEvent). The estimate uses 5-minute cache-write -// rates and is zero if the model is unrecognized. See estimateRunMetricsCost -// and #6936 for background. +// NOTE: TotalCostUSD is estimated from cached per-model rates derived +// from prior successful runs when the authoritative cost is missing +// (cancelled runs never emit the terminal ResultEvent). The estimate +// is zero if no cached rate exists for the model. See +// recordModelRates, estimateRunMetricsCost, and #6936 for background. // // cancelled is false when ctx is still live, in which case the caller's // normal control flow continues unchanged; the other return values are From 1ea267e195c66c690d00f77e1dded8e74c264b79 Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 12:18:30 -0400 Subject: [PATCH 3/7] fix: three-layer signal fix for cancelled run telemetry (#6936) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Layer 1 — action.yml: use `exec fullsend run` so signals go directly to fullsend instead of bash. Without exec, bash exits on SIGINT, fullsend becomes an orphan, and GHA kills it before cleanup can flush telemetry. Layer 2 — ExecStreamReader: send SIGINT (not SIGKILL) to openshell on context cancellation with a 5s WaitDelay, giving Claude Code time to flush its result event through the pipe. Layer 3 — parseClaudeStream: extract token usage from assistant-event messages (stream-json format) as fallback when stream_event wrappers are absent. Without this, the deferred TokensEvent on cancelled runs reports zero tokens. Co-Authored-By: Claude Opus 4.6 --- action.yml | 6 +- internal/runtime/claude_progress.go | 32 ++++++++++ internal/runtime/claude_progress_test.go | 76 ++++++++++++++++++++++++ internal/sandbox/sandbox.go | 11 +++- internal/sandbox/sandbox_test.go | 48 +++++++++++++++ 5 files changed, 169 insertions(+), 4 deletions(-) diff --git a/action.yml b/action.yml index 9ed38708da..6c21e5ebaf 100644 --- a/action.yml +++ b/action.yml @@ -446,7 +446,11 @@ runs: if [[ -n "${MINT_URL}" ]]; then MINT_FLAGS+=(--mint-url "${MINT_URL}") fi - fullsend run "${AGENT}" \ + # exec replaces the shell so signals (SIGINT/SIGTERM from GHA + # cancellation) go directly to fullsend, preventing it from being + # orphaned and killed before its cleanup path can flush telemetry + # and metrics (#6936). + exec fullsend run "${AGENT}" \ --fullsend-dir "${FULLSEND_DIR}" \ --output-dir "${GITHUB_WORKSPACE}/output" \ --target-repo "${TARGET_REPO}" \ diff --git a/internal/runtime/claude_progress.go b/internal/runtime/claude_progress.go index c0192d59c1..b5e1f7af1a 100644 --- a/internal/runtime/claude_progress.go +++ b/internal/runtime/claude_progress.go @@ -63,6 +63,12 @@ type assistantMessage struct { Message struct { Content json.RawMessage `json:"content"` Model string `json:"model"` + Usage struct { + InputTokens int `json:"input_tokens"` + OutputTokens int `json:"output_tokens"` + CacheCreationInputTokens int `json:"cache_creation_input_tokens"` + CacheReadInputTokens int `json:"cache_read_input_tokens"` + } `json:"usage"` } `json:"message"` } @@ -345,6 +351,32 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { onEvent(InitEvent{Model: msg.Message.Model}) } + // Track usage from assistant messages when stream_events + // are not present (stream-json output format). + u := msg.Message.Usage + if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadInputTokens > 0 || u.CacheCreationInputTokens > 0 { + cumulativeInput += totalInput + cumulativeOutput += totalOutput + cumulativeCacheRead += totalCacheRead + cumulativeCacheWrite += totalCacheWrite + totalInput = u.InputTokens + totalOutput = u.OutputTokens + totalCacheRead = u.CacheReadInputTokens + totalCacheWrite = u.CacheCreationInputTokens + + total := cumulativeInput + totalInput + cumulativeOutput + totalOutput + + cumulativeCacheRead + totalCacheRead + cumulativeCacheWrite + totalCacheWrite + if total-lastEmittedTotal >= tokenThreshold { + lastEmittedTotal = total + onEvent(TokensEvent{ + InputTokens: cumulativeInput + totalInput, + OutputTokens: cumulativeOutput + totalOutput, + CacheRead: cumulativeCacheRead + totalCacheRead, + CacheWrite: cumulativeCacheWrite + totalCacheWrite, + }) + } + } + // Real Claude Code output nests content under "message"; // fall back to the top-level "content" for older/flat shapes. content := msg.Message.Content diff --git a/internal/runtime/claude_progress_test.go b/internal/runtime/claude_progress_test.go index ca1c5f4f58..d09f3f3211 100644 --- a/internal/runtime/claude_progress_test.go +++ b/internal/runtime/claude_progress_test.go @@ -1325,3 +1325,79 @@ func TestParseClaudeStreamFinalTokensEventOnCancel(t *testing.T) { t.Errorf("expected 500 output tokens, got %d", tokens[0].OutputTokens) } } + +func TestParseClaudeStreamAssistantUsageFallback(t *testing.T) { + // When stream_event events are absent (stream-json format), usage + // should be extracted from assistant message events. + lines := []string{ + `{"type":"system","subtype":"init","model":"claude-opus-4-6"}`, + `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"hello"}],"usage":{"input_tokens":3000,"output_tokens":500,"cache_read_input_tokens":12000,"cache_creation_input_tokens":2000}}}`, + `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]}}`, + `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":4000,"output_tokens":800,"cache_read_input_tokens":14000,"cache_creation_input_tokens":1000}}}`, + // No result event — cancelled run. + } + + events := collectEvents(t, strings.Join(lines, "\n")) + + var tokens []TokensEvent + for _, e := range events { + if te, ok := e.(TokensEvent); ok { + tokens = append(tokens, te) + } + } + + if len(tokens) == 0 { + t.Fatal("expected at least one TokensEvent from assistant usage fallback") + } + last := tokens[len(tokens)-1] + // Cumulative: msg1 input=3000+msg2 input=4000=7000 + if last.InputTokens != 7000 { + t.Errorf("expected 7000 cumulative input tokens, got %d", last.InputTokens) + } + // Cumulative: msg1 output=500+msg2 output=800=1300 + if last.OutputTokens != 1300 { + t.Errorf("expected 1300 cumulative output tokens, got %d", last.OutputTokens) + } + // Cumulative cache read: 12000+14000=26000 + if last.CacheRead != 26000 { + t.Errorf("expected 26000 cumulative cache read, got %d", last.CacheRead) + } + // Cumulative cache write: 2000+1000=3000 + if last.CacheWrite != 3000 { + t.Errorf("expected 3000 cumulative cache write, got %d", last.CacheWrite) + } +} + +func TestProgressParserCancelledRunCapturesTokensFromAssistant(t *testing.T) { + // End-to-end test: progressParser should populate RunMetrics from + // assistant-event usage when no stream_events are present. + lines := []string{ + `{"type":"system","subtype":"init","model":"claude-opus-4-6"}`, + `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"working"}],"usage":{"input_tokens":5000,"output_tokens":1000,"cache_read_input_tokens":10000,"cache_creation_input_tokens":3000}}}`, + } + + input := strings.NewReader(strings.Join(lines, "\n")) + var buf bytes.Buffer + printer := ui.New(&buf) + metrics := &RunMetrics{} + + if err := progressParser(input, printer, metrics); err != nil { + t.Fatalf("progressParser returned error: %v", err) + } + + if metrics.InputTokens != 5000 { + t.Errorf("expected 5000 input tokens, got %d", metrics.InputTokens) + } + if metrics.OutputTokens != 1000 { + t.Errorf("expected 1000 output tokens, got %d", metrics.OutputTokens) + } + if metrics.CacheReadInputTokens != 10000 { + t.Errorf("expected 10000 cache read tokens, got %d", metrics.CacheReadInputTokens) + } + if metrics.CacheCreationInputTokens != 3000 { + t.Errorf("expected 3000 cache creation tokens, got %d", metrics.CacheCreationInputTokens) + } + if metrics.Model != "claude-opus-4-6" { + t.Errorf("expected model claude-opus-4-6, got %s", metrics.Model) + } +} diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 906deb45fb..e349d60278 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1365,9 +1365,12 @@ func ExecContext(ctx context.Context, sandboxName, command string, timeout time. // given writer. The caller must read stdout to completion, then call cmd.Wait(). // // The parent context is used as the base for the timeout context, so -// cancelling the parent (e.g. on SIGTERM) terminates the subprocess. This -// allows CLI-level signal handling to propagate into long-running sandbox -// commands. +// cancelling the parent (e.g. on SIGTERM) terminates the subprocess. On +// context cancellation, SIGINT is sent instead of the default SIGKILL so that +// openshell can forward the signal into the sandbox and the subprocess (e.g. +// Claude Code) has a chance to flush its final output (including cost data). +// A 5-second WaitDelay allows the graceful shutdown to complete before a +// force-kill. func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout time.Duration, stderrW io.Writer) (io.ReadCloser, *exec.Cmd, context.CancelFunc, error) { ctx, cancel := context.WithTimeout(ctx, timeout) timeoutSecs := fmt.Sprintf("%d", int(timeout.Seconds())) @@ -1378,6 +1381,8 @@ func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout "--timeout", timeoutSecs, "--", "sh", "-c", command, ) + cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGINT) } + cmd.WaitDelay = 5 * time.Second cmd.Stderr = stderrW stdout, err := cmd.StdoutPipe() diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index a9867e809e..6dc78b6452 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -303,6 +303,54 @@ func TestExecStreamReader_OpenshellNotInPath(t *testing.T) { assert.Error(t, err) } +func TestExecStreamReader_SendsSIGINTOnCancel(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("SIGINT not supported on Windows") + } + + bin := t.TempDir() + script := filepath.Join(bin, "openshell") + // Use a busy-wait loop instead of sleep so the script works with a + // restricted PATH that doesn't include /usr/bin. + require.NoError(t, os.WriteFile(script, []byte(`#!/bin/sh +trap 'echo "flushed-after-sigint"; exit 0' INT +echo "ready" +while true; do :; done +`), 0o755)) + t.Setenv("PATH", bin) + + ctx, cancel := context.WithCancel(context.Background()) + stdout, cmd, cleanup, err := ExecStreamReader(ctx, "test-sandbox", "echo hello", 30*time.Second, os.Stderr) + require.NoError(t, err) + defer cleanup() + + buf := make([]byte, 64) + n, err := stdout.Read(buf) + require.NoError(t, err) + assert.Contains(t, string(buf[:n]), "ready") + + cancel() + + var all []byte + for { + n, err = stdout.Read(buf) + if n > 0 { + all = append(all, buf[:n]...) + } + if err != nil { + break + } + } + assert.Contains(t, string(all), "flushed-after-sigint", + "subprocess should receive SIGINT (not SIGKILL) and have time to flush output") + + waitErr := cmd.Wait() + _ = waitErr + + assert.Equal(t, 5*time.Second, cmd.WaitDelay, + "WaitDelay should give the subprocess time to flush before force-kill") +} + func TestOsRootContainment(t *testing.T) { dir := t.TempDir() From d708592e7fa8b716172faac45b1b7aa75028ef7c Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 14:12:51 -0400 Subject: [PATCH 4/7] fix: SIGINT-into-sandbox for cancelled run cost data (#6936) The prior Cancel function only SIGINTs the openshell CLI, which does not propagate through gRPC to in-sandbox processes. Claude Code never receives SIGINT and never flushes the result event with total_cost_usd. Four changes fix this: 1. Setsid: isolate openshell from GHA's process-group SIGINT so the relay stays alive to pipe the result event back. 2. PID file: record the in-sandbox process PID at startup so the cancel function can target it directly. 3. Kill-exec: on context cancellation, spawn a separate openshell sandbox exec to send kill -INT to the PID inside the sandbox. 4. exec claude: replace the wrapper shell with claude so the PID file points to claude's process, not the shell. Includes diagnostic stderr output at cancel and stream-end points to verify the mechanism in e2e testing. Co-Authored-By: Claude Opus 4.6 --- internal/runtime/claude.go | 7 ++-- internal/sandbox/sandbox.go | 61 +++++++++++++++++++++++++++----- internal/sandbox/sandbox_test.go | 30 ++++++++++------ 3 files changed, 78 insertions(+), 20 deletions(-) diff --git a/internal/runtime/claude.go b/internal/runtime/claude.go index aeeb06ea88..d8cb0204d3 100644 --- a/internal/runtime/claude.go +++ b/internal/runtime/claude.go @@ -177,7 +177,9 @@ func (ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Prin innerHandler(evt) } - if parseErr := parseClaudeStream(r, handler); parseErr != nil { + parseErr := parseClaudeStream(r, handler) + fmt.Fprintf(os.Stderr, " stream ended: parseErr=%v ctxErr=%v cost=%.4f\n", parseErr, ctx.Err(), metrics.TotalCostUSD) + if parseErr != nil { fmt.Fprintf(os.Stderr, " progress parser: %v\n", sanitizeOutput(parseErr.Error())) cancel() io.Copy(io.Discard, r) @@ -188,6 +190,7 @@ func (ClaudeRuntime) Run(ctx context.Context, params RunParams, printer *ui.Prin if execCmd.ProcessState != nil { exitCode = execCmd.ProcessState.ExitCode() } + fmt.Fprintf(os.Stderr, " wait done: exitCode=%d waitErr=%v\n", exitCode, waitErr) if waitErr != nil && execCmd.ProcessState == nil { return exitCode, fmt.Errorf("openshell exec failed: %w", waitErr) @@ -350,7 +353,7 @@ func buildRunCommand(params RunParams) string { safe := strings.ReplaceAll(params.AgentBaseName, "'", "'\\''") parts := []string{ - fmt.Sprintf("cd %s && . %s && claude", params.RepoDir, envFile), + fmt.Sprintf("cd %s && . %s && exec claude", params.RepoDir, envFile), "--print", "--verbose", "--output-format stream-json", diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index e349d60278..4009bc7834 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1360,29 +1360,74 @@ func ExecContext(ctx context.Context, sandboxName, command string, timeout time. return stdoutBuf.String(), stderrBuf.String(), exitCode, nil } +// execPIDFile is the path inside the sandbox where the exec'd process PID +// is recorded so the cancel function can send SIGINT to it. +const execPIDFile = "/tmp/.fullsend_exec.pid" + // ExecStreamReader runs a command inside a sandbox, returning an io.ReadCloser for // stdout so the caller can parse structured output. Stderr is forwarded to the // given writer. The caller must read stdout to completion, then call cmd.Wait(). // // The parent context is used as the base for the timeout context, so // cancelling the parent (e.g. on SIGTERM) terminates the subprocess. On -// context cancellation, SIGINT is sent instead of the default SIGKILL so that -// openshell can forward the signal into the sandbox and the subprocess (e.g. -// Claude Code) has a chance to flush its final output (including cost data). -// A 5-second WaitDelay allows the graceful shutdown to complete before a -// force-kill. +// context cancellation, a separate openshell exec call sends SIGINT to the +// in-sandbox process (identified by a PID file written at startup). This is +// necessary because SIGINT to the openshell CLI does not propagate through +// gRPC to in-sandbox processes. The openshell relay process is left running +// so it continues piping stdout (e.g. Claude Code's terminal result event +// with cost data). A 5-second WaitDelay allows the graceful shutdown to +// complete; after that Go kills the openshell process. func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout time.Duration, stderrW io.Writer) (io.ReadCloser, *exec.Cmd, context.CancelFunc, error) { ctx, cancel := context.WithTimeout(ctx, timeout) timeoutSecs := fmt.Sprintf("%d", int(timeout.Seconds())) + // Prepend a PID-file write so the cancel function can target the + // in-sandbox process. Callers that use "exec" in their command (e.g. + // buildRunCommand) replace the shell, so the PID file points to the + // final process. + wrapped := fmt.Sprintf("echo $$ > %s; %s", execPIDFile, command) + cmd := exec.CommandContext(ctx, "openshell", "sandbox", "exec", "--name", sandboxName, "--no-tty", "--timeout", timeoutSecs, - "--", "sh", "-c", command, + "--", "sh", "-c", wrapped, ) - cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGINT) } - cmd.WaitDelay = 5 * time.Second + // Put openshell in its own session so process-group-wide signals + // (SIGINT from GHA cancellation) don't kill it before cmd.Cancel + // has a chance to send SIGINT into the sandbox and relay the + // result event through stdout. + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} + cmd.Cancel = func() error { + fmt.Fprintf(stderrW, " sandbox cancel: sending SIGINT into %s\n", sandboxName) + // Send SIGINT to the in-sandbox process so it can flush final + // output (e.g. Claude Code's result event with total_cost_usd). + // A background context is required because the parent is already + // cancelled. The goroutine runs concurrently so Cancel returns + // immediately and WaitDelay starts without blocking. + killCtx, killCancel := context.WithTimeout(context.Background(), 5*time.Second) + go func() { + defer killCancel() + killScript := fmt.Sprintf( + "PID=$(cat %s 2>/dev/null); echo \"sandbox-cancel: pid=$PID\" >&2; "+ + "kill -INT $PID 2>&1; echo \"sandbox-cancel: kill=$?\" >&2", + execPIDFile) + killCmd := exec.CommandContext(killCtx, "openshell", "sandbox", "exec", //nolint:gosec // sandboxName is not user input + "--name", sandboxName, + "--no-tty", + "--timeout", "5", + "--", "sh", "-c", killScript, + ) + killCmd.Stdout = stderrW + killCmd.Stderr = stderrW + if err := killCmd.Run(); err != nil { + fmt.Fprintf(stderrW, " sandbox cancel: kill-exec failed: %v\n", err) + } + }() + cmd.Process.Signal(syscall.SIGINT) //nolint:errcheck // best-effort; may already be dead + return nil + } + cmd.WaitDelay = 8 * time.Second cmd.Stderr = stderrW stdout, err := cmd.StdoutPipe() diff --git a/internal/sandbox/sandbox_test.go b/internal/sandbox/sandbox_test.go index 6dc78b6452..b72fd9c7f2 100644 --- a/internal/sandbox/sandbox_test.go +++ b/internal/sandbox/sandbox_test.go @@ -310,21 +310,31 @@ func TestExecStreamReader_SendsSIGINTOnCancel(t *testing.T) { bin := t.TempDir() script := filepath.Join(bin, "openshell") - // Use a busy-wait loop instead of sleep so the script works with a - // restricted PATH that doesn't include /usr/bin. + // Fake openshell: pass-through that runs whatever comes after "--". + // This lets the cancel function's separate "openshell sandbox exec" + // call also go through the fake and execute the kill command. require.NoError(t, os.WriteFile(script, []byte(`#!/bin/sh -trap 'echo "flushed-after-sigint"; exit 0' INT -echo "ready" -while true; do :; done +while [ $# -gt 0 ]; do + if [ "$1" = "--" ]; then + shift + exec "$@" + fi + shift +done +echo "no -- found" >&2; exit 1 `), 0o755)) - t.Setenv("PATH", bin) + t.Setenv("PATH", bin+":/bin:/usr/bin") + defer os.Remove(execPIDFile) ctx, cancel := context.WithCancel(context.Background()) - stdout, cmd, cleanup, err := ExecStreamReader(ctx, "test-sandbox", "echo hello", 30*time.Second, os.Stderr) + // The command traps SIGINT and flushes output, simulating Claude Code's + // graceful shutdown that emits the result event with cost data. + testCmd := "trap 'echo flushed-after-sigint; exit 0' INT; echo ready; while true; do :; done" + stdout, cmd, cleanup, err := ExecStreamReader(ctx, "test-sandbox", testCmd, 30*time.Second, os.Stderr) require.NoError(t, err) defer cleanup() - buf := make([]byte, 64) + buf := make([]byte, 256) n, err := stdout.Read(buf) require.NoError(t, err) assert.Contains(t, string(buf[:n]), "ready") @@ -342,12 +352,12 @@ while true; do :; done } } assert.Contains(t, string(all), "flushed-after-sigint", - "subprocess should receive SIGINT (not SIGKILL) and have time to flush output") + "in-sandbox process should receive SIGINT via the kill-exec mechanism and flush output") waitErr := cmd.Wait() _ = waitErr - assert.Equal(t, 5*time.Second, cmd.WaitDelay, + assert.Equal(t, 8*time.Second, cmd.WaitDelay, "WaitDelay should give the subprocess time to flush before force-kill") } From 7262bad3e300e7341d8fe18ea8fc8ba3bf5c3fbf Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 14:20:30 -0400 Subject: [PATCH 5/7] fix: stop SIGINTing openshell relay in Cancel (#6936) cmd.Process.Signal(SIGINT) kills openshell immediately, closing the stdout pipe before the kill-exec goroutine can send SIGINT to claude inside the sandbox. Claude's result event (with total_cost_usd) has nowhere to go because the pipe is already dead. Remove the direct SIGINT to openshell. The kill-exec goroutine is the sole mechanism: it sends SIGINT to claude via a separate openshell sandbox exec. Openshell stays alive to relay claude's result event through the pipe. WaitDelay (8s) is the fallback if claude doesn't exit. Co-Authored-By: Claude Opus 4.6 --- internal/sandbox/sandbox.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 4009bc7834..83cd929643 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1424,7 +1424,9 @@ func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout fmt.Fprintf(stderrW, " sandbox cancel: kill-exec failed: %v\n", err) } }() - cmd.Process.Signal(syscall.SIGINT) //nolint:errcheck // best-effort; may already be dead + // Do NOT signal the openshell relay process here. Openshell must + // stay alive to pipe claude's result event (with cost data) back + // through stdout. WaitDelay is the fallback if claude doesn't exit. return nil } cmd.WaitDelay = 8 * time.Second From e0399b7e27e6ba1c8aa53163592a81280b56f528 Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 14:39:03 -0400 Subject: [PATCH 6/7] refactor: remove rejected rate-cache approach, keep only SIGINT-into-sandbox fix (#6936) Remove pricing.go, pricing_test.go, and rate-cache wiring in run.go. Remove assistant-message usage tracking from claude_progress.go (separate concern). Revert doc changes that described the rate-cache approach. Update handleRunCancellation docstring to reflect the SIGINT mechanism. Co-Authored-By: Claude Opus 4.6 --- docs/cli/run.md | 2 +- .../infrastructure/distributed-tracing.md | 14 +- internal/cli/pricing.go | 220 ------------ internal/cli/pricing_test.go | 333 ------------------ internal/cli/run.go | 19 +- internal/runtime/claude_progress.go | 32 -- internal/runtime/claude_progress_test.go | 76 ---- 7 files changed, 11 insertions(+), 685 deletions(-) delete mode 100644 internal/cli/pricing.go delete mode 100644 internal/cli/pricing_test.go diff --git a/docs/cli/run.md b/docs/cli/run.md index 708c084ecb..96500184cf 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -94,7 +94,7 @@ Each run produces artifacts in the output directory: | `requested_model` | Model the harness/agent requested | | `override_source` | Where `requested_model` came from (`--model flag`, `FULLSEND_MODEL`, `FULLSEND_PI_MODEL`, `FULLSEND_CODEX_MODEL`, ` agents.`, `harness`, `default`), suffixed `, remapped by models.aliases` when a per-repo alias override applied to it | | `runtime_source` | Where `requested_runtime` came from (`--runtime flag`, `FULLSEND_RUNTIME`, the config file path — suffixed ` agents.` when the agent's entry decided — or `default (config not found)`) | -| `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations). On cancelled runs where the runtime never reports cost, fullsend estimates from cached per-model rates derived from prior successful runs. See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | +| `total_cost_usd` | Total inference cost in USD, as reported by the runtime (raw floating-point aggregate across all iterations; no fullsend-side pricing-table fallback). See [Cost data contract](../guides/infrastructure/distributed-tracing.md#cost-data-contract) | | `num_turns` | Number of conversation turns | | `iterations` | Number of agent iterations run; an iteration killed at the budget is not retried (see [Budget and deadline](#budget-and-deadline)) | | `per_model_usage` | Per-model-spec breakdown, present only when a runtime reports one (today: `pi` with the `Agent` tool enabled). See below | diff --git a/docs/guides/infrastructure/distributed-tracing.md b/docs/guides/infrastructure/distributed-tracing.md index a2526c17de..5d407f1e30 100644 --- a/docs/guides/infrastructure/distributed-tracing.md +++ b/docs/guides/infrastructure/distributed-tracing.md @@ -249,15 +249,11 @@ example, two iterations at `$0.414` and `$0.415` round individually to `$0.83` — or, with different fractional values, the aggregate may round differently than the sum of parts. -### Estimated cost on cancelled runs - -When a run completes normally, the runtime reports an authoritative cost -via the terminal `ResultEvent`. When a run is cancelled before that event, -fullsend estimates cost from cached per-model rates derived from prior -successful runs. The rates are stored in `.fullsend-cache/pricing-rates.json` -and update automatically via an exponential moving average. When no cached -rate exists for a model (e.g. first run in a fresh CI environment), the -cost remains `$0.00`. +### No pricing-table fallback + +If a runtime does not report cost (returns zero or the field is absent), +fullsend records zero. There is no fallback cost calculation from token +counts. A missing runtime cost propagates as `$0.00` on all surfaces. ### Distinction from backend-derived cost estimates diff --git a/internal/cli/pricing.go b/internal/cli/pricing.go deleted file mode 100644 index c75ab16adb..0000000000 --- a/internal/cli/pricing.go +++ /dev/null @@ -1,220 +0,0 @@ -package cli - -import ( - "encoding/json" - "os" - "path/filepath" - "strings" - "time" - - agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" -) - -// cachedRate stores a model's blended per-token USD rate derived from -// successful runs. The exponential moving average smooths out runs with -// unusual cache-hit ratios. -type cachedRate struct { - RatePerToken float64 `json:"rate_per_token"` - SampleCount int `json:"sample_count"` - UpdatedAt time.Time `json:"updated_at"` -} - -// rateCache is the on-disk format for pricing-rates.json. -type rateCache struct { - Rates map[string]cachedRate `json:"rates"` -} - -func rateCachePath(fullsendDir string) string { - return filepath.Join(fullsendDir, ".fullsend-cache", "pricing-rates.json") -} - -// normalizeModelKey strips the provider prefix from a model spec for use -// as a cache key. "anthropic-vertex/claude-opus-4-6" → "claude-opus-4-6". -func normalizeModelKey(model string) string { - if _, after, ok := strings.Cut(model, "/"); ok { - return after - } - return model -} - -func loadRateCache(fullsendDir string) rateCache { - data, err := os.ReadFile(rateCachePath(fullsendDir)) - if err != nil { - return rateCache{Rates: make(map[string]cachedRate)} - } - var rc rateCache - if err := json.Unmarshal(data, &rc); err != nil || rc.Rates == nil { - return rateCache{Rates: make(map[string]cachedRate)} - } - return rc -} - -func saveRateCache(fullsendDir string, rc rateCache) error { - p := rateCachePath(fullsendDir) - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - return err - } - data, err := json.MarshalIndent(rc, "", " ") - if err != nil { - return err - } - tmp := p + ".tmp" - if err := os.WriteFile(tmp, data, 0o644); err != nil { - return err - } - return os.Rename(tmp, p) -} - -// isStrippableSuffix reports whether a trailing dash-delimited segment is -// safe to strip during model-name fallback. Only date suffixes (all digits, -// 6+ chars like "20260301") and known non-identity tags are strippable. -// This prevents false matches like gpt-4o-mini → gpt-4o. -func isStrippableSuffix(s string) bool { - if len(s) >= 6 { - allDigits := true - for _, c := range s { - if c < '0' || c > '9' { - allDigits = false - break - } - } - if allDigits { - return true - } - } - switch s { - case "exp", "preview", "latest", "beta": - return true - } - return false -} - -// lookupCachedRate resolves a model to its cached rate. Tries exact match -// first (after provider-prefix strip), then strips trailing date suffixes -// and known non-identity tags like "exp" or "preview". -func lookupCachedRate(rc rateCache, model string) (cachedRate, bool) { - key := normalizeModelKey(model) - if r, ok := rc.Rates[key]; ok { - return r, true - } - for s := key; ; { - i := strings.LastIndex(s, "-") - if i <= 0 { - break - } - suffix := s[i+1:] - if !isStrippableSuffix(suffix) { - break - } - s = s[:i] - if r, ok := rc.Rates[s]; ok { - return r, true - } - } - return cachedRate{}, false -} - -func sumTokens(input, output, reasoning, cacheWrite, cacheRead int) int { - return input + output + reasoning + cacheWrite + cacheRead -} - -const emaAlpha = 0.3 - -func updateRate(existing cachedRate, exists bool, newRate float64) cachedRate { - rate := newRate - count := 1 - if exists { - rate = emaAlpha*newRate + (1-emaAlpha)*existing.RatePerToken - count = existing.SampleCount + 1 - } - return cachedRate{ - RatePerToken: rate, - SampleCount: count, - UpdatedAt: time.Now(), - } -} - -// recordModelRates writes blended per-model rates from a successful run -// to the on-disk cache. No-op when TotalCostUSD is zero. Returns an error -// if the cache file cannot be written. -func recordModelRates(fullsendDir string, m *agentruntime.RunMetrics) error { - if m.TotalCostUSD <= 0 || fullsendDir == "" { - return nil - } - - rc := loadRateCache(fullsendDir) - - if len(m.PerModelUsage) > 0 { - for spec, u := range m.PerModelUsage { - total := sumTokens(u.InputTokens, u.OutputTokens, 0, - u.CacheCreationInputTokens, u.CacheReadInputTokens) - if total == 0 || u.CostUSD <= 0 { - continue - } - key := normalizeModelKey(spec) - existing, exists := rc.Rates[key] - rc.Rates[key] = updateRate(existing, exists, u.CostUSD/float64(total)) - } - } else { - // Exclude ReasoningTokens: the deferred TokensEvent on cancelled - // runs does not capture them, so the rate denominator must match - // the token types available during estimation. - total := sumTokens(m.InputTokens, m.OutputTokens, 0, - m.CacheCreationInputTokens, m.CacheReadInputTokens) - if total == 0 { - return nil - } - key := normalizeModelKey(m.Model) - existing, exists := rc.Rates[key] - rc.Rates[key] = updateRate(existing, exists, m.TotalCostUSD/float64(total)) - } - - return saveRateCache(fullsendDir, rc) -} - -// estimateRunMetricsCost fills in TotalCostUSD on per-iteration RunMetrics -// when it is zero but tokens are present, using cached rates from prior -// successful runs. No-op when cost is already present or when no cached -// rate exists for the model. -func estimateRunMetricsCost(fullsendDir string, m *agentruntime.RunMetrics) { - if m.TotalCostUSD > 0 { - return - } - total := sumTokens(m.InputTokens, m.OutputTokens, m.ReasoningTokens, - m.CacheCreationInputTokens, m.CacheReadInputTokens) - if total == 0 || fullsendDir == "" { - return - } - - rc := loadRateCache(fullsendDir) - - if len(m.PerModelUsage) > 0 { - var costSum float64 - for spec, u := range m.PerModelUsage { - if u.CostUSD > 0 { - costSum += u.CostUSD - continue - } - tokens := sumTokens(u.InputTokens, u.OutputTokens, 0, - u.CacheCreationInputTokens, u.CacheReadInputTokens) - if tokens == 0 { - continue - } - rate, ok := lookupCachedRate(rc, spec) - if !ok { - continue - } - u.CostUSD = rate.RatePerToken * float64(tokens) - m.PerModelUsage[spec] = u - costSum += u.CostUSD - } - m.TotalCostUSD = costSum - return - } - - rate, ok := lookupCachedRate(rc, m.Model) - if !ok { - return - } - m.TotalCostUSD = rate.RatePerToken * float64(total) -} diff --git a/internal/cli/pricing_test.go b/internal/cli/pricing_test.go deleted file mode 100644 index 0dc45191c5..0000000000 --- a/internal/cli/pricing_test.go +++ /dev/null @@ -1,333 +0,0 @@ -package cli - -import ( - "math" - "os" - "path/filepath" - "testing" - - agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" -) - -func almostEqual(a, b, tol float64) bool { - return math.Abs(a-b) < tol -} - -func seedCache(t *testing.T, dir string, model string, cost float64, input, output, cacheWrite, cacheRead int) { - t.Helper() - m := &agentruntime.RunMetrics{ - TotalCostUSD: cost, - Model: model, - InputTokens: input, - OutputTokens: output, - CacheCreationInputTokens: cacheWrite, - CacheReadInputTokens: cacheRead, - } - if err := recordModelRates(dir, m); err != nil { - t.Fatalf("seedCache: %v", err) - } -} - -func TestRecordAndEstimate_SingleModel(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "claude-opus-4-6", 0.50, 10000, 5000, 2000, 8000) - - m := &agentruntime.RunMetrics{ - Model: "claude-opus-4-6", - InputTokens: 20000, - OutputTokens: 10000, - CacheCreationInputTokens: 4000, - CacheReadInputTokens: 16000, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD <= 0 { - t.Fatal("expected non-zero estimated cost") - } - // rate = 0.50 / 25000 = 0.00002; cost = 0.00002 * 50000 = 1.00 - if !almostEqual(m.TotalCostUSD, 1.0, 0.001) { - t.Errorf("got %v, want ~1.0", m.TotalCostUSD) - } -} - -func TestRecordAndEstimate_ProviderPrefix(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "anthropic-vertex/claude-opus-4-6", 0.25, 5000, 2500, 1000, 4000) - - m := &agentruntime.RunMetrics{ - Model: "anthropic-vertex/claude-opus-4-6", - InputTokens: 5000, - OutputTokens: 2500, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD <= 0 { - t.Fatal("expected non-zero cost") - } -} - -func TestRecordAndEstimate_DateSuffixFallback(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "claude-haiku-4-5", 0.10, 10000, 5000, 0, 0) - - m := &agentruntime.RunMetrics{ - Model: "claude-haiku-4-5-20260301", - InputTokens: 10000, - OutputTokens: 5000, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD <= 0 { - t.Fatal("expected fallback to match claude-haiku-4-5") - } -} - -func TestEstimate_NoCache(t *testing.T) { - dir := t.TempDir() - m := &agentruntime.RunMetrics{ - Model: "gpt-4o", - InputTokens: 10000, - OutputTokens: 5000, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD != 0 { - t.Errorf("expected 0 with no cache, got %v", m.TotalCostUSD) - } -} - -func TestEstimate_Noop_WhenCostPresent(t *testing.T) { - dir := t.TempDir() - m := &agentruntime.RunMetrics{ - TotalCostUSD: 0.50, - Model: "claude-opus-4-6", - InputTokens: 10000, - OutputTokens: 5000, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD != 0.50 { - t.Errorf("cost changed from 0.50 to %v", m.TotalCostUSD) - } -} - -func TestEstimate_Noop_EmptyDir(t *testing.T) { - m := &agentruntime.RunMetrics{ - Model: "claude-opus-4-6", - InputTokens: 10000, - OutputTokens: 5000, - } - estimateRunMetricsCost("", m) - if m.TotalCostUSD != 0 { - t.Errorf("expected 0 with empty dir, got %v", m.TotalCostUSD) - } -} - -func TestRecord_Noop_ZeroCost(t *testing.T) { - dir := t.TempDir() - if err := recordModelRates(dir, &agentruntime.RunMetrics{ - Model: "claude-opus-4-6", - InputTokens: 10000, - OutputTokens: 5000, - }); err != nil { - t.Fatal(err) - } - _, err := os.ReadFile(rateCachePath(dir)) - if err == nil { - t.Fatal("expected no cache file when cost is zero") - } -} - -func TestRecordAndEstimate_PerModelUsage(t *testing.T) { - dir := t.TempDir() - if err := recordModelRates(dir, &agentruntime.RunMetrics{ - TotalCostUSD: 0.15, - InputTokens: 15000, - OutputTokens: 8000, - PerModelUsage: map[string]agentruntime.ModelUsage{ - "anthropic-vertex/claude-sonnet-5": { - InputTokens: 10000, - OutputTokens: 5000, - CostUSD: 0.10, - }, - "anthropic-vertex/claude-haiku-4-5": { - InputTokens: 5000, - OutputTokens: 3000, - CostUSD: 0.05, - }, - }, - }); err != nil { - t.Fatal(err) - } - - m := &agentruntime.RunMetrics{ - InputTokens: 15000, - OutputTokens: 8000, - PerModelUsage: map[string]agentruntime.ModelUsage{ - "anthropic-vertex/claude-sonnet-5": { - InputTokens: 10000, - OutputTokens: 5000, - }, - "anthropic-vertex/claude-haiku-4-5": { - InputTokens: 5000, - OutputTokens: 3000, - }, - }, - } - estimateRunMetricsCost(dir, m) - - if m.TotalCostUSD <= 0 { - t.Fatal("expected non-zero total cost") - } - sonnet := m.PerModelUsage["anthropic-vertex/claude-sonnet-5"] - haiku := m.PerModelUsage["anthropic-vertex/claude-haiku-4-5"] - if sonnet.CostUSD <= 0 || haiku.CostUSD <= 0 { - t.Errorf("per-model costs not filled: sonnet=%v haiku=%v", sonnet.CostUSD, haiku.CostUSD) - } -} - -func TestRecordAndEstimate_PerModelUsage_MixedCosts(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "claude-haiku-4-5", 0.05, 5000, 3000, 0, 0) - - m := &agentruntime.RunMetrics{ - InputTokens: 15000, - OutputTokens: 8000, - PerModelUsage: map[string]agentruntime.ModelUsage{ - "anthropic/claude-sonnet-5": { - InputTokens: 10000, - OutputTokens: 5000, - CostUSD: 0.07, - }, - "anthropic/claude-haiku-4-5": { - InputTokens: 5000, - OutputTokens: 3000, - }, - }, - } - estimateRunMetricsCost(dir, m) - - if m.PerModelUsage["anthropic/claude-sonnet-5"].CostUSD != 0.07 { - t.Error("existing CostUSD was overwritten") - } - if m.PerModelUsage["anthropic/claude-haiku-4-5"].CostUSD <= 0 { - t.Error("haiku cost should be estimated from cache") - } - if m.TotalCostUSD <= 0.07 { - t.Error("total should include both models") - } -} - -func TestEMA_SmoothsRates(t *testing.T) { - dir := t.TempDir() - // First sample: rate = 0.10 / 10000 = 0.00001 - seedCache(t, dir, "claude-opus-4-6", 0.10, 5000, 5000, 0, 0) - // Second sample: rate = 0.20 / 10000 = 0.00002 - // EMA: 0.3 * 0.00002 + 0.7 * 0.00001 = 0.000013 - seedCache(t, dir, "claude-opus-4-6", 0.20, 5000, 5000, 0, 0) - - rc := loadRateCache(dir) - rate, ok := rc.Rates["claude-opus-4-6"] - if !ok { - t.Fatal("expected cached rate") - } - if !almostEqual(rate.RatePerToken, 0.000013, 0.0000001) { - t.Errorf("EMA rate = %v, want ~0.000013", rate.RatePerToken) - } - if rate.SampleCount != 2 { - t.Errorf("sample count = %d, want 2", rate.SampleCount) - } -} - -func TestNormalizeModelKey(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"claude-opus-4-6", "claude-opus-4-6"}, - {"anthropic-vertex/claude-opus-4-6", "claude-opus-4-6"}, - {"anthropic/claude-sonnet-5", "claude-sonnet-5"}, - {"gpt-4o", "gpt-4o"}, - {"openai/gpt-4o", "gpt-4o"}, - } - for _, tt := range tests { - got := normalizeModelKey(tt.input) - if got != tt.want { - t.Errorf("normalizeModelKey(%q) = %q, want %q", tt.input, got, tt.want) - } - } -} - -func TestLookupCachedRate_ExactThenSuffix(t *testing.T) { - rc := rateCache{Rates: map[string]cachedRate{ - "claude-opus-4-6": {RatePerToken: 0.00002, SampleCount: 3}, - "gpt-4o": {RatePerToken: 0.00001, SampleCount: 2}, - }} - - if _, ok := lookupCachedRate(rc, "claude-opus-4-6"); !ok { - t.Error("exact match failed") - } - if _, ok := lookupCachedRate(rc, "anthropic-vertex/claude-opus-4-6"); !ok { - t.Error("provider-prefix match failed") - } - if _, ok := lookupCachedRate(rc, "claude-opus-4-6-20260301"); !ok { - t.Error("date-suffix fallback failed") - } - if _, ok := lookupCachedRate(rc, "anthropic/claude-opus-4-6-exp-20260301"); !ok { - t.Error("compound suffix fallback failed") - } - if _, ok := lookupCachedRate(rc, "uncached-model"); ok { - t.Error("expected no match for uncached model") - } -} - -func TestLookupCachedRate_NoFalseMatchAcrossModels(t *testing.T) { - rc := rateCache{Rates: map[string]cachedRate{ - "gpt-4o": {RatePerToken: 0.00001, SampleCount: 2}, - }} - - if _, ok := lookupCachedRate(rc, "gpt-4o-mini"); ok { - t.Error("gpt-4o-mini must NOT match gpt-4o (different model, ~30x price difference)") - } - if _, ok := lookupCachedRate(rc, "gpt-4o-mini-20260301"); ok { - t.Error("gpt-4o-mini-20260301 must NOT match gpt-4o") - } - if _, ok := lookupCachedRate(rc, "gpt-4o"); !ok { - t.Error("exact match for gpt-4o should still work") - } - if _, ok := lookupCachedRate(rc, "gpt-4o-20260301"); !ok { - t.Error("date-suffix fallback for gpt-4o should work") - } -} - -func TestCacheFileAtomicity(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "claude-opus-4-6", 0.50, 10000, 5000, 0, 0) - - p := rateCachePath(dir) - if _, err := os.Stat(p); err != nil { - t.Fatalf("cache file missing: %v", err) - } - tmp := p + ".tmp" - if _, err := os.Stat(tmp); err == nil { - t.Error("tmp file should not persist after atomic write") - } - - cacheDir := filepath.Dir(p) - if _, err := os.Stat(cacheDir); err != nil { - t.Fatalf("cache dir missing: %v", err) - } -} - -func TestRecordAndEstimate_OpenAIModel(t *testing.T) { - dir := t.TempDir() - seedCache(t, dir, "openai/gpt-4o", 0.30, 20000, 10000, 0, 0) - - m := &agentruntime.RunMetrics{ - Model: "openai/gpt-4o", - InputTokens: 10000, - OutputTokens: 5000, - } - estimateRunMetricsCost(dir, m) - if m.TotalCostUSD <= 0 { - t.Fatal("expected non-zero cost for cached OpenAI model") - } - if !almostEqual(m.TotalCostUSD, 0.15, 0.001) { - t.Errorf("got %v, want ~0.15", m.TotalCostUSD) - } -} diff --git a/internal/cli/run.go b/internal/cli/run.go index 0adccc478d..e733078ebe 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2268,15 +2268,6 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep } } - // Record per-model rates from successful runs for future cost - // estimation; estimate USD cost from cached rates when the - // authoritative cost is missing (cancelled runs). Each call - // is a no-op when its precondition doesn't hold. - if err := recordModelRates(absFullsendDir, &metrics); err != nil { - printer.StepWarn(fmt.Sprintf("pricing rate cache: %v", err)) - } - estimateRunMetricsCost(absFullsendDir, &metrics) - // Accumulate behavioral metrics across iterations. aggregateRunMetrics(&aggMetrics, &metrics, iteration) @@ -3720,11 +3711,11 @@ func transcriptErrorMessage(te agentruntime.TranscriptError) string { // artifact upload step (if: always()) captures the partial usage data // (#6936). // -// NOTE: TotalCostUSD is estimated from cached per-model rates derived -// from prior successful runs when the authoritative cost is missing -// (cancelled runs never emit the terminal ResultEvent). The estimate -// is zero if no cached rate exists for the model. See -// recordModelRates, estimateRunMetricsCost, and #6936 for background. +// NOTE: TotalCostUSD is now reported by the SIGINT-into-sandbox +// mechanism (#6936): on cancellation, SIGINT is sent to the in-sandbox +// claude process, which flushes its ResultEvent (with cost data) before +// exiting. If the SIGINT delivery fails, TotalCostUSD falls back to +// zero — token counts are still captured via the deferred TokensEvent. // // cancelled is false when ctx is still live, in which case the caller's // normal control flow continues unchanged; the other return values are diff --git a/internal/runtime/claude_progress.go b/internal/runtime/claude_progress.go index b5e1f7af1a..c0192d59c1 100644 --- a/internal/runtime/claude_progress.go +++ b/internal/runtime/claude_progress.go @@ -63,12 +63,6 @@ type assistantMessage struct { Message struct { Content json.RawMessage `json:"content"` Model string `json:"model"` - Usage struct { - InputTokens int `json:"input_tokens"` - OutputTokens int `json:"output_tokens"` - CacheCreationInputTokens int `json:"cache_creation_input_tokens"` - CacheReadInputTokens int `json:"cache_read_input_tokens"` - } `json:"usage"` } `json:"message"` } @@ -351,32 +345,6 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { onEvent(InitEvent{Model: msg.Message.Model}) } - // Track usage from assistant messages when stream_events - // are not present (stream-json output format). - u := msg.Message.Usage - if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadInputTokens > 0 || u.CacheCreationInputTokens > 0 { - cumulativeInput += totalInput - cumulativeOutput += totalOutput - cumulativeCacheRead += totalCacheRead - cumulativeCacheWrite += totalCacheWrite - totalInput = u.InputTokens - totalOutput = u.OutputTokens - totalCacheRead = u.CacheReadInputTokens - totalCacheWrite = u.CacheCreationInputTokens - - total := cumulativeInput + totalInput + cumulativeOutput + totalOutput + - cumulativeCacheRead + totalCacheRead + cumulativeCacheWrite + totalCacheWrite - if total-lastEmittedTotal >= tokenThreshold { - lastEmittedTotal = total - onEvent(TokensEvent{ - InputTokens: cumulativeInput + totalInput, - OutputTokens: cumulativeOutput + totalOutput, - CacheRead: cumulativeCacheRead + totalCacheRead, - CacheWrite: cumulativeCacheWrite + totalCacheWrite, - }) - } - } - // Real Claude Code output nests content under "message"; // fall back to the top-level "content" for older/flat shapes. content := msg.Message.Content diff --git a/internal/runtime/claude_progress_test.go b/internal/runtime/claude_progress_test.go index d09f3f3211..ca1c5f4f58 100644 --- a/internal/runtime/claude_progress_test.go +++ b/internal/runtime/claude_progress_test.go @@ -1325,79 +1325,3 @@ func TestParseClaudeStreamFinalTokensEventOnCancel(t *testing.T) { t.Errorf("expected 500 output tokens, got %d", tokens[0].OutputTokens) } } - -func TestParseClaudeStreamAssistantUsageFallback(t *testing.T) { - // When stream_event events are absent (stream-json format), usage - // should be extracted from assistant message events. - lines := []string{ - `{"type":"system","subtype":"init","model":"claude-opus-4-6"}`, - `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"hello"}],"usage":{"input_tokens":3000,"output_tokens":500,"cache_read_input_tokens":12000,"cache_creation_input_tokens":2000}}}`, - `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]}}`, - `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"done"}],"usage":{"input_tokens":4000,"output_tokens":800,"cache_read_input_tokens":14000,"cache_creation_input_tokens":1000}}}`, - // No result event — cancelled run. - } - - events := collectEvents(t, strings.Join(lines, "\n")) - - var tokens []TokensEvent - for _, e := range events { - if te, ok := e.(TokensEvent); ok { - tokens = append(tokens, te) - } - } - - if len(tokens) == 0 { - t.Fatal("expected at least one TokensEvent from assistant usage fallback") - } - last := tokens[len(tokens)-1] - // Cumulative: msg1 input=3000+msg2 input=4000=7000 - if last.InputTokens != 7000 { - t.Errorf("expected 7000 cumulative input tokens, got %d", last.InputTokens) - } - // Cumulative: msg1 output=500+msg2 output=800=1300 - if last.OutputTokens != 1300 { - t.Errorf("expected 1300 cumulative output tokens, got %d", last.OutputTokens) - } - // Cumulative cache read: 12000+14000=26000 - if last.CacheRead != 26000 { - t.Errorf("expected 26000 cumulative cache read, got %d", last.CacheRead) - } - // Cumulative cache write: 2000+1000=3000 - if last.CacheWrite != 3000 { - t.Errorf("expected 3000 cumulative cache write, got %d", last.CacheWrite) - } -} - -func TestProgressParserCancelledRunCapturesTokensFromAssistant(t *testing.T) { - // End-to-end test: progressParser should populate RunMetrics from - // assistant-event usage when no stream_events are present. - lines := []string{ - `{"type":"system","subtype":"init","model":"claude-opus-4-6"}`, - `{"type":"assistant","message":{"model":"claude-opus-4-6","content":[{"type":"text","text":"working"}],"usage":{"input_tokens":5000,"output_tokens":1000,"cache_read_input_tokens":10000,"cache_creation_input_tokens":3000}}}`, - } - - input := strings.NewReader(strings.Join(lines, "\n")) - var buf bytes.Buffer - printer := ui.New(&buf) - metrics := &RunMetrics{} - - if err := progressParser(input, printer, metrics); err != nil { - t.Fatalf("progressParser returned error: %v", err) - } - - if metrics.InputTokens != 5000 { - t.Errorf("expected 5000 input tokens, got %d", metrics.InputTokens) - } - if metrics.OutputTokens != 1000 { - t.Errorf("expected 1000 output tokens, got %d", metrics.OutputTokens) - } - if metrics.CacheReadInputTokens != 10000 { - t.Errorf("expected 10000 cache read tokens, got %d", metrics.CacheReadInputTokens) - } - if metrics.CacheCreationInputTokens != 3000 { - t.Errorf("expected 3000 cache creation tokens, got %d", metrics.CacheCreationInputTokens) - } - if metrics.Model != "claude-opus-4-6" { - t.Errorf("expected model claude-opus-4-6, got %s", metrics.Model) - } -} From d419f66442d3c7981770ede2f87a9fbea21eb62b Mon Sep 17 00:00:00 2001 From: Adam Scerra Date: Thu, 10 Sep 2026 14:50:05 -0400 Subject: [PATCH 7/7] =?UTF-8?q?fix:=20address=20review-squad=20findings=20?= =?UTF-8?q?=E2=80=94=20docstring,=20diagnostics,=20docs=20(#6936)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix WaitDelay docstring: "5-second" → "8-second" to match code - Add empty-PID diagnostic in killScript so logs distinguish "pid-file missing" from "kill delivered" - Document stderrW thread-safety requirement and single-use invariant - Add comment on exec claude noting PID-file dependency Co-Authored-By: Claude Opus 4.6 --- internal/runtime/claude.go | 2 ++ internal/sandbox/sandbox.go | 12 ++++++++++-- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/internal/runtime/claude.go b/internal/runtime/claude.go index d8cb0204d3..69fdfc5c83 100644 --- a/internal/runtime/claude.go +++ b/internal/runtime/claude.go @@ -352,6 +352,8 @@ func buildRunCommand(params RunParams) string { envFile := sandbox.SandboxWorkspace + "/.env" safe := strings.ReplaceAll(params.AgentBaseName, "'", "'\\''") + // exec replaces the shell so ExecStreamReader's PID file points to + // claude, not sh — required for the SIGINT-into-sandbox cancel mechanism. parts := []string{ fmt.Sprintf("cd %s && . %s && exec claude", params.RepoDir, envFile), "--print", diff --git a/internal/sandbox/sandbox.go b/internal/sandbox/sandbox.go index 83cd929643..27dd0c8ff4 100644 --- a/internal/sandbox/sandbox.go +++ b/internal/sandbox/sandbox.go @@ -1375,8 +1375,14 @@ const execPIDFile = "/tmp/.fullsend_exec.pid" // necessary because SIGINT to the openshell CLI does not propagate through // gRPC to in-sandbox processes. The openshell relay process is left running // so it continues piping stdout (e.g. Claude Code's terminal result event -// with cost data). A 5-second WaitDelay allows the graceful shutdown to +// with cost data). An 8-second WaitDelay allows the graceful shutdown to // complete; after that Go kills the openshell process. +// +// stderrW must be safe for concurrent use: the cancel goroutine and the +// openshell subprocess both write to it simultaneously. +// +// The PID file path is a fixed singleton inside the sandbox. This function +// must not be called concurrently for the same sandbox. func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout time.Duration, stderrW io.Writer) (io.ReadCloser, *exec.Cmd, context.CancelFunc, error) { ctx, cancel := context.WithTimeout(ctx, timeout) timeoutSecs := fmt.Sprintf("%d", int(timeout.Seconds())) @@ -1409,7 +1415,9 @@ func ExecStreamReader(ctx context.Context, sandboxName, command string, timeout go func() { defer killCancel() killScript := fmt.Sprintf( - "PID=$(cat %s 2>/dev/null); echo \"sandbox-cancel: pid=$PID\" >&2; "+ + "PID=$(cat %s 2>/dev/null); "+ + "if [ -z \"$PID\" ]; then echo \"sandbox-cancel: pid-file missing or empty\" >&2; exit 1; fi; "+ + "echo \"sandbox-cancel: pid=$PID\" >&2; "+ "kill -INT $PID 2>&1; echo \"sandbox-cancel: kill=$?\" >&2", execPIDFile) killCmd := exec.CommandContext(killCtx, "openshell", "sandbox", "exec", //nolint:gosec // sandboxName is not user input