Preserve native diagnostic evidence
This commit is contained in:
@@ -368,6 +368,12 @@ versus zero states; do not snapshot the complete upstream event structure.
|
|||||||
Confirm debug remains optional and capture-disabled processing avoids prepared
|
Confirm debug remains optional and capture-disabled processing avoids prepared
|
||||||
message snapshots. Keep partial artifact-write failure coverage.
|
message snapshots. Keep partial artifact-write failure coverage.
|
||||||
|
|
||||||
|
**Complete.** Debug reports now retain native execution and prepared-run
|
||||||
|
evidence alongside Audita attribution. Repair request histories share unchanged
|
||||||
|
message prefixes, including native evidence. Focused adapter, runner, report,
|
||||||
|
and CLI tests pass for prepared contracts and hashes, optional capture,
|
||||||
|
attribution, native usage and cost, and partial artifact-write failures.
|
||||||
|
|
||||||
## Stage 7: Exercise Native CLI Usage Reporting and the Assembled Pipeline
|
## Stage 7: Exercise Native CLI Usage Reporting and the Assembled Pipeline
|
||||||
|
|
||||||
**Outcome:** The installed ckprompt family supplies invocation usage reporting
|
**Outcome:** The installed ckprompt family supplies invocation usage reporting
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package reporting
|
|
||||||
|
|
||||||
// TokenMetric distinguishes measured zero from unavailable provider usage.
|
|
||||||
type TokenMetric struct {
|
|
||||||
Value int `json:"value"`
|
|
||||||
Known bool `json:"known"`
|
|
||||||
Complete bool `json:"complete"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LLMUsage struct {
|
|
||||||
Prompt TokenMetric `json:"prompt"`
|
|
||||||
Completion TokenMetric `json:"completion"`
|
|
||||||
Total TokenMetric `json:"total"`
|
|
||||||
Cached TokenMetric `json:"cached"`
|
|
||||||
CacheWrite TokenMetric `json:"cache_write"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type LLMSummary struct {
|
|
||||||
LogicalCalls uint64 `json:"logical_calls"`
|
|
||||||
ProviderAttempts uint64 `json:"provider_attempts"`
|
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage LLMUsage `json:"usage"`
|
|
||||||
}
|
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -54,6 +55,39 @@ type pendingCall struct {
|
|||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// preparedEvidence keeps the native prepared run while allowing repair
|
||||||
|
// histories to retain a shared prefix of their append-only messages.
|
||||||
|
type preparedEvidence struct {
|
||||||
|
run pk.PreparedRun
|
||||||
|
history *preparedMessageHistory
|
||||||
|
}
|
||||||
|
|
||||||
|
type preparedMessageHistory struct{ messages []pk.RenderedMessage }
|
||||||
|
|
||||||
|
func (e preparedEvidence) MarshalJSON() ([]byte, error) { return json.Marshal(e.run) }
|
||||||
|
|
||||||
|
func (e preparedEvidence) ShareMessages(previous any) any {
|
||||||
|
prior, ok := previous.(preparedEvidence)
|
||||||
|
if !ok || prior.history == nil || len(prior.history.messages) > len(e.run.Messages) || !slices.EqualFunc(prior.history.messages, e.run.Messages[:len(prior.history.messages)], sameRenderedMessage) {
|
||||||
|
e.history = &preparedMessageHistory{messages: e.run.Messages}
|
||||||
|
} else {
|
||||||
|
e.history = prior.history
|
||||||
|
e.history.messages = append(e.history.messages, e.run.Messages[len(e.history.messages):]...)
|
||||||
|
}
|
||||||
|
e.run.Messages = slices.Clip(e.history.messages)
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameRenderedMessage(a, b pk.RenderedMessage) bool {
|
||||||
|
if a.Role != b.Role || a.Content != b.Content {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if a.CacheControl == nil || b.CacheControl == nil {
|
||||||
|
return a.CacheControl == b.CacheControl
|
||||||
|
}
|
||||||
|
return *a.CacheControl == *b.CacheControl
|
||||||
|
}
|
||||||
|
|
||||||
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
||||||
p.once.Do(func() {
|
p.once.Do(func() {
|
||||||
p.response, p.err = p.complete(result, err)
|
p.response, p.err = p.complete(result, err)
|
||||||
@@ -159,7 +193,7 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
|||||||
metadata := promptMetadata(details)
|
metadata := promptMetadata(details)
|
||||||
var snapshot *structuredoutput.PreparedSnapshot
|
var snapshot *structuredoutput.PreparedSnapshot
|
||||||
if req.CaptureDiagnostics {
|
if req.CaptureDiagnostics {
|
||||||
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata}
|
snapshot = &structuredoutput.PreparedSnapshot{Messages: convertMessages(details.Messages), Prompt: metadata, PromptKit: preparedEvidence{run: details}}
|
||||||
}
|
}
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
prepared, prompt = snapshot, metadata
|
prepared, prompt = snapshot, metadata
|
||||||
|
|||||||
@@ -325,6 +325,17 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
|||||||
if !requestSeen || count.Load() != 1 || response.Prepared == nil || len(response.Prepared.Messages) == 0 {
|
if !requestSeen || count.Load() != 1 || response.Prepared == nil || len(response.Prepared.Messages) == 0 {
|
||||||
t.Fatal("prepared call missing")
|
t.Fatal("prepared call missing")
|
||||||
}
|
}
|
||||||
|
encoded, err := json.Marshal(response.Prepared.PromptKit)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var native pk.PreparedRun
|
||||||
|
if err := json.Unmarshal(encoded, &native); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if native.MessageContentHash == "" || native.OutputContract.SchemaPath == "" || native.StructuredOutput == nil || native.StructuredOutput.JSONSchema == nil {
|
||||||
|
t.Fatalf("missing native prepared contract or hash: %+v", native)
|
||||||
|
}
|
||||||
if len(posted.Messages) != len(response.Prepared.Messages) {
|
if len(posted.Messages) != len(response.Prepared.Messages) {
|
||||||
t.Fatal("prepared and dispatched message counts differ")
|
t.Fatal("prepared and dispatched message counts differ")
|
||||||
}
|
}
|
||||||
@@ -348,6 +359,40 @@ func TestPreparedAdapterMetadataAndTargetGuard(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPreparedEvidenceSharesGrowingMessageHistory(t *testing.T) {
|
||||||
|
first := preparedEvidence{run: pk.PreparedRun{Messages: make([]pk.RenderedMessage, 1, 4)}}
|
||||||
|
first.run.Messages[0] = pk.RenderedMessage{Role: "user", Content: "first"}
|
||||||
|
first = first.ShareMessages(nil).(preparedEvidence)
|
||||||
|
second := preparedEvidence{run: pk.PreparedRun{Messages: []pk.RenderedMessage{{Role: "user", Content: "first"}, {Role: "assistant", Content: "reply"}}}}
|
||||||
|
second = second.ShareMessages(first).(preparedEvidence)
|
||||||
|
if &first.run.Messages[0] != &second.run.Messages[0] || len(first.run.Messages) != 1 || second.run.Messages[1].Content != "reply" {
|
||||||
|
t.Fatal("growing histories did not share an unchanged prefix")
|
||||||
|
}
|
||||||
|
changed := preparedEvidence{run: pk.PreparedRun{Messages: []pk.RenderedMessage{{Role: "user", Content: "changed"}}}}
|
||||||
|
changed = changed.ShareMessages(second).(preparedEvidence)
|
||||||
|
if changed.run.Messages[0].Content != "changed" || first.run.Messages[0].Content != "first" {
|
||||||
|
t.Fatal("changed history corrupted an earlier snapshot")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPreparedEvidenceIsOptional(t *testing.T) {
|
||||||
|
runtime, _, _ := adapterFixture(t, []reply{{200, `{"corrections":[]}`}}, 0, 0, nil)
|
||||||
|
client, err := runtime.NewRoleClient("proposal", "base", runtime.Config.LLM, CallHooks{})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := adapterRequest("proposal")
|
||||||
|
req.CaptureDiagnostics = false
|
||||||
|
var out map[string]any
|
||||||
|
response, err := client.CompleteStructured(context.Background(), req, &out)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if response.Prepared != nil {
|
||||||
|
t.Fatal("prepared evidence retained without diagnostic capture")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestOperatorPromptUsesOwnContractAndOptionalSharedText(t *testing.T) {
|
func TestOperatorPromptUsesOwnContractAndOptionalSharedText(t *testing.T) {
|
||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -3,25 +3,13 @@ package processreport
|
|||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/core/reporting"
|
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||||
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
|
|
||||||
func mapLLMSummary(source llm.ExecutionSummary) reporting.LLMSummary {
|
|
||||||
metric := func(value llm.TokenCount) reporting.TokenMetric {
|
|
||||||
return reporting.TokenMetric{Value: value.Value, Known: value.Known, Complete: value.Complete}
|
|
||||||
}
|
|
||||||
return reporting.LLMSummary{
|
|
||||||
LogicalCalls: source.LogicalCalls, ProviderAttempts: source.ProviderAttempts,
|
|
||||||
TransientRetries: source.TransientRetries, StructuralRepairs: source.StructuralRepairs,
|
|
||||||
Usage: reporting.LLMUsage{Prompt: metric(source.Usage.Prompt), Completion: metric(source.Usage.Completion), Total: metric(source.Usage.Total), Cached: metric(source.Usage.Cached), CacheWrite: metric(source.Usage.CacheWrite)},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type executionCall struct {
|
type executionCall struct {
|
||||||
TerminalCoverageComplete bool `json:"terminal_coverage_complete"`
|
|
||||||
RequestedPromptID string `json:"requested_prompt_id,omitempty"`
|
RequestedPromptID string `json:"requested_prompt_id,omitempty"`
|
||||||
CallID uint64 `json:"call_id"`
|
CallID uint64 `json:"call_id"`
|
||||||
Context structuredoutput.DiagnosticContext `json:"context"`
|
Context structuredoutput.DiagnosticContext `json:"context"`
|
||||||
@@ -30,69 +18,36 @@ type executionCall struct {
|
|||||||
Finished *time.Time `json:"finished,omitempty"`
|
Finished *time.Time `json:"finished,omitempty"`
|
||||||
ElapsedMS int64 `json:"elapsed_ms"`
|
ElapsedMS int64 `json:"elapsed_ms"`
|
||||||
Failure structuredoutput.FailureKind `json:"failure,omitempty"`
|
Failure structuredoutput.FailureKind `json:"failure,omitempty"`
|
||||||
Summary reporting.LLMSummary `json:"summary"`
|
PromptKit pk.ExecutionGroupSummary `json:"promptkit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type executionEvent struct {
|
// BuildLLMExecution preserves native evidence with Audita's logical-call context.
|
||||||
CallID uint64 `json:"call_id"`
|
|
||||||
Context structuredoutput.DiagnosticContext `json:"context"`
|
|
||||||
Kind string `json:"kind"`
|
|
||||||
RunID string `json:"run_id,omitempty"`
|
|
||||||
Time time.Time `json:"time"`
|
|
||||||
BackendID string `json:"backend_id,omitempty"`
|
|
||||||
ProfileID string `json:"profile_id,omitempty"`
|
|
||||||
Model string `json:"model,omitempty"`
|
|
||||||
Generation *uint64 `json:"generation,omitempty"`
|
|
||||||
Attempt *uint64 `json:"attempt,omitempty"`
|
|
||||||
Dispatched bool `json:"dispatched"`
|
|
||||||
CapacityWaitMS int64 `json:"capacity_wait_ms"`
|
|
||||||
GenerationMS int64 `json:"generation_ms"`
|
|
||||||
RetryDelayMS int64 `json:"retry_delay_ms"`
|
|
||||||
DurationMS int64 `json:"duration_ms"`
|
|
||||||
Outcome string `json:"outcome,omitempty"`
|
|
||||||
Failure string `json:"failure,omitempty"`
|
|
||||||
StatusCode int `json:"status_code,omitempty"`
|
|
||||||
RetriesExhausted bool `json:"retries_exhausted,omitempty"`
|
|
||||||
Attempts uint64 `json:"attempts"`
|
|
||||||
TransientRetries uint64 `json:"transient_retries"`
|
|
||||||
StructuralRepairs uint64 `json:"structural_repairs"`
|
|
||||||
Usage reporting.LLMUsage `json:"usage"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildLLMExecution serializes only safe observation fields and millisecond durations.
|
|
||||||
func BuildLLMExecution(snapshot llm.ObservationSnapshot) any {
|
func BuildLLMExecution(snapshot llm.ObservationSnapshot) any {
|
||||||
calls := make([]executionCall, 0, len(snapshot.Calls))
|
calls := make([]executionCall, 0, len(snapshot.Calls))
|
||||||
events := make([]executionEvent, 0, len(snapshot.Events))
|
events := make([]llm.ExecutionObservation, len(snapshot.Events))
|
||||||
|
copy(events, snapshot.Events)
|
||||||
eventsByCall := make(map[uint64][]llm.ExecutionObservation, len(snapshot.Calls))
|
eventsByCall := make(map[uint64][]llm.ExecutionObservation, len(snapshot.Calls))
|
||||||
for _, event := range snapshot.Events {
|
for _, event := range events {
|
||||||
eventsByCall[event.CallID] = append(eventsByCall[event.CallID], event)
|
eventsByCall[event.CallID] = append(eventsByCall[event.CallID], event)
|
||||||
}
|
}
|
||||||
for _, call := range snapshot.Calls {
|
for _, call := range snapshot.Calls {
|
||||||
group := llm.ObservationSnapshot{Calls: []llm.LogicalCall{call}, Events: eventsByCall[call.CallID]}
|
group := llm.ObservationSnapshot{Calls: []llm.LogicalCall{call}, Events: eventsByCall[call.CallID]}
|
||||||
summary := llm.Summarize(group)
|
|
||||||
var finished *time.Time
|
var finished *time.Time
|
||||||
if !call.Finished.IsZero() {
|
if !call.Finished.IsZero() {
|
||||||
value := call.Finished
|
value := call.Finished
|
||||||
finished = &value
|
finished = &value
|
||||||
}
|
}
|
||||||
calls = append(calls, executionCall{TerminalCoverageComplete: summary.TerminalCoverageComplete, RequestedPromptID: call.RequestedPromptID, CallID: call.CallID, Context: call.Context, Prompt: call.Prompt, Started: call.Started, Finished: finished, ElapsedMS: call.WallDuration.Milliseconds(), Failure: call.Failure, Summary: mapLLMSummary(summary)})
|
calls = append(calls, executionCall{
|
||||||
}
|
RequestedPromptID: call.RequestedPromptID, CallID: call.CallID, Context: call.Context,
|
||||||
for _, event := range snapshot.Events {
|
Prompt: call.Prompt, Started: call.Started, Finished: finished,
|
||||||
var generation, attempt *uint64
|
ElapsedMS: call.WallDuration.Milliseconds(), Failure: call.Failure,
|
||||||
if event.Generation != 0 {
|
PromptKit: llm.Summarize(group).PromptKit,
|
||||||
value := event.Generation
|
})
|
||||||
generation = &value
|
|
||||||
}
|
|
||||||
if event.Attempt != 0 {
|
|
||||||
value := event.Attempt
|
|
||||||
attempt = &value
|
|
||||||
}
|
|
||||||
events = append(events, executionEvent{CallID: event.CallID, Context: event.Context, Kind: event.Kind, RunID: event.RunID, Time: event.Time, BackendID: event.BackendID, ProfileID: event.ProfileID, Model: event.Model, Generation: generation, Attempt: attempt, Dispatched: event.Dispatched, CapacityWaitMS: event.CapacityWait.Milliseconds(), GenerationMS: event.GenerationDuration.Milliseconds(), RetryDelayMS: event.RetryDelay.Milliseconds(), DurationMS: event.Duration.Milliseconds(), Outcome: event.Outcome, Failure: event.Failure, StatusCode: event.StatusCode, RetriesExhausted: event.RetriesExhausted, Attempts: event.Attempts, TransientRetries: event.TransientRetries, StructuralRepairs: event.StructuralRepairs, Usage: mapLLMSummary(llm.ExecutionSummary{Usage: event.Usage}).Usage})
|
|
||||||
}
|
}
|
||||||
return struct {
|
return struct {
|
||||||
Summary llm.ExecutionSummary `json:"summary"`
|
Summary llm.ExecutionSummary `json:"summary"`
|
||||||
Calls []executionCall `json:"calls"`
|
Calls []executionCall `json:"calls"`
|
||||||
Events []executionEvent `json:"events"`
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
}{llm.Summarize(snapshot), calls, events}
|
}{llm.Summarize(snapshot), calls, events}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/contracts"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/llm"
|
||||||
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/runner"
|
||||||
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
"gitea.maximumdirect.net/eric/audita/v4/internal/framework/structuredoutput"
|
||||||
pk "go.maximumdirect.net/promptkit"
|
pk "go.maximumdirect.net/promptkit"
|
||||||
)
|
)
|
||||||
@@ -19,14 +21,14 @@ func TestExecutionReportingKeepsSafeMilliseconds(t *testing.T) {
|
|||||||
{CallID: 1, Context: structuredoutput.DiagnosticContext{Role: "proposal", ModuleInstance: "grammar-1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "primary", ProfileID: "draft", Model: "m"}, Started: start, Finished: start.Add(1500 * time.Millisecond), WallDuration: 1500 * time.Millisecond},
|
{CallID: 1, Context: structuredoutput.DiagnosticContext{Role: "proposal", ModuleInstance: "grammar-1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "primary", ProfileID: "draft", Model: "m"}, Started: start, Finished: start.Add(1500 * time.Millisecond), WallDuration: 1500 * time.Millisecond},
|
||||||
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation"}, Prompt: structuredoutput.PromptMetadata{BackendID: "secondary"}, Started: start, Finished: start.Add(5 * time.Millisecond), WallDuration: 5 * time.Millisecond, Failure: structuredoutput.FailureRuntime},
|
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation"}, Prompt: structuredoutput.PromptMetadata{BackendID: "secondary"}, Started: start, Finished: start.Add(5 * time.Millisecond), WallDuration: 5 * time.Millisecond, Failure: structuredoutput.FailureRuntime},
|
||||||
},
|
},
|
||||||
Events: []llm.ExecutionObservation{{CallID: 1, RunID: "run-1", Kind: string(pk.ExecutionFinished), BackendID: "primary", Attempts: 2, TransientRetries: 1, CapacityWait: 20 * time.Millisecond, GenerationDuration: 500 * time.Millisecond, RetryDelay: 100 * time.Millisecond}},
|
Events: []llm.ExecutionObservation{{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "run-1", Kind: pk.ExecutionFinished, BackendID: "primary", Attempts: 2, TransientRetries: 1, CapacityWait: 20 * time.Millisecond, GenerationDuration: 500 * time.Millisecond, RetryDelay: 100 * time.Millisecond}}},
|
||||||
}
|
}
|
||||||
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
serialized := string(raw)
|
serialized := string(raw)
|
||||||
if !strings.Contains(serialized, `"elapsed_ms":1500`) || !strings.Contains(serialized, `"generation_ms":500`) || strings.Contains(serialized, "_ns") || strings.Contains(serialized, `"attempt":0`) || strings.Contains(serialized, `"section_index":0`) {
|
if !strings.Contains(serialized, `"elapsed_ms":1500`) || !strings.Contains(serialized, `"promptkit"`) || !strings.Contains(serialized, `"run-1"`) {
|
||||||
t.Fatalf("execution serialization: %s", serialized)
|
t.Fatalf("execution serialization: %s", serialized)
|
||||||
}
|
}
|
||||||
if !strings.Contains(serialized, `"calls"`) || !strings.Contains(serialized, `"events"`) {
|
if !strings.Contains(serialized, `"calls"`) || !strings.Contains(serialized, `"events"`) {
|
||||||
@@ -34,9 +36,37 @@ func TestExecutionReportingKeepsSafeMilliseconds(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestIndexedExecutionRetainsNativeEvidence(t *testing.T) {
|
||||||
|
section, proposal := 2, 1
|
||||||
|
ctx := structuredoutput.DiagnosticContext{ModuleInstance: "grammar", SectionIndex: §ion, ProposalIndex: &proposal}
|
||||||
|
event := pk.ExecutionEvent{RunID: "native", Kind: pk.ExecutionFinished,
|
||||||
|
Usage: pk.ObservedTokenUsage{ReasoningTokens: pk.ObservedTokenCount{Value: 3, Known: true, Complete: true}, CachedTokens: pk.ObservedTokenCount{Known: true, Complete: true}},
|
||||||
|
CostUSD: pk.ObservedCost{Value: 0.25, Known: true, Complete: true, Source: pk.CostSourceProvider}}
|
||||||
|
snapshot := llm.ObservationSnapshot{Calls: []llm.LogicalCall{{CallID: 1, Context: ctx}}, Events: []llm.ExecutionObservation{{CallID: 1, Context: ctx, PromptKit: event}}}
|
||||||
|
indexed := IndexLLMObservations(snapshot, []runner.WorkUnitOutcome{{ModuleInstance: "grammar", Section: contracts.SectionMetadata{Index: section}, ProposalIndexOffset: 4}})
|
||||||
|
if *indexed.Calls[0].Context.ProposalIndex != 5 || *indexed.Events[0].Context.ProposalIndex != 5 || indexed.Events[0].PromptKit != event {
|
||||||
|
t.Fatalf("indexed evidence = %+v", indexed)
|
||||||
|
}
|
||||||
|
raw, err := json.Marshal(BuildLLMExecution(indexed))
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var decoded struct {
|
||||||
|
Summary llm.ExecutionSummary `json:"summary"`
|
||||||
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
usage := decoded.Summary.PromptKit.Usage
|
||||||
|
if usage.ReasoningTokens.Value != 3 || !usage.ReasoningTokens.Known || !usage.CachedTokens.Known || usage.CachedTokens.Value != 0 || decoded.Summary.PromptKit.CostUSD != event.CostUSD || decoded.Events[0].PromptKit.RunID != "native" {
|
||||||
|
t.Fatalf("serialized native evidence = %+v", decoded)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestReportSummaryAvailability(t *testing.T) {
|
func TestReportSummaryAvailability(t *testing.T) {
|
||||||
got := mapLLMSummary(llm.Summarize(llm.ObservationSnapshot{}))
|
got := llm.Summarize(llm.ObservationSnapshot{})
|
||||||
if got.LogicalCalls != 0 || !got.Usage.Total.Known || !got.Usage.Total.Complete {
|
if got.LogicalCalls != 0 || !got.PromptKit.Usage.TotalTokens.Known || !got.PromptKit.Usage.TotalTokens.Complete {
|
||||||
t.Fatalf("initialized empty summary: %+v", got)
|
t.Fatalf("initialized empty summary: %+v", got)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,7 +76,7 @@ func BenchmarkExecutionReports(b *testing.B) {
|
|||||||
snapshot := llm.ObservationSnapshot{}
|
snapshot := llm.ObservationSnapshot{}
|
||||||
for i := 0; i < n; i++ {
|
for i := 0; i < n; i++ {
|
||||||
snapshot.Calls = append(snapshot.Calls, llm.LogicalCall{CallID: uint64(i + 1), Prompt: structuredoutput.PromptMetadata{BackendID: "local"}, Context: structuredoutput.DiagnosticContext{ModuleInstance: "grammar", Role: "proposal"}})
|
snapshot.Calls = append(snapshot.Calls, llm.LogicalCall{CallID: uint64(i + 1), Prompt: structuredoutput.PromptMetadata{BackendID: "local"}, Context: structuredoutput.DiagnosticContext{ModuleInstance: "grammar", Role: "proposal"}})
|
||||||
snapshot.Events = append(snapshot.Events, llm.ExecutionObservation{RunID: fmt.Sprint(i), CallID: uint64(i + 1), Kind: string(pk.ExecutionFinished), Attempts: 1})
|
snapshot.Events = append(snapshot.Events, llm.ExecutionObservation{CallID: uint64(i + 1), PromptKit: pk.ExecutionEvent{RunID: fmt.Sprint(i), Kind: pk.ExecutionFinished, Attempts: 1}})
|
||||||
}
|
}
|
||||||
b.Run(fmt.Sprintf("execution/%d", n), func(b *testing.B) {
|
b.Run(fmt.Sprintf("execution/%d", n), func(b *testing.B) {
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
@@ -64,9 +94,9 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation", ModuleInstance: "grammar_1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "a"}},
|
{CallID: 2, Context: structuredoutput.DiagnosticContext{Role: "validation", ModuleInstance: "grammar_1"}, Prompt: structuredoutput.PromptMetadata{BackendID: "a"}},
|
||||||
},
|
},
|
||||||
Events: []llm.ExecutionObservation{
|
Events: []llm.ExecutionObservation{
|
||||||
{CallID: 1, RunID: "run-1", Kind: string(pk.ExecutionFinished), Attempts: 1, Usage: llm.Usage{Total: llm.TokenCount{Value: 7, Known: true, Complete: true}}},
|
{CallID: 1, PromptKit: pk.ExecutionEvent{RunID: "run-1", Kind: pk.ExecutionFinished, Attempts: 1, Usage: pk.ObservedTokenUsage{TotalTokens: pk.ObservedTokenCount{Value: 7, Known: true, Complete: true}}}},
|
||||||
{CallID: 3, RunID: "run-3", Kind: string(pk.ExecutionFinished), Attempts: 1},
|
{CallID: 3, PromptKit: pk.ExecutionEvent{RunID: "run-3", Kind: pk.ExecutionFinished, Attempts: 1}},
|
||||||
{CallID: 2, RunID: "run-2", Kind: string(pk.ExecutionFinished), Attempts: 1},
|
{CallID: 2, PromptKit: pk.ExecutionEvent{RunID: "run-2", Kind: pk.ExecutionFinished, Attempts: 1}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
raw, err := json.Marshal(BuildLLMExecution(snapshot))
|
||||||
@@ -75,7 +105,7 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var execution struct {
|
var execution struct {
|
||||||
Calls []executionCall `json:"calls"`
|
Calls []executionCall `json:"calls"`
|
||||||
Events []executionEvent `json:"events"`
|
Events []llm.ExecutionObservation `json:"events"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(raw, &execution); err != nil {
|
if err := json.Unmarshal(raw, &execution); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -90,7 +120,7 @@ func TestIndexedReportsPreserveOrderAndPartialUsage(t *testing.T) {
|
|||||||
t.Fatal("event order changed")
|
t.Fatal("event order changed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if execution.Calls[1].Summary.Usage.Total.Value != 7 || !execution.Calls[1].Summary.Usage.Total.Complete || execution.Calls[0].Summary.Usage.Total.Known {
|
if execution.Calls[1].PromptKit.Usage.TotalTokens.Value != 7 || !execution.Calls[1].PromptKit.Usage.TotalTokens.Complete || execution.Calls[0].PromptKit.Usage.TotalTokens.Known {
|
||||||
t.Fatalf("call usage: %+v", execution.Calls)
|
t.Fatalf("call usage: %+v", execution.Calls)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ func (s *sectionInteractions) write(offset int) {
|
|||||||
// Earlier snapshots keep their own lengths while additional turns add messages.
|
// Earlier snapshots keep their own lengths while additional turns add messages.
|
||||||
type repairHistory struct {
|
type repairHistory struct {
|
||||||
messages []structuredoutput.Message
|
messages []structuredoutput.Message
|
||||||
|
native any
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *structuredoutput.PreparedSnapshot {
|
func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *structuredoutput.PreparedSnapshot {
|
||||||
@@ -55,6 +56,10 @@ func (h *repairHistory) retain(prepared *structuredoutput.PreparedSnapshot) *str
|
|||||||
}
|
}
|
||||||
snapshot := *prepared
|
snapshot := *prepared
|
||||||
snapshot.Messages = slices.Clip(h.messages)
|
snapshot.Messages = slices.Clip(h.messages)
|
||||||
|
if shareable, ok := prepared.PromptKit.(interface{ ShareMessages(any) any }); ok {
|
||||||
|
snapshot.PromptKit = shareable.ShareMessages(h.native)
|
||||||
|
}
|
||||||
|
h.native = snapshot.PromptKit
|
||||||
return &snapshot
|
return &snapshot
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -260,7 +260,22 @@ func TestLaterRepairArtifactsUseOrderedProposalIndices(t *testing.T) {
|
|||||||
}
|
}
|
||||||
var request structuredoutput.PreparedSnapshot
|
var request structuredoutput.PreparedSnapshot
|
||||||
readInteraction(t, attempt.Artifacts.RequestPayloadPath, &request)
|
readInteraction(t, attempt.Artifacts.RequestPayloadPath, &request)
|
||||||
if !reflect.DeepEqual(&request, captured[i]) {
|
want, err := json.Marshal(captured[i])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
got, err := json.Marshal(&request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var gotValue, wantValue any
|
||||||
|
if err := json.Unmarshal(got, &gotValue); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(want, &wantValue); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !reflect.DeepEqual(gotValue, wantValue) {
|
||||||
t.Fatalf("request %d did not preserve prepared evidence", i+1)
|
t.Fatalf("request %d did not preserve prepared evidence", i+1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,6 +60,7 @@ type Response struct {
|
|||||||
// PreparedSnapshot is the exact rendered request snapshot. Its messages may
|
// PreparedSnapshot is the exact rendered request snapshot. Its messages may
|
||||||
// contain transcript and glossary content and belong only in protected diagnostics.
|
// contain transcript and glossary content and belong only in protected diagnostics.
|
||||||
type PreparedSnapshot struct {
|
type PreparedSnapshot struct {
|
||||||
|
PromptKit any `json:"promptkit,omitempty"`
|
||||||
Messages []Message `json:"messages"`
|
Messages []Message `json:"messages"`
|
||||||
Prompt PromptMetadata `json:"prompt"`
|
Prompt PromptMetadata `json:"prompt"`
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user