Keep reconciliation findings with the current evaluation
This commit is contained in:
@@ -9,30 +9,56 @@ import (
|
||||
"go.maximumdirect.net/promptkit"
|
||||
)
|
||||
|
||||
// OperationInput describes one reconciliation over fixed, already owned
|
||||
// records. Original is the unprocessed merged value used by fallback;
|
||||
// Deterministic is the separately preprocessed no-model candidate. Callers
|
||||
// retain responsibility for cloning mutable values captured by callbacks.
|
||||
type OperationInput[T, R any] struct {
|
||||
Source *source.SourceDocument
|
||||
Original T
|
||||
Deterministic T
|
||||
Records []R
|
||||
Limits Limits
|
||||
PromptID string
|
||||
CorrectionID string
|
||||
ProfileID string
|
||||
SessionID string
|
||||
Project func([]R) ([]Candidate, error)
|
||||
Interpret func(context.Context, Preparation, *promptkit.RunResult) (contracts.Evaluation[T], error)
|
||||
Fallback func(context.Context, T, contracts.Evaluation[T]) (T, error)
|
||||
Diagnostics contracts.TerminalDiagnostics[T]
|
||||
BaseDiagnostics []contracts.ProducerDiagnostic
|
||||
// Application is the domain result of applying one safe plan to fixed records.
|
||||
// Findings, omission details and evidence belong only to that proposal.
|
||||
type Application[T, F any] struct {
|
||||
Value T
|
||||
Findings F
|
||||
OmittedGroups int
|
||||
OmissionDetails []string
|
||||
Guidance []string
|
||||
Evidence any
|
||||
}
|
||||
|
||||
// PrepareOperation selects the deterministic, limited, or native operation;
|
||||
// it never runs a model, assesses a value, or chooses a terminal disposition.
|
||||
func PrepareOperation[T, R any](input OperationInput[T, R]) (contracts.PreparedOperation[T], error) {
|
||||
// Evaluation retains one complete proposal and its typed domain application.
|
||||
// No mutable proposal state is shared between native turns.
|
||||
type Evaluation[T, F any] struct {
|
||||
Candidate T
|
||||
Findings F
|
||||
Proposal ProposalResponse
|
||||
Issues []Issue
|
||||
OmittedGroups int
|
||||
OmissionDetails []string
|
||||
Guidance []string
|
||||
ApplicationEvidence any
|
||||
Model bool
|
||||
}
|
||||
|
||||
func (evaluation *Evaluation[T, F]) View() contracts.EvaluationView[T] {
|
||||
return contracts.EvaluationView[T]{Candidate: &evaluation.Candidate, Guidance: evaluation.Guidance, Evidence: func() (any, error) {
|
||||
return map[string]any{"proposal": evaluation.Proposal, "issues": evaluation.Issues, "omitted_groups": evaluation.OmittedGroups, "omission_details": evaluation.OmissionDetails, "application": evaluation.ApplicationEvidence}, nil
|
||||
}}
|
||||
}
|
||||
|
||||
// OperationInput describes owned, fixed records and the separate unprocessed
|
||||
// fallback value. Callers own cloning of mutable inputs and returned findings.
|
||||
type OperationInput[T, R, F any] struct {
|
||||
Source *source.SourceDocument
|
||||
Original T
|
||||
Deterministic T
|
||||
BaseFindings F
|
||||
Records []R
|
||||
Limits Limits
|
||||
PromptID, CorrectionID, ProfileID, SessionID string
|
||||
Project func([]R) ([]Candidate, error)
|
||||
Apply func(context.Context, Plan, []R) (Application[T, F], error)
|
||||
Fallback func(context.Context, T, *Evaluation[T, F]) (T, error)
|
||||
Diagnostics func(*Evaluation[T, F], contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error)
|
||||
}
|
||||
|
||||
// PrepareOperation prepares fixed source material and selects a typed core
|
||||
// operation. It does not execute a model, assess candidates, or select fallback.
|
||||
func PrepareOperation[T, R, F any](input OperationInput[T, R, F]) (contracts.PreparedOperation[T], error) {
|
||||
var candidates []Candidate
|
||||
var preparation Preparation
|
||||
evidence := func() (any, error) {
|
||||
@@ -40,17 +66,27 @@ func PrepareOperation[T, R any](input OperationInput[T, R]) (contracts.PreparedO
|
||||
}
|
||||
var fallback contracts.Fallback[T]
|
||||
if input.Fallback != nil {
|
||||
fallback = func(ctx context.Context, evaluation contracts.Evaluation[T]) (T, error) {
|
||||
fallback = func(ctx context.Context, current contracts.Evaluation[T]) (T, error) {
|
||||
evaluation, _ := current.(*Evaluation[T, F])
|
||||
if evaluation != nil && !evaluation.Model {
|
||||
evaluation = nil
|
||||
}
|
||||
return input.Fallback(ctx, input.Original, evaluation)
|
||||
}
|
||||
}
|
||||
noModel := func() contracts.PreparedOperation[T] {
|
||||
value := input.Deterministic
|
||||
var originalFallback contracts.Fallback[T]
|
||||
if fallback != nil {
|
||||
originalFallback = func(ctx context.Context, _ contracts.Evaluation[T]) (T, error) { return fallback(ctx, nil) }
|
||||
var diagnostics contracts.TerminalDiagnostics[T]
|
||||
if input.Diagnostics != nil {
|
||||
diagnostics = func(current contracts.Evaluation[T], outcome contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error) {
|
||||
evaluation, _ := current.(*Evaluation[T, F])
|
||||
if evaluation != nil && !evaluation.Model && outcome.Disposition == contracts.ProducerFallback {
|
||||
evaluation = nil
|
||||
}
|
||||
return input.Diagnostics(evaluation, outcome)
|
||||
}
|
||||
return contracts.DeterministicOperation[T]{Evaluation: contracts.CandidateEvaluation[T]{Result: contracts.EvaluationView[T]{Candidate: &value, Diagnostics: input.BaseDiagnostics}}, Fallback: originalFallback, Diagnostics: input.Diagnostics, Evidence: evidence}
|
||||
}
|
||||
noModel := func() contracts.PreparedOperation[T] {
|
||||
evaluation := &Evaluation[T, F]{Candidate: input.Deterministic, Findings: input.BaseFindings}
|
||||
return contracts.DeterministicOperation[T]{Evaluation: evaluation, Fallback: fallback, Diagnostics: diagnostics, Evidence: evidence}
|
||||
}
|
||||
if len(input.Records) < 2 {
|
||||
return noModel(), nil
|
||||
@@ -71,22 +107,39 @@ func PrepareOperation[T, R any](input OperationInput[T, R]) (contracts.PreparedO
|
||||
case InsufficientCandidates:
|
||||
return noModel(), nil
|
||||
case LimitExceeded:
|
||||
return contracts.PreparationLimit[T]{Cause: errors.New("candidate set exceeded semantic reconciliation preparation limits"), Fallback: fallback, Diagnostics: input.Diagnostics, Evidence: evidence}, nil
|
||||
return contracts.PreparationLimit[T]{Cause: errors.New("candidate set exceeded semantic reconciliation preparation limits"), Fallback: fallback, Diagnostics: diagnostics, Evidence: evidence}, nil
|
||||
}
|
||||
initial, err := InitialRequest(preparation, input.PromptID, input.ProfileID, input.SessionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Interpret == nil {
|
||||
return nil, errors.New("semantic reconciliation interpretation must be supplied")
|
||||
if input.Apply == nil {
|
||||
return nil, errors.New("semantic reconciliation application must be supplied")
|
||||
}
|
||||
return contracts.NativeOperation[T]{Initial: initial,
|
||||
Interpret: func(ctx context.Context, result *promptkit.RunResult) (contracts.Evaluation[T], error) {
|
||||
return input.Interpret(ctx, preparation, result)
|
||||
proposal, err := DecodeProposal(result.RawOutput)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
assessment := preparation.Assess(proposal)
|
||||
application, err := input.Apply(ctx, assessment.Plan(), input.Records)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
issues := assessment.Issues()
|
||||
guidance, err := CorrectionDetails(issues, preparation.CandidateNumberRange())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Evaluation[T, F]{Candidate: application.Value, Findings: application.Findings, Proposal: proposal, Issues: issues,
|
||||
OmittedGroups: assessment.DiscardedGroupCount() + application.OmittedGroups,
|
||||
OmissionDetails: append(IssueDetails(issues), application.OmissionDetails...),
|
||||
Guidance: append(guidance, application.Guidance...), ApplicationEvidence: application.Evidence, Model: true}, nil
|
||||
},
|
||||
Correction: func(_ context.Context, guidance []string) (promptkit.RunRequest, error) {
|
||||
return CorrectionRequest(input.CorrectionID, input.ProfileID, input.SessionID, guidance), nil
|
||||
},
|
||||
Fallback: fallback, Diagnostics: input.Diagnostics, Evidence: evidence,
|
||||
Fallback: fallback, Diagnostics: diagnostics, Evidence: evidence,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package semanticreconcile
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/notarius/internal/core/source"
|
||||
@@ -14,14 +15,14 @@ import (
|
||||
func TestPrepareOperationSelectsModelOrDeterministicWork(t *testing.T) {
|
||||
doc := &source.SourceDocument{ID: "document", Units: []source.SourceUnit{{ID: 1, Text: "Alpha"}, {ID: 2, Text: "Beta"}}}
|
||||
records := []string{"Alpha", "Beta"}
|
||||
input := OperationInput[[]string, string]{Source: doc, Original: []string{"original"}, Deterministic: []string{"preprocessed"}, Records: records, Limits: DefaultLimits(), PromptID: "initial", CorrectionID: "correct", ProfileID: "profile", SessionID: "session",
|
||||
input := OperationInput[[]string, string, string]{Source: doc, Original: []string{"original"}, Deterministic: []string{"preprocessed"}, Records: records, Limits: DefaultLimits(), PromptID: "initial", CorrectionID: "correct", ProfileID: "profile", SessionID: "session",
|
||||
Project: func(records []string) ([]Candidate, error) {
|
||||
return []Candidate{{Label: records[0], SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 1, EndUnitID: 1}}}, {Label: records[1], SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: 2, EndUnitID: 2}}}}, nil
|
||||
},
|
||||
Interpret: func(context.Context, Preparation, *promptkit.RunResult) (contracts.Evaluation[[]string], error) {
|
||||
return nil, nil
|
||||
Apply: func(context.Context, Plan, []string) (Application[[]string, string], error) {
|
||||
return Application[[]string, string]{}, nil
|
||||
},
|
||||
Fallback: func(_ context.Context, original []string, _ contracts.Evaluation[[]string]) ([]string, error) {
|
||||
Fallback: func(_ context.Context, original []string, _ *Evaluation[[]string, string]) ([]string, error) {
|
||||
return original, nil
|
||||
},
|
||||
}
|
||||
@@ -57,9 +58,91 @@ func TestPrepareOperationSelectsModelOrDeterministicWork(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type proposalClient struct {
|
||||
outputs []string
|
||||
call int
|
||||
failure error
|
||||
}
|
||||
|
||||
func (client *proposalClient) Generate(context.Context, promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
index := client.call
|
||||
client.call++
|
||||
if index >= len(client.outputs) {
|
||||
return nil, client.failure
|
||||
}
|
||||
return &promptkit.GenerateResponse{Content: client.outputs[index]}, nil
|
||||
}
|
||||
|
||||
func TestReconciliationKeepsOnlyTheFinalEvaluation(t *testing.T) {
|
||||
first := `{"duplicate_groups":[{"candidate_numbers":[1,2],"canonical_candidate_number":1},{"candidate_numbers":[3,99],"canonical_candidate_number":3}]}`
|
||||
second := `{"duplicate_groups":[{"candidate_numbers":[2,3],"canonical_candidate_number":2}]}`
|
||||
failure := errors.New("correction unavailable")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
outputs []string
|
||||
turns int
|
||||
failure error
|
||||
want []string
|
||||
omitted int
|
||||
wantModel bool
|
||||
}{
|
||||
{name: "replacement", outputs: []string{first, second}, turns: 1, want: []string{"B+C"}, wantModel: true},
|
||||
{name: "safe partial", outputs: []string{first}, want: []string{"A+B"}, omitted: 1, wantModel: true},
|
||||
{name: "failed correction", outputs: []string{first}, turns: 1, failure: failure, want: []string{"original"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
doc := &source.SourceDocument{ID: "doc", Units: []source.SourceUnit{{ID: 1, Text: "A"}, {ID: 2, Text: "B"}, {ID: 3, Text: "C"}}}
|
||||
records := []string{"A", "B", "C"}
|
||||
client := &proposalClient{outputs: test.outputs, failure: test.failure}
|
||||
var projected *Evaluation[[]string, string]
|
||||
input := OperationInput[[]string, string, string]{Source: doc, Original: []string{"original"}, Deterministic: records, Records: records, Limits: DefaultLimits(), PromptID: PromptID, CorrectionID: CorrectionPromptID, ProfileID: "test-profile",
|
||||
Project: func(values []string) ([]Candidate, error) {
|
||||
candidates := make([]Candidate, len(values))
|
||||
for i, value := range values {
|
||||
candidates[i] = Candidate{Label: value, SourceRefs: []source.SourceRef{{SourceID: doc.ID, StartUnitID: i + 1, EndUnitID: i + 1}}}
|
||||
}
|
||||
return candidates, nil
|
||||
},
|
||||
Apply: func(_ context.Context, plan Plan, values []string) (Application[[]string, string], error) {
|
||||
var combined []string
|
||||
for _, group := range plan.Groups() {
|
||||
members := group.MemberPositions()
|
||||
combined = append(combined, values[members[0]]+"+"+values[members[1]])
|
||||
}
|
||||
return Application[[]string, string]{Value: combined, Findings: "current"}, nil
|
||||
},
|
||||
Fallback: func(_ context.Context, original []string, evaluation *Evaluation[[]string, string]) ([]string, error) {
|
||||
if evaluation == nil {
|
||||
return original, nil
|
||||
}
|
||||
return evaluation.Candidate, nil
|
||||
},
|
||||
Diagnostics: func(evaluation *Evaluation[[]string, string], _ contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error) {
|
||||
projected = evaluation
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
execution := pipeline.ExecutionContext[[]string]{Engine: newReconciliationEngine(t, client), Controls: contracts.ProducerControls{Mode: contracts.ModePermissive, MaxAdditionalTurns: test.turns}, Assess: func(context.Context, []string) (contracts.CandidateAssessment, error) {
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}}
|
||||
result, err := pipeline.ExecuteOperation(context.Background(), execution, func(context.Context) (contracts.PreparedOperation[[]string], error) { return PrepareOperation(input) })
|
||||
if err != nil || !reflect.DeepEqual(result.Value, test.want) {
|
||||
t.Fatalf("value = %#v, error = %v", result.Value, err)
|
||||
}
|
||||
if test.wantModel {
|
||||
if projected == nil || projected.OmittedGroups != test.omitted || projected.Findings != "current" {
|
||||
t.Fatalf("final evaluation = %#v", projected)
|
||||
}
|
||||
} else if projected != nil {
|
||||
t.Fatalf("stale evaluation = %#v", projected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareOperationPropagatesProjectionErrorsAndLimits(t *testing.T) {
|
||||
bad := errors.New("projection failed")
|
||||
input := OperationInput[int, int]{Records: []int{1, 2}, Limits: DefaultLimits(), Project: func([]int) ([]Candidate, error) { return nil, bad }}
|
||||
input := OperationInput[int, int, string]{Records: []int{1, 2}, Limits: DefaultLimits(), Project: func([]int) ([]Candidate, error) { return nil, bad }}
|
||||
if _, err := PrepareOperation(input); !errors.Is(err, bad) {
|
||||
t.Fatalf("projection error = %v", err)
|
||||
}
|
||||
@@ -76,3 +159,47 @@ func TestPrepareOperationPropagatesProjectionErrorsAndLimits(t *testing.T) {
|
||||
t.Fatalf("operation = %T, want preparation limit", operation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeterministicAndLimitDiagnosticsFollowReturnedValue(t *testing.T) {
|
||||
input := OperationInput[string, string, string]{Original: "original", Deterministic: "normalized", BaseFindings: "base", Records: []string{"one"}, Limits: DefaultLimits(),
|
||||
Fallback: func(_ context.Context, original string, _ *Evaluation[string, string]) (string, error) {
|
||||
return original, nil
|
||||
},
|
||||
}
|
||||
var final *Evaluation[string, string]
|
||||
input.Diagnostics = func(evaluation *Evaluation[string, string], _ contracts.ProducerOutcome) ([]contracts.ProducerDiagnostic, error) {
|
||||
final = evaluation
|
||||
return nil, nil
|
||||
}
|
||||
assess := func(context.Context, string) (contracts.CandidateAssessment, error) {
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}
|
||||
run := func() (pipeline.OperationResult[string], error) {
|
||||
return pipeline.ExecuteOperation(context.Background(), pipeline.ExecutionContext[string]{Controls: contracts.ProducerControls{Mode: contracts.ModePermissive}, Assess: assess}, func(context.Context) (contracts.PreparedOperation[string], error) { return PrepareOperation(input) })
|
||||
}
|
||||
result, err := run()
|
||||
if err != nil || result.Value != "normalized" || final == nil || final.Findings != "base" {
|
||||
t.Fatalf("accepted result = %#v, evaluation = %#v, error = %v", result, final, err)
|
||||
}
|
||||
assess = func(context.Context, string) (contracts.CandidateAssessment, error) {
|
||||
return contracts.CandidateAssessment{Validators: []contracts.ValidatorAssessment{{ValidatorName: "rule", Decision: contracts.AssessmentRejected}}}, nil
|
||||
}
|
||||
result, err = run()
|
||||
if err != nil || result.Value != "original" || final != nil {
|
||||
t.Fatalf("fallback result = %#v, evaluation = %#v, error = %v", result, final, err)
|
||||
}
|
||||
input.Records = []string{"one", "two"}
|
||||
input.Source = &source.SourceDocument{ID: "doc", Units: []source.SourceUnit{{ID: 1}, {ID: 2}}}
|
||||
input.Limits.MaximumCandidates = 1
|
||||
input.Project = func([]string) ([]Candidate, error) {
|
||||
return []Candidate{{SourceRefs: []source.SourceRef{{SourceID: "doc", StartUnitID: 1, EndUnitID: 1}}}, {SourceRefs: []source.SourceRef{{SourceID: "doc", StartUnitID: 2, EndUnitID: 2}}}}, nil
|
||||
}
|
||||
assess = func(context.Context, string) (contracts.CandidateAssessment, error) {
|
||||
t.Fatal("limit must not assess a nonexistent candidate")
|
||||
return contracts.CandidateAssessment{}, nil
|
||||
}
|
||||
result, err = run()
|
||||
if err != nil || result.Value != "original" || final != nil {
|
||||
t.Fatalf("limit result = %#v, evaluation = %#v, error = %v", result, final, err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user