From 00fc11360ed8a65821069a59843e3762f519772c Mon Sep 17 00:00:00 2001 From: Eric Rakestraw Date: Mon, 23 Nov 2026 02:46:25 +0000 Subject: [PATCH] Verify native provider accounting and smoke reports with local HTTP --- docs/roadmap/implementation.md | 18 +- internal/cli/application_test.go | 2 +- internal/cli/provider_accounting_test.go | 165 ++++++++++++++++++ .../framework/pipeline/native_capture_test.go | 3 + 4 files changed, 184 insertions(+), 4 deletions(-) create mode 100644 internal/cli/provider_accounting_test.go diff --git a/docs/roadmap/implementation.md b/docs/roadmap/implementation.md index 8ca2ebc6..24a828e0 100644 --- a/docs/roadmap/implementation.md +++ b/docs/roadmap/implementation.md @@ -272,6 +272,17 @@ Use focused `-race` runs for the new concurrent fixture. No production API calls ## Stage 5 — Verify Provider Accounting And Native Smoke Exposure +**Status:** Complete. A real native HTTP client and one local server fixture +cover explicit OpenRouter selection on an arbitrary backend ID, reasoning/cache +details, positive and reported-zero cost, unchanged domain/completion output, +and native result/debug/diagnostic propagation. Installed smoke commands retain +reasoning and nullable ratio values in JSON, native default text, and separate +ordinary accounting; help does not load configuration. Recorded the published +smoke API's target-only prompt selection rather than inventing input flags. +Unknown-cost capture coverage and complete-example inherited-provider inspection +pass. Focused CLI/pipeline checks and whitespace pass; fixtures use no real +credentials and all HTTP calls stay local. Example configurations are unchanged. + **Goal:** Cover the new provider/accounting boundary once through the real HTTP client and installed native commands. @@ -297,9 +308,10 @@ contract linked from the feature roadmap. provider field, add custom response parsing, or add a second vLLM decoder suite; upstream owns those contracts. 4. Through the installed ckprompt suite, use the same local fixture for explicit - `promptkit test text_inference` with a concrete prompt, profile, and required - inline inputs. Request structured JSON (and YAML only if an existing test - covers it) and check reasoning and nullable cache-hit-ratio propagation. + `promptkit test text_inference` with a concrete prompt and profile. The selected + native smoke API uses the prompt only for target selection; it does not execute + its body or accept prompt inputs. Request structured JSON (and YAML only if + an existing test covers it) and check reasoning and nullable cache-hit-ratio propagation. Smoke usage is in its own report, not an added smoke cost field or duplicate ordinary accounting. Check default smoke output/help against native behavior without a full-format golden file. diff --git a/internal/cli/application_test.go b/internal/cli/application_test.go index 28a58e2c..85f3c806 100644 --- a/internal/cli/application_test.go +++ b/internal/cli/application_test.go @@ -17,7 +17,7 @@ func TestNativeApplicationBuiltinsNeedNoConfiguration(t *testing.T) { if err != nil { t.Fatal(err) } - for _, args := range [][]string{{"--help"}, {"help"}, {"version"}, {"completion", "bash"}, {"completion", "zsh"}, {"completion", "fish"}, {"config", "--help"}, {"pipeline", "--help"}, {"pipeline", "validate", "--help"}, {"pipeline", "run", "--help"}, {"run", "--help", "--show-tokens"}, {"config", "explain", "--show-tokens"}} { + for _, args := range [][]string{{"--help"}, {"help"}, {"version"}, {"completion", "bash"}, {"completion", "zsh"}, {"completion", "fish"}, {"config", "--help"}, {"pipeline", "--help"}, {"pipeline", "validate", "--help"}, {"pipeline", "run", "--help"}, {"run", "--help", "--show-tokens"}, {"config", "explain", "--show-tokens"}, {"promptkit", "test", "--help", "--show-tokens"}} { var out, diagnostics bytes.Buffer outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostics}) if outcome.Status != 0 || out.Len() == 0 { diff --git a/internal/cli/provider_accounting_test.go b/internal/cli/provider_accounting_test.go new file mode 100644 index 00000000..a888b5cf --- /dev/null +++ b/internal/cli/provider_accounting_test.go @@ -0,0 +1,165 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "go.maximumdirect.net/commandkit" + "go.maximumdirect.net/promptkit" +) + +func TestNativeProviderAccountingAndSmokeUseTheConfiguredConvention(t *testing.T) { + for _, zero := range []bool{false, true} { + t.Run(fmt.Sprintf("known-zero=%t", zero), func(t *testing.T) { + prompt, completion, reasoning, total, cached, written, cost := 8, 4, 1, 12, 2, 1, 0.125 + if zero { + prompt, completion, reasoning, total, cached, written, cost = 0, 0, 0, 0, 0, 0, 0 + } + var calls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + calls.Add(1) + if request.Method != http.MethodPost || request.URL.Path != "/v1/chat/completions" { + t.Errorf("unexpected local provider request: %s %s", request.Method, request.URL.Path) + } + if request.Header.Get("Authorization") != "" { + t.Error("credential-free fixture received authentication") + } + writer.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(writer).Encode(map[string]any{ + "choices": []any{map[string]any{"message": map[string]any{"role": "assistant", "content": `{"spell_casts":[]}`}, "finish_reason": "stop"}}, + "usage": map[string]any{ + "prompt_tokens": prompt, "completion_tokens": completion, "total_tokens": total, "cost": cost, + "prompt_tokens_details": map[string]any{"cached_tokens": cached, "cache_write_tokens": written}, + "completion_tokens_details": map[string]any{"reasoning_tokens": reasoning}, + }, + }) + })) + defer server.Close() + file := writeProductionContractConfig(t, fmt.Sprintf(`version: 6 +output: {directory: output} +debug: {directory: debug} +pipelines: + demo: + input: {module: seriatim} + chunk: {module: generic} + llm_profile: accounting-profile + artifacts: + spells: + extract: {module: dnd/spells} +promptkit: + backends: + - id: arbitrary-transport + provider: openrouter + endpoint: %q + profiles: + - id: accounting-profile + backend: arbitrary-transport + model: accounting-model + api_key_required: false +`, server.URL+"/v1")) + input := filepath.Join(filepath.Dir(file), "input.json") + writeConfigKitFile(t, input, `{"metadata":{"id":"wire-source"},"segments":[{"id":1,"start":0,"end":1,"speaker":"GM","text":"The party rests."}]}`) + app, err := NewApplication("development", Options{ + LookupEnv: emptyLookup, Now: func() time.Time { return time.Unix(42, 0) }, + RunIDGenerator: func(time.Time) (string, error) { return "wire-run", nil }, + }) + if err != nil { + t.Fatal(err) + } + var stdout, diagnostics bytes.Buffer + outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache=bypass", "--debug", "--progress=false", "--show-tokens", "--format=json"}, commandkit.Streams{Out: &stdout, Err: &diagnostics}) + if outcome.Status != 0 || calls.Load() != 1 { + t.Fatalf("HTTP pipeline: %#v calls=%d stderr=%s", outcome, calls.Load(), diagnostics.String()) + } + report := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) + if len(report) != 4 || report["artifact_count"] != float64(1) { + t.Fatalf("usage changed completion output: %#v", report) + } + artifact := readProductionJSON[map[string]any](t, filepath.Join(report["output_directory"].(string), "lanes", "spells.json")) + if len(artifact["spell_casts"].([]any)) != 0 { + t.Fatalf("unexpected domain output: %#v", artifact) + } + summary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(report["debug_directory"].(string), "executions.json")) + if len(summary.Members) != 1 || !summary.TerminalCoverageComplete || summary.Attempts != 1 || + summary.Usage.TotalTokens.Value != total || !summary.Usage.TotalTokens.Known || !summary.Usage.TotalTokens.Complete || + summary.Usage.ReasoningTokens.Value != reasoning || !summary.Usage.ReasoningTokens.Known || + summary.Usage.CachedTokens.Value != cached || summary.Usage.CacheWriteTokens.Value != written || + !summary.CostUSD.Known || !summary.CostUSD.Complete || summary.CostUSD.Value != cost || summary.CostUSD.Source != "provider" { + t.Fatalf("provider accounting lost at debug boundary: %#v", summary) + } + results := 0 + for name, content := range readTree(t, report["debug_directory"].(string)) { + if !strings.HasSuffix(name, "/result.json") { + continue + } + results++ + var result promptkit.RunResult + if err := json.Unmarshal(content, &result); err != nil || result.Usage.TotalTokens != total || result.Usage.ReasoningTokens != reasoning || result.Usage.CacheWriteTokens != written || !result.CostUSD.Known || result.CostUSD.Value != cost { + t.Fatalf("native result accounting: %#v %v", result, err) + } + } + if results != 1 { + t.Fatalf("native results=%d", results) + } + for _, fragment := range []string{"Prompts: 1", fmt.Sprintf("Total tokens: %d", total), fmt.Sprintf("Reasoning tokens: %d", reasoning), fmt.Sprintf("Cost: USD %g", cost)} { + if !strings.Contains(diagnostics.String(), fragment) { + t.Fatalf("missing %q: %s", fragment, diagnostics.String()) + } + } + // Native smoke selects a target, not the prompt's body or required inputs. + smoke := []string{"promptkit", "test", "text_inference", "--config", file, "--llm-prompt=notarius/dnd.spells", "--llm-profile=accounting-profile", "--show-tokens"} + stdout.Reset() + diagnostics.Reset() + outcome = app.Execute(context.Background(), append(smoke, "--format=json"), commandkit.Streams{Out: &stdout, Err: &diagnostics}) + if outcome.Status != 0 || calls.Load() != 2 { + t.Fatalf("native smoke: %#v calls=%d stderr=%s", outcome, calls.Load(), diagnostics.String()) + } + smokeReport := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) + usage := smokeReport["usage"].(map[string]any) + count := usage["reasoning_tokens"].(map[string]any) + if smokeReport["kind"] != "text_inference" || smokeReport["completed"] != true || count["value"] != float64(reasoning) || count["known"] != true || count["complete"] != true { + t.Fatalf("smoke reasoning: %#v", smokeReport) + } + if zero && usage["cache_hit_ratio"] != nil || !zero && usage["cache_hit_ratio"] != 0.25 { + t.Fatalf("smoke nullable ratio: %#v", usage) + } + if _, exists := smokeReport["cost_usd"]; exists { + t.Fatal("smoke acquired a cost field") + } + if !strings.Contains(diagnostics.String(), "Prompts: 0") || !strings.Contains(diagnostics.String(), "Total tokens: 0") { + t.Fatalf("smoke usage duplicated ordinary execution accounting: %s", diagnostics.String()) + } + stdout.Reset() + diagnostics.Reset() + outcome = app.Execute(context.Background(), smoke, commandkit.Streams{Out: &stdout, Err: &diagnostics}) + if outcome.Status != 0 || calls.Load() != 3 || json.Valid(stdout.Bytes()) || !strings.Contains(stdout.String(), "text_inference") || !zero && !strings.Contains(stdout.String(), "25.0%") { + t.Fatalf("native default smoke text: %#v stdout=%s stderr=%s", outcome, stdout.String(), diagnostics.String()) + } + }) + } +} + +func TestCompleteExampleInheritsNativeOpenRouterProvider(t *testing.T) { + app, err := NewApplication("development", Options{LookupEnv: emptyLookup}) + if err != nil { + t.Fatal(err) + } + var stdout, diagnostics bytes.Buffer + outcome := app.Execute(context.Background(), []string{"promptkit", "show", "backend", "limited-openrouter", "--config", repositoryPath("examples", "dnd-complete", "config.yml"), "--format=json"}, commandkit.Streams{Out: &stdout, Err: &diagnostics}) + if outcome.Status != 0 { + t.Fatalf("backend inspection: %#v %s", outcome, diagnostics.String()) + } + backend := decodeCompletionReport(t, commandkit.FormatJSON, stdout.Bytes()) + if backend["provider"] != "openrouter" || backend["zero_cost"] != nil { + t.Fatalf("native inheritance changed: %#v", backend) + } +} diff --git a/internal/framework/pipeline/native_capture_test.go b/internal/framework/pipeline/native_capture_test.go index 8dc3aad0..0ee4d8e5 100644 --- a/internal/framework/pipeline/native_capture_test.go +++ b/internal/framework/pipeline/native_capture_test.go @@ -127,6 +127,9 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing if summary.Usage.TotalTokens.Known || summary.Usage.TotalTokens.Complete { t.Fatalf("fabricated known usage: %#v", summary.Usage) } + if summary.CostUSD.Known || summary.CostUSD.Complete { + t.Fatalf("fabricated known cost: %#v", summary.CostUSD) + } if nativeEvidenceCount(evidence, "/result.json") != 4 || nativeEvidenceCount(evidence, "/exchange.json") != 4 { t.Fatalf("missing native results/exchanges: %v", evidence.files) }