Capture evidence for core-owned operations
This commit is contained in:
@@ -267,8 +267,7 @@ permissive behavior is neither widened nor removed.
|
|||||||
## Stage 4 — Move Native Evaluation And Continuation Into The Executor
|
## Stage 4 — Move Native Evaluation And Continuation Into The Executor
|
||||||
|
|
||||||
**Status:** Complete. Existing integrations still use the previous producer
|
**Status:** Complete. Existing integrations still use the previous producer
|
||||||
entry point until their scheduled migrations; capture binding for the new entry
|
entry point until their scheduled migrations.
|
||||||
point remains assigned to the next work.
|
|
||||||
|
|
||||||
**Goal:** Own model production and replace coupled outer candidate variables.
|
**Goal:** Own model production and replace coupled outer candidate variables.
|
||||||
|
|
||||||
@@ -331,6 +330,8 @@ the selected cache contract, adding dimensions, or persisting evaluation metadat
|
|||||||
|
|
||||||
## Stage 6 — Attach Evidence And Observation To Core-Owned Operations
|
## Stage 6 — Attach Evidence And Observation To Core-Owned Operations
|
||||||
|
|
||||||
|
**Status:** Complete.
|
||||||
|
|
||||||
**Goal:** Keep standard evidence out of integration lifecycle code.
|
**Goal:** Keep standard evidence out of integration lifecycle code.
|
||||||
|
|
||||||
**Inspect:** `pipeline/{native_capture,operation_capture,producer}.go`,
|
**Inspect:** `pipeline/{native_capture,operation_capture,producer}.go`,
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ type OperationResult[T any] struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ExecuteOperation invokes preparation once and executes its selected form.
|
// ExecuteOperation invokes preparation once and executes its selected form.
|
||||||
func ExecuteOperation[T any](ctx context.Context, execution ExecutionContext[T], prepare contracts.Preparation[T]) (OperationResult[T], error) {
|
func ExecuteOperation[T any](ctx context.Context, execution ExecutionContext[T], prepare contracts.Preparation[T]) (result OperationResult[T], failure error) {
|
||||||
var empty OperationResult[T]
|
var empty OperationResult[T]
|
||||||
if ctx == nil {
|
if ctx == nil {
|
||||||
return empty, errors.New("operation context must not be nil")
|
return empty, errors.New("operation context must not be nil")
|
||||||
@@ -42,6 +42,18 @@ func ExecuteOperation[T any](ctx context.Context, execution ExecutionContext[T],
|
|||||||
if prepare == nil {
|
if prepare == nil {
|
||||||
return empty, errors.New("operation preparation must be supplied")
|
return empty, errors.New("operation preparation must be supplied")
|
||||||
}
|
}
|
||||||
|
if execution.Execution.Capture != nil {
|
||||||
|
defer func() {
|
||||||
|
errorText := ""
|
||||||
|
if failure != nil {
|
||||||
|
errorText = failure.Error()
|
||||||
|
}
|
||||||
|
if err := execution.Execution.RecordEvidence("operation-terminal.json", map[string]any{"outcome": result.Outcome, "error": errorText}); err != nil {
|
||||||
|
result = empty
|
||||||
|
failure = errors.Join(failure, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
operation, err := prepare(ctx)
|
operation, err := prepare(ctx)
|
||||||
if canceled := ctx.Err(); canceled != nil {
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
return empty, canceled
|
return empty, canceled
|
||||||
@@ -49,6 +61,11 @@ func ExecuteOperation[T any](ctx context.Context, execution ExecutionContext[T],
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return empty, err
|
return empty, err
|
||||||
}
|
}
|
||||||
|
if execution.Execution.Capture != nil {
|
||||||
|
if err := execution.Execution.RecordEvidence("operation-preparation.json", map[string]any{"operation": fmt.Sprintf("%T", operation)}); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
|
}
|
||||||
switch prepared := operation.(type) {
|
switch prepared := operation.(type) {
|
||||||
case contracts.DeterministicOperation[T]:
|
case contracts.DeterministicOperation[T]:
|
||||||
return executeDeterministic(ctx, execution, prepared)
|
return executeDeterministic(ctx, execution, prepared)
|
||||||
@@ -58,11 +75,17 @@ func ExecuteOperation[T any](ctx context.Context, execution ExecutionContext[T],
|
|||||||
}
|
}
|
||||||
return executeDeterministic(ctx, execution, *prepared)
|
return executeDeterministic(ctx, execution, *prepared)
|
||||||
case contracts.PreparationLimit[T]:
|
case contracts.PreparationLimit[T]:
|
||||||
|
if err := recordDomainEvidence(execution.Execution, "preparation-domain.json", prepared.Evidence); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
return finishOperation(ctx, execution.Controls.Mode, prepared.Cause, nil, contracts.CandidateAssessment{}, prepared.Fallback, prepared.Diagnostics)
|
return finishOperation(ctx, execution.Controls.Mode, prepared.Cause, nil, contracts.CandidateAssessment{}, prepared.Fallback, prepared.Diagnostics)
|
||||||
case *contracts.PreparationLimit[T]:
|
case *contracts.PreparationLimit[T]:
|
||||||
if prepared == nil {
|
if prepared == nil {
|
||||||
return empty, errors.New("preparation limit must not be nil")
|
return empty, errors.New("preparation limit must not be nil")
|
||||||
}
|
}
|
||||||
|
if err := recordDomainEvidence(execution.Execution, "preparation-domain.json", prepared.Evidence); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
return finishOperation(ctx, execution.Controls.Mode, prepared.Cause, nil, contracts.CandidateAssessment{}, prepared.Fallback, prepared.Diagnostics)
|
return finishOperation(ctx, execution.Controls.Mode, prepared.Cause, nil, contracts.CandidateAssessment{}, prepared.Fallback, prepared.Diagnostics)
|
||||||
case contracts.NativeOperation[T]:
|
case contracts.NativeOperation[T]:
|
||||||
return executeNative(ctx, execution, prepared)
|
return executeNative(ctx, execution, prepared)
|
||||||
@@ -86,6 +109,11 @@ func executeDeterministic[T any](ctx context.Context, execution ExecutionContext
|
|||||||
}
|
}
|
||||||
view := operation.Evaluation.View()
|
view := operation.Evaluation.View()
|
||||||
assessment, err := execution.Assess(ctx, *view.Candidate)
|
assessment, err := execution.Assess(ctx, *view.Candidate)
|
||||||
|
if execution.Execution.Capture != nil {
|
||||||
|
if captureErr := captureEvaluation(execution.Execution, "deterministic", operation.Evaluation, assessment, view.Guidance, err == nil && assessment.Accepted() && len(view.Guidance) == 0, err); captureErr != nil {
|
||||||
|
return empty, errors.Join(ctx.Err(), err, captureErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
if canceled := ctx.Err(); canceled != nil {
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
return empty, canceled
|
return empty, canceled
|
||||||
}
|
}
|
||||||
@@ -99,6 +127,41 @@ func executeDeterministic[T any](ctx context.Context, execution ExecutionContext
|
|||||||
return completeOperation(*view.Candidate, operation.Evaluation, assessment, outcome, operation.Diagnostics)
|
return completeOperation(*view.Candidate, operation.Evaluation, assessment, outcome, operation.Diagnostics)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// recordDomainEvidence invokes optional domain projections only when capture
|
||||||
|
// is enabled. Projection and writing failures are required-capture failures.
|
||||||
|
func recordDomainEvidence(execution contracts.ExecutionOptions, name string, project func() (any, error)) error {
|
||||||
|
if execution.Capture == nil || project == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
value, err := project()
|
||||||
|
if err != nil {
|
||||||
|
return &contracts.CaptureError{Cause: err}
|
||||||
|
}
|
||||||
|
return execution.RecordEvidence(name, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
func captureEvaluation[T any](execution contracts.ExecutionOptions, id string, evaluation contracts.Evaluation[T], assessment contracts.CandidateAssessment, guidance []string, accepted bool, failure error) error {
|
||||||
|
if execution.Capture == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var candidate bool
|
||||||
|
if evaluation != nil {
|
||||||
|
view := evaluation.View()
|
||||||
|
candidate = view.Candidate != nil
|
||||||
|
if err := recordDomainEvidence(execution, "interpretations/"+id+"-domain.json", view.Evidence); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
errorText := ""
|
||||||
|
if failure != nil {
|
||||||
|
errorText = failure.Error()
|
||||||
|
}
|
||||||
|
return execution.RecordEvidence("interpretations/"+id+".json", map[string]any{
|
||||||
|
"usable_candidate": candidate, "accepted": accepted, "correction_guidance": guidance,
|
||||||
|
"assessment": assessmentEvidence(assessment), "error": errorText,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func finishOperation[T any](ctx context.Context, mode contracts.ExecutionMode, cause error, evaluation contracts.Evaluation[T], assessment contracts.CandidateAssessment, fallback contracts.Fallback[T], diagnostics contracts.TerminalDiagnostics[T]) (OperationResult[T], error) {
|
func finishOperation[T any](ctx context.Context, mode contracts.ExecutionMode, cause error, evaluation contracts.Evaluation[T], assessment contracts.CandidateAssessment, fallback contracts.Fallback[T], diagnostics contracts.TerminalDiagnostics[T]) (OperationResult[T], error) {
|
||||||
var construct func(context.Context) (T, error)
|
var construct func(context.Context) (T, error)
|
||||||
if fallback != nil {
|
if fallback != nil {
|
||||||
|
|||||||
@@ -25,10 +25,20 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
if execution.Controls.MaxAdditionalTurns < 0 {
|
if execution.Controls.MaxAdditionalTurns < 0 {
|
||||||
return empty, fmt.Errorf("%w: additional turns must not be negative", promptkit.ErrInvalidRequest)
|
return empty, fmt.Errorf("%w: additional turns must not be negative", promptkit.ErrInvalidRequest)
|
||||||
}
|
}
|
||||||
|
if err := recordDomainEvidence(execution.Execution, "preparation-domain.json", operation.Evidence); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
var current nativeEvaluation[T]
|
var current nativeEvaluation[T]
|
||||||
var fatal error
|
var fatal error
|
||||||
evaluate := func(result *promptkit.RunResult) {
|
evaluate := func(result *promptkit.RunResult) {
|
||||||
current = nativeEvaluation[T]{}
|
current = nativeEvaluation[T]{}
|
||||||
|
if execution.Execution.Capture != nil && result != nil {
|
||||||
|
defer func() {
|
||||||
|
if err := captureEvaluation(execution.Execution, result.RunID, current.evaluation, current.assessment, current.guidance, current.accepted, errors.Join(current.failure, fatal)); err != nil {
|
||||||
|
fatal = errors.Join(fatal, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
if err := CheckNativeResult(result, nil); err != nil {
|
if err := CheckNativeResult(result, nil); err != nil {
|
||||||
current.failure = err
|
current.failure = err
|
||||||
return
|
return
|
||||||
@@ -82,16 +92,41 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
|
|
||||||
request := producerRequest(operation.Initial, execution.Execution)
|
request := producerRequest(operation.Initial, execution.Execution)
|
||||||
request.CaptureExchange = request.CaptureExchange || (operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0)
|
request.CaptureExchange = request.CaptureExchange || (operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0)
|
||||||
|
request, capture := CaptureNativeRequest(request, scopeEvidence(execution.Execution.Capture, "initial"))
|
||||||
|
if err := capture.Err(); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
var result *promptkit.RunResult
|
var result *promptkit.RunResult
|
||||||
var err error
|
var err error
|
||||||
var cacheKey string
|
var cacheKey string
|
||||||
cache := execution.Cache
|
cache := execution.Cache
|
||||||
|
if execution.Execution.Capture != nil {
|
||||||
|
if err := execution.Execution.RecordEvidence("cache/selection.json", map[string]any{"mode": execution.Controls.Cache, "reuse_eligible": execution.ReuseEligible, "store_available": cache != nil && cache.Store != nil}); err != nil {
|
||||||
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||||
|
}
|
||||||
|
if cache != nil {
|
||||||
|
copy := *cache
|
||||||
|
existing := copy.Observe
|
||||||
|
copy.Observe = func(ctx context.Context, observation contracts.CacheObservation) error {
|
||||||
|
if err := captureCacheObservation(execution.Execution.Capture, observation); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if existing != nil {
|
||||||
|
return existing(ctx, observation)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cache = ©
|
||||||
|
}
|
||||||
|
}
|
||||||
if cache != nil && cache.Store != nil && execution.ReuseEligible && execution.Controls.Cache != contracts.CacheBypass {
|
if cache != nil && cache.Store != nil && execution.ReuseEligible && execution.Controls.Cache != contracts.CacheBypass {
|
||||||
if cache.Encode == nil || cache.Decode == nil {
|
if cache.Encode == nil || cache.Decode == nil {
|
||||||
return empty, errors.New("producer cache codec must be supplied")
|
err := errors.New("producer cache codec must be supplied")
|
||||||
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||||
}
|
}
|
||||||
if mode := execution.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh {
|
if mode := execution.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh {
|
||||||
return empty, fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode)
|
err := fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode)
|
||||||
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||||
}
|
}
|
||||||
var prepared *promptkit.PreparedExecution
|
var prepared *promptkit.PreparedExecution
|
||||||
prepared, err = execution.Engine.PrepareExecution(ctx, request)
|
prepared, err = execution.Engine.PrepareExecution(ctx, request)
|
||||||
@@ -99,14 +134,20 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
defer prepared.Discard()
|
defer prepared.Discard()
|
||||||
details := prepared.Details()
|
details := prepared.Details()
|
||||||
cacheKey = details.MessageContentHash
|
cacheKey = details.MessageContentHash
|
||||||
|
if capture != nil {
|
||||||
|
capture.RetainPrepared(copyPreparedEvidence(details))
|
||||||
|
}
|
||||||
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); err != nil {
|
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); err != nil {
|
||||||
return empty, err
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||||
}
|
}
|
||||||
reused, lookupErr := lookupProducerCache(ctx, cache, execution.Controls.Cache, cacheKey)
|
reused, lookupErr := lookupProducerCache(ctx, cache, execution.Controls.Cache, cacheKey)
|
||||||
if lookupErr != nil {
|
if lookupErr != nil {
|
||||||
return empty, lookupErr
|
return empty, captureFailure(lookupErr, capture.Finish(nil, lookupErr, false, false))
|
||||||
}
|
}
|
||||||
if reused != nil {
|
if reused != nil {
|
||||||
|
if err := capture.Finish(nil, nil, false, true); err != nil {
|
||||||
|
return empty, err
|
||||||
|
}
|
||||||
return OperationResult[T]{Value: *reused, Outcome: contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}}, nil
|
return OperationResult[T]{Value: *reused, Outcome: contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}}, nil
|
||||||
}
|
}
|
||||||
result, err = execution.Engine.RunPrepared(ctx, prepared)
|
result, err = execution.Engine.RunPrepared(ctx, prepared)
|
||||||
@@ -118,11 +159,14 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
decision = "ineligible"
|
decision = "ineligible"
|
||||||
}
|
}
|
||||||
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil {
|
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil {
|
||||||
return empty, err
|
return empty, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
result, err = execution.Engine.Run(ctx, request)
|
result, err = execution.Engine.Run(ctx, request)
|
||||||
}
|
}
|
||||||
|
if captureErr := capture.Finish(result, err, ctx.Err() != nil, false); captureErr != nil {
|
||||||
|
return empty, captureFailure(errors.Join(ctx.Err(), err), captureErr)
|
||||||
|
}
|
||||||
if canceled := ctx.Err(); canceled != nil {
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
return empty, canceled
|
return empty, canceled
|
||||||
}
|
}
|
||||||
@@ -139,10 +183,17 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
return empty, fatal
|
return empty, fatal
|
||||||
}
|
}
|
||||||
if !current.accepted && err == nil && len(current.guidance) > 0 && operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0 {
|
if !current.accepted && err == nil && len(current.guidance) > 0 && operation.Correction != nil && execution.Controls.MaxAdditionalTurns > 0 {
|
||||||
|
var pendingCapture *NativeCapture
|
||||||
|
var recordingErr error
|
||||||
coordination, coordinateErr := execution.Engine.Coordinate(ctx, promptkit.CoordinateRequest{
|
coordination, coordinateErr := execution.Engine.Coordinate(ctx, promptkit.CoordinateRequest{
|
||||||
Start: result.Exchange, AdditionalTurns: execution.Controls.MaxAdditionalTurns,
|
Start: result.Exchange, AdditionalTurns: execution.Controls.MaxAdditionalTurns,
|
||||||
Next: func(_ context.Context, turn promptkit.ConversationTurn) (*promptkit.RunRequest, error) {
|
Next: func(_ context.Context, turn promptkit.ConversationTurn) (*promptkit.RunRequest, error) {
|
||||||
if turn.Result != nil {
|
if turn.Result != nil {
|
||||||
|
recordingErr = pendingCapture.Finish(turn.Result, nil, false, false)
|
||||||
|
pendingCapture = nil
|
||||||
|
if recordingErr != nil {
|
||||||
|
return nil, recordingErr
|
||||||
|
}
|
||||||
evaluate(turn.Result)
|
evaluate(turn.Result)
|
||||||
}
|
}
|
||||||
if fatal != nil {
|
if fatal != nil {
|
||||||
@@ -155,8 +206,18 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
// Selecting another execution invalidates the entire previous
|
// Selecting another execution invalidates the entire previous
|
||||||
// evaluation before even attempting to construct its request.
|
// evaluation before even attempting to construct its request.
|
||||||
current = nativeEvaluation[T]{}
|
current = nativeEvaluation[T]{}
|
||||||
|
correctionPath := ""
|
||||||
|
if execution.Execution.Capture != nil {
|
||||||
|
correctionPath = "corrections/" + turn.Exchange.Details().RunID
|
||||||
|
if recordingErr = execution.Execution.RecordEvidence(correctionPath+"/assignment.json", map[string]any{"guidance": guidance}); recordingErr != nil {
|
||||||
|
return nil, recordingErr
|
||||||
|
}
|
||||||
|
}
|
||||||
next, err := operation.Correction(ctx, guidance)
|
next, err := operation.Correction(ctx, guidance)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if correctionPath != "" {
|
||||||
|
recordingErr = execution.Execution.RecordEvidence(correctionPath+"/construction-failure.json", map[string]any{"error": err.Error()})
|
||||||
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if operation.Initial.ProfileID != "" {
|
if operation.Initial.ProfileID != "" {
|
||||||
@@ -166,9 +227,21 @@ func executeNative[T any](ctx context.Context, execution ExecutionContext[T], op
|
|||||||
next.SessionID = operation.Initial.SessionID
|
next.SessionID = operation.Initial.SessionID
|
||||||
}
|
}
|
||||||
next = producerRequest(next, execution.Execution)
|
next = producerRequest(next, execution.Execution)
|
||||||
|
if correctionPath != "" {
|
||||||
|
next, pendingCapture = CaptureNativeRequest(next, scopeEvidence(execution.Execution.Capture, correctionPath))
|
||||||
|
if recordingErr = pendingCapture.Err(); recordingErr != nil {
|
||||||
|
return nil, recordingErr
|
||||||
|
}
|
||||||
|
}
|
||||||
return &next, nil
|
return &next, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
if pendingCapture != nil {
|
||||||
|
recordingErr = errors.Join(recordingErr, pendingCapture.Finish(coordination.Undelivered, coordinateErr, coordination.Undelivered != nil, false))
|
||||||
|
}
|
||||||
|
if recordingErr != nil {
|
||||||
|
return empty, captureFailure(errors.Join(ctx.Err(), coordinateErr), recordingErr)
|
||||||
|
}
|
||||||
if canceled := ctx.Err(); canceled != nil {
|
if canceled := ctx.Err(); canceled != nil {
|
||||||
return empty, canceled
|
return empty, canceled
|
||||||
}
|
}
|
||||||
|
|||||||
209
internal/framework/pipeline/prepared_operation_capture_test.go
Normal file
209
internal/framework/pipeline/prepared_operation_capture_test.go
Normal file
@@ -0,0 +1,209 @@
|
|||||||
|
package pipeline
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||||
|
"go.maximumdirect.net/promptkit"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestNativeCaptureOperationKeepsHistoryAndObservesActualExecutions(t *testing.T) {
|
||||||
|
evidence := &nativeEvidence{}
|
||||||
|
var group promptkit.ExecutionGroup
|
||||||
|
providerCalls, prepared, projections := 0, 0, 0
|
||||||
|
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||||
|
providerCalls++
|
||||||
|
return &promptkit.GenerateResponse{Content: fmt.Sprintf(`{"value":%d}`, providerCalls-1)}, nil
|
||||||
|
}))
|
||||||
|
ctx := promptkit.WithExecutionObserver(context.Background(), group.Observe)
|
||||||
|
result, err := ExecuteOperation(ctx, ExecutionContext[int]{Engine: engine, Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1},
|
||||||
|
Execution: contracts.ExecutionOptions{Capture: evidence, OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared++ }},
|
||||||
|
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||||
|
if value == 1 {
|
||||||
|
return acceptedProducerAssessment(ctx, value)
|
||||||
|
}
|
||||||
|
return rejectedProducerAssessment(ctx, value)
|
||||||
|
}}, func(context.Context) (contracts.PreparedOperation[int], error) {
|
||||||
|
return contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Correction: producerCorrection,
|
||||||
|
Evidence: func() (any, error) { projections++; return "fixed preparation", nil },
|
||||||
|
Interpret: func(ctx context.Context, native *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||||
|
candidate, _, err := interpretProducerNumber(ctx, native)
|
||||||
|
value := *candidate
|
||||||
|
return contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: candidate, Evidence: func() (any, error) { projections++; return value, nil }}}, err
|
||||||
|
}}, nil
|
||||||
|
})
|
||||||
|
summary := group.Snapshot()
|
||||||
|
if err != nil || result.Value != 1 || providerCalls != 2 || prepared != 2 || projections != 3 || len(summary.Members) != 2 || !summary.TerminalCoverageComplete {
|
||||||
|
t.Fatalf("result=%#v err=%v calls=%d prepared=%d projections=%d summary=%#v", result, err, providerCalls, prepared, projections, summary)
|
||||||
|
}
|
||||||
|
if nativeEvidenceCount(evidence, "/result.json") != 2 || nativeEvidenceCount(evidence, "-domain.json") != 3 || nativeEvidenceCount(evidence, "/assignment.json") != 1 {
|
||||||
|
t.Fatalf("native evidence missing: %v", evidence.files)
|
||||||
|
}
|
||||||
|
if _, ok := evidence.files["operation-terminal.json"]; !ok {
|
||||||
|
t.Fatal("terminal evidence missing")
|
||||||
|
}
|
||||||
|
if _, ok := evidence.files["preparation-domain.json"]; !ok {
|
||||||
|
t.Fatal("preparation evidence missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEvidenceOperationIsLazyAndRequiredWhenEnabled(t *testing.T) {
|
||||||
|
for _, enabled := range []bool{false, true} {
|
||||||
|
cause := errors.New("evidence projection failed")
|
||||||
|
candidate, projections, assessed, fallback := 1, 0, 0, 0
|
||||||
|
var writer contracts.EvidenceWriter
|
||||||
|
if enabled {
|
||||||
|
writer = &nativeEvidence{}
|
||||||
|
}
|
||||||
|
result, err := ExecuteOperation(context.Background(), ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Execution: contracts.ExecutionOptions{Capture: writer},
|
||||||
|
Assess: func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||||
|
assessed++
|
||||||
|
return contracts.CandidateAssessment{}, nil
|
||||||
|
}},
|
||||||
|
func(context.Context) (contracts.PreparedOperation[int], error) {
|
||||||
|
return contracts.DeterministicOperation[int]{Evaluation: contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: &candidate,
|
||||||
|
Evidence: func() (any, error) { projections++; return nil, cause }}},
|
||||||
|
Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallback++; return 0, nil }}, nil
|
||||||
|
})
|
||||||
|
if enabled {
|
||||||
|
var captureErr *contracts.CaptureError
|
||||||
|
if !errors.Is(err, cause) || !errors.As(err, &captureErr) || projections != 1 || result.Outcome.Disposition != "" {
|
||||||
|
t.Fatalf("enabled evidence=%#v %v projections=%d", result, err, projections)
|
||||||
|
}
|
||||||
|
} else if err != nil || result.Value != 1 || projections != 0 {
|
||||||
|
t.Fatalf("disabled evidence=%#v %v projections=%d", result, err, projections)
|
||||||
|
}
|
||||||
|
if assessed != 1 || fallback != 0 {
|
||||||
|
t.Fatalf("assessed=%d fallback=%d", assessed, fallback)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeCaptureOperationCacheHitDoesNotInventExecution(t *testing.T) {
|
||||||
|
_, store := filesystemProducerCache(t)
|
||||||
|
evidence := &nativeEvidence{}
|
||||||
|
calls := 0
|
||||||
|
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||||
|
calls++
|
||||||
|
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
|
||||||
|
}))
|
||||||
|
bound := numberCacheOperation(store)
|
||||||
|
var group promptkit.ExecutionGroup
|
||||||
|
ctx := promptkit.WithExecutionObserver(context.Background(), group.Observe)
|
||||||
|
execution := ExecutionContext[int]{Engine: engine, Controls: bound.Controls, ReuseEligible: true, Cache: bound.Cache, Assess: acceptedProducerAssessment}
|
||||||
|
if _, err := ExecuteOperation(ctx, execution, cacheableNumberOperation(nativeProducerInitial())); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
execution.Execution.Capture = evidence
|
||||||
|
execution.Assess = func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||||
|
t.Fatal("cache hit assessed")
|
||||||
|
return contracts.CandidateAssessment{}, nil
|
||||||
|
}
|
||||||
|
result, err := ExecuteOperation(ctx, execution, cacheableNumberOperation(nativeProducerInitial()))
|
||||||
|
if err != nil || result.Value != 1 || calls != 1 || len(group.Snapshot().Members) != 1 || nativeEvidenceCount(evidence, "/result.json") != 0 {
|
||||||
|
t.Fatalf("hit=%#v err=%v calls=%d", result, err, calls)
|
||||||
|
}
|
||||||
|
if _, ok := evidence.files["cache/hit.json"]; !ok {
|
||||||
|
t.Fatal("cache-hit evidence missing")
|
||||||
|
}
|
||||||
|
if _, ok := evidence.files["initial/unexecuted/prepared.json"]; !ok {
|
||||||
|
t.Fatal("prepared cache evidence missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeCaptureOperationPreservesFailureAndNeverFallsBack(t *testing.T) {
|
||||||
|
providerErr := errors.New("provider failure")
|
||||||
|
captureErr := errors.New("recording failure")
|
||||||
|
evidence := &nativeEvidence{fail: func(name string) error {
|
||||||
|
if strings.HasSuffix(name, "/availability.json") {
|
||||||
|
return captureErr
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||||
|
return nil, providerErr
|
||||||
|
}))
|
||||||
|
fallbacks := 0
|
||||||
|
result, err := ExecuteOperation(context.Background(), ExecutionContext[int]{Engine: engine, Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Execution: contracts.ExecutionOptions{Capture: evidence}, Assess: acceptedProducerAssessment},
|
||||||
|
func(ctx context.Context) (contracts.PreparedOperation[int], error) {
|
||||||
|
prepared, err := cacheableNumberOperation(nativeProducerInitial())(ctx)
|
||||||
|
operation := prepared.(contracts.NativeOperation[int])
|
||||||
|
operation.Fallback = func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return 0, nil }
|
||||||
|
return operation, err
|
||||||
|
})
|
||||||
|
var captured *contracts.CaptureError
|
||||||
|
if !errors.Is(err, providerErr) || !errors.Is(err, captureErr) || !errors.As(err, &captured) || result.Outcome.Disposition != "" || fallbacks != 0 {
|
||||||
|
t.Fatalf("result=%#v err=%v fallback=%d", result, err, fallbacks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeCaptureOperationUndeliveredResponseIsNotAssessed(t *testing.T) {
|
||||||
|
evidence := &nativeEvidence{}
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
defer cancel()
|
||||||
|
finished, assessments, fallbacks := 0, 0, 0
|
||||||
|
ctx = promptkit.WithExecutionObserver(ctx, func(event promptkit.ExecutionEvent) {
|
||||||
|
if event.Kind == promptkit.ExecutionFinished {
|
||||||
|
finished++
|
||||||
|
if finished == 2 {
|
||||||
|
cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||||
|
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||||
|
}))
|
||||||
|
result, err := ExecuteOperation(ctx, ExecutionContext[int]{Engine: engine, Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 1}, Execution: contracts.ExecutionOptions{Capture: evidence},
|
||||||
|
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||||
|
assessments++
|
||||||
|
return rejectedProducerAssessment(ctx, value)
|
||||||
|
}},
|
||||||
|
func(ctx context.Context) (contracts.PreparedOperation[int], error) {
|
||||||
|
prepared, err := cacheableNumberOperation(nativeProducerInitial())(ctx)
|
||||||
|
operation := prepared.(contracts.NativeOperation[int])
|
||||||
|
operation.Fallback = func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil }
|
||||||
|
return operation, err
|
||||||
|
})
|
||||||
|
if !errors.Is(err, context.Canceled) || result.Outcome.Disposition != "" || assessments != 1 || fallbacks != 0 || nativeEvidenceCount(evidence, "/result.json") != 2 {
|
||||||
|
t.Fatalf("result=%#v err=%v assessed=%d fallback=%d", result, err, assessments, fallbacks)
|
||||||
|
}
|
||||||
|
for name, content := range evidence.files {
|
||||||
|
if strings.HasSuffix(name, "/availability.json") && strings.Contains(string(content), `"unassessed": true`) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Fatal("undelivered response lacks unassessed evidence")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNativeCaptureOperationCorrectionFailurePreservesCause(t *testing.T) {
|
||||||
|
cause := errors.New("cannot build correction")
|
||||||
|
for _, failCapture := range []bool{false, true} {
|
||||||
|
recording := errors.New("cannot record correction")
|
||||||
|
evidence := &nativeEvidence{fail: func(name string) error {
|
||||||
|
if failCapture && strings.HasSuffix(name, "/construction-failure.json") {
|
||||||
|
return recording
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}}
|
||||||
|
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||||
|
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||||
|
}))
|
||||||
|
result, err := ExecuteOperation(context.Background(), ExecutionContext[int]{Engine: engine, Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Execution: contracts.ExecutionOptions{Capture: evidence}, Assess: rejectedProducerAssessment},
|
||||||
|
func(ctx context.Context) (contracts.PreparedOperation[int], error) {
|
||||||
|
prepared, err := cacheableNumberOperation(nativeProducerInitial())(ctx)
|
||||||
|
operation := prepared.(contracts.NativeOperation[int])
|
||||||
|
operation.Correction = func(context.Context, []string) (promptkit.RunRequest, error) { return promptkit.RunRequest{}, cause }
|
||||||
|
return operation, err
|
||||||
|
})
|
||||||
|
if !errors.Is(err, cause) || result.Outcome.Disposition != "" || (failCapture && !errors.Is(err, recording)) {
|
||||||
|
t.Fatalf("capture=%t result=%#v err=%v", failCapture, result, err)
|
||||||
|
}
|
||||||
|
if !failCapture && nativeEvidenceCount(evidence, "/construction-failure.json") != 1 {
|
||||||
|
t.Fatal("correction construction evidence missing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user