Verify native usage reporting across recovery and delivery boundaries

This commit is contained in:
2026-11-23 02:43:43 +00:00
parent 7aa4f2ec4d
commit 63beae814b
5 changed files with 107 additions and 27 deletions

View File

@@ -27,16 +27,17 @@ type recoveryClient struct {
requests []promptkit.GenerateRequest
failEvents, failNPC, correctScene bool
failure error
reportUsage bool
}
func (client *recoveryClient) Generate(ctx context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
func (client *recoveryClient) Generate(ctx context.Context, request promptkit.GenerateRequest) (response *promptkit.GenerateResponse, err error) {
role := enemyEventRequestRole(request)
if productionSchemaHasProperty(request, "classification") {
role = "classification"
}
client.mu.Lock()
client.requests = append(client.requests, request)
failEvents, failNPC := client.failEvents, client.failNPC
failEvents, failNPC, reportUsage := client.failEvents, client.failNPC, client.reportUsage
transcript, _ := productionJSONInput(request, "units")
combat := strings.Contains(string(transcript), "Roll initiative")
incorrectScene := role == "kind" && combat && client.correctScene
@@ -44,6 +45,14 @@ func (client *recoveryClient) Generate(ctx context.Context, request promptkit.Ge
client.correctScene = false
}
client.mu.Unlock()
defer func() {
if reportUsage && response != nil {
response.Usage = promptkit.TokenUsage{PromptTokens: 8, CompletionTokens: 4, ReasoningTokens: 1, TotalTokens: 12, CachedTokens: 2, CacheWriteTokens: 1}
response.UsagePresence = &promptkit.TokenUsagePresence{PromptTokens: true, CompletionTokens: true, ReasoningTokens: true, TotalTokens: true, CachedTokens: true, CacheWriteTokens: true}
cost := 0.125
response.CostUSD = &cost
}
}()
if role == "events" && failEvents || role == "npcs" && combat && failNPC {
return nil, client.failure
}
@@ -160,11 +169,12 @@ promptkit:
return fixture
}
func (fixture *recoveryFixture) run(t *testing.T) (commandkit.Outcome, runResult, string) {
func (fixture *recoveryFixture) run(t *testing.T, flags ...string) (commandkit.Outcome, runResult, string) {
t.Helper()
args := []string{"run", "dnd-session", "--config", fixture.config, "--input-file", filepath.Join(filepath.Dir(fixture.config), "transcript.json"), "--debug", "--progress=false", "--format=json", "--llm-session-id=recovery-session", "--llm-transient-retries=0",
"--set", "/pipelines/dnd-session/max_additional_turns=1",
}
args = append(args, flags...)
app, err := NewApplication("development", fixture.options)
if err != nil {
t.Fatal(err)
@@ -186,8 +196,29 @@ func (fixture *recoveryFixture) run(t *testing.T) (commandkit.Outcome, runResult
func TestAssembledRecoveryReusesCorrectedPredecessorsAndChunkPlan(t *testing.T) {
fixture := newRecoveryFixture(t)
fixture.client.reportUsage = true
configured, err := os.ReadFile(fixture.config)
if err != nil {
t.Fatal(err)
}
// Exercise worker context propagation without testing backend queue defaults.
writeConfigKitFile(t, fixture.config, strings.ReplaceAll(strings.ReplaceAll(string(configured), "workers: 1", "workers: 3"), "concurrency_limit: 1", "concurrency_limit: 3"))
checkUsage := func(directory, diagnostics string, executions, reported int) {
t.Helper()
summary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(directory, "executions.json"))
if len(summary.Members) != executions || summary.Attempts != uint64(executions) || summary.RepairCalls != 0 || !summary.TerminalCoverageComplete ||
!summary.Usage.TotalTokens.Known || summary.Usage.TotalTokens.Value != 12*reported || summary.Usage.ReasoningTokens.Value != reported ||
!summary.CostUSD.Known || summary.CostUSD.Value != float64(reported)*0.125 || summary.CostUSD.Complete != (executions == reported) {
t.Fatalf("native observation differs from fixture work: %#v; executions=%d reported=%d", summary, executions, reported)
}
for _, fragment := range []string{fmt.Sprintf("Prompts: %d\n", executions), fmt.Sprintf("Total tokens: %d", summary.Usage.TotalTokens.Value), fmt.Sprintf("Reasoning tokens: %d", reported), fmt.Sprintf("Cost: USD %g", summary.CostUSD.Value)} {
if !strings.Contains(diagnostics, fragment) {
t.Fatalf("missing native diagnostic %q: %s", fragment, diagnostics)
}
}
}
fixture.client.failEvents, fixture.client.correctScene = true, true
outcome, _, diagnostics := fixture.run(t)
outcome, _, diagnostics := fixture.run(t, "--show-tokens")
if outcome.Status != 1 || !errors.Is(outcome.Cause, fixture.client.failure) {
t.Fatalf("downstream failure=%#v diagnostics=%q", outcome, diagnostics)
}
@@ -204,9 +235,13 @@ func TestAssembledRecoveryReusesCorrectedPredecessorsAndChunkPlan(t *testing.T)
}
}
summary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(firstDebug, "executions.json"))
if len(summary.Members) != len(requests) || summary.Attempts != uint64(len(requests)) || !summary.TerminalCoverageComplete || summary.Usage.TotalTokens.Known {
if len(summary.Members) != len(requests) || summary.Attempts != uint64(len(requests)) || !summary.TerminalCoverageComplete || !summary.Usage.TotalTokens.Known {
t.Fatalf("failed-run native facts lost or duplicated: %#v", summary)
}
checkUsage(firstDebug, diagnostics, len(requests), len(requests)-1)
if strings.LastIndex(diagnostics, "Prompts:") > strings.LastIndex(diagnostics, fixture.client.failure.Error()) {
t.Fatal("failure explanation preceded final usage")
}
// Locate only the initial scene request's native hash in available capture;
// assert domain bytes at that key, not a persisted execution ledger.
var correctedKey string
@@ -232,7 +267,7 @@ func TestAssembledRecoveryReusesCorrectedPredecessorsAndChunkPlan(t *testing.T)
t.Fatalf("cache did not retain the corrected domain candidate: %#v", corrected)
}
fixture.client.failEvents = false
outcome, report, diagnostics := fixture.run(t)
outcome, report, diagnostics := fixture.run(t, "--show-tokens")
if outcome.Status != 0 || report.FallbackCount != 0 || report.ArtifactCount != 12 {
t.Fatalf("recovery=%#v report=%#v diagnostics=%q", outcome, report, diagnostics)
}
@@ -246,12 +281,13 @@ func TestAssembledRecoveryReusesCorrectedPredecessorsAndChunkPlan(t *testing.T)
t.Fatalf("recovery reran accepted %s: %v -> %v", role, counts, after)
}
}
checkUsage(report.DebugDirectory, diagnostics, 1, 1)
artifact := readProductionJSON[dnd.EnemyEventList](t, filepath.Join(report.OutputDirectory, "lanes", "enemy-events.json"))
if len(artifact.Events) != 1 || artifact.Events[0].SourceRefs[0].SourceID != "session-ravenfall" {
t.Fatalf("recovered domain evidence=%#v", artifact)
}
stable := readTree(t, fixture.cache)
outcome, hitReport, diagnostics := fixture.run(t)
outcome, hitReport, diagnostics := fixture.run(t, "--show-tokens")
if outcome.Status != 0 || hitReport.ArtifactCount != 12 {
t.Fatalf("cached run=%#v diagnostics=%q", outcome, diagnostics)
}
@@ -265,6 +301,7 @@ func TestAssembledRecoveryReusesCorrectedPredecessorsAndChunkPlan(t *testing.T)
}
}
hitSummary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(hitReport.DebugDirectory, "executions.json"))
checkUsage(hitReport.DebugDirectory, diagnostics, 0, 0)
if len(hitSummary.Members) != 0 || !hitSummary.TerminalCoverageComplete {
t.Fatalf("full hit fabricated historical execution totals: %#v", hitSummary)
}