Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7396: fix(usage): preserve cost-only task accounting (#8441)

importcpp636f8896dd7f
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 33a966ddd5..a831584502 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8767,7 +8767,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
// Convert agent usage map to task usage entries.
var usageEntries []TaskUsageEntry
for model, u := range result.Usage {
- if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 {
+ if u.InputTokens == 0 && u.OutputTokens == 0 && u.CacheReadTokens == 0 && u.CacheWriteTokens == 0 && u.CostUSDTicks <= 0 {
continue
}
usageEntries = append(usageEntries, TaskUsageEntry{
diff --git a/server/internal/daemon/task_usage_test.go b/server/internal/daemon/task_usage_test.go
new file mode 100644
index 0000000000..29439249c1
--- /dev/null
+++ b/server/internal/daemon/task_usage_test.go
@@ -0,0 +1,86 @@
+package daemon
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// A test-created Grok ACP process carries provider cost through the real
+// backend and runTask conversion, without an installed CLI or model account.
+const taskUsageGrokFixture = `#!/bin/sh
+case "$*" in *--version*) echo '1.0.0'; exit 0;; esac
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"authMethods":[{"id":"cached_token","name":"Test authentication"}],"agentCapabilities":{"mcpCapabilities":{"http":true,"sse":true}}}}\n' "$id";;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"test-session","models":{"currentModelId":"grok-4.6","availableModels":[{"modelId":"grok-4.6","name":"Test model"}]}}}\n' "$id";;
+ *'"method":"session/prompt"'*)
+ printf '%s\n' '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"test-session","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}}}'
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","_meta":{"modelId":"grok-4.6","usage":{"inputTokens":FIXTURE_INPUT,"costUsdTicks":FIXTURE_COST}}}}\n' "$id";;
+ *) if [ -n "$id" ]; then printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"; fi;;
+ esac
+done
+`
+
+func TestRunTaskPreservesProviderCostWithoutTokens(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script agent fixture is POSIX-only")
+ }
+ for _, tc := range []struct {
+ name string
+ input, cost int64
+ want []TaskUsageEntry
+ }{
+ {"cost_only", 0, 100000000, []TaskUsageEntry{{Provider: "grok", Model: "grok-4.6", CostUSDTicks: 100000000}}},
+ {"tokens_and_cost", 10, 100000000, []TaskUsageEntry{{Provider: "grok", Model: "grok-4.6", InputTokens: 10, CostUSDTicks: 100000000}}},
+ {"tokens_only", 10, 0, []TaskUsageEntry{{Provider: "grok", Model: "grok-4.6", InputTokens: 10}}},
+ {"empty", 0, 0, nil},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))
+ fake := filepath.Join(t.TempDir(), "grok-fixture")
+ script := strings.NewReplacer("FIXTURE_INPUT", fmt.Sprint(tc.input), "FIXTURE_COST", fmt.Sprint(tc.cost)).Replace(taskUsageGrokFixture)
+ writeTestExecutable(t, fake, []byte(script))
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+ d := &Daemon{
+ client: NewClient(srv.URL), logger: logger,
+ workspaces: make(map[string]*workspaceState), activeEnvRoots: make(map[string]int),
+ runtimeIndex: map[string]Runtime{"test-rt": {ID: "test-rt", Provider: "grok"}},
+ cfg: Config{
+ WorkspacesRoot: t.TempDir(), AgentTimeout: 5 * time.Second, ServerBaseURL: srv.URL,
+ Agents: map[string]AgentEntry{"grok": {Path: fake}},
+ },
+ }
+ task := Task{
+ ID: "test-task", WorkspaceID: "test-ws", RuntimeID: "test-rt", IssueID: "test-issue",
+ AgentID: "test-agent", AuthToken: "mat_test_usage",
+ Agent: &AgentData{ID: "test-agent", Name: "test", Model: "grok-4.6"},
+ }
+ result, err := d.runTask(context.Background(), task, "grok", 0, logger)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if result.Status != "completed" || result.Comment != "done" {
+ t.Fatalf("unexpected result: %+v", result)
+ }
+ if !reflect.DeepEqual(result.Usage, tc.want) {
+ t.Fatalf("usage = %+v, want %+v", result.Usage, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index b610a91f48..a08a8975ff 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -706,11 +706,11 @@ func distributeAuthoritativeCost(actual float64, estimated [4]float64) [4]float6
}
func (m *BusinessMetrics) recordPricedTokens(provider, model, tokenType, runtimeMode, source string, tokens int64, cost float64) {
- if tokens <= 0 {
- return
- }
tokenType = NormalizeTokenType(tokenType)
- m.llmTokens.WithLabelValues(provider, model, tokenType, runtimeMode, source).Add(float64(tokens))
+ if tokens > 0 {
+ m.llmTokens.WithLabelValues(provider, model, tokenType, runtimeMode, source).Add(float64(tokens))
+ }
+ // Provider-reported cost can exist without a token breakdown.
if cost > 0 {
m.llmCostUSD.WithLabelValues(provider, model, tokenType, runtimeMode, source).Add(cost)
}
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index 915a441b9b..11672d92b0 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -297,6 +297,59 @@ func TestBusinessMetricsFallsBackToRateTableWithoutProviderCost(t *testing.T) {
}
}
+func TestBusinessMetricsCostOnlyUsage(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ model string
+ provider string
+ requestModel string
+ }{
+ {"priced", "grok-4.6", "xai", "grok-4.6"},
+ {"unpriced", "grok-composer-2.5-fast", "grok", "unknown"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ m := NewBusinessMetrics()
+ const actualUSD = 0.01
+ m.RecordLLMUsage("issue", "local", "grok", tc.model,
+ 0, 0, 0, 0, int64(actualUSD*CostUSDTicksPerUSD))
+
+ // Inspect collectors without creating zero-token series in the test.
+ if got := testutil.CollectAndCount(m.llmTokens); got != 0 {
+ t.Errorf("priced token series = %d, want 0", got)
+ }
+ if got := testutil.CollectAndCount(m.llmUnpricedTokens); got != 0 {
+ t.Errorf("unpriced token series = %d, want 0", got)
+ }
+ if got := testutil.CollectAndCount(m.llmCostUSD); got != 1 {
+ t.Errorf("cost series = %d, want 1", got)
+ }
+ got := testutil.ToFloat64(m.llmCostUSD.WithLabelValues(
+ tc.provider, tc.model, "input", "local", "issue"))
+ if math.Abs(got-actualUSD) > 1e-9 {
+ t.Errorf("recorded cost = %v, want %v", got, actualUSD)
+ }
+ if got := testutil.ToFloat64(m.llmRequests.WithLabelValues(tc.provider, tc.requestModel, "local")); got != 1 {
+ t.Errorf("request counter = %v, want 1", got)
+ }
+ })
+ }
+}
+
+func TestBusinessMetricsEmptyPricedUsage(t *testing.T) {
+ m := NewBusinessMetrics()
+ m.RecordLLMUsage("issue", "local", "grok", "grok-4.6", 0, 0, 0, 0, 0)
+
+ if got := testutil.CollectAndCount(m.llmTokens); got != 0 {
+ t.Errorf("token series = %d, want 0", got)
+ }
+ if got := testutil.CollectAndCount(m.llmCostUSD); got != 0 {
+ t.Errorf("cost series = %d, want 0", got)
+ }
+ if got := testutil.ToFloat64(m.llmRequests.WithLabelValues("xai", "grok-4.6", "local")); got != 1 {
+ t.Errorf("request counter = %v, want 1", got)
+ }
+}
+
func TestDistributeAuthoritativeCost(t *testing.T) {
t.Parallel()