Complete the core operation execution cutover
This commit is contained in:
@@ -58,24 +58,6 @@ type InputAdapter interface {
|
||||
Parse(ctx context.Context, req ParseRequest) (*source.SourceDocument, error)
|
||||
}
|
||||
|
||||
type ChunkRequest struct {
|
||||
Operation ProducerOperation[source.ChunkPlan] `json:"-"`
|
||||
Source *source.SourceDocument `json:"-"`
|
||||
SourceInput LLMInputMaterial `json:"source_input,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
References ReferenceSet `json:"references,omitempty"`
|
||||
LLMProfile string `json:"llm_profile,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
}
|
||||
|
||||
type ChunkPlanResult struct {
|
||||
// Fallback is an optional module-owned algorithm for deterministic rejection.
|
||||
Fallback func(context.Context) (source.ChunkPlan, error) `json:"-"`
|
||||
Outcome ProducerOutcome `json:"outcome"`
|
||||
Plan source.ChunkPlan `json:"plan"`
|
||||
Diagnostics []ProducerDiagnostic `json:"diagnostics,omitempty"`
|
||||
}
|
||||
|
||||
type Chunker interface {
|
||||
Key() string
|
||||
ReferenceSlots() []ReferenceSlot
|
||||
|
||||
@@ -251,16 +251,15 @@ func (chunker fakeChunker) ReferenceSlots() []ReferenceSlot {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (chunker fakeChunker) Plan(ctx context.Context, req ChunkRequest) (ChunkPlanResult, error) {
|
||||
return ChunkPlanResult{
|
||||
Plan: source.ChunkPlan{
|
||||
SourceDigest: req.Source.Digest,
|
||||
Ranges: []source.ChunkRange{{
|
||||
StartUnitID: req.Source.Units[0].ID,
|
||||
EndUnitID: req.Source.Units[len(req.Source.Units)-1].ID,
|
||||
}},
|
||||
},
|
||||
}, nil
|
||||
func (chunker fakeChunker) PrepareChunk(ctx context.Context, req ChunkInput) (PreparedOperation[source.ChunkPlan], error) {
|
||||
plan := source.ChunkPlan{
|
||||
SourceDigest: req.Source.Digest,
|
||||
Ranges: []source.ChunkRange{{
|
||||
StartUnitID: req.Source.Units[0].ID,
|
||||
EndUnitID: req.Source.Units[len(req.Source.Units)-1].ID,
|
||||
}},
|
||||
}
|
||||
return DeterministicOperation[source.ChunkPlan]{Evaluation: CandidateEvaluation[source.ChunkPlan]{Result: EvaluationView[source.ChunkPlan]{Candidate: &plan}}}, nil
|
||||
}
|
||||
|
||||
type fakeExtractor struct {
|
||||
@@ -277,12 +276,13 @@ func (extractor fakeExtractor) ReferenceSlots() []ReferenceSlot {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (extractor fakeExtractor) Extract(ctx context.Context, req TypedExtractionRequest[fakeArtifact]) (TypedExtractionResult[fakeArtifact], error) {
|
||||
func (extractor fakeExtractor) PrepareExtraction(ctx context.Context, req ExtractionInput) (PreparedOperation[fakeArtifact], error) {
|
||||
value := "example"
|
||||
if req.AmbientContext["mode"] == "chunked" {
|
||||
value = "chunked"
|
||||
}
|
||||
return TypedExtractionResult[fakeArtifact]{Value: fakeArtifact{Value: value}}, nil
|
||||
result := fakeArtifact{Value: value}
|
||||
return DeterministicOperation[fakeArtifact]{Evaluation: CandidateEvaluation[fakeArtifact]{Result: EvaluationView[fakeArtifact]{Candidate: &result}}}, nil
|
||||
}
|
||||
|
||||
type fakeMerger struct {
|
||||
@@ -293,8 +293,9 @@ func (merger fakeMerger) Key() string {
|
||||
return merger.key
|
||||
}
|
||||
|
||||
func (merger fakeMerger) Merge(ctx context.Context, req TypedMergeRequest[fakeArtifact]) (TypedMergeResult[fakeArtifact], error) {
|
||||
return TypedMergeResult[fakeArtifact]{Value: req.ExtractOutputs[0].Value}, nil
|
||||
func (merger fakeMerger) PrepareMerge(ctx context.Context, req MergeInput[fakeArtifact]) (PreparedOperation[fakeArtifact], error) {
|
||||
value := req.ExtractOutputs[0].Value
|
||||
return DeterministicOperation[fakeArtifact]{Evaluation: CandidateEvaluation[fakeArtifact]{Result: EvaluationView[fakeArtifact]{Candidate: &value}}}, nil
|
||||
}
|
||||
|
||||
type fakeNormalizer struct {
|
||||
@@ -309,8 +310,9 @@ func (normalizer fakeNormalizer) ReferenceSlots() []ReferenceSlot {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (normalizer fakeNormalizer) Normalize(ctx context.Context, req TypedNormalizeRequest[fakeArtifact]) (TypedNormalizeResult[fakeArtifact], error) {
|
||||
return TypedNormalizeResult[fakeArtifact]{Value: req.MergeOutput.Value}, nil
|
||||
func (normalizer fakeNormalizer) PrepareNormalize(ctx context.Context, req NormalizeInput[fakeArtifact]) (PreparedOperation[fakeArtifact], error) {
|
||||
value := req.MergeOutput.Value
|
||||
return DeterministicOperation[fakeArtifact]{Evaluation: CandidateEvaluation[fakeArtifact]{Result: EvaluationView[fakeArtifact]{Candidate: &value}}}, nil
|
||||
}
|
||||
|
||||
type fakeOutputEncoder struct {
|
||||
|
||||
@@ -118,16 +118,6 @@ type CandidateAssessment struct {
|
||||
|
||||
type CandidateAssessor[T any] func(context.Context, T) (CandidateAssessment, error)
|
||||
|
||||
// ProducerOperation is supplied explicitly by the runner for one operation.
|
||||
// Validators receive ExecutionOptions, never a producer assessment callback.
|
||||
type ProducerOperation[T any] struct {
|
||||
Controls ProducerControls
|
||||
Assess CandidateAssessor[T] `json:"-"`
|
||||
Execution ExecutionOptions
|
||||
ReuseEligible bool
|
||||
Cache *ProducerCache[T] `json:"-"`
|
||||
}
|
||||
|
||||
type ProducerDisposition string
|
||||
|
||||
const (
|
||||
|
||||
@@ -33,75 +33,17 @@ type NormalizeArtifact[T any] struct {
|
||||
Value T
|
||||
}
|
||||
|
||||
type TypedExtractionRequest[T any] struct {
|
||||
Operation ProducerOperation[T]
|
||||
Source *source.SourceDocument
|
||||
Chunk *source.Chunk
|
||||
AmbientContext map[string]any
|
||||
SourceInput LLMInputMaterial
|
||||
SessionID string
|
||||
References ReferenceSet
|
||||
LLMProfile string
|
||||
Metadata map[string]any
|
||||
}
|
||||
|
||||
type TypedExtractionResult[T any] struct {
|
||||
// Fallback is an optional module-owned algorithm for deterministic rejection.
|
||||
Fallback func(context.Context) (T, error) `json:"-"`
|
||||
Outcome ProducerOutcome
|
||||
Value T
|
||||
Diagnostics []ProducerDiagnostic
|
||||
}
|
||||
|
||||
type Extractor[T any] interface {
|
||||
Key() string
|
||||
ReferenceSlots() []ReferenceSlot
|
||||
PrepareExtraction(context.Context, ExtractionInput) (PreparedOperation[T], error)
|
||||
}
|
||||
|
||||
type TypedMergeRequest[T any] struct {
|
||||
Operation ProducerOperation[T]
|
||||
Source *source.SourceDocument
|
||||
LaneID string
|
||||
ExtractOutputs []ExtractArtifact[T]
|
||||
SourceInput LLMInputMaterial
|
||||
SessionID string
|
||||
References ReferenceSet
|
||||
LLMProfile string
|
||||
Metadata map[string]any
|
||||
}
|
||||
|
||||
type TypedMergeResult[T any] struct {
|
||||
Fallback func(context.Context) (T, error) `json:"-"`
|
||||
Outcome ProducerOutcome
|
||||
Value T
|
||||
Diagnostics []ProducerDiagnostic
|
||||
}
|
||||
|
||||
type Merger[T any] interface {
|
||||
Key() string
|
||||
PrepareMerge(context.Context, MergeInput[T]) (PreparedOperation[T], error)
|
||||
}
|
||||
|
||||
type TypedNormalizeRequest[T any] struct {
|
||||
Operation ProducerOperation[T]
|
||||
Source *source.SourceDocument
|
||||
LaneID string
|
||||
MergeOutput MergeArtifact[T]
|
||||
SourceInput LLMInputMaterial
|
||||
SessionID string
|
||||
References ReferenceSet
|
||||
LLMProfile string
|
||||
Metadata map[string]any
|
||||
}
|
||||
|
||||
type TypedNormalizeResult[T any] struct {
|
||||
Fallback func(context.Context) (T, error) `json:"-"`
|
||||
Outcome ProducerOutcome
|
||||
Value T
|
||||
Diagnostics []ProducerDiagnostic
|
||||
}
|
||||
|
||||
type Normalizer[T any] interface {
|
||||
Key() string
|
||||
ReferenceSlots() []ReferenceSlot
|
||||
|
||||
@@ -35,7 +35,7 @@ profiles:
|
||||
chain.validators = append(chain.validators, preparedValidator{resolved: ResolvedValidator{Binding: Binding(name)}})
|
||||
}
|
||||
var order []string
|
||||
operation := contracts.ProducerOperation[int]{
|
||||
operation := ExecutionContext[int]{
|
||||
Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, ReuseEligible: true,
|
||||
Assess: func(ctx context.Context, _ int) (contracts.CandidateAssessment, error) {
|
||||
return executeValidationChain(ctx, chain, func(ctx context.Context, validator preparedValidator) (contracts.ValidationResult, error) {
|
||||
@@ -51,7 +51,7 @@ profiles:
|
||||
})
|
||||
},
|
||||
}
|
||||
value, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
value, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
if err != nil || value != 1 || outcome.Disposition != contracts.ProducerAccepted || calls != 3 || !reflect.DeepEqual(order, []string{"first-native", "second-native"}) {
|
||||
t.Fatalf("nested assessment=%d %#v %v, native calls=%d order=%v", value, outcome, err, calls, order)
|
||||
}
|
||||
|
||||
@@ -84,7 +84,7 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
|
||||
OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared++ },
|
||||
Capture: evidence,
|
||||
}
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Execution: options,
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Execution: options,
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
request, _ := producerCorrection(ctx, []string{"nested assessment"})
|
||||
request = producerRequest(request, options)
|
||||
@@ -108,7 +108,7 @@ func TestNativeCapturePreservesFullEvidenceAndCountsEachExecutionOnce(t *testing
|
||||
initial.OnPrepared = func(_ context.Context, details promptkit.PreparedRun) {
|
||||
details.Messages[0].Content = "changed by existing preparation hook"
|
||||
}
|
||||
value, _, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber, producerCorrection, nil)
|
||||
value, _, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: initial, Interpret: interpretNumberEvaluation, Correction: producerCorrection, Fallback: nil})
|
||||
if err != nil || value != 1 {
|
||||
t.Fatalf("result=%d, %v", value, err)
|
||||
}
|
||||
@@ -172,7 +172,7 @@ func TestNativeCaptureRecordsCacheDetailsWithoutExecution(t *testing.T) {
|
||||
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
|
||||
}))
|
||||
operation := numberCacheOperation(store)
|
||||
if _, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil); err != nil {
|
||||
if _, _, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
evidence := &nativeEvidence{}
|
||||
@@ -185,7 +185,7 @@ func TestNativeCaptureRecordsCacheDetailsWithoutExecution(t *testing.T) {
|
||||
t.Fatal("cache hit reassessed")
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}
|
||||
value, _, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
value, _, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
if err != nil || value != 1 {
|
||||
t.Fatalf("hit=%d, %v", value, err)
|
||||
}
|
||||
@@ -257,14 +257,14 @@ func TestNativeCaptureUndeliveredResponseRemainsUnassessed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
})
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 1},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 1},
|
||||
Execution: contracts.ExecutionOptions{Capture: evidence},
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
return rejectedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, producerCorrection, func(context.Context, *int) (int, error) { fallbackCalls++; return -1, nil })
|
||||
_, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbackCalls++; return -1, nil }})
|
||||
if !errors.Is(err, context.Canceled) || assessed != 1 || fallbackCalls != 0 || outcome.Disposition != "" {
|
||||
t.Fatalf("undelivered=%#v %v, assessments=%d fallbacks=%d", outcome, err, assessed, fallbackCalls)
|
||||
}
|
||||
@@ -297,13 +297,13 @@ func TestNativeCaptureFailureNeverRetriesOrFallsBack(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Execution: contracts.ExecutionOptions{Capture: evidence},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Execution: contracts.ExecutionOptions{Capture: evidence},
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
return rejectedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, producerCorrection, func(context.Context, *int) (int, error) { fallbackCalls++; return -1, nil })
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbackCalls++; return -1, nil }})
|
||||
var recording *contracts.CaptureError
|
||||
if !errors.Is(err, captureErr) || !errors.As(err, &recording) || calls > 1 || fallbackCalls != 0 || outcome.Disposition != "" {
|
||||
t.Fatalf("capture failure=%#v %v, calls=%d assessed=%d fallback=%d", outcome, err, calls, assessed, fallbackCalls)
|
||||
@@ -336,12 +336,12 @@ func TestNativeCaptureSupportsConcurrentOperationsOnOneGroup(t *testing.T) {
|
||||
var workers sync.WaitGroup
|
||||
for index := range operations {
|
||||
workers.Go(func() {
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: acceptedProducerAssessment,
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: acceptedProducerAssessment,
|
||||
Execution: contracts.ExecutionOptions{Capture: scopeEvidence(evidence, fmt.Sprintf("operations/%d", index)),
|
||||
OnPrepared: func(context.Context, promptkit.PreparedRun) { prepared.Add(1) },
|
||||
},
|
||||
}
|
||||
_, _, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
_, _, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
failures <- err
|
||||
})
|
||||
}
|
||||
@@ -385,10 +385,10 @@ func TestNativeCaptureRetainsCorrectionInputsWhenPreparationFails(t *testing.T)
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Assess: rejectedProducerAssessment, Execution: contracts.ExecutionOptions{Capture: evidence}}
|
||||
_, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, func(context.Context, []string) (promptkit.RunRequest, error) {
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, Assess: rejectedProducerAssessment, Execution: contracts.ExecutionOptions{Capture: evidence}}
|
||||
_, _, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: func(context.Context, []string) (promptkit.RunRequest, error) {
|
||||
return promptkit.RunRequest{PromptID: "missing-correction", Inputs: map[string]promptkit.ArtifactRef{"guidance": promptkit.Inline("constructed correction input")}}, nil
|
||||
}, nil)
|
||||
}, Fallback: nil})
|
||||
if err == nil || calls != 1 {
|
||||
t.Fatalf("missing correction preparation: %v calls=%d", err, calls)
|
||||
}
|
||||
@@ -414,8 +414,11 @@ func TestNativeCaptureFailurePreservesProviderCause(t *testing.T) {
|
||||
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
return nil, primary
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Assess: acceptedProducerAssessment, Execution: contracts.ExecutionOptions{Capture: evidence}}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, func(context.Context, *int) (int, error) { t.Fatal("capture failure invoked fallback"); return 0, nil })
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Assess: acceptedProducerAssessment, Execution: contracts.ExecutionOptions{Capture: evidence}}
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) {
|
||||
t.Fatal("capture failure invoked fallback")
|
||||
return 0, nil
|
||||
}})
|
||||
if !errors.Is(err, primary) || !errors.Is(err, recording) || outcome.Disposition != "" {
|
||||
t.Fatalf("failure causes lost: %#v %v", outcome, err)
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ func finishOperation[T any](ctx context.Context, mode contracts.ExecutionMode, c
|
||||
if fallback != nil {
|
||||
construct = func(ctx context.Context) (T, error) { return fallback(ctx, evaluation) }
|
||||
}
|
||||
value, outcome, err := FinishProducerFailure(ctx, mode, cause, construct)
|
||||
value, outcome, err := finishProducerFailure(ctx, mode, cause, construct)
|
||||
if err != nil {
|
||||
return OperationResult[T]{}, err
|
||||
}
|
||||
|
||||
@@ -149,10 +149,10 @@ func TestInterpretationCaptureFailureCannotConstructPermissiveFallback(t *testin
|
||||
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
|
||||
}))
|
||||
fallbacks := 0
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Assess: acceptedProducerAssessment}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), func(context.Context, *promptkit.RunResult) (*int, []string, error) {
|
||||
return nil, nil, &contracts.CaptureError{Cause: primary}
|
||||
}, nil, func(context.Context, *int) (int, error) { fallbacks++; return -1, nil })
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Assess: acceptedProducerAssessment}
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(context.Context, *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
return numberEvaluation(nil, nil), &contracts.CaptureError{Cause: primary}
|
||||
}, Correction: nil, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil }})
|
||||
if !errors.Is(err, primary) || fallbacks != 0 || outcome.Disposition != "" {
|
||||
t.Fatalf("capture failure became fallback: %#v %v calls=%d", outcome, err, fallbacks)
|
||||
}
|
||||
|
||||
30
internal/framework/pipeline/operation_fixture_test.go
Normal file
30
internal/framework/pipeline/operation_fixture_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
func runNativeOperation[T any](ctx context.Context, engine *promptkit.Engine, execution ExecutionContext[T], operation contracts.NativeOperation[T]) (T, contracts.ProducerOutcome, error) {
|
||||
execution.Engine = engine
|
||||
result, err := ExecuteOperation(ctx, execution, func(context.Context) (contracts.PreparedOperation[T], error) { return operation, nil })
|
||||
return result.Value, result.Outcome, err
|
||||
}
|
||||
|
||||
func numberEvaluation(candidate *int, guidance []string) contracts.Evaluation[int] {
|
||||
return contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: candidate, Guidance: guidance}}
|
||||
}
|
||||
|
||||
func evaluationCandidate(evaluation contracts.Evaluation[int]) *int {
|
||||
if evaluation == nil {
|
||||
return nil
|
||||
}
|
||||
return evaluation.View().Candidate
|
||||
}
|
||||
|
||||
func interpretNumberEvaluation(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
candidate, guidance, err := interpretProducerNumber(ctx, result)
|
||||
return numberEvaluation(candidate, guidance), err
|
||||
}
|
||||
@@ -2,287 +2,11 @@ package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// RunProducer connects native execution to typed interpretation and application
|
||||
// assessment. Interpretation returns nil when no typed candidate can be built;
|
||||
// actionable findings remain separate from operational errors. Correction builds
|
||||
// only the next assignment, never conversation history. Fallback receives only
|
||||
// the final usable candidate, or nil after an unusable/failed execution.
|
||||
func RunProducer[T any](
|
||||
ctx context.Context,
|
||||
engine *promptkit.Engine,
|
||||
operation contracts.ProducerOperation[T],
|
||||
initial promptkit.RunRequest,
|
||||
interpret func(context.Context, *promptkit.RunResult) (*T, []string, error),
|
||||
correct func(context.Context, []string) (promptkit.RunRequest, error),
|
||||
fallback func(context.Context, *T) (T, error),
|
||||
) (T, contracts.ProducerOutcome, error) {
|
||||
var zero T
|
||||
if ctx == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer context must not be nil")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, err
|
||||
}
|
||||
if interpret == nil || operation.Assess == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer interpretation and assessment must be supplied")
|
||||
}
|
||||
if operation.Controls.MaxAdditionalTurns < 0 {
|
||||
return zero, contracts.ProducerOutcome{}, fmt.Errorf("%w: additional turns must not be negative", promptkit.ErrInvalidRequest)
|
||||
}
|
||||
|
||||
var candidate *T
|
||||
var guidance []string
|
||||
var failure error
|
||||
var assessmentError error
|
||||
accepted := false
|
||||
evaluate := func(result *promptkit.RunResult) {
|
||||
candidate, guidance, failure, accepted = nil, nil, nil, false
|
||||
var assessment contracts.CandidateAssessment
|
||||
defer func() {
|
||||
if operation.Execution.Capture == nil || result == nil {
|
||||
return
|
||||
}
|
||||
errorText := ""
|
||||
if failure != nil {
|
||||
errorText = failure.Error()
|
||||
}
|
||||
if err := operation.Execution.RecordEvidence("interpretations/"+result.RunID+".json", map[string]any{
|
||||
"run_id": result.RunID, "usable_candidate": candidate != nil, "accepted": accepted,
|
||||
"correction_guidance": guidance, "assessment": assessmentEvidence(assessment), "error": errorText,
|
||||
}); err != nil {
|
||||
assessmentError = errors.Join(assessmentError, err)
|
||||
}
|
||||
}()
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
failure = canceled
|
||||
return
|
||||
}
|
||||
if failure = CheckNativeResult(result, nil); failure != nil {
|
||||
return
|
||||
}
|
||||
candidate, guidance, failure = interpret(ctx, result)
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
failure = canceled
|
||||
return
|
||||
}
|
||||
if failure != nil {
|
||||
var captureErr *contracts.CaptureError
|
||||
if errors.As(failure, &captureErr) {
|
||||
assessmentError = failure
|
||||
}
|
||||
candidate, guidance = nil, nil
|
||||
return
|
||||
}
|
||||
if candidate == nil {
|
||||
failure = errors.New("producer response could not be interpreted as a usable candidate")
|
||||
return
|
||||
}
|
||||
var err error
|
||||
assessment, err = operation.Assess(ctx, *candidate)
|
||||
if err != nil {
|
||||
assessmentError = err
|
||||
return
|
||||
}
|
||||
validatorGuidance, err := assessment.Guidance()
|
||||
if err != nil {
|
||||
assessmentError = err
|
||||
return
|
||||
}
|
||||
guidance = append(guidance, validatorGuidance...)
|
||||
accepted = assessment.Accepted() && len(guidance) == 0
|
||||
failure = assessment.Err()
|
||||
if !accepted && failure == nil {
|
||||
failure = errors.New("producer candidate requires correction")
|
||||
}
|
||||
}
|
||||
|
||||
request := producerRequest(initial, operation.Execution)
|
||||
request.CaptureExchange = request.CaptureExchange || (correct != nil && operation.Controls.MaxAdditionalTurns > 0)
|
||||
request, capture := CaptureNativeRequest(request, scopeEvidence(operation.Execution.Capture, "initial"))
|
||||
if captureErr := capture.Err(); captureErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureErr
|
||||
}
|
||||
var result *promptkit.RunResult
|
||||
var err error
|
||||
var cacheKey string
|
||||
cache := operation.Cache
|
||||
if captureErr := operation.Execution.RecordEvidence("cache/selection.json", map[string]any{"mode": operation.Controls.Cache, "reuse_eligible": operation.ReuseEligible, "store_available": cache != nil && cache.Store != nil}); captureErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureErr
|
||||
}
|
||||
if cache != nil && operation.Execution.Capture != nil {
|
||||
owned := *cache
|
||||
existing := owned.Observe
|
||||
owned.Observe = func(ctx context.Context, observation contracts.CacheObservation) error {
|
||||
if err := captureCacheObservation(operation.Execution.Capture, observation); err != nil {
|
||||
return err
|
||||
}
|
||||
if existing != nil {
|
||||
return existing(ctx, observation)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
cache = &owned
|
||||
}
|
||||
if cache != nil && cache.Store != nil && operation.ReuseEligible && operation.Controls.Cache != contracts.CacheBypass {
|
||||
if cache.Encode == nil || cache.Decode == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer cache codec must be supplied")
|
||||
}
|
||||
if mode := operation.Controls.Cache; mode != "" && mode != contracts.CacheAuto && mode != contracts.CacheRefresh {
|
||||
return zero, contracts.ProducerOutcome{}, fmt.Errorf("%w: unknown cache mode %q", promptkit.ErrInvalidRequest, mode)
|
||||
}
|
||||
var prepared *promptkit.PreparedExecution
|
||||
prepared, err = engine.PrepareExecution(ctx, request)
|
||||
if err == nil {
|
||||
defer prepared.Discard()
|
||||
details := prepared.Details()
|
||||
if capture != nil {
|
||||
capture.RetainPrepared(copyPreparedEvidence(details))
|
||||
}
|
||||
cacheKey = details.MessageContentHash
|
||||
if captureErr := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: "prepared", MessageContentHash: cacheKey, Prepared: &details}); captureErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureFailure(captureErr, capture.Finish(nil, captureErr, false, false))
|
||||
}
|
||||
reused, lookupErr := lookupProducerCache(ctx, cache, operation.Controls.Cache, cacheKey)
|
||||
if lookupErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureFailure(lookupErr, capture.Finish(nil, lookupErr, false, false))
|
||||
}
|
||||
if reused != nil {
|
||||
if captureErr := capture.Finish(nil, nil, false, true); captureErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureErr
|
||||
}
|
||||
return *reused, contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: true}, nil
|
||||
}
|
||||
result, err = engine.RunPrepared(ctx, prepared)
|
||||
}
|
||||
} else {
|
||||
if cache != nil {
|
||||
decision := "bypass"
|
||||
if !operation.ReuseEligible {
|
||||
decision = "ineligible"
|
||||
}
|
||||
if err := observeProducerCache(ctx, cache, contracts.CacheObservation{Decision: decision}); err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureFailure(err, capture.Finish(nil, err, false, false))
|
||||
}
|
||||
}
|
||||
result, err = engine.Run(ctx, request)
|
||||
}
|
||||
if captureErr := capture.Finish(result, err, ctx.Err() != nil, false); captureErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureFailure(errors.Join(ctx.Err(), err), captureErr)
|
||||
}
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return zero, contracts.ProducerOutcome{}, canceled
|
||||
}
|
||||
if err != nil {
|
||||
failure = CheckNativeResult(result, err)
|
||||
} else {
|
||||
evaluate(result)
|
||||
}
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return zero, contracts.ProducerOutcome{}, canceled
|
||||
}
|
||||
if assessmentError != nil {
|
||||
return zero, contracts.ProducerOutcome{}, assessmentError
|
||||
}
|
||||
|
||||
if !accepted && err == nil && len(guidance) > 0 && correct != nil && operation.Controls.MaxAdditionalTurns > 0 {
|
||||
var pendingCapture *NativeCapture
|
||||
var recordingErr error
|
||||
coordination, coordinateErr := engine.Coordinate(ctx, promptkit.CoordinateRequest{
|
||||
Start: result.Exchange, AdditionalTurns: operation.Controls.MaxAdditionalTurns,
|
||||
Next: func(_ context.Context, turn promptkit.ConversationTurn) (*promptkit.RunRequest, error) {
|
||||
// The first callback has no new result. Its findings already exist.
|
||||
if turn.Result != nil {
|
||||
recordingErr = pendingCapture.Finish(turn.Result, nil, false, false)
|
||||
pendingCapture = nil
|
||||
if recordingErr != nil {
|
||||
return nil, recordingErr
|
||||
}
|
||||
evaluate(turn.Result)
|
||||
}
|
||||
if assessmentError != nil {
|
||||
return nil, assessmentError
|
||||
}
|
||||
if accepted || len(guidance) == 0 || turn.RemainingTurns == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
// Once another execution is selected, an earlier candidate is not a
|
||||
// terminal fallback source if construction or native execution fails.
|
||||
candidate = nil
|
||||
correctionPath := ""
|
||||
if operation.Execution.Capture != nil {
|
||||
correctionPath = "corrections/" + turn.Exchange.Details().RunID
|
||||
recordingErr = operation.Execution.RecordEvidence(correctionPath+"/assignment.json", map[string]any{"guidance": guidance})
|
||||
if recordingErr != nil {
|
||||
return nil, recordingErr
|
||||
}
|
||||
}
|
||||
next, buildErr := correct(ctx, guidance)
|
||||
if buildErr != nil {
|
||||
if correctionPath != "" {
|
||||
recordingErr = operation.Execution.RecordEvidence(correctionPath+"/construction-failure.json", map[string]any{"error": buildErr.Error()})
|
||||
}
|
||||
return nil, buildErr
|
||||
}
|
||||
if initial.ProfileID != "" {
|
||||
next.ProfileID = initial.ProfileID
|
||||
}
|
||||
if initial.SessionID != "" {
|
||||
next.SessionID = initial.SessionID
|
||||
}
|
||||
next = producerRequest(next, operation.Execution)
|
||||
if operation.Execution.Capture != nil {
|
||||
next, pendingCapture = CaptureNativeRequest(next, scopeEvidence(operation.Execution.Capture, correctionPath))
|
||||
if recordingErr = pendingCapture.Err(); recordingErr != nil {
|
||||
return nil, recordingErr
|
||||
}
|
||||
}
|
||||
return &next, nil
|
||||
},
|
||||
})
|
||||
if pendingCapture != nil {
|
||||
recordingErr = errors.Join(recordingErr, pendingCapture.Finish(coordination.Undelivered, coordinateErr, coordination.Undelivered != nil, false))
|
||||
}
|
||||
if recordingErr != nil {
|
||||
return zero, contracts.ProducerOutcome{}, captureFailure(coordinateErr, recordingErr)
|
||||
}
|
||||
if canceled := ctx.Err(); canceled != nil {
|
||||
return zero, contracts.ProducerOutcome{}, canceled
|
||||
}
|
||||
if coordination.Undelivered != nil {
|
||||
if coordinateErr == nil {
|
||||
coordinateErr = errors.New("native continuation response was not delivered")
|
||||
}
|
||||
return zero, contracts.ProducerOutcome{}, coordinateErr
|
||||
}
|
||||
if assessmentError != nil {
|
||||
return zero, contracts.ProducerOutcome{}, assessmentError
|
||||
}
|
||||
if coordinateErr != nil {
|
||||
candidate, failure, accepted = nil, coordinateErr, false
|
||||
}
|
||||
}
|
||||
if accepted {
|
||||
if cacheKey != "" {
|
||||
if err := storeProducerCache(ctx, cache, operation.Controls.Cache, cacheKey, *candidate); err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, err
|
||||
}
|
||||
}
|
||||
return *candidate, contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: operation.ReuseEligible}, nil
|
||||
}
|
||||
var construct func(context.Context) (T, error)
|
||||
if fallback != nil {
|
||||
construct = func(ctx context.Context) (T, error) { return fallback(ctx, candidate) }
|
||||
}
|
||||
return FinishProducerFailure(ctx, operation.Controls.Mode, failure, construct)
|
||||
}
|
||||
|
||||
// producerRequest applies native request overrides and preparation hooks to a value copy.
|
||||
func producerRequest(request promptkit.RunRequest, options contracts.ExecutionOptions) promptkit.RunRequest {
|
||||
if options.Execution != nil {
|
||||
|
||||
@@ -41,8 +41,8 @@ func (store *producerCacheStore) Store(ctx context.Context, mode contracts.Cache
|
||||
return store.inner.Store(ctx, mode, hash, content)
|
||||
}
|
||||
|
||||
func numberCacheOperation(store contracts.ArtifactCache) contracts.ProducerOperation[int] {
|
||||
return contracts.ProducerOperation[int]{
|
||||
func numberCacheOperation(store contracts.ArtifactCache) ExecutionContext[int] {
|
||||
return ExecutionContext[int]{
|
||||
Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, Cache: contracts.CacheAuto, MaxAdditionalTurns: 1},
|
||||
ReuseEligible: true, Assess: acceptedProducerAssessment,
|
||||
Cache: &contracts.ProducerCache[int]{
|
||||
@@ -103,19 +103,19 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
|
||||
}
|
||||
// The response is a proposal; the cache must contain the applied typed value,
|
||||
// not the private response or an earlier candidate.
|
||||
interpretApplied := func(ctx context.Context, response *promptkit.RunResult) (*int, []string, error) {
|
||||
interpretApplied := func(ctx context.Context, response *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
value, guidance, err := interpretProducerNumber(ctx, response)
|
||||
if value != nil {
|
||||
*value *= 10
|
||||
}
|
||||
return value, guidance, err
|
||||
return numberEvaluation(value, guidance), err
|
||||
}
|
||||
store.beforeWrite = func(hash string, content []byte) {
|
||||
if assessments != 2 || calls != 2 || string(content) != "20" || hash != keys[0] {
|
||||
t.Fatalf("early or incorrect cache store: %s %q, calls=%d assessments=%d", hash, content, calls, assessments)
|
||||
}
|
||||
}
|
||||
value, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretApplied, producerCorrection, nil)
|
||||
value, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretApplied, Correction: producerCorrection, Fallback: nil})
|
||||
if err != nil || value != 20 || outcome.Disposition != contracts.ProducerAccepted || store.writes != 1 || nativePrepared != 2 || events == 0 {
|
||||
t.Fatalf("accepted correction = %d %#v %v; writes %d, prepared %d, events %d", value, outcome, err, store.writes, nativePrepared, events)
|
||||
}
|
||||
@@ -132,11 +132,10 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
|
||||
t.Fatal("cache hit reassessed")
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}
|
||||
value, outcome, err = RunProducer(ctx, engine, operation, initial,
|
||||
func(context.Context, *promptkit.RunResult) (*int, []string, error) {
|
||||
t.Fatal("cache hit interpreted a model result")
|
||||
return nil, nil, nil
|
||||
}, producerCorrection, nil)
|
||||
value, outcome, err = runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: initial, Interpret: func(context.Context, *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
t.Fatal("cache hit interpreted a model result")
|
||||
return numberEvaluation(nil, nil), nil
|
||||
}, Correction: producerCorrection, Fallback: nil})
|
||||
if err != nil || value != 20 || !outcome.ReuseEligible || calls != 2 || assessments != 2 || nativePrepared != 2 || events != priorEvents || store.writes != 1 || len(keys) != 2 || keys[0] != keys[1] {
|
||||
t.Fatalf("settings/session reuse = %d %#v %v; calls=%d assessments=%d native-prepared=%d events=%d keys=%v", value, outcome, err, calls, assessments, nativePrepared, events, keys)
|
||||
}
|
||||
@@ -145,7 +144,7 @@ func TestProducerCachesAppliedCorrectionUnderInitialKeyAndReusesWithoutExecution
|
||||
}
|
||||
operation.Assess = acceptedProducerAssessment
|
||||
initial.Inputs["source"] = promptkit.Inline("changed source content")
|
||||
value, _, err = RunProducer(ctx, engine, operation, initial, interpretApplied, producerCorrection, nil)
|
||||
value, _, err = runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: initial, Interpret: interpretApplied, Correction: producerCorrection, Fallback: nil})
|
||||
if err != nil || value != 20 || calls != 3 || len(keys) != 3 || keys[0] == keys[2] || store.writes != 2 {
|
||||
t.Fatalf("content change did not miss: value %d error %v calls %d keys %v", value, err, calls, keys)
|
||||
}
|
||||
@@ -188,7 +187,7 @@ func TestProducerExecutesFrozenPreparedHandleAfterLookup(t *testing.T) {
|
||||
t.Fatalf("mutable snapshot changed key: %s", key)
|
||||
}
|
||||
}
|
||||
if value, _, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber, nil, nil); err != nil || value != 1 {
|
||||
if value, _, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: initial, Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil}); err != nil || value != 1 {
|
||||
t.Fatalf("prepared execution = %d, %v", value, err)
|
||||
}
|
||||
if started != 1 || finished != 1 {
|
||||
@@ -241,8 +240,7 @@ func TestProducerCacheSkipsIneligibleBypassedAndNonacceptedWrites(t *testing.T)
|
||||
}
|
||||
return acceptedProducerAssessment(ctx, value)
|
||||
}
|
||||
_, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, producerCorrection,
|
||||
func(context.Context, *int) (int, error) { return -1, nil })
|
||||
_, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { return -1, nil }})
|
||||
switch {
|
||||
case test.cancel:
|
||||
if !errors.Is(err, context.Canceled) || outcome.Disposition != "" {
|
||||
@@ -296,7 +294,7 @@ func TestProducerCacheMissesOnUnusableArtifactAndTreatsIOAsDiagnostic(t *testing
|
||||
store.readErr = errors.New("unreadable cache")
|
||||
store.writeErr = errors.New("unwritable cache")
|
||||
}
|
||||
value, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
value, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
if err != nil || value != 1 || outcome.Disposition != contracts.ProducerAccepted || calls != 1 || len(diagnostics) == 0 {
|
||||
t.Fatalf("cache diagnostic changed successful work: %d %#v %v, calls %d, diagnostics %v", value, outcome, err, calls, diagnostics)
|
||||
}
|
||||
@@ -322,7 +320,7 @@ func TestProducerCacheDoesNotHideEncodingOrCaptureFailureWithFallback(t *testing
|
||||
operation.Cache.Observe = func(context.Context, contracts.CacheObservation) error { return failure }
|
||||
}
|
||||
fallbacks := 0
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, func(context.Context, *int) (int, error) { fallbacks++; return -1, nil })
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil }})
|
||||
if !errors.Is(err, failure) || fallbacks != 0 || store.writes != 0 || outcome.Disposition != "" {
|
||||
t.Fatalf("%s failure=%#v %v, fallback=%d", boundary, outcome, err, fallbacks)
|
||||
}
|
||||
@@ -349,7 +347,7 @@ func TestProducerCacheFailedRefreshPreservesPreviousArtifact(t *testing.T) {
|
||||
}
|
||||
operation := numberCacheOperation(store)
|
||||
operation.Controls.Cache = contracts.CacheRefresh
|
||||
if _, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil); err == nil {
|
||||
if _, _, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil}); err == nil {
|
||||
t.Fatal("refresh failure accepted")
|
||||
}
|
||||
content, err := os.ReadFile(filepath.Join(root, key+".json"))
|
||||
|
||||
@@ -8,9 +8,9 @@ import (
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/framework/contracts"
|
||||
)
|
||||
|
||||
// FinishProducerFailure applies the resolved terminal mode without retrying
|
||||
// finishProducerFailure applies the resolved terminal mode without retrying
|
||||
// production or running ordinary validators against a supported fallback.
|
||||
func FinishProducerFailure[T any](ctx context.Context, mode contracts.ExecutionMode, cause error, fallback func(context.Context) (T, error)) (T, contracts.ProducerOutcome, error) {
|
||||
func finishProducerFailure[T any](ctx context.Context, mode contracts.ExecutionMode, cause error, fallback func(context.Context) (T, error)) (T, contracts.ProducerOutcome, error) {
|
||||
var zero T
|
||||
if ctx == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer context must not be nil")
|
||||
@@ -44,30 +44,3 @@ func FinishProducerFailure[T any](ctx context.Context, mode contracts.ExecutionM
|
||||
return zero, contracts.ProducerOutcome{}, fmt.Errorf("unsupported producer mode %q", mode)
|
||||
}
|
||||
}
|
||||
|
||||
// AssessProducer assesses a no-model result once, including deterministic
|
||||
// short-circuits inside otherwise model-backed modules. It never constructs a
|
||||
// native request or gives deterministic work a correction loop.
|
||||
func AssessProducer[T any](ctx context.Context, operation contracts.ProducerOperation[T], value T, fallback func(context.Context) (T, error)) (T, contracts.ProducerOutcome, error) {
|
||||
var zero T
|
||||
if ctx == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer context must not be nil")
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, err
|
||||
}
|
||||
if operation.Assess == nil {
|
||||
return zero, contracts.ProducerOutcome{}, errors.New("producer assessment must be supplied")
|
||||
}
|
||||
assessment, err := operation.Assess(ctx, value)
|
||||
if err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return zero, contracts.ProducerOutcome{}, err
|
||||
}
|
||||
if !assessment.Accepted() {
|
||||
return FinishProducerFailure(ctx, operation.Controls.Mode, assessment.Err(), fallback)
|
||||
}
|
||||
return value, contracts.ProducerOutcome{Disposition: contracts.ProducerAccepted, ReuseEligible: operation.ReuseEligible}, nil
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ func TestProducerTerminalModeControlsSupportedFallback(t *testing.T) {
|
||||
failure := errors.New("candidate not accepted")
|
||||
for _, mode := range []contracts.ExecutionMode{contracts.ModeStrict, contracts.ModePermissive} {
|
||||
calls := 0
|
||||
value, outcome, err := FinishProducerFailure(context.Background(), mode, failure, func(context.Context) (string, error) { calls++; return "supported", nil })
|
||||
value, outcome, err := finishProducerFailure(context.Background(), mode, failure, func(context.Context) (string, error) { calls++; return "supported", nil })
|
||||
if mode == contracts.ModeStrict {
|
||||
if !errors.Is(err, failure) || calls != 0 || value != "" || outcome.Disposition != "" {
|
||||
t.Fatalf("strict = %q %#v %v, calls %d", value, outcome, err, calls)
|
||||
@@ -25,11 +25,11 @@ func TestProducerTerminalModeControlsSupportedFallback(t *testing.T) {
|
||||
|
||||
func TestProducerFallbackCannotHideConstructionFailure(t *testing.T) {
|
||||
original, construction := errors.New("original failure"), errors.New("no invariant-preserving fallback")
|
||||
_, outcome, err := FinishProducerFailure(context.Background(), contracts.ModePermissive, original, func(context.Context) (string, error) { return "", construction })
|
||||
_, outcome, err := finishProducerFailure(context.Background(), contracts.ModePermissive, original, func(context.Context) (string, error) { return "", construction })
|
||||
if !errors.Is(err, original) || !errors.Is(err, construction) || outcome.Disposition != "" {
|
||||
t.Fatalf("outcome = %#v, error = %v", outcome, err)
|
||||
}
|
||||
if _, _, err := FinishProducerFailure[string](context.Background(), contracts.ModePermissive, original, nil); !errors.Is(err, original) {
|
||||
if _, _, err := finishProducerFailure[string](context.Background(), contracts.ModePermissive, original, nil); !errors.Is(err, original) {
|
||||
t.Fatalf("unsupported fallback = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func TestProducerCancellationNeverDeliversFallback(t *testing.T) {
|
||||
if !cancelDuringFallback {
|
||||
cancel()
|
||||
}
|
||||
value, outcome, err := FinishProducerFailure(ctx, contracts.ModePermissive, errors.New("failure"), func(context.Context) (string, error) {
|
||||
value, outcome, err := finishProducerFailure(ctx, contracts.ModePermissive, errors.New("failure"), func(context.Context) (string, error) {
|
||||
calls++
|
||||
cancel()
|
||||
return "not delivered", nil
|
||||
@@ -57,7 +57,7 @@ func TestProducerCancellationNeverDeliversFallback(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestProducerLocalTimeoutDoesNotBecomeCallerCancellation(t *testing.T) {
|
||||
value, outcome, err := FinishProducerFailure(context.Background(), contracts.ModePermissive, context.DeadlineExceeded, func(context.Context) (string, error) { return "supported", nil })
|
||||
value, outcome, err := finishProducerFailure(context.Background(), contracts.ModePermissive, context.DeadlineExceeded, func(context.Context) (string, error) { return "supported", nil })
|
||||
if err != nil || value != "supported" || outcome.Disposition != contracts.ProducerFallback {
|
||||
t.Fatalf("local timeout = %q %#v %v", value, outcome, err)
|
||||
}
|
||||
@@ -67,7 +67,7 @@ func TestNoModelProducerIsAssessedOnceWithoutRevalidatingFallback(t *testing.T)
|
||||
for _, approve := range []bool{true, false} {
|
||||
for _, mode := range []contracts.ExecutionMode{contracts.ModeStrict, contracts.ModePermissive} {
|
||||
assessed, fallbacks := 0, 0
|
||||
operation := contracts.ProducerOperation[string]{
|
||||
operation := ExecutionContext[string]{
|
||||
Controls: contracts.ProducerControls{Mode: mode}, ReuseEligible: true,
|
||||
Assess: func(context.Context, string) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
@@ -77,7 +77,14 @@ func TestNoModelProducerIsAssessedOnceWithoutRevalidatingFallback(t *testing.T)
|
||||
return contracts.CandidateAssessment{Validators: []contracts.ValidatorAssessment{{ValidatorName: "policy", Decision: contracts.AssessmentRejected, Result: contracts.ValidationResult{Message: "not accepted"}}}}, nil
|
||||
},
|
||||
}
|
||||
value, outcome, err := AssessProducer(context.Background(), operation, "candidate", func(context.Context) (string, error) { fallbacks++; return "supported", nil })
|
||||
candidate := "candidate"
|
||||
result, err := ExecuteOperation(context.Background(), operation, func(context.Context) (contracts.PreparedOperation[string], error) {
|
||||
return contracts.DeterministicOperation[string]{Evaluation: contracts.CandidateEvaluation[string]{Result: contracts.EvaluationView[string]{Candidate: &candidate}}, Fallback: func(context.Context, contracts.Evaluation[string]) (string, error) {
|
||||
fallbacks++
|
||||
return "supported", nil
|
||||
}}, nil
|
||||
})
|
||||
value, outcome := result.Value, result.Outcome
|
||||
if assessed != 1 {
|
||||
t.Fatalf("assessed %d times", assessed)
|
||||
}
|
||||
@@ -98,12 +105,19 @@ func TestNoModelProducerIsAssessedOnceWithoutRevalidatingFallback(t *testing.T)
|
||||
|
||||
func TestNoModelProducerStopsAfterAssessmentCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive},
|
||||
Assess: func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||
cancel()
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}}
|
||||
_, outcome, err := AssessProducer(ctx, operation, 1, func(context.Context) (int, error) { t.Fatal("fallback after cancellation"); return 0, nil })
|
||||
candidate := 1
|
||||
result, err := ExecuteOperation(ctx, operation, func(context.Context) (contracts.PreparedOperation[int], error) {
|
||||
return contracts.DeterministicOperation[int]{Evaluation: contracts.CandidateEvaluation[int]{Result: contracts.EvaluationView[int]{Candidate: &candidate}}, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) {
|
||||
t.Fatal("fallback after cancellation")
|
||||
return 0, nil
|
||||
}}, nil
|
||||
})
|
||||
outcome := result.Outcome
|
||||
if !errors.Is(err, context.Canceled) || outcome.Disposition != "" {
|
||||
t.Fatalf("cancellation = %#v %v", outcome, err)
|
||||
}
|
||||
|
||||
@@ -116,7 +116,7 @@ func TestNativeProducerAcceptsOnlyAssessedCandidates(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: fmt.Sprintf(`{"value":%d}`, value)}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: test.mode, MaxAdditionalTurns: test.turns}, ReuseEligible: true,
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: test.mode, MaxAdditionalTurns: test.turns}, ReuseEligible: true,
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessments++
|
||||
if value == 1 {
|
||||
@@ -125,19 +125,17 @@ func TestNativeProducerAcceptsOnlyAssessedCandidates(t *testing.T) {
|
||||
return rejectedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
value, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(),
|
||||
func(ctx context.Context, result *promptkit.RunResult) (*int, []string, error) {
|
||||
interpreted++
|
||||
return interpretProducerNumber(ctx, result)
|
||||
},
|
||||
producerCorrection,
|
||||
func(_ context.Context, final *int) (int, error) {
|
||||
fallbacks++
|
||||
if final == nil || *final != test.values[len(test.values)-1] {
|
||||
t.Fatalf("fallback did not receive the final usable candidate: %v", final)
|
||||
}
|
||||
return -1, nil
|
||||
})
|
||||
value, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpreted++
|
||||
return interpretNumberEvaluation(ctx, result)
|
||||
}, Correction: producerCorrection, Fallback: func(_ context.Context, evaluation contracts.Evaluation[int]) (int, error) {
|
||||
final := evaluationCandidate(evaluation)
|
||||
fallbacks++
|
||||
if final == nil || *final != test.values[len(test.values)-1] {
|
||||
t.Fatalf("fallback did not receive the final usable candidate: %v", final)
|
||||
}
|
||||
return -1, nil
|
||||
}})
|
||||
if calls != len(test.values) || assessments != calls || interpreted != calls {
|
||||
t.Fatalf("provider=%d interpretation=%d assessment=%d; want %d each", calls, interpreted, assessments, len(test.values))
|
||||
}
|
||||
@@ -169,28 +167,26 @@ func TestNativeProducerDoesNotInterpretFailedNativeValidation(t *testing.T) {
|
||||
}
|
||||
return &promptkit.GenerateResponse{Content: "not JSON"}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessments++
|
||||
return rejectedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(),
|
||||
func(ctx context.Context, result *promptkit.RunResult) (*int, []string, error) {
|
||||
interpretations++
|
||||
return interpretProducerNumber(ctx, result)
|
||||
},
|
||||
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
corrections++
|
||||
return producerCorrection(ctx, guidance)
|
||||
},
|
||||
func(_ context.Context, candidate *int) (int, error) {
|
||||
fallbacks++
|
||||
if candidate != nil {
|
||||
t.Fatal("structurally failed response recovered a prior candidate")
|
||||
}
|
||||
return -1, nil
|
||||
})
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpretations++
|
||||
return interpretNumberEvaluation(ctx, result)
|
||||
}, Correction: func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
corrections++
|
||||
return producerCorrection(ctx, guidance)
|
||||
}, Fallback: func(_ context.Context, evaluation contracts.Evaluation[int]) (int, error) {
|
||||
candidate := evaluationCandidate(evaluation)
|
||||
fallbacks++
|
||||
if candidate != nil {
|
||||
t.Fatal("structurally failed response recovered a prior candidate")
|
||||
}
|
||||
return -1, nil
|
||||
}})
|
||||
want := 0
|
||||
if failCorrection {
|
||||
want = 1
|
||||
@@ -206,12 +202,11 @@ func TestNativeProducerReportsCompletedValidationFailure(t *testing.T) {
|
||||
return &promptkit.GenerateResponse{Content: "not JSON"}, nil
|
||||
}))
|
||||
interpreted := false
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: rejectedProducerAssessment}
|
||||
_, _, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(),
|
||||
func(context.Context, *promptkit.RunResult) (*int, []string, error) {
|
||||
interpreted = true
|
||||
return nil, nil, nil
|
||||
}, nil, nil)
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: rejectedProducerAssessment}
|
||||
_, _, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(context.Context, *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpreted = true
|
||||
return numberEvaluation(nil, nil), nil
|
||||
}, Correction: nil, Fallback: nil})
|
||||
var invalid *NativeValidationError
|
||||
if !errors.As(err, &invalid) || errors.Is(err, promptkit.ErrValidation) || len(invalid.Validation.Errors) == 0 || interpreted {
|
||||
t.Fatalf("completed validation failure = %v, interpreted = %t", err, interpreted)
|
||||
@@ -232,24 +227,22 @@ func TestNativeProducerFailureDoesNotRecoverEarlierCandidate(t *testing.T) {
|
||||
}
|
||||
return nil, failure
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
return rejectedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(),
|
||||
func(ctx context.Context, result *promptkit.RunResult) (*int, []string, error) {
|
||||
interpreted++
|
||||
return interpretProducerNumber(ctx, result)
|
||||
},
|
||||
producerCorrection,
|
||||
func(_ context.Context, candidate *int) (int, error) {
|
||||
if candidate != nil {
|
||||
t.Fatal("failed execution recovered an earlier candidate")
|
||||
}
|
||||
return -1, nil
|
||||
})
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpreted++
|
||||
return interpretNumberEvaluation(ctx, result)
|
||||
}, Correction: producerCorrection, Fallback: func(_ context.Context, evaluation contracts.Evaluation[int]) (int, error) {
|
||||
candidate := evaluationCandidate(evaluation)
|
||||
if candidate != nil {
|
||||
t.Fatal("failed execution recovered an earlier candidate")
|
||||
}
|
||||
return -1, nil
|
||||
}})
|
||||
want := 0
|
||||
if failCorrection {
|
||||
want = 1
|
||||
@@ -261,7 +254,7 @@ func TestNativeProducerFailureDoesNotRecoverEarlierCandidate(t *testing.T) {
|
||||
engine := nativeProducerEngine(t, producerClientFunc(func(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
return nil, failure
|
||||
}))
|
||||
_, _, err := RunProducer(context.Background(), engine, contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: acceptedProducerAssessment}, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
_, _, err := runNativeOperation(context.Background(), engine, ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict}, Assess: acceptedProducerAssessment}, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatalf("native failure cause was lost: %v", err)
|
||||
}
|
||||
@@ -273,17 +266,15 @@ func TestNativeProducerUnavailableAssessmentSuppliesNoCorrection(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 5},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 5},
|
||||
Assess: func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||
return contracts.CandidateAssessment{Validators: []contracts.ValidatorAssessment{{Decision: contracts.AssessmentUnavailable, Failure: errors.New("provider unavailable")}}}, nil
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber,
|
||||
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
corrections++
|
||||
return producerCorrection(ctx, guidance)
|
||||
},
|
||||
func(context.Context, *int) (int, error) { return -1, nil })
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
corrections++
|
||||
return producerCorrection(ctx, guidance)
|
||||
}, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { return -1, nil }})
|
||||
if err != nil || outcome.Disposition != contracts.ProducerFallback || calls != 1 || corrections != 0 {
|
||||
t.Fatalf("unavailable assessment = %#v %v, calls %d/%d", outcome, err, calls, corrections)
|
||||
}
|
||||
@@ -316,27 +307,26 @@ func TestNativeProducerPreservesConversationAndExplicitSelections(t *testing.T)
|
||||
observed++
|
||||
}
|
||||
})
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Assess: rejectedProducerAssessment,
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Assess: rejectedProducerAssessment,
|
||||
Execution: contracts.ExecutionOptions{Execution: &promptkit.ExecutionTargetOverride{Model: overrideModel},
|
||||
OnPrepared: func(_ context.Context, details promptkit.PreparedRun) {
|
||||
profiles = append(profiles, details.SelectedProfileID)
|
||||
},
|
||||
},
|
||||
}
|
||||
_, outcome, err := RunProducer(ctx, engine, operation, initial, interpretProducerNumber,
|
||||
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
if !reflect.DeepEqual(guidance, []string{"Return value one."}) {
|
||||
t.Fatalf("unexpected correction guidance: %#v", guidance)
|
||||
_, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: initial, Interpret: interpretNumberEvaluation, Correction: func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
if !reflect.DeepEqual(guidance, []string{"Return value one."}) {
|
||||
t.Fatalf("unexpected correction guidance: %#v", guidance)
|
||||
}
|
||||
request, err := producerCorrection(ctx, guidance)
|
||||
request.OnPrepared = func(context.Context, promptkit.PreparedRun) { correctionPrepared++ }
|
||||
request.Observer = func(event promptkit.ExecutionEvent) {
|
||||
if event.Kind == promptkit.ExecutionFinished {
|
||||
correctionObserved++
|
||||
}
|
||||
request, err := producerCorrection(ctx, guidance)
|
||||
request.OnPrepared = func(context.Context, promptkit.PreparedRun) { correctionPrepared++ }
|
||||
request.Observer = func(event promptkit.ExecutionEvent) {
|
||||
if event.Kind == promptkit.ExecutionFinished {
|
||||
correctionObserved++
|
||||
}
|
||||
}
|
||||
return request, err
|
||||
}, func(context.Context, *int) (int, error) { return -1, nil })
|
||||
}
|
||||
return request, err
|
||||
}, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { return -1, nil }})
|
||||
if err != nil || outcome.Disposition != contracts.ProducerFallback || len(requests) != 3 || observed != 3 || initialPrepared != 1 || correctionPrepared != 2 {
|
||||
t.Fatalf("native continuation = %#v %v, counts %d/%d/%d/%d", outcome, err, len(requests), observed, initialPrepared, correctionPrepared)
|
||||
}
|
||||
@@ -379,7 +369,7 @@ func TestNativeProducerCancellationDoesNotDeliverOrFallback(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":0}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2},
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
if moment == "inside assessment" {
|
||||
@@ -400,16 +390,13 @@ func TestNativeProducerCancellationDoesNotDeliverOrFallback(t *testing.T) {
|
||||
if moment == "before initial" {
|
||||
cancel()
|
||||
}
|
||||
_, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(),
|
||||
func(ctx context.Context, result *promptkit.RunResult) (*int, []string, error) {
|
||||
interpreted++
|
||||
if moment == "inside interpretation" {
|
||||
cancel()
|
||||
}
|
||||
return interpretProducerNumber(ctx, result)
|
||||
},
|
||||
producerCorrection,
|
||||
func(context.Context, *int) (int, error) { fallbacks++; return -1, nil })
|
||||
_, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpreted++
|
||||
if moment == "inside interpretation" {
|
||||
cancel()
|
||||
}
|
||||
return interpretNumberEvaluation(ctx, result)
|
||||
}, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil }})
|
||||
if !errors.Is(err, context.Canceled) || outcome.Disposition != "" || fallbacks != 0 {
|
||||
t.Fatalf("cancellation = %#v %v, fallback calls %d", outcome, err, fallbacks)
|
||||
}
|
||||
@@ -455,20 +442,18 @@ func TestNativeProducerOperationTimeoutKeepsCallerActive(t *testing.T) {
|
||||
initial := nativeProducerInitial()
|
||||
initial.OperationTimeout = time.Second
|
||||
parent := context.Background()
|
||||
_, outcome, err := RunProducer(parent, engine, contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: mode, MaxAdditionalTurns: 2}, Assess: rejectedProducerAssessment},
|
||||
initial, interpretProducerNumber,
|
||||
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
request, err := producerCorrection(ctx, guidance)
|
||||
request.OperationTimeout = time.Second
|
||||
return request, err
|
||||
},
|
||||
func(_ context.Context, final *int) (int, error) {
|
||||
fallbacks++
|
||||
if final != nil {
|
||||
t.Fatal("timeout recovered an earlier candidate")
|
||||
}
|
||||
return -1, nil
|
||||
})
|
||||
_, outcome, err := runNativeOperation(parent, engine, ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: mode, MaxAdditionalTurns: 2}, Assess: rejectedProducerAssessment}, contracts.NativeOperation[int]{Initial: initial, Interpret: interpretNumberEvaluation, Correction: func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
request, err := producerCorrection(ctx, guidance)
|
||||
request.OperationTimeout = time.Second
|
||||
return request, err
|
||||
}, Fallback: func(_ context.Context, evaluation contracts.Evaluation[int]) (int, error) {
|
||||
final := evaluationCandidate(evaluation)
|
||||
fallbacks++
|
||||
if final != nil {
|
||||
t.Fatal("timeout recovered an earlier candidate")
|
||||
}
|
||||
return -1, nil
|
||||
}})
|
||||
if parent.Err() != nil {
|
||||
t.Fatalf("native timeout canceled caller: %v", parent.Err())
|
||||
}
|
||||
@@ -491,30 +476,28 @@ func TestNativeProducerInterpretationFindingsUseNativeCorrection(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, ReuseEligible: true,
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModeStrict, MaxAdditionalTurns: 1}, ReuseEligible: true,
|
||||
Assess: func(ctx context.Context, value int) (contracts.CandidateAssessment, error) {
|
||||
assessed++
|
||||
return acceptedProducerAssessment(ctx, value)
|
||||
},
|
||||
}
|
||||
value, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(),
|
||||
func(ctx context.Context, result *promptkit.RunResult) (*int, []string, error) {
|
||||
interpreted++
|
||||
candidate, _, err := interpretProducerNumber(ctx, result)
|
||||
if interpreted == 1 {
|
||||
if !usable {
|
||||
candidate = nil
|
||||
}
|
||||
return candidate, []string{"Use the supplied candidate handles."}, err
|
||||
value, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[int], error) {
|
||||
interpreted++
|
||||
candidate, _, err := interpretProducerNumber(ctx, result)
|
||||
if interpreted == 1 {
|
||||
if !usable {
|
||||
candidate = nil
|
||||
}
|
||||
return candidate, nil, err
|
||||
},
|
||||
func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
if !reflect.DeepEqual(guidance, []string{"Use the supplied candidate handles."}) {
|
||||
t.Fatalf("module findings lost: %#v", guidance)
|
||||
}
|
||||
return producerCorrection(ctx, guidance)
|
||||
}, nil)
|
||||
return numberEvaluation(candidate, []string{"Use the supplied candidate handles."}), err
|
||||
}
|
||||
return numberEvaluation(candidate, nil), err
|
||||
}, Correction: func(ctx context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
if !reflect.DeepEqual(guidance, []string{"Use the supplied candidate handles."}) {
|
||||
t.Fatalf("module findings lost: %#v", guidance)
|
||||
}
|
||||
return producerCorrection(ctx, guidance)
|
||||
}, Fallback: nil})
|
||||
wantAssessed := 1
|
||||
if usable {
|
||||
wantAssessed = 2
|
||||
@@ -532,10 +515,10 @@ func TestNativeProducerAssessmentContractFailureDoesNotFallback(t *testing.T) {
|
||||
calls++
|
||||
return &promptkit.GenerateResponse{Content: `{"value":1}`}, nil
|
||||
}))
|
||||
operation := contracts.ProducerOperation[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Assess: func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||
operation := ExecutionContext[int]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 2}, Assess: func(context.Context, int) (contracts.CandidateAssessment, error) {
|
||||
return contracts.CandidateAssessment{}, failure
|
||||
}}
|
||||
_, outcome, err := RunProducer(context.Background(), engine, operation, nativeProducerInitial(), interpretProducerNumber, producerCorrection, func(context.Context, *int) (int, error) { fallbacks++; return -1, nil })
|
||||
_, outcome, err := runNativeOperation(context.Background(), engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: producerCorrection, Fallback: func(context.Context, contracts.Evaluation[int]) (int, error) { fallbacks++; return -1, nil }})
|
||||
if !errors.Is(err, failure) || outcome.Disposition != "" || calls != 1 || fallbacks != 0 {
|
||||
t.Fatalf("framework failure = %#v %v, calls %d/%d", outcome, err, calls, fallbacks)
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ func TestTypedCacheDecodeUsesCodecAndCurrentSourceWithoutSemanticAssessment(t *t
|
||||
var warnings []contracts.ProducerDiagnostic
|
||||
cache := artifactProducerCache(RunInput{Cache: store}, typed, contracts.ExecutionClassLLMBacked,
|
||||
contracts.DiagnosticOrigin{Stage: contracts.DiagnosticOriginStageExtract, ModuleKey: "native"}, doc, nil, &warnings)
|
||||
specialized := specializeProducerOperation[codecNotes](contracts.ProducerOperation[any]{Cache: cache}).Cache
|
||||
specialized := specializeExecutionContext[codecNotes](ExecutionContext[any]{Cache: cache}).Cache
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
content []byte
|
||||
@@ -191,7 +191,7 @@ func TestTypedCacheDecodeUsesCodecAndCurrentSourceWithoutSemanticAssessment(t *t
|
||||
})
|
||||
}
|
||||
// A codec mismatch stays a typed error at the registry boundary.
|
||||
wrong := specializeProducerOperation[codecScore](contracts.ProducerOperation[any]{Cache: cache}).Cache
|
||||
wrong := specializeExecutionContext[codecScore](ExecutionContext[any]{Cache: cache}).Cache
|
||||
if _, err := wrong.Decode([]byte(`{"items":[]}`)); err == nil {
|
||||
t.Fatal("cache decode crossed an incompatible Go type")
|
||||
}
|
||||
@@ -215,7 +215,7 @@ func TestProducerCacheCancellationDuringHitCannotDeliverAcceptance(t *testing.T)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_, outcome, err := RunProducer(ctx, engine, operation, nativeProducerInitial(), interpretProducerNumber, nil, nil)
|
||||
_, outcome, err := runNativeOperation(ctx, engine, operation, contracts.NativeOperation[int]{Initial: nativeProducerInitial(), Interpret: interpretNumberEvaluation, Correction: nil, Fallback: nil})
|
||||
if !errors.Is(err, context.Canceled) || outcome.Disposition != "" {
|
||||
t.Fatalf("canceled hit delivered acceptance: %#v %v", outcome, err)
|
||||
}
|
||||
|
||||
@@ -67,10 +67,10 @@ type typedMergeOperation func(context.Context, any, contracts.MergeInput[any], E
|
||||
type typedNormalizeOperation func(context.Context, any, contracts.NormalizeInput[any], ExecutionContext[any]) (erasedTypedResult, error)
|
||||
type typedValidateOperation func(context.Context, any, typedValidationTarget) (contracts.ValidationResult, error)
|
||||
|
||||
// specializeProducerOperation keeps type erasure inside the registry boundary.
|
||||
func specializeProducerOperation[T any](operation contracts.ProducerOperation[any]) contracts.ProducerOperation[T] {
|
||||
result := contracts.ProducerOperation[T]{Controls: operation.Controls, Execution: operation.Execution, ReuseEligible: operation.ReuseEligible}
|
||||
if cache := operation.Cache; cache != nil {
|
||||
// specializeExecutionContext keeps type erasure inside the registry boundary.
|
||||
func specializeExecutionContext[T any](execution ExecutionContext[any]) ExecutionContext[T] {
|
||||
result := ExecutionContext[T]{Engine: execution.Engine, Controls: execution.Controls, Execution: execution.Execution, ReuseEligible: execution.ReuseEligible}
|
||||
if cache := execution.Cache; cache != nil {
|
||||
result.Cache = &contracts.ProducerCache[T]{Store: cache.Store, Observe: cache.Observe}
|
||||
if cache.Encode != nil {
|
||||
result.Cache.Encode = func(value T) ([]byte, error) { return cache.Encode(value) }
|
||||
@@ -86,15 +86,10 @@ func specializeProducerOperation[T any](operation contracts.ProducerOperation[an
|
||||
}
|
||||
}
|
||||
}
|
||||
if operation.Assess != nil {
|
||||
if execution.Assess != nil {
|
||||
result.Assess = func(ctx context.Context, value T) (contracts.CandidateAssessment, error) {
|
||||
return operation.Assess(ctx, value)
|
||||
return execution.Assess(ctx, value)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func specializeExecutionContext[T any](execution ExecutionContext[any]) ExecutionContext[T] {
|
||||
operation := specializeProducerOperation[T](contracts.ProducerOperation[any]{Controls: execution.Controls, Execution: execution.Execution, ReuseEligible: execution.ReuseEligible, Assess: execution.Assess, Cache: execution.Cache})
|
||||
return ExecutionContext[T]{Engine: execution.Engine, Controls: operation.Controls, Execution: operation.Execution, ReuseEligible: operation.ReuseEligible, Assess: operation.Assess, Cache: operation.Cache}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func TestTypedRegistryCarriesOperationAssessmentAndOutcome(t *testing.T) {
|
||||
calls := 0
|
||||
zero := 0
|
||||
native := &promptkit.ExecutionTargetOverride{}
|
||||
operation := contracts.ProducerOperation[any]{
|
||||
operation := ExecutionContext[any]{
|
||||
Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: 0, Cache: contracts.CacheBypass},
|
||||
Execution: contracts.ExecutionOptions{Execution: native, TransientRetries: &zero},
|
||||
ReuseEligible: false,
|
||||
@@ -82,7 +82,7 @@ func TestTypedRegistryCarriesOperationAssessmentAndOutcome(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collaborationProducer) func(context.Context, contracts.ProducerOperation[any], any) (erasedTypedResult, error) {
|
||||
func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collaborationProducer) func(context.Context, ExecutionContext[any], any) (erasedTypedResult, error) {
|
||||
t.Helper()
|
||||
spec := ModuleSpec{Key: impl.Key(), Stage: stage, ExecutionClass: contracts.ExecutionClassLLMBacked, ArtifactKind: "test/value"}
|
||||
switch stage {
|
||||
@@ -92,8 +92,8 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry, _ := registry.typedEntry(spec.Key)
|
||||
return func(ctx context.Context, op contracts.ProducerOperation[any], _ any) (erasedTypedResult, error) {
|
||||
return entry.extract(ctx, impl, contracts.ExtractionInput{}, ExecutionContext[any]{Controls: op.Controls, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Assess: op.Assess, Cache: op.Cache})
|
||||
return func(ctx context.Context, op ExecutionContext[any], _ any) (erasedTypedResult, error) {
|
||||
return entry.extract(ctx, impl, contracts.ExtractionInput{}, op)
|
||||
}
|
||||
case StageMerge:
|
||||
registry := NewMergerRegistry()
|
||||
@@ -101,8 +101,8 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry, _ := registry.typedEntry(spec.Key, spec.ArtifactKind)
|
||||
return func(ctx context.Context, op contracts.ProducerOperation[any], value any) (erasedTypedResult, error) {
|
||||
return entry.merge(ctx, impl, contracts.MergeInput[any]{ExtractOutputs: []contracts.ExtractArtifact[any]{{Value: value}}}, ExecutionContext[any]{Controls: op.Controls, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Assess: op.Assess, Cache: op.Cache})
|
||||
return func(ctx context.Context, op ExecutionContext[any], value any) (erasedTypedResult, error) {
|
||||
return entry.merge(ctx, impl, contracts.MergeInput[any]{ExtractOutputs: []contracts.ExtractArtifact[any]{{Value: value}}}, op)
|
||||
}
|
||||
default:
|
||||
registry := NewNormalizerRegistry()
|
||||
@@ -110,8 +110,8 @@ func registerCollaborationProducer(t *testing.T, stage ModuleStage, impl *collab
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry, _ := registry.typedEntry(spec.Key, spec.ArtifactKind)
|
||||
return func(ctx context.Context, op contracts.ProducerOperation[any], value any) (erasedTypedResult, error) {
|
||||
return entry.normalize(ctx, impl, contracts.NormalizeInput[any]{MergeOutput: contracts.MergeArtifact[any]{Value: value}}, ExecutionContext[any]{Controls: op.Controls, Execution: op.Execution, ReuseEligible: op.ReuseEligible, Assess: op.Assess, Cache: op.Cache})
|
||||
return func(ctx context.Context, op ExecutionContext[any], value any) (erasedTypedResult, error) {
|
||||
return entry.normalize(ctx, impl, contracts.NormalizeInput[any]{MergeOutput: contracts.MergeArtifact[any]{Value: value}}, op)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,7 +120,7 @@ func TestTypedExtractionRegistryAssessesPreparedExactType(t *testing.T) {
|
||||
impl := &collaborationProducer{}
|
||||
invoke := registerCollaborationProducer(t, StageExtract, impl)
|
||||
assessments := 0
|
||||
result, err := invoke(context.Background(), contracts.ProducerOperation[any]{ReuseEligible: true, Assess: func(_ context.Context, value any) (contracts.CandidateAssessment, error) {
|
||||
result, err := invoke(context.Background(), ExecutionContext[any]{ReuseEligible: true, Assess: func(_ context.Context, value any) (contracts.CandidateAssessment, error) {
|
||||
assessments++
|
||||
if reflect.TypeOf(value) != reflect.TypeFor[collaborationValue]() || value != (collaborationValue{"candidate"}) {
|
||||
t.Fatalf("candidate = %#v", value)
|
||||
@@ -135,7 +135,7 @@ func TestTypedExtractionRegistryAssessesPreparedExactType(t *testing.T) {
|
||||
func TestTypedRegistryRejectsIncompatibleOperationValues(t *testing.T) {
|
||||
for _, stage := range []ModuleStage{StageMerge, StageNormalize} {
|
||||
invoke := registerCollaborationProducer(t, stage, &collaborationProducer{})
|
||||
if _, err := invoke(context.Background(), contracts.ProducerOperation[any]{}, struct{ Text string }{"candidate"}); err == nil {
|
||||
if _, err := invoke(context.Background(), ExecutionContext[any]{}, struct{ Text string }{"candidate"}); err == nil {
|
||||
t.Fatalf("%s accepted structurally similar but incompatible Go type", stage)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user