feat(pluginhost): expose cache write TTL token counts in usage.handle

- Add optional CacheCreation5mTokens and CacheCreation1hTokens pointer fields to pluginapi.UsageDetail while preserving aggregate CacheCreationTokens.
- Forward independent pointer copies via coreusage.CloneInt64Ptr in usageAdapter.HandleUsage to preserve missing versus explicit zero values across streaming and non-streaming paths.
- Add SDK, adapter, RPC schema, and Claude streaming/non-streaming regression tests.

Closes: #7630
This commit is contained in:
Luis Pater
2026-11-17 20:34:47 +08:00
parent 34d8fe0f68
commit f7b3ccdff9
6 changed files with 318 additions and 18 deletions

View File

@@ -1006,6 +1006,75 @@ func TestUsageAdapterPropagatesNativeKeyAndAccessProvider(t *testing.T) {
}
}
func TestUsageAdapterDeliversClaudeStreamingAndNonStreamingCacheCreationTTL(t *testing.T) {
plugin := &capturingUsagePlugin{captured: make(chan pluginapi.UsageRecord, 2)}
host := newHostWithRecords(capabilityRecord{
id: "usage-claude-ttl",
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
UsagePlugin: plugin,
}},
})
adapter := &usageAdapter{
host: host,
pluginID: "usage-claude-ttl",
plugin: plugin,
}
// Non-streaming Claude usage payload with 5m + 1h breakdown.
nonStreamDetail := helps.ParseClaudeUsage([]byte(`{
"usage": {
"input_tokens": 100,
"output_tokens": 50,
"cache_creation_input_tokens": 1500,
"cache_creation": {
"ephemeral_5m_input_tokens": 1000,
"ephemeral_1h_input_tokens": 500
}
}
}`))
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Stream: false,
Detail: nonStreamDetail,
})
recNonStream := <-plugin.captured
if recNonStream.Detail.CacheCreationTokens != 1500 {
t.Fatalf("non-stream CacheCreationTokens = %d, want 1500", recNonStream.Detail.CacheCreationTokens)
}
if recNonStream.Detail.CacheCreation5mTokens == nil || *recNonStream.Detail.CacheCreation5mTokens != 1000 {
t.Fatalf("non-stream CacheCreation5mTokens = %v, want 1000", recNonStream.Detail.CacheCreation5mTokens)
}
if recNonStream.Detail.CacheCreation1hTokens == nil || *recNonStream.Detail.CacheCreation1hTokens != 500 {
t.Fatalf("non-stream CacheCreation1hTokens = %v, want 500", recNonStream.Detail.CacheCreation1hTokens)
}
// Streaming Claude SSE events with 5m=0 and 1h=45045 preserved across message_start + message_delta.
var streamBuf helps.StreamUsageBuffer
streamBuf.ObserveClaudeStream([]byte(`data: {"type":"message_start","message":{"id":"msg_1","model":"claude-sonnet-4-6","usage":{"input_tokens":16,"cache_creation_input_tokens":45045,"cache_read_input_tokens":0,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":45045},"output_tokens":4}}}`))
streamBuf.ObserveClaudeStream([]byte(`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":24}}`))
streamDetail, ok := streamBuf.Detail()
if !ok {
t.Fatal("expected streaming Claude usage detail")
}
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Stream: true,
Detail: streamDetail,
})
recStream := <-plugin.captured
if recStream.Detail.CacheCreationTokens != 45045 {
t.Fatalf("stream CacheCreationTokens = %d, want 45045", recStream.Detail.CacheCreationTokens)
}
if recStream.Detail.CacheCreation5mTokens == nil || *recStream.Detail.CacheCreation5mTokens != 0 {
t.Fatalf("stream CacheCreation5mTokens = %v, want explicit 0", recStream.Detail.CacheCreation5mTokens)
}
if recStream.Detail.CacheCreation1hTokens == nil || *recStream.Detail.CacheCreation1hTokens != 45045 {
t.Fatalf("stream CacheCreation1hTokens = %v, want 45045", recStream.Detail.CacheCreation1hTokens)
}
}
func TestExecutorAdapterExecuteAttributesResponsesUsageToSelectedAuth(t *testing.T) {
plugin := newTestUsageCapturePlugin("plugin-provider-responses")
registerTestUsagePlugin(t, "test-executor-adapter-responses-auth-usage", plugin)

View File

@@ -3252,6 +3252,76 @@ func TestUsageAdapterPropagatesModalityTokenDetails(t *testing.T) {
}
}
func TestUsageAdapterPropagatesCacheCreationTTLDetails(t *testing.T) {
var gotRecord pluginapi.UsageRecord
plugin := usagePluginFunc(func(ctx context.Context, record pluginapi.UsageRecord) {
gotRecord = record
})
host := newHostWithRecords(capabilityRecord{
id: "usage-cache-ttl-details",
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
UsagePlugin: plugin,
}},
})
adapter := &usageAdapter{
host: host,
pluginID: "usage-cache-ttl-details",
plugin: plugin,
}
cache5m := int64(1000)
cache1h := int64(500)
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: coreusage.Detail{
InputTokens: 100,
OutputTokens: 50,
CacheCreationTokens: 1500,
TotalTokens: 1650,
CacheCreation5mTokens: &cache5m,
CacheCreation1hTokens: &cache1h,
},
})
// Mutate caller-owned source values after HandleUsage to verify independent pointer copies.
cache5m = 999
cache1h = 999
got := gotRecord.Detail
if got.CacheCreationTokens != 1500 {
t.Fatalf("CacheCreationTokens = %d, want 1500", got.CacheCreationTokens)
}
if got.CacheCreation5mTokens == nil || got.CacheCreation5mTokens == &cache5m || *got.CacheCreation5mTokens != 1000 {
t.Fatalf("CacheCreation5mTokens = %v, want independent pointer to 1000", got.CacheCreation5mTokens)
}
if got.CacheCreation1hTokens == nil || got.CacheCreation1hTokens == &cache1h || *got.CacheCreation1hTokens != 500 {
t.Fatalf("CacheCreation1hTokens = %v, want independent pointer to 500", got.CacheCreation1hTokens)
}
// Verify explicit zero remains distinct from absent (nil).
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: coreusage.Detail{
CacheCreationTokens: 45045,
CacheCreation5mTokens: coreusage.Int64Ptr(0),
CacheCreation1hTokens: nil,
},
})
got = gotRecord.Detail
if got.CacheCreationTokens != 45045 {
t.Fatalf("CacheCreationTokens = %d, want 45045", got.CacheCreationTokens)
}
if got.CacheCreation5mTokens == nil || *got.CacheCreation5mTokens != 0 {
t.Fatalf("CacheCreation5mTokens = %v, want explicit 0", got.CacheCreation5mTokens)
}
if got.CacheCreation1hTokens != nil {
t.Fatalf("CacheCreation1hTokens = %v, want nil", got.CacheCreation1hTokens)
}
}
func TestUsageAdapterPreservesExplicitGenerateFalse(t *testing.T) {
var gotGenerate bool
plugin := usagePluginFunc(func(ctx context.Context, record pluginapi.UsageRecord) {

View File

@@ -633,24 +633,26 @@ func (a *usageAdapter) HandleUsage(ctx context.Context, record coreusage.Record)
Body: record.Fail.Body,
},
Detail: pluginapi.UsageDetail{
InputTokens: record.Detail.InputTokens,
OutputTokens: record.Detail.OutputTokens,
ReasoningTokens: record.Detail.ReasoningTokens,
CachedTokens: record.Detail.CachedTokens,
CacheReadTokens: record.Detail.CacheReadTokens,
CacheCreationTokens: record.Detail.CacheCreationTokens,
TotalTokens: record.Detail.TotalTokens,
TextInputTokens: coreusage.CloneInt64Ptr(record.Detail.TextInputTokens),
ImageInputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageInputTokens),
AudioInputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioInputTokens),
VideoInputTokens: coreusage.CloneInt64Ptr(record.Detail.VideoInputTokens),
FileInputTokens: coreusage.CloneInt64Ptr(record.Detail.FileInputTokens),
CachedTextTokens: coreusage.CloneInt64Ptr(record.Detail.CachedTextTokens),
CachedImageTokens: coreusage.CloneInt64Ptr(record.Detail.CachedImageTokens),
CachedAudioTokens: coreusage.CloneInt64Ptr(record.Detail.CachedAudioTokens),
TextOutputTokens: coreusage.CloneInt64Ptr(record.Detail.TextOutputTokens),
ImageOutputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageOutputTokens),
AudioOutputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioOutputTokens),
InputTokens: record.Detail.InputTokens,
OutputTokens: record.Detail.OutputTokens,
ReasoningTokens: record.Detail.ReasoningTokens,
CachedTokens: record.Detail.CachedTokens,
CacheReadTokens: record.Detail.CacheReadTokens,
CacheCreationTokens: record.Detail.CacheCreationTokens,
TotalTokens: record.Detail.TotalTokens,
CacheCreation5mTokens: coreusage.CloneInt64Ptr(record.Detail.CacheCreation5mTokens),
CacheCreation1hTokens: coreusage.CloneInt64Ptr(record.Detail.CacheCreation1hTokens),
TextInputTokens: coreusage.CloneInt64Ptr(record.Detail.TextInputTokens),
ImageInputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageInputTokens),
AudioInputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioInputTokens),
VideoInputTokens: coreusage.CloneInt64Ptr(record.Detail.VideoInputTokens),
FileInputTokens: coreusage.CloneInt64Ptr(record.Detail.FileInputTokens),
CachedTextTokens: coreusage.CloneInt64Ptr(record.Detail.CachedTextTokens),
CachedImageTokens: coreusage.CloneInt64Ptr(record.Detail.CachedImageTokens),
CachedAudioTokens: coreusage.CloneInt64Ptr(record.Detail.CachedAudioTokens),
TextOutputTokens: coreusage.CloneInt64Ptr(record.Detail.TextOutputTokens),
ImageOutputTokens: coreusage.CloneInt64Ptr(record.Detail.ImageOutputTokens),
AudioOutputTokens: coreusage.CloneInt64Ptr(record.Detail.AudioOutputTokens),
},
ResponseHeaders: cloneHeader(record.ResponseHeaders),
})

View File

@@ -1006,6 +1006,102 @@ func TestUsageRecordRPCModalityTokenCounters(t *testing.T) {
}
}
func TestUsageRecordRPCCacheCreationTTLCounters(t *testing.T) {
var deliveredRaw []byte
var deliveredRecord pluginapi.UsageRecord
rpcAdapter := &rpcPluginAdapter{
id: "rpc-usage-cache-ttl",
client: &lifecycleTestClient{call: func(_ context.Context, method string, request []byte) ([]byte, error) {
if method != pluginabi.MethodUsageHandle {
return nil, io.ErrUnexpectedEOF
}
deliveredRaw = bytes.Clone(request)
if errUnmarshal := json.Unmarshal(request, &deliveredRecord); errUnmarshal != nil {
return nil, errUnmarshal
}
return marshalRPCResult(rpcEmptyResponse{})
}},
}
host := newHostWithRecords(capabilityRecord{
id: "rpc-usage-cache-ttl",
plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
UsagePlugin: rpcAdapter,
}},
})
rpcAdapter.host = host
adapter := &usageAdapter{
host: host,
pluginID: "rpc-usage-cache-ttl",
plugin: rpcAdapter,
}
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: coreusage.Detail{
InputTokens: 100,
OutputTokens: 50,
CacheCreationTokens: 1500,
TotalTokens: 1650,
CacheCreation5mTokens: coreusage.Int64Ptr(1000),
CacheCreation1hTokens: coreusage.Int64Ptr(500),
},
})
got := deliveredRecord.Detail
if got.CacheCreationTokens != 1500 {
t.Fatalf("delivered CacheCreationTokens = %d, want 1500", got.CacheCreationTokens)
}
if got.CacheCreation5mTokens == nil || *got.CacheCreation5mTokens != 1000 {
t.Fatalf("delivered CacheCreation5mTokens = %v, want 1000", got.CacheCreation5mTokens)
}
if got.CacheCreation1hTokens == nil || *got.CacheCreation1hTokens != 500 {
t.Fatalf("delivered CacheCreation1hTokens = %v, want 500", got.CacheCreation1hTokens)
}
// Legacy plugins compiled against the 7-field UsageDetail must still unmarshal cleanly.
type legacyUsageDetail struct {
InputTokens int64
OutputTokens int64
ReasoningTokens int64
CachedTokens int64
CacheReadTokens int64
CacheCreationTokens int64
TotalTokens int64
}
type legacyUsageRecordWithDetail struct {
Provider string
Model string
Detail legacyUsageDetail
}
var legacyRec legacyUsageRecordWithDetail
if errLegacy := json.Unmarshal(deliveredRaw, &legacyRec); errLegacy != nil {
t.Fatalf("Unmarshal(legacyUsageRecordWithDetail) error = %v", errLegacy)
}
if legacyRec.Detail.CacheCreationTokens != 1500 {
t.Fatalf("legacyUsageRecordWithDetail.Detail.CacheCreationTokens = %d, want 1500", legacyRec.Detail.CacheCreationTokens)
}
// Verify explicit zero and nil over RPC.
adapter.HandleUsage(context.Background(), coreusage.Record{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: coreusage.Detail{
CacheCreationTokens: 500,
CacheCreation5mTokens: coreusage.Int64Ptr(0),
CacheCreation1hTokens: nil,
},
})
got = deliveredRecord.Detail
if got.CacheCreation5mTokens == nil || *got.CacheCreation5mTokens != 0 {
t.Fatalf("delivered CacheCreation5mTokens = %v, want explicit 0", got.CacheCreation5mTokens)
}
if got.CacheCreation1hTokens != nil {
t.Fatalf("delivered CacheCreation1hTokens = %v, want nil", got.CacheCreation1hTokens)
}
}
type recordingRawPatchClient struct {
schemaVersion uint32
methods []string

View File

@@ -1924,6 +1924,10 @@ type UsageDetail struct {
// TotalTokens is the total token count.
TotalTokens int64
// CacheCreation5mTokens is the optional 5-minute TTL cache creation token count.
CacheCreation5mTokens *int64
// CacheCreation1hTokens is the optional 1-hour TTL cache creation token count.
CacheCreation1hTokens *int64
// TextInputTokens is the optional text input token count.
TextInputTokens *int64
// ImageInputTokens is the optional image input token count.

View File

@@ -987,6 +987,65 @@ func TestUsageDetailModalityTokenCounters(t *testing.T) {
}
}
func TestUsageDetailCacheCreationTTLCounters(t *testing.T) {
int64Ptr := func(v int64) *int64 { return &v }
record := UsageRecord{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: UsageDetail{
InputTokens: 100,
OutputTokens: 50,
CacheCreationTokens: 1500,
TotalTokens: 1650,
CacheCreation5mTokens: int64Ptr(1000),
CacheCreation1hTokens: int64Ptr(500),
},
}
raw, errMarshal := json.Marshal(record)
if errMarshal != nil {
t.Fatalf("Marshal(UsageRecord) error = %v", errMarshal)
}
var decoded UsageRecord
if errUnmarshal := json.Unmarshal(raw, &decoded); errUnmarshal != nil {
t.Fatalf("Unmarshal(UsageRecord) error = %v", errUnmarshal)
}
got := decoded.Detail
if got.CacheCreationTokens != 1500 {
t.Fatalf("CacheCreationTokens = %d, want 1500", got.CacheCreationTokens)
}
if got.CacheCreation5mTokens == nil || *got.CacheCreation5mTokens != 1000 {
t.Fatalf("CacheCreation5mTokens = %v, want 1000", got.CacheCreation5mTokens)
}
if got.CacheCreation1hTokens == nil || *got.CacheCreation1hTokens != 500 {
t.Fatalf("CacheCreation1hTokens = %v, want 500", got.CacheCreation1hTokens)
}
zeroAndNil := UsageRecord{
Provider: "claude",
Model: "claude-sonnet-4-6",
Detail: UsageDetail{
CacheCreationTokens: 0,
CacheCreation5mTokens: int64Ptr(0),
CacheCreation1hTokens: nil,
},
}
rawZero, errMarshalZero := json.Marshal(zeroAndNil)
if errMarshalZero != nil {
t.Fatalf("Marshal(zeroAndNil) error = %v", errMarshalZero)
}
var decodedZero UsageRecord
if errUnmarshalZero := json.Unmarshal(rawZero, &decodedZero); errUnmarshalZero != nil {
t.Fatalf("Unmarshal(zeroAndNil) error = %v", errUnmarshalZero)
}
if decodedZero.Detail.CacheCreation5mTokens == nil || *decodedZero.Detail.CacheCreation5mTokens != 0 {
t.Fatalf("CacheCreation5mTokens = %v, want explicit 0", decodedZero.Detail.CacheCreation5mTokens)
}
if decodedZero.Detail.CacheCreation1hTokens != nil {
t.Fatalf("CacheCreation1hTokens = %v, want nil", decodedZero.Detail.CacheCreation1hTokens)
}
}
func TestQuotaPayloadJSON(t *testing.T) {
// Test camelCase input
camelJSON := []byte(`{