Verify native usage reporting across recovery and delivery boundaries
This commit is contained in:
@@ -17,12 +17,15 @@ 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"}} {
|
||||
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"}} {
|
||||
var out, diagnostics bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &out, Err: &diagnostics})
|
||||
if outcome.Status != 0 || out.Len() == 0 {
|
||||
t.Fatalf("%v: %#v, %s", args, outcome, diagnostics.String())
|
||||
}
|
||||
if strings.Contains(diagnostics.String(), "Observed PromptKit execution usage") {
|
||||
t.Fatalf("help/builtin started usage reporting: %s", diagnostics.String())
|
||||
}
|
||||
if args[0] == "version" && !strings.Contains(out.String(), "v1.2.3") {
|
||||
t.Fatalf("release identity missing: %s", out.String())
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/pipeline"
|
||||
units "gitea.maximumdirect.net/eric/notarius/internal/modules/generic/chunk/units"
|
||||
jsonoutput "gitea.maximumdirect.net/eric/notarius/internal/modules/generic/output/json"
|
||||
"go.maximumdirect.net/ckconfig"
|
||||
"go.maximumdirect.net/ckprompt"
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
@@ -204,7 +206,13 @@ func runFixture(t *testing.T, probe *runProbe, configure ...func(string) string)
|
||||
state = &nativeLoaders{engineOptions: []promptkit.Option{promptkit.WithLLMClient(probe)}}
|
||||
return state
|
||||
}
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "notarius"}, pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return catalogFromRegistries(registries), nil }, pipelineRunCommand("development", newState, func() (pipeline.Registries, error) { return registries, nil }, options)), commandkit.Alias("run", "pipeline run"))
|
||||
definitions := ckprompt.FromEngine(func(ctx context.Context, selection ckconfig.Selection, _ struct{}, state *nativeLoaders) (*promptkit.Engine, error) {
|
||||
return state.engine(ctx, selection)
|
||||
})
|
||||
definitions.NewState = newState
|
||||
declarations := []commandkit.Declaration{pipelineCommands(newState, func() (pipeline.ModuleCatalog, error) { return catalogFromRegistries(registries), nil }, pipelineRunCommand("development", newState, func() (pipeline.Registries, error) { return registries, nil }, options)), commandkit.Alias("run", "pipeline run")}
|
||||
declarations = append(declarations, ckprompt.Declarations(definitions)...)
|
||||
app, err := commandkit.New(commandkit.Identity{Name: "notarius"}, declarations...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"go.maximumdirect.net/commandkit"
|
||||
"go.maximumdirect.net/configkit"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func decodeCompletionReport(t *testing.T, format commandkit.Format, content []byte) map[string]any {
|
||||
@@ -83,8 +84,8 @@ func TestNativeRunCompletionFormatsFollowPublicationAndCapture(t *testing.T) {
|
||||
app, file, input, _ := runFixture(t, probe)
|
||||
output := &completedRunWriter{t: t, file: file, captured: true}
|
||||
var diagnostics bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--format", string(format)}, commandkit.Streams{Out: output, Err: &diagnostics})
|
||||
if outcome.Status != 0 || !strings.Contains(diagnostics.String(), "Running pipeline") {
|
||||
outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--show-tokens", "--format", string(format)}, commandkit.Streams{Out: output, Err: &diagnostics})
|
||||
if outcome.Status != 0 || !strings.Contains(diagnostics.String(), "Running pipeline") || !strings.Contains(diagnostics.String(), "Observed PromptKit execution usage") {
|
||||
t.Fatalf("completion: %#v stderr=%s", outcome, diagnostics.String())
|
||||
}
|
||||
directory := filepath.Join(filepath.Dir(file), "output-must-not-exist", "run-1")
|
||||
@@ -151,11 +152,14 @@ func TestNativeRunQuietAndDebugUseNativeModeOrdering(t *testing.T) {
|
||||
probe := &runProbe{}
|
||||
app, file, input, _ := runFixture(t, probe)
|
||||
var output, diagnostics bytes.Buffer
|
||||
args := append([]string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--format", "json"}, test.flags...)
|
||||
args := append([]string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--show-tokens", "--format", "json"}, test.flags...)
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &output, Err: &diagnostics})
|
||||
if outcome.Status != 0 || test.quiet != (output.Len() == 0) || test.progress != strings.Contains(diagnostics.String(), "Running pipeline") {
|
||||
t.Fatalf("native mode order: %#v output=%s stderr=%s", outcome, output.String(), diagnostics.String())
|
||||
}
|
||||
if test.quiet == strings.Contains(diagnostics.String(), "Observed PromptKit execution usage") {
|
||||
t.Fatalf("usage quiet selection: %q", diagnostics.String())
|
||||
}
|
||||
assertCompletedRunFiles(t, file, true)
|
||||
}
|
||||
}
|
||||
@@ -167,10 +171,14 @@ func TestNativeRunCancellationKeepsItsCauseAndPublishesNothing(t *testing.T) {
|
||||
defer cancel()
|
||||
probe.onGenerate = cancel
|
||||
var output, diagnostics bytes.Buffer
|
||||
outcome := app.Execute(ctx, []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--quiet"}, commandkit.Streams{Out: &output, Err: &diagnostics})
|
||||
outcome := app.Execute(ctx, []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--debug", "--show-tokens"}, commandkit.Streams{Out: &output, Err: &diagnostics})
|
||||
if outcome.Status != 1 || !errors.Is(outcome.Cause, context.Canceled) || output.Len() != 0 || diagnostics.Len() == 0 {
|
||||
t.Fatalf("cancellation: %#v stdout=%s stderr=%s", outcome, output.String(), diagnostics.String())
|
||||
}
|
||||
summary := readProductionJSON[promptkit.ExecutionGroupSummary](t, filepath.Join(filepath.Dir(file), "debug-must-not-exist", "run-1", "executions.json"))
|
||||
if len(summary.Members) != 1 || !summary.TerminalCoverageComplete || !strings.Contains(diagnostics.String(), "Prompts: 1") {
|
||||
t.Fatalf("canceled work lost: %#v %s", summary, diagnostics.String())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(filepath.Dir(file), "output-must-not-exist")); !os.IsNotExist(err) {
|
||||
t.Fatalf("cancellation published artifacts: %v", err)
|
||||
}
|
||||
@@ -223,21 +231,34 @@ func TestNativeRunReportDeliveryFailuresRetainArtifactsAndNativePresentation(t *
|
||||
}
|
||||
|
||||
func TestNativeRunDiagnosticDeliveryFailureIsNotAnOperationFailure(t *testing.T) {
|
||||
sentinel := errors.New("diagnostic delivery sentinel")
|
||||
probe := &runProbe{correctFirst: true}
|
||||
app, file, input, _ := runFixture(t, probe)
|
||||
var output bytes.Buffer
|
||||
outcome := app.Execute(context.Background(), []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--set", `/pipelines/demo/mode="permissive"`, "--set", "/pipelines/demo/max_additional_turns=0", "--format", "json", "--verbose"}, commandkit.Streams{Out: &output, Err: failingResultWriter{cause: sentinel}})
|
||||
if outcome.Status != 1 || outcome.Cause != nil || !errors.Is(outcome.Presentation.Diagnostics.WriteError, sentinel) || outcome.Presentation.Diagnostics.State != commandkit.DeliveryIncomplete {
|
||||
t.Fatalf("diagnostic delivery: %#v", outcome)
|
||||
for _, showUsage := range []bool{false, true} {
|
||||
t.Run(map[bool]string{false: "warnings", true: "usage"}[showUsage], func(t *testing.T) {
|
||||
sentinel := errors.New("diagnostic delivery sentinel")
|
||||
probe := &runProbe{correctFirst: true}
|
||||
app, file, input, _ := runFixture(t, probe)
|
||||
var output bytes.Buffer
|
||||
args := []string{"run", "demo", "--config", file, "--input-file", input, "--cache", "bypass", "--set", `/pipelines/demo/mode="permissive"`, "--set", "/pipelines/demo/max_additional_turns=0", "--format", "json"}
|
||||
if showUsage {
|
||||
args = append(args, "--show-tokens", "--progress=false")
|
||||
} else {
|
||||
args = append(args, "--verbose")
|
||||
}
|
||||
outcome := app.Execute(context.Background(), args, commandkit.Streams{Out: &output, Err: failingResultWriter{cause: sentinel}})
|
||||
if outcome.Status != 1 || outcome.Cause != nil || !errors.Is(outcome.Presentation.Diagnostics.WriteError, sentinel) || outcome.Presentation.Diagnostics.State != commandkit.DeliveryIncomplete {
|
||||
t.Fatalf("diagnostic delivery: %#v", outcome)
|
||||
}
|
||||
if report := decodeCompletionReport(t, commandkit.FormatJSON, output.Bytes()); report["fallback_count"] != float64(1) {
|
||||
t.Fatalf("completed report was replaced by a delivery envelope: %#v", report)
|
||||
}
|
||||
if !strings.Contains(outcome.Explanation.Message, filepath.Join(filepath.Dir(file), "output-must-not-exist", "run-1")) {
|
||||
t.Fatalf("presentation failure lost available artifacts: %#v", outcome)
|
||||
}
|
||||
if probe.produced != 1 {
|
||||
t.Fatalf("reporting reran model work: %d", probe.produced)
|
||||
}
|
||||
assertCompletedRunFiles(t, file, false)
|
||||
})
|
||||
}
|
||||
if report := decodeCompletionReport(t, commandkit.FormatJSON, output.Bytes()); report["fallback_count"] != float64(1) {
|
||||
t.Fatalf("completed report was replaced by a delivery envelope: %#v", report)
|
||||
}
|
||||
if !strings.Contains(outcome.Explanation.Message, filepath.Join(filepath.Dir(file), "output-must-not-exist", "run-1")) {
|
||||
t.Fatalf("presentation failure lost available artifacts: %#v", outcome)
|
||||
}
|
||||
assertCompletedRunFiles(t, file, false)
|
||||
}
|
||||
|
||||
func TestNativeRunCaptureFailureAfterPublicationDoesNotReportSuccess(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user