Verify native usage reporting across the pipeline

This commit is contained in:
2026-11-23 04:42:54 +00:00
parent c477bcc388
commit fa5d834f13
4 changed files with 104 additions and 19 deletions

View File

@@ -17,6 +17,7 @@ import (
"time" "time"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
pk "go.maximumdirect.net/promptkit"
) )
type repairWireMessage struct { type repairWireMessage struct {
@@ -115,7 +116,7 @@ func (p *correctionProvider) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
raw, _ := json.Marshal(content) raw, _ := json.Marshal(content)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}]}`, raw) fmt.Fprintf(w, `{"model":"fixture","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, raw)
} }
func TestSubprocessReportsDefectOnOriginatingRepair(t *testing.T) { func TestSubprocessReportsDefectOnOriginatingRepair(t *testing.T) {
@@ -190,7 +191,7 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
provider.mu.Lock() provider.mu.Lock()
provider.decimalReferences = tc.decimalReferences provider.decimalReferences = tc.decimalReferences
provider.mu.Unlock() provider.mu.Unlock()
args := []string{"--verbose"} args := []string{"--verbose", "--show-tokens"}
if tc.debug { if tc.debug {
args = append(args, "--debug") args = append(args, "--debug")
} }
@@ -222,6 +223,9 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
provider.mu.Lock() provider.mu.Lock()
requests := append([]repairWireRequest(nil), provider.requests...) requests := append([]repairWireRequest(nil), provider.requests...)
provider.mu.Unlock() provider.mu.Unlock()
if !strings.Contains(stderr, fmt.Sprintf("Prompts: %d", len(requests))) || !strings.Contains(stderr, "Total tokens:") {
t.Fatalf("native usage did not cover the assembled pipeline: requests=%d stderr=%s", len(requests), stderr)
}
var base []repairWireMessage var base []repairWireMessage
var branches [][]repairWireMessage var branches [][]repairWireMessage
for _, req := range requests { for _, req := range requests {
@@ -271,13 +275,13 @@ func TestSubprocessCorrectionRepairConversation(t *testing.T) {
} }
var execution struct { var execution struct {
Summary struct { Summary struct {
ProviderAttempts int `json:"provider_attempts"` PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
} `json:"summary"` } `json:"summary"`
} }
if err := json.Unmarshal(data, &execution); err != nil { if err := json.Unmarshal(data, &execution); err != nil {
t.Fatal(err) t.Fatal(err)
} }
if got := execution.Summary.ProviderAttempts; got != len(requests) { if got := execution.Summary.PromptKit.Attempts; got != uint64(len(requests)) {
t.Fatalf("execution provider attempts = %d, captured requests = %d", got, len(requests)) t.Fatalf("execution provider attempts = %d, captured requests = %d", got, len(requests))
} }
} }
@@ -336,7 +340,7 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
f, provider := setupCorrectionFixture(t, 2, false, true) f, provider := setupCorrectionFixture(t, 2, false, true)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() defer cancel()
args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug"} args := []string{"-test.run=^TestProcessSubprocessHelper$", "--", "process", f.transcript, "--config", f.config, "--output", f.output, "--debug", "--show-tokens"}
command := exec.CommandContext(ctx, os.Args[0], args...) command := exec.CommandContext(ctx, os.Args[0], args...)
command.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1") command.Env = append(os.Environ(), "AUDITA_HELPER_PROCESS=1")
var stderr bytes.Buffer var stderr bytes.Buffer
@@ -356,6 +360,12 @@ func TestSubprocessCancellationDuringCorrectionRepair(t *testing.T) {
if ctx.Err() != nil || err == nil { if ctx.Err() != nil || err == nil {
t.Fatalf("cancellation: %v ctx=%v stderr=%s", err, ctx.Err(), stderr.String()) t.Fatalf("cancellation: %v ctx=%v stderr=%s", err, ctx.Err(), stderr.String())
} }
provider.mu.Lock()
count := len(provider.requests)
provider.mu.Unlock()
if !strings.Contains(stderr.String(), fmt.Sprintf("Prompts: %d", count)) {
t.Fatalf("canceled usage missing executions: requests=%d stderr=%s", count, stderr.String())
}
if _, err := os.Stat(f.output); !os.IsNotExist(err) { if _, err := os.Stat(f.output); !os.IsNotExist(err) {
t.Fatalf("transcript published: %v", err) t.Fatalf("transcript published: %v", err)
} }

View File

@@ -8,6 +8,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
@@ -24,6 +25,8 @@ import (
"gitea.maximumdirect.net/eric/audita/v4/internal/cli" "gitea.maximumdirect.net/eric/audita/v4/internal/cli"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting" "gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
"gitea.maximumdirect.net/eric/audita/v4/internal/core/schema" "gitea.maximumdirect.net/eric/audita/v4/internal/core/schema"
"gitea.maximumdirect.net/eric/audita/v4/internal/prompts"
pk "go.maximumdirect.net/promptkit"
"go.yaml.in/yaml/v4" "go.yaml.in/yaml/v4"
) )
@@ -195,7 +198,7 @@ func (p *fixtureProvider) serve(w http.ResponseWriter, r *http.Request) {
} }
encoded, _ := json.Marshal(content) encoded, _ := json.Marshal(content)
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5}}`, encoded) _, _ = fmt.Fprintf(w, `{"model":"synthetic","choices":[{"message":{"content":%s}}],"usage":{"prompt_tokens":2,"completion_tokens":3,"total_tokens":5,"completion_tokens_details":{"reasoning_tokens":1},"cost":0.02}}`, encoded)
} }
// Read the supplied candidate JSON independently of the bundled instruction prose. // Read the supplied candidate JSON independently of the bundled instruction prose.
@@ -261,6 +264,25 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") { if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
repairs = 1 repairs = 1
} }
if repairs == 0 {
promptDir := filepath.Join(dir, "prompts")
if err := os.Mkdir(promptDir, 0700); err != nil {
t.Fatal(err)
}
for _, meta := range prompts.RegisteredMetadata() {
if strings.HasSuffix(meta.PromptID, ".repair") {
continue
}
data, err := fs.ReadFile(prompts.Filesystem(), meta.EmbeddedPath)
if err != nil {
t.Fatal(err)
}
data = append(data, []byte(" repair_attempts: 0\n")...)
if err := os.WriteFile(filepath.Join(promptDir, filepath.Base(meta.EmbeddedPath)), data, 0600); err != nil {
t.Fatal(err)
}
}
}
var stageList []string var stageList []string
for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") { for _, name := range strings.Split(strings.Trim(modules, "[]"), ",") {
if name = strings.TrimSpace(name); name != "" { if name = strings.TrimSpace(name); name != "" {
@@ -271,7 +293,7 @@ func newProcessFixture(t *testing.T, mode, modules string) processFixture {
if len(stageList) != 0 { if len(stageList) != 0 {
pipeline = " stages:\n" + strings.Join(stageList, "\n") + "\n" pipeline = " stages:\n" + strings.Join(stageList, "\n") + "\n"
} }
configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\n repair_attempts: %d\npipeline:\n%sdiagnostics:\n work_dir: %s\n", repairs, pipeline, filepath.Join(dir, "runs")) configText := fmt.Sprintf("version: 3\nllm:\n proposal_profile: proposal\n validation_profile: validation\n transient_retries: 0\n correction_repair_attempts: 0\npipeline:\n%sdiagnostics:\n work_dir: %s\n", pipeline, filepath.Join(dir, "runs"))
if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") { if strings.HasPrefix(mode, "span-") || strings.HasPrefix(mode, "decision-") {
configText += "validation:\n max_prompt_tokens: 4096\nchunking:\n target_sections: 1\n max_section_tokens: 8192\n min_section_tokens: 1\nnormalization:\n max_segment_gap: 0\n" configText += "validation:\n max_prompt_tokens: 4096\nchunking:\n target_sections: 1\n max_section_tokens: 8192\n min_section_tokens: 1\nnormalization:\n max_segment_gap: 0\n"
} }
@@ -311,6 +333,54 @@ func (f processFixture) run(t *testing.T, includeOutput bool, extra ...string) (
return code, stdout.String(), stderr.String() return code, stdout.String(), stderr.String()
} }
func TestSubprocessNativeUsageReporting(t *testing.T) {
for _, tc := range []struct {
name, mode, modules string
flags []string
fileOutput bool
wantPrompts string
wantUsage bool
}{
{"normalization", "normal", "[]", []string{"--show-tokens"}, false, "Prompts: 0", true},
{"failed provider", "all-model-failure", "[grammar]", []string{"--show-tokens"}, false, "Prompts: 1", true},
{"quiet", "normal", "[grammar]", []string{"--show-tokens", "--quiet"}, true, "", false},
} {
t.Run(tc.name, func(t *testing.T) {
f := newProcessFixture(t, tc.mode, tc.modules)
code, stdout, stderr := f.run(t, tc.fileOutput, tc.flags...)
if code != 0 || strings.Contains(stdout, "Observed PromptKit execution usage") || strings.Contains(stderr, "Observed PromptKit execution usage") != tc.wantUsage {
t.Fatalf("status=%d stdout=%q stderr=%q", code, stdout, stderr)
}
if tc.wantUsage && !strings.Contains(stderr, tc.wantPrompts) {
t.Fatalf("missing usage count %q: %s", tc.wantPrompts, stderr)
}
if !tc.fileOutput && !json.Valid([]byte(stdout)) {
t.Fatalf("stdout is not transcript JSON: %q", stdout)
}
if _, err := os.Stat(filepath.Join(f.dir, "report.md")); err != nil {
t.Fatalf("ordinary report missing: %v", err)
}
})
}
}
func TestSubprocessExplicitProviderUsage(t *testing.T) {
f := newProcessFixture(t, "normal", "[grammar]")
path := filepath.Join(f.dir, "prompts.yml")
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
data = bytes.Replace(data, []byte(" - id: local\n"), []byte(" - id: local\n provider: openrouter\n"), 1)
if err := os.WriteFile(path, data, 0600); err != nil {
t.Fatal(err)
}
code, stdout, stderr := f.run(t, false, "--show-tokens")
if code != 0 || !json.Valid([]byte(stdout)) || f.provider.callCount() != 3 || !strings.Contains(stderr, "Reasoning tokens: 3") || !strings.Contains(stderr, "Cost: USD 0.06") {
t.Fatalf("provider usage: status=%d calls=%d stdout=%q stderr=%q", code, f.provider.callCount(), stdout, stderr)
}
}
func (f processFixture) errors(t *testing.T) reporting.ErrorsDocument { func (f processFixture) errors(t *testing.T) reporting.ErrorsDocument {
t.Helper() t.Helper()
raw, err := os.ReadFile(filepath.Join(f.dir, "errors.yml")) raw, err := os.ReadFile(filepath.Join(f.dir, "errors.yml"))
@@ -431,10 +501,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) {
} }
var execution struct { var execution struct {
Calls []struct { Calls []struct {
Summary struct { PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
ProviderAttempts int `json:"provider_attempts"`
StructuralRepairs int `json:"structural_repairs"`
} `json:"summary"`
} `json:"calls"` } `json:"calls"`
} }
if err := json.Unmarshal(raw, &execution); err != nil { if err := json.Unmarshal(raw, &execution); err != nil {
@@ -444,7 +511,7 @@ func (f processFixture) assertNoStructuralRepairs(t *testing.T, wantCalls int) {
t.Fatalf("unexpected generation counts: calls=%d provider=%d", len(execution.Calls), f.provider.callCount()) t.Fatalf("unexpected generation counts: calls=%d provider=%d", len(execution.Calls), f.provider.callCount())
} }
for _, call := range execution.Calls { for _, call := range execution.Calls {
if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 { if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 {
t.Fatalf("unexpected structural repair: %+v", call) t.Fatalf("unexpected structural repair: %+v", call)
} }
} }
@@ -492,10 +559,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in
} }
var execution struct { var execution struct {
Calls []struct { Calls []struct {
Summary struct { PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
ProviderAttempts int `json:"provider_attempts"`
StructuralRepairs int `json:"structural_repairs"`
} `json:"summary"`
} `json:"calls"` } `json:"calls"`
} }
if err := json.Unmarshal(raw, &execution); err != nil { if err := json.Unmarshal(raw, &execution); err != nil {
@@ -505,7 +569,7 @@ func (f processFixture) assertDecisionRequestsUseOneAttempt(t *testing.T) [][]in
t.Fatalf("logical/provider calls: %d/%d", len(execution.Calls), providerCalls) t.Fatalf("logical/provider calls: %d/%d", len(execution.Calls), providerCalls)
} }
for _, call := range execution.Calls { for _, call := range execution.Calls {
if call.Summary.ProviderAttempts != 1 || call.Summary.StructuralRepairs != 0 { if call.PromptKit.Attempts != 1 || call.PromptKit.RepairCalls != 0 {
t.Fatalf("extra generation or structural repair: %+v", call) t.Fatalf("extra generation or structural repair: %+v", call)
} }
} }
@@ -1414,7 +1478,7 @@ func TestSubprocessProfileSources(t *testing.T) {
f := newProcessFixture(t, "success", "[]") f := newProcessFixture(t, "success", "[]")
// PromptKit uses profile IDs, not filename stems. A report-named profile is // PromptKit uses profile IDs, not filename stems. A report-named profile is
// still an input and must not be overwritten during report initialization. // still an input and must not be overwritten during report initialization.
if err := os.Mkdir(filepath.Join(f.dir, "prompts"), 0700); err != nil { if err := os.MkdirAll(filepath.Join(f.dir, "prompts"), 0700); err != nil {
t.Fatal(err) t.Fatal(err)
} }
loaded := filepath.Join(f.dir, "prompts", "errors.yml") loaded := filepath.Join(f.dir, "prompts", "errors.yml")

View File

@@ -409,6 +409,13 @@ the controlled workload, without copying CommandKit's report template or
PromptKit's full retry/cost accounting suite. Keep Audita's ordinary completion PromptKit's full retry/cost accounting suite. Keep Audita's ordinary completion
message, partial-success behavior, capacity sharing, and output lifecycle. message, partial-success behavior, capacity sharing, and output lifecycle.
**Complete.** Assembled command tests exercise native usage reporting through
proposal, validation, correction repair, failure, cancellation, debug and
quiet modes, as well as normalization-only processing. They cover an explicit
OpenRouter provider, prepared contract inspection, transcript stdout isolation,
and ordinary reports. The CLI, subprocess, and LLM package tests pass with
controlled providers and prompt-owned fixture budgets.
## Stage 8: Update Maintained Examples, Migration Guidance, and Canonical Docs ## Stage 8: Update Maintained Examples, Migration Guidance, and Canonical Docs
**Outcome:** Documentation explains Audita's changed integration and links to **Outcome:** Documentation explains Audita's changed integration and links to

View File

@@ -194,11 +194,15 @@ collections:
t.Fatalf("validator status=%d out=%q err=%q", outcome.Status, out, stderr) t.Fatalf("validator status=%d out=%q err=%q", outcome.Status, out, stderr)
} }
validatorPreview := append([]string{"promptkit", "show", "prepared", "audita/validators.editorial_review"}, common...) validatorPreview := append([]string{"promptkit", "show", "prepared", "audita/validators.editorial_review"}, common...)
validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=") validatorPreview = append(validatorPreview, "--llm-var", `PayloadJSON=[{"correction_index":1,"original_segment_text":"teh cat","corrected_segment_text":"the cat"}]`, "--llm-var", "TranscriptDescriptionBlock=", "--format=json")
outcome, out, stderr = execute(validatorPreview...) outcome, out, stderr = execute(validatorPreview...)
if outcome.Status != 0 || !strings.Contains(out, "teh cat") { if outcome.Status != 0 || !strings.Contains(out, "teh cat") {
t.Fatalf("validator preview status=%d out=%q err=%q", outcome.Status, out, stderr) t.Fatalf("validator preview status=%d out=%q err=%q", outcome.Status, out, stderr)
} }
var prepared pk.PreparedRun
if err := json.Unmarshal([]byte(out), &prepared); err != nil || prepared.MessageContentHash == "" || prepared.StructuredOutput == nil || prepared.OutputContract.SchemaPath == "" {
t.Fatalf("preview missing prepared contract or hash: %+v, error=%v, output=%s", prepared, err, out)
}
if calls != 0 { if calls != 0 {
t.Fatalf("inspection made %d provider calls", calls) t.Fatalf("inspection made %d provider calls", calls)
} }